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 :send_draft, "Send draft", 'y'
34 k.add :edit_labels, "Edit or add labels for a thread", 'l'
35 k.add :expand_all_quotes, "Expand/collapse all quotes in a message", 'o'
36 k.add :jump_to_next_open, "Jump to next open message", 'n'
37 k.add :jump_to_prev_open, "Jump to previous open message", 'p'
38 k.add :align_current_message, "Align current message in buffer", 'z'
39 k.add :toggle_starred, "Star or unstar message", '*'
40 k.add :toggle_new, "Toggle unread/read status of message", 'N'
41 # k.add :collapse_non_new_messages, "Collapse all but unread messages", 'N'
42 k.add :reply, "Reply to a message", 'r'
43 k.add :forward, "Forward a message or attachment", 'f'
44 k.add :alias, "Edit alias/nickname for a person", 'i'
45 k.add :edit_as_new, "Edit message as new", 'D'
46 k.add :save_to_disk, "Save message/attachment to disk", 's'
47 k.add :search, "Search for messages from particular people", 'S'
48 k.add :compose, "Compose message to person", 'm'
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", '|'
53 k.add_multi "(a)rchive/(d)elete/mark as (s)pam/mark as u(N)read:", '.' do |kk|
54 kk.add :archive_and_kill, "Archive this thread and kill buffer", 'a'
55 kk.add :delete_and_kill, "Delete this thread and kill buffer", 'd'
56 kk.add :spam_and_kill, "Mark this thread as spam and kill buffer", 's'
57 kk.add :unread_and_kill, "Mark this thread as unread and kill buffer", 'N'
60 k.add_multi "(a)rchive/(d)elete/mark as (s)pam/mark as u(N)read/do (n)othing:", ',' do |kk|
61 kk.add :archive_and_next, "Archive this thread, kill buffer, and view next", 'a'
62 kk.add :delete_and_next, "Delete this thread, kill buffer, and view next", 'd'
63 kk.add :spam_and_next, "Mark this thread as spam, kill buffer, and view next", 's'
64 kk.add :unread_and_next, "Mark this thread as unread, kill buffer, and view next", 'N'
65 kk.add :do_nothing_and_next, "Kill buffer, and view next", 'n'
68 k.add_multi "(a)rchive/(d)elete/mark as (s)pam/mark as u(N)read/do (n)othing:", ']' do |kk|
69 kk.add :archive_and_prev, "Archive this thread, kill buffer, and view previous", 'a'
70 kk.add :delete_and_prev, "Delete this thread, kill buffer, and view previous", 'd'
71 kk.add :spam_and_prev, "Mark this thread as spam, kill buffer, and view previous", 's'
72 kk.add :unread_and_prev, "Mark this thread as unread, kill buffer, and view previous", 'N'
73 kk.add :do_nothing_and_prev, "Kill buffer, and view previous", 'n'
77 ## there are a couple important instance variables we hold to format
78 ## the thread and to provide line-based functionality. @layout is a
79 ## map from Messages to MessageLayouts, and @chunk_layout from
80 ## Chunks to ChunkLayouts. @message_lines is a map from row #s to
81 ## Message objects. @chunk_lines is a map from row #s to Chunk
82 ## objects. @person_lines is a map from row #s to Person objects.
84 def initialize thread, hidden_labels=[], index_mode=nil
87 @hidden_labels = hidden_labels
89 ## used for dispatch-and-next
90 @index_mode = index_mode
93 @layout = SavingHash.new { MessageLayout.new }
94 @chunk_layout = SavingHash.new { ChunkLayout.new }
95 earliest, latest = nil, nil
99 @thread.each do |m, d, p|
102 @layout[m].state = initial_state_for m
103 @layout[m].color = altcolor ? :alternate_patina_color : :message_patina_color
104 @layout[m].star_color = altcolor ? :alternate_starred_patina_color : :starred_patina_color
105 @layout[m].orig_new = m.has_label? :read
107 if latest_date.nil? || m.date > latest_date
113 @layout[latest].state = :open if @layout[latest].state == :closed
114 @layout[earliest].state = :detailed if earliest.has_label?(:unread) || @thread.size == 1
116 @thread.remove_label :unread
120 def draw_line ln, opts={}
122 super ln, :highlight => true
127 def lines; @text.length; end
128 def [] i; @text[i]; end
131 m = @message_lines[curpos] or return
132 BufferManager.spawn_unless_exists("Full header for #{m.id}") do
133 TextMode.new m.raw_header
137 def toggle_detailed_header
138 m = @message_lines[curpos] or return
139 @layout[m].state = (@layout[m].state == :detailed ? :open : :detailed)
144 m = @message_lines[curpos] or return
145 mode = ReplyMode.new m
146 BufferManager.spawn "Reply to #{m.subj}", mode
149 def subscribe_to_list
150 m = @message_lines[curpos] or return
151 if m.list_subscribe && m.list_subscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
152 ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
154 BufferManager.flash "Can't find List-Subscribe header for this message."
158 def unsubscribe_from_list
159 m = @message_lines[curpos] or return
160 if m.list_unsubscribe && m.list_unsubscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
161 ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
163 BufferManager.flash "Can't find List-Unsubscribe header for this message."
168 if(chunk = @chunk_lines[curpos]) && chunk.is_a?(Chunk::Attachment)
169 ForwardMode.spawn_nicely :attachments => [chunk]
170 elsif(m = @message_lines[curpos])
171 ForwardMode.spawn_nicely :message => m
175 include CanAliasContacts
177 p = @person_lines[curpos] or return
183 p = @person_lines[curpos] or return
184 mode = PersonSearchResultsMode.new [p]
185 BufferManager.spawn "Search for #{p.name}", mode
186 mode.load_threads :num => mode.buffer.content_height
190 p = @person_lines[curpos]
192 ComposeMode.spawn_nicely :to_default => p
194 ComposeMode.spawn_nicely
199 reserved_labels = @thread.labels.select { |l| LabelManager::RESERVED_LABELS.include? l }
200 new_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", @thread.labels
202 return unless new_labels
203 @thread.labels = (reserved_labels + new_labels).uniq
204 new_labels.each { |l| LabelManager << l }
206 UpdateManager.relay self, :labeled, @thread.first
210 m = @message_lines[curpos] or return
211 toggle_label m, :starred
215 m = @message_lines[curpos] or return
216 toggle_label m, :unread
219 def toggle_label m, label
220 if m.has_label? label
225 ## TODO: don't recalculate EVERYTHING just to add a stupid little
226 ## star to the display
228 UpdateManager.relay self, :single_message_labeled, m
231 ## called when someone presses enter when the cursor is highlighting
232 ## a chunk. for expandable chunks (including messages) we toggle
233 ## open/closed state; for viewable chunks (like attachments) we
236 chunk = @chunk_lines[curpos] or return
238 if chunk.is_a?(Message)
240 elsif chunk.expandable?
244 layout.state = (layout.state != :closed ? :closed : :open)
245 #cursor_down if layout.state == :closed # too annoying
247 elsif chunk.viewable?
253 m = @message_lines[curpos] or return
254 mode = ComposeMode.new(:body => m.quotable_body_lines, :to => m.to, :cc => m.cc, :subj => m.subj, :bcc => m.bcc, :refs => m.refs, :replytos => m.replytos)
255 BufferManager.spawn "edit as new", mode
260 chunk = @chunk_lines[curpos] or return
262 when Chunk::Attachment
263 fn = BufferManager.ask_for_filename :filename, "Save attachment to file: ", ($config[:default_attachment_save_dir] + chunk.filename)
264 save_to_file(fn) { |f| f.print chunk.raw_content } if fn
266 m = @message_lines[curpos]
267 fn = BufferManager.ask_for_filename :filename, "Save message to file: "
269 save_to_file(fn) do |f|
270 m.each_raw_message_line { |l| f.print l }
276 m = @message_lines[curpos] or return
278 mode = ResumeMode.new m
279 BufferManager.spawn "Edit message", mode
280 BufferManager.kill_buffer self.buffer
283 BufferManager.flash "Not a draft message!"
288 m = @message_lines[curpos] or return
290 mode = ResumeMode.new m
291 BufferManager.spawn "Send message", mode
292 BufferManager.kill_buffer self.buffer
295 BufferManager.flash "Not a draft message!"
299 def jump_to_first_open loose_alignment=false
300 m = @message_lines[0] or return
301 if @layout[m].state != :closed
302 jump_to_message m, loose_alignment
304 jump_to_next_open loose_alignment
308 def jump_to_next_open loose_alignment=false
309 return continue_search_in_buffer if in_search? # hack: allow 'n' to apply to both operations
310 m = (curpos ... @message_lines.length).argfind { |i| @message_lines[i] }
312 while nextm = @layout[m].next
313 break if @layout[nextm].state != :closed
316 jump_to_message nextm, loose_alignment if nextm
319 def align_current_message
320 m = @message_lines[curpos] or return
324 def jump_to_prev_open loose_alignment=false
325 m = (0 .. curpos).to_a.reverse.argfind { |i| @message_lines[i] } # bah, .to_a
327 ## jump to the top of the current message if we're in the body;
328 ## otherwise, to the previous message
332 while(prevm = @layout[m].prev)
333 break if @layout[prevm].state != :closed
336 jump_to_message prevm, loose_alignment if prevm
338 jump_to_message m, loose_alignment
342 IDEAL_TOP_CONTEXT = 3 # try and give 3 rows of top context
343 IDEAL_LEFT_CONTEXT = 4 # try and give 4 columns of left context
344 def jump_to_message m, loose_alignment=false
346 left = l.depth * INDENT_SPACES
347 right = left + l.width
349 ## jump to the top line
351 jump_to_line [l.top - IDEAL_TOP_CONTEXT, 0].max # give 3 lines of top context
356 ## jump to the left column
359 -IDEAL_LEFT_CONTEXT + (l.width - buffer.content_width + IDEAL_LEFT_CONTEXT + 1).clamp(0, IDEAL_LEFT_CONTEXT)
364 jump_to_col [ideal_left, 0].max
366 ## either way, move the cursor to the first line
370 def expand_all_messages
371 @global_message_state ||= :closed
372 @global_message_state = (@global_message_state == :closed ? :open : :closed)
373 @layout.each { |m, l| l.state = @global_message_state }
377 def collapse_non_new_messages
378 @layout.each { |m, l| l.state = l.orig_new ? :open : :closed }
382 def expand_all_quotes
383 if(m = @message_lines[curpos])
384 quotes = m.chunks.select { |c| (c.is_a?(Chunk::Quote) || c.is_a?(Chunk::Signature)) && c.lines.length > 1 }
385 numopen = quotes.inject(0) { |s, c| s + (@chunk_layout[c].state == :open ? 1 : 0) }
386 newstate = numopen > quotes.length / 2 ? :closed : :open
387 quotes.each { |c| @chunk_layout[c].state = newstate }
393 @layout = @chunk_layout = @text = nil # for good luck
396 def archive_and_kill; archive_and_then :kill end
397 def spam_and_kill; spam_and_then :kill end
398 def delete_and_kill; delete_and_then :kill end
399 def unread_and_kill; unread_and_then :kill end
401 def archive_and_next; archive_and_then :next end
402 def spam_and_next; spam_and_then :next end
403 def delete_and_next; delete_and_then :next end
404 def unread_and_next; unread_and_then :next end
405 def do_nothing_and_next; do_nothing_and_then :next end
407 def archive_and_prev; archive_and_then :prev end
408 def spam_and_prev; spam_and_then :prev end
409 def delete_and_prev; delete_and_then :prev end
410 def unread_and_prev; unread_and_then :prev end
411 def do_nothing_and_prev; do_nothing_and_then :prev end
413 def archive_and_then op
415 @thread.remove_label :inbox
416 UpdateManager.relay self, :archived, @thread.first
422 @thread.apply_label :spam
423 UpdateManager.relay self, :spammed, @thread.first
427 def delete_and_then op
429 @thread.apply_label :deleted
430 UpdateManager.relay self, :deleted, @thread.first
434 def unread_and_then op
436 @thread.apply_label :unread
437 UpdateManager.relay self, :unread, @thread.first
441 def do_nothing_and_then op
450 yield if block_given?
451 BufferManager.kill_buffer_safely buffer
456 @index_mode.launch_next_thread_after @thread, &l
458 @index_mode.launch_prev_thread_before @thread, &l
462 raise ArgumentError, "unknown thread dispatch operation #{op.inspect}"
468 chunk = @chunk_lines[curpos]
469 chunk = nil unless chunk.is_a?(Chunk::Attachment)
470 message = @message_lines[curpos] unless chunk
472 return unless chunk || message
474 command = BufferManager.ask(:shell, "pipe command: ")
475 return if command.nil? || command.empty?
477 output = pipe_to_process(command) do |stream|
479 stream.print chunk.raw_content
481 message.each_raw_message_line { |l| stream.print l }
486 BufferManager.spawn "Output of '#{command}'", TextMode.new(output)
488 BufferManager.flash "'#{command}' done!"
494 def initial_state_for m
495 if m.has_label?(:starred) || m.has_label?(:unread)
504 buffer.mark_dirty if buffer
507 ## here we generate the actual content lines. we accumulate
508 ## everything into @text, and we set @chunk_lines and
509 ## @message_lines, and we update @layout.
517 @thread.each do |m, depth, parent|
518 unless m.is_a? Message # handle nil and :fake_root
519 @text += chunk_to_lines m, nil, @text.length, depth, parent
524 ## is this still necessary?
525 next unless @layout[m].state # skip discarded drafts
528 text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
531 l.bot = @text.length + text.length # updated below
535 # l.state we preserve
536 l.width = 0 # updated below
537 @layout[l.prev].next = m if l.prev
539 (0 ... text.length).each do |i|
540 @chunk_lines[@text.length + i] = m
541 @message_lines[@text.length + i] = m
542 lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
547 if l.state != :closed
549 cl = @chunk_layout[c]
551 ## set the default state for chunks
553 if c.expandable? && c.respond_to?(:initial_state)
559 text = chunk_to_lines c, cl.state, @text.length, depth
560 (0 ... text.length).each do |i|
561 @chunk_lines[@text.length + i] = c
562 @message_lines[@text.length + i] = m
563 lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
564 l.width = lw if lw > l.width
568 @layout[m].bot = @text.length
573 def message_patina_lines m, state, start, parent, prefix, color, star_color
574 prefix_widget = [color, prefix]
576 open_widget = [color, (state == :closed ? "+ " : "- ")]
577 new_widget = [color, (m.has_label?(:unread) ? "N" : " ")]
578 starred_widget = if m.has_label?(:starred)
583 attach_widget = [color, (m.has_label?(:attachment) ? "@" : " ")]
587 @person_lines[start] = m.from
588 [[prefix_widget, open_widget, new_widget, attach_widget, starred_widget,
590 "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
593 @person_lines[start] = m.from
594 [[prefix_widget, open_widget, new_widget, attach_widget, starred_widget,
596 "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s}) #{m.snippet}"]]]
599 @person_lines[start] = m.from
600 from_line = [[prefix_widget, open_widget, new_widget, attach_widget, starred_widget,
601 [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
605 m.to.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
606 addressee_lines += format_person_list " To: ", m.to
609 m.cc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
610 addressee_lines += format_person_list " Cc: ", m.cc
613 m.bcc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
614 addressee_lines += format_person_list " Bcc: ", m.bcc
617 headers = OrderedHash.new
618 headers["Date"] = "#{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})"
619 headers["Subject"] = m.subj
621 show_labels = @thread.labels - LabelManager::HIDDEN_RESERVED_LABELS
622 unless show_labels.empty?
623 headers["Labels"] = show_labels.map { |x| x.to_s }.sort.join(', ')
626 headers["In reply to"] = "#{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}"
629 HookManager.run "detailed-headers", :message => m, :headers => headers
631 from_line + (addressee_lines + headers.map { |k, v| " #{k}: #{v}" }).map { |l| [[color, prefix + " " + l]] }
635 def format_person_list prefix, people
636 ptext = people.map { |p| format_person p }
637 pad = " " * prefix.length
638 [prefix + ptext.first + (ptext.length > 1 ? "," : "")] +
639 ptext[1 .. -1].map_with_index do |e, i|
640 pad + e + (i == ptext.length - 1 ? "" : ",")
645 p.longname + (ContactManager.is_aliased_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
648 ## todo: check arguments on this overly complex function
649 def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil, star_color=nil
650 prefix = " " * INDENT_SPACES * depth
653 [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
655 [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
657 message_patina_lines(chunk, state, start, parent, prefix, color, star_color) +
658 (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. Hit 'e' to edit, 'y' to send. <<<"]]] : [])
661 raise "Bad chunk: #{chunk.inspect}" unless chunk.respond_to?(:inlineable?) ## debugging
663 chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
664 elsif chunk.expandable?
667 [[[chunk.patina_color, "#{prefix}+ #{chunk.patina_text}"]]]
669 [[[chunk.patina_color, "#{prefix}- #{chunk.patina_text}"]]] + chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
672 [[[chunk.patina_color, "#{prefix}x #{chunk.patina_text}"]]]
678 BufferManager.flash "viewing #{chunk.content_type} attachment..."
679 success = chunk.view!
680 BufferManager.erase_flash
681 BufferManager.completely_redraw_screen
683 BufferManager.spawn "Attachment: #{chunk.filename}", TextMode.new(chunk.to_s, chunk.filename)
684 BufferManager.flash "Couldn't execute view command, viewing as text."