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