]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
make thread-view-mode 'n' and 'p' work with unreceived messages
[sup] / lib / sup / modes / thread-view-mode.rb
1 require 'open3'
2 module Redwood
3
4 class ThreadViewMode < LineCursorMode
5   ## this holds all info we need to lay out a message
6   class MessageLayout
7     attr_accessor :top, :bot, :prev, :next, :depth, :width, :state, :color, :star_color, :orig_new
8   end
9
10   class ChunkLayout
11     attr_accessor :state
12   end
13
14   DATE_FORMAT = "%B %e %Y %l:%M%P"
15   INDENT_SPACES = 2 # how many spaces to indent child messages
16
17   HookManager.register "detailed-headers", <<EOS
18 Add or remove headers from the detailed header display of a message.
19 Variables:
20   message: The message whose headers are to be formatted.
21   headers: A hash of header (name, value) pairs, initialized to the default
22            headers.
23 Return value:
24   None. The variable 'headers' should be modified in place.
25 EOS
26
27   register_keymap do |k|
28     k.add :toggle_detailed_header, "Toggle detailed header", 'h'
29     k.add :show_header, "Show full message header", 'H'
30     k.add :activate_chunk, "Expand/collapse or activate item", :enter
31     k.add :expand_all_messages, "Expand/collapse all messages", 'E'
32     k.add :edit_draft, "Edit draft", 'e'
33     k.add :edit_labels, "Edit or add labels for a thread", 'l'
34     k.add :expand_all_quotes, "Expand/collapse all quotes in a message", 'o'
35     k.add :jump_to_next_open, "Jump to next open message", 'n'
36     k.add :jump_to_prev_open, "Jump to previous open message", 'p'
37     k.add :toggle_starred, "Star or unstar message", '*'
38     k.add :toggle_new, "Toggle unread/read status of message", 'N'
39 #    k.add :collapse_non_new_messages, "Collapse all but unread messages", 'N'
40     k.add :reply, "Reply to a message", 'r'
41     k.add :forward, "Forward a message or attachment", 'f'
42     k.add :alias, "Edit alias/nickname for a person", 'i'
43     k.add :edit_as_new, "Edit message as new", 'D'
44     k.add :save_to_disk, "Save message/attachment to disk", 's'
45     k.add :search, "Search for messages from particular people", 'S'
46     k.add :compose, "Compose message to person", 'm'
47     k.add :subscribe_to_list, "Subscribe to/unsubscribe from mailing list", "("
48     k.add :unsubscribe_from_list, "Subscribe to/unsubscribe from mailing list", ")"
49     k.add :pipe_message, "Pipe message or attachment to a shell command", '|'
50
51     k.add_multi "(A)rchive/(d)elete/mark as (s)pam/mark as u(N)read:", '.' do |kk|
52       kk.add :archive_and_kill, "Archive this thread and kill buffer", 'a'
53       kk.add :delete_and_kill, "Delete this thread and kill buffer", 'd'
54       kk.add :spam_and_kill, "Mark this thread as spam and kill buffer", 's'
55       kk.add :unread_and_kill, "Mark this thread as unread and kill buffer", 'N'
56     end
57
58     k.add_multi "(A)rchive/(d)elete/mark as (s)pam/mark as u(N)read/do (n)othing:", ',' do |kk|
59       kk.add :archive_and_next, "Archive this thread, kill buffer, and view next", 'a'
60       kk.add :delete_and_next, "Delete this thread, kill buffer, and view next", 'd'
61       kk.add :spam_and_next, "Mark this thread as spam, kill buffer, and view next", 's'
62       kk.add :unread_and_next, "Mark this thread as unread, kill buffer, and view next", 'N'
63       kk.add :do_nothing_and_next, "Kill buffer, and view next", 'n'
64     end
65   end
66
67   ## there are a couple important instance variables we hold to format
68   ## the thread and to provide line-based functionality. @layout is a
69   ## map from Messages to MessageLayouts, and @chunk_layout from
70   ## Chunks to ChunkLayouts.  @message_lines is a map from row #s to
71   ## Message objects.  @chunk_lines is a map from row #s to Chunk
72   ## objects. @person_lines is a map from row #s to Person objects.
73
74   def initialize thread, hidden_labels=[], index_mode=nil
75     super()
76     @thread = thread
77     @hidden_labels = hidden_labels
78
79     ## used for dispatch-and-next
80     @index_mode = index_mode
81     @dying = false
82
83     @layout = SavingHash.new { MessageLayout.new }
84     @chunk_layout = SavingHash.new { ChunkLayout.new }
85     earliest, latest = nil, nil
86     latest_date = nil
87     altcolor = false
88
89     @thread.each do |m, d, p|
90       next unless m
91       earliest ||= m
92       @layout[m].state = initial_state_for m
93       @layout[m].color = altcolor ? :alternate_patina_color : :message_patina_color
94       @layout[m].star_color = altcolor ? :alternate_starred_patina_color : :starred_patina_color
95       @layout[m].orig_new = m.has_label? :read
96       altcolor = !altcolor
97       if latest_date.nil? || m.date > latest_date
98         latest_date = m.date
99         latest = m
100       end
101     end
102
103     @layout[latest].state = :open if @layout[latest].state == :closed
104     @layout[earliest].state = :detailed if earliest.has_label?(:unread) || @thread.size == 1
105
106     @thread.remove_label :unread
107     regen_text
108   end
109
110   def draw_line ln, opts={}
111     if ln == curpos
112       super ln, :highlight => true
113     else
114       super
115     end
116   end
117   def lines; @text.length; end
118   def [] i; @text[i]; end
119
120   def show_header
121     m = @message_lines[curpos] or return
122     BufferManager.spawn_unless_exists("Full header for #{m.id}") do
123       TextMode.new m.raw_header
124     end
125   end
126
127   def toggle_detailed_header
128     m = @message_lines[curpos] or return
129     @layout[m].state = (@layout[m].state == :detailed ? :open : :detailed)
130     update
131   end
132
133   def reply
134     m = @message_lines[curpos] or return
135     mode = ReplyMode.new m
136     BufferManager.spawn "Reply to #{m.subj}", mode
137   end
138
139   def subscribe_to_list
140     m = @message_lines[curpos] or return
141     if m.list_subscribe && m.list_subscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
142       ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
143     else
144       BufferManager.flash "Can't find List-Subscribe header for this message."
145     end
146   end
147
148   def unsubscribe_from_list
149     m = @message_lines[curpos] or return
150     if m.list_unsubscribe && m.list_unsubscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
151       ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
152     else
153       BufferManager.flash "Can't find List-Unsubscribe header for this message."
154     end
155   end
156
157   def forward
158     if(chunk = @chunk_lines[curpos]) && chunk.is_a?(Chunk::Attachment)
159       ForwardMode.spawn_nicely :attachments => [chunk]
160     elsif(m = @message_lines[curpos])
161       ForwardMode.spawn_nicely :message => m
162     end
163   end
164
165   include CanAliasContacts
166   def alias
167     p = @person_lines[curpos] or return
168     alias_contact p
169     update
170   end
171
172   def search
173     p = @person_lines[curpos] or return
174     mode = PersonSearchResultsMode.new [p]
175     BufferManager.spawn "Search for #{p.name}", mode
176     mode.load_threads :num => mode.buffer.content_height
177   end    
178
179   def compose
180     p = @person_lines[curpos]
181     if p
182       ComposeMode.spawn_nicely :to => [p]
183     else
184       ComposeMode.spawn_nicely
185     end
186   end    
187
188   def edit_labels
189     reserved_labels = @thread.labels.select { |l| LabelManager::RESERVED_LABELS.include? l }
190     new_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", @thread.labels
191
192     return unless new_labels
193     @thread.labels = (reserved_labels + new_labels).uniq
194     new_labels.each { |l| LabelManager << l }
195     update
196     UpdateManager.relay self, :labeled, @thread.first
197   end
198
199   def toggle_starred
200     m = @message_lines[curpos] or return
201     toggle_label m, :starred
202   end
203
204   def toggle_new
205     m = @message_lines[curpos] or return
206     toggle_label m, :unread
207   end
208
209   def toggle_label m, label
210     if m.has_label? label
211       m.remove_label label
212     else
213       m.add_label label
214     end
215     ## TODO: don't recalculate EVERYTHING just to add a stupid little
216     ## star to the display
217     update
218     UpdateManager.relay self, :single_message_labeled, m
219   end
220
221   ## called when someone presses enter when the cursor is highlighting
222   ## a chunk. for expandable chunks (including messages) we toggle
223   ## open/closed state; for viewable chunks (like attachments) we
224   ## view.
225   def activate_chunk
226     chunk = @chunk_lines[curpos] or return
227     layout = 
228       if chunk.is_a?(Message)
229         @layout[chunk]
230       elsif chunk.expandable?
231         @chunk_layout[chunk]
232       end
233     if layout
234       layout.state = (layout.state != :closed ? :closed : :open)
235       #cursor_down if layout.state == :closed # too annoying
236       update
237     elsif chunk.viewable?
238       view chunk
239     end
240   end
241
242   def edit_as_new
243     m = @message_lines[curpos] or return
244     mode = ComposeMode.new(:body => m.quotable_body_lines, :to => m.to, :cc => m.cc, :subj => m.subj, :bcc => m.bcc)
245     BufferManager.spawn "edit as new", mode
246     mode.edit_message
247   end
248
249   def save_to_disk
250     chunk = @chunk_lines[curpos] or return
251     case chunk
252     when Chunk::Attachment
253       fn = BufferManager.ask_for_filename :filename, "Save attachment to file: ", chunk.filename
254       save_to_file(fn) { |f| f.print chunk.raw_content } if fn
255     else
256       m = @message_lines[curpos]
257       fn = BufferManager.ask_for_filename :filename, "Save message to file: "
258       return unless fn
259       save_to_file(fn) do |f|
260         m.each_raw_message_line { |l| f.print l }
261       end
262     end
263   end
264
265   def edit_draft
266     m = @message_lines[curpos] or return
267     if m.is_draft?
268       mode = ResumeMode.new m
269       BufferManager.spawn "Edit message", mode
270       BufferManager.kill_buffer self.buffer
271       mode.edit_message
272     else
273       BufferManager.flash "Not a draft message!"
274     end
275   end
276
277   def jump_to_first_open
278     m = @message_lines[0] or return
279     if @layout[m].state != :closed
280       jump_to_message m
281     else
282       jump_to_next_open
283     end
284   end
285
286   def jump_to_next_open
287     return continue_search_in_buffer if in_search? # hack: allow 'n' to apply to both operations
288     m = (curpos ... @message_lines.length).argfind { |i| @message_lines[i] }
289     return unless m
290     while nextm = @layout[m].next
291       break if @layout[nextm].state != :closed
292       m = nextm
293     end
294     jump_to_message nextm if nextm
295   end
296
297   def jump_to_prev_open
298     m = (0 .. curpos).to_a.reverse.argfind { |i| @message_lines[i] } # bah, .to_a
299     return unless m
300     ## jump to the top of the current message if we're in the body;
301     ## otherwise, to the previous message
302     
303     top = @layout[m].top
304     if curpos == top
305       while(prevm = @layout[m].prev)
306         break if @layout[prevm].state != :closed
307         m = prevm
308       end
309       jump_to_message prevm if prevm
310     else
311       jump_to_message m
312     end
313   end
314
315   def jump_to_message m
316     l = @layout[m]
317     left = l.depth * INDENT_SPACES
318     right = left + l.width
319
320     ## jump to the top line unless both top and bottom fit in the current view
321     jump_to_line l.top unless l.top >= topline && l.top <= botline && l.bot >= topline && l.bot <= botline
322
323     ## jump to the left columns unless both left and right fit in the current view
324     jump_to_col left unless left >= leftcol && left <= rightcol && right >= leftcol && right <= rightcol
325
326     ## either way, move the cursor to the first line
327     set_cursor_pos l.top
328   end
329
330   def expand_all_messages
331     @global_message_state ||= :closed
332     @global_message_state = (@global_message_state == :closed ? :open : :closed)
333     @layout.each { |m, l| l.state = @global_message_state }
334     update
335   end
336
337   def collapse_non_new_messages
338     @layout.each { |m, l| l.state = l.orig_new ? :open : :closed }
339     update
340   end
341
342   def expand_all_quotes
343     if(m = @message_lines[curpos])
344       quotes = m.chunks.select { |c| (c.is_a?(Chunk::Quote) || c.is_a?(Chunk::Signature)) && c.lines.length > 1 }
345       numopen = quotes.inject(0) { |s, c| s + (@chunk_layout[c].state == :open ? 1 : 0) }
346       newstate = numopen > quotes.length / 2 ? :closed : :open
347       quotes.each { |c| @chunk_layout[c].state = newstate }
348       update
349     end
350   end
351
352   def cleanup
353     @layout = @chunk_layout = @text = nil # for good luck
354   end
355
356   def archive_and_kill; archive_and_then :kill end
357   def spam_and_kill; spam_and_then :kill end
358   def delete_and_kill; delete_and_then :kill end
359   def unread_and_kill; unread_and_then :kill end
360
361   def archive_and_next; archive_and_then :next end
362   def spam_and_next; spam_and_then :next end
363   def delete_and_next; delete_and_then :next end
364   def unread_and_next; unread_and_then :next end
365   def do_nothing_and_next; do_nothing_and_then :next end
366
367   def archive_and_then op
368     dispatch op do
369       @thread.remove_label :inbox
370       UpdateManager.relay self, :archived, @thread.first
371     end
372   end
373
374   def spam_and_then op
375     dispatch op do
376       @thread.apply_label :spam
377       UpdateManager.relay self, :spammed, @thread.first
378     end
379   end
380
381   def delete_and_then op
382     dispatch op do
383       @thread.apply_label :deleted
384       UpdateManager.relay self, :deleted, @thread.first
385     end
386   end
387
388   def unread_and_then op
389     dispatch op do
390       @thread.apply_label :unread
391       UpdateManager.relay self, :unread, @thread.first
392     end
393   end
394
395   def do_nothing_and_then op
396     dispatch op
397   end
398
399   def dispatch op
400     return if @dying
401     @dying = true
402
403     case op
404     when :next
405       @index_mode.launch_next_thread_after(@thread) do
406         @thread.save Index if block_given? && yield
407         BufferManager.kill_buffer_safely buffer
408       end
409     when :kill
410       @thread.save Index if yield
411       BufferManager.kill_buffer_safely buffer
412     else
413       raise ArgumentError, "unknown thread dispatch operation #{op.inspect}"
414     end
415   end
416   private :dispatch
417
418   def pipe_message
419     chunk = @chunk_lines[curpos]
420     chunk = nil unless chunk.is_a?(Chunk::Attachment)
421     message = @message_lines[curpos] unless chunk
422
423     return unless chunk || message
424
425     command = BufferManager.ask(:shell, "pipe command: ")
426     return if command.nil? || command.empty?
427
428     output = pipe_to_process(command) do |stream|
429       if chunk
430         stream.print chunk.raw_content
431       else
432         message.each_raw_message_line { |l| stream.print l }
433       end
434     end
435
436     if output
437       BufferManager.spawn "Output of '#{command}'", TextMode.new(output)
438     else
439       BufferManager.flash "'#{command}' done!"
440     end
441   end
442
443 private
444
445   def initial_state_for m
446     if m.has_label?(:starred) || m.has_label?(:unread)
447       :open
448     else
449       :closed
450     end
451   end
452
453   def update
454     regen_text
455     buffer.mark_dirty if buffer
456   end
457
458   ## here we generate the actual content lines. we accumulate
459   ## everything into @text, and we set @chunk_lines and
460   ## @message_lines, and we update @layout.
461   def regen_text
462     @text = []
463     @chunk_lines = []
464     @message_lines = []
465     @person_lines = []
466
467     prevm = nil
468     @thread.each do |m, depth, parent|
469       unless m.is_a? Message # handle nil and :fake_root
470         @text += chunk_to_lines m, nil, @text.length, depth, parent
471         next
472       end
473       l = @layout[m]
474
475       ## is this still necessary?
476       next unless @layout[m].state # skip discarded drafts
477
478       ## build the patina
479       text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
480       
481       l.top = @text.length
482       l.bot = @text.length + text.length # updated below
483       l.prev = prevm
484       l.next = nil
485       l.depth = depth
486       # l.state we preserve
487       l.width = 0 # updated below
488       @layout[l.prev].next = m if l.prev
489
490       (0 ... text.length).each do |i|
491         @chunk_lines[@text.length + i] = m
492         @message_lines[@text.length + i] = m
493         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
494       end
495
496       @text += text
497       prevm = m 
498       if l.state != :closed
499         m.chunks.each do |c|
500           cl = @chunk_layout[c]
501
502           ## set the default state for chunks
503           cl.state ||=
504             if c.expandable? && c.respond_to?(:initial_state)
505               c.initial_state
506             else
507               :closed
508             end
509
510           text = chunk_to_lines c, cl.state, @text.length, depth
511           (0 ... text.length).each do |i|
512             @chunk_lines[@text.length + i] = c
513             @message_lines[@text.length + i] = m
514             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
515             l.width = lw if lw > l.width
516           end
517           @text += text
518         end
519         @layout[m].bot = @text.length
520       end
521     end
522   end
523
524   def message_patina_lines m, state, start, parent, prefix, color, star_color
525     prefix_widget = [color, prefix]
526
527     open_widget = [color, (state == :closed ? "+ " : "- ")]
528     new_widget = [color, (m.has_label?(:unread) ? "N" : " ")]
529     starred_widget = 
530       if m.has_label?(:starred)
531         [star_color, "* "]
532       else
533         [color, "  "]
534       end
535
536     case state
537     when :open
538       @person_lines[start] = m.from
539       [[prefix_widget, open_widget, new_widget, starred_widget,
540         [color, 
541             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
542
543     when :closed
544       @person_lines[start] = m.from
545       [[prefix_widget, open_widget, new_widget, starred_widget,
546         [color, 
547         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
548
549     when :detailed
550       @person_lines[start] = m.from
551       from_line = [[prefix_widget, open_widget, new_widget, starred_widget,
552           [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
553
554       addressee_lines = []
555       unless m.to.empty?
556         m.to.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
557         addressee_lines += format_person_list "   To: ", m.to
558       end
559       unless m.cc.empty?
560         m.cc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
561         addressee_lines += format_person_list "   Cc: ", m.cc
562       end
563       unless m.bcc.empty?
564         m.bcc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
565         addressee_lines += format_person_list "   Bcc: ", m.bcc
566       end
567
568       headers = OrderedHash.new
569       headers["Date"] = "#{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})"
570       headers["Subject"] = m.subj
571
572       show_labels = @thread.labels - LabelManager::HIDDEN_RESERVED_LABELS
573       unless show_labels.empty?
574         headers["Labels"] = show_labels.map { |x| x.to_s }.sort.join(', ')
575       end
576       if parent
577         headers["In reply to"] = "#{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}"
578       end
579
580       HookManager.run "detailed-headers", :message => m, :headers => headers
581       
582       from_line + (addressee_lines + headers.map { |k, v| "   #{k}: #{v}" }).map { |l| [[color, prefix + "  " + l]] }
583     end
584   end
585
586   def format_person_list prefix, people
587     ptext = people.map { |p| format_person p }
588     pad = " " * prefix.length
589     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
590       ptext[1 .. -1].map_with_index do |e, i|
591         pad + e + (i == ptext.length - 1 ? "" : ",")
592       end
593   end
594
595   def format_person p
596     p.longname + (ContactManager.is_aliased_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
597   end
598
599   ## todo: check arguments on this overly complex function
600   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil, star_color=nil
601     prefix = " " * INDENT_SPACES * depth
602     case chunk
603     when :fake_root
604       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
605     when nil
606       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
607     when Message
608       message_patina_lines(chunk, state, start, parent, prefix, color, star_color) +
609         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
610
611     else
612       raise "Bad chunk: #{chunk.inspect}" unless chunk.respond_to?(:inlineable?) ## debugging
613       if chunk.inlineable?
614         chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
615       elsif chunk.expandable?
616         case state
617         when :closed
618           [[[chunk.patina_color, "#{prefix}+ #{chunk.patina_text}"]]]
619         when :open
620           [[[chunk.patina_color, "#{prefix}- #{chunk.patina_text}"]]] + chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
621         end
622       else
623         [[[chunk.patina_color, "#{prefix}x #{chunk.patina_text}"]]]
624       end
625     end
626   end
627
628   def view chunk
629     BufferManager.flash "viewing #{chunk.content_type} attachment..."
630     success = chunk.view!
631     BufferManager.erase_flash
632     BufferManager.completely_redraw_screen
633     unless success
634       BufferManager.spawn "Attachment: #{chunk.filename}", TextMode.new(chunk.to_s, chunk.filename)
635       BufferManager.flash "Couldn't execute view command, viewing as text."
636     end
637   end
638 end
639
640 end