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