]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-index-mode.rb
Merge commit 'origin/various-mbox-fixes'
[sup] / lib / sup / modes / thread-index-mode.rb
1 module Redwood
2
3 ## subclasses should implement:
4 ## - is_relevant?
5
6 class ThreadIndexMode < LineCursorMode
7   DATE_WIDTH = Time::TO_NICE_S_MAX_LEN
8   MIN_FROM_WIDTH = 15
9   LOAD_MORE_THREAD_NUM = 20
10
11   HookManager.register "index-mode-size-widget", <<EOS
12 Generates the per-thread size widget for each thread.
13 Variables:
14   thread: The message thread to be formatted.
15 EOS
16
17   HookManager.register "mark-as-spam", <<EOS
18 This hook is run when a thread is marked as spam
19 Variables:
20   thread: The message thread being marked as spam.
21 EOS
22
23   register_keymap do |k|
24     k.add :load_threads, "Load #{LOAD_MORE_THREAD_NUM} more threads", 'M'
25     k.add_multi "Load all threads (! to confirm) :", '!' do |kk|
26       kk.add :load_all_threads, "Load all threads (may list a _lot_ of threads)", '!'
27     end
28     k.add :cancel_search, "Cancel current search", :ctrl_g
29     k.add :reload, "Refresh view", '@'
30     k.add :toggle_archived, "Toggle archived status", 'a'
31     k.add :toggle_starred, "Star or unstar all messages in thread", '*'
32     k.add :toggle_new, "Toggle new/read status of all messages in thread", 'N'
33     k.add :edit_labels, "Edit or add labels for a thread", 'l'
34     k.add :edit_message, "Edit message (drafts only)", 'e'
35     k.add :toggle_spam, "Mark/unmark thread as spam", 'S'
36     k.add :toggle_deleted, "Delete/undelete thread", 'd'
37     k.add :kill, "Kill thread (never to be seen in inbox again)", '&'
38     k.add :save, "Save changes now", '$'
39     k.add :jump_to_next_new, "Jump to next new thread", :tab
40     k.add :reply, "Reply to latest message in a thread", 'r'
41     k.add :forward, "Forward latest message in a thread", 'f'
42     k.add :toggle_tagged, "Tag/untag selected thread", 't'
43     k.add :toggle_tagged_all, "Tag/untag all threads", 'T'
44     k.add :tag_matching, "Tag matching threads", 'g'
45     k.add :apply_to_tagged, "Apply next command to all tagged threads", '+', '='
46     k.add :join_threads, "Force tagged threads to be joined into the same thread", '#'
47   end
48
49   def initialize hidden_labels=[], load_thread_opts={}
50     super()
51     @mutex = Mutex.new # covers the following variables:
52     @threads = {}
53     @hidden_threads = {}
54     @size_widget_width = nil
55     @size_widgets = {}
56     @tags = Tagger.new self
57
58     ## these guys, and @text and @lines, are not covered
59     @load_thread = nil
60     @load_thread_opts = load_thread_opts
61     @hidden_labels = hidden_labels + LabelManager::HIDDEN_RESERVED_LABELS
62     @date_width = DATE_WIDTH
63
64     @interrupt_search = false
65     
66     initialize_threads # defines @ts and @ts_mutex
67     update # defines @text and @lines
68
69     UpdateManager.register self
70
71     @save_thread_mutex = Mutex.new
72
73     @last_load_more_size = nil
74     to_load_more do |size|
75       next if @last_load_more_size == 0
76       load_threads :num => 1, :background => false
77       load_threads :num => (size - 1),
78                    :when_done => lambda { |num| @last_load_more_size = num }
79     end
80   end
81
82   def unsaved?; dirty? end
83   def lines; @text.length; end
84   def [] i; @text[i]; end
85   def contains_thread? t; @threads.include?(t) end
86
87   def reload
88     drop_all_threads
89     BufferManager.draw_screen
90     load_threads :num => buffer.content_height
91   end
92
93   ## open up a thread view window
94   def select t=nil, when_done=nil
95     t ||= cursor_thread or return
96
97     Redwood::reporting_thread("load messages for thread-view-mode") do
98       num = t.size
99       message = "Loading #{num.pluralize 'message body'}..."
100       BufferManager.say(message) do |sid|
101         t.each_with_index do |(m, *o), i|
102           next unless m
103           BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1
104           m.load_from_source! 
105         end
106       end
107       mode = ThreadViewMode.new t, @hidden_labels, self
108       BufferManager.spawn t.subj, mode
109       BufferManager.draw_screen
110       mode.jump_to_first_open true
111       BufferManager.draw_screen # lame TODO: make this unnecessary
112       ## the first draw_screen is needed before topline and botline
113       ## are set, and the second to show the cursor having moved
114
115       update_text_for_line curpos
116       UpdateManager.relay self, :read, t.first
117       when_done.call if when_done
118     end
119   end
120
121   def multi_select threads
122     threads.each { |t| select t }
123   end
124
125   ## these two methods are called by thread-view-modes when the user
126   ## wants to view the previous/next thread without going back to
127   ## index-mode. we update the cursor as a convenience.
128   def launch_next_thread_after thread, &b
129     launch_another_thread thread, 1, &b
130   end
131
132   def launch_prev_thread_before thread, &b
133     launch_another_thread thread, -1, &b
134   end
135
136   def launch_another_thread thread, direction, &b
137     l = @lines[thread] or return
138     target_l = l + direction
139     t = @mutex.synchronize do
140       if target_l >= 0 && target_l < @threads.length
141         @threads[target_l]
142       end
143     end
144
145     if t # there's a next thread
146       set_cursor_pos target_l # move out of mutex?
147       select t, b
148     elsif b # no next thread. call the block anyways
149       b.call
150     end
151   end
152   
153   def handle_single_message_labeled_update sender, m
154     ## no need to do anything different here; we don't differentiate 
155     ## messages from their containing threads
156     handle_labeled_update sender, m
157   end
158
159   def handle_labeled_update sender, m
160     if(t = thread_containing(m)) 
161       l = @lines[t] or return
162       update_text_for_line l
163     elsif is_relevant?(m)
164       add_or_unhide m
165     end
166   end
167
168   def handle_simple_update sender, m
169     t = thread_containing(m) or return
170     l = @lines[t] or return
171     update_text_for_line l
172   end
173
174   %w(read unread archived starred unstarred).each do |state|
175     define_method "handle_#{state}_update" do |*a|
176       handle_simple_update(*a)
177     end
178   end
179
180   ## overwrite me!
181   def is_relevant? m; false; end
182
183   def handle_added_update sender, m
184     add_or_unhide m
185     BufferManager.draw_screen
186   end
187
188   def handle_single_message_deleted_update sender, m
189     @ts_mutex.synchronize do
190       return unless @ts.contains? m
191       @ts.remove_id m.id
192     end
193     update
194   end
195
196   def handle_deleted_update sender, m
197     t = @ts_mutex.synchronize { @ts.thread_for m }
198     return unless t
199     hide_thread t
200     update
201   end
202
203   def handle_spammed_update sender, m
204     t = @ts_mutex.synchronize { @ts.thread_for m }
205     return unless t
206     hide_thread t
207     update
208   end
209
210   def handle_undeleted_update sender, m
211     add_or_unhide m
212   end
213
214   def update
215     @mutex.synchronize do
216       ## let's see you do THIS in python
217       @threads = @ts.threads.select { |t| !@hidden_threads[t] }.sort_by { |t| [t.date, t.first.id] }.reverse
218       @size_widgets = @threads.map { |t| size_widget_for_thread t }
219       @size_widget_width = @size_widgets.max_of { |w| w.length }
220     end
221
222     regen_text
223   end
224
225   def edit_message
226     return unless(t = cursor_thread)
227     message, *crap = t.find { |m, *o| m.has_label? :draft }
228     if message
229       mode = ResumeMode.new message
230       BufferManager.spawn "Edit message", mode
231     else
232       BufferManager.flash "Not a draft message!"
233     end
234   end
235
236   def actually_toggle_starred t
237     if t.has_label? :starred # if ANY message has a star
238       t.remove_label :starred # remove from all
239       UpdateManager.relay self, :unstarred, t.first
240     else
241       t.first.add_label :starred # add only to first
242       UpdateManager.relay self, :starred, t.first
243     end
244   end  
245
246   def toggle_starred 
247     t = cursor_thread or return
248     actually_toggle_starred t
249     update_text_for_line curpos
250     cursor_down
251   end
252
253   def multi_toggle_starred threads
254     threads.each { |t| actually_toggle_starred t }
255     regen_text
256   end
257
258   def actually_toggle_archived t
259     if t.has_label? :inbox
260       t.remove_label :inbox
261       UpdateManager.relay self, :archived, t.first
262     else
263       t.apply_label :inbox
264       UpdateManager.relay self, :unarchived, t.first
265     end
266   end
267
268   def actually_toggle_spammed t
269     if t.has_label? :spam
270       t.remove_label :spam
271       UpdateManager.relay self, :unspammed, t.first
272     else
273       t.apply_label :spam
274       UpdateManager.relay self, :spammed, t.first
275     end
276   end
277
278   def actually_toggle_deleted t
279     if t.has_label? :deleted
280       t.remove_label :deleted
281       UpdateManager.relay self, :undeleted, t.first
282     else
283       t.apply_label :deleted
284       UpdateManager.relay self, :deleted, t.first
285     end
286   end
287
288   def toggle_archived 
289     t = cursor_thread or return
290     actually_toggle_archived t
291     update_text_for_line curpos
292   end
293
294   def multi_toggle_archived threads
295     threads.each { |t| actually_toggle_archived t }
296     regen_text
297   end
298
299   def toggle_new
300     t = cursor_thread or return
301     t.toggle_label :unread
302     update_text_for_line curpos
303     cursor_down
304   end
305
306   def multi_toggle_new threads
307     threads.each { |t| t.toggle_label :unread }
308     regen_text
309   end
310
311   def multi_toggle_tagged threads
312     @mutex.synchronize { @tags.drop_all_tags }
313     regen_text
314   end
315
316   def join_threads
317     ## this command has no non-tagged form. as a convenience, allow this
318     ## command to be applied to tagged threads without hitting ';'.
319     @tags.apply_to_tagged :join_threads
320   end
321
322   def multi_join_threads threads
323     @ts.join_threads threads or return
324     @tags.drop_all_tags # otherwise we have tag pointers to invalid threads!
325     update
326   end
327
328   def jump_to_next_new
329     n = @mutex.synchronize do
330       ((curpos + 1) ... lines).find { |i| @threads[i].has_label? :unread } ||
331         (0 ... curpos).find { |i| @threads[i].has_label? :unread }
332     end
333     if n
334       ## jump there if necessary
335       jump_to_line n unless n >= topline && n < botline
336       set_cursor_pos n
337     else
338       BufferManager.flash "No new messages"
339     end
340   end
341
342   def toggle_spam
343     t = cursor_thread or return
344     multi_toggle_spam [t]
345     HookManager.run("mark-as-spam", :thread => t)
346   end
347
348   ## both spam and deleted have the curious characteristic that you
349   ## always want to hide the thread after either applying or removing
350   ## that label. in all thread-index-views except for
351   ## label-search-results-mode, when you mark a message as spam or
352   ## deleted, you want it to disappear immediately; in LSRM, you only
353   ## see deleted or spam emails, and when you undelete or unspam them
354   ## you also want them to disappear immediately.
355   def multi_toggle_spam threads
356     threads.each do |t|
357       actually_toggle_spammed t
358       hide_thread t 
359     end
360     regen_text
361   end
362
363   def toggle_deleted
364     t = cursor_thread or return
365     multi_toggle_deleted [t]
366   end
367
368   ## see comment for multi_toggle_spam
369   def multi_toggle_deleted threads
370     threads.each do |t|
371       actually_toggle_deleted t
372       hide_thread t 
373     end
374     regen_text
375   end
376
377   def kill
378     t = cursor_thread or return
379     multi_kill [t]
380   end
381
382   def multi_kill threads
383     threads.each do |t|
384       t.apply_label :killed
385       hide_thread t
386     end
387     regen_text
388     BufferManager.flash "#{threads.size.pluralize 'Thread'} killed."
389   end
390
391   def save background=true
392     if background
393       Redwood::reporting_thread("saving thread") { actually_save }
394     else
395       actually_save
396     end
397   end
398
399   def actually_save
400     @save_thread_mutex.synchronize do
401       BufferManager.say("Saving contacts...") { ContactManager.instance.save }
402       dirty_threads = @mutex.synchronize { (@threads + @hidden_threads.keys).select { |t| t.dirty? } }
403       next if dirty_threads.empty?
404
405       BufferManager.say("Saving threads...") do |say_id|
406         dirty_threads.each_with_index do |t, i|
407           BufferManager.say "Saving modified thread #{i + 1} of #{dirty_threads.length}...", say_id
408           t.save Index
409         end
410       end
411     end
412   end
413
414   def cleanup
415     UpdateManager.unregister self
416
417     if @load_thread
418       @load_thread.kill 
419       BufferManager.clear @mbid if @mbid
420       sleep 0.1 # TODO: necessary?
421       BufferManager.erase_flash
422     end
423     save false
424     super
425   end
426
427   def toggle_tagged
428     t = cursor_thread or return
429     @mutex.synchronize { @tags.toggle_tag_for t }
430     update_text_for_line curpos
431     cursor_down
432   end
433   
434   def toggle_tagged_all
435     @mutex.synchronize { @threads.each { |t| @tags.toggle_tag_for t } }
436     regen_text
437   end
438
439   def tag_matching
440     query = BufferManager.ask :search, "tag threads matching (regex): "
441     return if query.nil? || query.empty?
442     query = begin
443       /#{query}/i
444     rescue RegexpError => e
445       BufferManager.flash "error interpreting '#{query}': #{e.message}"
446       return
447     end
448     @mutex.synchronize { @threads.each { |t| @tags.tag t if thread_matches?(t, query) } }
449     regen_text
450   end
451
452   def apply_to_tagged; @tags.apply_to_tagged; end
453
454   def edit_labels
455     thread = cursor_thread or return
456     speciall = (@hidden_labels + LabelManager::RESERVED_LABELS).uniq
457     keepl, modifyl = thread.labels.partition { |t| speciall.member? t }
458
459     user_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", modifyl, @hidden_labels
460
461     return unless user_labels
462     thread.labels = keepl + user_labels
463     user_labels.each { |l| LabelManager << l }
464     update_text_for_line curpos
465     UpdateManager.relay self, :labeled, thread.first
466   end
467
468   def multi_edit_labels threads
469     user_labels = BufferManager.ask_for_labels :labels, "Add/remove labels (use -label to remove): ", [], @hidden_labels
470     return unless user_labels
471
472     user_labels.map! { |l| (l.to_s =~ /^-/)? [l.to_s.gsub(/^-?/, '').to_sym, true] : [l, false] }
473     hl = user_labels.select { |(l,_)| @hidden_labels.member? l }
474     if hl.empty?
475       threads.each do |t|
476         user_labels.each do |(l, to_remove)|
477           if to_remove
478             t.remove_label l
479           else
480             t.apply_label l
481           end
482         end
483       end
484       user_labels.each { |(l,_)| LabelManager << l }
485     else
486       BufferManager.flash "'#{hl}' is a reserved label!"
487     end
488     regen_text
489   end
490
491   def reply
492     t = cursor_thread or return
493     m = t.latest_message
494     return if m.nil? # probably won't happen
495     m.load_from_source!
496     mode = ReplyMode.new m
497     BufferManager.spawn "Reply to #{m.subj}", mode
498   end
499
500   def forward
501     t = cursor_thread or return
502     m = t.latest_message
503     return if m.nil? # probably won't happen
504     m.load_from_source!
505     ForwardMode.spawn_nicely :message => m
506   end
507
508   def load_n_threads_background n=LOAD_MORE_THREAD_NUM, opts={}
509     return if @load_thread # todo: wrap in mutex
510     @load_thread = Redwood::reporting_thread("load threads for thread-index-mode") do
511       num = load_n_threads n, opts
512       opts[:when_done].call(num) if opts[:when_done]
513       @load_thread = nil
514     end
515   end
516
517   ## TODO: figure out @ts_mutex in this method
518   def load_n_threads n=LOAD_MORE_THREAD_NUM, opts={}
519     @interrupt_search = false
520     @mbid = BufferManager.say "Searching for threads..."
521
522     ts_to_load = n
523     ts_to_load = ts_to_load + @ts.size unless n == -1 # -1 means all threads
524
525     orig_size = @ts.size
526     last_update = Time.now
527     @ts.load_n_threads(ts_to_load, opts) do |i|
528       if (Time.now - last_update) >= 0.25
529         BufferManager.say "Loaded #{i.pluralize 'thread'}...", @mbid
530         update
531         BufferManager.draw_screen
532         last_update = Time.now
533       end
534       break if @interrupt_search
535     end
536     @ts.threads.each { |th| th.labels.each { |l| LabelManager << l } }
537
538     update
539     BufferManager.clear @mbid
540     @mbid = nil
541     BufferManager.draw_screen
542     @ts.size - orig_size
543   end
544   ignore_concurrent_calls :load_n_threads
545
546   def status
547     if (l = lines) == 0
548       "line 0 of 0"
549     else
550       "line #{curpos + 1} of #{l} #{dirty? ? '*modified*' : ''}"
551     end
552   end
553
554   def cancel_search
555     @interrupt_search = true
556   end
557
558   def load_all_threads
559     load_threads :num => -1
560   end
561
562   def load_threads opts={}
563     if opts[:num].nil?
564       n = ThreadIndexMode::LOAD_MORE_THREAD_NUM
565     else
566       n = opts[:num]
567     end
568
569     myopts = @load_thread_opts.merge({ :when_done => (lambda do |num|
570       opts[:when_done].call(num) if opts[:when_done]
571
572       if num > 0
573         BufferManager.flash "Found #{num.pluralize 'thread'}."
574       else
575         BufferManager.flash "No matches."
576       end
577     end)})
578
579     if opts[:background] || opts[:background].nil?
580       load_n_threads_background n, myopts
581     else
582       load_n_threads n, myopts
583     end
584   end
585   ignore_concurrent_calls :load_threads
586
587   def resize rows, cols
588     regen_text
589     super
590   end
591
592 protected
593
594   def add_or_unhide m
595     @ts_mutex.synchronize do
596       if (is_relevant?(m) || @ts.is_relevant?(m)) && !@ts.contains?(m)
597         @ts.load_thread_for_message m, @load_thread_opts
598       end
599
600       @hidden_threads.delete @ts.thread_for(m)
601     end
602
603     update
604   end
605
606   def thread_containing m; @ts_mutex.synchronize { @ts.thread_for m } end
607
608   ## used to tag threads by query. this can be made a lot more sophisticated,
609   ## but for right now we'll do the obvious this.
610   def thread_matches? t, query
611     t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
612   end
613
614   def size_widget_for_thread t
615     HookManager.run("index-mode-size-widget", :thread => t) || default_size_widget_for(t)
616   end
617
618   def cursor_thread; @mutex.synchronize { @threads[curpos] }; end
619
620   def drop_all_threads
621     @tags.drop_all_tags
622     initialize_threads
623     update
624   end
625
626   def hide_thread t
627     @mutex.synchronize do
628       i = @threads.index(t) or return
629       raise "already hidden" if @hidden_threads[t]
630       @hidden_threads[t] = true
631       @threads.delete_at i
632       @size_widgets.delete_at i
633       @tags.drop_tag_for t
634     end
635   end
636
637   def update_text_for_line l
638     return unless l # not sure why this happens, but it does, occasionally
639     
640     need_update = false
641
642     @mutex.synchronize do
643       @size_widgets[l] = size_widget_for_thread @threads[l]
644
645       ## if the widget size has increased, we need to redraw everyone
646       need_update = @size_widgets[l].size > @size_widget_width
647     end
648
649     if need_update
650       update
651     else
652       @text[l] = text_for_thread_at l
653       buffer.mark_dirty if buffer
654     end
655   end
656
657   def regen_text
658     threads = @mutex.synchronize { @threads }
659     @text = threads.map_with_index { |t, i| text_for_thread_at i }
660     @lines = threads.map_with_index { |t, i| [t, i] }.to_h
661     buffer.mark_dirty if buffer
662   end
663   
664   def authors; map { |m, *o| m.from if m }.compact.uniq; end
665
666   def author_names_and_newness_for_thread t
667     new = {}
668     authors = t.map do |m, *o|
669       next unless m
670
671       name = 
672         if AccountManager.is_account?(m.from)
673           "me"
674         elsif t.authors.size == 1
675           m.from.mediumname
676         else
677           m.from.shortname
678         end
679
680       new[name] ||= m.has_label?(:unread)
681       name
682     end
683
684     authors.compact.uniq.map { |a| [a, new[a]] }
685   end
686
687   def text_for_thread_at line
688     t, size_widget = @mutex.synchronize { [@threads[line], @size_widgets[line]] }
689
690     date = t.date.to_nice_s
691
692     starred = t.has_label?(:starred)
693
694     ## format the from column
695     cur_width = 0
696     ann = author_names_and_newness_for_thread t
697     from = []
698     ann.each_with_index do |(name, newness), i|
699       break if cur_width >= from_width
700       last = i == ann.length - 1
701
702       abbrev =
703         if cur_width + name.length > from_width
704           name[0 ... (from_width - cur_width - 1)] + "."
705         elsif cur_width + name.length == from_width
706           name[0 ... (from_width - cur_width)]
707         else
708           if last
709             name[0 ... (from_width - cur_width)]
710           else
711             name[0 ... (from_width - cur_width - 1)] + "," 
712           end
713         end
714
715       cur_width += abbrev.length
716
717       if last && from_width > cur_width
718         abbrev += " " * (from_width - cur_width)
719       end
720
721       from << [(newness ? :index_new_color : (starred ? :index_starred_color : :index_old_color)), abbrev]
722     end
723
724     dp = t.direct_participants.any? { |p| AccountManager.is_account? p }
725     p = dp || t.participants.any? { |p| AccountManager.is_account? p }
726
727     subj_color =
728       if t.has_label?(:draft)
729         :index_draft_color
730       elsif t.has_label?(:unread)
731         :index_new_color
732       elsif starred
733         :index_starred_color
734       else 
735         :index_old_color
736       end
737
738     snippet = t.snippet + (t.snippet.empty? ? "" : "...")
739
740     size_widget_text = sprintf "%#{ @size_widget_width}s", size_widget
741
742     [ 
743       [:tagged_color, @tags.tagged?(t) ? ">" : " "],
744       [:none, sprintf("%#{@date_width}s", date)],
745       (starred ? [:starred_color, "*"] : [:none, " "]),
746     ] +
747       from +
748       [
749       [subj_color, size_widget_text],
750       [:to_me_color, t.labels.member?(:attachment) ? "@" : " "],
751       [:to_me_color, dp ? ">" : (p ? '+' : " ")],
752       [subj_color, t.subj + (t.subj.empty? ? "" : " ")],
753     ] +
754       (t.labels - @hidden_labels).map { |label| [:label_color, "+#{label} "] } +
755       [[:snippet_color, snippet]
756     ]
757   end
758
759   def dirty?; @mutex.synchronize { (@hidden_threads.keys + @threads).any? { |t| t.dirty? } } end
760
761 private
762
763   def default_size_widget_for t
764     case t.size
765     when 1
766       ""
767     else
768       "(#{t.size})"
769     end
770   end
771
772   def from_width
773     [(buffer.content_width.to_f * 0.2).to_i, MIN_FROM_WIDTH].max
774   end
775
776   def initialize_threads
777     @ts = ThreadSet.new Index.instance, $config[:thread_by_subject]
778     @ts_mutex = Mutex.new
779     @hidden_threads = {}
780   end
781 end
782
783 end