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