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