File: systrayicon.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (437 lines) | stat: -rw-r--r-- 14,104 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
# -*- coding: utf-8 -*-
"""
Drop-In replacement for wx.TaskBarIcon

This one won't stop showing updates to the icon like wx.TaskBarIcon

"""

import ctypes
import os
import sys

import win32api
import win32con
import win32gui
import winerror

from DisplayCAL.options import debug, verbose
from DisplayCAL.wxaddons import wx, IdFactory


class Menu(wx.EvtHandler):
    def __init__(self):
        wx.EvtHandler.__init__(self)
        self.hmenu = win32gui.CreatePopupMenu()
        self.MenuItems = []
        self.Parent = None
        self._menuitems = {}
        # With wxPython 4, calling <EvtHandler>.Destroy() no longer makes the
        # instance evaluate to False in boolean comparisons, so we emulate that
        # functionality
        self._destroyed = False

    def Append(self, id, text, help="", kind=wx.ITEM_NORMAL):
        return self.AppendItem(MenuItem(self, id, text, help, kind))

    def AppendCheckItem(self, id, text, help=""):
        return self.Append(id, text, help, wx.ITEM_CHECK)

    def AppendItem(self, item):
        if item.Kind == wx.ITEM_SEPARATOR:
            flags = win32con.MF_SEPARATOR
        else:
            if item.subMenu:
                flags = win32con.MF_POPUP | win32con.MF_STRING
            else:
                flags = 0
            if not item.Enabled:
                flags |= win32con.MF_DISABLED
        # Use ctypes instead of win32gui.AppendMenu for unicode support
        ctypes.windll.User32.AppendMenuW(
            self.hmenu, flags, item.Id, str(item.ItemLabel)
        )
        self.MenuItems.append(item)
        self._menuitems[item.Id] = item
        if item.Checked:
            self.Check(item.Id)
        return item

    def AppendSubMenu(self, submenu, text, help=""):
        item = MenuItem(self, submenu.hmenu, text, help, wx.ITEM_NORMAL, submenu)
        return self.AppendItem(item)

    def AppendRadioItem(self, id, text, help=""):
        return self.Append(id, text, help, wx.ITEM_RADIO)

    def AppendSeparator(self):
        return self.Append(-1, "", kind=wx.ITEM_SEPARATOR)

    def Check(self, id, check=True):
        flags = win32con.MF_BYCOMMAND
        item_check = self._menuitems[id]
        if item_check.Kind == wx.ITEM_RADIO:
            if not check:
                return
            item_first = item_check
            item_last = item_check
            index = self.MenuItems.index(item_check)
            menuitems = self.MenuItems[:index]
            while menuitems:
                item = menuitems.pop()
                if item.Kind == wx.ITEM_RADIO:
                    item_first = item
                    item.Checked = False
                else:
                    break
            menuitems = self.MenuItems[index:]
            menuitems.reverse()
            while menuitems:
                item = menuitems.pop()
                if item.Kind == wx.ITEM_RADIO:
                    item_last = item
                    item.Checked = False
                else:
                    break
            win32gui.CheckMenuRadioItem(
                self.hmenu, item_first.Id, item_last.Id, item_check.Id, flags
            )
        else:
            if check:
                flags |= win32con.MF_CHECKED
            win32gui.CheckMenuItem(self.hmenu, item_check.Id, flags)
        item_check.Checked = check

    def Destroy(self):
        for menuitem in self.MenuItems:
            menuitem.Destroy()
        if not self.Parent:
            if debug or verbose > 1:
                print("DestroyMenu HMENU", self.hmenu)
            win32gui.DestroyMenu(self.hmenu)
        if debug or verbose > 1:
            print("Destroy", self.__class__.__name__, self)
        self._destroyed = True
        wx.EvtHandler.Destroy(self)

    def __bool__(self):
        return not self._destroyed

    def Enable(self, id, enable=True):
        flags = win32con.MF_BYCOMMAND
        if not enable:
            flags |= win32con.MF_DISABLED
        item = self._menuitems[id]
        win32gui.EnableMenuItem(self.hmenu, item.Id, flags)
        item.Enabled = enable


