]> git.notmuchmail.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
don't collapse one-line quotes and signatures
[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 Layout
6     attr_accessor :top, :bot, :prev, :next, :depth, :width, :state, :color
7   end
8
9   DATE_FORMAT = "%B %e %Y %l:%M%P"
10   INDENT_SPACES = 2 # how many spaces to indent child messages
11
12   register_keymap do |k|
13     k.add :toggle_detailed_header, "Toggle detailed header", 'd'
14     k.add :show_header, "Show full message header", 'H'
15     k.add :toggle_expanded, "Expand/collapse item", :enter
16     k.add :expand_all_messages, "Expand/collapse all messages", 'E'
17     k.add :edit_message, "Edit message (drafts only)", 'e'
18     k.add :expand_all_quotes, "Expand/collapse all quotes in a message", 'o'
19     k.add :jump_to_next_open, "Jump to next open message", 'n'
20     k.add :jump_to_prev_open, "Jump to previous open message", 'p'
21     k.add :toggle_starred, "Star or unstar message", '*'
22     k.add :collapse_non_new_messages, "Collapse all but new messages", 'N'
23     k.add :reply, "Reply to a message", 'r'
24     k.add :forward, "Forward a message", 'f'
25     k.add :alias, "Edit alias/nickname for a person", 'a'
26     k.add :edit_as_new, "Edit message as new", 'D'
27     k.add :save_to_disk, "Save message/attachment to disk", 's'
28     k.add :search, "Search for messages from particular people", 'S'
29   end
30
31   ## there are a couple important instance variables we hold to lay
32   ## out the thread and to provide line-based functionality. @layout
33   ## is a map from Message and Chunk objects to Layout objects. (for
34   ## chunks, we only use the state field right now.) @message_lines is
35   ## a map from row #s to Message objects. @chunk_lines is a map from
36   ## row #s to Chunk objects. @person_lines is a map from row #s to
37   ## Person objects.
38
39   def initialize thread, hidden_labels=[]
40     super()
41     @thread = thread
42     @hidden_labels = hidden_labels
43
44     @layout = {}
45     earliest, latest = nil, nil
46     latest_date = nil
47     altcolor = false
48     @thread.each do |m, d, p|
49       next unless m
50       earliest ||= m
51       @layout[m] = Layout.new
52       @layout[m].state = initial_state_for m
53       @layout[m].color = altcolor ? :alternate_patina_color : :message_patina_color
54       altcolor = !altcolor
55       if latest_date.nil? || m.date > latest_date
56         latest_date = m.date
57         latest = m
58       end
59     end
60
61     @layout[latest].state = :open if @layout[latest].state == :closed
62     @layout[earliest].state = :detailed if earliest.has_label?(:unread) || @thread.size == 1
63
64     BufferManager.say("Loading message bodies...") { regen_text }
65   end
66
67   def draw_line ln, opts={}
68     if ln == curpos
69       super ln, :highlight => true
70     else
71       super
72     end
73   end
74   def lines; @text.length; end
75   def [] i; @text[i]; end
76
77   def show_header
78     m = @message_lines[curpos] or return
79     BufferManager.spawn_unless_exists("Full header") do
80       TextMode.new m.raw_header
81     end
82   end
83
84   def toggle_detailed_header
85     m = @message_lines[curpos] or return
86     @layout[m].state = (@layout[m].state == :detailed ? :open : :detailed)
87     update
88   end
89
90   def reply
91     m = @message_lines[curpos] or return
92     mode = ReplyMode.new m
93     BufferManager.spawn "Reply to #{m.subj}", mode
94   end
95
96   def forward
97     m = @message_lines[curpos] or return
98     mode = ForwardMode.new m
99     BufferManager.spawn "Forward of #{m.subj}", mode
100     mode.edit
101   end
102
103   include CanAliasContacts
104   def alias
105     p = @person_lines[curpos] or return
106     alias_contact p
107     regen_text
108   end
109
110   def search
111     p = @person_lines[curpos] or return
112     mode = PersonSearchResultsMode.new [p]
113     BufferManager.spawn "search for #{p.name}", mode
114     mode.load_threads :num => mode.buffer.content_height
115   end    
116
117   def toggle_starred
118     m = @message_lines[curpos] or return
119     if m.has_label? :starred
120       m.remove_label :starred
121     else
122       m.add_label :starred
123     end
124     ## TODO: don't recalculate EVERYTHING just to add a stupid little
125     ## star to the display
126     update
127     UpdateManager.relay :starred, m
128   end
129
130   def toggle_expanded
131     chunk = @chunk_lines[curpos] or return
132     case chunk
133     when Message, Message::Quote, Message::Signature
134       return if chunk.lines.length == 1 unless chunk.is_a? Message # too small to expand/close
135       l = @layout[chunk]
136       l.state = (l.state != :closed ? :closed : :open)
137       cursor_down if l.state == :closed
138     when Message::Attachment
139       view_attachment chunk
140     end
141     update
142   end
143
144   def edit_as_new
145     m = @message_lines[curpos] or return
146     mode = ComposeMode.new(:body => m.basic_body_lines, :to => m.to, :cc => m.cc, :subj => m.subj, :bcc => m.bcc)
147     BufferManager.spawn "edit as new", mode
148     mode.edit
149   end
150
151   def save_to_disk
152     chunk = @chunk_lines[curpos] or return
153     case chunk
154     when Message::Attachment
155       fn = BufferManager.ask :filename, "Save attachment to file: ", chunk.filename
156       save_to_file(fn) { |f| f.print chunk } if fn
157     else
158       m = @message_lines[curpos]
159       fn = BufferManager.ask :filename, "Save message to file: "
160       save_to_file(fn) { |f| f.print m.raw_full_message } if fn
161     end
162   end
163
164   def edit_message
165     m = @message_lines[curpos] or return
166     if m.is_draft?
167       mode = ResumeMode.new m
168       BufferManager.spawn "Edit message", mode
169       mode.edit
170     else
171       BufferManager.flash "Not a draft message!"
172     end
173   end
174
175   def jump_to_first_open
176     m = @message_lines[0] or return
177     if @layout[m].state != :closed
178       jump_to_message m
179     else
180       jump_to_next_open
181     end
182   end
183
184   def jump_to_next_open
185     m = @message_lines[curpos] or return
186     while nextm = @layout[m].next
187       break if @layout[nextm].state != :closed
188       m = nextm
189     end
190     jump_to_message nextm if nextm
191   end
192
193   def jump_to_prev_open
194     m = @message_lines[curpos] or return
195     ## jump to the top of the current message if we're in the body;
196     ## otherwise, to the previous message
197     
198     top = @layout[m].top
199     if curpos == top
200       while(prevm = @layout[m].prev)
201         break if @layout[prevm].state != :closed
202         m = prevm
203       end
204       jump_to_message prevm if prevm
205     else
206       jump_to_message m
207     end
208   end
209
210   def jump_to_message m
211     l = @layout[m]
212     left = l.depth * INDENT_SPACES
213     right = left + l.width
214
215     ## jump to the top line unless both top and bottom fit in the current view
216     jump_to_line l.top unless l.top >= topline && l.top <= botline && l.bot >= topline && l.bot <= botline
217
218     ## jump to the left columns unless both left and right fit in the current view
219     jump_to_col left unless left >= leftcol && left <= rightcol && right >= leftcol && right <= rightcol
220
221     ## either way, move the cursor to the first line
222     set_cursor_pos l.top
223   end
224
225   def expand_all_messages
226     @global_message_state ||= :closed
227     @global_message_state = (@global_message_state == :closed ? :open : :closed)
228     @layout.each { |m, l| l.state = @global_message_state if m.is_a? Message }
229     update
230   end
231
232   def collapse_non_new_messages
233     @layout.each { |m, l| l.state = m.has_label?(:unread) ? :open : :closed }
234     update
235   end
236
237   def expand_all_quotes
238     if(m = @message_lines[curpos])
239       quotes = m.chunks.select { |c| (c.is_a?(Message::Quote) || c.is_a?(Message::Signature)) && c.lines.length > 1 }
240       numopen = quotes.inject(0) { |s, c| s + (@layout[c].state == :open ? 1 : 0) }
241       newstate = numopen > quotes.length / 2 ? :closed : :open
242       quotes.each { |c| @layout[c].state = newstate }
243       update
244     end
245   end
246
247   ## kinda slow for large threads. TODO: fasterify
248   def cleanup
249     BufferManager.say "Marking messages as read..." do
250       @thread.each do |m, d, p|
251         if m && m.has_label?(:unread)
252           m.remove_label :unread 
253           UpdateManager.relay :read, m
254         end
255       end
256     end
257     @layout = @text = nil
258   end
259
260 private 
261
262   def initial_state_for m
263     if m.has_label?(:starred) || m.has_label?(:unread)
264       :open
265     else
266       :closed
267     end
268   end
269
270   def update
271     regen_text
272     buffer.mark_dirty if buffer
273   end
274
275   ## here we generate the actual content lines. we accumulate
276   ## everything into @text, and we set @chunk_lines and
277   ## @message_lines, and we update @layout.
278   def regen_text
279     @text = []
280     @chunk_lines = []
281     @message_lines = []
282     @person_lines = []
283
284     prevm = nil
285     @thread.each do |m, depth, parent|
286       unless m.is_a? Message # handle nil and :fake_root
287         @text += chunk_to_lines m, nil, @text.length, depth, parent
288         next
289       end
290
291       ## we're occasionally called on @threads that have had messages
292       ## added to them since initialization. luckily we regen_text on
293       ## the entire thread every time the user does anything besides
294       ## scrolling (basically), so we can just slap this on here.
295       ##
296       ## to pick nits, the niceness that i do in the constructor with
297       ## 'latest' etc. (for automatically opening just the latest
298       ## message if everything's been read) will not be valid, but
299       ## that's just a nicety and hopefully this won't happen too
300       ## often.
301
302       unless @layout.member? m
303         l = @layout[m] = Layout.new
304         l.state = initial_state_for m
305         l.color = prevm && @layout[prevm].color == :message_patina_color ? :alternate_patina_color : :message_patina_color
306       end
307       l = @layout[m]
308
309       ## build the patina
310       text = chunk_to_lines m, l.state, @text.length, depth, parent, @layout[m].color
311       
312       l.top = @text.length
313       l.bot = @text.length + text.length # updated below
314       l.prev = prevm
315       l.next = nil
316       l.depth = depth
317       # l.state we preserve
318       l.width = 0 # updated below
319       @layout[l.prev].next = m if l.prev
320
321       (0 ... text.length).each do |i|
322         @chunk_lines[@text.length + i] = m
323         @message_lines[@text.length + i] = m
324         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
325       end
326
327       @text += text
328       prevm = m 
329       if @layout[m].state != :closed
330         m.chunks.each do |c|
331           cl = (@layout[c] ||= Layout.new)
332           cl.state ||= :closed
333           text = chunk_to_lines c, cl.state, @text.length, depth
334           (0 ... text.length).each do |i|
335             @chunk_lines[@text.length + i] = c
336             @message_lines[@text.length + i] = m
337             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
338             l.width = lw if lw > l.width
339           end
340           @text += text
341         end
342         @layout[m].bot = @text.length
343       end
344     end
345   end
346
347   def message_patina_lines m, state, start, parent, prefix, color
348     prefix_widget = [color, prefix]
349     widget = 
350       case state
351       when :closed
352         [color, "+ "]
353       when :open, :detailed
354         [color, "- "]
355       end
356     imp_widget = 
357       if m.has_label?(:starred)
358         [:starred_patina_color, "* "]
359       else
360         [color, "  "]
361       end
362
363     case state
364     when :open
365       @person_lines[start] = m.from
366       [[prefix_widget, widget, imp_widget,
367         [color, 
368             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
369
370     when :closed
371       @person_lines[start] = m.from
372       [[prefix_widget, widget, imp_widget,
373         [color, 
374         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
375
376     when :detailed
377       @person_lines[start] = m.from
378       from = [[prefix_widget, widget, imp_widget, [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
379
380       rest = []
381       unless m.to.empty?
382         m.to.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
383         rest += format_person_list "  To: ", m.to
384       end
385       unless m.cc.empty?
386         m.cc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
387         rest += format_person_list "  Cc: ", m.cc
388       end
389       unless m.bcc.empty?
390         m.bcc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
391         rest += format_person_list "  Bcc: ", m.bcc
392       end
393
394       rest += [
395         "  Date: #{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})",
396         "  Subject: #{m.subj}",
397         (parent ? "  In reply to: #{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}" : nil),
398         m.labels.empty? ? nil : "  Labels: #{m.labels.join(', ')}",
399       ].compact
400       
401       from + rest.map { |l| [[color, prefix + "  " + l]] }
402     end
403   end
404
405   def format_person_list prefix, people
406     ptext = people.map { |p| format_person p }
407     pad = " " * prefix.length
408     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
409       ptext[1 .. -1].map_with_index do |e, i|
410         pad + e + (i == ptext.length - 1 ? "" : ",")
411       end
412   end
413
414   def format_person p
415     p.longname + (ContactManager.is_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
416   end
417
418   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil
419     prefix = " " * INDENT_SPACES * depth
420     case chunk
421     when :fake_root
422       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
423     when nil
424       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
425     when Message
426       message_patina_lines(chunk, state, start, parent, prefix, color) +
427         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
428     when Message::Attachment
429       [[[:mime_color, "#{prefix}+ MIME attachment #{chunk.content_type}#{chunk.desc ? ' (' + chunk.desc + ')': ''}"]]]
430     when Message::Text
431       t = chunk.lines
432       if t.last =~ /^\s*$/ && t.length > 1
433         t.pop while t[-2] =~ /^\s*$/ # pop until only one file empty line
434       end
435       t.map { |line| [[:none, "#{prefix}#{line}"]] }
436     when Message::Quote
437       return [[[:quote_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
438       case state
439       when :closed
440         [[[:quote_patina_color, "#{prefix}+ (#{chunk.lines.length} quoted lines)"]]]
441       when :open
442         [[[:quote_patina_color, "#{prefix}- (#{chunk.lines.length} quoted lines)"]]] + chunk.lines.map { |line| [[:quote_color, "#{prefix}#{line}"]] }
443       end
444     when Message::Signature
445       return [[[:sig_patina_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
446       case state
447       when :closed
448         [[[:sig_patina_color, "#{prefix}+ (#{chunk.lines.length}-line signature)"]]]
449       when :open
450         [[[:sig_patina_color, "#{prefix}- (#{chunk.lines.length}-line signature)"]]] + chunk.lines.map { |line| [[:sig_color, "#{prefix}#{line}"]] }
451       end
452     else
453       raise "unknown chunk type #{chunk.class.name}"
454     end
455   end
456
457   def view_attachment a
458     BufferManager.flash "viewing #{a.content_type} attachment..."
459     a.view!
460     BufferManager.erase_flash
461     BufferManager.completely_redraw_screen
462   end
463
464 end
465
466 end