]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
move pipe-to-process functionality to a helper method in Mode
[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     output = pipe_to_process(command) do |stream|
360       if chunk
361         stream.print chunk.raw_content
362       else
363         message.each_raw_message_line { |l| stream.print l }
364       end
365     end
366
367     if output
368       BufferManager.spawn "Output of '#{command}'", TextMode.new(output)
369     else
370       BufferManager.flash "'#{command}' done!"
371     end
372   end
373
374 private
375
376   def initial_state_for m
377     if m.has_label?(:starred) || m.has_label?(:unread)
378       :open
379     else
380       :closed
381     end
382   end
383
384   def update
385     regen_text
386     buffer.mark_dirty if buffer
387   end
388
389   ## here we generate the actual content lines. we accumulate
390   ## everything into @text, and we set @chunk_lines and
391   ## @message_lines, and we update @layout.
392   def regen_text
393     @text = []
394     @chunk_lines = []
395     @message_lines = []
396     @person_lines = []
397
398     prevm = nil
399     @thread.each do |m, depth, parent|
400       unless m.is_a? Message # handle nil and :fake_root
401         @text += chunk_to_lines m, nil, @text.length, depth, parent
402         next
403       end
404       l = @layout[m]
405
406       ## is this still necessary?
407       next unless @layout[m].state # skip discarded drafts
408
409       ## build the patina
410       text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
411       
412       l.top = @text.length
413       l.bot = @text.length + text.length # updated below
414       l.prev = prevm
415       l.next = nil
416       l.depth = depth
417       # l.state we preserve
418       l.width = 0 # updated below
419       @layout[l.prev].next = m if l.prev
420
421       (0 ... text.length).each do |i|
422         @chunk_lines[@text.length + i] = m
423         @message_lines[@text.length + i] = m
424         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
425       end
426
427       @text += text
428       prevm = m 
429       if l.state != :closed
430         m.chunks.each do |c|
431           cl = @chunk_layout[c]
432
433           ## set the default state for chunks
434           cl.state ||=
435             if c.expandable? && c.respond_to?(:initial_state)
436               c.initial_state
437             else
438               :closed
439             end
440
441           text = chunk_to_lines c, cl.state, @text.length, depth
442           (0 ... text.length).each do |i|
443             @chunk_lines[@text.length + i] = c
444             @message_lines[@text.length + i] = m
445             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
446             l.width = lw if lw > l.width
447           end
448           @text += text
449         end
450         @layout[m].bot = @text.length
451       end
452     end
453   end
454
455   def message_patina_lines m, state, start, parent, prefix, color, star_color
456     prefix_widget = [color, prefix]
457
458     open_widget = [color, (state == :closed ? "+ " : "- ")]
459     new_widget = [color, (m.has_label?(:unread) ? "N" : " ")]
460     starred_widget = 
461       if m.has_label?(:starred)
462         [star_color, "* "]
463       else
464         [color, "  "]
465       end
466
467     case state
468     when :open
469       @person_lines[start] = m.from
470       [[prefix_widget, open_widget, new_widget, starred_widget,
471         [color, 
472             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
473
474     when :closed
475       @person_lines[start] = m.from
476       [[prefix_widget, open_widget, new_widget, starred_widget,
477         [color, 
478         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
479
480     when :detailed
481       @person_lines[start] = m.from
482       from_line = [[prefix_widget, open_widget, new_widget, starred_widget,
483           [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
484
485       addressee_lines = []
486       unless m.to.empty?
487         m.to.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
488         addressee_lines += format_person_list "   To: ", m.to
489       end
490       unless m.cc.empty?
491         m.cc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
492         addressee_lines += format_person_list "   Cc: ", m.cc
493       end
494       unless m.bcc.empty?
495         m.bcc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
496         addressee_lines += format_person_list "   Bcc: ", m.bcc
497       end
498
499       headers = OrderedHash.new
500       headers["Date"] = "#{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})"
501       headers["Subject"] = m.subj
502
503       show_labels = @thread.labels - LabelManager::HIDDEN_RESERVED_LABELS
504       unless show_labels.empty?
505         headers["Labels"] = show_labels.map { |x| x.to_s }.sort.join(', ')
506       end
507       if parent
508         headers["In reply to"] = "#{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}"
509       end
510
511       HookManager.run "detailed-headers", :message => m, :headers => headers
512       
513       from_line + (addressee_lines + headers.map { |k, v| "   #{k}: #{v}" }).map { |l| [[color, prefix + "  " + l]] }
514     end
515   end
516
517   def format_person_list prefix, people
518     ptext = people.map { |p| format_person p }
519     pad = " " * prefix.length
520     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
521       ptext[1 .. -1].map_with_index do |e, i|
522         pad + e + (i == ptext.length - 1 ? "" : ",")
523       end
524   end
525
526   def format_person p
527     p.longname + (ContactManager.is_aliased_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
528   end
529
530   ## todo: check arguments on this overly complex function
531   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil, star_color=nil
532     prefix = " " * INDENT_SPACES * depth
533     case chunk
534     when :fake_root
535       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
536     when nil
537       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
538     when Message
539       message_patina_lines(chunk, state, start, parent, prefix, color, star_color) +
540         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
541
542     else
543       raise "Bad chunk: #{chunk.inspect}" unless chunk.respond_to?(:inlineable?) ## debugging
544       if chunk.inlineable?
545         chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
546       elsif chunk.expandable?
547         case state
548         when :closed
549           [[[chunk.patina_color, "#{prefix}+ #{chunk.patina_text}"]]]
550         when :open
551           [[[chunk.patina_color, "#{prefix}- #{chunk.patina_text}"]]] + chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
552         end
553       else
554         [[[chunk.patina_color, "#{prefix}x #{chunk.patina_text}"]]]
555       end
556     end
557   end
558
559   def view chunk
560     BufferManager.flash "viewing #{chunk.content_type} attachment..."
561     success = chunk.view!
562     BufferManager.erase_flash
563     BufferManager.completely_redraw_screen
564     unless success
565       BufferManager.spawn "Attachment: #{chunk.filename}", TextMode.new(chunk.to_s)
566       BufferManager.flash "Couldn't execute view command, viewing as text."
567     end
568   end
569 end
570
571 end