class MenuItem:
    def __init__(
        self, menu, id=-1, text="", help="", kind=wx.ITEM_NORMAL, subMenu=None
    ):
        if id == -1:
            id = IdFactory.NewId()
        self.Menu = menu
        self.Id = id
        self.ItemLabel = text
        self.Help = help
        self.Kind = kind
        self.Enabled = True
        self.Checked = False
        self.subMenu = subMenu
        if subMenu:
            self.subMenu.Parent = menu

    def Check(self, check=True):
        self.Checked = check
        if self.Id in self.Menu._menuitems:
            self.Menu.Check(self.Id, check)

    def Destroy(self):
        if self.subMenu:
            self.subMenu.Destroy()
        if debug or verbose > 1:
            print(
                "Destroy",
                self.__class__.__name__,
                self.Id,
                _get_kind_str(self.Kind),
                self.ItemLabel,
            )
        if self.Id in IdFactory.ReservedIds:
            IdFactory.UnreserveId(self.Id)

    def Enable(self, enable=True):
        self.Enabled = enable
        if self.Id in self.Menu._menuitems:
            self.Menu.Enable(self.Id, enable)

    def GetId(self):
        return self.Id


class SysTrayIcon(wx.EvtHandler):
    def __init__(self):
        wx.EvtHandler.__init__(self)
        msg_TaskbarCreated = win32gui.RegisterWindowMessage("TaskbarCreated")
        message_map = {
            msg_TaskbarCreated: self.OnTaskbarCreated,
            win32con.WM_DESTROY: self.OnDestroy,
            win32con.WM_COMMAND: self.OnCommand,
            win32con.WM_USER + 20: self.OnTaskbarNotify,
        }

        wc = win32gui.WNDCLASS()
        hinst = wc.hInstance = win32api.GetModuleHandle(None)
        wc.lpszClassName = "SysTrayIcon"
        wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
        wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW)
        wc.hbrBackground = win32con.COLOR_WINDOW
        wc.lpfnWndProc = message_map

        classAtom = win32gui.RegisterClass(wc)

        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = win32gui.CreateWindow(
            wc.lpszClassName,
            "SysTrayIcon",
            style,
            0,
            0,
            win32con.CW_USEDEFAULT,
            win32con.CW_USEDEFAULT,
            0,
            0,
            hinst,
            None,
        )
        win32gui.UpdateWindow(self.hwnd)
        self._nid = None
        self.in_popup = False
        self.menu = None
        self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnRightUp)
        # With wxPython 4, calling <EvtHandler>.Destroy() no longer makes the
        # instance evaluate to False in boolean comparisons, so we emulate that
        # functionality
        self._destroyed = False

    def CreatePopupMenu(self):
        """Override this method in derived classes"""
        if self.menu:
            return self.menu
        menu = Menu()
        item = menu.AppendRadioItem(-1, "Radio 1")
        item.Check()
        menu.Bind(
            wx.EVT_MENU,
            lambda event: menu.Check(event.Id, event.IsChecked()),
            id=item.Id,
        )
        item = menu.AppendRadioItem(-1, "Radio 2")
        menu.Bind(
            wx.EVT_MENU,
            lambda event: menu.Check(event.Id, event.IsChecked()),
            id=item.Id,
        )
        menu.AppendSeparator()
        item = menu.AppendCheckItem(-1, "Checkable")
        item.Check()
        menu.Bind(
            wx.EVT_MENU,
            lambda event: menu.Check(event.Id, event.IsChecked()),
            id=item.Id,
        )
        menu.AppendSeparator()
        item = menu.AppendCheckItem(-1, "Disabled")
        item.Enable(False)
        menu.AppendSeparator()
        submenu = Menu()
        item = submenu.AppendCheckItem(-1, "Sub menu item")
        submenu.Bind(
            wx.EVT_MENU,
            lambda event: submenu.Check(event.Id, event.IsChecked()),
            id=item.Id,
        )
        subsubmenu = Menu()
        item = subsubmenu.AppendCheckItem(-1, "Sub sub menu item")
        subsubmenu.Bind(
            wx.EVT_MENU,
            lambda event: subsubmenu.Check(event.Id, event.IsChecked()),
            id=item.Id,
        )
        submenu.AppendSubMenu(subsubmenu, "Sub sub menu")
        menu.AppendSubMenu(submenu, "Sub menu")
        menu.AppendSeparator()
        item = menu.Append(-1, "Exit")
        menu.Bind(
            wx.EVT_MENU, lambda event: win32gui.DestroyWindow(self.hwnd), id=item.Id
        )
        return menu

    def OnCommand(self, hwnd, msg, wparam, lparam):
        print(
            "SysTrayIcon.OnCommand(hwnd={}, msg={}, wparam={}, lparam={})".format(
                repr(hwnd), repr(msg), repr(wparam), repr(lparam)
            )
        )
        if not self.menu:
            print("Warning: Don't have menu")
            return 0
        if wparam is None:
            print("Warning: No menu item is selected")
            return 0
        item = _get_selected_menu_item(wparam, self.menu)
        if not item:
            print(f"Warning: Don't have menu item ID {wparam}")
            return 0
        if debug or verbose > 1:
            print(
                item.__class__.__name__,
                item.Id,
                _get_kind_str(item.Kind),
                item.ItemLabel,
            )
        event = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED)
        event.Id = item.Id
        if item.Kind == wx.ITEM_RADIO:
            event.SetInt(1)
        elif item.Kind == wx.ITEM_CHECK:
            event.SetInt(int(not item.Checked))
        item.Menu.ProcessEvent(event)
        return 0

    def OnDestroy(self, hwnd, msg, wparam, lparam):
        self.Destroy()
        if not wx.GetApp() or not wx.GetApp().IsMainLoopRunning():
            win32gui.PostQuitMessage(0)
        return 0

    def Destroy(self):
        if self.menu:
            self.menu.Destroy()
        self.RemoveIcon()
        self._destroyed = True
        wx.EvtHandler.Destroy(self)

    def __bool__(self):
        return not self._destroyed

    def OnRightUp(self, event):
        self.PopupMenu(self.CreatePopupMenu())

    def OnTaskbarCreated(self, hwnd, msg, wparam, lparam):
        if self._nid:
            hicon, tooltip = self._nid[4:6]
            self._nid = None
            self.SetIcon(hicon, tooltip)

    def OnTaskbarNotify(self, hwnd, msg, wparam, lparam):
        if lparam == win32con.WM_LBUTTONDOWN:
            self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_DOWN))
        elif lparam == win32con.WM_LBUTTONUP:
            self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_UP))
        elif lparam == win32con.WM_LBUTTONDBLCLK:
            self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_DCLICK))
        elif lparam == win32con.WM_RBUTTONDOWN:
            self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_RIGHT_DOWN))
        elif lparam == win32con.WM_RBUTTONUP:
            self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_RIGHT_UP))
        return 1

    def PopupMenu(self, menu):
        if self.in_popup:
            return
        self.in_popup = True
        self.menu = menu
        try:
            pos = win32gui.GetCursorPos()
            # See remarks section under
            # https://msdn.microsoft.com/en-us/library/windows/desktop/ms648002(v=vs.85).aspx
            try:
                win32gui.SetForegroundWindow(self.hwnd)
            except win32gui.error:
                # Calls to SetForegroundWindow will fail if (e.g.) the Win10
                # start menu is currently shown
                pass
            win32gui.TrackPopupMenu(
                menu.hmenu, win32con.TPM_RIGHTBUTTON, pos[0], pos[1], 0, self.hwnd, None
            )
            win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
        finally:
            self.in_popup = False

    def RemoveIcon(self):
        if self._nid:
            self._nid = None
            try:
                win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, (self.hwnd, 0))
            except win32gui.error:
                return False
            return True
        return False

    def SetIcon(self, hicon, tooltip=""):
        if isinstance(hicon, wx.Icon):
            hicon = hicon.GetHandle()
        flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
        if self._nid:
            msg = win32gui.NIM_MODIFY
        else:
            msg = win32gui.NIM_ADD
        self._nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, tooltip)
        try:
            win32gui.Shell_NotifyIcon(msg, self._nid)
        except win32gui.error:
            return False
        return True


