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