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