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