6 Commits
16 changed files with 3522 additions and 2493 deletions
+8 -2
View File
@@ -11,7 +11,11 @@ The real taskbar is hidden and a see-through pill takes its place. The pill is a
- 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.
- Windows of the same program share one icon. Four Brave windows show one Brave icon with a small red 4 in its top right corner. Click it to bring up the window you used last; click again while one of them is in front to step to the next. Hover shows a preview of the window you used last, and dragging the icon moves all of its windows together. Untick "Combine windows of the same program into one icon" in the settings window to get one icon per window again.
Tick "Hide the bar until the mouse touches the screen edge" in the settings window and the bar slides out of sight when the mouse is away from it (and stops reserving screen space, so maximized windows use the whole screen). Push the mouse against the screen edge where the bar lives (the bottom, or the right edge in vertical mode) and it comes back. It stays up while a panel, menu or preview is open.
Drag the app icons and the Windows logo along the left row to reorder them. MirrorBar remembers the order of your apps and the logo's spot.
- Drag the clock, battery, volume, wifi and hidden-icons arrow along the right row to reorder them. That order is remembered.
- Rest the mouse on an app icon for a moment and a live preview of that window pops up beside the bar (minimized windows show their icon instead). Click the preview to switch to that window.
- Right-click an app icon and choose "Pin to MirrorBar" to keep it on the bar. A pinned app that isn't running shows as a launcher: click it to start the program, and when its window opens it takes that spot. Pinning works for normal programs; Store apps can't be pinned.
@@ -23,7 +27,9 @@ The real taskbar is hidden and a see-through pill takes its place. The pill is a
- 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.
- Click the little speech bubble and Google Messages for web opens in a small window above the bar, so you can read and answer texts without opening a browser tab. The first time, scan the QR code from the Messages app on your phone (Settings, Device pairing) and tick "Remember this computer"; after that it stays signed in. It runs Microsoft Edge in app mode (no tabs, no address bar) with its own private profile folder in `%LOCALAPPDATA%\MirrorBar\messages`, separate from your normal Edge, and goes only to messages.google.com. Once you have paired, MirrorBar quietly starts it in the background about 20 seconds after it launches, keeps the window just off the edge of the screen, and shows the unread count from the window title as a red number on the bubble. Click anywhere else and the window slides away again. Right-click the bubble and choose "Close Messages" to stop the background window and give the memory back. Messages for web only works while your phone is on and connected; that is how Google built it. A link someone texts you opens in your normal default browser, not in Edge: the Messages window is started with a debugging port that only listens on this PC (127.0.0.1), and MirrorBar hands any page that is not Messages or a Google sign-in page to the default browser and closes it. `messages-titles.txt` in the MirrorBar data folder keeps the first 25 different window titles it has seen, only so the unread badge can be tuned; delete it any time.
- "Show weather on the bar", "Show local news on the bar", "Show system stats on the bar" and "Show Google Messages on the bar" in the settings window turn each feature off. The icon leaves the bar and nothing is downloaded for it; tick the box again and it comes back.
- The weather, news and system stats panels are as see-through as the bar itself: set the bar to Clear and the panels go clear too, with only their text, pictures and outline staying solid. Untick "Panels match the bar's transparency" in the settings window to keep the panels solid.
+102
View File
@@ -0,0 +1,102 @@
package main
// Auto-hide: the bar slides out of sight when the mouse is away from it and
// comes back when the mouse touches the screen edge where it lives.
import (
"time"
"unsafe"
)
const (
ahTimerID = 9
ahDelay = 700 * time.Millisecond
ahEdgeSlack = 24 // device-independent pixels of leeway along the edge
)
var (
autoHide bool
ahHidden bool
ahLeftAt = time.Now()
menuOpen bool // a right-click menu of the bar is showing
)
// ahStart / ahStop run the quick mouse check only while auto-hide is on.
func ahStart() { pSetTimer.Call(hwndMain, ahTimerID, 60, 0) }
func ahStop() { pKillTimer.Call(hwndMain, ahTimerID) }
// ahBusy is true while something on screen depends on the bar staying put.
func ahBusy() bool {
if wxShown || newsShown || sysShown || gmShown || dragging || dragActive || menuOpen {
return true
}
if pvHwnd != 0 {
if v, _, _ := pIsWindowVisible.Call(pvHwnd); v != 0 {
return true
}
}
return false
}
func ahTick(hwnd uintptr) {
if !autoHide {
return
}
var cp point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp)))
sw, sh := screenSize()
pw, ph := pillSize()
x, y := pillPos(pw, ph)
slack := px(ahEdgeSlack)
if ahHidden {
var hot bool
if vertical {
hot = cp.X >= sw-2 && cp.Y >= y-slack && cp.Y <= y+ph+slack
} else {
hot = cp.Y >= sh-2 && cp.X >= x-slack && cp.X <= x+pw+slack
}
if hot {
ahHidden = false
ahLeftAt = time.Now()
positionBar(hwnd)
}
return
}
near := cp.X >= x-px(6) && cp.X <= x+pw+px(6) && cp.Y >= y-px(6) && cp.Y <= y+ph+px(6)
if near || ahBusy() {
ahLeftAt = time.Now()
return
}
if time.Since(ahLeftAt) > ahDelay {
ahHidden = true
positionBar(hwnd)
}
}
// setAutoHide is called by the settings window.
func setAutoHide(on bool) {
if autoHide == on {
return
}
autoHide = on
saveFeatures()
ahHidden = false
ahLeftAt = time.Now()
if on {
if appbarOn { // a bar that hides must not keep screen space reserved
abd := appBarData{Hwnd: hwndMain}
appBar(abmRemove, &abd)
appbarOn = false
}
ahStart()
} else {
ahStop()
if !customPos && !appbarOn {
abd := appBarData{Hwnd: hwndMain, CallbackMsg: callbackMsg}
appBar(abmNew, &abd)
appbarOn = true
}
}
positionBar(hwndMain)
}
+36 -1
View File
@@ -14,6 +14,7 @@ var (
showWeather = true
showNews = true
showSys = true
showGM = true // the Google Messages bubble
)
func featuresFile() string { return filepath.Join(dataDir(), "features.txt") }
@@ -36,14 +37,20 @@ func loadFeatures() {
showNews = on
case "sys":
showSys = on
case "messages":
showGM = on
case "panelfade":
flyMatchBar = on
case "group":
groupWins = on
case "autohide":
autoHide = on
}
}
}
func saveFeatures() {
s := "weather=" + b01(showWeather) + "\nnews=" + b01(showNews) + "\nsys=" + b01(showSys) + "\npanelfade=" + b01(flyMatchBar) + "\n"
s := "weather=" + b01(showWeather) + "\nnews=" + b01(showNews) + "\nsys=" + b01(showSys) + "\nmessages=" + b01(showGM) + "\npanelfade=" + b01(flyMatchBar) + "\ngroup=" + b01(groupWins) + "\nautohide=" + b01(autoHide) + "\n"
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(featuresFile(), []byte(s), 0o644)
}
@@ -98,6 +105,21 @@ func setShowSys(on bool) {
featuresChanged()
}
// setShowGM is called by the settings window.
func setShowGM(on bool) {
if showGM == on {
return
}
showGM = on
saveFeatures()
if on {
gmAutoTried = false // let the background check start Messages again
} else {
gmClose()
}
featuresChanged()
}
// setFlyMatchBar is called by the settings window: should the panels be as
// see-through as the bar?
func setFlyMatchBar(on bool) {
@@ -126,3 +148,16 @@ func zipStatusText() string {
}
return newsStatusText()
}
// setGroupWins is called by the settings window: one icon per program, with a
// count, or one icon per window.
func setGroupWins(on bool) {
if groupWins == on {
return
}
groupWins = on
saveFeatures()
styleCacheClear()
apps = groupApps(allApps)
positionBar(hwndMain)
}
+603 -602
View File
File diff suppressed because it is too large Load Diff
+558
View File
@@ -0,0 +1,558 @@
package main
// The Google Messages flyout: a speech bubble on the bar that opens Messages for
// web (messages.google.com) in a small window above the bar, so you can read and
// answer texts without opening a browser tab.
//
// How it works: MirrorBar starts Microsoft Edge in "app" mode (no tabs, no address
// bar) with its own private profile folder, so the sign-in from pairing your phone
// is remembered and never touches your normal Edge. Edge is already on every
// Windows 11 PC, so there is nothing to install. The window is kept just off the
// edge of the screen while the flyout is closed; clicking the bubble slides it
// above the bar, clicking anywhere else slides it away again. Because the page
// keeps running, the unread number in its window title can be shown on the bubble.
//
// Messages for web only works while the phone is on and connected; that is how
// Google built it, not something MirrorBar can change.
import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
)
const (
gmURL = "https://messages.google.com/web/conversations"
gmW = 780.0 // flyout size, in 96 dpi units
gmH = 580.0
gmTimerID = 3 // on the main window: watches for clicks outside the flyout
gmParkX = -32000
gmParkY = -32000
gmAutoDelay = 20 * time.Second // wait this long after start before opening Messages in the background
gmLaunchMax = 45 * time.Second // give up looking for the window after this long
gmSwpNoSize = 0x0001
gmSwpNoMove = 0x0002
gmSwpNoZOrder = 0x0004
gmSwpFrameChanged = 0x0020
gmSwShowNoActive = 4
gmWsExAppWindow = 0x00040000
gmGaRootOwner = 3
)
var (
pIsWindow = user32.NewProc("IsWindow")
pWindowFromPoint = user32.NewProc("WindowFromPoint")
pGetAncestor = user32.NewProc("GetAncestor")
pSetWindowLongPtr = user32.NewProc("SetWindowLongPtrW")
pSetWindowPlace = user32.NewProc("SetWindowPlacement")
)
var (
gmHwnd uintptr
gmPid uint32
gmShown bool
gmPrevBtn bool
gmPrevFg uintptr
gmShownAt time.Time
gmLaunching bool
gmLaunchedAt time.Time
gmWantOpen bool // the bubble was clicked while the window was still starting
gmAutoTried bool
gmUnread int
gmEnumCb uintptr
gmFound uintptr
gmLogged = map[string]bool{}
gmLoggedN int
)
type gmPlacementT struct {
Length uint32
Flags uint32
ShowCmd uint32
MinPos point
MaxPos point
Normal rect
}
// ---------- the button on the bar ----------
func drawGMIcon(hdc uintptr, r rect) {
if !layerFg {
return
}
col := iconColor()
cx, cy := center(r)
e := px(1)
l, t, rt, b := cx-px(6.5), cy-px(5.5), cx+px(6.5), cy+px(3)
fillRaw(hdc, rect{l, t, rt, t + e}, col)
fillRaw(hdc, rect{l, b - e, rt, b}, col)
fillRaw(hdc, rect{l, t, l + e, b}, col)
fillRaw(hdc, rect{rt - e, t, rt, b}, col)
// the little tail at the bottom left
polyline(hdc, []point{{cx - px(3.5), b}, {cx - px(3.5), cy + px(6)}, {cx - px(0.5), b}}, e, col)
// two lines of "text" in the bubble
fillRaw(hdc, rect{cx - px(4), cy - px(3), cx + px(4), cy - px(3) + e}, col)
fillRaw(hdc, rect{cx - px(4), cy - px(0.5), cx + px(1.5), cy - px(0.5) + e}, col)
if gmUnread > 0 {
br, bg, bb := styleColor(235, 70, 70)
bx, by, rad := cx+px(6.5), cy-px(5.5), px(5)
circleRaw(hdc, bx, by, rad, rgb(br, bg, bb))
txt := strconv.Itoa(gmUnread)
if gmUnread > 9 {
txt = "9+"
}
f := makeFont(px(8), 700)
old, _, _ := pSelectObject.Call(hdc, f)
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(255, 255, 255))
drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1})
pSelectObject.Call(hdc, old)
pDeleteObject.Call(f)
}
}
// ---------- finding and starting the browser window ----------
func gmProfileDir() string { return filepath.Join(dataDir(), "messages") }
func gmProfileExists() bool {
_, err := os.Stat(filepath.Join(gmProfileDir(), "Local State"))
return err == nil
}
// gmBrowserPath is Edge (always there on Windows 11), or Chrome if Edge is gone.
func gmBrowserPath() string {
type cand struct{ env, vendor, app, exe string }
for _, c := range []cand{
{"ProgramFiles(x86)", "Microsoft", "Edge", "msedge.exe"},
{"ProgramFiles", "Microsoft", "Edge", "msedge.exe"},
{"LOCALAPPDATA", "Microsoft", "Edge", "msedge.exe"},
{"ProgramFiles", "Google", "Chrome", "chrome.exe"},
{"ProgramFiles(x86)", "Google", "Chrome", "chrome.exe"},
{"LOCALAPPDATA", "Google", "Chrome", "chrome.exe"},
} {
base := os.Getenv(c.env)
if base == "" {
continue
}
p := filepath.Join(base, c.vendor, c.app, "Application", c.exe)
if _, err := os.Stat(p); err == nil {
return p
}
}
return ""
}
// gmLaunch starts the app window. Started in the background it opens minimized
// and is never given focus, so it does not interrupt whatever is being typed.
func gmLaunch(visible bool) bool {
exe := gmBrowserPath()
if exe == "" {
return false
}
prof := gmProfileDir()
if err := os.MkdirAll(prof, 0o755); err != nil {
return false
}
args := []string{
exe,
"--app=" + gmURL,
"--user-data-dir=" + prof,
// lets MirrorBar send clicked links to the default browser (this PC only)
"--remote-debugging-port=" + gmDebugPort,
"--remote-debugging-address=127.0.0.1",
"--no-first-run",
"--no-default-browser-check",
// keep the page awake while its window is parked off the screen
"--disable-features=CalculateNativeWinOcclusion",
"--disable-renderer-backgrounding",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
}
parts := make([]string, len(args))
for i, a := range args {
parts[i] = syscall.EscapeArg(a)
}
si := syscall.StartupInfo{Flags: 1} // STARTF_USESHOWWINDOW
si.Cb = uint32(unsafe.Sizeof(si))
si.ShowWindow = 7 // SW_SHOWMINNOACTIVE
if visible {
si.ShowWindow = 1 // SW_SHOWNORMAL
}
var pi syscall.ProcessInformation
err := syscall.CreateProcess(u16(exe), u16(strings.Join(parts, " ")), nil, nil, false, 0, nil, nil, &si, &pi)
if err != nil {
return false
}
gmPid = pi.ProcessId
gmStartLinkWatch()
syscall.CloseHandle(pi.Process)
syscall.CloseHandle(pi.Thread)
gmLaunching = true
gmLaunchedAt = time.Now()
gmWantOpen = visible
return true
}
func gmWindowTitle(hwnd uintptr) string {
var tb [512]uint16
n, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512)
return syscall.UTF16ToString(tb[:n])
}
// gmTitleMatch is true for the app window's title ("Messages for web", maybe
// with a count in front) and false for ordinary browser windows.
func gmTitleMatch(t string) bool {
l := strings.ToLower(t)
if strings.Contains(l, "microsoft edge") || strings.Contains(l, "google chrome") {
return false
}
return strings.Contains(l, "messages")
}
func gmEnumProc(hwnd, lparam uintptr) uintptr {
var cls [64]uint16
n, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 64)
if syscall.UTF16ToString(cls[:n]) != "Chrome_WidgetWin_1" {
return 1
}
if !gmTitleMatch(gmWindowTitle(hwnd)) {
return 1
}
var pid uint32
pGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if gmPid != 0 && pid == gmPid {
gmFound = hwnd
return 0 // exactly the window we started
}
if gmFound == 0 {
gmFound = hwnd
}
return 1
}
func gmFindWindow() uintptr {
if gmEnumCb == 0 {
gmEnumCb = syscall.NewCallback(gmEnumProc)
}
gmFound = 0
pEnumWindows.Call(gmEnumCb, 0)
return gmFound
}
func gmWindowOK() bool {
if gmHwnd == 0 {
return false
}
ok, _, _ := pIsWindow.Call(gmHwnd)
return ok != 0
}
// gmAdopt takes charge of the window once it exists: it stays out of the app
// list and Alt+Tab, and sits off screen until the bubble is clicked.
func gmAdopt(h uintptr) {
gmHwnd = h
var pid uint32
pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid)))
if pid != 0 {
gmPid = pid
}
ex, _, _ := pGetWindowLongPtr.Call(h, neg(-20))
want := (ex | wsExToolWindow) &^ gmWsExAppWindow
if want != ex {
pSetWindowLongPtr.Call(h, neg(-20), want)
pSetWindowPos.Call(h, 0, 0, 0, 0, 0, gmSwpNoMove|gmSwpNoSize|gmSwpNoZOrder|swpNoActivate|gmSwpFrameChanged)
}
gmLaunching = false
gmStartLinkWatch()
if gmWantOpen {
gmWantOpen = false
gmShow()
} else {
gmPark()
}
}
// ---------- moving the window ----------
func gmSize() (int32, int32) {
sw, sh := screenSize()
cw := min(px(gmW), sw-px(16))
ch := min(px(gmH), sh-px(24))
return cw, ch
}
// gmMove puts the window at x, y, w, h. A minimized window is first brought back
// to that spot without taking focus.
func gmMove(x, y, w, h int32, topmost, activate bool) {
if !gmWindowOK() {
return
}
if z, _, _ := pIsZoomed.Call(gmHwnd); z != 0 {
pShowWindow.Call(gmHwnd, swRestore)
}
if ic, _, _ := pIsIconic.Call(gmHwnd); ic != 0 {
cmd := uint32(gmSwShowNoActive)
if activate {
cmd = swRestore
}
wp := gmPlacementT{ShowCmd: cmd, Normal: rect{x, y, x + w, y + h}}
wp.Length = uint32(unsafe.Sizeof(wp))
pSetWindowPlace.Call(gmHwnd, uintptr(unsafe.Pointer(&wp)))
}
after := ^uintptr(1) // HWND_NOTOPMOST
if topmost {
after = hwndTopmost
}
var flags uintptr
if !activate {
flags = swpNoActivate
}
pSetWindowPos.Call(gmHwnd, after, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags|swpShowWindow)
}
func gmPark() {
cw, ch := gmSize()
gmMove(gmParkX, gmParkY, cw, ch, false, false)
}
// gmPlace is where the flyout goes: above a horizontal bar, to the left of a
// vertical one, centered on the bubble and always on the screen.
func gmPlace() (x, y, w, h int32) {
cw, ch := gmSize()
ar := trayAnchor(trayGM)
var wr rect
pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr)))
sw, sh := screenSize()
space := px(8)
if vertical {
x = wr.Left - cw - space
if x < 0 {
x = wr.Right + space
}
y = (ar.Top+ar.Bottom)/2 - ch/2
} else {
x = (ar.Left+ar.Right)/2 - cw/2
y = wr.Top - ch - space
if y < 0 {
y = wr.Bottom + space
}
}
return clampI(x, 0, sw-cw), clampI(y, 0, sh-ch), cw, ch
}
func gmFocus() {
// This program just received the click, so Windows lets it hand the focus on.
pSetForegroundWindow.Call(gmHwnd)
}
// ---------- open, close, click ----------
func gmToggle() {
if !showGM {
return
}
if gmShown {
gmHide()
return
}
previewHide()
weatherHide() // one panel at a time
newsHide()
sysHide()
if gmWindowOK() {
gmShow()
return
}
gmHwnd = 0
if gmLaunching {
gmWantOpen = true // it is still starting; open it the moment it exists
return
}
if !gmLaunch(true) {
shellOpen(gmURL, "") // no Edge or Chrome found: use the default browser
}
}
func gmShow() {
if !gmWindowOK() {
return
}
fg, _, _ := pGetForegroundWindow.Call()
if fg != gmHwnd {
gmPrevFg = fg
}
gmShown = true
gmPrevBtn = true // ignore a button that is still held from the click that opened this
gmShownAt = time.Now()
x, y, w, h := gmPlace()
gmMove(x, y, w, h, true, true)
gmFocus()
pSetTimer.Call(hwndMain, gmTimerID, 80, 0)
}
func gmHide() {
if !gmShown {
return
}
gmShown = false
pKillTimer.Call(hwndMain, gmTimerID)
if !gmWindowOK() {
return
}
fg, _, _ := pGetForegroundWindow.Call()
gmPark()
if fg == gmHwnd && gmPrevFg != 0 && gmPrevFg != hwndMain && gmPrevFg != gmHwnd {
if ok, _, _ := pIsWindow.Call(gmPrevFg); ok != 0 {
pSetForegroundWindow.Call(gmPrevFg) // give the keyboard back to what you were doing
}
}
}
// gmClose shuts the Messages window down (right-click, "Close Messages").
func gmClose() {
gmHide()
if gmWindowOK() {
pPostMessage.Call(gmHwnd, wmClose, 0, 0)
}
gmHwnd = 0
gmLaunching = false
gmWantOpen = false
gmAutoTried = true // do not bring it back by itself
gmUnread = 0
}
func gmShutdown() {
pKillTimer.Call(hwndMain, gmTimerID)
if gmWindowOK() {
pPostMessage.Call(gmHwnd, wmClose, 0, 0)
}
gmHwnd = 0
}
// gmPoll runs every 80 ms while the flyout is open and closes it when a mouse
// button goes down anywhere outside it (the bubble itself is left alone, so
// clicking it can close the flyout).
func gmPoll() {
if !gmShown {
return
}
if !gmWindowOK() {
gmShown = false
pKillTimer.Call(hwndMain, gmTimerID)
return
}
l, _, _ := pGetAsyncKeyState.Call(vkLButton)
r, _, _ := pGetAsyncKeyState.Call(vkRButton)
down := (l|r)&0x8000 != 0
if down && !gmPrevBtn && time.Since(gmShownAt) > 300*time.Millisecond {
var cp point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp)))
var fr rect
pGetWindowRect.Call(gmHwnd, uintptr(unsafe.Pointer(&fr)))
inside := inRect(fr, cp)
if !inside {
// a dialog or menu that belongs to the Messages window counts as inside
h, _, _ := pWindowFromPoint.Call(uintptr(uint32(cp.X)) | uintptr(uint32(cp.Y))<<32)
if h != 0 {
root, _, _ := pGetAncestor.Call(h, gmGaRootOwner)
inside = root == gmHwnd
}
}
if !inside && !inRect(trayAnchor(trayGM), cp) {
gmHide()
}
}
gmPrevBtn = down
}
// ---------- the background check ----------
var gmCountRe = regexp.MustCompile(`[\(\[](\d{1,3})\+?[\)\]]`)
func gmParseUnread(title string) int {
m := gmCountRe.FindStringSubmatch(title)
if m == nil {
return 0
}
n, _ := strconv.Atoi(m[1])
return n
}
// gmLogTitle keeps the first few different window titles in titles.txt next to
// the Messages profile, so the unread badge can be tuned if Google words it
// differently than expected. It stops after 25 so it never grows.
func gmLogTitle(t string) {
if t == "" || gmLogged[t] || gmLoggedN >= 25 {
return
}
gmLogged[t] = true
gmLoggedN++
f, err := os.OpenFile(filepath.Join(dataDir(), "messages-titles.txt"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return
}
defer f.Close()
if len(t) > 80 {
t = t[:80]
}
_, _ = f.WriteString(time.Now().Format("2006-01-02 15:04:05") + "\t" + t + "\n")
}
// gmTick runs from the bar's 250 ms timer. It starts Messages in the background
// once you have paired a phone, notices when the window goes away, and reads
// the unread count from the window title. Returns true when the bar needs a
// repaint.
func gmTick(tick int) (changed bool) {
defer func() {
if r := recover(); r != nil {
changed = false // optional feature; never take the bar down with it
}
}()
if !showGM {
return false
}
if gmHwnd != 0 && !gmWindowOK() {
gmHwnd = 0
gmShown = false
pKillTimer.Call(hwndMain, gmTimerID)
changed = gmUnread != 0
gmUnread = 0
}
if gmHwnd == 0 {
switch {
case gmLaunching:
if h := gmFindWindow(); h != 0 {
gmAdopt(h)
} else if time.Since(gmLaunchedAt) > gmLaunchMax {
gmLaunching = false
gmWantOpen = false
}
case !gmAutoTried && time.Since(startedAt) > gmAutoDelay:
gmAutoTried = true
if h := gmFindWindow(); h != 0 {
gmAdopt(h) // left over from an earlier run of MirrorBar
} else if gmProfileExists() {
gmLaunch(false)
}
}
}
if gmHwnd != 0 && tick%8 == 0 {
t := gmWindowTitle(gmHwnd)
gmLogTitle(t)
if n := gmParseUnread(t); n != gmUnread {
gmUnread = n
changed = true
}
}
return changed
}
+88
View File
@@ -0,0 +1,88 @@
package main
// Links clicked inside Google Messages open in the Windows default browser.
//
// Edge opens a clicked link in a new Edge window of the Messages profile. To
// hand those to the default browser, the Messages window is started with a
// debugging port that listens on this PC only (127.0.0.1). A small background
// loop looks at the list of open pages, and any page that is not Messages or
// a Google sign-in page is opened with the default browser and then closed.
import (
"encoding/json"
"net/http"
"net/url"
"runtime"
"strings"
"time"
"unsafe"
)
const gmDebugPort = "9341"
var gmLinkOnce bool
type gmTarget struct {
ID string `json:"id"`
Type string `json:"type"`
URL string `json:"url"`
}
// gmOwnHost reports whether a page belongs to Messages itself (including the
// Google sign-in pages used while pairing), which must stay where they are.
func gmOwnHost(host string) bool {
host = strings.ToLower(host)
for _, ok := range []string{"messages.google.com", "accounts.google.com", "gstatic.com", "googleusercontent.com"} {
if host == ok || strings.HasSuffix(host, "."+ok) {
return true
}
}
return false
}
func gmStartLinkWatch() {
if gmLinkOnce {
return
}
gmLinkOnce = true
go func() {
defer func() { recover() }()
runtime.LockOSThread()
pCoInitializeEx.Call(0, 2)
client := &http.Client{Timeout: 1500 * time.Millisecond, Transport: &http.Transport{DisableKeepAlives: true}}
base := "http://127.0.0.1:" + gmDebugPort
for {
time.Sleep(80 * time.Millisecond)
if gmHwnd == 0 {
continue
}
resp, err := client.Get(base + "/json/list")
if err != nil {
continue
}
var ts []gmTarget
err = json.NewDecoder(resp.Body).Decode(&ts)
resp.Body.Close()
if err != nil {
continue
}
for _, t := range ts {
if t.Type != "page" {
continue
}
u, err := url.Parse(t.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
continue
}
if gmOwnHost(u.Hostname()) {
continue
}
// close the Edge window first so it is on screen as briefly as possible
if r, err := client.Get(base + "/json/close/" + url.PathEscape(t.ID)); err == nil {
r.Body.Close()
}
pShellExecute.Call(0, uintptr(unsafe.Pointer(u16("open"))), uintptr(unsafe.Pointer(u16(t.URL))), 0, 0, 1)
}
}
}()
}
+134
View File
@@ -0,0 +1,134 @@
package main
// Combining windows: when "Combine windows of the same program" is on, all the
// open windows of one program (four Brave windows, say) share a single icon on
// the bar with a small red count in its top right corner. `allApps` is the full
// list of windows and launchers in bar order; `apps` is what the bar shows.
import (
"strconv"
"strings"
"time"
"unsafe"
)
var (
groupWins = true
allApps []appWin
winActiveAt = map[uintptr]time.Time{} // when each window was last the front one
)
// noteForeground remembers which window is in front, so a combined icon knows
// which of its windows you were using last.
func noteForeground(present map[uintptr]appWin) {
fg, _, _ := pGetForegroundWindow.Call()
if _, ok := present[fg]; ok {
winActiveAt[fg] = time.Now()
}
for h := range winActiveAt {
if _, ok := present[h]; !ok {
delete(winActiveAt, h)
}
}
}
// groupApps turns the full window list into the icons the bar shows.
func groupApps(list []appWin) []appWin {
out := make([]appWin, 0, len(list))
idx := map[string]int{}
for _, a := range list {
a.count, a.members = 1, nil
if a.hwnd == 0 {
out = append(out, a)
continue
}
a.members = []uintptr{a.hwnd}
if groupWins && a.exe != "" {
k := strings.ToLower(a.exe)
if i, ok := idx[k]; ok {
out[i].members = append(out[i].members, a.hwnd)
out[i].count++
continue
}
idx[k] = len(out)
}
out = append(out, a)
}
return out
}
// memberHwnd is the window a combined icon acts on: the one used most recently.
func memberHwnd(a appWin) uintptr {
if len(a.members) <= 1 {
return a.hwnd
}
best := a.members[0]
for _, m := range a.members[1:] {
if winActiveAt[m].After(winActiveAt[best]) {
best = m
}
}
return best
}
// syncAllFromGrouped puts allApps back in step after the icons were dragged
// into a new order: each icon brings all of its windows along.
func syncAllFromGrouped() {
byHwnd := map[uintptr]appWin{}
for _, a := range allApps {
if a.hwnd != 0 {
byHwnd[a.hwnd] = a
}
}
out := make([]appWin, 0, len(allApps))
for _, g := range apps {
if g.hwnd == 0 {
g.count, g.members = 0, nil
out = append(out, g)
continue
}
for _, m := range g.members {
if w, ok := byHwnd[m]; ok {
out = append(out, w)
}
}
}
allApps = out
}
// activateGroup handles a click on a combined icon: bring up the window used
// most recently, or, if one of them is already in front, step to the next.
func activateGroup(a appWin) {
fg, _, _ := pGetForegroundWindow.Call()
target := memberHwnd(a)
for i, m := range a.members {
if m == fg {
target = a.members[(i+1)%len(a.members)]
break
}
}
if iconic, _, _ := pIsIconic.Call(target); iconic != 0 {
pShowWindow.Call(target, swRestore)
}
pSetForegroundWindow.Call(target)
}
// drawCountBadge draws the little red number in the top right corner of an icon.
func drawCountBadge(hdc uintptr, cx, cy, isz int32, n int) {
br, bg, bb := styleColor(235, 70, 70)
bx, by, rad := cx+isz/2, cy-isz/2, px(5)
circleRaw(hdc, bx, by, rad, rgb(br, bg, bb))
txt := strconv.Itoa(n)
if n > 9 {
txt = "9+"
}
f := makeFont(px(8), 700)
old, _, _ := pSelectObject.Call(hdc, f)
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(255, 255, 255))
drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1})
pSelectObject.Call(hdc, old)
pDeleteObject.Call(f)
}
var _ = unsafe.Pointer(nil)
+52 -4
View File
@@ -306,6 +306,9 @@ type appWin struct {
title string
icon uintptr
exe string // full path of the program, "" when unknown
count int // windows combined into this icon (1 when alone)
members []uintptr // every window behind this icon
}
type alphaLevel struct {
@@ -437,6 +440,17 @@ func setTaskbarState(owner uintptr, state uintptr) {
appBar(abmSetState, &abd)
}
// keepOnTop puts the bar back in the topmost band if Windows or another program
// has knocked it out of it, which otherwise sinks it under every other window.
func keepOnTop(hwnd uintptr) {
ex, _, _ := pGetWindowLongPtr.Call(hwnd, neg(-20))
if ex&wsExTopmost != 0 {
return
}
const swpNoSize, swpNoMove = 0x0001, 0x0002
pSetWindowPos.Call(hwnd, hwndTopmost, 0, 0, 0, 0, swpNoSize|swpNoMove|swpNoActivate)
}
func hideTaskbar() {
tb := findTaskbar()
if tb == 0 {
@@ -462,7 +476,7 @@ func restoreAll() {
// ---------- open windows ----------
func collectWindow(hwnd uintptr) {
if hwnd == hwndMain {
if hwnd == hwndMain || (gmHwnd != 0 && hwnd == gmHwnd) {
return
}
vis, _, _ := pIsWindowVisible.Call(hwnd)
@@ -527,6 +541,10 @@ func activateApp(idx int) {
}
return
}
if apps[idx].count > 1 {
activateGroup(apps[idx])
return
}
fg, _, _ := pGetForegroundWindow.Call()
iconic, _, _ := pIsIconic.Call(h)
switch {
@@ -563,7 +581,7 @@ func barGap() int32 { return px(6) }
func positionBar(hwnd uintptr) {
pw, ph := pillSize()
if !customPos {
if !customPos && !autoHide {
sw, sh := screenSize()
edge := uintptr(abeBottom)
if vertical {
@@ -579,6 +597,14 @@ func positionBar(hwnd uintptr) {
appBar(abmSetPos, &abd)
}
x, y := pillPos(pw, ph)
if autoHide && ahHidden {
sw, sh := screenSize()
if vertical {
x = sw // just past the right edge
} else {
y = sh // just below the bottom edge
}
}
pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 1)
redraw(hwnd)
}
@@ -718,6 +744,9 @@ func drawAppGlyph(hdc uintptr, r rect, a appWin) {
if a.icon != 0 {
cx, cy := center(r)
pDrawIconEx.Call(hdc, uintptr(cx-isz/2), uintptr(cy-isz/2), styledIcon(a.icon), uintptr(isz), uintptr(isz), 0, 0, diNormal)
if a.count > 1 {
drawCountBadge(hdc, cx, cy, isz, a.count)
}
} else if rs := []rune(a.title); len(rs) > 0 {
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(245, 245, 245))
@@ -795,7 +824,7 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
var target uintptr
var exe string
if appIdx >= 0 && appIdx < len(apps) {
target = apps[appIdx].hwnd
target = memberHwnd(apps[appIdx])
title := []rune(apps[appIdx].title)
text := string(title)
@@ -894,8 +923,11 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
var pt point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
pSetForegroundWindow.Call(hwnd)
menuOpen = true
cmd, _, _ := pTrackPopupMenu.Call(menu, tpmRightButton|tpmBottomAlign|tpmReturnCmd,
uintptr(pt.X), uintptr(pt.Y), 0, hwnd, 0)
menuOpen = false
ahLeftAt = time.Now()
pDestroyMenu.Call(menu)
sysCommands := map[uintptr]uintptr{
@@ -974,13 +1006,25 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
return 0
case wmTimer:
if wparam == gmTimerID {
gmPoll()
return 0
}
if wparam == ahTimerID {
ahTick(hwnd)
return 0
}
if wparam == previewTimerID {
previewTick()
return 0
}
hideTaskbar()
keepOnTop(hwnd)
tick++
changed := refreshApps(tick%16 == 0)
if gmTick(tick) {
changed = true
}
if tick%4 == 0 && refreshStatus(tick%16 == 0) {
changed = true
}
@@ -1190,6 +1234,7 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
weatherShutdown()
newsShutdown()
sysShutdown()
gmShutdown()
abd := appBarData{Hwnd: hwnd}
appBar(abmRemove, &abd)
pKillTimer.Call(hwnd, timerID)
@@ -1324,7 +1369,7 @@ func main() {
}
// Register as an app bar so maximized windows stop above us.
if customPos {
if customPos || autoHide {
appbarOn = false
} else {
abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg}
@@ -1336,6 +1381,9 @@ func main() {
refreshApps(true)
positionBar(hwnd)
pSetTimer.Call(hwnd, timerID, 250, 0)
if autoHide {
ahStart()
}
weatherRefresh(false) // have the forecast ready before the cloud is first clicked
newsRefresh(false)
+360 -359
View File
@@ -1,359 +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|wsExLayered,
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))
flyRefresh(newsHwnd)
}
// 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
flyRefresh(newsHwnd)
}
}
// 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
flyFrame(hdc, W, H) // outline in the tray icon color; the background is added when painting
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)
}
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|wsExLayered,
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()
gmHide()
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))
flyRefresh(newsHwnd)
}
// 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
flyRefresh(newsHwnd)
}
}
// 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
flyFrame(hdc, W, H) // outline in the tray icon color; the background is added when painting
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)
}
+15 -7
View File
@@ -257,8 +257,12 @@ func refreshApps(refreshIcons bool) bool {
}
}
present0 := make(map[uintptr]appWin, len(present))
for h, w := range present {
present0[h] = w
}
var next []appWin
for _, a := range apps {
for _, a := range allApps {
if a.hwnd == 0 {
next = append(next, a) // a waiting launcher; sorted out below
continue
@@ -321,13 +325,17 @@ func refreshApps(refreshIcons bool) bool {
}
}
noteForeground(present0)
allApps = next
grouped := groupApps(next)
// Titles change constantly (browser tabs, documents) but nothing on the
// bar shows them, so only a change in which buttons exist, or their icons,
// counts as a change.
changed := len(next) != len(apps)
// bar shows them, so only a change in which buttons exist, their icons, or
// how many windows an icon stands for counts as a change.
changed := len(grouped) != len(apps)
if !changed {
for i := range next {
if next[i].hwnd != apps[i].hwnd || next[i].icon != apps[i].icon {
for i := range grouped {
if grouped[i].hwnd != apps[i].hwnd || grouped[i].icon != apps[i].icon || grouped[i].count != apps[i].count {
changed = true
break
}
@@ -336,7 +344,7 @@ func refreshApps(refreshIcons bool) bool {
if changed {
styleCacheClear() // icon handles can be reused by other icons
}
apps = next
apps = grouped
return changed
}
+1
View File
@@ -330,4 +330,5 @@ func moveSeq(from, to int) {
}
}
apps = next
syncAllFromGrouped()
}
+2 -1
View File
@@ -175,6 +175,7 @@ func previewShow(idx int) {
return
}
a := apps[idx]
a.hwnd = memberHwnd(a)
previewDropThumb()
iconic, _, _ := pIsIconic.Call(a.hwnd)
@@ -297,7 +298,7 @@ func previewTick() {
}
idx = appIndexAt(hwndMain, x)
if idx >= 0 && idx < len(apps) {
raw = apps[idx].hwnd
raw = memberHwnd(apps[idx])
}
}
target := raw
+392 -390
View File
@@ -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
}
+25 -8
View File
@@ -72,6 +72,9 @@ const (
idShowNews = 214
idShowSys = 215
idPanelFade = 216
idShowGM = 217
idGroup = 218
idAutoHide = 219
)
var (
@@ -82,7 +85,8 @@ var (
ctlAlpha, ctlAlphaValue, ctlLogo, ctlClock, ctlTrayIcons, ctlStyle uintptr
ctlVertical, ctlAutostart uintptr
ctlZip, ctlZipStatus uintptr
ctlShowWeather, ctlShowNews, ctlShowSys, ctlPanelFade uintptr
ctlShowWeather, ctlShowNews, ctlShowSys, ctlShowGM, ctlPanelFade uintptr
ctlGroup, ctlAutoHide uintptr
zipSyncing bool // true while the program itself is filling in the ZIP box
)
@@ -134,7 +138,7 @@ func openSettings() {
settingsFont = makeFont(px(13), 400)
}
r := rect{0, 0, px(400), px(488)}
r := rect{0, 0, px(400), px(572)}
pAdjustWindowRectEx.Call(uintptr(unsafe.Pointer(&r)), wsWindowFrame, 0, 0)
ow, oh := r.Right-r.Left, r.Bottom-r.Top
sw, sh := screenSize()
@@ -184,13 +188,17 @@ func openSettings() {
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)
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, 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)
ctlGroup = makeControl(hw, inst, "BUTTON", "Combine windows of the same program into one icon", bsAutoCheckBox|wsTabStop, 16, 458, 368, 22, idGroup)
ctlAutoHide = makeControl(hw, inst, "BUTTON", "Hide the bar until the mouse touches the screen edge", bsAutoCheckBox|wsTabStop, 16, 486, 368, 22, idAutoHide)
makeControl(hw, inst, "BUTTON", "Reset position", bsPushButton|wsTabStop, 16, 526, 116, 28, idResetPos)
makeControl(hw, inst, "BUTTON", "Reset bar width", bsPushButton|wsTabStop, 140, 526, 116, 28, idResetWidth)
makeControl(hw, inst, "BUTTON", "Close", bsDefPushButton|wsTabStop, 292, 526, 92, 28, idClose)
hwndSettings = hw
settingsSync()
@@ -212,9 +220,12 @@ func settingsSync() {
pSendMessage.Call(ctlShowWeather, bmSetCheck, boolWP(showWeather), 0)
pSendMessage.Call(ctlShowNews, bmSetCheck, boolWP(showNews), 0)
pSendMessage.Call(ctlShowSys, bmSetCheck, boolWP(showSys), 0)
pSendMessage.Call(ctlShowGM, bmSetCheck, boolWP(showGM), 0)
pSendMessage.Call(ctlPanelFade, bmSetCheck, boolWP(flyMatchBar), 0)
pSendMessage.Call(ctlVertical, bmSetCheck, boolWP(vertical), 0)
pSendMessage.Call(ctlAutostart, bmSetCheck, boolWP(autostartEnabled()), 0)
pSendMessage.Call(ctlGroup, bmSetCheck, boolWP(groupWins), 0)
pSendMessage.Call(ctlAutoHide, bmSetCheck, boolWP(autoHide), 0)
// Leave the ZIP box alone while the person is typing in it.
if f, _, _ := pGetFocus.Call(); f != ctlZip && zipText() != wxZip {
@@ -313,12 +324,18 @@ func settingsCommand(id, note uintptr) {
setShowNews(checked(ctlShowNews))
case idShowSys:
setShowSys(checked(ctlShowSys))
case idShowGM:
setShowGM(checked(ctlShowGM))
case idPanelFade:
setFlyMatchBar(checked(ctlPanelFade))
case idVertical:
vertical = checked(ctlVertical)
saveOrient()
resetPos(hwndMain)
case idGroup:
setGroupWins(checked(ctlGroup))
case idAutoHide:
setAutoHide(checked(ctlAutoHide))
case idAutostart:
setAutostart(checked(ctlAutostart))
settingsSync()
+271 -270
View File
@@ -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)
}
+875 -849
View File
File diff suppressed because it is too large Load Diff