From db0249bc14e52802be052cb839c361bd3a37461a Mon Sep 17 00:00:00 2001 From: weishaupt <1+weishaupt@noreply.localhost> Date: Sun, 8 Nov 2026 02:58:31 +0000 Subject: [PATCH] MirrorBar+ part 3: local news flyout, system stats flyout with copy, feature switches --- features.go | 115 ++++++++++++++++ newsfeed.go | 98 ++++++++++++++ newsflyout.go | 360 ++++++++++++++++++++++++++++++++++++++++++++++++++ sysflyout.go | 271 +++++++++++++++++++++++++++++++++++++ sysinfo.go | 298 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1142 insertions(+) create mode 100644 features.go create mode 100644 newsfeed.go create mode 100644 newsflyout.go create mode 100644 sysflyout.go create mode 100644 sysinfo.go diff --git a/features.go b/features.go new file mode 100644 index 0000000..1f0a551 --- /dev/null +++ b/features.go @@ -0,0 +1,115 @@ +package main + +// The two optional features, weather and local news. Each can be turned off in +// the settings window: its icon leaves the bar, its panel is closed, and nothing +// is downloaded for it. Both are on until switched off. + +import ( + "os" + "path/filepath" + "strings" +) + +var ( + showWeather = true + showNews = true + showSys = true +) + +func featuresFile() string { return filepath.Join(dataDir(), "features.txt") } + +func loadFeatures() { + b, err := os.ReadFile(featuresFile()) + if err != nil { + return + } + for _, ln := range strings.Split(string(b), "\n") { + k, v, ok := strings.Cut(strings.TrimSpace(ln), "=") + if !ok { + continue + } + on := strings.TrimSpace(v) != "0" + switch strings.TrimSpace(k) { + case "weather": + showWeather = on + case "news": + showNews = on + case "sys": + showSys = on + } + } +} + +func saveFeatures() { + s := "weather=" + b01(showWeather) + "\nnews=" + b01(showNews) + "\nsys=" + b01(showSys) + "\n" + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(featuresFile(), []byte(s), 0o644) +} + +func b01(b bool) string { + if b { + return "1" + } + return "0" +} + +// setShowWeather is called by the settings window. +func setShowWeather(on bool) { + if showWeather == on { + return + } + showWeather = on + saveFeatures() + if on { + weatherRefresh(false) + } else { + weatherHide() + } + featuresChanged() +} + +// setShowNews is called by the settings window. +func setShowNews(on bool) { + if showNews == on { + return + } + showNews = on + saveFeatures() + if on { + newsRefresh(false) + } else { + newsHide() + } + featuresChanged() +} + +// setShowSys is called by the settings window. +func setShowSys(on bool) { + if showSys == on { + return + } + showSys = on + saveFeatures() + if !on { + sysHide() + } + featuresChanged() +} + +func featuresChanged() { + settingsZipStatusUpdate() + redraw(hwndMain) +} + +// zipStatusText is the one line the settings window shows under the ZIP box. +func zipStatusText() string { + switch { + case !showWeather && !showNews: + return "Weather and news are both turned off." + case wxZip == "": + return "Type a 5 digit ZIP code to turn on weather and local news." + case showWeather: + return weatherStatusText() + } + return newsStatusText() +} diff --git a/newsfeed.go b/newsfeed.go new file mode 100644 index 0000000..e3ef13c --- /dev/null +++ b/newsfeed.go @@ -0,0 +1,98 @@ +package main + +// Reading a news feed. Only the standard library, no Windows calls, so it can +// be tested on its own. +// +// Local headlines come from Google News' place feed: it takes a place name such +// as "Huntington, Indiana" and returns what local papers, TV and radio stations +// near it are publishing. The place name comes from the ZIP code (the weather +// lookup already finds it), so the same ZIP code serves both panels. + +import ( + "encoding/xml" + "fmt" + "html" + "net/url" + "sort" + "strings" + "time" +) + +type newsItem struct { + title string + source string + link string + when time.Time +} + +const newsKeep = 30 // headlines kept per lookup + +func newsFeedURL(place string) string { + return "https://news.google.com/rss/headlines/section/geo/" + url.PathEscape(place) + "?hl=en-US&gl=US&ceid=US:en" +} + +// newsParse turns the feed into headlines, newest first. Only web links are +// kept, so nothing odd can be opened from the panel. +func newsParse(data []byte) ([]newsItem, error) { + var feed struct { + Items []struct { + Title string `xml:"title"` + Link string `xml:"link"` + PubDate string `xml:"pubDate"` + Source string `xml:"source"` + } `xml:"channel>item"` + } + if err := xml.Unmarshal(data, &feed); err != nil { + return nil, fmt.Errorf("The news feed could not be read.") + } + var out []newsItem + seen := map[string]bool{} + for _, it := range feed.Items { + link := strings.TrimSpace(it.Link) + if !strings.HasPrefix(link, "https://") && !strings.HasPrefix(link, "http://") { + continue + } + title := strings.TrimSpace(html.UnescapeString(it.Title)) + src := strings.TrimSpace(html.UnescapeString(it.Source)) + // Titles end with " - Source Name"; the source is shown on its own line. + if src != "" && strings.HasSuffix(title, " - "+src) { + title = strings.TrimSuffix(title, " - "+src) + } else if src == "" { + if i := strings.LastIndex(title, " - "); i > 0 { + src = strings.TrimSpace(title[i+3:]) + title = strings.TrimSpace(title[:i]) + } + } + key := strings.ToLower(title) + if title == "" || seen[key] { + continue + } + seen[key] = true + when, _ := time.Parse(time.RFC1123, strings.TrimSpace(it.PubDate)) + out = append(out, newsItem{title: title, source: src, link: link, when: when}) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].when.After(out[j].when) }) + if len(out) > newsKeep { + out = out[:newsKeep] + } + return out, nil +} + +// newsAge says how old a headline is: "12 min ago", "3 hr ago", "2 days ago". +func newsAge(t time.Time, now time.Time) string { + if t.IsZero() { + return "" + } + d := now.Sub(t) + switch { + case d < 0, d < time.Minute: + return "just now" + case d < time.Hour: + return fmt.Sprintf("%d min ago", int(d.Minutes())) + case d < 24*time.Hour: + return fmt.Sprintf("%d hr ago", int(d.Hours())) + case d < 48*time.Hour: + return "yesterday" + } + return fmt.Sprintf("%d days ago", int(d.Hours()/24)) +} diff --git a/newsflyout.go b/newsflyout.go new file mode 100644 index 0000000..e6e7777 --- /dev/null +++ b/newsflyout.go @@ -0,0 +1,360 @@ +package main + +// The local news flyout: a little newspaper on the bar that opens a panel above +// it with a list of local headlines. Each headline is a link; clicking one opens +// it in the default browser. The panel is its own window that never takes focus, +// it goes away when you click the newspaper again or click anywhere else, and it +// is painted at double size and shrunk down, the same way the weather panel is. + +import ( + "syscall" + "time" + "unsafe" +) + +const ( + newsW = 380.0 // panel width, in 96 dpi units + newsHead = 44.0 // header height + newsRow = 58.0 // height of one headline + newsFoot = 8.0 + newsMaxRows = 10 + + idcHandCursor = 32649 +) + +var ( + newsHwnd uintptr + newsShown bool + newsPrevBtn bool + newsHover = -1 // the headline under the mouse, -1 for none + newsVisible int // how many headlines the panel is showing +) + +// ---------- the button on the bar ---------- + +// drawNewsIcon draws the little newspaper on the bar. +func drawNewsIcon(hdc uintptr, r rect) { + if !layerFg { + return + } + col := iconColor() + cx, cy := center(r) + l, t, rt, b := cx-px(6), cy-px(5.5), cx+px(6), cy+px(5.5) + e := px(1) + 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{l + px(2.5), t + px(2.5), l + px(6), t + px(5.5)}, col) // the main headline + fillRaw(hdc, rect{l + px(7.5), t + px(2.5), rt - px(2.5), t + px(3.5)}, col) + fillRaw(hdc, rect{l + px(7.5), t + px(4.5), rt - px(2.5), t + px(5.5)}, col) + fillRaw(hdc, rect{l + px(2.5), t + px(7), rt - px(2.5), t + px(8)}, col) // lines of text +} + +// ---------- the panel window ---------- + +func newsInit(inst uintptr) { + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + className := u16("MirrorBarNews") + wc := wndClassEx{ + WndProc: syscall.NewCallback(newsProc), + Instance: inst, + Cursor: cursor, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + newsHwnd, _, _ = pCreateWindowEx.Call( + wsExToolWindow|wsExTopmost|wsExNoActivate, + uintptr(unsafe.Pointer(className)), + uintptr(unsafe.Pointer(u16(""))), + wsPopup, + 0, 0, 10, 10, + 0, 0, inst, 0) +} + +func newsProc(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, newsDraw) + return 0 + case wmTimer: + newsPoll() + return 0 + case wmSetCursor: + if newsHover >= 0 { + h, _, _ := pLoadCursor.Call(0, idcHandCursor) + pSetCursor.Call(h) + return 1 + } + case wmLButtonUp: + newsClick(int32(int16(lparam&0xFFFF)), int32(int16(lparam>>16&0xFFFF))) + return 0 + } + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +} + +// newsToggle is what clicking the newspaper does. +func newsToggle() { + if !showNews { + return + } + if newsShown { + newsHide() + return + } + if newsHwnd == 0 { + return + } + previewHide() + weatherHide() // one panel at a time + sysHide() + newsRefresh(false) + newsShown = true + newsPrevBtn = true // ignore a button that is still held from the click that opened this + newsHover = -1 + newsPlace() + pSetTimer.Call(newsHwnd, wxPollTimerID, 80, 0) +} + +func newsHide() { + if !newsShown { + return + } + newsShown = false + newsHover = -1 + pKillTimer.Call(newsHwnd, wxPollTimerID) + pShowWindow.Call(newsHwnd, swHide) +} + +func newsShutdown() { + newsHide() + if newsHwnd != 0 { + pDestroyWindow.Call(newsHwnd) + newsHwnd = 0 + } +} + +// newsVisibleRows is how many headlines fit on the screen, up to ten. +func newsVisibleRows(n int) int { + _, sh := screenSize() + avail := sh - px(90) - px(newsHead+newsFoot) + m := int(avail / px(newsRow)) + m = max(3, min(m, newsMaxRows)) + return min(n, m) +} + +// newsPlace sizes the panel for what it has to show and puts it next to the +// newspaper: above a horizontal bar, to the left of a vertical one. +func newsPlace() { + if newsHwnd == 0 { + return + } + s := newsSnapshot() + lh := wxShortH + newsVisible = 0 + if wxZip != "" && len(s.items) > 0 { + newsVisible = newsVisibleRows(len(s.items)) + lh = newsHead + float64(newsVisible)*newsRow + newsFoot + } + flyPlace(newsHwnd, trayAnchor(trayNews), px(newsW), px(lh)) + pInvalidateRect.Call(newsHwnd, 0, 1) +} + +// newsDone runs when a download finishes. +func newsDone() { + if newsShown { + newsPlace() + } +} + +// newsPoll closes the panel when a mouse button goes down anywhere outside it +// (the newspaper itself is left alone, so clicking it can close the panel) and +// keeps track of which headline the mouse is over. +func newsPoll() { + 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(newsHwnd, uintptr(unsafe.Pointer(&fr))) + if down && !newsPrevBtn && !inRect(fr, cp) && !inRect(trayAnchor(trayNews), cp) { + newsHide() + newsPrevBtn = down + return + } + newsPrevBtn = down + + h := -1 + if inRect(fr, cp) { + h = newsRowAt(cp.X-fr.Left, cp.Y-fr.Top) + } + if h != newsHover { + newsHover = h + pInvalidateRect.Call(newsHwnd, 0, 0) + } +} + +// newsRowAt is the headline under a spot in the panel (real pixels), or -1. +func newsRowAt(x, y int32) int { + ry := y - px(newsHead) + if ry < 0 || x < 0 { + return -1 + } + i := int(ry / px(newsRow)) + if i >= newsVisible { + return -1 + } + return i +} + +// newsClick runs when the panel is clicked: a headline opens in the browser, the +// header refreshes, and the messages in an empty panel are buttons. +func newsClick(x, y int32) { + s := newsSnapshot() + switch { + case wxZip == "": + newsHide() + openSettings() + return + case len(s.items) == 0: + if !s.loading { + newsRefresh(true) + } + return + case y < px(newsHead): + newsRefresh(true) + return + } + if i := newsRowAt(x, y); i >= 0 && i < len(s.items) { + link := s.items[i].link + newsHide() + shellOpen(link, "") // only web links were kept when the feed was read + } +} + +// ---------- painting ---------- + +func newsDraw(hdc uintptr, W, H int32) { + u := px + fillRaw(hdc, rect{0, 0, W, H}, iconColor()) // the outline follows the tray icon color + fillRaw(hdc, rect{u(1), u(1), W - u(1), H - u(1)}, colBack) + + pad := u(14) + s := newsSnapshot() + line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis) + + title := "Local news" + if s.place != "" && wxZip != "" { + title = s.place + " news" + } + wxText(hdc, title, rect{pad, u(10), W - pad - u(108), u(34)}, fMed, colText, line) + status := "" + switch { + case s.loading: + status = "Updating..." + case s.ok && s.err != "": + status = "Couldn't update" + case s.ok: + status = "Updated " + s.fetched.Format("3:04 PM") + } + wxText(hdc, status, rect{W - pad - u(108), u(12), W - pad, u(32)}, fSmall, colDim, dtRight|dtVCenter|dtSingleLine) + + // Nothing to show yet: say why. These messages are clickable. + if wxZip == "" || len(s.items) == 0 { + var head, sub string + switch { + case wxZip == "": + head, sub = "No ZIP code yet", "Click here to open the settings and type your ZIP code." + case s.loading: + head, sub = "Getting the headlines...", "" + default: + head, sub = "No news right now", s.err+" Click here to try again." + } + wxText(hdc, head, rect{pad, u(48), W - pad, u(74)}, fMed, colText, dtCenter|dtVCenter|dtSingleLine) + if sub != "" { + wxText(hdc, sub, rect{pad, u(78), W - pad, H - pad}, fText, colDim, dtCenter|dtWordBreak) + } + return + } + + fillRaw(hdc, rect{pad, u(newsHead) - u(2), W - pad, u(newsHead) - u(1)}, colRule) + now := time.Now() + for i := 0; i < newsVisible && i < len(s.items); i++ { + it := s.items[i] + y := u(newsHead) + int32(i)*u(newsRow) + head := colText + if i == newsHover { + fillRaw(hdc, rect{u(6), y, W - u(6), y + u(newsRow)}, rgb(40, 40, 48)) + head = colAccent + } + wxText(hdc, it.title, rect{pad, y + u(6), W - pad, y + u(42)}, fBold, head, dtLeft|dtWordBreak|dtEndEllipsis) + meta := it.source + if age := newsAge(it.when, now); age != "" { + if meta != "" { + meta += " ยท " + } + meta += age + } + wxText(hdc, meta, rect{pad, y + u(42), W - pad, y + u(56)}, fSmall, colDim, line) + if i < newsVisible-1 && i != newsHover && i+1 != newsHover { + fillRaw(hdc, rect{pad, y + u(newsRow) - u(1), W - pad, y + u(newsRow)}, colRule) + } + } +} + +// ---------- shared by both panels ---------- + +// trayAnchor is where an icon on the bar sits on the screen. +func trayAnchor(kind int) rect { + var wr rect + pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr))) + w, h := clientSize(hwndMain) + for _, it := range trayItems(w, h) { + if it.kind == kind { + r := it.r + if vertical { + r = mapRect(r, h) + } + return rect{wr.Left + r.Left, wr.Top + r.Top, wr.Left + r.Right, wr.Top + r.Bottom} + } + } + return wr +} + +// flyPlace puts a panel of size cw by ch next to an icon: above a horizontal +// bar, to the left of a vertical one, and always on the screen. +func flyPlace(hwnd uintptr, ar rect, cw, ch int32) { + var wr rect + pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr))) + sw, sh := screenSize() + space := px(8) + var x, y int32 + if vertical { + x = wr.Left - cw - space + if x < 0 { + x = wr.Right + space + } + y = (ar.Top+ar.Bottom)/2 - ch/2 + } else { + x = (ar.Left+ar.Right)/2 - cw/2 + y = wr.Top - ch - space + if y < 0 { + y = wr.Bottom + space + } + } + x = clampI(x, 0, sw-cw) + y = clampI(y, 0, sh-ch) + pSetWindowPos.Call(hwnd, hwndTopmost, uintptr(x), uintptr(y), uintptr(cw), uintptr(ch), swpNoActivate|swpShowWindow) +} diff --git a/sysflyout.go b/sysflyout.go new file mode 100644 index 0000000..12b7739 --- /dev/null +++ b/sysflyout.go @@ -0,0 +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, + 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 + pInvalidateRect.Call(sysHwnd, 0, 0) + 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)) + pInvalidateRect.Call(sysHwnd, 0, 1) +} + +// 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 { + pInvalidateRect.Call(sysHwnd, 0, 0) + } +} + +func sysCopy(text, what string) { + if clipboardSet(text) { + sysCopied = what + } else { + sysCopied = "Copy failed" + } + sysCopiedAt = time.Now() + pInvalidateRect.Call(sysHwnd, 0, 0) +} + +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 + fillRaw(hdc, rect{0, 0, W, H}, iconColor()) // the outline follows the tray icon color + fillRaw(hdc, rect{u(1), u(1), W - u(1), H - u(1)}, colBack) + + 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/sysinfo.go b/sysinfo.go new file mode 100644 index 0000000..bf3af97 --- /dev/null +++ b/sysinfo.go @@ -0,0 +1,298 @@ +package main + +// System information for the stats panel: the kind of thing neofetch prints. +// Everything is read from Windows itself (the registry and a few kernel calls); +// nothing goes over the network. + +import ( + "encoding/binary" + "fmt" + "net" + "os" + "runtime" + "strings" + "syscall" + "time" + "unsafe" +) + +var ( + pGlobalMemoryStatusEx = kern32t.NewProc("GlobalMemoryStatusEx") + pGetTickCount64 = kern32t.NewProc("GetTickCount64") + pGetLogicalDrives = kern32t.NewProc("GetLogicalDrives") + pGetDriveType = kern32t.NewProc("GetDriveTypeW") + pGetDiskFreeSpaceEx = kern32t.NewProc("GetDiskFreeSpaceExW") + pGlobalAlloc = kern32t.NewProc("GlobalAlloc") + pGlobalLock = kern32t.NewProc("GlobalLock") + pGlobalUnlock = kern32t.NewProc("GlobalUnlock") + pMoveMemory = kern32t.NewProc("RtlMoveMemory") + pOpenClipboard = user32.NewProc("OpenClipboard") + pEmptyClipboard = user32.NewProc("EmptyClipboard") + pSetClipboardData = user32.NewProc("SetClipboardData") + pCloseClipboard = user32.NewProc("CloseClipboard") +) + +type sysRow struct{ label, value string } + +// ---------- the registry ---------- + +func regRead(path, name string) (buf []byte, ok bool) { + var k syscall.Handle + if syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, u16(path), 0, syscall.KEY_READ, &k) != nil { + return nil, false + } + defer syscall.RegCloseKey(k) + var n, typ uint32 + if syscall.RegQueryValueEx(k, u16(name), nil, &typ, nil, &n) != nil || n == 0 { + return nil, false + } + buf = make([]byte, n) + if syscall.RegQueryValueEx(k, u16(name), nil, &typ, &buf[0], &n) != nil { + return nil, false + } + return buf[:n], true +} + +func regString(path, name string) string { + b, ok := regRead(path, name) + if !ok { + return "" + } + w := make([]uint16, 0, len(b)/2) + for i := 0; i+1 < len(b); i += 2 { + c := binary.LittleEndian.Uint16(b[i:]) + if c == 0 { + break + } + w = append(w, c) + } + return strings.TrimSpace(syscall.UTF16ToString(w)) +} + +func regDword(path, name string) (uint32, bool) { + b, ok := regRead(path, name) + if !ok || len(b) < 4 { + return 0, false + } + return binary.LittleEndian.Uint32(b), true +} + +// ---------- gathering ---------- + +type memStatusEx struct { + Length uint32 + MemoryLoad uint32 + TotalPhys, AvailPhys uint64 + TotalPage, AvailPage uint64 + TotalVirt, AvailVirt uint64 + AvailExtendedVirtual uint64 +} + +func gib(b uint64) string { return fmt.Sprintf("%.1f GiB", float64(b)/(1<<30)) } + +func sysUptime() string { + ms, _, _ := pGetTickCount64.Call() + d := time.Duration(ms) * time.Millisecond + days := int(d.Hours()) / 24 + hrs := int(d.Hours()) % 24 + mins := int(d.Minutes()) % 60 + var parts []string + if days > 0 { + parts = append(parts, fmt.Sprintf("%d day%s", days, plural(days))) + } + if days > 0 || hrs > 0 { + parts = append(parts, fmt.Sprintf("%d hour%s", hrs, plural(hrs))) + } + parts = append(parts, fmt.Sprintf("%d min%s", mins, plural(mins))) + return strings.Join(parts, ", ") +} + +func plural(n int) string { + if n == 1 { + return "" + } + return "s" +} + +func sysGather() []sysRow { + var rows []sysRow + add := func(l, v string) { + if strings.TrimSpace(v) != "" { + rows = append(rows, sysRow{l, v}) + } + } + + const cv = `SOFTWARE\Microsoft\Windows NT\CurrentVersion` + build := regString(cv, "CurrentBuild") + bn := 0 + fmt.Sscanf(build, "%d", &bn) + name := regString(cv, "ProductName") + if bn >= 22000 { + name = strings.Replace(name, "Windows 10", "Windows 11", 1) // Windows 11 still says 10 here + } + ver := regString(cv, "DisplayVersion") + arch := map[string]string{"amd64": "x86_64", "arm64": "arm64", "386": "x86"}[runtime.GOARCH] + osText := name + if ver != "" { + osText += " " + ver + } + if arch != "" { + osText += " " + arch + } + add("OS", osText) + + const bios = `HARDWARE\DESCRIPTION\System\BIOS` + host := strings.TrimSpace(regString(bios, "SystemManufacturer") + " " + regString(bios, "SystemProductName")) + add("Host", host) + + if build != "" { + k := "NT 10.0." + build + if ubr, ok := regDword(cv, "UBR"); ok { + k += fmt.Sprintf(".%d", ubr) + } + add("Kernel", k) + } + add("Uptime", sysUptime()) + add("Shell", "MirrorBar") + + sw, sh := screenSize() + res := fmt.Sprintf("%dx%d", sw, sh) + if s := int(scale*100 + 0.5); s != 100 { + res += fmt.Sprintf(" (%d%% scaling)", s) + } + add("Resolution", res) + + const cpuKey = `HARDWARE\DESCRIPTION\System\CentralProcessor\0` + cpu := strings.Join(strings.Fields(regString(cpuKey, "ProcessorNameString")), " ") + if cpu != "" { + cpu += fmt.Sprintf(" (%d threads)", runtime.NumCPU()) + } + add("CPU", cpu) + + // Graphics adapters: the display class lists them as 0000, 0001, ... + n := 0 + seen := map[string]bool{} + for i := 0; i < 10; i++ { + d := regString(fmt.Sprintf(`SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\%04d`, i), "DriverDesc") + if d == "" || seen[d] || strings.Contains(d, "Basic Display") || strings.Contains(d, "Remote Display") { + continue + } + seen[d] = true + n++ + l := "GPU" + if n > 1 { + l = fmt.Sprintf("GPU %d", n) + } + add(l, d) + } + + var ms memStatusEx + ms.Length = uint32(unsafe.Sizeof(ms)) + if r, _, _ := pGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms))); r != 0 && ms.TotalPhys > 0 { + used := ms.TotalPhys - ms.AvailPhys + add("Memory", fmt.Sprintf("%s / %s (%d%%)", gib(used), gib(ms.TotalPhys), used*100/ms.TotalPhys)) + } + + // Fixed drives only; a sleeping network drive could make this wait. + mask, _, _ := pGetLogicalDrives.Call() + for i := 0; i < 26; i++ { + if mask&(1<= 0 { + b := fmt.Sprintf("%d%%", battPct) + switch { + case battCharging: + b += ", charging" + case battAC: + b += ", plugged in" + } + add("Battery", b) + } + add("Local IP", localIP()) + return rows +} + +// localIP is this PC's first private IPv4 address. +func localIP() string { + addrs, err := net.InterfaceAddrs() + if err != nil { + return "" + } + for _, a := range addrs { + if ipn, ok := a.(*net.IPNet); ok && !ipn.IP.IsLoopback() { + if v4 := ipn.IP.To4(); v4 != nil && v4.IsPrivate() { + return v4.String() + } + } + } + return "" +} + +func sysUserHost() string { + u := os.Getenv("USERNAME") + h, _ := os.Hostname() + if u == "" { + return h + } + return u + "@" + h +} + +// sysText is everything as plain text, ready to paste. +func sysText(rows []sysRow) string { + head := sysUserHost() + var sb strings.Builder + sb.WriteString(head + "\r\n" + strings.Repeat("-", len([]rune(head))) + "\r\n") + for _, r := range rows { + sb.WriteString(r.label + ": " + r.value + "\r\n") + } + return sb.String() +} + +// ---------- the clipboard ---------- + +// clipboardSet puts plain text on the clipboard. Returns false if it couldn't. +func clipboardSet(text string) bool { + w, err := syscall.UTF16FromString(text) + if err != nil { + return false + } + for i := 0; i < 5; i++ { // another program may have it open for a moment + if r, _, _ := pOpenClipboard.Call(hwndMain); r != 0 { + break + } + if i == 4 { + return false + } + time.Sleep(30 * time.Millisecond) + } + defer pCloseClipboard.Call() + pEmptyClipboard.Call() + const gmemMoveable, cfUnicodeText = 0x0002, 13 + h, _, _ := pGlobalAlloc.Call(gmemMoveable, uintptr(len(w)*2)) + if h == 0 { + return false + } + p, _, _ := pGlobalLock.Call(h) + if p == 0 { + return false + } + pMoveMemory.Call(p, uintptr(unsafe.Pointer(&w[0])), uintptr(len(w)*2)) + pGlobalUnlock.Call(h) + r, _, _ := pSetClipboardData.Call(cfUnicodeText, h) + return r != 0 // the system owns the memory now +}