]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
fixed loading bug (messages now loaded completely before tehread-view-mode gets them...
[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     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     update
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       l = @layout[m]
291
292       ## build the patina
293       text = chunk_to_lines m, l.state, @text.length, depth, parent, @layout[m].color
294       
295       l.top = @text.length
296       l.bot = @text.length + text.length # updated below
297       l.prev = prevm
298       l.next = nil
299       l.depth = depth
300       # l.state we preserve
301       l.width = 0 # updated below
302       @layout[l.prev].next = m if l.prev
303
304       (0 ... text.length).each do |i|
305         @chunk_lines[@text.length + i] = m
306         @message_lines[@text.length + i] = m
307         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
308       end
309
310       @text += text
311       prevm = m 
312       if @layout[m].state != :closed
313         m.chunks.each do |c|
314           cl = (@layout[c] ||= Layout.new)
315           cl.state ||= :closed
316           text = chunk_to_lines c, cl.state, @text.length, depth
317           (0 ... text.length).each do |i|
318             @chunk_lines[@text.length + i] = c
319             @message_lines[@text.length + i] = m
320             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
321             l.width = lw if lw > l.width
322           end
323           @text += text
324         end
325         @layout[m].bot = @text.length
326       end
327     end
328   end
329
330   def message_patina_lines m, state, start, parent, prefix, color
331     prefix_widget = [color, prefix]
332     widget = 
333       case state
334       when :closed
335         [color, "+ "]
336       when :open, :detailed
337         [color, "- "]
338       end
339     imp_widget = 
340       if m.has_label?(:starred)
341         [:starred_patina_color, "* "]
342       else
343         [color, "  "]
344       end
345
346     case state
347     when :open
348       @person_lines[start] = m.from
349       [[prefix_widget, widget, imp_widget,
350         [color, 
351             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
352
353     when :closed
354       @person_lines[start] = m.from
355       [[prefix_widget, widget, imp_widget,
356         [color, 
357         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
358
359     when :detailed
360       @person_lines[start] = m.from
361       from = [[prefix_widget, widget, imp_widget, [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
362
363       rest = []
364       unless m.to.empty?
365         m.to.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
366         rest += format_person_list "  To: ", m.to
367       end
368       unless m.cc.empty?
369         m.cc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
370         rest += format_person_list "  Cc: ", m.cc
371       end
372       unless m.bcc.empty?
373         m.bcc.each_with_index { |p, i| @person_lines[start + rest.length + from.length + i] = p }
374         rest += format_person_list "  Bcc: ", m.bcc
375       end
376
377       rest += [
378         "  Date: #{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})",
379         "  Subject: #{m.subj}",
380         (parent ? "  In reply to: #{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}" : nil),
381         m.labels.empty? ? nil : "  Labels: #{m.labels.join(', ')}",
382       ].compact
383       
384       from + rest.map { |l| [[color, prefix + "  " + l]] }
385     end
386   end
387
388   def format_person_list prefix, people
389     ptext = people.map { |p| format_person p }
390     pad = " " * prefix.length
391     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
392       ptext[1 .. -1].map_with_index do |e, i|
393         pad + e + (i == ptext.length - 1 ? "" : ",")
394       end
395   end
396
397   def format_person p
398     p.longname + (ContactManager.is_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
399   end
400
401   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil
402     prefix = " " * INDENT_SPACES * depth
403     case chunk
404     when :fake_root
405       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
406     when nil
407       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
408     when Message
409       message_patina_lines(chunk, state, start, parent, prefix, color) +
410         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
411     when Message::Attachment
412       [[[:mime_color, "#{prefix}+ MIME attachment #{chunk.content_type}#{chunk.desc ? ' (' + chunk.desc + ')': ''}"]]]
413     when Message::Text
414       t = chunk.lines
415       if t.last =~ /^\s*$/ && t.length > 1
416         t.pop while t[-2] =~ /^\s*$/ # pop until only one file empty line
417       end
418       t.map { |line| [[:none, "#{prefix}#{line}"]] }
419     when Message::Quote
420       return [[[:quote_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
421       case state
422       when :closed
423         [[[:quote_patina_color, "#{prefix}+ (#{chunk.lines.length} quoted lines)"]]]
424       when :open
425         [[[:quote_patina_color, "#{prefix}- (#{chunk.lines.length} quoted lines)"]]] + chunk.lines.map { |line| [[:quote_color, "#{prefix}#{line}"]] }
426       end
427     when Message::Signature
428       return [[[:sig_patina_color, "#{prefix}#{chunk.lines.first}"]]] if chunk.lines.length == 1
429       case state
430       when :closed
431         [[[:sig_patina_color, "#{prefix}+ (#{chunk.lines.length}-line signature)"]]]
432       when :open
433         [[[:sig_patina_color, "#{prefix}- (#{chunk.lines.length}-line signature)"]]] + chunk.lines.map { |line| [[:sig_color, "#{prefix}#{line}"]] }
434       end
435     else
436       raise "unknown chunk type #{chunk.class.name}"
437     end
438   end
439
440   def view_attachment a
441     BufferManager.flash "viewing #{a.content_type} attachment..."
442     success = a.view!
443     BufferManager.erase_flash
444     BufferManager.completely_redraw_screen
445     BufferManager.flash "Couldn't execute view command." unless success
446   end
447
448 end
449
450 end