]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
bugfix: killed threads shouldn't be hidden a priori by thread-index-mode
[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
153       l = @layout[chunk]
154       l.state = (l.state != :closed ? :closed : :open)
155       cursor_down if l.state == :closed
156     when Message::Quote, Message::Signature
157       return if chunk.lines.length == 1
158       l = @chunk_layout[chunk]
159       l.state = (l.state != :closed ? :closed : :open)
160       cursor_down if l.state == :closed
161     when Message::Attachment
162       view_attachment chunk
163     end
164     update
165   end
166
167   def edit_as_new
168     m = @message_lines[curpos] or return
169     mode = ComposeMode.new(:body => m.basic_body_lines, :to => m.to, :cc => m.cc, :subj => m.subj, :bcc => m.bcc)
170     BufferManager.spawn "edit as new", mode
171     mode.edit
172   end
173
174   def save_to_disk
175     chunk = @chunk_lines[curpos] or return
176     case chunk
177     when Message::Attachment
178       fn = BufferManager.ask :filename, "Save attachment to file: ", chunk.filename
179       save_to_file(fn) { |f| f.print chunk } if fn
180     else
181       m = @message_lines[curpos]
182       fn = BufferManager.ask :filename, "Save message to file: "
183       save_to_file(fn) { |f| f.print m.raw_full_message } if fn
184     end
185   end
186
187   def edit_message
188     m = @message_lines[curpos] or return
189     if m.is_draft?
190       mode = ResumeMode.new m
191       BufferManager.spawn "Edit message", mode
192       mode.edit
193     else
194       BufferManager.flash "Not a draft message!"
195     end
196   end
197
198   def jump_to_first_open
199     m = @message_lines[0] or return
200     if @layout[m].state != :closed
201       jump_to_message m
202     else
203       jump_to_next_open
204     end
205   end
206
207   def jump_to_next_open
208     m = @message_lines[curpos] or return
209     while nextm = @layout[m].next
210       break if @layout[nextm].state != :closed
211       m = nextm
212     end
213     jump_to_message nextm if nextm
214   end
215
216   def jump_to_prev_open
217     m = @message_lines[curpos] or return
218     ## jump to the top of the current message if we're in the body;
219     ## otherwise, to the previous message
220     
221     top = @layout[m].top
222     if curpos == top
223       while(prevm = @layout[m].prev)
224         break if @layout[prevm].state != :closed
225         m = prevm
226       end
227       jump_to_message prevm if prevm
228     else
229       jump_to_message m
230     end
231   end
232
233   def jump_to_message m
234     l = @layout[m]
235     left = l.depth * INDENT_SPACES
236     right = left + l.width
237
238     ## jump to the top line unless both top and bottom fit in the current view
239     jump_to_line l.top unless l.top >= topline && l.top <= botline && l.bot >= topline && l.bot <= botline
240
241     ## jump to the left columns unless both left and right fit in the current view
242     jump_to_col left unless left >= leftcol && left <= rightcol && right >= leftcol && right <= rightcol
243
244     ## either way, move the cursor to the first line
245     set_cursor_pos l.top
246   end
247
248   def expand_all_messages
249     @global_message_state ||= :closed
250     @global_message_state = (@global_message_state == :closed ? :open : :closed)
251     @layout.each { |m, l| l.state = @global_message_state }
252     update
253   end
254
255   def collapse_non_new_messages
256     @layout.each { |m, l| l.state = l.orig_new ? :open : :closed }
257     update
258   end
259
260   def expand_all_quotes
261     if(m = @message_lines[curpos])
262       quotes = m.chunks.select { |c| (c.is_a?(Message::Quote) || c.is_a?(Message::Signature)) && c.lines.length > 1 }
263       numopen = quotes.inject(0) { |s, c| s + (@chunk_layout[c].state == :open ? 1 : 0) }
264       newstate = numopen > quotes.length / 2 ? :closed : :open
265       quotes.each { |c| @chunk_layout[c].state = newstate }
266       update
267     end
268   end
269
270   def cleanup
271     @layout = @chunk_layout = @text = nil # for good luck
272   end
273
274   def archive_and_kill
275     @thread.remove_label :inbox
276     UpdateManager.relay self, :archived, @thread
277     BufferManager.kill_buffer_safely buffer
278   end
279
280 private 
281
282   def initial_state_for m
283     if m.has_label?(:starred) || m.has_label?(:unread)
284       :open
285     else
286       :closed
287     end
288   end
289
290   def update
291     regen_text
292     buffer.mark_dirty if buffer
293   end
294
295   ## here we generate the actual content lines. we accumulate
296   ## everything into @text, and we set @chunk_lines and
297   ## @message_lines, and we update @layout.
298   def regen_text
299     @text = []
300     @chunk_lines = []
301     @message_lines = []
302     @person_lines = []
303
304     prevm = nil
305     @thread.each do |m, depth, parent|
306       unless m.is_a? Message # handle nil and :fake_root
307         @text += chunk_to_lines m, nil, @text.length, depth, parent
308         next
309       end
310       l = @layout[m]
311
312       ## build the patina
313       text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
314       
315       l.top = @text.length
316       l.bot = @text.length + text.length # updated below
317       l.prev = prevm
318       l.next = nil
319       l.depth = depth
320       # l.state we preserve
321       l.width = 0 # updated below
322       @layout[l.prev].next = m if l.prev
323
324       (0 ... text.length).each do |i|
325         @chunk_lines[@text.length + i] = m
326         @message_lines[@text.length + i] = m
327         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
328       end
329
330       @text += text
331       prevm = m 
332       if l.state != :closed
333         m.chunks.each do |c|
334           cl = @chunk_layout[c]
335           cl.state ||= :closed
336           text = chunk_to_lines c, cl.state, @text.length, depth
337           (0 ... text.length).each do |i|
338             @chunk_lines[@text.length + i] = c
339             @message_lines[@text.length + i] = m
340             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
341             l.width = lw if lw > l.width
342           end
343           @text += text
344         end
345         @layout[m].bot = @text.length
346       end
347     end
348   end
349
350   def message_patina_lines m, state, start, parent, prefix, color, star_color
351     prefix_widget = [color, prefix]
352     widget = 
353       case state
354       when :closed
355         [color, "+ "]
356       when :open, :detailed
357         [color, "- "]
358       end
359     imp_widget = 
360       if m.has_label?(:starred)
361         [star_color, "* "]
362       else
363         [color, "  "]
364       end
365
366     case state
367     when :open
368       @person_lines[start] = m.from
369       [[prefix_widget, widget, imp_widget,
370         [color, 
371             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
372
373     when :closed
374       @person_lines[start] = m.from
375       [[prefix_widget, widget, imp_widget,
376         [color, 
377         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
378
379     when :detailed
380       @person_lines[start] = m.from
381       from = [[prefix_widget, widget, imp_widget, [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
382
383       rest = []
384       unless m.to.empty?
385         m.to.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
386         rest += format_person_list "  To: ", m.to
387       end
388       unless m.cc.empty?
389         m.cc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
390         rest += format_person_list "  Cc: ", m.cc
391       end
392       unless m.bcc.empty?
393         m.bcc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
394         rest += format_person_list "  Bcc: ", m.bcc
395       end
396
397       rest += [
398         "  Date: #{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})",
399         "  Subject: #{m.subj}",
400         (parent ? "  In reply to: #{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}" : nil),
401         m.labels.empty? ? nil : "  Labels: #{m.labels.join(', ')}",
402       ].compact
403       
404       from + rest.map { |l| [[color, prefix + "  " + l]] }
405     end
406   end
407
408   def format_person_list prefix, people
409     ptext = people.map { |p| format_person p }
410     pad = " " * prefix.length
411     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
412       ptext[1 .. -1].map_with_index do |e, i|
413         pad + e + (i == ptext.length - 1 ? "" : ",")
414       end
415   end
416
417   def format_person p
418     p.longname + (ContactManager.is_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
419   end
420
421   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil, star_color=nil
422     prefix = " " * INDENT_SPACES * depth
423     case chunk
424     when :fake_root
425       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
426     when nil
427       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
428     when Message
429       message_patina_lines(chunk, state, start, parent, prefix, color, star_color) +
430         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
431     when Message::Attachment
432       [[[:mime_color, "#{prefix}+ MIME attachment #{chunk.content_type}#{chunk.desc ? ' (' + chunk.desc + ')': ''}"]]]
433     when Message::Text
434       t = chunk.lines
435       if t.last =~ /^\s*$/ && t.length > 1
436         t.pop while t[-2] =~ /^\s*$/ # pop until only one file empty line
437       end
438       t.map { |line| [[:none, "#{prefix}#{line}"]] }
439     when Message::Quote
440       return [[[:quote_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
441       case state
442       when :closed
443         [[[:quote_patina_color, "#{prefix}+ (#{chunk.lines.length} quoted lines)"]]]
444       when :open
445         [[[:quote_patina_color, "#{prefix}- (#{chunk.lines.length} quoted lines)"]]] + chunk.lines.map { |line| [[:quote_color, "#{prefix}#{line}"]] }
446       end
447     when Message::Signature
448       return [[[:sig_patina_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
449       case state
450       when :closed
451         [[[:sig_patina_color, "#{prefix}+ (#{chunk.lines.length}-line signature)"]]]
452       when :open
453         [[[:sig_patina_color, "#{prefix}- (#{chunk.lines.length}-line signature)"]]] + chunk.lines.map { |line| [[:sig_color, "#{prefix}#{line}"]] }
454       end
455     else
456       raise "unknown chunk type #{chunk.class.name}"
457     end
458   end
459
460   def view_attachment a
461     BufferManager.flash "viewing #{a.content_type} attachment..."
462     success = a.view!
463     BufferManager.erase_flash
464     BufferManager.completely_redraw_screen
465     unless success
466       BufferManager.spawn "Attachment: #{a.filename}", TextMode.new(a.to_s)
467       BufferManager.flash "Couldn't execute view command, viewing as text."
468     end
469   end
470 end
471
472 end