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