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