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