21 Commits
Author SHA1 Message Date
weishaupt f5d9389284 MirrorBar+ panels follow the bar transparency, part 2 2026-11-08 03:53:07 +00:00
weishaupt 572d64c280 MirrorBar+ panels follow the bar transparency, part 1 2026-11-08 03:52:53 +00:00
weishaupt db0249bc14 MirrorBar+ part 3: local news flyout, system stats flyout with copy, feature switches 2026-11-08 02:58:31 +00:00
weishaupt ddcb334a10 MirrorBar+ part 2: tray, weather, radar, local news data 2026-11-08 02:58:18 +00:00
weishaupt 6a84862b71 MirrorBar+ part 1: weather radar, outline color, show/hide switches, README 2026-11-08 02:58:02 +00:00
weishaupt 49ea564abf v27 part 3: README list fix 2026-11-08 02:16:08 +00:00
weishaupt 9db905b0df v27 part 2: weather icon on the bar, README 2026-11-08 02:15:36 +00:00
weishaupt e796560d0e v27: weather flyout with sun and cloud icon, ZIP code in settings 2026-11-08 02:15:20 +00:00
weishaupt c94e74451f v26: drop files onto app icons, settings window 2026-11-07 15:42:49 +00:00
weishaupt 807befdd53 Draggable left edge resize, part 2, README update 2026-11-06 23:32:47 +00:00
weishaupt 7e5cf13afe Draggable left edge resize, part 1 2026-11-06 23:32:26 +00:00
weishaupt 9e6b24268f Icon style (colorized or grayscale), part 2, README update 2026-11-06 16:00:43 +00:00
weishaupt ecde38f9e8 Icon style (colorized or grayscale), part 1 2026-11-06 16:00:27 +00:00
weishaupt 1c43c4b4bd Update README for previews, pinning, saved order and notification center 2026-11-06 15:36:40 +00:00
weishaupt f8f579252d Add hover previews, pinned apps, saved icon order and notification center menu item 2026-11-06 15:36:28 +00:00
weishaupt ddfd5a375b README: right row drag 2026-11-06 11:49:30 +00:00
weishaupt ed8a7cf275 Drag to reorder the clock, battery, volume, wifi and hidden icons arrow 2026-11-06 11:49:19 +00:00
weishaupt cab30fb5d3 README: drag to reorder 2026-11-06 11:43:56 +00:00
weishaupt 171afe6605 Drag to reorder the app icons and the Windows logo 2026-11-06 11:43:42 +00:00
weishaupt d72cf82604 README: colors and smooth rendering 2026-11-06 11:33:29 +00:00
weishaupt c4f2291136 Smooth edges, logo/clock/tray colors, hidden icons fix 2026-11-06 11:33:14 +00:00
22 changed files with 5628 additions and 302 deletions
+25 -4
View File
@@ -1,15 +1,35 @@
# MirrorBar # MirrorBar+
A small Windows 11 taskbar replacement, one exe, no installer, no dependencies. MirrorBar+ is a small Windows 11 taskbar replacement, one exe, no installer, no dependencies.
The real taskbar is hidden and a see-through pill takes its place. The pill is a mirror image around its center line. To the left of center is the Start button, with your open apps as small icon-only buttons stretching further left. To the right of center is the clock (time and date on one line), then battery, volume, wifi and the ^ hidden-icons arrow stretching further right. The real taskbar is hidden and a see-through pill takes its place. The pill is a mirror image around its center line. To the left of center is the Start button, with your open apps as small icon-only buttons stretching further left. To the right of center is the clock (time and date on one line), then a little sun-and-cloud for the weather, a little newspaper for local news, a little monitor for system stats, battery, volume, wifi and the ^ hidden-icons arrow stretching further right.
## What it does ## What it does
- Transparent pill that is only as wide as what is in it, centered on the screen with a few pixels of space under it. - Transparent pill that is only as wide as what is in it, centered on the screen with a few pixels of space under it.
- Drag it anywhere by its background. It remembers where you put it. Right-click and choose "Reset position to bottom center" to send it home. - Drag it anywhere by its background. It remembers where you put it. Right-click and choose "Reset position to bottom center" to send it home.
- Pull the far left end of the pill (the cursor turns into a double arrow) to shrink the empty space on the left. The center line stays put, and the left side stretches back out as you open more apps. Right-click and choose "Reset bar width" to go back to the mirrored look.
- Right-click and choose "Switch to vertical" to stand it up and down against the right edge of the screen. - Right-click and choose "Switch to vertical" to stand it up and down against the right edge of the screen.
- Right-click an app icon for the normal window options (Restore, Move, Size, Minimize, Maximize, Close) plus Open new window and Open file location. - Right-click an app icon for the normal window options (Restore, Move, Size, Minimize, Maximize, Close) plus Open new window and Open file location.
- Drag the app icons and the Windows logo along the left row to reorder them. MirrorBar remembers the order of your apps and the logo's spot.
- Drag the clock, battery, volume, wifi and hidden-icons arrow along the right row to reorder them. That order is remembered.
- Rest the mouse on an app icon for a moment and a live preview of that window pops up beside the bar (minimized windows show their icon instead). Click the preview to switch to that window.
- Right-click an app icon and choose "Pin to MirrorBar" to keep it on the bar. A pinned app that isn't running shows as a launcher: click it to start the program, and when its window opens it takes that spot. Pinning works for normal programs; Store apps can't be pinned.
- "Open notification center" is in the right-click menu.
- Drag files from Explorer onto an app icon and that program opens them, running or pinned.
- "MirrorBar settings..." in the right-click menu opens one window for background opacity, the three colors, icon style, the ZIP code, tickboxes to show or hide the weather, the local news and the system stats, vertical mode, start with Windows, and resetting the position and width. Changes apply as you make them.
- Smooth, outline-free icons and text, even when the pill is see-through.
- Click the storm cloud and a weather panel opens above the bar: the temperature in Fahrenheit, what it feels like, the high and low, humidity, wind, chance of rain, sunrise, sunset, UV index, the moon phase, a looping radar picture of the last hour or so centered on your ZIP code, and the next five days. Click the cloud again, or click anywhere else, and it closes. It needs a ZIP code: type it in "MirrorBar settings..." (a 5 digit US ZIP code) and the weather turns on at once. The forecast comes from Open-Meteo (open-meteo.com, free, no account), the radar map comes from RainViewer and Esri and is only downloaded when you open the panel, and MirrorBar only goes to the internet when a ZIP code is set. The cloud can be dragged along the right row like the other icons.
- Click the newspaper and a panel of local headlines opens above the bar, newest first, with the outlet and how long ago each ran. Click a headline and it opens in your default browser. It uses the same ZIP code as the weather: the ZIP code is turned into a town name and the headlines are Google News' feed for that town, so someone in 43220 gets Columbus stations and papers and someone in 46750 gets Fort Wayne and Huntington ones. The headlines are only downloaded when a ZIP code is set. Small towns have fewer stories than cities.
- "Show weather on the bar" and "Show local news on the bar" in the settings window turn either feature off. The icon leaves the bar and nothing is downloaded for it; tick the box again and it comes back.
- The weather, news and system stats panels are as see-through as the bar itself: set the bar to Clear and the panels go clear too, with only their text, pictures and outline staying solid. Untick "Panels match the bar's transparency" in the settings window to keep the panels solid.
- Click the little monitor and a panel opens with the usual neofetch information: OS, host, kernel, uptime, resolution, CPU, GPU, memory, each fixed disk, battery and local IP. Click any line to copy it to the clipboard, or click the top of the panel to copy everything as plain text you can paste into other programs. Nothing leaves your PC; it is all read from Windows.
- Pick the color of the Windows logo, the clock, and the battery/volume/wifi/arrow icons from the right-click menu (white, blue, sky blue, green, yellow, orange, red, pink, purple, black).
- "Icon style" in the right-click menu: colorized or grayscale. It applies to the app icons and to the logo, clock and tray icons.
- Background see-through level: Clear, Light, Medium or Solid. - Background see-through level: Clear, Light, Medium or Solid.
- "Start MirrorBar when I sign in" in the right-click menu. - "Start MirrorBar when I sign in" in the right-click menu.
- Scroll over the speaker to change the volume. Click the clock, battery, volume or wifi for the matching Windows panel. - Scroll over the speaker to change the volume. Click the clock, battery, volume or wifi for the matching Windows panel.
@@ -24,7 +44,7 @@ The real taskbar is hidden and a see-through pill takes its place. The pill is a
## Download ## Download
Grab `mirrorbar.zip` from the Releases page. If Windows shows a "protected your PC" warning, right-click the zip, choose Properties, check Unblock, and unzip it after that. Grab `MirrorBarPlus.zip` from the Releases page. If Windows shows a "protected your PC" warning, right-click the zip, choose Properties, check Unblock, and unzip it after that.
## Build ## Build
@@ -35,3 +55,4 @@ GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-H=windowsgui -s -w"
``` ```
Settings are kept in `%LOCALAPPDATA%\MirrorBar`. Settings are kept in `%LOCALAPPDATA%\MirrorBar`.
+159
View File
@@ -0,0 +1,159 @@
package main
// Resizing the left half: the center line (where the Start button and the
// clock meet) stays put, but the two halves no longer have to be the same
// length. Pull the far left end of the pill (the top end when it stands up) and
// the empty space shrinks, down to where the buttons touch. Open more apps and
// the left half stretches back out to fit them.
import (
"os"
"path/filepath"
"strconv"
"strings"
"unsafe"
)
const (
menuResetWidthID = 44
wmSetCursor = 0x0020
idcSizeWE = 32644
idcSizeNS = 32645
)
var (
pSetCursor = user32.NewProc("SetCursor")
leftPref int32 // 0: mirror the right half (the original look), -1: hug the buttons, else the chosen length
resizing bool
resizeFrom int32 // where the cursor was along the bar when the drag began
resizeLen int32 // the length of the left half when the drag began
)
func widthFile() string { return filepath.Join(dataDir(), "leftwidth.txt") }
func loadLeftPref() {
b, err := os.ReadFile(widthFile())
if err != nil {
return
}
switch s := strings.TrimSpace(string(b)); s {
case "tight":
leftPref = -1
case "", "mirror":
leftPref = 0
default:
if n, err := strconv.Atoi(s); err == nil && n > 0 {
leftPref = int32(n)
}
}
}
func saveLeftPref() {
_ = os.MkdirAll(dataDir(), 0o755)
s := "mirror"
switch {
case leftPref < 0:
s = "tight"
case leftPref > 0:
s = strconv.Itoa(int(leftPref))
}
_ = os.WriteFile(widthFile(), []byte(s), 0o644)
}
// halfLimit is the longest either half may be.
func halfLimit() int32 {
sw, _ := screenSize()
return sw/2 - px(4)
}
// rightHalf is the length of the right half: the tray items plus a little padding.
func rightHalf() int32 {
items := trayItemsAt(0, 1)
return min(items[len(items)-1].r.Right+px(16), halfLimit())
}
// leftContent is the least the left half needs: Start, every app, and padding.
func leftContent() int32 {
return startWidth() + int32(len(apps))*px(36) + px(16)
}
// leftHalf is the length of the left half.
func leftHalf() int32 {
lc := leftContent()
var h int32
switch {
case leftPref < 0:
h = lc
case leftPref > 0:
h = max(lc, leftPref)
default:
h = max(lc, rightHalf())
}
return min(h, halfLimit())
}
// axisX is where the center line is, along the bar, measured from its start.
func axisX(clientW int32) int32 { return leftHalf() }
// ---------- the drag handle ----------
func edgeZone(along int32) bool { return along >= 0 && along < px(10) }
func cursorAlong() int32 {
var p point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&p)))
if vertical {
return p.Y
}
return p.X
}
// overEdge reports whether the cursor is on the draggable far end of the pill.
func overEdge(hwnd uintptr) bool {
var p point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&p)))
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
if p.X < wr.Left || p.X >= wr.Right || p.Y < wr.Top || p.Y >= wr.Bottom {
return false
}
if vertical {
return edgeZone(p.Y - wr.Top)
}
return edgeZone(p.X - wr.Left)
}
func beginResize(hwnd uintptr) {
resizing = true
resizeFrom = cursorAlong()
resizeLen = leftHalf()
pSetCapture.Call(hwnd)
}
func moveResize(hwnd uintptr) {
newLen := resizeLen - (cursorAlong() - resizeFrom)
if newLen <= leftContent()+px(10) {
leftPref = -1 // pulled all the way in: hug the buttons
} else {
leftPref = min(newLen, halfLimit())
}
redraw(hwnd)
}
func endResize(hwnd uintptr) {
resizing = false
pReleaseCapture.Call()
saveLeftPref()
redraw(hwnd)
}
func sizeCursor() uintptr {
id := uintptr(idcSizeWE)
if vertical {
id = idcSizeNS
}
c, _, _ := pLoadCursor.Call(0, id)
return c
}
+68
View File
@@ -0,0 +1,68 @@
package main
// Dropping files on an app icon: drag a document (or several) from Explorer
// onto an icon on the bar and that program opens them, like the real taskbar
// does. Works for running programs and for pinned ones that are closed.
import (
"strings"
"syscall"
"unsafe"
)
const wmDropFiles = 0x0233
var (
pDragAcceptFiles = shell32.NewProc("DragAcceptFiles")
pDragQueryFile = shell32.NewProc("DragQueryFileW")
pDragQueryPoint = shell32.NewProc("DragQueryPoint")
pDragFinish = shell32.NewProc("DragFinish")
)
func enableFileDrop(hwnd uintptr) { pDragAcceptFiles.Call(hwnd, 1) }
// dropFiles handles WM_DROPFILES: work out which icon the files landed on and
// start that program with the file names.
func dropFiles(hwnd, hdrop uintptr) {
defer pDragFinish.Call(hdrop)
var pt point
pDragQueryPoint.Call(hdrop, uintptr(unsafe.Pointer(&pt)))
x := pt.X
if vertical {
x = pt.Y
}
idx := appIndexAt(hwnd, x)
if idx < 0 || idx >= len(apps) {
return // dropped on the Start button, the clock or empty bar
}
exe := apps[idx].exe
if exe == "" && apps[idx].hwnd != 0 {
exe = windowExePath(apps[idx].hwnd)
}
if exe == "" {
return // Store apps can't be started with a file this way
}
count, _, _ := pDragQueryFile.Call(hdrop, 0xFFFFFFFF, 0, 0)
var params []string
total := 0
for i := uintptr(0); i < count; i++ {
n, _, _ := pDragQueryFile.Call(hdrop, i, 0, 0)
if n == 0 {
continue
}
buf := make([]uint16, n+1)
pDragQueryFile.Call(hdrop, i, uintptr(unsafe.Pointer(&buf[0])), n+1)
p := `"` + syscall.UTF16ToString(buf) + `"`
if total+len(p) > 30000 { // a command line can't be longer than about 32,000 characters
break
}
total += len(p) + 1
params = append(params, p)
}
if len(params) == 0 {
return
}
shellOpen(exe, strings.Join(params, " "))
}
+128
View File
@@ -0,0 +1,128 @@
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()
}
+602
View File
@@ -0,0 +1,602 @@
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)
}
}
+166
View File
@@ -0,0 +1,166 @@
package main
// Painting the three panels (weather, news, system stats) as see-through
// windows that follow the bar's own background opacity. The panels are painted
// the same way the bar is: the content (text, pictures, lines) is drawn twice at
// double size, once on black and once on white; comparing the two copies shows
// how solid every pixel is. The panel's background color is then added back at
// the bar's see-through level, and the result is handed to Windows as a layered
// window with a transparency value for every pixel.
import (
"unsafe"
)
// flyMatchBar is the "panels match the bar's transparency" setting. When it is
// off the panels are solid, as they were before.
var flyMatchBar = true
func flyBgAlpha() uint32 {
if flyMatchBar {
return uint32(bgAlpha)
}
return 255
}
// flyFrame draws the one pixel outline around a panel, in the tray icon color.
// The background inside it is not painted here; flyRender adds it.
func flyFrame(hdc uintptr, W, H int32) {
t, col := px(1), iconColor()
fillRaw(hdc, rect{0, 0, W, t}, col)
fillRaw(hdc, rect{0, H - t, W, H}, col)
fillRaw(hdc, rect{0, 0, t, H}, col)
fillRaw(hdc, rect{W - t, 0, W, H}, col)
}
// flyLayer paints the content onto a flat color and returns its pixels.
func flyLayer(screen uintptr, w, h int32, base uintptr, draw func(hdc uintptr, W, H int32)) []uint32 {
mem, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(mem)
bmi := bitmapInfoHeader{Width: w, Height: -h, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
var bits unsafe.Pointer
bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0, uintptr(unsafe.Pointer(&bits)), 0, 0)
if bmp == 0 || bits == nil {
return nil
}
defer pDeleteObject.Call(bmp)
old, _, _ := pSelectObject.Call(mem, bmp)
defer pSelectObject.Call(mem, old)
fillRaw(mem, rect{0, 0, w, h}, base)
draw(mem, w, h)
pGdiFlush.Call()
out := make([]uint32, int(w)*int(h))
copy(out, unsafe.Slice((*uint32)(bits), len(out)))
return out
}
// flyRender paints one panel and puts it on the screen.
func flyRender(hwnd uintptr, draw func(hdc uintptr, W, H int32)) {
if hwnd == 0 {
return
}
if v, _, _ := pIsWindowVisible.Call(hwnd); v == 0 {
return
}
var rc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
W, H := rc.Right-rc.Left, rc.Bottom-rc.Top
if W <= 0 || H <= 0 {
return
}
const ss = 2
screen, _, _ := pGetDC.Call(0)
defer pReleaseDC.Call(0, screen)
saved := scale
scale *= ss
wxMakeFonts()
onBlack := flyLayer(screen, W*ss, H*ss, rgb(0, 0, 0), draw)
onWhite := flyLayer(screen, W*ss, H*ss, rgb(255, 255, 255), draw)
scale = saved
n := int(W) * int(H)
if len(onBlack) != n*ss*ss || len(onWhite) != len(onBlack) {
return
}
mem, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(mem)
bmi := bitmapInfoHeader{Width: W, Height: -H, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
var bits unsafe.Pointer
bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0, uintptr(unsafe.Pointer(&bits)), 0, 0)
if bmp == 0 || bits == nil {
return
}
defer pDeleteObject.Call(bmp)
old, _, _ := pSelectObject.Call(mem, bmp)
defer pSelectObject.Call(mem, old)
pix := unsafe.Slice((*uint32)(bits), n)
a := flyBgAlpha()
bgR, bgG, bgB := uint32(28)*a/255, uint32(28)*a/255, uint32(34)*a/255 // colBack at its see-through level
stride := int(W) * ss
for i := range pix {
x, y := i%int(W), i/int(W)
var br, bg, bb, wr, wg, wb uint32
for dy := 0; dy < ss; dy++ {
for dx := 0; dx < ss; dx++ {
k := (y*ss+dy)*stride + x*ss + dx
c, w := onBlack[k], onWhite[k]
br += c >> 16 & 0xFF
bg += c >> 8 & 0xFF
bb += c & 0xFF
wr += w >> 16 & 0xFF
wg += w >> 8 & 0xFF
wb += w & 0xFF
}
}
const cnt = ss * ss
br, bg, bb, wr, wg, wb = br/cnt, bg/cnt, bb/cnt, wr/cnt, wg/cnt, wb/cnt
d := (sub0(wr, br) + sub0(wg, bg) + sub0(wb, bb)) / 3
fa := 255 - min(d, 255) // how solid the content is here
fr, fg, fb := min(br, fa), min(bg, fa), min(bb, fa)
inv := 255 - fa
oa := fa + a*inv/255
pix[i] = oa<<24 | (fr+bgR*inv/255)<<16 | (fg+bgG*inv/255)<<8 | (fb + bgB*inv/255)
}
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
dst := point{wr.Left, wr.Top}
sz := size{W, H}
src := point{0, 0}
blend := blendFunction{Op: 0, Flags: 0, Alpha: 255, Format: 1} // AC_SRC_OVER, AC_SRC_ALPHA
pUpdateLayeredWindow.Call(hwnd, screen,
uintptr(unsafe.Pointer(&dst)), uintptr(unsafe.Pointer(&sz)),
mem, uintptr(unsafe.Pointer(&src)), 0,
uintptr(unsafe.Pointer(&blend)), ulwAlpha)
}
// flyRefresh repaints one of the panels.
func flyRefresh(hwnd uintptr) {
switch hwnd {
case wxHwnd:
flyRender(hwnd, wxDraw)
case newsHwnd:
flyRender(hwnd, newsDraw)
case sysHwnd:
flyRender(hwnd, sysDraw)
}
}
// flyRefreshAll repaints whichever panel is open (after a setting changed).
func flyRefreshAll() {
if wxShown {
flyRefresh(wxHwnd)
}
if newsShown {
flyRefresh(newsHwnd)
}
if sysShown {
flyRefresh(sysHwnd)
}
}
+198
View File
@@ -0,0 +1,198 @@
package main
// Icon style: colorized or grayscale. It applies to the app
// icons (their pixels are filtered) and to everything MirrorBar draws itself
// (the logo, clock, battery, volume, wifi and arrow colors).
import (
"os"
"path/filepath"
"strconv"
"strings"
"unsafe"
)
const (
modeColor = 0
modeGray = 1
menuStyleBase = 160
)
var (
pGetIconInfo = user32.NewProc("GetIconInfo")
pCreateIconIndirect = user32.NewProc("CreateIconIndirect")
pDestroyIcon = user32.NewProc("DestroyIcon")
pGetObject = gdi32.NewProc("GetObjectW")
pGetDIBits = gdi32.NewProc("GetDIBits")
iconMode = modeColor
styleCache = map[styleKey]uintptr{}
)
type styleKey struct {
icon uintptr
mode int
}
type iconInfo struct {
FIcon int32
XHot uint32
YHot uint32
Mask uintptr
Color uintptr
}
type bitmapObj struct {
Type int32
Width int32
Height int32
WidthBytes int32
Planes uint16
BitsPixel uint16
Bits uintptr
}
var styleNames = []string{"Colorized", "Grayscale"}
func styleFile() string { return filepath.Join(dataDir(), "iconstyle.txt") }
func loadIconMode() {
b, err := os.ReadFile(styleFile())
if err != nil {
return
}
if n, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && n >= 0 && n < len(styleNames) {
iconMode = n
}
}
func saveIconMode() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(styleFile(), []byte(strconv.Itoa(iconMode)), 0o644)
}
// styleCacheClear throws away the filtered copies of icons.
func styleCacheClear() {
for _, v := range styleCache {
if v != 0 {
pDestroyIcon.Call(v)
}
}
styleCache = map[styleKey]uintptr{}
}
// styledIcon is the icon as it should be drawn in the current style.
func styledIcon(ic uintptr) uintptr {
if ic == 0 || iconMode == modeColor {
return ic
}
k := styleKey{ic, iconMode}
if v, ok := styleCache[k]; ok {
if v != 0 {
return v
}
return ic
}
v := makeStyledIcon(ic, iconMode)
if len(styleCache) > 300 {
styleCacheClear()
}
styleCache[k] = v
if v == 0 {
return ic
}
return v
}
// makeStyledIcon returns a filtered copy of an icon, or 0 if it can't be done
// (the original is then drawn as it is).
func makeStyledIcon(ic uintptr, mode int) (result uintptr) {
defer func() {
if r := recover(); r != nil {
result = 0
}
}()
var ii iconInfo
r, _, _ := pGetIconInfo.Call(ic, uintptr(unsafe.Pointer(&ii)))
if r == 0 {
return 0
}
defer func() {
if ii.Mask != 0 {
pDeleteObject.Call(ii.Mask)
}
if ii.Color != 0 {
pDeleteObject.Call(ii.Color)
}
}()
if ii.Color == 0 {
return 0 // a two-color icon, leave it
}
var bm bitmapObj
pGetObject.Call(ii.Color, unsafe.Sizeof(bm), uintptr(unsafe.Pointer(&bm)))
w, h := int(bm.Width), int(bm.Height)
if w <= 0 || h <= 0 || w > 512 || h > 512 {
return 0
}
hdc, _, _ := pGetDC.Call(0)
defer pReleaseDC.Call(0, hdc)
bmi := bitmapInfoHeader{Width: int32(w), Height: int32(-h), Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
pix := make([]uint32, w*h)
n, _, _ := pGetDIBits.Call(hdc, ii.Color, 0, uintptr(h), uintptr(unsafe.Pointer(&pix[0])),
uintptr(unsafe.Pointer(&bmi)), 0)
if n == 0 {
return 0
}
for i, p := range pix {
a := p >> 24
cr, cg, cb := p>>16&0xFF, p>>8&0xFF, p&0xFF
y := (cr*299 + cg*587 + cb*114) / 1000 // works on premultiplied pixels too
pix[i] = a<<24 | y<<16 | y<<8 | y
}
var bits unsafe.Pointer
hb, _, _ := pCreateDIBSection.Call(hdc, uintptr(unsafe.Pointer(&bmi)), 0, uintptr(unsafe.Pointer(&bits)), 0, 0)
if hb == 0 || bits == nil {
return 0
}
copy(unsafe.Slice((*uint32)(bits), w*h), pix)
ni := iconInfo{FIcon: 1, Mask: ii.Mask, Color: hb}
nh, _, _ := pCreateIconIndirect.Call(uintptr(unsafe.Pointer(&ni)))
pDeleteObject.Call(hb)
return nh
}
// styleColor applies the style to a color MirrorBar draws itself.
func styleColor(r, g, b int) (int, int, int) {
if iconMode == modeGray {
y := (r*299 + g*587 + b*114) / 1000
return y, y, y
}
return r, g, b
}
func addStyleMenu(menu uintptr) {
sub, _, _ := pCreatePopupMenu.Call()
for i, name := range styleNames {
var flags uintptr
if i == iconMode {
flags = mfChecked
}
pAppendMenu.Call(sub, flags, uintptr(menuStyleBase+i), uintptr(unsafe.Pointer(u16(name))))
}
pAppendMenu.Call(menu, mfPopup, sub, uintptr(unsafe.Pointer(u16("Icon style"))))
}
func handleStyleCommand(cmd uintptr) bool {
if cmd < menuStyleBase || cmd >= menuStyleBase+uintptr(len(styleNames)) {
return false
}
iconMode = int(cmd - menuStyleBase)
saveIconMode()
styleCacheClear()
return true
}
+235 -239
View File
@@ -22,7 +22,6 @@
package main package main
import ( import (
"math"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@@ -303,9 +302,10 @@ type trackMouseEvent struct {
// appWin is one open window shown as an icon button on the left side of the bar. // appWin is one open window shown as an icon button on the left side of the bar.
type appWin struct { type appWin struct {
hwnd uintptr hwnd uintptr // 0 for a pinned program that has no window open right now
title string title string
icon uintptr icon uintptr
exe string // full path of the program, "" when unknown
} }
type alphaLevel struct { type alphaLevel struct {
@@ -515,58 +515,18 @@ func fetchIcon(hwnd uintptr) uintptr {
return 0 return 0
} }
// refreshApps re-reads the open windows, keeping existing buttons in their
// places and adding new windows at the far end. Returns true if anything changed.
func refreshApps(refreshIcons bool) bool {
enumFound = enumFound[:0]
pEnumWindows.Call(enumCb, 0)
present := make(map[uintptr]appWin, len(enumFound))
for _, f := range enumFound {
present[f.hwnd] = f
}
var next []appWin
for _, a := range apps {
if f, ok := present[a.hwnd]; ok {
a.title = f.title
next = append(next, a)
delete(present, a.hwnd)
}
}
for _, f := range enumFound {
if _, ok := present[f.hwnd]; ok {
next = append(next, f)
}
}
for i := range next {
if next[i].icon == 0 || refreshIcons {
if ic := fetchIcon(next[i].hwnd); ic != 0 {
next[i].icon = ic
}
}
}
// Titles change constantly (browser tabs, documents) but nothing on the
// bar shows them, so only a change in which windows exist, or their icons,
// counts as a change.
changed := len(next) != len(apps)
if !changed {
for i := range next {
if next[i].hwnd != apps[i].hwnd || next[i].icon != apps[i].icon {
changed = true
break
}
}
}
apps = next
return changed
}
func activateApp(idx int) { func activateApp(idx int) {
if idx < 0 || idx >= len(apps) { if idx < 0 || idx >= len(apps) {
return return
} }
h := apps[idx].hwnd 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() fg, _, _ := pGetForegroundWindow.Call()
iconic, _, _ := pIsIconic.Call(h) iconic, _, _ := pIsIconic.Call(h)
switch { switch {
@@ -591,18 +551,11 @@ func screenSize() (int32, int32) {
return int32(w), int32(h) return int32(w), int32(h)
} }
// pillWidth is the width the bar needs: the wider of the two halves, doubled so // pillWidth is the width the bar needs: the left half plus the right half. By
// the bar stays a mirror image around the center, plus a little padding. // 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 { func pillWidth() int32 {
sw, _ := screenSize() return leftHalf() + rightHalf()
left := startWidth() + int32(len(apps))*px(36)
items := trayItems(0, 1)
right := items[len(items)-1].r.Right
half := max(left, right) + px(16)
if limit := sw/2 - px(4); half > limit {
half = limit
}
return half * 2
} }
// barGap is the space left under the pill so it stands off the screen edge. // barGap is the space left under the pill so it stands off the screen edge.
@@ -635,29 +588,17 @@ func positionBar(hwnd uintptr) {
// too many to fit, the buttons shrink to a minimum width and the oldest run // too many to fit, the buttons shrink to a minimum width and the oldest run
// off the left edge. // off the left edge.
func appRects(clientW, clientH int32) []rect { func appRects(clientW, clientH int32) []rect {
n := int32(len(apps)) if len(apps) == 0 {
if n == 0 {
return nil return nil
} }
right := clientW/2 - startWidth() row := rowLayout(clientW, clientH)
avail := right - px(8) rects := make([]rect, len(apps))
bw := px(36) for i := range rects {
if avail/n < bw { rects[i] = row[seqOfApp(i)]
bw = avail / n
}
if bw < px(24) {
bw = px(24)
}
rects := make([]rect, n)
for i := int32(0); i < n; i++ {
r := right - i*bw
rects[i] = rect{r - bw, 0, r, clientH}
} }
return rects return rects
} }
// clientSize is the size of the bar in the horizontal layout (length, thickness),
// whichever way the real window is turned.
func clientSize(hwnd uintptr) (int32, int32) { func clientSize(hwnd uintptr) (int32, int32) {
var rc rect var rc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc))) pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
@@ -677,10 +618,30 @@ func appIndexAt(hwnd uintptr, x int32) int {
return -1 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) { 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) b, _, _ := pCreateSolidBrush.Call(color)
pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b) pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b)
pDeleteObject.Call(b) pDeleteObject.Call(b)
}
} }
func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) { func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) {
@@ -707,17 +668,17 @@ func drawLogo(hdc uintptr, r rect) {
total := sq*2 + gap total := sq*2 + gap
x := r.Left + (r.Right-r.Left-total)/2 x := r.Left + (r.Right-r.Left-total)/2
y := r.Top + (r.Bottom-r.Top-total)/2 y := r.Top + (r.Bottom-r.Top-total)/2
c := rgb(0, 120, 212) c := logoColor()
fill(hdc, rect{x, y, x + sq, y + sq}, c) fillFg(hdc, rect{x, y, x + sq, y + sq}, c)
fill(hdc, rect{x + sq + gap, y, x + total, y + sq}, c) fillFg(hdc, rect{x + sq + gap, y, x + total, y + sq}, c)
fill(hdc, rect{x, y + sq + gap, x + sq, y + total}, c) fillFg(hdc, rect{x, y + sq + gap, x + sq, y + total}, c)
fill(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c) fillFg(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c)
} }
func drawClock(hdc uintptr, r rect) { func drawClock(hdc uintptr, r rect) {
now := time.Now() now := time.Now()
pSetBkMode.Call(hdc, transparent) pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(245, 245, 245)) pSetTextColor.Call(hdc, clockColor())
// Time and date on one line, like "11:32 PM 11/5/2026". // Time and date on one line, like "11:32 PM 11/5/2026".
old, _, _ := pSelectObject.Call(hdc, fontTime) old, _, _ := pSelectObject.Call(hdc, fontTime)
drawText(hdc, now.Format("3:04 PM 1/2/2006"), r) drawText(hdc, now.Format("3:04 PM 1/2/2006"), r)
@@ -744,7 +705,7 @@ func drawApps(hdc uintptr, w, h int32) {
fill(hdc, inner, rgb(40, 40, 48)) fill(hdc, inner, rgb(40, 40, 48))
} }
if !vertical { if !vertical && layerFg {
drawAppGlyph(hdc, inner, a) drawAppGlyph(hdc, inner, a)
} }
} }
@@ -756,7 +717,7 @@ func drawAppGlyph(hdc uintptr, r rect, a appWin) {
isz := px(16) // the small taskbar icon size isz := px(16) // the small taskbar icon size
if a.icon != 0 { if a.icon != 0 {
cx, cy := center(r) cx, cy := center(r)
pDrawIconEx.Call(hdc, uintptr(cx-isz/2), uintptr(cy-isz/2), a.icon, uintptr(isz), uintptr(isz), 0, 0, diNormal) 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 { } else if rs := []rune(a.title); len(rs) > 0 {
pSetBkMode.Call(hdc, transparent) pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(245, 245, 245)) pSetTextColor.Call(hdc, rgb(245, 245, 245))
@@ -773,156 +734,10 @@ func premul(c uint32, a uint32) uint32 {
return a<<24 | r<<16 | g<<8 | b return a<<24 | r<<16 | g<<8 | b
} }
// redraw paints the whole bar into a 32 bit bitmap, sets each pixel's
// transparency (background pixels get the chosen see-through level, everything
// drawn on top stays solid) and hands it to Windows as a layered window.
// A vertical bar is drawn horizontally first and then turned a quarter turn;
// the icons and symbols are then drawn again upright on top.
func redraw(hwnd uintptr) {
if hwnd == 0 {
return
}
// Shrink or grow the pill to fit what is in it, staying centered where it is.
pw, ph := pillSize()
var crc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&crc)))
if (crc.Right != pw || crc.Bottom != ph) && !dragging {
x, y := pillPos(pw, ph)
pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 0)
}
w, h := clientSize(hwnd)
if w <= 0 || h <= 0 {
return
}
screen, _, _ := pGetDC.Call(0)
defer pReleaseDC.Call(0, screen)
mem, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(mem)
bmi := bitmapInfoHeader{Width: w, Height: -h, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
var bits unsafe.Pointer
bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0,
uintptr(unsafe.Pointer(&bits)), 0, 0)
if bmp == 0 || bits == nil {
return
}
defer pDeleteObject.Call(bmp)
old, _, _ := pSelectObject.Call(mem, bmp)
defer pSelectObject.Call(mem, old)
rc := rect{0, 0, w, h}
fill(mem, rc, rgb(22, 22, 26))
cx := w / 2
sr := rect{cx - startWidth(), 0, cx, h}
if hoverStart {
fill(mem, sr, rgb(58, 58, 68))
}
drawLogo(mem, sr)
drawApps(mem, w, h)
drawTray(mem, w, h)
pGdiFlush.Call()
// The finished picture: same as above for a horizontal bar.
fmem, fbits, fw, fh := mem, bits, w, h
if vertical {
fw, fh = h, w
bmiV := bitmapInfoHeader{Width: fw, Height: -fh, Planes: 1, BitCount: 32}
bmiV.Size = uint32(unsafe.Sizeof(bmiV))
var bitsV unsafe.Pointer
bmpV, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmiV)), 0,
uintptr(unsafe.Pointer(&bitsV)), 0, 0)
if bmpV == 0 || bitsV == nil {
return
}
defer pDeleteObject.Call(bmpV)
memV, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(memV)
oldV, _, _ := pSelectObject.Call(memV, bmpV)
defer pSelectObject.Call(memV, oldV)
src := unsafe.Slice((*uint32)(bits), int(w)*int(h))
dst := unsafe.Slice((*uint32)(bitsV), int(w)*int(h))
for y := int32(0); y < h; y++ {
for x := int32(0); x < w; x++ {
dst[int(x)*int(fw)+int(h-1-y)] = src[int(y)*int(w)+int(x)]
}
}
// Icons and symbols go back on upright.
for i, r := range appRects(w, h) {
if i < len(apps) {
drawAppGlyph(memV, mapRect(rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)}, h), apps[i])
}
}
for _, it := range trayItems(w, h) {
r := mapRect(it.r, h)
switch it.kind {
case trayBattery:
drawBattery(memV, r)
case trayVolume:
drawVolume(memV, r)
case trayWifi:
drawNetwork(memV, r)
case trayChevron:
drawChevron(memV, r)
}
}
pGdiFlush.Call()
fmem, fbits = memV, bitsV
}
pix := unsafe.Slice((*uint32)(fbits), int(fw)*int(fh))
a := uint32(bgAlpha)
hoverA := max(a, 120)
activeA := max(a, 150)
length := float64(max(fw, fh))
rad := float64(min(fw, fh)) / 2
for i, p := range pix {
c := p & 0x00FFFFFF
// Pill shape: how much of this pixel is inside the rounded ends.
along := float64(i%int(fw)) + 0.5
across := float64(i/int(fw)) + 0.5
if vertical {
along, across = across, along
}
da := 0.0
if along < rad {
da = rad - along
} else if along > length-rad {
da = along - (length - rad)
}
cov := rad - math.Hypot(da, across-rad) + 0.5
cov = math.Max(0, math.Min(1, cov))
sc := func(v uint32) uint32 { return uint32(float64(v) * cov) }
switch c {
case colBg:
pix[i] = premul(c, sc(a))
case colHStart, colHApp:
pix[i] = premul(c, sc(hoverA))
case colActive:
pix[i] = premul(c, sc(activeA))
default:
pix[i] = premul(c, sc(255))
}
}
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
dst := point{wr.Left, wr.Top}
sz := size{fw, fh}
src := point{0, 0}
blend := blendFunction{Op: 0, Flags: 0, Alpha: 255, Format: 1} // AC_SRC_OVER, AC_SRC_ALPHA
pUpdateLayeredWindow.Call(hwnd, screen,
uintptr(unsafe.Pointer(&dst)), uintptr(unsafe.Pointer(&sz)),
fmem, uintptr(unsafe.Pointer(&src)), 0,
uintptr(unsafe.Pointer(&blend)), ulwAlpha)
}
func inStart(hwnd uintptr, x int32) bool { func inStart(hwnd uintptr, x int32) bool {
w, _ := clientSize(hwnd) w, h := clientSize(hwnd)
cx := w / 2 r := startRect(w, h)
return x >= cx-startWidth() && x < cx return x >= r.Left && x < r.Right
} }
func tapWinKey() { func tapWinKey() {
@@ -990,13 +805,35 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&")) add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&"))
sep() sep()
exe = apps[appIdx].exe
if target != 0 && exe == "" {
exe = windowExePath(target) exe = windowExePath(target)
}
if target == 0 {
// A pinned program that isn't running: only launcher options apply.
add(0, menuLaunchID, "Open")
if exe != "" { 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, menuNewWindowID, "Open new window")
add(0, menuFileLocID, "Open file location") 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() sep()
} }
if target != 0 {
style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE
iconic, _, _ := pIsIconic.Call(target) iconic, _, _ := pIsIconic.Call(target)
zoomed, _, _ := pIsZoomed.Call(target) zoomed, _, _ := pIsZoomed.Call(target)
@@ -1016,11 +853,15 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
add(0, menuCloseID, "Close window") add(0, menuCloseID, "Close window")
sep() sep()
} }
}
if appIdx < 0 { if appIdx < 0 {
addTrayMenu(add, sep, trayKind) addTrayMenu(add, sep, trayKind)
} }
add(0, menuSettingsID, "MirrorBar settings...")
add(0, menuNotifyID, "Open notification center")
sep()
for i, l := range alphaLevels { for i, l := range alphaLevels {
var flags uintptr var flags uintptr
if bgAlpha == l.alpha { if bgAlpha == l.alpha {
@@ -1029,6 +870,8 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
add(flags, uintptr(menuLevelBase+i), "Background: "+l.name) add(flags, uintptr(menuLevelBase+i), "Background: "+l.name)
} }
sep() sep()
addColorMenus(menu)
sep()
orientText := "Switch to vertical" orientText := "Switch to vertical"
if vertical { if vertical {
orientText = "Switch to horizontal" orientText = "Switch to horizontal"
@@ -1039,6 +882,7 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
posFlags = mfGrayed posFlags = mfGrayed
} }
add(posFlags, menuResetPosID, "Reset position to bottom center") add(posFlags, menuResetPosID, "Reset position to bottom center")
add(0, menuResetWidthID, "Reset bar width")
var autoFlags uintptr var autoFlags uintptr
if autostartEnabled() { if autostartEnabled() {
autoFlags = mfChecked autoFlags = mfChecked
@@ -1067,6 +911,12 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
pDestroyWindow.Call(hwnd) pDestroyWindow.Call(hwnd)
case cmd == menuResetPosID: case cmd == menuResetPosID:
resetPos(hwnd) resetPos(hwnd)
case cmd == menuResetWidthID:
leftPref = 0
saveLeftPref()
redraw(hwnd)
case handleColorCommand(cmd):
redraw(hwnd)
case cmd == menuOrientID: case cmd == menuOrientID:
vertical = !vertical vertical = !vertical
saveOrient() saveOrient()
@@ -1075,6 +925,20 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
pPostMessage.Call(target, wmClose, 0, 0) pPostMessage.Call(target, wmClose, 0, 0)
case cmd == menuNewWindowID && exe != "": case cmd == menuNewWindowID && exe != "":
shellOpen(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 != "": case cmd == menuFileLocID && exe != "":
shellOpen("explorer.exe", `/select,"`+exe+`"`) shellOpen("explorer.exe", `/select,"`+exe+`"`)
case target != 0 && sysCommands[cmd] != 0: case target != 0 && sysCommands[cmd] != 0:
@@ -1089,6 +953,7 @@ func showMenu(hwnd uintptr, appIdx int, trayKind int) {
saveAlpha() saveAlpha()
redraw(hwnd) redraw(hwnd)
} }
settingsSync()
} }
func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) { func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
@@ -1109,6 +974,10 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
return 0 return 0
case wmTimer: case wmTimer:
if wparam == previewTimerID {
previewTick()
return 0
}
hideTaskbar() hideTaskbar()
tick++ tick++
changed := refreshApps(tick%16 == 0) changed := refreshApps(tick%16 == 0)
@@ -1127,8 +996,66 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
pDestroyWindow.Call(hwnd) pDestroyWindow.Call(hwnd)
} }
return 0 return 0
case wmMouseMove: case wmLButtonDown:
previewSuppress()
x := alongClient(lparam) 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) overStart := inStart(hwnd, x)
overApp := appIndexAt(hwnd, x) overApp := appIndexAt(hwnd, x)
overTray := trayAt(hwnd, x) overTray := trayAt(hwnd, x)
@@ -1138,6 +1065,9 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
hoverTray = overTray hoverTray = overTray
redraw(hwnd) redraw(hwnd)
} }
if overApp >= 0 {
previewKick()
}
if !trackingMouse { if !trackingMouse {
tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd} tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd}
pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme)))
@@ -1154,19 +1084,51 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
} }
return 0 return 0
case wmLButtonUp: case wmLButtonUp:
if resizing {
endResize(hwnd)
return 0
}
x := alongClient(lparam) x := alongClient(lparam)
if inStart(hwnd, x) { 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() tapWinKey()
} else if idx := appIndexAt(hwnd, x); idx >= 0 { } else if idx := appOfSeq(seq); idx >= 0 && idx < len(apps) {
activateApp(idx) activateApp(idx)
}
redraw(hwnd) redraw(hwnd)
} else if k := trayAt(hwnd, x); k != 0 { } 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) trayClick(k)
} }
redraw(hwnd)
} else if inStart(hwnd, x) {
tapWinKey()
}
return 0 return 0
case wmRButtonUp: case wmRButtonUp:
x := alongClient(lparam) x := alongClient(lparam)
previewBlock(true)
showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x))
previewBlock(false)
return 0
case wmDropFiles:
dropFiles(hwnd, wparam)
return 0
case wmWxDone:
weatherDone()
return 0 return 0
case wmMouseWheel: case wmMouseWheel:
// Scrolling over the volume icon changes the volume. The wheel // Scrolling over the volume icon changes the volume. The wheel
@@ -1184,17 +1146,25 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
var wr rect var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
x := alongScreen(lparam, wr) x := alongScreen(lparam, wr)
if inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 { if edgeZone(x) || inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 {
return htClient return htClient
} }
return htCaption 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: case wmNcLButtonDblClk:
return 0 // a double click on the drag area must not maximize the pill return 0 // a double click on the drag area must not maximize the pill
case wmNcRButtonUp: case wmNcRButtonUp:
var wr rect var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr))) pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
x := alongScreen(lparam, wr) x := alongScreen(lparam, wr)
previewBlock(true)
showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x)) showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x))
previewBlock(false)
return 0 return 0
case wmEnterSizeMove: case wmEnterSizeMove:
dragging = true dragging = true
@@ -1216,6 +1186,10 @@ func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
} }
return 0 return 0
case wmDestroy: case wmDestroy:
previewShutdown()
weatherShutdown()
newsShutdown()
sysShutdown()
abd := appBarData{Hwnd: hwnd} abd := appBarData{Hwnd: hwnd}
appBar(abmRemove, &abd) appBar(abmRemove, &abd)
pKillTimer.Call(hwnd, timerID) pKillTimer.Call(hwnd, timerID)
@@ -1269,7 +1243,15 @@ func main() {
loadAlpha() loadAlpha()
loadPos() loadPos()
loadStartSlot()
loadTrayOrder()
loadOrient() loadOrient()
loadLeftPref()
loadPinned()
loadOrderKeys()
loadIconMode()
loadZip()
loadFeatures()
hdc, _, _ := pGetDC.Call(0) hdc, _, _ := pGetDC.Call(0)
dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX) dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX)
@@ -1281,6 +1263,8 @@ func main() {
fontTime = makeFont(px(13), 400) fontTime = makeFont(px(13), 400)
fontDate = makeFont(px(11), 400) fontDate = makeFont(px(11), 400)
fontApp = makeFont(px(12), 600) fontApp = makeFont(px(12), 600)
initSuperFonts()
loadColors()
autoQuit = autoQuitDef autoQuit = autoQuitDef
if hasArg("--forever") || strings.Contains(name, "forever") { if hasArg("--forever") || strings.Contains(name, "forever") {
@@ -1320,6 +1304,11 @@ func main() {
return return
} }
hwndMain = hwnd hwndMain = hwnd
previewInit(inst)
weatherInit(inst)
newsInit(inst)
sysInit(inst)
enableFileDrop(hwnd)
refreshAutostartPath() refreshAutostartPath()
// Hotkey: Ctrl+Alt+Q exits and restores. // Hotkey: Ctrl+Alt+Q exits and restores.
@@ -1347,6 +1336,8 @@ func main() {
refreshApps(true) refreshApps(true)
positionBar(hwnd) positionBar(hwnd)
pSetTimer.Call(hwnd, timerID, 250, 0) pSetTimer.Call(hwnd, timerID, 250, 0)
weatherRefresh(false) // have the forecast ready before the cloud is first clicked
newsRefresh(false)
var m msg var m msg
for { for {
@@ -1354,6 +1345,11 @@ func main() {
if int32(r) <= 0 { if int32(r) <= 0 {
break break
} }
if hwndSettings != 0 {
if handled, _, _ := pIsDialogMessage.Call(hwndSettings, uintptr(unsafe.Pointer(&m))); handled != 0 {
continue
}
}
pTranslateMessage.Call(uintptr(unsafe.Pointer(&m))) pTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
pDispatchMessage.Call(uintptr(unsafe.Pointer(&m))) pDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
} }
+157
View File
@@ -0,0 +1,157 @@
package main
// Local news state and downloading. The place comes from the same ZIP code as
// the weather. Like the weather, the download runs on its own goroutine and the
// bar is told with a posted message when it finishes.
import (
"fmt"
"io"
"net/http"
"sync"
"time"
)
const newsFresh = 10 * time.Minute
type newsState struct {
zip string
place string
items []newsItem
ok bool
loading bool
err string
fetched time.Time
}
var (
newsMu sync.Mutex
news newsState
newsGen int
)
func newsSnapshot() newsState {
newsMu.Lock()
defer newsMu.Unlock()
s := news
s.items = append([]newsItem(nil), news.items...)
return s
}
// newsRefresh starts a download if there are no headlines for this ZIP code yet
// or they are old (or force is set). Safe to call as often as you like.
func newsRefresh(force bool) {
if !showNews {
return
}
zip := wxZip
newsMu.Lock()
if len(zip) != 5 {
news = newsState{}
newsGen++
newsMu.Unlock()
weatherNotify()
return
}
same := news.zip == zip
switch {
case same && news.loading && !force:
newsMu.Unlock()
return
case same && news.ok && time.Since(news.fetched) < newsFresh && !force:
newsMu.Unlock()
return
case same && !news.ok && news.err != "" && time.Since(news.fetched) < 30*time.Second && !force:
newsMu.Unlock() // it just failed; don't hammer the service
return
}
if !same {
news = newsState{zip: zip}
}
news.loading = true
news.err = ""
newsGen++
gen := newsGen
newsMu.Unlock()
weatherNotify()
go newsFetch(zip, gen)
}
func newsFetch(zip string, gen int) {
defer func() {
if r := recover(); r != nil {
newsFinish(gen, zip, "", nil, "The news lookup failed.")
}
}()
_, _, place, err := wxLocate(zip)
if err != nil {
newsFinish(gen, zip, "", nil, err.Error())
return
}
req, err := http.NewRequest("GET", newsFeedURL(place), nil)
if err != nil {
newsFinish(gen, zip, place, nil, "The news lookup failed.")
return
}
req.Header.Set("User-Agent", "MirrorBar news flyout")
resp, err := wxClient.Do(req)
if err != nil {
newsFinish(gen, zip, place, nil, "Can't reach the news service. Check your internet connection.")
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
newsFinish(gen, zip, place, nil, fmt.Sprintf("The news service said HTTP %d.", resp.StatusCode))
return
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
newsFinish(gen, zip, place, nil, "The news download was cut off.")
return
}
items, err := newsParse(data)
if err != nil {
newsFinish(gen, zip, place, nil, err.Error())
return
}
if len(items) == 0 {
newsFinish(gen, zip, place, nil, "No local headlines found for "+place+".")
return
}
newsFinish(gen, zip, place, items, "")
}
// newsFinish stores a result, unless the ZIP code changed while it was loading.
func newsFinish(gen int, zip, place string, items []newsItem, errText string) {
newsMu.Lock()
if gen != newsGen {
newsMu.Unlock()
return
}
news.loading = false
news.fetched = time.Now()
if place != "" {
news.place = place
}
if items != nil {
news.items, news.ok, news.err = items, true, ""
} else {
news.err = errText // keep older headlines on screen if there are any
}
newsMu.Unlock()
weatherNotify()
}
// newsStatusText is the line the settings window shows when only news is on.
func newsStatusText() string {
s := newsSnapshot()
switch {
case s.ok && s.place != "":
return "Showing local news for " + s.place
case s.loading:
return "Looking up " + wxZip + "..."
case s.err != "":
return s.err
}
return ""
}
+98
View File
@@ -0,0 +1,98 @@
package main
// Reading a news feed. Only the standard library, no Windows calls, so it can
// be tested on its own.
//
// Local headlines come from Google News' place feed: it takes a place name such
// as "Huntington, Indiana" and returns what local papers, TV and radio stations
// near it are publishing. The place name comes from the ZIP code (the weather
// lookup already finds it), so the same ZIP code serves both panels.
import (
"encoding/xml"
"fmt"
"html"
"net/url"
"sort"
"strings"
"time"
)
type newsItem struct {
title string
source string
link string
when time.Time
}
const newsKeep = 30 // headlines kept per lookup
func newsFeedURL(place string) string {
return "https://news.google.com/rss/headlines/section/geo/" + url.PathEscape(place) + "?hl=en-US&gl=US&ceid=US:en"
}
// newsParse turns the feed into headlines, newest first. Only web links are
// kept, so nothing odd can be opened from the panel.
func newsParse(data []byte) ([]newsItem, error) {
var feed struct {
Items []struct {
Title string `xml:"title"`
Link string `xml:"link"`
PubDate string `xml:"pubDate"`
Source string `xml:"source"`
} `xml:"channel>item"`
}
if err := xml.Unmarshal(data, &feed); err != nil {
return nil, fmt.Errorf("The news feed could not be read.")
}
var out []newsItem
seen := map[string]bool{}
for _, it := range feed.Items {
link := strings.TrimSpace(it.Link)
if !strings.HasPrefix(link, "https://") && !strings.HasPrefix(link, "http://") {
continue
}
title := strings.TrimSpace(html.UnescapeString(it.Title))
src := strings.TrimSpace(html.UnescapeString(it.Source))
// Titles end with " - Source Name"; the source is shown on its own line.
if src != "" && strings.HasSuffix(title, " - "+src) {
title = strings.TrimSuffix(title, " - "+src)
} else if src == "" {
if i := strings.LastIndex(title, " - "); i > 0 {
src = strings.TrimSpace(title[i+3:])
title = strings.TrimSpace(title[:i])
}
}
key := strings.ToLower(title)
if title == "" || seen[key] {
continue
}
seen[key] = true
when, _ := time.Parse(time.RFC1123, strings.TrimSpace(it.PubDate))
out = append(out, newsItem{title: title, source: src, link: link, when: when})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].when.After(out[j].when) })
if len(out) > newsKeep {
out = out[:newsKeep]
}
return out, nil
}
// newsAge says how old a headline is: "12 min ago", "3 hr ago", "2 days ago".
func newsAge(t time.Time, now time.Time) string {
if t.IsZero() {
return ""
}
d := now.Sub(t)
switch {
case d < 0, d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%d min ago", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%d hr ago", int(d.Hours()))
case d < 48*time.Hour:
return "yesterday"
}
return fmt.Sprintf("%d days ago", int(d.Hours()/24))
}
+359
View File
@@ -0,0 +1,359 @@
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)
}
+351
View File
@@ -0,0 +1,351 @@
package main
// Pinned apps and the saved icon order.
//
// A pinned app that has no open window still gets a button (a "launcher",
// which is an appWin with hwnd 0). Clicking it starts the program. When the
// program opens a window, the window takes over that very spot, and when its
// last window closes the launcher comes back in the same place.
//
// The order of the icons is remembered by program, so it comes back after a
// restart no matter which windows happen to be open.
import (
"os"
"path/filepath"
"strings"
"unsafe"
)
var (
pSHGetFileInfo = shell32.NewProc("SHGetFileInfoW")
pinned []string // full paths of pinned programs
orderKeys []string // programs in icon order, nearest the center first (lower case)
winExe = map[uintptr]string{}
exeIcons = map[string]uintptr{}
)
const (
menuPinID = 40
menuUnpinID = 41
menuNotifyID = 42
menuLaunchID = 43
shgfiIcon = 0x100
shgfiSmallIcon = 0x1
vkN = 0x4E
)
type shFileInfo struct {
Icon uintptr
IIcon int32
Attrs uint32
Display [260]uint16
Type [80]uint16
}
func pinnedFile() string { return filepath.Join(dataDir(), "pinned.txt") }
func orderFile() string { return filepath.Join(dataDir(), "order.txt") }
func readLines(path string) []string {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
var out []string
for _, l := range strings.Split(string(b), "\n") {
if l = strings.TrimSpace(l); l != "" {
out = append(out, l)
}
}
return out
}
func writeLines(path string, lines []string) {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644)
}
func loadPinned() { pinned = readLines(pinnedFile()) }
func savePinned() { writeLines(pinnedFile(), pinned) }
func loadOrderKeys() { orderKeys = readLines(orderFile()) }
func isPinned(exe string) bool {
if exe == "" {
return false
}
for _, p := range pinned {
if strings.EqualFold(p, exe) {
return true
}
}
return false
}
func pinApp(exe string) {
if exe == "" || isPinned(exe) {
return
}
pinned = append(pinned, exe)
savePinned()
saveOrder()
}
func unpinApp(exe string) {
var keep []string
for _, p := range pinned {
if !strings.EqualFold(p, exe) {
keep = append(keep, p)
}
}
pinned = keep
savePinned()
saveOrder()
}
// canPin is false for Store and other packaged apps: their programs can't be
// started again from a plain path.
func canPin(exe string) bool {
return exe != "" && !strings.Contains(strings.ToLower(exe), `\windowsapps\`)
}
// ---------- order ----------
func orderRank(exe string) int {
if exe == "" {
return -1
}
for i, k := range orderKeys {
if k == strings.ToLower(exe) {
return i
}
}
return -1
}
// saveOrder remembers the current icon order. Programs that aren't open right
// now keep their place relative to their old neighbors.
func saveOrder() {
var cur []string
have := map[string]bool{}
for _, a := range apps {
k := strings.ToLower(a.exe)
if k == "" || have[k] {
continue
}
have[k] = true
cur = append(cur, k)
}
res := cur
for i, k := range orderKeys {
if have[k] {
continue
}
pos := 0
for j := i - 1; j >= 0; j-- {
if p := indexOf(res, orderKeys[j]); p >= 0 {
pos = p + 1
break
}
}
res = append(res[:pos], append([]string{k}, res[pos:]...)...)
have[k] = true
}
if len(res) > 200 {
res = res[:200]
}
orderKeys = res
writeLines(orderFile(), orderKeys)
}
func indexOf(list []string, s string) int {
for i, v := range list {
if v == s {
return i
}
}
return -1
}
func insertAt(list []appWin, i int, a appWin) []appWin {
list = append(list, appWin{})
copy(list[i+1:], list[i:])
list[i] = a
return list
}
// addApp puts a new button into the list: into the spot of a waiting launcher
// for the same program, else beside the program's other windows, else where
// the saved order says, else at the far end.
func addApp(list []appWin, f appWin) []appWin {
if f.exe != "" {
if f.hwnd != 0 {
for i, a := range list {
if a.hwnd == 0 && strings.EqualFold(a.exe, f.exe) {
list[i] = f
return list
}
}
}
last := -1
for i, a := range list {
if a.hwnd != 0 && strings.EqualFold(a.exe, f.exe) {
last = i
}
}
if last >= 0 {
return insertAt(list, last+1, f)
}
if r := orderRank(f.exe); r >= 0 {
for i, a := range list {
if ra := orderRank(a.exe); ra < 0 || ra > r {
return insertAt(list, i, f)
}
}
}
}
return append(list, f)
}
// ---------- launchers and icons ----------
func launcher(exe string) appWin {
name := filepath.Base(exe)
name = strings.TrimSuffix(name, filepath.Ext(name))
return appWin{title: name, exe: exe, icon: exeIcon(exe)}
}
// exeIcon is the small icon of a program file, fetched once.
func exeIcon(path string) uintptr {
key := strings.ToLower(path)
if ic, ok := exeIcons[key]; ok {
return ic
}
var fi shFileInfo
r, _, _ := pSHGetFileInfo.Call(uintptr(unsafe.Pointer(u16(path))), 0,
uintptr(unsafe.Pointer(&fi)), unsafe.Sizeof(fi), shgfiIcon|shgfiSmallIcon)
var ic uintptr
if r != 0 {
ic = fi.Icon
}
exeIcons[key] = ic
return ic
}
// refreshApps re-reads the open windows and merges them with the pinned
// programs, keeping every button where it was. Returns true if anything changed.
func refreshApps(refreshIcons bool) bool {
enumFound = enumFound[:0]
pEnumWindows.Call(enumCb, 0)
present := make(map[uintptr]appWin, len(enumFound))
live := map[string]int{} // open windows per program
for _, f := range enumFound {
if _, ok := winExe[f.hwnd]; !ok {
winExe[f.hwnd] = windowExePath(f.hwnd)
}
f.exe = winExe[f.hwnd]
present[f.hwnd] = f
if f.exe != "" {
live[strings.ToLower(f.exe)]++
}
}
for h := range winExe {
if _, ok := present[h]; !ok {
delete(winExe, h)
}
}
var next []appWin
for _, a := range apps {
if a.hwnd == 0 {
next = append(next, a) // a waiting launcher; sorted out below
continue
}
if f, ok := present[a.hwnd]; ok {
a.title, a.exe = f.title, f.exe
next = append(next, a)
delete(present, a.hwnd)
} else if isPinned(a.exe) && live[strings.ToLower(a.exe)] == 0 {
// The last window of a pinned program closed: leave a launcher in its place.
next = append(next, launcher(a.exe))
}
}
for _, f := range enumFound {
if _, ok := present[f.hwnd]; ok {
next = addApp(next, f)
}
}
// Launchers for pinned programs that have neither a window nor a launcher yet.
have := map[string]bool{}
for _, a := range next {
if a.exe != "" {
have[strings.ToLower(a.exe)] = true
}
}
for _, p := range pinned {
if !have[strings.ToLower(p)] {
next = addApp(next, launcher(p))
have[strings.ToLower(p)] = true
}
}
// Drop launchers that are no longer needed.
var tidy []appWin
seen := map[string]bool{}
for _, a := range next {
if a.hwnd == 0 {
k := strings.ToLower(a.exe)
if !isPinned(a.exe) || live[k] > 0 || seen[k] {
continue
}
seen[k] = true
}
tidy = append(tidy, a)
}
next = tidy
for i := range next {
if next[i].hwnd == 0 {
if next[i].icon == 0 {
next[i].icon = exeIcon(next[i].exe)
}
continue
}
if next[i].icon == 0 || refreshIcons {
if ic := fetchIcon(next[i].hwnd); ic != 0 {
next[i].icon = ic
}
}
}
// Titles change constantly (browser tabs, documents) but nothing on the
// bar shows them, so only a change in which buttons exist, or their icons,
// counts as a change.
changed := len(next) != len(apps)
if !changed {
for i := range next {
if next[i].hwnd != apps[i].hwnd || next[i].icon != apps[i].icon {
changed = true
break
}
}
}
if changed {
styleCacheClear() // icon handles can be reused by other icons
}
apps = next
return changed
}
// ---------- notification center ----------
// openNotifications presses Win+N, which opens the notification center and calendar.
func openNotifications() {
pKeybdEvent.Call(vkLWin, 0, 0, 0)
pKeybdEvent.Call(vkN, 0, 0, 0)
pKeybdEvent.Call(vkN, 0, keyUp, 0)
pKeybdEvent.Call(vkLWin, 0, keyUp, 0)
}
+157 -6
View File
@@ -128,17 +128,20 @@ func pillPos(pw, ph int32) (int32, int32) {
return defaultPos(pw, ph) return defaultPos(pw, ph)
} }
sw, sh := screenSize() sw, sh := screenSize()
x := clampI(customCX-pw/2, 0, sw-pw) l := leftHalf() // the center line stays at the remembered spot
y := clampI(customY-ph/2, 0, sh-ph) if vertical {
return x, y return clampI(customCX-pw/2, 0, sw-pw), clampI(customY-l, 0, sh-ph)
}
return clampI(customCX-l, 0, sw-pw), clampI(customY-ph/2, 0, sh-ph)
} }
func defaultPos(pw, ph int32) (int32, int32) { func defaultPos(pw, ph int32) (int32, int32) {
sw, sh := screenSize() sw, sh := screenSize()
l := leftHalf() // the center line sits at the middle of the screen
if vertical { if vertical {
return sw - pw - barGap(), (sh - ph) / 2 return sw - pw - barGap(), sh/2 - l
} }
return (sw - pw) / 2, sh - ph - barGap() return sw/2 - l, sh - ph - barGap()
} }
// finishDrag runs when a drag ends: remember the new spot, or snap back to the // finishDrag runs when a drag ends: remember the new spot, or snap back to the
@@ -152,7 +155,12 @@ func finishDrag(hwnd uintptr) {
resetPos(hwnd) resetPos(hwnd)
return return
} }
customPos, customCX, customY = true, (wr.Left+wr.Right)/2, (wr.Top+wr.Bottom)/2 l := leftHalf()
if vertical {
customPos, customCX, customY = true, (wr.Left+wr.Right)/2, wr.Top+l
} else {
customPos, customCX, customY = true, wr.Left+l, (wr.Top+wr.Bottom)/2
}
savePos() savePos()
if appbarOn { if appbarOn {
// A floating bar no longer reserves screen space. // A floating bar no longer reserves screen space.
@@ -180,3 +188,146 @@ func resetPos(hwnd uintptr) {
} }
positionBar(hwnd) positionBar(hwnd)
} }
// ---------- the left row: Start button and app icons, all draggable ----------
var (
pSetCapture = user32.NewProc("SetCapture")
pReleaseCapture = user32.NewProc("ReleaseCapture")
)
const (
wmLButtonDown = 0x0201
wmCaptureChanged = 0x0215
)
var (
startSlot int // where the Start button sits in the left row (0 is against the center line)
dragSeq = -1 // row position of the item the mouse went down on, -1 for none
dragIsStart bool // the item being pressed is the Start button
dragStart int32 // where along the bar the mouse went down
dragActive bool // true once the mouse has moved far enough to count as a drag
)
func startSlotFile() string { return filepath.Join(dataDir(), "startslot.txt") }
func loadStartSlot() {
b, err := os.ReadFile(startSlotFile())
if err != nil {
return
}
if n, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && n >= 0 {
startSlot = n
}
}
func saveStartSlot() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(startSlotFile(), []byte(strconv.Itoa(startSlot)), 0o644)
}
func endIconDrag() {
dragSeq = -1
dragIsStart = false
dragActive = false
}
// slot is the Start button's position, kept within the row.
func slot() int {
return max(0, min(startSlot, len(apps)))
}
// The row is the Start button plus every app, from the center line leftward.
// A "row position" counts those items; app i sits at seqOfApp(i).
func seqOfApp(i int) int {
if i < slot() {
return i
}
return i + 1
}
func appOfSeq(t int) int {
if t < slot() {
return t
}
return t - 1
}
// rowLayout gives the rectangle of every row position (Start included).
func rowLayout(clientW, clientH int32) []rect {
n := int32(len(apps))
sl := int32(slot())
cx := axisX(clientW)
bw := px(36)
if n > 0 {
avail := cx - startWidth() - px(8)
if avail/n < bw {
bw = avail / n
}
if bw < px(24) {
bw = px(24)
}
}
rects := make([]rect, n+1)
x := cx
for k := int32(0); k <= n; k++ {
wd := bw
if k == sl {
wd = startWidth()
}
rects[k] = rect{x - wd, 0, x, clientH}
x -= wd
}
return rects
}
func startRect(clientW, clientH int32) rect {
return rowLayout(clientW, clientH)[slot()]
}
// seqAt is the row position under a spot along the bar, clamped to the ends.
func seqAt(hwnd uintptr, x int32) int {
w, h := clientSize(hwnd)
rects := rowLayout(w, h)
if x >= rects[0].Right {
return 0
}
if x < rects[len(rects)-1].Left {
return len(rects) - 1
}
for k, r := range rects {
if x >= r.Left && x < r.Right {
return k
}
}
return -1
}
// moveSeq moves one item of the row to another position, shifting the rest.
func moveSeq(from, to int) {
n := len(apps)
if from == to || from < 0 || to < 0 || from > n || to > n {
return
}
sl := slot()
seq := make([]int, 0, n+1) // -1 stands for the Start button, otherwise an app index
for k := 0; k <= n; k++ {
if k == sl {
seq = append(seq, -1)
} else {
seq = append(seq, appOfSeq(k))
}
}
v := seq[from]
rest := append(append([]int{}, seq[:from]...), seq[from+1:]...)
seq = append(append(append([]int{}, rest[:to]...), v), rest[to:]...)
next := make([]appWin, 0, n)
for k, a := range seq {
if a == -1 {
startSlot = k
} else {
next = append(next, apps[a])
}
}
apps = next
}
+385
View File
@@ -0,0 +1,385 @@
package main
// Hover preview: rest the mouse on an app icon and a small window with a live
// picture of that app appears next to the bar. Windows draws the picture
// itself (a DWM thumbnail), so it stays live and costs almost nothing. A
// minimized window has nothing live to show, so it gets its icon instead.
import (
"syscall"
"time"
"unsafe"
)
var (
pDwmRegisterThumbnail = dwmapi.NewProc("DwmRegisterThumbnail")
pDwmUnregisterThumbnail = dwmapi.NewProc("DwmUnregisterThumbnail")
pDwmUpdateThumbnailProperties = dwmapi.NewProc("DwmUpdateThumbnailProperties")
pDwmQueryThumbnailSourceSize = dwmapi.NewProc("DwmQueryThumbnailSourceSize")
pSetWindowPos = user32.NewProc("SetWindowPos")
pInvalidateRect = user32.NewProc("InvalidateRect")
)
const (
previewTimerID = 2
previewDelay = 350 * time.Millisecond
hwndTopmost = ^uintptr(0) // HWND_TOPMOST is (HWND)-1
swpNoActivate = 0x0010
swpShowWindow = 0x0040
wmMouseActivate = 0x0021
maNoActivate = 3
dtEndEllipsis = 0x8000
vkLButton = 0x01
dwmTnpDest = 0x1
dwmTnpOpacity = 0x4
dwmTnpVisible = 0x8
)
type dwmThumbProps struct {
Flags uint32
Dest rect
Src rect
Opacity byte
_ [3]byte
Visible int32
ClientOnly int32
}
var (
pvHwnd uintptr // the preview window itself
pvThumb uintptr // the live picture registered on it, if any
pvSrc uintptr // the window being previewed; 0 means nothing is showing
pvTitle string //
pvIcon uintptr //
pvIconic bool // true: no live picture, draw the icon instead
pvThumbR rect // picture area, in the preview's own coordinates
pvTitleR rect // title row
pvCand uintptr // the icon the mouse has been resting on
pvSince time.Time // since when
pvSupp uintptr // an icon that was just clicked: no preview until the mouse leaves it
pvTimer bool
pvBlock bool // a menu is open
)
func previewInit(inst uintptr) {
cursor, _, _ := pLoadCursor.Call(0, idcArrow)
className := u16("MirrorBarPreview")
wc := wndClassEx{
WndProc: syscall.NewCallback(previewProc),
Instance: inst,
Cursor: cursor,
ClassName: className,
}
wc.Size = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
pvHwnd, _, _ = pCreateWindowEx.Call(
wsExToolWindow|wsExTopmost|wsExNoActivate,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(u16(""))),
wsPopup,
0, 0, 10, 10,
0, 0, inst, 0)
}
func previewProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
defer func() {
if r := recover(); r != nil {
result = 0 // the preview is optional; never take the bar down with it
}
}()
switch uint32(m) {
case wmEraseBkgnd:
return 1
case wmMouseActivate:
return maNoActivate
case wmPaint:
previewPaint(hwnd)
return 0
case wmLButtonUp:
previewActivate()
return 0
}
r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam)
return r
}
func previewPaint(hwnd uintptr) {
var ps paintStruct
hdc, _, _ := pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
var rc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
edge, _, _ := pCreateSolidBrush.Call(rgb(78, 78, 92))
pFillRect.Call(hdc, uintptr(unsafe.Pointer(&rc)), edge)
pDeleteObject.Call(edge)
inner := rect{rc.Left + 1, rc.Top + 1, rc.Right - 1, rc.Bottom - 1}
body, _, _ := pCreateSolidBrush.Call(rgb(28, 28, 34))
pFillRect.Call(hdc, uintptr(unsafe.Pointer(&inner)), body)
pDeleteObject.Call(body)
isz := px(16)
if pvIcon != 0 {
y := pvTitleR.Top + (pvTitleR.Bottom-pvTitleR.Top-isz)/2
pDrawIconEx.Call(hdc, uintptr(pvTitleR.Left), uintptr(y), styledIcon(pvIcon), uintptr(isz), uintptr(isz), 0, 0, diNormal)
}
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(240, 240, 245))
old, _, _ := pSelectObject.Call(hdc, fontApp)
tr := rect{pvTitleR.Left + isz + px(6), pvTitleR.Top, pvTitleR.Right, pvTitleR.Bottom}
pDrawText.Call(hdc, uintptr(unsafe.Pointer(u16(pvTitle))), ^uintptr(0), uintptr(unsafe.Pointer(&tr)),
dtLeft|dtVCenter|dtSingleLine|dtNoPrefix|dtEndEllipsis)
pSelectObject.Call(hdc, old)
if pvIconic && pvIcon != 0 {
big := px(48)
cx := (pvThumbR.Left + pvThumbR.Right) / 2
cy := (pvThumbR.Top + pvThumbR.Bottom) / 2
pDrawIconEx.Call(hdc, uintptr(cx-big/2), uintptr(cy-big/2), styledIcon(pvIcon), uintptr(big), uintptr(big), 0, 0, diNormal)
}
pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
}
func previewDropThumb() {
if pvThumb != 0 {
pDwmUnregisterThumbnail.Call(pvThumb)
pvThumb = 0
}
}
func previewHide() {
previewDropThumb()
if pvSrc != 0 && pvHwnd != 0 {
pShowWindow.Call(pvHwnd, swHide)
}
pvSrc = 0
}
// previewIconRect is where an app icon sits on the screen.
func previewIconRect(idx int, wr rect) rect {
w, h := clientSize(hwndMain)
rs := appRects(w, h)
if idx < 0 || idx >= len(rs) {
return wr
}
r := rs[idx]
if vertical {
r = mapRect(r, barHeight)
}
return rect{wr.Left + r.Left, wr.Top + r.Top, wr.Left + r.Right, wr.Top + r.Bottom}
}
func previewShow(idx int) {
if pvHwnd == 0 || idx < 0 || idx >= len(apps) {
return
}
a := apps[idx]
previewDropThumb()
iconic, _, _ := pIsIconic.Call(a.hwnd)
pvIconic = iconic != 0
var tw, th int32
if !pvIconic {
var t uintptr
hr, _, _ := pDwmRegisterThumbnail.Call(pvHwnd, a.hwnd, uintptr(unsafe.Pointer(&t)))
if hr == 0 && t != 0 {
pvThumb = t
var sz size
hr2, _, _ := pDwmQueryThumbnailSourceSize.Call(t, uintptr(unsafe.Pointer(&sz)))
if hr2 == 0 && sz.CX > 0 && sz.CY > 0 {
f := min(float64(px(260))/float64(sz.CX), float64(px(160))/float64(sz.CY), 1.0)
tw = max(int32(float64(sz.CX)*f), 1)
th = max(int32(float64(sz.CY)*f), 1)
} else {
previewDropThumb()
pvIconic = true
}
} else {
pvIconic = true
}
}
if pvIconic {
tw, th = px(200), px(110)
}
pad, titleH, gap := px(8), px(22), px(4)
cw := max(px(180), tw+2*pad)
ch := pad + titleH + gap + th + pad
pvTitleR = rect{pad, pad, cw - pad, pad + titleH}
tx, ty := (cw-tw)/2, pad+titleH+gap
pvThumbR = rect{tx, ty, tx + tw, ty + th}
var wr rect
pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr)))
ir := previewIconRect(idx, 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 = (ir.Top+ir.Bottom)/2 - ch/2
} else {
x = (ir.Left+ir.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)
pvSrc, pvTitle, pvIcon = a.hwnd, a.title, a.icon
pSetWindowPos.Call(pvHwnd, hwndTopmost, uintptr(x), uintptr(y), uintptr(cw), uintptr(ch), swpNoActivate|swpShowWindow)
if pvThumb != 0 {
props := dwmThumbProps{Flags: dwmTnpDest | dwmTnpOpacity | dwmTnpVisible, Dest: pvThumbR, Opacity: 255, Visible: 1}
pDwmUpdateThumbnailProperties.Call(pvThumb, uintptr(unsafe.Pointer(&props)))
}
pInvalidateRect.Call(pvHwnd, 0, 1)
}
func inRect(r rect, p point) bool {
return p.X >= r.Left && p.X < r.Right && p.Y >= r.Top && p.Y < r.Bottom
}
// previewKick starts the short timer that watches where the mouse is.
func previewKick() {
if pvHwnd == 0 || pvTimer {
return
}
pSetTimer.Call(hwndMain, previewTimerID, 60, 0)
pvTimer = true
}
func previewStopTimer() {
if pvTimer {
pKillTimer.Call(hwndMain, previewTimerID)
pvTimer = false
}
}
// previewTick decides what the preview should be doing right now, from where
// the mouse is. It runs only while the mouse is near the bar.
func previewTick() {
defer func() {
if r := recover(); r != nil {
previewHide()
}
}()
if pvHwnd == 0 {
return
}
var cp point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp)))
var wr rect
pGetWindowRect.Call(hwndMain, uintptr(unsafe.Pointer(&wr)))
overBar := inRect(wr, cp)
btn, _, _ := pGetAsyncKeyState.Call(vkLButton)
if btn&0x8000 != 0 || pvBlock || dragging {
previewHide()
pvCand = 0
if !overBar {
previewStopTimer()
}
return
}
idx := -1
var raw uintptr
if overBar {
x := cp.X - wr.Left
if vertical {
x = cp.Y - wr.Top
}
idx = appIndexAt(hwndMain, x)
if idx >= 0 && idx < len(apps) {
raw = apps[idx].hwnd
}
}
target := raw
if raw != 0 && raw == pvSupp {
target = 0 // just clicked: stay quiet until the mouse moves off this icon
} else {
pvSupp = 0
}
if target != 0 {
if pvSrc == target {
if apps[idx].title != pvTitle {
pvTitle = apps[idx].title
pInvalidateRect.Call(pvHwnd, 0, 1)
}
return
}
if pvCand != target {
pvCand = target
pvSince = time.Now()
}
if pvSrc != 0 || time.Since(pvSince) >= previewDelay {
previewShow(idx)
}
return
}
pvCand = 0
if pvSrc != 0 {
var pr rect
pGetWindowRect.Call(pvHwnd, uintptr(unsafe.Pointer(&pr)))
g := px(10) // covers the small gap between the icon and the preview
pr = rect{pr.Left - g, pr.Top - g, pr.Right + g, pr.Bottom + g}
if inRect(pr, cp) {
return
}
previewHide()
}
if !overBar {
previewStopTimer()
}
}
// previewSuppress hides the preview because the icon was clicked, and keeps it
// away until the mouse leaves that icon.
func previewSuppress() {
if pvSrc != 0 {
pvSupp = pvSrc
} else {
pvSupp = pvCand
}
pvCand = 0
previewHide()
}
// previewBlock keeps the preview down while a menu is open.
func previewBlock(on bool) {
pvBlock = on
if on {
previewSuppress()
}
}
// previewActivate runs when the preview itself is clicked: bring that window forward.
func previewActivate() {
h := pvSrc
previewHide()
if h == 0 {
return
}
iconic, _, _ := pIsIconic.Call(h)
if iconic != 0 {
pShowWindow.Call(h, swRestore)
}
pSetForegroundWindow.Call(h)
}
func previewShutdown() {
previewStopTimer()
previewHide()
if pvHwnd != 0 {
pDestroyWindow.Call(pvHwnd)
pvHwnd = 0
}
}
+277
View File
@@ -0,0 +1,277 @@
package main
// Radar for the weather flyout: a small map centered on the ZIP code with the
// last hour or so of rain radar over it, played as a loop.
//
// Radar pictures come from RainViewer (rainviewer.com, free, no account): a list
// of the latest frames, then one picture tile per frame. The map under them is
// Esri's dark gray map (gray base plus a layer of place names). Both are lists
// of square tiles on the same world grid, so a window around the ZIP code is
// cut out of the tiles and each radar frame is laid over the map.
//
// Nothing here runs until the panel is opened, and it all happens on a
// background goroutine; the finished frames are plain pixel arrays that the
// panel draws straight to the screen.
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
_ "image/jpeg"
_ "image/png"
"math"
"sync"
"time"
)
const (
radarW = 520 // pixels in a finished frame; 520 by 250 matches the panel's 312 by 150 picture
radarH = 250
radarFrames = 8 // the newest eight frames, 10 minutes apart
radarFresh = 5 * time.Minute
// One world pixel grid serves everything: 65536 pixels around the globe. That is
// RainViewer's 512 pixel tiles at zoom 7 and Esri's 256 pixel tiles at zoom 8.
radarWorld = 65536.0
radarTileRV = 512
radarZoomRV = 7
radarTileMap = 256
radarZoomMap = 8
)
type radarState struct {
key string // the place these frames are for
frames [][]byte
times []time.Time
loading bool
err string
fetched time.Time
}
var (
rdMu sync.Mutex
rd radarState
rdGen int
rdIdx int // which frame is on screen; touched only by the panel's own thread
)
func radarSnapshot() radarState {
rdMu.Lock()
defer rdMu.Unlock()
return rd
}
// radarEnsure starts a radar download if there is none for this place yet, or
// the one we have is old. Called when the panel opens and when a forecast lands.
func radarEnsure(force bool) {
s := wxSnapshot()
if !s.ok {
return
}
key := fmt.Sprintf("%.3f,%.3f", s.lat, s.lon)
rdMu.Lock()
same := rd.key == key
switch {
case same && rd.loading && !force:
rdMu.Unlock()
return
case same && len(rd.frames) > 0 && time.Since(rd.fetched) < radarFresh && !force:
rdMu.Unlock()
return
case same && rd.err != "" && len(rd.frames) == 0 && time.Since(rd.fetched) < time.Minute && !force:
rdMu.Unlock() // it just failed; don't hammer the service
return
}
if !same {
rd = radarState{key: key}
}
rd.loading = true
rd.err = ""
rdGen++
gen := rdGen
rdMu.Unlock()
go radarFetch(key, s.lat, s.lon, gen)
}
func radarFinish(gen int, key string, frames [][]byte, times []time.Time, errText string) {
rdMu.Lock()
if gen != rdGen || rd.key != key {
rdMu.Unlock()
return
}
rd.loading = false
rd.fetched = time.Now()
if frames != nil {
rd.frames, rd.times, rd.err = frames, times, ""
} else {
rd.err = errText
}
rdMu.Unlock()
weatherNotify()
}
// worldPixel is where a place falls on the 65536 pixel world grid (Web Mercator).
func worldPixel(lat, lon float64) (x, y float64) {
x = (lon + 180) / 360 * radarWorld
r := lat * math.Pi / 180
y = (1 - math.Log(math.Tan(r)+1/math.Cos(r))/math.Pi) / 2 * radarWorld
return
}
type tileJob struct {
url string
img image.Image
err error
}
// fetchTiles downloads a set of tile pictures, a few at a time.
func fetchTiles(jobs []*tileJob) {
var wg sync.WaitGroup
sem := make(chan struct{}, 6)
for _, j := range jobs {
wg.Add(1)
sem <- struct{}{}
go func(j *tileJob) {
defer wg.Done()
defer func() { <-sem }()
defer func() {
if r := recover(); r != nil {
j.err = fmt.Errorf("tile failed")
}
}()
b, err := wxGetBytes(j.url)
if err != nil {
j.err = err
return
}
j.img, _, j.err = image.Decode(bytes.NewReader(b))
}(j)
}
wg.Wait()
}
func radarFetch(key string, lat, lon float64, gen int) {
defer func() {
if r := recover(); r != nil {
radarFinish(gen, key, nil, nil, "The radar lookup failed.")
}
}()
// 1. The list of radar frames.
var idx struct {
Host string `json:"host"`
Radar struct {
Past []struct {
Time int64 `json:"time"`
Path string `json:"path"`
} `json:"past"`
} `json:"radar"`
}
if _, err := wxGetJSON("https://api.rainviewer.com/public/weather-maps.json", &idx); err != nil || idx.Host == "" || len(idx.Radar.Past) == 0 {
radarFinish(gen, key, nil, nil, "Radar isn't available right now.")
return
}
past := idx.Radar.Past
if len(past) > radarFrames {
past = past[len(past)-radarFrames:]
}
// 2. Which tiles cover a window centered on the place.
cx, cy := worldPixel(lat, lon)
x0 := int(math.Floor(cx - radarW/2))
y0 := int(math.Floor(cy - radarH/2))
span := func(a, b int, size int) (lo, hi int) {
lo = int(math.Floor(float64(a) / float64(size)))
hi = int(math.Floor(float64(b) / float64(size)))
return
}
// 3. The map: gray base plus place names, from tiles 256 pixels wide at zoom 8.
base := image.NewRGBA(image.Rect(0, 0, radarW, radarH))
draw.Draw(base, base.Bounds(), image.NewUniform(color.RGBA{34, 34, 38, 255}), image.Point{}, draw.Src)
mx0, mx1 := span(x0, x0+radarW-1, radarTileMap)
my0, my1 := span(y0, y0+radarH-1, radarTileMap)
type placed struct {
job *tileJob
ox, oy int
}
var mapTiles []placed
var jobs []*tileJob
for _, layer := range []string{"World_Dark_Gray_Base", "World_Dark_Gray_Reference"} {
for ty := my0; ty <= my1; ty++ {
for tx := mx0; tx <= mx1; tx++ {
j := &tileJob{url: fmt.Sprintf("https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/%s/MapServer/tile/%d/%d/%d",
layer, radarZoomMap, ty, tx)}
mapTiles = append(mapTiles, placed{j, tx*radarTileMap - x0, ty*radarTileMap - y0})
jobs = append(jobs, j)
}
}
}
// 4. Every radar frame's tiles, 512 pixels wide at zoom 7.
rx0, rx1 := span(x0, x0+radarW-1, radarTileRV)
ry0, ry1 := span(y0, y0+radarH-1, radarTileRV)
type frameTiles struct {
t time.Time
tiles []placed
}
frames := make([]frameTiles, len(past))
for i, p := range past {
frames[i].t = time.Unix(p.Time, 0)
for ty := ry0; ty <= ry1; ty++ {
for tx := rx0; tx <= rx1; tx++ {
j := &tileJob{url: fmt.Sprintf("%s%s/%d/%d/%d/%d/2/1_1.png", idx.Host, p.Path, radarTileRV, radarZoomRV, tx, ty)}
frames[i].tiles = append(frames[i].tiles, placed{j, tx*radarTileRV - x0, ty*radarTileRV - y0})
jobs = append(jobs, j)
}
}
}
fetchTiles(jobs)
// The map must have come through; a missing radar frame is just skipped.
for _, m := range mapTiles {
if m.job.err != nil || m.job.img == nil {
radarFinish(gen, key, nil, nil, "The map for radar didn't load.")
return
}
b := m.job.img.Bounds()
draw.Draw(base, image.Rect(m.ox, m.oy, m.ox+b.Dx(), m.oy+b.Dy()), m.job.img, b.Min, draw.Over)
}
alpha := &image.Uniform{color.Alpha{A: 215}}
var out [][]byte
var times []time.Time
for _, f := range frames {
layer := image.NewRGBA(base.Bounds())
good := true
for _, t := range f.tiles {
if t.job.err != nil || t.job.img == nil {
good = false
break
}
b := t.job.img.Bounds()
draw.Draw(layer, image.Rect(t.ox, t.oy, t.ox+b.Dx(), t.oy+b.Dy()), t.job.img, b.Min, draw.Over)
}
if !good {
continue
}
comp := image.NewRGBA(base.Bounds())
copy(comp.Pix, base.Pix)
draw.DrawMask(comp, comp.Bounds(), layer, image.Point{}, alpha, image.Point{}, draw.Over)
// Windows wants blue, green, red order.
bgra := make([]byte, len(comp.Pix))
for i := 0; i+3 < len(comp.Pix); i += 4 {
bgra[i], bgra[i+1], bgra[i+2], bgra[i+3] = comp.Pix[i+2], comp.Pix[i+1], comp.Pix[i], 255
}
out = append(out, bgra)
times = append(times, f.t)
}
if len(out) == 0 {
radarFinish(gen, key, nil, nil, "Radar isn't available right now.")
return
}
radarFinish(gen, key, out, times, "")
}
+98
View File
@@ -0,0 +1,98 @@
package main
// Drawing the radar picture inside the weather panel, and stepping the loop.
import (
"unsafe"
)
var (
pStretchDIBits = gdi32.NewProc("StretchDIBits")
pSetViewportOrgEx = gdi32.NewProc("SetViewportOrgEx")
)
// wxRadarFits reports whether the panel with its radar picture fits on the
// screen, with some room left for the bar. On a small or heavily scaled screen
// the radar is left out and the rest of the panel stays as it was.
func wxRadarFits() bool {
_, sh := screenSize()
return px(wxFullH+wxRadarH) <= sh-px(90)
}
// radarAdvance moves the loop to its next frame. The newest frame is held for a
// few beats before it starts over.
func radarAdvance() {
if !wxShown || !wxRadarFits() {
return
}
rs := radarSnapshot()
n := len(rs.frames)
if n < 2 {
return
}
rdIdx %= n
if rdIdx == n-1 && rdHold < 3 {
rdHold++
return
}
rdHold = 0
rdIdx = (rdIdx + 1) % n
flyRefresh(wxHwnd)
}
func radarBox(hdc uintptr, r rect) {
t := px(1)
fillRaw(hdc, rect{r.Left, r.Top, r.Right, r.Top + t}, colRule)
fillRaw(hdc, rect{r.Left, r.Bottom - t, r.Right, r.Bottom}, colRule)
fillRaw(hdc, rect{r.Left, r.Top, r.Left + t, r.Bottom}, colRule)
fillRaw(hdc, rect{r.Right - t, r.Top, r.Right, r.Bottom}, colRule)
}
// radarDraw paints the radar picture (or a short message while there isn't one)
// into the rectangle r. The panel is painted at double size, so px() here is
// already the double size distance.
func radarDraw(hdc uintptr, r rect) {
rs := radarSnapshot()
w, h := r.Right-r.Left, r.Bottom-r.Top
if len(rs.frames) == 0 {
fillRaw(hdc, r, rgb(22, 22, 27))
msg := "Loading radar..."
if rs.err != "" {
msg = rs.err
}
wxText(hdc, msg, r, fText, colDim, dtCenter|dtVCenter|dtSingleLine)
radarBox(hdc, r)
return
}
i := rdIdx % len(rs.frames)
bmi := bitmapInfoHeader{Width: radarW, Height: -radarH, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
pSetStretchBltMode.Call(hdc, halftone)
pSetBrushOrgEx.Call(hdc, 0, 0, 0)
pStretchDIBits.Call(hdc,
uintptr(r.Left), uintptr(r.Top), uintptr(w), uintptr(h),
0, 0, radarW, radarH,
uintptr(unsafe.Pointer(&rs.frames[i][0])), uintptr(unsafe.Pointer(&bmi)), 0, srcCopy)
// You are here.
cx, cy := center(r)
circleRaw(hdc, cx, cy, px(5), rgb(245, 245, 245))
circleRaw(hdc, cx, cy, px(3), rgb(235, 70, 70))
// When this frame is from.
back := rgb(22, 22, 27)
label := "Radar"
if i < len(rs.times) {
label += " " + rs.times[i].Format("3:04 PM")
}
fillRaw(hdc, rect{r.Left, r.Top, r.Left + px(104), r.Top + px(19)}, back)
wxText(hdc, label, rect{r.Left + px(6), r.Top, r.Left + px(104), r.Top + px(19)}, fSmall, colText, dtLeft|dtVCenter|dtSingleLine)
// Where the pictures come from.
fillRaw(hdc, rect{r.Right - px(92), r.Bottom - px(14), r.Right, r.Bottom}, back)
wxText(hdc, "RainViewer, Esri", rect{r.Right - px(92), r.Bottom - px(14), r.Right - px(4), r.Bottom}, fTiny, colDim, dtRight|dtVCenter|dtSingleLine)
radarBox(hdc, r)
}
+390
View File
@@ -0,0 +1,390 @@
package main
// Painting the bar smoothly on a see-through background.
//
// Drawing icons and text straight onto a dark bitmap leaves a dark fringe
// around them once the background is made see-through. So the bar is painted
// in layers: one layer with only the backgrounds, and the icons, text and
// symbols drawn twice (once on black, once on white) at double size. Comparing
// the two copies shows exactly how see-through every edge pixel is, and
// shrinking back down gives smooth edges with no dark outline.
import (
"math"
"os"
"path/filepath"
"strconv"
"strings"
"unsafe"
)
const (
superSample = 2
mfPopup = 0x0010
menuLogoColorBase = 100
menuClockColorBase = 120
menuIconColorBase = 140
)
var (
fontTime2 uintptr
fontApp2 uintptr
)
// initSuperFonts makes the double size fonts used for the smooth pass.
func initSuperFonts() {
scale *= superSample
fontTime2 = makeFont(px(13), 400)
fontApp2 = makeFont(px(12), 600)
scale /= superSample
}
// ---------- colors ----------
type namedColor struct {
name string
r, g, b int
}
var palette = []namedColor{
{"White", 245, 245, 245},
{"Blue", 0, 120, 212},
{"Sky blue", 90, 190, 255},
{"Green", 70, 200, 110},
{"Yellow", 255, 205, 60},
{"Orange", 255, 140, 40},
{"Red", 235, 70, 70},
{"Pink", 255, 125, 195},
{"Purple", 175, 115, 240},
{"Black", 0, 0, 0},
}
var (
logoIdx = 1 // Blue, like the real Windows logo
clockIdx = 0 // White
iconIdx = 0 // White: battery, volume, wifi and the hidden-icons arrow
)
func colorOf(i int) uintptr {
if i < 0 || i >= len(palette) {
i = 0
}
c := palette[i]
r, g, b := styleColor(c.r, c.g, c.b)
return rgb(r, g, b)
}
func logoColor() uintptr { return colorOf(logoIdx) }
func clockColor() uintptr { return colorOf(clockIdx) }
func iconColor() uintptr { return colorOf(iconIdx) }
// iconDim is the color of the "off" bars on the volume and wifi icons.
func iconDim() uintptr {
c := palette[iconIdx]
if c.r+c.g+c.b < 300 { // a dark icon color: the off bars are lighter
return rgb(140, 140, 150)
}
return rgb(110, 110, 120)
}
func colorsFile() string { return filepath.Join(dataDir(), "colors.txt") }
func loadColors() {
b, err := os.ReadFile(colorsFile())
if err != nil {
return
}
parts := strings.Split(strings.TrimSpace(string(b)), ",")
if len(parts) < 2 || len(parts) > 3 {
return
}
vals := []int{0, 0, 0}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 || n >= len(palette) {
return
}
vals[i] = n
}
logoIdx, clockIdx, iconIdx = vals[0], vals[1], vals[2]
}
func saveColors() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(colorsFile(), []byte(strconv.Itoa(logoIdx)+","+strconv.Itoa(clockIdx)+","+strconv.Itoa(iconIdx)), 0o644)
}
// addColorMenus adds the two color pickers as sub menus.
func addColorMenus(menu uintptr) {
build := func(base uintptr, cur int, title string) {
sub, _, _ := pCreatePopupMenu.Call()
for i, c := range palette {
var flags uintptr
if i == cur {
flags = mfChecked
}
pAppendMenu.Call(sub, flags, base+uintptr(i), uintptr(unsafe.Pointer(u16(c.name))))
}
pAppendMenu.Call(menu, mfPopup, sub, uintptr(unsafe.Pointer(u16(title))))
}
build(menuLogoColorBase, logoIdx, "Windows logo color")
build(menuClockColorBase, clockIdx, "Clock color")
build(menuIconColorBase, iconIdx, "Tray icon color")
addStyleMenu(menu)
}
func handleColorCommand(cmd uintptr) bool {
n := uintptr(len(palette))
switch {
case cmd >= menuLogoColorBase && cmd < menuLogoColorBase+n:
logoIdx = int(cmd - menuLogoColorBase)
case cmd >= menuClockColorBase && cmd < menuClockColorBase+n:
clockIdx = int(cmd - menuClockColorBase)
case cmd >= menuIconColorBase && cmd < menuIconColorBase+n:
iconIdx = int(cmd - menuIconColorBase)
case handleStyleCommand(cmd):
return true
default:
return false
}
saveColors()
return true
}
// ---------- painting ----------
// renderLayer paints one layer of the bar (w by h in the horizontal layout)
// and returns its pixels at the real orientation. fills and fg choose which
// parts are painted; base is the color everything is painted onto.
func renderLayer(screen uintptr, w, h int32, fills, fg bool, base uintptr) []uint32 {
layerFills, layerFg = fills, fg
defer func() { layerFills, layerFg = true, true }()
mem, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(mem)
bmi := bitmapInfoHeader{Width: w, Height: -h, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
var bits unsafe.Pointer
bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0,
uintptr(unsafe.Pointer(&bits)), 0, 0)
if bmp == 0 || bits == nil {
return nil
}
defer pDeleteObject.Call(bmp)
old, _, _ := pSelectObject.Call(mem, bmp)
defer pSelectObject.Call(mem, old)
fillRaw(mem, rect{0, 0, w, h}, base)
sr := startRect(w, h)
if hoverStart {
fill(mem, sr, rgb(58, 58, 68))
}
drawLogo(mem, sr)
drawApps(mem, w, h)
drawTray(mem, w, h)
pGdiFlush.Call()
src := unsafe.Slice((*uint32)(bits), int(w)*int(h))
if !vertical {
out := make([]uint32, len(src))
copy(out, src)
return out
}
// Turn a quarter turn, then put the icons and symbols back on upright.
fw, fh := h, w
bmiV := bitmapInfoHeader{Width: fw, Height: -fh, Planes: 1, BitCount: 32}
bmiV.Size = uint32(unsafe.Sizeof(bmiV))
var bitsV unsafe.Pointer
bmpV, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmiV)), 0,
uintptr(unsafe.Pointer(&bitsV)), 0, 0)
if bmpV == 0 || bitsV == nil {
return nil
}
defer pDeleteObject.Call(bmpV)
memV, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(memV)
oldV, _, _ := pSelectObject.Call(memV, bmpV)
defer pSelectObject.Call(memV, oldV)
dst := unsafe.Slice((*uint32)(bitsV), int(w)*int(h))
for y := int32(0); y < h; y++ {
for x := int32(0); x < w; x++ {
dst[int(x)*int(fw)+int(h-1-y)] = src[int(y)*int(w)+int(x)]
}
}
if fg {
for i, r := range appRects(w, h) {
if i < len(apps) {
drawAppGlyph(memV, mapRect(rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)}, h), apps[i])
}
}
for _, it := range trayItems(w, h) {
r := mapRect(it.r, h)
switch it.kind {
case trayBattery:
drawBattery(memV, r)
case trayVolume:
drawVolume(memV, r)
case trayWifi:
drawNetwork(memV, r)
case trayChevron:
drawChevron(memV, r)
case trayWeather:
drawWeatherIcon(memV, r)
case trayNews:
drawNewsIcon(memV, r)
case traySys:
drawSysIcon(memV, r)
}
}
pGdiFlush.Call()
}
out := make([]uint32, len(dst))
copy(out, dst)
return out
}
// avg4 averages the superSample x superSample block of pixels that makes up
// one real pixel, one color channel at a time.
func avg4(p []uint32, stride, x, y int) (r, g, b uint32) {
var sr, sg, sb uint32
for dy := 0; dy < superSample; dy++ {
for dx := 0; dx < superSample; dx++ {
c := p[(y*superSample+dy)*stride+x*superSample+dx]
sr += c >> 16 & 0xFF
sg += c >> 8 & 0xFF
sb += c & 0xFF
}
}
n := uint32(superSample * superSample)
return sr / n, sg / n, sb / n
}
// redraw paints the whole bar and hands it to Windows as a layered window
// with a transparency value for every pixel.
func redraw(hwnd uintptr) {
if hwnd == 0 {
return
}
// Shrink or grow the pill to fit what is in it, staying centered where it is.
pw, ph := pillSize()
var crc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&crc)))
if (crc.Right != pw || crc.Bottom != ph) && !dragging {
x, y := pillPos(pw, ph)
pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 0)
}
w, h := clientSize(hwnd)
if w <= 0 || h <= 0 {
return
}
fw, fh := w, h
if vertical {
fw, fh = h, w
}
screen, _, _ := pGetDC.Call(0)
defer pReleaseDC.Call(0, screen)
// Layer 1: backgrounds, at real size.
bgPix := renderLayer(screen, w, h, true, false, rgb(22, 22, 26))
// Layers 2 and 3: icons, text and symbols on black and on white, at double size.
savedScale, savedTime, savedApp := scale, fontTime, fontApp
scale *= superSample
fontTime, fontApp = fontTime2, fontApp2
onBlack := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(0, 0, 0))
onWhite := renderLayer(screen, w*superSample, h*superSample, false, true, rgb(255, 255, 255))
scale, fontTime, fontApp = savedScale, savedTime, savedApp
n := int(fw) * int(fh)
if len(bgPix) != n || len(onBlack) != n*superSample*superSample || len(onWhite) != len(onBlack) {
return
}
// The finished bitmap that Windows will show.
mem, _, _ := pCreateCompatibleDC.Call(screen)
defer pDeleteDC.Call(mem)
bmi := bitmapInfoHeader{Width: fw, Height: -fh, Planes: 1, BitCount: 32}
bmi.Size = uint32(unsafe.Sizeof(bmi))
var bits unsafe.Pointer
bmp, _, _ := pCreateDIBSection.Call(screen, uintptr(unsafe.Pointer(&bmi)), 0,
uintptr(unsafe.Pointer(&bits)), 0, 0)
if bmp == 0 || bits == nil {
return
}
defer pDeleteObject.Call(bmp)
old, _, _ := pSelectObject.Call(mem, bmp)
defer pSelectObject.Call(mem, old)
pix := unsafe.Slice((*uint32)(bits), n)
a := uint32(bgAlpha)
hoverA := max(a, 120)
length := float64(max(fw, fh))
rad := float64(min(fw, fh)) / 2
stride := int(fw) * superSample
for i := range pix {
x, y := i%int(fw), i/int(fw)
// Background layer: the pill color or a hover highlight, at its own see-through level.
c := bgPix[i] & 0x00FFFFFF
bgA := a
if c != colBg {
bgA = hoverA
}
bgR := (c >> 16 & 0xFF) * bgA / 255
bgG := (c >> 8 & 0xFF) * bgA / 255
bgB := (c & 0xFF) * bgA / 255
// Foreground: how solid is this pixel, and what color is it.
br, bgn, bb := avg4(onBlack, stride, x, y)
wr, wg, wb := avg4(onWhite, stride, x, y)
d := (sub0(wr, br) + sub0(wg, bgn) + sub0(wb, bb)) / 3
fa := 255 - min(d, 255) // 255 where the two copies match (solid), 0 where they differ fully
fr, fg, fb := min(br, fa), min(bgn, fa), min(bb, fa)
// Foreground over background.
inv := 255 - fa
oa := fa + bgA*inv/255
or := fr + bgR*inv/255
og := fg + bgG*inv/255
ob := fb + bgB*inv/255
// Rounded ends: how much of this pixel is inside the pill.
along := float64(x) + 0.5
across := float64(y) + 0.5
if vertical {
along, across = across, along
}
da := 0.0
if along < rad {
da = rad - along
} else if along > length-rad {
da = along - (length - rad)
}
cov := math.Max(0, math.Min(1, rad-math.Hypot(da, across-rad)+0.5))
sc := func(v uint32) uint32 { return uint32(float64(v) * cov) }
pix[i] = sc(oa)<<24 | sc(or)<<16 | sc(og)<<8 | sc(ob)
}
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
dst := point{wr.Left, wr.Top}
sz := size{fw, fh}
src := point{0, 0}
blend := blendFunction{Op: 0, Flags: 0, Alpha: 255, Format: 1} // AC_SRC_OVER, AC_SRC_ALPHA
pUpdateLayeredWindow.Call(hwnd, screen,
uintptr(unsafe.Pointer(&dst)), uintptr(unsafe.Pointer(&sz)),
mem, uintptr(unsafe.Pointer(&src)), 0,
uintptr(unsafe.Pointer(&blend)), ulwAlpha)
}
func sub0(a, b uint32) uint32 {
if a > b {
return a - b
}
return 0
}
+368
View File
@@ -0,0 +1,368 @@
package main
// The settings window: everything the right-click menu can change, in one
// place. It opens from "MirrorBar settings..." in the menu. Changes apply the
// moment you make them, and the window stays in step if the menu is used too.
import (
"strconv"
"syscall"
"unsafe"
)
var (
pSendMessage = user32.NewProc("SendMessageW")
pSetWindowText = user32.NewProc("SetWindowTextW")
pIsDialogMessage = user32.NewProc("IsDialogMessageW")
pAdjustWindowRectEx = user32.NewProc("AdjustWindowRectEx")
pInitCommonControls = syscall.NewLazyDLL("comctl32.dll").NewProc("InitCommonControlsEx")
pGetFocus = user32.NewProc("GetFocus")
)
const (
menuSettingsID = 45
wmCommand = 0x0111
wmHScroll = 0x0114
wmSetFont = 0x0030
wsChild = 0x40000000
wsTabStop = 0x00010000
wsVScroll = 0x00200000
wsWindowFrame = 0x00C80000 // caption, system menu, border: a plain window that can't be resized
wsBorder = 0x00800000
bsPushButton = 0x0000
bsDefPushButton = 0x0001
bsAutoCheckBox = 0x0003
cbsDropDownList = 0x0003
tbsNoTicks = 0x0010
esAutoHScroll = 0x0080
esNumber = 0x2000
emSetLimitText = 0x00C5
enChange = 0x0300
bmGetCheck = 0x00F0
bmSetCheck = 0x00F1
cbAddString = 0x0143
cbGetCurSel = 0x0147
cbSetCurSel = 0x014E
tbmGetPos = 0x0400
tbmSetPos = 0x0405
tbmSetRange = 0x0406
cbnSelChange = 1
tbEndTrack = 8
colorBtnFace = 15
idAlpha = 200
idAlphaValue = 201
idLogo = 202
idClock = 203
idTrayIcons = 204
idStyle = 205
idVertical = 206
idAutostart = 207
idResetPos = 208
idResetWidth = 209
idClose = 210
idZip = 211
idZipStatus = 212
idShowWeather = 213
idShowNews = 214
idShowSys = 215
idPanelFade = 216
)
var (
hwndSettings uintptr
settingsClass bool
settingsFont uintptr
ctlAlpha, ctlAlphaValue, ctlLogo, ctlClock, ctlTrayIcons, ctlStyle uintptr
ctlVertical, ctlAutostart uintptr
ctlZip, ctlZipStatus uintptr
ctlShowWeather, ctlShowNews, ctlShowSys, ctlPanelFade uintptr
zipSyncing bool // true while the program itself is filling in the ZIP box
)
func boolWP(b bool) uintptr {
if b {
return 1
}
return 0
}
// makeControl creates one child control; sizes are in 96 dpi units.
func makeControl(parent, inst uintptr, class, text string, style uintptr, x, y, w, h int, id uintptr) uintptr {
hw, _, _ := pCreateWindowEx.Call(0,
uintptr(unsafe.Pointer(u16(class))), uintptr(unsafe.Pointer(u16(text))),
style|wsChild|wsVisible,
uintptr(px(float64(x))), uintptr(px(float64(y))), uintptr(px(float64(w))), uintptr(px(float64(h))),
parent, id, inst, 0)
if hw != 0 && settingsFont != 0 {
pSendMessage.Call(hw, wmSetFont, settingsFont, 1)
}
return hw
}
func openSettings() {
if hwndSettings != 0 {
pShowWindow.Call(hwndSettings, swRestore)
pSetForegroundWindow.Call(hwndSettings)
settingsSync()
return
}
inst, _, _ := pGetModuleHandle.Call(0)
className := u16("MirrorBarSettings")
if !settingsClass {
cursor, _, _ := pLoadCursor.Call(0, idcArrow)
wc := wndClassEx{
WndProc: syscall.NewCallback(settingsProc),
Instance: inst,
Cursor: cursor,
Background: colorBtnFace + 1,
ClassName: className,
}
wc.Size = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
icc := struct{ Size, Classes uint32 }{8, 0x4} // ICC_BAR_CLASSES: the slider
pInitCommonControls.Call(uintptr(unsafe.Pointer(&icc)))
settingsClass = true
}
if settingsFont == 0 {
settingsFont = makeFont(px(13), 400)
}
r := rect{0, 0, px(400), px(488)}
pAdjustWindowRectEx.Call(uintptr(unsafe.Pointer(&r)), wsWindowFrame, 0, 0)
ow, oh := r.Right-r.Left, r.Bottom-r.Top
sw, sh := screenSize()
hw, _, _ := pCreateWindowEx.Call(0,
uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(u16("MirrorBar settings"))),
wsWindowFrame,
uintptr(max(0, (sw-ow)/2)), uintptr(max(0, (sh-oh)/2)), uintptr(ow), uintptr(oh),
0, 0, inst, 0)
if hw == 0 {
return
}
label := func(text string, y int) {
makeControl(hw, inst, "STATIC", text, 0, 16, y+4, 150, 20, 0)
}
combo := func(y int, id uintptr) uintptr {
return makeControl(hw, inst, "COMBOBOX", "", cbsDropDownList|wsVScroll|wsTabStop, 170, y, 214, 200, id)
}
label("Background opacity", 16)
ctlAlpha = makeControl(hw, inst, "msctls_trackbar32", "", tbsNoTicks|wsTabStop, 166, 14, 170, 28, idAlpha)
ctlAlphaValue = makeControl(hw, inst, "STATIC", "", 0, 344, 20, 44, 20, idAlphaValue)
pSendMessage.Call(ctlAlpha, tbmSetRange, 1, uintptr(3|255<<16))
label("Windows logo color", 60)
ctlLogo = combo(60, idLogo)
label("Clock color", 96)
ctlClock = combo(96, idClock)
label("Tray icon color", 132)
ctlTrayIcons = combo(132, idTrayIcons)
label("Icon style", 168)
ctlStyle = combo(168, idStyle)
for _, c := range []uintptr{ctlLogo, ctlClock, ctlTrayIcons} {
for _, p := range palette {
pSendMessage.Call(c, cbAddString, 0, uintptr(unsafe.Pointer(u16(p.name))))
}
}
for _, n := range styleNames {
pSendMessage.Call(ctlStyle, cbAddString, 0, uintptr(unsafe.Pointer(u16(n))))
}
label("ZIP code", 204)
ctlZip = makeControl(hw, inst, "EDIT", "", esNumber|esAutoHScroll|wsBorder|wsTabStop, 170, 204, 90, 24, idZip)
pSendMessage.Call(ctlZip, emSetLimitText, 5, 0)
ctlZipStatus = makeControl(hw, inst, "STATIC", "", 0, 16, 236, 368, 20, idZipStatus)
ctlShowWeather = makeControl(hw, inst, "BUTTON", "Show weather on the bar", bsAutoCheckBox|wsTabStop, 16, 262, 368, 22, idShowWeather)
ctlShowNews = makeControl(hw, inst, "BUTTON", "Show local news on the bar", bsAutoCheckBox|wsTabStop, 16, 290, 368, 22, idShowNews)
ctlShowSys = makeControl(hw, inst, "BUTTON", "Show system stats on the bar", bsAutoCheckBox|wsTabStop, 16, 318, 368, 22, idShowSys)
ctlPanelFade = makeControl(hw, inst, "BUTTON", "Panels match the bar's transparency", bsAutoCheckBox|wsTabStop, 16, 346, 368, 22, idPanelFade)
ctlVertical = makeControl(hw, inst, "BUTTON", "Stand the bar up at the right edge (vertical)", bsAutoCheckBox|wsTabStop, 16, 374, 368, 22, idVertical)
ctlAutostart = makeControl(hw, inst, "BUTTON", "Start MirrorBar when I sign in", bsAutoCheckBox|wsTabStop, 16, 402, 368, 22, idAutostart)
makeControl(hw, inst, "BUTTON", "Reset position", bsPushButton|wsTabStop, 16, 442, 116, 28, idResetPos)
makeControl(hw, inst, "BUTTON", "Reset bar width", bsPushButton|wsTabStop, 140, 442, 116, 28, idResetWidth)
makeControl(hw, inst, "BUTTON", "Close", bsDefPushButton|wsTabStop, 292, 442, 92, 28, idClose)
hwndSettings = hw
settingsSync()
pShowWindow.Call(hw, 1)
pSetForegroundWindow.Call(hw)
}
// settingsSync makes every control show the current setting.
func settingsSync() {
if hwndSettings == 0 {
return
}
pSendMessage.Call(ctlAlpha, tbmSetPos, 1, uintptr(bgAlpha))
pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%"))))
pSendMessage.Call(ctlLogo, cbSetCurSel, uintptr(logoIdx), 0)
pSendMessage.Call(ctlClock, cbSetCurSel, uintptr(clockIdx), 0)
pSendMessage.Call(ctlTrayIcons, cbSetCurSel, uintptr(iconIdx), 0)
pSendMessage.Call(ctlStyle, cbSetCurSel, uintptr(iconMode), 0)
pSendMessage.Call(ctlShowWeather, bmSetCheck, boolWP(showWeather), 0)
pSendMessage.Call(ctlShowNews, bmSetCheck, boolWP(showNews), 0)
pSendMessage.Call(ctlShowSys, bmSetCheck, boolWP(showSys), 0)
pSendMessage.Call(ctlPanelFade, bmSetCheck, boolWP(flyMatchBar), 0)
pSendMessage.Call(ctlVertical, bmSetCheck, boolWP(vertical), 0)
pSendMessage.Call(ctlAutostart, bmSetCheck, boolWP(autostartEnabled()), 0)
// Leave the ZIP box alone while the person is typing in it.
if f, _, _ := pGetFocus.Call(); f != ctlZip && zipText() != wxZip {
zipSyncing = true
pSetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(u16(wxZip))))
zipSyncing = false
}
settingsZipStatusUpdate()
}
// zipText is what is typed in the ZIP box right now.
func zipText() string {
var buf [32]uint16
n, _, _ := pGetWindowText.Call(ctlZip, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
return syscall.UTF16ToString(buf[:n])
}
// settingsZipStatusUpdate refreshes the line under the ZIP box ("Showing weather for ...").
func settingsZipStatusUpdate() {
if hwndSettings == 0 || ctlZipStatus == 0 {
return
}
pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16(zipStatusText()))))
}
// zipEdited runs each time the ZIP box changes. Five digits turn the weather on
// for that ZIP code; an empty box turns it off.
func zipEdited() {
z := onlyDigits(zipText())
switch {
case len(z) == 5:
weatherSetZip(z)
case z == "":
weatherSetZip("")
default:
pSetWindowText.Call(ctlZipStatus, uintptr(unsafe.Pointer(u16("A ZIP code has 5 digits."))))
return
}
settingsZipStatusUpdate()
}
func comboChoice(c uintptr) int {
r, _, _ := pSendMessage.Call(c, cbGetCurSel, 0, 0)
return int(int32(r))
}
func checked(c uintptr) bool {
r, _, _ := pSendMessage.Call(c, bmGetCheck, 0, 0)
return r == 1
}
func settingsCommand(id, note uintptr) {
switch id {
case 1, 2: // Enter and Esc
pDestroyWindow.Call(hwndSettings)
case idClose:
pDestroyWindow.Call(hwndSettings)
case idLogo, idClock, idTrayIcons:
if note != cbnSelChange {
return
}
switch id {
case idLogo:
if i := comboChoice(ctlLogo); i >= 0 {
logoIdx = i
}
case idClock:
if i := comboChoice(ctlClock); i >= 0 {
clockIdx = i
}
case idTrayIcons:
if i := comboChoice(ctlTrayIcons); i >= 0 {
iconIdx = i
}
}
saveColors()
redraw(hwndMain)
flyRefreshAll()
case idStyle:
if note != cbnSelChange {
return
}
if i := comboChoice(ctlStyle); i >= 0 && i < len(styleNames) {
iconMode = i
saveIconMode()
styleCacheClear()
redraw(hwndMain)
}
case idZip:
if note == enChange && !zipSyncing {
zipEdited()
}
case idShowWeather:
setShowWeather(checked(ctlShowWeather))
case idShowNews:
setShowNews(checked(ctlShowNews))
case idShowSys:
setShowSys(checked(ctlShowSys))
case idPanelFade:
setFlyMatchBar(checked(ctlPanelFade))
case idVertical:
vertical = checked(ctlVertical)
saveOrient()
resetPos(hwndMain)
case idAutostart:
setAutostart(checked(ctlAutostart))
settingsSync()
case idResetPos:
resetPos(hwndMain)
case idResetWidth:
leftPref = 0
saveLeftPref()
redraw(hwndMain)
}
}
func settingsProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
defer func() {
if r := recover(); r != nil {
result = 0
}
}()
switch uint32(m) {
case wmCommand:
settingsCommand(wparam&0xFFFF, wparam>>16&0xFFFF)
return 0
case wmHScroll:
if lparam == ctlAlpha && ctlAlpha != 0 {
pos, _, _ := pSendMessage.Call(ctlAlpha, tbmGetPos, 0, 0)
n := int(pos)
if n >= 3 && n <= 255 && n != bgAlpha {
bgAlpha = n
pSetWindowText.Call(ctlAlphaValue, uintptr(unsafe.Pointer(u16(strconv.Itoa(bgAlpha*100/255)+"%"))))
redraw(hwndMain)
flyRefreshAll()
}
if wparam&0xFFFF == tbEndTrack {
saveAlpha()
}
}
return 0
case wmClose:
pDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
hwndSettings = 0
return 0
}
r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam)
return r
}
+270
View File
@@ -0,0 +1,270 @@
package main
// The system stats flyout: a little monitor on the bar that opens a panel with
// the sort of thing neofetch prints (OS, CPU, memory, disks, uptime...). Click a
// line to copy it, or click the header to copy everything as plain text that can
// be pasted into any other program.
import (
"syscall"
"time"
"unsafe"
)
const (
sysW = 420.0
sysHead = 44.0
sysRow_ = 24.0
sysFoot = 26.0
sysRefreshTimerID = 2
)
var (
sysHwnd uintptr
sysShown bool
sysPrevBtn bool
sysHover = -1
sysRows []sysRow
sysCopied string // what the header says after a copy: "Copied" or "Copy failed"
sysCopiedAt time.Time
sysTick int
)
// ---------- the button on the bar ----------
func drawSysIcon(hdc uintptr, r rect) {
if !layerFg {
return
}
col := iconColor()
cx, cy := center(r)
e := px(1)
l, t, rt, b := cx-px(6), cy-px(5.5), cx+px(6), cy+px(2.5)
fillRaw(hdc, rect{l, t, rt, t + e}, col)
fillRaw(hdc, rect{l, b - e, rt, b}, col)
fillRaw(hdc, rect{l, t, l + e, b}, col)
fillRaw(hdc, rect{rt - e, t, rt, b}, col)
fillRaw(hdc, rect{cx - px(1), b, cx + px(1), cy + px(4.5)}, col) // stand
fillRaw(hdc, rect{cx - px(3), cy + px(4.5), cx + px(3), cy + px(5.5)}, col)
fillRaw(hdc, rect{cx - px(3.5), cy - px(0.5), cx - px(2), cy + px(1.5)}, col) // little bars on the screen
fillRaw(hdc, rect{cx - px(1), cy - px(2.5), cx + px(0.5), cy + px(1.5)}, col)
fillRaw(hdc, rect{cx + px(2), cy - px(1.5), cx + px(3.5), cy + px(1.5)}, col)
}
// ---------- the panel window ----------
func sysInit(inst uintptr) {
cursor, _, _ := pLoadCursor.Call(0, idcArrow)
className := u16("MirrorBarSys")
wc := wndClassEx{
WndProc: syscall.NewCallback(sysProc),
Instance: inst,
Cursor: cursor,
ClassName: className,
}
wc.Size = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
sysHwnd, _, _ = pCreateWindowEx.Call(
wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(u16(""))),
wsPopup,
0, 0, 10, 10,
0, 0, inst, 0)
}
func sysProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
defer func() {
if r := recover(); r != nil {
result = 0 // the flyout is optional; never take the bar down with it
}
}()
switch uint32(m) {
case wmEraseBkgnd:
return 1
case wmMouseActivate:
return maNoActivate
case wmPaint:
flyPaint(hwnd, sysDraw)
return 0
case wmTimer:
if wparam == sysRefreshTimerID {
sysRows = sysGather() // uptime and memory move
flyRefresh(sysHwnd)
return 0
}
sysPoll()
return 0
case wmSetCursor:
if sysOverButton() {
h, _, _ := pLoadCursor.Call(0, idcHandCursor)
pSetCursor.Call(h)
return 1
}
case wmLButtonUp:
sysClick(int32(int16(lparam&0xFFFF)), int32(int16(lparam>>16&0xFFFF)))
return 0
}
r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam)
return r
}
// sysOverButton is true when the mouse is on something clickable: a line or the header.
func sysOverButton() bool {
var cp point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp)))
var fr rect
pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr)))
if !inRect(fr, cp) {
return false
}
y := cp.Y - fr.Top
return y < px(sysHead) || sysRowAt(y) >= 0
}
func sysToggle() {
if !showSys {
return
}
if sysShown {
sysHide()
return
}
if sysHwnd == 0 {
return
}
previewHide()
weatherHide() // one panel at a time
newsHide()
sysRows = sysGather()
sysShown = true
sysPrevBtn = true // ignore a button that is still held from the click that opened this
sysHover = -1
sysCopied = ""
sysPlace()
pSetTimer.Call(sysHwnd, wxPollTimerID, 80, 0)
pSetTimer.Call(sysHwnd, sysRefreshTimerID, 1500, 0)
}
func sysHide() {
if !sysShown {
return
}
sysShown = false
sysHover = -1
pKillTimer.Call(sysHwnd, wxPollTimerID)
pKillTimer.Call(sysHwnd, sysRefreshTimerID)
pShowWindow.Call(sysHwnd, swHide)
}
func sysShutdown() {
sysHide()
if sysHwnd != 0 {
pDestroyWindow.Call(sysHwnd)
sysHwnd = 0
}
}
func sysPlace() {
if sysHwnd == 0 {
return
}
lh := sysHead + float64(len(sysRows))*sysRow_ + sysFoot
flyPlace(sysHwnd, trayAnchor(traySys), px(sysW), px(lh))
flyRefresh(sysHwnd)
}
// sysRowAt is the line under a height in the panel (real pixels), or -1.
func sysRowAt(y int32) int {
ry := y - px(sysHead)
if ry < 0 {
return -1
}
i := int(ry / px(sysRow_))
if i >= len(sysRows) {
return -1
}
return i
}
func sysPoll() {
l, _, _ := pGetAsyncKeyState.Call(vkLButton)
r, _, _ := pGetAsyncKeyState.Call(vkRButton)
down := (l|r)&0x8000 != 0
var cp point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&cp)))
var fr rect
pGetWindowRect.Call(sysHwnd, uintptr(unsafe.Pointer(&fr)))
if down && !sysPrevBtn && !inRect(fr, cp) && !inRect(trayAnchor(traySys), cp) {
sysHide()
sysPrevBtn = down
return
}
sysPrevBtn = down
h := -1
if inRect(fr, cp) {
h = sysRowAt(cp.Y - fr.Top)
}
changed := h != sysHover
sysHover = h
if sysCopied != "" && time.Since(sysCopiedAt) > 1500*time.Millisecond {
sysCopied = ""
changed = true
}
if changed {
flyRefresh(sysHwnd)
}
}
func sysCopy(text, what string) {
if clipboardSet(text) {
sysCopied = what
} else {
sysCopied = "Copy failed"
}
sysCopiedAt = time.Now()
flyRefresh(sysHwnd)
}
func sysClick(x, y int32) {
if y < px(sysHead) {
sysCopy(sysText(sysRows), "Copied everything")
return
}
if i := sysRowAt(y); i >= 0 {
sysCopy(sysRows[i].label+": "+sysRows[i].value, "Copied "+sysRows[i].label)
}
}
// ---------- painting ----------
func sysDraw(hdc uintptr, W, H int32) {
u := px
flyFrame(hdc, W, H) // outline in the tray icon color; the background is added when painting
pad := u(14)
line := uintptr(dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis)
wxText(hdc, sysUserHost(), rect{pad, u(10), W - pad - u(150), u(34)}, fMed, colText, line)
btn, col := "Copy all", colAccent
if sysCopied != "" {
btn, col = sysCopied, colDim
}
wxText(hdc, btn, rect{W - pad - u(150), u(12), W - pad, u(32)}, fBold, col, dtRight|dtVCenter|dtSingleLine|dtEndEllipsis)
fillRaw(hdc, rect{pad, u(sysHead) - u(2), W - pad, u(sysHead) - u(1)}, colRule)
labelW := u(96)
for i, r := range sysRows {
y := u(sysHead) + int32(i)*u(sysRow_)
val := colText
if i == sysHover {
fillRaw(hdc, rect{u(6), y, W - u(6), y + u(sysRow_)}, rgb(40, 40, 48))
val = colAccent
}
wxText(hdc, r.label, rect{pad, y, pad + labelW, y + u(sysRow_)}, fBold, colAccent, line)
wxText(hdc, r.value, rect{pad + labelW, y, W - pad, y + u(sysRow_)}, fText, val, line)
}
y := u(sysHead) + int32(len(sysRows))*u(sysRow_)
wxText(hdc, "Click a line to copy it, or the top to copy everything.", rect{pad, y + u(4), W - pad, H - u(2)}, fTiny, colDim, line)
}
+298
View File
@@ -0,0 +1,298 @@
package main
// System information for the stats panel: the kind of thing neofetch prints.
// Everything is read from Windows itself (the registry and a few kernel calls);
// nothing goes over the network.
import (
"encoding/binary"
"fmt"
"net"
"os"
"runtime"
"strings"
"syscall"
"time"
"unsafe"
)
var (
pGlobalMemoryStatusEx = kern32t.NewProc("GlobalMemoryStatusEx")
pGetTickCount64 = kern32t.NewProc("GetTickCount64")
pGetLogicalDrives = kern32t.NewProc("GetLogicalDrives")
pGetDriveType = kern32t.NewProc("GetDriveTypeW")
pGetDiskFreeSpaceEx = kern32t.NewProc("GetDiskFreeSpaceExW")
pGlobalAlloc = kern32t.NewProc("GlobalAlloc")
pGlobalLock = kern32t.NewProc("GlobalLock")
pGlobalUnlock = kern32t.NewProc("GlobalUnlock")
pMoveMemory = kern32t.NewProc("RtlMoveMemory")
pOpenClipboard = user32.NewProc("OpenClipboard")
pEmptyClipboard = user32.NewProc("EmptyClipboard")
pSetClipboardData = user32.NewProc("SetClipboardData")
pCloseClipboard = user32.NewProc("CloseClipboard")
)
type sysRow struct{ label, value string }
// ---------- the registry ----------
func regRead(path, name string) (buf []byte, ok bool) {
var k syscall.Handle
if syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, u16(path), 0, syscall.KEY_READ, &k) != nil {
return nil, false
}
defer syscall.RegCloseKey(k)
var n, typ uint32
if syscall.RegQueryValueEx(k, u16(name), nil, &typ, nil, &n) != nil || n == 0 {
return nil, false
}
buf = make([]byte, n)
if syscall.RegQueryValueEx(k, u16(name), nil, &typ, &buf[0], &n) != nil {
return nil, false
}
return buf[:n], true
}
func regString(path, name string) string {
b, ok := regRead(path, name)
if !ok {
return ""
}
w := make([]uint16, 0, len(b)/2)
for i := 0; i+1 < len(b); i += 2 {
c := binary.LittleEndian.Uint16(b[i:])
if c == 0 {
break
}
w = append(w, c)
}
return strings.TrimSpace(syscall.UTF16ToString(w))
}
func regDword(path, name string) (uint32, bool) {
b, ok := regRead(path, name)
if !ok || len(b) < 4 {
return 0, false
}
return binary.LittleEndian.Uint32(b), true
}
// ---------- gathering ----------
type memStatusEx struct {
Length uint32
MemoryLoad uint32
TotalPhys, AvailPhys uint64
TotalPage, AvailPage uint64
TotalVirt, AvailVirt uint64
AvailExtendedVirtual uint64
}
func gib(b uint64) string { return fmt.Sprintf("%.1f GiB", float64(b)/(1<<30)) }
func sysUptime() string {
ms, _, _ := pGetTickCount64.Call()
d := time.Duration(ms) * time.Millisecond
days := int(d.Hours()) / 24
hrs := int(d.Hours()) % 24
mins := int(d.Minutes()) % 60
var parts []string
if days > 0 {
parts = append(parts, fmt.Sprintf("%d day%s", days, plural(days)))
}
if days > 0 || hrs > 0 {
parts = append(parts, fmt.Sprintf("%d hour%s", hrs, plural(hrs)))
}
parts = append(parts, fmt.Sprintf("%d min%s", mins, plural(mins)))
return strings.Join(parts, ", ")
}
func plural(n int) string {
if n == 1 {
return ""
}
return "s"
}
func sysGather() []sysRow {
var rows []sysRow
add := func(l, v string) {
if strings.TrimSpace(v) != "" {
rows = append(rows, sysRow{l, v})
}
}
const cv = `SOFTWARE\Microsoft\Windows NT\CurrentVersion`
build := regString(cv, "CurrentBuild")
bn := 0
fmt.Sscanf(build, "%d", &bn)
name := regString(cv, "ProductName")
if bn >= 22000 {
name = strings.Replace(name, "Windows 10", "Windows 11", 1) // Windows 11 still says 10 here
}
ver := regString(cv, "DisplayVersion")
arch := map[string]string{"amd64": "x86_64", "arm64": "arm64", "386": "x86"}[runtime.GOARCH]
osText := name
if ver != "" {
osText += " " + ver
}
if arch != "" {
osText += " " + arch
}
add("OS", osText)
const bios = `HARDWARE\DESCRIPTION\System\BIOS`
host := strings.TrimSpace(regString(bios, "SystemManufacturer") + " " + regString(bios, "SystemProductName"))
add("Host", host)
if build != "" {
k := "NT 10.0." + build
if ubr, ok := regDword(cv, "UBR"); ok {
k += fmt.Sprintf(".%d", ubr)
}
add("Kernel", k)
}
add("Uptime", sysUptime())
add("Shell", "MirrorBar")
sw, sh := screenSize()
res := fmt.Sprintf("%dx%d", sw, sh)
if s := int(scale*100 + 0.5); s != 100 {
res += fmt.Sprintf(" (%d%% scaling)", s)
}
add("Resolution", res)
const cpuKey = `HARDWARE\DESCRIPTION\System\CentralProcessor\0`
cpu := strings.Join(strings.Fields(regString(cpuKey, "ProcessorNameString")), " ")
if cpu != "" {
cpu += fmt.Sprintf(" (%d threads)", runtime.NumCPU())
}
add("CPU", cpu)
// Graphics adapters: the display class lists them as 0000, 0001, ...
n := 0
seen := map[string]bool{}
for i := 0; i < 10; i++ {
d := regString(fmt.Sprintf(`SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\%04d`, i), "DriverDesc")
if d == "" || seen[d] || strings.Contains(d, "Basic Display") || strings.Contains(d, "Remote Display") {
continue
}
seen[d] = true
n++
l := "GPU"
if n > 1 {
l = fmt.Sprintf("GPU %d", n)
}
add(l, d)
}
var ms memStatusEx
ms.Length = uint32(unsafe.Sizeof(ms))
if r, _, _ := pGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms))); r != 0 && ms.TotalPhys > 0 {
used := ms.TotalPhys - ms.AvailPhys
add("Memory", fmt.Sprintf("%s / %s (%d%%)", gib(used), gib(ms.TotalPhys), used*100/ms.TotalPhys))
}
// Fixed drives only; a sleeping network drive could make this wait.
mask, _, _ := pGetLogicalDrives.Call()
for i := 0; i < 26; i++ {
if mask&(1<<uint(i)) == 0 {
continue
}
root := string(rune('A'+i)) + `:\`
if t, _, _ := pGetDriveType.Call(uintptr(unsafe.Pointer(u16(root)))); t != 3 {
continue
}
var free, total, totalFree uint64
r, _, _ := pGetDiskFreeSpaceEx.Call(uintptr(unsafe.Pointer(u16(root))),
uintptr(unsafe.Pointer(&free)), uintptr(unsafe.Pointer(&total)), uintptr(unsafe.Pointer(&totalFree)))
if r == 0 || total == 0 {
continue
}
used := total - totalFree
add("Disk ("+root[:2]+")", fmt.Sprintf("%s / %s (%d%%)", gib(used), gib(total), used*100/total))
}
if battPct >= 0 {
b := fmt.Sprintf("%d%%", battPct)
switch {
case battCharging:
b += ", charging"
case battAC:
b += ", plugged in"
}
add("Battery", b)
}
add("Local IP", localIP())
return rows
}
// localIP is this PC's first private IPv4 address.
func localIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, a := range addrs {
if ipn, ok := a.(*net.IPNet); ok && !ipn.IP.IsLoopback() {
if v4 := ipn.IP.To4(); v4 != nil && v4.IsPrivate() {
return v4.String()
}
}
}
return ""
}
func sysUserHost() string {
u := os.Getenv("USERNAME")
h, _ := os.Hostname()
if u == "" {
return h
}
return u + "@" + h
}
// sysText is everything as plain text, ready to paste.
func sysText(rows []sysRow) string {
head := sysUserHost()
var sb strings.Builder
sb.WriteString(head + "\r\n" + strings.Repeat("-", len([]rune(head))) + "\r\n")
for _, r := range rows {
sb.WriteString(r.label + ": " + r.value + "\r\n")
}
return sb.String()
}
// ---------- the clipboard ----------
// clipboardSet puts plain text on the clipboard. Returns false if it couldn't.
func clipboardSet(text string) bool {
w, err := syscall.UTF16FromString(text)
if err != nil {
return false
}
for i := 0; i < 5; i++ { // another program may have it open for a moment
if r, _, _ := pOpenClipboard.Call(hwndMain); r != 0 {
break
}
if i == 4 {
return false
}
time.Sleep(30 * time.Millisecond)
}
defer pCloseClipboard.Call()
pEmptyClipboard.Call()
const gmemMoveable, cfUnicodeText = 0x0002, 13
h, _, _ := pGlobalAlloc.Call(gmemMoveable, uintptr(len(w)*2))
if h == 0 {
return false
}
p, _, _ := pGlobalLock.Call(h)
if p == 0 {
return false
}
pMoveMemory.Call(p, uintptr(unsafe.Pointer(&w[0])), uintptr(len(w)*2))
pGlobalUnlock.Call(h)
r, _, _ := pSetClipboardData.Call(cfUnicodeText, h)
return r != 0 // the system owns the memory now
}
+235 -29
View File
@@ -5,6 +5,8 @@ package main
import ( import (
"net" "net"
"os"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
"syscall" "syscall"
@@ -18,6 +20,9 @@ const (
trayVolume trayVolume
trayWifi trayWifi
trayChevron trayChevron
trayWeather // added after the others so saved orders from older versions still mean the same thing
trayNews
traySys
) )
const ( const (
@@ -39,6 +44,13 @@ const (
menuSoundID = 23 menuSoundID = 23
menuNetID = 24 menuNetID = 24
menuMuteID = 25 menuMuteID = 25
menuWeatherID = 26
menuWeatherZipID = 27
menuNewsID = 28
menuNewsZipID = 29
menuSysID = 34
menuSysCopyID = 35
) )
var ( var (
@@ -83,19 +95,45 @@ type trayItem struct {
} }
func trayItems(clientW, clientH int32) []trayItem { func trayItems(clientW, clientH int32) []trayItem {
x := clientW / 2 return trayItemsAt(axisX(clientW), clientH)
}
// trayItemsAt lays the right-hand items out rightward from x.
func trayItemsAt(x, clientH int32) []trayItem {
var out []trayItem var out []trayItem
add := func(kind int, w int32) { for _, kind := range trayOrder {
var w int32
switch kind {
case trayClock:
w = clockWidth()
case trayBattery:
if battPct < 0 {
continue // this PC has no battery
}
w = px(36)
case trayVolume, trayWifi:
w = px(36)
case trayWeather:
if !showWeather {
continue
}
w = px(36)
case trayNews:
if !showNews {
continue
}
w = px(36)
case traySys:
if !showSys {
continue
}
w = px(36)
case trayChevron:
w = px(28)
}
out = append(out, trayItem{kind, rect{x, 0, x + w, clientH}}) out = append(out, trayItem{kind, rect{x, 0, x + w, clientH}})
x += w x += w
} }
add(trayClock, clockWidth())
if battPct >= 0 {
add(trayBattery, px(36))
}
add(trayVolume, px(36))
add(trayWifi, px(36))
add(trayChevron, px(28))
return out return out
} }
@@ -145,13 +183,13 @@ func drawBattery(hdc uintptr, r rect) {
t := px(1) t := px(1)
left := cx - (bw+nubW)/2 left := cx - (bw+nubW)/2
top := cy - bh/2 top := cy - bh/2
white := rgb(245, 245, 245) white := iconColor()
fill(hdc, rect{left, top, left + bw, top + t}, white) fillFg(hdc, rect{left, top, left + bw, top + t}, white)
fill(hdc, rect{left, top + bh - t, left + bw, top + bh}, white) fillFg(hdc, rect{left, top + bh - t, left + bw, top + bh}, white)
fill(hdc, rect{left, top, left + t, top + bh}, white) fillFg(hdc, rect{left, top, left + t, top + bh}, white)
fill(hdc, rect{left + bw - t, top, left + bw, top + bh}, white) fillFg(hdc, rect{left + bw - t, top, left + bw, top + bh}, white)
fill(hdc, rect{left + bw, cy - nubH/2, left + bw + nubW, cy + nubH/2}, white) fillFg(hdc, rect{left + bw, cy - nubH/2, left + bw + nubW, cy + nubH/2}, white)
col := white col := white
switch { switch {
@@ -166,15 +204,15 @@ func drawBattery(hdc uintptr, r rect) {
if battPct > 0 && fw < px(1) { if battPct > 0 && fw < px(1) {
fw = px(1) fw = px(1)
} }
fill(hdc, rect{left + gap, top + gap, left + gap + fw, top + bh - gap}, col) fillFg(hdc, rect{left + gap, top + gap, left + gap + fw, top + bh - gap}, col)
} }
func drawVolume(hdc uintptr, r rect) { func drawVolume(hdc uintptr, r rect) {
cx, cy := center(r) cx, cy := center(r)
white, dim := rgb(245, 245, 245), rgb(110, 110, 120) white, dim := iconColor(), iconDim()
x0 := cx - px(9) x0 := cx - px(9)
fill(hdc, rect{x0, cy - px(3), x0 + px(3), cy + px(3)}, white) fillFg(hdc, rect{x0, cy - px(3), x0 + px(3), cy + px(3)}, white)
polygon(hdc, []point{ polygon(hdc, []point{
{x0 + px(3), cy - px(3)}, {x0 + px(3), cy - px(3)},
{x0 + px(7), cy - px(6)}, {x0 + px(7), cy - px(6)},
@@ -200,7 +238,7 @@ func drawVolume(hdc uintptr, r rect) {
if i < active { if i < active {
col = white col = white
} }
fill(hdc, rect{bx, cy - heights[i]/2, bx + px(2), cy + heights[i]/2}, col) fillFg(hdc, rect{bx, cy - heights[i]/2, bx + px(2), cy + heights[i]/2}, col)
} }
if volMuted { if volMuted {
polyline(hdc, []point{{x0 + px(10), cy - px(4)}, {x0 + px(17), cy + px(4)}}, px(1), white) polyline(hdc, []point{{x0 + px(10), cy - px(4)}, {x0 + px(17), cy + px(4)}}, px(1), white)
@@ -210,18 +248,18 @@ func drawVolume(hdc uintptr, r rect) {
func drawNetwork(hdc uintptr, r rect) { func drawNetwork(hdc uintptr, r rect) {
cx, cy := center(r) cx, cy := center(r)
white, dim := rgb(245, 245, 245), rgb(110, 110, 120) white, dim := iconColor(), iconDim()
if netKind == netWired { if netKind == netWired {
t := px(1) t := px(1)
l, tp := cx-px(7), cy-px(6) l, tp := cx-px(7), cy-px(6)
w, h := px(14), px(9) w, h := px(14), px(9)
fill(hdc, rect{l, tp, l + w, tp + t}, white) fillFg(hdc, rect{l, tp, l + w, tp + t}, white)
fill(hdc, rect{l, tp + h - t, l + w, tp + h}, white) fillFg(hdc, rect{l, tp + h - t, l + w, tp + h}, white)
fill(hdc, rect{l, tp, l + t, tp + h}, white) fillFg(hdc, rect{l, tp, l + t, tp + h}, white)
fill(hdc, rect{l + w - t, tp, l + w, tp + h}, white) fillFg(hdc, rect{l + w - t, tp, l + w, tp + h}, white)
fill(hdc, rect{cx - px(1), tp + h, cx + px(1), tp + h + px(3)}, white) fillFg(hdc, rect{cx - px(1), tp + h, cx + px(1), tp + h + px(3)}, white)
fill(hdc, rect{cx - px(4), tp + h + px(3), cx + px(4), tp + h + px(4)}, white) fillFg(hdc, rect{cx - px(4), tp + h + px(3), cx + px(4), tp + h + px(4)}, white)
return return
} }
@@ -243,7 +281,7 @@ func drawNetwork(hdc uintptr, r rect) {
if i < bars { if i < bars {
col = white col = white
} }
fill(hdc, rect{x, baseY - heights[i], x + px(2), baseY}, col) fillFg(hdc, rect{x, baseY - heights[i], x + px(2), baseY}, col)
x += px(4) x += px(4)
} }
if netKind == netNone { if netKind == netNone {
@@ -255,7 +293,7 @@ func drawNetwork(hdc uintptr, r rect) {
func drawChevron(hdc uintptr, r rect) { func drawChevron(hdc uintptr, r rect) {
cx, cy := center(r) cx, cy := center(r)
polyline(hdc, []point{{cx - px(5), cy + px(2)}, {cx, cy - px(3)}, {cx + px(5), cy + px(2)}}, polyline(hdc, []point{{cx - px(5), cy + px(2)}, {cx, cy - px(3)}, {cx + px(5), cy + px(2)}},
px(1.5), rgb(245, 245, 245)) px(1.5), iconColor())
} }
func drawTray(hdc uintptr, w, h int32) { func drawTray(hdc uintptr, w, h int32) {
@@ -263,7 +301,7 @@ func drawTray(hdc uintptr, w, h int32) {
if it.kind == hoverTray { if it.kind == hoverTray {
fill(hdc, rect{it.r.Left + px(1), it.r.Top + px(3), it.r.Right - px(1), it.r.Bottom - px(3)}, rgb(40, 40, 48)) fill(hdc, rect{it.r.Left + px(1), it.r.Top + px(3), it.r.Right - px(1), it.r.Bottom - px(3)}, rgb(40, 40, 48))
} }
if vertical && it.kind != trayClock { if !layerFg || (vertical && it.kind != trayClock) {
continue // a vertical bar draws these upright, after turning continue // a vertical bar draws these upright, after turning
} }
switch it.kind { switch it.kind {
@@ -277,6 +315,12 @@ func drawTray(hdc uintptr, w, h int32) {
drawNetwork(hdc, it.r) drawNetwork(hdc, it.r)
case trayChevron: case trayChevron:
drawChevron(hdc, it.r) drawChevron(hdc, it.r)
case trayWeather:
drawWeatherIcon(hdc, it.r)
case trayNews:
drawNewsIcon(hdc, it.r)
case traySys:
drawSysIcon(hdc, it.r)
} }
} }
} }
@@ -534,13 +578,40 @@ func tapChord(mod, k uintptr) {
} }
// trayClick opens the matching Windows panel with its keyboard shortcut. // trayClick opens the matching Windows panel with its keyboard shortcut.
const vkEscape = 0x1B
// overflowOpen reports whether the hidden icons flyout is on screen.
func overflowOpen() bool {
for _, class := range []string{"TopLevelWindowForOverflowXamlIsland", "NotifyIconOverflowWindow"} {
h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16(class))), 0)
if h != 0 {
if vis, _, _ := pIsWindowVisible.Call(h); vis != 0 {
return true
}
}
}
return false
}
func trayClick(kind int) { func trayClick(kind int) {
switch kind { switch kind {
case trayClock: case trayClock:
tapChord(vkLWin, 'N') // notification center and calendar tapChord(vkLWin, 'N') // notification center and calendar
case trayBattery, trayVolume, trayWifi: case trayBattery, trayVolume, trayWifi:
tapChord(vkLWin, 'A') // quick settings tapChord(vkLWin, 'A') // quick settings
case trayWeather:
weatherToggle()
case trayNews:
newsToggle()
case traySys:
sysToggle()
case trayChevron: case trayChevron:
// If the hidden icons are already showing, a second click closes them. Sending
// Win+B and Enter again would instead press Enter on the highlighted icon.
if overflowOpen() {
tapKey(vkEscape)
return
}
// Win+B moves focus to the notification area; Enter opens the hidden icons. // Win+B moves focus to the notification area; Enter opens the hidden icons.
tapChord(vkLWin, 'B') tapChord(vkLWin, 'B')
time.Sleep(150 * time.Millisecond) time.Sleep(150 * time.Millisecond)
@@ -616,6 +687,18 @@ func addTrayMenu(add func(flags uintptr, id uintptr, text string), sep func(), k
add(mfGrayed, 0, networkText()) add(mfGrayed, 0, networkText())
add(0, menuNetID, "Network && internet settings") add(0, menuNetID, "Network && internet settings")
sep() sep()
case trayWeather:
add(0, menuWeatherID, "Show weather")
add(0, menuWeatherZipID, "Weather ZIP code...")
sep()
case trayNews:
add(0, menuNewsID, "Show local news")
add(0, menuNewsZipID, "News ZIP code...")
sep()
case traySys:
add(0, menuSysID, "Show system stats")
add(0, menuSysCopyID, "Copy system stats")
sep()
} }
} }
@@ -630,6 +713,25 @@ func handleTrayCommand(cmd uintptr) bool {
shellOpen("ms-settings:sound", "") shellOpen("ms-settings:sound", "")
case menuNetID: case menuNetID:
shellOpen("ms-settings:network", "") shellOpen("ms-settings:network", "")
case menuWeatherID:
if !wxShown {
weatherToggle()
}
case menuNewsID:
if !newsShown {
newsToggle()
}
case menuSysID:
if !sysShown {
sysToggle()
}
case menuSysCopyID:
if clipboardSet(sysText(sysGather())) {
sysCopied = "Copied everything"
sysCopiedAt = time.Now()
}
case menuWeatherZipID, menuNewsZipID:
openSettings()
case menuAutostartID: case menuAutostartID:
setAutostart(!autostartEnabled()) setAutostart(!autostartEnabled())
case menuMuteID: case menuMuteID:
@@ -641,3 +743,107 @@ func handleTrayCommand(cmd uintptr) bool {
} }
return true return true
} }
// ---------- the right row can be rearranged too ----------
// trayOrder is the left to right order of the items to the right of center.
var trayOrder = []int{trayClock, trayWeather, trayNews, traySys, trayBattery, trayVolume, trayWifi, trayChevron}
var (
dragTray int // the tray item the mouse went down on, 0 for none
dragTrayStart int32 // where along the bar the mouse went down
dragTrayActive bool // true once the mouse has moved far enough to count as a drag
)
func trayOrderFile() string { return filepath.Join(dataDir(), "trayorder.txt") }
func loadTrayOrder() {
b, err := os.ReadFile(trayOrderFile())
if err != nil {
return
}
var order []int
seen := map[int]bool{}
for _, p := range strings.Split(strings.TrimSpace(string(b)), ",") {
n, err := strconv.Atoi(strings.TrimSpace(p))
if err != nil || n < trayClock || n > traySys || seen[n] {
return
}
seen[n] = true
order = append(order, n)
}
// An order saved before the weather cloud or the newspaper existed: put the new
// icon next to the clock (the newspaper goes after the cloud).
insertAfter := func(after, kind int) {
out := make([]int, 0, len(order)+1)
for _, k := range order {
out = append(out, k)
if k == after {
out = append(out, kind)
}
}
order = out
seen[kind] = true
}
if !seen[trayWeather] {
insertAfter(trayClock, trayWeather)
}
if !seen[trayNews] {
insertAfter(trayWeather, trayNews)
}
if !seen[traySys] {
insertAfter(trayNews, traySys)
}
if len(order) == len(trayOrder) {
trayOrder = order
}
}
func saveTrayOrder() {
parts := make([]string, len(trayOrder))
for i, k := range trayOrder {
parts[i] = strconv.Itoa(k)
}
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(trayOrderFile(), []byte(strings.Join(parts, ",")), 0o644)
}
// trayKindAt is the tray item under a spot along the bar, clamped to the ends
// of the right row.
func trayKindAt(hwnd uintptr, x int32) int {
w, h := clientSize(hwnd)
items := trayItems(w, h)
if len(items) == 0 {
return 0
}
if x < items[0].r.Left {
return items[0].kind
}
if x >= items[len(items)-1].r.Right {
return items[len(items)-1].kind
}
for _, it := range items {
if x >= it.r.Left && x < it.r.Right {
return it.kind
}
}
return 0
}
// moveTray puts one item where another one is, shifting the rest.
func moveTray(kind, target int) {
from, to := -1, -1
for i, k := range trayOrder {
if k == kind {
from = i
}
if k == target {
to = i
}
}
if from < 0 || to < 0 || from == to {
return
}
rest := append(append([]int{}, trayOrder[:from]...), trayOrder[from+1:]...)
trayOrder = append(append(append([]int{}, rest[:to]...), kind), rest[to:]...)
}
+580
View File
@@ -0,0 +1,580 @@
package main
// Weather data for the flyout. The location comes from the ZIP code typed in
// the settings window: Open-Meteo's geocoder turns it into a place (with
// api.zippopotam.us as a backup), then Open-Meteo's forecast service gives the
// current conditions and the next days, in Fahrenheit and miles per hour. The
// moon phase needs no service at all; it is worked out from the date.
//
// Everything that touches the network runs on its own goroutine. The result is
// kept under a lock and the bar is told with a posted message (wmWxDone), so
// the bar itself never waits on the internet.
import (
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
const wmWxDone = wmUser + 2
const (
wxFresh = 10 * time.Minute // how long a forecast counts as current
)
// Icon kinds, chosen from the WMO weather code Open-Meteo reports.
const (
wxSun = iota
wxPartly
wxCloudy
wxFog
wxRain
wxSnow
wxStorm
)
type wxNow struct {
temp, feels float64
humidity int
wind float64
code int
day bool
}
type wxDay struct {
date time.Time
code int
hi, lo float64
rain int
uv float64
sunrise string
sunset string
}
type wxState struct {
zip string
place string
lat float64
lon float64
now wxNow
days []wxDay // today first
ok bool // now and days hold a good forecast for zip
loading bool
err string
fetched time.Time
}
var (
wxMu sync.Mutex
wx wxState
wxGen int // bumped whenever the ZIP changes, so an old answer can be thrown away
wxZip string // the saved ZIP code; used on the bar's own thread only
wxClient = &http.Client{Timeout: 12 * time.Second}
)
// ---------- the saved ZIP code ----------
func zipFile() string { return filepath.Join(dataDir(), "zip.txt") }
func locCacheFile() string { return filepath.Join(dataDir(), "weatherloc.txt") }
func loadZip() {
b, err := os.ReadFile(zipFile())
if err != nil {
return
}
if z := onlyDigits(string(b)); len(z) == 5 {
wxZip = z
}
}
func saveZip() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(zipFile(), []byte(wxZip), 0o644)
}
func onlyDigits(s string) string {
var sb strings.Builder
for _, r := range s {
if r >= '0' && r <= '9' {
sb.WriteRune(r)
}
}
return sb.String()
}
// weatherSetZip is called by the settings window when the ZIP code changes.
// An empty string clears it.
func weatherSetZip(z string) {
if z == wxZip {
return
}
wxZip = z
saveZip()
if z == "" {
_ = os.Remove(locCacheFile())
}
weatherRefresh(true)
newsRefresh(true) // the local news follows the same ZIP code
}
// weatherRefresh starts a fetch if the forecast is missing or old (or force is
// set). Safe to call as often as you like.
func weatherRefresh(force bool) {
if !showWeather {
return
}
zip := wxZip
wxMu.Lock()
if len(zip) != 5 {
wx = wxState{}
wxGen++
wxMu.Unlock()
weatherNotify()
return
}
same := wx.zip == zip
if same && wx.loading && !force {
wxMu.Unlock()
return
}
if same && wx.ok && time.Since(wx.fetched) < wxFresh && !force {
wxMu.Unlock()
return
}
if !same {
wx = wxState{zip: zip}
}
wx.loading = true
wx.err = ""
wxGen++
gen := wxGen
wxMu.Unlock()
weatherNotify()
go wxFetch(zip, gen)
}
func weatherNotify() {
if hwndMain != 0 {
pPostMessage.Call(hwndMain, wmWxDone, 0, 0)
}
}
func wxSnapshot() wxState {
wxMu.Lock()
defer wxMu.Unlock()
s := wx
s.days = append([]wxDay(nil), wx.days...)
return s
}
// ---------- fetching ----------
func wxFetch(zip string, gen int) {
defer func() {
if r := recover(); r != nil {
wxFinish(gen, nil, "The weather lookup failed.")
}
}()
lat, lon, place, err := wxLocate(zip)
if err != nil {
wxFinish(gen, nil, err.Error())
return
}
st := wxState{zip: zip, place: place, lat: lat, lon: lon}
if err := wxForecast(&st); err != nil {
wxFinish(gen, nil, err.Error())
return
}
st.ok = true
st.fetched = time.Now()
wxFinish(gen, &st, "")
}
// wxFinish stores a result, unless the ZIP changed while it was being fetched.
func wxFinish(gen int, st *wxState, errText string) {
wxMu.Lock()
if gen != wxGen {
wxMu.Unlock()
return
}
if st != nil {
wx = *st
} else {
wx.loading = false
wx.err = errText
}
wxMu.Unlock()
weatherNotify()
}
func wxGetJSON(u string, v any) (status int, err error) {
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return 0, err
}
req.Header.Set("User-Agent", "MirrorBar weather flyout")
resp, err := wxClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return resp.StatusCode, fmt.Errorf("HTTP %d", resp.StatusCode)
}
return resp.StatusCode, json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(v)
}
// wxGetBytes downloads one file (a picture tile), up to 4 MB.
func wxGetBytes(u string) ([]byte, error) {
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "MirrorBar weather flyout")
resp, err := wxClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, 4<<20))
}
// wxLocate turns a ZIP code into a place. The answer is kept in a small file so
// the lookup happens once per ZIP code, not every time the bar starts.
func wxLocate(zip string) (lat, lon float64, place string, err error) {
if b, e := os.ReadFile(locCacheFile()); e == nil {
p := strings.Split(strings.TrimSpace(string(b)), "\t")
if len(p) == 4 && p[0] == zip {
la, e1 := strconv.ParseFloat(p[1], 64)
lo, e2 := strconv.ParseFloat(p[2], 64)
if e1 == nil && e2 == nil {
return la, lo, p[3], nil
}
}
}
reached := false
// Open-Meteo's own geocoder lists postal codes with each place. Other countries
// can share a number (46750 is also a town in Spain), so only a US match counts.
var gr struct {
Results []struct {
Name string `json:"name"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
CountryCode string `json:"country_code"`
Admin1 string `json:"admin1"`
Postcodes []string `json:"postcodes"`
} `json:"results"`
}
if st, e := wxGetJSON("https://geocoding-api.open-meteo.com/v1/search?name="+zip+"&count=10&language=en&format=json", &gr); e == nil || st != 0 {
reached = true
}
for _, r := range gr.Results {
if r.CountryCode != "US" {
continue
}
for _, pc := range r.Postcodes {
if pc == zip {
place = r.Name
if r.Admin1 != "" {
place += ", " + r.Admin1
}
wxSaveLoc(zip, r.Latitude, r.Longitude, place)
return r.Latitude, r.Longitude, place, nil
}
}
}
// Backup: a ZIP code service, for codes the geocoder doesn't list.
var zr struct {
Places []struct {
Name string `json:"place name"`
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
State string `json:"state"`
} `json:"places"`
}
st, e := wxGetJSON("https://api.zippopotam.us/us/"+zip, &zr)
if e == nil || st != 0 {
reached = true
}
if e == nil && len(zr.Places) > 0 {
p := zr.Places[0]
la, e1 := strconv.ParseFloat(p.Latitude, 64)
lo, e2 := strconv.ParseFloat(p.Longitude, 64)
if e1 == nil && e2 == nil {
place = p.Name
if p.State != "" {
place += ", " + p.State
}
wxSaveLoc(zip, la, lo, place)
return la, lo, place, nil
}
}
if !reached {
return 0, 0, "", fmt.Errorf("Can't reach the weather service. Check your internet connection.")
}
return 0, 0, "", fmt.Errorf("ZIP code %s was not found.", zip)
}
func wxSaveLoc(zip string, lat, lon float64, place string) {
_ = os.MkdirAll(dataDir(), 0o755)
s := zip + "\t" + strconv.FormatFloat(lat, 'f', 5, 64) + "\t" + strconv.FormatFloat(lon, 'f', 5, 64) + "\t" + place
_ = os.WriteFile(locCacheFile(), []byte(s), 0o644)
}
func wxForecast(st *wxState) error {
u := fmt.Sprintf("https://api.open-meteo.com/v1/forecast?latitude=%.4f&longitude=%.4f"+
"&current=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m,is_day"+
"&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,uv_index_max,sunrise,sunset"+
"&temperature_unit=fahrenheit&wind_speed_unit=mph&timezone=auto&forecast_days=6", st.lat, st.lon)
var fr struct {
Current struct {
Temp float64 `json:"temperature_2m"`
Feels float64 `json:"apparent_temperature"`
Humidity float64 `json:"relative_humidity_2m"`
Code int `json:"weather_code"`
Wind float64 `json:"wind_speed_10m"`
IsDay int `json:"is_day"`
} `json:"current"`
Daily struct {
Time []string `json:"time"`
Code []int `json:"weather_code"`
Max []float64 `json:"temperature_2m_max"`
Min []float64 `json:"temperature_2m_min"`
Rain []float64 `json:"precipitation_probability_max"`
UV []float64 `json:"uv_index_max"`
Sunrise []string `json:"sunrise"`
Sunset []string `json:"sunset"`
} `json:"daily"`
}
status, err := wxGetJSON(u, &fr)
if err != nil {
if status == 0 {
return fmt.Errorf("Can't reach the weather service. Check your internet connection.")
}
return fmt.Errorf("The weather service returned an error (%v).", err)
}
d := fr.Daily
n := len(d.Time)
if n < 2 || len(d.Code) < n || len(d.Max) < n || len(d.Min) < n {
return fmt.Errorf("The weather service sent a forecast MirrorBar couldn't read.")
}
st.now = wxNow{
temp: fr.Current.Temp,
feels: fr.Current.Feels,
humidity: int(math.Round(fr.Current.Humidity)),
wind: fr.Current.Wind,
code: fr.Current.Code,
day: fr.Current.IsDay != 0,
}
st.days = st.days[:0]
for i := 0; i < n; i++ {
dt, err := time.Parse("2006-01-02", d.Time[i])
if err != nil {
return fmt.Errorf("The weather service sent a forecast MirrorBar couldn't read.")
}
day := wxDay{date: dt, code: d.Code[i], hi: d.Max[i], lo: d.Min[i]}
if i < len(d.Rain) {
day.rain = int(math.Round(d.Rain[i]))
}
if i < len(d.UV) {
day.uv = d.UV[i]
}
if i < len(d.Sunrise) {
day.sunrise = wxClockText(d.Sunrise[i])
}
if i < len(d.Sunset) {
day.sunset = wxClockText(d.Sunset[i])
}
st.days = append(st.days, day)
}
return nil
}
// wxClockText turns "2026-11-07T07:19" into "7:19 AM".
func wxClockText(s string) string {
t, err := time.Parse("2006-01-02T15:04", s)
if err != nil {
return ""
}
return t.Format("3:04 PM")
}
// ---------- what the codes mean ----------
// wxKind picks the picture for a WMO weather code.
func wxKind(code int) int {
switch {
case code == 0, code == 1:
return wxSun
case code == 2:
return wxPartly
case code == 3:
return wxCloudy
case code == 45, code == 48:
return wxFog
case code >= 51 && code <= 67, code >= 80 && code <= 82:
return wxRain
case code >= 71 && code <= 77, code == 85, code == 86:
return wxSnow
case code >= 95:
return wxStorm
}
return wxCloudy
}
func wxDesc(code int) string {
switch code {
case 0:
return "Clear sky"
case 1:
return "Mostly clear"
case 2:
return "Partly cloudy"
case 3:
return "Overcast"
case 45, 48:
return "Fog"
case 51, 53, 55:
return "Drizzle"
case 56, 57:
return "Freezing drizzle"
case 61:
return "Light rain"
case 63:
return "Rain"
case 65:
return "Heavy rain"
case 66, 67:
return "Freezing rain"
case 71:
return "Light snow"
case 73:
return "Snow"
case 75:
return "Heavy snow"
case 77:
return "Snow grains"
case 80:
return "Light showers"
case 81:
return "Showers"
case 82:
return "Heavy showers"
case 85, 86:
return "Snow showers"
case 95:
return "Thunderstorm"
case 96, 99:
return "Thunderstorm with hail"
}
return "Cloudy"
}
func wxDeg(v float64) string { return strconv.Itoa(int(math.Round(v))) + "°" }
func wxF(v float64) string { return strconv.Itoa(int(math.Round(v))) + "°F" }
// ---------- the moon ----------
const synodicMonth = 29.530588853 // days from one new moon to the next
type moonInfo struct {
frac float64 // 0 is new, 0.5 is full, back to 1 at the next new moon
illum float64 // 0 to 1, how much of the face is lit
name string
fullIn int // whole days until the next full moon
tonight bool // it is full right now (within about half a day)
}
// moonElongation is how far the moon is ahead of the sun in the sky, in degrees
// (0 at new moon, 180 at full). It is the moon's mean position plus the main
// corrections for its uneven orbit (Meeus, Astronomical Algorithms, chapter 48),
// which keeps the phase within a fraction of a percent. Counting the average
// month from a known new moon would be up to 15 hours off.
func moonElongation(t time.Time) float64 {
jd := float64(t.Unix())/86400 + 2440587.5
T := (jd - 2451545.0) / 36525
T2, T3, T4 := T*T, T*T*T, T*T*T*T
D := 297.8501921 + 445267.1114034*T - 0.0018819*T2 + T3/545868 - T4/113065000
M := 357.5291092 + 35999.0502909*T - 0.0001536*T2 + T3/24490000
Mp := 134.9633964 + 477198.8675055*T + 0.0087414*T2 + T3/69699 - T4/14712000
r := math.Pi / 180
e := D + 6.289*math.Sin(Mp*r) - 2.100*math.Sin(M*r) + 1.274*math.Sin((2*D-Mp)*r) +
0.658*math.Sin(2*D*r) + 0.214*math.Sin(2*Mp*r) + 0.110*math.Sin(D*r)
e = math.Mod(e, 360)
if e < 0 {
e += 360
}
return e
}
func moonAt(t time.Time) moonInfo {
e := moonElongation(t)
m := moonInfo{frac: e / 360}
m.illum = (1 - math.Cos(e*math.Pi/180)) / 2
// Eight named phases, each an eighth of the cycle centered on its moment.
switch f := m.frac * 16; {
case f < 1:
m.name = "New Moon"
case f < 3:
m.name = "Waxing Crescent"
case f < 5:
m.name = "First Quarter"
case f < 7:
m.name = "Waxing Gibbous"
case f < 9:
m.name = "Full Moon"
case f < 11:
m.name = "Waning Gibbous"
case f < 13:
m.name = "Last Quarter"
case f < 15:
m.name = "Waning Crescent"
default:
m.name = "New Moon"
}
// Hours from now to the nearest full moon (negative just after one).
m.tonight = math.Abs(e-180)/360*synodicMonth*24 < 14
// Walk forward an hour at a time to the moment the moon next passes 180 degrees.
prev := e
for h := 1; h <= 31*24; h++ {
cur := moonElongation(t.Add(time.Duration(h) * time.Hour))
if prev < 180 && cur >= 180 {
m.fullIn = int(math.Round(float64(h) / 24))
break
}
prev = cur
}
return m
}
func (m moonInfo) fullText() string {
switch {
case m.tonight:
return "Full moon tonight"
case m.fullIn <= 1:
return "Full moon in 1 day"
}
return "Full moon in " + strconv.Itoa(m.fullIn) + " days"
}