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