File: notifier_universal.py

package info (click to toggle)
taskcoach 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,496 kB
  • ctags: 17,810
  • sloc: python: 72,170; makefile: 254; ansic: 120; xml: 29; sh: 16
file content (466 lines) | stat: -rw-r--r-- 14,464 bytes parent folder | download
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2014 Task Coach developers <developers@taskcoach.org>

Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import wx
from notifier import AbstractNotifier
from taskcoachlib import operating_system


#==============================================================================
# Utils

class AnimatedShow(wx.Timer):
    """
    Utility class to show a frame with an animation
    """

    def __init__(self, frame, show=True):
        super(AnimatedShow, self).__init__()

        if frame.CanSetTransparent():
            self.__frame = frame
            self.__step = 0
            self.__show = show

            id_ = wx.NewId()
            self.SetOwner(self, id_)
            wx.EVT_TIMER(self, id_, self.__OnTick)
            self.Start(100)
            wx.EVT_CLOSE(frame, self.__OnClose)

            frame.SetTransparent(0)

            if show:
                frame.Show()
        else:
            frame.Show(show)

    def __OnTick(self, event): # pylint: disable=W0613
        self.__step += 1

        if self.__show:
            alpha = int(255.0 * self.__step / 10)
        else:
            alpha = int(255.0 * (10 - (self.__step - 1)) / 10)

        self.__frame.SetTransparent(alpha)

        if self.__step == 10:
            self.Stop()

            if not self.__show:
                self.__frame.Close()

    def __OnClose(self, event):
        self.Stop()
        event.Skip()


class AnimatedMove(wx.Timer):
    """
    Utility class to move a frame with an animation
    """

    def __init__(self, frame, destination):
        super(AnimatedMove, self).__init__()

        self.__frame = frame
        self.__origin = frame.GetPositionTuple()
        self.__destination = destination
        self.__step = 0

        id_ = wx.NewId()
        self.SetOwner(self, id_)
        wx.EVT_TIMER(self, id_, self.__OnTick)
        self.Start(100)
        wx.EVT_CLOSE(frame, self.__OnClose)

    def __OnTick(self, event): # pylint: disable=W0613
        x0, y0 = self.__origin
        x1, y1 = self.__destination
        self.__step += 1

        curX = int(x0 + (x1 - x0) * 1.0 * self.__step / 10)
        curY = int(y0 + (y1 - y0) * 1.0 * self.__step / 10)

        self.__frame.SetPosition(wx.Point(curX, curY))

        if self.__step == 10:
            self.Stop()

    def __OnClose(self, event):
        self.Stop()
        event.Skip()


#==============================================================================
# Notifications

if operating_system.isWindows():
    class _NotifyBase(wx.MiniFrame):
        pass
elif operating_system.isGTK():
    class _NotifyBase(wx.PopupWindow):
        def __init__(self, parent, id_, title, style=0): # pylint: disable=W0613,E1003
            super(_NotifyBase, self).__init__(parent, id_) # No style

        def Close(self): # pylint: disable=W0221,E1003
            # Strange...
            super(_NotifyBase, self).Close()
            self.Destroy()
else:
    class _NotifyBase(wx.Frame):
        """FIXME: steals focus..."""


