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