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