def _get_kind_str(kind):
    return {
        wx.ITEM_SEPARATOR: "ITEM_SEPARATOR",
        wx.ITEM_NORMAL: "ITEM_NORMAL",
        wx.ITEM_CHECK: "ITEM_CHECK",
        wx.ITEM_RADIO: "ITEM_RADIO",
        wx.ITEM_DROPDOWN: "ITEM_DROPDOWN",
        wx.ITEM_MAX: "ITEM_MAX",
    }.get(kind, str(kind))


def _get_selected_menu_item(id, menu):
    if id in menu._menuitems:
        return menu._menuitems[id]
    else:
        for item in menu.MenuItems:
            if item.subMenu:
                item = _get_selected_menu_item(id, item.subMenu)
                if item:
                    return item


def main():
    app = wx.App(0)
    hinst = win32gui.GetModuleHandle(None)
    try:
        hicon = win32gui.LoadImage(
            hinst, 1, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE
        )
    except win32gui.error:
        hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
    tooltip = os.path.basename(sys.executable)
    icon = SysTrayIcon()
    icon.Bind(
        wx.EVT_TASKBAR_LEFT_UP,
        lambda event: wx.MessageDialog(
            None,
            "Native system tray icon demo (Windows only)",
            "SysTrayIcon class",
            wx.OK | wx.ICON_INFORMATION,
        ).ShowModal(),
    )
    icon.SetIcon(hicon, tooltip)
    win32gui.PumpMessages()


if __name__ == "__main__":
    main()