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