]> git.cworth.org Git - sup/blob - lib/sup/modes/label-list-mode.rb
9203773b1c9756fc9094f8d88c0d66e7bd49e76e
[sup] / lib / sup / modes / label-list-mode.rb
1 module Redwood
2
3 class LabelListMode < LineCursorMode
4   register_keymap do |k|
5     k.add :select_label, "Search by label", :enter
6     k.add :reload, "Discard label list and reload", '@'
7     k.add :toggle_show_unread_only, "Toggle between all labels and those with unread mail", :tab
8   end
9
10   attr_reader :value
11
12   def initialize
13     @labels = []
14     @text = []
15     @value = nil
16     @unread_only = false
17     super
18     regen_text
19   end
20
21   def lines; @text.length end
22   def [] i; @text[i] end
23
24   def status
25     if true
26       "No labels with unread messages"
27     else
28       super
29     end
30   end
31
32 protected
33   def toggle_show_unread_only
34     @unread_only = !@unread_only
35     reload
36   end
37
38   def reload
39     regen_text
40     buffer.mark_dirty if buffer
41   end
42
43   def regen_text
44     @text = []
45     labels = LabelManager.listable_labels
46
47     counts = labels.map do |label|
48       string = LabelManager.string_for label
49       total = Index.num_results_for :label => label
50       unread = Index.num_results_for :labels => [label, :unread]
51       [label, string, total, unread]
52     end.sort_by { |l, s, t, u| s.downcase }
53
54     width = counts.max_of { |l, s, t, u| s.length }
55
56     if @unread_only
57       counts.delete_if { | l, s, t, u | u == 0 }
58     end
59
60     @labels = []
61     counts.map do |label, string, total, unread|
62       if total == 0 && !LabelManager::RESERVED_LABELS.include?(label)
63         Redwood::log "no hits for label #{label}, deleting"
64         LabelManager.delete label
65         next
66       end
67
68       @text << [[(unread == 0 ? :labellist_old_color : :labellist_new_color),
69           sprintf("%#{width + 1}s %5d %s, %5d unread", string, total, total == 1 ? " message" : "messages", unread)]]
70       @labels << label
71       yield i if block_given?
72     end.compact
73   end
74
75   def select_label
76     @value, string = @labels[curpos]
77     return unless @value
78     LabelSearchResultsMode.spawn_nicely @value
79   end
80 end
81
82 end