4 class ThreadViewMode < LineCursorMode
5 ## this holds all info we need to lay out a message
7 attr_accessor :top, :bot, :prev, :next, :depth, :width, :state, :color, :star_color, :orig_new
14 DATE_FORMAT = "%B %e %Y %l:%M%P"
15 INDENT_SPACES = 2 # how many spaces to indent child messages
17 HookManager.register "detailed-headers", <<EOS
18 Add or remove headers from the detailed header display of a message.
20 message: The message whose headers are to be formatted.
21 headers: A hash of header (name, value) pairs, initialized to the default
24 None. The variable 'headers' should be modified in place.
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", '|'
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.
61 def initialize thread, hidden_labels=[]
64 @hidden_labels = hidden_labels
66 @layout = SavingHash.new { MessageLayout.new }
67 @chunk_layout = SavingHash.new { ChunkLayout.new }
68 earliest, latest = nil, nil
72 @thread.each do |m, d, p|
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
80 if latest_date.nil? || m.date > latest_date
86 @layout[latest].state = :open if @layout[latest].state == :closed
87 @layout[earliest].state = :detailed if earliest.has_label?(:unread) || @thread.size == 1
89 @thread.remove_label :unread
93 def draw_line ln, opts={}
95 super ln, :highlight => true
100 def lines; @text.length; end
101 def [] i; @text[i]; end
104 m = @message_lines[curpos] or return
105 BufferManager.spawn_unless_exists("Full header") do
106 TextMode.new m.raw_header
110 def toggle_detailed_header
111 m = @message_lines[curpos] or return
112 @layout[m].state = (@layout[m].state == :detailed ? :open : :detailed)
117 m = @message_lines[curpos] or return
118 mode = ReplyMode.new m
119 BufferManager.spawn "Reply to #{m.subj}", mode
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
127 BufferManager.flash "Can't find List-Subscribe header for this message."
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
136 BufferManager.flash "Can't find List-Unsubscribe header for this message."
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
148 include CanAliasContacts
150 p = @person_lines[curpos] or return
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
163 p = @person_lines[curpos]
165 ComposeMode.spawn_nicely :to => [p]
167 ComposeMode.spawn_nicely
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
175 return unless new_labels
176 @thread.labels = (reserved_labels + new_labels).uniq
177 new_labels.each { |l| LabelManager << l }
179 UpdateManager.relay self, :labeled, @thread.first
183 m = @message_lines[curpos] or return
184 toggle_label m, :starred
188 m = @message_lines[curpos] or return
189 toggle_label m, :unread
192 def toggle_label m, label
193 if m.has_label? label
198 ## TODO: don't recalculate EVERYTHING just to add a stupid little
199 ## star to the display
201 UpdateManager.relay self, :single_message_labeled, m
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
209 chunk = @chunk_lines[curpos] or return
211 if chunk.is_a?(Message)
213 elsif chunk.expandable?
217 layout.state = (layout.state != :closed ? :closed : :open)
218 #cursor_down if layout.state == :closed # too annoying
220 elsif chunk.viewable?
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
233 chunk = @chunk_lines[curpos] or return
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
239 m = @message_lines[curpos]
240 fn = BufferManager.ask_for_filename :filename, "Save message to file: "
242 save_to_file(fn) do |f|
243 m.each_raw_message_line { |l| f.print l }
249 m = @message_lines[curpos] or return
251 mode = ResumeMode.new m
252 BufferManager.spawn "Edit message", mode
253 BufferManager.kill_buffer self.buffer
256 BufferManager.flash "Not a draft message!"
260 def jump_to_first_open
261 m = @message_lines[0] or return
262 if @layout[m].state != :closed
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
276 jump_to_message nextm if nextm
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
286 while(prevm = @layout[m].prev)
287 break if @layout[prevm].state != :closed
290 jump_to_message prevm if prevm
296 def jump_to_message m
298 left = l.depth * INDENT_SPACES
299 right = left + l.width
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
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
307 ## either way, move the cursor to the first line
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 }
318 def collapse_non_new_messages
319 @layout.each { |m, l| l.state = l.orig_new ? :open : :closed }
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 }
334 @layout = @chunk_layout = @text = nil # for good luck
338 @thread.remove_label :inbox
339 UpdateManager.relay self, :archived, @thread.first
340 BufferManager.kill_buffer_safely buffer
344 @thread.apply_label :deleted
345 UpdateManager.relay self, :deleted, @thread.first
346 BufferManager.kill_buffer_safely buffer
350 chunk = @chunk_lines[curpos]
351 chunk = nil unless chunk.is_a?(Chunk::Attachment)
352 message = @message_lines[curpos] unless chunk
354 return unless chunk || message
356 command = BufferManager.ask(:shell, "pipe command: ")
357 return if command.nil? || command.empty?
359 Open3.popen3(command) do |input, output, error|
360 err, data, * = IO.select [error], [input], nil
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}!"
368 Redwood::log "error running #{command}: #{message}"
369 BufferManager.flash "Error: #{message}"
375 data.sync = false # buffer input
378 data.print chunk.raw_content
380 message.each_raw_message_line { |l| data.print l }
383 data.close # output will block unless input is closed
385 ## BUG?: shows errors or output but not both....
386 data, * = IO.select [output, error], nil, nil
390 BufferManager.flash "'#{command}' done!"
392 BufferManager.spawn "Output of '#{command}'", TextMode.new(data.read)
399 def initial_state_for m
400 if m.has_label?(:starred) || m.has_label?(:unread)
409 buffer.mark_dirty if buffer
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.
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
429 ## is this still necessary?
430 next unless @layout[m].state # skip discarded drafts
433 text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
436 l.bot = @text.length + text.length # updated below
440 # l.state we preserve
441 l.width = 0 # updated below
442 @layout[l.prev].next = m if l.prev
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
452 if l.state != :closed
454 cl = @chunk_layout[c]
456 ## set the default state for chunks
458 if c.expandable? && c.respond_to?(:initial_state)
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
473 @layout[m].bot = @text.length
478 def message_patina_lines m, state, start, parent, prefix, color, star_color
479 prefix_widget = [color, prefix]
481 open_widget = [color, (state == :closed ? "+ " : "- ")]
482 new_widget = [color, (m.has_label?(:unread) ? "N" : " ")]
484 if m.has_label?(:starred)
492 @person_lines[start] = m.from
493 [[prefix_widget, open_widget, new_widget, starred_widget,
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})"]]]
498 @person_lines[start] = m.from
499 [[prefix_widget, open_widget, new_widget, starred_widget,
501 "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s}) #{m.snippet}"]]]
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) : '?'}"]]]
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
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
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
522 headers = OrderedHash.new
523 headers["Date"] = "#{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})"
524 headers["Subject"] = m.subj
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(', ')
531 headers["In reply to"] = "#{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}"
534 HookManager.run "detailed-headers", :message => m, :headers => headers
536 from_line + (addressee_lines + headers.map { |k, v| " #{k}: #{v}" }).map { |l| [[color, prefix + " " + l]] }
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 ? "" : ",")
550 p.longname + (ContactManager.is_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
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
558 [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
560 [[[:missing_message_color, "#{prefix}<an unreceived 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'. <<<"]]] : [])
566 raise "Bad chunk: #{chunk.inspect}" unless chunk.respond_to?(:inlineable?) ## debugging
568 chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
569 elsif chunk.expandable?
572 [[[chunk.patina_color, "#{prefix}+ #{chunk.patina_text}"]]]
574 [[[chunk.patina_color, "#{prefix}- #{chunk.patina_text}"]]] + chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
577 [[[chunk.patina_color, "#{prefix}x #{chunk.patina_text}"]]]
583 BufferManager.flash "viewing #{chunk.content_type} attachment..."
584 success = chunk.view!
585 BufferManager.erase_flash
586 BufferManager.completely_redraw_screen
588 BufferManager.spawn "Attachment: #{chunk.filename}", TextMode.new(chunk.to_s)
589 BufferManager.flash "Couldn't execute view command, viewing as text."