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 || !showBattery { continue // this PC has no battery, or it was turned off in the settings } w = px(36) case trayVolume: if !showVolume { continue } w = px(36) case trayWifi: if !showWifi { continue } 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:]...) }