class NotificationFrameBase(_NotifyBase):
    """
    Base class for a notification frame.

    @ivar title: The notification title
    @type title: unicode
    @ivar icon: An optional icon
    @type icon: NoneType or wx.Bitmap
    """

    def __init__(self, title, icon=None, parent=None):
        self.title = title
        self.icon = icon
        style = self.Style() | (wx.STAY_ON_TOP if parent is None else wx.FRAME_FLOAT_ON_PARENT)
        super(NotificationFrameBase, self).__init__(parent, wx.ID_ANY, u'', style=style)
        self.Populate()

    def Populate(self):
        panel = wx.Panel(self, wx.ID_ANY)

        vsz = wx.BoxSizer(wx.VERTICAL)
        hsz = wx.BoxSizer(wx.HORIZONTAL)

        if self.icon is not None:
            hsz.Add(wx.StaticBitmap(panel, wx.ID_ANY, self.icon), 0,
                    wx.ALL|wx.ALIGN_CENTRE, 2)

        # Seems that font copy-on-write does not work sometimes...
        font = wx.FontFromNativeInfoString(wx.NORMAL_FONT.GetNativeFontInfoDesc())
        font.SetPointSize(8)
        font.SetWeight(wx.FONTWEIGHT_BOLD)

        titleCtrl = wx.StaticText(panel, wx.ID_ANY, self.title)
        titleCtrl.SetFont(font)
        hsz.Add(titleCtrl, 1, wx.ALL|wx.ALIGN_CENTRE, 2)

        btn = self.CloseButton(panel)
        if btn is not None:
            hsz.Add(btn, 0, wx.ALL, 2)
            wx.EVT_BUTTON(btn, wx.ID_ANY, self.DoClose)

        vsz.Add(hsz, 0, wx.ALL|wx.EXPAND, 2)

        self.AddInnerContent(vsz, panel)

        panel.SetSizer(vsz)

        sz = wx.BoxSizer()
        sz.Add(panel, 1, wx.EXPAND)
        self.SetSizer(sz)
        self.Fit()

    def Unpopulate(self):
        self.DestroyChildren()
        self.SetSizer(None)

    def CloseButton(self, panel):
        """
        Override this to return a button instance if you want to
        customize the close button. You may also return None but if
        you do so, please provide another way for the user to dismiss
        the notification.
        """

        return wx.BitmapButton(panel, wx.ID_ANY,
                               wx.ArtProvider.GetBitmap('cross_red_icon',
                                                        wx.ART_FRAME_ICON,
                                                        (16, 16)))

    def AddInnerContent(self, sizer, panel):
        """
        Use this to customize the content of the frame.

        @param sizer: A vertical sizer to which you should add
            your UI elements.
        @param panel: Your parent panel.
        """

    def Style(self):
        """Return the frame's style"""

        style = wx.FRAME_NO_TASKBAR|wx.TAB_TRAVERSAL

        if operating_system.isMac():
            # style |= wx.NO_BORDER|wx.POPUP_WINDOW

            # XXXFIXME: without the POPUP_WINDOW style, the frame
            # steals the focus. But with it, when the frame is created
            # while the user is on another Space that the main
            # window's, it cannot receive user events any more, so
            # cannot be dismissed...

            style |= wx.NO_BORDER

        return style

    def DoClose(self, event=None): # pylint: disable=W0613
        """Use this method instead of Close. Never use Close directly."""

        NotificationCenter().HideFrame(self) # pylint: disable=E1101


class NotificationFrame(NotificationFrameBase):
    """
    A simple (and ugly) notification frame that displays a message.

    @ivar message: Message to display
    @type message: unicode
    """

    def __init__(self, message, *args, **kwargs):
        self.message = message

        super(NotificationFrame, self).__init__(*args, **kwargs)

    def AddInnerContent(self, sizer, panel):
        sizer.Add(wx.StaticText(panel, wx.ID_ANY, self.message), 1, wx.ALL|wx.EXPAND, 5)


class _NotificationCenter(wx.EvtHandler):
    """
    The class that handles notification frames.
    """

    framePool = []

    def __init__(self):
        super(_NotificationCenter, self).__init__()

        self.displayedFrames = []
        self.waitingFrames = []
        self.notificationWidth = 300
        self.notificationMargin = 5

        self.__tmr = wx.Timer()
        id_ = wx.NewId()
        self.__tmr.SetOwner(self, id_)
        wx.EVT_TIMER(self, id_, self.__OnTick)
        self.__tmr.Start(1000)

    def NotifyFrame(self, frm, timeout=None):
        """
        Present a new notification frame.

        @param frm: The frame to show
        @param timeout: Time to display the frame before automatically
            hiding it; in seconds.
        """

        if frm.GetParent():
            dx, dy = frm.GetParent().GetPosition()
            dw, dh = frm.GetParent().GetSizeTuple()
        else:
            dx, dy, dw, dh = self.GetDisplayRect()

        w, h = frm.GetSizeTuple()
        w = w if w > self.notificationWidth else self.notificationWidth

        bottom = dy + dh - self.notificationMargin

        for otherFrame, height, tmo in self.displayedFrames:
            bottom -= height + self.notificationMargin
            if bottom - h < 0:
                self.waitingFrames.append((frm, timeout))
                return

        if frm.GetParent():
            x = min(self.GetDisplayRect()[2] - self.notificationMargin - w,
                    dx + dw + self.notificationMargin)
        else:
            x = dx + dw - w - self.notificationMargin

        frm.SetDimensions(x,
                          bottom - h - self.notificationMargin,
                          w, h)
        self.displayedFrames.append((frm, h, timeout))

        frm.Layout()

        AnimatedShow(frm)

    def CheckWaiting(self):
        waiting = self.waitingFrames
        self.waitingFrames = []
        for frm, tmo in waiting:
            self.NotifyFrame(frm, timeout=tmo)

    def Notify(self, title, msg, icon=None, timeout=None):
        """
        Present a new simple notification frame.

        @param title: Notification title
        @param msg: Notification message
        @param timeout: See L{NotifyFrame}.
        """

        frm = NotificationFrame(msg, title, icon=icon)
        self.NotifyFrame(frm, timeout=timeout)

    def HideFrame(self, frm):
        """
        Hide a notification frame.
        """

        for idx, (frame, height, tmo) in enumerate(self.displayedFrames):
            if frame == frm:
                self.displayedFrames[idx] = (frame, height, 1)
                break

        self.CheckWaiting()

    def HideAll(self):
        """
        Hide all notification frames. Call this when you want to close
        your main frame, or else the wx loop won't exit.
        """

        for idx, (frame, height, tmo) in enumerate(self.displayedFrames):
            self.displayedFrames[idx] = (frame, height, 1)
        for frame, timeout in self.waitingFrames:
            frame.Close()
        self.waitingFrames = []

    def GetDisplayRect(self):
        """
        Returns the geometry of the main application frame's display
        """

        dpyIndex = wx.Display.GetFromWindow(wx.GetApp().GetTopWindow())
        if dpyIndex == wx.NOT_FOUND:
            return wx.ClientDisplayRect()
        return wx.Display(dpyIndex).GetClientArea()

    def __OnTick(self, event): # pylint: disable=W0613
        s = 0
        newList = []

        for frame, height, tmo in self.displayedFrames:
            if frame.GetParent():
                dx, dy = frame.GetParent().GetPosition()
                dw, dh = frame.GetParent().GetSizeTuple()
            else:
                dx, dy, dw, dh = self.GetDisplayRect()

            bottom = dy + dh - self.notificationMargin

            if s == 0:
                if tmo == 1:
                    frame.Close()
                    s = 1
                    continue

                newList.append((frame, height, tmo - 1 if tmo is not None else None))
                bottom -= height + self.notificationMargin
            else:
                if tmo == 1:
                    frame.Close()
                else:
                    newList.append((frame, height, tmo - 1 if tmo is not None else None))
                    x, y = frame.GetPositionTuple()
                    AnimatedMove(frame, (x, bottom - height - self.notificationMargin))
                    bottom -= height + self.notificationMargin

        self.displayedFrames = newList
        self.CheckWaiting()


