Debian Codegraph @

DisplayCAL/systrayicon.py

raw
1 """Drop-In replacement for wx.TaskBarIcon.
2
3 This one won't stop showing updates to the icon like wx.TaskBarIcon
4
5 """
6
7 from __future__ import annotations
8
9 import contextlib
10 import ctypes
11 import os
12 import sys
13
14 import win32api
15 import win32con
16 import win32gui
17
18 from DisplayCAL.options import DEBUG, VERBOSE
19 from DisplayCAL.wx_addons import IdFactory, wx
20
21
22 class Menu(wx.EvtHandler):
23 """A class that represents a system tray icon menu."""
24
25 def __init__(self) -> None:
26 wx.EvtHandler.__init__(self)
27 self.hmenu = win32gui.CreatePopupMenu()
28 self.MenuItems = []
29 self.Parent = None
30 self._menuitems = {}
31 # With wxPython 4, calling <EvtHandler>.Destroy() no longer makes the
32 # instance evaluate to False in boolean comparisons, so we emulate that
33 # functionality
34 self._destroyed = False
35
36 def Append( # noqa: N802
37 self,
38 id: int, # noqa: A002
39 text: str,
40 help: str = "", # noqa: A002
41 kind: int = wx.ITEM_NORMAL,
42 ) -> MenuItem:
43 """Append a menu item to the menu.
44
45 Args:
46 id (int): The ID of the menu item. If -1, a new ID will be
47 generated.
48 text (str): The label text for the menu item.
49 help (str): Help text for the menu item, not used in this
50 implementation.
51 kind (int): The type of the menu item, e.g., wx.ITEM_NORMAL,
52 wx.ITEM_CHECK, etc.
53
54 Returns:
55 MenuItem: A MenuItem instance representing the appended item.
56 """
57 return self.AppendItem(MenuItem(self, id, text, help, kind))
58
59 def AppendCheckItem(self, id: int, text: str, help: str = "") -> MenuItem: # noqa: A002, N802
60 """Append a checkable menu item to the menu.
61
62 Args:
63 id (int): The ID of the menu item. If -1, a new ID will be
64 generated.
65 text (str): The label text for the menu item.
66 help (str): Help text for the menu item, not used in this
67 implementation.
68
69 Returns:
70 MenuItem: A MenuItem instance representing the checkable item.
71 """
72 return self.Append(id, text, help, wx.ITEM_CHECK)
73
74 def AppendItem(self, item: MenuItem) -> MenuItem: # noqa: N802
75 """Append a menu item to the menu.
76
77 Args:
78 item (MenuItem): The MenuItem instance to append.
79
80 Returns:
81 MenuItem: The appended MenuItem instance.
82 """
83 if item.Kind == wx.ITEM_SEPARATOR:
84 flags = win32con.MF_SEPARATOR
85 else:
86 flags = win32con.MF_POPUP | win32con.MF_STRING if item.subMenu else 0
87 if not item.Enabled:
88 flags |= win32con.MF_DISABLED
89 # Use ctypes instead of win32gui.AppendMenu for unicode support
90 ctypes.windll.User32.AppendMenuW(
91 self.hmenu, flags, item.Id, str(item.ItemLabel)
92 )
93 self.MenuItems.append(item)
94 self._menuitems[item.Id] = item
95 if item.Checked:
96 self.Check(item.Id)
97 return item
98
99 def AppendSubMenu(self, submenu: Menu, text: str, help: str = "") -> MenuItem: # noqa: A002, N802
100 """Append a submenu to the menu.
101
102 Args:
103 submenu (Menu): The submenu to append.
104 text (str): The label text for the submenu.
105 help (str): Help text for the submenu, not used in this
106 implementation.
107
108 Returns:
109 MenuItem: A MenuItem instance representing the submenu.
110 """
111 item = MenuItem(self, submenu.hmenu, text, help, wx.ITEM_NORMAL, submenu)
112 return self.AppendItem(item)
113
114 def AppendRadioItem(self, id: int, text: str, help: str = "") -> MenuItem: # noqa: A002, N802
115 """Append a radio item to the menu.
116
117 Args:
118 id (int): The ID of the menu item. If -1, a new ID will be
119 generated.
120 text (str): The label text for the menu item.
121 help (str): Help text for the menu item, not used in this
122 implementation.
123
124 Returns:
125 MenuItem: A MenuItem instance representing the radio item.
126 """
127 return self.Append(id, text, help, wx.ITEM_RADIO)
128
129 def AppendSeparator(self) -> MenuItem: # noqa: N802
130 """Append a separator to the menu.
131
132 Returns:
133 MenuItem: A MenuItem instance representing the separator.
134 """
135 return self.Append(-1, "", kind=wx.ITEM_SEPARATOR)
136
137 def Check(self, id: int, check: bool = True) -> None: # noqa: A002, N802
138 """Check or uncheck a menu item by its ID.
139
140 Args:
141 id (int): The ID of the menu item to check or uncheck.
142 check (bool): True to check the menu item, False to uncheck it.
143 """
144 flags = win32con.MF_BYCOMMAND
145 item_check = self._menuitems[id]
146 if item_check.Kind == wx.ITEM_RADIO:
147 if not check:
148 return
149 item_first = item_check
150 item_last = item_check
151 index = self.MenuItems.index(item_check)
152 menuitems = self.MenuItems[:index]
153 while menuitems:
154 item = menuitems.pop()
155 if item.Kind == wx.ITEM_RADIO:
156 item_first = item
157 item.Checked = False
158 else:
159 break
160 menuitems = self.MenuItems[index:]
161 menuitems.reverse()
162 while menuitems:
163 item = menuitems.pop()
164 if item.Kind == wx.ITEM_RADIO:
165 item_last = item
166 item.Checked = False
167 else:
168 break
169 win32gui.CheckMenuRadioItem(
170 self.hmenu, item_first.Id, item_last.Id, item_check.Id, flags
171 )
172 else:
173 if check:
174 flags |= win32con.MF_CHECKED
175 win32gui.CheckMenuItem(self.hmenu, item_check.Id, flags)
176 item_check.Checked = check
177
178 def Destroy(self) -> None: # noqa: N802
179 """Destroy the Menu instance and all its menu items."""
180 for menuitem in self.MenuItems:
181 menuitem.Destroy()
182 if not self.Parent:
183 if DEBUG or VERBOSE > 1:
184 print("DestroyMenu HMENU", self.hmenu)
185 win32gui.DestroyMenu(self.hmenu)
186 if DEBUG or VERBOSE > 1:
187 print("Destroy", self.__class__.__name__, self)
188 self._destroyed = True
189 wx.EvtHandler.Destroy(self)
190
191 def __bool__(self) -> bool:
192 """Return the Menu instance's destroyed state as a bool.
193
194 Returns:
195 bool: True if the Menu instance is not destroyed,
196 """
197 return not self._destroyed
198
199 def Enable(self, id: int, enable: bool = True) -> None: # noqa: A002, N802
200 """Enable or disable a menu item by its ID.
201
202 Args:
203 id (int): The ID of the menu item to enable or disable.
204 enable (bool, optional): True to enable the menu item, False to
205 disable it.
206 """
207 flags = win32con.MF_BYCOMMAND
208 if not enable:
209 flags |= win32con.MF_DISABLED
210 item = self._menuitems[id]
211 win32gui.EnableMenuItem(self.hmenu, item.Id, flags)
212 item.Enabled = enable
213
214
215 class MenuItem:
216 """A class that represents a menu item in a system tray icon.
217
218 Args:
219 menu (Menu): The parent menu to which this item belongs.
220 id_ (int, optional): The ID of the menu item. Defaults to -1, which
221 generates a new ID.
222 text (str, optional): The label text for the menu item.
223 help (str, optional): Help text for the menu item, not used in this
224 implementation.
225 kind (int, optional): The type of the menu item, e.g., wx.ITEM_NORMAL,
226 wx.ITEM_CHECK, etc.
227 subMenu (None | Menu, optional): An optional submenu associated with
228 this menu item.
229 """
230
231 def __init__(
232 self,
233 menu: Menu,
234 id_: int = -1,
235 text: str = "",
236 help: str = "", # noqa: A002
237 kind: int = wx.ITEM_NORMAL,
238 subMenu: None | Menu = None, # noqa: N803
239 ) -> None:
240 if id_ == -1:
241 id_ = IdFactory.NewId()
242 self.Menu = menu
243 self.Id = id_
244 self.ItemLabel = text
245 self.Help = help
246 self.Kind = kind
247 self.Enabled = True
248 self.Checked = False
249 self.subMenu = subMenu
250 if subMenu:
251 self.subMenu.Parent = menu
252
253 def Check(self, check: bool = True) -> None: # noqa: N802
254 """Check or uncheck the menu item.
255
256 Args:
257 check (bool): True to check the menu item, False to uncheck it.
258 """
259 self.Checked = check
260 if self.Id in self.Menu._menuitems:
261 self.Menu.Check(self.Id, check)
262
263 def Destroy(self) -> None: # noqa: N802
264 """Destroy the menu item and its associated submenu if it exists."""
265 if self.subMenu:
266 self.subMenu.Destroy()
267 if DEBUG or VERBOSE > 1:
268 print(
269 "Destroy",
270 self.__class__.__name__,
271 self.Id,
272 _get_kind_str(self.Kind),
273 self.ItemLabel,
274 )
275 if self.Id in IdFactory.ReservedIds:
276 IdFactory.UnreserveId(self.Id)
277
278 def Enable(self, enable: bool = True) -> None: # noqa: N802
279 """Enable or disable the menu item.
280
281 Args:
282 enable (bool): True to enable the menu item, False to disable it.
283 """
284 self.Enabled = enable
285 if self.Id in self.Menu._menuitems:
286 self.Menu.Enable(self.Id, enable)
287
288 def GetId(self) -> int: # noqa: N802
289 """Get the ID of the menu item.
290
291 Returns:
292 int: The ID of the menu item.
293 """
294 return self.Id
295
296
297 class SysTrayIcon(wx.EvtHandler):
298 """A class that creates a system tray icon with a context menu."""
299
300 def __init__(self) -> None:
301 wx.EvtHandler.__init__(self)
302 msg_taskbar_created = win32gui.RegisterWindowMessage("TaskbarCreated")
303 message_map = {
304 msg_taskbar_created: self.OnTaskbarCreated,
305 win32con.WM_DESTROY: self.OnDestroy,
306 win32con.WM_COMMAND: self.OnCommand,
307 win32con.WM_USER + 20: self.OnTaskbarNotify,
308 }
309
310 wc = win32gui.WNDCLASS()
311 hinst = wc.hInstance = win32api.GetModuleHandle(None)
312 wc.lpszClassName = "SysTrayIcon"
313 wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
314 wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW)
315 wc.hbrBackground = win32con.COLOR_WINDOW
316 wc.lpfnWndProc = message_map
317
318 _class_atom = win32gui.RegisterClass(wc)
319
320 style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
321 self.hwnd = win32gui.CreateWindow(
322 wc.lpszClassName,
323 "SysTrayIcon",
324 style,
325 0,
326 0,
327 win32con.CW_USEDEFAULT,
328 win32con.CW_USEDEFAULT,
329 0,
330 0,
331 hinst,
332 None,
333 )
334 win32gui.UpdateWindow(self.hwnd)
335 self._nid = None
336 self.in_popup = False
337 self.menu = None
338 self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnRightUp)
339 # With wxPython 4, calling <EvtHandler>.Destroy() no longer makes the
340 # instance evaluate to False in boolean comparisons, so we emulate that
341 # functionality
342 self._destroyed = False
343
344 def CreatePopupMenu(self) -> Menu: # noqa: N802
345 """Override this method in derived classes.
346
347 Returns:
348 Menu: A wx.Menu instance representing the context menu for the
349 system tray icon.
350 """
351 if self.menu:
352 return self.menu
353 menu = Menu()
354 item = menu.AppendRadioItem(-1, "Radio 1")
355 item.Check()
356 menu.Bind(
357 wx.EVT_MENU,
358 lambda event: menu.Check(event.Id, event.IsChecked()),
359 id=item.Id,
360 )
361 item = menu.AppendRadioItem(-1, "Radio 2")
362 menu.Bind(
363 wx.EVT_MENU,
364 lambda event: menu.Check(event.Id, event.IsChecked()),
365 id=item.Id,
366 )
367 menu.AppendSeparator()
368 item = menu.AppendCheckItem(-1, "Checkable")
369 item.Check()
370 menu.Bind(
371 wx.EVT_MENU,
372 lambda event: menu.Check(event.Id, event.IsChecked()),
373 id=item.Id,
374 )
375 menu.AppendSeparator()
376 item = menu.AppendCheckItem(-1, "Disabled")
377 item.Enable(False)
378 menu.AppendSeparator()
379 submenu = Menu()
380 item = submenu.AppendCheckItem(-1, "Sub menu item")
381 submenu.Bind(
382 wx.EVT_MENU,
383 lambda event: submenu.Check(event.Id, event.IsChecked()),
384 id=item.Id,
385 )
386 subsubmenu = Menu()
387 item = subsubmenu.AppendCheckItem(-1, "Sub sub menu item")
388 subsubmenu.Bind(
389 wx.EVT_MENU,
390 lambda event: subsubmenu.Check(event.Id, event.IsChecked()),
391 id=item.Id,
392 )
393 submenu.AppendSubMenu(subsubmenu, "Sub sub menu")
394 menu.AppendSubMenu(submenu, "Sub menu")
395 menu.AppendSeparator()
396 item = menu.Append(-1, "Exit")
397 menu.Bind(
398 wx.EVT_MENU, lambda event: win32gui.DestroyWindow(self.hwnd), id=item.Id
399 )
400 return menu
401
402 def OnCommand(self, hwnd: int, msg: int, wparam: int, lparam: int) -> int: # noqa: N802
403 """Handle the command event when a menu item is selected.
404
405 Args:
406 hwnd (int): Handle to the window.
407 msg (int): Message identifier.
408 wparam (int): Additional message information, typically the ID of the
409 selected menu item.
410 lparam (int): Additional message information, not used in this context.
411
412 Returns:
413 int: Always returns 0 to indicate the message was processed.
414 """
415 print(
416 f"SysTrayIcon.OnCommand(hwnd={hwnd!r}, msg={msg!r}, "
417 f"wparam={wparam!r}, lparam={lparam!r})"
418 )
419 if not self.menu:
420 print("Warning: Don't have menu")
421 return 0
422 if wparam is None:
423 print("Warning: No menu item is selected")
424 return 0
425 item = _get_selected_menu_item(wparam, self.menu)
426 if not item:
427 print(f"Warning: Don't have menu item ID {wparam}")
428 return 0
429 if DEBUG or VERBOSE > 1:
430 print(
431 item.__class__.__name__,
432 item.Id,
433 _get_kind_str(item.Kind),
434 item.ItemLabel,
435 )
436 event = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED)
437 event.Id = item.Id
438 if item.Kind == wx.ITEM_RADIO:
439 event.SetInt(1)
440 elif item.Kind == wx.ITEM_CHECK:
441 event.SetInt(int(not item.Checked))
442 item.Menu.ProcessEvent(event)
443 return 0
444
445 def OnDestroy(self, hwnd: int, msg: int, wparam: int, lparam: int) -> int: # noqa: N802
446 """Handle the window destroy event.
447
448 Args:
449 hwnd (int): Handle to the window.
450 msg (int): Message identifier.
451 wparam (int): Additional message information.
452 lparam (int): Additional message information.
453
454 Returns:
455 int: Always returns 0 to indicate the message was processed.
456 """
457 self.Destroy()
458 if not wx.GetApp() or not wx.GetApp().IsMainLoopRunning():
459 win32gui.PostQuitMessage(0)
460 return 0
461
462 def Destroy(self) -> None: # noqa: N802
463 """Destroy the SysTrayIcon instance and remove the icon from the system tray."""
464 if self.menu:
465 self.menu.Destroy()
466 self.RemoveIcon()
467 self._destroyed = True
468 wx.EvtHandler.Destroy(self)
469
470 def __bool__(self) -> bool:
471 """Return the SysTrayIcon instance's destroyed state as a bool.
472
473 Returns:
474 bool: True if the SysTrayIcon instance is not destroyed,
475 """
476 return not self._destroyed
477
478 def OnRightUp(self, event: wx.Event) -> None: # noqa: N802
479 """Handle the right mouse button up event.
480
481 Args:
482 event (wx.Event): The event object containing information about the
483 right mouse button up event.
484 """
485 self.PopupMenu(self.CreatePopupMenu())
486
487 def OnTaskbarCreated(self, hwnd: int, msg: int, wparam: int, lparam: int) -> int: # noqa: N802
488 """Handle the taskbar created event.
489
490 Args:
491 hwnd (int): Handle to the window.
492 msg (int): Message identifier.
493 wparam (int): Additional message information.
494 lparam (int): Additional message information.
495
496 Returns:
497 int: Always returns 1 to indicate the message was processed.
498 """
499 if not self._nid:
500 return 1
501 hicon, tooltip = self._nid[4:6]
502 self._nid = None
503 self.SetIcon(hicon, tooltip)
504
505 return 1
506
507 def OnTaskbarNotify( # noqa: N802
508 self, hwnd: int, msg: int, wparam: int, lparam: int
509 ) -> int:
510 """Handle taskbar notifications.
511
512 Args:
513 hwnd (int): Handle to the window.
514 msg (int): Message identifier.
515 wparam (int): Additional message information.
516 lparam (int): Additional message information, indicating the type of
517 mouse event (e.g., left button down, right button up).
518
519 Returns:
520 int: Always returns 1 to indicate the message was processed.
521 """
522 if lparam == win32con.WM_LBUTTONDOWN:
523 self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_DOWN))
524 elif lparam == win32con.WM_LBUTTONUP:
525 self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_UP))
526 elif lparam == win32con.WM_LBUTTONDBLCLK:
527 self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_LEFT_DCLICK))
528 elif lparam == win32con.WM_RBUTTONDOWN:
529 self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_RIGHT_DOWN))
530 elif lparam == win32con.WM_RBUTTONUP:
531 self.ProcessEvent(wx.CommandEvent(wx.wxEVT_TASKBAR_RIGHT_UP))
532 return 1
533
534 def PopupMenu(self, menu: Menu) -> None: # noqa: N802
535 """Display a context menu at the current cursor position.
536
537 Args:
538 menu (Menu): The menu to display.
539 """
540 if self.in_popup:
541 return
542 self.in_popup = True
543 self.menu = menu
544 try:
545 pos = win32gui.GetCursorPos()
546 # See remarks section under
547 # https://msdn.microsoft.com/en-us/library/windows/desktop/ms648002(v=vs.85).aspx
548 with contextlib.suppress(win32gui.error):
549 win32gui.SetForegroundWindow(self.hwnd)
550 # Calls to SetForegroundWindow will fail if (e.g.) the Win10
551 # start menu is currently shown
552 win32gui.TrackPopupMenu(
553 menu.hmenu, win32con.TPM_RIGHTBUTTON, pos[0], pos[1], 0, self.hwnd, None
554 )
555 win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
556 finally:
557 self.in_popup = False
558
559 def RemoveIcon(self) -> bool: # noqa: N802
560 """Remove the system tray icon.
561
562 Returns:
563 bool: True if the icon was removed successfully, False otherwise.
564 """
565 if not self._nid:
566 return False
567 self._nid = None
568 try:
569 win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, (self.hwnd, 0))
570 except win32gui.error:
571 return False
572 return True
573
574 def SetIcon(self, hicon: int | wx.Icon, tooltip: str = "") -> bool: # noqa: N802
575 """Set the icon and tooltip for the system tray icon.
576
577 Args:
578 hicon (int | wx.Icon): The icon to set, can be a wx.Icon instance
579 or an icon handle.
580 tooltip (str): The tooltip text to display when hovering over the
581 icon.
582
583 Returns:
584 bool: True if the icon was set successfully, False otherwise.
585 """
586 if isinstance(hicon, wx.Icon):
587 hicon = hicon.GetHandle()
588 flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
589 msg = win32gui.NIM_MODIFY if self._nid else win32gui.NIM_ADD
590 self._nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, tooltip)
591 try:
592 win32gui.Shell_NotifyIcon(msg, self._nid)
593 except win32gui.error:
594 return False
595 return True
596
597
598 def _get_kind_str(kind: str) -> str:
599 """Get a string representation of the menu item kind.
600
601 Returns:
602 str: The string representation of the menu item kind.
603 """
604 return {
605 wx.ITEM_SEPARATOR: "ITEM_SEPARATOR",
606 wx.ITEM_NORMAL: "ITEM_NORMAL",
607 wx.ITEM_CHECK: "ITEM_CHECK",
608 wx.ITEM_RADIO: "ITEM_RADIO",
609 wx.ITEM_DROPDOWN: "ITEM_DROPDOWN",
610 wx.ITEM_MAX: "ITEM_MAX",
611 }.get(kind, str(kind))
612
613
614 def _get_selected_menu_item(id: int, menu: Menu) -> None | MenuItem: # noqa: A002
615 """Recursively search for a menu item by ID in the menu and its submenus.
616
617 Args:
618 id (int): The ID of the menu item to search for.
619 menu (Menu): The menu to search in.
620
621 Returns:
622 None | MenuItem: The found menu item or None if not found.
623 """
624 if id in menu._menuitems:
625 return menu._menuitems[id]
626
627 for item in menu.MenuItems:
628 if not item.subMenu:
629 continue
630 item = _get_selected_menu_item(id, item.subMenu)
631 if item:
632 return item
633
634 return None
635
636
637 def main() -> None:
638 """Main function to create and run the system tray icon."""
639 _app = wx.App(0)
640 hinst = win32gui.GetModuleHandle(None)
641 try:
642 hicon = win32gui.LoadImage(
643 hinst, 1, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE
644 )
645 except win32gui.error:
646 hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
647 tooltip = os.path.basename(sys.executable)
648 icon = SysTrayIcon()
649 icon.Bind(
650 wx.EVT_TASKBAR_LEFT_UP,
651 lambda event: wx.MessageDialog(
652 None,
653 "Native system tray icon demo (Windows only)",
654 "SysTrayIcon class",
655 wx.OK | wx.ICON_INFORMATION,
656 ).ShowModal(),
657 )
658 icon.SetIcon(hicon, tooltip)
659 win32gui.PumpMessages()
660
661
662 if __name__ == "__main__":
663 main()