- setup.ps1: the elevated part removes the old tasks ("TT LCD Dashboard" and
the elevated "The Kurgan"); back in the unelevated part, setup registers
"The Kurgan" as the user with RunLevel Limited and starts it. Registered
as the user, the tray's "Start with Windows" can change it without admin
rights (checked on this machine with a throwaway task). Running setup.ps1
from an elevated window is refused, since the task must be registered
unelevated. The hardware service's install follows in stage 9.
- kurgan/tray.py: texts for an unelevated task; a failed toggle suggests
re-running setup.ps1 (for a task an older setup registered elevated).
- README: the task is unelevated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
403 lines
17 KiB
Python
403 lines
17 KiB
Python
"""Notification-area icon for The Kurgan.
|
|
|
|
The tooltip shows the power draw; the menu shows each capability's status and has
|
|
"Open The Kurgan" (the web UI), "Start with Windows" and "Exit". Clicking the icon with the
|
|
left button opens the web UI directly. notify() shows a balloon tip when something starts
|
|
going wrong (fan failsafes, AI server errors, failing sensors).
|
|
|
|
"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task on or off.
|
|
setup.ps1 registers that task as you, without admin rights, so changing it needs none. The task
|
|
itself stays enabled, so it can still be started by hand: Start-ScheduledTask "The Kurgan"
|
|
|
|
If The Kurgan is ever run elevated (it shouldn't be), Windows would drop Explorer's clicks on
|
|
the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import ctypes.wintypes as wt
|
|
import logging
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
# The sword's hilt, 16-256 px (made by kurgan/assets/make_assets.py from The-Kurgan-Sword.png).
|
|
ICON_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "kurgan.ico")
|
|
TASK_NAME = "The Kurgan"
|
|
LEGACY_TASK_NAME = "TT LCD Dashboard" # until setup.ps1 re-registers the task
|
|
|
|
|
|
# ----------------------------------------------------------------------------- startup task
|
|
|
|
def _powershell(script: str) -> str:
|
|
r = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
capture_output=True, text=True, timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
|
|
if r.returncode != 0:
|
|
lines = [ln.strip() for ln in (r.stderr or r.stdout).splitlines() if ln.strip()]
|
|
raise RuntimeError(lines[0] if lines else f"PowerShell exited with code {r.returncode}")
|
|
return r.stdout.strip()
|
|
|
|
|
|
_QUERY = """
|
|
$t = Get-ScheduledTask -TaskName '%TASK%' -ErrorAction SilentlyContinue
|
|
if (-not $t) { 'missing' }
|
|
elseif ($t.State -ne 'Disabled' -and @($t.Triggers | Where-Object {
|
|
$_.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger' -and $_.Enabled }).Count) { 'on' }
|
|
else { 'off' }
|
|
"""
|
|
|
|
_SET = """
|
|
$ErrorActionPreference = 'Stop'
|
|
$t = Get-ScheduledTask -TaskName '%TASK%'
|
|
$n = 0
|
|
foreach ($tr in $t.Triggers) {
|
|
if ($tr.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger') { $tr.Enabled = %ON%; $n++ }
|
|
}
|
|
if (-not $n) { throw 'The startup task has no logon trigger; run setup.ps1 again.' }
|
|
Set-ScheduledTask -InputObject $t | Out-Null
|
|
if (%ON% -and $t.State -eq 'Disabled') { Enable-ScheduledTask -TaskName '%TASK%' | Out-Null }
|
|
"""
|
|
|
|
|
|
def _task_state(name: str) -> str:
|
|
return _powershell(_QUERY.replace("%TASK%", name))
|
|
|
|
|
|
def startup_task() -> str | None:
|
|
"""The installed startup task's name, preferring The Kurgan's own."""
|
|
for name in (TASK_NAME, LEGACY_TASK_NAME):
|
|
if _task_state(name) != "missing":
|
|
return name
|
|
return None
|
|
|
|
|
|
def autostart_enabled() -> bool | None:
|
|
"""True/False: the startup task does/doesn't run at logon. None: it isn't installed."""
|
|
name = startup_task()
|
|
return None if name is None else _task_state(name) == "on"
|
|
|
|
|
|
def set_autostart(on: bool) -> None:
|
|
name = startup_task()
|
|
if name is None:
|
|
raise RuntimeError("The startup task isn't installed; run setup.ps1.")
|
|
_powershell(_SET.replace("%TASK%", name).replace("%ON%", "$true" if on else "$false"))
|
|
|
|
|
|
# ----------------------------------------------------------------------------- Win32
|
|
|
|
_u32 = ctypes.WinDLL("user32", use_last_error=True)
|
|
_shell32 = ctypes.WinDLL("shell32", use_last_error=True)
|
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
|
LRESULT = ctypes.c_ssize_t
|
|
WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM)
|
|
|
|
WM_NULL, WM_DESTROY, WM_CLOSE, WM_TIMER = 0x0000, 0x0002, 0x0010, 0x0113
|
|
WM_LBUTTONUP, WM_RBUTTONUP = 0x0202, 0x0205
|
|
WM_TRAY = 0x8000 + 1 # WM_APP + 1: Explorer -> us, mouse events on the icon
|
|
WM_TRAY_TIP = 0x8000 + 2 # WM_APP + 2: main thread -> us, tooltip changed
|
|
WM_TRAY_INFO = 0x8000 + 3 # WM_APP + 3: any thread -> us, balloon tip to show
|
|
NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2
|
|
NIF_MESSAGE, NIF_ICON, NIF_TIP, NIF_INFO = 0x1, 0x2, 0x4, 0x10
|
|
NIIF_NONE, NIIF_WARNING, NIIF_ERROR = 0x0, 0x2, 0x3
|
|
MF_STRING, MF_GRAYED, MF_CHECKED, MF_SEPARATOR = 0x0, 0x1, 0x8, 0x800
|
|
TPM_RIGHTBUTTON, TPM_NONOTIFY, TPM_RETURNCMD = 0x2, 0x80, 0x100
|
|
MB_ICONWARNING, MB_SETFOREGROUND = 0x30, 0x10000
|
|
MSGFLT_ALLOW = 1
|
|
RETRY_TIMER = 1
|
|
|
|
|
|
class WNDCLASSEXW(ctypes.Structure):
|
|
_fields_ = [("cbSize", wt.UINT), ("style", wt.UINT), ("lpfnWndProc", WNDPROC), ("cbClsExtra", ctypes.c_int),
|
|
("cbWndExtra", ctypes.c_int), ("hInstance", wt.HINSTANCE), ("hIcon", wt.HICON),
|
|
("hCursor", wt.HANDLE), ("hbrBackground", wt.HBRUSH), ("lpszMenuName", wt.LPCWSTR),
|
|
("lpszClassName", wt.LPCWSTR), ("hIconSm", wt.HICON)]
|
|
|
|
|
|
class NOTIFYICONDATAW(ctypes.Structure):
|
|
_fields_ = [("cbSize", wt.DWORD), ("hWnd", wt.HWND), ("uID", wt.UINT), ("uFlags", wt.UINT),
|
|
("uCallbackMessage", wt.UINT), ("hIcon", wt.HICON), ("szTip", wt.WCHAR * 128),
|
|
("dwState", wt.DWORD), ("dwStateMask", wt.DWORD), ("szInfo", wt.WCHAR * 256),
|
|
("uVersion", wt.UINT), ("szInfoTitle", wt.WCHAR * 64), ("dwInfoFlags", wt.DWORD),
|
|
("guidItem", ctypes.c_byte * 16), ("hBalloonIcon", wt.HICON)]
|
|
|
|
|
|
_u32.RegisterClassExW.argtypes = [ctypes.POINTER(WNDCLASSEXW)]
|
|
_u32.RegisterClassExW.restype = wt.ATOM
|
|
_u32.CreateWindowExW.argtypes = [wt.DWORD, wt.LPCWSTR, wt.LPCWSTR, wt.DWORD, ctypes.c_int, ctypes.c_int,
|
|
ctypes.c_int, ctypes.c_int, wt.HWND, wt.HMENU, wt.HINSTANCE, wt.LPVOID]
|
|
_u32.CreateWindowExW.restype = wt.HWND
|
|
_u32.DefWindowProcW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
|
|
_u32.DefWindowProcW.restype = LRESULT
|
|
_u32.GetMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT]
|
|
_u32.GetMessageW.restype = wt.BOOL
|
|
_u32.TranslateMessage.argtypes = [ctypes.POINTER(wt.MSG)]
|
|
_u32.DispatchMessageW.argtypes = [ctypes.POINTER(wt.MSG)]
|
|
_u32.DispatchMessageW.restype = LRESULT
|
|
_u32.PostMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
|
|
_u32.PostMessageW.restype = wt.BOOL
|
|
_u32.PostQuitMessage.argtypes = [ctypes.c_int]
|
|
_u32.DestroyWindow.argtypes = [wt.HWND]
|
|
_u32.RegisterWindowMessageW.argtypes = [wt.LPCWSTR]
|
|
_u32.RegisterWindowMessageW.restype = wt.UINT
|
|
_u32.ChangeWindowMessageFilterEx.argtypes = [wt.HWND, wt.UINT, wt.DWORD, wt.LPVOID]
|
|
_u32.ChangeWindowMessageFilterEx.restype = wt.BOOL
|
|
_u32.LoadImageW.argtypes = [wt.HINSTANCE, wt.LPCWSTR, wt.UINT, ctypes.c_int, ctypes.c_int, wt.UINT]
|
|
_u32.LoadImageW.restype = wt.HANDLE
|
|
_u32.DestroyIcon.argtypes = [wt.HICON]
|
|
_u32.CreatePopupMenu.restype = wt.HMENU
|
|
_u32.AppendMenuW.argtypes = [wt.HMENU, wt.UINT, ctypes.c_size_t, wt.LPCWSTR]
|
|
_u32.TrackPopupMenu.argtypes = [wt.HMENU, wt.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, wt.HWND, wt.LPVOID]
|
|
_u32.TrackPopupMenu.restype = ctypes.c_int
|
|
_u32.DestroyMenu.argtypes = [wt.HMENU]
|
|
_u32.GetCursorPos.argtypes = [ctypes.POINTER(wt.POINT)]
|
|
_u32.SetForegroundWindow.argtypes = [wt.HWND]
|
|
_u32.SetTimer.argtypes = [wt.HWND, ctypes.c_size_t, wt.UINT, wt.LPVOID]
|
|
_u32.SetTimer.restype = ctypes.c_size_t
|
|
_u32.KillTimer.argtypes = [wt.HWND, ctypes.c_size_t]
|
|
_u32.MessageBoxW.argtypes = [wt.HWND, wt.LPCWSTR, wt.LPCWSTR, wt.UINT]
|
|
_shell32.Shell_NotifyIconW.argtypes = [wt.DWORD, ctypes.POINTER(NOTIFYICONDATAW)]
|
|
_shell32.Shell_NotifyIconW.restype = wt.BOOL
|
|
_k32.GetModuleHandleW.argtypes = [wt.LPCWSTR]
|
|
_k32.GetModuleHandleW.restype = wt.HMODULE
|
|
|
|
|
|
def _is_admin() -> bool:
|
|
try:
|
|
return bool(_shell32.IsUserAnAdmin())
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
class TrayIcon:
|
|
"""Notification-area icon on its own thread.
|
|
|
|
status_lines() is called when the menu opens; on_open/on_exit are called from the tray thread."""
|
|
|
|
CLASS_NAME = "KurganTray"
|
|
ID_OPEN, ID_AUTOSTART, ID_EXIT = 1, 2, 3
|
|
|
|
def __init__(self, title: str, icon_path: str, on_exit, on_open=None, status_lines=None):
|
|
self.title = title
|
|
self.icon_path = icon_path
|
|
self.on_exit = on_exit
|
|
self.on_open = on_open
|
|
self.status_lines = status_lines or (lambda: [])
|
|
self._tip = title
|
|
self._info: tuple[str, str, int] | None = None
|
|
self._hwnd = None
|
|
self._hicon = None
|
|
self._shown = False
|
|
self._autostart: bool | None = None
|
|
self._autostart_known = False
|
|
self._msg_taskbar = _u32.RegisterWindowMessageW("TaskbarCreated")
|
|
self._wndproc = WNDPROC(self._proc) # keep a reference: Windows calls it
|
|
self._thread = threading.Thread(target=self._run, name="tray", daemon=True)
|
|
|
|
# -- called from other threads
|
|
|
|
def start(self) -> None:
|
|
self._thread.start()
|
|
threading.Thread(target=self._refresh_autostart, name="tray-autostart", daemon=True).start()
|
|
|
|
def set_tooltip(self, text: str) -> None:
|
|
text = text[:127]
|
|
if text != self._tip:
|
|
self._tip = text
|
|
if self._hwnd:
|
|
_u32.PostMessageW(self._hwnd, WM_TRAY_TIP, 0, 0)
|
|
|
|
def notify(self, title: str, message: str, warning: bool = False) -> None:
|
|
"""Show a balloon tip; safe from any thread (it queues on the tray window)."""
|
|
self._info = (title[:63], message[:255], NIIF_WARNING if warning else NIIF_NONE)
|
|
if self._hwnd:
|
|
_u32.PostMessageW(self._hwnd, WM_TRAY_INFO, 0, 0)
|
|
|
|
def _info_nid(self) -> NOTIFYICONDATAW:
|
|
title, message, flags = self._info
|
|
nid = NOTIFYICONDATAW()
|
|
nid.cbSize = ctypes.sizeof(nid)
|
|
nid.hWnd = self._hwnd
|
|
nid.uID = 1
|
|
nid.uFlags = NIF_INFO
|
|
nid.szInfo = message
|
|
nid.szInfoTitle = title
|
|
nid.dwInfoFlags = flags
|
|
return nid
|
|
|
|
def _show_info(self) -> None:
|
|
_shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(self._info_nid()))
|
|
|
|
def close(self) -> None:
|
|
if self._hwnd:
|
|
_u32.PostMessageW(self._hwnd, WM_CLOSE, 0, 0)
|
|
self._thread.join(timeout=3)
|
|
|
|
# -- tray thread
|
|
|
|
def _run(self) -> None:
|
|
try:
|
|
try:
|
|
_u32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # per-monitor v2: crisp menu and icon
|
|
except Exception:
|
|
pass
|
|
hinst = _k32.GetModuleHandleW(None)
|
|
wc = WNDCLASSEXW()
|
|
wc.cbSize = ctypes.sizeof(wc)
|
|
wc.lpfnWndProc = self._wndproc
|
|
wc.hInstance = hinst
|
|
wc.lpszClassName = self.CLASS_NAME
|
|
_u32.RegisterClassExW(ctypes.byref(wc)) # fails harmlessly if already registered
|
|
# A hidden top-level window: message-only windows miss the TaskbarCreated broadcast.
|
|
hwnd = _u32.CreateWindowExW(0, self.CLASS_NAME, self.title, 0, 0, 0, 0, 0, None, None, hinst, None)
|
|
if not hwnd:
|
|
raise OSError(f"CreateWindowEx failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
|
for msg in (WM_TRAY, self._msg_taskbar):
|
|
_u32.ChangeWindowMessageFilterEx(hwnd, msg, MSGFLT_ALLOW, None)
|
|
size = _u32.GetSystemMetrics(49) # SM_CXSMICON
|
|
self._hicon = _u32.LoadImageW(None, self.icon_path, 1, size, size, 0x10) # IMAGE_ICON, LR_LOADFROMFILE
|
|
self._hwnd = hwnd
|
|
self._add()
|
|
msg = wt.MSG()
|
|
while _u32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
|
|
_u32.TranslateMessage(ctypes.byref(msg))
|
|
_u32.DispatchMessageW(ctypes.byref(msg))
|
|
except Exception:
|
|
log.exception("Tray icon failed")
|
|
finally:
|
|
if self._hicon:
|
|
_u32.DestroyIcon(self._hicon)
|
|
self._hwnd = None
|
|
|
|
def _notify(self, op: int) -> bool:
|
|
nid = NOTIFYICONDATAW()
|
|
nid.cbSize = ctypes.sizeof(nid)
|
|
nid.hWnd = self._hwnd
|
|
nid.uID = 1
|
|
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP
|
|
nid.uCallbackMessage = WM_TRAY
|
|
nid.hIcon = self._hicon
|
|
nid.szTip = self._tip
|
|
return bool(_shell32.Shell_NotifyIconW(op, ctypes.byref(nid)))
|
|
|
|
def _add(self) -> None:
|
|
"""Add the icon; at logon the taskbar may not exist yet, so keep retrying."""
|
|
self._shown = self._notify(NIM_ADD) or self._notify(NIM_MODIFY)
|
|
if self._shown:
|
|
_u32.KillTimer(self._hwnd, RETRY_TIMER)
|
|
log.info("Tray icon shown")
|
|
else:
|
|
_u32.SetTimer(self._hwnd, RETRY_TIMER, 5000, None)
|
|
|
|
def _proc(self, hwnd, msg, wparam, lparam):
|
|
try:
|
|
if msg == WM_TRAY:
|
|
event = lparam & 0xFFFF
|
|
if event == WM_LBUTTONUP and self.on_open is not None:
|
|
self.on_open()
|
|
elif event in (WM_LBUTTONUP, WM_RBUTTONUP):
|
|
self._menu()
|
|
return 0
|
|
if msg == WM_TRAY_TIP:
|
|
if self._shown:
|
|
self._notify(NIM_MODIFY)
|
|
return 0
|
|
if msg == WM_TRAY_INFO:
|
|
if self._shown and self._info is not None:
|
|
self._show_info()
|
|
return 0
|
|
if msg == self._msg_taskbar or (msg == WM_TIMER and wparam == RETRY_TIMER):
|
|
self._add() # Explorer restarted (or the taskbar wasn't up yet)
|
|
return 0
|
|
if msg == WM_CLOSE:
|
|
self._notify(NIM_DELETE)
|
|
_u32.DestroyWindow(hwnd)
|
|
return 0
|
|
if msg == WM_DESTROY:
|
|
_u32.PostQuitMessage(0)
|
|
return 0
|
|
except Exception:
|
|
log.exception("Tray icon message %#x failed", msg)
|
|
return _u32.DefWindowProcW(hwnd, msg, wparam, lparam)
|
|
|
|
def _menu(self) -> None:
|
|
cmd = 0
|
|
m = _u32.CreatePopupMenu()
|
|
try:
|
|
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, self.title)
|
|
try:
|
|
lines = list(self.status_lines())
|
|
except Exception:
|
|
log.exception("Tray status failed")
|
|
lines = []
|
|
for line in lines:
|
|
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, line[:120])
|
|
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
|
|
if self.on_open is not None:
|
|
_u32.AppendMenuW(m, MF_STRING, self.ID_OPEN, f"Open {self.title}")
|
|
if not self._autostart_known:
|
|
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART, "Start with Windows (checking...)")
|
|
elif self._autostart is None:
|
|
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART,
|
|
"Start with Windows (run setup.ps1 first)")
|
|
else:
|
|
_u32.AppendMenuW(m, MF_STRING | (MF_CHECKED if self._autostart else 0), self.ID_AUTOSTART,
|
|
"Start with Windows")
|
|
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
|
|
_u32.AppendMenuW(m, MF_STRING, self.ID_EXIT, "Exit")
|
|
pt = wt.POINT()
|
|
_u32.GetCursorPos(ctypes.byref(pt))
|
|
_u32.SetForegroundWindow(self._hwnd) # otherwise the menu doesn't close when clicking elsewhere
|
|
cmd = _u32.TrackPopupMenu(m, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, pt.x, pt.y, 0,
|
|
self._hwnd, None)
|
|
_u32.PostMessageW(self._hwnd, WM_NULL, 0, 0)
|
|
finally:
|
|
_u32.DestroyMenu(m)
|
|
if cmd == self.ID_EXIT:
|
|
log.info("Exit chosen from the tray menu")
|
|
self.on_exit()
|
|
elif cmd == self.ID_OPEN:
|
|
self.on_open()
|
|
elif cmd == self.ID_AUTOSTART:
|
|
self._toggle_autostart()
|
|
|
|
def _refresh_autostart(self) -> None:
|
|
try:
|
|
self._autostart = autostart_enabled()
|
|
except Exception as e:
|
|
log.warning("Couldn't read the startup task: %s", e)
|
|
self._autostart = None
|
|
self._autostart_known = True
|
|
|
|
def _toggle_autostart(self) -> None:
|
|
want = not self._autostart
|
|
try:
|
|
set_autostart(want)
|
|
log.info("Start with Windows turned %s", "on" if want else "off")
|
|
except Exception as e:
|
|
log.warning("Couldn't change Start with Windows: %s", e)
|
|
hint = "" if _is_admin() else (
|
|
"\n\nIf the task was registered with admin rights (by an older setup.ps1), run "
|
|
"setup.ps1 again: it registers the task as you, and then this works.")
|
|
_u32.MessageBoxW(self._hwnd, f"Couldn't turn Start with Windows {'on' if want else 'off'}.\n\n{e}{hint}",
|
|
self.title, MB_ICONWARNING | MB_SETFOREGROUND)
|
|
self._refresh_autostart() # show what the task really says now
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Quick check: show the icon for 20 s with a test tooltip.
|
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
|
print("Start with Windows:", autostart_enabled())
|
|
done = threading.Event()
|
|
tray = TrayIcon("The Kurgan (test)", ICON_PATH, on_exit=done.set, status_lines=lambda: ["Test run"])
|
|
tray.start()
|
|
for i in range(20):
|
|
tray.set_tooltip(f"The Kurgan (test)\n{i} s")
|
|
if done.wait(1):
|
|
break
|
|
tray.close()
|