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