class NotificationCenter(object):
    _instance = None

    def __new__(self):
        if NotificationCenter._instance is None:
            NotificationCenter._instance = _NotificationCenter()
        return NotificationCenter._instance


class UniversalNotifier(AbstractNotifier):
    def getName(self):
        return 'Task Coach'

    def isAvailable(self):
        return True

    def notify(self, title, summary, bitmap, **kwargs):
        NotificationCenter().Notify(title, summary, icon=bitmap) # pylint: disable=E1101


AbstractNotifier.register(UniversalNotifier())


if __name__ == '__main__':
    class TestNotificationFrame(NotificationFrameBase):
        def AddInnerContent(self, sizer, panel):
            choice = wx.Choice(panel, wx.ID_ANY)
            choice.Append('One')
            choice.Append('Two')
            choice.Append('Three')
            sizer.Add(choice, 0, wx.ALL|wx.EXPAND, 5)

            hsz = wx.BoxSizer(wx.HORIZONTAL)
            hsz.Add(wx.Button(panel, wx.ID_ANY, u'OK'), 1, wx.ALL, 2)
            hsz.Add(wx.Button(panel, wx.ID_ANY, u'Cancel'), 1, wx.ALL, 2)
            sizer.Add(hsz, 0, wx.EXPAND|wx.ALL, 5)

        def CloseButton(self, panel):
            return None


    class TestFrame(wx.Frame):
        def __init__(self):
            super(TestFrame, self).__init__(None, wx.ID_ANY, 'Test frame')
            # pylint: disable=E1101
            NotificationCenter().Notify('Sample title', 'Sample content', timeout=3)
            NotificationCenter().Notify('Other sample', 'Multi-line sample content\nfor example\nDont try this at home', timeout=3,
                                        icon=wx.ArtProvider.GetBitmap('taskcoach', wx.ART_FRAME_ICON, (16, 16)))
            NotificationCenter().Notify('Before last sample', 'Spam!')
            NotificationCenter().NotifyFrame(TestNotificationFrame('Test custom',
                                                                   icon=wx.ArtProvider.GetBitmap('taskcoach', wx.ART_FRAME_ICON, (16, 16))))
            NotificationCenter().Notify('Last sample', 'Foobar!')

            wx.EVT_CLOSE(self, self.OnClose)

        def OnClose(self, evt):
            NotificationCenter().HideAll() # pylint: disable=E1101
            evt.Skip()


    class App(wx.App):
        def OnInit(self):
            from taskcoachlib.gui import artprovider
            artprovider.init()
            TestFrame().Show()
            return True


    App(0).MainLoop()