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