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