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