notificationicon.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. # Pure ctypes windows taskbar notification icon
  2. # via https://gist.github.com/jasonbot/5759510
  3. # Modified for ZeroNet
  4. import ctypes
  5. import ctypes.wintypes
  6. import os
  7. import uuid
  8. import time
  9. import gevent
  10. import threading
  11. try:
  12. from queue import Empty as queue_Empty # Python 3
  13. except ImportError:
  14. from Queue import Empty as queue_Empty # Python 2
  15. __all__ = ['NotificationIcon']
  16. # Create popup menu
  17. CreatePopupMenu = ctypes.windll.user32.CreatePopupMenu
  18. CreatePopupMenu.restype = ctypes.wintypes.HMENU
  19. CreatePopupMenu.argtypes = []
  20. MF_BYCOMMAND = 0x0
  21. MF_BYPOSITION = 0x400
  22. MF_BITMAP = 0x4
  23. MF_CHECKED = 0x8
  24. MF_DISABLED = 0x2
  25. MF_ENABLED = 0x0
  26. MF_GRAYED = 0x1
  27. MF_MENUBARBREAK = 0x20
  28. MF_MENUBREAK = 0x40
  29. MF_OWNERDRAW = 0x100
  30. MF_POPUP = 0x10
  31. MF_SEPARATOR = 0x800
  32. MF_STRING = 0x0
  33. MF_UNCHECKED = 0x0
  34. InsertMenu = ctypes.windll.user32.InsertMenuW
  35. InsertMenu.restype = ctypes.wintypes.BOOL
  36. InsertMenu.argtypes = [ctypes.wintypes.HMENU, ctypes.wintypes.UINT, ctypes.wintypes.UINT, ctypes.wintypes.UINT, ctypes.wintypes.LPCWSTR]
  37. AppendMenu = ctypes.windll.user32.AppendMenuW
  38. AppendMenu.restype = ctypes.wintypes.BOOL
  39. AppendMenu.argtypes = [ctypes.wintypes.HMENU, ctypes.wintypes.UINT, ctypes.wintypes.UINT, ctypes.wintypes.LPCWSTR]
  40. SetMenuDefaultItem = ctypes.windll.user32.SetMenuDefaultItem
  41. SetMenuDefaultItem.restype = ctypes.wintypes.BOOL
  42. SetMenuDefaultItem.argtypes = [ctypes.wintypes.HMENU, ctypes.wintypes.UINT, ctypes.wintypes.UINT]
  43. class POINT(ctypes.Structure):
  44. _fields_ = [ ('x', ctypes.wintypes.LONG),
  45. ('y', ctypes.wintypes.LONG)]
  46. GetCursorPos = ctypes.windll.user32.GetCursorPos
  47. GetCursorPos.argtypes = [ctypes.POINTER(POINT)]
  48. SetForegroundWindow = ctypes.windll.user32.SetForegroundWindow
  49. SetForegroundWindow.argtypes = [ctypes.wintypes.HWND]
  50. TPM_LEFTALIGN = 0x0
  51. TPM_CENTERALIGN = 0x4
  52. TPM_RIGHTALIGN = 0x8
  53. TPM_TOPALIGN = 0x0
  54. TPM_VCENTERALIGN = 0x10
  55. TPM_BOTTOMALIGN = 0x20
  56. TPM_NONOTIFY = 0x80
  57. TPM_RETURNCMD = 0x100
  58. TPM_LEFTBUTTON = 0x0
  59. TPM_RIGHTBUTTON = 0x2
  60. TPM_HORNEGANIMATION = 0x800
  61. TPM_HORPOSANIMATION = 0x400
  62. TPM_NOANIMATION = 0x4000
  63. TPM_VERNEGANIMATION = 0x2000
  64. TPM_VERPOSANIMATION = 0x1000
  65. TrackPopupMenu = ctypes.windll.user32.TrackPopupMenu
  66. TrackPopupMenu.restype = ctypes.wintypes.BOOL
  67. TrackPopupMenu.argtypes = [ctypes.wintypes.HMENU, ctypes.wintypes.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.wintypes.HWND, ctypes.c_void_p]
  68. PostMessage = ctypes.windll.user32.PostMessageW
  69. PostMessage.restype = ctypes.wintypes.BOOL
  70. PostMessage.argtypes = [ctypes.wintypes.HWND, ctypes.wintypes.UINT, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM]
  71. DestroyMenu = ctypes.windll.user32.DestroyMenu
  72. DestroyMenu.restype = ctypes.wintypes.BOOL
  73. DestroyMenu.argtypes = [ctypes.wintypes.HMENU]
  74. # Create notification icon
  75. GUID = ctypes.c_ubyte * 16
  76. class TimeoutVersionUnion(ctypes.Union):
  77. _fields_ = [('uTimeout', ctypes.wintypes.UINT),
  78. ('uVersion', ctypes.wintypes.UINT),]
  79. NIS_HIDDEN = 0x1
  80. NIS_SHAREDICON = 0x2
  81. class NOTIFYICONDATA(ctypes.Structure):
  82. def __init__(self, *args, **kwargs):
  83. super(NOTIFYICONDATA, self).__init__(*args, **kwargs)
  84. self.cbSize = ctypes.sizeof(self)
  85. _fields_ = [
  86. ('cbSize', ctypes.wintypes.DWORD),
  87. ('hWnd', ctypes.wintypes.HWND),
  88. ('uID', ctypes.wintypes.UINT),
  89. ('uFlags', ctypes.wintypes.UINT),
  90. ('uCallbackMessage', ctypes.wintypes.UINT),
  91. ('hIcon', ctypes.wintypes.HICON),
  92. ('szTip', ctypes.wintypes.WCHAR * 64),
  93. ('dwState', ctypes.wintypes.DWORD),
  94. ('dwStateMask', ctypes.wintypes.DWORD),
  95. ('szInfo', ctypes.wintypes.WCHAR * 256),
  96. ('union', TimeoutVersionUnion),
  97. ('szInfoTitle', ctypes.wintypes.WCHAR * 64),
  98. ('dwInfoFlags', ctypes.wintypes.DWORD),
  99. ('guidItem', GUID),
  100. ('hBalloonIcon', ctypes.wintypes.HICON),
  101. ]
  102. NIM_ADD = 0
  103. NIM_MODIFY = 1
  104. NIM_DELETE = 2
  105. NIM_SETFOCUS = 3
  106. NIM_SETVERSION = 4
  107. NIF_MESSAGE = 1
  108. NIF_ICON = 2
  109. NIF_TIP = 4
  110. NIF_STATE = 8
  111. NIF_INFO = 16
  112. NIF_GUID = 32
  113. NIF_REALTIME = 64
  114. NIF_SHOWTIP = 128
  115. NIIF_NONE = 0
  116. NIIF_INFO = 1
  117. NIIF_WARNING = 2
  118. NIIF_ERROR = 3
  119. NIIF_USER = 4
  120. NOTIFYICON_VERSION = 3
  121. NOTIFYICON_VERSION_4 = 4
  122. Shell_NotifyIcon = ctypes.windll.shell32.Shell_NotifyIconW
  123. Shell_NotifyIcon.restype = ctypes.wintypes.BOOL
  124. Shell_NotifyIcon.argtypes = [ctypes.wintypes.DWORD, ctypes.POINTER(NOTIFYICONDATA)]
  125. # Load icon/image
  126. IMAGE_BITMAP = 0
  127. IMAGE_ICON = 1
  128. IMAGE_CURSOR = 2
  129. LR_CREATEDIBSECTION = 0x00002000
  130. LR_DEFAULTCOLOR = 0x00000000
  131. LR_DEFAULTSIZE = 0x00000040
  132. LR_LOADFROMFILE = 0x00000010
  133. LR_LOADMAP3DCOLORS = 0x00001000
  134. LR_LOADTRANSPARENT = 0x00000020
  135. LR_MONOCHROME = 0x00000001
  136. LR_SHARED = 0x00008000
  137. LR_VGACOLOR = 0x00000080
  138. OIC_SAMPLE = 32512
  139. OIC_HAND = 32513
  140. OIC_QUES = 32514
  141. OIC_BANG = 32515
  142. OIC_NOTE = 32516
  143. OIC_WINLOGO = 32517
  144. OIC_WARNING = OIC_BANG
  145. OIC_ERROR = OIC_HAND
  146. OIC_INFORMATION = OIC_NOTE
  147. LoadImage = ctypes.windll.user32.LoadImageW
  148. LoadImage.restype = ctypes.wintypes.HANDLE
  149. LoadImage.argtypes = [ctypes.wintypes.HINSTANCE, ctypes.wintypes.LPCWSTR, ctypes.wintypes.UINT, ctypes.c_int, ctypes.c_int, ctypes.wintypes.UINT]
  150. # CreateWindow call
  151. WNDPROC = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.wintypes.HWND, ctypes.c_uint, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)
  152. DefWindowProc = ctypes.windll.user32.DefWindowProcW
  153. DefWindowProc.restype = ctypes.c_int
  154. DefWindowProc.argtypes = [ctypes.wintypes.HWND, ctypes.c_uint, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM]
  155. WS_OVERLAPPED = 0x00000000L
  156. WS_POPUP = 0x80000000L
  157. WS_CHILD = 0x40000000L
  158. WS_MINIMIZE = 0x20000000L
  159. WS_VISIBLE = 0x10000000L
  160. WS_DISABLED = 0x08000000L
  161. WS_CLIPSIBLINGS = 0x04000000L
  162. WS_CLIPCHILDREN = 0x02000000L
  163. WS_MAXIMIZE = 0x01000000L
  164. WS_CAPTION = 0x00C00000L
  165. WS_BORDER = 0x00800000L
  166. WS_DLGFRAME = 0x00400000L
  167. WS_VSCROLL = 0x00200000L
  168. WS_HSCROLL = 0x00100000L
  169. WS_SYSMENU = 0x00080000L
  170. WS_THICKFRAME = 0x00040000L
  171. WS_GROUP = 0x00020000L
  172. WS_TABSTOP = 0x00010000L
  173. WS_MINIMIZEBOX = 0x00020000L
  174. WS_MAXIMIZEBOX = 0x00010000L
  175. WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED |
  176. WS_CAPTION |
  177. WS_SYSMENU |
  178. WS_THICKFRAME |
  179. WS_MINIMIZEBOX |
  180. WS_MAXIMIZEBOX)
  181. SM_XVIRTUALSCREEN = 76
  182. SM_YVIRTUALSCREEN = 77
  183. SM_CXVIRTUALSCREEN = 78
  184. SM_CYVIRTUALSCREEN = 79
  185. SM_CMONITORS = 80
  186. SM_SAMEDISPLAYFORMAT = 81
  187. WM_NULL = 0x0000
  188. WM_CREATE = 0x0001
  189. WM_DESTROY = 0x0002
  190. WM_MOVE = 0x0003
  191. WM_SIZE = 0x0005
  192. WM_ACTIVATE = 0x0006
  193. WM_SETFOCUS = 0x0007
  194. WM_KILLFOCUS = 0x0008
  195. WM_ENABLE = 0x000A
  196. WM_SETREDRAW = 0x000B
  197. WM_SETTEXT = 0x000C
  198. WM_GETTEXT = 0x000D
  199. WM_GETTEXTLENGTH = 0x000E
  200. WM_PAINT = 0x000F
  201. WM_CLOSE = 0x0010
  202. WM_QUERYENDSESSION = 0x0011
  203. WM_QUIT = 0x0012
  204. WM_QUERYOPEN = 0x0013
  205. WM_ERASEBKGND = 0x0014
  206. WM_SYSCOLORCHANGE = 0x0015
  207. WM_ENDSESSION = 0x0016
  208. WM_SHOWWINDOW = 0x0018
  209. WM_CTLCOLOR = 0x0019
  210. WM_WININICHANGE = 0x001A
  211. WM_SETTINGCHANGE = 0x001A
  212. WM_DEVMODECHANGE = 0x001B
  213. WM_ACTIVATEAPP = 0x001C
  214. WM_FONTCHANGE = 0x001D
  215. WM_TIMECHANGE = 0x001E
  216. WM_CANCELMODE = 0x001F
  217. WM_SETCURSOR = 0x0020
  218. WM_MOUSEACTIVATE = 0x0021
  219. WM_CHILDACTIVATE = 0x0022
  220. WM_QUEUESYNC = 0x0023
  221. WM_GETMINMAXINFO = 0x0024
  222. WM_PAINTICON = 0x0026
  223. WM_ICONERASEBKGND = 0x0027
  224. WM_NEXTDLGCTL = 0x0028
  225. WM_SPOOLERSTATUS = 0x002A
  226. WM_DRAWITEM = 0x002B
  227. WM_MEASUREITEM = 0x002C
  228. WM_DELETEITEM = 0x002D
  229. WM_VKEYTOITEM = 0x002E
  230. WM_CHARTOITEM = 0x002F
  231. WM_SETFONT = 0x0030
  232. WM_GETFONT = 0x0031
  233. WM_SETHOTKEY = 0x0032
  234. WM_GETHOTKEY = 0x0033
  235. WM_QUERYDRAGICON = 0x0037
  236. WM_COMPAREITEM = 0x0039
  237. WM_GETOBJECT = 0x003D
  238. WM_COMPACTING = 0x0041
  239. WM_COMMNOTIFY = 0x0044
  240. WM_WINDOWPOSCHANGING = 0x0046
  241. WM_WINDOWPOSCHANGED = 0x0047
  242. WM_POWER = 0x0048
  243. WM_COPYDATA = 0x004A
  244. WM_CANCELJOURNAL = 0x004B
  245. WM_NOTIFY = 0x004E
  246. WM_INPUTLANGCHANGEREQUEST = 0x0050
  247. WM_INPUTLANGCHANGE = 0x0051
  248. WM_TCARD = 0x0052
  249. WM_HELP = 0x0053
  250. WM_USERCHANGED = 0x0054
  251. WM_NOTIFYFORMAT = 0x0055
  252. WM_CONTEXTMENU = 0x007B
  253. WM_STYLECHANGING = 0x007C
  254. WM_STYLECHANGED = 0x007D
  255. WM_DISPLAYCHANGE = 0x007E
  256. WM_GETICON = 0x007F
  257. WM_SETICON = 0x0080
  258. WM_NCCREATE = 0x0081
  259. WM_NCDESTROY = 0x0082
  260. WM_NCCALCSIZE = 0x0083
  261. WM_NCHITTEST = 0x0084
  262. WM_NCPAINT = 0x0085
  263. WM_NCACTIVATE = 0x0086
  264. WM_GETDLGCODE = 0x0087
  265. WM_SYNCPAINT = 0x0088
  266. WM_NCMOUSEMOVE = 0x00A0
  267. WM_NCLBUTTONDOWN = 0x00A1
  268. WM_NCLBUTTONUP = 0x00A2
  269. WM_NCLBUTTONDBLCLK = 0x00A3
  270. WM_NCRBUTTONDOWN = 0x00A4
  271. WM_NCRBUTTONUP = 0x00A5
  272. WM_NCRBUTTONDBLCLK = 0x00A6
  273. WM_NCMBUTTONDOWN = 0x00A7
  274. WM_NCMBUTTONUP = 0x00A8
  275. WM_NCMBUTTONDBLCLK = 0x00A9
  276. WM_KEYDOWN = 0x0100
  277. WM_KEYUP = 0x0101
  278. WM_CHAR = 0x0102
  279. WM_DEADCHAR = 0x0103
  280. WM_SYSKEYDOWN = 0x0104
  281. WM_SYSKEYUP = 0x0105
  282. WM_SYSCHAR = 0x0106
  283. WM_SYSDEADCHAR = 0x0107
  284. WM_KEYLAST = 0x0108
  285. WM_IME_STARTCOMPOSITION = 0x010D
  286. WM_IME_ENDCOMPOSITION = 0x010E
  287. WM_IME_COMPOSITION = 0x010F
  288. WM_IME_KEYLAST = 0x010F
  289. WM_INITDIALOG = 0x0110
  290. WM_COMMAND = 0x0111
  291. WM_SYSCOMMAND = 0x0112
  292. WM_TIMER = 0x0113
  293. WM_HSCROLL = 0x0114
  294. WM_VSCROLL = 0x0115
  295. WM_INITMENU = 0x0116
  296. WM_INITMENUPOPUP = 0x0117
  297. WM_MENUSELECT = 0x011F
  298. WM_MENUCHAR = 0x0120
  299. WM_ENTERIDLE = 0x0121
  300. WM_MENURBUTTONUP = 0x0122
  301. WM_MENUDRAG = 0x0123
  302. WM_MENUGETOBJECT = 0x0124
  303. WM_UNINITMENUPOPUP = 0x0125
  304. WM_MENUCOMMAND = 0x0126
  305. WM_CTLCOLORMSGBOX = 0x0132
  306. WM_CTLCOLOREDIT = 0x0133
  307. WM_CTLCOLORLISTBOX = 0x0134
  308. WM_CTLCOLORBTN = 0x0135
  309. WM_CTLCOLORDLG = 0x0136
  310. WM_CTLCOLORSCROLLBAR = 0x0137
  311. WM_CTLCOLORSTATIC = 0x0138
  312. WM_MOUSEMOVE = 0x0200
  313. WM_LBUTTONDOWN = 0x0201
  314. WM_LBUTTONUP = 0x0202
  315. WM_LBUTTONDBLCLK = 0x0203
  316. WM_RBUTTONDOWN = 0x0204
  317. WM_RBUTTONUP = 0x0205
  318. WM_RBUTTONDBLCLK = 0x0206
  319. WM_MBUTTONDOWN = 0x0207
  320. WM_MBUTTONUP = 0x0208
  321. WM_MBUTTONDBLCLK = 0x0209
  322. WM_MOUSEWHEEL = 0x020A
  323. WM_PARENTNOTIFY = 0x0210
  324. WM_ENTERMENULOOP = 0x0211
  325. WM_EXITMENULOOP = 0x0212
  326. WM_NEXTMENU = 0x0213
  327. WM_SIZING = 0x0214
  328. WM_CAPTURECHANGED = 0x0215
  329. WM_MOVING = 0x0216
  330. WM_DEVICECHANGE = 0x0219
  331. WM_MDICREATE = 0x0220
  332. WM_MDIDESTROY = 0x0221
  333. WM_MDIACTIVATE = 0x0222
  334. WM_MDIRESTORE = 0x0223
  335. WM_MDINEXT = 0x0224
  336. WM_MDIMAXIMIZE = 0x0225
  337. WM_MDITILE = 0x0226
  338. WM_MDICASCADE = 0x0227
  339. WM_MDIICONARRANGE = 0x0228
  340. WM_MDIGETACTIVE = 0x0229
  341. WM_MDISETMENU = 0x0230
  342. WM_ENTERSIZEMOVE = 0x0231
  343. WM_EXITSIZEMOVE = 0x0232
  344. WM_DROPFILES = 0x0233
  345. WM_MDIREFRESHMENU = 0x0234
  346. WM_IME_SETCONTEXT = 0x0281
  347. WM_IME_NOTIFY = 0x0282
  348. WM_IME_CONTROL = 0x0283
  349. WM_IME_COMPOSITIONFULL = 0x0284
  350. WM_IME_SELECT = 0x0285
  351. WM_IME_CHAR = 0x0286
  352. WM_IME_REQUEST = 0x0288
  353. WM_IME_KEYDOWN = 0x0290
  354. WM_IME_KEYUP = 0x0291
  355. WM_MOUSEHOVER = 0x02A1
  356. WM_MOUSELEAVE = 0x02A3
  357. WM_CUT = 0x0300
  358. WM_COPY = 0x0301
  359. WM_PASTE = 0x0302
  360. WM_CLEAR = 0x0303
  361. WM_UNDO = 0x0304
  362. WM_RENDERFORMAT = 0x0305
  363. WM_RENDERALLFORMATS = 0x0306
  364. WM_DESTROYCLIPBOARD = 0x0307
  365. WM_DRAWCLIPBOARD = 0x0308
  366. WM_PAINTCLIPBOARD = 0x0309
  367. WM_VSCROLLCLIPBOARD = 0x030A
  368. WM_SIZECLIPBOARD = 0x030B
  369. WM_ASKCBFORMATNAME = 0x030C
  370. WM_CHANGECBCHAIN = 0x030D
  371. WM_HSCROLLCLIPBOARD = 0x030E
  372. WM_QUERYNEWPALETTE = 0x030F
  373. WM_PALETTEISCHANGING = 0x0310
  374. WM_PALETTECHANGED = 0x0311
  375. WM_HOTKEY = 0x0312
  376. WM_PRINT = 0x0317
  377. WM_PRINTCLIENT = 0x0318
  378. WM_HANDHELDFIRST = 0x0358
  379. WM_HANDHELDLAST = 0x035F
  380. WM_AFXFIRST = 0x0360
  381. WM_AFXLAST = 0x037F
  382. WM_PENWINFIRST = 0x0380
  383. WM_PENWINLAST = 0x038F
  384. WM_APP = 0x8000
  385. WM_USER = 0x0400
  386. WM_REFLECT = WM_USER + 0x1c00
  387. class WNDCLASSEX(ctypes.Structure):
  388. def __init__(self, *args, **kwargs):
  389. super(WNDCLASSEX, self).__init__(*args, **kwargs)
  390. self.cbSize = ctypes.sizeof(self)
  391. _fields_ = [("cbSize", ctypes.c_uint),
  392. ("style", ctypes.c_uint),
  393. ("lpfnWndProc", WNDPROC),
  394. ("cbClsExtra", ctypes.c_int),
  395. ("cbWndExtra", ctypes.c_int),
  396. ("hInstance", ctypes.wintypes.HANDLE),
  397. ("hIcon", ctypes.wintypes.HANDLE),
  398. ("hCursor", ctypes.wintypes.HANDLE),
  399. ("hBrush", ctypes.wintypes.HANDLE),
  400. ("lpszMenuName", ctypes.wintypes.LPCWSTR),
  401. ("lpszClassName", ctypes.wintypes.LPCWSTR),
  402. ("hIconSm", ctypes.wintypes.HANDLE)]
  403. ShowWindow = ctypes.windll.user32.ShowWindow
  404. ShowWindow.argtypes = [ctypes.wintypes.HWND, ctypes.c_int]
  405. def GenerateDummyWindow(callback, uid):
  406. newclass = WNDCLASSEX()
  407. newclass.lpfnWndProc = callback
  408. newclass.lpszClassName = uid.replace("-", "")
  409. ATOM = ctypes.windll.user32.RegisterClassExW(ctypes.byref(newclass))
  410. hwnd = ctypes.windll.user32.CreateWindowExW(0, newclass.lpszClassName, None, WS_POPUP, 0, 0, 0, 0, 0, 0, 0, 0)
  411. return hwnd
  412. # Message loop calls
  413. TIMERCALLBACK = ctypes.WINFUNCTYPE(None,
  414. ctypes.wintypes.HWND,
  415. ctypes.wintypes.UINT,
  416. ctypes.POINTER(ctypes.wintypes.UINT),
  417. ctypes.wintypes.DWORD)
  418. SetTimer = ctypes.windll.user32.SetTimer
  419. SetTimer.restype = ctypes.POINTER(ctypes.wintypes.UINT)
  420. SetTimer.argtypes = [ctypes.wintypes.HWND,
  421. ctypes.POINTER(ctypes.wintypes.UINT),
  422. ctypes.wintypes.UINT,
  423. TIMERCALLBACK]
  424. KillTimer = ctypes.windll.user32.KillTimer
  425. KillTimer.restype = ctypes.wintypes.BOOL
  426. KillTimer.argtypes = [ctypes.wintypes.HWND,
  427. ctypes.POINTER(ctypes.wintypes.UINT)]
  428. class MSG(ctypes.Structure):
  429. _fields_ = [ ('HWND', ctypes.wintypes.HWND),
  430. ('message', ctypes.wintypes.UINT),
  431. ('wParam', ctypes.wintypes.WPARAM),
  432. ('lParam', ctypes.wintypes.LPARAM),
  433. ('time', ctypes.wintypes.DWORD),
  434. ('pt', POINT)]
  435. GetMessage = ctypes.windll.user32.GetMessageW
  436. GetMessage.restype = ctypes.wintypes.BOOL
  437. GetMessage.argtypes = [ctypes.POINTER(MSG), ctypes.wintypes.HWND, ctypes.wintypes.UINT, ctypes.wintypes.UINT]
  438. TranslateMessage = ctypes.windll.user32.TranslateMessage
  439. TranslateMessage.restype = ctypes.wintypes.ULONG
  440. TranslateMessage.argtypes = [ctypes.POINTER(MSG)]
  441. DispatchMessage = ctypes.windll.user32.DispatchMessageW
  442. DispatchMessage.restype = ctypes.wintypes.ULONG
  443. DispatchMessage.argtypes = [ctypes.POINTER(MSG)]
  444. def LoadIcon(iconfilename, small=False):
  445. return LoadImage(0,
  446. unicode(iconfilename),
  447. IMAGE_ICON,
  448. 16 if small else 0,
  449. 16 if small else 0,
  450. LR_LOADFROMFILE)
  451. class NotificationIcon(object):
  452. def __init__(self, iconfilename, tooltip=None):
  453. assert os.path.isfile(unicode(iconfilename)), "{} doesn't exist".format(iconfilename)
  454. self._iconfile = unicode(iconfilename)
  455. self._hicon = LoadIcon(self._iconfile, True)
  456. assert self._hicon, "Failed to load {}".format(iconfilename)
  457. #self._pumpqueue = Queue.Queue()
  458. self._die = False
  459. self._timerid = None
  460. self._uid = uuid.uuid4()
  461. self._tooltip = unicode(tooltip) if tooltip else u''
  462. #self._thread = threading.Thread(target=self._run)
  463. #self._thread.start()
  464. self._info_bubble = None
  465. self.items = []
  466. def _bubble(self, iconinfo):
  467. if self._info_bubble:
  468. info_bubble = self._info_bubble
  469. self._info_bubble = None
  470. message = unicode(self._info_bubble)
  471. iconinfo.uFlags |= NIF_INFO
  472. iconinfo.szInfo = message
  473. iconinfo.szInfoTitle = message
  474. iconinfo.dwInfoFlags = NIIF_INFO
  475. iconinfo.union.uTimeout = 10000
  476. Shell_NotifyIcon(NIM_MODIFY, ctypes.pointer(iconinfo))
  477. def _run(self):
  478. self.WM_TASKBARCREATED = ctypes.windll.user32.RegisterWindowMessageW(u'TaskbarCreated')
  479. self._windowproc = WNDPROC(self._callback)
  480. self._hwnd = GenerateDummyWindow(self._windowproc, str(self._uid))
  481. iconinfo = NOTIFYICONDATA()
  482. iconinfo.hWnd = self._hwnd
  483. iconinfo.uID = 100
  484. iconinfo.uFlags = NIF_ICON | NIF_SHOWTIP | NIF_MESSAGE | (NIF_TIP if self._tooltip else 0)
  485. iconinfo.uCallbackMessage = WM_MENUCOMMAND
  486. iconinfo.hIcon = self._hicon
  487. iconinfo.szTip = self._tooltip
  488. Shell_NotifyIcon(NIM_ADD, ctypes.pointer(iconinfo))
  489. self.iconinfo = iconinfo
  490. PostMessage(self._hwnd, WM_NULL, 0, 0)
  491. message = MSG()
  492. last_time = -1
  493. ret = None
  494. while not self._die:
  495. try:
  496. ret = GetMessage(ctypes.pointer(message), 0, 0, 0)
  497. TranslateMessage(ctypes.pointer(message))
  498. DispatchMessage(ctypes.pointer(message))
  499. except Exception, err:
  500. # print "NotificationIcon error", err, message
  501. message = MSG()
  502. time.sleep(0.125)
  503. print "Icon thread stopped, removing icon..."
  504. Shell_NotifyIcon(NIM_DELETE, ctypes.cast(ctypes.pointer(iconinfo), ctypes.POINTER(NOTIFYICONDATA)))
  505. ctypes.windll.user32.DestroyWindow(self._hwnd)
  506. ctypes.windll.user32.DestroyIcon(self._hicon)
  507. def _menu(self):
  508. if not hasattr(self, 'items'):
  509. return
  510. menu = CreatePopupMenu()
  511. func = None
  512. try:
  513. iidx = 1000
  514. defaultitem = -1
  515. item_map = {}
  516. for fs in self.items:
  517. iidx += 1
  518. if isinstance(fs, basestring):
  519. if fs and not fs.strip('-_='):
  520. AppendMenu(menu, MF_SEPARATOR, iidx, fs)
  521. else:
  522. AppendMenu(menu, MF_STRING | MF_GRAYED, iidx, fs)
  523. elif isinstance(fs, tuple):
  524. if callable(fs[0]):
  525. itemstring = fs[0]()
  526. else:
  527. itemstring = unicode(fs[0])
  528. flags = MF_STRING
  529. if itemstring.startswith("!"):
  530. itemstring = itemstring[1:]
  531. defaultitem = iidx
  532. if itemstring.startswith("+"):
  533. itemstring = itemstring[1:]
  534. flags = flags | MF_CHECKED
  535. itemcallable = fs[1]
  536. item_map[iidx] = itemcallable
  537. if itemcallable is False:
  538. flags = flags | MF_DISABLED
  539. elif not callable(itemcallable):
  540. flags = flags | MF_GRAYED
  541. AppendMenu(menu, flags, iidx, itemstring)
  542. if defaultitem != -1:
  543. SetMenuDefaultItem(menu, defaultitem, 0)
  544. pos = POINT()
  545. GetCursorPos(ctypes.pointer(pos))
  546. PostMessage(self._hwnd, WM_NULL, 0, 0)
  547. SetForegroundWindow(self._hwnd)
  548. ti = TrackPopupMenu(menu, TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, pos.x, pos.y, 0, self._hwnd, None)
  549. if ti in item_map:
  550. func = item_map[ti]
  551. PostMessage(self._hwnd, WM_NULL, 0, 0)
  552. finally:
  553. DestroyMenu(menu)
  554. if func: func()
  555. def clicked(self):
  556. self._menu()
  557. def _callback(self, hWnd, msg, wParam, lParam):
  558. # Check if the main thread is still alive
  559. if msg == WM_TIMER:
  560. if not any(thread.getName() == 'MainThread' and thread.isAlive()
  561. for thread in threading.enumerate()):
  562. self._die = True
  563. elif msg == WM_MENUCOMMAND and lParam == WM_LBUTTONUP:
  564. self.clicked()
  565. elif msg == WM_MENUCOMMAND and lParam == WM_RBUTTONUP:
  566. self._menu()
  567. elif msg == self.WM_TASKBARCREATED: # Explorer restarted, add the icon again.
  568. Shell_NotifyIcon(NIM_ADD, ctypes.pointer(self.iconinfo))
  569. else:
  570. return DefWindowProc(hWnd, msg, wParam, lParam)
  571. return 1
  572. def die(self):
  573. self._die = True
  574. PostMessage(self._hwnd, WM_NULL, 0, 0)
  575. time.sleep(0.2)
  576. try:
  577. Shell_NotifyIcon(NIM_DELETE, self.iconinfo)
  578. except Exception, err:
  579. print "Icon remove error", err
  580. ctypes.windll.user32.DestroyWindow(self._hwnd)
  581. ctypes.windll.user32.DestroyIcon(self._hicon)
  582. def pump(self):
  583. try:
  584. while not self._pumpqueue.empty():
  585. callable = self._pumpqueue.get(False)
  586. callable()
  587. except queue_Empty:
  588. pass
  589. def announce(self, text):
  590. self._info_bubble = text
  591. def hideConsole():
  592. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  593. def showConsole():
  594. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 1)
  595. def hasConsole():
  596. return ctypes.windll.kernel32.GetConsoleWindow() != 0
  597. if __name__ == "__main__":
  598. import time
  599. def greet():
  600. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  601. print "Hello"
  602. def quit():
  603. ni._die = True
  604. def announce():
  605. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 1)
  606. ni.announce("Hello there")
  607. def clicked():
  608. ni.announce("Hello")
  609. def dynamicTitle():
  610. return "!The time is: %s" % time.time()
  611. ni = NotificationIcon(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../trayicon.ico'), "ZeroNet 0.2.9")
  612. ni.items = [
  613. (dynamicTitle, False),
  614. ('Hello', greet),
  615. ('Title', False),
  616. ('!Default', greet),
  617. ('+Popup bubble', announce),
  618. 'Nothing',
  619. '--',
  620. ('Quit', quit)
  621. ]
  622. ni.clicked = clicked
  623. import atexit
  624. @atexit.register
  625. def goodbye():
  626. print "You are now leaving the Python sector."
  627. ni._run()