]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-index-mode.rb
save contacts.txt on '$'
[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 :add_labels, "Add labels: ", [], @hidden_labels
452     return unless user_labels
453     
454     hl = user_labels.select { |l| @hidden_labels.member? l }
455     if hl.empty?
456       threads.each { |t| user_labels.each { |l| t.apply_label l } }
457       user_labels.each { |l| LabelManager << l }
458     else
459       BufferManager.flash "'#{hl}' is a reserved label!"
460     end
461     regen_text
462   end
463
464   def reply
465     t = cursor_thread or return
466     m = t.latest_message
467     return if m.nil? # probably won't happen
468     m.load_from_source!
469     mode = ReplyMode.new m
470     BufferManager.spawn "Reply to #{m.subj}", mode
471   end
472
473   def forward
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     ForwardMode.spawn_nicely :message => m
479   end
480
481   def load_n_threads_background n=LOAD_MORE_THREAD_NUM, opts={}
482     return if @load_thread # todo: wrap in mutex
483     @load_thread = Redwood::reporting_thread("load threads for thread-index-mode") do
484       num = load_n_threads n, opts
485       opts[:when_done].call(num) if opts[:when_done]
486       @load_thread = nil
487     end
488   end
489
490   ## TODO: figure out @ts_mutex in this method
491   def load_n_threads n=LOAD_MORE_THREAD_NUM, opts={}
492     @interrupt_search = false
493     @mbid = BufferManager.say "Searching for threads..."
494
495     ts_to_load = n
496     ts_to_load = ts_to_load + @ts.size unless n == -1 # -1 means all threads
497
498     orig_size = @ts.size
499     last_update = Time.now
500     @ts.load_n_threads(ts_to_load, opts) do |i|
501       if (Time.now - last_update) >= 0.25
502         BufferManager.say "Loaded #{i.pluralize 'thread'}...", @mbid
503         update
504         BufferManager.draw_screen
505         last_update = Time.now
506       end
507       break if @interrupt_search
508     end
509     @ts.threads.each { |th| th.labels.each { |l| LabelManager << l } }
510
511     update
512     BufferManager.clear @mbid
513     @mbid = nil
514     BufferManager.draw_screen
515     @ts.size - orig_size
516   end
517   ignore_concurrent_calls :load_n_threads
518
519   def status
520     if (l = lines) == 0
521       "line 0 of 0"
522     else
523       "line #{curpos + 1} of #{l} #{dirty? ? '*modified*' : ''}"
524     end
525   end
526
527   def cancel_search
528     @interrupt_search = true
529   end
530
531   def load_all_threads
532     load_threads :num => -1
533   end
534
535   def load_threads opts={}
536     if opts[:num].nil?
537       n = ThreadIndexMode::LOAD_MORE_THREAD_NUM
538     else
539       n = opts[:num]
540     end
541
542     myopts = @load_thread_opts.merge({ :when_done => (lambda do |num|
543       opts[:when_done].call(num) if opts[:when_done]
544
545       if num > 0
546         BufferManager.flash "Found #{num.pluralize 'thread'}."
547       else
548         BufferManager.flash "No matches."
549       end
550     end)})
551
552     if opts[:background] || opts[:background].nil?
553       load_n_threads_background n, myopts
554     else
555       load_n_threads n, myopts
556     end
557   end
558   ignore_concurrent_calls :load_threads
559
560   def resize rows, cols
561     regen_text
562     super
563   end
564
565 protected
566
567   def add_or_unhide m
568     @ts_mutex.synchronize do
569       if (is_relevant?(m) || @ts.is_relevant?(m)) && !@ts.contains?(m)
570         @ts.load_thread_for_message m
571       end
572
573       @hidden_threads.delete @ts.thread_for(m)
574     end
575
576     update
577   end
578
579   def thread_containing m; @ts_mutex.synchronize { @ts.thread_for m } end
580
581   ## used to tag threads by query. this can be made a lot more sophisticated,
582   ## but for right now we'll do the obvious this.
583   def thread_matches? t, query
584     t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
585   end
586
587   def size_widget_for_thread t
588     HookManager.run("index-mode-size-widget", :thread => t) || default_size_widget_for(t)
589   end
590
591   def cursor_thread; @mutex.synchronize { @threads[curpos] }; end
592
593   def drop_all_threads
594     @tags.drop_all_tags
595     initialize_threads
596     update
597   end
598
599   def hide_thread t
600     @mutex.synchronize do
601       i = @threads.index(t) or return
602       raise "already hidden" if @hidden_threads[t]
603       @hidden_threads[t] = true
604       @threads.delete_at i
605       @size_widgets.delete_at i
606       @tags.drop_tag_for t
607     end
608   end
609
610   def update_text_for_line l
611     return unless l # not sure why this happens, but it does, occasionally
612     
613     need_update = false
614
615     @mutex.synchronize do
616       @size_widgets[l] = size_widget_for_thread @threads[l]
617
618       ## if the widget size has increased, we need to redraw everyone
619       need_update = @size_widgets[l].size > @size_widget_width
620     end
621
622     if need_update
623       update
624     else
625       @text[l] = text_for_thread_at l
626       buffer.mark_dirty if buffer
627     end
628   end
629
630   def regen_text
631     threads = @mutex.synchronize { @threads }
632     @text = threads.map_with_index { |t, i| text_for_thread_at i }
633     @lines = threads.map_with_index { |t, i| [t, i] }.to_h
634     buffer.mark_dirty if buffer
635   end
636   
637   def authors; map { |m, *o| m.from if m }.compact.uniq; end
638
639   def author_names_and_newness_for_thread t
640     new = {}
641     authors = t.map do |m, *o|
642       next unless m
643
644       name = 
645         if AccountManager.is_account?(m.from)
646           "me"
647         elsif t.authors.size == 1
648           m.from.mediumname
649         else
650           m.from.shortname
651         end
652
653       new[name] ||= m.has_label?(:unread)
654       name
655     end
656
657     authors.compact.uniq.map { |a| [a, new[a]] }
658   end
659
660   def text_for_thread_at line
661     t, size_widget = @mutex.synchronize { [@threads[line], @size_widgets[line]] }
662
663     date = t.date.to_nice_s
664
665     starred = t.has_label?(:starred)
666
667     ## format the from column
668     cur_width = 0
669     ann = author_names_and_newness_for_thread t
670     from = []
671     ann.each_with_index do |(name, newness), i|
672       break if cur_width >= from_width
673       last = i == ann.length - 1
674
675       abbrev =
676         if cur_width + name.length > from_width
677           name[0 ... (from_width - cur_width - 1)] + "."
678         elsif cur_width + name.length == from_width
679           name[0 ... (from_width - cur_width)]
680         else
681           if last
682             name[0 ... (from_width - cur_width)]
683           else
684             name[0 ... (from_width - cur_width - 1)] + "," 
685           end
686         end
687
688       cur_width += abbrev.length
689
690       if last && from_width > cur_width
691         abbrev += " " * (from_width - cur_width)
692       end
693
694       from << [(newness ? :index_new_color : (starred ? :index_starred_color : :index_old_color)), abbrev]
695     end
696
697     dp = t.direct_participants.any? { |p| AccountManager.is_account? p }
698     p = dp || t.participants.any? { |p| AccountManager.is_account? p }
699
700     subj_color =
701       if t.has_label?(:draft)
702         :index_draft_color
703       elsif t.has_label?(:unread)
704         :index_new_color
705       elsif starred
706         :index_starred_color
707       else 
708         :index_old_color
709       end
710
711     snippet = t.snippet + (t.snippet.empty? ? "" : "...")
712
713     size_widget_text = sprintf "%#{ @size_widget_width}s", size_widget
714
715     [ 
716       [:tagged_color, @tags.tagged?(t) ? ">" : " "],
717       [:none, sprintf("%#{@date_width}s", date)],
718       (starred ? [:starred_color, "*"] : [:none, " "]),
719     ] +
720       from +
721       [
722       [subj_color, size_widget_text],
723       [:to_me_color, t.labels.member?(:attachment) ? "@" : " "],
724       [:to_me_color, dp ? ">" : (p ? '+' : " ")],
725       [subj_color, t.subj + (t.subj.empty? ? "" : " ")],
726     ] +
727       (t.labels - @hidden_labels).map { |label| [:label_color, "+#{label} "] } +
728       [[:snippet_color, snippet]
729     ]
730
731   end
732
733   def dirty?; @mutex.synchronize { (@hidden_threads.keys + @threads).any? { |t| t.dirty? } } end
734
735 private
736
737   def default_size_widget_for t
738     case t.size
739     when 1
740       ""
741     else
742       "(#{t.size})"
743     end
744   end
745
746   def from_width
747     [(buffer.content_width.to_f * 0.2).to_i, MIN_FROM_WIDTH].max
748   end
749
750   def initialize_threads
751     @ts = ThreadSet.new Index.instance, $config[:thread_by_subject]
752     @ts_mutex = Mutex.new
753     @hidden_threads = {}
754   end
755 end
756
757 end