]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-index-mode.rb
Added UndoManager class
[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     k.add :undo, "Undo the previous action", 'u'
48   end
49
50   def initialize hidden_labels=[], load_thread_opts={}
51     super()
52     @mutex = Mutex.new # covers the following variables:
53     @threads = {}
54     @hidden_threads = {}
55     @size_widget_width = nil
56     @size_widgets = {}
57     @tags = Tagger.new self
58
59     ## these guys, and @text and @lines, are not covered
60     @load_thread = nil
61     @load_thread_opts = load_thread_opts
62     @hidden_labels = hidden_labels + LabelManager::HIDDEN_RESERVED_LABELS
63     @date_width = DATE_WIDTH
64
65     @interrupt_search = false
66     
67     initialize_threads # defines @ts and @ts_mutex
68     update # defines @text and @lines
69
70     UpdateManager.register self
71
72     @last_load_more_size = nil
73     to_load_more do |size|
74       next if @last_load_more_size == 0
75       load_threads :num => 1, :background => false
76       load_threads :num => (size - 1),
77                    :when_done => lambda { |num| @last_load_more_size = num }
78     end
79   end
80
81   def lines; @text.length; end
82   def [] i; @text[i]; end
83   def contains_thread? t; @threads.include?(t) end
84
85   def reload
86     drop_all_threads
87     UndoManager.clear
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 undo
214     UndoManager.undo
215   end
216
217   def update
218     @mutex.synchronize do
219       ## let's see you do THIS in python
220       @threads = @ts.threads.select { |t| !@hidden_threads[t] }.sort_by { |t| [t.date, t.first.id] }.reverse
221       @size_widgets = @threads.map { |t| size_widget_for_thread t }
222       @size_widget_width = @size_widgets.max_of { |w| w.length }
223     end
224
225     regen_text
226   end
227
228   def edit_message
229     return unless(t = cursor_thread)
230     message, *crap = t.find { |m, *o| m.has_label? :draft }
231     if message
232       mode = ResumeMode.new message
233       BufferManager.spawn "Edit message", mode
234     else
235       BufferManager.flash "Not a draft message!"
236     end
237   end
238
239   def actually_toggle_starred t
240     if t.has_label? :starred # if ANY message has a star
241       t.remove_label :starred # remove from all
242       UpdateManager.relay self, :unstarred, t.first
243     else
244       t.first.add_label :starred # add only to first
245       UpdateManager.relay self, :starred, t.first
246     end
247   end  
248
249   def toggle_starred 
250     t = cursor_thread or return
251     actually_toggle_starred t
252     update_text_for_line curpos
253     cursor_down
254   end
255
256   def multi_toggle_starred threads
257     threads.each { |t| actually_toggle_starred t }
258     regen_text
259   end
260
261   def actually_toggle_archived t
262     if t.has_label? :inbox
263       t.remove_label :inbox
264       UpdateManager.relay self, :archived, t.first
265     else
266       t.apply_label :inbox
267       UpdateManager.relay self, :unarchived, t.first
268     end
269   end
270
271   def actually_toggle_spammed t
272     if t.has_label? :spam
273       t.remove_label :spam
274       UpdateManager.relay self, :unspammed, t.first
275     else
276       t.apply_label :spam
277       UpdateManager.relay self, :spammed, t.first
278     end
279   end
280
281   def actually_toggle_deleted t
282     if t.has_label? :deleted
283       t.remove_label :deleted
284       UpdateManager.relay self, :undeleted, t.first
285     else
286       t.apply_label :deleted
287       UpdateManager.relay self, :deleted, t.first
288     end
289   end
290
291   def toggle_archived 
292     t = cursor_thread or return
293     actually_toggle_archived t
294     update_text_for_line curpos
295   end
296
297   def multi_toggle_archived threads
298     threads.each { |t| actually_toggle_archived t }
299     regen_text
300   end
301
302   def toggle_new
303     t = cursor_thread or return
304     t.toggle_label :unread
305     update_text_for_line curpos
306     cursor_down
307   end
308
309   def multi_toggle_new threads
310     threads.each { |t| t.toggle_label :unread }
311     regen_text
312   end
313
314   def multi_toggle_tagged threads
315     @mutex.synchronize { @tags.drop_all_tags }
316     regen_text
317   end
318
319   def join_threads
320     ## this command has no non-tagged form. as a convenience, allow this
321     ## command to be applied to tagged threads without hitting ';'.
322     @tags.apply_to_tagged :join_threads
323   end
324
325   def multi_join_threads threads
326     @ts.join_threads threads or return
327     @tags.drop_all_tags # otherwise we have tag pointers to invalid threads!
328     update
329   end
330
331   def jump_to_next_new
332     n = @mutex.synchronize do
333       ((curpos + 1) ... lines).find { |i| @threads[i].has_label? :unread } ||
334         (0 ... curpos).find { |i| @threads[i].has_label? :unread }
335     end
336     if n
337       ## jump there if necessary
338       jump_to_line n unless n >= topline && n < botline
339       set_cursor_pos n
340     else
341       BufferManager.flash "No new messages"
342     end
343   end
344
345   def toggle_spam
346     t = cursor_thread or return
347     multi_toggle_spam [t]
348     HookManager.run("mark-as-spam", :thread => t)
349   end
350
351   ## both spam and deleted have the curious characteristic that you
352   ## always want to hide the thread after either applying or removing
353   ## that label. in all thread-index-views except for
354   ## label-search-results-mode, when you mark a message as spam or
355   ## deleted, you want it to disappear immediately; in LSRM, you only
356   ## see deleted or spam emails, and when you undelete or unspam them
357   ## you also want them to disappear immediately.
358   def multi_toggle_spam threads
359     threads.each do |t|
360       actually_toggle_spammed t
361       hide_thread t 
362     end
363     regen_text
364   end
365
366   def toggle_deleted
367     t = cursor_thread or return
368     multi_toggle_deleted [t]
369   end
370
371   ## see comment for multi_toggle_spam
372   def multi_toggle_deleted threads
373     threads.each do |t|
374       actually_toggle_deleted t
375       hide_thread t 
376     end
377     regen_text
378   end
379
380   def kill
381     t = cursor_thread or return
382     multi_kill [t]
383   end
384
385   def multi_kill threads
386     threads.each do |t|
387       t.apply_label :killed
388       hide_thread t
389     end
390     regen_text
391     BufferManager.flash "#{threads.size.pluralize 'Thread'} killed."
392   end
393
394   def save
395     dirty_threads = @mutex.synchronize { (@threads + @hidden_threads.keys).select { |t| t.dirty? } }
396     return if dirty_threads.empty?
397
398     BufferManager.say("Saving threads...") do |say_id|
399       dirty_threads.each_with_index do |t, i|
400         BufferManager.say "Saving modified thread #{i + 1} of #{dirty_threads.length}...", say_id
401         t.save Index
402       end
403     end
404   end
405
406   def cleanup
407     UpdateManager.unregister self
408
409     if @load_thread
410       @load_thread.kill 
411       BufferManager.clear @mbid if @mbid
412       sleep 0.1 # TODO: necessary?
413       BufferManager.erase_flash
414     end
415     save
416     super
417   end
418
419   def toggle_tagged
420     t = cursor_thread or return
421     @mutex.synchronize { @tags.toggle_tag_for t }
422     update_text_for_line curpos
423     cursor_down
424   end
425   
426   def toggle_tagged_all
427     @mutex.synchronize { @threads.each { |t| @tags.toggle_tag_for t } }
428     regen_text
429   end
430
431   def tag_matching
432     query = BufferManager.ask :search, "tag threads matching: "
433     return if query.nil? || query.empty?
434     query = /#{query}/i
435     @mutex.synchronize { @threads.each { |t| @tags.tag t if thread_matches?(t, query) } }
436     regen_text
437   end
438
439   def apply_to_tagged; @tags.apply_to_tagged; end
440
441   def edit_labels
442     thread = cursor_thread or return
443     speciall = (@hidden_labels + LabelManager::RESERVED_LABELS).uniq
444     keepl, modifyl = thread.labels.partition { |t| speciall.member? t }
445
446     user_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", modifyl, @hidden_labels
447
448     return unless user_labels
449     thread.labels = keepl + user_labels
450     user_labels.each { |l| LabelManager << l }
451     update_text_for_line curpos
452     UpdateManager.relay self, :labeled, thread.first
453   end
454
455   def multi_edit_labels threads
456     user_labels = BufferManager.ask_for_labels :add_labels, "Add labels: ", [], @hidden_labels
457     return unless user_labels
458     
459     hl = user_labels.select { |l| @hidden_labels.member? l }
460     if hl.empty?
461       threads.each { |t| user_labels.each { |l| t.apply_label l } }
462       user_labels.each { |l| LabelManager << l }
463     else
464       BufferManager.flash "'#{hl}' is a reserved label!"
465     end
466     regen_text
467   end
468
469   def reply
470     t = cursor_thread or return
471     m = t.latest_message
472     return if m.nil? # probably won't happen
473     m.load_from_source!
474     mode = ReplyMode.new m
475     BufferManager.spawn "Reply to #{m.subj}", mode
476   end
477
478   def forward
479     t = cursor_thread or return
480     m = t.latest_message
481     return if m.nil? # probably won't happen
482     m.load_from_source!
483     ForwardMode.spawn_nicely :message => m
484   end
485
486   def load_n_threads_background n=LOAD_MORE_THREAD_NUM, opts={}
487     return if @load_thread # todo: wrap in mutex
488     @load_thread = Redwood::reporting_thread("load threads for thread-index-mode") do
489       num = load_n_threads n, opts
490       opts[:when_done].call(num) if opts[:when_done]
491       @load_thread = nil
492     end
493   end
494
495   ## TODO: figure out @ts_mutex in this method
496   def load_n_threads n=LOAD_MORE_THREAD_NUM, opts={}
497     @interrupt_search = false
498     @mbid = BufferManager.say "Searching for threads..."
499
500     ts_to_load = n
501     ts_to_load = ts_to_load + @ts.size unless n == -1 # -1 means all threads
502
503     orig_size = @ts.size
504     last_update = Time.now
505     @ts.load_n_threads(ts_to_load, opts) do |i|
506       if (Time.now - last_update) >= 0.25
507         BufferManager.say "Loaded #{i.pluralize 'thread'}...", @mbid
508         update
509         BufferManager.draw_screen
510         last_update = Time.now
511       end
512       break if @interrupt_search
513     end
514     @ts.threads.each { |th| th.labels.each { |l| LabelManager << l } }
515
516     update
517     BufferManager.clear @mbid
518     @mbid = nil
519     BufferManager.draw_screen
520     @ts.size - orig_size
521   end
522   ignore_concurrent_calls :load_n_threads
523
524   def status
525     if (l = lines) == 0
526       "line 0 of 0"
527     else
528       "line #{curpos + 1} of #{l} #{dirty? ? '*modified*' : ''}"
529     end
530   end
531
532   def cancel_search
533     @interrupt_search = true
534   end
535
536   def load_all_threads
537     load_threads :num => -1
538   end
539
540   def load_threads opts={}
541     if opts[:num].nil?
542       n = ThreadIndexMode::LOAD_MORE_THREAD_NUM
543     else
544       n = opts[:num]
545     end
546
547     myopts = @load_thread_opts.merge({ :when_done => (lambda do |num|
548       opts[:when_done].call(num) if opts[:when_done]
549
550       if num > 0
551         BufferManager.flash "Found #{num.pluralize 'thread'}."
552       else
553         BufferManager.flash "No matches."
554       end
555     end)})
556
557     if opts[:background] || opts[:background].nil?
558       load_n_threads_background n, myopts
559     else
560       load_n_threads n, myopts
561     end
562   end
563   ignore_concurrent_calls :load_threads
564
565   def resize rows, cols
566     regen_text
567     super
568   end
569
570 protected
571
572   def add_or_unhide m
573     @ts_mutex.synchronize do
574       if (is_relevant?(m) || @ts.is_relevant?(m)) && !@ts.contains?(m)
575         @ts.load_thread_for_message m
576       end
577
578       @hidden_threads.delete @ts.thread_for(m)
579     end
580
581     update
582   end
583
584   def thread_containing m; @ts_mutex.synchronize { @ts.thread_for m } end
585
586   ## used to tag threads by query. this can be made a lot more sophisticated,
587   ## but for right now we'll do the obvious this.
588   def thread_matches? t, query
589     t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
590   end
591
592   def size_widget_for_thread t
593     HookManager.run("index-mode-size-widget", :thread => t) || default_size_widget_for(t)
594   end
595
596   def cursor_thread; @mutex.synchronize { @threads[curpos] }; end
597
598   def drop_all_threads
599     @tags.drop_all_tags
600     initialize_threads
601     update
602   end
603
604   def hide_thread t
605     @mutex.synchronize do
606       i = @threads.index(t) or return
607       raise "already hidden" if @hidden_threads[t]
608       @hidden_threads[t] = true
609       @threads.delete_at i
610       @size_widgets.delete_at i
611       @tags.drop_tag_for t
612     end
613   end
614
615   def update_text_for_line l
616     return unless l # not sure why this happens, but it does, occasionally
617     
618     need_update = false
619
620     @mutex.synchronize do
621       @size_widgets[l] = size_widget_for_thread @threads[l]
622
623       ## if the widget size has increased, we need to redraw everyone
624       need_update = @size_widgets[l].size > @size_widget_width
625     end
626
627     if need_update
628       update
629     else
630       @text[l] = text_for_thread_at l
631       buffer.mark_dirty if buffer
632     end
633   end
634
635   def regen_text
636     threads = @mutex.synchronize { @threads }
637     @text = threads.map_with_index { |t, i| text_for_thread_at i }
638     @lines = threads.map_with_index { |t, i| [t, i] }.to_h
639     buffer.mark_dirty if buffer
640   end
641   
642   def authors; map { |m, *o| m.from if m }.compact.uniq; end
643
644   def author_names_and_newness_for_thread t
645     new = {}
646     authors = t.map do |m, *o|
647       next unless m
648
649       name = 
650         if AccountManager.is_account?(m.from)
651           "me"
652         elsif t.authors.size == 1
653           m.from.mediumname
654         else
655           m.from.shortname
656         end
657
658       new[name] ||= m.has_label?(:unread)
659       name
660     end
661
662     authors.compact.uniq.map { |a| [a, new[a]] }
663   end
664
665   def text_for_thread_at line
666     t, size_widget = @mutex.synchronize { [@threads[line], @size_widgets[line]] }
667
668     date = t.date.to_nice_s
669
670     starred = t.has_label?(:starred)
671
672     ## format the from column
673     cur_width = 0
674     ann = author_names_and_newness_for_thread t
675     from = []
676     ann.each_with_index do |(name, newness), i|
677       break if cur_width >= from_width
678       last = i == ann.length - 1
679
680       abbrev =
681         if cur_width + name.length > from_width
682           name[0 ... (from_width - cur_width - 1)] + "."
683         elsif cur_width + name.length == from_width
684           name[0 ... (from_width - cur_width)]
685         else
686           if last
687             name[0 ... (from_width - cur_width)]
688           else
689             name[0 ... (from_width - cur_width - 1)] + "," 
690           end
691         end
692
693       cur_width += abbrev.length
694
695       if last && from_width > cur_width
696         abbrev += " " * (from_width - cur_width)
697       end
698
699       from << [(newness ? :index_new_color : (starred ? :index_starred_color : :index_old_color)), abbrev]
700     end
701
702     dp = t.direct_participants.any? { |p| AccountManager.is_account? p }
703     p = dp || t.participants.any? { |p| AccountManager.is_account? p }
704
705     subj_color =
706       if t.has_label?(:draft)
707         :index_draft_color
708       elsif t.has_label?(:unread)
709         :index_new_color
710       elsif starred
711         :index_starred_color
712       else 
713         :index_old_color
714       end
715
716     snippet = t.snippet + (t.snippet.empty? ? "" : "...")
717
718     size_widget_text = sprintf "%#{ @size_widget_width}s", size_widget
719
720     [ 
721       [:tagged_color, @tags.tagged?(t) ? ">" : " "],
722       [:none, sprintf("%#{@date_width}s", date)],
723       (starred ? [:starred_color, "*"] : [:none, " "]),
724     ] +
725       from +
726       [
727       [subj_color, size_widget_text],
728       [:to_me_color, t.labels.member?(:attachment) ? "@" : " "],
729       [:to_me_color, dp ? ">" : (p ? '+' : " ")],
730       [subj_color, t.subj + (t.subj.empty? ? "" : " ")],
731     ] +
732       (t.labels - @hidden_labels).map { |label| [:label_color, "+#{label} "] } +
733       [[:snippet_color, snippet]
734     ]
735
736   end
737
738   def dirty?; @mutex.synchronize { (@hidden_threads.keys + @threads).any? { |t| t.dirty? } } end
739
740 private
741
742   def default_size_widget_for t
743     case t.size
744     when 1
745       ""
746     else
747       "(#{t.size})"
748     end
749   end
750
751   def from_width
752     [(buffer.content_width.to_f * 0.2).to_i, MIN_FROM_WIDTH].max
753   end
754
755   def initialize_threads
756     @ts = ThreadSet.new Index.instance, $config[:thread_by_subject]
757     @ts_mutex = Mutex.new
758     @hidden_threads = {}
759   end
760 end
761
762 end