]> git.cworth.org Git - sup/blob - lib/sup/modes/thread-view-mode.rb
fix (mostly!) the updates system
[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   HookManager.register "detailed-headers", <<EOS
17 Add or remove headers from the detailed header display of a message.
18 Variables:
19   message: The message whose headers are to be formatted.
20   headers: A hash of header (name, value) pairs, initialized to the default
21            headers.
22 Return value:
23   None. The variable 'headers' should be modified in place.
24 EOS
25
26   register_keymap do |k|
27     k.add :toggle_detailed_header, "Toggle detailed header", 'h'
28     k.add :show_header, "Show full message header", 'H'
29     k.add :activate_chunk, "Expand/collapse or activate item", :enter
30     k.add :expand_all_messages, "Expand/collapse all messages", 'E'
31     k.add :edit_draft, "Edit draft", 'e'
32     k.add :edit_labels, "Edit or add labels for a thread", 'l'
33     k.add :expand_all_quotes, "Expand/collapse all quotes in a message", 'o'
34     k.add :jump_to_next_open, "Jump to next open message", 'n'
35     k.add :jump_to_prev_open, "Jump to previous open message", 'p'
36     k.add :toggle_starred, "Star or unstar message", '*'
37     k.add :toggle_new, "Toggle new/read status of message", 'N'
38 #    k.add :collapse_non_new_messages, "Collapse all but unread messages", 'N'
39     k.add :reply, "Reply to a message", 'r'
40     k.add :forward, "Forward a message", 'f'
41     k.add :alias, "Edit alias/nickname for a person", 'i'
42     k.add :edit_as_new, "Edit message as new", 'D'
43     k.add :save_to_disk, "Save message/attachment to disk", 's'
44     k.add :search, "Search for messages from particular people", 'S'
45     k.add :compose, "Compose message to person", 'm'
46     k.add :archive_and_kill, "Archive thread and kill buffer", 'a'
47     k.add :delete_and_kill, "Delete thread and kill buffer", 'd'
48     k.add :subscribe_to_list, "Subscribe to/unsubscribe from mailing list", "("
49     k.add :unsubscribe_from_list, "Subscribe to/unsubscribe from mailing list", ")"
50   end
51
52   ## there are a couple important instance variables we hold to format
53   ## the thread and to provide line-based functionality. @layout is a
54   ## map from Messages to MessageLayouts, and @chunk_layout from
55   ## Chunks to ChunkLayouts.  @message_lines is a map from row #s to
56   ## Message objects.  @chunk_lines is a map from row #s to Chunk
57   ## objects. @person_lines is a map from row #s to Person objects.
58
59   def initialize thread, hidden_labels=[]
60     super()
61     @thread = thread
62     @hidden_labels = hidden_labels
63
64     @layout = SavingHash.new { MessageLayout.new }
65     @chunk_layout = SavingHash.new { ChunkLayout.new }
66     earliest, latest = nil, nil
67     latest_date = nil
68     altcolor = false
69
70     @thread.each do |m, d, p|
71       next unless m
72       earliest ||= m
73       @layout[m].state = initial_state_for m
74       @layout[m].color = altcolor ? :alternate_patina_color : :message_patina_color
75       @layout[m].star_color = altcolor ? :alternate_starred_patina_color : :starred_patina_color
76       @layout[m].orig_new = m.has_label? :read
77       altcolor = !altcolor
78       if latest_date.nil? || m.date > latest_date
79         latest_date = m.date
80         latest = m
81       end
82     end
83
84     @layout[latest].state = :open if @layout[latest].state == :closed
85     @layout[earliest].state = :detailed if earliest.has_label?(:unread) || @thread.size == 1
86
87     @thread.remove_label :unread
88     regen_text
89   end
90
91   def draw_line ln, opts={}
92     if ln == curpos
93       super ln, :highlight => true
94     else
95       super
96     end
97   end
98   def lines; @text.length; end
99   def [] i; @text[i]; end
100
101   def show_header
102     m = @message_lines[curpos] or return
103     BufferManager.spawn_unless_exists("Full header") do
104       TextMode.new m.raw_header
105     end
106   end
107
108   def toggle_detailed_header
109     m = @message_lines[curpos] or return
110     @layout[m].state = (@layout[m].state == :detailed ? :open : :detailed)
111     update
112   end
113
114   def reply
115     m = @message_lines[curpos] or return
116     mode = ReplyMode.new m
117     BufferManager.spawn "Reply to #{m.subj}", mode
118   end
119
120   def subscribe_to_list
121     m = @message_lines[curpos] or return
122     if m.list_subscribe && m.list_subscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
123       ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
124     else
125       BufferManager.flash "Can't find List-Subscribe header for this message."
126     end
127   end
128
129   def unsubscribe_from_list
130     m = @message_lines[curpos] or return
131     if m.list_unsubscribe && m.list_unsubscribe =~ /<mailto:(.*?)\?(subject=(.*?))>/
132       ComposeMode.spawn_nicely :from => AccountManager.account_for(m.recipient_email), :to => [PersonManager.person_for($1)], :subj => $3
133     else
134       BufferManager.flash "Can't find List-Unsubscribe header for this message."
135     end
136   end
137
138   def forward
139     m = @message_lines[curpos] or return
140     ForwardMode.spawn_nicely m
141   end
142
143   include CanAliasContacts
144   def alias
145     p = @person_lines[curpos] or return
146     alias_contact p
147     update
148   end
149
150   def search
151     p = @person_lines[curpos] or return
152     mode = PersonSearchResultsMode.new [p]
153     BufferManager.spawn "Search for #{p.name}", mode
154     mode.load_threads :num => mode.buffer.content_height
155   end    
156
157   def compose
158     p = @person_lines[curpos]
159     if p
160       ComposeMode.spawn_nicely :to => [p]
161     else
162       ComposeMode.spawn_nicely
163     end
164   end    
165
166   def edit_labels
167     reserved_labels = @thread.labels.select { |l| LabelManager::RESERVED_LABELS.include? l }
168     new_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", @thread.labels
169
170     return unless new_labels
171     @thread.labels = (reserved_labels + new_labels).uniq
172     new_labels.each { |l| LabelManager << l }
173     update
174     UpdateManager.relay self, :labeled, @thread.first
175   end
176
177   def toggle_starred
178     m = @message_lines[curpos] or return
179     toggle_label m, :starred
180   end
181
182   def toggle_new
183     m = @message_lines[curpos] or return
184     toggle_label m, :unread
185   end
186
187   def toggle_label m, label
188     if m.has_label? label
189       m.remove_label label
190     else
191       m.add_label label
192     end
193     ## TODO: don't recalculate EVERYTHING just to add a stupid little
194     ## star to the display
195     update
196     UpdateManager.relay self, :single_message_labeled, m
197   end
198
199   ## called when someone presses enter when the cursor is highlighting
200   ## a chunk. for expandable chunks (including messages) we toggle
201   ## open/closed state; for viewable chunks (like attachments) we
202   ## view.
203   def activate_chunk
204     chunk = @chunk_lines[curpos] or return
205     layout = 
206       if chunk.is_a?(Message)
207         @layout[chunk]
208       elsif chunk.expandable?
209         @chunk_layout[chunk]
210       end
211     if layout
212       layout.state = (layout.state != :closed ? :closed : :open)
213       #cursor_down if layout.state == :closed # too annoying
214       update
215     elsif chunk.viewable?
216       view chunk
217     end
218   end
219
220   def edit_as_new
221     m = @message_lines[curpos] or return
222     mode = ComposeMode.new(:body => m.quotable_body_lines, :to => m.to, :cc => m.cc, :subj => m.subj, :bcc => m.bcc)
223     BufferManager.spawn "edit as new", mode
224     mode.edit_message
225   end
226
227   def save_to_disk
228     chunk = @chunk_lines[curpos] or return
229     case chunk
230     when Chunk::Attachment
231       fn = BufferManager.ask_for_filename :filename, "Save attachment to file: ", chunk.filename
232       save_to_file(fn) { |f| f.print chunk.raw_content } if fn
233     else
234       m = @message_lines[curpos]
235       fn = BufferManager.ask_for_filename :filename, "Save message to file: "
236       return unless fn
237       save_to_file(fn) do |f|
238         m.each_raw_message_line { |l| f.print l }
239       end
240     end
241   end
242
243   def edit_draft
244     m = @message_lines[curpos] or return
245     if m.is_draft?
246       mode = ResumeMode.new m
247       BufferManager.spawn "Edit message", mode
248       BufferManager.kill_buffer self.buffer
249       mode.edit_message
250     else
251       BufferManager.flash "Not a draft message!"
252     end
253   end
254
255   def jump_to_first_open
256     m = @message_lines[0] or return
257     if @layout[m].state != :closed
258       jump_to_message m
259     else
260       jump_to_next_open
261     end
262   end
263
264   def jump_to_next_open
265     return continue_search_in_buffer if in_search? # hack: allow 'n' to apply to both operations
266     m = @message_lines[curpos] or return
267     while nextm = @layout[m].next
268       break if @layout[nextm].state != :closed
269       m = nextm
270     end
271     jump_to_message nextm if nextm
272   end
273
274   def jump_to_prev_open
275     m = @message_lines[curpos] or return
276     ## jump to the top of the current message if we're in the body;
277     ## otherwise, to the previous message
278     
279     top = @layout[m].top
280     if curpos == top
281       while(prevm = @layout[m].prev)
282         break if @layout[prevm].state != :closed
283         m = prevm
284       end
285       jump_to_message prevm if prevm
286     else
287       jump_to_message m
288     end
289   end
290
291   def jump_to_message m
292     l = @layout[m]
293     left = l.depth * INDENT_SPACES
294     right = left + l.width
295
296     ## jump to the top line unless both top and bottom fit in the current view
297     jump_to_line l.top unless l.top >= topline && l.top <= botline && l.bot >= topline && l.bot <= botline
298
299     ## jump to the left columns unless both left and right fit in the current view
300     jump_to_col left unless left >= leftcol && left <= rightcol && right >= leftcol && right <= rightcol
301
302     ## either way, move the cursor to the first line
303     set_cursor_pos l.top
304   end
305
306   def expand_all_messages
307     @global_message_state ||= :closed
308     @global_message_state = (@global_message_state == :closed ? :open : :closed)
309     @layout.each { |m, l| l.state = @global_message_state }
310     update
311   end
312
313   def collapse_non_new_messages
314     @layout.each { |m, l| l.state = l.orig_new ? :open : :closed }
315     update
316   end
317
318   def expand_all_quotes
319     if(m = @message_lines[curpos])
320       quotes = m.chunks.select { |c| (c.is_a?(Chunk::Quote) || c.is_a?(Chunk::Signature)) && c.lines.length > 1 }
321       numopen = quotes.inject(0) { |s, c| s + (@chunk_layout[c].state == :open ? 1 : 0) }
322       newstate = numopen > quotes.length / 2 ? :closed : :open
323       quotes.each { |c| @chunk_layout[c].state = newstate }
324       update
325     end
326   end
327
328   def cleanup
329     @layout = @chunk_layout = @text = nil # for good luck
330   end
331
332   def archive_and_kill
333     @thread.remove_label :inbox
334     UpdateManager.relay self, :archived, @thread.first
335     BufferManager.kill_buffer_safely buffer
336   end
337
338   def delete_and_kill
339     @thread.apply_label :deleted
340     UpdateManager.relay self, :deleted, @thread.first
341     BufferManager.kill_buffer_safely buffer
342   end
343
344 private
345
346   def initial_state_for m
347     if m.has_label?(:starred) || m.has_label?(:unread)
348       :open
349     else
350       :closed
351     end
352   end
353
354   def update
355     regen_text
356     buffer.mark_dirty if buffer
357   end
358
359   ## here we generate the actual content lines. we accumulate
360   ## everything into @text, and we set @chunk_lines and
361   ## @message_lines, and we update @layout.
362   def regen_text
363     @text = []
364     @chunk_lines = []
365     @message_lines = []
366     @person_lines = []
367
368     prevm = nil
369     @thread.each do |m, depth, parent|
370       unless m.is_a? Message # handle nil and :fake_root
371         @text += chunk_to_lines m, nil, @text.length, depth, parent
372         next
373       end
374       l = @layout[m]
375
376       ## is this still necessary?
377       next unless @layout[m].state # skip discarded drafts
378
379       ## build the patina
380       text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
381       
382       l.top = @text.length
383       l.bot = @text.length + text.length # updated below
384       l.prev = prevm
385       l.next = nil
386       l.depth = depth
387       # l.state we preserve
388       l.width = 0 # updated below
389       @layout[l.prev].next = m if l.prev
390
391       (0 ... text.length).each do |i|
392         @chunk_lines[@text.length + i] = m
393         @message_lines[@text.length + i] = m
394         lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum
395       end
396
397       @text += text
398       prevm = m 
399       if l.state != :closed
400         m.chunks.each do |c|
401           cl = @chunk_layout[c]
402
403           ## set the default state for chunks
404           cl.state ||=
405             if c.expandable? && c.respond_to?(:initial_state)
406               c.initial_state
407             else
408               :closed
409             end
410
411           text = chunk_to_lines c, cl.state, @text.length, depth
412           (0 ... text.length).each do |i|
413             @chunk_lines[@text.length + i] = c
414             @message_lines[@text.length + i] = m
415             lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.length }.sum - (depth * INDENT_SPACES)
416             l.width = lw if lw > l.width
417           end
418           @text += text
419         end
420         @layout[m].bot = @text.length
421       end
422     end
423   end
424
425   def message_patina_lines m, state, start, parent, prefix, color, star_color
426     prefix_widget = [color, prefix]
427
428     open_widget = [color, (state == :closed ? "+ " : "- ")]
429     new_widget = [color, (m.has_label?(:unread) ? "N" : " ")]
430     starred_widget = 
431       if m.has_label?(:starred)
432         [star_color, "* "]
433       else
434         [color, "  "]
435       end
436
437     case state
438     when :open
439       @person_lines[start] = m.from
440       [[prefix_widget, open_widget, new_widget, starred_widget,
441         [color, 
442             "#{m.from ? m.from.mediumname : '?'} to #{m.recipients.map { |l| l.shortname }.join(', ')} #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})"]]]
443
444     when :closed
445       @person_lines[start] = m.from
446       [[prefix_widget, open_widget, new_widget, starred_widget,
447         [color, 
448         "#{m.from ? m.from.mediumname : '?'}, #{m.date.to_nice_s} (#{m.date.to_nice_distance_s})  #{m.snippet}"]]]
449
450     when :detailed
451       @person_lines[start] = m.from
452       from_line = [[prefix_widget, open_widget, new_widget, starred_widget,
453           [color, "From: #{m.from ? format_person(m.from) : '?'}"]]]
454
455       addressee_lines = []
456       unless m.to.empty?
457         m.to.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
458         addressee_lines += format_person_list "   To: ", m.to
459       end
460       unless m.cc.empty?
461         m.cc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
462         addressee_lines += format_person_list "   Cc: ", m.cc
463       end
464       unless m.bcc.empty?
465         m.bcc.each_with_index { |p, i| @person_lines[start + addressee_lines.length + from_line.length + i] = p }
466         addressee_lines += format_person_list "   Bcc: ", m.bcc
467       end
468
469       headers = OrderedHash.new
470       headers["Date"] = "#{m.date.strftime DATE_FORMAT} (#{m.date.to_nice_distance_s})"
471       headers["Subject"] = m.subj
472
473       show_labels = @thread.labels - LabelManager::HIDDEN_RESERVED_LABELS
474       unless show_labels.empty?
475         headers["Labels"] = show_labels.map { |x| x.to_s }.sort.join(', ')
476       end
477       if parent
478         headers["In reply to"] = "#{parent.from.mediumname}'s message of #{parent.date.strftime DATE_FORMAT}"
479       end
480
481       HookManager.run "detailed-headers", :message => m, :headers => headers
482       
483       from_line + (addressee_lines + headers.map { |k, v| "   #{k}: #{v}" }).map { |l| [[color, prefix + "  " + l]] }
484     end
485   end
486
487   def format_person_list prefix, people
488     ptext = people.map { |p| format_person p }
489     pad = " " * prefix.length
490     [prefix + ptext.first + (ptext.length > 1 ? "," : "")] + 
491       ptext[1 .. -1].map_with_index do |e, i|
492         pad + e + (i == ptext.length - 1 ? "" : ",")
493       end
494   end
495
496   def format_person p
497     p.longname + (ContactManager.is_contact?(p) ? " (#{ContactManager.alias_for p})" : "")
498   end
499
500   ## todo: check arguments on this overly complex function
501   def chunk_to_lines chunk, state, start, depth, parent=nil, color=nil, star_color=nil
502     prefix = " " * INDENT_SPACES * depth
503     case chunk
504     when :fake_root
505       [[[:missing_message_color, "#{prefix}<one or more unreceived messages>"]]]
506     when nil
507       [[[:missing_message_color, "#{prefix}<an unreceived message>"]]]
508     when Message
509       message_patina_lines(chunk, state, start, parent, prefix, color, star_color) +
510         (chunk.is_draft? ? [[[:draft_notification_color, prefix + " >>> This message is a draft. To edit, hit 'e'. <<<"]]] : [])
511
512     else
513       raise "Bad chunk: #{chunk.inspect}" unless chunk.respond_to?(:inlineable?) ## debugging
514       if chunk.inlineable?
515         chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
516       elsif chunk.expandable?
517         case state
518         when :closed
519           [[[chunk.patina_color, "#{prefix}+ #{chunk.patina_text}"]]]
520         when :open
521           [[[chunk.patina_color, "#{prefix}- #{chunk.patina_text}"]]] + chunk.lines.map { |line| [[chunk.color, "#{prefix}#{line}"]] }
522         end
523       else
524         [[[chunk.patina_color, "#{prefix}x #{chunk.patina_text}"]]]
525       end
526     end
527   end
528
529   def view chunk
530     BufferManager.flash "viewing #{chunk.content_type} attachment..."
531     success = chunk.view!
532     BufferManager.erase_flash
533     BufferManager.completely_redraw_screen
534     unless success
535       BufferManager.spawn "Attachment: #{chunk.filename}", TextMode.new(chunk.to_s)
536       BufferManager.flash "Couldn't execute view command, viewing as text."
537     end
538   end
539 end
540
541 end