~jconti/recent-notifications/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python
"""
Main.py
March 26, 2011

The main recent-notifications-unity application.
"""

import logging
import os

from gi.repository import GObject, Gtk

try:
  from gi.repository import Unity
except:
  Unity = None

import Timestamp

from About import show_about
from Config import Config
from MessageList import MessageList
from Notification import Notification
from Theme import Theme
from Translations import _

# Setup the application logging to file and stdout for errors
def setup_logging():
  log_format = "%(asctime)s %(name)s %(levelname)s: %(message)s"

  logging.basicConfig(level=logging.DEBUG, 
      filename=os.path.expanduser("~/.cache/recent-notifications.log"),
      format=log_format,
      filemode="w")

  console = logging.StreamHandler()
  console.setLevel(logging.ERROR)
  console.setFormatter(logging.Formatter(log_format))

  logging.getLogger("").addHandler(console)

setup_logging()
logger = logging.getLogger("Main")

SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))

PREFERENCES_PATH = "~/.config/recent-notifications/preferences"

class Column(object):
  """Maps column names to column numbers."""
  APP_NAME  = 0
  SEPARATOR = 1
  COUNT     = 2

class MainWindow(Gtk.Window):
  def __init__(self):
    GObject.GObject.__init__(self)

    self._default_size = 400

    self.set_title(_("Recent Notifications"))
    self.set_default_size(self._default_size, self._default_size)
    self.connect("destroy", self.on_destroy)
    self.connect("focus-in-event", self.on_focus_in)
    self.connect("focus-out-event", self.on_focus_out)
    self.connect("size-allocate", self.on_size_allocate)

    self._message_count = 0

    self._uimanager = Gtk.UIManager()
    self.add_accel_group(self._uimanager.get_accel_group())

    self._actiongroup = Gtk.ActionGroup("MenuBar")
    self._actiongroup.add_actions([
      ("Messages", None, _("_Messages"), None, None, None),
      ("Clear", Gtk.STOCK_CLEAR, None, None, None, self.on_clear),
      ("Quit", Gtk.STOCK_QUIT, None, None, None, self.on_destroy),
      ("Help", None, _("_Help"), None, None, None),
      ("About", Gtk.STOCK_ABOUT, None, None, None, self.on_show_about)
    ])
    self._uimanager.insert_action_group(self._actiongroup)

    self._uimanager.add_ui_from_string("""
      <ui>
        <menubar name="MenuBar">
          <menu action="Messages">
            <menuitem action="Clear"/>
            <menuitem action="Quit"/>
          </menu>
          <menu action="Help">
            <menuitem action="About"/>
          </menu>
        </menubar>
      </ui>
    """)

    self._vbox = Gtk.VBox()
    self.add(self._vbox)

    self._menubar = self._uimanager.get_widget("/MenuBar")
    self._vbox.pack_start(self._menubar, False, False, 0)

    self._message_list = MessageList()
    self._vbox.pack_start(self._message_list, True, True, 2)

    # app_name, is_separator, count
    self._combolist = Gtk.ListStore(str, bool, int)
    self._combobox = Gtk.ComboBox()
    self._combobox.set_model(self._combolist)
    self._combo_app_cell = Gtk.CellRendererText()
    self._combobox.pack_start(self._combo_app_cell, True)
    self._combobox.add_attribute(self._combo_app_cell, "text", Column.APP_NAME)
    self._combo_count_cell = Gtk.CellRendererText()
    self._combobox.pack_start(self._combo_count_cell, False)
    self._combobox.add_attribute(self._combo_count_cell, "text", Column.COUNT)
    self._combobox.set_row_separator_func(lambda m, i, *args: m.get_value(i, Column.SEPARATOR), None)
    self._combobox.connect("changed", self.on_combobox_changed)
    self._vbox.pack_start(self._combobox, False, False, 0)

    self.initialize_combobox()

    if Unity:
      self._launcher = Unity.LauncherEntry.get_for_desktop_id("recent-notifications.desktop")
    else:
      self._launcher = None

    self._notify = Notification()
    self._notify.connect("message-received", self.on_message_received)

    self._preferences = Config(PREFERENCES_PATH)
    self._preferences.set_if_unset("theme", "default")

    # load the theme
    theme_name = self._preferences.get("theme", "default")
    theme = Theme(theme_name)
    theme.apply_gtk_styles()
    self._message_list.set_theme(theme)

  def zero_count(self):
    """Zero the message count"""
    self._message_count = 0
    self.update_count()

  def increment_count(self):
    """Increments the message count"""
    self._message_count += 1
    self.update_count()

  def update_count(self):
    """Updates the message count display"""
    if self._launcher:
      self._launcher.set_property("count", self._message_count)
      if self._message_count > 0:
        self._launcher.set_property("count_visible", True)
      else:
        self._launcher.set_property("count_visible", False)

  def increment_count_column(self, iter):
    """Increments the count column of the given iter"""
    count = self._combolist.get_value(iter, Column.COUNT)
    self._combolist.set_value(iter, Column.COUNT, count + 1)

  def increment_combobox(self, app_name):
    """Updates the combobox app names and message counts."""
    # Add a separator if there isn't one yet
    if len(self._combolist) == 1:
      self._combolist.append(["Separator", True, 0])

    iter = self._combolist.get_iter_first()
    self.increment_count_column(iter)

    updated_count = False
    iter = self._combolist.iter_next(iter)
    while iter != None:
      name = self._combolist.get_value(iter, Column.APP_NAME)
      if name == app_name:
        self.increment_count_column(iter)
        updated_count = True
        break
      iter = self._combolist.iter_next(iter)
    if not updated_count:
      iter = self._combolist.append([app_name, False, 1])

  def initialize_combobox(self):
    """Clear the combobox and set the initial entry."""
    self._combolist.clear()
    self._combolist.append([_("All Applications"), False, 0])
    self._comboapps = {}
    self._combobox.set_active(0)

  def on_clear(self, *args):
    """Clear the messages"""
    self._message_list.clear_messages()

  def on_combobox_changed(self, combobox, *args):
    """Filter based on app_name"""
    active = self._combobox.get_active()
    if active == 0:
      self._message_list.filter_by(None)
    else:
      iter = self._combobox.get_active_iter()
      app_name = self._combolist.get_value(iter, Column.APP_NAME)
      self._message_list.filter_by(app_name)

  def on_destroy(self, *args):
    """Quit the application"""
    Gtk.main_quit()

  def on_focus_in(self, widget, event):
    """Window receives focus"""
    pass

  def on_focus_out(self, widget, event):
    """Window receives focus"""
    self.zero_count()
    self._message_list.mark_as_read()

  def on_message_received(self, monitor, message):
    """Received a notification"""
    self.increment_count()
    self.increment_combobox(message.app_name)
    self._message_list.add_message(message)

  def on_size_allocate(self, widget, size):
    """Resize event"""
    self._message_list.set_width(size.width)

  def on_show_about(self, *args):
    """Show the about dialog"""
    show_about()

def main():
  icon_path = os.path.join(SCRIPT_PATH, "..", "icons")
  theme = Gtk.IconTheme.get_default()
  theme.append_search_path(icon_path)

  window = MainWindow()
  window.show_all()
  Gtk.main()

if __name__ == "__main__":
  main()