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