sup

A curses threads-with-tags style email client

sup.git

git clone https://supmua.dev/git/sup/

lib/sup/modes/thread_index_mode.rb (29746B) - raw

      1 require 'set'
      2 
      3 module Redwood
      4 
      5 ## subclasses should implement:
      6 ## - is_relevant?
      7 
      8 class ThreadIndexMode < LineCursorMode
      9   DATE_WIDTH = Time::TO_NICE_S_MAX_LEN
     10   MIN_FROM_WIDTH = 15
     11   LOAD_MORE_THREAD_NUM = 20
     12 
     13   HookManager.register "index-mode-size-widget", <<EOS
     14 Generates the per-thread size widget for each thread.
     15 Variables:
     16   thread: The message thread to be formatted.
     17 EOS
     18 
     19   HookManager.register "index-mode-date-widget", <<EOS
     20 Generates the per-thread date widget for each thread.
     21 Variables:
     22   thread: The message thread to be formatted.
     23 EOS
     24 
     25   HookManager.register "mark-as-spam", <<EOS
     26 This hook is run when a thread is marked as spam
     27 Variables:
     28   thread: The message thread being marked as spam.
     29 EOS
     30 
     31   register_keymap do |k|
     32     k.add :load_threads, "Load #{LOAD_MORE_THREAD_NUM} more threads", 'M'
     33     k.add_multi "Load all threads (! to confirm) :", '!' do |kk|
     34       kk.add :load_all_threads, "Load all threads (may list a _lot_ of threads)", '!'
     35     end
     36     k.add :read_and_archive, "Archive thread (remove from inbox) and mark read", 'A'
     37     k.add :cancel_search, "Cancel current search", :ctrl_g
     38     k.add :reload, "Refresh view", '@'
     39     k.add :toggle_archived, "Toggle archived status", 'a'
     40     k.add :toggle_starred, "Star or unstar all messages in thread", '*'
     41     k.add :toggle_new, "Toggle new/read status of all messages in thread", 'N'
     42     k.add :edit_labels, "Edit or add labels for a thread", 'l'
     43     k.add :edit_message, "Edit message (drafts only)", 'e'
     44     k.add :toggle_spam, "Mark/unmark thread as spam", 'S'
     45     k.add :toggle_deleted, "Delete/undelete thread", 'd'
     46     k.add :kill, "Kill thread (never to be seen in inbox again)", '&'
     47     k.add :flush_index, "Flush all changes now", '$'
     48     k.add :jump_to_next_new, "Jump to next new thread", :tab
     49     k.add :reply, "Reply to latest message in a thread", 'r'
     50     k.add :reply_all, "Reply to all participants of the latest message in a thread", 'G'
     51     k.add :forward, "Forward latest message in a thread", 'f'
     52     k.add :toggle_tagged, "Tag/untag selected thread", 't'
     53     k.add :toggle_tagged_all, "Tag/untag all threads", 'T'
     54     k.add :tag_matching, "Tag matching threads", 'g'
     55     k.add :apply_to_tagged, "Apply next command to all tagged threads", '+', '='
     56     k.add :join_threads, "Force tagged threads to be joined into the same thread", '#'
     57     k.add :undo, "Undo the previous action", 'u'
     58   end
     59 
     60   def initialize hidden_labels=[], load_thread_opts={}
     61     super()
     62     @mutex = Mutex.new # covers the following variables:
     63     @threads = []
     64     @hidden_threads = {}
     65     @size_widget_width = nil
     66     @size_widgets = []
     67     @date_widget_width = nil
     68     @date_widgets = []
     69     @tags = Tagger.new self
     70 
     71     ## these guys, and @text and @lines, are not covered
     72     @load_thread = nil
     73     @load_thread_opts = load_thread_opts
     74     @hidden_labels = hidden_labels + LabelManager::HIDDEN_RESERVED_LABELS
     75     @date_width = DATE_WIDTH
     76 
     77     @interrupt_search = false
     78 
     79     initialize_threads # defines @ts and @ts_mutex
     80     update # defines @text and @lines
     81 
     82     UpdateManager.register self
     83 
     84     @save_thread_mutex = Mutex.new
     85 
     86     @last_load_more_size = nil
     87     to_load_more do |size|
     88       next if @last_load_more_size == 0
     89       load_threads :num => size,
     90                    :when_done => lambda { |num| @last_load_more_size = num }
     91     end
     92   end
     93 
     94   def unsaved?; dirty? end
     95   def lines; @text.length; end
     96   def [] i; @text[i]; end
     97   def contains_thread? t; @threads.include?(t) end
     98 
     99   def reload
    100     drop_all_threads
    101     UndoManager.clear
    102     BufferManager.draw_screen
    103     load_threads :num => buffer.content_height
    104   end
    105 
    106   ## open up a thread view window
    107   def select t=nil, when_done=nil
    108     t ||= cursor_thread or return
    109 
    110     Redwood::reporting_thread("load messages for thread-view-mode") do
    111       num = t.size
    112       message = "Loading #{num.pluralize 'message body'}..."
    113       BufferManager.say(message) do |sid|
    114         t.each_with_index do |(m, *_), i|
    115           next unless m
    116           BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1
    117           m.load_from_source!
    118         end
    119       end
    120       mode = ThreadViewMode.new t, @hidden_labels, self
    121       BufferManager.spawn t.subj, mode
    122       BufferManager.draw_screen
    123       mode.jump_to_first_open if $config[:jump_to_open_message]
    124       BufferManager.draw_screen # lame TODO: make this unnecessary
    125       ## the first draw_screen is needed before topline and botline
    126       ## are set, and the second to show the cursor having moved
    127 
    128       t.remove_label :unread
    129       Index.save_thread t
    130 
    131       update_text_for_line curpos
    132       UpdateManager.relay self, :read, t.first
    133       when_done.call if when_done
    134     end
    135   end
    136 
    137   def multi_select threads
    138     threads.each { |t| select t }
    139   end
    140 
    141   ## these two methods are called by thread-view-modes when the user
    142   ## wants to view the previous/next thread without going back to
    143   ## index-mode. we update the cursor as a convenience.
    144   def launch_next_thread_after thread, &b
    145     launch_another_thread thread, 1, &b
    146   end
    147 
    148   def launch_prev_thread_before thread, &b
    149     launch_another_thread thread, -1, &b
    150   end
    151 
    152   def launch_another_thread thread, direction, &b
    153     l = @lines[thread] or return
    154     target_l = l + direction
    155     t = @mutex.synchronize do
    156       if target_l >= 0 && target_l < @threads.length
    157         @threads[target_l]
    158       end
    159     end
    160 
    161     if t # there's a next thread
    162       set_cursor_pos target_l # move out of mutex?
    163       select t, b
    164     elsif b # no next thread. call the block anyways
    165       b.call
    166     end
    167   end
    168 
    169   def handle_single_message_labeled_update sender, m
    170     ## no need to do anything different here; we don't differentiate
    171     ## messages from their containing threads
    172     handle_labeled_update sender, m
    173   end
    174 
    175   def handle_labeled_update sender, m
    176     if(t = thread_containing(m))
    177       l = @lines[t] or return
    178       update_text_for_line l
    179     elsif is_relevant?(m)
    180       add_or_unhide m
    181     end
    182   end
    183 
    184   def handle_simple_update sender, m
    185     t = thread_containing(m) or return
    186     l = @lines[t] or return
    187     update_text_for_line l
    188   end
    189 
    190   %w(read unread archived starred unstarred).each do |state|
    191     define_method "handle_#{state}_update" do |*a|
    192       handle_simple_update(*a)
    193     end
    194   end
    195 
    196   ## overwrite me!
    197   def is_relevant? m; false; end
    198 
    199   def handle_added_update sender, m
    200     add_or_unhide m
    201     BufferManager.draw_screen
    202   end
    203 
    204   def handle_updated_update sender, m
    205     t = thread_containing(m) or return
    206     l = @lines[t] or return
    207     @ts_mutex.synchronize do
    208       @ts.delete_message m
    209       @ts.add_message m
    210     end
    211     Index.save_thread t, sync_back = false
    212     update_text_for_line l
    213   end
    214 
    215   def handle_location_deleted_update sender, m
    216     t = thread_containing(m)
    217     delete_thread t if t and t.first.id == m.id
    218     @ts_mutex.synchronize do
    219       @ts.delete_message m if t
    220     end
    221     update
    222   end
    223 
    224   def handle_single_message_deleted_update sender, m
    225     @ts_mutex.synchronize do
    226       return unless @ts.contains? m
    227       @ts.remove_id m.id
    228     end
    229     update
    230   end
    231 
    232   def handle_deleted_update sender, m
    233     t = @ts_mutex.synchronize { @ts.thread_for m }
    234     return unless t
    235     hide_thread t
    236     update
    237   end
    238 
    239   def handle_killed_update sender, m
    240     t = @ts_mutex.synchronize { @ts.thread_for m }
    241     return unless t
    242     hide_thread t
    243     update
    244   end
    245 
    246   def handle_spammed_update sender, m
    247     t = @ts_mutex.synchronize { @ts.thread_for m }
    248     return unless t
    249     hide_thread t
    250     update
    251   end
    252 
    253   def handle_undeleted_update sender, m
    254     add_or_unhide m
    255   end
    256 
    257   def handle_unkilled_update sender, m
    258     add_or_unhide m
    259   end
    260 
    261   def undo
    262     UndoManager.undo
    263   end
    264 
    265   def update
    266     old_cursor_thread = cursor_thread
    267     @mutex.synchronize do
    268       ## let's see you do THIS in python
    269       @threads = @ts.threads.select { |t| !@hidden_threads.member?(t) }.select(&:has_message?).sort_by(&:sort_key)
    270       @size_widgets = @threads.map { |t| size_widget_for_thread t }
    271       @size_widget_width = @size_widgets.max_of { |w| w.display_length }
    272       @date_widgets = @threads.map { |t| date_widget_for_thread t }
    273       @date_widget_width = @date_widgets.max_of { |w| w.display_length }
    274     end
    275     set_cursor_pos @threads.index(old_cursor_thread)||curpos
    276 
    277     regen_text
    278   end
    279 
    280   def edit_message
    281     return unless(t = cursor_thread)
    282     message, *_ = t.find { |m, *o| m.has_label? :draft }
    283     if message
    284       mode = ResumeMode.new message
    285       BufferManager.spawn "Edit message", mode
    286     else
    287       BufferManager.flash "Not a draft message!"
    288     end
    289   end
    290 
    291   ## returns an undo lambda
    292   def actually_toggle_starred t
    293     if t.has_label? :starred # if ANY message has a star
    294       t.remove_label :starred # remove from all
    295       UpdateManager.relay self, :unstarred, t.first
    296       lambda do
    297         t.first.add_label :starred
    298         UpdateManager.relay self, :starred, t.first
    299         regen_text
    300       end
    301     else
    302       t.first.add_label :starred # add only to first
    303       UpdateManager.relay self, :starred, t.first
    304       lambda do
    305         t.remove_label :starred
    306         UpdateManager.relay self, :unstarred, t.first
    307         regen_text
    308       end
    309     end
    310   end
    311 
    312   def toggle_starred
    313     t = cursor_thread or return
    314     undo = actually_toggle_starred t
    315     UndoManager.register "toggling thread starred status", undo, lambda { Index.save_thread t }
    316     update_text_for_line curpos
    317     cursor_down
    318     Index.save_thread t
    319   end
    320 
    321   def multi_toggle_starred threads
    322     UndoManager.register "toggling #{threads.size.pluralize 'thread'} starred status",
    323       threads.map { |t| actually_toggle_starred t },
    324       lambda { threads.each { |t| Index.save_thread t } }
    325     regen_text
    326     threads.each { |t| Index.save_thread t }
    327   end
    328 
    329   ## returns an undo lambda
    330   def actually_toggle_archived t
    331     thread = t
    332     pos = curpos
    333     if t.has_label? :inbox
    334       t.remove_label :inbox
    335       UpdateManager.relay self, :archived, t.first
    336       lambda do
    337         thread.apply_label :inbox
    338         update_text_for_line pos
    339         UpdateManager.relay self,:unarchived, thread.first
    340       end
    341     else
    342       t.apply_label :inbox
    343       UpdateManager.relay self, :unarchived, t.first
    344       lambda do
    345         thread.remove_label :inbox
    346         update_text_for_line pos
    347         UpdateManager.relay self, :unarchived, thread.first
    348       end
    349     end
    350   end
    351 
    352   ## returns an undo lambda
    353   def actually_toggle_spammed t
    354     thread = t
    355     if t.has_label? :spam
    356       t.remove_label :spam
    357       add_or_unhide t.first
    358       UpdateManager.relay self, :unspammed, t.first
    359       lambda do
    360         thread.apply_label :spam
    361         self.hide_thread thread
    362         UpdateManager.relay self,:spammed, thread.first
    363       end
    364     else
    365       t.apply_label :spam
    366       hide_thread t
    367       UpdateManager.relay self, :spammed, t.first
    368       lambda do
    369         thread.remove_label :spam
    370         add_or_unhide thread.first
    371         UpdateManager.relay self,:unspammed, thread.first
    372       end
    373     end
    374   end
    375 
    376   ## returns an undo lambda
    377   def actually_toggle_deleted t
    378     if t.has_label? :deleted
    379       t.remove_label :deleted
    380       add_or_unhide t.first
    381       UpdateManager.relay self, :undeleted, t.first
    382       lambda do
    383         t.apply_label :deleted
    384         hide_thread t
    385         UpdateManager.relay self, :deleted, t.first
    386       end
    387     else
    388       t.apply_label :deleted
    389       hide_thread t
    390       UpdateManager.relay self, :deleted, t.first
    391       lambda do
    392         t.remove_label :deleted
    393         add_or_unhide t.first
    394         UpdateManager.relay self, :undeleted, t.first
    395       end
    396     end
    397   end
    398 
    399   def toggle_archived
    400     t = cursor_thread or return
    401     undo = actually_toggle_archived t
    402     UndoManager.register "deleting/undeleting thread #{t.first.id}", undo, lambda { update_text_for_line curpos },
    403                          lambda { Index.save_thread t }
    404     update_text_for_line curpos
    405     Index.save_thread t
    406   end
    407 
    408   def multi_toggle_archived threads
    409     undos = threads.map { |t| actually_toggle_archived t }
    410     UndoManager.register "deleting/undeleting #{threads.size.pluralize 'thread'}", undos, lambda { regen_text },
    411                          lambda { threads.each { |t| Index.save_thread t } }
    412     regen_text
    413     threads.each { |t| Index.save_thread t }
    414   end
    415 
    416   def toggle_new
    417     t = cursor_thread or return
    418     t.toggle_label :unread
    419     update_text_for_line curpos
    420     cursor_down
    421     Index.save_thread t
    422   end
    423 
    424   def multi_toggle_new threads
    425     threads.each { |t| t.toggle_label :unread }
    426     regen_text
    427     threads.each { |t| Index.save_thread t }
    428   end
    429 
    430   def multi_toggle_tagged threads
    431     @mutex.synchronize { @tags.drop_all_tags }
    432     regen_text
    433   end
    434 
    435   def join_threads
    436     ## this command has no non-tagged form. as a convenience, allow this
    437     ## command to be applied to tagged threads without hitting ';'.
    438     @tags.apply_to_tagged :join_threads
    439   end
    440 
    441   def multi_join_threads threads
    442     @ts.join_threads threads or return
    443     threads.each { |t| Index.save_thread t }
    444     @tags.drop_all_tags # otherwise we have tag pointers to invalid threads!
    445     update
    446   end
    447 
    448   def jump_to_next_new
    449     n = @mutex.synchronize do
    450       ((curpos + 1) ... lines).find { |i| @threads[i].has_label? :unread } ||
    451         (0 ... curpos).find { |i| @threads[i].has_label? :unread }
    452     end
    453     if n
    454       ## jump there if necessary
    455       jump_to_line n unless n >= topline && n < botline
    456       set_cursor_pos n
    457     else
    458       BufferManager.flash "No new messages."
    459     end
    460   end
    461 
    462   def toggle_spam
    463     t = cursor_thread or return
    464     multi_toggle_spam [t]
    465   end
    466 
    467   ## both spam and deleted have the curious characteristic that you
    468   ## always want to hide the thread after either applying or removing
    469   ## that label. in all thread-index-views except for
    470   ## label-search-results-mode, when you mark a message as spam or
    471   ## deleted, you want it to disappear immediately; in LSRM, you only
    472   ## see deleted or spam emails, and when you undelete or unspam them
    473   ## you also want them to disappear immediately.
    474   def multi_toggle_spam threads
    475     undos = threads.map { |t| actually_toggle_spammed t }
    476     threads.each { |t| HookManager.run("mark-as-spam", :thread => t) }
    477     UndoManager.register "marking/unmarking  #{threads.size.pluralize 'thread'} as spam",
    478                          undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } }
    479     regen_text
    480     threads.each { |t| Index.save_thread t }
    481   end
    482 
    483   def toggle_deleted
    484     t = cursor_thread or return
    485     multi_toggle_deleted [t]
    486   end
    487 
    488   ## see comment for multi_toggle_spam
    489   def multi_toggle_deleted threads
    490     undos = threads.map { |t| actually_toggle_deleted t }
    491     UndoManager.register "deleting/undeleting #{threads.size.pluralize 'thread'}",
    492                          undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } }
    493     regen_text
    494     threads.each { |t| Index.save_thread t }
    495   end
    496 
    497   ## returns an undo lambda
    498   def actually_toggle_killed t
    499     if t.has_label? :killed
    500       t.remove_label :killed
    501       add_or_unhide t.first
    502       UpdateManager.relay self, :labeled, t.first
    503       lambda do
    504         t.apply_label :killed
    505         hide_thread t
    506         UpdateManager.relay self, :labeled, t.first
    507       end
    508     else
    509       t.apply_label :killed
    510       hide_thread t
    511       UpdateManager.relay self, :labeled, t.first
    512       lambda do
    513         t.remove_label :killed
    514         add_or_unhide t.first
    515         UpdateManager.relay self, :labeled, t.first
    516       end
    517     end
    518   end
    519 
    520   def kill
    521     t = cursor_thread or return
    522     multi_kill [t]
    523   end
    524 
    525   def flush_index
    526     @flush_id = BufferManager.say "Flushing index..."
    527     Index.save_index
    528     BufferManager.clear @flush_id
    529   end
    530 
    531   ## m-m-m-m-MULTI-KILL
    532   def multi_kill threads
    533     undos = threads.map { |t| actually_toggle_killed t }
    534     UndoManager.register "killing/unkilling #{threads.size.pluralize 'threads'}", undos,
    535                          lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } }
    536     regen_text
    537     threads.each { |t| Index.save_thread t }
    538     killed, unkilled = threads.partition { |t| t.has_label? :killed }.map(&:size)
    539     BufferManager.flash "#{killed.pluralize 'thread'} killed, #{unkilled} unkilled"
    540   end
    541 
    542   def cleanup
    543     UpdateManager.unregister self
    544 
    545     if @load_thread
    546       @load_thread.kill
    547       BufferManager.clear @mbid if @mbid
    548       sleep 0.1 # TODO: necessary?
    549       BufferManager.erase_flash
    550     end
    551     dirty_threads = @mutex.synchronize { (@threads + @hidden_threads.keys).select { |t| t.dirty? } }
    552     fail "dirty threads remain" unless dirty_threads.empty?
    553     super
    554   end
    555 
    556   def toggle_tagged
    557     t = cursor_thread or return
    558     @mutex.synchronize { @tags.toggle_tag_for t }
    559     update_text_for_line curpos
    560     cursor_down
    561   end
    562 
    563   def toggle_tagged_all
    564     @mutex.synchronize { @threads.each { |t| @tags.toggle_tag_for t } }
    565     regen_text
    566   end
    567 
    568   def tag_matching
    569     query = BufferManager.ask :search, "tag threads matching (regex): "
    570     return if query.nil? || query.empty?
    571     query = begin
    572       /#{query}/i
    573     rescue RegexpError => e
    574       BufferManager.flash "error interpreting '#{query}': #{e.message}"
    575       return
    576     end
    577     @mutex.synchronize { @threads.each { |t| @tags.tag t if thread_matches?(t, query) } }
    578     regen_text
    579   end
    580 
    581   def apply_to_tagged; @tags.apply_to_tagged; end
    582 
    583   def edit_labels
    584     thread = cursor_thread or return
    585     speciall = (@hidden_labels + LabelManager::RESERVED_LABELS).uniq
    586 
    587     old_labels = thread.labels
    588     pos = curpos
    589 
    590     keepl, modifyl = thread.labels.partition { |t| speciall.member? t }
    591 
    592     user_labels = BufferManager.ask_for_labels :label, "Labels for thread: ", modifyl.sort_by {|x| x.to_s}, @hidden_labels
    593     return unless user_labels
    594 
    595     thread.labels = Set.new(keepl) + user_labels
    596     user_labels.each { |l| LabelManager << l }
    597     update_text_for_line curpos
    598 
    599     UndoManager.register "labeling thread" do
    600       thread.labels = old_labels
    601       update_text_for_line pos
    602       UpdateManager.relay self, :labeled, thread.first
    603       Index.save_thread thread
    604     end
    605 
    606     UpdateManager.relay self, :labeled, thread.first
    607     Index.save_thread thread
    608   end
    609 
    610   def multi_edit_labels threads
    611     user_labels = BufferManager.ask_for_labels :labels, "Add/remove labels (use -label to remove): ", [], @hidden_labels
    612     return unless user_labels
    613 
    614     user_labels.map! { |l| (l.to_s =~ /^-/)? [l.to_s.gsub(/^-?/, '').to_sym, true] : [l, false] }
    615     hl = user_labels.select { |(l,_)| @hidden_labels.member? l }
    616     unless hl.empty?
    617       BufferManager.flash "'#{hl}' is a reserved label!"
    618       return
    619     end
    620 
    621     old_labels = threads.map { |t| t.labels.dup }
    622 
    623     threads.each do |t|
    624       user_labels.each do |(l, to_remove)|
    625         if to_remove
    626           t.remove_label l
    627         else
    628           t.apply_label l
    629           LabelManager << l
    630         end
    631       end
    632       UpdateManager.relay self, :labeled, t.first
    633     end
    634 
    635     regen_text
    636 
    637     UndoManager.register "labeling #{threads.size.pluralize 'thread'}" do
    638       threads.zip(old_labels).map do |t, old_labels|
    639         t.labels = old_labels
    640         UpdateManager.relay self, :labeled, t.first
    641         Index.save_thread t
    642       end
    643       regen_text
    644     end
    645 
    646     threads.each { |t| Index.save_thread t }
    647   end
    648 
    649   def reply type_arg=nil
    650     t = cursor_thread or return
    651     m = t.latest_message
    652     return if m.nil? # probably won't happen
    653     m.load_from_source!
    654     mode = ReplyMode.new m, type_arg
    655     BufferManager.spawn "Reply to #{m.subj}", mode
    656   end
    657 
    658   def reply_all; reply :all; end
    659 
    660   def forward
    661     t = cursor_thread or return
    662     m = t.latest_message
    663     return if m.nil? # probably won't happen
    664     m.load_from_source!
    665     ForwardMode.spawn_nicely :message => m
    666   end
    667 
    668   def load_n_threads_background n=LOAD_MORE_THREAD_NUM, opts={}
    669     return if @load_thread # todo: wrap in mutex
    670     @load_thread = Redwood::reporting_thread("load threads for thread-index-mode") do
    671       num = load_n_threads n, opts
    672       opts[:when_done].call(num) if opts[:when_done]
    673       @load_thread = nil
    674     end
    675   end
    676 
    677   ## TODO: figure out @ts_mutex in this method
    678   def load_n_threads n=LOAD_MORE_THREAD_NUM, opts={}
    679     @interrupt_search = false
    680     @mbid = BufferManager.say "Searching for threads..."
    681 
    682     ts_to_load = n
    683     ts_to_load = ts_to_load + @ts.size unless n == -1 # -1 means all threads
    684 
    685     orig_size = @ts.size
    686     last_update = Time.now
    687     @ts.load_n_threads(ts_to_load, opts) do |i|
    688       if (Time.now - last_update) >= 0.25
    689         BufferManager.say "Loaded #{i.pluralize 'thread'}...", @mbid
    690         update
    691         BufferManager.draw_screen
    692         last_update = Time.now
    693       end
    694       ::Thread.pass
    695       break if @interrupt_search
    696     end
    697     @ts.threads.each { |th| th.labels.each { |l| LabelManager << l } }
    698 
    699     update
    700     BufferManager.clear @mbid if @mbid
    701     @mbid = nil
    702     BufferManager.draw_screen
    703     @ts.size - orig_size
    704   end
    705   ignore_concurrent_calls :load_n_threads
    706 
    707   def status
    708     if (l = lines) == 0
    709       "line 0 of 0"
    710     else
    711       "line #{curpos + 1} of #{l}"
    712     end
    713   end
    714 
    715   def cancel_search
    716     @interrupt_search = true
    717   end
    718 
    719   def load_all_threads
    720     load_threads :num => -1
    721   end
    722 
    723   def load_threads opts={}
    724     if opts[:num].nil?
    725       n = ThreadIndexMode::LOAD_MORE_THREAD_NUM
    726     else
    727       n = opts[:num]
    728     end
    729 
    730     myopts = @load_thread_opts.merge({ :when_done => (lambda do |num|
    731       opts[:when_done].call(num) if opts[:when_done]
    732 
    733       if num > 0
    734         BufferManager.flash "Found #{num.pluralize 'thread'}."
    735       else
    736         BufferManager.flash "No matches."
    737       end
    738     end)})
    739 
    740     if opts[:background] || opts[:background].nil?
    741       load_n_threads_background n, myopts
    742     else
    743       load_n_threads n, myopts
    744     end
    745   end
    746   ignore_concurrent_calls :load_threads
    747 
    748   def read_and_archive
    749     return unless cursor_thread
    750     thread = cursor_thread # to make sure lambda only knows about 'old' cursor_thread
    751 
    752     was_unread = thread.labels.member? :unread
    753     UndoManager.register "reading and archiving thread" do
    754       thread.apply_label :inbox
    755       thread.apply_label :unread if was_unread
    756       add_or_unhide thread.first
    757       Index.save_thread thread
    758     end
    759 
    760     cursor_thread.remove_label :unread
    761     cursor_thread.remove_label :inbox
    762     hide_thread cursor_thread
    763     regen_text
    764     Index.save_thread thread
    765   end
    766 
    767   def multi_read_and_archive threads
    768     old_labels = threads.map { |t| t.labels.dup }
    769 
    770     threads.each do |t|
    771       t.remove_label :unread
    772       t.remove_label :inbox
    773       hide_thread t
    774     end
    775     regen_text
    776 
    777     UndoManager.register "reading and archiving #{threads.size.pluralize 'thread'}" do
    778       threads.zip(old_labels).each do |t, l|
    779         t.labels = l
    780         add_or_unhide t.first
    781         Index.save_thread t
    782       end
    783       regen_text
    784     end
    785 
    786     threads.each { |t| Index.save_thread t }
    787   end
    788 
    789   def resize rows, cols
    790     regen_text
    791     super
    792   end
    793 
    794 protected
    795 
    796   def add_or_unhide m
    797     @ts_mutex.synchronize do
    798       if (is_relevant?(m) || @ts.is_relevant?(m)) && !@ts.contains?(m)
    799         @ts.load_thread_for_message m, @load_thread_opts
    800       end
    801 
    802       @hidden_threads.delete @ts.thread_for(m)
    803     end
    804 
    805     update
    806   end
    807 
    808   def thread_containing m; @ts_mutex.synchronize { @ts.thread_for m } end
    809 
    810   ## used to tag threads by query. this can be made a lot more sophisticated,
    811   ## but for right now we'll do the obvious this.
    812   def thread_matches? t, query
    813     t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
    814   end
    815 
    816   def size_widget_for_thread t
    817     HookManager.run("index-mode-size-widget", :thread => t) || default_size_widget_for(t)
    818   end
    819 
    820   def date_widget_for_thread t
    821     HookManager.run("index-mode-date-widget", :thread => t) || default_date_widget_for(t)
    822   end
    823 
    824   def cursor_thread; @mutex.synchronize { @threads[curpos] }; end
    825 
    826   def drop_all_threads
    827     @tags.drop_all_tags
    828     initialize_threads
    829     update
    830   end
    831 
    832   def delete_thread t
    833     @mutex.synchronize do
    834       i = @threads.index(t) or return
    835       @threads.delete_at i
    836       @size_widgets.delete_at i
    837       @date_widgets.delete_at i
    838       @tags.drop_tag_for t
    839     end
    840   end
    841 
    842   def hide_thread t
    843     @mutex.synchronize do
    844       i = @threads.index(t) or return
    845       raise "already hidden" if @hidden_threads[t]
    846       @hidden_threads[t] = true
    847       @threads.delete_at i
    848       @size_widgets.delete_at i
    849       @date_widgets.delete_at i
    850       @tags.drop_tag_for t
    851     end
    852   end
    853 
    854   def update_text_for_line l
    855     return unless l # not sure why this happens, but it does, occasionally
    856 
    857     need_update = false
    858 
    859     @mutex.synchronize do
    860       # and certainly not sure why this happens..
    861       #
    862       # probably a race condition between thread modification and updating
    863       # going on.
    864       return if @threads[l].empty?
    865 
    866       @size_widgets[l] = size_widget_for_thread @threads[l]
    867       @date_widgets[l] = date_widget_for_thread @threads[l]
    868 
    869       ## if a widget size has increased, we need to redraw everyone
    870       need_update =
    871         (@size_widgets[l].size > @size_widget_width) or
    872         (@date_widgets[l].size > @date_widget_width)
    873     end
    874 
    875     if need_update
    876       update
    877     else
    878       @text[l] = text_for_thread_at l
    879       buffer.mark_dirty if buffer
    880     end
    881   end
    882 
    883   def regen_text
    884     threads = @mutex.synchronize { @threads }
    885     @text = threads.map_with_index { |t, i| text_for_thread_at i }
    886     @lines = threads.map_with_index { |t, i| [t, i] }.to_h
    887     buffer.mark_dirty if buffer
    888   end
    889 
    890   def authors; map { |m, *o| m.from if m }.compact.uniq; end
    891 
    892   ## preserve author order from the thread
    893   def author_names_and_newness_for_thread t, limit=nil
    894     new = {}
    895     seen = {}
    896     authors = t.map do |m, *o|
    897       next unless m && m.from
    898       new[m.from] ||= m.has_label?(:unread)
    899       next if seen[m.from]
    900       seen[m.from] = true
    901       m.from
    902     end.compact
    903 
    904     result = []
    905     authors.each do |a|
    906       break if limit && result.size >= limit
    907       name = if AccountManager.is_account?(a)
    908         "me"
    909       elsif t.authors.size == 1
    910         a.mediumname
    911       else
    912         a.shortname
    913       end
    914 
    915       result << [name, new[a]]
    916     end
    917 
    918     if result.size == 1 && (author_and_newness = result.assoc("me"))
    919       unless (recipients = t.participants - t.authors).empty?
    920         result = recipients.collect do |r|
    921           break if limit && result.size >= limit
    922           name = (recipients.size == 1) ? r.mediumname : r.shortname
    923           ["(#{name})", author_and_newness[1]]
    924         end
    925       end
    926     end
    927 
    928     result
    929   end
    930 
    931   AUTHOR_LIMIT = 5
    932   def text_for_thread_at line
    933     t, size_widget, date_widget = @mutex.synchronize do
    934       [@threads[line], @size_widgets[line], @date_widgets[line]]
    935     end
    936 
    937     starred = t.has_label? :starred
    938 
    939     ## format the from column
    940     cur_width = 0
    941     ann = author_names_and_newness_for_thread t, AUTHOR_LIMIT
    942     from = []
    943     ann.each_with_index do |(name, newness), i|
    944       break if cur_width >= from_width
    945       last = i == ann.length - 1
    946 
    947       abbrev =
    948         if cur_width + name.display_length > from_width
    949           name.slice_by_display_length(from_width - cur_width - 1) + "."
    950         elsif cur_width + name.display_length == from_width
    951           name.slice_by_display_length(from_width - cur_width)
    952         else
    953           if last
    954             name.slice_by_display_length(from_width - cur_width)
    955           else
    956             name.slice_by_display_length(from_width - cur_width - 1) + ","
    957           end
    958         end
    959 
    960       cur_width += abbrev.display_length
    961 
    962       if last && from_width > cur_width
    963         abbrev += " " * (from_width - cur_width)
    964       end
    965 
    966       from << [(newness ? :index_new_color : (starred ? :index_starred_color : :index_old_color)), abbrev]
    967     end
    968 
    969     is_me = AccountManager.method(:is_account?)
    970     directly_participated = t.direct_participants.any?(&is_me)
    971     participated = directly_participated || t.participants.any?(&is_me)
    972 
    973     subj_color =
    974       if t.has_label?(:draft)
    975         :index_draft_color
    976       elsif t.has_label?(:unread)
    977         :index_new_color
    978       elsif starred
    979         :index_starred_color
    980       elsif Colormap.sym_is_defined(:index_subject_color)
    981         :index_subject_color
    982       else
    983         :index_old_color
    984       end
    985 
    986     size_padding = @size_widget_width - size_widget.display_length
    987     size_widget_text = sprintf "%#{size_padding}s%s", "", size_widget
    988 
    989     date_padding = @date_widget_width - date_widget.display_length
    990     date_widget_text = sprintf "%#{date_padding}s%s", "", date_widget
    991 
    992     [
    993       [:tagged_color, @tags.tagged?(t) ? ">" : " "],
    994       [:date_color, date_widget_text],
    995       [:starred_color, (starred ? "*" : " ")],
    996     ] +
    997       from +
    998       [
    999       [:size_widget_color, size_widget_text],
   1000       [:with_attachment_color , t.labels.member?(:attachment) ? "@" : " "],
   1001       [:to_me_color, directly_participated ? ">" : (participated ? '+' : " ")],
   1002     ] +
   1003       (t.labels - @hidden_labels).sort_by {|x| x.to_s}.map {
   1004             |label| [Colormap.sym_is_defined("label_#{label}_color".to_sym) || :label_color, "#{label} "]
   1005       } +
   1006       [
   1007       [subj_color, t.subj + (t.subj.empty? ? "" : " ")],
   1008       [:snippet_color, t.snippet],
   1009     ]
   1010   end
   1011 
   1012   def dirty?; @mutex.synchronize { (@hidden_threads.keys + @threads).any? { |t| t.dirty? } } end
   1013 
   1014 private
   1015 
   1016   def default_size_widget_for t
   1017     case t.size
   1018     when 1
   1019       ""
   1020     else
   1021       "(#{t.size})"
   1022     end
   1023   end
   1024 
   1025   def default_date_widget_for t
   1026     t.date.getlocal.to_nice_s
   1027   end
   1028 
   1029   def from_width
   1030     if buffer
   1031       [(buffer.content_width.to_f * 0.2).to_i, MIN_FROM_WIDTH].max
   1032     else
   1033       MIN_FROM_WIDTH # not sure why the buffer is gone
   1034     end
   1035   end
   1036 
   1037   def initialize_threads
   1038     @ts = ThreadSet.new Index.instance, $config[:thread_by_subject]
   1039     @ts_mutex = Mutex.new
   1040     @hidden_threads = {}
   1041   end
   1042 end
   1043 
   1044 end