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