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