]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-index-mode.rb
Merge branch 'sup-sync-improvements' into next
[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   HookManager.register "mark-as-spam", <<EOS
18 This hook is run when a thread is marked as spam
19 Variables:
20   thread: The message thread being marked as spam.
21 EOS
22
23   register_keymap do |k|
24     k.add :load_threads, "Load #{LOAD_MORE_THREAD_NUM} more threads", 'M'
25     k.add_multi "Load all threads (! to confirm) :", '!' do |kk|
26       kk.add :load_all_threads, "Load all threads (may list a _lot_ of threads)", '!'
27     end
28     k.add :cancel_search, "Cancel current search", :ctrl_g
29     k.add :reload, "Refresh view", '@'
30     k.add :toggle_archived, "Toggle archived status", 'a'
31     k.add :toggle_starred, "Star or unstar all messages in thread", '*'
32     k.add :toggle_new, "Toggle new/read status of all messages in thread", 'N'
33     k.add :edit_labels, "Edit or add labels for a thread", 'l'
34     k.add :edit_message, "Edit message (drafts only)", 'e'
35     k.add :toggle_spam, "Mark/unmark thread as spam", 'S'
36     k.add :toggle_deleted, "Delete/undelete thread", 'd'
37     k.add :kill, "Kill thread (never to be seen in inbox again)", '&'
38     k.add :save, "Save changes now", '$'
39     k.add :jump_to_next_new, "Jump to next new thread", :tab
40     k.add :reply, "Reply to latest message in a thread", 'r'
41     k.add :forward, "Forward latest message in a thread", 'f'
42     k.add :toggle_tagged, "Tag/untag selected thread", 't'
43     k.add :toggle_tagged_all, "Tag/untag all threads", 'T'
44     k.add :tag_matching, "Tag matching threads", 'g'
45     k.add :apply_to_tagged, "Apply next command to all tagged threads", '+'
46     k.add :join_threads, "Force tagged threads to be joined into the same thread", '#'
47     k.add :undo, "Undo the previous action", 'u'
48   end
49
50   def initialize hidden_labels=[], load_thread_opts={}
51     super()
52     @mutex = Mutex.new # covers the following variables:
53     @threads = {}
54     @hidden_threads = {}
55     @size_widget_width = nil
56     @size_widgets = {}
57     @tags = Tagger.new self
58
59     ## these guys, and @text and @lines, are not covered
60     @load_thread = nil
61     @load_thread_opts = load_thread_opts
62     @hidden_labels = hidden_labels + LabelManager::HIDDEN_RESERVED_LABELS
63     @date_width = DATE_WIDTH
64
65     @interrupt_search = false
66     
67     initialize_threads # defines @ts and @ts_mutex
68     update # defines @text and @lines
69
70     UpdateManager.register self
71
72     @save_thread_mutex = Mutex.new
73
74     @last_load_more_size = nil
75     to_load_more do |size|
76       next if @last_load_more_size == 0
77       load_threads :num => 1, :background => false
78       load_threads :num => (size - 1),
79                    :when_done => lambda { |num| @last_load_more_size = num }
80     end
81   end
82
83   def unsaved?; dirty? end
84   def lines; @text.length; end
85   def [] i; @text[i]; end
86   def contains_thread? t; @threads.include?(t) end
87
88   def reload
89     drop_all_threads
90     UndoManager.clear
91     BufferManager.draw_screen
92     load_threads :num => buffer.content_height
93   end
94
95   ## open up a thread view window
96   def select t=nil, when_done=nil
97     t ||= cursor_thread or return
98
99     Redwood::reporting_thread("load messages for thread-view-mode") do
100       num = t.size
101       message = "Loading #{num.pluralize 'message body'}..."
102       BufferManager.say(message) do |sid|
103         t.each_with_index do |(m, *o), i|
104           next unless m
105           BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1
106           m.load_from_source! 
107         end
108       end
109       mode = ThreadViewMode.new t, @hidden_labels, self
110       BufferManager.spawn t.subj, mode
111       BufferManager.draw_screen
112       mode.jump_to_first_open true
113       BufferManager.draw_screen # lame TODO: make this unnecessary
114       ## the first draw_screen is needed before topline and botline
115       ## are set, and the second to show the cursor having moved
116
117       update_text_for_line curpos
118       UpdateManager.relay self, :read, t.first
119       when_done.call if when_done
120     end
121   end
122
123   def multi_select threads
124     threads.each { |t| select t }
125   end
126
127   ## these two methods are called by thread-view-modes when the user
128   ## wants to view the previous/next thread without going back to
129   ## index-mode. we update the cursor as a convenience.
130   def launch_next_thread_after thread, &b
131     launch_another_thread thread, 1, &b
132   end
133
134   def launch_prev_thread_before thread, &b
135     launch_another_thread thread, -1, &b
136   end
137
138   def launch_another_thread thread, direction, &b
139     l = @lines[thread] or return
140     target_l = l + direction
141     t = @mutex.synchronize do
142       if target_l >= 0 && target_l < @threads.length
143         @threads[target_l]
144       end
145     end
146
147     if t # there's a next thread
148       set_cursor_pos target_l # move out of mutex?
149       select t, b
150     elsif b # no next thread. call the block anyways
151       b.call
152     end
153   end
154   
155   def handle_single_message_labeled_update sender, m
156     ## no need to do anything different here; we don't differentiate 
157     ## messages from their containing threads
158     handle_labeled_update sender, m
159   end
160
161   def handle_labeled_update sender, m
162     if(t = thread_containing(m)) 
163       l = @lines[t] or return
164       update_text_for_line l
165     elsif is_relevant?(m)
166       add_or_unhide m
167     end
168   end
169
170   def handle_simple_update sender, m
171     t = thread_containing(m) or return
172     l = @lines[t] or return
173     update_text_for_line l
174   end
175
176   %w(read unread archived starred unstarred).each do |state|
177     define_method "handle_#{state}_update" do |*a|
178       handle_simple_update(*a)
179     end
180   end
181
182   ## overwrite me!
183   def is_relevant? m; false; end
184
185   def handle_added_update sender, m
186     add_or_unhide m
187     BufferManager.draw_screen
188   end
189
190   def handle_single_message_deleted_update sender, m
191     @ts_mutex.synchronize do
192       return unless @ts.contains? m
193       @ts.remove_id m.id
194     end
195     update
196   end
197
198   def handle_deleted_update sender, m
199     t = @ts_mutex.synchronize { @ts.thread_for m }
200     return unless t
201     hide_thread t
202     update
203   end
204
205   def handle_spammed_update sender, m
206     t = @ts_mutex.synchronize { @ts.thread_for m }
207     return unless t
208     hide_thread t
209     update
210   end
211
212   def handle_undeleted_update sender, m
213     add_or_unhide m
214   end
215
216   def undo
217     UndoManager.undo
218   end
219
220   def update
221     @mutex.synchronize do
222       ## let's see you do THIS in python
223       @threads = @ts.threads.select { |t| !@hidden_threads[t] }.sort_by { |t| [t.date, t.first.id] }.reverse
224       @size_widgets = @threads.map { |t| size_widget_for_thread t }
225       @size_widget_width = @size_widgets.max_of { |w| w.length }
226     end
227
228     regen_text
229   end
230
231   def edit_message
232     return unless(t = cursor_thread)
233     message, *crap = t.find { |m, *o| m.has_label? :draft }
234     if message
235       mode = ResumeMode.new message
236       BufferManager.spawn "Edit message", mode
237     else
238       BufferManager.flash "Not a draft message!"
239     end
240   end
241
242   def actually_toggle_starred t
243     thread = t # cargo cult programming
244     pos = curpos
245     if t.has_label? :starred # if ANY message has a star
246       undo = lambda {
247         thread.first.add_label :starred
248         update_text_for_line pos
249         UpdateManager.relay self, :starred, thread.first
250       }
251       t.remove_label :starred # remove from all
252       UpdateManager.relay self, :unstarred, t.first
253     else
254       undo = lambda {
255         thread.remove_label :starred
256         update_text_for_line pos
257         UpdateManager.relay self, :unstarred, thread.first
258       }
259       t.first.add_label :starred # add only to first
260       UpdateManager.relay self, :starred, t.first
261     end
262
263     return undo
264   end  
265
266   def toggle_starred 
267     t = cursor_thread or return
268     undo = actually_toggle_starred t
269     UndoManager.register("starring/unstarring thread #{t.first.id}",undo)
270     update_text_for_line curpos
271     cursor_down
272   end
273
274   def multi_toggle_starred threads
275     undo = threads.map { |t| actually_toggle_starred t }
276     UndoManager.register("starring/unstarring #{threads.size} #{threads.size.pluralize 'thread'}",
277                          undo)
278     regen_text
279   end
280
281   def actually_toggle_archived t
282     thread = t
283     pos = curpos
284     if t.has_label? :inbox
285       t.remove_label :inbox
286       undo = lambda {
287         thread.apply_label :inbox
288         update_text_for_line pos
289         UpdateManager.relay self,:unarchived, thread.first
290       }
291       UpdateManager.relay self, :archived, t.first
292     else
293       t.apply_label :inbox
294       undo = lambda {
295         thread.remove_label :inbox
296         update_text_for_line pos
297         UpdateManager.relay self, :unarchived, thread.first
298       }
299       UpdateManager.relay self, :unarchived, t.first
300     end
301
302     return undo
303   end
304
305   def actually_toggle_spammed t
306     thread = t
307     if t.has_label? :spam
308       undo = lambda {
309         thread.apply_label :spam
310         self.hide_thread thread
311         UpdateManager.relay self,:spammed, thread.first
312       }
313       t.remove_label :spam
314       add_or_unhide t.first
315       UpdateManager.relay self, :unspammed, t.first
316     else
317       undo = lambda {
318         thread.remove_label :spam
319         add_or_unhide thread.first
320         UpdateManager.relay self,:unspammed, thread.first
321       }
322       t.apply_label :spam
323       hide_thread t
324       UpdateManager.relay self, :spammed, t.first
325     end
326
327     return undo
328   end
329
330   def actually_toggle_deleted t
331     if t.has_label? :deleted
332       undo = lambda {
333         t.apply_label :deleted
334         hide_thread t
335         UpdateManager.relay self, :deleted, t.first
336       }
337       t.remove_label :deleted
338       add_or_unhide t.first
339       UpdateManager.relay self, :undeleted, t.first
340     else
341       undo = lambda {
342         t.remove_label :deleted
343         add_or_unhide t.first
344         UpdateManager.relay self, :undeleted, t.first
345       }
346       t.apply_label :deleted
347   hide_thread t
348       UpdateManager.relay self, :deleted, t.first
349     end
350
351     return undo
352   end
353
354   def toggle_archived 
355     t = cursor_thread or return
356     undo = [actually_toggle_archived(t), lambda {self.update_text_for_line curpos}]
357     UndoManager.register("deleting/undeleting thread #{t.first.id}",undo)
358     update_text_for_line curpos
359   end
360
361   def multi_toggle_archived threads
362     undo = threads.map { |t| actually_toggle_archived t}
363     UndoManager.register("deleting/undeleting #{threads.size} #{threads.size.pluralize 'thread'}",
364                          undo << lambda {self.regen_text})
365     regen_text
366   end
367
368   def toggle_new
369     t = cursor_thread or return
370     t.toggle_label :unread
371     update_text_for_line curpos
372     cursor_down
373   end
374
375   def multi_toggle_new threads
376     threads.each { |t| t.toggle_label :unread }
377     regen_text
378   end
379
380   def multi_toggle_tagged threads
381     @mutex.synchronize { @tags.drop_all_tags }
382     regen_text
383   end
384
385   def join_threads
386     ## this command has no non-tagged form. as a convenience, allow this
387     ## command to be applied to tagged threads without hitting ';'.
388     @tags.apply_to_tagged :join_threads
389   end
390
391   def multi_join_threads threads
392     @ts.join_threads threads or return
393     @tags.drop_all_tags # otherwise we have tag pointers to invalid threads!
394     update
395   end
396
397   def jump_to_next_new
398     n = @mutex.synchronize do
399       ((curpos + 1) ... lines).find { |i| @threads[i].has_label? :unread } ||
400         (0 ... curpos).find { |i| @threads[i].has_label? :unread }
401     end
402     if n
403       ## jump there if necessary
404       jump_to_line n unless n >= topline && n < botline
405       set_cursor_pos n
406     else
407       BufferManager.flash "No new messages"
408     end
409   end
410
411   def toggle_spam
412     t = cursor_thread or return
413     multi_toggle_spam [t]
414     HookManager.run("mark-as-spam", :thread => t)
415   end
416
417   ## both spam and deleted have the curious characteristic that you
418   ## always want to hide the thread after either applying or removing
419   ## that label. in all thread-index-views except for
420   ## label-search-results-mode, when you mark a message as spam or
421   ## deleted, you want it to disappear immediately; in LSRM, you only
422   ## see deleted or spam emails, and when you undelete or unspam them
423   ## you also want them to disappear immediately.
424   def multi_toggle_spam threads
425     undo = threads.map{ |t| actually_toggle_spammed t}
426     UndoManager.register("marking/unmarking #{threads.size} #{threads.size.pluralize 'thread'} as spam",
427                          undo <<  lambda {self.regen_text})
428     regen_text
429   end
430
431   def toggle_deleted
432     t = cursor_thread or return
433     multi_toggle_deleted [t]
434   end
435
436   ## see comment for multi_toggle_spam
437   def multi_toggle_deleted threads
438     undo = threads.map{ |t| actually_toggle_deleted t}
439     UndoManager.register("deleting/undeleting #{threads.size} #{threads.size.pluralize 'thread'}",
440                          undo << lambda {regen_text})
441     regen_text
442   end
443
444   def kill
445     t = cursor_thread or return
446     multi_kill [t]
447   end
448
449   ## m-m-m-m-MULTI-KILL
450   def multi_kill threads
451     undo = threads.map do |t|
452       t.apply_label :killed
453       hide_thread t
454       thread = t
455       lambda { thread.remove_label :killed
456         add_or_unhide thread.first
457       }
458     end
459     UndoManager.register("killing #{threads.size} #{threads.size.pluralize 'thread'}",
460                          undo << lambda {regen_text})
461     regen_text
462     BufferManager.flash "#{threads.size.pluralize 'Thread'} killed."
463   end
464
465   def save background=true
466     if background
467       Redwood::reporting_thread("saving thread") { actually_save }
468     else
469       actually_save
470     end
471   end
472
473   def actually_save
474     @save_thread_mutex.synchronize do
475       BufferManager.say("Saving contacts...") { ContactManager.instance.save }
476       dirty_threads = @mutex.synchronize { (@threads + @hidden_threads.keys).select { |t| t.dirty? } }
477       next if dirty_threads.empty?
478
479       BufferManager.say("Saving threads...") do |say_id|
480         dirty_threads.each_with_index do |t, i|
481           BufferManager.say "Saving modified thread #{i + 1} of #{dirty_threads.length}...", say_id
482           t.save Index
483         end
484       end
485     end
486   end
487
488   def cleanup
489     UpdateManager.unregister self
490
491     if @load_thread
492       @load_thread.kill 
493       BufferManager.clear @mbid if @mbid
494       sleep 0.1 # TODO: necessary?
495       BufferManager.erase_flash
496     end
497     save false
498     super
499   end
500
501   def toggle_tagged
502     t = cursor_thread or return
503     @mutex.synchronize { @tags.toggle_tag_for t }
504     update_text_for_line curpos
505     cursor_down
506   end
507   
508   def toggle_tagged_all
509     @mutex.synchronize { @threads.each { |t| @tags.toggle_tag_for t } }
510     regen_text
511   end
512
513   def tag_matching
514     query = BufferManager.ask :search, "tag threads matching (regex): "
515     return if query.nil? || query.empty?
516     query = begin
517       /#{query}/i
518     rescue RegexpError => e
519       BufferManager.flash "error interpreting '#{query}': #{e.message}"
520       return
521     end
522     @mutex.synchronize { @threads.each { |t| @tags.tag t if thread_matches?(t, query) } }
523     regen_text
524   end
525
526   def apply_to_tagged; @tags.apply_to_tagged; end
527
528   def edit_labels
529     thread = cursor_thread or return
530     speciall = (@hidden_labels + LabelManager::RESERVED_LABELS).uniq
531
532     old_labels = thread.labels
533     pos = curpos
534
535     keepl, modifyl = thread.labels.partition { |t| speciall.member? t }
536
537     user_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", modifyl, @hidden_labels
538
539     return unless user_labels
540     thread.labels = keepl + user_labels
541     user_labels.each { |l| LabelManager << l }
542     update_text_for_line curpos
543
544     undo = lambda{
545       thread.labels = old_labels
546       update_text_for_line pos
547       UpdateManager.relay self, :labeled, thread.first
548     }
549
550     UndoManager.register("labeling thread #{thread.first.id}", undo)
551
552     UpdateManager.relay self, :labeled, thread.first
553   end
554
555   def multi_edit_labels threads
556     user_labels = BufferManager.ask_for_labels :labels, "Add/remove labels (use -label to remove): ", [], @hidden_labels
557     return unless user_labels
558
559     user_labels.map! { |l| (l.to_s =~ /^-/)? [l.to_s.gsub(/^-?/, '').to_sym, true] : [l, false] }
560     hl = user_labels.select { |(l,_)| @hidden_labels.member? l }
561     if hl.empty?
562       undo = threads.map do |t|
563         old_labels = t.labels
564         user_labels.each do |(l, to_remove)|
565           if to_remove
566             t.remove_label l
567           else
568             t.apply_label l
569           end
570         end
571         ## UpdateManager or some other regresh mechanism?
572         UpdateManager.relay self, :labeled, t.first
573         lambda do
574           t.labels = old_labels
575           UpdateManager.relay self, :labeled, t.first
576         end
577       end
578       user_labels.each { |(l,_)| LabelManager << l }
579       UndoManager.register("labeling #{threads.size} #{threads.size.pluralize 'thread'}",
580                           undo << lambda { regen_text})
581     else
582       BufferManager.flash "'#{hl}' is a reserved label!"
583     end
584     regen_text
585   end
586
587   def reply
588     t = cursor_thread or return
589     m = t.latest_message
590     return if m.nil? # probably won't happen
591     m.load_from_source!
592     mode = ReplyMode.new m
593     BufferManager.spawn "Reply to #{m.subj}", mode
594   end
595
596   def forward
597     t = cursor_thread or return
598     m = t.latest_message
599     return if m.nil? # probably won't happen
600     m.load_from_source!
601     ForwardMode.spawn_nicely :message => m
602   end
603
604   def load_n_threads_background n=LOAD_MORE_THREAD_NUM, opts={}
605     return if @load_thread # todo: wrap in mutex
606     @load_thread = Redwood::reporting_thread("load threads for thread-index-mode") do
607       num = load_n_threads n, opts
608       opts[:when_done].call(num) if opts[:when_done]
609       @load_thread = nil
610     end
611   end
612
613   ## TODO: figure out @ts_mutex in this method
614   def load_n_threads n=LOAD_MORE_THREAD_NUM, opts={}
615     @interrupt_search = false
616     @mbid = BufferManager.say "Searching for threads..."
617
618     ts_to_load = n
619     ts_to_load = ts_to_load + @ts.size unless n == -1 # -1 means all threads
620
621     orig_size = @ts.size
622     last_update = Time.now
623     @ts.load_n_threads(ts_to_load, opts) do |i|
624       if (Time.now - last_update) >= 0.25
625         BufferManager.say "Loaded #{i.pluralize 'thread'}...", @mbid
626         update
627         BufferManager.draw_screen
628         last_update = Time.now
629       end
630       break if @interrupt_search
631     end
632     @ts.threads.each { |th| th.labels.each { |l| LabelManager << l } }
633
634     update
635     BufferManager.clear @mbid
636     @mbid = nil
637     BufferManager.draw_screen
638     @ts.size - orig_size
639   end
640   ignore_concurrent_calls :load_n_threads
641
642   def status
643     if (l = lines) == 0
644       "line 0 of 0"
645     else
646       "line #{curpos + 1} of #{l} #{dirty? ? '*modified*' : ''}"
647     end
648   end
649
650   def cancel_search
651     @interrupt_search = true
652   end
653
654   def load_all_threads
655     load_threads :num => -1
656   end
657
658   def load_threads opts={}
659     if opts[:num].nil?
660       n = ThreadIndexMode::LOAD_MORE_THREAD_NUM
661     else
662       n = opts[:num]
663     end
664
665     myopts = @load_thread_opts.merge({ :when_done => (lambda do |num|
666       opts[:when_done].call(num) if opts[:when_done]
667
668       if num > 0
669         BufferManager.flash "Found #{num.pluralize 'thread'}."
670       else
671         BufferManager.flash "No matches."
672       end
673     end)})
674
675     if opts[:background] || opts[:background].nil?
676       load_n_threads_background n, myopts
677     else
678       load_n_threads n, myopts
679     end
680   end
681   ignore_concurrent_calls :load_threads
682
683   def resize rows, cols
684     regen_text
685     super
686   end
687
688 protected
689
690   def add_or_unhide m
691     @ts_mutex.synchronize do
692       if (is_relevant?(m) || @ts.is_relevant?(m)) && !@ts.contains?(m)
693         @ts.load_thread_for_message m, @load_thread_opts
694       end
695
696       @hidden_threads.delete @ts.thread_for(m)
697     end
698
699     update
700   end
701
702   def thread_containing m; @ts_mutex.synchronize { @ts.thread_for m } end
703
704   ## used to tag threads by query. this can be made a lot more sophisticated,
705   ## but for right now we'll do the obvious this.
706   def thread_matches? t, query
707     t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
708   end
709
710   def size_widget_for_thread t
711     HookManager.run("index-mode-size-widget", :thread => t) || default_size_widget_for(t)
712   end
713
714   def cursor_thread; @mutex.synchronize { @threads[curpos] }; end
715
716   def drop_all_threads
717     @tags.drop_all_tags
718     initialize_threads
719     update
720   end
721
722   def hide_thread t
723     @mutex.synchronize do
724       i = @threads.index(t) or return
725       raise "already hidden" if @hidden_threads[t]
726       @hidden_threads[t] = true
727       @threads.delete_at i
728       @size_widgets.delete_at i
729       @tags.drop_tag_for t
730     end
731   end
732
733   def update_text_for_line l
734     return unless l # not sure why this happens, but it does, occasionally
735     
736     need_update = false
737
738     @mutex.synchronize do
739       @size_widgets[l] = size_widget_for_thread @threads[l]
740
741       ## if the widget size has increased, we need to redraw everyone
742       need_update = @size_widgets[l].size > @size_widget_width
743     end
744
745     if need_update
746       update
747     else
748       @text[l] = text_for_thread_at l
749       buffer.mark_dirty if buffer
750     end
751   end
752
753   def regen_text
754     threads = @mutex.synchronize { @threads }
755     @text = threads.map_with_index { |t, i| text_for_thread_at i }
756     @lines = threads.map_with_index { |t, i| [t, i] }.to_h
757     buffer.mark_dirty if buffer
758   end
759   
760   def authors; map { |m, *o| m.from if m }.compact.uniq; end
761
762   def author_names_and_newness_for_thread t
763     new = {}
764     authors = t.map do |m, *o|
765       next unless m
766
767       name = 
768         if AccountManager.is_account?(m.from)
769           "me"
770         elsif t.authors.size == 1
771           m.from.mediumname
772         else
773           m.from.shortname
774         end
775
776       new[name] ||= m.has_label?(:unread)
777       name
778     end
779
780     authors.compact.uniq.map { |a| [a, new[a]] }
781   end
782
783   def text_for_thread_at line
784     t, size_widget = @mutex.synchronize { [@threads[line], @size_widgets[line]] }
785
786     date = t.date.to_nice_s
787
788     starred = t.has_label?(:starred)
789
790     ## format the from column
791     cur_width = 0
792     ann = author_names_and_newness_for_thread t
793     from = []
794     ann.each_with_index do |(name, newness), i|
795       break if cur_width >= from_width
796       last = i == ann.length - 1
797
798       abbrev =
799         if cur_width + name.length > from_width
800           name[0 ... (from_width - cur_width - 1)] + "."
801         elsif cur_width + name.length == from_width
802           name[0 ... (from_width - cur_width)]
803         else
804           if last
805             name[0 ... (from_width - cur_width)]
806           else
807             name[0 ... (from_width - cur_width - 1)] + "," 
808           end
809         end
810
811       cur_width += abbrev.length
812
813       if last && from_width > cur_width
814         abbrev += " " * (from_width - cur_width)
815       end
816
817       from << [(newness ? :index_new_color : (starred ? :index_starred_color : :index_old_color)), abbrev]
818     end
819
820     dp = t.direct_participants.any? { |p| AccountManager.is_account? p }
821     p = dp || t.participants.any? { |p| AccountManager.is_account? p }
822
823     subj_color =
824       if t.has_label?(:draft)
825         :index_draft_color
826       elsif t.has_label?(:unread)
827         :index_new_color
828       elsif starred
829         :index_starred_color
830       else 
831         :index_old_color
832       end
833
834     snippet = t.snippet + (t.snippet.empty? ? "" : "...")
835
836     size_widget_text = sprintf "%#{ @size_widget_width}s", size_widget
837
838     [ 
839       [:tagged_color, @tags.tagged?(t) ? ">" : " "],
840       [:none, sprintf("%#{@date_width}s", date)],
841       (starred ? [:starred_color, "*"] : [:none, " "]),
842     ] +
843       from +
844       [
845       [subj_color, size_widget_text],
846       [:to_me_color, t.labels.member?(:attachment) ? "@" : " "],
847       [:to_me_color, dp ? ">" : (p ? '+' : " ")],
848       [subj_color, t.subj + (t.subj.empty? ? "" : " ")],
849     ] +
850       (t.labels - @hidden_labels).map { |label| [:label_color, "+#{label} "] } +
851       [[:snippet_color, snippet]
852     ]
853   end
854
855   def dirty?; @mutex.synchronize { (@hidden_threads.keys + @threads).any? { |t| t.dirty? } } end
856
857 private
858
859   def default_size_widget_for t
860     case t.size
861     when 1
862       ""
863     else
864       "(#{t.size})"
865     end
866   end
867
868   def from_width
869     [(buffer.content_width.to_f * 0.2).to_i, MIN_FROM_WIDTH].max
870   end
871
872   def initialize_threads
873     @ts = ThreadSet.new Index.instance, $config[:thread_by_subject]
874     @ts_mutex = Mutex.new
875     @hidden_threads = {}
876   end
877 end
878
879 end