diff --git a/README.md b/README.md index 68e8a49..b8f9bdd 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,60 @@ -# 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. - -- "Show weather on the bar" and "Show local news on the bar" in the settings window turn either 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. +- 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`. + diff --git a/render.go b/render.go index 47a3db2..540d39b 100644 --- a/render.go +++ b/render.go @@ -1,390 +1,392 @@ -package main - -// Painting the bar smoothly on a see-through background. -// -// Drawing icons and text straight onto a dark bitmap leaves a dark fringe -// around them once the background is made see-through. So the bar is painted -// in layers: one layer with only the backgrounds, and the icons, text and -// symbols drawn twice (once on black, once on white) at double size. Comparing -// the two copies shows exactly how see-through every edge pixel is, and -// shrinking back down gives smooth edges with no dark outline. - -import ( - "math" - "os" - "path/filepath" - "strconv" - "strings" - "unsafe" -) - -const ( - superSample = 2 - mfPopup = 0x0010 - - menuLogoColorBase = 100 - menuClockColorBase = 120 - menuIconColorBase = 140 -) - -var ( - fontTime2 uintptr - fontApp2 uintptr -) - -// initSuperFonts makes the double size fonts used for the smooth pass. -func initSuperFonts() { - scale *= superSample - fontTime2 = makeFont(px(13), 400) - fontApp2 = makeFont(px(12), 600) - scale /= superSample -} - -// ---------- colors ---------- - -type namedColor struct { - name string - r, g, b int -} - -var palette = []namedColor{ - {"White", 245, 245, 245}, - {"Blue", 0, 120, 212}, - {"Sky blue", 90, 190, 255}, - {"Green", 70, 200, 110}, - {"Yellow", 255, 205, 60}, - {"Orange", 255, 140, 40}, - {"Red", 235, 70, 70}, - {"Pink", 255, 125, 195}, - {"Purple", 175, 115, 240}, - {"Black", 0, 0, 0}, -} - -var ( - logoIdx = 1 // Blue, like the real Windows logo - clockIdx = 0 // White - iconIdx = 0 // White: battery, volume, wifi and the hidden-icons arrow -) - -func colorOf(i int) uintptr { - if i < 0 || i >= len(palette) { - i = 0 - } - c := palette[i] - r, g, b := styleColor(c.r, c.g, c.b) - return rgb(r, g, b) -} - -func logoColor() uintptr { return colorOf(logoIdx) } -func clockColor() uintptr { return colorOf(clockIdx) } -func iconColor() uintptr { return colorOf(iconIdx) } - -// iconDim is the color of the "off" bars on the volume and wifi icons. -func iconDim() uintptr { - c := palette[iconIdx] - if c.r+c.g+c.b < 300 { // a dark icon color: the off bars are lighter - return rgb(140, 140, 150) - } - return rgb(110, 110, 120) -} - -func colorsFile() string { return filepath.Join(dataDir(), "colors.txt") } - -func loadColors() { - b, err := os.ReadFile(colorsFile()) - if err != nil { - return - } - parts := strings.Split(strings.TrimSpace(string(b)), ",") - if len(parts) < 2 || len(parts) > 3 { - return - } - vals := []int{0, 0, 0} - for i, p := range parts { - n, err := strconv.Atoi(p) - if err != nil || n < 0 || n >= len(palette) { - return - } - vals[i] = n - } - logoIdx, clockIdx, iconIdx = vals[0], vals[1], vals[2] -} - -func saveColors() { - _ = os.MkdirAll(dataDir(), 0o755) - _ = os.WriteFile(colorsFile(), []byte(strconv.Itoa(logoIdx)+","+strconv.Itoa(clockIdx)+","+strconv.Itoa(iconIdx)), 0o644) -} - -// addColorMenus adds the two color pickers as sub menus. -func addColorMenus(menu uintptr) { - build := func(base uintptr, cur int, title string) { - sub, _, _ := pCreatePopupMenu.Call() - for i, c := range palette { - var flags uintptr - if i == cur { - flags = mfChecked - } - pAppendMenu.Call(sub, flags, base+uintptr(i), uintptr(unsafe.Pointer(u16(c.name)))) - } - pAppendMenu.Call(menu, mfPopup, sub, uintptr(unsafe.Pointer(u16(title)))) - } - build(menuLogoColorBase, logoIdx, "Windows logo color") - build(menuClockColorBase, clockIdx, "Clock color") - build(menuIconColorBase, iconIdx, "Tray icon color") - addStyleMenu(menu) -} - -func handleColorCommand(cmd uintptr) bool { - n := uintptr(len(palette)) - switch { - case cmd >= menuLogoColorBase && cmd < menuLogoColorBase+n: - logoIdx = int(cmd - menuLogoColorBase) - case cmd >= menuClockColorBase && cmd < menuClockColorBase+n: - clockIdx = int(cmd - menuClockColorBase) - case cmd >= menuIconColorBase && cmd < menuIconColorBase+n: - iconIdx = int(cmd - menuIconColorBase) - case handleStyleCommand(cmd): - return true - default: - return false - } - saveColors() - return true -} - -// ---------- painting ---------- - -// renderLayer paints one layer of the bar (w by h in the horizontal layout) -// and returns its pixels at the real orientation. fills and fg choose which -// parts are painted; base is the color everything is painted onto. -func renderLayer(screen uintptr, w, h int32, fills, fg bool, base uintptr) []uint32 { - layerFills, layerFg = fills, fg - defer func() { layerFills, layerFg = true, true }() - - 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 nil - } - defer pDeleteObject.Call(bmp) - old, _, _ := pSelectObject.Call(mem, bmp) - defer pSelectObject.Call(mem, old) - - fillRaw(mem, rect{0, 0, w, h}, base) - sr := startRect(w, h) - if hoverStart { - fill(mem, sr, rgb(58, 58, 68)) - } - drawLogo(mem, sr) - drawApps(mem, w, h) - drawTray(mem, w, h) - pGdiFlush.Call() - - src := unsafe.Slice((*uint32)(bits), int(w)*int(h)) - if !vertical { - out := make([]uint32, len(src)) - copy(out, src) - return out - } - - // Turn a quarter turn, then put the icons and symbols back on upright. - 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 nil - } - defer pDeleteObject.Call(bmpV) - memV, _, _ := pCreateCompatibleDC.Call(screen) - defer pDeleteDC.Call(memV) - oldV, _, _ := pSelectObject.Call(memV, bmpV) - defer pSelectObject.Call(memV, oldV) - - 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)] - } - } - if fg { - 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) - case trayWeather: - drawWeatherIcon(memV, r) - case trayNews: - drawNewsIcon(memV, r) - case traySys: - drawSysIcon(memV, r) - } - } - pGdiFlush.Call() - } - out := make([]uint32, len(dst)) - copy(out, dst) - return out -} - -// avg4 averages the superSample x superSample block of pixels that makes up -// one real pixel, one color channel at a time. -func avg4(p []uint32, stride, x, y int) (r, g, b uint32) { - var sr, sg, sb uint32 - for dy := 0; dy < superSample; dy++ { - for dx := 0; dx < superSample; dx++ { - c := p[(y*superSample+dy)*stride+x*superSample+dx] - sr += c >> 16 & 0xFF - sg += c >> 8 & 0xFF - sb += c & 0xFF - } - } - n := uint32(superSample * superSample) - return sr / n, sg / n, sb / n -} - -// redraw paints the whole bar and hands it to Windows as a layered window -// with a transparency value for every pixel. -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 - } - fw, fh := w, h - if vertical { - fw, fh = h, w - } - - screen, _, _ := pGetDC.Call(0) - defer pReleaseDC.Call(0, screen) - - // Layer 1: backgrounds, at real size. - bgPix := renderLayer(screen, w, h, true, false, rgb(22, 22, 26)) - - // Layers 2 and 3: icons, text and symbols on black and on white, at double size. - savedScale, savedTime, savedApp := scale, fontTime, fontApp - scale *= superSample - fontTime, fontApp = fontTime2, fontApp2 - onBlack := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(0, 0, 0)) - onWhite := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(255, 255, 255)) - scale, fontTime, fontApp = savedScale, savedTime, savedApp - - n := int(fw) * int(fh) - if len(bgPix) != n || len(onBlack) != n*superSample*superSample || len(onWhite) != len(onBlack) { - return - } - - // The finished bitmap that Windows will show. - mem, _, _ := pCreateCompatibleDC.Call(screen) - defer pDeleteDC.Call(mem) - bmi := bitmapInfoHeader{Width: fw, Height: -fh, 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) - pix := unsafe.Slice((*uint32)(bits), n) - - a := uint32(bgAlpha) - hoverA := max(a, 120) - length := float64(max(fw, fh)) - rad := float64(min(fw, fh)) / 2 - stride := int(fw) * superSample - - for i := range pix { - x, y := i%int(fw), i/int(fw) - - // Background layer: the pill color or a hover highlight, at its own see-through level. - c := bgPix[i] & 0x00FFFFFF - bgA := a - if c != colBg { - bgA = hoverA - } - bgR := (c >> 16 & 0xFF) * bgA / 255 - bgG := (c >> 8 & 0xFF) * bgA / 255 - bgB := (c & 0xFF) * bgA / 255 - - // Foreground: how solid is this pixel, and what color is it. - br, bgn, bb := avg4(onBlack, stride, x, y) - wr, wg, wb := avg4(onWhite, stride, x, y) - d := (sub0(wr, br) + sub0(wg, bgn) + sub0(wb, bb)) / 3 - fa := 255 - min(d, 255) // 255 where the two copies match (solid), 0 where they differ fully - fr, fg, fb := min(br, fa), min(bgn, fa), min(bb, fa) - - // Foreground over background. - inv := 255 - fa - oa := fa + bgA*inv/255 - or := fr + bgR*inv/255 - og := fg + bgG*inv/255 - ob := fb + bgB*inv/255 - - // Rounded ends: how much of this pixel is inside the pill. - along := float64(x) + 0.5 - across := float64(y) + 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 := math.Max(0, math.Min(1, rad-math.Hypot(da, across-rad)+0.5)) - sc := func(v uint32) uint32 { return uint32(float64(v) * cov) } - pix[i] = sc(oa)<<24 | sc(or)<<16 | sc(og)<<8 | sc(ob) - } - - 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)), - mem, uintptr(unsafe.Pointer(&src)), 0, - uintptr(unsafe.Pointer(&blend)), ulwAlpha) -} - -func sub0(a, b uint32) uint32 { - if a > b { - return a - b - } - return 0 -} +package main + +// Painting the bar smoothly on a see-through background. +// +// Drawing icons and text straight onto a dark bitmap leaves a dark fringe +// around them once the background is made see-through. So the bar is painted +// in layers: one layer with only the backgrounds, and the icons, text and +// symbols drawn twice (once on black, once on white) at double size. Comparing +// the two copies shows exactly how see-through every edge pixel is, and +// shrinking back down gives smooth edges with no dark outline. + +import ( + "math" + "os" + "path/filepath" + "strconv" + "strings" + "unsafe" +) + +const ( + superSample = 2 + mfPopup = 0x0010 + + menuLogoColorBase = 100 + menuClockColorBase = 120 + menuIconColorBase = 140 +) + +var ( + fontTime2 uintptr + fontApp2 uintptr +) + +// initSuperFonts makes the double size fonts used for the smooth pass. +func initSuperFonts() { + scale *= superSample + fontTime2 = makeFont(px(13), 400) + fontApp2 = makeFont(px(12), 600) + scale /= superSample +} + +// ---------- colors ---------- + +type namedColor struct { + name string + r, g, b int +} + +var palette = []namedColor{ + {"White", 245, 245, 245}, + {"Blue", 0, 120, 212}, + {"Sky blue", 90, 190, 255}, + {"Green", 70, 200, 110}, + {"Yellow", 255, 205, 60}, + {"Orange", 255, 140, 40}, + {"Red", 235, 70, 70}, + {"Pink", 255, 125, 195}, + {"Purple", 175, 115, 240}, + {"Black", 0, 0, 0}, +} + +var ( + logoIdx = 1 // Blue, like the real Windows logo + clockIdx = 0 // White + iconIdx = 0 // White: battery, volume, wifi and the hidden-icons arrow +) + +func colorOf(i int) uintptr { + if i < 0 || i >= len(palette) { + i = 0 + } + c := palette[i] + r, g, b := styleColor(c.r, c.g, c.b) + return rgb(r, g, b) +} + +func logoColor() uintptr { return colorOf(logoIdx) } +func clockColor() uintptr { return colorOf(clockIdx) } +func iconColor() uintptr { return colorOf(iconIdx) } + +// iconDim is the color of the "off" bars on the volume and wifi icons. +func iconDim() uintptr { + c := palette[iconIdx] + if c.r+c.g+c.b < 300 { // a dark icon color: the off bars are lighter + return rgb(140, 140, 150) + } + return rgb(110, 110, 120) +} + +func colorsFile() string { return filepath.Join(dataDir(), "colors.txt") } + +func loadColors() { + b, err := os.ReadFile(colorsFile()) + if err != nil { + return + } + parts := strings.Split(strings.TrimSpace(string(b)), ",") + if len(parts) < 2 || len(parts) > 3 { + return + } + vals := []int{0, 0, 0} + for i, p := range parts { + n, err := strconv.Atoi(p) + if err != nil || n < 0 || n >= len(palette) { + return + } + vals[i] = n + } + logoIdx, clockIdx, iconIdx = vals[0], vals[1], vals[2] +} + +func saveColors() { + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(colorsFile(), []byte(strconv.Itoa(logoIdx)+","+strconv.Itoa(clockIdx)+","+strconv.Itoa(iconIdx)), 0o644) +} + +// addColorMenus adds the two color pickers as sub menus. +func addColorMenus(menu uintptr) { + build := func(base uintptr, cur int, title string) { + sub, _, _ := pCreatePopupMenu.Call() + for i, c := range palette { + var flags uintptr + if i == cur { + flags = mfChecked + } + pAppendMenu.Call(sub, flags, base+uintptr(i), uintptr(unsafe.Pointer(u16(c.name)))) + } + pAppendMenu.Call(menu, mfPopup, sub, uintptr(unsafe.Pointer(u16(title)))) + } + build(menuLogoColorBase, logoIdx, "Windows logo color") + build(menuClockColorBase, clockIdx, "Clock color") + build(menuIconColorBase, iconIdx, "Tray icon color") + addStyleMenu(menu) +} + +func handleColorCommand(cmd uintptr) bool { + n := uintptr(len(palette)) + switch { + case cmd >= menuLogoColorBase && cmd < menuLogoColorBase+n: + logoIdx = int(cmd - menuLogoColorBase) + case cmd >= menuClockColorBase && cmd < menuClockColorBase+n: + clockIdx = int(cmd - menuClockColorBase) + case cmd >= menuIconColorBase && cmd < menuIconColorBase+n: + iconIdx = int(cmd - menuIconColorBase) + case handleStyleCommand(cmd): + return true + default: + return false + } + saveColors() + return true +} + +// ---------- painting ---------- + +// renderLayer paints one layer of the bar (w by h in the horizontal layout) +// and returns its pixels at the real orientation. fills and fg choose which +// parts are painted; base is the color everything is painted onto. +func renderLayer(screen uintptr, w, h int32, fills, fg bool, base uintptr) []uint32 { + layerFills, layerFg = fills, fg + defer func() { layerFills, layerFg = true, true }() + + 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 nil + } + defer pDeleteObject.Call(bmp) + old, _, _ := pSelectObject.Call(mem, bmp) + defer pSelectObject.Call(mem, old) + + fillRaw(mem, rect{0, 0, w, h}, base) + sr := startRect(w, h) + if hoverStart { + fill(mem, sr, rgb(58, 58, 68)) + } + drawLogo(mem, sr) + drawApps(mem, w, h) + drawTray(mem, w, h) + pGdiFlush.Call() + + src := unsafe.Slice((*uint32)(bits), int(w)*int(h)) + if !vertical { + out := make([]uint32, len(src)) + copy(out, src) + return out + } + + // Turn a quarter turn, then put the icons and symbols back on upright. + 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 nil + } + defer pDeleteObject.Call(bmpV) + memV, _, _ := pCreateCompatibleDC.Call(screen) + defer pDeleteDC.Call(memV) + oldV, _, _ := pSelectObject.Call(memV, bmpV) + defer pSelectObject.Call(memV, oldV) + + 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)] + } + } + if fg { + 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) + case trayWeather: + drawWeatherIcon(memV, r) + case trayNews: + drawNewsIcon(memV, r) + case traySys: + drawSysIcon(memV, r) + case trayGM: + drawGMIcon(memV, r) + } + } + pGdiFlush.Call() + } + out := make([]uint32, len(dst)) + copy(out, dst) + return out +} + +// avg4 averages the superSample x superSample block of pixels that makes up +// one real pixel, one color channel at a time. +func avg4(p []uint32, stride, x, y int) (r, g, b uint32) { + var sr, sg, sb uint32 + for dy := 0; dy < superSample; dy++ { + for dx := 0; dx < superSample; dx++ { + c := p[(y*superSample+dy)*stride+x*superSample+dx] + sr += c >> 16 & 0xFF + sg += c >> 8 & 0xFF + sb += c & 0xFF + } + } + n := uint32(superSample * superSample) + return sr / n, sg / n, sb / n +} + +// redraw paints the whole bar and hands it to Windows as a layered window +// with a transparency value for every pixel. +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 + } + fw, fh := w, h + if vertical { + fw, fh = h, w + } + + screen, _, _ := pGetDC.Call(0) + defer pReleaseDC.Call(0, screen) + + // Layer 1: backgrounds, at real size. + bgPix := renderLayer(screen, w, h, true, false, rgb(22, 22, 26)) + + // Layers 2 and 3: icons, text and symbols on black and on white, at double size. + savedScale, savedTime, savedApp := scale, fontTime, fontApp + scale *= superSample + fontTime, fontApp = fontTime2, fontApp2 + onBlack := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(0, 0, 0)) + onWhite := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(255, 255, 255)) + scale, fontTime, fontApp = savedScale, savedTime, savedApp + + n := int(fw) * int(fh) + if len(bgPix) != n || len(onBlack) != n*superSample*superSample || len(onWhite) != len(onBlack) { + return + } + + // The finished bitmap that Windows will show. + mem, _, _ := pCreateCompatibleDC.Call(screen) + defer pDeleteDC.Call(mem) + bmi := bitmapInfoHeader{Width: fw, Height: -fh, 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) + pix := unsafe.Slice((*uint32)(bits), n) + + a := uint32(bgAlpha) + hoverA := max(a, 120) + length := float64(max(fw, fh)) + rad := float64(min(fw, fh)) / 2 + stride := int(fw) * superSample + + for i := range pix { + x, y := i%int(fw), i/int(fw) + + // Background layer: the pill color or a hover highlight, at its own see-through level. + c := bgPix[i] & 0x00FFFFFF + bgA := a + if c != colBg { + bgA = hoverA + } + bgR := (c >> 16 & 0xFF) * bgA / 255 + bgG := (c >> 8 & 0xFF) * bgA / 255 + bgB := (c & 0xFF) * bgA / 255 + + // Foreground: how solid is this pixel, and what color is it. + br, bgn, bb := avg4(onBlack, stride, x, y) + wr, wg, wb := avg4(onWhite, stride, x, y) + d := (sub0(wr, br) + sub0(wg, bgn) + sub0(wb, bb)) / 3 + fa := 255 - min(d, 255) // 255 where the two copies match (solid), 0 where they differ fully + fr, fg, fb := min(br, fa), min(bgn, fa), min(bb, fa) + + // Foreground over background. + inv := 255 - fa + oa := fa + bgA*inv/255 + or := fr + bgR*inv/255 + og := fg + bgG*inv/255 + ob := fb + bgB*inv/255 + + // Rounded ends: how much of this pixel is inside the pill. + along := float64(x) + 0.5 + across := float64(y) + 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 := math.Max(0, math.Min(1, rad-math.Hypot(da, across-rad)+0.5)) + sc := func(v uint32) uint32 { return uint32(float64(v) * cov) } + pix[i] = sc(oa)<<24 | sc(or)<<16 | sc(og)<<8 | sc(ob) + } + + 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)), + mem, uintptr(unsafe.Pointer(&src)), 0, + uintptr(unsafe.Pointer(&blend)), ulwAlpha) +} + +func sub0(a, b uint32) uint32 { + if a > b { + return a - b + } + return 0 +} diff --git a/settings.go b/settings.go index f12749c..d2abed6 100644 --- a/settings.go +++ b/settings.go @@ -1,368 +1,373 @@ -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 -) - -var ( - hwndSettings uintptr - settingsClass bool - settingsFont uintptr - - ctlAlpha, ctlAlphaValue, ctlLogo, ctlClock, ctlTrayIcons, ctlStyle uintptr - ctlVertical, ctlAutostart uintptr - ctlZip, ctlZipStatus uintptr - ctlShowWeather, ctlShowNews, ctlShowSys, 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(488)} - 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) - ctlPanelFade = makeControl(hw, inst, "BUTTON", "Panels match the bar's transparency", bsAutoCheckBox|wsTabStop, 16, 346, 368, 22, idPanelFade) - ctlVertical = makeControl(hw, inst, "BUTTON", "Stand the bar up at the right edge (vertical)", bsAutoCheckBox|wsTabStop, 16, 374, 368, 22, idVertical) - ctlAutostart = makeControl(hw, inst, "BUTTON", "Start MirrorBar when I sign in", bsAutoCheckBox|wsTabStop, 16, 402, 368, 22, idAutostart) - - makeControl(hw, inst, "BUTTON", "Reset position", bsPushButton|wsTabStop, 16, 442, 116, 28, idResetPos) - makeControl(hw, inst, "BUTTON", "Reset bar width", bsPushButton|wsTabStop, 140, 442, 116, 28, idResetWidth) - makeControl(hw, inst, "BUTTON", "Close", bsDefPushButton|wsTabStop, 292, 442, 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(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 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 +) + +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 +} diff --git a/sysflyout.go b/sysflyout.go index 95b23ef..17bf199 100644 --- a/sysflyout.go +++ b/sysflyout.go @@ -1,270 +1,271 @@ -package main - -// The system stats flyout: a little monitor on the bar that opens a panel with -// the sort of thing neofetch prints (OS, CPU, memory, disks, uptime...). Click a -// line to copy it, or click the header to copy everything as plain text that can -// be pasted into any other program. - -import ( - "syscall" - "time" - "unsafe" -) - -const ( - sysW = 420.0 - sysHead = 44.0 - sysRow_ = 24.0 - sysFoot = 26.0 - - sysRefreshTimerID = 2 -) - -var ( - sysHwnd uintptr - sysShown bool - sysPrevBtn bool - sysHover = -1 - sysRows []sysRow - sysCopied string // what the header says after a copy: "Copied" or "Copy failed" - sysCopiedAt time.Time - sysTick int -) - -// ---------- the button on the bar ---------- - -func drawSysIcon(hdc uintptr, r rect) { - if !layerFg { - return - } - col := iconColor() - cx, cy := center(r) - e := px(1) - l, t, rt, b := cx-px(6), cy-px(5.5), cx+px(6), cy+px(2.5) - 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) - fillRaw(hdc, rect{cx - px(1), b, cx + px(1), cy + px(4.5)}, col) // stand - fillRaw(hdc, rect{cx - px(3), cy + px(4.5), cx + px(3), cy + px(5.5)}, col) - fillRaw(hdc, rect{cx - px(3.5), cy - px(0.5), cx - px(2), cy + px(1.5)}, col) // little bars on the screen - fillRaw(hdc, rect{cx - px(1), cy - px(2.5), cx + px(0.5), cy + px(1.5)}, col) - fillRaw(hdc, rect{cx + px(2), cy - px(1.5), cx + px(3.5), cy + px(1.5)}, col) -} - -// ---------- the panel window ---------- - -func sysInit(inst uintptr) { - cursor, _, _ := pLoadCursor.Call(0, idcArrow) - className := u16("MirrorBarSys") - wc := wndClassEx{ - WndProc: syscall.NewCallback(sysProc), - Instance: inst, - Cursor: cursor, - ClassName: className, - } - wc.Size = uint32(unsafe.Sizeof(wc)) - pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) - sysHwnd, _, _ = pCreateWindowEx.Call( - wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, - uintptr(unsafe.Pointer(className)), - uintptr(unsafe.Pointer(u16(""))), - wsPopup, - 0, 0, 10, 10, - 0, 0, inst, 0) -} - -func sysProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { - defer func() { - if r := recover(); r != nil { - result = 0 // the flyout is optional; never take the bar down with it - } - }() - switch uint32(m) { - case wmEraseBkgnd: - return 1 - case wmMouseActivate: - return maNoActivate - case wmPaint: - flyPaint(hwnd, sysDraw) - return 0 - case wmTimer: - if wparam == sysRefreshTimerID { - sysRows = sysGather() // uptime and memory move - flyRefresh(sysHwnd) - return 0 - } - sysPoll() - return 0 - case wmSetCursor: - if sysOverButton() { - h, _, _ := pLoadCursor.Call(0, idcHandCursor) - pSetCursor.Call(h) - return 1 - } - case wmLButtonUp: - sysClick(int32(int16(lparam&0xFFFF)), int32(int16(lparam>>16&0xFFFF))) - return 0 - } - r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) - return r -} - -// sysOverButton is true when the mouse is on something clickable: a line or the header. -func sysOverButton() bool { - var cp point - pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) - var fr rect - pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr))) - if !inRect(fr, cp) { - return false - } - y := cp.Y - fr.Top - return y < px(sysHead) || sysRowAt(y) >= 0 -} - -func sysToggle() { - if !showSys { - return - } - if sysShown { - sysHide() - return - } - if sysHwnd == 0 { - return - } - previewHide() - weatherHide() // one panel at a time - newsHide() - sysRows = sysGather() - sysShown = true - sysPrevBtn = true // ignore a button that is still held from the click that opened this - sysHover = -1 - sysCopied = "" - sysPlace() - pSetTimer.Call(sysHwnd, wxPollTimerID, 80, 0) - pSetTimer.Call(sysHwnd, sysRefreshTimerID, 1500, 0) -} - -func sysHide() { - if !sysShown { - return - } - sysShown = false - sysHover = -1 - pKillTimer.Call(sysHwnd, wxPollTimerID) - pKillTimer.Call(sysHwnd, sysRefreshTimerID) - pShowWindow.Call(sysHwnd, swHide) -} - -func sysShutdown() { - sysHide() - if sysHwnd != 0 { - pDestroyWindow.Call(sysHwnd) - sysHwnd = 0 - } -} - -func sysPlace() { - if sysHwnd == 0 { - return - } - lh := sysHead + float64(len(sysRows))*sysRow_ + sysFoot - flyPlace(sysHwnd, trayAnchor(traySys), px(sysW), px(lh)) - flyRefresh(sysHwnd) -} - -// sysRowAt is the line under a height in the panel (real pixels), or -1. -func sysRowAt(y int32) int { - ry := y - px(sysHead) - if ry < 0 { - return -1 - } - i := int(ry / px(sysRow_)) - if i >= len(sysRows) { - return -1 - } - return i -} - -func sysPoll() { - l, _, _ := pGetAsyncKeyState.Call(vkLButton) - r, _, _ := pGetAsyncKeyState.Call(vkRButton) - down := (l|r)&0x8000 != 0 - var cp point - pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) - var fr rect - pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr))) - if down && !sysPrevBtn && !inRect(fr, cp) && !inRect(trayAnchor(traySys), cp) { - sysHide() - sysPrevBtn = down - return - } - sysPrevBtn = down - - h := -1 - if inRect(fr, cp) { - h = sysRowAt(cp.Y - fr.Top) - } - changed := h != sysHover - sysHover = h - if sysCopied != "" && time.Since(sysCopiedAt) > 1500*time.Millisecond { - sysCopied = "" - changed = true - } - if changed { - flyRefresh(sysHwnd) - } -} - -func sysCopy(text, what string) { - if clipboardSet(text) { - sysCopied = what - } else { - sysCopied = "Copy failed" - } - sysCopiedAt = time.Now() - flyRefresh(sysHwnd) -} - -func sysClick(x, y int32) { - if y < px(sysHead) { - sysCopy(sysText(sysRows), "Copied everything") - return - } - if i := sysRowAt(y); i >= 0 { - sysCopy(sysRows[i].label+": "+sysRows[i].value, "Copied "+sysRows[i].label) - } -} - -// ---------- painting ---------- - -func sysDraw(hdc uintptr, W, H int32) { - u := px - flyFrame(hdc, W, H) // outline in the tray icon color; the background is added when painting - - pad := u(14) - line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis) - wxText(hdc, sysUserHost(), rect{pad, u(10), W - pad - u(150), u(34)}, fMed, colText, line) - btn, col := "Copy all", colAccent - if sysCopied != "" { - btn, col = sysCopied, colDim - } - wxText(hdc, btn, rect{W - pad - u(150), u(12), W - pad, u(32)}, fBold, col, dtRight|dtVCenter|dtSingleLine|dtEndEllipsis) - fillRaw(hdc, rect{pad, u(sysHead) - u(2), W - pad, u(sysHead) - u(1)}, colRule) - - labelW := u(96) - for i, r := range sysRows { - y := u(sysHead) + int32(i)*u(sysRow_) - val := colText - if i == sysHover { - fillRaw(hdc, rect{u(6), y, W - u(6), y + u(sysRow_)}, rgb(40, 40, 48)) - val = colAccent - } - wxText(hdc, r.label, rect{pad, y, pad + labelW, y + u(sysRow_)}, fBold, colAccent, line) - wxText(hdc, r.value, rect{pad + labelW, y, W - pad, y + u(sysRow_)}, fText, val, line) - } - y := u(sysHead) + int32(len(sysRows))*u(sysRow_) - wxText(hdc, "Click a line to copy it, or the top to copy everything.", rect{pad, y + u(4), W - pad, H - u(2)}, fTiny, colDim, line) -} +package main + +// The system stats flyout: a little monitor on the bar that opens a panel with +// the sort of thing neofetch prints (OS, CPU, memory, disks, uptime...). Click a +// line to copy it, or click the header to copy everything as plain text that can +// be pasted into any other program. + +import ( + "syscall" + "time" + "unsafe" +) + +const ( + sysW = 420.0 + sysHead = 44.0 + sysRow_ = 24.0 + sysFoot = 26.0 + + sysRefreshTimerID = 2 +) + +var ( + sysHwnd uintptr + sysShown bool + sysPrevBtn bool + sysHover = -1 + sysRows []sysRow + sysCopied string // what the header says after a copy: "Copied" or "Copy failed" + sysCopiedAt time.Time + sysTick int +) + +// ---------- the button on the bar ---------- + +func drawSysIcon(hdc uintptr, r rect) { + if !layerFg { + return + } + col := iconColor() + cx, cy := center(r) + e := px(1) + l, t, rt, b := cx-px(6), cy-px(5.5), cx+px(6), cy+px(2.5) + 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) + fillRaw(hdc, rect{cx - px(1), b, cx + px(1), cy + px(4.5)}, col) // stand + fillRaw(hdc, rect{cx - px(3), cy + px(4.5), cx + px(3), cy + px(5.5)}, col) + fillRaw(hdc, rect{cx - px(3.5), cy - px(0.5), cx - px(2), cy + px(1.5)}, col) // little bars on the screen + fillRaw(hdc, rect{cx - px(1), cy - px(2.5), cx + px(0.5), cy + px(1.5)}, col) + fillRaw(hdc, rect{cx + px(2), cy - px(1.5), cx + px(3.5), cy + px(1.5)}, col) +} + +// ---------- the panel window ---------- + +func sysInit(inst uintptr) { + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + className := u16("MirrorBarSys") + wc := wndClassEx{ + WndProc: syscall.NewCallback(sysProc), + Instance: inst, + Cursor: cursor, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + sysHwnd, _, _ = pCreateWindowEx.Call( + wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, + uintptr(unsafe.Pointer(className)), + uintptr(unsafe.Pointer(u16(""))), + wsPopup, + 0, 0, 10, 10, + 0, 0, inst, 0) +} + +func sysProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { + defer func() { + if r := recover(); r != nil { + result = 0 // the flyout is optional; never take the bar down with it + } + }() + switch uint32(m) { + case wmEraseBkgnd: + return 1 + case wmMouseActivate: + return maNoActivate + case wmPaint: + flyPaint(hwnd, sysDraw) + return 0 + case wmTimer: + if wparam == sysRefreshTimerID { + sysRows = sysGather() // uptime and memory move + flyRefresh(sysHwnd) + return 0 + } + sysPoll() + return 0 + case wmSetCursor: + if sysOverButton() { + h, _, _ := pLoadCursor.Call(0, idcHandCursor) + pSetCursor.Call(h) + return 1 + } + case wmLButtonUp: + sysClick(int32(int16(lparam&0xFFFF)), int32(int16(lparam>>16&0xFFFF))) + return 0 + } + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +} + +// sysOverButton is true when the mouse is on something clickable: a line or the header. +func sysOverButton() bool { + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + var fr rect + pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr))) + if !inRect(fr, cp) { + return false + } + y := cp.Y - fr.Top + return y < px(sysHead) || sysRowAt(y) >= 0 +} + +func sysToggle() { + if !showSys { + return + } + if sysShown { + sysHide() + return + } + if sysHwnd == 0 { + return + } + previewHide() + weatherHide() // one panel at a time + newsHide() + gmHide() + sysRows = sysGather() + sysShown = true + sysPrevBtn = true // ignore a button that is still held from the click that opened this + sysHover = -1 + sysCopied = "" + sysPlace() + pSetTimer.Call(sysHwnd, wxPollTimerID, 80, 0) + pSetTimer.Call(sysHwnd, sysRefreshTimerID, 1500, 0) +} + +func sysHide() { + if !sysShown { + return + } + sysShown = false + sysHover = -1 + pKillTimer.Call(sysHwnd, wxPollTimerID) + pKillTimer.Call(sysHwnd, sysRefreshTimerID) + pShowWindow.Call(sysHwnd, swHide) +} + +func sysShutdown() { + sysHide() + if sysHwnd != 0 { + pDestroyWindow.Call(sysHwnd) + sysHwnd = 0 + } +} + +func sysPlace() { + if sysHwnd == 0 { + return + } + lh := sysHead + float64(len(sysRows))*sysRow_ + sysFoot + flyPlace(sysHwnd, trayAnchor(traySys), px(sysW), px(lh)) + flyRefresh(sysHwnd) +} + +// sysRowAt is the line under a height in the panel (real pixels), or -1. +func sysRowAt(y int32) int { + ry := y - px(sysHead) + if ry < 0 { + return -1 + } + i := int(ry / px(sysRow_)) + if i >= len(sysRows) { + return -1 + } + return i +} + +func sysPoll() { + l, _, _ := pGetAsyncKeyState.Call(vkLButton) + r, _, _ := pGetAsyncKeyState.Call(vkRButton) + down := (l|r)&0x8000 != 0 + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + var fr rect + pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr))) + if down && !sysPrevBtn && !inRect(fr, cp) && !inRect(trayAnchor(traySys), cp) { + sysHide() + sysPrevBtn = down + return + } + sysPrevBtn = down + + h := -1 + if inRect(fr, cp) { + h = sysRowAt(cp.Y - fr.Top) + } + changed := h != sysHover + sysHover = h + if sysCopied != "" && time.Since(sysCopiedAt) > 1500*time.Millisecond { + sysCopied = "" + changed = true + } + if changed { + flyRefresh(sysHwnd) + } +} + +func sysCopy(text, what string) { + if clipboardSet(text) { + sysCopied = what + } else { + sysCopied = "Copy failed" + } + sysCopiedAt = time.Now() + flyRefresh(sysHwnd) +} + +func sysClick(x, y int32) { + if y < px(sysHead) { + sysCopy(sysText(sysRows), "Copied everything") + return + } + if i := sysRowAt(y); i >= 0 { + sysCopy(sysRows[i].label+": "+sysRows[i].value, "Copied "+sysRows[i].label) + } +} + +// ---------- painting ---------- + +func sysDraw(hdc uintptr, W, H int32) { + u := px + flyFrame(hdc, W, H) // outline in the tray icon color; the background is added when painting + + pad := u(14) + line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis) + wxText(hdc, sysUserHost(), rect{pad, u(10), W - pad - u(150), u(34)}, fMed, colText, line) + btn, col := "Copy all", colAccent + if sysCopied != "" { + btn, col = sysCopied, colDim + } + wxText(hdc, btn, rect{W - pad - u(150), u(12), W - pad, u(32)}, fBold, col, dtRight|dtVCenter|dtSingleLine|dtEndEllipsis) + fillRaw(hdc, rect{pad, u(sysHead) - u(2), W - pad, u(sysHead) - u(1)}, colRule) + + labelW := u(96) + for i, r := range sysRows { + y := u(sysHead) + int32(i)*u(sysRow_) + val := colText + if i == sysHover { + fillRaw(hdc, rect{u(6), y, W - u(6), y + u(sysRow_)}, rgb(40, 40, 48)) + val = colAccent + } + wxText(hdc, r.label, rect{pad, y, pad + labelW, y + u(sysRow_)}, fBold, colAccent, line) + wxText(hdc, r.value, rect{pad + labelW, y, W - pad, y + u(sysRow_)}, fText, val, line) + } + y := u(sysHead) + int32(len(sysRows))*u(sysRow_) + wxText(hdc, "Click a line to copy it, or the top to copy everything.", rect{pad, y + u(4), W - pad, H - u(2)}, fTiny, colDim, line) +} diff --git a/tray.go b/tray.go index 07a2a6e..fb341bb 100644 --- a/tray.go +++ b/tray.go @@ -1,849 +1,875 @@ -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" - "os" - "path/filepath" - "strconv" - "strings" - "syscall" - "time" - "unsafe" -) - -const ( - trayClock = iota + 1 - trayBattery - trayVolume - trayWifi - trayChevron - trayWeather // added after the others so saved orders from older versions still mean the same thing - trayNews - traySys -) - -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 - - menuWeatherID = 26 - menuWeatherZipID = 27 - menuNewsID = 28 - menuNewsZipID = 29 - menuSysID = 34 - menuSysCopyID = 35 -) - -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 { - return trayItemsAt(axisX(clientW), clientH) -} - -// trayItemsAt lays the right-hand items out rightward from x. -func trayItemsAt(x, clientH int32) []trayItem { - var out []trayItem - for _, kind := range trayOrder { - var w int32 - switch kind { - case trayClock: - w = clockWidth() - case trayBattery: - if battPct < 0 { - continue // this PC has no battery - } - w = px(36) - case trayVolume, trayWifi: - w = px(36) - case trayWeather: - if !showWeather { - continue - } - w = px(36) - case trayNews: - if !showNews { - continue - } - w = px(36) - case traySys: - if !showSys { - continue - } - w = px(36) - case trayChevron: - w = px(28) - } - out = append(out, trayItem{kind, rect{x, 0, x + w, clientH}}) - x += w - } - 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 := iconColor() - - fillFg(hdc, rect{left, top, left + bw, top + t}, white) - fillFg(hdc, rect{left, top + bh - t, left + bw, top + bh}, white) - fillFg(hdc, rect{left, top, left + t, top + bh}, white) - fillFg(hdc, rect{left + bw - t, top, left + bw, top + bh}, white) - fillFg(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) - } - fillFg(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 := iconColor(), iconDim() - x0 := cx - px(9) - - fillFg(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 - } - fillFg(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 := iconColor(), iconDim() - - if netKind == netWired { - t := px(1) - l, tp := cx-px(7), cy-px(6) - w, h := px(14), px(9) - fillFg(hdc, rect{l, tp, l + w, tp + t}, white) - fillFg(hdc, rect{l, tp + h - t, l + w, tp + h}, white) - fillFg(hdc, rect{l, tp, l + t, tp + h}, white) - fillFg(hdc, rect{l + w - t, tp, l + w, tp + h}, white) - fillFg(hdc, rect{cx - px(1), tp + h, cx + px(1), tp + h + px(3)}, white) - fillFg(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 - } - fillFg(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), iconColor()) -} - -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 !layerFg || (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) - case trayWeather: - drawWeatherIcon(hdc, it.r) - case trayNews: - drawNewsIcon(hdc, it.r) - case traySys: - drawSysIcon(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. -const vkEscape = 0x1B - -// overflowOpen reports whether the hidden icons flyout is on screen. -func overflowOpen() bool { - for _, class := range []string{"TopLevelWindowForOverflowXamlIsland", "NotifyIconOverflowWindow"} { - h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16(class))), 0) - if h != 0 { - if vis, _, _ := pIsWindowVisible.Call(h); vis != 0 { - return true - } - } - } - return false -} - -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 trayWeather: - weatherToggle() - case trayNews: - newsToggle() - case traySys: - sysToggle() - case trayChevron: - // If the hidden icons are already showing, a second click closes them. Sending - // Win+B and Enter again would instead press Enter on the highlighted icon. - if overflowOpen() { - tapKey(vkEscape) - return - } - // 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() - case trayWeather: - add(0, menuWeatherID, "Show weather") - add(0, menuWeatherZipID, "Weather ZIP code...") - sep() - case trayNews: - add(0, menuNewsID, "Show local news") - add(0, menuNewsZipID, "News ZIP code...") - sep() - case traySys: - add(0, menuSysID, "Show system stats") - add(0, menuSysCopyID, "Copy system stats") - 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 menuWeatherID: - if !wxShown { - weatherToggle() - } - case menuNewsID: - if !newsShown { - newsToggle() - } - case menuSysID: - if !sysShown { - sysToggle() - } - case menuSysCopyID: - if clipboardSet(sysText(sysGather())) { - sysCopied = "Copied everything" - sysCopiedAt = time.Now() - } - case menuWeatherZipID, menuNewsZipID: - openSettings() - case menuAutostartID: - setAutostart(!autostartEnabled()) - case menuMuteID: - tapKey(vkVolumeMute) - time.Sleep(60 * time.Millisecond) - refreshStatus(false) - default: - return false - } - return true -} - -// ---------- the right row can be rearranged too ---------- - -// trayOrder is the left to right order of the items to the right of center. -var trayOrder = []int{trayClock, trayWeather, trayNews, traySys, trayBattery, trayVolume, trayWifi, trayChevron} - -var ( - dragTray int // the tray item the mouse went down on, 0 for none - dragTrayStart int32 // where along the bar the mouse went down - dragTrayActive bool // true once the mouse has moved far enough to count as a drag -) - -func trayOrderFile() string { return filepath.Join(dataDir(), "trayorder.txt") } - -func loadTrayOrder() { - b, err := os.ReadFile(trayOrderFile()) - if err != nil { - return - } - var order []int - seen := map[int]bool{} - for _, p := range strings.Split(strings.TrimSpace(string(b)), ",") { - n, err := strconv.Atoi(strings.TrimSpace(p)) - if err != nil || n < trayClock || n > traySys || seen[n] { - return - } - seen[n] = true - order = append(order, n) - } - // An order saved before the weather cloud or the newspaper existed: put the new - // icon next to the clock (the newspaper goes after the cloud). - insertAfter := func(after, kind int) { - out := make([]int, 0, len(order)+1) - for _, k := range order { - out = append(out, k) - if k == after { - out = append(out, kind) - } - } - order = out - seen[kind] = true - } - if !seen[trayWeather] { - insertAfter(trayClock, trayWeather) - } - if !seen[trayNews] { - insertAfter(trayWeather, trayNews) - } - if !seen[traySys] { - insertAfter(trayNews, traySys) - } - if len(order) == len(trayOrder) { - trayOrder = order - } -} - -func saveTrayOrder() { - parts := make([]string, len(trayOrder)) - for i, k := range trayOrder { - parts[i] = strconv.Itoa(k) - } - _ = os.MkdirAll(dataDir(), 0o755) - _ = os.WriteFile(trayOrderFile(), []byte(strings.Join(parts, ",")), 0o644) -} - -// trayKindAt is the tray item under a spot along the bar, clamped to the ends -// of the right row. -func trayKindAt(hwnd uintptr, x int32) int { - w, h := clientSize(hwnd) - items := trayItems(w, h) - if len(items) == 0 { - return 0 - } - if x < items[0].r.Left { - return items[0].kind - } - if x >= items[len(items)-1].r.Right { - return items[len(items)-1].kind - } - for _, it := range items { - if x >= it.r.Left && x < it.r.Right { - return it.kind - } - } - return 0 -} - -// moveTray puts one item where another one is, shifting the rest. -func moveTray(kind, target int) { - from, to := -1, -1 - for i, k := range trayOrder { - if k == kind { - from = i - } - if k == target { - to = i - } - } - if from < 0 || to < 0 || from == to { - return - } - rest := append(append([]int{}, trayOrder[:from]...), trayOrder[from+1:]...) - trayOrder = append(append(append([]int{}, rest[:to]...), kind), rest[to:]...) -} +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" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + trayClock = iota + 1 + trayBattery + trayVolume + trayWifi + trayChevron + trayWeather // added after the others so saved orders from older versions still mean the same thing + trayNews + traySys + trayGM // Google Messages +) + +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 + + menuWeatherID = 26 + menuWeatherZipID = 27 + menuNewsID = 28 + menuNewsZipID = 29 + menuSysID = 34 + menuSysCopyID = 35 + menuGMID = 36 + menuGMCloseID = 37 +) + +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 { + return trayItemsAt(axisX(clientW), clientH) +} + +// trayItemsAt lays the right-hand items out rightward from x. +func trayItemsAt(x, clientH int32) []trayItem { + var out []trayItem + for _, kind := range trayOrder { + var w int32 + switch kind { + case trayClock: + w = clockWidth() + case trayBattery: + if battPct < 0 { + continue // this PC has no battery + } + w = px(36) + case trayVolume, trayWifi: + w = px(36) + case trayWeather: + if !showWeather { + continue + } + w = px(36) + case trayNews: + if !showNews { + continue + } + w = px(36) + case traySys: + if !showSys { + continue + } + w = px(36) + case trayGM: + if !showGM { + continue + } + w = px(36) + case trayChevron: + w = px(28) + } + out = append(out, trayItem{kind, rect{x, 0, x + w, clientH}}) + x += w + } + 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 := iconColor() + + fillFg(hdc, rect{left, top, left + bw, top + t}, white) + fillFg(hdc, rect{left, top + bh - t, left + bw, top + bh}, white) + fillFg(hdc, rect{left, top, left + t, top + bh}, white) + fillFg(hdc, rect{left + bw - t, top, left + bw, top + bh}, white) + fillFg(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) + } + fillFg(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 := iconColor(), iconDim() + x0 := cx - px(9) + + fillFg(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 + } + fillFg(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 := iconColor(), iconDim() + + if netKind == netWired { + t := px(1) + l, tp := cx-px(7), cy-px(6) + w, h := px(14), px(9) + fillFg(hdc, rect{l, tp, l + w, tp + t}, white) + fillFg(hdc, rect{l, tp + h - t, l + w, tp + h}, white) + fillFg(hdc, rect{l, tp, l + t, tp + h}, white) + fillFg(hdc, rect{l + w - t, tp, l + w, tp + h}, white) + fillFg(hdc, rect{cx - px(1), tp + h, cx + px(1), tp + h + px(3)}, white) + fillFg(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 + } + fillFg(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), iconColor()) +} + +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 !layerFg || (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) + case trayWeather: + drawWeatherIcon(hdc, it.r) + case trayNews: + drawNewsIcon(hdc, it.r) + case traySys: + drawSysIcon(hdc, it.r) + case trayGM: + drawGMIcon(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. +const vkEscape = 0x1B + +// overflowOpen reports whether the hidden icons flyout is on screen. +func overflowOpen() bool { + for _, class := range []string{"TopLevelWindowForOverflowXamlIsland", "NotifyIconOverflowWindow"} { + h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16(class))), 0) + if h != 0 { + if vis, _, _ := pIsWindowVisible.Call(h); vis != 0 { + return true + } + } + } + return false +} + +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 trayWeather: + weatherToggle() + case trayNews: + newsToggle() + case traySys: + sysToggle() + case trayGM: + gmToggle() + case trayChevron: + // If the hidden icons are already showing, a second click closes them. Sending + // Win+B and Enter again would instead press Enter on the highlighted icon. + if overflowOpen() { + tapKey(vkEscape) + return + } + // 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() + case trayWeather: + add(0, menuWeatherID, "Show weather") + add(0, menuWeatherZipID, "Weather ZIP code...") + sep() + case trayNews: + add(0, menuNewsID, "Show local news") + add(0, menuNewsZipID, "News ZIP code...") + sep() + case traySys: + add(0, menuSysID, "Show system stats") + add(0, menuSysCopyID, "Copy system stats") + sep() + case trayGM: + add(0, menuGMID, "Show Messages") + add(0, menuGMCloseID, "Close Messages (stop checking for texts)") + 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 menuWeatherID: + if !wxShown { + weatherToggle() + } + case menuNewsID: + if !newsShown { + newsToggle() + } + case menuSysID: + if !sysShown { + sysToggle() + } + case menuGMID: + if !gmShown { + gmToggle() + } + case menuGMCloseID: + gmClose() + redraw(hwndMain) + case menuSysCopyID: + if clipboardSet(sysText(sysGather())) { + sysCopied = "Copied everything" + sysCopiedAt = time.Now() + } + case menuWeatherZipID, menuNewsZipID: + openSettings() + case menuAutostartID: + setAutostart(!autostartEnabled()) + case menuMuteID: + tapKey(vkVolumeMute) + time.Sleep(60 * time.Millisecond) + refreshStatus(false) + default: + return false + } + return true +} + +// ---------- the right row can be rearranged too ---------- + +// trayOrder is the left to right order of the items to the right of center. +var trayOrder = []int{trayClock, trayWeather, trayNews, traySys, trayGM, trayBattery, trayVolume, trayWifi, trayChevron} + +var ( + dragTray int // the tray item the mouse went down on, 0 for none + dragTrayStart int32 // where along the bar the mouse went down + dragTrayActive bool // true once the mouse has moved far enough to count as a drag +) + +func trayOrderFile() string { return filepath.Join(dataDir(), "trayorder.txt") } + +func loadTrayOrder() { + b, err := os.ReadFile(trayOrderFile()) + if err != nil { + return + } + var order []int + seen := map[int]bool{} + for _, p := range strings.Split(strings.TrimSpace(string(b)), ",") { + n, err := strconv.Atoi(strings.TrimSpace(p)) + if err != nil || n < trayClock || n > trayGM || seen[n] { + return + } + seen[n] = true + order = append(order, n) + } + // An order saved before the weather cloud or the newspaper existed: put the new + // icon next to the clock (the newspaper goes after the cloud). + insertAfter := func(after, kind int) { + out := make([]int, 0, len(order)+1) + for _, k := range order { + out = append(out, k) + if k == after { + out = append(out, kind) + } + } + order = out + seen[kind] = true + } + if !seen[trayWeather] { + insertAfter(trayClock, trayWeather) + } + if !seen[trayNews] { + insertAfter(trayWeather, trayNews) + } + if !seen[traySys] { + insertAfter(trayNews, traySys) + } + if !seen[trayGM] { + insertAfter(traySys, trayGM) + } + if len(order) == len(trayOrder) { + trayOrder = order + } +} + +func saveTrayOrder() { + parts := make([]string, len(trayOrder)) + for i, k := range trayOrder { + parts[i] = strconv.Itoa(k) + } + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(trayOrderFile(), []byte(strings.Join(parts, ",")), 0o644) +} + +// trayKindAt is the tray item under a spot along the bar, clamped to the ends +// of the right row. +func trayKindAt(hwnd uintptr, x int32) int { + w, h := clientSize(hwnd) + items := trayItems(w, h) + if len(items) == 0 { + return 0 + } + if x < items[0].r.Left { + return items[0].kind + } + if x >= items[len(items)-1].r.Right { + return items[len(items)-1].kind + } + for _, it := range items { + if x >= it.r.Left && x < it.r.Right { + return it.kind + } + } + return 0 +} + +// moveTray puts one item where another one is, shifting the rest. +func moveTray(kind, target int) { + from, to := -1, -1 + for i, k := range trayOrder { + if k == kind { + from = i + } + if k == target { + to = i + } + } + if from < 0 || to < 0 || from == to { + return + } + rest := append(append([]int{}, trayOrder[:from]...), trayOrder[from+1:]...) + trayOrder = append(append(append([]int{}, rest[:to]...), kind), rest[to:]...) +}