vendor/github.com/tadvi/systray/systray_windows.go

630 lines · 14205 bytes

  1/*
  2 * Copyright (C) 2019 The Systray Authors. All Rights Reserved.
  3 */
  4
  5package systray
  6
  7import (
  8	"errors"
  9	"path/filepath"
 10	"syscall"
 11	"unsafe"
 12)
 13
 14const (
 15	WM_LBUTTONUP     = 0x0202
 16	WM_LBUTTONDBLCLK = 0x0203
 17	WM_RBUTTONUP     = 0x0205
 18	WM_USER          = 0x0400
 19	WM_TRAYICON      = WM_USER + 69
 20
 21	WS_EX_APPWINDOW     = 0x00040000
 22	WS_OVERLAPPEDWINDOW = 0X00000000 | 0X00C00000 | 0X00080000 | 0X00040000 | 0X00020000 | 0X00010000
 23	CW_USEDEFAULT       = 0x80000000
 24
 25	NIM_ADD        = 0x00000000
 26	NIM_MODIFY     = 0x00000001
 27	NIM_DELETE     = 0x00000002
 28	NIM_SETVERSION = 0x00000004
 29
 30	NIF_MESSAGE = 0x00000001
 31	NIF_ICON    = 0x00000002
 32	NIF_TIP     = 0x00000004
 33	NIF_STATE   = 0x00000008
 34	NIF_INFO    = 0x00000010
 35
 36	NIS_HIDDEN = 0x00000001
 37
 38	NIIF_NONE               = 0x00000000
 39	NIIF_INFO               = 0x00000001
 40	NIIF_WARNING            = 0x00000002
 41	NIIF_ERROR              = 0x00000003
 42	NIIF_USER               = 0x00000004
 43	NIIF_NOSOUND            = 0x00000010
 44	NIIF_LARGE_ICON         = 0x00000020
 45	NIIF_RESPECT_QUIET_TIME = 0x00000080
 46	NIIF_ICON_MASK          = 0x0000000F
 47
 48	IMAGE_BITMAP    = 0
 49	IMAGE_ICON      = 1
 50	LR_LOADFROMFILE = 0x00000010
 51	LR_DEFAULTSIZE  = 0x00000040
 52
 53	IDC_ARROW     = 32512
 54	COLOR_WINDOW  = 5
 55	COLOR_BTNFACE = 15
 56
 57	GWLP_USERDATA       = -21
 58	WS_CLIPSIBLINGS     = 0X04000000
 59	WS_EX_CONTROLPARENT = 0X00010000
 60
 61	HWND_MESSAGE       = ^HWND(2)
 62	NOTIFYICON_VERSION = 4
 63
 64	IDI_APPLICATION = 32512
 65	WM_APP          = 32768
 66	WM_COMMAND      = 273
 67
 68	MenuItemMsgID       = WM_APP + 1024
 69	NotifyIconMessageId = WM_APP + iota
 70
 71	MF_STRING       = 0x00000000
 72	MF_ENABLED      = 0x00000000
 73	MF_GRAYED       = 0x00000001
 74	MF_DISABLED     = 0x00000002
 75	MF_SEPARATOR    = 0x00000800
 76	MF_CHECKED      = 0x00000008
 77	MF_MENUBARBREAK = 0x00000020
 78
 79	TPM_LEFTALIGN = 0x0000
 80	WM_NULL       = 0
 81)
 82
 83var (
 84	kernel32         = syscall.MustLoadDLL("kernel32")
 85	GetModuleHandle  = kernel32.MustFindProc("GetModuleHandleW")
 86	GetConsoleWindow = kernel32.MustFindProc("GetConsoleWindow")
 87	GetLastError     = kernel32.MustFindProc("GetLastError")
 88
 89	shell32          = syscall.MustLoadDLL("shell32.dll")
 90	Shell_NotifyIcon = shell32.MustFindProc("Shell_NotifyIconW")
 91
 92	user32 = syscall.MustLoadDLL("user32.dll")
 93
 94	GetMessage       = user32.MustFindProc("GetMessageW")
 95	IsDialogMessage  = user32.MustFindProc("IsDialogMessageW")
 96	TranslateMessage = user32.MustFindProc("TranslateMessage")
 97	DispatchMessage  = user32.MustFindProc("DispatchMessageW")
 98
 99	ShowWindow       = user32.MustFindProc("ShowWindow")
100	UpdateWindow     = user32.MustFindProc("UpdateWindow")
101	DefWindowProc    = user32.MustFindProc("DefWindowProcW")
102	RegisterClassEx  = user32.MustFindProc("RegisterClassExW")
103	GetDesktopWindow = user32.MustFindProc("GetDesktopWindow")
104	CreateWindowEx   = user32.MustFindProc("CreateWindowExW")
105
106	CreatePopupMenu         = user32.MustFindProc("CreatePopupMenu")
107	procAppendMenuW         = user32.MustFindProc("AppendMenuW")
108	procGetCursorPos        = user32.MustFindProc("GetCursorPos")
109	procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow")
110	procTrackPopupMenu      = user32.MustFindProc("TrackPopupMenu")
111	procPostMessage         = user32.MustFindProc("PostMessageW")
112
113	LoadImage  = user32.MustFindProc("LoadImageW")
114	LoadIcon   = user32.MustFindProc("LoadIconW")
115	LoadCursor = user32.MustFindProc("LoadCursorW")
116)
117
118type NOTIFYICONDATA struct {
119	CbSize           uint32
120	HWnd             HWND
121	UID              uint32
122	UFlags           uint32
123	UCallbackMessage uint32
124	HIcon            HICON
125	SzTip            [128]uint16
126	DwState          uint32
127	DwStateMask      uint32
128	SzInfo           [256]uint16
129	UVersion         uint32
130	SzInfoTitle      [64]uint16
131	DwInfoFlags      uint32
132	GuidItem         GUID
133	HBalloonIcon     HICON
134}
135
136type GUID struct {
137	Data1 uint32
138	Data2 uint16
139	Data3 uint16
140	Data4 [8]byte
141}
142
143type WNDCLASSEX struct {
144	CbSize        uint32
145	Style         uint32
146	LpfnWndProc   uintptr
147	CbClsExtra    int32
148	CbWndExtra    int32
149	HInstance     HINSTANCE
150	HIcon         HICON
151	HCursor       HCURSOR
152	HbrBackground HBRUSH
153	LpszMenuName  *uint16
154	LpszClassName *uint16
155	HIconSm       HICON
156}
157
158type MSG struct {
159	HWnd    HWND
160	Message uint32
161	WParam  uintptr
162	LParam  uintptr
163	Time    uint32
164	Pt      POINT
165}
166
167type POINT struct {
168	X, Y int32
169}
170
171type (
172	HANDLE    uintptr
173	HINSTANCE HANDLE
174	HCURSOR   HANDLE
175	HICON     HANDLE
176	HWND      HANDLE
177	HGDIOBJ   HANDLE
178	HBRUSH    HGDIOBJ
179)
180
181type HMENU HANDLE
182
183type WindowProc func(hwnd HWND, msg uint32, wparam, lparam uintptr) uintptr
184
185type MenuItem struct {
186	Label string
187
188	Disabled  bool
189	Checked   bool
190	BarBreak  bool
191	Separator bool
192
193	OnClick func()
194}
195
196type Systray struct {
197	id     uint32
198	hwnd   HWND
199	hinst  HINSTANCE
200	lclick func()
201	rclick func()
202
203	Menu []*MenuItem
204}
205
206func New() (*Systray, error) {
207	ni := &Systray{lclick: func() {}, rclick: func() {}}
208
209	MainClassName := "MainForm"
210	ni.hinst, _ = RegisterWindow(MainClassName, ni.WinProc)
211
212	mhwnd, _, _ := CreateWindowEx.Call(
213		WS_EX_CONTROLPARENT,
214		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(MainClassName))),
215		0,
216		WS_OVERLAPPEDWINDOW|WS_CLIPSIBLINGS,
217		CW_USEDEFAULT,
218		CW_USEDEFAULT,
219		CW_USEDEFAULT,
220		CW_USEDEFAULT,
221		0,
222		0,
223		0,
224		0)
225	if mhwnd == 0 {
226		return nil, errors.New("create main win failed")
227	}
228
229	NotifyIconClassName := "NotifyIconForm"
230	RegisterWindow(NotifyIconClassName, ni.WinProc)
231
232	hwnd, _, _ := CreateWindowEx.Call(
233		0,
234		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(NotifyIconClassName))),
235		0,
236		0,
237		0,
238		0,
239		0,
240		0,
241		uintptr(HWND_MESSAGE),
242		0,
243		0,
244		0)
245	if hwnd == 0 {
246		return nil, errors.New("create notify win failed")
247	}
248
249	ni.hwnd = HWND(hwnd) // Important to keep this inside struct.
250
251	nid := NOTIFYICONDATA{
252		HWnd:             HWND(hwnd),
253		UFlags:           NIF_MESSAGE | NIF_STATE,
254		DwState:          NIS_HIDDEN,
255		DwStateMask:      NIS_HIDDEN,
256		UCallbackMessage: NotifyIconMessageId,
257	}
258	nid.CbSize = uint32(unsafe.Sizeof(nid))
259
260	ret, _, _ := Shell_NotifyIcon.Call(NIM_ADD, uintptr(unsafe.Pointer(&nid)))
261	if ret == 0 {
262		return nil, errors.New("shell notify create failed")
263	}
264
265	nid.UVersion = NOTIFYICON_VERSION
266
267	ret, _, _ = Shell_NotifyIcon.Call(NIM_SETVERSION, uintptr(unsafe.Pointer(&nid)))
268	if ret == 0 {
269		return nil, errors.New("shell notify version failed")
270	}
271
272	ni.id = nid.UID
273	return ni, nil
274}
275
276func (p *Systray) HWND() HWND {
277	return p.hwnd
278}
279
280// AppendMenu add menu item.
281func (p *Systray) AppendMenu(label string, onclick func()) {
282	p.Menu = append(p.Menu, &MenuItem{Label: label, OnClick: onclick})
283}
284
285// AppendSeparator to the menu.
286func (p *Systray) AppendSeparator() {
287	p.Menu = append(p.Menu, &MenuItem{Separator: true})
288}
289
290func (p *Systray) Stop() error {
291	nid := NOTIFYICONDATA{
292		UID:  p.id,
293		HWnd: HWND(p.hwnd),
294	}
295	nid.CbSize = uint32(unsafe.Sizeof(nid))
296
297	ret, _, _ := Shell_NotifyIcon.Call(NIM_DELETE, uintptr(unsafe.Pointer(&nid)))
298	if ret == 0 {
299		return errors.New("shell notify delete failed")
300	}
301	return nil
302}
303
304func MakeIntResource(id uint16) *uint16 {
305	return (*uint16)(unsafe.Pointer(uintptr(id)))
306}
307
308// Show shows custom tray icon.
309func (p *Systray) Show(iconResID uint16, hint string) error {
310	icon, _, _ := LoadIcon.Call(uintptr(p.hinst), uintptr(unsafe.Pointer(MakeIntResource(iconResID))))
311	if icon == 0 {
312		icon, _, _ = LoadIcon.Call(0, uintptr(IDI_APPLICATION))
313	}
314
315	err := p.SetIcon(HICON(icon))
316	if err != nil {
317		return err
318	}
319	err = p.SetTooltip(hint)
320	if err != nil {
321		return err
322	}
323	return p.SetVisible(true)
324}
325
326func loadIconFile(file string) (HICON, error) {
327	path, err := filepath.Abs(file)
328	if err != nil {
329		return 0, err
330	}
331	icon, err := NewIconFromFile(path)
332	if err != nil {
333		return 0, err
334	}
335	return HICON(icon), nil
336}
337
338// ShowCustom shows custom tray icon.
339func (p *Systray) ShowCustom(file string, hint string) error {
340	hicon, err := loadIconFile(file)
341	if err != nil {
342		icon, _, _ := LoadIcon.Call(0, uintptr(IDI_APPLICATION))
343		hicon = HICON(icon)
344	}
345
346	err = p.SetIcon(hicon)
347	if err != nil {
348		return err
349	}
350	err = p.SetTooltip(hint)
351	if err != nil {
352		return err
353	}
354	return p.SetVisible(true)
355}
356
357func (p *Systray) OnClick(fn func()) {
358	p.lclick = fn
359}
360
361func (p *Systray) OnRightClick(fn func()) {
362	p.rclick = fn
363}
364
365func (p *Systray) SetTooltip(tooltip string) error {
366	nid := NOTIFYICONDATA{
367		UID:  p.id,
368		HWnd: HWND(p.hwnd),
369	}
370	nid.CbSize = uint32(unsafe.Sizeof(nid))
371
372	nid.UFlags = NIF_TIP
373	copy(nid.SzTip[:], syscall.StringToUTF16(tooltip))
374
375	ret, _, _ := Shell_NotifyIcon.Call(NIM_MODIFY, uintptr(unsafe.Pointer(&nid)))
376	if ret == 0 {
377		return errors.New("shell notify tooltip failed")
378	}
379	return nil
380}
381
382func (p *Systray) ShowMessage(title, msg string, bigIcon bool) error {
383	nid := NOTIFYICONDATA{
384		UID:  p.id,
385		HWnd: HWND(p.hwnd),
386	}
387	if bigIcon == true {
388		nid.DwInfoFlags = NIIF_USER
389	}
390
391	nid.CbSize = uint32(unsafe.Sizeof(nid))
392
393	nid.UFlags = NIF_INFO
394	copy(nid.SzInfoTitle[:], syscall.StringToUTF16(title))
395	copy(nid.SzInfo[:], syscall.StringToUTF16(msg))
396
397	ret, _, _ := Shell_NotifyIcon.Call(NIM_MODIFY, uintptr(unsafe.Pointer(&nid)))
398	if ret == 0 {
399		return errors.New("shell notify tooltip failed")
400	}
401	return nil
402}
403
404func (p *Systray) SetVisible(visible bool) error {
405	nid := NOTIFYICONDATA{
406		UID:  p.id,
407		HWnd: HWND(p.hwnd),
408	}
409	nid.CbSize = uint32(unsafe.Sizeof(nid))
410
411	nid.UFlags = NIF_STATE
412	nid.DwStateMask = NIS_HIDDEN
413	if !visible {
414		nid.DwState = NIS_HIDDEN
415	}
416
417	ret, _, _ := Shell_NotifyIcon.Call(NIM_MODIFY, uintptr(unsafe.Pointer(&nid)))
418	if ret == 0 {
419		return errors.New("shell notify tooltip failed")
420	}
421	return nil
422}
423
424func (p *Systray) SetIcon(hicon HICON) error {
425	nid := NOTIFYICONDATA{
426		UID:  p.id,
427		HWnd: HWND(p.hwnd),
428	}
429	nid.CbSize = uint32(unsafe.Sizeof(nid))
430
431	nid.UFlags = NIF_ICON
432	if hicon == 0 {
433		nid.HIcon = 0
434	} else {
435		nid.HIcon = hicon
436	}
437
438	ret, _, _ := Shell_NotifyIcon.Call(NIM_MODIFY, uintptr(unsafe.Pointer(&nid)))
439	if ret == 0 {
440		return errors.New("shell notify icon failed")
441	}
442	return nil
443}
444
445func (p *Systray) WinProc(hwnd HWND, msg uint32, wparam, lparam uintptr) uintptr {
446	switch msg {
447	case NotifyIconMessageId:
448		if lparam == WM_LBUTTONUP {
449			p.lclick()
450			if len(p.Menu) > 0 {
451				p.displayMenu(p.Menu)
452			}
453		} else if lparam == WM_RBUTTONUP {
454			p.rclick()
455			if len(p.Menu) > 0 {
456				p.displayMenu(p.Menu)
457			}
458		}
459
460	case WM_COMMAND:
461		cmdMsgID := int(wparam & 0xffff)
462		switch cmdMsgID {
463		default:
464			if cmdMsgID >= MenuItemMsgID && cmdMsgID < (MenuItemMsgID+len(p.Menu)) {
465				itemIndex := cmdMsgID - MenuItemMsgID
466				menuItem := p.Menu[itemIndex]
467				menuItem.OnClick()
468			}
469		}
470	}
471
472	result, _, _ := DefWindowProc.Call(uintptr(hwnd), uintptr(msg), wparam, lparam)
473	return result
474}
475
476func (p *Systray) Run() error {
477	hwnd := p.hwnd
478	var msg MSG
479	for {
480		rt, _, _ := GetMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
481		switch int(rt) {
482		case 0:
483			return nil
484		case -1:
485			return errors.New("run failed")
486		}
487
488		is, _, _ := IsDialogMessage.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&msg)))
489		if is == 0 {
490			TranslateMessage.Call(uintptr(unsafe.Pointer(&msg)))
491			DispatchMessage.Call(uintptr(unsafe.Pointer(&msg)))
492		}
493	}
494	return nil
495}
496
497func (p *Systray) displayMenu(menuItems []*MenuItem) error {
498	ret, _, _ := CreatePopupMenu.Call(0, 0, 0, 0)
499	if ret == 0 {
500		return errors.New("can not create menu")
501	}
502	menu := HMENU(ret)
503
504	for index, item := range menuItems {
505		var ret bool
506		itemID := MenuItemMsgID + index
507		flags := MF_STRING
508		if item.Disabled {
509			flags = flags | MF_GRAYED
510		}
511		if item.Checked {
512			flags = flags | MF_CHECKED
513		}
514		if item.BarBreak {
515			flags = flags | MF_MENUBARBREAK
516		}
517		if item.Separator {
518			flags = flags | MF_SEPARATOR
519		}
520
521		ret = appendMenu(menu, uintptr(flags), uintptr(itemID), item.Label)
522		if ret == false {
523			return errors.New("AppendMenu failed")
524		}
525	}
526
527	x, y, ok := getCursorPos()
528	if ok == false {
529		return errors.New("GetCursorPos failed")
530	}
531
532	if setForegroundWindow(p.hwnd) == false {
533		return errors.New("SetForegroundWindow failed")
534	}
535
536	if trackPopupMenu(menu, TPM_LEFTALIGN, x, y-5, p.hwnd) == false {
537		return errors.New("TrackPopupMenu failed")
538	}
539
540	if ret, _, _ := procPostMessage.Call(uintptr(p.hwnd), uintptr(WM_NULL), 0, 0); ret == 0 {
541		return errors.New("PostMessage failed")
542	}
543	return nil
544}
545
546func trackPopupMenu(menu HMENU, flags uint, x, y int, wnd HWND) bool {
547	ret, _, _ := procTrackPopupMenu.Call(
548		uintptr(menu),
549		uintptr(flags),
550		uintptr(x),
551		uintptr(y),
552		0,
553		uintptr(wnd),
554		0,
555	)
556	return ret != 0
557}
558
559func setForegroundWindow(wnd HWND) bool {
560	ret, _, _ := procSetForegroundWindow.Call(
561		uintptr(wnd),
562	)
563	return ret != 0
564}
565
566func getCursorPos() (x, y int, ok bool) {
567	pt := POINT{}
568	ret, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
569	return int(pt.X), int(pt.Y), ret != 0
570}
571
572func appendMenu(menu HMENU, flags uintptr, id uintptr, text string) bool {
573	ret, _, _ := procAppendMenuW.Call(
574		uintptr(menu),
575		flags,
576		id,
577		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))),
578	)
579	return ret != 0
580}
581
582func NewIconFromFile(filePath string) (uintptr, error) {
583	absFilePath, err := filepath.Abs(filePath)
584	if err != nil {
585		return 0, err
586	}
587	hicon, _, _ := LoadImage.Call(
588		0,
589		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(absFilePath))),
590		IMAGE_ICON,
591		0,
592		0,
593		LR_DEFAULTSIZE|LR_LOADFROMFILE)
594	if hicon == 0 {
595		return 0, errors.New("load image failed: " + filePath)
596	}
597	return hicon, nil
598}
599
600func RegisterWindow(name string, proc WindowProc) (HINSTANCE, error) {
601	hinst, _, _ := GetModuleHandle.Call(0)
602	if hinst == 0 {
603		return 0, errors.New("get module handle failed")
604	}
605	hicon, _, _ := LoadIcon.Call(0, uintptr(IDI_APPLICATION))
606	if hicon == 0 {
607		return 0, errors.New("load icon failed")
608	}
609	hcursor, _, _ := LoadCursor.Call(0, uintptr(IDC_ARROW))
610	if hcursor == 0 {
611		return 0, errors.New("load cursor failed")
612	}
613
614	hi := HINSTANCE(hinst)
615
616	var wc WNDCLASSEX
617	wc.CbSize = uint32(unsafe.Sizeof(wc))
618	wc.LpfnWndProc = syscall.NewCallback(proc)
619	wc.HInstance = hi
620	wc.HIcon = HICON(hicon)
621	wc.HCursor = HCURSOR(hcursor)
622	wc.HbrBackground = COLOR_BTNFACE + 1
623	wc.LpszClassName = syscall.StringToUTF16Ptr(name)
624
625	atom, _, _ := RegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
626	if atom == 0 {
627		return 0, errors.New("register class failed")
628	}
629	return hi, nil
630}