diff --git a/features.go b/features.go index a2c61f4..5fda943 100644 --- a/features.go +++ b/features.go @@ -1,128 +1,146 @@ -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 - case "panelfade": - flyMatchBar = on - } - } -} - -func saveFeatures() { - s := "weather=" + b01(showWeather) + "\nnews=" + b01(showNews) + "\nsys=" + b01(showSys) + "\npanelfade=" + b01(flyMatchBar) + "\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() -} - -// setFlyMatchBar is called by the settings window: should the panels be as -// see-through as the bar? -func setFlyMatchBar(on bool) { - if flyMatchBar == on { - return - } - flyMatchBar = on - saveFeatures() - flyRefreshAll() -} - -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() -} +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 + showGM = true // the Google Messages bubble +) + +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 + case "messages": + showGM = on + case "panelfade": + flyMatchBar = on + } + } +} + +func saveFeatures() { + s := "weather=" + b01(showWeather) + "\nnews=" + b01(showNews) + "\nsys=" + b01(showSys) + "\nmessages=" + b01(showGM) + "\npanelfade=" + b01(flyMatchBar) + "\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() +} + +// 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) { + if flyMatchBar == on { + return + } + flyMatchBar = on + saveFeatures() + flyRefreshAll() +} + +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/flyout.go b/flyout.go index 03f1256..9b45a56 100644 --- a/flyout.go +++ b/flyout.go @@ -1,602 +1,603 @@ -package main - -// The weather flyout: a storm cloud on the bar that opens a small panel above -// it with the current weather, the next five days and the moon phase. -// -// The panel is its own window, like the hover preview: it never takes focus -// from what you are working in. It goes away when you click the cloud again or -// click anywhere else. It is painted at double size and shrunk down so the -// round pictures (sun, clouds, moon) have smooth edges. - -import ( - "math" - "strconv" - "syscall" - "time" - "unsafe" -) - -var ( - pEllipse = gdi32.NewProc("Ellipse") - pStretchBlt = gdi32.NewProc("StretchBlt") - pSetStretchBltMode = gdi32.NewProc("SetStretchBltMode") - pSetBrushOrgEx = gdi32.NewProc("SetBrushOrgEx") -) - -const ( - wxLayoutW = 340.0 // panel width, in 96 dpi units - wxFullH = 428.0 // panel height when there is a forecast to show - wxRadarH = 158.0 // extra height when the radar picture fits on the screen - wxShortH = 150.0 // panel height for the "add a ZIP code" and error messages - - wxPollTimerID = 1 - wxAnimTimerID = 2 - vkRButton = 0x02 - srcCopy = 0x00CC0020 - halftone = 4 - dtWordBreak = 0x0010 - dtRight = 0x0002 -) - -var ( - wxHwnd uintptr - wxShown bool - wxPrevBtn bool // a mouse button was down at the last look - - wxFontsMade bool - fBig, fMed, fText, fBold, fSmall, fTiny uintptr - - rdHold int // how many beats the newest radar frame has been held for -) - -// ---------- the button on the bar ---------- - -// circleRaw paints a filled circle with no outline. -func circleRaw(hdc uintptr, cx, cy, rad int32, color uintptr) { - brush, _, _ := pCreateSolidBrush.Call(color) - nullPen, _, _ := pGetStockObject.Call(8) // NULL_PEN - oldBrush, _, _ := pSelectObject.Call(hdc, brush) - oldPen, _, _ := pSelectObject.Call(hdc, nullPen) - pEllipse.Call(hdc, uintptr(cx-rad), uintptr(cy-rad), uintptr(cx+rad+1), uintptr(cy+rad+1)) - pSelectObject.Call(hdc, oldPen) - pSelectObject.Call(hdc, oldBrush) - pDeleteObject.Call(brush) -} - -// drawWeatherIcon draws the little storm cloud on the bar. -func drawWeatherIcon(hdc uintptr, r rect) { - if !layerFg { - return - } - cx, cy := center(r) - cx -= px(0.5) - - // A small sun up and to the left, with a cloud drifting in front of its lower right. - br, bg, bb := styleColor(255, 205, 60) - sun := rgb(br, bg, bb) - sx, sy := cx-px(2), cy-px(2) - circleRaw(hdc, sx, sy, px(3), sun) - for k := 0; k < 8; k++ { - a := float64(k) * math.Pi / 4 - c, s := math.Cos(a), math.Sin(a) - polyline(hdc, []point{ - {sx + int32(math.Round(c*float64(px(4.3)))), sy + int32(math.Round(s*float64(px(4.3))))}, - {sx + int32(math.Round(c*float64(px(5.5)))), sy + int32(math.Round(s*float64(px(5.5))))}, - }, px(1), sun) - } - - col := iconColor() - circleRaw(hdc, cx-px(0.5), cy+px(3.5), px(2.5), col) - circleRaw(hdc, cx+px(2.5), cy+px(1.5), px(3.2), col) - circleRaw(hdc, cx+px(5.5), cy+px(3.5), px(2.3), col) - fillRaw(hdc, rect{cx - px(0.5), cy + px(3.5), cx + px(5.5), cy + px(6)}, col) -} - -// ---------- the panel window ---------- - -func weatherInit(inst uintptr) { - cursor, _, _ := pLoadCursor.Call(0, idcArrow) - className := u16("MirrorBarWeather") - wc := wndClassEx{ - WndProc: syscall.NewCallback(weatherProc), - Instance: inst, - Cursor: cursor, - ClassName: className, - } - wc.Size = uint32(unsafe.Sizeof(wc)) - pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) - wxHwnd, _, _ = pCreateWindowEx.Call( - wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, - uintptr(unsafe.Pointer(className)), - uintptr(unsafe.Pointer(u16(""))), - wsPopup, - 0, 0, 10, 10, - 0, 0, inst, 0) -} - -func weatherProc(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: - wxPaint(hwnd) - return 0 - case wmTimer: - if wparam == wxAnimTimerID { - radarAdvance() - return 0 - } - weatherPoll() - return 0 - case wmLButtonUp: - weatherClick() - return 0 - } - r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) - return r -} - -// weatherToggle is what clicking the cloud does. -func weatherToggle() { - if wxShown { - weatherHide() - return - } - if wxHwnd == 0 || !showWeather { - return - } - previewHide() - newsHide() // one panel at a time - sysHide() - weatherRefresh(false) - wxShown = true - wxPrevBtn = true // ignore a button that is still held from the click that opened this - weatherPlace() - pSetTimer.Call(wxHwnd, wxPollTimerID, 80, 0) - pSetTimer.Call(wxHwnd, wxAnimTimerID, 450, 0) - radarEnsure(false) -} - -func weatherHide() { - if !wxShown { - return - } - wxShown = false - pKillTimer.Call(wxHwnd, wxPollTimerID) - pKillTimer.Call(wxHwnd, wxAnimTimerID) - pShowWindow.Call(wxHwnd, swHide) -} - -func weatherShutdown() { - weatherHide() - if wxHwnd != 0 { - pDestroyWindow.Call(wxHwnd) - wxHwnd = 0 - } -} - -// weatherAnchor is where the cloud sits on the screen. -func weatherAnchor() rect { return trayAnchor(trayWeather) } - -// weatherPlace sizes the panel for what it has to show and puts it next to the -// cloud: above a horizontal bar, to the left of a vertical one. -func weatherPlace() { - if wxHwnd == 0 { - return - } - s := wxSnapshot() - lh := wxShortH - if s.ok && wxZip != "" { - lh = wxFullH - if wxRadarFits() { - lh += wxRadarH - } - } - cw, ch := px(wxLayoutW), px(lh) - - ar := weatherAnchor() - 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(wxHwnd, hwndTopmost, uintptr(x), uintptr(y), uintptr(cw), uintptr(ch), swpNoActivate|swpShowWindow) - flyRefresh(wxHwnd) -} - -// weatherPoll closes the panel when a mouse button goes down anywhere outside -// it (the cloud itself is left alone, so clicking it can close the panel). -func weatherPoll() { - l, _, _ := pGetAsyncKeyState.Call(vkLButton) - r, _, _ := pGetAsyncKeyState.Call(vkRButton) - down := (l|r)&0x8000 != 0 - if down && !wxPrevBtn { - var cp point - pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) - var fr rect - pGetWindowRect.Call(wxHwnd, uintptr(unsafe.Pointer(&fr))) - if !inRect(fr, cp) && !inRect(weatherAnchor(), cp) { - weatherHide() - } - } - wxPrevBtn = down -} - -// weatherClick runs when the panel itself is clicked: the messages in it are -// buttons (open the settings, try again). -func weatherClick() { - s := wxSnapshot() - switch { - case wxZip == "": - weatherHide() - openSettings() - case !s.ok && !s.loading: - weatherRefresh(true) - } -} - -// weatherDone runs when a lookup finishes. -func weatherDone() { - newsDone() - if wxShown { - weatherPlace() - radarEnsure(false) - } - settingsZipStatusUpdate() -} - -// weatherStatusText is the one line the settings window shows under the ZIP box. -func weatherStatusText() string { - if wxZip == "" { - return "Type a 5 digit ZIP code to turn the weather on." - } - s := wxSnapshot() - switch { - case s.ok && s.place != "": - return "Showing weather for " + s.place - case s.loading: - return "Looking up " + wxZip + "..." - case s.err != "": - return s.err - } - return "" -} - -// ---------- painting ---------- - -func wxMakeFonts() { - if wxFontsMade { - return - } - // Called while the scale is doubled, so these are double size fonts. - fBig = makeFont(px(34), 400) - fMed = makeFont(px(15), 600) - fText = makeFont(px(13), 400) - fBold = makeFont(px(13), 600) - fSmall = makeFont(px(11), 400) - fTiny = makeFont(px(9), 400) - wxFontsMade = true -} - -func wxPaint(hwnd uintptr) { flyPaint(hwnd, wxDraw) } - -// flyPaint answers a paint request: the panel is rendered see-through (see -// flyrender.go) instead of being painted by Windows. -func flyPaint(hwnd uintptr, draw func(hdc uintptr, W, H int32)) { - var ps paintStruct - pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) - pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) - flyRender(hwnd, draw) -} - -var ( - colBack = rgb(28, 28, 34) - colRule = rgb(52, 52, 62) - colText = rgb(240, 240, 245) - colDim = rgb(150, 150, 165) - colAccent = rgb(90, 190, 255) -) - -func wxText(hdc uintptr, s string, r rect, font, col, flags uintptr) { - pSetBkMode.Call(hdc, transparent) - pSetTextColor.Call(hdc, col) - old, _, _ := pSelectObject.Call(hdc, font) - drawTextFmt(hdc, s, r, flags|dtNoPrefix) - pSelectObject.Call(hdc, old) -} - -// wxDraw paints the whole panel. The scale is already doubled, so every px() -// here is a double size distance. -func wxDraw(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) - inner := W - 2*pad - s := wxSnapshot() - line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis) - rule := func(y int32) { fillRaw(hdc, rect{pad, y, W - pad, y + u(1)}, colRule) } - - // Header: the place on the left, how fresh the data is on the right. - title := "Weather" - if s.place != "" && wxZip != "" { - title = s.place - } - 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 == "" || !s.ok { - body := rect{pad, u(48), W - pad, H - pad} - 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 forecast...", "" - default: - head, sub = "No weather right now", s.err+" Click here to try again." - } - wxText(hdc, head, rect{body.Left, body.Top, body.Right, body.Top + u(26)}, fMed, colText, dtCenter|dtVCenter|dtSingleLine) - if sub != "" { - wxText(hdc, sub, rect{body.Left, body.Top + u(30), body.Right, body.Bottom}, fText, colDim, dtCenter|dtWordBreak) - } - return - } - - now, today := s.now, s.days[0] - - // Current conditions. - wxIcon(hdc, wxKind(now.code), rect{pad, u(42), pad + u(64), u(42) + u(64)}, now.day) - wxText(hdc, wxF(now.temp), rect{pad + u(76), u(38), pad + u(76) + u(120), u(88)}, fBig, colText, dtLeft|dtVCenter|dtSingleLine) - wxText(hdc, wxDesc(now.code), rect{pad + u(76), u(88), W - pad, u(110)}, fText, colDim, line) - wxText(hdc, "Feels like "+wxF(now.feels), rect{W - pad - u(124), u(44), W - pad, u(62)}, fText, colText, dtRight|dtVCenter|dtSingleLine) - wxText(hdc, "High "+wxDeg(today.hi)+" Low "+wxDeg(today.lo), rect{W - pad - u(124), u(64), W - pad, u(82)}, fText, colText, dtRight|dtVCenter|dtSingleLine) - rule(u(124)) - - // Details, three across. - colW := inner / 3 - cell := func(i int, row int32, label, value string) { - x := pad + int32(i)*colW - y := u(132) + row*u(44) - wxText(hdc, label, rect{x, y, x + colW, y + u(14)}, fSmall, colDim, line) - wxText(hdc, value, rect{x, y + u(14), x + colW, y + u(36)}, fBold, colText, line) - } - dash := func(v string) string { - if v == "" { - return "-" - } - return v - } - cell(0, 0, "Humidity", strconv.Itoa(now.humidity)+"%") - cell(1, 0, "Wind", strconv.Itoa(int(math.Round(now.wind)))+" mph") - cell(2, 0, "Chance of rain", strconv.Itoa(today.rain)+"%") - cell(0, 1, "Sunrise", dash(today.sunrise)) - cell(1, 1, "Sunset", dash(today.sunset)) - cell(2, 1, "UV index", strconv.Itoa(int(math.Round(today.uv)))) - rule(u(218)) - - // Radar, when the panel is tall enough to have room for it. Everything below it - // is drawn the same way, just moved down. - if H >= u(wxFullH+wxRadarH-1) { - radarDraw(hdc, rect{pad, u(226), W - pad, u(226) + u(150)}) - rule(u(382)) - pSetViewportOrgEx.Call(hdc, 0, uintptr(u(wxRadarH)), 0) - defer pSetViewportOrgEx.Call(hdc, 0, 0, 0) - } - - // Moon. - moon := moonAt(time.Now()) - wxMoonDraw(hdc, pad+u(24), u(254), u(22), moon, s.lat >= 0) - tx := pad + u(60) - wxText(hdc, moon.name, rect{tx, u(232), W - pad, u(252)}, fMed, colText, line) - wxText(hdc, strconv.Itoa(int(math.Round(moon.illum*100)))+"% lit", rect{tx, u(254), W - pad, u(272)}, fText, colDim, line) - wxText(hdc, moon.fullText(), rect{tx, u(272), W - pad, u(288)}, fSmall, colDim, line) - rule(u(296)) - - // The next five days. - wxText(hdc, "5-DAY FORECAST", rect{pad, u(304), W - pad, u(320)}, fSmall, colDim, line) - days := s.days[1:] - if len(days) > 5 { - days = days[:5] - } - cw := inner / 5 - for i, d := range days { - x := pad + int32(i)*cw - col := rect{x, 0, x + cw, 0} - wxText(hdc, d.date.Weekday().String()[:3], rect{col.Left, u(324), col.Right, u(342)}, fBold, colText, dtCenter|dtVCenter|dtSingleLine) - ic := u(32) - ix := x + (cw-ic)/2 - wxIcon(hdc, wxKind(d.code), rect{ix, u(344), ix + ic, u(344) + ic}, true) - wxText(hdc, wxDeg(d.hi), rect{col.Left, u(380), col.Right, u(400)}, fBold, colText, dtCenter|dtVCenter|dtSingleLine) - wxText(hdc, wxDeg(d.lo), rect{col.Left, u(400), col.Right, u(418)}, fText, colDim, dtCenter|dtVCenter|dtSingleLine) - } -} - -// ---------- pictures ---------- - -func wxCircle(hdc uintptr, cx, cy, rad float64, color uintptr) { - circleRaw(hdc, int32(math.Round(cx)), int32(math.Round(cy)), int32(math.Round(rad)), color) -} - -// wxCloud draws a cloud about 0.67 of s wide, centered on cx and cy. -func wxCloud(hdc uintptr, cx, cy, s float64, color uintptr) { - cy += 0.045 * s // the cloud's own middle sits a little above its circles - wxCircle(hdc, cx-0.20*s, cy+0.03*s, 0.14*s, color) - wxCircle(hdc, cx-0.02*s, cy-0.07*s, 0.19*s, color) - wxCircle(hdc, cx+0.20*s, cy+0.04*s, 0.13*s, color) - fillRaw(hdc, rect{ - int32(math.Round(cx - 0.20*s)), int32(math.Round(cy + 0.02*s)), - int32(math.Round(cx + 0.20*s)), int32(math.Round(cy + 0.17*s)), - }, color) -} - -func wxLine(hdc uintptr, x0, y0, x1, y1, width float64, color uintptr) { - polyline(hdc, []point{ - {int32(math.Round(x0)), int32(math.Round(y0))}, - {int32(math.Round(x1)), int32(math.Round(y1))}, - }, max(1, int32(math.Round(width))), color) -} - -func wxSunGlyph(hdc uintptr, cx, cy, s float64) { - col := rgb(255, 200, 60) - wxCircle(hdc, cx, cy, 0.2*s, col) - for k := 0; k < 8; k++ { - a := float64(k) * math.Pi / 4 - c, si := math.Cos(a), math.Sin(a) - wxLine(hdc, cx+c*0.30*s, cy+si*0.30*s, cx+c*0.43*s, cy+si*0.43*s, 0.05*s, col) - } -} - -func wxCrescent(hdc uintptr, cx, cy, rad float64) { - brush, _, _ := pCreateSolidBrush.Call(rgb(235, 232, 205)) - defer pDeleteObject.Call(brush) - ix, iy, ir := cx+0.45*rad, cy-0.25*rad, 0.85*rad // the circle that is cut out - top := int32(math.Round(cy)) - r := int32(math.Ceil(rad)) - for dy := -r; dy <= r; dy++ { - y := top + dy - oh2 := rad*rad - float64(dy)*float64(dy) - if oh2 <= 0 { - continue - } - oh := math.Sqrt(oh2) - x0, x1 := cx-oh, cx+oh - var segs [][2]float64 - fy := float64(y) + 0.5 - iy - if ih2 := ir*ir - fy*fy; ih2 > 0 { - ih := math.Sqrt(ih2) - if l := ix - ih; l > x0 { - segs = append(segs, [2]float64{x0, math.Min(l, x1)}) - } - if rr := ix + ih; rr < x1 { - segs = append(segs, [2]float64{math.Max(rr, x0), x1}) - } - } else { - segs = append(segs, [2]float64{x0, x1}) - } - for _, sg := range segs { - if sg[1]-sg[0] < 0.5 { - continue - } - line := rect{int32(math.Round(sg[0])), y, int32(math.Round(sg[1])), y + 1} - pFillRect.Call(hdc, uintptr(unsafe.Pointer(&line)), brush) - } - } -} - -// wxIcon draws the picture for a kind of weather inside the square r. -func wxIcon(hdc uintptr, kind int, r rect, day bool) { - s := float64(r.Right - r.Left) - cx := float64(r.Left+r.Right) / 2 - cy := float64(r.Top+r.Bottom) / 2 - light := rgb(205, 212, 225) - - switch kind { - case wxSun: - if day { - wxSunGlyph(hdc, cx, cy, s) - } else { - wxCrescent(hdc, cx, cy, 0.3*s) - } - case wxPartly: - if day { - wxSunGlyph(hdc, cx-0.14*s, cy-0.15*s, 0.8*s) - } else { - wxCrescent(hdc, cx-0.14*s, cy-0.15*s, 0.22*s) - } - wxCloud(hdc, cx+0.04*s, cy+0.08*s, 0.9*s, light) - case wxCloudy: - wxCloud(hdc, cx, cy, 1.1*s, light) - case wxFog: - fog := rgb(150, 158, 172) - wxCloud(hdc, cx, cy-0.1*s, s, fog) - for i, w := range []float64{0.26, 0.20, 0.26} { - y := cy + (0.16+0.10*float64(i))*s - wxLine(hdc, cx-w*s, y, cx+w*s, y, 0.04*s, fog) - } - case wxRain: - wxCloud(hdc, cx, cy-0.1*s, s, rgb(170, 180, 198)) - for _, dx := range []float64{-0.16, 0, 0.16} { - x := cx + dx*s - wxLine(hdc, x, cy+0.14*s, x-0.04*s, cy+0.32*s, 0.045*s, rgb(80, 165, 255)) - } - case wxSnow: - wxCloud(hdc, cx, cy-0.1*s, s, rgb(185, 195, 212)) - wxCircle(hdc, cx-0.15*s, cy+0.17*s, 0.035*s, colText) - wxCircle(hdc, cx, cy+0.29*s, 0.035*s, colText) - wxCircle(hdc, cx+0.15*s, cy+0.17*s, 0.035*s, colText) - case wxStorm: - wxCloud(hdc, cx, cy-0.12*s, s, rgb(115, 122, 140)) - pts := [][2]float64{{0.07, 0.02}, {-0.09, 0.24}, {0.01, 0.24}, {-0.07, 0.42}, {0.13, 0.16}, {0.03, 0.16}} - bolt := make([]point, len(pts)) - for i, p := range pts { - bolt[i] = point{int32(math.Round(cx + p[0]*s)), int32(math.Round(cy + p[1]*s))} - } - polygon(hdc, bolt, rgb(255, 205, 60)) - } -} - -// wxMoonDraw draws the moon with its lit part. A waxing moon is lit on the -// right and a waning one on the left; south of the equator that is the other -// way around. -func wxMoonDraw(hdc uintptr, cx, cy, r int32, m moonInfo, north bool) { - wxCircle(hdc, float64(cx), float64(cy), float64(r), rgb(58, 60, 74)) - - brush, _, _ := pCreateSolidBrush.Call(rgb(236, 232, 208)) - defer pDeleteObject.Call(brush) - - waxing := m.frac < 0.5 - theta := 2 * math.Pi * m.frac - if !waxing { - theta = 2 * math.Pi * (1 - m.frac) - } - ct := math.Cos(theta) - for dy := -r; dy <= r; dy++ { - hw := math.Sqrt(math.Max(0, float64(r)*float64(r)-float64(dy)*float64(dy))) - xt := hw * ct - x0, x1 := xt, hw - if !waxing { - x0, x1 = -hw, -xt - } - if !north { - x0, x1 = -x1, -x0 - } - if x1-x0 < 0.5 { - continue - } - line := rect{cx + int32(math.Round(x0)), cy + dy, cx + int32(math.Round(x1)), cy + dy + 1} - pFillRect.Call(hdc, uintptr(unsafe.Pointer(&line)), brush) - } -} +package main + +// The weather flyout: a storm cloud on the bar that opens a small panel above +// it with the current weather, the next five days and the moon phase. +// +// The panel is its own window, like the hover preview: it never takes focus +// from what you are working in. It goes away when you click the cloud again or +// click anywhere else. It is painted at double size and shrunk down so the +// round pictures (sun, clouds, moon) have smooth edges. + +import ( + "math" + "strconv" + "syscall" + "time" + "unsafe" +) + +var ( + pEllipse = gdi32.NewProc("Ellipse") + pStretchBlt = gdi32.NewProc("StretchBlt") + pSetStretchBltMode = gdi32.NewProc("SetStretchBltMode") + pSetBrushOrgEx = gdi32.NewProc("SetBrushOrgEx") +) + +const ( + wxLayoutW = 340.0 // panel width, in 96 dpi units + wxFullH = 428.0 // panel height when there is a forecast to show + wxRadarH = 158.0 // extra height when the radar picture fits on the screen + wxShortH = 150.0 // panel height for the "add a ZIP code" and error messages + + wxPollTimerID = 1 + wxAnimTimerID = 2 + vkRButton = 0x02 + srcCopy = 0x00CC0020 + halftone = 4 + dtWordBreak = 0x0010 + dtRight = 0x0002 +) + +var ( + wxHwnd uintptr + wxShown bool + wxPrevBtn bool // a mouse button was down at the last look + + wxFontsMade bool + fBig, fMed, fText, fBold, fSmall, fTiny uintptr + + rdHold int // how many beats the newest radar frame has been held for +) + +// ---------- the button on the bar ---------- + +// circleRaw paints a filled circle with no outline. +func circleRaw(hdc uintptr, cx, cy, rad int32, color uintptr) { + brush, _, _ := pCreateSolidBrush.Call(color) + nullPen, _, _ := pGetStockObject.Call(8) // NULL_PEN + oldBrush, _, _ := pSelectObject.Call(hdc, brush) + oldPen, _, _ := pSelectObject.Call(hdc, nullPen) + pEllipse.Call(hdc, uintptr(cx-rad), uintptr(cy-rad), uintptr(cx+rad+1), uintptr(cy+rad+1)) + pSelectObject.Call(hdc, oldPen) + pSelectObject.Call(hdc, oldBrush) + pDeleteObject.Call(brush) +} + +// drawWeatherIcon draws the little storm cloud on the bar. +func drawWeatherIcon(hdc uintptr, r rect) { + if !layerFg { + return + } + cx, cy := center(r) + cx -= px(0.5) + + // A small sun up and to the left, with a cloud drifting in front of its lower right. + br, bg, bb := styleColor(255, 205, 60) + sun := rgb(br, bg, bb) + sx, sy := cx-px(2), cy-px(2) + circleRaw(hdc, sx, sy, px(3), sun) + for k := 0; k < 8; k++ { + a := float64(k) * math.Pi / 4 + c, s := math.Cos(a), math.Sin(a) + polyline(hdc, []point{ + {sx + int32(math.Round(c*float64(px(4.3)))), sy + int32(math.Round(s*float64(px(4.3))))}, + {sx + int32(math.Round(c*float64(px(5.5)))), sy + int32(math.Round(s*float64(px(5.5))))}, + }, px(1), sun) + } + + col := iconColor() + circleRaw(hdc, cx-px(0.5), cy+px(3.5), px(2.5), col) + circleRaw(hdc, cx+px(2.5), cy+px(1.5), px(3.2), col) + circleRaw(hdc, cx+px(5.5), cy+px(3.5), px(2.3), col) + fillRaw(hdc, rect{cx - px(0.5), cy + px(3.5), cx + px(5.5), cy + px(6)}, col) +} + +// ---------- the panel window ---------- + +func weatherInit(inst uintptr) { + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + className := u16("MirrorBarWeather") + wc := wndClassEx{ + WndProc: syscall.NewCallback(weatherProc), + Instance: inst, + Cursor: cursor, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + wxHwnd, _, _ = pCreateWindowEx.Call( + wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, + uintptr(unsafe.Pointer(className)), + uintptr(unsafe.Pointer(u16(""))), + wsPopup, + 0, 0, 10, 10, + 0, 0, inst, 0) +} + +func weatherProc(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: + wxPaint(hwnd) + return 0 + case wmTimer: + if wparam == wxAnimTimerID { + radarAdvance() + return 0 + } + weatherPoll() + return 0 + case wmLButtonUp: + weatherClick() + return 0 + } + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +} + +// weatherToggle is what clicking the cloud does. +func weatherToggle() { + if wxShown { + weatherHide() + return + } + if wxHwnd == 0 || !showWeather { + return + } + previewHide() + newsHide() // one panel at a time + sysHide() + gmHide() + weatherRefresh(false) + wxShown = true + wxPrevBtn = true // ignore a button that is still held from the click that opened this + weatherPlace() + pSetTimer.Call(wxHwnd, wxPollTimerID, 80, 0) + pSetTimer.Call(wxHwnd, wxAnimTimerID, 450, 0) + radarEnsure(false) +} + +func weatherHide() { + if !wxShown { + return + } + wxShown = false + pKillTimer.Call(wxHwnd, wxPollTimerID) + pKillTimer.Call(wxHwnd, wxAnimTimerID) + pShowWindow.Call(wxHwnd, swHide) +} + +func weatherShutdown() { + weatherHide() + if wxHwnd != 0 { + pDestroyWindow.Call(wxHwnd) + wxHwnd = 0 + } +} + +// weatherAnchor is where the cloud sits on the screen. +func weatherAnchor() rect { return trayAnchor(trayWeather) } + +// weatherPlace sizes the panel for what it has to show and puts it next to the +// cloud: above a horizontal bar, to the left of a vertical one. +func weatherPlace() { + if wxHwnd == 0 { + return + } + s := wxSnapshot() + lh := wxShortH + if s.ok && wxZip != "" { + lh = wxFullH + if wxRadarFits() { + lh += wxRadarH + } + } + cw, ch := px(wxLayoutW), px(lh) + + ar := weatherAnchor() + 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(wxHwnd, hwndTopmost, uintptr(x), uintptr(y), uintptr(cw), uintptr(ch), swpNoActivate|swpShowWindow) + flyRefresh(wxHwnd) +} + +// weatherPoll closes the panel when a mouse button goes down anywhere outside +// it (the cloud itself is left alone, so clicking it can close the panel). +func weatherPoll() { + l, _, _ := pGetAsyncKeyState.Call(vkLButton) + r, _, _ := pGetAsyncKeyState.Call(vkRButton) + down := (l|r)&0x8000 != 0 + if down && !wxPrevBtn { + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + var fr rect + pGetWindowRect.Call(wxHwnd, uintptr(unsafe.Pointer(&fr))) + if !inRect(fr, cp) && !inRect(weatherAnchor(), cp) { + weatherHide() + } + } + wxPrevBtn = down +} + +// weatherClick runs when the panel itself is clicked: the messages in it are +// buttons (open the settings, try again). +func weatherClick() { + s := wxSnapshot() + switch { + case wxZip == "": + weatherHide() + openSettings() + case !s.ok && !s.loading: + weatherRefresh(true) + } +} + +// weatherDone runs when a lookup finishes. +func weatherDone() { + newsDone() + if wxShown { + weatherPlace() + radarEnsure(false) + } + settingsZipStatusUpdate() +} + +// weatherStatusText is the one line the settings window shows under the ZIP box. +func weatherStatusText() string { + if wxZip == "" { + return "Type a 5 digit ZIP code to turn the weather on." + } + s := wxSnapshot() + switch { + case s.ok && s.place != "": + return "Showing weather for " + s.place + case s.loading: + return "Looking up " + wxZip + "..." + case s.err != "": + return s.err + } + return "" +} + +// ---------- painting ---------- + +func wxMakeFonts() { + if wxFontsMade { + return + } + // Called while the scale is doubled, so these are double size fonts. + fBig = makeFont(px(34), 400) + fMed = makeFont(px(15), 600) + fText = makeFont(px(13), 400) + fBold = makeFont(px(13), 600) + fSmall = makeFont(px(11), 400) + fTiny = makeFont(px(9), 400) + wxFontsMade = true +} + +func wxPaint(hwnd uintptr) { flyPaint(hwnd, wxDraw) } + +// flyPaint answers a paint request: the panel is rendered see-through (see +// flyrender.go) instead of being painted by Windows. +func flyPaint(hwnd uintptr, draw func(hdc uintptr, W, H int32)) { + var ps paintStruct + pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + flyRender(hwnd, draw) +} + +var ( + colBack = rgb(28, 28, 34) + colRule = rgb(52, 52, 62) + colText = rgb(240, 240, 245) + colDim = rgb(150, 150, 165) + colAccent = rgb(90, 190, 255) +) + +func wxText(hdc uintptr, s string, r rect, font, col, flags uintptr) { + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, col) + old, _, _ := pSelectObject.Call(hdc, font) + drawTextFmt(hdc, s, r, flags|dtNoPrefix) + pSelectObject.Call(hdc, old) +} + +// wxDraw paints the whole panel. The scale is already doubled, so every px() +// here is a double size distance. +func wxDraw(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) + inner := W - 2*pad + s := wxSnapshot() + line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis) + rule := func(y int32) { fillRaw(hdc, rect{pad, y, W - pad, y + u(1)}, colRule) } + + // Header: the place on the left, how fresh the data is on the right. + title := "Weather" + if s.place != "" && wxZip != "" { + title = s.place + } + 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 == "" || !s.ok { + body := rect{pad, u(48), W - pad, H - pad} + 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 forecast...", "" + default: + head, sub = "No weather right now", s.err+" Click here to try again." + } + wxText(hdc, head, rect{body.Left, body.Top, body.Right, body.Top + u(26)}, fMed, colText, dtCenter|dtVCenter|dtSingleLine) + if sub != "" { + wxText(hdc, sub, rect{body.Left, body.Top + u(30), body.Right, body.Bottom}, fText, colDim, dtCenter|dtWordBreak) + } + return + } + + now, today := s.now, s.days[0] + + // Current conditions. + wxIcon(hdc, wxKind(now.code), rect{pad, u(42), pad + u(64), u(42) + u(64)}, now.day) + wxText(hdc, wxF(now.temp), rect{pad + u(76), u(38), pad + u(76) + u(120), u(88)}, fBig, colText, dtLeft|dtVCenter|dtSingleLine) + wxText(hdc, wxDesc(now.code), rect{pad + u(76), u(88), W - pad, u(110)}, fText, colDim, line) + wxText(hdc, "Feels like "+wxF(now.feels), rect{W - pad - u(124), u(44), W - pad, u(62)}, fText, colText, dtRight|dtVCenter|dtSingleLine) + wxText(hdc, "High "+wxDeg(today.hi)+" Low "+wxDeg(today.lo), rect{W - pad - u(124), u(64), W - pad, u(82)}, fText, colText, dtRight|dtVCenter|dtSingleLine) + rule(u(124)) + + // Details, three across. + colW := inner / 3 + cell := func(i int, row int32, label, value string) { + x := pad + int32(i)*colW + y := u(132) + row*u(44) + wxText(hdc, label, rect{x, y, x + colW, y + u(14)}, fSmall, colDim, line) + wxText(hdc, value, rect{x, y + u(14), x + colW, y + u(36)}, fBold, colText, line) + } + dash := func(v string) string { + if v == "" { + return "-" + } + return v + } + cell(0, 0, "Humidity", strconv.Itoa(now.humidity)+"%") + cell(1, 0, "Wind", strconv.Itoa(int(math.Round(now.wind)))+" mph") + cell(2, 0, "Chance of rain", strconv.Itoa(today.rain)+"%") + cell(0, 1, "Sunrise", dash(today.sunrise)) + cell(1, 1, "Sunset", dash(today.sunset)) + cell(2, 1, "UV index", strconv.Itoa(int(math.Round(today.uv)))) + rule(u(218)) + + // Radar, when the panel is tall enough to have room for it. Everything below it + // is drawn the same way, just moved down. + if H >= u(wxFullH+wxRadarH-1) { + radarDraw(hdc, rect{pad, u(226), W - pad, u(226) + u(150)}) + rule(u(382)) + pSetViewportOrgEx.Call(hdc, 0, uintptr(u(wxRadarH)), 0) + defer pSetViewportOrgEx.Call(hdc, 0, 0, 0) + } + + // Moon. + moon := moonAt(time.Now()) + wxMoonDraw(hdc, pad+u(24), u(254), u(22), moon, s.lat >= 0) + tx := pad + u(60) + wxText(hdc, moon.name, rect{tx, u(232), W - pad, u(252)}, fMed, colText, line) + wxText(hdc, strconv.Itoa(int(math.Round(moon.illum*100)))+"% lit", rect{tx, u(254), W - pad, u(272)}, fText, colDim, line) + wxText(hdc, moon.fullText(), rect{tx, u(272), W - pad, u(288)}, fSmall, colDim, line) + rule(u(296)) + + // The next five days. + wxText(hdc, "5-DAY FORECAST", rect{pad, u(304), W - pad, u(320)}, fSmall, colDim, line) + days := s.days[1:] + if len(days) > 5 { + days = days[:5] + } + cw := inner / 5 + for i, d := range days { + x := pad + int32(i)*cw + col := rect{x, 0, x + cw, 0} + wxText(hdc, d.date.Weekday().String()[:3], rect{col.Left, u(324), col.Right, u(342)}, fBold, colText, dtCenter|dtVCenter|dtSingleLine) + ic := u(32) + ix := x + (cw-ic)/2 + wxIcon(hdc, wxKind(d.code), rect{ix, u(344), ix + ic, u(344) + ic}, true) + wxText(hdc, wxDeg(d.hi), rect{col.Left, u(380), col.Right, u(400)}, fBold, colText, dtCenter|dtVCenter|dtSingleLine) + wxText(hdc, wxDeg(d.lo), rect{col.Left, u(400), col.Right, u(418)}, fText, colDim, dtCenter|dtVCenter|dtSingleLine) + } +} + +// ---------- pictures ---------- + +func wxCircle(hdc uintptr, cx, cy, rad float64, color uintptr) { + circleRaw(hdc, int32(math.Round(cx)), int32(math.Round(cy)), int32(math.Round(rad)), color) +} + +// wxCloud draws a cloud about 0.67 of s wide, centered on cx and cy. +func wxCloud(hdc uintptr, cx, cy, s float64, color uintptr) { + cy += 0.045 * s // the cloud's own middle sits a little above its circles + wxCircle(hdc, cx-0.20*s, cy+0.03*s, 0.14*s, color) + wxCircle(hdc, cx-0.02*s, cy-0.07*s, 0.19*s, color) + wxCircle(hdc, cx+0.20*s, cy+0.04*s, 0.13*s, color) + fillRaw(hdc, rect{ + int32(math.Round(cx - 0.20*s)), int32(math.Round(cy + 0.02*s)), + int32(math.Round(cx + 0.20*s)), int32(math.Round(cy + 0.17*s)), + }, color) +} + +func wxLine(hdc uintptr, x0, y0, x1, y1, width float64, color uintptr) { + polyline(hdc, []point{ + {int32(math.Round(x0)), int32(math.Round(y0))}, + {int32(math.Round(x1)), int32(math.Round(y1))}, + }, max(1, int32(math.Round(width))), color) +} + +func wxSunGlyph(hdc uintptr, cx, cy, s float64) { + col := rgb(255, 200, 60) + wxCircle(hdc, cx, cy, 0.2*s, col) + for k := 0; k < 8; k++ { + a := float64(k) * math.Pi / 4 + c, si := math.Cos(a), math.Sin(a) + wxLine(hdc, cx+c*0.30*s, cy+si*0.30*s, cx+c*0.43*s, cy+si*0.43*s, 0.05*s, col) + } +} + +func wxCrescent(hdc uintptr, cx, cy, rad float64) { + brush, _, _ := pCreateSolidBrush.Call(rgb(235, 232, 205)) + defer pDeleteObject.Call(brush) + ix, iy, ir := cx+0.45*rad, cy-0.25*rad, 0.85*rad // the circle that is cut out + top := int32(math.Round(cy)) + r := int32(math.Ceil(rad)) + for dy := -r; dy <= r; dy++ { + y := top + dy + oh2 := rad*rad - float64(dy)*float64(dy) + if oh2 <= 0 { + continue + } + oh := math.Sqrt(oh2) + x0, x1 := cx-oh, cx+oh + var segs [][2]float64 + fy := float64(y) + 0.5 - iy + if ih2 := ir*ir - fy*fy; ih2 > 0 { + ih := math.Sqrt(ih2) + if l := ix - ih; l > x0 { + segs = append(segs, [2]float64{x0, math.Min(l, x1)}) + } + if rr := ix + ih; rr < x1 { + segs = append(segs, [2]float64{math.Max(rr, x0), x1}) + } + } else { + segs = append(segs, [2]float64{x0, x1}) + } + for _, sg := range segs { + if sg[1]-sg[0] < 0.5 { + continue + } + line := rect{int32(math.Round(sg[0])), y, int32(math.Round(sg[1])), y + 1} + pFillRect.Call(hdc, uintptr(unsafe.Pointer(&line)), brush) + } + } +} + +// wxIcon draws the picture for a kind of weather inside the square r. +func wxIcon(hdc uintptr, kind int, r rect, day bool) { + s := float64(r.Right - r.Left) + cx := float64(r.Left+r.Right) / 2 + cy := float64(r.Top+r.Bottom) / 2 + light := rgb(205, 212, 225) + + switch kind { + case wxSun: + if day { + wxSunGlyph(hdc, cx, cy, s) + } else { + wxCrescent(hdc, cx, cy, 0.3*s) + } + case wxPartly: + if day { + wxSunGlyph(hdc, cx-0.14*s, cy-0.15*s, 0.8*s) + } else { + wxCrescent(hdc, cx-0.14*s, cy-0.15*s, 0.22*s) + } + wxCloud(hdc, cx+0.04*s, cy+0.08*s, 0.9*s, light) + case wxCloudy: + wxCloud(hdc, cx, cy, 1.1*s, light) + case wxFog: + fog := rgb(150, 158, 172) + wxCloud(hdc, cx, cy-0.1*s, s, fog) + for i, w := range []float64{0.26, 0.20, 0.26} { + y := cy + (0.16+0.10*float64(i))*s + wxLine(hdc, cx-w*s, y, cx+w*s, y, 0.04*s, fog) + } + case wxRain: + wxCloud(hdc, cx, cy-0.1*s, s, rgb(170, 180, 198)) + for _, dx := range []float64{-0.16, 0, 0.16} { + x := cx + dx*s + wxLine(hdc, x, cy+0.14*s, x-0.04*s, cy+0.32*s, 0.045*s, rgb(80, 165, 255)) + } + case wxSnow: + wxCloud(hdc, cx, cy-0.1*s, s, rgb(185, 195, 212)) + wxCircle(hdc, cx-0.15*s, cy+0.17*s, 0.035*s, colText) + wxCircle(hdc, cx, cy+0.29*s, 0.035*s, colText) + wxCircle(hdc, cx+0.15*s, cy+0.17*s, 0.035*s, colText) + case wxStorm: + wxCloud(hdc, cx, cy-0.12*s, s, rgb(115, 122, 140)) + pts := [][2]float64{{0.07, 0.02}, {-0.09, 0.24}, {0.01, 0.24}, {-0.07, 0.42}, {0.13, 0.16}, {0.03, 0.16}} + bolt := make([]point, len(pts)) + for i, p := range pts { + bolt[i] = point{int32(math.Round(cx + p[0]*s)), int32(math.Round(cy + p[1]*s))} + } + polygon(hdc, bolt, rgb(255, 205, 60)) + } +} + +// wxMoonDraw draws the moon with its lit part. A waxing moon is lit on the +// right and a waning one on the left; south of the equator that is the other +// way around. +func wxMoonDraw(hdc uintptr, cx, cy, r int32, m moonInfo, north bool) { + wxCircle(hdc, float64(cx), float64(cy), float64(r), rgb(58, 60, 74)) + + brush, _, _ := pCreateSolidBrush.Call(rgb(236, 232, 208)) + defer pDeleteObject.Call(brush) + + waxing := m.frac < 0.5 + theta := 2 * math.Pi * m.frac + if !waxing { + theta = 2 * math.Pi * (1 - m.frac) + } + ct := math.Cos(theta) + for dy := -r; dy <= r; dy++ { + hw := math.Sqrt(math.Max(0, float64(r)*float64(r)-float64(dy)*float64(dy))) + xt := hw * ct + x0, x1 := xt, hw + if !waxing { + x0, x1 = -hw, -xt + } + if !north { + x0, x1 = -x1, -x0 + } + if x1-x0 < 0.5 { + continue + } + line := rect{cx + int32(math.Round(x0)), cy + dy, cx + int32(math.Round(x1)), cy + dy + 1} + pFillRect.Call(hdc, uintptr(unsafe.Pointer(&line)), brush) + } +} diff --git a/gmflyout.go b/gmflyout.go new file mode 100644 index 0000000..03aba18 --- /dev/null +++ b/gmflyout.go @@ -0,0 +1,553 @@ +package main + +// The Google Messages flyout: a speech bubble on the bar that opens Messages for +// web (messages.google.com) in a small window above the bar, so you can read and +// answer texts without opening a browser tab. +// +// How it works: MirrorBar starts Microsoft Edge in "app" mode (no tabs, no address +// bar) with its own private profile folder, so the sign-in from pairing your phone +// is remembered and never touches your normal Edge. Edge is already on every +// Windows 11 PC, so there is nothing to install. The window is kept just off the +// edge of the screen while the flyout is closed; clicking the bubble slides it +// above the bar, clicking anywhere else slides it away again. Because the page +// keeps running, the unread number in its window title can be shown on the bubble. +// +// Messages for web only works while the phone is on and connected; that is how +// Google built it, not something MirrorBar can change. + +import ( + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + gmURL = "https://messages.google.com/web/conversations" + + gmW = 780.0 // flyout size, in 96 dpi units + gmH = 580.0 + + gmTimerID = 3 // on the main window: watches for clicks outside the flyout + gmParkX = -32000 + gmParkY = -32000 + gmAutoDelay = 20 * time.Second // wait this long after start before opening Messages in the background + gmLaunchMax = 45 * time.Second // give up looking for the window after this long + + gmSwpNoSize = 0x0001 + gmSwpNoMove = 0x0002 + gmSwpNoZOrder = 0x0004 + gmSwpFrameChanged = 0x0020 + gmSwShowNoActive = 4 + gmWsExAppWindow = 0x00040000 + gmGaRootOwner = 3 +) + +var ( + pIsWindow = user32.NewProc("IsWindow") + pWindowFromPoint = user32.NewProc("WindowFromPoint") + pGetAncestor = user32.NewProc("GetAncestor") + pSetWindowLongPtr = user32.NewProc("SetWindowLongPtrW") + pSetWindowPlace = user32.NewProc("SetWindowPlacement") +) + +var ( + gmHwnd uintptr + gmPid uint32 + gmShown bool + gmPrevBtn bool + gmPrevFg uintptr + gmShownAt time.Time + gmLaunching bool + gmLaunchedAt time.Time + gmWantOpen bool // the bubble was clicked while the window was still starting + gmAutoTried bool + gmUnread int + gmEnumCb uintptr + gmFound uintptr + gmLogged = map[string]bool{} + gmLoggedN int +) + +type gmPlacementT struct { + Length uint32 + Flags uint32 + ShowCmd uint32 + MinPos point + MaxPos point + Normal rect +} + +// ---------- the button on the bar ---------- + +func drawGMIcon(hdc uintptr, r rect) { + if !layerFg { + return + } + col := iconColor() + cx, cy := center(r) + e := px(1) + l, t, rt, b := cx-px(6.5), cy-px(5.5), cx+px(6.5), cy+px(3) + fillRaw(hdc, rect{l, t, rt, t + e}, col) + fillRaw(hdc, rect{l, b - e, rt, b}, col) + fillRaw(hdc, rect{l, t, l + e, b}, col) + fillRaw(hdc, rect{rt - e, t, rt, b}, col) + // the little tail at the bottom left + polyline(hdc, []point{{cx - px(3.5), b}, {cx - px(3.5), cy + px(6)}, {cx - px(0.5), b}}, e, col) + // two lines of "text" in the bubble + fillRaw(hdc, rect{cx - px(4), cy - px(3), cx + px(4), cy - px(3) + e}, col) + fillRaw(hdc, rect{cx - px(4), cy - px(0.5), cx + px(1.5), cy - px(0.5) + e}, col) + + if gmUnread > 0 { + br, bg, bb := styleColor(235, 70, 70) + bx, by, rad := cx+px(6.5), cy-px(5.5), px(5) + circleRaw(hdc, bx, by, rad, rgb(br, bg, bb)) + txt := strconv.Itoa(gmUnread) + if gmUnread > 9 { + txt = "9+" + } + f := makeFont(px(8), 700) + old, _, _ := pSelectObject.Call(hdc, f) + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(255, 255, 255)) + drawText(hdc, txt, rect{bx - rad, by - rad, bx + rad + 1, by + rad + 1}) + pSelectObject.Call(hdc, old) + pDeleteObject.Call(f) + } +} + +// ---------- finding and starting the browser window ---------- + +func gmProfileDir() string { return filepath.Join(dataDir(), "messages") } + +func gmProfileExists() bool { + _, err := os.Stat(filepath.Join(gmProfileDir(), "Local State")) + return err == nil +} + +// gmBrowserPath is Edge (always there on Windows 11), or Chrome if Edge is gone. +func gmBrowserPath() string { + type cand struct{ env, vendor, app, exe string } + for _, c := range []cand{ + {"ProgramFiles(x86)", "Microsoft", "Edge", "msedge.exe"}, + {"ProgramFiles", "Microsoft", "Edge", "msedge.exe"}, + {"LOCALAPPDATA", "Microsoft", "Edge", "msedge.exe"}, + {"ProgramFiles", "Google", "Chrome", "chrome.exe"}, + {"ProgramFiles(x86)", "Google", "Chrome", "chrome.exe"}, + {"LOCALAPPDATA", "Google", "Chrome", "chrome.exe"}, + } { + base := os.Getenv(c.env) + if base == "" { + continue + } + p := filepath.Join(base, c.vendor, c.app, "Application", c.exe) + if _, err := os.Stat(p); err == nil { + return p + } + } + return "" +} + +// gmLaunch starts the app window. Started in the background it opens minimized +// and is never given focus, so it does not interrupt whatever is being typed. +func gmLaunch(visible bool) bool { + exe := gmBrowserPath() + if exe == "" { + return false + } + prof := gmProfileDir() + if err := os.MkdirAll(prof, 0o755); err != nil { + return false + } + args := []string{ + exe, + "--app=" + gmURL, + "--user-data-dir=" + prof, + "--no-first-run", + "--no-default-browser-check", + // keep the page awake while its window is parked off the screen + "--disable-features=CalculateNativeWinOcclusion", + "--disable-renderer-backgrounding", + "--disable-background-timer-throttling", + "--disable-backgrounding-occluded-windows", + } + parts := make([]string, len(args)) + for i, a := range args { + parts[i] = syscall.EscapeArg(a) + } + si := syscall.StartupInfo{Flags: 1} // STARTF_USESHOWWINDOW + si.Cb = uint32(unsafe.Sizeof(si)) + si.ShowWindow = 7 // SW_SHOWMINNOACTIVE + if visible { + si.ShowWindow = 1 // SW_SHOWNORMAL + } + var pi syscall.ProcessInformation + err := syscall.CreateProcess(u16(exe), u16(strings.Join(parts, " ")), nil, nil, false, 0, nil, nil, &si, &pi) + if err != nil { + return false + } + gmPid = pi.ProcessId + syscall.CloseHandle(pi.Process) + syscall.CloseHandle(pi.Thread) + gmLaunching = true + gmLaunchedAt = time.Now() + gmWantOpen = visible + return true +} + +func gmWindowTitle(hwnd uintptr) string { + var tb [512]uint16 + n, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) + return syscall.UTF16ToString(tb[:n]) +} + +// gmTitleMatch is true for the app window's title ("Messages for web", maybe +// with a count in front) and false for ordinary browser windows. +func gmTitleMatch(t string) bool { + l := strings.ToLower(t) + if strings.Contains(l, "microsoft edge") || strings.Contains(l, "google chrome") { + return false + } + return strings.Contains(l, "messages") +} + +func gmEnumProc(hwnd, lparam uintptr) uintptr { + var cls [64]uint16 + n, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 64) + if syscall.UTF16ToString(cls[:n]) != "Chrome_WidgetWin_1" { + return 1 + } + if !gmTitleMatch(gmWindowTitle(hwnd)) { + return 1 + } + var pid uint32 + pGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) + if gmPid != 0 && pid == gmPid { + gmFound = hwnd + return 0 // exactly the window we started + } + if gmFound == 0 { + gmFound = hwnd + } + return 1 +} + +func gmFindWindow() uintptr { + if gmEnumCb == 0 { + gmEnumCb = syscall.NewCallback(gmEnumProc) + } + gmFound = 0 + pEnumWindows.Call(gmEnumCb, 0) + return gmFound +} + +func gmWindowOK() bool { + if gmHwnd == 0 { + return false + } + ok, _, _ := pIsWindow.Call(gmHwnd) + return ok != 0 +} + +// gmAdopt takes charge of the window once it exists: it stays out of the app +// list and Alt+Tab, and sits off screen until the bubble is clicked. +func gmAdopt(h uintptr) { + gmHwnd = h + var pid uint32 + pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) + if pid != 0 { + gmPid = pid + } + ex, _, _ := pGetWindowLongPtr.Call(h, neg(-20)) + want := (ex | wsExToolWindow) &^ gmWsExAppWindow + if want != ex { + pSetWindowLongPtr.Call(h, neg(-20), want) + pSetWindowPos.Call(h, 0, 0, 0, 0, 0, gmSwpNoMove|gmSwpNoSize|gmSwpNoZOrder|swpNoActivate|gmSwpFrameChanged) + } + gmLaunching = false + if gmWantOpen { + gmWantOpen = false + gmShow() + } else { + gmPark() + } +} + +// ---------- moving the window ---------- + +func gmSize() (int32, int32) { + sw, sh := screenSize() + cw := min(px(gmW), sw-px(16)) + ch := min(px(gmH), sh-px(24)) + return cw, ch +} + +// gmMove puts the window at x, y, w, h. A minimized window is first brought back +// to that spot without taking focus. +func gmMove(x, y, w, h int32, topmost, activate bool) { + if !gmWindowOK() { + return + } + if z, _, _ := pIsZoomed.Call(gmHwnd); z != 0 { + pShowWindow.Call(gmHwnd, swRestore) + } + if ic, _, _ := pIsIconic.Call(gmHwnd); ic != 0 { + cmd := uint32(gmSwShowNoActive) + if activate { + cmd = swRestore + } + wp := gmPlacementT{ShowCmd: cmd, Normal: rect{x, y, x + w, y + h}} + wp.Length = uint32(unsafe.Sizeof(wp)) + pSetWindowPlace.Call(gmHwnd, uintptr(unsafe.Pointer(&wp))) + } + after := ^uintptr(1) // HWND_NOTOPMOST + if topmost { + after = hwndTopmost + } + var flags uintptr + if !activate { + flags = swpNoActivate + } + pSetWindowPos.Call(gmHwnd, after, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags|swpShowWindow) +} + +func gmPark() { + cw, ch := gmSize() + gmMove(gmParkX, gmParkY, cw, ch, false, false) +} + +// gmPlace is where the flyout goes: above a horizontal bar, to the left of a +// vertical one, centered on the bubble and always on the screen. +func gmPlace() (x, y, w, h int32) { + cw, ch := gmSize() + ar := trayAnchor(trayGM) + var wr rect + pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr))) + sw, sh := screenSize() + space := px(8) + if vertical { + x = wr.Left - cw - space + if x < 0 { + x = wr.Right + space + } + y = (ar.Top+ar.Bottom)/2 - ch/2 + } else { + x = (ar.Left+ar.Right)/2 - cw/2 + y = wr.Top - ch - space + if y < 0 { + y = wr.Bottom + space + } + } + return clampI(x, 0, sw-cw), clampI(y, 0, sh-ch), cw, ch +} + +func gmFocus() { + // This program just received the click, so Windows lets it hand the focus on. + pSetForegroundWindow.Call(gmHwnd) +} + +// ---------- open, close, click ---------- + +func gmToggle() { + if !showGM { + return + } + if gmShown { + gmHide() + return + } + previewHide() + weatherHide() // one panel at a time + newsHide() + sysHide() + if gmWindowOK() { + gmShow() + return + } + gmHwnd = 0 + if gmLaunching { + gmWantOpen = true // it is still starting; open it the moment it exists + return + } + if !gmLaunch(true) { + shellOpen(gmURL, "") // no Edge or Chrome found: use the default browser + } +} + +func gmShow() { + if !gmWindowOK() { + return + } + fg, _, _ := pGetForegroundWindow.Call() + if fg != gmHwnd { + gmPrevFg = fg + } + gmShown = true + gmPrevBtn = true // ignore a button that is still held from the click that opened this + gmShownAt = time.Now() + x, y, w, h := gmPlace() + gmMove(x, y, w, h, true, true) + gmFocus() + pSetTimer.Call(hwndMain, gmTimerID, 80, 0) +} + +func gmHide() { + if !gmShown { + return + } + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + if !gmWindowOK() { + return + } + fg, _, _ := pGetForegroundWindow.Call() + gmPark() + if fg == gmHwnd && gmPrevFg != 0 && gmPrevFg != hwndMain && gmPrevFg != gmHwnd { + if ok, _, _ := pIsWindow.Call(gmPrevFg); ok != 0 { + pSetForegroundWindow.Call(gmPrevFg) // give the keyboard back to what you were doing + } + } +} + +// gmClose shuts the Messages window down (right-click, "Close Messages"). +func gmClose() { + gmHide() + if gmWindowOK() { + pPostMessage.Call(gmHwnd, wmClose, 0, 0) + } + gmHwnd = 0 + gmLaunching = false + gmWantOpen = false + gmAutoTried = true // do not bring it back by itself + gmUnread = 0 +} + +func gmShutdown() { + pKillTimer.Call(hwndMain, gmTimerID) + if gmWindowOK() { + pPostMessage.Call(gmHwnd, wmClose, 0, 0) + } + gmHwnd = 0 +} + +// gmPoll runs every 80 ms while the flyout is open and closes it when a mouse +// button goes down anywhere outside it (the bubble itself is left alone, so +// clicking it can close the flyout). +func gmPoll() { + if !gmShown { + return + } + if !gmWindowOK() { + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + return + } + l, _, _ := pGetAsyncKeyState.Call(vkLButton) + r, _, _ := pGetAsyncKeyState.Call(vkRButton) + down := (l|r)&0x8000 != 0 + if down && !gmPrevBtn && time.Since(gmShownAt) > 300*time.Millisecond { + var cp point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp))) + var fr rect + pGetWindowRect.Call(gmHwnd, uintptr(unsafe.Pointer(&fr))) + inside := inRect(fr, cp) + if !inside { + // a dialog or menu that belongs to the Messages window counts as inside + h, _, _ := pWindowFromPoint.Call(uintptr(uint32(cp.X)) | uintptr(uint32(cp.Y))<<32) + if h != 0 { + root, _, _ := pGetAncestor.Call(h, gmGaRootOwner) + inside = root == gmHwnd + } + } + if !inside && !inRect(trayAnchor(trayGM), cp) { + gmHide() + } + } + gmPrevBtn = down +} + +// ---------- the background check ---------- + +var gmCountRe = regexp.MustCompile(`[\(\[](\d{1,3})\+?[\)\]]`) + +func gmParseUnread(title string) int { + m := gmCountRe.FindStringSubmatch(title) + if m == nil { + return 0 + } + n, _ := strconv.Atoi(m[1]) + return n +} + +// gmLogTitle keeps the first few different window titles in titles.txt next to +// the Messages profile, so the unread badge can be tuned if Google words it +// differently than expected. It stops after 25 so it never grows. +func gmLogTitle(t string) { + if t == "" || gmLogged[t] || gmLoggedN >= 25 { + return + } + gmLogged[t] = true + gmLoggedN++ + f, err := os.OpenFile(filepath.Join(dataDir(), "messages-titles.txt"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + if len(t) > 80 { + t = t[:80] + } + _, _ = f.WriteString(time.Now().Format("2006-01-02 15:04:05") + "\t" + t + "\n") +} + +// gmTick runs from the bar's 250 ms timer. It starts Messages in the background +// once you have paired a phone, notices when the window goes away, and reads +// the unread count from the window title. Returns true when the bar needs a +// repaint. +func gmTick(tick int) (changed bool) { + defer func() { + if r := recover(); r != nil { + changed = false // optional feature; never take the bar down with it + } + }() + if !showGM { + return false + } + if gmHwnd != 0 && !gmWindowOK() { + gmHwnd = 0 + gmShown = false + pKillTimer.Call(hwndMain, gmTimerID) + changed = gmUnread != 0 + gmUnread = 0 + } + if gmHwnd == 0 { + switch { + case gmLaunching: + if h := gmFindWindow(); h != 0 { + gmAdopt(h) + } else if time.Since(gmLaunchedAt) > gmLaunchMax { + gmLaunching = false + gmWantOpen = false + } + case !gmAutoTried && time.Since(startedAt) > gmAutoDelay: + gmAutoTried = true + if h := gmFindWindow(); h != 0 { + gmAdopt(h) // left over from an earlier run of MirrorBar + } else if gmProfileExists() { + gmLaunch(false) + } + } + } + if gmHwnd != 0 && tick%8 == 0 { + t := gmWindowTitle(gmHwnd) + gmLogTitle(t) + if n := gmParseUnread(t); n != gmUnread { + gmUnread = n + changed = true + } + } + return changed +} diff --git a/main.go b/main.go index 8cf4bbe..863cd8d 100644 --- a/main.go +++ b/main.go @@ -1,1359 +1,1367 @@ -// MirrorBar proof of concept, version 3. -// -// Hides the real Windows taskbar and puts up a replacement bar laid out in -// mirror image around the exact center of the screen: -// -// left of center: Start button against the center line, open apps as small -// icons growing leftward from it (oldest window nearest Start) -// right of center: clock against the center line -// -// The bar is drawn as a per-pixel transparent window. Right click the bar to -// pick how see-through the background is (Clear, Light, Medium, Solid). -// -// Not built yet: battery, volume, wifi and the hidden icons arrow on the -// right side of the clock. -// -// Safety: -// - By default it closes itself after 10 minutes and restores the real taskbar. -// Pass --forever, or run it under a file name containing "forever", to turn that off. -// - Right click the bar, or press Ctrl+Alt+Q, to exit and restore. -// - Run restore_taskbar.exe (the same program under that name) or pass -// --restore to bring the real taskbar back if anything goes wrong. -package main - -import ( - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - "syscall" - "time" - "unsafe" -) - -func init() { runtime.LockOSThread() } - -// Extra Win32 calls used by the app right-click menu. -var ( - pIsZoomed = syscall.NewLazyDLL("user32.dll").NewProc("IsZoomed") - pGetWindowThreadProcessId = syscall.NewLazyDLL("user32.dll").NewProc("GetWindowThreadProcessId") - pOpenProcess = syscall.NewLazyDLL("kernel32.dll").NewProc("OpenProcess") - pCloseHandle = syscall.NewLazyDLL("kernel32.dll").NewProc("CloseHandle") - pQueryFullProcessImage = syscall.NewLazyDLL("kernel32.dll").NewProc("QueryFullProcessImageNameW") - pShellExecute = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW") -) - -const ( - wmSysCommand = 0x0112 - - scSize = 0xF000 - scMove = 0xF010 - scMinimize = 0xF020 - scMaximize = 0xF030 - scRestore = 0xF120 - - wsMaximizeBox = 0x00010000 - wsMinimizeBox = 0x00020000 - wsThickFrame = 0x00040000 - - mfGrayed = 0x0003 // MF_GRAYED | MF_DISABLED - - menuNewWindowID = 3 - menuFileLocID = 4 - menuRestoreID = 5 - menuMoveID = 6 - menuSizeID = 7 - menuMinimizeID = 8 - menuMaximizeID = 9 -) - -var ( - user32 = syscall.NewLazyDLL("user32.dll") - gdi32 = syscall.NewLazyDLL("gdi32.dll") - kernel32 = syscall.NewLazyDLL("kernel32.dll") - shell32 = syscall.NewLazyDLL("shell32.dll") - dwmapi = syscall.NewLazyDLL("dwmapi.dll") - - pRegisterClassEx = user32.NewProc("RegisterClassExW") - pCreateWindowEx = user32.NewProc("CreateWindowExW") - pDefWindowProc = user32.NewProc("DefWindowProcW") - pGetMessage = user32.NewProc("GetMessageW") - pTranslateMessage = user32.NewProc("TranslateMessage") - pDispatchMessage = user32.NewProc("DispatchMessageW") - pPostQuitMessage = user32.NewProc("PostQuitMessage") - pDestroyWindow = user32.NewProc("DestroyWindow") - pShowWindow = user32.NewProc("ShowWindow") - pFindWindow = user32.NewProc("FindWindowW") - pIsWindowVisible = user32.NewProc("IsWindowVisible") - pIsIconic = user32.NewProc("IsIconic") - pSetTimer = user32.NewProc("SetTimer") - pKillTimer = user32.NewProc("KillTimer") - pBeginPaint = user32.NewProc("BeginPaint") - pEndPaint = user32.NewProc("EndPaint") - pGetClientRect = user32.NewProc("GetClientRect") - pGetWindowRect = user32.NewProc("GetWindowRect") - pUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow") - pFillRect = user32.NewProc("FillRect") - pDrawText = user32.NewProc("DrawTextW") - pDrawIconEx = user32.NewProc("DrawIconEx") - pGetSystemMetrics = user32.NewProc("GetSystemMetrics") - pMoveWindow = user32.NewProc("MoveWindow") - pRegisterWindowMessage = user32.NewProc("RegisterWindowMessageW") - pRegisterHotKey = user32.NewProc("RegisterHotKey") - pUnregisterHotKey = user32.NewProc("UnregisterHotKey") - pKeybdEvent = user32.NewProc("keybd_event") - pLoadCursor = user32.NewProc("LoadCursorW") - pTrackMouseEvent = user32.NewProc("TrackMouseEvent") - pGetCursorPos = user32.NewProc("GetCursorPos") - pCreatePopupMenu = user32.NewProc("CreatePopupMenu") - pAppendMenu = user32.NewProc("AppendMenuW") - pTrackPopupMenu = user32.NewProc("TrackPopupMenu") - pDestroyMenu = user32.NewProc("DestroyMenu") - pSetForegroundWindow = user32.NewProc("SetForegroundWindow") - pGetForegroundWindow = user32.NewProc("GetForegroundWindow") - pSetProcessDPIAware = user32.NewProc("SetProcessDPIAware") - pGetDC = user32.NewProc("GetDC") - pReleaseDC = user32.NewProc("ReleaseDC") - pEnumWindows = user32.NewProc("EnumWindows") - pGetWindow = user32.NewProc("GetWindow") - pGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW") - pGetWindowTextLength = user32.NewProc("GetWindowTextLengthW") - pGetWindowText = user32.NewProc("GetWindowTextW") - pGetClassName = user32.NewProc("GetClassNameW") - pGetClassLongPtr = user32.NewProc("GetClassLongPtrW") - pSendMessageTimeout = user32.NewProc("SendMessageTimeoutW") - pPostMessage = user32.NewProc("PostMessageW") - pCreateSolidBrush = gdi32.NewProc("CreateSolidBrush") - pDeleteObject = gdi32.NewProc("DeleteObject") - pCreateFont = gdi32.NewProc("CreateFontW") - pSelectObject = gdi32.NewProc("SelectObject") - pSetBkMode = gdi32.NewProc("SetBkMode") - pSetTextColor = gdi32.NewProc("SetTextColor") - pCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC") - pCreateDIBSection = gdi32.NewProc("CreateDIBSection") - pGdiFlush = gdi32.NewProc("GdiFlush") - pDeleteDC = gdi32.NewProc("DeleteDC") - pGetDeviceCaps = gdi32.NewProc("GetDeviceCaps") - pGetModuleHandle = kernel32.NewProc("GetModuleHandleW") - pCreateMutex = kernel32.NewProc("CreateMutexW") - pSHAppBarMessage = shell32.NewProc("SHAppBarMessage") - pDwmGetWindowAttribute = dwmapi.NewProc("DwmGetWindowAttribute") -) - -const ( - wmDestroy = 0x0002 - wmClose = 0x0010 - wmPaint = 0x000F - wmSettingChange = 0x001A - wmEraseBkgnd = 0x0014 - wmEndSession = 0x0016 - wmGetIcon = 0x007F - wmDisplayChange = 0x007E - wmTimer = 0x0113 - wmMouseMove = 0x0200 - wmLButtonUp = 0x0202 - wmRButtonUp = 0x0205 - wmMouseLeave = 0x02A3 - wmHotkey = 0x0312 - wmUser = 0x0400 - - wsPopup = 0x80000000 - wsVisible = 0x10000000 - wsExToolWindow = 0x00000080 - wsExTopmost = 0x00000008 - wsExLayered = 0x00080000 - wsExNoActivate = 0x08000000 - wsExAppWindow = 0x00040000 - - swHide = 0 - swMinimize = 6 - swShowNA = 8 - swRestore = 9 - - abmNew = 0 - abmRemove = 1 - abmQueryPos = 2 - abmSetPos = 3 - abmGetState = 4 - abmSetState = 10 - abeBottom = 3 - abnPosChanged = 1 - absAutoHide = 1 - absAlwaysOnTop = 2 - - modAlt = 0x0001 - modControl = 0x0002 - vkLWin = 0x5B - keyUp = 0x0002 - - tmeLeave = 0x00000002 - - tpmRightButton = 0x0002 - tpmBottomAlign = 0x0020 - tpmReturnCmd = 0x0100 - mfChecked = 0x0008 - mfSeparator = 0x0800 - - dtLeft = 0x0000 - dtCenter = 0x0001 - dtVCenter = 0x0004 - dtSingleLine = 0x0020 - dtNoPrefix = 0x0800 - - transparent = 1 - logPixelsX = 88 - smCxScreen = 0 - smCyScreen = 1 - idcArrow = 32512 - diNormal = 0x0003 - gwOwner = 4 - dwmaCloaked = 14 - smtoAbort = 0x0002 - ulwAlpha = 0x0002 - - errorAlreadyExists = 183 - - timerID = 1 - hotkeyID = 1 - menuExitID = 1 - menuCloseID = 2 - menuLevelBase = 11 - autoQuitDef = 10 * time.Minute - - // Colors as they sit in the bitmap (0xRRGGBB). The draw code uses these - // exact colors so the alpha pass can tell background from foreground. - colBg = 22<<16 | 22<<8 | 26 - colHStart = 58<<16 | 58<<8 | 68 - colHApp = 40<<16 | 40<<8 | 48 - colActive = 52<<16 | 52<<8 | 62 -) - -type rect struct{ Left, Top, Right, Bottom int32 } -type point struct{ X, Y int32 } -type size struct{ CX, CY int32 } - -type blendFunction struct { - Op, Flags, Alpha, Format byte -} - -type bitmapInfoHeader struct { - Size uint32 - Width int32 - Height int32 - Planes uint16 - BitCount uint16 - Compression uint32 - SizeImage uint32 - XPelsPerMeter int32 - YPelsPerMeter int32 - ClrUsed uint32 - ClrImportant uint32 -} - -type wndClassEx struct { - Size uint32 - Style uint32 - WndProc uintptr - ClsExtra int32 - WndExtra int32 - Instance uintptr - Icon uintptr - Cursor uintptr - Background uintptr - MenuName *uint16 - ClassName *uint16 - IconSm uintptr -} - -type msg struct { - Hwnd uintptr - Message uint32 - WParam uintptr - LParam uintptr - Time uint32 - Pt point -} - -type paintStruct struct { - Hdc uintptr - Erase int32 - Rc rect - Restore int32 - IncUpdate int32 - Reserved [32]byte -} - -type appBarData struct { - Size uint32 - Hwnd uintptr - CallbackMsg uint32 - Edge uint32 - Rc rect - LParam uintptr -} - -type trackMouseEvent struct { - Size uint32 - Flags uint32 - HwndTrack uintptr - HoverTime uint32 -} - -// appWin is one open window shown as an icon button on the left side of the bar. -type appWin struct { - hwnd uintptr // 0 for a pinned program that has no window open right now - title string - icon uintptr - exe string // full path of the program, "" when unknown -} - -type alphaLevel struct { - name string - alpha int -} - -var alphaLevels = []alphaLevel{ - {"Clear", 3}, - {"Light", 70}, - {"Medium", 140}, - {"Solid", 255}, -} - -var ( - hwndMain uintptr - callbackMsg uint32 = wmUser + 1 - taskbarCreated uint32 - hoverStart bool - hoverApp = -1 - trackingMouse bool - scale float64 = 1 - barHeight int32 - fontTime uintptr - fontDate uintptr - fontApp uintptr - startedAt time.Time - autoQuit time.Duration - tick int - restored bool - bgAlpha = 70 - - apps []appWin - enumFound []appWin - enumCb uintptr - lastFgSeen uintptr -) - -func u16(s string) *uint16 { - p, _ := syscall.UTF16PtrFromString(s) - return p -} - -func rgb(r, g, b int) uintptr { return uintptr(r | g<<8 | b<<16) } - -func px(v float64) int32 { return int32(v*scale + 0.5) } - -// neg turns a small negative number into the form Win32 index arguments expect. -func neg(n int) uintptr { return uintptr(n) } - -func hasArg(name string) bool { - for _, a := range os.Args[1:] { - if strings.EqualFold(a, name) { - return true - } - } - return false -} - -func dataDir() string { - base := os.Getenv("LOCALAPPDATA") - if base == "" { - base = os.TempDir() - } - return filepath.Join(base, "MirrorBar") -} - -// ---------- settings ---------- - -func alphaFile() string { return filepath.Join(dataDir(), "alpha.txt") } - -func loadAlpha() { - b, err := os.ReadFile(alphaFile()) - if err != nil { - return - } - n, err := strconv.Atoi(strings.TrimSpace(string(b))) - if err != nil || n < 3 || n > 255 { - return - } - bgAlpha = n -} - -func saveAlpha() { - _ = os.MkdirAll(dataDir(), 0o755) - _ = os.WriteFile(alphaFile(), []byte(strconv.Itoa(bgAlpha)), 0o644) -} - -// ---------- real taskbar handling ---------- - -func findTaskbar() uintptr { - h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16("Shell_TrayWnd"))), 0) - return h -} - -func appBar(message uintptr, abd *appBarData) uintptr { - abd.Size = uint32(unsafe.Sizeof(*abd)) - r, _, _ := pSHAppBarMessage.Call(message, uintptr(unsafe.Pointer(abd))) - return r -} - -func stateFile() string { return filepath.Join(dataDir(), "state.txt") } - -func saveOriginalState(owner uintptr) { - f := stateFile() - if _, err := os.Stat(f); err == nil { - return // a state is already saved from an earlier run, keep the true original - } - abd := appBarData{Hwnd: owner} - st := appBar(abmGetState, &abd) - _ = os.MkdirAll(filepath.Dir(f), 0o755) - _ = os.WriteFile(f, []byte(strconv.Itoa(int(st))), 0o644) -} - -func loadOriginalState() uintptr { - b, err := os.ReadFile(stateFile()) - if err != nil { - return absAlwaysOnTop - } - n, err := strconv.Atoi(strings.TrimSpace(string(b))) - if err != nil { - return absAlwaysOnTop - } - return uintptr(n) -} - -func setTaskbarState(owner uintptr, state uintptr) { - abd := appBarData{Hwnd: owner, LParam: state} - appBar(abmSetState, &abd) -} - -func hideTaskbar() { - tb := findTaskbar() - if tb == 0 { - return - } - vis, _, _ := pIsWindowVisible.Call(tb) - if vis != 0 { - pShowWindow.Call(tb, swHide) - } -} - -// restoreAll brings the real taskbar back exactly as it was. -func restoreAll() { - tb := findTaskbar() - if tb != 0 { - setTaskbarState(tb, loadOriginalState()) - pShowWindow.Call(tb, swShowNA) - } - _ = os.Remove(stateFile()) - restored = true -} - -// ---------- open windows ---------- - -func collectWindow(hwnd uintptr) { - if hwnd == hwndMain { - return - } - vis, _, _ := pIsWindowVisible.Call(hwnd) - if vis == 0 { - return - } - owner, _, _ := pGetWindow.Call(hwnd, gwOwner) - if owner != 0 { - return - } - ex, _, _ := pGetWindowLongPtr.Call(hwnd, neg(-20)) - if ex&wsExToolWindow != 0 && ex&wsExAppWindow == 0 { - return - } - var cloaked uint32 - pDwmGetWindowAttribute.Call(hwnd, dwmaCloaked, uintptr(unsafe.Pointer(&cloaked)), 4) - if cloaked != 0 { - return - } - n, _, _ := pGetWindowTextLength.Call(hwnd) - if n == 0 { - return - } - var cls [128]uint16 - cn, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 128) - switch syscall.UTF16ToString(cls[:cn]) { - case "Progman", "Shell_TrayWnd", "Shell_SecondaryTrayWnd", "Windows.UI.Core.CoreWindow": - return - } - var tb [512]uint16 - tn, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) - enumFound = append(enumFound, appWin{hwnd: hwnd, title: syscall.UTF16ToString(tb[:tn])}) -} - -func fetchIcon(hwnd uintptr) uintptr { - var res uintptr - for _, which := range []uintptr{2, 0, 1} { - res = 0 - pSendMessageTimeout.Call(hwnd, wmGetIcon, which, 0, smtoAbort, 40, uintptr(unsafe.Pointer(&res))) - if res != 0 { - return res - } - } - for _, idx := range []int{-34, -14} { - r, _, _ := pGetClassLongPtr.Call(hwnd, neg(idx)) - if r != 0 { - return r - } - } - return 0 -} - -func activateApp(idx int) { - if idx < 0 || idx >= len(apps) { - return - } - h := apps[idx].hwnd - if h == 0 { - // A pinned program with no window: start it. - if apps[idx].exe != "" { - shellOpen(apps[idx].exe, "") - } - return - } - fg, _, _ := pGetForegroundWindow.Call() - iconic, _, _ := pIsIconic.Call(h) - switch { - case iconic != 0: - pShowWindow.Call(h, swRestore) - pSetForegroundWindow.Call(h) - case h == fg: - pShowWindow.Call(h, swMinimize) - default: - pSetForegroundWindow.Call(h) - } -} - -// ---------- our bar ---------- - -func startWidth() int32 { return px(52) } -func clockWidth() int32 { return px(140) } - -func screenSize() (int32, int32) { - w, _, _ := pGetSystemMetrics.Call(smCxScreen) - h, _, _ := pGetSystemMetrics.Call(smCyScreen) - return int32(w), int32(h) -} - -// pillWidth is the width the bar needs: the left half plus the right half. By -// default the left half is as long as the right one (a mirror image); pulling -// the far left end changes that (see barwidth.go). -func pillWidth() int32 { - return leftHalf() + rightHalf() -} - -// barGap is the space left under the pill so it stands off the screen edge. -func barGap() int32 { return px(6) } - -func positionBar(hwnd uintptr) { - pw, ph := pillSize() - if !customPos { - sw, sh := screenSize() - edge := uintptr(abeBottom) - if vertical { - edge = abeRight - } - abd := appBarData{Hwnd: hwnd, Edge: uint32(edge), Rc: rect{0, 0, sw, sh}} - appBar(abmQueryPos, &abd) - if vertical { - abd.Rc.Left = abd.Rc.Right - barHeight - barGap() - } else { - abd.Rc.Top = abd.Rc.Bottom - barHeight - barGap() - } - appBar(abmSetPos, &abd) - } - x, y := pillPos(pw, ph) - pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 1) - redraw(hwnd) -} - -// appRects lays the app buttons out leftward from the Start button. -// Button 0 sits against Start; each later one is further left. If there are -// too many to fit, the buttons shrink to a minimum width and the oldest run -// off the left edge. -func appRects(clientW, clientH int32) []rect { - if len(apps) == 0 { - return nil - } - row := rowLayout(clientW, clientH) - rects := make([]rect, len(apps)) - for i := range rects { - rects[i] = row[seqOfApp(i)] - } - return rects -} - -func clientSize(hwnd uintptr) (int32, int32) { - var rc rect - pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc))) - if vertical { - return rc.Bottom - rc.Top, rc.Right - rc.Left - } - return rc.Right - rc.Left, rc.Bottom - rc.Top -} - -func appIndexAt(hwnd uintptr, x int32) int { - w, h := clientSize(hwnd) - for i, r := range appRects(w, h) { - if x >= r.Left && x < r.Right { - return i - } - } - return -1 -} - -// The bar is painted in layers (see render.go): one layer holds only the -// backgrounds and hover fills, another only the icons, text and symbols. -var layerFills, layerFg = true, true - -// fill paints a background or hover rectangle (background layer only). -func fill(hdc uintptr, r rect, color uintptr) { - if layerFills { - fillRaw(hdc, r, color) - } -} - -// fillFg paints a solid piece of a symbol (foreground layer only). -func fillFg(hdc uintptr, r rect, color uintptr) { - if layerFg { - fillRaw(hdc, r, color) - } -} - -func fillRaw(hdc uintptr, r rect, color uintptr) { - { - b, _, _ := pCreateSolidBrush.Call(color) - pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b) - pDeleteObject.Call(b) - } -} - -func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) { - w := u16(s) - pDrawText.Call(hdc, uintptr(unsafe.Pointer(w)), ^uintptr(0), uintptr(unsafe.Pointer(&r)), format) -} - -func drawText(hdc uintptr, s string, r rect) { - drawTextFmt(hdc, s, r, dtCenter|dtVCenter|dtSingleLine|dtNoPrefix) -} - -// makeFont uses plain antialiasing (not ClearType) because ClearType's colored -// edges look wrong on a transparent window. -func makeFont(height int32, weight int) uintptr { - f, _, _ := pCreateFont.Call( - uintptr(-height), 0, 0, 0, uintptr(weight), 0, 0, 0, - 1, 0, 0, 4, 0, uintptr(unsafe.Pointer(u16("Segoe UI")))) - return f -} - -func drawLogo(hdc uintptr, r rect) { - sq := px(8) - gap := px(2) - total := sq*2 + gap - x := r.Left + (r.Right-r.Left-total)/2 - y := r.Top + (r.Bottom-r.Top-total)/2 - c := logoColor() - fillFg(hdc, rect{x, y, x + sq, y + sq}, c) - fillFg(hdc, rect{x + sq + gap, y, x + total, y + sq}, c) - fillFg(hdc, rect{x, y + sq + gap, x + sq, y + total}, c) - fillFg(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c) -} - -func drawClock(hdc uintptr, r rect) { - now := time.Now() - pSetBkMode.Call(hdc, transparent) - pSetTextColor.Call(hdc, clockColor()) - // Time and date on one line, like "11:32 PM 11/5/2026". - old, _, _ := pSelectObject.Call(hdc, fontTime) - drawText(hdc, now.Format("3:04 PM 1/2/2006"), r) - pSelectObject.Call(hdc, old) -} - -// drawApps draws each open window as a small icon only, no label. -func drawApps(hdc uintptr, w, h int32) { - rects := appRects(w, h) - if len(rects) == 0 { - return - } - pSetBkMode.Call(hdc, transparent) - pSetTextColor.Call(hdc, rgb(245, 245, 245)) - old, _, _ := pSelectObject.Call(hdc, fontApp) - - for i, r := range rects { - if i >= len(apps) { - break - } - a := apps[i] - inner := rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)} - if i == hoverApp { - fill(hdc, inner, rgb(40, 40, 48)) - } - - if !vertical && layerFg { - drawAppGlyph(hdc, inner, a) - } - } - pSelectObject.Call(hdc, old) -} - -// drawAppGlyph draws one app's small icon (or its first letter) centered in r. -func drawAppGlyph(hdc uintptr, r rect, a appWin) { - isz := px(16) // the small taskbar icon size - 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) - } else if rs := []rune(a.title); len(rs) > 0 { - pSetBkMode.Call(hdc, transparent) - pSetTextColor.Call(hdc, rgb(245, 245, 245)) - old, _, _ := pSelectObject.Call(hdc, fontApp) - drawText(hdc, strings.ToUpper(string(rs[0])), r) - pSelectObject.Call(hdc, old) - } -} - -func premul(c uint32, a uint32) uint32 { - r := (c >> 16 & 0xFF) * a / 255 - g := (c >> 8 & 0xFF) * a / 255 - b := (c & 0xFF) * a / 255 - return a<<24 | r<<16 | g<<8 | b -} - -func inStart(hwnd uintptr, x int32) bool { - w, h := clientSize(hwnd) - r := startRect(w, h) - return x >= r.Left && x < r.Right -} - -func tapWinKey() { - pKeybdEvent.Call(vkLWin, 0, 0, 0) - pKeybdEvent.Call(vkLWin, 0, keyUp, 0) -} - -// windowExePath returns the full path of the program that owns a window, or "" -// when it can't be found or the window belongs to the Windows app host -// (Settings, Store apps), which can't be launched again by path. -func windowExePath(h uintptr) string { - var pid uint32 - pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) - if pid == 0 { - return "" - } - proc, _, _ := pOpenProcess.Call(0x1000, 0, uintptr(pid)) // PROCESS_QUERY_LIMITED_INFORMATION - if proc == 0 { - return "" - } - defer pCloseHandle.Call(proc) - var buf [1024]uint16 - n := uint32(len(buf)) - r, _, _ := pQueryFullProcessImage.Call(proc, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n))) - if r == 0 { - return "" - } - path := syscall.UTF16ToString(buf[:n]) - if strings.EqualFold(filepath.Base(path), "ApplicationFrameHost.exe") { - return "" - } - return path -} - -func shellOpen(file, params string) { - var p uintptr - if params != "" { - p = uintptr(unsafe.Pointer(u16(params))) - } - pShellExecute.Call(0, uintptr(unsafe.Pointer(u16("open"))), uintptr(unsafe.Pointer(u16(file))), p, 0, 1) -} - -// showMenu pops up the right-click menu. Over an app icon it starts with that -// window's own options (the same ones its title bar menu has), then the -// MirrorBar settings. Over empty bar it shows only the settings. -func showMenu(hwnd uintptr, appIdx int, trayKind int) { - menu, _, _ := pCreatePopupMenu.Call() - add := func(flags uintptr, id uintptr, text string) { - pAppendMenu.Call(menu, flags, id, uintptr(unsafe.Pointer(u16(text)))) - } - sep := func() { pAppendMenu.Call(menu, mfSeparator, 0, 0) } - - // Remember which window this menu is for. The list can change while the - // menu is open, so don't go back to the index afterwards. - var target uintptr - var exe string - if appIdx >= 0 && appIdx < len(apps) { - target = apps[appIdx].hwnd - - title := []rune(apps[appIdx].title) - text := string(title) - if len(title) > 40 { - text = string(title[:40]) + "..." - } - add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&")) - sep() - - exe = apps[appIdx].exe - if target != 0 && exe == "" { - exe = windowExePath(target) - } - if target == 0 { - // A pinned program that isn't running: only launcher options apply. - add(0, menuLaunchID, "Open") - if exe != "" { - add(0, menuFileLocID, "Open file location") - } - sep() - add(0, menuUnpinID, "Unpin from MirrorBar") - sep() - } - if exe != "" && target != 0 { - add(0, menuNewWindowID, "Open new window") - add(0, menuFileLocID, "Open file location") - switch { - case isPinned(exe): - add(0, menuUnpinID, "Unpin from MirrorBar") - case canPin(exe): - add(0, menuPinID, "Pin to MirrorBar") - default: - add(mfGrayed, 0, "Pin to MirrorBar (Store apps can't be pinned)") - } - sep() - } - - if target != 0 { - style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE - iconic, _, _ := pIsIconic.Call(target) - zoomed, _, _ := pIsZoomed.Call(target) - normal := iconic == 0 && zoomed == 0 - enabled := func(ok bool) uintptr { - if ok { - return 0 - } - return mfGrayed - } - add(enabled(!normal), menuRestoreID, "Restore") - add(enabled(normal), menuMoveID, "Move") - add(enabled(normal && style&wsThickFrame != 0), menuSizeID, "Size") - add(enabled(iconic == 0 && style&wsMinimizeBox != 0), menuMinimizeID, "Minimize") - add(enabled(zoomed == 0 && style&wsMaximizeBox != 0), menuMaximizeID, "Maximize") - sep() - add(0, menuCloseID, "Close window") - sep() - } - } - - if appIdx < 0 { - addTrayMenu(add, sep, trayKind) - } - - add(0, menuSettingsID, "MirrorBar settings...") - add(0, menuNotifyID, "Open notification center") - sep() - for i, l := range alphaLevels { - var flags uintptr - if bgAlpha == l.alpha { - flags = mfChecked - } - add(flags, uintptr(menuLevelBase+i), "Background: "+l.name) - } - sep() - addColorMenus(menu) - sep() - orientText := "Switch to vertical" - if vertical { - orientText = "Switch to horizontal" - } - add(0, menuOrientID, orientText) - var posFlags uintptr - if !customPos { - posFlags = mfGrayed - } - add(posFlags, menuResetPosID, "Reset position to bottom center") - add(0, menuResetWidthID, "Reset bar width") - var autoFlags uintptr - if autostartEnabled() { - autoFlags = mfChecked - } - add(autoFlags, menuAutostartID, "Start MirrorBar when I sign in") - sep() - add(0, menuExitID, "Exit MirrorBar and restore taskbar") - - var pt point - pGetCursorPos.Call(uintptr(unsafe.Pointer(&pt))) - pSetForegroundWindow.Call(hwnd) - cmd, _, _ := pTrackPopupMenu.Call(menu, tpmRightButton|tpmBottomAlign|tpmReturnCmd, - uintptr(pt.X), uintptr(pt.Y), 0, hwnd, 0) - pDestroyMenu.Call(menu) - - sysCommands := map[uintptr]uintptr{ - menuRestoreID: scRestore, - menuMoveID: scMove, - menuSizeID: scSize, - menuMinimizeID: scMinimize, - menuMaximizeID: scMaximize, - } - - switch { - case cmd == menuExitID: - pDestroyWindow.Call(hwnd) - case cmd == menuResetPosID: - resetPos(hwnd) - case cmd == menuResetWidthID: - leftPref = 0 - saveLeftPref() - redraw(hwnd) - case handleColorCommand(cmd): - redraw(hwnd) - case cmd == menuOrientID: - vertical = !vertical - saveOrient() - resetPos(hwnd) - case cmd == menuCloseID && target != 0: - pPostMessage.Call(target, wmClose, 0, 0) - case cmd == menuNewWindowID && exe != "": - shellOpen(exe, "") - case cmd == menuLaunchID && exe != "": - shellOpen(exe, "") - case cmd == menuPinID && exe != "": - pinApp(exe) - refreshApps(false) - redraw(hwnd) - case cmd == menuUnpinID && exe != "": - unpinApp(exe) - refreshApps(false) - redraw(hwnd) - case cmd == menuSettingsID: - openSettings() - case cmd == menuNotifyID: - openNotifications() - case cmd == menuFileLocID && exe != "": - shellOpen("explorer.exe", `/select,"`+exe+`"`) - case target != 0 && sysCommands[cmd] != 0: - if cmd != menuMinimizeID { - pSetForegroundWindow.Call(target) - } - pPostMessage.Call(target, wmSysCommand, sysCommands[cmd], 0) - case handleTrayCommand(cmd): - redraw(hwnd) - case cmd >= menuLevelBase && cmd < menuLevelBase+uintptr(len(alphaLevels)): - bgAlpha = alphaLevels[cmd-menuLevelBase].alpha - saveAlpha() - redraw(hwnd) - } - settingsSync() -} - -func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { - defer func() { - if r := recover(); r != nil { - restoreAll() - os.Exit(1) - } - }() - - switch uint32(m) { - case wmEraseBkgnd: - return 1 - case wmPaint: - // The bar is a layered window drawn by redraw(); just mark this paint as handled. - var ps paintStruct - pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) - pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) - return 0 - case wmTimer: - if wparam == previewTimerID { - previewTick() - return 0 - } - hideTaskbar() - tick++ - changed := refreshApps(tick%16 == 0) - if tick%4 == 0 && refreshStatus(tick%16 == 0) { - changed = true - } - fg, _, _ := pGetForegroundWindow.Call() - if fg != lastFgSeen { - lastFgSeen = fg - changed = true - } - if changed || tick%4 == 0 { - redraw(hwnd) - } - if autoQuit > 0 && time.Since(startedAt) >= autoQuit { - pDestroyWindow.Call(hwnd) - } - return 0 - case wmLButtonDown: - previewSuppress() - x := alongClient(lparam) - if edgeZone(x) { - beginResize(hwnd) - return 0 - } - if inStart(hwnd, x) { - dragSeq, dragIsStart, dragStart, dragActive = slot(), true, x, false - pSetCapture.Call(hwnd) - } else if idx := appIndexAt(hwnd, x); idx >= 0 { - dragSeq, dragIsStart, dragStart, dragActive = seqOfApp(idx), false, x, false - pSetCapture.Call(hwnd) - } else if k := trayAt(hwnd, x); k != 0 { - dragTray, dragTrayStart, dragTrayActive = k, x, false - pSetCapture.Call(hwnd) - } - return 0 - case wmCaptureChanged: - resizing = false - endIconDrag() - dragTray, dragTrayActive = 0, false - return 0 - case wmMouseMove: - if resizing { - moveResize(hwnd) - return 0 - } - x := alongClient(lparam) - if dragSeq >= 0 && dragSeq <= len(apps) { - if !dragActive && abs32(x-dragStart) > px(5) { - dragActive = true - } - if dragActive { - if t := seqAt(hwnd, x); t >= 0 && t != dragSeq { - moveSeq(dragSeq, t) - dragSeq = t - } - hoverStart = dragIsStart - hoverApp = -1 - if !dragIsStart { - hoverApp = appOfSeq(dragSeq) - } - redraw(hwnd) - return 0 - } - } - if dragTray != 0 { - if !dragTrayActive && abs32(x-dragTrayStart) > px(5) { - dragTrayActive = true - } - if dragTrayActive { - if t := trayKindAt(hwnd, x); t != 0 && t != dragTray { - moveTray(dragTray, t) - } - hoverStart, hoverApp, hoverTray = false, -1, dragTray - redraw(hwnd) - return 0 - } - } - overStart := inStart(hwnd, x) - overApp := appIndexAt(hwnd, x) - overTray := trayAt(hwnd, x) - if overStart != hoverStart || overApp != hoverApp || overTray != hoverTray { - hoverStart = overStart - hoverApp = overApp - hoverTray = overTray - redraw(hwnd) - } - if overApp >= 0 { - previewKick() - } - if !trackingMouse { - tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd} - pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) - trackingMouse = true - } - return 0 - case wmMouseLeave: - trackingMouse = false - if hoverStart || hoverApp != -1 || hoverTray != 0 { - hoverStart = false - hoverApp = -1 - hoverTray = 0 - redraw(hwnd) - } - return 0 - case wmLButtonUp: - if resizing { - endResize(hwnd) - return 0 - } - x := alongClient(lparam) - if dragSeq >= 0 { - // A press on the Start button or an app icon: a click if it never moved, otherwise the drag ends here. - seq, wasStart, wasDrag := dragSeq, dragIsStart, dragActive - endIconDrag() - pReleaseCapture.Call() - if wasDrag { - saveStartSlot() - saveOrder() - } else if wasStart { - tapWinKey() - } else if idx := appOfSeq(seq); idx >= 0 && idx < len(apps) { - activateApp(idx) - } - redraw(hwnd) - } else if dragTray != 0 { - // A press on a tray item: a click if it never moved, otherwise the drag ends here. - k, wasDrag := dragTray, dragTrayActive - dragTray, dragTrayActive = 0, false - pReleaseCapture.Call() - if wasDrag { - saveTrayOrder() - } else { - trayClick(k) - } - redraw(hwnd) - } else if inStart(hwnd, x) { - tapWinKey() - } - return 0 - case wmRButtonUp: - x := alongClient(lparam) - previewBlock(true) - showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) - previewBlock(false) - return 0 - case wmDropFiles: - dropFiles(hwnd, wparam) - return 0 - case wmWxDone: - weatherDone() - return 0 - case wmMouseWheel: - // Scrolling over the volume icon changes the volume. The wheel - // position arrives in screen coordinates, so make it relative to the bar. - var wr rect - pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) - x := alongScreen(lparam, wr) - if trayAt(hwnd, x) == trayVolume { - nudgeVolume(int(int16(wparam>>16)) / 120) - redraw(hwnd) - } - return 0 - case wmNcHitTest: - // Buttons act as buttons; everything else on the pill drags it. - var wr rect - pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) - x := alongScreen(lparam, wr) - if edgeZone(x) || inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 { - return htClient - } - return htCaption - case wmSetCursor: - // The far end of the pill shows the resize arrow. - if resizing || (uint16(lparam&0xFFFF) == htClient && overEdge(hwnd)) { - pSetCursor.Call(sizeCursor()) - return 1 - } - case wmNcLButtonDblClk: - return 0 // a double click on the drag area must not maximize the pill - case wmNcRButtonUp: - var wr rect - pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) - x := alongScreen(lparam, wr) - previewBlock(true) - showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) - previewBlock(false) - return 0 - case wmEnterSizeMove: - dragging = true - return 0 - case wmExitSizeMove: - finishDrag(hwnd) - return 0 - case wmHotkey: - if wparam == hotkeyID { - pDestroyWindow.Call(hwnd) - } - return 0 - case wmDisplayChange, wmSettingChange: - positionBar(hwnd) - return 0 - case wmEndSession: - if wparam != 0 { - restoreAll() - } - return 0 - case wmDestroy: - previewShutdown() - weatherShutdown() - newsShutdown() - sysShutdown() - abd := appBarData{Hwnd: hwnd} - appBar(abmRemove, &abd) - pKillTimer.Call(hwnd, timerID) - pUnregisterHotKey.Call(hwnd, hotkeyID) - restoreAll() - pPostQuitMessage.Call(0) - return 0 - } - - if uint32(m) == callbackMsg { - if wparam == abnPosChanged { - positionBar(hwnd) - } - return 0 - } - if taskbarCreated != 0 && uint32(m) == taskbarCreated { - // Explorer restarted and rebuilt the taskbar: hide it again. - tb := findTaskbar() - if tb != 0 { - setTaskbarState(tb, absAutoHide|absAlwaysOnTop) - } - hideTaskbar() - positionBar(hwnd) - return 0 - } - - r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) - return r -} - -func main() { - // Launched under the name restore_taskbar.exe, or with --restore: just bring it back. - name := strings.ToLower(filepath.Base(os.Args[0])) - if hasArg("--restore") || strings.Contains(name, "restore") { - restoreAll() - return - } - - // Escape hatch: hold Shift while it starts (for example at sign-in) to skip it entirely. - if shiftHeld() { - return - } - - pSetProcessDPIAware.Call() - - // Only one copy at a time. - _, _, err := pCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(u16("Local\\MirrorBarPoC")))) - if errno, ok := err.(syscall.Errno); ok && errno == errorAlreadyExists { - return - } - - loadAlpha() - loadPos() - loadStartSlot() - loadTrayOrder() - loadOrient() - loadLeftPref() - loadPinned() - loadOrderKeys() - loadIconMode() - loadZip() - loadFeatures() - - hdc, _, _ := pGetDC.Call(0) - dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX) - pReleaseDC.Call(0, hdc) - if dpi > 0 { - scale = float64(dpi) / 96.0 - } - barHeight = px(36) - fontTime = makeFont(px(13), 400) - fontDate = makeFont(px(11), 400) - fontApp = makeFont(px(12), 600) - initSuperFonts() - loadColors() - - autoQuit = autoQuitDef - if hasArg("--forever") || strings.Contains(name, "forever") { - autoQuit = 0 - } - startedAt = time.Now() - - enumCb = syscall.NewCallback(func(hwnd, lparam uintptr) uintptr { - collectWindow(hwnd) - return 1 - }) - - inst, _, _ := pGetModuleHandle.Call(0) - cursor, _, _ := pLoadCursor.Call(0, idcArrow) - className := u16("MirrorBarWindow") - wc := wndClassEx{ - WndProc: syscall.NewCallback(wndProc), - Instance: inst, - Cursor: cursor, - ClassName: className, - } - wc.Size = uint32(unsafe.Sizeof(wc)) - pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) - - taskbarCreated64, _, _ := pRegisterWindowMessage.Call(uintptr(unsafe.Pointer(u16("TaskbarCreated")))) - taskbarCreated = uint32(taskbarCreated64) - - sw, sh := screenSize() - hwnd, _, _ := pCreateWindowEx.Call( - wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, - uintptr(unsafe.Pointer(className)), - uintptr(unsafe.Pointer(u16("MirrorBar"))), - wsPopup|wsVisible, - 0, uintptr(sh-barHeight), uintptr(sw), uintptr(barHeight), - 0, 0, inst, 0) - if hwnd == 0 { - return - } - hwndMain = hwnd - previewInit(inst) - weatherInit(inst) - newsInit(inst) - sysInit(inst) - enableFileDrop(hwnd) - refreshAutostartPath() - - // Hotkey: Ctrl+Alt+Q exits and restores. - pRegisterHotKey.Call(hwnd, hotkeyID, modControl|modAlt, 'Q') - - // Release the real taskbar's reserved screen space, remember how it was, hide it. - tb := waitForTaskbar(12 * time.Second) - if tb != 0 { - saveOriginalState(hwnd) - setTaskbarState(hwnd, absAutoHide|absAlwaysOnTop) - time.Sleep(300 * time.Millisecond) - hideTaskbar() - } - - // Register as an app bar so maximized windows stop above us. - if customPos { - appbarOn = false - } else { - abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg} - appBar(abmNew, &abd) - } - - pCoInitializeEx.Call(0, 2) // COINIT_APARTMENTTHREADED, needed for the volume control - refreshStatus(true) - refreshApps(true) - positionBar(hwnd) - pSetTimer.Call(hwnd, timerID, 250, 0) - weatherRefresh(false) // have the forecast ready before the cloud is first clicked - newsRefresh(false) - - var m msg - for { - r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0) - if int32(r) <= 0 { - break - } - if hwndSettings != 0 { - if handled, _, _ := pIsDialogMessage.Call(hwndSettings, uintptr(unsafe.Pointer(&m))); handled != 0 { - continue - } - } - pTranslateMessage.Call(uintptr(unsafe.Pointer(&m))) - pDispatchMessage.Call(uintptr(unsafe.Pointer(&m))) - } - if !restored { - restoreAll() - } -} +// MirrorBar proof of concept, version 3. +// +// Hides the real Windows taskbar and puts up a replacement bar laid out in +// mirror image around the exact center of the screen: +// +// left of center: Start button against the center line, open apps as small +// icons growing leftward from it (oldest window nearest Start) +// right of center: clock against the center line +// +// The bar is drawn as a per-pixel transparent window. Right click the bar to +// pick how see-through the background is (Clear, Light, Medium, Solid). +// +// Not built yet: battery, volume, wifi and the hidden icons arrow on the +// right side of the clock. +// +// Safety: +// - By default it closes itself after 10 minutes and restores the real taskbar. +// Pass --forever, or run it under a file name containing "forever", to turn that off. +// - Right click the bar, or press Ctrl+Alt+Q, to exit and restore. +// - Run restore_taskbar.exe (the same program under that name) or pass +// --restore to bring the real taskbar back if anything goes wrong. +package main + +import ( + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +func init() { runtime.LockOSThread() } + +// Extra Win32 calls used by the app right-click menu. +var ( + pIsZoomed = syscall.NewLazyDLL("user32.dll").NewProc("IsZoomed") + pGetWindowThreadProcessId = syscall.NewLazyDLL("user32.dll").NewProc("GetWindowThreadProcessId") + pOpenProcess = syscall.NewLazyDLL("kernel32.dll").NewProc("OpenProcess") + pCloseHandle = syscall.NewLazyDLL("kernel32.dll").NewProc("CloseHandle") + pQueryFullProcessImage = syscall.NewLazyDLL("kernel32.dll").NewProc("QueryFullProcessImageNameW") + pShellExecute = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW") +) + +const ( + wmSysCommand = 0x0112 + + scSize = 0xF000 + scMove = 0xF010 + scMinimize = 0xF020 + scMaximize = 0xF030 + scRestore = 0xF120 + + wsMaximizeBox = 0x00010000 + wsMinimizeBox = 0x00020000 + wsThickFrame = 0x00040000 + + mfGrayed = 0x0003 // MF_GRAYED | MF_DISABLED + + menuNewWindowID = 3 + menuFileLocID = 4 + menuRestoreID = 5 + menuMoveID = 6 + menuSizeID = 7 + menuMinimizeID = 8 + menuMaximizeID = 9 +) + +var ( + user32 = syscall.NewLazyDLL("user32.dll") + gdi32 = syscall.NewLazyDLL("gdi32.dll") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + shell32 = syscall.NewLazyDLL("shell32.dll") + dwmapi = syscall.NewLazyDLL("dwmapi.dll") + + pRegisterClassEx = user32.NewProc("RegisterClassExW") + pCreateWindowEx = user32.NewProc("CreateWindowExW") + pDefWindowProc = user32.NewProc("DefWindowProcW") + pGetMessage = user32.NewProc("GetMessageW") + pTranslateMessage = user32.NewProc("TranslateMessage") + pDispatchMessage = user32.NewProc("DispatchMessageW") + pPostQuitMessage = user32.NewProc("PostQuitMessage") + pDestroyWindow = user32.NewProc("DestroyWindow") + pShowWindow = user32.NewProc("ShowWindow") + pFindWindow = user32.NewProc("FindWindowW") + pIsWindowVisible = user32.NewProc("IsWindowVisible") + pIsIconic = user32.NewProc("IsIconic") + pSetTimer = user32.NewProc("SetTimer") + pKillTimer = user32.NewProc("KillTimer") + pBeginPaint = user32.NewProc("BeginPaint") + pEndPaint = user32.NewProc("EndPaint") + pGetClientRect = user32.NewProc("GetClientRect") + pGetWindowRect = user32.NewProc("GetWindowRect") + pUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow") + pFillRect = user32.NewProc("FillRect") + pDrawText = user32.NewProc("DrawTextW") + pDrawIconEx = user32.NewProc("DrawIconEx") + pGetSystemMetrics = user32.NewProc("GetSystemMetrics") + pMoveWindow = user32.NewProc("MoveWindow") + pRegisterWindowMessage = user32.NewProc("RegisterWindowMessageW") + pRegisterHotKey = user32.NewProc("RegisterHotKey") + pUnregisterHotKey = user32.NewProc("UnregisterHotKey") + pKeybdEvent = user32.NewProc("keybd_event") + pLoadCursor = user32.NewProc("LoadCursorW") + pTrackMouseEvent = user32.NewProc("TrackMouseEvent") + pGetCursorPos = user32.NewProc("GetCursorPos") + pCreatePopupMenu = user32.NewProc("CreatePopupMenu") + pAppendMenu = user32.NewProc("AppendMenuW") + pTrackPopupMenu = user32.NewProc("TrackPopupMenu") + pDestroyMenu = user32.NewProc("DestroyMenu") + pSetForegroundWindow = user32.NewProc("SetForegroundWindow") + pGetForegroundWindow = user32.NewProc("GetForegroundWindow") + pSetProcessDPIAware = user32.NewProc("SetProcessDPIAware") + pGetDC = user32.NewProc("GetDC") + pReleaseDC = user32.NewProc("ReleaseDC") + pEnumWindows = user32.NewProc("EnumWindows") + pGetWindow = user32.NewProc("GetWindow") + pGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW") + pGetWindowTextLength = user32.NewProc("GetWindowTextLengthW") + pGetWindowText = user32.NewProc("GetWindowTextW") + pGetClassName = user32.NewProc("GetClassNameW") + pGetClassLongPtr = user32.NewProc("GetClassLongPtrW") + pSendMessageTimeout = user32.NewProc("SendMessageTimeoutW") + pPostMessage = user32.NewProc("PostMessageW") + pCreateSolidBrush = gdi32.NewProc("CreateSolidBrush") + pDeleteObject = gdi32.NewProc("DeleteObject") + pCreateFont = gdi32.NewProc("CreateFontW") + pSelectObject = gdi32.NewProc("SelectObject") + pSetBkMode = gdi32.NewProc("SetBkMode") + pSetTextColor = gdi32.NewProc("SetTextColor") + pCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC") + pCreateDIBSection = gdi32.NewProc("CreateDIBSection") + pGdiFlush = gdi32.NewProc("GdiFlush") + pDeleteDC = gdi32.NewProc("DeleteDC") + pGetDeviceCaps = gdi32.NewProc("GetDeviceCaps") + pGetModuleHandle = kernel32.NewProc("GetModuleHandleW") + pCreateMutex = kernel32.NewProc("CreateMutexW") + pSHAppBarMessage = shell32.NewProc("SHAppBarMessage") + pDwmGetWindowAttribute = dwmapi.NewProc("DwmGetWindowAttribute") +) + +const ( + wmDestroy = 0x0002 + wmClose = 0x0010 + wmPaint = 0x000F + wmSettingChange = 0x001A + wmEraseBkgnd = 0x0014 + wmEndSession = 0x0016 + wmGetIcon = 0x007F + wmDisplayChange = 0x007E + wmTimer = 0x0113 + wmMouseMove = 0x0200 + wmLButtonUp = 0x0202 + wmRButtonUp = 0x0205 + wmMouseLeave = 0x02A3 + wmHotkey = 0x0312 + wmUser = 0x0400 + + wsPopup = 0x80000000 + wsVisible = 0x10000000 + wsExToolWindow = 0x00000080 + wsExTopmost = 0x00000008 + wsExLayered = 0x00080000 + wsExNoActivate = 0x08000000 + wsExAppWindow = 0x00040000 + + swHide = 0 + swMinimize = 6 + swShowNA = 8 + swRestore = 9 + + abmNew = 0 + abmRemove = 1 + abmQueryPos = 2 + abmSetPos = 3 + abmGetState = 4 + abmSetState = 10 + abeBottom = 3 + abnPosChanged = 1 + absAutoHide = 1 + absAlwaysOnTop = 2 + + modAlt = 0x0001 + modControl = 0x0002 + vkLWin = 0x5B + keyUp = 0x0002 + + tmeLeave = 0x00000002 + + tpmRightButton = 0x0002 + tpmBottomAlign = 0x0020 + tpmReturnCmd = 0x0100 + mfChecked = 0x0008 + mfSeparator = 0x0800 + + dtLeft = 0x0000 + dtCenter = 0x0001 + dtVCenter = 0x0004 + dtSingleLine = 0x0020 + dtNoPrefix = 0x0800 + + transparent = 1 + logPixelsX = 88 + smCxScreen = 0 + smCyScreen = 1 + idcArrow = 32512 + diNormal = 0x0003 + gwOwner = 4 + dwmaCloaked = 14 + smtoAbort = 0x0002 + ulwAlpha = 0x0002 + + errorAlreadyExists = 183 + + timerID = 1 + hotkeyID = 1 + menuExitID = 1 + menuCloseID = 2 + menuLevelBase = 11 + autoQuitDef = 10 * time.Minute + + // Colors as they sit in the bitmap (0xRRGGBB). The draw code uses these + // exact colors so the alpha pass can tell background from foreground. + colBg = 22<<16 | 22<<8 | 26 + colHStart = 58<<16 | 58<<8 | 68 + colHApp = 40<<16 | 40<<8 | 48 + colActive = 52<<16 | 52<<8 | 62 +) + +type rect struct{ Left, Top, Right, Bottom int32 } +type point struct{ X, Y int32 } +type size struct{ CX, CY int32 } + +type blendFunction struct { + Op, Flags, Alpha, Format byte +} + +type bitmapInfoHeader struct { + Size uint32 + Width int32 + Height int32 + Planes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter int32 + YPelsPerMeter int32 + ClrUsed uint32 + ClrImportant uint32 +} + +type wndClassEx struct { + Size uint32 + Style uint32 + WndProc uintptr + ClsExtra int32 + WndExtra int32 + Instance uintptr + Icon uintptr + Cursor uintptr + Background uintptr + MenuName *uint16 + ClassName *uint16 + IconSm uintptr +} + +type msg struct { + Hwnd uintptr + Message uint32 + WParam uintptr + LParam uintptr + Time uint32 + Pt point +} + +type paintStruct struct { + Hdc uintptr + Erase int32 + Rc rect + Restore int32 + IncUpdate int32 + Reserved [32]byte +} + +type appBarData struct { + Size uint32 + Hwnd uintptr + CallbackMsg uint32 + Edge uint32 + Rc rect + LParam uintptr +} + +type trackMouseEvent struct { + Size uint32 + Flags uint32 + HwndTrack uintptr + HoverTime uint32 +} + +// appWin is one open window shown as an icon button on the left side of the bar. +type appWin struct { + hwnd uintptr // 0 for a pinned program that has no window open right now + title string + icon uintptr + exe string // full path of the program, "" when unknown +} + +type alphaLevel struct { + name string + alpha int +} + +var alphaLevels = []alphaLevel{ + {"Clear", 3}, + {"Light", 70}, + {"Medium", 140}, + {"Solid", 255}, +} + +var ( + hwndMain uintptr + callbackMsg uint32 = wmUser + 1 + taskbarCreated uint32 + hoverStart bool + hoverApp = -1 + trackingMouse bool + scale float64 = 1 + barHeight int32 + fontTime uintptr + fontDate uintptr + fontApp uintptr + startedAt time.Time + autoQuit time.Duration + tick int + restored bool + bgAlpha = 70 + + apps []appWin + enumFound []appWin + enumCb uintptr + lastFgSeen uintptr +) + +func u16(s string) *uint16 { + p, _ := syscall.UTF16PtrFromString(s) + return p +} + +func rgb(r, g, b int) uintptr { return uintptr(r | g<<8 | b<<16) } + +func px(v float64) int32 { return int32(v*scale + 0.5) } + +// neg turns a small negative number into the form Win32 index arguments expect. +func neg(n int) uintptr { return uintptr(n) } + +func hasArg(name string) bool { + for _, a := range os.Args[1:] { + if strings.EqualFold(a, name) { + return true + } + } + return false +} + +func dataDir() string { + base := os.Getenv("LOCALAPPDATA") + if base == "" { + base = os.TempDir() + } + return filepath.Join(base, "MirrorBar") +} + +// ---------- settings ---------- + +func alphaFile() string { return filepath.Join(dataDir(), "alpha.txt") } + +func loadAlpha() { + b, err := os.ReadFile(alphaFile()) + if err != nil { + return + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || n < 3 || n > 255 { + return + } + bgAlpha = n +} + +func saveAlpha() { + _ = os.MkdirAll(dataDir(), 0o755) + _ = os.WriteFile(alphaFile(), []byte(strconv.Itoa(bgAlpha)), 0o644) +} + +// ---------- real taskbar handling ---------- + +func findTaskbar() uintptr { + h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16("Shell_TrayWnd"))), 0) + return h +} + +func appBar(message uintptr, abd *appBarData) uintptr { + abd.Size = uint32(unsafe.Sizeof(*abd)) + r, _, _ := pSHAppBarMessage.Call(message, uintptr(unsafe.Pointer(abd))) + return r +} + +func stateFile() string { return filepath.Join(dataDir(), "state.txt") } + +func saveOriginalState(owner uintptr) { + f := stateFile() + if _, err := os.Stat(f); err == nil { + return // a state is already saved from an earlier run, keep the true original + } + abd := appBarData{Hwnd: owner} + st := appBar(abmGetState, &abd) + _ = os.MkdirAll(filepath.Dir(f), 0o755) + _ = os.WriteFile(f, []byte(strconv.Itoa(int(st))), 0o644) +} + +func loadOriginalState() uintptr { + b, err := os.ReadFile(stateFile()) + if err != nil { + return absAlwaysOnTop + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil { + return absAlwaysOnTop + } + return uintptr(n) +} + +func setTaskbarState(owner uintptr, state uintptr) { + abd := appBarData{Hwnd: owner, LParam: state} + appBar(abmSetState, &abd) +} + +func hideTaskbar() { + tb := findTaskbar() + if tb == 0 { + return + } + vis, _, _ := pIsWindowVisible.Call(tb) + if vis != 0 { + pShowWindow.Call(tb, swHide) + } +} + +// restoreAll brings the real taskbar back exactly as it was. +func restoreAll() { + tb := findTaskbar() + if tb != 0 { + setTaskbarState(tb, loadOriginalState()) + pShowWindow.Call(tb, swShowNA) + } + _ = os.Remove(stateFile()) + restored = true +} + +// ---------- open windows ---------- + +func collectWindow(hwnd uintptr) { + if hwnd == hwndMain || (gmHwnd != 0 && hwnd == gmHwnd) { + return + } + vis, _, _ := pIsWindowVisible.Call(hwnd) + if vis == 0 { + return + } + owner, _, _ := pGetWindow.Call(hwnd, gwOwner) + if owner != 0 { + return + } + ex, _, _ := pGetWindowLongPtr.Call(hwnd, neg(-20)) + if ex&wsExToolWindow != 0 && ex&wsExAppWindow == 0 { + return + } + var cloaked uint32 + pDwmGetWindowAttribute.Call(hwnd, dwmaCloaked, uintptr(unsafe.Pointer(&cloaked)), 4) + if cloaked != 0 { + return + } + n, _, _ := pGetWindowTextLength.Call(hwnd) + if n == 0 { + return + } + var cls [128]uint16 + cn, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 128) + switch syscall.UTF16ToString(cls[:cn]) { + case "Progman", "Shell_TrayWnd", "Shell_SecondaryTrayWnd", "Windows.UI.Core.CoreWindow": + return + } + var tb [512]uint16 + tn, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512) + enumFound = append(enumFound, appWin{hwnd: hwnd, title: syscall.UTF16ToString(tb[:tn])}) +} + +func fetchIcon(hwnd uintptr) uintptr { + var res uintptr + for _, which := range []uintptr{2, 0, 1} { + res = 0 + pSendMessageTimeout.Call(hwnd, wmGetIcon, which, 0, smtoAbort, 40, uintptr(unsafe.Pointer(&res))) + if res != 0 { + return res + } + } + for _, idx := range []int{-34, -14} { + r, _, _ := pGetClassLongPtr.Call(hwnd, neg(idx)) + if r != 0 { + return r + } + } + return 0 +} + +func activateApp(idx int) { + if idx < 0 || idx >= len(apps) { + return + } + h := apps[idx].hwnd + if h == 0 { + // A pinned program with no window: start it. + if apps[idx].exe != "" { + shellOpen(apps[idx].exe, "") + } + return + } + fg, _, _ := pGetForegroundWindow.Call() + iconic, _, _ := pIsIconic.Call(h) + switch { + case iconic != 0: + pShowWindow.Call(h, swRestore) + pSetForegroundWindow.Call(h) + case h == fg: + pShowWindow.Call(h, swMinimize) + default: + pSetForegroundWindow.Call(h) + } +} + +// ---------- our bar ---------- + +func startWidth() int32 { return px(52) } +func clockWidth() int32 { return px(140) } + +func screenSize() (int32, int32) { + w, _, _ := pGetSystemMetrics.Call(smCxScreen) + h, _, _ := pGetSystemMetrics.Call(smCyScreen) + return int32(w), int32(h) +} + +// pillWidth is the width the bar needs: the left half plus the right half. By +// default the left half is as long as the right one (a mirror image); pulling +// the far left end changes that (see barwidth.go). +func pillWidth() int32 { + return leftHalf() + rightHalf() +} + +// barGap is the space left under the pill so it stands off the screen edge. +func barGap() int32 { return px(6) } + +func positionBar(hwnd uintptr) { + pw, ph := pillSize() + if !customPos { + sw, sh := screenSize() + edge := uintptr(abeBottom) + if vertical { + edge = abeRight + } + abd := appBarData{Hwnd: hwnd, Edge: uint32(edge), Rc: rect{0, 0, sw, sh}} + appBar(abmQueryPos, &abd) + if vertical { + abd.Rc.Left = abd.Rc.Right - barHeight - barGap() + } else { + abd.Rc.Top = abd.Rc.Bottom - barHeight - barGap() + } + appBar(abmSetPos, &abd) + } + x, y := pillPos(pw, ph) + pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 1) + redraw(hwnd) +} + +// appRects lays the app buttons out leftward from the Start button. +// Button 0 sits against Start; each later one is further left. If there are +// too many to fit, the buttons shrink to a minimum width and the oldest run +// off the left edge. +func appRects(clientW, clientH int32) []rect { + if len(apps) == 0 { + return nil + } + row := rowLayout(clientW, clientH) + rects := make([]rect, len(apps)) + for i := range rects { + rects[i] = row[seqOfApp(i)] + } + return rects +} + +func clientSize(hwnd uintptr) (int32, int32) { + var rc rect + pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc))) + if vertical { + return rc.Bottom - rc.Top, rc.Right - rc.Left + } + return rc.Right - rc.Left, rc.Bottom - rc.Top +} + +func appIndexAt(hwnd uintptr, x int32) int { + w, h := clientSize(hwnd) + for i, r := range appRects(w, h) { + if x >= r.Left && x < r.Right { + return i + } + } + return -1 +} + +// The bar is painted in layers (see render.go): one layer holds only the +// backgrounds and hover fills, another only the icons, text and symbols. +var layerFills, layerFg = true, true + +// fill paints a background or hover rectangle (background layer only). +func fill(hdc uintptr, r rect, color uintptr) { + if layerFills { + fillRaw(hdc, r, color) + } +} + +// fillFg paints a solid piece of a symbol (foreground layer only). +func fillFg(hdc uintptr, r rect, color uintptr) { + if layerFg { + fillRaw(hdc, r, color) + } +} + +func fillRaw(hdc uintptr, r rect, color uintptr) { + { + b, _, _ := pCreateSolidBrush.Call(color) + pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b) + pDeleteObject.Call(b) + } +} + +func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) { + w := u16(s) + pDrawText.Call(hdc, uintptr(unsafe.Pointer(w)), ^uintptr(0), uintptr(unsafe.Pointer(&r)), format) +} + +func drawText(hdc uintptr, s string, r rect) { + drawTextFmt(hdc, s, r, dtCenter|dtVCenter|dtSingleLine|dtNoPrefix) +} + +// makeFont uses plain antialiasing (not ClearType) because ClearType's colored +// edges look wrong on a transparent window. +func makeFont(height int32, weight int) uintptr { + f, _, _ := pCreateFont.Call( + uintptr(-height), 0, 0, 0, uintptr(weight), 0, 0, 0, + 1, 0, 0, 4, 0, uintptr(unsafe.Pointer(u16("Segoe UI")))) + return f +} + +func drawLogo(hdc uintptr, r rect) { + sq := px(8) + gap := px(2) + total := sq*2 + gap + x := r.Left + (r.Right-r.Left-total)/2 + y := r.Top + (r.Bottom-r.Top-total)/2 + c := logoColor() + fillFg(hdc, rect{x, y, x + sq, y + sq}, c) + fillFg(hdc, rect{x + sq + gap, y, x + total, y + sq}, c) + fillFg(hdc, rect{x, y + sq + gap, x + sq, y + total}, c) + fillFg(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c) +} + +func drawClock(hdc uintptr, r rect) { + now := time.Now() + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, clockColor()) + // Time and date on one line, like "11:32 PM 11/5/2026". + old, _, _ := pSelectObject.Call(hdc, fontTime) + drawText(hdc, now.Format("3:04 PM 1/2/2006"), r) + pSelectObject.Call(hdc, old) +} + +// drawApps draws each open window as a small icon only, no label. +func drawApps(hdc uintptr, w, h int32) { + rects := appRects(w, h) + if len(rects) == 0 { + return + } + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(245, 245, 245)) + old, _, _ := pSelectObject.Call(hdc, fontApp) + + for i, r := range rects { + if i >= len(apps) { + break + } + a := apps[i] + inner := rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)} + if i == hoverApp { + fill(hdc, inner, rgb(40, 40, 48)) + } + + if !vertical && layerFg { + drawAppGlyph(hdc, inner, a) + } + } + pSelectObject.Call(hdc, old) +} + +// drawAppGlyph draws one app's small icon (or its first letter) centered in r. +func drawAppGlyph(hdc uintptr, r rect, a appWin) { + isz := px(16) // the small taskbar icon size + 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) + } else if rs := []rune(a.title); len(rs) > 0 { + pSetBkMode.Call(hdc, transparent) + pSetTextColor.Call(hdc, rgb(245, 245, 245)) + old, _, _ := pSelectObject.Call(hdc, fontApp) + drawText(hdc, strings.ToUpper(string(rs[0])), r) + pSelectObject.Call(hdc, old) + } +} + +func premul(c uint32, a uint32) uint32 { + r := (c >> 16 & 0xFF) * a / 255 + g := (c >> 8 & 0xFF) * a / 255 + b := (c & 0xFF) * a / 255 + return a<<24 | r<<16 | g<<8 | b +} + +func inStart(hwnd uintptr, x int32) bool { + w, h := clientSize(hwnd) + r := startRect(w, h) + return x >= r.Left && x < r.Right +} + +func tapWinKey() { + pKeybdEvent.Call(vkLWin, 0, 0, 0) + pKeybdEvent.Call(vkLWin, 0, keyUp, 0) +} + +// windowExePath returns the full path of the program that owns a window, or "" +// when it can't be found or the window belongs to the Windows app host +// (Settings, Store apps), which can't be launched again by path. +func windowExePath(h uintptr) string { + var pid uint32 + pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid))) + if pid == 0 { + return "" + } + proc, _, _ := pOpenProcess.Call(0x1000, 0, uintptr(pid)) // PROCESS_QUERY_LIMITED_INFORMATION + if proc == 0 { + return "" + } + defer pCloseHandle.Call(proc) + var buf [1024]uint16 + n := uint32(len(buf)) + r, _, _ := pQueryFullProcessImage.Call(proc, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n))) + if r == 0 { + return "" + } + path := syscall.UTF16ToString(buf[:n]) + if strings.EqualFold(filepath.Base(path), "ApplicationFrameHost.exe") { + return "" + } + return path +} + +func shellOpen(file, params string) { + var p uintptr + if params != "" { + p = uintptr(unsafe.Pointer(u16(params))) + } + pShellExecute.Call(0, uintptr(unsafe.Pointer(u16("open"))), uintptr(unsafe.Pointer(u16(file))), p, 0, 1) +} + +// showMenu pops up the right-click menu. Over an app icon it starts with that +// window's own options (the same ones its title bar menu has), then the +// MirrorBar settings. Over empty bar it shows only the settings. +func showMenu(hwnd uintptr, appIdx int, trayKind int) { + menu, _, _ := pCreatePopupMenu.Call() + add := func(flags uintptr, id uintptr, text string) { + pAppendMenu.Call(menu, flags, id, uintptr(unsafe.Pointer(u16(text)))) + } + sep := func() { pAppendMenu.Call(menu, mfSeparator, 0, 0) } + + // Remember which window this menu is for. The list can change while the + // menu is open, so don't go back to the index afterwards. + var target uintptr + var exe string + if appIdx >= 0 && appIdx < len(apps) { + target = apps[appIdx].hwnd + + title := []rune(apps[appIdx].title) + text := string(title) + if len(title) > 40 { + text = string(title[:40]) + "..." + } + add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&")) + sep() + + exe = apps[appIdx].exe + if target != 0 && exe == "" { + exe = windowExePath(target) + } + if target == 0 { + // A pinned program that isn't running: only launcher options apply. + add(0, menuLaunchID, "Open") + if exe != "" { + add(0, menuFileLocID, "Open file location") + } + sep() + add(0, menuUnpinID, "Unpin from MirrorBar") + sep() + } + if exe != "" && target != 0 { + add(0, menuNewWindowID, "Open new window") + add(0, menuFileLocID, "Open file location") + switch { + case isPinned(exe): + add(0, menuUnpinID, "Unpin from MirrorBar") + case canPin(exe): + add(0, menuPinID, "Pin to MirrorBar") + default: + add(mfGrayed, 0, "Pin to MirrorBar (Store apps can't be pinned)") + } + sep() + } + + if target != 0 { + style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE + iconic, _, _ := pIsIconic.Call(target) + zoomed, _, _ := pIsZoomed.Call(target) + normal := iconic == 0 && zoomed == 0 + enabled := func(ok bool) uintptr { + if ok { + return 0 + } + return mfGrayed + } + add(enabled(!normal), menuRestoreID, "Restore") + add(enabled(normal), menuMoveID, "Move") + add(enabled(normal && style&wsThickFrame != 0), menuSizeID, "Size") + add(enabled(iconic == 0 && style&wsMinimizeBox != 0), menuMinimizeID, "Minimize") + add(enabled(zoomed == 0 && style&wsMaximizeBox != 0), menuMaximizeID, "Maximize") + sep() + add(0, menuCloseID, "Close window") + sep() + } + } + + if appIdx < 0 { + addTrayMenu(add, sep, trayKind) + } + + add(0, menuSettingsID, "MirrorBar settings...") + add(0, menuNotifyID, "Open notification center") + sep() + for i, l := range alphaLevels { + var flags uintptr + if bgAlpha == l.alpha { + flags = mfChecked + } + add(flags, uintptr(menuLevelBase+i), "Background: "+l.name) + } + sep() + addColorMenus(menu) + sep() + orientText := "Switch to vertical" + if vertical { + orientText = "Switch to horizontal" + } + add(0, menuOrientID, orientText) + var posFlags uintptr + if !customPos { + posFlags = mfGrayed + } + add(posFlags, menuResetPosID, "Reset position to bottom center") + add(0, menuResetWidthID, "Reset bar width") + var autoFlags uintptr + if autostartEnabled() { + autoFlags = mfChecked + } + add(autoFlags, menuAutostartID, "Start MirrorBar when I sign in") + sep() + add(0, menuExitID, "Exit MirrorBar and restore taskbar") + + var pt point + pGetCursorPos.Call(uintptr(unsafe.Pointer(&pt))) + pSetForegroundWindow.Call(hwnd) + cmd, _, _ := pTrackPopupMenu.Call(menu, tpmRightButton|tpmBottomAlign|tpmReturnCmd, + uintptr(pt.X), uintptr(pt.Y), 0, hwnd, 0) + pDestroyMenu.Call(menu) + + sysCommands := map[uintptr]uintptr{ + menuRestoreID: scRestore, + menuMoveID: scMove, + menuSizeID: scSize, + menuMinimizeID: scMinimize, + menuMaximizeID: scMaximize, + } + + switch { + case cmd == menuExitID: + pDestroyWindow.Call(hwnd) + case cmd == menuResetPosID: + resetPos(hwnd) + case cmd == menuResetWidthID: + leftPref = 0 + saveLeftPref() + redraw(hwnd) + case handleColorCommand(cmd): + redraw(hwnd) + case cmd == menuOrientID: + vertical = !vertical + saveOrient() + resetPos(hwnd) + case cmd == menuCloseID && target != 0: + pPostMessage.Call(target, wmClose, 0, 0) + case cmd == menuNewWindowID && exe != "": + shellOpen(exe, "") + case cmd == menuLaunchID && exe != "": + shellOpen(exe, "") + case cmd == menuPinID && exe != "": + pinApp(exe) + refreshApps(false) + redraw(hwnd) + case cmd == menuUnpinID && exe != "": + unpinApp(exe) + refreshApps(false) + redraw(hwnd) + case cmd == menuSettingsID: + openSettings() + case cmd == menuNotifyID: + openNotifications() + case cmd == menuFileLocID && exe != "": + shellOpen("explorer.exe", `/select,"`+exe+`"`) + case target != 0 && sysCommands[cmd] != 0: + if cmd != menuMinimizeID { + pSetForegroundWindow.Call(target) + } + pPostMessage.Call(target, wmSysCommand, sysCommands[cmd], 0) + case handleTrayCommand(cmd): + redraw(hwnd) + case cmd >= menuLevelBase && cmd < menuLevelBase+uintptr(len(alphaLevels)): + bgAlpha = alphaLevels[cmd-menuLevelBase].alpha + saveAlpha() + redraw(hwnd) + } + settingsSync() +} + +func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { + defer func() { + if r := recover(); r != nil { + restoreAll() + os.Exit(1) + } + }() + + switch uint32(m) { + case wmEraseBkgnd: + return 1 + case wmPaint: + // The bar is a layered window drawn by redraw(); just mark this paint as handled. + var ps paintStruct + pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + return 0 + case wmTimer: + if wparam == gmTimerID { + gmPoll() + return 0 + } + if wparam == previewTimerID { + previewTick() + return 0 + } + hideTaskbar() + tick++ + changed := refreshApps(tick%16 == 0) + if gmTick(tick) { + changed = true + } + if tick%4 == 0 && refreshStatus(tick%16 == 0) { + changed = true + } + fg, _, _ := pGetForegroundWindow.Call() + if fg != lastFgSeen { + lastFgSeen = fg + changed = true + } + if changed || tick%4 == 0 { + redraw(hwnd) + } + if autoQuit > 0 && time.Since(startedAt) >= autoQuit { + pDestroyWindow.Call(hwnd) + } + return 0 + case wmLButtonDown: + previewSuppress() + x := alongClient(lparam) + if edgeZone(x) { + beginResize(hwnd) + return 0 + } + if inStart(hwnd, x) { + dragSeq, dragIsStart, dragStart, dragActive = slot(), true, x, false + pSetCapture.Call(hwnd) + } else if idx := appIndexAt(hwnd, x); idx >= 0 { + dragSeq, dragIsStart, dragStart, dragActive = seqOfApp(idx), false, x, false + pSetCapture.Call(hwnd) + } else if k := trayAt(hwnd, x); k != 0 { + dragTray, dragTrayStart, dragTrayActive = k, x, false + pSetCapture.Call(hwnd) + } + return 0 + case wmCaptureChanged: + resizing = false + endIconDrag() + dragTray, dragTrayActive = 0, false + return 0 + case wmMouseMove: + if resizing { + moveResize(hwnd) + return 0 + } + x := alongClient(lparam) + if dragSeq >= 0 && dragSeq <= len(apps) { + if !dragActive && abs32(x-dragStart) > px(5) { + dragActive = true + } + if dragActive { + if t := seqAt(hwnd, x); t >= 0 && t != dragSeq { + moveSeq(dragSeq, t) + dragSeq = t + } + hoverStart = dragIsStart + hoverApp = -1 + if !dragIsStart { + hoverApp = appOfSeq(dragSeq) + } + redraw(hwnd) + return 0 + } + } + if dragTray != 0 { + if !dragTrayActive && abs32(x-dragTrayStart) > px(5) { + dragTrayActive = true + } + if dragTrayActive { + if t := trayKindAt(hwnd, x); t != 0 && t != dragTray { + moveTray(dragTray, t) + } + hoverStart, hoverApp, hoverTray = false, -1, dragTray + redraw(hwnd) + return 0 + } + } + overStart := inStart(hwnd, x) + overApp := appIndexAt(hwnd, x) + overTray := trayAt(hwnd, x) + if overStart != hoverStart || overApp != hoverApp || overTray != hoverTray { + hoverStart = overStart + hoverApp = overApp + hoverTray = overTray + redraw(hwnd) + } + if overApp >= 0 { + previewKick() + } + if !trackingMouse { + tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd} + pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) + trackingMouse = true + } + return 0 + case wmMouseLeave: + trackingMouse = false + if hoverStart || hoverApp != -1 || hoverTray != 0 { + hoverStart = false + hoverApp = -1 + hoverTray = 0 + redraw(hwnd) + } + return 0 + case wmLButtonUp: + if resizing { + endResize(hwnd) + return 0 + } + x := alongClient(lparam) + if dragSeq >= 0 { + // A press on the Start button or an app icon: a click if it never moved, otherwise the drag ends here. + seq, wasStart, wasDrag := dragSeq, dragIsStart, dragActive + endIconDrag() + pReleaseCapture.Call() + if wasDrag { + saveStartSlot() + saveOrder() + } else if wasStart { + tapWinKey() + } else if idx := appOfSeq(seq); idx >= 0 && idx < len(apps) { + activateApp(idx) + } + redraw(hwnd) + } else if dragTray != 0 { + // A press on a tray item: a click if it never moved, otherwise the drag ends here. + k, wasDrag := dragTray, dragTrayActive + dragTray, dragTrayActive = 0, false + pReleaseCapture.Call() + if wasDrag { + saveTrayOrder() + } else { + trayClick(k) + } + redraw(hwnd) + } else if inStart(hwnd, x) { + tapWinKey() + } + return 0 + case wmRButtonUp: + x := alongClient(lparam) + previewBlock(true) + showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) + previewBlock(false) + return 0 + case wmDropFiles: + dropFiles(hwnd, wparam) + return 0 + case wmWxDone: + weatherDone() + return 0 + case wmMouseWheel: + // Scrolling over the volume icon changes the volume. The wheel + // position arrives in screen coordinates, so make it relative to the bar. + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + if trayAt(hwnd, x) == trayVolume { + nudgeVolume(int(int16(wparam>>16)) / 120) + redraw(hwnd) + } + return 0 + case wmNcHitTest: + // Buttons act as buttons; everything else on the pill drags it. + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + if edgeZone(x) || inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 { + return htClient + } + return htCaption + case wmSetCursor: + // The far end of the pill shows the resize arrow. + if resizing || (uint16(lparam&0xFFFF) == htClient && overEdge(hwnd)) { + pSetCursor.Call(sizeCursor()) + return 1 + } + case wmNcLButtonDblClk: + return 0 // a double click on the drag area must not maximize the pill + case wmNcRButtonUp: + var wr rect + pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) + x := alongScreen(lparam, wr) + previewBlock(true) + showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) + previewBlock(false) + return 0 + case wmEnterSizeMove: + dragging = true + return 0 + case wmExitSizeMove: + finishDrag(hwnd) + return 0 + case wmHotkey: + if wparam == hotkeyID { + pDestroyWindow.Call(hwnd) + } + return 0 + case wmDisplayChange, wmSettingChange: + positionBar(hwnd) + return 0 + case wmEndSession: + if wparam != 0 { + restoreAll() + } + return 0 + case wmDestroy: + previewShutdown() + weatherShutdown() + newsShutdown() + sysShutdown() + gmShutdown() + abd := appBarData{Hwnd: hwnd} + appBar(abmRemove, &abd) + pKillTimer.Call(hwnd, timerID) + pUnregisterHotKey.Call(hwnd, hotkeyID) + restoreAll() + pPostQuitMessage.Call(0) + return 0 + } + + if uint32(m) == callbackMsg { + if wparam == abnPosChanged { + positionBar(hwnd) + } + return 0 + } + if taskbarCreated != 0 && uint32(m) == taskbarCreated { + // Explorer restarted and rebuilt the taskbar: hide it again. + tb := findTaskbar() + if tb != 0 { + setTaskbarState(tb, absAutoHide|absAlwaysOnTop) + } + hideTaskbar() + positionBar(hwnd) + return 0 + } + + r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam) + return r +} + +func main() { + // Launched under the name restore_taskbar.exe, or with --restore: just bring it back. + name := strings.ToLower(filepath.Base(os.Args[0])) + if hasArg("--restore") || strings.Contains(name, "restore") { + restoreAll() + return + } + + // Escape hatch: hold Shift while it starts (for example at sign-in) to skip it entirely. + if shiftHeld() { + return + } + + pSetProcessDPIAware.Call() + + // Only one copy at a time. + _, _, err := pCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(u16("Local\\MirrorBarPoC")))) + if errno, ok := err.(syscall.Errno); ok && errno == errorAlreadyExists { + return + } + + loadAlpha() + loadPos() + loadStartSlot() + loadTrayOrder() + loadOrient() + loadLeftPref() + loadPinned() + loadOrderKeys() + loadIconMode() + loadZip() + loadFeatures() + + hdc, _, _ := pGetDC.Call(0) + dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX) + pReleaseDC.Call(0, hdc) + if dpi > 0 { + scale = float64(dpi) / 96.0 + } + barHeight = px(36) + fontTime = makeFont(px(13), 400) + fontDate = makeFont(px(11), 400) + fontApp = makeFont(px(12), 600) + initSuperFonts() + loadColors() + + autoQuit = autoQuitDef + if hasArg("--forever") || strings.Contains(name, "forever") { + autoQuit = 0 + } + startedAt = time.Now() + + enumCb = syscall.NewCallback(func(hwnd, lparam uintptr) uintptr { + collectWindow(hwnd) + return 1 + }) + + inst, _, _ := pGetModuleHandle.Call(0) + cursor, _, _ := pLoadCursor.Call(0, idcArrow) + className := u16("MirrorBarWindow") + wc := wndClassEx{ + WndProc: syscall.NewCallback(wndProc), + Instance: inst, + Cursor: cursor, + ClassName: className, + } + wc.Size = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + + taskbarCreated64, _, _ := pRegisterWindowMessage.Call(uintptr(unsafe.Pointer(u16("TaskbarCreated")))) + taskbarCreated = uint32(taskbarCreated64) + + sw, sh := screenSize() + hwnd, _, _ := pCreateWindowEx.Call( + wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered, + uintptr(unsafe.Pointer(className)), + uintptr(unsafe.Pointer(u16("MirrorBar"))), + wsPopup|wsVisible, + 0, uintptr(sh-barHeight), uintptr(sw), uintptr(barHeight), + 0, 0, inst, 0) + if hwnd == 0 { + return + } + hwndMain = hwnd + previewInit(inst) + weatherInit(inst) + newsInit(inst) + sysInit(inst) + enableFileDrop(hwnd) + refreshAutostartPath() + + // Hotkey: Ctrl+Alt+Q exits and restores. + pRegisterHotKey.Call(hwnd, hotkeyID, modControl|modAlt, 'Q') + + // Release the real taskbar's reserved screen space, remember how it was, hide it. + tb := waitForTaskbar(12 * time.Second) + if tb != 0 { + saveOriginalState(hwnd) + setTaskbarState(hwnd, absAutoHide|absAlwaysOnTop) + time.Sleep(300 * time.Millisecond) + hideTaskbar() + } + + // Register as an app bar so maximized windows stop above us. + if customPos { + appbarOn = false + } else { + abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg} + appBar(abmNew, &abd) + } + + pCoInitializeEx.Call(0, 2) // COINIT_APARTMENTTHREADED, needed for the volume control + refreshStatus(true) + refreshApps(true) + positionBar(hwnd) + pSetTimer.Call(hwnd, timerID, 250, 0) + weatherRefresh(false) // have the forecast ready before the cloud is first clicked + newsRefresh(false) + + var m msg + for { + r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0) + if int32(r) <= 0 { + break + } + if hwndSettings != 0 { + if handled, _, _ := pIsDialogMessage.Call(hwndSettings, uintptr(unsafe.Pointer(&m))); handled != 0 { + continue + } + } + pTranslateMessage.Call(uintptr(unsafe.Pointer(&m))) + pDispatchMessage.Call(uintptr(unsafe.Pointer(&m))) + } + if !restored { + restoreAll() + } +} diff --git a/newsflyout.go b/newsflyout.go index 3dc8db9..091b811 100644 --- a/newsflyout.go +++ b/newsflyout.go @@ -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) +}