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