From 3e0fc4e6ec019b16afe8b04c55fac0f1bb6553ef Mon Sep 17 00:00:00 2001 From: weishaupt <1+weishaupt@noreply.localhost> Date: Sun, 8 Nov 2026 19:45:37 +0000 Subject: [PATCH] Combine windows of one program into a counted icon, auto-hide, settings and README, part 2 --- README.md | 124 +++--- autohide.go | 102 +++++ gmflyout.go | 1111 ++++++++++++++++++++++++++------------------------- group.go | 134 +++++++ settings.go | 758 ++++++++++++++++++----------------- 5 files changed, 1243 insertions(+), 986 deletions(-) create mode 100644 autohide.go create mode 100644 group.go diff --git a/README.md b/README.md index b8f9bdd..9199678 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,64 @@ -# MirrorBar+ - -MirrorBar+ is a small Windows 11 taskbar replacement, one exe, no installer, no dependencies. - -The real taskbar is hidden and a see-through pill takes its place. The pill is a mirror image around its center line. To the left of center is the Start button, with your open apps as small icon-only buttons stretching further left. To the right of center is the clock (time and date on one line), then a little sun-and-cloud for the weather, a little newspaper for local news, a little monitor for system stats, battery, volume, wifi and the ^ hidden-icons arrow stretching further right. - -## What it does - -- Transparent pill that is only as wide as what is in it, centered on the screen with a few pixels of space under it. -- Drag it anywhere by its background. It remembers where you put it. Right-click and choose "Reset position to bottom center" to send it home. -- Pull the far left end of the pill (the cursor turns into a double arrow) to shrink the empty space on the left. The center line stays put, and the left side stretches back out as you open more apps. Right-click and choose "Reset bar width" to go back to the mirrored look. -- Right-click and choose "Switch to vertical" to stand it up and down against the right edge of the screen. -- Right-click an app icon for the normal window options (Restore, Move, Size, Minimize, Maximize, Close) plus Open new window and Open file location. -- Drag the app icons and the Windows logo along the left row to reorder them. MirrorBar remembers the order of your apps and the logo's spot. -- Drag the clock, battery, volume, wifi and hidden-icons arrow along the right row to reorder them. That order is remembered. -- Rest the mouse on an app icon for a moment and a live preview of that window pops up beside the bar (minimized windows show their icon instead). Click the preview to switch to that window. -- Right-click an app icon and choose "Pin to MirrorBar" to keep it on the bar. A pinned app that isn't running shows as a launcher: click it to start the program, and when its window opens it takes that spot. Pinning works for normal programs; Store apps can't be pinned. -- "Open notification center" is in the right-click menu. -- Drag files from Explorer onto an app icon and that program opens them, running or pinned. -- "MirrorBar settings..." in the right-click menu opens one window for background opacity, the three colors, icon style, the ZIP code, tickboxes to show or hide the weather, the local news and the system stats, vertical mode, start with Windows, and resetting the position and width. Changes apply as you make them. -- Smooth, outline-free icons and text, even when the pill is see-through. -- Click the storm cloud and a weather panel opens above the bar: the temperature in Fahrenheit, what it feels like, the high and low, humidity, wind, chance of rain, sunrise, sunset, UV index, the moon phase, a looping radar picture of the last hour or so centered on your ZIP code, and the next five days. Click the cloud again, or click anywhere else, and it closes. It needs a ZIP code: type it in "MirrorBar settings..." (a 5 digit US ZIP code) and the weather turns on at once. The forecast comes from Open-Meteo (open-meteo.com, free, no account), the radar map comes from RainViewer and Esri and is only downloaded when you open the panel, and MirrorBar only goes to the internet when a ZIP code is set. The cloud can be dragged along the right row like the other icons. - -- Click the newspaper and a panel of local headlines opens above the bar, newest first, with the outlet and how long ago each ran. Click a headline and it opens in your default browser. It uses the same ZIP code as the weather: the ZIP code is turned into a town name and the headlines are Google News' feed for that town, so someone in 43220 gets Columbus stations and papers and someone in 46750 gets Fort Wayne and Huntington ones. The headlines are only downloaded when a ZIP code is set. Small towns have fewer stories than cities. - -- Click the little speech bubble and Google Messages for web opens in a small window above the bar, so you can read and answer texts without opening a browser tab. The first time, scan the QR code from the Messages app on your phone (Settings, Device pairing) and tick "Remember this computer"; after that it stays signed in. It runs Microsoft Edge in app mode (no tabs, no address bar) with its own private profile folder in `%LOCALAPPDATA%\MirrorBar\messages`, separate from your normal Edge, and goes only to messages.google.com. Once you have paired, MirrorBar quietly starts it in the background about 20 seconds after it launches, keeps the window just off the edge of the screen, and shows the unread count from the window title as a red number on the bubble. Click anywhere else and the window slides away again. Right-click the bubble and choose "Close Messages" to stop the background window and give the memory back. Messages for web only works while your phone is on and connected; that is how Google built it. `messages-titles.txt` in the MirrorBar data folder keeps the first 25 different window titles it has seen, only so the unread badge can be tuned; delete it any time. - -- "Show weather on the bar", "Show local news on the bar", "Show system stats on the bar" and "Show Google Messages on the bar" in the settings window turn each feature off. The icon leaves the bar and nothing is downloaded for it; tick the box again and it comes back. - -- The weather, news and system stats panels are as see-through as the bar itself: set the bar to Clear and the panels go clear too, with only their text, pictures and outline staying solid. Untick "Panels match the bar's transparency" in the settings window to keep the panels solid. - -- Click the little monitor and a panel opens with the usual neofetch information: OS, host, kernel, uptime, resolution, CPU, GPU, memory, each fixed disk, battery and local IP. Click any line to copy it to the clipboard, or click the top of the panel to copy everything as plain text you can paste into other programs. Nothing leaves your PC; it is all read from Windows. -- Pick the color of the Windows logo, the clock, and the battery/volume/wifi/arrow icons from the right-click menu (white, blue, sky blue, green, yellow, orange, red, pink, purple, black). -- "Icon style" in the right-click menu: colorized or grayscale. It applies to the app icons and to the logo, clock and tray icons. -- Background see-through level: Clear, Light, Medium or Solid. -- "Start MirrorBar when I sign in" in the right-click menu. -- Scroll over the speaker to change the volume. Click the clock, battery, volume or wifi for the matching Windows panel. - -## Safety - -- `mirrorbar.exe` quits by itself after 10 minutes and brings the normal taskbar back. `mirrorbar_forever.exe` (or any copy started with `--forever`) does not. -- Ctrl+Alt+Q quits and restores the taskbar. -- Right-click, "Exit MirrorBar and restore taskbar". -- Hold Shift while it launches and it exits at once without touching anything. -- `restore_taskbar.exe` (the same program, renamed) or `--restore` puts the normal taskbar back. - -## Download - -Grab `MirrorBarPlus.zip` from the Releases page. If Windows shows a "protected your PC" warning, right-click the zip, choose Properties, check Unblock, and unzip it after that. - -## Build - -Go 1.24 or newer, standard library only: - -``` -GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-H=windowsgui -s -w" -o mirrorbar.exe . -``` - -Settings are kept in `%LOCALAPPDATA%\MirrorBar`. - +# MirrorBar+ + +MirrorBar+ is a small Windows 11 taskbar replacement, one exe, no installer, no dependencies. + +The real taskbar is hidden and a see-through pill takes its place. The pill is a mirror image around its center line. To the left of center is the Start button, with your open apps as small icon-only buttons stretching further left. To the right of center is the clock (time and date on one line), then a little sun-and-cloud for the weather, a little newspaper for local news, a little monitor for system stats, battery, volume, wifi and the ^ hidden-icons arrow stretching further right. + +## What it does + +- Transparent pill that is only as wide as what is in it, centered on the screen with a few pixels of space under it. +- Drag it anywhere by its background. It remembers where you put it. Right-click and choose "Reset position to bottom center" to send it home. +- Pull the far left end of the pill (the cursor turns into a double arrow) to shrink the empty space on the left. The center line stays put, and the left side stretches back out as you open more apps. Right-click and choose "Reset bar width" to go back to the mirrored look. +- Right-click and choose "Switch to vertical" to stand it up and down against the right edge of the screen. +- Right-click an app icon for the normal window options (Restore, Move, Size, Minimize, Maximize, Close) plus Open new window and Open file location. +- Windows of the same program share one icon. Four Brave windows show one Brave icon with a small red 4 in its top right corner. Click it to bring up the window you used last; click again while one of them is in front to step to the next. Hover shows a preview of the window you used last, and dragging the icon moves all of its windows together. Untick "Combine windows of the same program into one icon" in the settings window to get one icon per window again. + +Tick "Hide the bar until the mouse touches the screen edge" in the settings window and the bar slides out of sight when the mouse is away from it (and stops reserving screen space, so maximized windows use the whole screen). Push the mouse against the screen edge where the bar lives (the bottom, or the right edge in vertical mode) and it comes back. It stays up while a panel, menu or preview is open. + +Drag the app icons and the Windows logo along the left row to reorder them. MirrorBar remembers the order of your apps and the logo's spot. +- Drag the clock, battery, volume, wifi and hidden-icons arrow along the right row to reorder them. That order is remembered. +- Rest the mouse on an app icon for a moment and a live preview of that window pops up beside the bar (minimized windows show their icon instead). Click the preview to switch to that window. +- Right-click an app icon and choose "Pin to MirrorBar" to keep it on the bar. A pinned app that isn't running shows as a launcher: click it to start the program, and when its window opens it takes that spot. Pinning works for normal programs; Store apps can't be pinned. +- "Open notification center" is in the right-click menu. +- Drag files from Explorer onto an app icon and that program opens them, running or pinned. +- "MirrorBar settings..." in the right-click menu opens one window for background opacity, the three colors, icon style, the ZIP code, tickboxes to show or hide the weather, the local news and the system stats, vertical mode, start with Windows, and resetting the position and width. Changes apply as you make them. +- Smooth, outline-free icons and text, even when the pill is see-through. +- Click the storm cloud and a weather panel opens above the bar: the temperature in Fahrenheit, what it feels like, the high and low, humidity, wind, chance of rain, sunrise, sunset, UV index, the moon phase, a looping radar picture of the last hour or so centered on your ZIP code, and the next five days. Click the cloud again, or click anywhere else, and it closes. It needs a ZIP code: type it in "MirrorBar settings..." (a 5 digit US ZIP code) and the weather turns on at once. The forecast comes from Open-Meteo (open-meteo.com, free, no account), the radar map comes from RainViewer and Esri and is only downloaded when you open the panel, and MirrorBar only goes to the internet when a ZIP code is set. The cloud can be dragged along the right row like the other icons. + +- Click the newspaper and a panel of local headlines opens above the bar, newest first, with the outlet and how long ago each ran. Click a headline and it opens in your default browser. It uses the same ZIP code as the weather: the ZIP code is turned into a town name and the headlines are Google News' feed for that town, so someone in 43220 gets Columbus stations and papers and someone in 46750 gets Fort Wayne and Huntington ones. The headlines are only downloaded when a ZIP code is set. Small towns have fewer stories than cities. + +- Click the little speech bubble and Google Messages for web opens in a small window above the bar, so you can read and answer texts without opening a browser tab. The first time, scan the QR code from the Messages app on your phone (Settings, Device pairing) and tick "Remember this computer"; after that it stays signed in. It runs Microsoft Edge in app mode (no tabs, no address bar) with its own private profile folder in `%LOCALAPPDATA%\MirrorBar\messages`, separate from your normal Edge, and goes only to messages.google.com. Once you have paired, MirrorBar quietly starts it in the background about 20 seconds after it launches, keeps the window just off the edge of the screen, and shows the unread count from the window title as a red number on the bubble. Click anywhere else and the window slides away again. Right-click the bubble and choose "Close Messages" to stop the background window and give the memory back. Messages for web only works while your phone is on and connected; that is how Google built it. A link someone texts you opens in your normal default browser, not in Edge: the Messages window is started with a debugging port that only listens on this PC (127.0.0.1), and MirrorBar hands any page that is not Messages or a Google sign-in page to the default browser and closes it. `messages-titles.txt` in the MirrorBar data folder keeps the first 25 different window titles it has seen, only so the unread badge can be tuned; delete it any time. + +- "Show weather on the bar", "Show local news on the bar", "Show system stats on the bar" and "Show Google Messages on the bar" in the settings window turn each feature off. The icon leaves the bar and nothing is downloaded for it; tick the box again and it comes back. + +- The weather, news and system stats panels are as see-through as the bar itself: set the bar to Clear and the panels go clear too, with only their text, pictures and outline staying solid. Untick "Panels match the bar's transparency" in the settings window to keep the panels solid. + +- Click the little monitor and a panel opens with the usual neofetch information: OS, host, kernel, uptime, resolution, CPU, GPU, memory, each fixed disk, battery and local IP. Click any line to copy it to the clipboard, or click the top of the panel to copy everything as plain text you can paste into other programs. Nothing leaves your PC; it is all read from Windows. +- Pick the color of the Windows logo, the clock, and the battery/volume/wifi/arrow icons from the right-click menu (white, blue, sky blue, green, yellow, orange, red, pink, purple, black). +- "Icon style" in the right-click menu: colorized or grayscale. It applies to the app icons and to the logo, clock and tray icons. +- Background see-through level: Clear, Light, Medium or Solid. +- "Start MirrorBar when I sign in" in the right-click menu. +- Scroll over the speaker to change the volume. Click the clock, battery, volume or wifi for the matching Windows panel. + +## Safety + +- `mirrorbar.exe` quits by itself after 10 minutes and brings the normal taskbar back. `mirrorbar_forever.exe` (or any copy started with `--forever`) does not. +- Ctrl+Alt+Q quits and restores the taskbar. +- Right-click, "Exit MirrorBar and restore taskbar". +- Hold Shift while it launches and it exits at once without touching anything. +- `restore_taskbar.exe` (the same program, renamed) or `--restore` puts the normal taskbar back. + +## Download + +Grab `MirrorBarPlus.zip` from the Releases page. If Windows shows a "protected your PC" warning, right-click the zip, choose Properties, check Unblock, and unzip it after that. + +## Build + +Go 1.24 or newer, standard library only: + +``` +GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-H=windowsgui -s -w" -o mirrorbar.exe . +``` + +Settings are kept in `%LOCALAPPDATA%\MirrorBar`. + diff --git a/autohide.go b/autohide.go new file mode 100644 index 0000000..a17c922 --- /dev/null +++ b/autohide.go @@ -0,0 +1,102 @@ +package main + +// Auto-hide: the bar slides out of sight when the mouse is away from it and +// comes back when the mouse touches the screen edge where it lives. + +import ( + "time" + "unsafe" +) + +const ( + ahTimerID = 9 + ahDelay = 700 * time.Millisecond + ahEdgeSlack = 24 // device-independent pixels of leeway along the edge +) + +var ( + autoHide bool + ahHidden bool + ahLeftAt = time.Now() + menuOpen bool // a right-click menu of the bar is showing +) + +// ahStart / ahStop run the quick mouse check only while auto-hide is on. +func ahStart() { pSetTimer.Call(hwndMain, ahTimerID, 60, 0) } +func ahStop() { pKillTimer.Call(hwndMain, ahTimerID) } + +// ahBusy is true while something on screen depends on the bar staying put. +func ahBusy() bool { + if wxShown || newsShown || sysShown || gmShown || dragging || dragActive || menuOpen { + return true + } + if pvHwnd != 0 { + if v, _, _ := pIsWindowVisible.Call(pvHwnd); v != 0 { + return true + } + } + return false +} + +func ahTick(hwnd uintptr) { + if !autoHide { + return + } + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + sw, sh := screenSize() + pw, ph := pillSize() + x, y := pillPos(pw, ph) + slack := px(ahEdgeSlack) + + if ahHidden { + var hot bool + if vertical { + hot = cp.X >= sw-2 && cp.Y >= y-slack && cp.Y <= y+ph+slack + } else { + hot = cp.Y >= sh-2 && cp.X >= x-slack && cp.X <= x+pw+slack + } + if hot { + ahHidden = false + ahLeftAt = time.Now() + positionBar(hwnd) + } + return + } + near := cp.X >= x-px(6) && cp.X <= x+pw+px(6) && cp.Y >= y-px(6) && cp.Y <= y+ph+px(6) + if near || ahBusy() { + ahLeftAt = time.Now() + return + } + if time.Since(ahLeftAt) > ahDelay { + ahHidden = true + positionBar(hwnd) + } +} + +// setAutoHide is called by the settings window. +func setAutoHide(on bool) { + if autoHide == on { + return + } + autoHide = on + saveFeatures() + ahHidden = false + ahLeftAt = time.Now() + if on { + if appbarOn { // a bar that hides must not keep screen space reserved + abd := appBarData{Hwnd: hwndMain} + appBar(abmRemove, &abd) + appbarOn = false + } + ahStart() + } else { + ahStop() + if !customPos && !appbarOn { + abd := appBarData{Hwnd: hwndMain, CallbackMsg: callbackMsg} + appBar(abmNew, &abd) + appbarOn = true + } + } + positionBar(hwndMain) +} diff --git a/gmflyout.go b/gmflyout.go index 03aba18..22371e3 100644 --- a/gmflyout.go +++ b/gmflyout.go @@ -1,553 +1,558 @@ -package main - -// The Google Messages flyout: a speech bubble on the bar that opens Messages for -// web (messages.google.com) in a small window above the bar, so you can read and -// answer texts without opening a browser tab. -// -// How it works: MirrorBar starts Microsoft Edge in "app" mode (no tabs, no address -// bar) with its own private profile folder, so the sign-in from pairing your phone -// is remembered and never touches your normal Edge. Edge is already on every -// Windows 11 PC, so there is nothing to install. The window is kept just off the -// edge of the screen while the flyout is closed; clicking the bubble slides it -// above the bar, clicking anywhere else slides it away again. Because the page -// keeps running, the unread number in its window title can be shown on the bubble. -// -// Messages for web only works while the phone is on and connected; that is how -// Google built it, not something MirrorBar can change. - -import ( - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "syscall" - "time" - "unsafe" -) - -const ( - gmURL = "https://messages.google.com/web/conversations" - - gmW = 780.0 // flyout size, in 96 dpi units - gmH = 580.0 - - gmTimerID = 3 // on the main window: watches for clicks outside the flyout - gmParkX = -32000 - gmParkY = -32000 - gmAutoDelay = 20 * time.Second // wait this long after start before opening Messages in the background - gmLaunchMax = 45 * time.Second // give up looking for the window after this long - - gmSwpNoSize = 0x0001 - gmSwpNoMove = 0x0002 - gmSwpNoZOrder = 0x0004 - gmSwpFrameChanged = 0x0020 - gmSwShowNoActive = 4 - gmWsExAppWindow = 0x00040000 - gmGaRootOwner = 3 -) - -var ( - pIsWindow = user32.NewProc("IsWindow") - pWindowFromPoint = user32.NewProc("WindowFromPoint") - pGetAncestor = user32.NewProc("GetAncestor") - pSetWindowLongPtr = user32.NewProc("SetWindowLongPtrW") - pSetWindowPlace = user32.NewProc("SetWindowPlacement") -) - -var ( - gmHwnd uintptr - gmPid uint32 - gmShown bool - gmPrevBtn bool - gmPrevFg uintptr - gmShownAt time.Time - gmLaunching bool - gmLaunchedAt time.Time - gmWantOpen bool // the bubble was clicked while the window was still starting - gmAutoTried bool - gmUnread int - gmEnumCb uintptr - gmFound uintptr - gmLogged = map[string]bool{} - gmLoggedN int -) - -type gmPlacementT struct { - Length uint32 - Flags uint32 - ShowCmd uint32 - MinPos point - MaxPos point - Normal rect -} - -// ---------- the button on the bar ---------- - -func drawGMIcon(hdc uintptr, r rect) { - if !layerFg { - return - } - col := iconColor() - cx, cy := center(r) - e := px(1) - l, t, rt, b := cx-px(6.5), cy-px(5.5), cx+px(6.5), cy+px(3) - fillRaw(hdc, rect{l, t, rt, t + e}, col) - fillRaw(hdc, rect{l, b - e, rt, b}, col) - fillRaw(hdc, rect{l, t, l + e, b}, col) - fillRaw(hdc, rect{rt - e, t, rt, b}, col) - // the little tail at the bottom left - polyline(hdc, []point{{cx - px(3.5), b}, {cx - px(3.5), cy + px(6)}, {cx - px(0.5), b}}, e, col) - // two lines of "text" in the bubble - fillRaw(hdc, rect{cx - px(4), cy - px(3), cx + px(4), cy - px(3) + e}, col) - fillRaw(hdc, rect{cx - px(4), cy - px(0.5), cx + px(1.5), cy - px(0.5) + e}, col) - - if gmUnread > 0 { - br, bg, bb := styleColor(235, 70, 70) - bx, by, rad := cx+px(6.5), cy-px(5.5), px(5) - circleRaw(hdc, bx, by, rad, rgb(br, bg, bb)) - txt := strconv.Itoa(gmUnread) - if gmUnread > 9 { - txt = "9+" - } - f := makeFont(px(8), 700) - old, _, _ := pSelectObject.Call(hdc, f) - pSetBkMode.Call(hdc, transparent) - pSetTextColor.Call(hdc, rgb(255, 255, 255)) - drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1}) - pSelectObject.Call(hdc, old) - pDeleteObject.Call(f) - } -} - -// ---------- finding and starting the browser window ---------- - -func gmProfileDir() string { return filepath.Join(dataDir(), "messages") } - -func gmProfileExists() bool { - _, err := os.Stat(filepath.Join(gmProfileDir(), "Local State")) - return err == nil -} - -// gmBrowserPath is Edge (always there on Windows 11), or Chrome if Edge is gone. -func gmBrowserPath() string { - type cand struct{ env, vendor, app, exe string } - for _, c := range []cand{ - {"ProgramFiles(x86)", "Microsoft", "Edge", "msedge.exe"}, - {"ProgramFiles", "Microsoft", "Edge", "msedge.exe"}, - {"LOCALAPPDATA", "Microsoft", "Edge", "msedge.exe"}, - {"ProgramFiles", "Google", "Chrome", "chrome.exe"}, - {"ProgramFiles(x86)", "Google", "Chrome", "chrome.exe"}, - {"LOCALAPPDATA", "Google", "Chrome", "chrome.exe"}, - } { - base := os.Getenv(c.env) - if base == "" { - continue - } - p := filepath.Join(base, c.vendor, c.app, "Application", c.exe) - if _, err := os.Stat(p); err == nil { - return p - } - } - return "" -} - -// gmLaunch starts the app window. Started in the background it opens minimized -// and is never given focus, so it does not interrupt whatever is being typed. -func gmLaunch(visible bool) bool { - exe := gmBrowserPath() - if exe == "" { - return false - } - prof := gmProfileDir() - if err := os.MkdirAll(prof, 0o755); err != nil { - return false - } - args := []string{ - exe, - "--app=" + gmURL, - "--user-data-dir=" + prof, - "--no-first-run", - "--no-default-browser-check", - // keep the page awake while its window is parked off the screen - "--disable-features=CalculateNativeWinOcclusion", - "--disable-renderer-backgrounding", - "--disable-background-timer-throttling", - "--disable-backgrounding-occluded-windows", - } - parts := make([]string, len(args)) - for i, a := range args { - parts[i] = syscall.EscapeArg(a) - } - si := syscall.StartupInfo{Flags: 1} // STARTF_USESHOWWINDOW - si.Cb = uint32(unsafe.Sizeof(si)) - si.ShowWindow = 7 // SW_SHOWMINNOACTIVE - if visible { - si.ShowWindow = 1 // SW_SHOWNORMAL - } - var pi syscall.ProcessInformation - err := syscall.CreateProcess(u16(exe), u16(strings.Join(parts, " ")), nil, nil, false, 0, nil, nil, &si, &pi) - if err != nil { - return false - } - gmPid = pi.ProcessId - syscall.CloseHandle(pi.Process) - syscall.CloseHandle(pi.Thread) - gmLaunching = true - gmLaunchedAt = time.Now() - gmWantOpen = visible - return true -} - -func gmWindowTitle(hwnd uintptr) string { - var tb [512]uint16 - n, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) - return syscall.UTF16ToString(tb[:n]) -} - -// gmTitleMatch is true for the app window's title ("Messages for web", maybe -// with a count in front) and false for ordinary browser windows. -func gmTitleMatch(t string) bool { - l := strings.ToLower(t) - if strings.Contains(l, "microsoft edge") || strings.Contains(l, "google chrome") { - return false - } - return strings.Contains(l, "messages") -} - -func gmEnumProc(hwnd, lparam uintptr) uintptr { - var cls [64]uint16 - n, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 64) - if syscall.UTF16ToString(cls[:n]) != "Chrome_WidgetWin_1" { - return 1 - } - if !gmTitleMatch(gmWindowTitle(hwnd)) { - return 1 - } - var pid uint32 - pGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) - if gmPid != 0 && pid == gmPid { - gmFound = hwnd - return 0 // exactly the window we started - } - if gmFound == 0 { - gmFound = hwnd - } - return 1 -} - -func gmFindWindow() uintptr { - if gmEnumCb == 0 { - gmEnumCb = syscall.NewCallback(gmEnumProc) - } - gmFound = 0 - pEnumWindows.Call(gmEnumCb, 0) - return gmFound -} - -func gmWindowOK() bool { - if gmHwnd == 0 { - return false - } - ok, _, _ := pIsWindow.Call(gmHwnd) - return ok != 0 -} - -// gmAdopt takes charge of the window once it exists: it stays out of the app -// list and Alt+Tab, and sits off screen until the bubble is clicked. -func gmAdopt(h uintptr) { - gmHwnd = h - var pid uint32 - pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) - if pid != 0 { - gmPid = pid - } - ex, _, _ := pGetWindowLongPtr.Call(h, neg(-20)) - want := (ex | wsExToolWindow) &^ gmWsExAppWindow - if want != ex { - pSetWindowLongPtr.Call(h, neg(-20), want) - pSetWindowPos.Call(h, 0, 0, 0, 0, 0, gmSwpNoMove|gmSwpNoSize|gmSwpNoZOrder|swpNoActivate|gmSwpFrameChanged) - } - gmLaunching = false - if gmWantOpen { - gmWantOpen = false - gmShow() - } else { - gmPark() - } -} - -// ---------- moving the window ---------- - -func gmSize() (int32, int32) { - sw, sh := screenSize() - cw := min(px(gmW), sw-px(16)) - ch := min(px(gmH), sh-px(24)) - return cw, ch -} - -// gmMove puts the window at x, y, w, h. A minimized window is first brought back -// to that spot without taking focus. -func gmMove(x, y, w, h int32, topmost, activate bool) { - if !gmWindowOK() { - return - } - if z, _, _ := pIsZoomed.Call(gmHwnd); z != 0 { - pShowWindow.Call(gmHwnd, swRestore) - } - if ic, _, _ := pIsIconic.Call(gmHwnd); ic != 0 { - cmd := uint32(gmSwShowNoActive) - if activate { - cmd = swRestore - } - wp := gmPlacementT{ShowCmd: cmd, Normal: rect{x, y, x + w, y + h}} - wp.Length = uint32(unsafe.Sizeof(wp)) - pSetWindowPlace.Call(gmHwnd, uintptr(unsafe.Pointer(&wp))) - } - after := ^uintptr(1) // HWND_NOTOPMOST - if topmost { - after = hwndTopmost - } - var flags uintptr - if !activate { - flags = swpNoActivate - } - pSetWindowPos.Call(gmHwnd, after, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags|swpShowWindow) -} - -func gmPark() { - cw, ch := gmSize() - gmMove(gmParkX, gmParkY, cw, ch, false, false) -} - -// gmPlace is where the flyout goes: above a horizontal bar, to the left of a -// vertical one, centered on the bubble and always on the screen. -func gmPlace() (x, y, w, h int32) { - cw, ch := gmSize() - ar := trayAnchor(trayGM) - var wr rect - pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr))) - sw, sh := screenSize() - space := px(8) - if vertical { - x = wr.Left - cw - space - if x < 0 { - x = wr.Right + space - } - y = (ar.Top+ar.Bottom)/2 - ch/2 - } else { - x = (ar.Left+ar.Right)/2 - cw/2 - y = wr.Top - ch - space - if y < 0 { - y = wr.Bottom + space - } - } - return clampI(x, 0, sw-cw), clampI(y, 0, sh-ch), cw, ch -} - -func gmFocus() { - // This program just received the click, so Windows lets it hand the focus on. - pSetForegroundWindow.Call(gmHwnd) -} - -// ---------- open, close, click ---------- - -func gmToggle() { - if !showGM { - return - } - if gmShown { - gmHide() - return - } - previewHide() - weatherHide() // one panel at a time - newsHide() - sysHide() - if gmWindowOK() { - gmShow() - return - } - gmHwnd = 0 - if gmLaunching { - gmWantOpen = true // it is still starting; open it the moment it exists - return - } - if !gmLaunch(true) { - shellOpen(gmURL, "") // no Edge or Chrome found: use the default browser - } -} - -func gmShow() { - if !gmWindowOK() { - return - } - fg, _, _ := pGetForegroundWindow.Call() - if fg != gmHwnd { - gmPrevFg = fg - } - gmShown = true - gmPrevBtn = true // ignore a button that is still held from the click that opened this - gmShownAt = time.Now() - x, y, w, h := gmPlace() - gmMove(x, y, w, h, true, true) - gmFocus() - pSetTimer.Call(hwndMain, gmTimerID, 80, 0) -} - -func gmHide() { - if !gmShown { - return - } - gmShown = false - pKillTimer.Call(hwndMain, gmTimerID) - if !gmWindowOK() { - return - } - fg, _, _ := pGetForegroundWindow.Call() - gmPark() - if fg == gmHwnd && gmPrevFg != 0 && gmPrevFg != hwndMain && gmPrevFg != gmHwnd { - if ok, _, _ := pIsWindow.Call(gmPrevFg); ok != 0 { - pSetForegroundWindow.Call(gmPrevFg) // give the keyboard back to what you were doing - } - } -} - -// gmClose shuts the Messages window down (right-click, "Close Messages"). -func gmClose() { - gmHide() - if gmWindowOK() { - pPostMessage.Call(gmHwnd, wmClose, 0, 0) - } - gmHwnd = 0 - gmLaunching = false - gmWantOpen = false - gmAutoTried = true // do not bring it back by itself - gmUnread = 0 -} - -func gmShutdown() { - pKillTimer.Call(hwndMain, gmTimerID) - if gmWindowOK() { - pPostMessage.Call(gmHwnd, wmClose, 0, 0) - } - gmHwnd = 0 -} - -// gmPoll runs every 80 ms while the flyout is open and closes it when a mouse -// button goes down anywhere outside it (the bubble itself is left alone, so -// clicking it can close the flyout). -func gmPoll() { - if !gmShown { - return - } - if !gmWindowOK() { - gmShown = false - pKillTimer.Call(hwndMain, gmTimerID) - return - } - l, _, _ := pGetAsyncKeyState.Call(vkLButton) - r, _, _ := pGetAsyncKeyState.Call(vkRButton) - down := (l|r)&0x8000 != 0 - if down && !gmPrevBtn && time.Since(gmShownAt) > 300*time.Millisecond { - var cp point - pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) - var fr rect - pGetWindowRect.Call(gmHwnd, uintptr(unsafe.Pointer(&fr))) - inside := inRect(fr, cp) - if !inside { - // a dialog or menu that belongs to the Messages window counts as inside - h, _, _ := pWindowFromPoint.Call(uintptr(uint32(cp.X)) | uintptr(uint32(cp.Y))<<32) - if h != 0 { - root, _, _ := pGetAncestor.Call(h, gmGaRootOwner) - inside = root == gmHwnd - } - } - if !inside && !inRect(trayAnchor(trayGM), cp) { - gmHide() - } - } - gmPrevBtn = down -} - -// ---------- the background check ---------- - -var gmCountRe = regexp.MustCompile(`[\(\[](\d{1,3})\+?[\)\]]`) - -func gmParseUnread(title string) int { - m := gmCountRe.FindStringSubmatch(title) - if m == nil { - return 0 - } - n, _ := strconv.Atoi(m[1]) - return n -} - -// gmLogTitle keeps the first few different window titles in titles.txt next to -// the Messages profile, so the unread badge can be tuned if Google words it -// differently than expected. It stops after 25 so it never grows. -func gmLogTitle(t string) { - if t == "" || gmLogged[t] || gmLoggedN >= 25 { - return - } - gmLogged[t] = true - gmLoggedN++ - f, err := os.OpenFile(filepath.Join(dataDir(), "messages-titles.txt"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) - if err != nil { - return - } - defer f.Close() - if len(t) > 80 { - t = t[:80] - } - _, _ = f.WriteString(time.Now().Format("2006-01-02 15:04:05") + "\t" + t + "\n") -} - -// gmTick runs from the bar's 250 ms timer. It starts Messages in the background -// once you have paired a phone, notices when the window goes away, and reads -// the unread count from the window title. Returns true when the bar needs a -// repaint. -func gmTick(tick int) (changed bool) { - defer func() { - if r := recover(); r != nil { - changed = false // optional feature; never take the bar down with it - } - }() - if !showGM { - return false - } - if gmHwnd != 0 && !gmWindowOK() { - gmHwnd = 0 - gmShown = false - pKillTimer.Call(hwndMain, gmTimerID) - changed = gmUnread != 0 - gmUnread = 0 - } - if gmHwnd == 0 { - switch { - case gmLaunching: - if h := gmFindWindow(); h != 0 { - gmAdopt(h) - } else if time.Since(gmLaunchedAt) > gmLaunchMax { - gmLaunching = false - gmWantOpen = false - } - case !gmAutoTried && time.Since(startedAt) > gmAutoDelay: - gmAutoTried = true - if h := gmFindWindow(); h != 0 { - gmAdopt(h) // left over from an earlier run of MirrorBar - } else if gmProfileExists() { - gmLaunch(false) - } - } - } - if gmHwnd != 0 && tick%8 == 0 { - t := gmWindowTitle(gmHwnd) - gmLogTitle(t) - if n := gmParseUnread(t); n != gmUnread { - gmUnread = n - changed = true - } - } - return changed -} +package main + +// The Google Messages flyout: a speech bubble on the bar that opens Messages for +// web (messages.google.com) in a small window above the bar, so you can read and +// answer texts without opening a browser tab. +// +// How it works: MirrorBar starts Microsoft Edge in "app" mode (no tabs, no address +// bar) with its own private profile folder, so the sign-in from pairing your phone +// is remembered and never touches your normal Edge. Edge is already on every +// Windows 11 PC, so there is nothing to install. The window is kept just off the +// edge of the screen while the flyout is closed; clicking the bubble slides it +// above the bar, clicking anywhere else slides it away again. Because the page +// keeps running, the unread number in its window title can be shown on the bubble. +// +// Messages for web only works while the phone is on and connected; that is how +// Google built it, not something MirrorBar can change. + +import ( + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + gmURL = "https://messages.google.com/web/conversations" + + gmW = 780.0 // flyout size, in 96 dpi units + gmH = 580.0 + + gmTimerID = 3 // on the main window: watches for clicks outside the flyout + gmParkX = -32000 + gmParkY = -32000 + gmAutoDelay = 20 * time.Second // wait this long after start before opening Messages in the background + gmLaunchMax = 45 * time.Second // give up looking for the window after this long + + gmSwpNoSize = 0x0001 + gmSwpNoMove = 0x0002 + gmSwpNoZOrder = 0x0004 + gmSwpFrameChanged = 0x0020 + gmSwShowNoActive = 4 + gmWsExAppWindow = 0x00040000 + gmGaRootOwner = 3 +) + +var ( + pIsWindow = user32.NewProc("IsWindow") + pWindowFromPoint = user32.NewProc("WindowFromPoint") + pGetAncestor = user32.NewProc("GetAncestor") + pSetWindowLongPtr = user32.NewProc("SetWindowLongPtrW") + pSetWindowPlace = user32.NewProc("SetWindowPlacement") +) + +var ( + gmHwnd uintptr + gmPid uint32 + gmShown bool + gmPrevBtn bool + gmPrevFg uintptr + gmShownAt time.Time + gmLaunching bool + gmLaunchedAt time.Time + gmWantOpen bool // the bubble was clicked while the window was still starting + gmAutoTried bool + gmUnread int + gmEnumCb uintptr + gmFound uintptr + gmLogged = map[string]bool{} + gmLoggedN int +) + +type gmPlacementT struct { + Length uint32 + Flags uint32 + ShowCmd uint32 + MinPos point + MaxPos point + Normal rect +} + +// ---------- the button on the bar ---------- + +func drawGMIcon(hdc uintptr, r rect) { + if !layerFg { + return + } + col := iconColor() + cx, cy := center(r) + e := px(1) + l, t, rt, b := cx-px(6.5), cy-px(5.5), cx+px(6.5), cy+px(3) + fillRaw(hdc, rect{l, t, rt, t + e}, col) + fillRaw(hdc, rect{l, b - e, rt, b}, col) + fillRaw(hdc, rect{l, t, l + e, b}, col) + fillRaw(hdc, rect{rt - e, t, rt, b}, col) + // the little tail at the bottom left + polyline(hdc, []point{{cx - px(3.5), b}, {cx - px(3.5), cy + px(6)}, {cx - px(0.5), b}}, e, col) + // two lines of "text" in the bubble + fillRaw(hdc, rect{cx - px(4), cy - px(3), cx + px(4), cy - px(3) + e}, col) + fillRaw(hdc, rect{cx - px(4), cy - px(0.5), cx + px(1.5), cy - px(0.5) + e}, col) + + if gmUnread > 0 { + br, bg, bb := styleColor(235, 70, 70) + bx, by, rad := cx+px(6.5), cy-px(5.5), px(5) + circleRaw(hdc, bx, by, rad, rgb(br, bg, bb)) + txt := strconv.Itoa(gmUnread) + if gmUnread > 9 { + txt = "9+" + } + f := makeFont(px(8), 700) + old, _, _ := pSelectObject.Call(hdc, f) + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(255, 255, 255)) + drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1}) + pSelectObject.Call(hdc, old) + pDeleteObject.Call(f) + } +} + +// ---------- finding and starting the browser window ---------- + +func gmProfileDir() string { return filepath.Join(dataDir(), "messages") } + +func gmProfileExists() bool { + _, err := os.Stat(filepath.Join(gmProfileDir(), "Local State")) + return err == nil +} + +// gmBrowserPath is Edge (always there on Windows 11), or Chrome if Edge is gone. +func gmBrowserPath() string { + type cand struct{ env, vendor, app, exe string } + for _, c := range []cand{ + {"ProgramFiles(x86)", "Microsoft", "Edge", "msedge.exe"}, + {"ProgramFiles", "Microsoft", "Edge", "msedge.exe"}, + {"LOCALAPPDATA", "Microsoft", "Edge", "msedge.exe"}, + {"ProgramFiles", "Google", "Chrome", "chrome.exe"}, + {"ProgramFiles(x86)", "Google", "Chrome", "chrome.exe"}, + {"LOCALAPPDATA", "Google", "Chrome", "chrome.exe"}, + } { + base := os.Getenv(c.env) + if base == "" { + continue + } + p := filepath.Join(base, c.vendor, c.app, "Application", c.exe) + if _, err := os.Stat(p); err == nil { + return p + } + } + return "" +} + +// gmLaunch starts the app window. Started in the background it opens minimized +// and is never given focus, so it does not interrupt whatever is being typed. +func gmLaunch(visible bool) bool { + exe := gmBrowserPath() + if exe == "" { + return false + } + prof := gmProfileDir() + if err := os.MkdirAll(prof, 0o755); err != nil { + return false + } + args := []string{ + exe, + "--app=" + gmURL, + "--user-data-dir=" + prof, + // lets MirrorBar send clicked links to the default browser (this PC only) + "--remote-debugging-port=" + gmDebugPort, + "--remote-debugging-address=127.0.0.1", + "--no-first-run", + "--no-default-browser-check", + // keep the page awake while its window is parked off the screen + "--disable-features=CalculateNativeWinOcclusion", + "--disable-renderer-backgrounding", + "--disable-background-timer-throttling", + "--disable-backgrounding-occluded-windows", + } + parts := make([]string, len(args)) + for i, a := range args { + parts[i] = syscall.EscapeArg(a) + } + si := syscall.StartupInfo{Flags: 1} // STARTF_USESHOWWINDOW + si.Cb = uint32(unsafe.Sizeof(si)) + si.ShowWindow = 7 // SW_SHOWMINNOACTIVE + if visible { + si.ShowWindow = 1 // SW_SHOWNORMAL + } + var pi syscall.ProcessInformation + err := syscall.CreateProcess(u16(exe), u16(strings.Join(parts, " ")), nil, nil, false, 0, nil, nil, &si, &pi) + if err != nil { + return false + } + gmPid = pi.ProcessId + gmStartLinkWatch() + syscall.CloseHandle(pi.Process) + syscall.CloseHandle(pi.Thread) + gmLaunching = true + gmLaunchedAt = time.Now() + gmWantOpen = visible + return true +} + +func gmWindowTitle(hwnd uintptr) string { + var tb [512]uint16 + n, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) + return syscall.UTF16ToString(tb[:n]) +} + +// gmTitleMatch is true for the app window's title ("Messages for web", maybe +// with a count in front) and false for ordinary browser windows. +func gmTitleMatch(t string) bool { + l := strings.ToLower(t) + if strings.Contains(l, "microsoft edge") || strings.Contains(l, "google chrome") { + return false + } + return strings.Contains(l, "messages") +} + +func gmEnumProc(hwnd, lparam uintptr) uintptr { + var cls [64]uint16 + n, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 64) + if syscall.UTF16ToString(cls[:n]) != "Chrome_WidgetWin_1" { + return 1 + } + if !gmTitleMatch(gmWindowTitle(hwnd)) { + return 1 + } + var pid uint32 + pGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) + if gmPid != 0 && pid == gmPid { + gmFound = hwnd + return 0 // exactly the window we started + } + if gmFound == 0 { + gmFound = hwnd + } + return 1 +} + +func gmFindWindow() uintptr { + if gmEnumCb == 0 { + gmEnumCb = syscall.NewCallback(gmEnumProc) + } + gmFound = 0 + pEnumWindows.Call(gmEnumCb, 0) + return gmFound +} + +func gmWindowOK() bool { + if gmHwnd == 0 { + return false + } + ok, _, _ := pIsWindow.Call(gmHwnd) + return ok != 0 +} + +// gmAdopt takes charge of the window once it exists: it stays out of the app +// list and Alt+Tab, and sits off screen until the bubble is clicked. +func gmAdopt(h uintptr) { + gmHwnd = h + var pid uint32 + pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) + if pid != 0 { + gmPid = pid + } + ex, _, _ := pGetWindowLongPtr.Call(h, neg(-20)) + want := (ex | wsExToolWindow) &^ gmWsExAppWindow + if want != ex { + pSetWindowLongPtr.Call(h, neg(-20), want) + pSetWindowPos.Call(h, 0, 0, 0, 0, 0, gmSwpNoMove|gmSwpNoSize|gmSwpNoZOrder|swpNoActivate|gmSwpFrameChanged) + } + gmLaunching = false + gmStartLinkWatch() + if gmWantOpen { + gmWantOpen = false + gmShow() + } else { + gmPark() + } +} + +// ---------- moving the window ---------- + +func gmSize() (int32, int32) { + sw, sh := screenSize() + cw := min(px(gmW), sw-px(16)) + ch := min(px(gmH), sh-px(24)) + return cw, ch +} + +// gmMove puts the window at x, y, w, h. A minimized window is first brought back +// to that spot without taking focus. +func gmMove(x, y, w, h int32, topmost, activate bool) { + if !gmWindowOK() { + return + } + if z, _, _ := pIsZoomed.Call(gmHwnd); z != 0 { + pShowWindow.Call(gmHwnd, swRestore) + } + if ic, _, _ := pIsIconic.Call(gmHwnd); ic != 0 { + cmd := uint32(gmSwShowNoActive) + if activate { + cmd = swRestore + } + wp := gmPlacementT{ShowCmd: cmd, Normal: rect{x, y, x + w, y + h}} + wp.Length = uint32(unsafe.Sizeof(wp)) + pSetWindowPlace.Call(gmHwnd, uintptr(unsafe.Pointer(&wp))) + } + after := ^uintptr(1) // HWND_NOTOPMOST + if topmost { + after = hwndTopmost + } + var flags uintptr + if !activate { + flags = swpNoActivate + } + pSetWindowPos.Call(gmHwnd, after, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags|swpShowWindow) +} + +func gmPark() { + cw, ch := gmSize() + gmMove(gmParkX, gmParkY, cw, ch, false, false) +} + +// gmPlace is where the flyout goes: above a horizontal bar, to the left of a +// vertical one, centered on the bubble and always on the screen. +func gmPlace() (x, y, w, h int32) { + cw, ch := gmSize() + ar := trayAnchor(trayGM) + var wr rect + pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr))) + sw, sh := screenSize() + space := px(8) + if vertical { + x = wr.Left - cw - space + if x < 0 { + x = wr.Right + space + } + y = (ar.Top+ar.Bottom)/2 - ch/2 + } else { + x = (ar.Left+ar.Right)/2 - cw/2 + y = wr.Top - ch - space + if y < 0 { + y = wr.Bottom + space + } + } + return clampI(x, 0, sw-cw), clampI(y, 0, sh-ch), cw, ch +} + +func gmFocus() { + // This program just received the click, so Windows lets it hand the focus on. + pSetForegroundWindow.Call(gmHwnd) +} + +// ---------- open, close, click ---------- + +func gmToggle() { + if !showGM { + return + } + if gmShown { + gmHide() + return + } + previewHide() + weatherHide() // one panel at a time + newsHide() + sysHide() + if gmWindowOK() { + gmShow() + return + } + gmHwnd = 0 + if gmLaunching { + gmWantOpen = true // it is still starting; open it the moment it exists + return + } + if !gmLaunch(true) { + shellOpen(gmURL, "") // no Edge or Chrome found: use the default browser + } +} + +func gmShow() { + if !gmWindowOK() { + return + } + fg, _, _ := pGetForegroundWindow.Call() + if fg != gmHwnd { + gmPrevFg = fg + } + gmShown = true + gmPrevBtn = true // ignore a button that is still held from the click that opened this + gmShownAt = time.Now() + x, y, w, h := gmPlace() + gmMove(x, y, w, h, true, true) + gmFocus() + pSetTimer.Call(hwndMain, gmTimerID, 80, 0) +} + +func gmHide() { + if !gmShown { + return + } + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + if !gmWindowOK() { + return + } + fg, _, _ := pGetForegroundWindow.Call() + gmPark() + if fg == gmHwnd && gmPrevFg != 0 && gmPrevFg != hwndMain && gmPrevFg != gmHwnd { + if ok, _, _ := pIsWindow.Call(gmPrevFg); ok != 0 { + pSetForegroundWindow.Call(gmPrevFg) // give the keyboard back to what you were doing + } + } +} + +// gmClose shuts the Messages window down (right-click, "Close Messages"). +func gmClose() { + gmHide() + if gmWindowOK() { + pPostMessage.Call(gmHwnd, wmClose, 0, 0) + } + gmHwnd = 0 + gmLaunching = false + gmWantOpen = false + gmAutoTried = true // do not bring it back by itself + gmUnread = 0 +} + +func gmShutdown() { + pKillTimer.Call(hwndMain, gmTimerID) + if gmWindowOK() { + pPostMessage.Call(gmHwnd, wmClose, 0, 0) + } + gmHwnd = 0 +} + +// gmPoll runs every 80 ms while the flyout is open and closes it when a mouse +// button goes down anywhere outside it (the bubble itself is left alone, so +// clicking it can close the flyout). +func gmPoll() { + if !gmShown { + return + } + if !gmWindowOK() { + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + return + } + l, _, _ := pGetAsyncKeyState.Call(vkLButton) + r, _, _ := pGetAsyncKeyState.Call(vkRButton) + down := (l|r)&0x8000 != 0 + if down && !gmPrevBtn && time.Since(gmShownAt) > 300*time.Millisecond { + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + var fr rect + pGetWindowRect.Call(gmHwnd, uintptr(unsafe.Pointer(&fr))) + inside := inRect(fr, cp) + if !inside { + // a dialog or menu that belongs to the Messages window counts as inside + h, _, _ := pWindowFromPoint.Call(uintptr(uint32(cp.X)) | uintptr(uint32(cp.Y))<<32) + if h != 0 { + root, _, _ := pGetAncestor.Call(h, gmGaRootOwner) + inside = root == gmHwnd + } + } + if !inside && !inRect(trayAnchor(trayGM), cp) { + gmHide() + } + } + gmPrevBtn = down +} + +// ---------- the background check ---------- + +var gmCountRe = regexp.MustCompile(`[\(\[](\d{1,3})\+?[\)\]]`) + +func gmParseUnread(title string) int { + m := gmCountRe.FindStringSubmatch(title) + if m == nil { + return 0 + } + n, _ := strconv.Atoi(m[1]) + return n +} + +// gmLogTitle keeps the first few different window titles in titles.txt next to +// the Messages profile, so the unread badge can be tuned if Google words it +// differently than expected. It stops after 25 so it never grows. +func gmLogTitle(t string) { + if t == "" || gmLogged[t] || gmLoggedN >= 25 { + return + } + gmLogged[t] = true + gmLoggedN++ + f, err := os.OpenFile(filepath.Join(dataDir(), "messages-titles.txt"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + if len(t) > 80 { + t = t[:80] + } + _, _ = f.WriteString(time.Now().Format("2006-01-02 15:04:05") + "\t" + t + "\n") +} + +// gmTick runs from the bar's 250 ms timer. It starts Messages in the background +// once you have paired a phone, notices when the window goes away, and reads +// the unread count from the window title. Returns true when the bar needs a +// repaint. +func gmTick(tick int) (changed bool) { + defer func() { + if r := recover(); r != nil { + changed = false // optional feature; never take the bar down with it + } + }() + if !showGM { + return false + } + if gmHwnd != 0 && !gmWindowOK() { + gmHwnd = 0 + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + changed = gmUnread != 0 + gmUnread = 0 + } + if gmHwnd == 0 { + switch { + case gmLaunching: + if h := gmFindWindow(); h != 0 { + gmAdopt(h) + } else if time.Since(gmLaunchedAt) > gmLaunchMax { + gmLaunching = false + gmWantOpen = false + } + case !gmAutoTried && time.Since(startedAt) > gmAutoDelay: + gmAutoTried = true + if h := gmFindWindow(); h != 0 { + gmAdopt(h) // left over from an earlier run of MirrorBar + } else if gmProfileExists() { + gmLaunch(false) + } + } + } + if gmHwnd != 0 && tick%8 == 0 { + t := gmWindowTitle(gmHwnd) + gmLogTitle(t) + if n := gmParseUnread(t); n != gmUnread { + gmUnread = n + changed = true + } + } + return changed +} diff --git a/group.go b/group.go new file mode 100644 index 0000000..7e979ee --- /dev/null +++ b/group.go @@ -0,0 +1,134 @@ +package main + +// Combining windows: when "Combine windows of the same program" is on, all the +// open windows of one program (four Brave windows, say) share a single icon on +// the bar with a small red count in its top right corner. `allApps` is the full +// list of windows and launchers in bar order; `apps` is what the bar shows. + +import ( + "strconv" + "strings" + "time" + "unsafe" +) + +var ( + groupWins = true + allApps []appWin + winActiveAt = map[uintptr]time.Time{} // when each window was last the front one +) + +// noteForeground remembers which window is in front, so a combined icon knows +// which of its windows you were using last. +func noteForeground(present map[uintptr]appWin) { + fg, _, _ := pGetForegroundWindow.Call() + if _, ok := present[fg]; ok { + winActiveAt[fg] = time.Now() + } + for h := range winActiveAt { + if _, ok := present[h]; !ok { + delete(winActiveAt, h) + } + } +} + +// groupApps turns the full window list into the icons the bar shows. +func groupApps(list []appWin) []appWin { + out := make([]appWin, 0, len(list)) + idx := map[string]int{} + for _, a := range list { + a.count, a.members = 1, nil + if a.hwnd == 0 { + out = append(out, a) + continue + } + a.members = []uintptr{a.hwnd} + if groupWins && a.exe != "" { + k := strings.ToLower(a.exe) + if i, ok := idx[k]; ok { + out[i].members = append(out[i].members, a.hwnd) + out[i].count++ + continue + } + idx[k] = len(out) + } + out = append(out, a) + } + return out +} + +// memberHwnd is the window a combined icon acts on: the one used most recently. +func memberHwnd(a appWin) uintptr { + if len(a.members) <= 1 { + return a.hwnd + } + best := a.members[0] + for _, m := range a.members[1:] { + if winActiveAt[m].After(winActiveAt[best]) { + best = m + } + } + return best +} + +// syncAllFromGrouped puts allApps back in step after the icons were dragged +// into a new order: each icon brings all of its windows along. +func syncAllFromGrouped() { + byHwnd := map[uintptr]appWin{} + for _, a := range allApps { + if a.hwnd != 0 { + byHwnd[a.hwnd] = a + } + } + out := make([]appWin, 0, len(allApps)) + for _, g := range apps { + if g.hwnd == 0 { + g.count, g.members = 0, nil + out = append(out, g) + continue + } + for _, m := range g.members { + if w, ok := byHwnd[m]; ok { + out = append(out, w) + } + } + } + allApps = out +} + +// activateGroup handles a click on a combined icon: bring up the window used +// most recently, or, if one of them is already in front, step to the next. +func activateGroup(a appWin) { + fg, _, _ := pGetForegroundWindow.Call() + target := memberHwnd(a) + for i, m := range a.members { + if m == fg { + target = a.members[(i+1)%len(a.members)] + break + } + } + if iconic, _, _ := pIsIconic.Call(target); iconic != 0 { + pShowWindow.Call(target, swRestore) + } + pSetForegroundWindow.Call(target) +} + +// drawCountBadge draws the little red number in the top right corner of an icon. +func drawCountBadge(hdc uintptr, cx, cy, isz int32, n int) { + br, bg, bb := styleColor(235, 70, 70) + bx, by, rad := cx+isz/2, cy-isz/2, px(5) + circleRaw(hdc, bx, by, rad, rgb(br, bg, bb)) + txt := strconv.Itoa(n) + if n > 9 { + txt = "9+" + } + f := makeFont(px(8), 700) + old, _, _ := pSelectObject.Call(hdc, f) + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(255, 255, 255)) + drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1}) + pSelectObject.Call(hdc, old) + pDeleteObject.Call(f) +} + +var _ = unsafe.Pointer(nil) diff --git a/settings.go b/settings.go index d2abed6..788dc97 100644 --- a/settings.go +++ b/settings.go @@ -1,373 +1,385 @@ -package main - -// The settings window: everything the right-click menu can change, in one -// place. It opens from "MirrorBar settings..." in the menu. Changes apply the -// moment you make them, and the window stays in step if the menu is used too. - -import ( - "strconv" - "syscall" - "unsafe" -) - -var ( - pSendMessage = user32.NewProc("SendMessageW") - pSetWindowText = user32.NewProc("SetWindowTextW") - pIsDialogMessage = user32.NewProc("IsDialogMessageW") - pAdjustWindowRectEx = user32.NewProc("AdjustWindowRectEx") - pInitCommonControls = syscall.NewLazyDLL("comctl32.dll").NewProc("InitCommonControlsEx") - pGetFocus = user32.NewProc("GetFocus") -) - -const ( - menuSettingsID = 45 - - wmCommand = 0x0111 - wmHScroll = 0x0114 - wmSetFont = 0x0030 - - wsChild = 0x40000000 - wsTabStop = 0x00010000 - wsVScroll = 0x00200000 - wsWindowFrame = 0x00C80000 // caption, system menu, border: a plain window that can't be resized - wsBorder = 0x00800000 - bsPushButton = 0x0000 - bsDefPushButton = 0x0001 - bsAutoCheckBox = 0x0003 - cbsDropDownList = 0x0003 - tbsNoTicks = 0x0010 - esAutoHScroll = 0x0080 - esNumber = 0x2000 - - emSetLimitText = 0x00C5 - enChange = 0x0300 - - bmGetCheck = 0x00F0 - bmSetCheck = 0x00F1 - cbAddString = 0x0143 - cbGetCurSel = 0x0147 - cbSetCurSel = 0x014E - tbmGetPos = 0x0400 - tbmSetPos = 0x0405 - tbmSetRange = 0x0406 - - cbnSelChange = 1 - tbEndTrack = 8 - colorBtnFace = 15 - - idAlpha = 200 - idAlphaValue = 201 - idLogo = 202 - idClock = 203 - idTrayIcons = 204 - idStyle = 205 - idVertical = 206 - idAutostart = 207 - idResetPos = 208 - idResetWidth = 209 - idClose = 210 - idZip = 211 - idZipStatus = 212 - idShowWeather = 213 - idShowNews = 214 - idShowSys = 215 - idPanelFade = 216 - idShowGM = 217 -) - -var ( - hwndSettings uintptr - settingsClass bool - settingsFont uintptr - - ctlAlpha, ctlAlphaValue, ctlLogo, ctlClock, ctlTrayIcons, ctlStyle uintptr - ctlVertical, ctlAutostart uintptr - ctlZip, ctlZipStatus uintptr - ctlShowWeather, ctlShowNews, ctlShowSys, ctlShowGM, ctlPanelFade uintptr - zipSyncing bool // true while the program itself is filling in the ZIP box -) - -func boolWP(b bool) uintptr { - if b { - return 1 - } - return 0 -} - -// makeControl creates one child control; sizes are in 96 dpi units. -func makeControl(parent, inst uintptr, class, text string, style uintptr, x, y, w, h int, id uintptr) uintptr { - hw, _, _ := pCreateWindowEx.Call(0, - uintptr(unsafe.Pointer(u16(class))), uintptr(unsafe.Pointer(u16(text))), - style|wsChild|wsVisible, - uintptr(px(float64(x))), uintptr(px(float64(y))), uintptr(px(float64(w))), uintptr(px(float64(h))), - parent, id, inst, 0) - if hw != 0 && settingsFont != 0 { - pSendMessage.Call(hw, wmSetFont, settingsFont, 1) - } - return hw -} - -func openSettings() { - if hwndSettings != 0 { - pShowWindow.Call(hwndSettings, swRestore) - pSetForegroundWindow.Call(hwndSettings) - settingsSync() - return - } - inst, _, _ := pGetModuleHandle.Call(0) - className := u16("MirrorBarSettings") - if !settingsClass { - cursor, _, _ := pLoadCursor.Call(0, idcArrow) - wc := wndClassEx{ - WndProc: syscall.NewCallback(settingsProc), - Instance: inst, - Cursor: cursor, - Background: colorBtnFace + 1, - ClassName: className, - } - wc.Size = uint32(unsafe.Sizeof(wc)) - pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) - icc := struct{ Size, Classes uint32 }{8, 0x4} // ICC_BAR_CLASSES: the slider - pInitCommonControls.Call(uintptr(unsafe.Pointer(&icc))) - settingsClass = true - } - if settingsFont == 0 { - settingsFont = makeFont(px(13), 400) - } - - r := rect{0, 0, px(400), px(516)} - pAdjustWindowRectEx.Call(uintptr(unsafe.Pointer(&r)), wsWindowFrame, 0, 0) - ow, oh := r.Right-r.Left, r.Bottom-r.Top - sw, sh := screenSize() - hw, _, _ := pCreateWindowEx.Call(0, - uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(u16("MirrorBar settings"))), - wsWindowFrame, - uintptr(max(0, (sw-ow)/2)), uintptr(max(0, (sh-oh)/2)), uintptr(ow), uintptr(oh), - 0, 0, inst, 0) - if hw == 0 { - return - } - - label := func(text string, y int) { - makeControl(hw, inst, "STATIC", text, 0, 16, y+4, 150, 20, 0) - } - combo := func(y int, id uintptr) uintptr { - return makeControl(hw, inst, "COMBOBOX", "", cbsDropDownList|wsVScroll|wsTabStop, 170, y, 214, 200, id) - } - - label("Background opacity", 16) - ctlAlpha = makeControl(hw, inst, "msctls_trackbar32", "", tbsNoTicks|wsTabStop, 166, 14, 170, 28, idAlpha) - ctlAlphaValue = makeControl(hw, inst, "STATIC", "", 0, 344, 20, 44, 20, idAlphaValue) - pSendMessage.Call(ctlAlpha, tbmSetRange, 1, uintptr(3|255<<16)) - - label("Windows logo color", 60) - ctlLogo = combo(60, idLogo) - label("Clock color", 96) - ctlClock = combo(96, idClock) - label("Tray icon color", 132) - ctlTrayIcons = combo(132, idTrayIcons) - label("Icon style", 168) - ctlStyle = combo(168, idStyle) - for _, c := range []uintptr{ctlLogo, ctlClock, ctlTrayIcons} { - for _, p := range palette { - pSendMessage.Call(c, cbAddString, 0, uintptr(unsafe.Pointer(u16(p.name)))) - } - } - for _, n := range styleNames { - pSendMessage.Call(ctlStyle, cbAddString, 0, uintptr(unsafe.Pointer(u16(n)))) - } - - label("ZIP code", 204) - ctlZip = makeControl(hw, inst, "EDIT", "", esNumber|esAutoHScroll|wsBorder|wsTabStop, 170, 204, 90, 24, idZip) - pSendMessage.Call(ctlZip, emSetLimitText, 5, 0) - ctlZipStatus = makeControl(hw, inst, "STATIC", "", 0, 16, 236, 368, 20, idZipStatus) - - ctlShowWeather = makeControl(hw, inst, "BUTTON", "Show weather on the bar", bsAutoCheckBox|wsTabStop, 16, 262, 368, 22, idShowWeather) - ctlShowNews = makeControl(hw, inst, "BUTTON", "Show local news on the bar", bsAutoCheckBox|wsTabStop, 16, 290, 368, 22, idShowNews) - ctlShowSys = makeControl(hw, inst, "BUTTON", "Show system stats on the bar", bsAutoCheckBox|wsTabStop, 16, 318, 368, 22, idShowSys) - ctlShowGM = makeControl(hw, inst, "BUTTON", "Show Google Messages on the bar", bsAutoCheckBox|wsTabStop, 16, 346, 368, 22, idShowGM) - ctlPanelFade = makeControl(hw, inst, "BUTTON", "Panels match the bar's transparency", bsAutoCheckBox|wsTabStop, 16, 374, 368, 22, idPanelFade) - ctlVertical = makeControl(hw, inst, "BUTTON", "Stand the bar up at the right edge (vertical)", bsAutoCheckBox|wsTabStop, 16, 402, 368, 22, idVertical) - ctlAutostart = makeControl(hw, inst, "BUTTON", "Start MirrorBar when I sign in", bsAutoCheckBox|wsTabStop, 16, 430, 368, 22, idAutostart) - - makeControl(hw, inst, "BUTTON", "Reset position", bsPushButton|wsTabStop, 16, 470, 116, 28, idResetPos) - makeControl(hw, inst, "BUTTON", "Reset bar width", bsPushButton|wsTabStop, 140, 470, 116, 28, idResetWidth) - makeControl(hw, inst, "BUTTON", "Close", bsDefPushButton|wsTabStop, 292, 470, 92, 28, idClose) - - hwndSettings = hw - settingsSync() - pShowWindow.Call(hw, 1) - pSetForegroundWindow.Call(hw) -} - -// settingsSync makes every control show the current setting. -func settingsSync() { - if hwndSettings == 0 { - return - } - pSendMessage.Call(ctlAlpha, tbmSetPos, 1, uintptr(bgAlpha)) - pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%")))) - pSendMessage.Call(ctlLogo, cbSetCurSel, uintptr(logoIdx), 0) - pSendMessage.Call(ctlClock, cbSetCurSel, uintptr(clockIdx), 0) - pSendMessage.Call(ctlTrayIcons, cbSetCurSel, uintptr(iconIdx), 0) - pSendMessage.Call(ctlStyle, cbSetCurSel, uintptr(iconMode), 0) - pSendMessage.Call(ctlShowWeather, bmSetCheck, boolWP(showWeather), 0) - pSendMessage.Call(ctlShowNews, bmSetCheck, boolWP(showNews), 0) - pSendMessage.Call(ctlShowSys, bmSetCheck, boolWP(showSys), 0) - pSendMessage.Call(ctlShowGM, bmSetCheck, boolWP(showGM), 0) - pSendMessage.Call(ctlPanelFade, bmSetCheck, boolWP(flyMatchBar), 0) - pSendMessage.Call(ctlVertical, bmSetCheck, boolWP(vertical), 0) - pSendMessage.Call(ctlAutostart, bmSetCheck, boolWP(autostartEnabled()), 0) - - // Leave the ZIP box alone while the person is typing in it. - if f, _, _ := pGetFocus.Call(); f != ctlZip && zipText() != wxZip { - zipSyncing = true - pSetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(u16(wxZip)))) - zipSyncing = false - } - settingsZipStatusUpdate() -} - -// zipText is what is typed in the ZIP box right now. -func zipText() string { - var buf [32]uint16 - n, _, _ := pGetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) - return syscall.UTF16ToString(buf[:n]) -} - -// settingsZipStatusUpdate refreshes the line under the ZIP box ("Showing weather for ..."). -func settingsZipStatusUpdate() { - if hwndSettings == 0 || ctlZipStatus == 0 { - return - } - pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16(zipStatusText())))) -} - -// zipEdited runs each time the ZIP box changes. Five digits turn the weather on -// for that ZIP code; an empty box turns it off. -func zipEdited() { - z := onlyDigits(zipText()) - switch { - case len(z) == 5: - weatherSetZip(z) - case z == "": - weatherSetZip("") - default: - pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16("A ZIP code has 5 digits.")))) - return - } - settingsZipStatusUpdate() -} - -func comboChoice(c uintptr) int { - r, _, _ := pSendMessage.Call(c, cbGetCurSel, 0, 0) - return int(int32(r)) -} - -func checked(c uintptr) bool { - r, _, _ := pSendMessage.Call(c, bmGetCheck, 0, 0) - return r == 1 -} - -func settingsCommand(id, note uintptr) { - switch id { - case 1, 2: // Enter and Esc - pDestroyWindow.Call(hwndSettings) - case idClose: - pDestroyWindow.Call(hwndSettings) - case idLogo, idClock, idTrayIcons: - if note != cbnSelChange { - return - } - switch id { - case idLogo: - if i := comboChoice(ctlLogo); i >= 0 { - logoIdx = i - } - case idClock: - if i := comboChoice(ctlClock); i >= 0 { - clockIdx = i - } - case idTrayIcons: - if i := comboChoice(ctlTrayIcons); i >= 0 { - iconIdx = i - } - } - saveColors() - redraw(hwndMain) - flyRefreshAll() - case idStyle: - if note != cbnSelChange { - return - } - if i := comboChoice(ctlStyle); i >= 0 && i < len(styleNames) { - iconMode = i - saveIconMode() - styleCacheClear() - redraw(hwndMain) - } - case idZip: - if note == enChange && !zipSyncing { - zipEdited() - } - case idShowWeather: - setShowWeather(checked(ctlShowWeather)) - case idShowNews: - setShowNews(checked(ctlShowNews)) - case idShowSys: - setShowSys(checked(ctlShowSys)) - case idShowGM: - setShowGM(checked(ctlShowGM)) - case idPanelFade: - setFlyMatchBar(checked(ctlPanelFade)) - case idVertical: - vertical = checked(ctlVertical) - saveOrient() - resetPos(hwndMain) - case idAutostart: - setAutostart(checked(ctlAutostart)) - settingsSync() - case idResetPos: - resetPos(hwndMain) - case idResetWidth: - leftPref = 0 - saveLeftPref() - redraw(hwndMain) - } -} - -func settingsProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { - defer func() { - if r := recover(); r != nil { - result = 0 - } - }() - switch uint32(m) { - case wmCommand: - settingsCommand(wparam&0xFFFF, wparam>>16&0xFFFF) - return 0 - case wmHScroll: - if lparam == ctlAlpha && ctlAlpha != 0 { - pos, _, _ := pSendMessage.Call(ctlAlpha, tbmGetPos, 0, 0) - n := int(pos) - if n >= 3 && n <= 255 && n != bgAlpha { - bgAlpha = n - pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%")))) - redraw(hwndMain) - flyRefreshAll() - } - if wparam&0xFFFF == tbEndTrack { - saveAlpha() - } - } - return 0 - case wmClose: - pDestroyWindow.Call(hwnd) - return 0 - case wmDestroy: - hwndSettings = 0 - return 0 - } - r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) - return r -} +package main + +// The settings window: everything the right-click menu can change, in one +// place. It opens from "MirrorBar settings..." in the menu. Changes apply the +// moment you make them, and the window stays in step if the menu is used too. + +import ( + "strconv" + "syscall" + "unsafe" +) + +var ( + pSendMessage = user32.NewProc("SendMessageW") + pSetWindowText = user32.NewProc("SetWindowTextW") + pIsDialogMessage = user32.NewProc("IsDialogMessageW") + pAdjustWindowRectEx = user32.NewProc("AdjustWindowRectEx") + pInitCommonControls = syscall.NewLazyDLL("comctl32.dll").NewProc("InitCommonControlsEx") + pGetFocus = user32.NewProc("GetFocus") +) + +const ( + menuSettingsID = 45 + + wmCommand = 0x0111 + wmHScroll = 0x0114 + wmSetFont = 0x0030 + + wsChild = 0x40000000 + wsTabStop = 0x00010000 + wsVScroll = 0x00200000 + wsWindowFrame = 0x00C80000 // caption, system menu, border: a plain window that can't be resized + wsBorder = 0x00800000 + bsPushButton = 0x0000 + bsDefPushButton = 0x0001 + bsAutoCheckBox = 0x0003 + cbsDropDownList = 0x0003 + tbsNoTicks = 0x0010 + esAutoHScroll = 0x0080 + esNumber = 0x2000 + + emSetLimitText = 0x00C5 + enChange = 0x0300 + + bmGetCheck = 0x00F0 + bmSetCheck = 0x00F1 + cbAddString = 0x0143 + cbGetCurSel = 0x0147 + cbSetCurSel = 0x014E + tbmGetPos = 0x0400 + tbmSetPos = 0x0405 + tbmSetRange = 0x0406 + + cbnSelChange = 1 + tbEndTrack = 8 + colorBtnFace = 15 + + idAlpha = 200 + idAlphaValue = 201 + idLogo = 202 + idClock = 203 + idTrayIcons = 204 + idStyle = 205 + idVertical = 206 + idAutostart = 207 + idResetPos = 208 + idResetWidth = 209 + idClose = 210 + idZip = 211 + idZipStatus = 212 + idShowWeather = 213 + idShowNews = 214 + idShowSys = 215 + idPanelFade = 216 + idShowGM = 217 + idGroup = 218 + idAutoHide = 219 +) + +var ( + hwndSettings uintptr + settingsClass bool + settingsFont uintptr + + ctlAlpha, ctlAlphaValue, ctlLogo, ctlClock, ctlTrayIcons, ctlStyle uintptr + ctlVertical, ctlAutostart uintptr + ctlZip, ctlZipStatus uintptr + ctlShowWeather, ctlShowNews, ctlShowSys, ctlShowGM, ctlPanelFade uintptr + ctlGroup, ctlAutoHide uintptr + zipSyncing bool // true while the program itself is filling in the ZIP box +) + +func boolWP(b bool) uintptr { + if b { + return 1 + } + return 0 +} + +// makeControl creates one child control; sizes are in 96 dpi units. +func makeControl(parent, inst uintptr, class, text string, style uintptr, x, y, w, h int, id uintptr) uintptr { + hw, _, _ := pCreateWindowEx.Call(0, + uintptr(unsafe.Pointer(u16(class))), uintptr(unsafe.Pointer(u16(text))), + style|wsChild|wsVisible, + uintptr(px(float64(x))), uintptr(px(float64(y))), uintptr(px(float64(w))), uintptr(px(float64(h))), + parent, id, inst, 0) + if hw != 0 && settingsFont != 0 { + pSendMessage.Call(hw, wmSetFont, settingsFont, 1) + } + return hw +} + +func openSettings() { + if hwndSettings != 0 { + pShowWindow.Call(hwndSettings, swRestore) + pSetForegroundWindow.Call(hwndSettings) + settingsSync() + return + } + inst, _, _ := pGetModuleHandle.Call(0) + className := u16("MirrorBarSettings") + if !settingsClass { + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + wc := wndClassEx{ + WndProc: syscall.NewCallback(settingsProc), + Instance: inst, + Cursor: cursor, + Background: colorBtnFace + 1, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + icc := struct{ Size, Classes uint32 }{8, 0x4} // ICC_BAR_CLASSES: the slider + pInitCommonControls.Call(uintptr(unsafe.Pointer(&icc))) + settingsClass = true + } + if settingsFont == 0 { + settingsFont = makeFont(px(13), 400) + } + + r := rect{0, 0, px(400), px(572)} + pAdjustWindowRectEx.Call(uintptr(unsafe.Pointer(&r)), wsWindowFrame, 0, 0) + ow, oh := r.Right-r.Left, r.Bottom-r.Top + sw, sh := screenSize() + hw, _, _ := pCreateWindowEx.Call(0, + uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(u16("MirrorBar settings"))), + wsWindowFrame, + uintptr(max(0, (sw-ow)/2)), uintptr(max(0, (sh-oh)/2)), uintptr(ow), uintptr(oh), + 0, 0, inst, 0) + if hw == 0 { + return + } + + label := func(text string, y int) { + makeControl(hw, inst, "STATIC", text, 0, 16, y+4, 150, 20, 0) + } + combo := func(y int, id uintptr) uintptr { + return makeControl(hw, inst, "COMBOBOX", "", cbsDropDownList|wsVScroll|wsTabStop, 170, y, 214, 200, id) + } + + label("Background opacity", 16) + ctlAlpha = makeControl(hw, inst, "msctls_trackbar32", "", tbsNoTicks|wsTabStop, 166, 14, 170, 28, idAlpha) + ctlAlphaValue = makeControl(hw, inst, "STATIC", "", 0, 344, 20, 44, 20, idAlphaValue) + pSendMessage.Call(ctlAlpha, tbmSetRange, 1, uintptr(3|255<<16)) + + label("Windows logo color", 60) + ctlLogo = combo(60, idLogo) + label("Clock color", 96) + ctlClock = combo(96, idClock) + label("Tray icon color", 132) + ctlTrayIcons = combo(132, idTrayIcons) + label("Icon style", 168) + ctlStyle = combo(168, idStyle) + for _, c := range []uintptr{ctlLogo, ctlClock, ctlTrayIcons} { + for _, p := range palette { + pSendMessage.Call(c, cbAddString, 0, uintptr(unsafe.Pointer(u16(p.name)))) + } + } + for _, n := range styleNames { + pSendMessage.Call(ctlStyle, cbAddString, 0, uintptr(unsafe.Pointer(u16(n)))) + } + + label("ZIP code", 204) + ctlZip = makeControl(hw, inst, "EDIT", "", esNumber|esAutoHScroll|wsBorder|wsTabStop, 170, 204, 90, 24, idZip) + pSendMessage.Call(ctlZip, emSetLimitText, 5, 0) + ctlZipStatus = makeControl(hw, inst, "STATIC", "", 0, 16, 236, 368, 20, idZipStatus) + + ctlShowWeather = makeControl(hw, inst, "BUTTON", "Show weather on the bar", bsAutoCheckBox|wsTabStop, 16, 262, 368, 22, idShowWeather) + ctlShowNews = makeControl(hw, inst, "BUTTON", "Show local news on the bar", bsAutoCheckBox|wsTabStop, 16, 290, 368, 22, idShowNews) + ctlShowSys = makeControl(hw, inst, "BUTTON", "Show system stats on the bar", bsAutoCheckBox|wsTabStop, 16, 318, 368, 22, idShowSys) + ctlShowGM = makeControl(hw, inst, "BUTTON", "Show Google Messages on the bar", bsAutoCheckBox|wsTabStop, 16, 346, 368, 22, idShowGM) + ctlPanelFade = makeControl(hw, inst, "BUTTON", "Panels match the bar's transparency", bsAutoCheckBox|wsTabStop, 16, 374, 368, 22, idPanelFade) + ctlVertical = makeControl(hw, inst, "BUTTON", "Stand the bar up at the right edge (vertical)", bsAutoCheckBox|wsTabStop, 16, 402, 368, 22, idVertical) + ctlAutostart = makeControl(hw, inst, "BUTTON", "Start MirrorBar when I sign in", bsAutoCheckBox|wsTabStop, 16, 430, 368, 22, idAutostart) + + ctlGroup = makeControl(hw, inst, "BUTTON", "Combine windows of the same program into one icon", bsAutoCheckBox|wsTabStop, 16, 458, 368, 22, idGroup) + ctlAutoHide = makeControl(hw, inst, "BUTTON", "Hide the bar until the mouse touches the screen edge", bsAutoCheckBox|wsTabStop, 16, 486, 368, 22, idAutoHide) + + makeControl(hw, inst, "BUTTON", "Reset position", bsPushButton|wsTabStop, 16, 526, 116, 28, idResetPos) + makeControl(hw, inst, "BUTTON", "Reset bar width", bsPushButton|wsTabStop, 140, 526, 116, 28, idResetWidth) + makeControl(hw, inst, "BUTTON", "Close", bsDefPushButton|wsTabStop, 292, 526, 92, 28, idClose) + + hwndSettings = hw + settingsSync() + pShowWindow.Call(hw, 1) + pSetForegroundWindow.Call(hw) +} + +// settingsSync makes every control show the current setting. +func settingsSync() { + if hwndSettings == 0 { + return + } + pSendMessage.Call(ctlAlpha, tbmSetPos, 1, uintptr(bgAlpha)) + pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%")))) + pSendMessage.Call(ctlLogo, cbSetCurSel, uintptr(logoIdx), 0) + pSendMessage.Call(ctlClock, cbSetCurSel, uintptr(clockIdx), 0) + pSendMessage.Call(ctlTrayIcons, cbSetCurSel, uintptr(iconIdx), 0) + pSendMessage.Call(ctlStyle, cbSetCurSel, uintptr(iconMode), 0) + pSendMessage.Call(ctlShowWeather, bmSetCheck, boolWP(showWeather), 0) + pSendMessage.Call(ctlShowNews, bmSetCheck, boolWP(showNews), 0) + pSendMessage.Call(ctlShowSys, bmSetCheck, boolWP(showSys), 0) + pSendMessage.Call(ctlShowGM, bmSetCheck, boolWP(showGM), 0) + pSendMessage.Call(ctlPanelFade, bmSetCheck, boolWP(flyMatchBar), 0) + pSendMessage.Call(ctlVertical, bmSetCheck, boolWP(vertical), 0) + pSendMessage.Call(ctlAutostart, bmSetCheck, boolWP(autostartEnabled()), 0) + pSendMessage.Call(ctlGroup, bmSetCheck, boolWP(groupWins), 0) + pSendMessage.Call(ctlAutoHide, bmSetCheck, boolWP(autoHide), 0) + + // Leave the ZIP box alone while the person is typing in it. + if f, _, _ := pGetFocus.Call(); f != ctlZip && zipText() != wxZip { + zipSyncing = true + pSetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(u16(wxZip)))) + zipSyncing = false + } + settingsZipStatusUpdate() +} + +// zipText is what is typed in the ZIP box right now. +func zipText() string { + var buf [32]uint16 + n, _, _ := pGetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) + return syscall.UTF16ToString(buf[:n]) +} + +// settingsZipStatusUpdate refreshes the line under the ZIP box ("Showing weather for ..."). +func settingsZipStatusUpdate() { + if hwndSettings == 0 || ctlZipStatus == 0 { + return + } + pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16(zipStatusText())))) +} + +// zipEdited runs each time the ZIP box changes. Five digits turn the weather on +// for that ZIP code; an empty box turns it off. +func zipEdited() { + z := onlyDigits(zipText()) + switch { + case len(z) == 5: + weatherSetZip(z) + case z == "": + weatherSetZip("") + default: + pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16("A ZIP code has 5 digits.")))) + return + } + settingsZipStatusUpdate() +} + +func comboChoice(c uintptr) int { + r, _, _ := pSendMessage.Call(c, cbGetCurSel, 0, 0) + return int(int32(r)) +} + +func checked(c uintptr) bool { + r, _, _ := pSendMessage.Call(c, bmGetCheck, 0, 0) + return r == 1 +} + +func settingsCommand(id, note uintptr) { + switch id { + case 1, 2: // Enter and Esc + pDestroyWindow.Call(hwndSettings) + case idClose: + pDestroyWindow.Call(hwndSettings) + case idLogo, idClock, idTrayIcons: + if note != cbnSelChange { + return + } + switch id { + case idLogo: + if i := comboChoice(ctlLogo); i >= 0 { + logoIdx = i + } + case idClock: + if i := comboChoice(ctlClock); i >= 0 { + clockIdx = i + } + case idTrayIcons: + if i := comboChoice(ctlTrayIcons); i >= 0 { + iconIdx = i + } + } + saveColors() + redraw(hwndMain) + flyRefreshAll() + case idStyle: + if note != cbnSelChange { + return + } + if i := comboChoice(ctlStyle); i >= 0 && i < len(styleNames) { + iconMode = i + saveIconMode() + styleCacheClear() + redraw(hwndMain) + } + case idZip: + if note == enChange && !zipSyncing { + zipEdited() + } + case idShowWeather: + setShowWeather(checked(ctlShowWeather)) + case idShowNews: + setShowNews(checked(ctlShowNews)) + case idShowSys: + setShowSys(checked(ctlShowSys)) + case idShowGM: + setShowGM(checked(ctlShowGM)) + case idPanelFade: + setFlyMatchBar(checked(ctlPanelFade)) + case idVertical: + vertical = checked(ctlVertical) + saveOrient() + resetPos(hwndMain) + case idGroup: + setGroupWins(checked(ctlGroup)) + case idAutoHide: + setAutoHide(checked(ctlAutoHide)) + case idAutostart: + setAutostart(checked(ctlAutostart)) + settingsSync() + case idResetPos: + resetPos(hwndMain) + case idResetWidth: + leftPref = 0 + saveLeftPref() + redraw(hwndMain) + } +} + +func settingsProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { + defer func() { + if r := recover(); r != nil { + result = 0 + } + }() + switch uint32(m) { + case wmCommand: + settingsCommand(wparam&0xFFFF, wparam>>16&0xFFFF) + return 0 + case wmHScroll: + if lparam == ctlAlpha && ctlAlpha != 0 { + pos, _, _ := pSendMessage.Call(ctlAlpha, tbmGetPos, 0, 0) + n := int(pos) + if n >= 3 && n <= 255 && n != bgAlpha { + bgAlpha = n + pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%")))) + redraw(hwndMain) + flyRefreshAll() + } + if wparam&0xFFFF == tbEndTrack { + saveAlpha() + } + } + return 0 + case wmClose: + pDestroyWindow.Call(hwnd) + return 0 + case wmDestroy: + hwndSettings = 0 + return 0 + } + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +}