From fc728beff8435268018fd03f16682d13732ae37e Mon Sep 17 00:00:00 2001 From: weishaupt <1+weishaupt@noreply.localhost> Date: Fri, 6 Nov 2026 11:08:21 +0000 Subject: [PATCH] Upload files to "/" --- autostart.go | 133 +++++ go.mod | 3 + main.go | 1363 ++++++++++++++++++++++++++++++++++++++++++++++++++ pos.go | 182 +++++++ tray.go | 643 ++++++++++++++++++++++++ 5 files changed, 2324 insertions(+) create mode 100644 autostart.go create mode 100644 go.mod create mode 100644 main.go create mode 100644 pos.go create mode 100644 tray.go diff --git a/autostart.go b/autostart.go new file mode 100644 index 0000000..5896bba --- /dev/null +++ b/autostart.go @@ -0,0 +1,133 @@ +package main + +// Start with Windows: a per-user entry in the Run list, toggled from the +// right-click menu. No administrator rights needed. + +import ( + "os" + "strings" + "syscall" + "time" + "unsafe" +) + +var ( + advapi32 = syscall.NewLazyDLL("advapi32.dll") + pRegOpenKeyEx = advapi32.NewProc("RegOpenKeyExW") + pRegSetValueEx = advapi32.NewProc("RegSetValueExW") + pRegQueryValueEx = advapi32.NewProc("RegQueryValueExW") + pRegDeleteValue = advapi32.NewProc("RegDeleteValueW") + pRegCloseKey = advapi32.NewProc("RegCloseKey") + pGetAsyncKeyState = syscall.NewLazyDLL("user32.dll").NewProc("GetAsyncKeyState") +) + +const ( + hkeyCurrentUser = 0x80000001 + keyQuerySet = 0x0003 // KEY_QUERY_VALUE | KEY_SET_VALUE + regSZ = 1 + vkShift = 0x10 + + menuAutostartID = 31 + runKeyPath = `Software\Microsoft\Windows\CurrentVersion\Run` + runValueName = "MirrorBar" +) + +func openRunKey() (uintptr, bool) { + var key uintptr + path := u16(runKeyPath) + r, _, _ := pRegOpenKeyEx.Call(hkeyCurrentUser, uintptr(unsafe.Pointer(path)), 0, keyQuerySet, + uintptr(unsafe.Pointer(&key))) + return key, r == 0 +} + +// autostartCommand is what Windows runs at sign-in: this program, with the +// self-closing safety timer turned off. +func autostartCommand() string { + exe, err := os.Executable() + if err != nil { + return "" + } + return `"` + exe + `" --forever` +} + +func autostartValue() (string, bool) { + key, ok := openRunKey() + if !ok { + return "", false + } + defer pRegCloseKey.Call(key) + + name := u16(runValueName) + var typ uint32 + var buf [1024]uint16 + size := uint32(len(buf) * 2) + r, _, _ := pRegQueryValueEx.Call(key, uintptr(unsafe.Pointer(name)), 0, + uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))) + if r != 0 || typ != regSZ || size > uint32(len(buf)*2) { + return "", false + } + return syscall.UTF16ToString(buf[:size/2]), true +} + +func autostartEnabled() bool { + _, ok := autostartValue() + return ok +} + +func setAutostart(on bool) { + key, ok := openRunKey() + if !ok { + return + } + defer pRegCloseKey.Call(key) + + name := u16(runValueName) + if !on { + pRegDeleteValue.Call(key, uintptr(unsafe.Pointer(name))) + return + } + cmd := autostartCommand() + if cmd == "" { + return + } + data, err := syscall.UTF16FromString(cmd) + if err != nil { + return + } + pRegSetValueEx.Call(key, uintptr(unsafe.Pointer(name)), 0, regSZ, + uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)*2)) +} + +// refreshAutostartPath keeps the sign-in entry pointing at the copy of the +// program that was run most recently, so a new version in a new folder takes +// over. It does nothing if start with Windows is off. +func refreshAutostartPath() { + cur, ok := autostartValue() + if !ok { + return + } + if want := autostartCommand(); want != "" && !strings.EqualFold(cur, want) { + setAutostart(true) + } +} + +// shiftHeld is the escape hatch: hold Shift while the program starts and it +// exits at once without touching the taskbar. +func shiftHeld() bool { + r, _, _ := pGetAsyncKeyState.Call(vkShift) + return r&0x8000 != 0 +} + +// waitForTaskbar gives Explorer time to create the real taskbar at sign-in. +func waitForTaskbar(max time.Duration) uintptr { + deadline := time.Now().Add(max) + for { + if tb := findTaskbar(); tb != 0 { + return tb + } + if time.Now().After(deadline) { + return 0 + } + time.Sleep(300 * time.Millisecond) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..23c8473 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module mirrorbar + +go 1.24 diff --git a/main.go b/main.go new file mode 100644 index 0000000..385783f --- /dev/null +++ b/main.go @@ -0,0 +1,1363 @@ +// MirrorBar proof of concept, version 3. +// +// Hides the real Windows taskbar and puts up a replacement bar laid out in +// mirror image around the exact center of the screen: +// +// left of center: Start button against the center line, open apps as small +// icons growing leftward from it (oldest window nearest Start) +// right of center: clock against the center line +// +// The bar is drawn as a per-pixel transparent window. Right click the bar to +// pick how see-through the background is (Clear, Light, Medium, Solid). +// +// Not built yet: battery, volume, wifi and the hidden icons arrow on the +// right side of the clock. +// +// Safety: +// - By default it closes itself after 10 minutes and restores the real taskbar. +// Pass --forever, or run it under a file name containing "forever", to turn that off. +// - Right click the bar, or press Ctrl+Alt+Q, to exit and restore. +// - Run restore_taskbar.exe (the same program under that name) or pass +// --restore to bring the real taskbar back if anything goes wrong. +package main + +import ( + "math" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +func init() { runtime.LockOSThread() } + +// Extra Win32 calls used by the app right-click menu. +var ( + pIsZoomed = syscall.NewLazyDLL("user32.dll").NewProc("IsZoomed") + pGetWindowThreadProcessId = syscall.NewLazyDLL("user32.dll").NewProc("GetWindowThreadProcessId") + pOpenProcess = syscall.NewLazyDLL("kernel32.dll").NewProc("OpenProcess") + pCloseHandle = syscall.NewLazyDLL("kernel32.dll").NewProc("CloseHandle") + pQueryFullProcessImage = syscall.NewLazyDLL("kernel32.dll").NewProc("QueryFullProcessImageNameW") + pShellExecute = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW") +) + +const ( + wmSysCommand = 0x0112 + + scSize = 0xF000 + scMove = 0xF010 + scMinimize = 0xF020 + scMaximize = 0xF030 + scRestore = 0xF120 + + wsMaximizeBox = 0x00010000 + wsMinimizeBox = 0x00020000 + wsThickFrame = 0x00040000 + + mfGrayed = 0x0003 // MF_GRAYED | MF_DISABLED + + menuNewWindowID = 3 + menuFileLocID = 4 + menuRestoreID = 5 + menuMoveID = 6 + menuSizeID = 7 + menuMinimizeID = 8 + menuMaximizeID = 9 +) + +var ( + user32 = syscall.NewLazyDLL("user32.dll") + gdi32 = syscall.NewLazyDLL("gdi32.dll") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + shell32 = syscall.NewLazyDLL("shell32.dll") + dwmapi = syscall.NewLazyDLL("dwmapi.dll") + + pRegisterClassEx = user32.NewProc("RegisterClassExW") + pCreateWindowEx = user32.NewProc("CreateWindowExW") + pDefWindowProc = user32.NewProc("DefWindowProcW") + pGetMessage = user32.NewProc("GetMessageW") + pTranslateMessage = user32.NewProc("TranslateMessage") + pDispatchMessage = user32.NewProc("DispatchMessageW") + pPostQuitMessage = user32.NewProc("PostQuitMessage") + pDestroyWindow = user32.NewProc("DestroyWindow") + pShowWindow = user32.NewProc("ShowWindow") + pFindWindow = user32.NewProc("FindWindowW") + pIsWindowVisible = user32.NewProc("IsWindowVisible") + pIsIconic = user32.NewProc("IsIconic") + pSetTimer = user32.NewProc("SetTimer") + pKillTimer = user32.NewProc("KillTimer") + pBeginPaint = user32.NewProc("BeginPaint") + pEndPaint = user32.NewProc("EndPaint") + pGetClientRect = user32.NewProc("GetClientRect") + pGetWindowRect = user32.NewProc("GetWindowRect") + pUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow") + pFillRect = user32.NewProc("FillRect") + pDrawText = user32.NewProc("DrawTextW") + pDrawIconEx = user32.NewProc("DrawIconEx") + pGetSystemMetrics = user32.NewProc("GetSystemMetrics") + pMoveWindow = user32.NewProc("MoveWindow") + pRegisterWindowMessage = user32.NewProc("RegisterWindowMessageW") + pRegisterHotKey = user32.NewProc("RegisterHotKey") + pUnregisterHotKey = user32.NewProc("UnregisterHotKey") + pKeybdEvent = user32.NewProc("keybd_event") + pLoadCursor = user32.NewProc("LoadCursorW") + pTrackMouseEvent = user32.NewProc("TrackMouseEvent") + pGetCursorPos = user32.NewProc("GetCursorPos") + pCreatePopupMenu = user32.NewProc("CreatePopupMenu") + pAppendMenu = user32.NewProc("AppendMenuW") + pTrackPopupMenu = user32.NewProc("TrackPopupMenu") + pDestroyMenu = user32.NewProc("DestroyMenu") + pSetForegroundWindow = user32.NewProc("SetForegroundWindow") + pGetForegroundWindow = user32.NewProc("GetForegroundWindow") + pSetProcessDPIAware = user32.NewProc("SetProcessDPIAware") + pGetDC = user32.NewProc("GetDC") + pReleaseDC = user32.NewProc("ReleaseDC") + pEnumWindows = user32.NewProc("EnumWindows") + pGetWindow = user32.NewProc("GetWindow") + pGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW") + pGetWindowTextLength = user32.NewProc("GetWindowTextLengthW") + pGetWindowText = user32.NewProc("GetWindowTextW") + pGetClassName = user32.NewProc("GetClassNameW") + pGetClassLongPtr = user32.NewProc("GetClassLongPtrW") + pSendMessageTimeout = user32.NewProc("SendMessageTimeoutW") + pPostMessage = user32.NewProc("PostMessageW") + pCreateSolidBrush = gdi32.NewProc("CreateSolidBrush") + pDeleteObject = gdi32.NewProc("DeleteObject") + pCreateFont = gdi32.NewProc("CreateFontW") + pSelectObject = gdi32.NewProc("SelectObject") + pSetBkMode = gdi32.NewProc("SetBkMode") + pSetTextColor = gdi32.NewProc("SetTextColor") + pCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC") + pCreateDIBSection = gdi32.NewProc("CreateDIBSection") + pGdiFlush = gdi32.NewProc("GdiFlush") + pDeleteDC = gdi32.NewProc("DeleteDC") + pGetDeviceCaps = gdi32.NewProc("GetDeviceCaps") + pGetModuleHandle = kernel32.NewProc("GetModuleHandleW") + pCreateMutex = kernel32.NewProc("CreateMutexW") + pSHAppBarMessage = shell32.NewProc("SHAppBarMessage") + pDwmGetWindowAttribute = dwmapi.NewProc("DwmGetWindowAttribute") +) + +const ( + wmDestroy = 0x0002 + wmClose = 0x0010 + wmPaint = 0x000F + wmSettingChange = 0x001A + wmEraseBkgnd = 0x0014 + wmEndSession = 0x0016 + wmGetIcon = 0x007F + wmDisplayChange = 0x007E + wmTimer = 0x0113 + wmMouseMove = 0x0200 + wmLButtonUp = 0x0202 + wmRButtonUp = 0x0205 + wmMouseLeave = 0x02A3 + wmHotkey = 0x0312 + wmUser = 0x0400 + + wsPopup = 0x80000000 + wsVisible = 0x10000000 + wsExToolWindow = 0x00000080 + wsExTopmost = 0x00000008 + wsExLayered = 0x00080000 + wsExNoActivate = 0x08000000 + wsExAppWindow = 0x00040000 + + swHide = 0 + swMinimize = 6 + swShowNA = 8 + swRestore = 9 + + abmNew = 0 + abmRemove = 1 + abmQueryPos = 2 + abmSetPos = 3 + abmGetState = 4 + abmSetState = 10 + abeBottom = 3 + abnPosChanged = 1 + absAutoHide = 1 + absAlwaysOnTop = 2 + + modAlt = 0x0001 + modControl = 0x0002 + vkLWin = 0x5B + keyUp = 0x0002 + + tmeLeave = 0x00000002 + + tpmRightButton = 0x0002 + tpmBottomAlign = 0x0020 + tpmReturnCmd = 0x0100 + mfChecked = 0x0008 + mfSeparator = 0x0800 + + dtLeft = 0x0000 + dtCenter = 0x0001 + dtVCenter = 0x0004 + dtSingleLine = 0x0020 + dtNoPrefix = 0x0800 + + transparent = 1 + logPixelsX = 88 + smCxScreen = 0 + smCyScreen = 1 + idcArrow = 32512 + diNormal = 0x0003 + gwOwner = 4 + dwmaCloaked = 14 + smtoAbort = 0x0002 + ulwAlpha = 0x0002 + + errorAlreadyExists = 183 + + timerID = 1 + hotkeyID = 1 + menuExitID = 1 + menuCloseID = 2 + menuLevelBase = 11 + autoQuitDef = 10 * time.Minute + + // Colors as they sit in the bitmap (0xRRGGBB). The draw code uses these + // exact colors so the alpha pass can tell background from foreground. + colBg = 22<<16 | 22<<8 | 26 + colHStart = 58<<16 | 58<<8 | 68 + colHApp = 40<<16 | 40<<8 | 48 + colActive = 52<<16 | 52<<8 | 62 +) + +type rect struct{ Left, Top, Right, Bottom int32 } +type point struct{ X, Y int32 } +type size struct{ CX, CY int32 } + +type blendFunction struct { + Op, Flags, Alpha, Format byte +} + +type bitmapInfoHeader struct { + Size uint32 + Width int32 + Height int32 + Planes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter int32 + YPelsPerMeter int32 + ClrUsed uint32 + ClrImportant uint32 +} + +type wndClassEx struct { + Size uint32 + Style uint32 + WndProc uintptr + ClsExtra int32 + WndExtra int32 + Instance uintptr + Icon uintptr + Cursor uintptr + Background uintptr + MenuName *uint16 + ClassName *uint16 + IconSm uintptr +} + +type msg struct { + Hwnd uintptr + Message uint32 + WParam uintptr + LParam uintptr + Time uint32 + Pt point +} + +type paintStruct struct { + Hdc uintptr + Erase int32 + Rc rect + Restore int32 + IncUpdate int32 + Reserved [32]byte +} + +type appBarData struct { + Size uint32 + Hwnd uintptr + CallbackMsg uint32 + Edge uint32 + Rc rect + LParam uintptr +} + +type trackMouseEvent struct { + Size uint32 + Flags uint32 + HwndTrack uintptr + HoverTime uint32 +} + +// appWin is one open window shown as an icon button on the left side of the bar. +type appWin struct { + hwnd uintptr + title string + icon uintptr +} + +type alphaLevel struct { + name string + alpha int +} + +var alphaLevels = []alphaLevel{ + {"Clear", 3}, + {"Light", 70}, + {"Medium", 140}, + {"Solid", 255}, +} + +var ( + hwndMain uintptr + callbackMsg uint32 = wmUser + 1 + taskbarCreated uint32 + hoverStart bool + hoverApp = -1 + trackingMouse bool + scale float64 = 1 + barHeight int32 + fontTime uintptr + fontDate uintptr + fontApp uintptr + startedAt time.Time + autoQuit time.Duration + tick int + restored bool + bgAlpha = 70 + + apps []appWin + enumFound []appWin + enumCb uintptr + lastFgSeen uintptr +) + +func u16(s string) *uint16 { + p, _ := syscall.UTF16PtrFromString(s) + return p +} + +func rgb(r, g, b int) uintptr { return uintptr(r | g<<8 | b<<16) } + +func px(v float64) int32 { return int32(v*scale + 0.5) } + +// neg turns a small negative number into the form Win32 index arguments expect. +func neg(n int) uintptr { return uintptr(n) } + +func hasArg(name string) bool { + for _, a := range os.Args[1:] { + if strings.EqualFold(a, name) { + return true + } + } + return false +} + +func dataDir() string { + base := os.Getenv("LOCALAPPDATA") + if base == "" { + base = os.TempDir() + } + return filepath.Join(base, "MirrorBar") +} + +// ---------- settings ---------- + +func alphaFile() string { return filepath.Join(dataDir(), "alpha.txt") } + +func loadAlpha() { + b, err := os.ReadFile(alphaFile()) + if err != nil { + return + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || n < 3 || n > 255 { + return + } + bgAlpha = n +} + +func saveAlpha() { + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(alphaFile(), []byte(strconv.Itoa(bgAlpha)), 0o644) +} + +// ---------- real taskbar handling ---------- + +func findTaskbar() uintptr { + h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16("Shell_TrayWnd"))), 0) + return h +} + +func appBar(message uintptr, abd *appBarData) uintptr { + abd.Size = uint32(unsafe.Sizeof(*abd)) + r, _, _ := pSHAppBarMessage.Call(message, uintptr(unsafe.Pointer(abd))) + return r +} + +func stateFile() string { return filepath.Join(dataDir(), "state.txt") } + +func saveOriginalState(owner uintptr) { + f := stateFile() + if _, err := os.Stat(f); err == nil { + return // a state is already saved from an earlier run, keep the true original + } + abd := appBarData{Hwnd: owner} + st := appBar(abmGetState, &abd) + _ = os.MkdirAll(filepath.Dir(f), 0o755) + _ = os.WriteFile(f, []byte(strconv.Itoa(int(st))), 0o644) +} + +func loadOriginalState() uintptr { + b, err := os.ReadFile(stateFile()) + if err != nil { + return absAlwaysOnTop + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil { + return absAlwaysOnTop + } + return uintptr(n) +} + +func setTaskbarState(owner uintptr, state uintptr) { + abd := appBarData{Hwnd: owner, LParam: state} + appBar(abmSetState, &abd) +} + +func hideTaskbar() { + tb := findTaskbar() + if tb == 0 { + return + } + vis, _, _ := pIsWindowVisible.Call(tb) + if vis != 0 { + pShowWindow.Call(tb, swHide) + } +} + +// restoreAll brings the real taskbar back exactly as it was. +func restoreAll() { + tb := findTaskbar() + if tb != 0 { + setTaskbarState(tb, loadOriginalState()) + pShowWindow.Call(tb, swShowNA) + } + _ = os.Remove(stateFile()) + restored = true +} + +// ---------- open windows ---------- + +func collectWindow(hwnd uintptr) { + if hwnd == hwndMain { + return + } + vis, _, _ := pIsWindowVisible.Call(hwnd) + if vis == 0 { + return + } + owner, _, _ := pGetWindow.Call(hwnd, gwOwner) + if owner != 0 { + return + } + ex, _, _ := pGetWindowLongPtr.Call(hwnd, neg(-20)) + if ex&wsExToolWindow != 0 && ex&wsExAppWindow == 0 { + return + } + var cloaked uint32 + pDwmGetWindowAttribute.Call(hwnd, dwmaCloaked, uintptr(unsafe.Pointer(&cloaked)), 4) + if cloaked != 0 { + return + } + n, _, _ := pGetWindowTextLength.Call(hwnd) + if n == 0 { + return + } + var cls [128]uint16 + cn, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 128) + switch syscall.UTF16ToString(cls[:cn]) { + case "Progman", "Shell_TrayWnd", "Shell_SecondaryTrayWnd", "Windows.UI.Core.CoreWindow": + return + } + var tb [512]uint16 + tn, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) + enumFound = append(enumFound, appWin{hwnd: hwnd, title: syscall.UTF16ToString(tb[:tn])}) +} + +func fetchIcon(hwnd uintptr) uintptr { + var res uintptr + for _, which := range []uintptr{2, 0, 1} { + res = 0 + pSendMessageTimeout.Call(hwnd, wmGetIcon, which, 0, smtoAbort, 40, uintptr(unsafe.Pointer(&res))) + if res != 0 { + return res + } + } + for _, idx := range []int{-34, -14} { + r, _, _ := pGetClassLongPtr.Call(hwnd, neg(idx)) + if r != 0 { + return r + } + } + return 0 +} + +// refreshApps re-reads the open windows, keeping existing buttons in their +// places and adding new windows at the far end. Returns true if anything changed. +func refreshApps(refreshIcons bool) bool { + enumFound = enumFound[:0] + pEnumWindows.Call(enumCb, 0) + + present := make(map[uintptr]appWin, len(enumFound)) + for _, f := range enumFound { + present[f.hwnd] = f + } + var next []appWin + for _, a := range apps { + if f, ok := present[a.hwnd]; ok { + a.title = f.title + next = append(next, a) + delete(present, a.hwnd) + } + } + for _, f := range enumFound { + if _, ok := present[f.hwnd]; ok { + next = append(next, f) + } + } + for i := range next { + if next[i].icon == 0 || refreshIcons { + if ic := fetchIcon(next[i].hwnd); ic != 0 { + next[i].icon = ic + } + } + } + + // Titles change constantly (browser tabs, documents) but nothing on the + // bar shows them, so only a change in which windows exist, or their icons, + // counts as a change. + changed := len(next) != len(apps) + if !changed { + for i := range next { + if next[i].hwnd != apps[i].hwnd || next[i].icon != apps[i].icon { + changed = true + break + } + } + } + apps = next + return changed +} + +func activateApp(idx int) { + if idx < 0 || idx >= len(apps) { + return + } + h := apps[idx].hwnd + fg, _, _ := pGetForegroundWindow.Call() + iconic, _, _ := pIsIconic.Call(h) + switch { + case iconic != 0: + pShowWindow.Call(h, swRestore) + pSetForegroundWindow.Call(h) + case h == fg: + pShowWindow.Call(h, swMinimize) + default: + pSetForegroundWindow.Call(h) + } +} + +// ---------- our bar ---------- + +func startWidth() int32 { return px(52) } +func clockWidth() int32 { return px(140) } + +func screenSize() (int32, int32) { + w, _, _ := pGetSystemMetrics.Call(smCxScreen) + h, _, _ := pGetSystemMetrics.Call(smCyScreen) + return int32(w), int32(h) +} + +// pillWidth is the width the bar needs: the wider of the two halves, doubled so +// the bar stays a mirror image around the center, plus a little padding. +func pillWidth() int32 { + sw, _ := screenSize() + left := startWidth() + int32(len(apps))*px(36) + items := trayItems(0, 1) + right := items[len(items)-1].r.Right + half := max(left, right) + px(16) + if limit := sw/2 - px(4); half > limit { + half = limit + } + return half * 2 +} + +// barGap is the space left under the pill so it stands off the screen edge. +func barGap() int32 { return px(6) } + +func positionBar(hwnd uintptr) { + pw, ph := pillSize() + if !customPos { + sw, sh := screenSize() + edge := uintptr(abeBottom) + if vertical { + edge = abeRight + } + abd := appBarData{Hwnd: hwnd, Edge: uint32(edge), Rc: rect{0, 0, sw, sh}} + appBar(abmQueryPos, &abd) + if vertical { + abd.Rc.Left = abd.Rc.Right - barHeight - barGap() + } else { + abd.Rc.Top = abd.Rc.Bottom - barHeight - barGap() + } + appBar(abmSetPos, &abd) + } + x, y := pillPos(pw, ph) + pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 1) + redraw(hwnd) +} + +// appRects lays the app buttons out leftward from the Start button. +// Button 0 sits against Start; each later one is further left. If there are +// too many to fit, the buttons shrink to a minimum width and the oldest run +// off the left edge. +func appRects(clientW, clientH int32) []rect { + n := int32(len(apps)) + if n == 0 { + return nil + } + right := clientW/2 - startWidth() + avail := right - px(8) + bw := px(36) + if avail/n < bw { + bw = avail / n + } + if bw < px(24) { + bw = px(24) + } + rects := make([]rect, n) + for i := int32(0); i < n; i++ { + r := right - i*bw + rects[i] = rect{r - bw, 0, r, clientH} + } + return rects +} + +// clientSize is the size of the bar in the horizontal layout (length, thickness), +// whichever way the real window is turned. +func clientSize(hwnd uintptr) (int32, int32) { + var rc rect + pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc))) + if vertical { + return rc.Bottom - rc.Top, rc.Right - rc.Left + } + return rc.Right - rc.Left, rc.Bottom - rc.Top +} + +func appIndexAt(hwnd uintptr, x int32) int { + w, h := clientSize(hwnd) + for i, r := range appRects(w, h) { + if x >= r.Left && x < r.Right { + return i + } + } + return -1 +} + +func fill(hdc uintptr, r rect, color uintptr) { + b, _, _ := pCreateSolidBrush.Call(color) + pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b) + pDeleteObject.Call(b) +} + +func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) { + w := u16(s) + pDrawText.Call(hdc, uintptr(unsafe.Pointer(w)), ^uintptr(0), uintptr(unsafe.Pointer(&r)), format) +} + +func drawText(hdc uintptr, s string, r rect) { + drawTextFmt(hdc, s, r, dtCenter|dtVCenter|dtSingleLine|dtNoPrefix) +} + +// makeFont uses plain antialiasing (not ClearType) because ClearType's colored +// edges look wrong on a transparent window. +func makeFont(height int32, weight int) uintptr { + f, _, _ := pCreateFont.Call( + uintptr(-height), 0, 0, 0, uintptr(weight), 0, 0, 0, + 1, 0, 0, 4, 0, uintptr(unsafe.Pointer(u16("Segoe UI")))) + return f +} + +func drawLogo(hdc uintptr, r rect) { + sq := px(8) + gap := px(2) + total := sq*2 + gap + x := r.Left + (r.Right-r.Left-total)/2 + y := r.Top + (r.Bottom-r.Top-total)/2 + c := rgb(0, 120, 212) + fill(hdc, rect{x, y, x + sq, y + sq}, c) + fill(hdc, rect{x + sq + gap, y, x + total, y + sq}, c) + fill(hdc, rect{x, y + sq + gap, x + sq, y + total}, c) + fill(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c) +} + +func drawClock(hdc uintptr, r rect) { + now := time.Now() + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(245, 245, 245)) + // Time and date on one line, like "11:32 PM 11/5/2026". + old, _, _ := pSelectObject.Call(hdc, fontTime) + drawText(hdc, now.Format("3:04 PM 1/2/2006"), r) + pSelectObject.Call(hdc, old) +} + +// drawApps draws each open window as a small icon only, no label. +func drawApps(hdc uintptr, w, h int32) { + rects := appRects(w, h) + if len(rects) == 0 { + return + } + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(245, 245, 245)) + old, _, _ := pSelectObject.Call(hdc, fontApp) + + for i, r := range rects { + if i >= len(apps) { + break + } + a := apps[i] + inner := rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)} + if i == hoverApp { + fill(hdc, inner, rgb(40, 40, 48)) + } + + if !vertical { + drawAppGlyph(hdc, inner, a) + } + } + pSelectObject.Call(hdc, old) +} + +// drawAppGlyph draws one app's small icon (or its first letter) centered in r. +func drawAppGlyph(hdc uintptr, r rect, a appWin) { + isz := px(16) // the small taskbar icon size + if a.icon != 0 { + cx, cy := center(r) + pDrawIconEx.Call(hdc, uintptr(cx-isz/2), uintptr(cy-isz/2), a.icon, uintptr(isz), uintptr(isz), 0, 0, diNormal) + } else if rs := []rune(a.title); len(rs) > 0 { + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(245, 245, 245)) + old, _, _ := pSelectObject.Call(hdc, fontApp) + drawText(hdc, strings.ToUpper(string(rs[0])), r) + pSelectObject.Call(hdc, old) + } +} + +func premul(c uint32, a uint32) uint32 { + r := (c >> 16 & 0xFF) * a / 255 + g := (c >> 8 & 0xFF) * a / 255 + b := (c & 0xFF) * a / 255 + return a<<24 | r<<16 | g<<8 | b +} + +// redraw paints the whole bar into a 32 bit bitmap, sets each pixel's +// transparency (background pixels get the chosen see-through level, everything +// drawn on top stays solid) and hands it to Windows as a layered window. +// A vertical bar is drawn horizontally first and then turned a quarter turn; +// the icons and symbols are then drawn again upright on top. +func redraw(hwnd uintptr) { + if hwnd == 0 { + return + } + // Shrink or grow the pill to fit what is in it, staying centered where it is. + pw, ph := pillSize() + var crc rect + pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&crc))) + if (crc.Right != pw || crc.Bottom != ph) && !dragging { + x, y := pillPos(pw, ph) + pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 0) + } + w, h := clientSize(hwnd) + if w <= 0 || h <= 0 { + return + } + + screen, _, _ := pGetDC.Call(0) + defer pReleaseDC.Call(0, screen) + mem, _, _ := pCreateCompatibleDC.Call(screen) + defer pDeleteDC.Call(mem) + + bmi := bitmapInfoHeader{Width: w, Height: -h, Planes: 1, BitCount: 32} + bmi.Size = uint32(unsafe.Sizeof(bmi)) + var bits unsafe.Pointer + bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0, + uintptr(unsafe.Pointer(&bits)), 0, 0) + if bmp == 0 || bits == nil { + return + } + defer pDeleteObject.Call(bmp) + old, _, _ := pSelectObject.Call(mem, bmp) + defer pSelectObject.Call(mem, old) + + rc := rect{0, 0, w, h} + fill(mem, rc, rgb(22, 22, 26)) + cx := w / 2 + sr := rect{cx - startWidth(), 0, cx, h} + if hoverStart { + fill(mem, sr, rgb(58, 58, 68)) + } + drawLogo(mem, sr) + drawApps(mem, w, h) + drawTray(mem, w, h) + pGdiFlush.Call() + + // The finished picture: same as above for a horizontal bar. + fmem, fbits, fw, fh := mem, bits, w, h + if vertical { + fw, fh = h, w + bmiV := bitmapInfoHeader{Width: fw, Height: -fh, Planes: 1, BitCount: 32} + bmiV.Size = uint32(unsafe.Sizeof(bmiV)) + var bitsV unsafe.Pointer + bmpV, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmiV)), 0, + uintptr(unsafe.Pointer(&bitsV)), 0, 0) + if bmpV == 0 || bitsV == nil { + return + } + defer pDeleteObject.Call(bmpV) + memV, _, _ := pCreateCompatibleDC.Call(screen) + defer pDeleteDC.Call(memV) + oldV, _, _ := pSelectObject.Call(memV, bmpV) + defer pSelectObject.Call(memV, oldV) + + src := unsafe.Slice((*uint32)(bits), int(w)*int(h)) + dst := unsafe.Slice((*uint32)(bitsV), int(w)*int(h)) + for y := int32(0); y < h; y++ { + for x := int32(0); x < w; x++ { + dst[int(x)*int(fw)+int(h-1-y)] = src[int(y)*int(w)+int(x)] + } + } + // Icons and symbols go back on upright. + for i, r := range appRects(w, h) { + if i < len(apps) { + drawAppGlyph(memV, mapRect(rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)}, h), apps[i]) + } + } + for _, it := range trayItems(w, h) { + r := mapRect(it.r, h) + switch it.kind { + case trayBattery: + drawBattery(memV, r) + case trayVolume: + drawVolume(memV, r) + case trayWifi: + drawNetwork(memV, r) + case trayChevron: + drawChevron(memV, r) + } + } + pGdiFlush.Call() + fmem, fbits = memV, bitsV + } + + pix := unsafe.Slice((*uint32)(fbits), int(fw)*int(fh)) + a := uint32(bgAlpha) + hoverA := max(a, 120) + activeA := max(a, 150) + length := float64(max(fw, fh)) + rad := float64(min(fw, fh)) / 2 + for i, p := range pix { + c := p & 0x00FFFFFF + // Pill shape: how much of this pixel is inside the rounded ends. + along := float64(i%int(fw)) + 0.5 + across := float64(i/int(fw)) + 0.5 + if vertical { + along, across = across, along + } + da := 0.0 + if along < rad { + da = rad - along + } else if along > length-rad { + da = along - (length - rad) + } + cov := rad - math.Hypot(da, across-rad) + 0.5 + cov = math.Max(0, math.Min(1, cov)) + sc := func(v uint32) uint32 { return uint32(float64(v) * cov) } + switch c { + case colBg: + pix[i] = premul(c, sc(a)) + case colHStart, colHApp: + pix[i] = premul(c, sc(hoverA)) + case colActive: + pix[i] = premul(c, sc(activeA)) + default: + pix[i] = premul(c, sc(255)) + } + } + + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + dst := point{wr.Left, wr.Top} + sz := size{fw, fh} + src := point{0, 0} + blend := blendFunction{Op: 0, Flags: 0, Alpha: 255, Format: 1} // AC_SRC_OVER, AC_SRC_ALPHA + pUpdateLayeredWindow.Call(hwnd, screen, + uintptr(unsafe.Pointer(&dst)), uintptr(unsafe.Pointer(&sz)), + fmem, uintptr(unsafe.Pointer(&src)), 0, + uintptr(unsafe.Pointer(&blend)), ulwAlpha) +} + +func inStart(hwnd uintptr, x int32) bool { + w, _ := clientSize(hwnd) + cx := w / 2 + return x >= cx-startWidth() && x < cx +} + +func tapWinKey() { + pKeybdEvent.Call(vkLWin, 0, 0, 0) + pKeybdEvent.Call(vkLWin, 0, keyUp, 0) +} + +// windowExePath returns the full path of the program that owns a window, or "" +// when it can't be found or the window belongs to the Windows app host +// (Settings, Store apps), which can't be launched again by path. +func windowExePath(h uintptr) string { + var pid uint32 + pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) + if pid == 0 { + return "" + } + proc, _, _ := pOpenProcess.Call(0x1000, 0, uintptr(pid)) // PROCESS_QUERY_LIMITED_INFORMATION + if proc == 0 { + return "" + } + defer pCloseHandle.Call(proc) + var buf [1024]uint16 + n := uint32(len(buf)) + r, _, _ := pQueryFullProcessImage.Call(proc, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n))) + if r == 0 { + return "" + } + path := syscall.UTF16ToString(buf[:n]) + if strings.EqualFold(filepath.Base(path), "ApplicationFrameHost.exe") { + return "" + } + return path +} + +func shellOpen(file, params string) { + var p uintptr + if params != "" { + p = uintptr(unsafe.Pointer(u16(params))) + } + pShellExecute.Call(0, uintptr(unsafe.Pointer(u16("open"))), uintptr(unsafe.Pointer(u16(file))), p, 0, 1) +} + +// showMenu pops up the right-click menu. Over an app icon it starts with that +// window's own options (the same ones its title bar menu has), then the +// MirrorBar settings. Over empty bar it shows only the settings. +func showMenu(hwnd uintptr, appIdx int, trayKind int) { + menu, _, _ := pCreatePopupMenu.Call() + add := func(flags uintptr, id uintptr, text string) { + pAppendMenu.Call(menu, flags, id, uintptr(unsafe.Pointer(u16(text)))) + } + sep := func() { pAppendMenu.Call(menu, mfSeparator, 0, 0) } + + // Remember which window this menu is for. The list can change while the + // menu is open, so don't go back to the index afterwards. + var target uintptr + var exe string + if appIdx >= 0 && appIdx < len(apps) { + target = apps[appIdx].hwnd + + title := []rune(apps[appIdx].title) + text := string(title) + if len(title) > 40 { + text = string(title[:40]) + "..." + } + add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&")) + sep() + + exe = windowExePath(target) + if exe != "" { + add(0, menuNewWindowID, "Open new window") + add(0, menuFileLocID, "Open file location") + sep() + } + + style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE + iconic, _, _ := pIsIconic.Call(target) + zoomed, _, _ := pIsZoomed.Call(target) + normal := iconic == 0 && zoomed == 0 + enabled := func(ok bool) uintptr { + if ok { + return 0 + } + return mfGrayed + } + add(enabled(!normal), menuRestoreID, "Restore") + add(enabled(normal), menuMoveID, "Move") + add(enabled(normal && style&wsThickFrame != 0), menuSizeID, "Size") + add(enabled(iconic == 0 && style&wsMinimizeBox != 0), menuMinimizeID, "Minimize") + add(enabled(zoomed == 0 && style&wsMaximizeBox != 0), menuMaximizeID, "Maximize") + sep() + add(0, menuCloseID, "Close window") + sep() + } + + if appIdx < 0 { + addTrayMenu(add, sep, trayKind) + } + + for i, l := range alphaLevels { + var flags uintptr + if bgAlpha == l.alpha { + flags = mfChecked + } + add(flags, uintptr(menuLevelBase+i), "Background: "+l.name) + } + sep() + orientText := "Switch to vertical" + if vertical { + orientText = "Switch to horizontal" + } + add(0, menuOrientID, orientText) + var posFlags uintptr + if !customPos { + posFlags = mfGrayed + } + add(posFlags, menuResetPosID, "Reset position to bottom center") + var autoFlags uintptr + if autostartEnabled() { + autoFlags = mfChecked + } + add(autoFlags, menuAutostartID, "Start MirrorBar when I sign in") + sep() + add(0, menuExitID, "Exit MirrorBar and restore taskbar") + + var pt point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&pt))) + pSetForegroundWindow.Call(hwnd) + cmd, _, _ := pTrackPopupMenu.Call(menu, tpmRightButton|tpmBottomAlign|tpmReturnCmd, + uintptr(pt.X), uintptr(pt.Y), 0, hwnd, 0) + pDestroyMenu.Call(menu) + + sysCommands := map[uintptr]uintptr{ + menuRestoreID: scRestore, + menuMoveID: scMove, + menuSizeID: scSize, + menuMinimizeID: scMinimize, + menuMaximizeID: scMaximize, + } + + switch { + case cmd == menuExitID: + pDestroyWindow.Call(hwnd) + case cmd == menuResetPosID: + resetPos(hwnd) + case cmd == menuOrientID: + vertical = !vertical + saveOrient() + resetPos(hwnd) + case cmd == menuCloseID && target != 0: + pPostMessage.Call(target, wmClose, 0, 0) + case cmd == menuNewWindowID && exe != "": + shellOpen(exe, "") + case cmd == menuFileLocID && exe != "": + shellOpen("explorer.exe", `/select,"`+exe+`"`) + case target != 0 && sysCommands[cmd] != 0: + if cmd != menuMinimizeID { + pSetForegroundWindow.Call(target) + } + pPostMessage.Call(target, wmSysCommand, sysCommands[cmd], 0) + case handleTrayCommand(cmd): + redraw(hwnd) + case cmd >= menuLevelBase && cmd < menuLevelBase+uintptr(len(alphaLevels)): + bgAlpha = alphaLevels[cmd-menuLevelBase].alpha + saveAlpha() + redraw(hwnd) + } +} + +func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { + defer func() { + if r := recover(); r != nil { + restoreAll() + os.Exit(1) + } + }() + + switch uint32(m) { + case wmEraseBkgnd: + return 1 + case wmPaint: + // The bar is a layered window drawn by redraw(); just mark this paint as handled. + var ps paintStruct + pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + return 0 + case wmTimer: + hideTaskbar() + tick++ + changed := refreshApps(tick%16 == 0) + if tick%4 == 0 && refreshStatus(tick%16 == 0) { + changed = true + } + fg, _, _ := pGetForegroundWindow.Call() + if fg != lastFgSeen { + lastFgSeen = fg + changed = true + } + if changed || tick%4 == 0 { + redraw(hwnd) + } + if autoQuit > 0 && time.Since(startedAt) >= autoQuit { + pDestroyWindow.Call(hwnd) + } + return 0 + case wmMouseMove: + x := alongClient(lparam) + overStart := inStart(hwnd, x) + overApp := appIndexAt(hwnd, x) + overTray := trayAt(hwnd, x) + if overStart != hoverStart || overApp != hoverApp || overTray != hoverTray { + hoverStart = overStart + hoverApp = overApp + hoverTray = overTray + redraw(hwnd) + } + if !trackingMouse { + tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd} + pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) + trackingMouse = true + } + return 0 + case wmMouseLeave: + trackingMouse = false + if hoverStart || hoverApp != -1 || hoverTray != 0 { + hoverStart = false + hoverApp = -1 + hoverTray = 0 + redraw(hwnd) + } + return 0 + case wmLButtonUp: + x := alongClient(lparam) + if inStart(hwnd, x) { + tapWinKey() + } else if idx := appIndexAt(hwnd, x); idx >= 0 { + activateApp(idx) + redraw(hwnd) + } else if k := trayAt(hwnd, x); k != 0 { + trayClick(k) + } + return 0 + case wmRButtonUp: + x := alongClient(lparam) + showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) + return 0 + case wmMouseWheel: + // Scrolling over the volume icon changes the volume. The wheel + // position arrives in screen coordinates, so make it relative to the bar. + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + if trayAt(hwnd, x) == trayVolume { + nudgeVolume(int(int16(wparam>>16)) / 120) + redraw(hwnd) + } + return 0 + case wmNcHitTest: + // Buttons act as buttons; everything else on the pill drags it. + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + if inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 { + return htClient + } + return htCaption + case wmNcLButtonDblClk: + return 0 // a double click on the drag area must not maximize the pill + case wmNcRButtonUp: + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) + return 0 + case wmEnterSizeMove: + dragging = true + return 0 + case wmExitSizeMove: + finishDrag(hwnd) + return 0 + case wmHotkey: + if wparam == hotkeyID { + pDestroyWindow.Call(hwnd) + } + return 0 + case wmDisplayChange, wmSettingChange: + positionBar(hwnd) + return 0 + case wmEndSession: + if wparam != 0 { + restoreAll() + } + return 0 + case wmDestroy: + abd := appBarData{Hwnd: hwnd} + appBar(abmRemove, &abd) + pKillTimer.Call(hwnd, timerID) + pUnregisterHotKey.Call(hwnd, hotkeyID) + restoreAll() + pPostQuitMessage.Call(0) + return 0 + } + + if uint32(m) == callbackMsg { + if wparam == abnPosChanged { + positionBar(hwnd) + } + return 0 + } + if taskbarCreated != 0 && uint32(m) == taskbarCreated { + // Explorer restarted and rebuilt the taskbar: hide it again. + tb := findTaskbar() + if tb != 0 { + setTaskbarState(tb, absAutoHide|absAlwaysOnTop) + } + hideTaskbar() + positionBar(hwnd) + return 0 + } + + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +} + +func main() { + // Launched under the name restore_taskbar.exe, or with --restore: just bring it back. + name := strings.ToLower(filepath.Base(os.Args[0])) + if hasArg("--restore") || strings.Contains(name, "restore") { + restoreAll() + return + } + + // Escape hatch: hold Shift while it starts (for example at sign-in) to skip it entirely. + if shiftHeld() { + return + } + + pSetProcessDPIAware.Call() + + // Only one copy at a time. + _, _, err := pCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(u16("Local\\MirrorBarPoC")))) + if errno, ok := err.(syscall.Errno); ok && errno == errorAlreadyExists { + return + } + + loadAlpha() + loadPos() + loadOrient() + + hdc, _, _ := pGetDC.Call(0) + dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX) + pReleaseDC.Call(0, hdc) + if dpi > 0 { + scale = float64(dpi) / 96.0 + } + barHeight = px(36) + fontTime = makeFont(px(13), 400) + fontDate = makeFont(px(11), 400) + fontApp = makeFont(px(12), 600) + + autoQuit = autoQuitDef + if hasArg("--forever") || strings.Contains(name, "forever") { + autoQuit = 0 + } + startedAt = time.Now() + + enumCb = syscall.NewCallback(func(hwnd, lparam uintptr) uintptr { + collectWindow(hwnd) + return 1 + }) + + inst, _, _ := pGetModuleHandle.Call(0) + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + className := u16("MirrorBarWindow") + wc := wndClassEx{ + WndProc: syscall.NewCallback(wndProc), + Instance: inst, + Cursor: cursor, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + + taskbarCreated64, _, _ := pRegisterWindowMessage.Call(uintptr(unsafe.Pointer(u16("TaskbarCreated")))) + taskbarCreated = uint32(taskbarCreated64) + + sw, sh := screenSize() + hwnd, _, _ := pCreateWindowEx.Call( + wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, + uintptr(unsafe.Pointer(className)), + uintptr(unsafe.Pointer(u16("MirrorBar"))), + wsPopup|wsVisible, + 0, uintptr(sh-barHeight), uintptr(sw), uintptr(barHeight), + 0, 0, inst, 0) + if hwnd == 0 { + return + } + hwndMain = hwnd + refreshAutostartPath() + + // Hotkey: Ctrl+Alt+Q exits and restores. + pRegisterHotKey.Call(hwnd, hotkeyID, modControl|modAlt, 'Q') + + // Release the real taskbar's reserved screen space, remember how it was, hide it. + tb := waitForTaskbar(12 * time.Second) + if tb != 0 { + saveOriginalState(hwnd) + setTaskbarState(hwnd, absAutoHide|absAlwaysOnTop) + time.Sleep(300 * time.Millisecond) + hideTaskbar() + } + + // Register as an app bar so maximized windows stop above us. + if customPos { + appbarOn = false + } else { + abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg} + appBar(abmNew, &abd) + } + + pCoInitializeEx.Call(0, 2) // COINIT_APARTMENTTHREADED, needed for the volume control + refreshStatus(true) + refreshApps(true) + positionBar(hwnd) + pSetTimer.Call(hwnd, timerID, 250, 0) + + var m msg + for { + r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0) + if int32(r) <= 0 { + break + } + pTranslateMessage.Call(uintptr(unsafe.Pointer(&m))) + pDispatchMessage.Call(uintptr(unsafe.Pointer(&m))) + } + if !restored { + restoreAll() + } +} diff --git a/pos.go b/pos.go new file mode 100644 index 0000000..70c4543 --- /dev/null +++ b/pos.go @@ -0,0 +1,182 @@ +package main + +// Moving the pill: the whole background of the bar is a drag area, the dragged +// spot is remembered, and "Reset position" in the menu goes back to the default +// (bottom center, a few pixels above the screen edge). + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "unsafe" +) + +const ( + menuResetPosID = 32 + menuOrientID = 33 + abeRight = 2 + + wmNcHitTest = 0x0084 + wmNcLButtonDblClk = 0x00A3 + wmNcRButtonUp = 0x00A5 + wmEnterSizeMove = 0x0231 + wmExitSizeMove = 0x0232 + htClient = 1 + htCaption = 2 +) + +var ( + customPos bool // false means the default spot + customCX int32 // center of the pill when moved + customY int32 // vertical center of the pill when moved + vertical bool // true: the bar stands up and down at the right edge + dragging bool + appbarOn = true +) + +func posFile() string { return filepath.Join(dataDir(), "pos.txt") } + +func loadPos() { + b, err := os.ReadFile(posFile()) + if err != nil { + return + } + parts := strings.Split(strings.TrimSpace(string(b)), ",") + if len(parts) != 2 { + return + } + cx, e1 := strconv.Atoi(parts[0]) + y, e2 := strconv.Atoi(parts[1]) + if e1 != nil || e2 != nil { + return + } + customPos, customCX, customY = true, int32(cx), int32(y) +} + +func savePos() { + if !customPos { + _ = os.Remove(posFile()) + return + } + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(posFile(), []byte(strconv.Itoa(int(customCX))+","+strconv.Itoa(int(customY))), 0o644) +} + +func orientFile() string { return filepath.Join(dataDir(), "orient.txt") } + +func loadOrient() { + b, err := os.ReadFile(orientFile()) + vertical = err == nil && strings.TrimSpace(string(b)) == "vertical" +} + +func saveOrient() { + _ = os.MkdirAll(dataDir(), 0o755) + v := "horizontal" + if vertical { + v = "vertical" + } + _ = os.WriteFile(orientFile(), []byte(v), 0o644) +} + +// Everything is laid out as if the bar were horizontal (a "length" along the +// bar and a "thickness" across it). Vertical mode turns the picture a quarter +// turn, so mouse positions are converted back to a position along the bar. +func alongClient(lparam uintptr) int32 { + x := int32(int16(lparam & 0xFFFF)) + y := int32(int16(lparam >> 16 & 0xFFFF)) + if vertical { + return y + } + return x +} + +func alongScreen(lparam uintptr, wr rect) int32 { + x := int32(int16(lparam&0xFFFF)) - wr.Left + y := int32(int16(lparam>>16&0xFFFF)) - wr.Top + if vertical { + return y + } + return x +} + +// pillSize is the real window size for the current orientation. +func pillSize() (int32, int32) { + l := pillWidth() + if vertical { + return barHeight, l + } + return l, barHeight +} + +// mapRect turns a rectangle from the horizontal layout into the same spot on +// the turned bar (a clockwise quarter turn; t is the bar's thickness). +func mapRect(r rect, t int32) rect { + return rect{t - r.Bottom, r.Left, t - r.Top, r.Right} +} + +func clampI(v, lo, hi int32) int32 { + if hi < lo { + hi = lo + } + return max(lo, min(hi, v)) +} + +// pillPos is where the top-left of a pill of width nw belongs. +func pillPos(pw, ph int32) (int32, int32) { + if !customPos { + return defaultPos(pw, ph) + } + sw, sh := screenSize() + x := clampI(customCX-pw/2, 0, sw-pw) + y := clampI(customY-ph/2, 0, sh-ph) + return x, y +} + +func defaultPos(pw, ph int32) (int32, int32) { + sw, sh := screenSize() + if vertical { + return sw - pw - barGap(), (sh - ph) / 2 + } + return (sw - pw) / 2, sh - ph - barGap() +} + +// finishDrag runs when a drag ends: remember the new spot, or snap back to the +// default if it was dropped right on it. +func finishDrag(hwnd uintptr) { + dragging = false + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + dx, dy := defaultPos(wr.Right-wr.Left, wr.Bottom-wr.Top) + if abs32(wr.Left-dx) <= px(8) && abs32(wr.Top-dy) <= px(8) { + resetPos(hwnd) + return + } + customPos, customCX, customY = true, (wr.Left+wr.Right)/2, (wr.Top+wr.Bottom)/2 + savePos() + if appbarOn { + // A floating bar no longer reserves screen space. + abd := appBarData{Hwnd: hwnd} + appBar(abmRemove, &abd) + appbarOn = false + } + redraw(hwnd) +} + +func abs32(v int32) int32 { + if v < 0 { + return -v + } + return v +} + +func resetPos(hwnd uintptr) { + customPos = false + savePos() + if !appbarOn { + abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg} + appBar(abmNew, &abd) + appbarOn = true + } + positionBar(hwnd) +} diff --git a/tray.go b/tray.go new file mode 100644 index 0000000..92bef25 --- /dev/null +++ b/tray.go @@ -0,0 +1,643 @@ +package main + +// The right side of the bar, in mirror order from the center line outward: +// clock, battery, volume, network, hidden icons arrow. + +import ( + "net" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + trayClock = iota + 1 + trayBattery + trayVolume + trayWifi + trayChevron +) + +const ( + netNone = iota + netWired + netWifi +) + +const ( + wmMouseWheel = 0x020A + + vkReturn = 0x0D + vkVolumeMute = 0xAD + vkVolumeDown = 0xAE + vkVolumeUp = 0xAF + + menuDateID = 21 + menuPowerID = 22 + menuSoundID = 23 + menuNetID = 24 + menuMuteID = 25 +) + +var ( + gdi32t = syscall.NewLazyDLL("gdi32.dll") + ole32 = syscall.NewLazyDLL("ole32.dll") + wlanapi = syscall.NewLazyDLL("wlanapi.dll") + kern32t = syscall.NewLazyDLL("kernel32.dll") + + pMoveToEx = gdi32t.NewProc("MoveToEx") + pLineTo = gdi32t.NewProc("LineTo") + pCreatePen = gdi32t.NewProc("CreatePen") + pPolygon = gdi32t.NewProc("Polygon") + pGetStockObject = gdi32t.NewProc("GetStockObject") + pCoInitializeEx = ole32.NewProc("CoInitializeEx") + pCoCreateInstance = ole32.NewProc("CoCreateInstance") + pWlanOpenHandle = wlanapi.NewProc("WlanOpenHandle") + pWlanCloseHandle = wlanapi.NewProc("WlanCloseHandle") + pWlanEnumInterfaces = wlanapi.NewProc("WlanEnumInterfaces") + pWlanQueryInterface = wlanapi.NewProc("WlanQueryInterface") + pWlanFreeMemory = wlanapi.NewProc("WlanFreeMemory") + pGetSystemPowerStatus = kern32t.NewProc("GetSystemPowerStatus") +) + +// Current values shown on the right side. +var ( + battPct = -1 // -1 means this PC has no battery, so no battery icon + battCharging bool + battAC bool + volLevel float32 + volMuted bool + volOK bool + netKind = netNone + netQuality int + hoverTray int +) + +// ---------- layout ---------- + +type trayItem struct { + kind int + r rect +} + +func trayItems(clientW, clientH int32) []trayItem { + x := clientW / 2 + var out []trayItem + add := func(kind int, w int32) { + out = append(out, trayItem{kind, rect{x, 0, x + w, clientH}}) + x += w + } + add(trayClock, clockWidth()) + if battPct >= 0 { + add(trayBattery, px(36)) + } + add(trayVolume, px(36)) + add(trayWifi, px(36)) + add(trayChevron, px(28)) + return out +} + +func trayAt(hwnd uintptr, x int32) int { + w, h := clientSize(hwnd) + for _, it := range trayItems(w, h) { + if x >= it.r.Left && x < it.r.Right { + return it.kind + } + } + return 0 +} + +// ---------- drawing ---------- + +func polyline(hdc uintptr, pts []point, width int32, color uintptr) { + if len(pts) < 2 { + return + } + pen, _, _ := pCreatePen.Call(0, uintptr(width), color) + old, _, _ := pSelectObject.Call(hdc, pen) + pMoveToEx.Call(hdc, uintptr(pts[0].X), uintptr(pts[0].Y), 0) + for _, p := range pts[1:] { + pLineTo.Call(hdc, uintptr(p.X), uintptr(p.Y)) + } + pSelectObject.Call(hdc, old) + pDeleteObject.Call(pen) +} + +func polygon(hdc uintptr, pts []point, color uintptr) { + brush, _, _ := pCreateSolidBrush.Call(color) + nullPen, _, _ := pGetStockObject.Call(8) // NULL_PEN + oldBrush, _, _ := pSelectObject.Call(hdc, brush) + oldPen, _, _ := pSelectObject.Call(hdc, nullPen) + pPolygon.Call(hdc, uintptr(unsafe.Pointer(&pts[0])), uintptr(len(pts))) + pSelectObject.Call(hdc, oldPen) + pSelectObject.Call(hdc, oldBrush) + pDeleteObject.Call(brush) +} + +func center(r rect) (int32, int32) { return (r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2 } + +func drawBattery(hdc uintptr, r rect) { + cx, cy := center(r) + bw, bh := px(18), px(9) + nubW, nubH := px(2), px(4) + t := px(1) + left := cx - (bw+nubW)/2 + top := cy - bh/2 + white := rgb(245, 245, 245) + + fill(hdc, rect{left, top, left + bw, top + t}, white) + fill(hdc, rect{left, top + bh - t, left + bw, top + bh}, white) + fill(hdc, rect{left, top, left + t, top + bh}, white) + fill(hdc, rect{left + bw - t, top, left + bw, top + bh}, white) + fill(hdc, rect{left + bw, cy - nubH/2, left + bw + nubW, cy + nubH/2}, white) + + col := white + switch { + case battCharging || battAC: + col = rgb(90, 205, 120) + case battPct <= 15: + col = rgb(235, 80, 80) + } + gap := t + px(1) + inner := bw - 2*gap + fw := inner * int32(battPct) / 100 + if battPct > 0 && fw < px(1) { + fw = px(1) + } + fill(hdc, rect{left + gap, top + gap, left + gap + fw, top + bh - gap}, col) +} + +func drawVolume(hdc uintptr, r rect) { + cx, cy := center(r) + white, dim := rgb(245, 245, 245), rgb(110, 110, 120) + x0 := cx - px(9) + + fill(hdc, rect{x0, cy - px(3), x0 + px(3), cy + px(3)}, white) + polygon(hdc, []point{ + {x0 + px(3), cy - px(3)}, + {x0 + px(7), cy - px(6)}, + {x0 + px(7), cy + px(6)}, + {x0 + px(3), cy + px(3)}, + }, white) + + active := 0 + if volOK && !volMuted { + switch { + case volLevel > 0.66: + active = 3 + case volLevel > 0.33: + active = 2 + case volLevel > 0: + active = 1 + } + } + heights := []int32{px(5), px(9), px(13)} + for i := 0; i < 3; i++ { + bx := x0 + px(10) + int32(i)*px(3) + col := dim + if i < active { + col = white + } + fill(hdc, rect{bx, cy - heights[i]/2, bx + px(2), cy + heights[i]/2}, col) + } + if volMuted { + polyline(hdc, []point{{x0 + px(10), cy - px(4)}, {x0 + px(17), cy + px(4)}}, px(1), white) + polyline(hdc, []point{{x0 + px(10), cy + px(4)}, {x0 + px(17), cy - px(4)}}, px(1), white) + } +} + +func drawNetwork(hdc uintptr, r rect) { + cx, cy := center(r) + white, dim := rgb(245, 245, 245), rgb(110, 110, 120) + + if netKind == netWired { + t := px(1) + l, tp := cx-px(7), cy-px(6) + w, h := px(14), px(9) + fill(hdc, rect{l, tp, l + w, tp + t}, white) + fill(hdc, rect{l, tp + h - t, l + w, tp + h}, white) + fill(hdc, rect{l, tp, l + t, tp + h}, white) + fill(hdc, rect{l + w - t, tp, l + w, tp + h}, white) + fill(hdc, rect{cx - px(1), tp + h, cx + px(1), tp + h + px(3)}, white) + fill(hdc, rect{cx - px(4), tp + h + px(3), cx + px(4), tp + h + px(4)}, white) + return + } + + bars := 0 + if netKind == netWifi { + bars = (netQuality + 24) / 25 + if bars < 1 { + bars = 1 + } + if bars > 4 { + bars = 4 + } + } + heights := []int32{px(3), px(5), px(8), px(11)} + baseY := cy + px(5) + x := cx - px(7) + for i := 0; i < 4; i++ { + col := dim + if i < bars { + col = white + } + fill(hdc, rect{x, baseY - heights[i], x + px(2), baseY}, col) + x += px(4) + } + if netKind == netNone { + polyline(hdc, []point{{cx + px(1), cy - px(6)}, {cx + px(8), cy + px(1)}}, px(1), white) + polyline(hdc, []point{{cx + px(1), cy + px(1)}, {cx + px(8), cy - px(6)}}, px(1), white) + } +} + +func drawChevron(hdc uintptr, r rect) { + cx, cy := center(r) + polyline(hdc, []point{{cx - px(5), cy + px(2)}, {cx, cy - px(3)}, {cx + px(5), cy + px(2)}}, + px(1.5), rgb(245, 245, 245)) +} + +func drawTray(hdc uintptr, w, h int32) { + for _, it := range trayItems(w, h) { + if it.kind == hoverTray { + fill(hdc, rect{it.r.Left + px(1), it.r.Top + px(3), it.r.Right - px(1), it.r.Bottom - px(3)}, rgb(40, 40, 48)) + } + if vertical && it.kind != trayClock { + continue // a vertical bar draws these upright, after turning + } + switch it.kind { + case trayClock: + drawClock(hdc, it.r) + case trayBattery: + drawBattery(hdc, it.r) + case trayVolume: + drawVolume(hdc, it.r) + case trayWifi: + drawNetwork(hdc, it.r) + case trayChevron: + drawChevron(hdc, it.r) + } + } +} + +// ---------- battery ---------- + +type systemPowerStatus struct { + ACLineStatus byte + BatteryFlag byte + BatteryLifePercent byte + SystemStatusFlag byte + BatteryLifeTime uint32 + BatteryFullLifeTime uint32 +} + +func readBattery() (pct int, charging, ac bool) { + var s systemPowerStatus + r, _, _ := pGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&s))) + if r == 0 || s.BatteryFlag == 255 || s.BatteryFlag&128 != 0 || s.BatteryLifePercent > 100 { + return -1, false, false + } + return int(s.BatteryLifePercent), s.BatteryFlag&8 != 0, s.ACLineStatus == 1 +} + +// ---------- volume (Windows Core Audio, called by hand) ---------- + +type guid struct { + D1 uint32 + D2 uint16 + D3 uint16 + D4 [8]byte +} + +var ( + clsidMMDeviceEnumerator = guid{0xBCDE0395, 0xE52F, 0x467C, [8]byte{0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}} + iidIMMDeviceEnumerator = guid{0xA95664D2, 0x9614, 0x4F35, [8]byte{0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}} + iidIAudioEndpointVolume = guid{0x5CDF2C82, 0x841E, 0x4546, [8]byte{0x97, 0x22, 0x0C, 0xF7, 0x40, 0x78, 0x22, 0x9A}} +) + +// vcall calls method number idx of a COM object. +func vcall(obj unsafe.Pointer, idx uintptr, args ...uintptr) uintptr { + vtbl := *(*unsafe.Pointer)(obj) + fn := *(*uintptr)(unsafe.Add(vtbl, idx*unsafe.Sizeof(uintptr(0)))) + all := append([]uintptr{uintptr(obj)}, args...) + r, _, _ := syscall.SyscallN(fn, all...) + return r +} + +func failed(hr uintptr) bool { return int32(hr) < 0 } + +// withEndpointVolume hands f the speakers' volume control, then releases everything. +func withEndpointVolume(f func(vol unsafe.Pointer)) bool { + var enum unsafe.Pointer + hr, _, _ := pCoCreateInstance.Call( + uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), 0, 23, + uintptr(unsafe.Pointer(&iidIMMDeviceEnumerator)), uintptr(unsafe.Pointer(&enum))) + if failed(hr) || enum == nil { + return false + } + defer vcall(enum, 2) // Release + + var dev unsafe.Pointer + // GetDefaultAudioEndpoint(eRender, eConsole) + if failed(vcall(enum, 4, 0, 0, uintptr(unsafe.Pointer(&dev)))) || dev == nil { + return false + } + defer vcall(dev, 2) + + var vol unsafe.Pointer + // Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, &vol) + if failed(vcall(dev, 3, uintptr(unsafe.Pointer(&iidIAudioEndpointVolume)), 23, 0, uintptr(unsafe.Pointer(&vol)))) || vol == nil { + return false + } + defer vcall(vol, 2) + + f(vol) + return true +} + +func readVolume() (level float32, muted bool, ok bool) { + ok = withEndpointVolume(func(vol unsafe.Pointer) { + var l float32 + var m int32 + vcall(vol, 9, uintptr(unsafe.Pointer(&l))) // GetMasterVolumeLevelScalar + vcall(vol, 15, uintptr(unsafe.Pointer(&m))) // GetMute + level, muted = l, m != 0 + }) + return +} + +// ---------- network ---------- + +type wlanIfaceHeader struct { + Count uint32 + Index uint32 +} + +type wlanIfaceInfo struct { + Guid guid + Desc [256]uint16 + State uint32 +} + +type wlanAssoc struct { + SSIDLen uint32 + SSID [32]byte + BssType uint32 + Bssid [6]byte + PhyType uint32 + PhyIndex uint32 + Quality uint32 + RxRate uint32 + TxRate uint32 +} + +type wlanConn struct { + State uint32 + Mode uint32 + Profile [256]uint16 + Assoc wlanAssoc +} + +// wifiState reports whether a Wi-Fi adapter is connected and its signal (0 to 100). +func wifiState() (connected bool, quality int) { + var negotiated uint32 + var client uintptr + if r, _, _ := pWlanOpenHandle.Call(2, 0, uintptr(unsafe.Pointer(&negotiated)), uintptr(unsafe.Pointer(&client))); r != 0 { + return false, 0 + } + defer pWlanCloseHandle.Call(client, 0) + + var list unsafe.Pointer + if r, _, _ := pWlanEnumInterfaces.Call(client, 0, uintptr(unsafe.Pointer(&list))); r != 0 || list == nil { + return false, 0 + } + defer pWlanFreeMemory.Call(uintptr(list)) + + n := int((*wlanIfaceHeader)(list).Count) + first := unsafe.Add(list, unsafe.Sizeof(wlanIfaceHeader{})) + for i := 0; i < n; i++ { + info := (*wlanIfaceInfo)(unsafe.Add(first, uintptr(i)*unsafe.Sizeof(wlanIfaceInfo{}))) + if info.State != 1 { // wlan_interface_state_connected + continue + } + var dataSize uint32 + var data unsafe.Pointer + var valueType uint32 + r, _, _ := pWlanQueryInterface.Call(client, uintptr(unsafe.Pointer(&info.Guid)), + 7, // wlan_intf_opcode_current_connection + 0, uintptr(unsafe.Pointer(&dataSize)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&valueType))) + if r != 0 || data == nil { + continue + } + q := int((*wlanConn)(data).Assoc.Quality) + pWlanFreeMemory.Call(uintptr(data)) + return true, q + } + return false, 0 +} + +// wiredUp reports whether a real wired network adapter has a usable address. +func wiredUp() bool { + ifs, err := net.Interfaces() + if err != nil { + return false + } + skip := []string{"virtual", "vethernet", "vmware", "vbox", "bluetooth", "wsl", "hyper-v", + "loopback", "wi-fi", "wireless", "wlan", "pseudo", "tailscale", "vpn"} + for _, i := range ifs { + if i.Flags&net.FlagUp == 0 || i.Flags&net.FlagLoopback != 0 || len(i.HardwareAddr) == 0 { + continue + } + name := strings.ToLower(i.Name) + bad := false + for _, s := range skip { + if strings.Contains(name, s) { + bad = true + break + } + } + if bad { + continue + } + addrs, _ := i.Addrs() + for _, a := range addrs { + ipn, ok := a.(*net.IPNet) + if !ok { + continue + } + if ip4 := ipn.IP.To4(); ip4 != nil && !(ip4[0] == 169 && ip4[1] == 254) { + return true + } + } + } + return false +} + +func readNetwork() (kind int, quality int) { + if ok, q := wifiState(); ok { + return netWifi, q + } + if wiredUp() { + return netWired, 0 + } + return netNone, 0 +} + +// ---------- refresh ---------- + +// refreshStatus reads battery and volume every call, and the network when full +// is set. Returns true if anything shown on the bar changed. +func refreshStatus(full bool) bool { + changed := false + + pct, ch, ac := readBattery() + if pct != battPct || ch != battCharging || ac != battAC { + battPct, battCharging, battAC = pct, ch, ac + changed = true + } + + lvl, mu, ok := readVolume() + diff := lvl - volLevel + if diff < 0 { + diff = -diff + } + if ok != volOK || mu != volMuted || (ok && diff > 0.004) { + volLevel, volMuted, volOK = lvl, mu, ok + changed = true + } + + if full { + k, q := readNetwork() + if k != netKind || (q+24)/25 != (netQuality+24)/25 { + netKind, netQuality = k, q + changed = true + } else { + netQuality = q + } + } + return changed +} + +// ---------- clicks and menus ---------- + +func tapKey(k uintptr) { + pKeybdEvent.Call(k, 0, 0, 0) + pKeybdEvent.Call(k, 0, keyUp, 0) +} + +func tapChord(mod, k uintptr) { + pKeybdEvent.Call(mod, 0, 0, 0) + pKeybdEvent.Call(k, 0, 0, 0) + pKeybdEvent.Call(k, 0, keyUp, 0) + pKeybdEvent.Call(mod, 0, keyUp, 0) +} + +// trayClick opens the matching Windows panel with its keyboard shortcut. +func trayClick(kind int) { + switch kind { + case trayClock: + tapChord(vkLWin, 'N') // notification center and calendar + case trayBattery, trayVolume, trayWifi: + tapChord(vkLWin, 'A') // quick settings + case trayChevron: + // Win+B moves focus to the notification area; Enter opens the hidden icons. + tapChord(vkLWin, 'B') + time.Sleep(150 * time.Millisecond) + tapKey(vkReturn) + } +} + +// nudgeVolume presses the volume keys, one press per wheel notch. +func nudgeVolume(steps int) { + key := uintptr(vkVolumeUp) + if steps < 0 { + key = vkVolumeDown + steps = -steps + } + for i := 0; i < steps; i++ { + tapKey(key) + } + time.Sleep(60 * time.Millisecond) + refreshStatus(false) +} + +func batteryText() string { + s := "Battery: " + strconv.Itoa(battPct) + "%" + switch { + case battCharging: + s += ", charging" + case battAC: + s += ", plugged in" + } + return s +} + +func volumeText() string { + switch { + case !volOK: + return "Volume: unavailable" + case volMuted: + return "Volume: muted" + } + return "Volume: " + strconv.Itoa(int(volLevel*100+0.5)) + "%" +} + +func networkText() string { + switch netKind { + case netWifi: + return "Wi-Fi: connected, signal " + strconv.Itoa(netQuality) + "%" + case netWired: + return "Ethernet: connected" + } + return "No network connection" +} + +// addTrayMenu adds the entries for the right-side item that was right-clicked. +func addTrayMenu(add func(flags uintptr, id uintptr, text string), sep func(), kind int) { + switch kind { + case trayClock: + add(0, menuDateID, "Adjust date and time") + sep() + case trayBattery: + add(mfGrayed, 0, batteryText()) + add(0, menuPowerID, "Power && battery settings") + sep() + case trayVolume: + add(mfGrayed, 0, volumeText()) + if volMuted { + add(0, menuMuteID, "Unmute") + } else { + add(0, menuMuteID, "Mute") + } + add(0, menuSoundID, "Sound settings") + sep() + case trayWifi: + add(mfGrayed, 0, networkText()) + add(0, menuNetID, "Network && internet settings") + sep() + } +} + +// handleTrayCommand runs a menu choice from addTrayMenu. Returns true if it was one. +func handleTrayCommand(cmd uintptr) bool { + switch cmd { + case menuDateID: + shellOpen("ms-settings:dateandtime", "") + case menuPowerID: + shellOpen("ms-settings:powersleep", "") + case menuSoundID: + shellOpen("ms-settings:sound", "") + case menuNetID: + shellOpen("ms-settings:network", "") + case menuAutostartID: + setAutostart(!autostartEnabled()) + case menuMuteID: + tapKey(vkVolumeMute) + time.Sleep(60 * time.Millisecond) + refreshStatus(false) + default: + return false + } + return true +}