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