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