Files
MirrorBar/main.go
T

1243 lines
33 KiB
Go

// MirrorBar proof of concept, version 3.
//
// Hides the real Windows taskbar and puts up a replacement bar laid out in
// mirror image around the exact center of the screen:
//
// left of center: Start button against the center line, open apps as small
// icons growing leftward from it (oldest window nearest Start)
// right of center: clock against the center line
//
// The bar is drawn as a per-pixel transparent window. Right click the bar to
// pick how see-through the background is (Clear, Light, Medium, Solid).
//
// Not built yet: battery, volume, wifi and the hidden icons arrow on the
// right side of the clock.
//
// Safety:
// - By default it closes itself after 10 minutes and restores the real taskbar.
// Pass --forever, or run it under a file name containing "forever", to turn that off.
// - Right click the bar, or press Ctrl+Alt+Q, to exit and restore.
// - Run restore_taskbar.exe (the same program under that name) or pass
// --restore to bring the real taskbar back if anything goes wrong.
package main
import (
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
)
func init() { runtime.LockOSThread() }
// Extra Win32 calls used by the app right-click menu.
var (
pIsZoomed = syscall.NewLazyDLL("user32.dll").NewProc("IsZoomed")
pGetWindowThreadProcessId = syscall.NewLazyDLL("user32.dll").NewProc("GetWindowThreadProcessId")
pOpenProcess = syscall.NewLazyDLL("kernel32.dll").NewProc("OpenProcess")
pCloseHandle = syscall.NewLazyDLL("kernel32.dll").NewProc("CloseHandle")
pQueryFullProcessImage = syscall.NewLazyDLL("kernel32.dll").NewProc("QueryFullProcessImageNameW")
pShellExecute = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW")
)
const (
wmSysCommand = 0x0112
scSize = 0xF000
scMove = 0xF010
scMinimize = 0xF020
scMaximize = 0xF030
scRestore = 0xF120
wsMaximizeBox = 0x00010000
wsMinimizeBox = 0x00020000
wsThickFrame = 0x00040000
mfGrayed = 0x0003 // MF_GRAYED | MF_DISABLED
menuNewWindowID = 3
menuFileLocID = 4
menuRestoreID = 5
menuMoveID = 6
menuSizeID = 7
menuMinimizeID = 8
menuMaximizeID = 9
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
gdi32 = syscall.NewLazyDLL("gdi32.dll")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
shell32 = syscall.NewLazyDLL("shell32.dll")
dwmapi = syscall.NewLazyDLL("dwmapi.dll")
pRegisterClassEx = user32.NewProc("RegisterClassExW")
pCreateWindowEx = user32.NewProc("CreateWindowExW")
pDefWindowProc = user32.NewProc("DefWindowProcW")
pGetMessage = user32.NewProc("GetMessageW")
pTranslateMessage = user32.NewProc("TranslateMessage")
pDispatchMessage = user32.NewProc("DispatchMessageW")
pPostQuitMessage = user32.NewProc("PostQuitMessage")
pDestroyWindow = user32.NewProc("DestroyWindow")
pShowWindow = user32.NewProc("ShowWindow")
pFindWindow = user32.NewProc("FindWindowW")
pIsWindowVisible = user32.NewProc("IsWindowVisible")
pIsIconic = user32.NewProc("IsIconic")
pSetTimer = user32.NewProc("SetTimer")
pKillTimer = user32.NewProc("KillTimer")
pBeginPaint = user32.NewProc("BeginPaint")
pEndPaint = user32.NewProc("EndPaint")
pGetClientRect = user32.NewProc("GetClientRect")
pGetWindowRect = user32.NewProc("GetWindowRect")
pUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow")
pFillRect = user32.NewProc("FillRect")
pDrawText = user32.NewProc("DrawTextW")
pDrawIconEx = user32.NewProc("DrawIconEx")
pGetSystemMetrics = user32.NewProc("GetSystemMetrics")
pMoveWindow = user32.NewProc("MoveWindow")
pRegisterWindowMessage = user32.NewProc("RegisterWindowMessageW")
pRegisterHotKey = user32.NewProc("RegisterHotKey")
pUnregisterHotKey = user32.NewProc("UnregisterHotKey")
pKeybdEvent = user32.NewProc("keybd_event")
pLoadCursor = user32.NewProc("LoadCursorW")
pTrackMouseEvent = user32.NewProc("TrackMouseEvent")
pGetCursorPos = user32.NewProc("GetCursorPos")
pCreatePopupMenu = user32.NewProc("CreatePopupMenu")
pAppendMenu = user32.NewProc("AppendMenuW")
pTrackPopupMenu = user32.NewProc("TrackPopupMenu")
pDestroyMenu = user32.NewProc("DestroyMenu")
pSetForegroundWindow = user32.NewProc("SetForegroundWindow")
pGetForegroundWindow = user32.NewProc("GetForegroundWindow")
pSetProcessDPIAware = user32.NewProc("SetProcessDPIAware")
pGetDC = user32.NewProc("GetDC")
pReleaseDC = user32.NewProc("ReleaseDC")
pEnumWindows = user32.NewProc("EnumWindows")
pGetWindow = user32.NewProc("GetWindow")
pGetWindowLongPtr = user32.NewProc("GetWindowLongPtrW")
pGetWindowTextLength = user32.NewProc("GetWindowTextLengthW")
pGetWindowText = user32.NewProc("GetWindowTextW")
pGetClassName = user32.NewProc("GetClassNameW")
pGetClassLongPtr = user32.NewProc("GetClassLongPtrW")
pSendMessageTimeout = user32.NewProc("SendMessageTimeoutW")
pPostMessage = user32.NewProc("PostMessageW")
pCreateSolidBrush = gdi32.NewProc("CreateSolidBrush")
pDeleteObject = gdi32.NewProc("DeleteObject")
pCreateFont = gdi32.NewProc("CreateFontW")
pSelectObject = gdi32.NewProc("SelectObject")
pSetBkMode = gdi32.NewProc("SetBkMode")
pSetTextColor = gdi32.NewProc("SetTextColor")
pCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC")
pCreateDIBSection = gdi32.NewProc("CreateDIBSection")
pGdiFlush = gdi32.NewProc("GdiFlush")
pDeleteDC = gdi32.NewProc("DeleteDC")
pGetDeviceCaps = gdi32.NewProc("GetDeviceCaps")
pGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
pCreateMutex = kernel32.NewProc("CreateMutexW")
pSHAppBarMessage = shell32.NewProc("SHAppBarMessage")
pDwmGetWindowAttribute = dwmapi.NewProc("DwmGetWindowAttribute")
)
const (
wmDestroy = 0x0002
wmClose = 0x0010
wmPaint = 0x000F
wmSettingChange = 0x001A
wmEraseBkgnd = 0x0014
wmEndSession = 0x0016
wmGetIcon = 0x007F
wmDisplayChange = 0x007E
wmTimer = 0x0113
wmMouseMove = 0x0200
wmLButtonUp = 0x0202
wmRButtonUp = 0x0205
wmMouseLeave = 0x02A3
wmHotkey = 0x0312
wmUser = 0x0400
wsPopup = 0x80000000
wsVisible = 0x10000000
wsExToolWindow = 0x00000080
wsExTopmost = 0x00000008
wsExLayered = 0x00080000
wsExNoActivate = 0x08000000
wsExAppWindow = 0x00040000
swHide = 0
swMinimize = 6
swShowNA = 8
swRestore = 9
abmNew = 0
abmRemove = 1
abmQueryPos = 2
abmSetPos = 3
abmGetState = 4
abmSetState = 10
abeBottom = 3
abnPosChanged = 1
absAutoHide = 1
absAlwaysOnTop = 2
modAlt = 0x0001
modControl = 0x0002
vkLWin = 0x5B
keyUp = 0x0002
tmeLeave = 0x00000002
tpmRightButton = 0x0002
tpmBottomAlign = 0x0020
tpmReturnCmd = 0x0100
mfChecked = 0x0008
mfSeparator = 0x0800
dtLeft = 0x0000
dtCenter = 0x0001
dtVCenter = 0x0004
dtSingleLine = 0x0020
dtNoPrefix = 0x0800
transparent = 1
logPixelsX = 88
smCxScreen = 0
smCyScreen = 1
idcArrow = 32512
diNormal = 0x0003
gwOwner = 4
dwmaCloaked = 14
smtoAbort = 0x0002
ulwAlpha = 0x0002
errorAlreadyExists = 183
timerID = 1
hotkeyID = 1
menuExitID = 1
menuCloseID = 2
menuLevelBase = 11
autoQuitDef = 10 * time.Minute
// Colors as they sit in the bitmap (0xRRGGBB). The draw code uses these
// exact colors so the alpha pass can tell background from foreground.
colBg = 22<<16 | 22<<8 | 26
colHStart = 58<<16 | 58<<8 | 68
colHApp = 40<<16 | 40<<8 | 48
colActive = 52<<16 | 52<<8 | 62
)
type rect struct{ Left, Top, Right, Bottom int32 }
type point struct{ X, Y int32 }
type size struct{ CX, CY int32 }
type blendFunction struct {
Op, Flags, Alpha, Format byte
}
type bitmapInfoHeader struct {
Size uint32
Width int32
Height int32
Planes uint16
BitCount uint16
Compression uint32
SizeImage uint32
XPelsPerMeter int32
YPelsPerMeter int32
ClrUsed uint32
ClrImportant uint32
}
type wndClassEx struct {
Size uint32
Style uint32
WndProc uintptr
ClsExtra int32
WndExtra int32
Instance uintptr
Icon uintptr
Cursor uintptr
Background uintptr
MenuName *uint16
ClassName *uint16
IconSm uintptr
}
type msg struct {
Hwnd uintptr
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt point
}
type paintStruct struct {
Hdc uintptr
Erase int32
Rc rect
Restore int32
IncUpdate int32
Reserved [32]byte
}
type appBarData struct {
Size uint32
Hwnd uintptr
CallbackMsg uint32
Edge uint32
Rc rect
LParam uintptr
}
type trackMouseEvent struct {
Size uint32
Flags uint32
HwndTrack uintptr
HoverTime uint32
}
// appWin is one open window shown as an icon button on the left side of the bar.
type appWin struct {
hwnd uintptr
title string
icon uintptr
}
type alphaLevel struct {
name string
alpha int
}
var alphaLevels = []alphaLevel{
{"Clear", 3},
{"Light", 70},
{"Medium", 140},
{"Solid", 255},
}
var (
hwndMain uintptr
callbackMsg uint32 = wmUser + 1
taskbarCreated uint32
hoverStart bool
hoverApp = -1
trackingMouse bool
scale float64 = 1
barHeight int32
fontTime uintptr
fontDate uintptr
fontApp uintptr
startedAt time.Time
autoQuit time.Duration
tick int
restored bool
bgAlpha = 70
apps []appWin
enumFound []appWin
enumCb uintptr
lastFgSeen uintptr
)
func u16(s string) *uint16 {
p, _ := syscall.UTF16PtrFromString(s)
return p
}
func rgb(r, g, b int) uintptr { return uintptr(r | g<<8 | b<<16) }
func px(v float64) int32 { return int32(v*scale + 0.5) }
// neg turns a small negative number into the form Win32 index arguments expect.
func neg(n int) uintptr { return uintptr(n) }
func hasArg(name string) bool {
for _, a := range os.Args[1:] {
if strings.EqualFold(a, name) {
return true
}
}
return false
}
func dataDir() string {
base := os.Getenv("LOCALAPPDATA")
if base == "" {
base = os.TempDir()
}
return filepath.Join(base, "MirrorBar")
}
// ---------- settings ----------
func alphaFile() string { return filepath.Join(dataDir(), "alpha.txt") }
func loadAlpha() {
b, err := os.ReadFile(alphaFile())
if err != nil {
return
}
n, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil || n < 3 || n > 255 {
return
}
bgAlpha = n
}
func saveAlpha() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(alphaFile(), []byte(strconv.Itoa(bgAlpha)), 0o644)
}
// ---------- real taskbar handling ----------
func findTaskbar() uintptr {
h, _, _ := pFindWindow.Call(uintptr(unsafe.Pointer(u16("Shell_TrayWnd"))), 0)
return h
}
func appBar(message uintptr, abd *appBarData) uintptr {
abd.Size = uint32(unsafe.Sizeof(*abd))
r, _, _ := pSHAppBarMessage.Call(message, uintptr(unsafe.Pointer(abd)))
return r
}
func stateFile() string { return filepath.Join(dataDir(), "state.txt") }
func saveOriginalState(owner uintptr) {
f := stateFile()
if _, err := os.Stat(f); err == nil {
return // a state is already saved from an earlier run, keep the true original
}
abd := appBarData{Hwnd: owner}
st := appBar(abmGetState, &abd)
_ = os.MkdirAll(filepath.Dir(f), 0o755)
_ = os.WriteFile(f, []byte(strconv.Itoa(int(st))), 0o644)
}
func loadOriginalState() uintptr {
b, err := os.ReadFile(stateFile())
if err != nil {
return absAlwaysOnTop
}
n, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil {
return absAlwaysOnTop
}
return uintptr(n)
}
func setTaskbarState(owner uintptr, state uintptr) {
abd := appBarData{Hwnd: owner, LParam: state}
appBar(abmSetState, &abd)
}
func hideTaskbar() {
tb := findTaskbar()
if tb == 0 {
return
}
vis, _, _ := pIsWindowVisible.Call(tb)
if vis != 0 {
pShowWindow.Call(tb, swHide)
}
}
// restoreAll brings the real taskbar back exactly as it was.
func restoreAll() {
tb := findTaskbar()
if tb != 0 {
setTaskbarState(tb, loadOriginalState())
pShowWindow.Call(tb, swShowNA)
}
_ = os.Remove(stateFile())
restored = true
}
// ---------- open windows ----------
func collectWindow(hwnd uintptr) {
if hwnd == hwndMain {
return
}
vis, _, _ := pIsWindowVisible.Call(hwnd)
if vis == 0 {
return
}
owner, _, _ := pGetWindow.Call(hwnd, gwOwner)
if owner != 0 {
return
}
ex, _, _ := pGetWindowLongPtr.Call(hwnd, neg(-20))
if ex&wsExToolWindow != 0 && ex&wsExAppWindow == 0 {
return
}
var cloaked uint32
pDwmGetWindowAttribute.Call(hwnd, dwmaCloaked, uintptr(unsafe.Pointer(&cloaked)), 4)
if cloaked != 0 {
return
}
n, _, _ := pGetWindowTextLength.Call(hwnd)
if n == 0 {
return
}
var cls [128]uint16
cn, _, _ := pGetClassName.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), 128)
switch syscall.UTF16ToString(cls[:cn]) {
case "Progman", "Shell_TrayWnd", "Shell_SecondaryTrayWnd", "Windows.UI.Core.CoreWindow":
return
}
var tb [512]uint16
tn, _, _ := pGetWindowText.Call(hwnd, uintptr(unsafe.Pointer(&tb[0])), 512)
enumFound = append(enumFound, appWin{hwnd: hwnd, title: syscall.UTF16ToString(tb[:tn])})
}
func fetchIcon(hwnd uintptr) uintptr {
var res uintptr
for _, which := range []uintptr{2, 0, 1} {
res = 0
pSendMessageTimeout.Call(hwnd, wmGetIcon, which, 0, smtoAbort, 40, uintptr(unsafe.Pointer(&res)))
if res != 0 {
return res
}
}
for _, idx := range []int{-34, -14} {
r, _, _ := pGetClassLongPtr.Call(hwnd, neg(idx))
if r != 0 {
return r
}
}
return 0
}
// 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) {
if idx < 0 || idx >= len(apps) {
return
}
h := apps[idx].hwnd
fg, _, _ := pGetForegroundWindow.Call()
iconic, _, _ := pIsIconic.Call(h)
switch {
case iconic != 0:
pShowWindow.Call(h, swRestore)
pSetForegroundWindow.Call(h)
case h == fg:
pShowWindow.Call(h, swMinimize)
default:
pSetForegroundWindow.Call(h)
}
}
// ---------- our bar ----------
func startWidth() int32 { return px(52) }
func clockWidth() int32 { return px(140) }
func screenSize() (int32, int32) {
w, _, _ := pGetSystemMetrics.Call(smCxScreen)
h, _, _ := pGetSystemMetrics.Call(smCyScreen)
return int32(w), int32(h)
}
// pillWidth is the width the bar needs: the wider of the two halves, doubled so
// the bar stays a mirror image around the center, plus a little padding.
func pillWidth() int32 {
sw, _ := screenSize()
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.
func barGap() int32 { return px(6) }
func positionBar(hwnd uintptr) {
pw, ph := pillSize()
if !customPos {
sw, sh := screenSize()
edge := uintptr(abeBottom)
if vertical {
edge = abeRight
}
abd := appBarData{Hwnd: hwnd, Edge: uint32(edge), Rc: rect{0, 0, sw, sh}}
appBar(abmQueryPos, &abd)
if vertical {
abd.Rc.Left = abd.Rc.Right - barHeight - barGap()
} else {
abd.Rc.Top = abd.Rc.Bottom - barHeight - barGap()
}
appBar(abmSetPos, &abd)
}
x, y := pillPos(pw, ph)
pMoveWindow.Call(hwnd, uintptr(x), uintptr(y), uintptr(pw), uintptr(ph), 1)
redraw(hwnd)
}
// appRects lays the app buttons out leftward from the Start button.
// Button 0 sits against Start; each later one is further left. If there are
// too many to fit, the buttons shrink to a minimum width and the oldest run
// off the left edge.
func appRects(clientW, clientH int32) []rect {
n := int32(len(apps))
if n == 0 {
return nil
}
right := clientW/2 - startWidth()
avail := right - px(8)
bw := px(36)
if avail/n < bw {
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
}
// 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) {
var rc rect
pGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
if vertical {
return rc.Bottom - rc.Top, rc.Right - rc.Left
}
return rc.Right - rc.Left, rc.Bottom - rc.Top
}
func appIndexAt(hwnd uintptr, x int32) int {
w, h := clientSize(hwnd)
for i, r := range appRects(w, h) {
if x >= r.Left && x < r.Right {
return i
}
}
return -1
}
// The bar is painted in layers (see render.go): one layer holds only the
// backgrounds and hover fills, another only the icons, text and symbols.
var layerFills, layerFg = true, true
// fill paints a background or hover rectangle (background layer only).
func fill(hdc uintptr, r rect, color uintptr) {
if layerFills {
fillRaw(hdc, r, color)
}
}
// fillFg paints a solid piece of a symbol (foreground layer only).
func fillFg(hdc uintptr, r rect, color uintptr) {
if layerFg {
fillRaw(hdc, r, color)
}
}
func fillRaw(hdc uintptr, r rect, color uintptr) {
{
b, _, _ := pCreateSolidBrush.Call(color)
pFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), b)
pDeleteObject.Call(b)
}
}
func drawTextFmt(hdc uintptr, s string, r rect, format uintptr) {
w := u16(s)
pDrawText.Call(hdc, uintptr(unsafe.Pointer(w)), ^uintptr(0), uintptr(unsafe.Pointer(&r)), format)
}
func drawText(hdc uintptr, s string, r rect) {
drawTextFmt(hdc, s, r, dtCenter|dtVCenter|dtSingleLine|dtNoPrefix)
}
// makeFont uses plain antialiasing (not ClearType) because ClearType's colored
// edges look wrong on a transparent window.
func makeFont(height int32, weight int) uintptr {
f, _, _ := pCreateFont.Call(
uintptr(-height), 0, 0, 0, uintptr(weight), 0, 0, 0,
1, 0, 0, 4, 0, uintptr(unsafe.Pointer(u16("Segoe UI"))))
return f
}
func drawLogo(hdc uintptr, r rect) {
sq := px(8)
gap := px(2)
total := sq*2 + gap
x := r.Left + (r.Right-r.Left-total)/2
y := r.Top + (r.Bottom-r.Top-total)/2
c := logoColor()
fillFg(hdc, rect{x, y, x + sq, y + sq}, c)
fillFg(hdc, rect{x + sq + gap, y, x + total, y + sq}, c)
fillFg(hdc, rect{x, y + sq + gap, x + sq, y + total}, c)
fillFg(hdc, rect{x + sq + gap, y + sq + gap, x + total, y + total}, c)
}
func drawClock(hdc uintptr, r rect) {
now := time.Now()
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, clockColor())
// Time and date on one line, like "11:32 PM 11/5/2026".
old, _, _ := pSelectObject.Call(hdc, fontTime)
drawText(hdc, now.Format("3:04 PM 1/2/2006"), r)
pSelectObject.Call(hdc, old)
}
// drawApps draws each open window as a small icon only, no label.
func drawApps(hdc uintptr, w, h int32) {
rects := appRects(w, h)
if len(rects) == 0 {
return
}
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(245, 245, 245))
old, _, _ := pSelectObject.Call(hdc, fontApp)
for i, r := range rects {
if i >= len(apps) {
break
}
a := apps[i]
inner := rect{r.Left + px(2), r.Top + px(3), r.Right - px(2), r.Bottom - px(3)}
if i == hoverApp {
fill(hdc, inner, rgb(40, 40, 48))
}
if !vertical && layerFg {
drawAppGlyph(hdc, inner, a)
}
}
pSelectObject.Call(hdc, old)
}
// drawAppGlyph draws one app's small icon (or its first letter) centered in r.
func drawAppGlyph(hdc uintptr, r rect, a appWin) {
isz := px(16) // the small taskbar icon size
if a.icon != 0 {
cx, cy := center(r)
pDrawIconEx.Call(hdc, uintptr(cx-isz/2), uintptr(cy-isz/2), a.icon, uintptr(isz), uintptr(isz), 0, 0, diNormal)
} else if rs := []rune(a.title); len(rs) > 0 {
pSetBkMode.Call(hdc, transparent)
pSetTextColor.Call(hdc, rgb(245, 245, 245))
old, _, _ := pSelectObject.Call(hdc, fontApp)
drawText(hdc, strings.ToUpper(string(rs[0])), r)
pSelectObject.Call(hdc, old)
}
}
func premul(c uint32, a uint32) uint32 {
r := (c >> 16 & 0xFF) * a / 255
g := (c >> 8 & 0xFF) * a / 255
b := (c & 0xFF) * a / 255
return a<<24 | r<<16 | g<<8 | b
}
func inStart(hwnd uintptr, x int32) bool {
w, _ := clientSize(hwnd)
cx := w / 2
return x >= cx-startWidth() && x < cx
}
func tapWinKey() {
pKeybdEvent.Call(vkLWin, 0, 0, 0)
pKeybdEvent.Call(vkLWin, 0, keyUp, 0)
}
// windowExePath returns the full path of the program that owns a window, or ""
// when it can't be found or the window belongs to the Windows app host
// (Settings, Store apps), which can't be launched again by path.
func windowExePath(h uintptr) string {
var pid uint32
pGetWindowThreadProcessId.Call(h, uintptr(unsafe.Pointer(&pid)))
if pid == 0 {
return ""
}
proc, _, _ := pOpenProcess.Call(0x1000, 0, uintptr(pid)) // PROCESS_QUERY_LIMITED_INFORMATION
if proc == 0 {
return ""
}
defer pCloseHandle.Call(proc)
var buf [1024]uint16
n := uint32(len(buf))
r, _, _ := pQueryFullProcessImage.Call(proc, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)))
if r == 0 {
return ""
}
path := syscall.UTF16ToString(buf[:n])
if strings.EqualFold(filepath.Base(path), "ApplicationFrameHost.exe") {
return ""
}
return path
}
func shellOpen(file, params string) {
var p uintptr
if params != "" {
p = uintptr(unsafe.Pointer(u16(params)))
}
pShellExecute.Call(0, uintptr(unsafe.Pointer(u16("open"))), uintptr(unsafe.Pointer(u16(file))), p, 0, 1)
}
// showMenu pops up the right-click menu. Over an app icon it starts with that
// window's own options (the same ones its title bar menu has), then the
// MirrorBar settings. Over empty bar it shows only the settings.
func showMenu(hwnd uintptr, appIdx int, trayKind int) {
menu, _, _ := pCreatePopupMenu.Call()
add := func(flags uintptr, id uintptr, text string) {
pAppendMenu.Call(menu, flags, id, uintptr(unsafe.Pointer(u16(text))))
}
sep := func() { pAppendMenu.Call(menu, mfSeparator, 0, 0) }
// Remember which window this menu is for. The list can change while the
// menu is open, so don't go back to the index afterwards.
var target uintptr
var exe string
if appIdx >= 0 && appIdx < len(apps) {
target = apps[appIdx].hwnd
title := []rune(apps[appIdx].title)
text := string(title)
if len(title) > 40 {
text = string(title[:40]) + "..."
}
add(mfGrayed, 0, strings.ReplaceAll(text, "&", "&&"))
sep()
exe = windowExePath(target)
if exe != "" {
add(0, menuNewWindowID, "Open new window")
add(0, menuFileLocID, "Open file location")
sep()
}
style, _, _ := pGetWindowLongPtr.Call(target, neg(-16)) // GWL_STYLE
iconic, _, _ := pIsIconic.Call(target)
zoomed, _, _ := pIsZoomed.Call(target)
normal := iconic == 0 && zoomed == 0
enabled := func(ok bool) uintptr {
if ok {
return 0
}
return mfGrayed
}
add(enabled(!normal), menuRestoreID, "Restore")
add(enabled(normal), menuMoveID, "Move")
add(enabled(normal && style&wsThickFrame != 0), menuSizeID, "Size")
add(enabled(iconic == 0 && style&wsMinimizeBox != 0), menuMinimizeID, "Minimize")
add(enabled(zoomed == 0 && style&wsMaximizeBox != 0), menuMaximizeID, "Maximize")
sep()
add(0, menuCloseID, "Close window")
sep()
}
if appIdx < 0 {
addTrayMenu(add, sep, trayKind)
}
for i, l := range alphaLevels {
var flags uintptr
if bgAlpha == l.alpha {
flags = mfChecked
}
add(flags, uintptr(menuLevelBase+i), "Background: "+l.name)
}
sep()
addColorMenus(menu)
sep()
orientText := "Switch to vertical"
if vertical {
orientText = "Switch to horizontal"
}
add(0, menuOrientID, orientText)
var posFlags uintptr
if !customPos {
posFlags = mfGrayed
}
add(posFlags, menuResetPosID, "Reset position to bottom center")
var autoFlags uintptr
if autostartEnabled() {
autoFlags = mfChecked
}
add(autoFlags, menuAutostartID, "Start MirrorBar when I sign in")
sep()
add(0, menuExitID, "Exit MirrorBar and restore taskbar")
var pt point
pGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
pSetForegroundWindow.Call(hwnd)
cmd, _, _ := pTrackPopupMenu.Call(menu, tpmRightButton|tpmBottomAlign|tpmReturnCmd,
uintptr(pt.X), uintptr(pt.Y), 0, hwnd, 0)
pDestroyMenu.Call(menu)
sysCommands := map[uintptr]uintptr{
menuRestoreID: scRestore,
menuMoveID: scMove,
menuSizeID: scSize,
menuMinimizeID: scMinimize,
menuMaximizeID: scMaximize,
}
switch {
case cmd == menuExitID:
pDestroyWindow.Call(hwnd)
case cmd == menuResetPosID:
resetPos(hwnd)
case handleColorCommand(cmd):
redraw(hwnd)
case cmd == menuOrientID:
vertical = !vertical
saveOrient()
resetPos(hwnd)
case cmd == menuCloseID && target != 0:
pPostMessage.Call(target, wmClose, 0, 0)
case cmd == menuNewWindowID && exe != "":
shellOpen(exe, "")
case cmd == menuFileLocID && exe != "":
shellOpen("explorer.exe", `/select,"`+exe+`"`)
case target != 0 && sysCommands[cmd] != 0:
if cmd != menuMinimizeID {
pSetForegroundWindow.Call(target)
}
pPostMessage.Call(target, wmSysCommand, sysCommands[cmd], 0)
case handleTrayCommand(cmd):
redraw(hwnd)
case cmd >= menuLevelBase && cmd < menuLevelBase+uintptr(len(alphaLevels)):
bgAlpha = alphaLevels[cmd-menuLevelBase].alpha
saveAlpha()
redraw(hwnd)
}
}
func wndProc(hwnd, m, wparam, lparam uintptr) (result uintptr) {
defer func() {
if r := recover(); r != nil {
restoreAll()
os.Exit(1)
}
}()
switch uint32(m) {
case wmEraseBkgnd:
return 1
case wmPaint:
// The bar is a layered window drawn by redraw(); just mark this paint as handled.
var ps paintStruct
pBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
pEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
return 0
case wmTimer:
hideTaskbar()
tick++
changed := refreshApps(tick%16 == 0)
if tick%4 == 0 && refreshStatus(tick%16 == 0) {
changed = true
}
fg, _, _ := pGetForegroundWindow.Call()
if fg != lastFgSeen {
lastFgSeen = fg
changed = true
}
if changed || tick%4 == 0 {
redraw(hwnd)
}
if autoQuit > 0 && time.Since(startedAt) >= autoQuit {
pDestroyWindow.Call(hwnd)
}
return 0
case wmMouseMove:
x := alongClient(lparam)
overStart := inStart(hwnd, x)
overApp := appIndexAt(hwnd, x)
overTray := trayAt(hwnd, x)
if overStart != hoverStart || overApp != hoverApp || overTray != hoverTray {
hoverStart = overStart
hoverApp = overApp
hoverTray = overTray
redraw(hwnd)
}
if !trackingMouse {
tme := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, HwndTrack: hwnd}
pTrackMouseEvent.Call(uintptr(unsafe.Pointer(&tme)))
trackingMouse = true
}
return 0
case wmMouseLeave:
trackingMouse = false
if hoverStart || hoverApp != -1 || hoverTray != 0 {
hoverStart = false
hoverApp = -1
hoverTray = 0
redraw(hwnd)
}
return 0
case wmLButtonUp:
x := alongClient(lparam)
if inStart(hwnd, x) {
tapWinKey()
} else if idx := appIndexAt(hwnd, x); idx >= 0 {
activateApp(idx)
redraw(hwnd)
} else if k := trayAt(hwnd, x); k != 0 {
trayClick(k)
}
return 0
case wmRButtonUp:
x := alongClient(lparam)
showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x))
return 0
case wmMouseWheel:
// Scrolling over the volume icon changes the volume. The wheel
// position arrives in screen coordinates, so make it relative to the bar.
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
x := alongScreen(lparam, wr)
if trayAt(hwnd, x) == trayVolume {
nudgeVolume(int(int16(wparam>>16)) / 120)
redraw(hwnd)
}
return 0
case wmNcHitTest:
// Buttons act as buttons; everything else on the pill drags it.
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
x := alongScreen(lparam, wr)
if inStart(hwnd, x) || appIndexAt(hwnd, x) >= 0 || trayAt(hwnd, x) != 0 {
return htClient
}
return htCaption
case wmNcLButtonDblClk:
return 0 // a double click on the drag area must not maximize the pill
case wmNcRButtonUp:
var wr rect
pGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&wr)))
x := alongScreen(lparam, wr)
showMenu(hwnd, appIndexAt(hwnd, x), trayAt(hwnd, x))
return 0
case wmEnterSizeMove:
dragging = true
return 0
case wmExitSizeMove:
finishDrag(hwnd)
return 0
case wmHotkey:
if wparam == hotkeyID {
pDestroyWindow.Call(hwnd)
}
return 0
case wmDisplayChange, wmSettingChange:
positionBar(hwnd)
return 0
case wmEndSession:
if wparam != 0 {
restoreAll()
}
return 0
case wmDestroy:
abd := appBarData{Hwnd: hwnd}
appBar(abmRemove, &abd)
pKillTimer.Call(hwnd, timerID)
pUnregisterHotKey.Call(hwnd, hotkeyID)
restoreAll()
pPostQuitMessage.Call(0)
return 0
}
if uint32(m) == callbackMsg {
if wparam == abnPosChanged {
positionBar(hwnd)
}
return 0
}
if taskbarCreated != 0 && uint32(m) == taskbarCreated {
// Explorer restarted and rebuilt the taskbar: hide it again.
tb := findTaskbar()
if tb != 0 {
setTaskbarState(tb, absAutoHide|absAlwaysOnTop)
}
hideTaskbar()
positionBar(hwnd)
return 0
}
r, _, _ := pDefWindowProc.Call(hwnd, m, wparam, lparam)
return r
}
func main() {
// Launched under the name restore_taskbar.exe, or with --restore: just bring it back.
name := strings.ToLower(filepath.Base(os.Args[0]))
if hasArg("--restore") || strings.Contains(name, "restore") {
restoreAll()
return
}
// Escape hatch: hold Shift while it starts (for example at sign-in) to skip it entirely.
if shiftHeld() {
return
}
pSetProcessDPIAware.Call()
// Only one copy at a time.
_, _, err := pCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(u16("Local\\MirrorBarPoC"))))
if errno, ok := err.(syscall.Errno); ok && errno == errorAlreadyExists {
return
}
loadAlpha()
loadPos()
loadOrient()
hdc, _, _ := pGetDC.Call(0)
dpi, _, _ := pGetDeviceCaps.Call(hdc, logPixelsX)
pReleaseDC.Call(0, hdc)
if dpi > 0 {
scale = float64(dpi) / 96.0
}
barHeight = px(36)
fontTime = makeFont(px(13), 400)
fontDate = makeFont(px(11), 400)
fontApp = makeFont(px(12), 600)
initSuperFonts()
loadColors()
autoQuit = autoQuitDef
if hasArg("--forever") || strings.Contains(name, "forever") {
autoQuit = 0
}
startedAt = time.Now()
enumCb = syscall.NewCallback(func(hwnd, lparam uintptr) uintptr {
collectWindow(hwnd)
return 1
})
inst, _, _ := pGetModuleHandle.Call(0)
cursor, _, _ := pLoadCursor.Call(0, idcArrow)
className := u16("MirrorBarWindow")
wc := wndClassEx{
WndProc: syscall.NewCallback(wndProc),
Instance: inst,
Cursor: cursor,
ClassName: className,
}
wc.Size = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
taskbarCreated64, _, _ := pRegisterWindowMessage.Call(uintptr(unsafe.Pointer(u16("TaskbarCreated"))))
taskbarCreated = uint32(taskbarCreated64)
sw, sh := screenSize()
hwnd, _, _ := pCreateWindowEx.Call(
wsExToolWindow|wsExTopmost|wsExNoActivate|wsExLayered,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(u16("MirrorBar"))),
wsPopup|wsVisible,
0, uintptr(sh-barHeight), uintptr(sw), uintptr(barHeight),
0, 0, inst, 0)
if hwnd == 0 {
return
}
hwndMain = hwnd
refreshAutostartPath()
// Hotkey: Ctrl+Alt+Q exits and restores.
pRegisterHotKey.Call(hwnd, hotkeyID, modControl|modAlt, 'Q')
// Release the real taskbar's reserved screen space, remember how it was, hide it.
tb := waitForTaskbar(12 * time.Second)
if tb != 0 {
saveOriginalState(hwnd)
setTaskbarState(hwnd, absAutoHide|absAlwaysOnTop)
time.Sleep(300 * time.Millisecond)
hideTaskbar()
}
// Register as an app bar so maximized windows stop above us.
if customPos {
appbarOn = false
} else {
abd := appBarData{Hwnd: hwnd, CallbackMsg: callbackMsg}
appBar(abmNew, &abd)
}
pCoInitializeEx.Call(0, 2) // COINIT_APARTMENTTHREADED, needed for the volume control
refreshStatus(true)
refreshApps(true)
positionBar(hwnd)
pSetTimer.Call(hwnd, timerID, 250, 0)
var m msg
for {
r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
if int32(r) <= 0 {
break
}
pTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
pDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
}
if !restored {
restoreAll()
}
}