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