diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rs index 2f463d84..18edb3f5 100644 --- a/plugins/topbar/src/main.rs +++ b/plugins/topbar/src/main.rs @@ -1,4015 +1,4021 @@ -// topbar: replaces the Windows taskbar with a panel on the chosen screen edge, -// drawn in the Windows 11 taskbar palette: Start, pinned apps and open windows in the center; tray apps, language, wifi, -// volume, battery and date/time on the right. `--restore` brings the normal taskbar back (used by uninstall). -#![windows_subsystem = "windows"] -#![allow(unsafe_op_in_unsafe_fn)] -use std::{ - cell::{Cell, RefCell}, - mem::{size_of, zeroed}, - os::windows::process::CommandExt, - path::PathBuf, - process::Command, - ptr::{null, null_mut}, - thread, - sync::Mutex, - collections::HashMap, - sync::atomic::{AtomicBool, AtomicIsize, Ordering::Relaxed}, -}; -#[macro_use] -extern crate winrust_common; -use winrust_common as i18n; -use winrust_common::style::{Style, card, on_accent, pal, rgb, style, ui_face}; -mod clip; -mod widgets; // the mods' widgets on the bar -mod hist; -mod fly; -mod quick; -mod tray; -mod status; -mod run; -mod shot; -mod lang; -mod settings; -mod second; // a bar on every other monitor -mod notif; // notifications under the calendar -mod thumbs; -mod wmi; -use {tray::*, status::*, run::*, shot::*, lang::*, settings::*}; -use windows::{ - Win32::{ - Media::Audio::{Endpoints::IAudioEndpointVolume, IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender}, - System::Com::{CLSCTX_ALL, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, IPersistFile, STGM}, - UI::Shell::{IShellLinkW, ShellLink}, - }, - core::{Interface, PCWSTR}, -}; -use windows_sys::Win32::{ - Foundation::*, - Globalization::{GetDateFormatW, GetLocaleInfoW, GetTimeFormatW}, - Graphics::{ - Dwm::DwmGetWindowAttribute, - Gdi::*, - GdiPlus::{ - FillModeAlternate, GdipAddPathArc, GdipClosePathFigure, GdipCreateFromHDC, GdipCreatePath, GdipCreateSolidFill, GdipDeleteBrush, GdipDeleteGraphics, GdipDeletePath, GdipFillPath, GdipSetPixelOffsetMode, - GdipSetSmoothingMode, GdiplusStartup, GdiplusStartupInput, GpBrush, GpGraphics, GpPath, GpSolidFill, PixelOffsetModeHalf, SmoothingModeAntiAlias, - GdipCreatePen1, GdipDeletePen, GdipDrawArc, GdipDrawLine, GdipFillEllipse, GdipSetPenEndCap, GdipSetPenStartCap, GpPen, LineCapRound, UnitPixel, - }, - }, - NetworkManagement::WiFi::*, - System::{ - LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW}, - Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS}, - SystemInformation::{GetLocalTime, GetTickCount64}, - Threading::{OpenProcess, QueryFullProcessImageNameW, TerminateProcess}, - }, - UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*}, -}; - -/// A corner radius in logical px, 0 in the square styles. -fn rr(v: i32) -> i32 { - if style().square() { 0 } else { sc(v) } -} -/// The bar sits at the top of the screen (by position setting or tiling theme). -fn at_top() -> bool { - !vert() && (i18n::style::side() == i18n::style::Side::Top || style() == Style::Tiling) -} -/// The bar stands on the left or right edge of the screen (its "width" is bar_h(), it spans the screen height). -fn vert() -> bool { - matches!(i18n::style::side(), i18n::style::Side::Left | i18n::style::Side::Right) -} -/// The floating dock (a pill in the middle of the bottom edge). -fn dock() -> bool { - style() == Style::Dock && i18n::style::side() == i18n::style::Side::Bottom -} -/// Screen x of a side bar's current left edge, slid away by the show/hide animation. -unsafe fn bar_x() -> i32 { - if i18n::style::side() == i18n::style::Side::Left { -bar_off() } else { GetSystemMetrics(SM_CXSCREEN) - bar_h() + bar_off() } -} -/// Top-left of the bar window now. -unsafe fn bar_pos() -> (i32, i32) { - if vert() { (bar_x(), 0) } else { (bar_x_w().0, bar_y()) } -} -/// Screen x of a popup of width `w` next to a side bar. -unsafe fn side_x(w: i32) -> i32 { - if i18n::style::side() == i18n::style::Side::Left { bar_h() + sc(8) } else { GetSystemMetrics(SM_CXSCREEN) - bar_h() - sc(8) - w } -} -/// Length of the bar's long axis: the screen height for a side bar, the width otherwise. -unsafe fn axis_len() -> i32 { - GetSystemMetrics(if vert() { SM_CYSCREEN } else { SM_CXSCREEN }) -} -/// Gap under the floating dock. -fn dock_gap() -> i32 { - if dock() { sc(8) } else { 0 } -} -/// Screen x and width of the bar: the whole screen, or the dock in the middle. -unsafe fn bar_x_w() -> (i32, i32) { - let cx = GetSystemMetrics(SM_CXSCREEN); - if dock() { - let w = (cx * 3 / 5).max(sc(720)).min(cx); - ((cx - w) / 2, w) - } else { - (0, cx) - } -} -/// Screen y of the bar's current top edge, slid away by the show/hide animation. -unsafe fn bar_y() -> i32 { - if at_top() { -bar_off() } else { bar_top() + bar_off() } -} -/// Screen y of a popup of height `h` next to the bar: above it, or below it when the bar is at the top. -unsafe fn pop_y(h: i32) -> i32 { - if vert() { GetSystemMetrics(SM_CYSCREEN) - sc(8) - h } else if at_top() { bar_h() + sc(8) } else { bar_top() - sc(8) - h } -} -const GOOD: u32 = winrust_common::style::GOOD; -const BAD: u32 = winrust_common::style::BAD; -const WARN: u32 = winrust_common::style::WARN; -const CALLBACK: u32 = WM_APP + 1; -const WM_MOUSELEAVE: u32 = 0x02A3; // not exported under the enabled features -const NO_WINDOW: u32 = 0x0800_0000; -const BAR_H: i32 = 40; -// hit-test results. Buttons (Start, pins, windows) are >= 0 in left-to-right order; tray apps are TAPP + index. -const NONE: i32 = -1; -const SEARCH: i32 = -10; -const TASKVIEW: i32 = -14; // Task View button (virtual desktops), right of search (#83) -const LEAD: i32 = 2; // slots before Start: search, Task View -const CLOCK: i32 = -4; -const LANG: i32 = -6; -const WIFI_I: i32 = -7; -const VOL_I: i32 = -8; -const BAT_I: i32 = -9; -const TAPP: i32 = -1000; -const SHOWDESK: i32 = -13; // the thin strip right of the clock: show desktop (#87) -const GEAR: i32 = -12; // the gear at the left end: the Style menu -const GEAR_X: (i32, i32) = (6, 36); // its left edge and width, before scaling (sc() is applied where used) -const POW_R: i32 = -15; // Restart button next to the clock (#173) -const POW_S: i32 = -16; // Shut down button -// The right group: the language label, then one pill with the wifi, the volume and (on a laptop) the battery with its -// percentage. layout() adds these up and paint() draws them at the same offsets, so the group is as wide as it draws. -const SYS_LANG: i32 = 42; // the language label's slot -const SYS_WIFI: i32 = 32; // the wifi icon's slot -const SYS_VOL: i32 = 22; // the volume glyph -const SYS_BAT_W: i32 = 22; // the battery itself -const SYS_BAT_PCT: i32 = 40; // the percentage next to it -const SYS_BAT: i32 = SYS_BAT_W + 8 + SYS_BAT_PCT; // 70: the battery and the percentage -const SYS_END: i32 = 2; // air after the last icon, inside the pill -const CLOCK_PAD: i32 = 10; // air on each side of the clock block -const CLOCK_MIN: i32 = 72; // a short date ("1/1/2026") must not make the block hug its edges -const SYS_GRP: i32 = -11; // hover key of the one pill around wifi + volume + battery (they open the same panel) -const WIN_START: u32 = WM_APP + 10; // posted by the keyboard hook: Win key pressed alone -const ALT_TAB: u32 = WM_APP + 11; // posted by the keyboard hook: Alt+Tab (wp 1 = Shift held: backwards) -const ALT_UP: u32 = WM_APP + 12; // posted by the keyboard hook: Alt released while switching (wp 1 = Esc: cancel) -static SWITCHING: AtomicBool = AtomicBool::new(false); // Alt+Tab switcher open (the hook thread reads it) -static FULLSCREEN: AtomicBool = AtomicBool::new(false); -static DESK_HIDE: AtomicBool = AtomicBool::new(false); // the desktop in front and the pointer away from the bar for 2 s -static WIN_ALONE: AtomicBool = AtomicBool::new(false); -static BAR: AtomicIsize = AtomicIsize::new(0); // the bar window, for the hook thread -const WIN_NUM: u32 = WM_APP + 15; // posted by the keyboard hook: Win+1..9 (wp 0..8) = the n-th button of the bar -const WIN_X: u32 = WM_APP + 17; // posted by the keyboard hook: Win+X = our power-user menu (start_menu) -const NEXT_LANG: u32 = WM_APP + 16; // posted by the keyboard hook: Win+Space with no explorer (wp 1 = Shift held: previous layout) -const TILE_WINDOWS: u32 = WM_APP + 19; // posted by the keyboard hook: Ctrl+Alt+T -const VOLKEY: u32 = WM_APP + 14; // posted by the keyboard hook: a volume key (wp 0 up, 1 down, 2 mute) -const WIN_V: u32 = WM_APP + 18; // posted by the keyboard hook: Win+V with no explorer (our clipboard history, #171) -const SNIP: u32 = WM_APP + 13; // posted by the keyboard hook: PrtSc / Win+Shift+S with no explorer to handle them -static EXPLORER_UP: AtomicBool = AtomicBool::new(true); // explorer's taskbar exists (it handles PrtSc itself then); refreshed by the bar - -struct Pin { - lnk: Vec, - target: String, // lower-case exe path, "" if unknown - args: String, // what the shortcut passes to it (browser profile), "" if none - aumid: String, // lower-case AppUserModelID the shortcut carries (a browser profile's own, #132), "" if none - icon: HICON, -} -struct Btn { - pin: Option, - wins: Vec, - icon: HICON, // the window's icon for unpinned buttons, looked up on refresh, not every animation frame -} - -/// One notification-area icon, as an app registered it through Shell_NotifyIcon (we own the "Shell_TrayWnd" they talk to). -struct TIcon { - hwnd: HWND, // the app's callback window - uid: u32, - guid: [u8; 16], // zero unless the app identifies the icon by GUID - icon: HICON, // our own copy - cb: u32, // uCallbackMessage - ver: u32, // NIM_SETVERSION value; >= 4 means the NOTIFYICON_VERSION_4 message format - hidden: bool, - tip: String, - key: String, // owner exe file name, lower-case: what the "keep on the bar" choice is stored under -} -const WM_COPYDATA: u32 = 0x4A; -#[repr(C)] -struct Cds { - dw: usize, - cb: u32, - p: *const u8, -} -static USAGE: Mutex>> = Mutex::new(None); // launches per shortcut name, lower-case - -fn appdata_file(name: &str) -> PathBuf { - PathBuf::from(std::env::var_os("APPDATA").unwrap_or_default()).join(name) -} -fn uses(name: &str) -> u32 { - USAGE - .lock() - .unwrap() - .get_or_insert_with(|| std::fs::read_to_string(appdata_file("topbar-usage.txt")).unwrap_or_default().lines().filter_map(|l| l.rsplit_once('\t')).filter_map(|(k, n)| Some((k.to_string(), n.parse().ok()?))).collect()) - .get(name) - .copied() - .unwrap_or(0) -} -/// Counts one launch of the shortcut at `path` (by file name, so the same app pinned and in Start counts together). -fn bump(path: &str) { - bump_name(&std::path::Path::new(path).file_stem().unwrap_or_default().to_string_lossy()); -} -/// Counts one launch of the app called `name` (Start search ranks by it). -fn bump_name(name: &str) { - let name = name.to_lowercase(); - uses(&name); // loads the file first - let mut g = USAGE.lock().unwrap(); - let m = g.as_mut().unwrap(); - *m.entry(name).or_insert(0) += 1; - let _ = std::fs::write(appdata_file("topbar-usage.txt"), m.iter().map(|(k, n)| format!("{k}\t{n}\n")).collect::()); -} -fn lnk_uses(lnk: &std::path::Path) -> u32 { - uses(&lnk.file_stem().unwrap_or_default().to_string_lossy().to_lowercase()) -} - -thread_local! { - static HOST: Cell = const { Cell::new(null_mut()) }; - static SKIP: RefCell> = const { RefCell::new(Vec::new()) }; // windows their app took off the taskbar (ITaskbarList::DeleteTab) - static TIPWND: Cell = const { Cell::new(null_mut()) }; - static SWWND: Cell = const { Cell::new(null_mut()) }; // the Alt+Tab switcher - static SW: RefCell<(Vec, usize)> = const { RefCell::new((Vec::new(), 0)) }; // its windows (z-order) and selection - static TIP: RefCell = const { RefCell::new(String::new()) }; - static PINS: RefCell> = const { RefCell::new(Vec::new()) }; - static BTNS: RefCell> = const { RefCell::new(Vec::new()) }; // [0] is always Start (pin None, no wins) - static BUTTON_ORDER: RefCell> = const { RefCell::new(Vec::new()) }; - static TAPPS: RefCell> = const { RefCell::new(Vec::new()) }; - static SHOWN: RefCell>> = const { RefCell::new(None) }; // tray icons kept on the bar (by exe); None = none: every tray icon lives in the chevron flyout - static TRAYFLY: Cell = const { Cell::new(null_mut()) }; - static TF_ANIM: Cell<(u64, i32, i32)> = const { Cell::new((0, 0, 0)) }; // tray flyout: when it opened, its final x, y - static FHOT: Cell = const { Cell::new(-1) }; - static HOT: Cell = const { Cell::new(NONE) }; - static ORDER: RefCell> = const { RefCell::new(Vec::new()) }; // unpinned windows in the order their buttons were added - static HV: RefCell> = RefCell::new(HashMap::new()); // hover fade per element: (0..1, last update ms) - static BUSY: Cell = const { Cell::new(false) }; // a fade is still running: the painter asks for another frame - static BAR_P: Cell = const { Cell::new(0.0) }; // bar slide: 0 = off screen, 1 = in place - static BAR_T: Cell = const { Cell::new(0) }; - static DESK_T: Cell = const { Cell::new(0) }; // last moment the bar had a reason to stay on the desktop - static SCALE: Cell = const { Cell::new(1.0) }; - static FS_WND: Cell = const { Cell::new(0) }; // the window last seen fullscreen (fullscreen_now) - static FS_OFF: Cell = const { Cell::new(0) }; // when a fullscreen window was last missing, ms (0 = it is there) - static OLD_STATE: Cell = const { Cell::new(ABS_ALWAYSONTOP as usize) }; - static BAT: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = no battery, on AC) - static VOL: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = unknown, muted) - static WIFI: Cell = const { Cell::new(-1) }; // signal quality 0..100, -1 = not on wifi - static INET: Cell = const { Cell::new(true) }; // Windows sees a way to the internet (any adapter) - static TICK: Cell = const { Cell::new(0) }; - static EP: RefCell> = const { RefCell::new(None) }; - static TB_MSG: Cell = const { Cell::new(0) }; // "TaskbarCreated" - static SH_MSG: Cell = const { Cell::new(0) }; // "SHELLHOOK": window events for the shell (we are the shell hook window without explorer) - static EXP_TRAY: Cell = const { Cell::new(null_mut()) }; // explorer's taskbar we registered with - static FLASH: RefCell> = const { RefCell::new(Vec::new()) }; // windows asking for attention (FlashWindowEx) until activated (#129) - static APP_FG: Cell = const { Cell::new(null_mut()) }; // last foreground window that is not ours: the language button acts on it - static LANG_TRY: Cell<(u32, usize, usize)> = const { Cell::new((0, 0, 0)) }; // (thread, layout before, layout asked for) of the last switch, checked by timer 7 - static BAR_WORK: Cell<(i32, i32, i32, i32)> = const { Cell::new((-1, -1, -1, -1)) }; // last work area reserved by place() -} - -fn wide(s: &str) -> Vec { - s.encode_utf16().chain([0]).collect() -} -fn sc(v: i32) -> i32 { - (v as f32 * SCALE.get()) as i32 -} -/// Taskbar symbols use the chosen size; slots and hit targets stay unchanged. -fn icon_sc(v: i32) -> i32 { - sc((v as f32 * i18n::style::icon_size() as f32 / 100.0).round() as i32).max(1) -} -fn bar_h() -> i32 { - let d = [-6, 0, 8][i18n::style::bar_size() as usize % 3]; // small / normal / large - if vert() { sc(60 + d) } else { sc(BAR_H + d) } -} -/// The width of the right group: exactly what paint() draws at those offsets. A wider slot was a hole between the -/// volume icon and the clock (and a click on empty space opened the battery panel). -fn sys_w() -> i32 { - sc(SYS_LANG + SYS_WIFI + SYS_VOL + SYS_END + if BAT.get().0 >= 0 { SYS_BAT } else { 0 }) -} -/// Width and height of `s` in the font `f` of `dc`. -unsafe fn text_size(dc: HDC, f: HFONT, s: &str) -> (i32, i32) { - SelectObject(dc, f); - let w = wide(s); - let mut sz: SIZE = zeroed(); - GetTextExtentPoint32W(dc, w.as_ptr(), w.len() as i32 - 1, &mut sz); - (sz.cx, sz.cy) -} -/// The clock cell: the wider of the time and the date in the bar's own fonts (the ones it paints them with), with the -/// same air on both sides, so a narrow clock ("9:05") and a wide date sit the same in it. -fn clock_w() -> i32 { - unsafe { - let [_, f_small, _, f_bold] = bar_fonts(); - let dc = CreateCompatibleDC(null_mut()); - let (tm, dt) = clock_texts(); - let w = clock_cell_w(text_size(dc, f_bold, &tm).0, text_size(dc, f_small, &dt).0); - DeleteDC(dc); - w - } -} -/// The cell of the clock: the wider of its two lines plus the same air on both sides. -fn clock_cell_w(tw: i32, dw: i32) -> i32 { - (tw.max(dw) + 2 * sc(CLOCK_PAD)).max(sc(CLOCK_MIN)) -} -/// Screen y of the bar's top edge when it is in place (bottom of the primary monitor, or its top in the tiling style). -unsafe fn bar_top() -> i32 { - if at_top() { 0 } else { GetSystemMetrics(SM_CYSCREEN) - bar_h() - dock_gap() } -} - -// ---------- taskbar / appbar ---------- - -const FCELL: i32 = 38; - -/// (columns, window width, window height) for the current number of icons. -fn fly_size() -> (usize, i32, i32) { - let n = over_idx().len().max(1); - let cols = n.min(6); - (cols, sc(FCELL) * cols as i32 + sc(16), sc(FCELL) * n.div_ceil(cols) as i32 + sc(16) + sc(26)) -} - -unsafe fn fly_toggle() { - let w = TRAYFLY.get(); - if IsWindowVisible(w) != 0 { - ShowWindow(w, SW_HIDE); - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it - return; - } - let (_, fw, fh) = fly_size(); - FHOT.set(-1); - let scr = GetSystemMetrics(SM_CXSCREEN); - let (bx, bw) = bar_x_w(); - let cx = bx + layout(if vert() { axis_len() } else { bw }).apps.0 + sc(12); // above the chevron - SetWindowRgn(w, CreateRoundRectRgn(0, 0, fw + 1, fh + 1, rr(12), rr(12)), 1); - let (x, y) = if vert() { (side_x(fw), (cx - fh / 2).min(GetSystemMetrics(SM_CYSCREEN) - fh - sc(8)).max(sc(8))) } else { ((cx - fw / 2).min(scr - fw - sc(8)).max(sc(8)), pop_y(fh)) }; - TF_ANIM.set((now_ms(), x, y)); - SetLayeredWindowAttributes(w, 0, 0, LWA_ALPHA); // tf_step fades it in - SetWindowPos(w, HWND_TOPMOST, x, y + tf_slide(0.0), fw, fh, SWP_SHOWWINDOW); - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it - SetTimer(w, 1, 15, None); - SetForegroundWindow(w); // so that WM_ACTIVATE tells us when the user clicks elsewhere -} - -/// How far the tray flyout still is from its place at opening progress `e` (0..1): it rises toward the bar's far side. -unsafe fn tf_slide(e: f32) -> i32 { - let d = ((1.0 - e) * sc(14) as f32) as i32; - if at_top() { -d } else { d } -} - -/// Opening progress 0..1 of the tray flyout, eased, and of its icon `n` (each one starts 25 ms after the previous). -unsafe fn tf_progress(n: i32) -> f32 { - let age = now_ms().saturating_sub(TF_ANIM.get().0) as f32; - ease(((age - 25.0 * n as f32) / 200.0).clamp(0.0, 1.0)) -} - -unsafe extern "system" fn fly_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { - let cell_at = |lp: LPARAM| -> i32 { - let (x, y) = ((lp & 0xffff) as i16 as i32 - sc(8), ((lp >> 16) & 0xffff) as i16 as i32 - sc(8)); - let (cols, _, _) = fly_size(); - let n = over_idx().len() as i32; - if x < 0 || y < 0 || x >= sc(FCELL) * cols as i32 { - return -1; - } - let i = (y / sc(FCELL)) * cols as i32 + x / sc(FCELL); - if i < n { i } else { -1 } - }; - match msg { - WM_PAINT => { - let mut ps: PAINTSTRUCT = zeroed(); - let wdc = BeginPaint(hwnd, &mut ps); - let mut r: RECT = zeroed(); - GetClientRect(hwnd, &mut r); - // drawn off screen first: painting every animation frame straight to the window flickered (#199) - let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, r.right, r.bottom)); - let screen_bmp = SelectObject(dc, bmp); - fill(dc, r, pal().line, sc(12)); - fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, pal().bg, sc(12)); - let (cols, _, _) = fly_size(); - let f = tip_font(); - let of = SelectObject(dc, f); - SetBkMode(dc, TRANSPARENT as i32); - SetTextColor(dc, pal().dim); - let mut tip = String::new(); - let over = over_idx(); - TAPPS.with_borrow(|t| { - for (n, ti) in over.iter().map(|&i| &t[i]).enumerate() { - let (x, y) = (sc(8) + (n % cols) as i32 * sc(FCELL), sc(8) + (n / cols) as i32 * sc(FCELL)); - if FHOT.get() == n as i32 { - fill(dc, RECT { left: x, top: y, right: x + sc(FCELL), bottom: y + sc(FCELL) }, pal().hover, sc(6)); - tip = ti.tip.clone(); - } - if !ti.icon.is_null() { - // 16 logical px, the small-icon size apps make theirs for: any other size gets resampled and blurs - DrawIconEx(dc, x + sc(19) - sc(16) / 2, y + sc(18) - sc(16) / 2, ti.icon, sc(16), sc(16), 0, null_mut(), DI_NORMAL); - } - } - }); - if tip.is_empty() { - tip = if over.is_empty() { t!("Больше значков нет", "No more icons", ja: "これ以上アイコンはありません", pt: "Não há mais ícones", zh: "没有更多图标").into() } else { t!("Средняя кнопка: перенести на панель", "Middle click: move to the bar", ja: "中クリック: バーに移動", pt: "Clique do meio: mover para a barra", zh: "中键单击:移到任务栏").into() }; - } - let mut tr = RECT { left: sc(10), top: r.bottom - sc(26), right: r.right - sc(10), bottom: r.bottom - sc(4) }; - DrawTextW(dc, wide(&tip).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_SINGLELINE | DT_END_ELLIPSIS | DT_VCENTER); - SelectObject(dc, of); - DeleteObject(f); - BitBlt(wdc, 0, 0, r.right, r.bottom, dc, 0, 0, SRCCOPY); - SelectObject(dc, screen_bmp); - DeleteObject(bmp); - DeleteDC(dc); - EndPaint(hwnd, &ps); - 0 - } - WM_ERASEBKGND => 1, - WM_MOUSEMOVE => { - let mut tme = TRACKMOUSEEVENT { cbSize: size_of::() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 }; - TrackMouseEvent(&mut tme); - if FHOT.replace(cell_at(lp)) != cell_at(lp) { - InvalidateRect(hwnd, null(), 0); - } - 0 - } - WM_MOUSELEAVE => { - FHOT.set(-1); - InvalidateRect(hwnd, null(), 0); - 0 - } - WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => { - let i = cell_at(lp); - let ti = over_idx().get(i.max(0) as usize).and_then(|&k| TAPPS.with_borrow(|t| t.get(k).map(|x| ((x.hwnd, x.uid, x.cb, x.ver), x.key.clone())))); - if let (true, Some((t, key))) = (i >= 0, ti) { - if msg == WM_MBUTTONDOWN { - toggle_shown(&key); - InvalidateRect(hwnd, null(), 0); - } else { - ShowWindow(hwnd, SW_HIDE); - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it - tray_click(t, msg == WM_LBUTTONDOWN); - } - } - 0 - } - WM_ACTIVATE if wp & 0xffff == 0 => { - ShowWindow(hwnd, SW_HIDE); - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it - 0 - } - WM_TIMER => { - let (_, x, y) = TF_ANIM.get(); - let e = tf_progress(0); - SetLayeredWindowAttributes(hwnd, 0, (255.0 * e) as u8, LWA_ALPHA); - SetWindowPos(hwnd, null_mut(), x, y + tf_slide(e), 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - InvalidateRect(hwnd, null(), 0); - if e >= 1.0 { - KillTimer(hwnd, 1); - } - 0 - } - _ => DefWindowProcW(hwnd, msg, wp, lp), - } -} - -// ---------- tray tooltip: a small popup under the icon after the mouse rests on it ---------- - -unsafe fn tip_font() -> HFONT { - CreateFontW(-sc(12), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide(ui_face()).as_ptr()) -} - -unsafe extern "system" fn tip_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { - if msg != WM_PAINT { - return DefWindowProcW(hwnd, msg, wp, lp); - } - let mut ps: PAINTSTRUCT = zeroed(); - let dc = BeginPaint(hwnd, &mut ps); - let mut r: RECT = zeroed(); - GetClientRect(hwnd, &mut r); - fill(dc, r, pal().line, sc(8)); - fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, pal().bg, sc(8)); - let f = tip_font(); - let of = SelectObject(dc, f); - SetBkMode(dc, TRANSPARENT as i32); - SetTextColor(dc, pal().text); - let mut tr = RECT { left: sc(8), top: sc(5), right: r.right - sc(8), bottom: r.bottom - sc(5) }; - TIP.with_borrow(|s| DrawTextW(dc, wide(s).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_WORDBREAK)); - SelectObject(dc, of); - DeleteObject(f); - EndPaint(hwnd, &ps); - 0 -} - -/// Tooltip text of a bar element ("" = none). -unsafe fn tip_text(h: i32) -> String { - match h { - SEARCH => "Search".into(), - TASKVIEW => t!("Представление задач", "Task View", ja: "タスク ビュー", pt: "Visão de Tarefas").into(), - POW_R => t!("Перезагрузка", "Restart", ja: "再起動", pt: "Reiniciar", zh: "重启").into(), - POW_S => t!("Завершение работы", "Shut down", ja: "シャットダウン", pt: "Desligar", zh: "关机").into(), - 0 => "Start".into(), - TAPP => "Hidden icons".into(), - GEAR => t!("Стиль", "Style", ja: "スタイル", pt: "Estilo", zh: "样式").into(), - SHOWDESK => t!("Показать рабочий стол", "Show desktop", ja: "デスクトップを表示", pt: "Mostrar a área de trabalho", zh: "显示桌面").into(), - CLOCK => { - let mut t: SYSTEMTIME = zeroed(); - GetLocalTime(&mut t); - let mut b = [0u16; 80]; - let n = GetDateFormatW(0x0400, 2, &t, null(), b.as_mut_ptr(), 80).max(1) as usize - 1; // DATE_LONGDATE - String::from_utf16_lossy(&b[..n]) - } - LANG => tf!("Язык ввода: {}", "Input language: {}", ja: "入力言語: {}", pt: "Idioma de entrada: {}", zh: "输入语言:{}", layout_names(layouts().1).0), - WIFI_I => match net() { - Link::Wifi(q) => tf!("Wi‑Fi · сигнал {q}%", "Wi‑Fi · signal {q}%", ja: "Wi‑Fi · 信号 {q}%", pt: "Wi‑Fi · sinal {q}%", zh: "Wi‑Fi · 信号 {q}%"), - Link::NoInternet(_) => t!("Wi‑Fi подключён, но интернета нет", "Wi‑Fi connected, no internet", ja: "Wi‑Fi 接続済み、インターネットなし", pt: "Wi‑Fi conectado, sem internet", zh: "Wi‑Fi 已连接,无 Internet").into(), - Link::Cable => t!("Интернет по кабелю", "Internet over a cable", ja: "有線のインターネット", pt: "Internet por cabo", zh: "有线网络").into(), - Link::Offline => t!("Нет подключения к сети", "Not connected", ja: "未接続", pt: "Não conectado", zh: "未连接").into(), - }, - VOL_I => vol_tip(), - BAT_I => match BAT.get() { - (p, ac) if p >= 0 => format!("Battery {p}%{}", if ac { " · plugged in" } else { "" }), - _ => String::new(), - }, - t if t > TAPP && t < TAPP + 100 => bar_idx().get((t - TAPP - 1) as usize).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|i| i.tip.clone()))).unwrap_or_default(), - i if i >= 1 => { - let (wins, lnk) = BTNS.with_borrow(|b| b.get(i as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| wstr_of(&x.lnk))))))).unwrap_or_default(); - let title = |w: HWND| { - let mut b = [0u16; 256]; - let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize; - String::from_utf16_lossy(&b[..n]) - }; - match (wins.first(), lnk) { - (Some(&w), _) if wins.len() > 1 => format!("{} (+{})", title(w), wins.len() - 1), - (Some(&w), _) => title(w), - (None, Some(l)) => std::path::Path::new(&l).file_stem().unwrap_or_default().to_string_lossy().into(), - _ => String::new(), - } - } - _ => String::new(), - } -} - -fn vol_tip() -> String { - match VOL.get() { - (v, false) if v >= 0 => format!("Volume {v}%"), - (_, true) => "Muted".into(), - _ => "Volume".into(), - } -} - -/// Shows `s` in a small rounded popup above the bar, centered on screen x `cx`. -unsafe fn show_tip(s: String, cx: i32) { - let tw = TIPWND.get(); - if s.is_empty() || tw.is_null() { - return; - } - let (dc, f) = (GetDC(tw), tip_font()); - let of = SelectObject(dc, f); - let mut r = RECT { left: 0, top: 0, right: sc(280), bottom: 0 }; - DrawTextW(dc, wide(&s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_NOPREFIX | DT_WORDBREAK); - SelectObject(dc, of); - DeleteObject(f); - ReleaseDC(tw, dc); - let (w, h) = (r.right + sc(16), r.bottom + sc(10)); - TIP.set(s); - SetWindowRgn(tw, CreateRoundRectRgn(0, 0, w + 1, h + 1, rr(8), rr(8)), 1); - if vert() { - let y = (cx - h / 2).min(GetSystemMetrics(SM_CYSCREEN) - h - sc(4)).max(sc(4)); - SetWindowPos(tw, HWND_TOPMOST, side_x(w), y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); - InvalidateRect(tw, null(), 1); - return; - } - let x = (cx - w / 2).min(GetSystemMetrics(SM_CXSCREEN) - w - sc(4)).max(sc(4)); - SetWindowPos(tw, HWND_TOPMOST, x, if at_top() { bar_h() - bar_off() + sc(6) } else { bar_top() + bar_off() - h - sc(6) }, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); - InvalidateRect(tw, null(), 1); -} - -// ---------- Alt+Tab switcher: a grid of the open windows with live previews, most recently used first (#92) ---------- - -const SW_CLIP_TIMER: usize = 9; - -thread_local! { - static SW_MON: Cell = const { Cell::new(RECT { left: 0, top: 0, right: 0, bottom: 0 }) }; // the monitor it is shown on - static SW_CARDS: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; // card rects, DWM previews - // where the pointer was when the switcher opened: a window appearing under a still pointer gets a WM_MOUSEMOVE, - // which must not pick the card under it (#183, #116); None once the pointer really moved - static SW_PT: Cell> = const { Cell::new(None) }; - // a game's cursor clip when the switcher opened, and its window: put back on close when we return to it - static SW_CLIP: Cell> = const { Cell::new(None) }; -} - -unsafe fn cursor() -> (i32, i32) { - let mut p: POINT = zeroed(); - GetCursorPos(&mut p); - (p.x, p.y) -} - -/// A clip smaller than the whole virtual desktop: a game (or another app) has confined the pointer. -unsafe fn clipped(c: &RECT) -> bool { - c.left > GetSystemMetrics(SM_XVIRTUALSCREEN) - || c.top > GetSystemMetrics(SM_YVIRTUALSCREEN) - || c.right < GetSystemMetrics(SM_XVIRTUALSCREEN) + GetSystemMetrics(SM_CXVIRTUALSCREEN) - || c.bottom < GetSystemMetrics(SM_YVIRTUALSCREEN) + GetSystemMetrics(SM_CYVIRTUALSCREEN) -} - -unsafe fn alt_tab(back: bool) { - let sw = SWWND.get(); - if IsWindowVisible(sw) == 0 { - let mut v: Vec = Vec::new(); - EnumWindows(Some(collect), &mut v as *mut _ as LPARAM); // z-order: the active window first, then the one before it - // per monitor: only the windows on the active window's monitor (when there is another one to switch to), shown on that monitor - let mut mon = RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }; - if i18n::style::alttab_per_monitor() && !v.is_empty() { - let of = |w: HWND| MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST); - let m0 = of(v[0]); - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(m0, &mut mi) != 0 { - let same: Vec = v.iter().copied().filter(|&w| of(w) == m0).collect(); - if same.len() > 1 { - v = same; - mon = mi.rcMonitor; - } - } - } - let n = v.len(); - if n == 0 { - return SWITCHING.store(false, Relaxed); - } - SW.set((v, if n == 1 { 0 } else if back { n - 1 } else { 1 })); - SW_MON.set(mon); - SW_PT.set(Some(cursor())); - // a game in mouse-look clips the pointer to a pixel at its center and re-clips it while it keeps the focus, so the - // pointer snaps back the moment it leaves the cards. Take the focus (as the system switcher does) so the game lets - // the pointer go anywhere, and release the clip too in case it keeps it without the focus. - let mut c: RECT = zeroed(); - let fg = GetForegroundWindow(); - SW_CLIP.set(None); - if GetClipCursor(&mut c) != 0 && clipped(&c) { - SW_CLIP.set(Some((c, fg))); - ClipCursor(null()); - SetTimer(sw, SW_CLIP_TIMER, 10, None); - } - sw_layout(sw); - if SW_CLIP.get().is_some() { - let ex = GetWindowLongW(sw, GWL_EXSTYLE) as u32; - SetWindowLongW(sw, GWL_EXSTYLE, (ex & !WS_EX_NOACTIVATE) as i32); - force_fg(sw); - } - } else { - SW.with_borrow_mut(|(v, i)| *i = if back { (*i + v.len() - 1) % v.len() } else { (*i + 1) % v.len() }); - } - InvalidateRect(sw, null(), 0); -} - -/// Sizes the switcher for its windows (centered on its monitor) and puts the live previews on the cards. -unsafe fn sw_layout(sw: HWND) { - let mon = SW_MON.get(); - let (scr, sch) = (mon.right - mon.left, mon.bottom - mon.top); - let pad = sc(thumbs::GAP) + sc(4); - let wins = SW.with_borrow(|(v, _)| v.clone()); - let (mut rects, tw, th) = thumbs::grid(wins.len(), scr * 9 / 10 - 2 * pad, sch * 8 / 10 - 2 * pad, sc(thumbs::CARD_W * 3 / 2), sc(thumbs::CARD_H * 3 / 2), sc(thumbs::GAP)); // bigger than hover previews (#190) - rects.iter_mut().for_each(|r| *r = RECT { left: r.left + pad, top: r.top + pad, right: r.right + pad, bottom: r.bottom + pad }); - let (w, h) = (tw + 2 * pad, th + 2 * pad); - SW_CARDS.with_borrow_mut(|(_, ids)| thumbs::unregister(sw, ids)); - SetWindowRgn(sw, CreateRoundRectRgn(0, 0, w + 1, h + 1, rr(18), rr(18)), 1); - SetWindowPos(sw, HWND_TOPMOST, mon.left + (scr - w) / 2, mon.top + (sch - h) / 2, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); - let ids = thumbs::register(sw, &wins, &rects); - SW_CARDS.set((rects, ids)); -} - -/// Delete (or a click on ×) in the switcher: closes the selected window and takes it off the list. -unsafe fn alt_close() { - let w = SW.with_borrow_mut(|(v, i)| { - let w = v.get(*i).copied(); - if w.is_some() { - v.remove(*i); - *i = (*i).min(v.len().saturating_sub(1)); - } - w - }); - if let Some(w) = w { - PostMessageW(w, WM_CLOSE, 0, 0); - } - if SW.with_borrow(|(v, _)| v.is_empty()) { - alt_done(true); - SWITCHING.store(false, Relaxed); - } else { - sw_layout(SWWND.get()); - InvalidateRect(SWWND.get(), null(), 0); - } -} - -/// Alt released: switch to the selected window (restored if minimized). Esc: just close. -unsafe fn alt_done(cancel: bool) { - ShowWindow(SWWND.get(), SW_HIDE); - KillTimer(SWWND.get(), SW_CLIP_TIMER); - SW_CARDS.with_borrow_mut(|(r, ids)| { - thumbs::unregister(SWWND.get(), ids); - r.clear(); - }); - let (v, i) = SW.take(); - let target = v.get(i).copied().filter(|_| !cancel); - if let Some(w) = target { - bring(w); - } - // we took the focus and made the switcher activatable because a game was clipping the pointer: put the style back, - // return the focus to that game on Esc, and give it its mouse-look clip back when we stay on / return to it - if let Some((c, fg)) = SW_CLIP.take() { - let sw = SWWND.get(); - let ex = GetWindowLongW(sw, GWL_EXSTYLE) as u32; - SetWindowLongW(sw, GWL_EXSTYLE, (ex | WS_EX_NOACTIVATE) as i32); - if cancel { - force_fg(fg); - } - if cancel || target == Some(fg) { - ClipCursor(&c); - } - } -} - -unsafe extern "system" fn sw_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { - let (x, y) = ((lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); - let at = || SW_CARDS.with_borrow(|(r, _)| thumbs::card_at(r, x, y)); - match msg { - WM_PAINT => SW.with_borrow(|(v, sel)| SW_CARDS.with_borrow(|(r, ids)| thumbs::paint(hwnd, v, r, ids, Some(*sel)))), - WM_MOUSEACTIVATE => return MA_NOACTIVATE as isize, - // the pointer picks a card, a click switches to it, a middle click or × closes it, the wheel steps through - WM_MOUSEMOVE => { - if SW_PT.get().is_some_and(|p| p == cursor()) { - return 0; - } - SW_PT.set(None); - if let Some(k) = at() { - if SW.with_borrow_mut(|(_, i)| std::mem::replace(i, k)) != k { - InvalidateRect(hwnd, null(), 0); - } - } - } - WM_LBUTTONUP | WM_MBUTTONUP => { - let Some(k) = at() else { return 0 }; - SW.with_borrow_mut(|(_, i)| *i = k); - let c = SW_CARDS.with_borrow(|(r, _)| thumbs::close_rect(&r[k])); - if msg == WM_MBUTTONUP || (x >= c.left && x < c.right && y >= c.top && y < c.bottom) { - alt_close(); - } else { - SWITCHING.store(false, Relaxed); - if GetAsyncKeyState(VK_MENU as i32) < 0 { - keys(&[0xE8]); // Alt is still down: its release must not open the menu bar of the app we switch to - } - alt_done(false); - } - } - WM_MOUSEWHEEL => alt_tab((wp >> 16) as i16 > 0), - WM_TIMER if wp == SW_CLIP_TIMER => { ClipCursor(null()); } - _ => return DefWindowProcW(hwnd, msg, wp, lp), - } - 0 -} - -unsafe fn hide_tip(bar: HWND) { - KillTimer(bar, 2); - ShowWindow(TIPWND.get(), SW_HIDE); -} - -unsafe fn set_state(hwnd: HWND, state: usize) { - let mut ab: APPBARDATA = zeroed(); - ab.cbSize = size_of::() as u32; - ab.hWnd = hwnd; - ab.lParam = state as isize; - SHAppBarMessage(ABM_SETSTATE, &mut ab); -} - -/// Hides the real taskbar and sets it to auto-hide so Windows gives its work-area strip back. -unsafe fn hide_taskbar() { - set_state(tray()[0], ABS_AUTOHIDE as usize); - for t in ours_to_hide() { - ShowWindow(t, SW_HIDE); - } -} - -/// Explorer's taskbars the bar replaces: the other monitors' ones only while it has a bar of its own there. -unsafe fn ours_to_hide() -> Vec { - let mut t = tray(); - t.truncate(if second::enabled() { usize::MAX } else { 1 }); - t.retain(|t| !t.is_null()); - t -} - -fn taskbar_state_file() -> PathBuf { - appdata_file("topbar-taskbar-state.txt") -} - -/// The taskbar mode (always on top / auto-hide bits) the user had before the bar hid it. It lives in a file so that -/// `--restore` (reshell's watchdog after a crash) puts back the user's own mode, not the Windows default. -fn saved_taskbar_state() -> Option { - std::fs::read_to_string(taskbar_state_file()).ok()?.trim().parse().ok() -} - -fn forget_taskbar_state() { - let _ = std::fs::remove_file(taskbar_state_file()); -} - -/// At start: the mode to give back later. A file left by a crashed run wins (explorer's current mode is then our own -/// auto-hide); otherwise the current mode is the user's and is written down. Without explorer's taskbar: the default. -unsafe fn remember_taskbar_state() -> usize { - if let Some(s) = saved_taskbar_state() { - return s; - } - let tb = tray()[0]; - if tb.is_null() { - return ABS_ALWAYSONTOP as usize; - } - let mut ab: APPBARDATA = zeroed(); - ab.cbSize = size_of::() as u32; - ab.hWnd = tb; - let s = SHAppBarMessage(ABM_GETSTATE, &mut ab); - let _ = std::fs::write(taskbar_state_file(), s.to_string()); - s -} - -unsafe fn show_taskbar(state: usize) { - set_state(tray()[0], state); - for t in tray().into_iter().filter(|t| !t.is_null()) { - ShowWindow(t, SW_SHOWNA); - } -} - -// explorer re-shows its taskbar on hover / restart; hide it again -unsafe fn hide_taskbar_if_shown() { - if ours_to_hide().into_iter().any(|t| IsWindowVisible(t) != 0) { - hide_taskbar(); - } -} - -/// Reserves a strip on the bar's screen edge so maximized windows stay clear of it. -unsafe fn place(hwnd: HWND) { - apply_opacity(hwnd); - let (cx, cy) = (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); - let mut ab: APPBARDATA = zeroed(); - ab.cbSize = size_of::() as u32; - ab.hWnd = hwnd; - // the reserved strip: the bar itself plus the dock's gap under it - // the dock reserves nothing: maximized windows take the whole screen and the dock slides away over them - let strip = if dock() || i18n::style::autohide() { 0 } else { bar_h() }; - if vert() { - let left = i18n::style::side() == i18n::style::Side::Left; - ab.uEdge = if left { ABE_LEFT } else { ABE_RIGHT }; - ab.rc = if left { RECT { left: 0, top: 0, right: strip, bottom: cy } } else { RECT { left: cx - strip, top: 0, right: cx, bottom: cy } }; - SHAppBarMessage(ABM_QUERYPOS, &mut ab); - if left { ab.rc.left = sane_edge(ab.rc.left, cx) } else { ab.rc.right = cx - sane_edge(cx - ab.rc.right, cx) } - if left { ab.rc.right = ab.rc.left + strip } else { ab.rc.left = ab.rc.right - strip } - } else if at_top() { - ab.uEdge = ABE_TOP; - ab.rc = RECT { left: 0, top: 0, right: cx, bottom: strip }; - SHAppBarMessage(ABM_QUERYPOS, &mut ab); - ab.rc.top = sane_edge(ab.rc.top, cy); - ab.rc.bottom = ab.rc.top + strip; - } else { - ab.uEdge = ABE_BOTTOM; - ab.rc = RECT { left: 0, top: cy - strip, right: cx, bottom: cy }; - SHAppBarMessage(ABM_QUERYPOS, &mut ab); - ab.rc.bottom = cy - sane_edge(cy - ab.rc.bottom, cy); - ab.rc.top = ab.rc.bottom - strip; - } - SHAppBarMessage(ABM_SETPOS, &mut ab); - // No explorer (rs-shell / rust-explorer): nobody handles appbars, so set the work area ourselves. Without it maximized - // windows slide under the bar and, covering the whole monitor, count as "fullscreen" and hide the bar. - // Also with Explorer: it does not always honour the appbar when its own taskbar is hidden (#89). - let work = if vert() { if ab.uEdge == ABE_LEFT { RECT { left: ab.rc.right, top: 0, right: cx, bottom: cy } } else { RECT { left: 0, top: 0, right: ab.rc.left, bottom: cy } } } else if at_top() { RECT { left: 0, top: ab.rc.bottom, right: cx, bottom: cy } } else { RECT { left: 0, top: 0, right: cx, bottom: ab.rc.top } }; - BAR_WORK.set((work.left, work.top, work.right, work.bottom)); - set_work_area(work); - let (x, w) = bar_x_w(); - // the dock is a pill; the other styles a plain strip - SetWindowRgn(hwnd, if dock() { CreateRoundRectRgn(0, 0, w + 1, bar_h() + 1, bar_h(), bar_h()) } else { null_mut() }, 1); - if vert() { - SetWindowPos(hwnd, HWND_TOPMOST, bar_x(), 0, bar_h(), cy, SWP_NOACTIVATE | SWP_NOZORDER); - } else { - // SWP_NOZORDER: the bar is topmost from its creation on. Raising it again here (this runs on every display change, which - // a game switching into fullscreen causes) put it over the game and knocked that out of fullscreen, in a loop. - SetWindowPos(hwnd, HWND_TOPMOST, x, bar_y(), w, bar_h(), SWP_NOACTIVATE | SWP_NOZORDER); - } - InvalidateRect(hwnd, null(), 0); - second::sync(); -} - -/// How far from its screen edge the bar may sit after ABM_QUERYPOS (room left for other appbars). Explorer sometimes answers -/// with a far-off edge (a stale or huge appbar entry), and the work area then shrank to half the screen (#106): past a -/// quarter of the screen, or off it, the bar goes back to the edge. -fn sane_edge(offset: i32, size: i32) -> i32 { - if (0..=size / 4).contains(&offset) { offset } else { 0 } -} - -unsafe fn set_work_area(mut want: RECT) { - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - GetMonitorInfoW(MonitorFromRect(&want, MONITOR_DEFAULTTONEAREST), &mut mi); - let cur = mi.rcWork; - if (cur.left, cur.top, cur.right, cur.bottom) != (want.left, want.top, want.right, want.bottom) { - // SPIF_SENDCHANGE waits for every top-level window (took ~3 s, #94): set quietly and post the notice instead - SystemParametersInfoW(SPI_SETWORKAREA, 0, &mut want as *mut _ as *mut _, 0); - PostMessageW(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETWORKAREA as usize, 0); - EnumWindows(Some(fit_maximized), &want as *const RECT as isize); - } -} - -/// Explorer and display changes can reset the work area after the bar has already claimed its edge. -unsafe fn work_area_drifted() -> bool { - let want = BAR_WORK.get(); - if want.0 < 0 { return false; } - let mut current: RECT = zeroed(); - SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut current as *mut _ as *mut _, 0) != 0 - && (current.left, current.top, current.right, current.bottom) != want -} - -/// A window that was already maximized keeps its old height when the work area shrinks: trim it (size only, no restore). -unsafe extern "system" fn fit_maximized(h: HWND, lp: isize) -> i32 { - let want = &*(lp as *const RECT); - // the work area belongs to one monitor: a window maximized on another one would be cut to a sliver - if IsWindowVisible(h) == 0 || IsZoomed(h) == 0 || MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST) != MonitorFromRect(want, MONITOR_DEFAULTTONEAREST) { - return 1; - } - let mut r: RECT = zeroed(); - GetWindowRect(h, &mut r); - let f =GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER); // a maximized window overhangs by its border - let n = RECT { left: r.left.max(want.left - f), top: r.top.max(want.top - f), right: r.right.min(want.right + f), bottom: r.bottom.min(want.bottom + f) }; - if (n.left, n.top, n.right, n.bottom) != (r.left, r.top, r.right, r.bottom) && n.right > n.left && n.bottom > n.top { - SetWindowPos(h, null_mut(), n.left, n.top, n.right - n.left, n.bottom - n.top, SWP_NOZORDER | SWP_NOACTIVATE); - } - fit_normal(h); - 1 -} - -/// Shrink `n` (a restore rectangle) into `work`, keeping it as large as still fits. Returns true if it changed. -fn clamp_rect(n: &mut RECT, work: RECT) -> bool { - let maxw = work.right - work.left; - let maxh = work.bottom - work.top; - let nw = (n.right - n.left).min(maxw); - let nh = (n.bottom - n.top).min(maxh); - let x = n.left.max(work.left).min(work.right - nw); - let y = n.top.max(work.top).min(work.bottom - nh); - if (n.left, n.top, n.right, n.bottom) == (x, y, x + nw, y + nh) { - return false; - } - *n = RECT { left: x, top: y, right: x + nw, bottom: y + nh }; - true -} - -/// `rcNormalPosition` is in workspace coordinates: shifted by what bars take on the top and left. -fn workspace(work: RECT, monitor: RECT) -> RECT { - let (dx, dy) = (work.left - monitor.left, work.top - monitor.top); - RECT { left: work.left - dx, top: work.top - dy, right: work.right - dx, bottom: work.bottom - dy } -} - -/// A window maximized while the work area was the whole monitor keeps that size as its restore rectangle, so -/// restoring it later leaves it past the screen edge and under the bar (#268). Clamp a maximized window's normal -/// placement into its monitor's work area; the next restore then lands inside it. Only maximized windows: a -/// borderless fullscreen game or a window spanning monitors is not zoomed and is left alone. -unsafe fn fit_normal(w: HWND) { - if IsWindowVisible(w) == 0 || IsIconic(w) != 0 || IsZoomed(w) == 0 || IsHungAppWindow(w) != 0 { - return; - } - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { - return; - } - let mut wp: WINDOWPLACEMENT = zeroed(); - wp.length = size_of::() as u32; - if GetWindowPlacement(w, &mut wp) == 0 { - return; - } - if clamp_rect(&mut wp.rcNormalPosition, workspace(mi.rcWork, mi.rcMonitor)) { - wp.showCmd = 8; // SW_SHOWNA: SW_SHOWMAXIMIZED would steal the focus - wp.flags |= 4; // WPF_ASYNCWINDOWPLACEMENT: a busy app must not stall the bar - let _ = SetWindowPlacement(w, &wp); - } -} - -/// A window restored from maximized keeps the maximized frame (the monitor plus its invisible resize border), which -/// leaves it past the screen edge and under the bar (#268); being restored, fit_normal no longer sees it. Shrink exactly -/// that shape to the work area: larger than the monitor on both axes but by no more than the border. A window spanning -/// monitors or one genuinely larger is much bigger and left alone. -unsafe fn fit_restored(w: HWND) { - let framed = GetWindowLongW(w, GWL_STYLE) as u32 & (WS_CAPTION | WS_THICKFRAME) == WS_CAPTION | WS_THICKFRAME; - if !framed || IsWindowVisible(w) == 0 || IsIconic(w) != 0 || IsZoomed(w) != 0 || IsHungAppWindow(w) != 0 { - return; - } - let mut r: RECT = zeroed(); - if GetWindowRect(w, &mut r) == 0 { - return; - } - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { - return; - } - let (ww, wh) = (r.right - r.left, r.bottom - r.top); - let (mw, mh) = (mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top); - if ww < mw + 8 || wh < mh + 8 || ww > mw + 32 || wh > mh + 32 { - return; - } - let work = mi.rcWork; - SetWindowPos(w, null_mut(), work.left, work.top, work.right - work.left, work.bottom - work.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS); -} - -// ---------- data: windows, pins, tray apps, volume, wifi, battery ---------- - -thread_local! { - static EXE_CACHE: RefCell> = RefCell::new(HashMap::new()); // hwnd -> (pid, exe): refresh runs twice a second -} - -unsafe fn exe_of(h: HWND) -> String { - let mut pid = 0u32; - GetWindowThreadProcessId(h, &mut pid); - if let Some(e) = EXE_CACHE.with_borrow(|c| c.get(&(h as usize)).filter(|(p, e)| *p == pid && !e.is_empty()).map(|(_, e)| e.clone())) { - return e; - } - let p = OpenProcess(0x1000, 0, pid); // PROCESS_QUERY_LIMITED_INFORMATION - if p.is_null() { - return String::new(); - } - let (mut b, mut n) = ([0u16; 520], 520u32); - let ok = QueryFullProcessImageNameW(p, 0, b.as_mut_ptr(), &mut n); - CloseHandle(p); - let exe = if ok == 0 { String::new() } else { String::from_utf16_lossy(&b[..n as usize]).to_lowercase() }; - EXE_CACHE.with_borrow_mut(|c| { - if c.len() > 512 { - c.clear(); // closed windows never leave on their own - } - c.insert(h as usize, (pid, exe.clone())); - }); - exe -} - -unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> i32 { - let ex = GetWindowLongW(h, GWL_EXSTYLE) as u32; - let mut cloaked = 0u32; // UWP windows that are suspended / on another desktop are visible but cloaked - DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as *mut _, 4); - let mut cls = [0u16; 32]; - let n = GetClassNameW(h, cls.as_mut_ptr(), 32) as usize; - let ours = String::from_utf16_lossy(&cls[..n]) == "topbar"; - let skipped = SKIP.with_borrow(|s| s.contains(&h)); - if IsWindowVisible(h) != 0 && GetWindow(h, GW_OWNER).is_null() && cloaked == 0 && !ours && GetWindowTextLengthW(h) > 0 && (ex & WS_EX_TOOLWINDOW == 0 || ex & WS_EX_APPWINDOW != 0) && !skipped { - (*(lp as *mut Vec)).push(h); - } - 1 -} - -/// "%windir%\explorer.exe" -> "C:\Windows\explorer.exe" (unknown variables stay as they are). -/// A Run-box command ("cmd", "%appdata%", "control") as a real path the shell can draw an icon for: environment -/// variables expanded, a bare name looked up on PATH like Win+R does. Anything else comes back as it was. -unsafe fn resolve_cmd(s: &str) -> String { - use windows_sys::Win32::Storage::FileSystem::SearchPathW; - let e = expand_env(s); - if e.contains(['\\', '/', ':']) { - return e; - } - let mut b = [0u16; 520]; - let n = SearchPathW(null(), wide(&e).as_ptr(), wide(".exe").as_ptr(), b.len() as u32, b.as_mut_ptr(), null_mut()) as usize; - if n > 0 && n < b.len() { String::from_utf16_lossy(&b[..n]) } else { e } -} - -fn expand_env(s: &str) -> String { - let parts: Vec<&str> = s.split('%').collect(); - let mut out = String::new(); - for (i, p) in parts.iter().enumerate() { - match std::env::var(p) { - // odd pieces sit between two '%': a variable name - Ok(v) if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&v), - _ if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&format!("%{p}%")), - _ if i % 2 == 1 => out.push_str(&format!("%{p}")), // a lone '%' with nothing to close it - _ => out.push_str(p), - } - } - out -} - -/// Target exe of a shortcut (lower-case), "" if it has none (e.g. Store apps). -unsafe fn lnk_target(lnk: &[u16]) -> String { - (|| -> Option { - let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; - sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; - let mut b = [0u16; 520]; - sl.GetPath(&mut b, null_mut(), 0).ok()?; - let path = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]); - if !path.is_empty() { - return Some(path.to_lowercase()); - } - // shell links without a file target (the File Explorer pin) usually take their icon from the app's exe: - // "%windir%\explorer.exe,0" -> match the app's windows by that exe - let mut idx = 0; - sl.GetIconLocation(&mut b, &mut idx).ok()?; - let icon = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]); - let icon = expand_env(&icon).to_lowercase(); - icon.ends_with(".exe").then_some(icon) - })() - .unwrap_or_default() -} - -/// The target's own icon: SHGetFileInfo on the .lnk adds the shortcut arrow, so that is only the fallback. -unsafe fn lnk_icon(lnk: &[u16], target: &str) -> HICON { - let ic = item_icon(&resolve_cmd(&wstr_of(lnk)), icon_px()); - if !ic.is_null() { - return ic; - } - let mut icon: HICON = null_mut(); - if !target.is_empty() { - ExtractIconExW(wide(target).as_ptr(), 0, null_mut(), &mut icon, 1); - } - if icon.is_null() { - let mut sfi: SHFILEINFOW = zeroed(); - SHGetFileInfoW(lnk.as_ptr(), 0, &mut sfi, size_of::() as u32, SHGFI_ICON | SHGFI_SMALLICON); - icon = sfi.hIcon; - } - icon -} - -/// Size app icons are drawn at. Icons are loaded at exactly this size: -/// a 32 px icon stretched by DrawIconEx comes out jagged. -fn icon_px() -> i32 { - icon_sc(24) -} - -/// Icon of a file, shortcut (its target's icon, no arrow) or shell item ("shell:AppsFolder\") rendered by the -/// shell at exactly `px` pixels, the way Explorer gets its icons. Null if the shell has none. -unsafe fn item_icon(path: &str, px: i32) -> HICON { - use windows::Win32::{ - Foundation::SIZE, - UI::Shell::{IShellItem, IShellItemImageFactory, SHCreateItemFromParsingName, SIIGBF_ICONONLY}, - }; - let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide(path).as_ptr()), None) else { return null_mut() }; - let Ok(f) = item.cast::() else { return null_mut() }; - let Ok(bmp) = f.GetImage(SIZE { cx: px, cy: px }, SIIGBF_ICONONLY) else { return null_mut() }; - let color = bmp.0 as HBITMAP; - let mask = CreateBitmap(px, px, 1, 1, null()); // ignored: the 32-bit colour bitmap carries the alpha - let mut ii = ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color }; - let ic = CreateIconIndirect(&mut ii); - DeleteObject(mask); - DeleteObject(color); - ic -} - -thread_local! { - static EXE_ICONS: RefCell> = RefCell::new(HashMap::new()); // crisp icons of running apps, by exe -} - -/// Recreate cached app icons after the size changes so they remain crisp. -unsafe fn reload_icons() { - PINS.with_borrow_mut(|pins| { - for pin in pins.iter_mut() { - let icon = lnk_icon(&pin.lnk, &pin.target); - if !pin.icon.is_null() { DestroyIcon(pin.icon); } - pin.icon = icon; - } - }); - EXE_ICONS.with_borrow_mut(|icons| { - for icon in icons.values() { - if !icon.is_null() { DestroyIcon(*icon); } - } - icons.clear(); - }); - refresh_buttons(); -} - -/// Icon of a running window for its bar button: its exe's icon at the exact size (cached), else what the window reports. -/// Apps run by a generic host (Store apps in ApplicationFrameHost, Java games in javaw, scripts in python...) would all -/// get the host's icon: those keep the window's own icon. -unsafe fn win_icon(w: HWND) -> HICON { - let exe = exe_of(w); - let own = |w| { - let i = icon_of(w); - if i.is_null() { LoadIconW(null_mut(), IDI_APPLICATION) } else { i } // never a blank button (#91) - }; - if exe.is_empty() || is_host(&exe) { - // a Store app lives in ApplicationFrameHost: the shell draws the icon of the app id of the frame's CoreWindow - if exe.ends_with("applicationframehost.exe") { - let ic = store_icon(w); - if !ic.is_null() { - return ic; - } - } - return own(w); - } - let ic = EXE_ICONS.with_borrow_mut(|m| *m.entry(exe.clone()).or_insert_with(|| item_icon(&exe, icon_px()))); - if ic.is_null() { own(w) } else { ic } -} - -fn is_host(exe: &str) -> bool { - const HOSTS: [&str; 8] = ["applicationframehost.exe", "javaw.exe", "java.exe", "pythonw.exe", "python.exe", "mmc.exe", "rundll32.exe", "dllhost.exe"]; - HOSTS.iter().any(|h| exe.rsplit('\\').next() == Some(*h)) -} - -/// Icon of the Store app behind an ApplicationFrameHost window (cached by app id), null if it cannot be found. -unsafe fn store_icon(frame: HWND) -> HICON { - use windows_sys::Win32::Storage::Packaging::Appx::GetApplicationUserModelId; - let core = FindWindowExW(frame, null_mut(), wide("Windows.UI.Core.CoreWindow").as_ptr(), null()); - if core.is_null() { - return null_mut(); - } - let mut pid = 0u32; - GetWindowThreadProcessId(core, &mut pid); - let p = OpenProcess(windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if p.is_null() { - return null_mut(); - } - let mut buf = [0u16; 256]; - let mut len = buf.len() as u32; - let ok = GetApplicationUserModelId(p, &mut len, buf.as_mut_ptr()) == 0; - CloseHandle(p); - if !ok { - return null_mut(); - } - let id = format!(r"shell:AppsFolder\{}", wstr_of(&buf)); - EXE_ICONS.with_borrow_mut(|m| *m.entry(id.clone()).or_insert_with(|| item_icon(&id, icon_px()))) -} - -/// "c:\program files\windowsapps\claude_5.1.0.0_x64__pzs8\app\claude.exe" -> ("claude_pzs8", "app\claude.exe"): -/// the package family (name + publisher id, the same across versions) and the path inside the package folder. -fn msix_family(target: &str) -> Option<(String, String)> { - let l = target.to_lowercase(); - let (_, tail) = l.split_once(r"\windowsapps\")?; - let (folder, rest) = tail.split_once('\\')?; - let parts: Vec<&str> = folder.split('_').collect(); // name_version_arch_resourceid_publisherid - (parts.len() == 5).then(|| (format!("{}_{}", parts[0], parts[4]), rest.to_string())) -} - -/// A pin of a Store (MSIX) app points into its versioned package folder, which is gone after every app update -/// ("Windows cannot find ...\Claude_5.11492.5.0_x64__...\claude.exe"). Re-points the .lnk to the installed version. -/// Returns the new target (lower-case), None if the target exists or is not in a package. -unsafe fn fix_msix_pin(lnk: &[u16], target: &str) -> Option { - use windows_sys::Win32::Storage::Packaging::Appx::{GetPackagePathByFullName, GetPackagesByPackageFamily}; - if target.is_empty() || std::path::Path::new(target).exists() { - return None; - } - let (family, rest) = msix_family(target)?; - let fam = wide(&family); - let (mut count, mut len) = (0u32, 0u32); - GetPackagesByPackageFamily(fam.as_ptr(), &mut count, null_mut(), &mut len, null_mut()); // sizes only - if count == 0 { - return None; // the app was uninstalled - } - let (mut names, mut buf) = (vec![null_mut::(); count as usize], vec![0u16; len as usize]); - if GetPackagesByPackageFamily(fam.as_ptr(), &mut count, names.as_mut_ptr(), &mut len, buf.as_mut_ptr()) != 0 { - return None; - } - let mut path = [0u16; 520]; - let mut plen = path.len() as u32; - if GetPackagePathByFullName(names[0], &mut plen, path.as_mut_ptr()) != 0 { - return None; - } - let new = std::path::Path::new(&wstr_of(&path)).join(&rest); - if !new.exists() { - return None; - } - let new = new.to_string_lossy().to_lowercase(); - let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; - let pf = sl.cast::().ok()?; - pf.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; - sl.SetPath(PCWSTR(wide(&new).as_ptr())).ok()?; - pf.Save(PCWSTR(lnk.as_ptr()), true).ok()?; - Some(new) -} - -fn pin_order_file() -> PathBuf { - appdata_file("topbar-pin-order.txt") -} - -/// The pins' current order, as the .lnk file names, one per line. -unsafe fn save_pin_order() { - let text: String = PINS.with_borrow(|p| p.iter().map(|x| format!("{} -", std::path::Path::new(&wstr_of(&x.lnk)).file_name().unwrap_or_default().to_string_lossy())).collect()); - let _ = std::fs::write(pin_order_file(), text); -} - -/// What makes two pins the same app: the target exe and its arguments, or the app id of a Store app (no file target). -/// ("", "") when neither is known. -unsafe fn pin_key(lnk: &[u16]) -> (String, String) { - let target = lnk_target(lnk); - if !target.is_empty() { - return (target, lnk_args(lnk).to_lowercase()); - } - let id = lnk_aumid(lnk).to_lowercase(); - (if id.is_empty() { id } else { format!("aumid:{id}") }, String::new()) -} - -/// The AppUserModelID a shortcut carries (Store and web app pins), "" if none. -unsafe fn lnk_aumid(lnk: &[u16]) -> String { - use windows::{core::GUID, Win32::{Foundation::PROPERTYKEY, System::Com::{CoTaskMemFree, StructuredStorage::PropVariantToStringAlloc}, UI::Shell::PropertiesSystem::IPropertyStore}}; - (|| -> Option { - let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; - sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; - let ps: IPropertyStore = sl.cast().ok()?; - let key = PROPERTYKEY { fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3), pid: 5 }; // PKEY_AppUserModel_ID - let v = ps.GetValue(&key).ok()?; - let p = PropVariantToStringAlloc(&v).ok()?; - let s = p.to_string().ok(); - CoTaskMemFree(Some(p.0 as *const _)); - s - })() - .unwrap_or_default() -} - -/// The AppUserModelID a window carries (Store apps, installed web apps), "" if none. -unsafe fn win_aumid(h: HWND) -> String { - use windows::{core::GUID, Win32::{Foundation::{HWND as WHWND, PROPERTYKEY}, System::Com::{CoTaskMemFree, StructuredStorage::PropVariantToStringAlloc}, UI::Shell::PropertiesSystem::{IPropertyStore, SHGetPropertyStoreForWindow}}}; - (|| -> Option { - let ps: IPropertyStore = SHGetPropertyStoreForWindow(WHWND(h)).ok()?; - let key = PROPERTYKEY { fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3), pid: 5 }; // PKEY_AppUserModel_ID - let p = PropVariantToStringAlloc(&ps.GetValue(&key).ok()?).ok()?; - let s = p.to_string().ok(); - CoTaskMemFree(Some(p.0 as *const _)); - s - })() - .unwrap_or_default() - .to_lowercase() -} - -/// Taskbar pins the user removed from our bar: Windows still lists them in `FavoritesResolve`, they must not come back. -fn unpinned_file() -> PathBuf { - appdata_file(r"topbar-taskband\unpinned.txt") -} - -fn key_line(k: &(String, String)) -> String { - format!("{}|{}", k.0, k.1) -} - -/// Windows keeps every taskbar pin, in order, as serialized shortcuts in `Taskband\FavoritesResolve` (also those with no -/// .lnk in the TaskBar folder: Steam, Chrome app shortcuts, #93). Each one is written out as a .lnk of our own, named by -/// target and arguments so the name stays the same between runs. Returns (key = target + args, file) in the taskbar's order. -unsafe fn taskband_links() -> Vec<((String, String), PathBuf)> { - use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_BINARY, RegGetValueW}; - let mut n = 0u32; - let (key, val) = (wide(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband"), wide("FavoritesResolve")); - if RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), val.as_ptr(), RRF_RT_REG_BINARY, null_mut(), null_mut(), &mut n) != 0 || n == 0 { - return vec![]; - } - let mut blob = vec![0u8; n as usize]; - if RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), val.as_ptr(), RRF_RT_REG_BINARY, null_mut(), blob.as_mut_ptr().cast(), &mut n) != 0 { - return vec![]; - } - // every entry starts with the ShellLink header (size 0x4C + the shell link CLSID) - const HEAD: [u8; 20] = [0x4C, 0, 0, 0, 0x01, 0x14, 0x02, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46]; - let starts: Vec = (0..blob.len().saturating_sub(HEAD.len())).filter(|&i| blob[i..i + HEAD.len()] == HEAD).collect(); - let dir = appdata_file("topbar-taskband"); - let _ = std::fs::create_dir_all(&dir); - // copies from an earlier run: a pin removed in Windows since must not linger - std::fs::read_dir(&dir).into_iter().flatten().flatten().filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("lnk"))).for_each(|e| { - let _ = std::fs::remove_file(e.path()); - }); - let tmp = dir.join("tmp.lnk"); - let gone: Vec = std::fs::read_to_string(unpinned_file()).unwrap_or_default().lines().map(str::to_string).collect(); - let mut out = vec![]; - for (k, &a) in starts.iter().enumerate() { - let b = starts.get(k + 1).copied().unwrap_or(blob.len()); - if std::fs::write(&tmp, &blob[a..b]).is_err() { - continue; - } - let key = pin_key(&wide(&tmp.to_string_lossy())); - if key.0.is_empty() || gone.contains(&key_line(&key)) { - continue; - } - // most entries point at a .lnk (the pin's own in the TaskBar folder, or one in ImplicitAppShortcuts for a browser - // profile): that file is the pin; one whose file is gone (File Explorer replaced by rust-explorer) is no pin at all. - // The unpinned list holds the resolved key (unpin() reads it from that same file), so it is checked after resolving. - if key.0.ends_with(".lnk") { - let real = PathBuf::from(&key.0); - let rk = pin_key(&wide(&real.to_string_lossy())); - if real.is_file() && !rk.0.is_empty() && !gone.contains(&key_line(&rk)) { - out.push((rk, real)); - } - continue; - } - // a readable, stable file name: the exe's name (or the app id's) plus a hash of the whole key - let base = key.0.strip_prefix("aumid:").unwrap_or_else(|| std::path::Path::new(&key.0).file_stem().and_then(|s| s.to_str()).unwrap_or("")); - let stem: String = base.chars().map(|c| if c.is_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(40).collect(); - let h = key_line(&key).bytes().fold(5381u32, |h, c| h.wrapping_mul(33) ^ c as u32); - let file = dir.join(format!("{stem}-{h:08x}.lnk")); - if std::fs::copy(&tmp, &file).is_ok() { - out.push((key, file)); - } - } - let _ = std::fs::remove_file(tmp); - out -} - -/// Pinned apps (the .lnk files Windows keeps for the taskbar) with their icons and target exe. -unsafe fn load_pins() { - let Some(appdata) = std::env::var_os("APPDATA") else { return }; - let dir = PathBuf::from(appdata).join(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"); - let mut files: Vec<_> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("lnk"))).collect(); - files.sort(); - files.sort_by_key(|f| std::cmp::Reverse(lnk_uses(f))); // most used first (stable: ties stay alphabetical) - // the Windows taskbar's own order (#90) and the pins that have no file in the folder (#93) - let fav = taskband_links(); - let key_of = |f: &PathBuf| pin_key(&wide(&f.to_string_lossy())); - let mut keys: Vec<_> = files.iter().map(key_of).collect(); - for (k, f) in &fav { - if !keys.contains(k) { - keys.push(k.clone()); - files.push(f.clone()); - } - } - let at: HashMap = files.iter().cloned().zip(&keys).map(|(f, k)| (f, fav.iter().position(|(fk, _)| fk == k).unwrap_or(usize::MAX))).collect(); - files.sort_by_key(|f| at[f]); // stable: pins the taskbar does not list keep the most-used order, after the listed ones - // an order the user set (Move left / right) wins; pins not in it keep the order above, after the listed ones - let order: Vec = std::fs::read_to_string(pin_order_file()).unwrap_or_default().lines().map(|l| l.to_lowercase()).collect(); - files.sort_by_key(|f| order.iter().position(|n| *n == f.file_name().unwrap_or_default().to_string_lossy().to_lowercase()).unwrap_or(usize::MAX)); - for f in files { - let lnk = wide(&f.to_string_lossy()); - let target = lnk_target(&lnk); - let target = fix_msix_pin(&lnk, &target).unwrap_or(target); - let icon = lnk_icon(&lnk, &target); - let args = lnk_args(&lnk); - let aumid = lnk_aumid(&lnk).to_lowercase(); - PINS.with_borrow_mut(|p| p.push(Pin { lnk, target, args, aumid, icon })); - } - // once: a File Explorer button for the installed file manager (the marker keeps an unpinned one gone) - let marker = appdata_file("topbar-explorer-pin.txt"); - let rx = std::env::var_os("ProgramFiles").map(|pf| PathBuf::from(pf).join(r"rust-explorer\rust-explorer.exe")); - if let Some(rx) = rx.filter(|rx| rx.is_file() && !marker.exists()) { - pin_exe(&rx.to_string_lossy(), ""); - let _ = std::fs::write(marker, "1"); - } -} - -/// The exe the File Explorer pin stands for (lower-case): its icon location, "%windir%\explorer.exe". -fn file_explorer_exe() -> String { - expand_env(r"%windir%\explorer.exe").to_lowercase() -} - -/// The windows of WinRust's file manager belong to the File Explorer pin when there is one: that pin is what the user clicks -/// to open "Explorer" here, and only windows of explorer.exe matched it, so its button never showed them (a minimized -/// window looked gone and the click started a second one). Without such a pin they keep their own exe's button. -fn as_pinned_exe(exe: &str, explorer: &str, explorer_pinned: bool) -> String { - if explorer_pinned && exe.ends_with(r"\rust-explorer\rust-explorer.exe") { explorer.to_string() } else { exe.to_string() } -} - -/// `...\app-1.0.9001\discord.exe` without the version folder: Squirrel apps (Discord, Slack...) move on every update. -fn unversioned(exe: &str) -> String { - exe.split('\\').filter(|p| !p.strip_prefix("app-").is_some_and(|v| v.starts_with(|c: char| c.is_ascii_digit()))).collect::>().join(r"\") -} - -/// A window of `exe` (with AppUserModelID `id`) belongs to a pin of another exe (#198): the same AppUserModelID, a pin of -/// Squirrel's launcher (`Update.exe --processStart App.exe`) or of an older version folder. All lower-case but `args`. -fn pin_of_other_exe(target: &str, args: &str, aumid: &str, exe: &str, id: &str) -> bool { - if !aumid.is_empty() && aumid == id { - return true; - } - let args = args.to_lowercase(); - if let (Some(dir), Some(at)) = (target.strip_suffix(r"\update.exe"), args.find("--processstart")) { - let name = args[at + "--processstart".len()..].trim_start_matches(['=', ' ', '"']).split(['"', ' ']).next().unwrap_or(""); - return !name.is_empty() && exe.strip_prefix(dir).is_some_and(|r| r.starts_with('\\') && r.rsplit('\\').next() == Some(name)); - } - !exe.is_empty() && unversioned(target) == unversioned(exe) -} - -fn refresh_buttons() { - let mut wins: Vec = Vec::new(); - unsafe { EnumWindows(Some(collect), &mut wins as *mut _ as LPARAM) }; - let mut btns = vec![Btn { pin: None, wins: vec![], icon: null_mut() }]; - PINS.with_borrow(|pins| btns.extend((0..pins.len()).map(|i| Btn { pin: Some(i), wins: vec![], icon: null_mut() }))); - let mut loose: Vec = Vec::new(); - let explorer = file_explorer_exe(); - let explorer_pinned = PINS.with_borrow(|p| p.iter().any(|p| p.target == explorer)); - for w in wins { - let exe = unsafe { exe_of(w) }; - let exe = as_pinned_exe(&exe, &explorer, explorer_pinned); - // pins of one exe (two browser profiles, #132) tell their windows apart by AppUserModelID; a pin or window without one - // takes any window of its exe - let pin = PINS.with_borrow(|p| { - let mine: Vec = (0..p.len()).filter(|&i| !p[i].target.is_empty() && p[i].target == exe).collect(); - let id = unsafe { win_meta(w).0 }; - if mine.is_empty() { - return (0..p.len()).find(|&i| pin_of_other_exe(&p[i].target, &p[i].args, &p[i].aumid, &exe, &id)); - } - mine.iter().copied().find(|&i| !id.is_empty() && p[i].aumid == id).or_else(|| mine.iter().copied().find(|&i| id.is_empty() || p[i].aumid.is_empty())) - }); - match pin { - Some(i) => btns[1 + i].wins.push(w), - None => loose.push(w), - } - } - // EnumWindows lists by z-order, so clicking a window would jump its button to the front: keep the order they first appeared in - let mut keys: Vec = vec![String::new(); btns.len()]; // keys[i] belongs to btns[i]; "" matches nothing - ORDER.with_borrow_mut(|o| { - o.retain(|w| loose.contains(w)); - o.extend(loose.iter().filter(|w| !o.contains(w)).copied().collect::>()); - for &w in o.iter() { - // windows of one app share a button (a click then offers the list); generic hosts (Store apps, java...) stay apart (#90) - // the window's own AppUserModelID is part of the key: a web app installed from Brave runs as brave.exe too (#118, #117) - let exe = unsafe { exe_of(w) }; - let key = format!("{exe}|{}", unsafe { win_meta(w).0 }); - let same = (!exe.is_empty() && !is_host(&exe)).then(|| keys.iter().position(|k| *k == key)).flatten(); - match same { - Some(i) => btns[i].wins.push(w), - None => { - btns.push(Btn { pin: None, wins: vec![w], icon: unsafe { win_meta(w).1 } }); - keys.push(key); - } - } - } - }); - let keys: Vec = btns.iter().skip(1).filter_map(key_for_button).collect(); - BUTTON_ORDER.with_borrow_mut(|order| { - order.retain(|key| keys.contains(key)); - for key in &keys { if !order.contains(key) { order.push(key.clone()); } } - btns[1..].sort_by_key(|b| key_for_button(b).and_then(|key| order.iter().position(|x| *x == key)).unwrap_or(usize::MAX)); - }); - BTNS.set(btns); -} - -thread_local! { - // hwnd -> (pid, when read, AppUserModelID, icon): the AUMID is a COM call and a host app's icon up to two 40 ms - // WM_GETICON round trips, too much for every refresh; re-read after META_TTL (apps set both shortly after start) - static META: RefCell> = RefCell::new(HashMap::new()); -} -const META_TTL: u64 = 4000; - -unsafe fn win_meta(w: HWND) -> (String, HICON) { - let mut pid = 0u32; - GetWindowThreadProcessId(w, &mut pid); - let now = now_ms(); - if let Some(v) = META.with_borrow(|m| m.get(&(w as usize)).filter(|e| e.0 == pid && now.saturating_sub(e.1) < META_TTL).map(|e| (e.2.clone(), e.3))) { - return v; - } - let v = (win_aumid(w), win_icon(w)); - META.with_borrow_mut(|m| { - if m.len() > 512 { - m.clear(); // closed windows never leave on their own - } - m.insert(w as usize, (pid, now, v.0.clone(), v.1)); - }); - v -} - -/// A minimized window that Windows left as a caption stub on the desktop (it sits at the bottom left with its restore / -/// maximize / close buttons) goes off screen, as explorer's taskbar would have done. Restoring it is unaffected. -unsafe fn hide_stub(w: HWND) { - let mut r: RECT = zeroed(); - if IsIconic(w) != 0 && GetWindowRect(w, &mut r) != 0 && r.left > -30000 { - SetWindowPos(w, null_mut(), -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } -} - -fn refresh() { - refresh_windows(); - refresh_status(); -} - -/// The buttons: on window events (win_event) and every few seconds as a safety net. -fn refresh_windows() { - refresh_buttons(); - BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).for_each(|&w| unsafe { hide_stub(w); fit_normal(w); fit_restored(w) })); -} - -/// Everything polled once a second: battery, volume, wifi, explorer, dead tray icons. -fn refresh_status() { - let n = TICK.get(); - TICK.set(n + 1); - unsafe { - let mut p: SYSTEM_POWER_STATUS = zeroed(); - let ok = GetSystemPowerStatus(&mut p) != 0 && p.BatteryFlag & 128 == 0 && p.BatteryLifePercent <= 100; - BAT.set(if ok { (p.BatteryLifePercent as i32, p.ACLineStatus == 1) } else { (-1, false) }); - read_volume(); - let up = !find_other("Shell_TrayWnd").is_null(); - if EXPLORER_UP.swap(up, Relaxed) && !up { - place(BAR.load(Relaxed) as HWND); // Explorer (started for Settings) is gone and took the reserved strip with it - // icons that apps put into Explorer's (hidden) tray went with it: ask every app to register again, now with us. - // The empty-tray check below misses this when some icons already reached the bar. - announce(); - } - if TAPPS.with_borrow(|t| t.is_empty()) && n % 4 == 2 { - announce(); // no icons yet (apps started before us, or explorer restarted): ask them to register again - } - if n % 3 == 0 { - read_wifi(); - } - } - unsafe { - // icons of apps that died without NIM_DELETE - TAPPS.with_borrow_mut(|t| { - t.retain(|x| { - let alive = IsWindow(x.hwnd) != 0; - if !alive { - DestroyIcon(x.icon); - } - alive - }) - }); - // explorer re-raises its own Shell_TrayWnd now and then; ours must stay in front so apps keep finding it first - SetWindowPos(HOST.get(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); - } -} - -// ---------- layout / hit-testing ---------- - -// ---------- Restart and Shut down on the bar (#173): one pill between the system group and the clock ---------- - -fn power_off_marker() -> PathBuf { - appdata_file("topbar-no-power.txt") -} - -/// The buttons of the pill; none when switched off in the bar's settings (#208), and the pill takes no room then. -fn power_keys() -> &'static [i32] { - if power_off_marker().exists() { &[] } else { &[POW_R, POW_S] } -} - -pub(crate) fn power_shown() -> bool { - !power_keys().is_empty() -} - -pub(crate) fn set_power_shown(on: bool) { - let _ = if on { std::fs::remove_file(power_off_marker()) } else { std::fs::write(power_off_marker(), "1") }; -} - -/// Restart or shut down after a confirmation, so a stray click does not end the session. -unsafe fn power_click(key: i32) { - let (q, arg) = if key == POW_R { - (t!("Перезагрузить компьютер?", "Restart the computer?", ja: "コンピューターを再起動しますか?", pt: "Reiniciar o computador?", zh: "要重启计算机吗?"), "/r") - } else { - (t!("Выключить компьютер?", "Shut down the computer?", ja: "コンピューターをシャットダウンしますか?", pt: "Desligar o computador?", zh: "要关闭计算机吗?"), "/s") - }; - if MessageBoxW(BAR.load(Relaxed) as HWND, wide(q).as_ptr(), wide("WinRust").as_ptr(), MB_YESNO | MB_ICONQUESTION | MB_TOPMOST | MB_SETFOREGROUND) == IDYES { - let _ = Command::new("shutdown.exe").args([arg, "/t", "0"]).creation_flags(NO_WINDOW).spawn(); - } -} - -/// Draws the power buttons; `cell(start, len)` is the button's rectangle along the bar. -unsafe fn paint_power(dc: HDC, l: &Layout, hot: i32, f_glyph: HFONT, cell: impl Fn(i32, i32) -> RECT) { - let pill = cell(l.power.0, l.power.1 - l.power.0); - fill(dc, pill, mix(pal().bg, pal().hover, 0.6), sc(8)); - SelectObject(dc, f_glyph); - for (i, &k) in power_keys().iter().enumerate() { - let rc = cell(l.power.0 + i as i32 * sc(32), sc(32)); - glow(dc, k, hot == k, rc, mix(pal().bg, pal().hover, 0.6), mix(pal().hover, pal().accent, 0.35), sc(8)); - text(dc, if k == POW_R { "\u{E777}" } else { "\u{E7E8}" }, rc, pal().text, DT_CENTER); - } -} - -struct Layout { - gear_x: i32, // Style/Bar settings gear: far left normally, or right of Start when start_left is on - start_x: i32, // Start (Windows) button: far left corner when start_left is on, or in the main group - x0: i32, // first slot of the main group: Search, Task View, then Start (unless start_left) and apps - bw: i32, - gap: i32, - power: (i32, i32), - apps: (i32, i32), - sys: (i32, i32), - wid: (i32, i32), // the mods' widgets, between the tray icons and the system group - clock: (i32, i32), -} - -impl Layout { - fn btn_pos(&self, i: i32) -> i32 { - if i == 0 { - self.start_x - } else { - let lead = if i18n::style::start_left() { LEAD - 1 } else { LEAD }; - self.x0 + (i + lead) * (self.bw + self.gap) - } - } -} - -#[derive(Clone, PartialEq, Eq)] -enum DragButton { Pin(Vec), Window(isize) } -struct ButtonDrag { button: DragButton, start_x: i32, start_y: i32, moved: bool } -thread_local! { static BUTTON_DRAG: RefCell> = const { RefCell::new(None) }; } - -fn move_item(items: &mut Vec, from: usize, to: usize) -> bool { - if from >= items.len() || to >= items.len() || from == to { return false; } - let item = items.remove(from); - items.insert(to, item); - true -} - -fn button_key(index: i32) -> Option { - if index < 1 { return None; } - BTNS.with_borrow(|b| b.get(index as usize).and_then(key_for_button)) -} - -fn key_for_button(button: &Btn) -> Option { - match button.pin { - Some(i) => PINS.with_borrow(|pins| pins.get(i).map(|p| DragButton::Pin(p.lnk.clone()))), - None => button.wins.first().map(|w| DragButton::Window(*w as isize)), - } -} - -fn save_button_order() { - BUTTON_ORDER.with_borrow(|order| { - let pins = order.iter().filter_map(|key| match key { DragButton::Pin(path) => Some(std::path::Path::new(&wstr_of(path)).file_name().unwrap_or_default().to_string_lossy().into_owned()), _ => None }).collect::>().join("\n"); - let _ = std::fs::write(appdata_file("topbar-pin-order.txt"), pins); - }); -} - -fn reorder_buttons(from: DragButton, to: DragButton) { - let changed = BUTTON_ORDER.with_borrow_mut(|order| { - if let (Some(from), Some(to)) = (order.iter().position(|x| *x == from), order.iter().position(|x| *x == to)) { - move_item(order, from, to) - } else { - false - } - }); - if changed { - let pins: Vec> = BUTTON_ORDER.with_borrow(|order| order.iter().filter_map(|key| match key { DragButton::Pin(path) => Some(path.clone()), _ => None }).collect()); - PINS.with_borrow_mut(|items| items.sort_by_key(|item| pins.iter().position(|p| *p == item.lnk).unwrap_or(usize::MAX))); - refresh_buttons(); - } -} - -unsafe fn drag_target(hwnd: HWND, x: i32, y: i32) -> Option { - let mut rect: RECT = zeroed(); - GetClientRect(hwnd, &mut rect); - let (axis, length) = if vert() { (y, rect.bottom) } else { (x, rect.right) }; - let layout = layout(length); - let count = BTNS.with_borrow(|b| b.len()) as i32; - let lead = if i18n::style::start_left() { LEAD - 1 } else { LEAD }; // the same slots as Layout::btn_pos - drag_slot(axis, layout.x0, layout.bw, layout.gap, count, layout.apps.0, lead).and_then(button_key) -} - -/// The button under `axis`: button i sits in slot i + `lead` from x0 (Layout::btn_pos); Start (0) is never a target. -fn drag_slot(axis: i32, x0: i32, bw: i32, gap: i32, count: i32, apps_left: i32, lead: i32) -> Option { - if count <= 1 || bw <= 0 || gap < 0 || axis < x0 || axis >= apps_left { return None; } - Some(((axis - x0 + gap / 2) / (bw + gap) - lead).clamp(1, count - 1)) -} - -fn layout(w: i32) -> Layout { - let gap = sc(4); - let clock = (w - sc(6) - clock_w(), w - sc(6)); - let power = (clock.0 - sc(4) - sc(32) * power_keys().len() as i32, clock.0 - sc(4)); - let sys = (power.0 - sc(4) - sys_w(), power.0 - sc(4)); - let wid = (sys.0 - widgets::width(), sys.0); - let apps = (wid.0 - sc(24) * tray_count() as i32, wid.0); - let margin = (w - apps.0) + sc(8); // keep the button group centered and clear of both sides - let sl = i18n::style::start_left(); - let btns_len = BTNS.with_borrow(|b| b.len()) as i32; - let total_n = btns_len + LEAD; // + the search and Task View slots - let bw = (((w - 2 * margin + gap) / total_n.max(1)) - gap).clamp(sc(16), sc(44 + [-6, 0, 8][i18n::style::bar_size() as usize % 3])); - let group_n = total_n - i32::from(sl); - // centered on search + (Start if not pinned left) + pins only: opening an unpinned window adds a button on the right instead of shifting left - let fixed = (PINS.with_borrow(|p| p.len()) as i32 + LEAD + if sl { 0 } else { 1 }).min(group_n); - // ...but never so far right that the windows' buttons run into the tray: then the whole row shifts left - let right_limit = w - margin - (group_n * (bw + gap) - gap); - let centered = (w - (fixed * (bw + gap) - gap)) / 2; - let (start_left_x, gear_x) = if sl { - let sx = sc(GEAR_X.0); - (sx, sx + bw + gap) - } else { - (0, sc(GEAR_X.0)) - }; - let left_min = gear_x + sc(GEAR_X.1 + 6); - let x0 = if i18n::style::align_left() { 0 } else { centered }.min(right_limit).max(left_min); // clear of the gear (and Start if pinned left) - let start_x = if sl { start_left_x } else { x0 + LEAD * (bw + gap) }; - Layout { gear_x, start_x, x0, bw, gap, power, apps, sys, wid, clock } -} - -unsafe fn hit(hwnd: HWND, x: i32, y: i32) -> i32 { - let mut r: RECT = zeroed(); - GetClientRect(hwnd, &mut r); - // a side bar runs the same layout along its height - let (x, l) = if vert() { (y, layout(r.bottom)) } else { (x, layout(r.right)) }; - let sl = i18n::style::start_left(); - if sl { - if x < l.start_x + l.bw { - return 0; // Start reaches all the way to the screen corner - } - if x >= l.gear_x && x < l.gear_x + sc(GEAR_X.1) { - return GEAR; - } - } else if x < l.gear_x + sc(GEAR_X.1) { - return GEAR; - } - if x >= l.clock.1 { - return SHOWDESK; - } - if x >= l.clock.0 { - return CLOCK; - } - if x >= l.power.0 { - return power_keys().get(((x - l.power.0) / sc(32)) as usize).copied().unwrap_or(NONE); - } - if x >= l.sys.0 { - let d = x - l.sys.0; - let (lw, ww) = (sc(SYS_LANG), sc(SYS_WIFI)); - return if d < lw { LANG } else if d < lw + ww { WIFI_I } else if d < lw + ww + sc(SYS_VOL) { VOL_I } else if BAT.get().0 >= 0 { BAT_I } else { NONE }; - } - if x >= l.wid.0 { - return NONE; // a widget is text only - } - if x >= l.apps.0 { - return TAPP + (x - l.apps.0) / sc(24); - } - let n = BTNS.with_borrow(|b| b.len()) as i32 + LEAD - i32::from(sl); - let (d, i) = (x - l.x0, (x - l.x0) / (l.bw + l.gap)); - if d < 0 || d % (l.bw + l.gap) >= l.bw || i >= n { NONE } else if i == 0 { SEARCH } else if i == 1 { TASKVIEW } else { i - LEAD + i32::from(sl) } -} - -// ---------- animation ---------- - -fn mix(a: u32, b: u32, t: f32) -> u32 { - let ch = |s: u32| { - let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32); - (x + (y - x) * t) as u32 - }; - ch(0) | ch(8) << 8 | ch(16) << 16 -} - -fn ease(t: f32) -> f32 { - t * t * (3.0 - 2.0 * t) -} - -unsafe fn now_ms() -> u64 { - GetTickCount64() -} - -/// Eased 0..1 hover value of one element: glides toward `on` (1) / off (0) instead of jumping. Sets BUSY while it moves, -/// the painter then schedules another frame. -unsafe fn hv(key: i32, on: bool) -> f32 { - let now = now_ms(); - let target = if on { 1.0 } else { 0.0 }; - let v = HV.with_borrow_mut(|m| { - let e = m.entry(key).or_insert((0.0, now)); - let dt = now.saturating_sub(e.1).min(50) as f32; // a long pause must not make the first frame jump - e.1 = now; - e.0 = if e.0 < target { (e.0 + dt / 130.0).min(target) } else { (e.0 - dt / 180.0).max(target) }; - e.0 - }); - if v != target { - BUSY.set(true); - } - ease(v) -} - -/// Rounded highlight that fades in and out; `from` is the colour it sits on. A click also flashes it in the accent colour. -unsafe fn glow(dc: HDC, key: i32, on: bool, r: RECT, from: u32, to: u32, rad: i32) { - let t = hv(key, on); - let p = press_t(key); - if t > 0.01 || p > 0.0 { - fill(dc, r, mix(mix(from, to, t), pal().accent, 0.5 * p), rad); - } -} - -thread_local! { - static PRESS: Cell<(i32, u64)> = const { Cell::new((i32::MIN, 0)) }; // last clicked element and when - static SEEN: RefCell> = RefCell::new(HashMap::new()); // when each taskbar button first showed -} - -/// Marks `key` as just clicked / dropped on: its highlight flashes and its icon squeezes for a moment. -unsafe fn press(key: i32) { - PRESS.set((key, now_ms())); -} - -/// 1.0 right after the click, easing to 0 over 320 ms (keeps the painter running meanwhile). -unsafe fn press_t(key: i32) -> f32 { - let (k, t0) = PRESS.get(); - let t = now_ms().saturating_sub(t0) as f32 / 320.0; - if k != key || t >= 1.0 { - return 0.0; - } - BUSY.set(true); - (1.0 - t) * (1.0 - t) -} - -/// 0..1 over 260 ms after a taskbar button first appears: new windows pop in instead of snapping into place. -unsafe fn appear(key: isize) -> f32 { - let now = now_ms(); - let t0 = SEEN.with_borrow_mut(|m| { - if m.len() > 512 { - m.clear(); // shortcut: closed windows are never pruned one by one; a clear only replays the pop-in - } - *m.entry(key).or_insert(now) - }); - let t = now.saturating_sub(t0) as f32 / 260.0; - if t >= 1.0 { - return 1.0; - } - BUSY.set(true); - ease(t) -} - -/// How far the bar sits below its place: it rises in at start and drops out of the way (and back) when a fullscreen -/// window takes the screen. -fn bar_off() -> i32 { - ((1.0 - ease(BAR_P.get())) * (bar_h() + dock_gap()) as f32) as i32 -} - -unsafe fn bar_anim(hwnd: HWND) { - BAR_T.set(now_ms()); - SetTimer(hwnd, 5, 15, None); -} - -unsafe fn bar_step(hwnd: HWND) { - // hides for a fullscreen game or video, and with "auto-hide" on while the pointer is away (never otherwise: not over the desktop, not in any style) - let target = if FULLSCREEN.load(Relaxed) || (i18n::style::autohide() && DESK_HIDE.load(Relaxed)) { 0.0 } else { 1.0 }; - let now = now_ms(); - let dt = now.saturating_sub(BAR_T.replace(now)).min(50) as f32; - let p = BAR_P.get(); - let p = if p < target { (p + dt / 380.0).min(target) } else { (p - dt / 240.0).max(target) }; - BAR_P.set(p); - let shown = p > 0.0 && IsWindowVisible(hwnd) == 0; - if shown { - ShowWindow(hwnd, SW_SHOWNOACTIVATE); - } - let (px, py) = bar_pos(); - // on top of the other topmost windows only when it comes back; sliding away must not raise it over a fullscreen game - SetWindowPos(hwnd, HWND_TOPMOST, px, py, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | if shown { 0 } else { SWP_NOZORDER }); - if p == target { - KillTimer(hwnd, 5); - if p == 0.0 { - ShowWindow(hwnd, SW_HIDE); // not just moved away: a hidden bar cannot cover a game - } - } -} - -/// True when the foreground window covers the whole primary monitor (game, F11 video, presentation). -/// A maximized window does not: the bar's reserved strip keeps it below the bar. -unsafe fn fullscreen_now(bar: HWND) -> bool { - fg_covers(bar).is_some_and(|m| (m.left, m.top) == (0, 0)) -} - -/// The monitor the foreground window covers whole, if it covers one. -unsafe fn fg_covers(bar: HWND) -> Option { - let fg = GetForegroundWindow(); - if fg.is_null() || fg == bar || IsWindowVisible(fg) == 0 { - return None; - } - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mut mi); - let m = mi.rcMonitor; - // A fullscreen game brought back with Alt+Tab gets the foreground while still minimized and only then switches the screen - // over: if the bar stayed on top then, the game lost fullscreen again. The window that was fullscreen counts as such - // while it comes back, and so does any Direct3D game Windows itself reports as fullscreen. - let mut quns = 0; - if windows_sys::Win32::UI::Shell::SHQueryUserNotificationState(&mut quns) >= 0 && quns == 3 { - return Some(m); // QUNS_RUNNING_D3D_FULL_SCREEN - } - if IsIconic(fg) != 0 { - return (fg as isize == FS_WND.get()).then_some(m); - } - let mut cls = [0u16; 64]; - let n = GetClassNameW(fg, cls.as_mut_ptr(), 64).max(0) as usize; - if matches!(String::from_utf16_lossy(&cls[..n]).as_str(), "Progman" | "WorkerW" | "Shell_TrayWnd" | "Shell_SecondaryTrayWnd" | "RustExplorer") { - return None; // the desktop itself is full size (rs-shell's desktop is a rust-explorer window; a file manager is never "fullscreen") - } - let mut r: RECT = zeroed(); - GetWindowRect(fg, &mut r); - let caption = GetWindowLongW(fg, GWL_STYLE) as u32 & WS_CAPTION == WS_CAPTION; - let fs = covers_monitor(r, m, caption, IsZoomed(fg) != 0); - if fs { - FS_WND.set(fg as isize); - } - fs.then_some(m) -} - -/// A game switching into fullscreen leaves the screen without any foreground window for a moment, again and again until it -/// settles: the bar must not come back in that moment (it would land on top and knock the game out of fullscreen, which then -/// tries again, in a loop). So the bar returns only once fullscreen has been gone for 1.5 s without a break. -unsafe fn fs_settled(now_fs: bool) -> bool { - if now_fs { - FS_OFF.set(0); - return true; - } - if !FULLSCREEN.load(Relaxed) { - return false; - } - // the same window back with a frame (video left fullscreen) or gone: no game switching, no wait (#269) - let w = FS_WND.get() as HWND; - if !w.is_null() && (IsWindow(w) == 0 || (GetForegroundWindow() == w && IsIconic(w) == 0 && GetWindowLongW(w, GWL_STYLE) as u32 & WS_CAPTION == WS_CAPTION)) { - FS_OFF.set(0); - return false; - } - let now = now_ms(); - if FS_OFF.get() == 0 { - FS_OFF.set(now); - } - if now.saturating_sub(FS_OFF.get()) < 1500 { - return true; - } - FS_OFF.set(0); - false -} - -/// A framed maximized window overhangs the monitor by its border and is not fullscreen (#88); but a game in "borderless -/// window" mode that keeps its caption style while sized to the monitor (SDL, GLFW, Dota 2 and others) is. Such a window -/// can sit a pixel past the monitor edge (Minecraft: 1921 wide on a 1920 monitor), so it has to "cover", not "equal". -fn covers_monitor(r: RECT, m: RECT, caption: bool, zoomed: bool) -> bool { - if caption && zoomed { - return false; // a framed maximized window: not a game (#88) - } - if caption && (r.left < m.left - 1 || r.top < m.top - 1) { - return false; // its border overhangs: a framed window sized like a maximized one (Firefox after restore, #237) - } - r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom -} - -/// True when no app window is on screen (none open, or all minimized: Win+D): the user is looking at the desktop. -unsafe fn desktop_now() -> bool { - BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).all(|&w| IsIconic(w) != 0)) -} - -unsafe fn fs_update(hwnd: HWND) { - second::update(hwnd); - let fs = fs_settled(fullscreen_now(hwnd)); - // a fullscreen game keeps the screen: the pointer at the bottom edge does not bring the bar (games park it at the - // edges all the time); Win opens Start, which brings the bar with it - let mut pt = POINT { x: 0, y: 0 }; - GetCursorPos(&mut pt); - // desktop in front: the bar leaves 2 s after the pointer does and comes back at the bottom edge (an open flyout keeps it) - let now = now_ms(); - let sh = GetSystemMetrics(SM_CYSCREEN); - let sw = GetSystemMetrics(SM_CXSCREEN); - let over = if vert() { - if i18n::style::side() == i18n::style::Side::Left { pt.x <= 0 || (pt.x < bar_h() && BAR_P.get() > 0.0) } else { pt.x >= sw - 1 || (pt.x >= sw - bar_h() && BAR_P.get() > 0.0) } - } else if at_top() { pt.y <= 0 || (pt.y < bar_h() && BAR_P.get() > 0.0) } else { pt.y >= sh - 1 || (pt.y >= sh - bar_h() - dock_gap() && BAR_P.get() > 0.0) }; - if fs || !(i18n::style::autohide() || desktop_now() || dock_covered()) || fly::any_open() || over { - DESK_T.set(now); - } - let desk = !fs && now.saturating_sub(DESK_T.get()) >= 2000; - if DESK_HIDE.swap(desk, Relaxed) != desk { - bar_anim(hwnd); - } - if FULLSCREEN.swap(fs, Relaxed) != fs { - if fs { - fly::close_now(); - hide_tip(hwnd); - thumbs::hide_preview(); - } - bar_anim(hwnd); - } - // the 250 ms watch is only needed while the pointer decides (auto-hide, dock, desktop, bar away); otherwise - // the foreground event, ABN_FULLSCREENAPP and the 1 s tick call this - let poll = i18n::style::autohide() || dock() || desktop_now() || DESK_HIDE.load(Relaxed) || FS_OFF.get() != 0; - if FS_POLL.replace(poll) != poll { - if poll { - SetTimer(hwnd, 3, 250, None); - } else { - KillTimer(hwnd, 3); - } - } -} - -thread_local! { - static FS_POLL: Cell = const { Cell::new(true) }; // timer 3 runs (set in main) -} - -/// The dock is in the way of the window in front (one dragged down under it): it hides like over the -/// desktop and comes back when the pointer touches the bottom edge. -unsafe fn dock_covered() -> bool { - if !dock() { - return false; - } - let fg = GetForegroundWindow(); - // a maximized window never hides the dock (it could stay gone until the window was restored) - if fg.is_null() || IsIconic(fg) != 0 || IsZoomed(fg) != 0 || fg == BAR.load(Relaxed) as HWND || fly::any_open() { - return false; - } - let mut r: RECT = zeroed(); - GetWindowRect(fg, &mut r); - let (x, w) = bar_x_w(); - let top = GetSystemMetrics(SM_CYSCREEN) - bar_h() - dock_gap(); - r.bottom > top && r.right > x && r.left < x + w -} - -/// A bar that should be on screen but is hidden or off its edge (a late display change at boot) is put back (#287). -unsafe fn keep_in_place(hwnd: HWND) { - if FULLSCREEN.load(Relaxed) || i18n::style::autohide() { - return; - } - if BAR_P.get() < 1.0 { - bar_anim(hwnd); - return; - } - let mut r: RECT = zeroed(); - GetWindowRect(hwnd, &mut r); - let wrong_height = vert() && r.bottom - r.top != GetSystemMetrics(SM_CYSCREEN); - if IsWindowVisible(hwnd) == 0 || (r.left, r.top) != bar_pos() || wrong_height { - ShowWindow(hwnd, SW_SHOWNOACTIVATE); - place(hwnd); - } -} - -thread_local! { static DRAG_OVER: Cell = const { Cell::new(NONE) }; } - -/// Something dragged from another window and held over an app button brings that app forward (#265). -// shortcut: polled by the 1 s tick, so 1-2 s; an OLE drop target if that feels slow -unsafe fn drag_hover(hwnd: HWND) { - let mut p = POINT { x: 0, y: 0 }; - GetCursorPos(&mut p); - // our own presses are in BUTTON_DRAG: not a drag from outside - let held = GetAsyncKeyState(VK_LBUTTON as i32) < 0 && BUTTON_DRAG.with_borrow(|d| d.is_none()) && WindowFromPoint(p) == hwnd; - let mut h = NONE; - if held { - ScreenToClient(hwnd, &mut p); - h = hit(hwnd, p.x, p.y); - } - if DRAG_OVER.replace(h) != h || button_key(h).is_none() { return; } - let w = BTNS.with_borrow(|b| b.get(h as usize).and_then(|b| b.wins.first().copied())); - if let Some(w) = w.filter(|&w| GetForegroundWindow() != w) { bring(w); } -} - -/// SetForegroundWindow that also works when the request comes from a keyboard hook (we have not "received input" then). -unsafe fn force_fg(hw: HWND) { - winrust_common::fg::force(hw); -} - -thread_local! { - // windows topbar itself minimized while maximized: they must come back maximized even if the placement flags lost it (#268) - static WAS_MAX: RefCell> = const { RefCell::new(Vec::new()) }; -} - -/// Records that `w` is being minimized from a maximized state, so `bring` returns it maximized. -unsafe fn note_minimize(w: HWND) { - WAS_MAX.with_borrow_mut(|v| { - v.retain(|&x| x != w && IsWindow(x) != 0); - if IsZoomed(w) != 0 { - v.push(w); - } - }); -} - -/// Switches to a window (Alt+Tab, its button, a preview, a menu). A maximized one comes back maximized in a single step; any -/// other minimized one goes through SwitchToThisWindow, the call Windows' own Alt+Tab makes: it activates and restores in one -/// step. Restoring first and activating after made a fullscreen game get the foreground, lose it to the previous window and -/// get it again; it then gave up on fullscreen (stayed black). -pub(crate) unsafe fn bring(w: HWND) { - // WPF_RESTORETOMAXIMIZED: the window was maximized before it was minimized, so it must come back maximized. - const RESTORE_TO_MAX: u32 = 0x0002; - let mut wp: WINDOWPLACEMENT = zeroed(); - wp.length = size_of::() as u32; - let placed = GetWindowPlacement(w, &mut wp) != 0; - let was_iconic = IsIconic(w) != 0; - let remembered = WAS_MAX.with_borrow_mut(|v| v.iter().position(|&x| x == w).map(|i| { v.swap_remove(i); })); - let was_max = was_iconic && (remembered.is_some() || (placed && wp.flags & RESTORE_TO_MAX != 0)); - if was_max && placed { - // show it maximized straight away: SwitchToThisWindow first restores it, and maximizing after visibly flickers - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(MonitorFromRect(&wp.rcNormalPosition, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 { - clamp_rect(&mut wp.rcNormalPosition, workspace(mi.rcWork, mi.rcMonitor)); - } - wp.showCmd = 3; // SW_SHOWMAXIMIZED - if SetWindowPlacement(w, &wp) == 0 { - SwitchToThisWindow(w, 1); - } - } else if was_iconic { - SwitchToThisWindow(w, 1); - if IsIconic(w) != 0 { - ShowWindow(w, SW_RESTORE); - } - } - if GetForegroundWindow() != w { - force_fg(w); // the click that called us owns the foreground, so showing it may not have taken it - } -} - -/// Fills `r` (right / bottom exclusive) in colour `c`; `rad` > 0 rounds the corners (rad = corner diameter), anti-aliased -/// through GDI+. Plain GDI for square boxes and when GDI+ is not available. -unsafe fn fill(dc: HDC, r: RECT, c: u32, rad: i32) { - let rad = if style().square() { 0 } else { rad }; - let (w, h) = ((r.right - r.left) as f32, (r.bottom - r.top) as f32); - if w <= 0.0 || h <= 0.0 { - return; - } - let mut g: *mut GpGraphics = null_mut(); - if rad <= 0 || GdipCreateFromHDC(dc, &mut g) != 0 || g.is_null() { - let b = CreateSolidBrush(c); - if rad <= 0 { - FillRect(dc, &r, b); - } else { - let (ob, op) = (SelectObject(dc, b), SelectObject(dc, GetStockObject(NULL_PEN))); - RoundRect(dc, r.left, r.top, r.right + 1, r.bottom + 1, rad, rad); - SelectObject(dc, ob); - SelectObject(dc, op); - } - DeleteObject(b); - return; - } - GdipSetSmoothingMode(g, SmoothingModeAntiAlias); - GdipSetPixelOffsetMode(g, PixelOffsetModeHalf); // pixel i spans [i, i+1): straight edges stay crisp - let (x, y, d) = (r.left as f32, r.top as f32, (rad as f32).min(w).min(h)); - let mut path: *mut GpPath = null_mut(); - GdipCreatePath(FillModeAlternate, &mut path); - GdipAddPathArc(path, x, y, d, d, 180.0, 90.0); - GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0); - GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0); - GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0); - GdipClosePathFigure(path); - let mut br: *mut GpSolidFill = null_mut(); - GdipCreateSolidFill(0xFF00_0000 | (c & 255) << 16 | (c & 0xFF00) | (c >> 16 & 255), &mut br); // COLORREF -> ARGB - GdipFillPath(g, br as *mut GpBrush, path); - GdipDeleteBrush(br as *mut GpBrush); - GdipDeletePath(path); - GdipDeleteGraphics(g); -} - -unsafe fn text(dc: HDC, s: &str, mut r: RECT, c: u32, flags: u32) { - SetTextColor(dc, c); - let w = wide(s); - DrawTextW(dc, w.as_ptr(), -1, &mut r, flags | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS); -} - -unsafe fn icon_of(h: HWND) -> HICON { - for which in [1usize, 2] { - // ICON_BIG, ICON_SMALL2 - let mut r = 0usize; - SendMessageTimeoutW(h, WM_GETICON, which, 0, SMTO_ABORTIFHUNG, 40, &mut r); - if r != 0 { - return r as HICON; - } - } - let c = GetClassLongPtrW(h, GCLP_HICON); - (if c != 0 { c } else { GetClassLongPtrW(h, GCLP_HICONSM) }) as HICON -} - -/// The app window the user is typing in: the foreground window, or, while our own bar / panel / menu holds the -/// foreground (after a right click, a closed Start...), the last app window that had it. -unsafe fn app_window() -> HWND { - let fg = GetForegroundWindow(); - let mut pid = 0u32; - GetWindowThreadProcessId(fg, &mut pid); - if !fg.is_null() && pid != std::process::id() { - APP_FG.set(fg); - return fg; - } - let last = APP_FG.get(); - if IsWindow(last) != 0 { last } else { fg } -} - -thread_local! { - static WIN_DIRTY: Cell = const { Cell::new(false) }; // a window refresh is already scheduled (timer 8) -} - -/// Repaints (GDI+, the costly part) only when something shown changed; `tick`: every 10th tick anyway as a safety net. -unsafe fn repaint_if_changed(hwnd: HWND, tick: bool) { - let (last, quiet) = SIG.get(); - let s = view_sig(); - if s != last || (tick && quiet >= 10) { - SIG.set((s, 0)); - InvalidateRect(hwnd, null(), 0); - second::invalidate(); - } else if tick { - SIG.set((s, quiet + 1)); - } -} - -/// Window events (WINEVENT_OUTOFCONTEXT: delivered on the bar's thread inside GetMessageW). Instead of enumerating every -/// window twice a second, the bar looks again ~30 ms after something that can change a button happened. -unsafe extern "system" fn win_event(_: windows_sys::Win32::UI::Accessibility::HWINEVENTHOOK, ev: u32, w: HWND, id: i32, child: i32, _: u32, _: u32) { - if id != 0 || child != 0 || w.is_null() { - return; // only whole windows (not carets, cursors, parts of controls) - } - let bar = BAR.load(Relaxed) as HWND; - if bar.is_null() { - return; - } - let known = || BTNS.with_borrow(|b| b.iter().any(|b| b.wins.contains(&w))); - let top = || GetAncestor(w, GA_PARENT) == GetDesktopWindow(); - let relevant = match ev { - 0x0003 => { - fs_update(bar); // EVENT_SYSTEM_FOREGROUND: the active button and fullscreen may change - true - } - 0x8001 => known(), // destroyed: it can no longer be asked anything, but it may be one of ours - 0x800C => !known() && top(), // title set: a window with no title had no button yet - _ => top() || known(), // created, shown, hidden, cloaked, uncloaked, minimized, restored - }; - if relevant && !WIN_DIRTY.replace(true) { - SetTimer(bar, 8, 30, None); - } -} - -/// Hash of everything the bar paints from polled state. -unsafe fn view_sig() -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - BTNS.with_borrow(|b| b.iter().for_each(|b| (b.pin, b.icon as usize, b.wins.iter().map(|&w| (w as usize, IsIconic(w))).collect::>()).hash(&mut h))); - (GetForegroundWindow() as usize, BAT.get(), VOL.get(), WIFI.get(), INET.get(), EXPLORER_UP.load(Relaxed), clock_texts(), lang_name()).hash(&mut h); - TAPPS.with_borrow(|t| t.iter().for_each(|x| (x.hwnd as usize, x.uid, x.icon as usize, x.hidden, &x.tip).hash(&mut h))); - h.finish() -} - -unsafe fn clock_texts() -> (String, String) { - clock_texts_of(0x0400) // LOCALE_USER_DEFAULT -} -/// The time and the date as `locale` (an LCID) formats them: short time without seconds, short date. -unsafe fn clock_texts_of(locale: u32) -> (String, String) { - let mut t: SYSTEMTIME = zeroed(); - GetLocalTime(&mut t); - let (mut a, mut b) = ([0u16; 40], [0u16; 40]); - let n = GetTimeFormatW(locale, 2, &t, null(), a.as_mut_ptr(), 40).max(1) as usize - 1; // TIME_NOSECONDS - let m = GetDateFormatW(locale, 1, &t, null(), b.as_mut_ptr(), 40).max(1) as usize - 1; // DATE_SHORTDATE - (String::from_utf16_lossy(&a[..n]), String::from_utf16_lossy(&b[..m])) -} - -/// The side bar: the same layout as the bottom one, run along the height (top to bottom: gear, search, Start, pins and windows, -/// tray, system, clock), icons only. -unsafe fn paint_vert(dc: HDC, cr: RECT, fonts: [HFONT; 4]) { - let [f_txt, f_small, f_glyph, f_bold] = fonts; - let l = layout(cr.bottom); - let fg = GetForegroundWindow(); - let (lft, rgt) = (sc(6), cr.right - sc(6)); - let cx = (lft + rgt) / 2; - let left = i18n::style::side() == i18n::style::Side::Left; - let hot = HOT.get(); - let active_bg = mix(pal().active, pal().accent, 0.12); - let cell = |y: i32, len: i32| RECT { left: lft, top: y, right: rgt, bottom: y + len }; - let dim = mix(pal().dim, pal().text, 0.5); - - let gr = cell(l.gear_x, sc(GEAR_X.1)); - glow(dc, GEAR, hot == GEAR, gr, pal().bg, pal().hover, sc(8)); - SelectObject(dc, f_glyph); - text(dc, "\u{E713}", gr, if hot == GEAR { pal().text } else { dim }, DT_CENTER); - - let sb = cell(l.x0, l.bw); - glow(dc, SEARCH, hot == SEARCH, sb, pal().bg, pal().hover, sc(8)); - text(dc, "\u{E721}", sb, if hot == SEARCH { pal().text } else { dim }, DT_CENTER); - let tb = cell(l.x0 + l.bw + l.gap, l.bw); - glow(dc, TASKVIEW, hot == TASKVIEW, tb, pal().bg, pal().hover, sc(8)); - text(dc, "\u{E7C4}", tb, if hot == TASKVIEW { pal().text } else { dim }, DT_CENTER); - - BTNS.with_borrow(|btns| { - for (i, b) in btns.iter().enumerate() { - let y = l.btn_pos(i as i32); - let r = cell(y, l.bw); - let mid = y + l.bw / 2; - let act = b.wins.contains(&fg); - let att = !act && FLASH.with_borrow(|f| b.wins.iter().any(|w| f.contains(w))); // flashing: lit until it is activated - let (th, ta, tp) = (hv(i as i32, hot == i as i32), hv(2000 + i as i32, act), press_t(i as i32)); - if th > 0.01 || ta > 0.01 || tp > 0.0 { - fill(dc, r, mix(mix(mix(pal().bg, pal().hover, th), active_bg, ta), pal().accent, 0.5 * tp), sc(8)); - } - if att { - fill(dc, r, mix(pal().bg, pal().accent, 0.4), sc(8)); - } - if i == 0 { - let t = ((icon_sc(8) as f32) * (1.0 + 0.12 * th) * (1.0 - 0.2 * tp)) as i32; - let g = sc(1).max(1); - let tint = [mix(pal().accent, pal().text, 0.35), mix(pal().accent, pal().text, 0.15), mix(pal().accent, pal().text, 0.15), pal().accent]; - for (k, (dx, dy)) in [(-1, -1), (0, -1), (-1, 0), (0, 0)].into_iter().enumerate() { - let (px, py) = (cx + if dx < 0 { -t - g } else { g }, mid + if dy < 0 { -t - g } else { g }); - fill(dc, RECT { left: px, top: py, right: px + t, bottom: py + t }, tint[k], sc(3)); - } - continue; - } - let ic = match b.pin { - Some(p) => PINS.with_borrow(|pins| pins.get(p).map_or(null_mut(), |p| p.icon)), - None => b.icon, - }; - let ic = if ic.is_null() { b.wins.first().map_or(ic, |&w| icon_of(w)) } else { ic }; // a pin whose icon failed to load (#91) - let key = b.pin.map(|p| -(p as isize) - 1).or_else(|| b.wins.first().map(|&w| w as isize)).unwrap_or(0); - let isz = (icon_px().min(l.bw - sc(6)) as f32 * (1.0 - 0.18 * tp) * (0.55 + 0.45 * appear(key))) as i32; - if !ic.is_null() { - DrawIconEx(dc, cx - isz / 2, mid - isz / 2, ic, isz, isz, 0, null_mut(), DI_NORMAL); - } - if !b.wins.is_empty() { - // the running-app pill stands on the edge facing the screen's border - let min = b.wins.iter().all(|&w| IsIconic(w) != 0); - let pl = sc(6) + (sc(12) as f32 * ta) as i32; - let col = if act || att { pal().accent } else if min { mix(pal().dim, pal().bg, 0.45) } else { pal().dim }; - let px = if left { sc(1) } else { cr.right - sc(4) }; - fill(dc, RECT { left: px, top: mid - pl / 2, right: px + sc(3), bottom: mid + pl / 2 }, col, sc(3)); - } - } - }); - - fill(dc, RECT { left: cx - sc(9), top: l.apps.0 - sc(5), right: cx + sc(9), bottom: l.apps.0 - sc(5) + 1 }, pal().line, 0); - - glow(dc, TAPP, hot == TAPP, cell(l.apps.0, sc(24)), pal().bg, pal().hover, sc(8)); - let turn = ease(hv(TF_KEY, IsWindowVisible(TRAYFLY.get()) != 0)); - chevron(dc, cx, l.apps.0 + sc(12), icon_sc(5), if left { 90.0 } else { 270.0 } + 180.0 * turn, mix(pal().text, pal().accent, turn)); - SelectObject(dc, f_txt); - let bar = bar_idx(); - TAPPS.with_borrow(|t| { - for (k, &ix) in bar.iter().enumerate() { - let (i, ti) = (k + 1, &t[ix]); - let y = l.apps.0 + i as i32 * sc(24); - glow(dc, TAPP + i as i32, hot == TAPP + i as i32, cell(y, sc(24)), pal().bg, pal().hover, sc(8)); - if !ti.icon.is_null() { - let size = icon_sc(16); - DrawIconEx(dc, cx - size / 2, y + (sc(24) - size) / 2, ti.icon, size, size, 0, null_mut(), DI_NORMAL); - } - } - }); - - paint_power(dc, &l, hot, f_glyph, cell); - glow(dc, LANG, hot == LANG, cell(l.sys.0, sc(SYS_LANG)), pal().bg, pal().hover, sc(8)); - let grp = cell(l.sys.0 + sc(SYS_LANG + 2), l.sys.1 - l.sys.0 - sc(SYS_LANG + 2)); - let (tg, pg) = (hv(SYS_GRP, matches!(hot, WIFI_I | VOL_I | BAT_I) || fly::is_open(fly::Kind::Quick)), press_t(WIFI_I).max(press_t(VOL_I)).max(press_t(BAT_I))); - if tg > 0.01 || pg > 0.0 { - fill(dc, grp, mix(mix(pal().bg, pal().hover, tg), pal().accent, 0.5 * pg), sc(8)); - } - text(dc, &lang_name(), cell(l.sys.0, sc(SYS_LANG)), pal().text, DT_CENTER); - let y0 = l.sys.0 + sc(SYS_LANG); - net_icon(dc, cx, y0 + sc(SYS_WIFI) / 2, icon_sc(17), f_glyph); - SelectObject(dc, f_glyph); - let (vol, muted) = VOL.get(); - let vg = if muted || vol == 0 { "\u{E74F}" } else if vol < 34 { "\u{E993}" } else if vol < 67 { "\u{E994}" } else { "\u{E995}" }; - let y1 = y0 + sc(SYS_WIFI); - text(dc, vg, cell(y1, sc(SYS_VOL)), if muted { BAD } else { pal().text }, DT_CENTER); - let (pct, ac) = BAT.get(); - if pct >= 0 { - let col = if ac { GOOD } else if pct <= 15 { BAD } else { pal().text }; - let (bw, bh) = (icon_sc(SYS_BAT_W), icon_sc(11)); - let (bx, by) = (cx - bw / 2 - sc(1), y1 + sc(SYS_VOL)); - fill(dc, RECT { left: bx, top: by, right: bx + bw, bottom: by + bh }, col, sc(4)); - fill(dc, RECT { left: bx + sc(1), top: by + sc(1), right: bx + bw - sc(1), bottom: by + bh - sc(1) }, mix(pal().bg, pal().hover, tg), sc(3)); - let fw = ((bw - sc(4)) * pct / 100).max(sc(1)); - fill(dc, RECT { left: bx + sc(2), top: by + sc(2), right: bx + sc(2) + fw, bottom: by + bh - sc(2) }, col, sc(2)); - fill(dc, RECT { left: bx + bw + sc(1), top: by + sc(3), right: bx + bw + sc(3), bottom: by + bh - sc(3) }, col, sc(1)); - SelectObject(dc, f_small); - text(dc, &format!("{pct}%"), cell(y1 + sc(SYS_VOL + SYS_BAT_W + 8), sc(18)), pal().text, DT_CENTER); - } - - let cb = cell(l.clock.0, l.clock.1 - l.clock.0); - glow(dc, CLOCK, hot == CLOCK || fly::is_open(fly::Kind::Cal), cb, pal().bg, pal().hover, sc(8)); - let (tm, dt) = clock_texts(); - let mid = (cb.top + cb.bottom) / 2; - SelectObject(dc, f_bold); - text(dc, &tm, RECT { left: cb.left, top: cb.top, right: cb.right, bottom: mid + sc(1) }, pal().text, DT_CENTER); - SelectObject(dc, f_small); - text(dc, &dt, RECT { left: cb.left, top: mid - sc(1), right: cb.right, bottom: cb.bottom }, mix(pal().dim, pal().text, 0.35), DT_CENTER); -} - -thread_local! { - static BG: Cell<(HDC, HBITMAP, u64)> = const { Cell::new((null_mut(), null_mut(), 0)) }; // cached background layer and its key - static FONTS: Cell<([HFONT; 4], u64)> = const { Cell::new(([null_mut(); 4], 0)) }; -} - -fn key_of(v: impl std::hash::Hash) -> u64 { - use std::hash::Hasher; - let mut h = std::collections::hash_map::DefaultHasher::new(); - v.hash(&mut h); - h.finish() | 1 // never 0, the "empty" key -} - -/// The bar's background for this size, side and style, redrawn only when one of them changes. -unsafe fn bg_layer(wdc: HDC, cr: RECT) -> HDC { - let h = cr.bottom; - let p = pal(); - let key = key_of((cr.right, h, vert(), at_top(), i18n::style::side() == i18n::style::Side::Left, style().light(), format!("{:?}", style()), [p.bg, p.text, p.line, p.accent], SCALE.get().to_bits())); - let (mut dc, mut bmp, k) = BG.get(); - if k == key && !dc.is_null() { - return dc; - } - if dc.is_null() { - dc = CreateCompatibleDC(wdc); - } - if !bmp.is_null() { - DeleteObject(bmp); - } - bmp = CreateCompatibleBitmap(wdc, cr.right, h); - SelectObject(dc, bmp); // the DC's first bitmap is the stock 1x1 one: nothing to give back - BG.set((dc, bmp, key)); - // frosted-glass look: a hairline on top, a faint light catch under it, then the panel colour fading in - let lit = mix(pal().bg, pal().text, 0.045); - if vert() { - fill(dc, cr, pal().bg, 0); - } else { - for y in 0..h { - fill(dc, RECT { left: 0, top: y, right: cr.right, bottom: y + 1 }, mix(lit, pal().bg, (y as f32 / sc(18) as f32).min(1.0)), 0); - } - } - winrust_common::style::backdrop(dc, cr, sc(100) as f32 / 100.0); - if vert() { - // the hairline faces the windows - let x = if i18n::style::side() == i18n::style::Side::Left { cr.right - 1 } else { 0 }; - fill(dc, RECT { left: x, top: 0, right: x + 1, bottom: h }, pal().line, 0); - } - let edge = if at_top() { h - 1 } else { 0 }; // the hairline faces the windows - if !vert() { - fill(dc, RECT { left: 0, top: edge, right: cr.right, bottom: edge + 1 }, pal().line, 0); - } - if !at_top() && !vert() { - fill(dc, RECT { left: 0, top: 1, right: cr.right, bottom: 2 }, mix(pal().bg, pal().text, 0.08), 0); - } - dc -} - -fn bar_fonts_key(scale: f32, ui: &str, icon: &str, icon_size: u8) -> u64 { - key_of((scale.to_bits(), ui, icon, icon_size)) -} - -/// The bar's four fonts, made again only when the scale, icon size or style's faces change. -unsafe fn bar_fonts() -> [HFONT; 4] { - let icon_size = i18n::style::icon_size(); - let key = bar_fonts_key(SCALE.get(), ui_face(), winrust_common::style::icon_face(), icon_size); - let (fonts, k) = FONTS.get(); - if k == key { - return fonts; - } - fonts.iter().filter(|f| !f.is_null()).for_each(|&f| { - DeleteObject(f); - }); - let (face, gface) = (wide(ui_face()), wide(winrust_common::style::icon_face())); - let font = |f: &[u16], px: i32, wt: i32| CreateFontW(-sc(px), 0, 0, 0, wt, 0, 0, 0, 1, 0, 0, 5, 0, f.as_ptr()); - let icon_px = (16.0 * icon_size as f32 / 100.0).round() as i32; - let fonts = [font(&face, 13, 400), font(&face, 12, 400), font(&gface, icon_px, 400), font(&face, 13, 600)]; - FONTS.set((fonts, key)); - fonts -} - -unsafe fn paint(hwnd: HWND) { - let mut ps: PAINTSTRUCT = zeroed(); - let wdc = BeginPaint(hwnd, &mut ps); - let mut cr: RECT = zeroed(); - GetClientRect(hwnd, &mut cr); - let h = cr.bottom; - BUSY.set(false); - let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, h)); - let old = SelectObject(dc, bmp); - // the background (gradient, facets, hairlines) is the same every frame: drawn once per size / style, then copied - BitBlt(dc, 0, 0, cr.right, h, bg_layer(wdc, cr), 0, 0, SRCCOPY); - SetBkMode(dc, TRANSPARENT as i32); - let [f_txt, f_small, f_glyph, f_bold] = bar_fonts(); - let of = SelectObject(dc, f_txt); - - 'horiz: { - - if vert() { - paint_vert(dc, cr, [f_txt, f_small, f_glyph, f_bold]); - break 'horiz; - } - let l = layout(cr.right); - let fg = GetForegroundWindow(); - let (top, bot) = (sc(4), h - sc(4)); - let mid = (top + bot) / 2; - let cell = |x: i32, w: i32| RECT { left: x, top, right: x + w, bottom: bot }; - let hot = HOT.get(); - let active_bg = mix(pal().active, pal().accent, 0.12); // the focused app's button: a hint of the accent, not plain grey - - // the gear: the Style menu - let gr = RECT { left: l.gear_x, top, right: l.gear_x + sc(GEAR_X.1), bottom: bot }; - glow(dc, GEAR, hot == GEAR, gr, pal().bg, pal().hover, sc(8)); - SelectObject(dc, f_glyph); - text(dc, "\u{E713}", gr, if hot == GEAR { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); - - // search button (left of Start) - let sb = RECT { left: l.x0, top, right: l.x0 + l.bw, bottom: bot }; - glow(dc, SEARCH, hot == SEARCH, sb, pal().bg, pal().hover, sc(8)); - SelectObject(dc, f_glyph); - text(dc, "\u{E721}", sb, if hot == SEARCH { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); - let tb = RECT { left: l.x0 + l.bw + l.gap, top, right: l.x0 + 2 * l.bw + l.gap, bottom: bot }; - glow(dc, TASKVIEW, hot == TASKVIEW, tb, pal().bg, pal().hover, sc(8)); - text(dc, "\u{E7C4}", tb, if hot == TASKVIEW { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); - - // Start, pinned apps, open windows (center) - BTNS.with_borrow(|btns| { - for (i, b) in btns.iter().enumerate() { - let x = l.btn_pos(i as i32); - let r = RECT { left: x, top, right: x + l.bw, bottom: bot }; - let act = b.wins.contains(&fg); - let att = !act && FLASH.with_borrow(|f| b.wins.iter().any(|w| f.contains(w))); // flashing: lit until it is activated - let (th, ta, tp) = (hv(i as i32, hot == i as i32), hv(2000 + i as i32, act), press_t(i as i32)); - if th > 0.01 || ta > 0.01 || tp > 0.0 { - fill(dc, r, mix(mix(mix(pal().bg, pal().hover, th), active_bg, ta), pal().accent, 0.5 * tp), sc(8)); - } - if att { - fill(dc, r, mix(pal().bg, pal().accent, 0.4), sc(8)); - } - if i == 0 { - // Windows logo in four tiles, lit from the top left; grows a little on hover, squeezes on click - let t = ((icon_sc(8) as f32) * (1.0 + 0.12 * th) * (1.0 - 0.2 * tp)) as i32; - let (g, cx) = (sc(1).max(1), (r.left + r.right) / 2); - let tint = [mix(pal().accent, pal().text, 0.35), mix(pal().accent, pal().text, 0.15), mix(pal().accent, pal().text, 0.15), pal().accent]; - for (k, (dx, dy)) in [(-1, -1), (0, -1), (-1, 0), (0, 0)].into_iter().enumerate() { - let (px, py) = (cx + if dx < 0 { -t - g } else { g }, mid + if dy < 0 { -t - g } else { g }); - fill(dc, RECT { left: px, top: py, right: px + t, bottom: py + t }, tint[k], sc(3)); - } - continue; - } - let ic = match b.pin { - Some(p) => PINS.with_borrow(|pins| pins.get(p).map_or(null_mut(), |p| p.icon)), - None => b.icon, - }; - let ic = if ic.is_null() { b.wins.first().map_or(ic, |&w| icon_of(w)) } else { ic }; // a pin whose icon failed to load (#91) - let key = b.pin.map(|p| -(p as isize) - 1).or_else(|| b.wins.first().map(|&w| w as isize)).unwrap_or(0); - // squeezes on click, grows in when new, lifts a pixel on hover - let isz = (icon_px().min(l.bw - sc(6)) as f32 * (1.0 - 0.18 * tp) * (0.55 + 0.45 * appear(key))) as i32; - if !ic.is_null() { - DrawIconEx(dc, x + (l.bw - isz) / 2, mid - isz / 2 - sc(2) - (sc(1) as f32 * th) as i32, ic, isz, isz, 0, null_mut(), DI_NORMAL); - } - if !b.wins.is_empty() { - let min = b.wins.iter().all(|&w| IsIconic(w) != 0); - let pw = sc(6) + (sc(12) as f32 * ta) as i32; // the running-app pill stretches when its window is active - let py = bot - sc(4); - let col = if act || att { pal().accent } else if min { mix(pal().dim, pal().bg, 0.45) } else { pal().dim }; - fill(dc, RECT { left: x + (l.bw - pw) / 2, top: py, right: x + (l.bw + pw) / 2, bottom: py + sc(3) }, col, sc(3)); - if b.wins.len() > 1 { - // a second, shorter pill: more than one window behind this button - fill(dc, RECT { left: x + (l.bw + pw) / 2 + sc(2), top: py, right: x + (l.bw + pw) / 2 + sc(5), bottom: py + sc(3) }, col, sc(3)); - } - } - } - }); - - // a hairline between the app buttons and the tray side - fill(dc, RECT { left: l.apps.0 - sc(5), top: mid - sc(9), right: l.apps.0 - sc(5) + 1, bottom: mid + sc(9) }, pal().line, 0); - - // tray apps - glow(dc, TAPP, hot == TAPP, cell(l.apps.0, sc(24)), pal().bg, pal().hover, sc(8)); - SelectObject(dc, f_glyph); - let open_tf = IsWindowVisible(TRAYFLY.get()) != 0; - let turn = ease(hv(TF_KEY, open_tf)); // the chevron turns over as the flyout opens, and back - let cc = cell(l.apps.0, sc(24)); - chevron(dc, (cc.left + cc.right) / 2, mid, icon_sc(5), if at_top() { 180.0 } else { 0.0 } + 180.0 * turn, mix(pal().text, pal().accent, turn)); - SelectObject(dc, f_txt); - let bar = bar_idx(); - TAPPS.with_borrow(|t| { - for (k, &ix) in bar.iter().enumerate() { - let (i, ti) = (k + 1, &t[ix]); - let x = l.apps.0 + i as i32 * sc(24); - glow(dc, TAPP + i as i32, hot == TAPP + i as i32, cell(x, sc(24)), pal().bg, pal().hover, sc(8)); - if !ti.icon.is_null() { - let size = icon_sc(16); - DrawIconEx(dc, x + (sc(24) - size) / 2, mid - size / 2, ti.icon, size, size, 0, null_mut(), DI_NORMAL); - } - } - }); - - widgets::paint(dc, l.wid.0, top, bot); - // system group: language on its own, then one pill for wifi + volume + battery (like Windows 11: they open one panel) - paint_power(dc, &l, hot, f_glyph, |s, len| RECT { left: s, top, right: s + len, bottom: bot }); - let tb = RECT { left: l.sys.0, top, right: l.sys.1, bottom: bot }; - glow(dc, LANG, hot == LANG, cell(tb.left, sc(SYS_LANG)), pal().bg, pal().hover, sc(8)); - let grp = RECT { left: tb.left + sc(SYS_LANG + 2), top, right: tb.right, bottom: bot }; - let (tg, pg) = (hv(SYS_GRP, matches!(hot, WIFI_I | VOL_I | BAT_I) || fly::is_open(fly::Kind::Quick)), press_t(WIFI_I).max(press_t(VOL_I)).max(press_t(BAT_I))); - if tg > 0.01 || pg > 0.0 { - fill(dc, grp, mix(mix(pal().bg, pal().hover, tg), pal().accent, 0.5 * pg), sc(8)); - } - let x = tb.left + sc(SYS_LANG); - text(dc, &lang_name(), cell(tb.left, sc(SYS_LANG)), pal().text, DT_CENTER); - net_icon(dc, x + sc(SYS_WIFI) / 2, mid, icon_sc(17), f_glyph); - SelectObject(dc, f_glyph); - let (vol, muted) = VOL.get(); - let vg = if muted || vol == 0 { "\u{E74F}" } else if vol < 34 { "\u{E993}" } else if vol < 67 { "\u{E994}" } else { "\u{E995}" }; - let xv = x + sc(SYS_WIFI); - text(dc, vg, cell(xv, sc(SYS_VOL)), if muted { BAD } else { pal().text }, DT_CENTER); - let (pct, ac) = BAT.get(); - if pct >= 0 { - let x = xv + sc(SYS_VOL); - let col = if ac { GOOD } else if pct <= 15 { BAD } else { pal().text }; - let (bw, bh) = (icon_sc(SYS_BAT_W), icon_sc(11)); - let by = mid - bh / 2; - fill(dc, RECT { left: x, top: by, right: x + bw, bottom: by + bh }, col, sc(4)); // outline - fill(dc, RECT { left: x + sc(1), top: by + sc(1), right: x + bw - sc(1), bottom: by + bh - sc(1) }, mix(pal().bg, pal().hover, tg), sc(3)); - let fw = ((bw - sc(4)) * pct / 100).max(sc(1)); - fill(dc, RECT { left: x + sc(2), top: by + sc(2), right: x + sc(2) + fw, bottom: by + bh - sc(2) }, col, sc(2)); - fill(dc, RECT { left: x + bw + sc(1), top: by + sc(3), right: x + bw + sc(3), bottom: by + bh - sc(3) }, col, sc(1)); // terminal nub - SelectObject(dc, f_txt); - text(dc, &format!("{pct}%"), cell(x + bw + sc(8), sc(SYS_BAT_PCT)), pal().text, DT_LEFT); - } - - // time (semibold) over the date (dimmed); the cell is as wide as the wider line, so both get the same air - let cb = cell(l.clock.0, l.clock.1 - l.clock.0); - glow(dc, CLOCK, hot == CLOCK || fly::is_open(fly::Kind::Cal), cb, pal().bg, pal().hover, sc(8)); - let (tm, dt) = clock_texts(); - SelectObject(dc, f_bold); - text(dc, &tm, RECT { left: cb.left, top: cb.top, right: cb.right, bottom: mid + sc(1) }, pal().text, DT_CENTER); - SelectObject(dc, f_small); - text(dc, &dt, RECT { left: cb.left, top: mid - sc(1), right: cb.right, bottom: cb.bottom }, mix(pal().dim, pal().text, 0.35), DT_CENTER); - } - - BitBlt(wdc, 0, 0, cr.right, h, dc, 0, 0, SRCCOPY); - SelectObject(dc, of); - SelectObject(dc, old); - DeleteObject(bmp); - DeleteDC(dc); - if BUSY.get() { - SetTimer(hwnd, 4, 16, None); // next animation frame - } else { - KillTimer(hwnd, 4); - } - EndPaint(hwnd, &ps); -} - -// ---------- input ---------- - -/// Presses the keys in order, releases them in reverse (e.g. Win+A). -unsafe fn keys(vks: &[u16]) { - let send = |vk: u16, up: bool| { - let mut i: INPUT = zeroed(); - i.r#type = INPUT_KEYBOARD; - i.Anonymous.ki.wVk = vk; - i.Anonymous.ki.dwFlags = if up { KEYEVENTF_KEYUP } else { 0 }; - SendInput(1, &i, size_of::() as i32); - }; - vks.iter().for_each(|&v| send(v, false)); - vks.iter().rev().for_each(|&v| send(v, true)); -} - -/// Releases `vk` alone: a swallowed key-up handed back to the shell as a synthetic one (see `run::kb_hook`). -unsafe fn key_up(vk: u16) { - let mut i: INPUT = zeroed(); - i.r#type = INPUT_KEYBOARD; - i.Anonymous.ki.wVk = vk; - i.Anonymous.ki.dwFlags = KEYEVENTF_KEYUP; - SendInput(1, &i, size_of::() as i32); -} - -/// WM_CLOSE. A window of an elevated app ignores it from our normal-rights process (UIPI), so then -/// ask for admin once (UAC) and let an elevated taskkill send the close request. -unsafe fn close_window(w: HWND) { - if PostMessageW(w, WM_CLOSE, 0, 0) == 0 { - let mut pid = 0u32; - GetWindowThreadProcessId(w, &mut pid); - ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/PID {pid}")).as_ptr(), null(), SW_HIDE); - } -} - -/// App id of the Store app a .lnk of a pin points into (its package folder), None for anything else. -unsafe fn msix_app_id(lnk: &str) -> Option { - let (family, _) = msix_family(&lnk_target(&wide(lnk)))?; - let prefix = format!("{family}!").to_lowercase(); - fly::apps_folder().into_iter().map(|a| a.1).find(|id| id.to_lowercase().starts_with(&prefix)) -} - -/// Starts a Store app by its app id. false = it did not start (the caller falls back to explorer). -unsafe fn activate_app(aumid: &str) -> bool { - use windows::Win32::UI::Shell::{ACTIVATEOPTIONS, ApplicationActivationManager, IApplicationActivationManager}; - CoCreateInstance::<_, IApplicationActivationManager>(&ApplicationActivationManager, None, CLSCTX_ALL) - .and_then(|m| m.ActivateApplication(PCWSTR(wide(aumid).as_ptr()), PCWSTR::null(), ACTIVATEOPTIONS(0))) - .is_ok() -} - -/// Opens a file, shortcut, URI or program with the desktop user's normal token: the bar itself may run elevated (see the -/// launcher), and everything started from it must not inherit that. -unsafe fn open(path: &[u16]) { - let n = path.iter().position(|&c| c == 0).unwrap_or(path.len()); - let p = String::from_utf16_lossy(&path[..n]); - // the bar never takes the foreground (WS_EX_NOACTIVATE), so what it starts (via explorer / runas) may not come to the - // front either; it did get the click, which lets it hand that right on (#207) - AllowSetForegroundWindow(u32::MAX); // ASFW_ANY - if p.to_lowercase().ends_with(".lnk") { - bump(&p); - } - if p.to_lowercase().starts_with("ms-settings:") { - return winrust_common::settings::open(&p); // needs Explorer as shell: it is started for the time Settings is open - } - // Store (MSIX) apps: by app id through the activation manager. A path into the protected package folder ("no app - // associated") and shell:AppsFolder via explorer ("class not registered" when Explorer is not the shell) both fail. - let aumid = if p.to_lowercase().starts_with(r"shell:appsfolder\") { Some(p[r"shell:appsfolder\".len()..].to_string()) } else { msix_app_id(&p) }; - if aumid.is_some_and(|id| activate_app(&id)) { - return; - } - // A program is a path to Explorer, and Explorer is not the shell on a WinRust machine: `explorer.exe wt.exe` only - // opens a folder window, so the Win+X "Terminal" item showed the file manager and a task manager never started. - if winrust_common::launch::is_program(&p) { - winrust_common::launch::program(&p); - return; - } - // Everything else through explorer.exe: it hands paths, shortcuts, shell addresses and URIs to the shell with the - // desktop user's normal token. ShellExecuteW from here would inherit this bar's admin rights, and an elevated app - // cannot receive files dragged in from normal windows (UIPI), and PrtSc / Win+Shift+S (ms-screenclip:) do not work - // when started elevated. With an argument and no explorer shell running, explorer.exe hands the target to its COM - // host and does not become a shell or raise a taskbar. - if Command::new("explorer.exe").arg(&p).spawn().is_err() { - ShellExecuteW(null_mut(), wide("open").as_ptr(), wide(&p).as_ptr(), null(), null(), SW_SHOWNORMAL); - } -} - -/// Starts the disk cleaner (rs-du, installed next to the task manager) elevated: it reads the raw volume. -/// Right-click menu of an app button, like the Windows taskbar's jump list: pin / unpin, close, end process. -fn wstr_of(w: &[u16]) -> String { - String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())]) -} - -/// "1 окно", "3 окна", "5 окон"; "1 window", "2 windows"; "3 个窗口" (no plural in Chinese). -fn windows_ru(n: usize) -> String { - use i18n::Lang; - let w = match lang!() { - Lang::En => if n == 1 { "window" } else { "windows" }, - Lang::Pt => if n == 1 { "janela" } else { "janelas" }, - Lang::Ja => "ウィンドウ", - Lang::Zh => "个窗口", - Lang::Ru => match (n % 10, n % 100) { - (1, x) if x != 11 => "окно", - (2..=4, x) if !(12..=14).contains(&x) => "окна", - _ => "окон", - }, - }; - format!("{n} {w}") -} - -/// Right-click menu of an app button, like the Windows 11 jump list: the app on top, its windows (when there are several), -/// open / pin / Start, then close and end process in red. -unsafe fn app_menu(hwnd: HWND, h: i32) { - #[derive(Clone, Copy)] - enum A { - Win(HWND), - Open, - Pin, - Left, - Right, - Start, - Close, - Kill, - } - let (wins, pin, bicon) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin, b.icon)).unwrap_or((vec![], None, null_mut()))); - let exe = wins.first().map(|&w| exe_of(w)).unwrap_or_default(); - let (lnk, picon) = pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| (wstr_of(&x.lnk), x.icon)))).unwrap_or_default(); - let launch = if lnk.is_empty() { exe.clone() } else { lnk.clone() }; - let stem = std::path::Path::new(&launch).file_stem().unwrap_or_default().to_string_lossy().to_string(); - let name: String = stem.chars().take(1).flat_map(char::to_uppercase).chain(stem.chars().skip(1)).collect(); - let sub = match (wins.len(), pin.is_some()) { - (0, _) => t!("Закреплено · не запущено", "Pinned · not running", ja: "固定済み · 未起動", pt: "Fixado · não está em execução", zh: "已固定 · 未运行").to_string(), - (n, true) => tf!("Закреплено · {}", "Pinned · {}", ja: "固定済み · {}", pt: "Fixado · {}", zh: "已固定 · {}", windows_ru(n)), - (n, false) => tf!("Запущено · {}", "Running · {}", ja: "実行中 · {}", pt: "Em execução · {}", zh: "运行中 · {}", windows_ru(n)), - }; - let icon = if picon.is_null() { bicon } else { picon }; - let mut items: Vec<(fly::MItem, A)> = Vec::new(); - if wins.len() > 1 { - for &w in wins.iter().take(6) { - let mut b = [0u16; 256]; - let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize; - items.push((fly::MItem { icon: icon_of(w), ..fly::MItem::new(String::from_utf16_lossy(&b[..n])) }, A::Win(w))); - } - } - if !launch.is_empty() { - let it = fly::MItem::new(if wins.is_empty() { t!("Открыть", "Open", ja: "開く", pt: "Abrir", zh: "打开") } else { t!("Новое окно", "New window", ja: "新しいウィンドウ", pt: "Nova janela", zh: "新建窗口") }); - items.push((if items.is_empty() { it } else { it.sep() }, A::Open)); - } - if pin.is_some() { - items.push((fly::MItem::new(t!("Открепить от панели", "Unpin from the bar", ja: "バーから固定を外す", pt: "Desafixar da barra", zh: "从任务栏取消固定")), A::Pin)); - } else if !exe.is_empty() { - items.push((fly::MItem::new(t!("Закрепить на панели", "Pin to the bar", ja: "バーに固定する", pt: "Fixar na barra", zh: "固定到任务栏")), A::Pin)); - } - if let Some(p) = pin.filter(|_| !lnk.is_empty()) { - let n = PINS.with_borrow(|p| p.len()); - if p > 0 { - items.push((fly::MItem::new(if vert() { t!("Выше", "Move up", ja: "上へ移動", pt: "Mover para cima", zh: "上移") } else { t!("Сдвинуть влево", "Move left", ja: "左へ移動", pt: "Mover para a esquerda", zh: "左移") }), A::Left)); - } - if p + 1 < n { - items.push((fly::MItem::new(if vert() { t!("Ниже", "Move down", ja: "下へ移動", pt: "Mover para baixo", zh: "下移") } else { t!("Сдвинуть вправо", "Move right", ja: "右へ移動", pt: "Mover para a direita", zh: "右移") }), A::Right)); - } - } - if !launch.is_empty() { - let s = fly::start_pinned(&launch); - items.push((fly::MItem::new(if s { t!("Убрать из Пуска", "Remove from Start", ja: "スタートから削除", pt: "Remover do Iniciar", zh: "从开始菜单移除") } else { t!("Добавить в Пуск", "Add to Start", ja: "スタートに追加", pt: "Adicionar ao Iniciar", zh: "添加到开始菜单") }), A::Start)); - } - if !wins.is_empty() { - items.push((fly::MItem::new(if wins.len() > 1 { t!("Закрыть все окна", "Close all windows", ja: "すべてのウィンドウを閉じる", pt: "Fechar todas as janelas", zh: "关闭所有窗口") } else { t!("Закрыть окно", "Close window", ja: "ウィンドウを閉じる", pt: "Fechar janela", zh: "关闭窗口") }).hint("Alt+F4").sep(), A::Close)); - items.push((fly::MItem::new(t!("Завершить процесс", "End process", ja: "プロセスを終了", pt: "Finalizar processo", zh: "结束进程")).danger(), A::Kill)); - } - let acts: Vec = items.iter().map(|x| x.1).collect(); - let items = items.into_iter().map(|x| x.0).collect(); - let first_pid = wins.first().map_or(0, |&w| { let mut pid = 0; GetWindowThreadProcessId(w, &mut pid); pid }); - fly::menu(tip_cx(&bar_layout(hwnd), h), Some((icon, "", name, sub)), items, move |i| { - match acts.get(i).copied() { - Some(A::Win(w)) => { - bring(w); - } - Some(A::Open) => open(&wide(&launch)), - Some(A::Pin) => { - // by path, not by the index seen when the menu opened: PINS may have changed meanwhile - match PINS.with_borrow(|p| p.iter().position(|x| !lnk.is_empty() && wstr_of(&x.lnk) == lnk)) { - Some(p) => unpin(p), - None if lnk.is_empty() => pin_exe(&exe, &proc_args(first_pid)), - None => {} - } - refresh_buttons(); // the buttons hold indices into PINS: a stale one would index past the end on the next paint - } - Some(a @ (A::Left | A::Right)) => { - // by path again; the new order is saved and load_pins takes it - if let Some(p) = PINS.with_borrow(|p| p.iter().position(|x| wstr_of(&x.lnk) == lnk)) { - let to = if matches!(a, A::Left) { p.wrapping_sub(1) } else { p + 1 }; - if PINS.with_borrow_mut(|v| (to < v.len()).then(|| v.swap(p, to))).is_some() { - let pins: Vec = PINS.with_borrow(|v| v.iter().map(|p| DragButton::Pin(p.lnk.clone())).collect()); - BUTTON_ORDER.with_borrow_mut(|order| { - let mut pins = pins.into_iter(); - for entry in order.iter_mut() { if matches!(entry, DragButton::Pin(_)) { if let Some(pin) = pins.next() { *entry = pin; } } } - }); - save_pin_order(); - refresh_buttons(); - } - } - } - Some(A::Start) => fly::start_toggle(&launch), - Some(A::Close) => wins.iter().for_each(|&w| close_window(w)), - Some(A::Kill) => { - let mut pids: Vec = wins - .iter() - .map(|&w| { - let mut pid = 0u32; - GetWindowThreadProcessId(w, &mut pid); - pid - }) - .collect(); - pids.sort_unstable(); - pids.dedup(); // several windows of one app: one kill (and at most one UAC prompt), not one per window - for pid in pids { - let p = OpenProcess(1, 0, pid); // PROCESS_TERMINATE; works on elevated apps when the bar itself runs elevated - if p.is_null() || TerminateProcess(p, 1) == 0 { - ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/F /T /PID {pid}")).as_ptr(), null(), SW_HIDE); - } - if !p.is_null() { - CloseHandle(p); - } - } - } - None => {} - } - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); - }); -} - -fn pin_dir() -> PathBuf { - appdata_file(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar") -} - -unsafe fn unpin(i: usize) { - let Some(p) = PINS.with_borrow_mut(|p| (i < p.len()).then(|| p.remove(i))) else { return }; - let n = p.lnk.iter().position(|&c| c == 0).unwrap_or(p.lnk.len()); - // remembered, or the next start would bring it back from the Windows taskbar's list - let key = pin_key(&p.lnk); - if !key.0.is_empty() { - let mut t = std::fs::read_to_string(unpinned_file()).unwrap_or_default(); - t.push_str(&key_line(&key)); - t.push('\n'); - let _ = std::fs::create_dir_all(appdata_file("topbar-taskband")); - let _ = std::fs::write(unpinned_file(), t); - } - let _ = std::fs::remove_file(String::from_utf16_lossy(&p.lnk[..n])); - DestroyIcon(p.icon); -} - -/// Arguments of a shortcut ("" if none). -unsafe fn lnk_args(lnk: &[u16]) -> String { - (|| -> Option { - let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; - sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; - let mut b = [0u16; 2048]; - sl.GetArguments(&mut b).ok()?; - Some(wstr_of(&b)) - })() - .unwrap_or_default() -} - -/// What a running process was started with, minus the exe (e.g. `--profile-directory="Profile 2"`). -fn proc_args(pid: u32) -> String { - if pid == 0 { - return String::new(); - } - // the PEB first (microseconds); WMI only for a process that cannot be opened for reading - let cl = winrust_common::proc::cmdline(pid).or_else(|| wmi::string(r"root\cimv2", &format!("SELECT CommandLine FROM Win32_Process WHERE ProcessId={pid}"), "CommandLine")); - let cl = cl.map(|c| c.trim().to_string()).unwrap_or_default(); - let rest = match cl.strip_prefix('"') { - Some(r) => r.split_once('"').map_or("", |x| x.1), - None => cl.split_once(' ').map_or("", |x| x.1), - }; - rest.trim().to_string() -} - -/// Pins an app: a shortcut to its exe (with `args`) in the folder where Windows keeps taskbar pins. -/// A dropped .lnk is copied as it is, so its arguments (browser profile) and icon stay. Already pinned (same target and -/// arguments) = nothing. -unsafe fn pin_exe(path: &str, args: &str) { - let is_lnk = path.to_lowercase().ends_with(".lnk"); - // targets are compared with exe_of(), which is lower-case - let exe = if is_lnk { lnk_target(&wide(path)) } else { path.to_lowercase() }; - let args = if is_lnk { lnk_args(&wide(path)) } else { args.to_string() }; - let exe = exe.as_str(); - if exe.is_empty() || PINS.with_borrow(|p| p.iter().any(|p| p.target == exe && p.args == args)) { - return; - } - let stem = std::path::Path::new(if is_lnk { path } else { exe }).file_stem().unwrap_or_default().to_string_lossy().to_string(); - let name: String = stem.chars().enumerate().map(|(i, c)| if i == 0 { c.to_ascii_uppercase() } else { c }).collect(); - let _ = std::fs::create_dir_all(pin_dir()); - // a free name: two pins of one exe with different arguments (two browser profiles) must not overwrite each other - let Some(file) = (1..).map(|n| pin_dir().join(if n == 1 { format!("{name}.lnk") } else { format!("{name} ({n}).lnk") })).find(|p| !p.exists()) else { return }; - let lnk = wide(&file.to_string_lossy()); - let ok = if is_lnk && std::fs::copy(path, &file).is_ok() { - Some(()) - } else { - (|| -> Option<()> { - let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; - sl.SetPath(PCWSTR(wide(exe).as_ptr())).ok()?; - if !args.is_empty() { - sl.SetArguments(PCWSTR(wide(&args).as_ptr())).ok()?; - } - sl.cast::().ok()?.Save(PCWSTR(lnk.as_ptr()), true).ok() - })() - }; - if ok.is_some() { - // pinned again: no longer on the unpinned list - let line = key_line(&(exe.to_string(), args.to_lowercase())); - if let Ok(t) = std::fs::read_to_string(unpinned_file()) { - let _ = std::fs::write(unpinned_file(), t.lines().filter(|l| *l != line).map(|l| format!("{l}\n")).collect::()); - } - let icon = lnk_icon(&lnk, exe); - PINS.with_borrow_mut(|p| p.push(Pin { lnk, target: exe.to_string(), args, aumid: String::new(), icon })); - } -} - -/// Files dropped on the bar: on the Start button they are added to Start (the panel opens and the new row pulses), -/// anywhere else they are pinned to the bar. -unsafe fn on_drop(hwnd: HWND, hd: HDROP) { - let mut pt: POINT = zeroed(); - DragQueryPoint(hd, &mut pt); - let n = DragQueryFileW(hd, u32::MAX, null_mut(), 0); - let files: Vec = (0..n) - .map(|i| { - let len = DragQueryFileW(hd, i, null_mut(), 0) as usize; - let mut b = vec![0u16; len + 1]; - DragQueryFileW(hd, i, b.as_mut_ptr(), b.len() as u32); - String::from_utf16_lossy(&b[..len]) - }) - .collect(); - DragFinish(hd); - let h = hit(hwnd, pt.x, pt.y); - press(if h == NONE { 0 } else { h }); - if h == 0 { - let added: Vec<&String> = files.iter().filter(|f| fly::start_pin(f)).collect(); - let name = |p: &str| std::path::Path::new(p).file_stem().unwrap_or_default().to_string_lossy().to_string(); - if !fly::is_open(fly::Kind::Start) { - fly::toggle(fly::Kind::Start); - } - fly::note(&match added.len() { - 0 => "Already in Start".to_string(), - 1 => format!("Added to Start: {}", name(added[0])), - n => format!("Added {n} items to Start"), - }); - } else { - files.iter().for_each(|f| pin_exe(f, "")); - refresh_buttons(); - } - InvalidateRect(hwnd, null(), 0); -} - -/// The junk remover (purge, installed on request): lists what it would delete and asks for YES in its own elevated console. -pub(crate) fn purge_installed() -> bool { - std::env::var_os("ProgramFiles").is_some_and(|pf| PathBuf::from(pf).join(r"purge\purge.exe").is_file()) -} - -unsafe fn open_purge() { - if let Some(pf) = std::env::var_os("ProgramFiles") { - let exe = PathBuf::from(pf).join(r"purge\purge.exe"); - ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("--ask").as_ptr(), null(), SW_SHOWNORMAL); - } -} - -unsafe fn open_cleaner() { - let Some(pf) = std::env::var_os("ProgramFiles") else { return }; - let exe = PathBuf::from(pf).join(r"rtaskmgr\rs-du.exe"); - if exe.is_file() { - ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("C: --clean --ask").as_ptr(), null(), SW_SHOWNORMAL); - } -} - -unsafe extern "system" fn find_launcher(h: HWND, lp: LPARAM) -> i32 { - let mut cls = [0u16; 32]; - let n = GetClassNameW(h, cls.as_mut_ptr(), 32).max(0) as usize; - if String::from_utf16_lossy(&cls[..n]) == "rs_launcher" { - *(lp as *mut HWND) = h; - return 0; - } - 1 -} - -/// Asks the running rs-launcher to show itself by sending the message its Alt+Space hotkey produces. -/// Faking the key presses did not reliably reach it from this (elevated) process. false = it is not running. -unsafe fn open_launcher() -> bool { - let mut h: HWND = null_mut(); - EnumWindows(Some(find_launcher), &mut h as *mut _ as LPARAM); - if h.is_null() { - return false; - } - AllowSetForegroundWindow(u32::MAX); // else no focus, so no click-outside close (#292) - PostMessageW(h, WM_HOTKEY, 1, (MOD_ALT | MOD_NOREPEAT) as isize | ((VK_SPACE as isize) << 16)); - true -} - -/// Right click on Start: the Win+X menu (Explorer's own is gone with the bar). -unsafe fn start_menu() { - let bar = BAR.load(Relaxed) as HWND; - // (label in ru/en/ja/pt/zh, target); "!" targets are actions of ours, the rest goes through `open` - let tools: [(&str, &str, &str, &str, &str, &str); 15] = [ - ("Приложения и возможности", "Apps and Features", "アプリと機能", "Aplicativos e Recursos", "应用和功能", "ms-settings:appsfeatures"), - ("Электропитание", "Power Options", "電源オプション", "Opções de Energia", "电源选项", "powercfg.cpl"), - ("Просмотр событий", "Event Viewer", "イベント ビューアー", "Visualizador de Eventos", "事件查看器", "eventvwr.msc"), - ("Система", "System", "システム", "Sistema", "系统", "ms-settings:about"), - ("Диспетчер устройств", "Device Manager", "デバイス マネージャー", "Gerenciador de Dispositivos", "设备管理器", "devmgmt.msc"), - ("Сетевые подключения", "Network Connections", "ネットワーク接続", "Conexões de Rede", "网络连接", "ms-settings:network"), - ("Управление дисками", "Disk Management", "ディスクの管理", "Gerenciamento de Disco", "磁盘管理", "diskmgmt.msc"), - ("Управление компьютером", "Computer Management", "コンピューターの管理", "Gerenciamento do Computador", "计算机管理", "compmgmt.msc"), - ("Терминал", "Terminal", "ターミナル", "Terminal", "终端", "!term"), - ("Диспетчер задач", "Task Manager", "タスク マネージャー", "Gerenciador de Tarefas", "任务管理器", "taskmgr.exe"), - ("Параметры", "Settings", "設定", "Configurações", "设置", "ms-settings:"), - ("Проводник", "File Explorer", "エクスプローラー", "Explorador de Arquivos", "文件资源管理器", "shell:MyComputerFolder"), - ("Выполнить", "Run", "ファイル名を指定して実行", "Executar", "运行", "!run"), - ("Рабочий стол", "Desktop", "デスクトップ", "Área de Trabalho", "桌面", "!desktop"), - ("Представление задач", "Task View", "タスク ビュー", "Visão de Tarefas", "任务视图", "!taskview"), - ]; - let power = [("Блокировка", "Lock", "ロック", "Bloquear", "锁定", "!lock"), ("Сон", "Sleep", "スリープ", "Suspender", "睡眠", "!sleep"), ("Перезагрузка", "Restart", "再起動", "Reiniciar", "重启", "!restart"), ("Завершение работы", "Shut down", "シャットダウン", "Desligar", "关机", "!shutdown")]; - let mut items = Vec::new(); - let mut targets = Vec::new(); - for (i, (ru, en, ja, pt, zh, to)) in tools.iter().chain(power.iter()).enumerate() { - let it = fly::MItem::new(t!(*ru, *en, ja: *ja, pt: *pt, zh: *zh)); - items.push(if i == tools.len() { it.sep() } else { it }); - targets.push(*to); - } - let head = (null_mut(), "\u{E700}", t!("Пуск", "Start", ja: "開始", pt: "Iniciar", zh: "启动").to_string(), String::new()); - fly::menu(tip_cx(&bar_layout(bar), 0), Some(head), items, move |i| { - let Some(&to) = targets.get(i) else { return }; - let quiet = |c: &mut Command| { let _ = c.creation_flags(NO_WINDOW).spawn(); }; - match to { - "!term" => { - let wt = std::env::var_os("LOCALAPPDATA").map(|b| PathBuf::from(b).join(r"Microsoft\WindowsApps\wt.exe")).filter(|p| p.is_file()); - open(&wide(if wt.is_some() { "wt.exe" } else { "powershell.exe" })); - } - "!run" => run_box(), - "!desktop" => winrust_common::desktop::toggle(), - "!taskview" => keys(&[VK_LWIN, VK_TAB]), // virtual desktops (#83) - "!lock" => quiet(Command::new("rundll32.exe").args(["user32.dll,LockWorkStation"])), - "!sleep" => fly::sleep_now(), - "!restart" => quiet(Command::new("shutdown").args(["/r", "/t", "0"])), - "!shutdown" => quiet(Command::new("shutdown").args(["/s", "/t", "0"])), - _ => open(&wide(to)), - } - }); -} - -/// Puts the open, not minimized windows side by side in the work area. -/// A window dropped with the pointer on the screen edge snaps (Windows 11 style): left / right edge = that half of the monitor's -/// work area, top edge = maximized. Only resizable windows; without Explorer nothing else does this. -unsafe extern "system" fn snap_proc(_: windows_sys::Win32::UI::Accessibility::HWINEVENTHOOK, ev: u32, w: HWND, id: i32, _: i32, _: u32, _: u32) { - if id != 0 || w.is_null() { - return; - } - if ev == 0x000A { - // the drag starts: its size, so that the end can tell a move (magnet) from a resize (left alone) - let r = frame(w); - DRAG_SIZE.set((r.right - r.left, r.bottom - r.top)); - return; - } - if IsWindowVisible(w) == 0 || IsZoomed(w) != 0 { - return; - } - if stick() && !edge_snap(w) { - let r = frame(w); - if DRAG_SIZE.get() == (r.right - r.left, r.bottom - r.top) { - magnet_window(w, r); - } - return; - } - if GetWindowLongW(w, GWL_STYLE) as u32 & WS_THICKFRAME == 0 { - return; - } - let mut pt: POINT = zeroed(); - GetCursorPos(&mut pt); - let mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST); - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(mon, &mut mi) == 0 { - return; - } - let (m, a) = (mi.rcMonitor, mi.rcWork); - let half = (a.right - a.left) / 2; - if pt.y <= m.top + 1 { - ShowWindow(w, SW_MAXIMIZE); - } else if pt.x <= m.left + 1 { - SetWindowPos(w, null_mut(), a.left, a.top, half, a.bottom - a.top, SWP_NOZORDER | SWP_NOACTIVATE); - } else if pt.x >= m.right - 2 { - SetWindowPos(w, null_mut(), a.left + half, a.top, half, a.bottom - a.top, SWP_NOZORDER | SWP_NOACTIVATE); - } -} - -// ---------- window magnet (#133): a dragged window that ends near a screen edge or another window's edge sticks to it ---------- - -thread_local! { - static DRAG_SIZE: Cell<(i32, i32)> = const { Cell::new((0, 0)) }; -} -static STICK: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0xFF); // 0 off, 1 on, 0xFF not read yet - -fn stick_file() -> PathBuf { - appdata_file("topbar-stick.txt") -} - -pub(crate) fn stick() -> bool { - if STICK.load(Relaxed) == 0xFF { - STICK.store(std::fs::read_to_string(stick_file()).is_ok_and(|s| s.trim() == "1") as u8, Relaxed); - } - STICK.load(Relaxed) == 1 -} - -pub(crate) fn set_stick(on: bool) { - STICK.store(on as u8, Relaxed); - let _ = std::fs::write(stick_file(), if on { "1" } else { "0" }); -} - -/// Would the edge snap above take this drop (the pointer on a screen edge)? -unsafe fn edge_snap(w: HWND) -> bool { - let mut pt: POINT = zeroed(); - GetCursorPos(&mut pt); - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - GetMonitorInfoW(MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 - && GetWindowLongW(w, GWL_STYLE) as u32 & WS_THICKFRAME != 0 - && (pt.y <= mi.rcMonitor.top + 1 || pt.x <= mi.rcMonitor.left + 1 || pt.x >= mi.rcMonitor.right - 2) -} - -/// The window's visible frame (without the invisible resize borders Windows 10/11 add around it). -unsafe fn frame(w: HWND) -> RECT { - let mut r: RECT = zeroed(); - if DwmGetWindowAttribute(w, 9, &mut r as *mut _ as *mut _, size_of::() as u32) != 0 { - GetWindowRect(w, &mut r); // DWMWA_EXTENDED_FRAME_BOUNDS failed - } - r -} - -/// How far to move `r` so that its nearest edge within `d` px lands on one of the edges (0 when none is that close). -/// `xs`/`ys`: the vertical / horizontal lines it may stick to. -fn magnet(r: RECT, xs: &[i32], ys: &[i32], d: i32) -> (i32, i32) { - let best = |a: i32, b: i32, es: &[i32]| es.iter().flat_map(|&e| [e - a, e - b]).filter(|v| v.abs() <= d).min_by_key(|v| v.abs()).unwrap_or(0); - (best(r.left, r.right, xs), best(r.top, r.bottom, ys)) -} - -unsafe fn magnet_window(w: HWND, r: RECT) { - let mut mi: MONITORINFO = zeroed(); - mi.cbSize = size_of::() as u32; - if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { - return; - } - let a = mi.rcWork; - let (mut xs, mut ys) = (vec![a.left, a.right], vec![a.top, a.bottom]); - // the other windows' edges: only those beside this one (overlapping along the other axis), so a far window does not pull - let mut v: Vec = Vec::new(); - EnumWindows(Some(collect), &mut v as *mut _ as LPARAM); - for o in v.into_iter().filter(|&o| o != w && IsIconic(o) == 0 && IsZoomed(o) == 0) { - let f = frame(o); - if f.top < r.bottom && f.bottom > r.top { - xs.extend([f.left, f.right]); - } - if f.left < r.right && f.right > r.left { - ys.extend([f.top, f.bottom]); - } - } - let (dx, dy) = magnet(r, &xs, &ys, sc(14)); - if (dx, dy) != (0, 0) { - let mut wr: RECT = zeroed(); - GetWindowRect(w, &mut wr); - SetWindowPos(w, null_mut(), wr.left + dx, wr.top + dy, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } -} - -/// Win+1..9: opens the n-th app button's pin, or brings its window up (a second press on the only window minimizes it, -/// with several windows each press moves on to the next one). -unsafe fn win_num(n: usize) { - let Some((wins, pin)) = BTNS.with_borrow(|b| b.get(n + 1).map(|b| (b.wins.clone(), b.pin))) else { return }; - if wins.is_empty() { - if let Some(l) = pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))) { - open(&l); - } - return; - } - let i = wins.iter().position(|&w| w == GetForegroundWindow()); - let w = i.map_or(wins[0], |i| wins[(i + 1) % wins.len()]); - if wins.len() == 1 && i.is_some() { - note_minimize(w); - ShowWindow(w, SW_MINIMIZE); - } else { - bring(w); - } -} - -unsafe fn tile_windows() { - let wins: Vec = BTNS.with_borrow(|b| b.iter().flat_map(|b| b.wins.iter().copied()).filter(|&w| IsIconic(w) == 0).collect()); - if wins.is_empty() { - return; - } - let mut wa: RECT = zeroed(); - SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut wa as *mut _ as *mut _, 0); - for &w in &wins { - ShowWindow(w, SW_RESTORE); // a maximized window ignores tiling - } - TileWindows(null_mut(), MDITILE_VERTICAL, &wa, wins.len() as u32, wins.as_ptr()); -} - -unsafe fn click(h: i32, left: bool, mid: bool) { - match h { - SEARCH if left => { - // our search (rs-launcher listens for Alt+Space); without it the Start panel's own search - let exe = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join(r"rs-search\rs-launcher.exe")).filter(|p| p.is_file()); - if let Some(exe) = exe { - if !open_launcher() { - // killed: restart it; faked Alt+Space opens the window menu (#291) - let _ = i18n::launch::program(&exe.to_string_lossy()); - fly::toggle(fly::Kind::Start); - } - } else { - fly::toggle(fly::Kind::Start); - } - } - // virtual desktops (#83). Task View lives in explorer's shell: without it Win+Tab does nothing (#120), so the button - // opens our window grid instead (the Alt+Tab one: click a card, arrows + Enter, Esc or the button again closes) - TASKVIEW if left && !find_other("Shell_TrayWnd").is_null() => keys(&[VK_LWIN, VK_TAB]), - TASKVIEW if left => { - if IsWindowVisible(SWWND.get()) != 0 { - SWITCHING.store(false, Relaxed); - alt_done(true); - } else { - SWITCHING.store(true, Relaxed); - alt_tab(false); - } - } - // left: the language picker; right: straight to the next one (Win+Space is explorer's, gone under rs-shell) - LANG if left => lang_menu(BAR.load(Relaxed) as HWND), - LANG => next_lang(BAR.load(Relaxed) as HWND, false), - WIFI_I => fly::toggle_click(if left { fly::Kind::Quick } else { fly::Kind::Wifi }), // right click: the network list - VOL_I | BAT_I => fly::toggle_click(fly::Kind::Quick), - CLOCK if left => fly::toggle_click(fly::Kind::Cal), - CLOCK => { - // right click: like Windows 11, a menu with the date and time and notification settings (#126) - let items = vec![ - fly::MItem::new(t!("Настройка даты и времени", "Adjust date and time", ja: "日付と時刻を調整する", pt: "Ajustar data e hora")), - fly::MItem::new(t!("Параметры уведомлений", "Notification settings", ja: "通知の設定", pt: "Configurações de notificação")), - ]; - fly::menu(tip_cx(&bar_layout(BAR.load(Relaxed) as HWND), CLOCK), None, items, |i| { - if i == 0 { - // the classic applet opens at once with or without Explorer; the Settings page needs Explorer started first - let _ = Command::new("control.exe").arg("timedate.cpl").creation_flags(NO_WINDOW).spawn(); - } else { - open(&wide("ms-settings:notifications")); - } - }); - } - SHOWDESK if left => winrust_common::desktop::toggle(), - POW_R | POW_S if left => power_click(h), - GEAR => style_menu(), - TAPP..=-900 => { - let slot = (h - TAPP) as usize; - if slot == 0 { - if left { - fly_toggle(); - } - } else if mid { - if let Some(k) = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| x.key.clone()))) { - toggle_shown(&k); // back into the flyout - } - } else { - let ti = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| (x.hwnd, x.uid, x.cb, x.ver)))); - ti.into_iter().for_each(|ti| tray_click(ti, left)); - } - } - 0 if left => fly::toggle_click(fly::Kind::Start), - 0 => start_menu(), - 1.. => { - let (wins, lnk) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))))).unwrap_or_default()); - match (wins.first(), left) { - // not running: launch the pinned app (a Store app may have updated since the pins were loaded) - (None, true) => lnk.iter().for_each(|l| { - PINS.with_borrow_mut(|p| p.iter_mut().filter(|x| x.lnk == *l).for_each(|x| x.target = fix_msix_pin(l, &x.target).unwrap_or(std::mem::take(&mut x.target)))); - open(l) - }), - (Some(&w), false) => close_window(w), // right / middle click - // several windows of one app: pick which one (the same list the right-click menu opens with) - (Some(_), true) if wins.len() > 1 => app_menu(BAR.load(Relaxed) as HWND, h), - (Some(&w), true) => { - // like the Windows taskbar: the active app's button minimizes it, a minimized one restores, any other raises - let fg = GetForegroundWindow(); - if wins.contains(&fg) && IsIconic(fg) == 0 { - note_minimize(fg); - ShowWindow(fg, SW_MINIMIZE); - } else { - bring(w); - } - } - _ => {} - } - } - _ => {} - } -} - -#[repr(C)] -struct ShellHookInfo { - hwnd: HWND, - rc: RECT, -} - -/// HSHELL_GETMINRECT: a window is minimizing / restoring and asks where its taskbar button is: the shrink animation -/// flies there instead of to the bottom left corner of the screen. -unsafe fn min_rect(info: *mut ShellHookInfo, bar: HWND) { - let (w, l) = ((*info).hwnd, bar_layout(bar)); - let exe = exe_of(w); - let i = BTNS.with_borrow(|b| b.iter().position(|b| b.wins.contains(&w)).or_else(|| b.iter().position(|b| !exe.is_empty() && b.wins.first().is_some_and(|&x| exe_of(x) == exe)))); - let x = match i { - Some(i) => l.btn_pos(i as i32), - None => (l.x0 + l.apps.0) / 2, // no button (yet): the middle of the bar - }; - if vert() { - let left = bar_x() + sc(4); - (*info).rc = RECT { left, top: x, right: left + bar_h() - sc(8), bottom: x + l.bw }; - return; - } - let (top, x) = (bar_top() + sc(4), x + bar_x_w().0); - (*info).rc = RECT { left: x, top, right: x + l.bw, bottom: top + bar_h() - sc(8) }; -} - -/// Screen x of the middle of a bar element, for its tooltip and menus. -unsafe fn tip_cx(l: &Layout, h: i32) -> i32 { - // along the bar: screen x for a bottom bar, screen y for a side bar - (if vert() { 0 } else { bar_x_w().0 }) + match h { - GEAR => l.gear_x + sc(GEAR_X.1 / 2), - SEARCH => l.x0 + l.bw / 2, - TASKVIEW => l.x0 + (l.bw + l.gap) + l.bw / 2, - CLOCK => (l.clock.0 + l.clock.1) / 2, - SHOWDESK => l.clock.1 + sc(3), - POW_R | POW_S => l.power.0 + power_keys().iter().position(|&k| k == h).unwrap_or(0) as i32 * sc(32) + sc(16), - LANG => l.sys.0 + sc(21), - WIFI_I => l.sys.0 + sc(58), - VOL_I => l.sys.0 + sc(90), - BAT_I => l.sys.0 + sc(130), - t if (TAPP..TAPP + 100).contains(&t) => l.apps.0 + (t - TAPP) * sc(24) + sc(12), - i => l.btn_pos(i) + l.bw / 2, - } -} - -unsafe fn bar_layout(hwnd: HWND) -> Layout { - let mut r: RECT = zeroed(); - GetClientRect(hwnd, &mut r); - layout(if vert() { r.bottom } else { r.right }) -} - -/// Registers the bar as an appbar with explorer (again after explorer restarts: its list starts empty). -unsafe fn appbar_new(hwnd: HWND) { - let mut ab: APPBARDATA = zeroed(); - ab.cbSize = size_of::() as u32; - ab.hWnd = hwnd; - ab.uCallbackMessage = CALLBACK; - SHAppBarMessage(ABM_NEW, &mut ab); - EXP_TRAY.set(tray()[0]); -} - -unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { - if msg != 0 && msg == SH_MSG.get() { - if wp == 5 && lp != 0 { - min_rect(lp as *mut ShellHookInfo, hwnd); // HSHELL_GETMINRECT - return 1; - } - let w = lp as HWND; - match wp { - 0x8006 => FLASH.with_borrow_mut(|f| if !f.contains(&w) { f.push(w) }), // HSHELL_FLASH - 4 | 0x8004 | 2 => FLASH.with_borrow_mut(|f| f.retain(|&x| x != w)), // activated (HSHELL_WINDOWACTIVATED / RUDEAPPACTIVATED), destroyed - _ => return 0, - } - InvalidateRect(hwnd, null(), 0); - second::invalidate(); - return 0; - } - if msg != 0 && msg == TB_MSG.get() { - // also our own announce(): act only when explorer's taskbar is a new window (explorer restarted / came back) - let t = tray()[0]; - if !t.is_null() && t != EXP_TRAY.get() { - appbar_new(hwnd); - hide_taskbar(); - place(hwnd); - } - return 0; - } - match msg { - WM_PAINT => paint(hwnd), - WM_ERASEBKGND => return 1, - WM_TIMER if wp == 2 => { - KillTimer(hwnd, 2); - let h = HOT.get(); - if h != NONE && !fly::any_open() { - let cx = tip_cx(&bar_layout(hwnd), h); - // an app button with windows shows their live previews (#92), anything else its tip - if !thumbs::show_preview(h, cx) { - thumbs::hide_preview(); - show_tip(tip_text(h), cx); - } - } - } - WM_TIMER if wp == 6 => hide_tip(hwnd), // the volume readout after a wheel turn - WM_TIMER if wp == 3 => fs_update(hwnd), - WM_TIMER if wp == 7 => { - KillTimer(hwnd, 7); - let (tid, before, next) = LANG_TRY.get(); - if GetKeyboardLayout(tid) as usize == before && !EXPLORER_UP.load(Relaxed) { - // no explorer, so no system switcher to fall back on: ask the app's top-level window as well (some apps - // only listen there, not on the focused child) - PostMessageW(app_window(), WM_INPUTLANGCHANGEREQUEST, 0, next as isize); - } else if GetKeyboardLayout(tid) as usize == before { - let w = app_window(); - if GetForegroundWindow() != w { - force_fg(w); // Win+Space switches the window in front: put the app back there first - } - keys(&[VK_LWIN, VK_SPACE]); // the app ignored the request: the system switcher always works (with explorer) - } - InvalidateRect(hwnd, null(), 0); // the label shows the new language right away - } - WM_TIMER if wp == 4 => { - InvalidateRect(hwnd, null(), 0); - } - WM_TIMER if wp == 5 => bar_step(hwnd), - WIN_START => fly::toggle(fly::Kind::Start), - ALT_TAB => alt_tab(wp == 1), - WIN_NUM => win_num(wp), - WIN_X => start_menu(), - WIN_V => { - let (x, w) = bar_x_w(); - hist::show(hwnd, x + w / 2); - } - 0x031D => hist::on_update(hwnd), // WM_CLIPBOARDUPDATE - NEXT_LANG => next_lang(hwnd, wp == 1), - TILE_WINDOWS => tile_windows(), - ALT_UP if wp == 2 => alt_close(), - ALT_UP => alt_done(wp == 1), - SNIP if wp == 1 => screenshot_notice(hwnd), - SNIP if wp == 2 => clip_notice(hwnd), - SNIP => clip::start(), - VOLKEY => { - if wp == 2 { toggle_mute() } else { add_volume(if wp == 0 { 4 } else { -4 }) } - KillTimer(hwnd, 2); - show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I)); - SetTimer(hwnd, 6, 1200, None); - InvalidateRect(hwnd, null(), 0); - } - WM_DROPFILES => on_drop(hwnd, wp as HDROP), - WM_TIMER if wp == 8 => { - // window events since the last look (win_event): one refresh for the whole burst - KillTimer(hwnd, 8); - WIN_DIRTY.set(false); - hide_taskbar_if_shown(); - refresh_windows(); - repaint_if_changed(hwnd, false); - } - WM_TIMER => { - hide_taskbar_if_shown(); - if work_area_drifted() { place(hwnd); } - refresh_status(); - if widgets::poll() { - // a mod's widget text changed (a file date check, once a second); this tick may run on another window - InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); - } - if TICK.get() % 5 == 0 { - refresh_windows(); // safety net for a window event the hook did not report - } - fs_update(hwnd); // style switches (auto-hide, dock) take effect without a window event - drag_hover(hwnd); - keep_in_place(hwnd); - repaint_if_changed(hwnd, true); - } - WM_MOUSEMOVE => { - let x = (lp & 0xffff) as i16 as i32; - let y = (lp >> 16) as i16 as i32; - BUTTON_DRAG.with_borrow_mut(|d| if let Some(d) = d { if (x - d.start_x).abs() >= sc(4) || (y - d.start_y).abs() >= sc(4) { d.moved = true; } }); - let moving = BUTTON_DRAG.with_borrow(|d| d.as_ref().filter(|d| d.moved).map(|d| d.button.clone())); - if let Some(from) = moving { - if let Some(to) = drag_target(hwnd, x, y) { reorder_buttons(from, to); } - hide_tip(hwnd); - InvalidateRect(hwnd, null(), 0); - return 0; - } - let h = hit(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); - let mut tme = TRACKMOUSEEVENT { cbSize: size_of::() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 }; - TrackMouseEvent(&mut tme); - if HOT.replace(h) != h { - hide_tip(hwnd); - if h != NONE { - SetTimer(hwnd, 2, 450, None); - } - InvalidateRect(hwnd, null(), 0); - } - } - WM_MOUSELEAVE => { - hide_tip(hwnd); - HOT.set(-1); - InvalidateRect(hwnd, null(), 0); - } - WM_MOUSEWHEEL => { - add_volume(if (wp >> 16) as i16 > 0 { 2 } else { -2 }); // wheel anywhere on the bar = volume - press(VOL_I); // the speaker flashes so it is clear what the wheel changed - KillTimer(hwnd, 2); - if !fly::any_open() { - show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I)); // and the level shows above it for a moment - SetTimer(hwnd, 6, 1200, None); - } - InvalidateRect(hwnd, null(), 0); - } - WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => { - let x = (lp & 0xffff) as i16 as i32; - let y = (lp >> 16) as i16 as i32; - let h = hit(hwnd, x, y); - if msg == WM_LBUTTONDOWN { - if let Some(button) = button_key(h) { - BUTTON_DRAG.set(Some(ButtonDrag { button, start_x: x, start_y: y, moved: false })); - SetCapture(hwnd); - hide_tip(hwnd); - press(h); - InvalidateRect(hwnd, null(), 0); - return 0; - } - } - let x = if vert() { (lp >> 16) as i16 as i32 } else { x }; // position along the bar - hide_tip(hwnd); - thumbs::hide_preview(); - if h != NONE { - press(h); - } - if h == NONE && msg == WM_RBUTTONDOWN { - fly::context_menu(x); // right click on an empty spot - } else if h >= 1 && msg == WM_RBUTTONDOWN { - app_menu(hwnd, h); - } else { - click(h, msg == WM_LBUTTONDOWN, msg == WM_MBUTTONDOWN); - } - InvalidateRect(hwnd, null(), 0); - } - WM_LBUTTONUP => { - let drag = BUTTON_DRAG.take(); - if let Some(drag) = drag { - ReleaseCapture(); - let target = hit(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); - if drag.moved { - if let Some(to) = drag_target(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32) { reorder_buttons(drag.button, to); } - save_button_order(); - } else if button_key(target).as_ref() == Some(&drag.button) { - click(target, true, false); - } - InvalidateRect(hwnd, null(), 0); - } - } - WM_CAPTURECHANGED => { if BUTTON_DRAG.take().is_some_and(|d| d.moved) { save_button_order(); } } - CALLBACK => { - if wp == ABN_FULLSCREENAPP as usize { - fs_update(hwnd); - } else if wp == ABN_POSCHANGED as usize { - place(hwnd); - } - } - WM_DISPLAYCHANGE => place(hwnd), - WM_SETTINGCHANGE if wp == SPI_SETWORKAREA as usize => { - if work_area_drifted() { place(hwnd); } - } - WM_DESTROY => { - let mut ab: APPBARDATA = zeroed(); - ab.cbSize = size_of::() as u32; - ab.hWnd = hwnd; - SHAppBarMessage(ABM_REMOVE, &mut ab); - set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // ours: give the strip back - second::release(); - show_taskbar(OLD_STATE.get()); - forget_taskbar_state(); - DestroyWindow(HOST.replace(null_mut())); - announce(); // icons go back to explorer's tray - PostQuitMessage(0); - } - _ => return DefWindowProcW(hwnd, msg, wp, lp), - } - 0 -} - -fn main() { - unsafe { - if std::env::args().any(|a| a == "--restore") { - show_taskbar(saved_taskbar_state().unwrap_or(ABS_ALWAYSONTOP as usize)); - forget_taskbar_state(); - set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // a killed bar's reserved strip - second::restore_work_areas(); - announce(); // a killed bar took its tray icons with it; apps re-register with explorer - return; - } - if std::env::args().any(|a| a == "--shot") { - SetProcessDPIAware(); - let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed()); - inp.GdiplusVersion = 1; - GdiplusStartup(&mut tok, &inp, null_mut()); - screenshot(); - return; - } - // `topbar --preview quick|wifi`: one flyout on its own (no bar, no hooks), to look at a style change; the process is closed by hand - if let Some(p) = std::env::args().skip_while(|a| a != "--preview").nth(1) { - SetProcessDPIAware(); - let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed()); - inp.GdiplusVersion = 1; - GdiplusStartup(&mut tok, &inp, null_mut()); - fly::init(GetModuleHandleW(null())); - fly::PREVIEW.store(true, Relaxed); - fly::toggle(if p == "wifi" { fly::Kind::Wifi } else { fly::Kind::Quick }); - let mut msg: MSG = zeroed(); - while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 { - TranslateMessage(&msg); - DispatchMessageW(&msg); - } - return; - } - // Atomic single-instance guard (FindWindow alone raced when two launchers started us at once); the handle lives until exit. - let m = windows_sys::Win32::System::Threading::CreateMutexW(null(), 0, wide("Local\\topbar-single").as_ptr()); - if m.is_null() || GetLastError() == ERROR_ALREADY_EXISTS || !FindWindowW(wide("topbar").as_ptr(), null()).is_null() { - return; // already running - } - let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); - // Without explorer nobody hides minimized windows: they sit as small caption stubs at the bottom left of the screen. - // ARW_HIDE moves them off screen (this session only: fWinIni 0 does not touch the saved setting). - let mut mm: MINIMIZEDMETRICS = zeroed(); - mm.cbSize = size_of::() as u32; - if SystemParametersInfoW(SPI_GETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0) != 0 { - mm.iArrange |= ARW_HIDE as i32; - SystemParametersInfoW(SPI_SETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0); - } - let (mut gtok, mut gin): (usize, GdiplusStartupInput) = (0, zeroed()); - gin.GdiplusVersion = 1; - GdiplusStartup(&mut gtok, &gin, null_mut()); // anti-aliased shapes; fill() falls back to GDI if this failed - TB_MSG.set(RegisterWindowMessageW(wide("TaskbarCreated").as_ptr())); - SH_MSG.set(RegisterWindowMessageW(wide("SHELLHOOK").as_ptr())); - SetProcessDPIAware(); - let dc = GetDC(null_mut()); - SCALE.set(GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0); - ReleaseDC(null_mut(), dc); - SHOWN.set(std::fs::read_to_string(appdata_file("topbar-tray.txt")).ok().map(|s| s.lines().map(str::to_string).collect())); - load_pins(); - fly::init(GetModuleHandleW(null())); - thread::spawn(fly::load_apps); - thread::spawn(winrust_common::eco::auto_loop); // efficiency mode for background CPU hogs while the Game profile is on - thread::spawn(winrust_common::mem::auto_loop); // standby purge when memory runs short, switched on from the task manager's Speed page - let hi = GetModuleHandleW(null()); - let class = wide("topbar"); - let wc = WNDCLASSW { lpfnWndProc: Some(wndproc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: class.as_ptr(), ..zeroed() }; - RegisterClassW(&wc); - let hwnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE | WS_EX_LAYERED, class.as_ptr(), class.as_ptr(), WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), bar_h(), null_mut(), null_mut(), hi, null()); - // Our own Shell_TrayWnd (hidden, topmost, so apps find it before explorer's): apps register their tray icons here. - let tc = wide("Shell_TrayWnd"); - RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tray_proc), hInstance: hi, lpszClassName: tc.as_ptr(), ..zeroed() }); - HOST.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tc.as_ptr(), null(), WS_POPUP, 0, 0, 0, 0, null_mut(), null_mut(), hi, null())); - // The bar may run elevated while apps and explorer do not; UIPI would drop their messages to us (icon data, appbar callbacks). - ChangeWindowMessageFilterEx(HOST.get(), WM_COPYDATA, MSGFLT_ALLOW, null_mut()); - // ITaskbarList::HrInit reads the task band from this property of the first Shell_TrayWnd, which is ours: without it - // HrInit failed (E_NOTIMPL) for every app while the bar ran. DeleteTab / AddTab then come here (tray_proc). - SetPropW(HOST.get(), wide("TaskbandHWND").as_ptr(), HOST.get()); - ChangeWindowMessageFilterEx(HOST.get(), SH_MSG.get(), MSGFLT_ALLOW, null_mut()); - ChangeWindowMessageFilterEx(hwnd, CALLBACK, MSGFLT_ALLOW, null_mut()); - ChangeWindowMessageFilterEx(hwnd, TB_MSG.get(), MSGFLT_ALLOW, null_mut()); // explorer restarted (it runs unelevated) - // files dragged from a normal-rights app onto the (elevated) bar: Start button = add to Start, elsewhere = pin - DragAcceptFiles(hwnd, 1); - for m in [WM_DROPFILES, 0x49 /* WM_COPYGLOBALDATA */, WM_COPYDATA] { - ChangeWindowMessageFilterEx(hwnd, m, MSGFLT_ALLOW, null_mut()); - } - let fc = wide("topbar_trayfly"); - RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(fly_proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: fc.as_ptr(), ..zeroed() }); - TRAYFLY.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_LAYERED, fc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); - let tipc = wide("topbar_tip"); - RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tip_proc), hInstance: hi, lpszClassName: tipc.as_ptr(), ..zeroed() }); - TIPWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tipc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); - let swc = wide("topbar_alttab"); - RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(sw_proc), hInstance: hi, lpszClassName: swc.as_ptr(), ..zeroed() }); - SWWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, swc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); - let pvc = wide("topbar_preview"); - RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(thumbs::pv_proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: pvc.as_ptr(), ..zeroed() }); - thumbs::PVWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, pvc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); - OLD_STATE.set(remember_taskbar_state()); - appbar_new(hwnd); - // Without explorer nobody is the "taskman" window, so Windows treats minimized windows as loose icons and leaves - // them as caption stubs on the desktop. Becoming that window (what explorer's taskbar does) makes them hide properly - // and gets us HSHELL_GETMINRECT. Only when explorer's taskbar is absent: with it running its own registration stays. - if find_other("Shell_TrayWnd").is_null() { - if let Some(f) = GetProcAddress(GetModuleHandleW(wide("user32.dll").as_ptr()), b"SetTaskmanWindow\0".as_ptr()) { - std::mem::transmute::<_, unsafe extern "system" fn(HWND) -> i32>(f)(hwnd); - } - } - // window events for the shell (minimize target, HSHELL_FLASH): also next to explorer, whose taskbar we hide - RegisterShellHookWindow(hwnd); - hide_taskbar(); - place(hwnd); - refresh(); - announce(); // apps already running re-add their icons to us - SetTimer(hwnd, 1, 1000, None); // status poll; windows come from win_event - BAR.store(hwnd as isize, Relaxed); - hist::init(hwnd); - bar_anim(hwnd); // the bar slides in (it starts hidden above the screen) - SetTimer(hwnd, 3, 250, None); // fullscreen watch - windows_sys::Win32::UI::Accessibility::SetWinEventHook(0x000A, 0x000B, null_mut(), Some(snap_proc), 0, 0, 0); // EVENT_SYSTEM_MOVESIZESTART..END - // foreground, minimize start/end, create..hide, name, cloaked/uncloaked (2 = WINEVENT_SKIPOWNPROCESS). Not - // LOCATIONCHANGE: it fires for every caret and cursor move; a fullscreen switch comes as ABN_FULLSCREENAPP and the 1 s tick - for (a, b) in [(0x0003, 0x0003), (0x0016, 0x0017), (0x8000, 0x8003), (0x800C, 0x800C), (0x8017, 0x8018)] { - windows_sys::Win32::UI::Accessibility::SetWinEventHook(a, b, null_mut(), Some(win_event), 0, 0, 2); - } - thread::spawn(|| { - let mut hook = SetWindowsHookExW(WH_KEYBOARD_LL, Some(kb_hook), GetModuleHandleW(null()), 0); - // Windows silently drops a low-level hook that once answers too slowly (busy boot), leaving Win+R, Start and - // Alt+Tab dead with no explorer to fall back on: set it again now and then. Callbacks run only inside - // GetMessageW on this thread, so swapping here never delivers a key twice. - SetTimer(null_mut(), 0, 30_000, None); - let mut m: MSG = zeroed(); - while GetMessageW(&mut m, null_mut(), 0, 0) > 0 { - if m.message == WM_TIMER { - let new = SetWindowsHookExW(WH_KEYBOARD_LL, Some(kb_hook), GetModuleHandleW(null()), 0); - if !new.is_null() { - if !hook.is_null() { - UnhookWindowsHookEx(hook); - } - hook = new; - } - } - } - }); - let mut m: MSG = zeroed(); - while GetMessageW(&mut m, null_mut(), 0, 0) > 0 { - TranslateMessage(&m); - DispatchMessageW(&m); - } - } -} - -#[cfg(test)] -mod pin_match_tests { - use super::pin_of_other_exe; - - #[test] - fn windows_find_their_pin_across_exes() { - let up = r"c:\users\a\appdata\local\discord\update.exe"; - let app = r"c:\users\a\appdata\local\discord\app-1.0.9002\discord.exe"; - assert!(pin_of_other_exe(up, "--processStart Discord.exe", "", app, "")); - assert!(pin_of_other_exe(up, "--processStart=\"Discord.exe\"", "", app, "")); - assert!(pin_of_other_exe(r"c:\users\a\appdata\local\discord\app-1.0.9001\discord.exe", "", "", app, "")); - assert!(pin_of_other_exe(r"c:\x\launcher.exe", "", "com.app", app, "com.app")); - assert!(!pin_of_other_exe(up, "--processStart Slack.exe", "", app, "")); - assert!(!pin_of_other_exe(r"c:\x\launcher.exe", "", "", app, "")); - assert!(!pin_of_other_exe("", "", "", app, "")); - } -} - -#[cfg(test)] -mod tests { - #[test] - fn magnet_picks_the_nearest_edge_within_reach() { - let r = windows_sys::Win32::Foundation::RECT { left: 105, top: 50, right: 505, bottom: 350 }; - assert_eq!(super::magnet(r, &[100, 900], &[0, 1000], 14), (-5, 0)); // left edge to 100 - assert_eq!(super::magnet(r, &[512, 100], &[], 14), (-5, 0)); // 105->100 (5) beats 505->512 (7) - assert_eq!(super::magnet(r, &[515], &[340], 14), (10, -10)); // right edge to 515, bottom to 340 - assert_eq!(super::magnet(r, &[130, 0], &[80], 14), (0, 0)); // nothing close enough - } - - #[test] - fn a_far_off_appbar_edge_goes_back_to_the_screen_edge() { - assert_eq!(super::sane_edge(48, 1080), 48); // another bar below ours: stack above it - assert_eq!(super::sane_edge(540, 1080), 0); // half the screen (#106) - assert_eq!(super::sane_edge(-20, 1080), 0); - } - - /// The clock cell is measured from the time and the date in the bar's own fonts, so the air around the block is the - /// same in every language, and the date of a locale still fits (no ellipsis, no clipped slash). - #[test] - fn clock_cell_fits_every_locale() { - use super::*; - const LOCALES: [(u32, &str); 5] = [(0x0409, "en-US"), (0x0419, "ru-RU"), (0x0411, "ja-JP"), (0x0416, "pt-BR"), (0x0804, "zh-CN")]; - unsafe { - SCALE.set(2.0); // the 200 % case, the tightest one: everything else scales with it - let [_, f_date, _, f_time] = bar_fonts(); // the fonts the bar paints the clock with - let dc = CreateCompatibleDC(null_mut()); - for (locale, name) in LOCALES { - let (tm, dt) = clock_texts_of(locale); - let (tw, dw) = (text_size(dc, f_time, &tm).0, text_size(dc, f_date, &dt).0); - let w = clock_cell_w(tw, dw); - assert!(tw <= w - 2 * sc(CLOCK_PAD), "{name}: the time {tm} does not fit its cell"); - assert!(dw <= w - 2 * sc(CLOCK_PAD), "{name}: the date {dt} does not fit its cell"); - assert!(w >= sc(CLOCK_MIN), "{name}: the cell is narrower than the minimum"); - } - DeleteDC(dc); - } - } - - /// The right group ends where its last icon ends: a wider slot was the hole between the volume icon and the clock - /// (and a battery panel under a click on empty space). - #[test] - fn system_group_is_as_wide_as_it_draws() { - use super::*; - BAT.set((-1, false)); // a desktop: no battery in the group - assert_eq!(sys_w(), SYS_LANG + SYS_WIFI + SYS_VOL + SYS_END); - BAT.set((80, false)); - assert_eq!(sys_w(), SYS_LANG + SYS_WIFI + SYS_VOL + SYS_BAT + SYS_END); - BAT.set((-1, false)); - } - - #[test] - fn borderless_games_count_as_fullscreen() { - use super::{RECT, covers_monitor}; - let m = RECT { left: 0, top: 0, right: 1920, bottom: 1080 }; - assert!(covers_monitor(m, m, false, false)); // plain borderless / exclusive fullscreen - assert!(covers_monitor(m, m, true, false)); // borderless window that kept its caption style - // Minecraft (SDL_app): caption style, not maximized, sized one pixel past the monitor — still fullscreen - assert!(covers_monitor(RECT { left: 0, top: 0, right: 1921, bottom: 1080 }, m, true, false)); - assert!(!covers_monitor(RECT { left: -8, top: -8, right: 1928, bottom: 1088 }, m, true, true)); // framed maximized window (#88) - assert!(!covers_monitor(m, m, true, true)); // a maximized window is never a game - assert!(!covers_monitor(RECT { left: -8, top: -8, right: 1928, bottom: 1088 }, m, true, false)); // same, IsZoomed false (#237) - assert!(!covers_monitor(RECT { left: 0, top: 0, right: 1920, bottom: 1032 }, m, false, false)); // leaves the bar's strip - } - - fn pinned_and_running_items_can_be_reordered_together() { - use super::DragButton::{Pin, Window}; - let mut items = vec![Pin(vec![1]), Window(42), Pin(vec![2])]; - assert!(super::move_item(&mut items, 0, 1)); - assert!(matches!(items.as_slice(), [Window(42), Pin(_), Pin(_)])); - assert!(super::move_item(&mut items, 2, 0)); - assert!(matches!(items.as_slice(), [Pin(_), Window(42), Pin(_)])); - } - #[test] - fn drag_accepts_gaps_and_edges_without_targeting_start() { - assert_eq!(super::drag_slot(208, 100, 40, 4, 5, 400, 1), Some(1)); - assert_eq!(super::drag_slot(232, 100, 40, 4, 5, 400, 1), Some(2)); - assert_eq!(super::drag_slot(399, 100, 40, 4, 5, 400, 1), Some(4)); - assert_eq!(super::drag_slot(400, 100, 40, 4, 5, 400, 1), None); - // search and Task View before Start: the first button after Start is three slots in - assert_eq!(super::drag_slot(100 + 3 * 44, 100, 40, 4, 5, 400, 2), Some(1)); - } - #[test] - fn network_icon_state() { - use super::{INET, Link, WIFI, arcs_lit, net}; - let at = |q: i32, inet: bool| { - WIFI.set(q); - INET.set(inet); - net() - }; - assert!(at(80, true) == Link::Wifi(80)); - assert!(at(80, false) == Link::NoInternet(80)); // wifi without a way out: the warning icon - assert!(at(-1, true) == Link::Cable); - assert!(at(-1, false) == Link::Offline); // nothing at all: the crossed-out wifi icon - assert_eq!((arcs_lit(0), arcs_lit(40), arcs_lit(100)), (1, 2, 3)); - } - - #[test] - fn file_manager_windows_belong_to_the_file_explorer_pin() { - use super::as_pinned_exe; - let (rx, ex) = (r"c:\program files\rust-explorer\rust-explorer.exe", r"c:\windows\explorer.exe"); - assert_eq!(as_pinned_exe(rx, ex, true), ex); // the pin the user clicks gets the windows - assert_eq!(as_pinned_exe(rx, ex, false), rx); // no such pin: the file manager's own pin keeps them - assert_eq!(as_pinned_exe(r"c:\tools\other.exe", ex, true), r"c:\tools\other.exe"); - } - - #[test] - fn bar_fonts_key_changes_with_icon_size() { - let a = super::bar_fonts_key(1.0, "Segoe UI Variable", "Segoe Fluent Icons", 60); - let b = super::bar_fonts_key(1.0, "Segoe UI Variable", "Segoe Fluent Icons", 100); - assert_ne!(a, b); - } - - #[test] - fn mix_blends() { - assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.0), super::rgb(0, 0, 0)); - assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 1.0), super::rgb(200, 100, 50)); - assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.5), super::rgb(100, 50, 25)); - } - - #[test] - fn msix_family_from_package_path() { - let f = super::msix_family(r"C:\Program Files\WindowsApps\Claude_5.11492.5.0_x64__pzs8sxrjxfjjc\app\claude.exe"); - assert_eq!(f, Some(("claude_pzs8sxrjxfjjc".into(), r"app\claude.exe".into()))); - assert_eq!(super::msix_family(r"C:\Program Files\Steam\steam.exe"), None); - } - - #[test] - fn stale_claude_pin_resolves_to_installed_version() { - // real system check: skipped where the Claude package is not installed (CI) - let old = r"c:\program files\windowsapps\claude_5.11492.5.0_x64__pzs8sxrjxfjjc\app\claude.exe"; - let Some((fam, _)) = super::msix_family(old) else { panic!() }; - let mut n = 0u32; - let mut len = 0u32; - unsafe { windows_sys::Win32::Storage::Packaging::Appx::GetPackagesByPackageFamily(super::wide(&fam).as_ptr(), &mut n, std::ptr::null_mut(), &mut len, std::ptr::null_mut()) }; - if n == 0 { - return; - } - let tmp = std::env::temp_dir().join("topbar-msix-test.lnk"); - let _ = std::fs::remove_file(&tmp); - unsafe { - use windows::Win32::System::Com::*; - let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); - let sl: windows::Win32::UI::Shell::IShellLinkW = CoCreateInstance(&windows::Win32::UI::Shell::ShellLink, None, CLSCTX_INPROC_SERVER).unwrap(); - sl.SetPath(windows::core::PCWSTR(super::wide(old).as_ptr())).unwrap(); - windows::core::Interface::cast::(&sl).unwrap().Save(windows::core::PCWSTR(super::wide(&tmp.to_string_lossy()).as_ptr()), true).unwrap(); - let lnk = super::wide(&tmp.to_string_lossy()); - let new = super::fix_msix_pin(&lnk, old).expect("re-pointed"); - assert!(std::path::Path::new(&new).exists() && new.ends_with(r"\app\claude.exe"), "{new}"); - assert_eq!(super::lnk_target(&lnk), new); - } - let _ = std::fs::remove_file(&tmp); - } -} - -#[cfg(test)] -mod env_tests { - #[test] - fn expands_known_variables_only() { - let windir = std::env::var("windir").unwrap(); - assert_eq!(super::expand_env(r"%windir%\explorer.exe"), format!(r"{windir}\explorer.exe")); - assert_eq!(super::expand_env(r"%no_such_var_x%\a.exe"), r"%no_such_var_x%\a.exe"); - assert_eq!(super::expand_env("100% sure"), "100% sure"); - } -} - -#[cfg(test)] -mod restore_rect_tests { - use super::*; - - #[test] - fn maximized_restore_rect_fits_under_a_top_bar() { - let m = RECT { left: 0, top: 0, right: 1920, bottom: 1080 }; - let work = workspace(RECT { top: 40, ..m }, m); - let mut n = RECT { left: -8, top: -8, right: 1928, bottom: 1088 }; - assert!(clamp_rect(&mut n, work)); - assert_eq!((n.left, n.top, n.right, n.bottom), (0, 0, 1920, 1040)); - assert!(!clamp_rect(&mut n, work)); - } -} +// topbar: replaces the Windows taskbar with a panel on the chosen screen edge, +// drawn in the Windows 11 taskbar palette: Start, pinned apps and open windows in the center; tray apps, language, wifi, +// volume, battery and date/time on the right. `--restore` brings the normal taskbar back (used by uninstall). +#![windows_subsystem = "windows"] +#![allow(unsafe_op_in_unsafe_fn)] +use std::{ + cell::{Cell, RefCell}, + mem::{size_of, zeroed}, + os::windows::process::CommandExt, + path::PathBuf, + process::Command, + ptr::{null, null_mut}, + thread, + sync::Mutex, + collections::HashMap, + sync::atomic::{AtomicBool, AtomicIsize, Ordering::Relaxed}, +}; +#[macro_use] +extern crate winrust_common; +use winrust_common as i18n; +use winrust_common::style::{Style, card, on_accent, pal, rgb, style, ui_face}; +mod clip; +mod widgets; // the mods' widgets on the bar +mod hist; +mod fly; +mod quick; +mod tray; +mod status; +mod run; +mod shot; +mod lang; +mod settings; +mod second; // a bar on every other monitor +mod notif; // notifications under the calendar +mod thumbs; +mod wmi; +use {tray::*, status::*, run::*, shot::*, lang::*, settings::*}; +use windows::{ + Win32::{ + Media::Audio::{Endpoints::IAudioEndpointVolume, IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender}, + System::Com::{CLSCTX_ALL, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, IPersistFile, STGM}, + UI::Shell::{IShellLinkW, ShellLink}, + }, + core::{Interface, PCWSTR}, +}; +use windows_sys::Win32::{ + Foundation::*, + Globalization::{GetDateFormatW, GetLocaleInfoW, GetTimeFormatW}, + Graphics::{ + Dwm::DwmGetWindowAttribute, + Gdi::*, + GdiPlus::{ + FillModeAlternate, GdipAddPathArc, GdipClosePathFigure, GdipCreateFromHDC, GdipCreatePath, GdipCreateSolidFill, GdipDeleteBrush, GdipDeleteGraphics, GdipDeletePath, GdipFillPath, GdipSetPixelOffsetMode, + GdipSetSmoothingMode, GdiplusStartup, GdiplusStartupInput, GpBrush, GpGraphics, GpPath, GpSolidFill, PixelOffsetModeHalf, SmoothingModeAntiAlias, + GdipCreatePen1, GdipDeletePen, GdipDrawArc, GdipDrawLine, GdipFillEllipse, GdipSetPenEndCap, GdipSetPenStartCap, GpPen, LineCapRound, UnitPixel, + }, + }, + NetworkManagement::WiFi::*, + System::{ + LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW}, + Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS}, + SystemInformation::{GetLocalTime, GetTickCount64}, + Threading::{OpenProcess, QueryFullProcessImageNameW, TerminateProcess}, + }, + UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*}, +}; + +/// A corner radius in logical px, 0 in the square styles. +fn rr(v: i32) -> i32 { + if style().square() { 0 } else { sc(v) } +} +/// The bar sits at the top of the screen (by position setting or tiling theme). +fn at_top() -> bool { + !vert() && (i18n::style::side() == i18n::style::Side::Top || style() == Style::Tiling) +} +/// The bar stands on the left or right edge of the screen (its "width" is bar_h(), it spans the screen height). +fn vert() -> bool { + matches!(i18n::style::side(), i18n::style::Side::Left | i18n::style::Side::Right) +} +/// The floating dock (a pill in the middle of the bottom edge). +fn dock() -> bool { + style() == Style::Dock && i18n::style::side() == i18n::style::Side::Bottom +} +/// Screen x of a side bar's current left edge, slid away by the show/hide animation. +unsafe fn bar_x() -> i32 { + if i18n::style::side() == i18n::style::Side::Left { -bar_off() } else { GetSystemMetrics(SM_CXSCREEN) - bar_h() + bar_off() } +} +/// Top-left of the bar window now. +unsafe fn bar_pos() -> (i32, i32) { + if vert() { (bar_x(), 0) } else { (bar_x_w().0, bar_y()) } +} +/// Screen x of a popup of width `w` next to a side bar. +unsafe fn side_x(w: i32) -> i32 { + if i18n::style::side() == i18n::style::Side::Left { bar_h() + sc(8) } else { GetSystemMetrics(SM_CXSCREEN) - bar_h() - sc(8) - w } +} +/// Length of the bar's long axis: the screen height for a side bar, the width otherwise. +unsafe fn axis_len() -> i32 { + GetSystemMetrics(if vert() { SM_CYSCREEN } else { SM_CXSCREEN }) +} +/// Gap under the floating dock. +fn dock_gap() -> i32 { + if dock() { sc(8) } else { 0 } +} +/// Screen x and width of the bar: the whole screen, or the dock in the middle. +unsafe fn bar_x_w() -> (i32, i32) { + let cx = GetSystemMetrics(SM_CXSCREEN); + if dock() { + let w = (cx * 3 / 5).max(sc(720)).min(cx); + ((cx - w) / 2, w) + } else { + (0, cx) + } +} +/// Screen y of the bar's current top edge, slid away by the show/hide animation. +unsafe fn bar_y() -> i32 { + if at_top() { -bar_off() } else { bar_top() + bar_off() } +} +/// Screen y of a popup of height `h` next to the bar: above it, or below it when the bar is at the top. +unsafe fn pop_y(h: i32) -> i32 { + if vert() { GetSystemMetrics(SM_CYSCREEN) - sc(8) - h } else if at_top() { bar_h() + sc(8) } else { bar_top() - sc(8) - h } +} +const GOOD: u32 = winrust_common::style::GOOD; +const BAD: u32 = winrust_common::style::BAD; +const WARN: u32 = winrust_common::style::WARN; +const CALLBACK: u32 = WM_APP + 1; +const WM_MOUSELEAVE: u32 = 0x02A3; // not exported under the enabled features +const NO_WINDOW: u32 = 0x0800_0000; +const BAR_H: i32 = 40; +// hit-test results. Buttons (Start, pins, windows) are >= 0 in left-to-right order; tray apps are TAPP + index. +const NONE: i32 = -1; +const SEARCH: i32 = -10; +const TASKVIEW: i32 = -14; // Task View button (virtual desktops), right of search (#83) +const LEAD: i32 = 2; // slots before Start: search, Task View +const CLOCK: i32 = -4; +const LANG: i32 = -6; +const WIFI_I: i32 = -7; +const VOL_I: i32 = -8; +const BAT_I: i32 = -9; +const TAPP: i32 = -1000; +const SHOWDESK: i32 = -13; // the thin strip right of the clock: show desktop (#87) +const GEAR: i32 = -12; // the gear at the left end: the Style menu +const GEAR_X: (i32, i32) = (6, 36); // its left edge and width, before scaling (sc() is applied where used) +const POW_R: i32 = -15; // Restart button next to the clock (#173) +const POW_S: i32 = -16; // Shut down button +// The right group: the language label, then one pill with the wifi, the volume and (on a laptop) the battery with its +// percentage. layout() adds these up and paint() draws them at the same offsets, so the group is as wide as it draws. +const SYS_LANG: i32 = 42; // the language label's slot +const SYS_WIFI: i32 = 32; // the wifi icon's slot +const SYS_VOL: i32 = 22; // the volume glyph +const SYS_BAT_W: i32 = 22; // the battery itself +const SYS_BAT_PCT: i32 = 40; // the percentage next to it +const SYS_BAT: i32 = SYS_BAT_W + 8 + SYS_BAT_PCT; // 70: the battery and the percentage +const SYS_END: i32 = 2; // air after the last icon, inside the pill +const CLOCK_PAD: i32 = 10; // air on each side of the clock block +const CLOCK_MIN: i32 = 72; // a short date ("1/1/2026") must not make the block hug its edges +const SYS_GRP: i32 = -11; // hover key of the one pill around wifi + volume + battery (they open the same panel) +const WIN_START: u32 = WM_APP + 10; // posted by the keyboard hook: Win key pressed alone +const ALT_TAB: u32 = WM_APP + 11; // posted by the keyboard hook: Alt+Tab (wp 1 = Shift held: backwards) +const ALT_UP: u32 = WM_APP + 12; // posted by the keyboard hook: Alt released while switching (wp 1 = Esc: cancel) +static SWITCHING: AtomicBool = AtomicBool::new(false); // Alt+Tab switcher open (the hook thread reads it) +static FULLSCREEN: AtomicBool = AtomicBool::new(false); +static DESK_HIDE: AtomicBool = AtomicBool::new(false); // the desktop in front and the pointer away from the bar for 2 s +static WIN_ALONE: AtomicBool = AtomicBool::new(false); +static BAR: AtomicIsize = AtomicIsize::new(0); // the bar window, for the hook thread +const WIN_NUM: u32 = WM_APP + 15; // posted by the keyboard hook: Win+1..9 (wp 0..8) = the n-th button of the bar +const WIN_X: u32 = WM_APP + 17; // posted by the keyboard hook: Win+X = our power-user menu (start_menu) +const NEXT_LANG: u32 = WM_APP + 16; // posted by the keyboard hook: Win+Space with no explorer (wp 1 = Shift held: previous layout) +const TILE_WINDOWS: u32 = WM_APP + 19; // posted by the keyboard hook: Ctrl+Alt+T +const VOLKEY: u32 = WM_APP + 14; // posted by the keyboard hook: a volume key (wp 0 up, 1 down, 2 mute) +const WIN_V: u32 = WM_APP + 18; // posted by the keyboard hook: Win+V with no explorer (our clipboard history, #171) +const SNIP: u32 = WM_APP + 13; // posted by the keyboard hook: PrtSc / Win+Shift+S with no explorer to handle them +static EXPLORER_UP: AtomicBool = AtomicBool::new(true); // explorer's taskbar exists (it handles PrtSc itself then); refreshed by the bar + +struct Pin { + lnk: Vec, + target: String, // lower-case exe path, "" if unknown + args: String, // what the shortcut passes to it (browser profile), "" if none + aumid: String, // lower-case AppUserModelID the shortcut carries (a browser profile's own, #132), "" if none + icon: HICON, +} +struct Btn { + pin: Option, + wins: Vec, + icon: HICON, // the window's icon for unpinned buttons, looked up on refresh, not every animation frame +} + +/// One notification-area icon, as an app registered it through Shell_NotifyIcon (we own the "Shell_TrayWnd" they talk to). +struct TIcon { + hwnd: HWND, // the app's callback window + uid: u32, + guid: [u8; 16], // zero unless the app identifies the icon by GUID + icon: HICON, // our own copy + cb: u32, // uCallbackMessage + ver: u32, // NIM_SETVERSION value; >= 4 means the NOTIFYICON_VERSION_4 message format + hidden: bool, + tip: String, + key: String, // owner exe file name, lower-case: what the "keep on the bar" choice is stored under +} +const WM_COPYDATA: u32 = 0x4A; +#[repr(C)] +struct Cds { + dw: usize, + cb: u32, + p: *const u8, +} +static USAGE: Mutex>> = Mutex::new(None); // launches per shortcut name, lower-case + +fn appdata_file(name: &str) -> PathBuf { + PathBuf::from(std::env::var_os("APPDATA").unwrap_or_default()).join(name) +} +fn uses(name: &str) -> u32 { + USAGE + .lock() + .unwrap() + .get_or_insert_with(|| std::fs::read_to_string(appdata_file("topbar-usage.txt")).unwrap_or_default().lines().filter_map(|l| l.rsplit_once('\t')).filter_map(|(k, n)| Some((k.to_string(), n.parse().ok()?))).collect()) + .get(name) + .copied() + .unwrap_or(0) +} +/// Counts one launch of the shortcut at `path` (by file name, so the same app pinned and in Start counts together). +fn bump(path: &str) { + bump_name(&std::path::Path::new(path).file_stem().unwrap_or_default().to_string_lossy()); +} +/// Counts one launch of the app called `name` (Start search ranks by it). +fn bump_name(name: &str) { + let name = name.to_lowercase(); + uses(&name); // loads the file first + let mut g = USAGE.lock().unwrap(); + let m = g.as_mut().unwrap(); + *m.entry(name).or_insert(0) += 1; + let _ = std::fs::write(appdata_file("topbar-usage.txt"), m.iter().map(|(k, n)| format!("{k}\t{n}\n")).collect::()); +} +fn lnk_uses(lnk: &std::path::Path) -> u32 { + uses(&lnk.file_stem().unwrap_or_default().to_string_lossy().to_lowercase()) +} + +thread_local! { + static HOST: Cell = const { Cell::new(null_mut()) }; + static SKIP: RefCell> = const { RefCell::new(Vec::new()) }; // windows their app took off the taskbar (ITaskbarList::DeleteTab) + static TIPWND: Cell = const { Cell::new(null_mut()) }; + static SWWND: Cell = const { Cell::new(null_mut()) }; // the Alt+Tab switcher + static SW: RefCell<(Vec, usize)> = const { RefCell::new((Vec::new(), 0)) }; // its windows (z-order) and selection + static TIP: RefCell = const { RefCell::new(String::new()) }; + static PINS: RefCell> = const { RefCell::new(Vec::new()) }; + static BTNS: RefCell> = const { RefCell::new(Vec::new()) }; // [0] is always Start (pin None, no wins) + static BUTTON_ORDER: RefCell> = const { RefCell::new(Vec::new()) }; + static TAPPS: RefCell> = const { RefCell::new(Vec::new()) }; + static SHOWN: RefCell>> = const { RefCell::new(None) }; // tray icons kept on the bar (by exe); None = none: every tray icon lives in the chevron flyout + static TRAYFLY: Cell = const { Cell::new(null_mut()) }; + static TF_ANIM: Cell<(u64, i32, i32)> = const { Cell::new((0, 0, 0)) }; // tray flyout: when it opened, its final x, y + static FHOT: Cell = const { Cell::new(-1) }; + static HOT: Cell = const { Cell::new(NONE) }; + static ORDER: RefCell> = const { RefCell::new(Vec::new()) }; // unpinned windows in the order their buttons were added + static HV: RefCell> = RefCell::new(HashMap::new()); // hover fade per element: (0..1, last update ms) + static BUSY: Cell = const { Cell::new(false) }; // a fade is still running: the painter asks for another frame + static BAR_P: Cell = const { Cell::new(0.0) }; // bar slide: 0 = off screen, 1 = in place + static BAR_T: Cell = const { Cell::new(0) }; + static DESK_T: Cell = const { Cell::new(0) }; // last moment the bar had a reason to stay on the desktop + static SCALE: Cell = const { Cell::new(1.0) }; + static FS_WND: Cell = const { Cell::new(0) }; // the window last seen fullscreen (fullscreen_now) + static FS_OFF: Cell = const { Cell::new(0) }; // when a fullscreen window was last missing, ms (0 = it is there) + static OLD_STATE: Cell = const { Cell::new(ABS_ALWAYSONTOP as usize) }; + static BAT: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = no battery, on AC) + static VOL: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = unknown, muted) + static WIFI: Cell = const { Cell::new(-1) }; // signal quality 0..100, -1 = not on wifi + static INET: Cell = const { Cell::new(true) }; // Windows sees a way to the internet (any adapter) + static TICK: Cell = const { Cell::new(0) }; + static EP: RefCell> = const { RefCell::new(None) }; + static TB_MSG: Cell = const { Cell::new(0) }; // "TaskbarCreated" + static SH_MSG: Cell = const { Cell::new(0) }; // "SHELLHOOK": window events for the shell (we are the shell hook window without explorer) + static EXP_TRAY: Cell = const { Cell::new(null_mut()) }; // explorer's taskbar we registered with + static FLASH: RefCell> = const { RefCell::new(Vec::new()) }; // windows asking for attention (FlashWindowEx) until activated (#129) + static APP_FG: Cell = const { Cell::new(null_mut()) }; // last foreground window that is not ours: the language button acts on it + static LANG_TRY: Cell<(u32, usize, usize)> = const { Cell::new((0, 0, 0)) }; // (thread, layout before, layout asked for) of the last switch, checked by timer 7 + static BAR_WORK: Cell<(i32, i32, i32, i32)> = const { Cell::new((-1, -1, -1, -1)) }; // last work area reserved by place() +} + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain([0]).collect() +} +fn sc(v: i32) -> i32 { + (v as f32 * SCALE.get()) as i32 +} +/// Taskbar symbols use the chosen size; slots and hit targets stay unchanged. +fn icon_sc(v: i32) -> i32 { + sc((v as f32 * i18n::style::icon_size() as f32 / 100.0).round() as i32).max(1) +} +fn bar_h() -> i32 { + let d = [-6, 0, 8][i18n::style::bar_size() as usize % 3]; // small / normal / large + if vert() { sc(60 + d) } else { sc(BAR_H + d) } +} +/// The width of the right group: exactly what paint() draws at those offsets. A wider slot was a hole between the +/// volume icon and the clock (and a click on empty space opened the battery panel). +fn sys_w() -> i32 { + sc(SYS_LANG + SYS_WIFI + SYS_VOL + SYS_END + if BAT.get().0 >= 0 { SYS_BAT } else { 0 }) +} +/// Width and height of `s` in the font `f` of `dc`. +unsafe fn text_size(dc: HDC, f: HFONT, s: &str) -> (i32, i32) { + SelectObject(dc, f); + let w = wide(s); + let mut sz: SIZE = zeroed(); + GetTextExtentPoint32W(dc, w.as_ptr(), w.len() as i32 - 1, &mut sz); + (sz.cx, sz.cy) +} +/// The clock cell: the wider of the time and the date in the bar's own fonts (the ones it paints them with), with the +/// same air on both sides, so a narrow clock ("9:05") and a wide date sit the same in it. +fn clock_w() -> i32 { + unsafe { + let [_, f_small, _, f_bold] = bar_fonts(); + let dc = CreateCompatibleDC(null_mut()); + let (tm, dt) = clock_texts(); + let w = clock_cell_w(text_size(dc, f_bold, &tm).0, text_size(dc, f_small, &dt).0); + DeleteDC(dc); + w + } +} +/// The cell of the clock: the wider of its two lines plus the same air on both sides. +fn clock_cell_w(tw: i32, dw: i32) -> i32 { + (tw.max(dw) + 2 * sc(CLOCK_PAD)).max(sc(CLOCK_MIN)) +} +/// Screen y of the bar's top edge when it is in place (bottom of the primary monitor, or its top in the tiling style). +unsafe fn bar_top() -> i32 { + if at_top() { 0 } else { GetSystemMetrics(SM_CYSCREEN) - bar_h() - dock_gap() } +} + +// ---------- taskbar / appbar ---------- + +const FCELL: i32 = 38; + +/// (columns, window width, window height) for the current number of icons. +fn fly_size() -> (usize, i32, i32) { + let n = over_idx().len().max(1); + let cols = n.min(6); + (cols, sc(FCELL) * cols as i32 + sc(16), sc(FCELL) * n.div_ceil(cols) as i32 + sc(16) + sc(26)) +} + +unsafe fn fly_toggle() { + let w = TRAYFLY.get(); + if IsWindowVisible(w) != 0 { + ShowWindow(w, SW_HIDE); + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it + return; + } + let (_, fw, fh) = fly_size(); + FHOT.set(-1); + let scr = GetSystemMetrics(SM_CXSCREEN); + let (bx, bw) = bar_x_w(); + let cx = bx + layout(if vert() { axis_len() } else { bw }).apps.0 + sc(12); // above the chevron + SetWindowRgn(w, CreateRoundRectRgn(0, 0, fw + 1, fh + 1, rr(12), rr(12)), 1); + let (x, y) = if vert() { (side_x(fw), (cx - fh / 2).min(GetSystemMetrics(SM_CYSCREEN) - fh - sc(8)).max(sc(8))) } else { ((cx - fw / 2).min(scr - fw - sc(8)).max(sc(8)), pop_y(fh)) }; + TF_ANIM.set((now_ms(), x, y)); + SetLayeredWindowAttributes(w, 0, 0, LWA_ALPHA); // tf_step fades it in + SetWindowPos(w, HWND_TOPMOST, x, y + tf_slide(0.0), fw, fh, SWP_SHOWWINDOW); + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it + SetTimer(w, 1, 15, None); + SetForegroundWindow(w); // so that WM_ACTIVATE tells us when the user clicks elsewhere +} + +/// How far the tray flyout still is from its place at opening progress `e` (0..1): it rises toward the bar's far side. +unsafe fn tf_slide(e: f32) -> i32 { + let d = ((1.0 - e) * sc(14) as f32) as i32; + if at_top() { -d } else { d } +} + +/// Opening progress 0..1 of the tray flyout, eased, and of its icon `n` (each one starts 25 ms after the previous). +unsafe fn tf_progress(n: i32) -> f32 { + let age = now_ms().saturating_sub(TF_ANIM.get().0) as f32; + ease(((age - 25.0 * n as f32) / 200.0).clamp(0.0, 1.0)) +} + +unsafe extern "system" fn fly_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + let cell_at = |lp: LPARAM| -> i32 { + let (x, y) = ((lp & 0xffff) as i16 as i32 - sc(8), ((lp >> 16) & 0xffff) as i16 as i32 - sc(8)); + let (cols, _, _) = fly_size(); + let n = over_idx().len() as i32; + if x < 0 || y < 0 || x >= sc(FCELL) * cols as i32 { + return -1; + } + let i = (y / sc(FCELL)) * cols as i32 + x / sc(FCELL); + if i < n { i } else { -1 } + }; + match msg { + WM_PAINT => { + let mut ps: PAINTSTRUCT = zeroed(); + let wdc = BeginPaint(hwnd, &mut ps); + let mut r: RECT = zeroed(); + GetClientRect(hwnd, &mut r); + // drawn off screen first: painting every animation frame straight to the window flickered (#199) + let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, r.right, r.bottom)); + let screen_bmp = SelectObject(dc, bmp); + fill(dc, r, pal().line, sc(12)); + fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, pal().bg, sc(12)); + let (cols, _, _) = fly_size(); + let f = tip_font(); + let of = SelectObject(dc, f); + SetBkMode(dc, TRANSPARENT as i32); + SetTextColor(dc, pal().dim); + let mut tip = String::new(); + let over = over_idx(); + TAPPS.with_borrow(|t| { + for (n, ti) in over.iter().map(|&i| &t[i]).enumerate() { + let (x, y) = (sc(8) + (n % cols) as i32 * sc(FCELL), sc(8) + (n / cols) as i32 * sc(FCELL)); + if FHOT.get() == n as i32 { + fill(dc, RECT { left: x, top: y, right: x + sc(FCELL), bottom: y + sc(FCELL) }, pal().hover, sc(6)); + tip = ti.tip.clone(); + } + if !ti.icon.is_null() { + // 16 logical px, the small-icon size apps make theirs for: any other size gets resampled and blurs + DrawIconEx(dc, x + sc(19) - sc(16) / 2, y + sc(18) - sc(16) / 2, ti.icon, sc(16), sc(16), 0, null_mut(), DI_NORMAL); + } + } + }); + if tip.is_empty() { + tip = if over.is_empty() { t!("Больше значков нет", "No more icons", ja: "これ以上アイコンはありません", pt: "Não há mais ícones", zh: "没有更多图标").into() } else { t!("Средняя кнопка: перенести на панель", "Middle click: move to the bar", ja: "中クリック: バーに移動", pt: "Clique do meio: mover para a barra", zh: "中键单击:移到任务栏").into() }; + } + let mut tr = RECT { left: sc(10), top: r.bottom - sc(26), right: r.right - sc(10), bottom: r.bottom - sc(4) }; + DrawTextW(dc, wide(&tip).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_SINGLELINE | DT_END_ELLIPSIS | DT_VCENTER); + SelectObject(dc, of); + DeleteObject(f); + BitBlt(wdc, 0, 0, r.right, r.bottom, dc, 0, 0, SRCCOPY); + SelectObject(dc, screen_bmp); + DeleteObject(bmp); + DeleteDC(dc); + EndPaint(hwnd, &ps); + 0 + } + WM_ERASEBKGND => 1, + WM_MOUSEMOVE => { + let mut tme = TRACKMOUSEEVENT { cbSize: size_of::() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 }; + TrackMouseEvent(&mut tme); + if FHOT.replace(cell_at(lp)) != cell_at(lp) { + InvalidateRect(hwnd, null(), 0); + } + 0 + } + WM_MOUSELEAVE => { + FHOT.set(-1); + InvalidateRect(hwnd, null(), 0); + 0 + } + WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => { + let i = cell_at(lp); + let ti = over_idx().get(i.max(0) as usize).and_then(|&k| TAPPS.with_borrow(|t| t.get(k).map(|x| ((x.hwnd, x.uid, x.cb, x.ver), x.key.clone())))); + if let (true, Some((t, key))) = (i >= 0, ti) { + if msg == WM_MBUTTONDOWN { + toggle_shown(&key); + InvalidateRect(hwnd, null(), 0); + } else { + ShowWindow(hwnd, SW_HIDE); + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it + tray_click(t, msg == WM_LBUTTONDOWN); + } + } + 0 + } + WM_ACTIVATE if wp & 0xffff == 0 => { + ShowWindow(hwnd, SW_HIDE); + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); // the bar's chevron turns with it + 0 + } + WM_TIMER => { + let (_, x, y) = TF_ANIM.get(); + let e = tf_progress(0); + SetLayeredWindowAttributes(hwnd, 0, (255.0 * e) as u8, LWA_ALPHA); + SetWindowPos(hwnd, null_mut(), x, y + tf_slide(e), 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + InvalidateRect(hwnd, null(), 0); + if e >= 1.0 { + KillTimer(hwnd, 1); + } + 0 + } + _ => DefWindowProcW(hwnd, msg, wp, lp), + } +} + +// ---------- tray tooltip: a small popup under the icon after the mouse rests on it ---------- + +unsafe fn tip_font() -> HFONT { + CreateFontW(-sc(12), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide(ui_face()).as_ptr()) +} + +unsafe extern "system" fn tip_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if msg != WM_PAINT { + return DefWindowProcW(hwnd, msg, wp, lp); + } + let mut ps: PAINTSTRUCT = zeroed(); + let dc = BeginPaint(hwnd, &mut ps); + let mut r: RECT = zeroed(); + GetClientRect(hwnd, &mut r); + fill(dc, r, pal().line, sc(8)); + fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, pal().bg, sc(8)); + let f = tip_font(); + let of = SelectObject(dc, f); + SetBkMode(dc, TRANSPARENT as i32); + SetTextColor(dc, pal().text); + let mut tr = RECT { left: sc(8), top: sc(5), right: r.right - sc(8), bottom: r.bottom - sc(5) }; + TIP.with_borrow(|s| DrawTextW(dc, wide(s).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_WORDBREAK)); + SelectObject(dc, of); + DeleteObject(f); + EndPaint(hwnd, &ps); + 0 +} + +/// Tooltip text of a bar element ("" = none). +unsafe fn tip_text(h: i32) -> String { + match h { + SEARCH => "Search".into(), + TASKVIEW => t!("Представление задач", "Task View", ja: "タスク ビュー", pt: "Visão de Tarefas").into(), + POW_R => t!("Перезагрузка", "Restart", ja: "再起動", pt: "Reiniciar", zh: "重启").into(), + POW_S => t!("Завершение работы", "Shut down", ja: "シャットダウン", pt: "Desligar", zh: "关机").into(), + 0 => "Start".into(), + TAPP => "Hidden icons".into(), + GEAR => t!("Стиль", "Style", ja: "スタイル", pt: "Estilo", zh: "样式").into(), + SHOWDESK => t!("Показать рабочий стол", "Show desktop", ja: "デスクトップを表示", pt: "Mostrar a área de trabalho", zh: "显示桌面").into(), + CLOCK => { + let mut t: SYSTEMTIME = zeroed(); + GetLocalTime(&mut t); + let mut b = [0u16; 80]; + let n = GetDateFormatW(0x0400, 2, &t, null(), b.as_mut_ptr(), 80).max(1) as usize - 1; // DATE_LONGDATE + String::from_utf16_lossy(&b[..n]) + } + LANG => tf!("Язык ввода: {}", "Input language: {}", ja: "入力言語: {}", pt: "Idioma de entrada: {}", zh: "输入语言:{}", layout_names(layouts().1).0), + WIFI_I => match net() { + Link::Wifi(q) => tf!("Wi‑Fi · сигнал {q}%", "Wi‑Fi · signal {q}%", ja: "Wi‑Fi · 信号 {q}%", pt: "Wi‑Fi · sinal {q}%", zh: "Wi‑Fi · 信号 {q}%"), + Link::NoInternet(_) => t!("Wi‑Fi подключён, но интернета нет", "Wi‑Fi connected, no internet", ja: "Wi‑Fi 接続済み、インターネットなし", pt: "Wi‑Fi conectado, sem internet", zh: "Wi‑Fi 已连接,无 Internet").into(), + Link::Cable => t!("Интернет по кабелю", "Internet over a cable", ja: "有線のインターネット", pt: "Internet por cabo", zh: "有线网络").into(), + Link::Offline => t!("Нет подключения к сети", "Not connected", ja: "未接続", pt: "Não conectado", zh: "未连接").into(), + }, + VOL_I => vol_tip(), + BAT_I => match BAT.get() { + (p, ac) if p >= 0 => format!("Battery {p}%{}", if ac { " · plugged in" } else { "" }), + _ => String::new(), + }, + t if t > TAPP && t < TAPP + 100 => bar_idx().get((t - TAPP - 1) as usize).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|i| i.tip.clone()))).unwrap_or_default(), + i if i >= 1 => { + let (wins, lnk) = BTNS.with_borrow(|b| b.get(i as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| wstr_of(&x.lnk))))))).unwrap_or_default(); + let title = |w: HWND| { + let mut b = [0u16; 256]; + let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize; + String::from_utf16_lossy(&b[..n]) + }; + match (wins.first(), lnk) { + (Some(&w), _) if wins.len() > 1 => format!("{} (+{})", title(w), wins.len() - 1), + (Some(&w), _) => title(w), + (None, Some(l)) => std::path::Path::new(&l).file_stem().unwrap_or_default().to_string_lossy().into(), + _ => String::new(), + } + } + _ => String::new(), + } +} + +fn vol_tip() -> String { + match VOL.get() { + (v, false) if v >= 0 => format!("Volume {v}%"), + (_, true) => "Muted".into(), + _ => "Volume".into(), + } +} + +/// Shows `s` in a small rounded popup above the bar, centered on screen x `cx`. +unsafe fn show_tip(s: String, cx: i32) { + let tw = TIPWND.get(); + if s.is_empty() || tw.is_null() { + return; + } + let (dc, f) = (GetDC(tw), tip_font()); + let of = SelectObject(dc, f); + let mut r = RECT { left: 0, top: 0, right: sc(280), bottom: 0 }; + DrawTextW(dc, wide(&s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_NOPREFIX | DT_WORDBREAK); + SelectObject(dc, of); + DeleteObject(f); + ReleaseDC(tw, dc); + let (w, h) = (r.right + sc(16), r.bottom + sc(10)); + TIP.set(s); + SetWindowRgn(tw, CreateRoundRectRgn(0, 0, w + 1, h + 1, rr(8), rr(8)), 1); + if vert() { + let y = (cx - h / 2).min(GetSystemMetrics(SM_CYSCREEN) - h - sc(4)).max(sc(4)); + SetWindowPos(tw, HWND_TOPMOST, side_x(w), y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); + InvalidateRect(tw, null(), 1); + return; + } + let x = (cx - w / 2).min(GetSystemMetrics(SM_CXSCREEN) - w - sc(4)).max(sc(4)); + SetWindowPos(tw, HWND_TOPMOST, x, if at_top() { bar_h() - bar_off() + sc(6) } else { bar_top() + bar_off() - h - sc(6) }, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); + InvalidateRect(tw, null(), 1); +} + +// ---------- Alt+Tab switcher: a grid of the open windows with live previews, most recently used first (#92) ---------- + +const SW_CLIP_TIMER: usize = 9; + +thread_local! { + static SW_MON: Cell = const { Cell::new(RECT { left: 0, top: 0, right: 0, bottom: 0 }) }; // the monitor it is shown on + static SW_CARDS: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; // card rects, DWM previews + // where the pointer was when the switcher opened: a window appearing under a still pointer gets a WM_MOUSEMOVE, + // which must not pick the card under it (#183, #116); None once the pointer really moved + static SW_PT: Cell> = const { Cell::new(None) }; + // a game's cursor clip when the switcher opened, and its window: put back on close when we return to it + static SW_CLIP: Cell> = const { Cell::new(None) }; +} + +unsafe fn cursor() -> (i32, i32) { + let mut p: POINT = zeroed(); + GetCursorPos(&mut p); + (p.x, p.y) +} + +/// A clip smaller than the whole virtual desktop: a game (or another app) has confined the pointer. +unsafe fn clipped(c: &RECT) -> bool { + c.left > GetSystemMetrics(SM_XVIRTUALSCREEN) + || c.top > GetSystemMetrics(SM_YVIRTUALSCREEN) + || c.right < GetSystemMetrics(SM_XVIRTUALSCREEN) + GetSystemMetrics(SM_CXVIRTUALSCREEN) + || c.bottom < GetSystemMetrics(SM_YVIRTUALSCREEN) + GetSystemMetrics(SM_CYVIRTUALSCREEN) +} + +unsafe fn alt_tab(back: bool) { + let sw = SWWND.get(); + if IsWindowVisible(sw) == 0 { + let mut v: Vec = Vec::new(); + EnumWindows(Some(collect), &mut v as *mut _ as LPARAM); // z-order: the active window first, then the one before it + // per monitor: only the windows on the active window's monitor (when there is another one to switch to), shown on that monitor + let mut mon = RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }; + if i18n::style::alttab_per_monitor() && !v.is_empty() { + let of = |w: HWND| MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST); + let m0 = of(v[0]); + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(m0, &mut mi) != 0 { + let same: Vec = v.iter().copied().filter(|&w| of(w) == m0).collect(); + if same.len() > 1 { + v = same; + mon = mi.rcMonitor; + } + } + } + let n = v.len(); + if n == 0 { + return SWITCHING.store(false, Relaxed); + } + SW.set((v, if n == 1 { 0 } else if back { n - 1 } else { 1 })); + SW_MON.set(mon); + SW_PT.set(Some(cursor())); + // a game in mouse-look clips the pointer to a pixel at its center and re-clips it while it keeps the focus, so the + // pointer snaps back the moment it leaves the cards. Take the focus (as the system switcher does) so the game lets + // the pointer go anywhere, and release the clip too in case it keeps it without the focus. + let mut c: RECT = zeroed(); + let fg = GetForegroundWindow(); + SW_CLIP.set(None); + if GetClipCursor(&mut c) != 0 && clipped(&c) { + SW_CLIP.set(Some((c, fg))); + ClipCursor(null()); + SetTimer(sw, SW_CLIP_TIMER, 10, None); + } + sw_layout(sw); + if SW_CLIP.get().is_some() { + let ex = GetWindowLongW(sw, GWL_EXSTYLE) as u32; + SetWindowLongW(sw, GWL_EXSTYLE, (ex & !WS_EX_NOACTIVATE) as i32); + force_fg(sw); + } + } else { + SW.with_borrow_mut(|(v, i)| *i = if back { (*i + v.len() - 1) % v.len() } else { (*i + 1) % v.len() }); + } + InvalidateRect(sw, null(), 0); +} + +/// Sizes the switcher for its windows (centered on its monitor) and puts the live previews on the cards. +unsafe fn sw_layout(sw: HWND) { + let mon = SW_MON.get(); + let (scr, sch) = (mon.right - mon.left, mon.bottom - mon.top); + let pad = sc(thumbs::GAP) + sc(4); + let wins = SW.with_borrow(|(v, _)| v.clone()); + let (mut rects, tw, th) = thumbs::grid(wins.len(), scr * 9 / 10 - 2 * pad, sch * 8 / 10 - 2 * pad, sc(thumbs::CARD_W * 3 / 2), sc(thumbs::CARD_H * 3 / 2), sc(thumbs::GAP)); // bigger than hover previews (#190) + rects.iter_mut().for_each(|r| *r = RECT { left: r.left + pad, top: r.top + pad, right: r.right + pad, bottom: r.bottom + pad }); + let (w, h) = (tw + 2 * pad, th + 2 * pad); + SW_CARDS.with_borrow_mut(|(_, ids)| thumbs::unregister(sw, ids)); + SetWindowRgn(sw, CreateRoundRectRgn(0, 0, w + 1, h + 1, rr(18), rr(18)), 1); + SetWindowPos(sw, HWND_TOPMOST, mon.left + (scr - w) / 2, mon.top + (sch - h) / 2, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); + let ids = thumbs::register(sw, &wins, &rects); + SW_CARDS.set((rects, ids)); +} + +/// Delete (or a click on ×) in the switcher: closes the selected window and takes it off the list. +unsafe fn alt_close() { + let w = SW.with_borrow_mut(|(v, i)| { + let w = v.get(*i).copied(); + if w.is_some() { + v.remove(*i); + *i = (*i).min(v.len().saturating_sub(1)); + } + w + }); + if let Some(w) = w { + PostMessageW(w, WM_CLOSE, 0, 0); + } + if SW.with_borrow(|(v, _)| v.is_empty()) { + alt_done(true); + SWITCHING.store(false, Relaxed); + } else { + sw_layout(SWWND.get()); + InvalidateRect(SWWND.get(), null(), 0); + } +} + +/// Alt released: switch to the selected window (restored if minimized). Esc: just close. +unsafe fn alt_done(cancel: bool) { + ShowWindow(SWWND.get(), SW_HIDE); + KillTimer(SWWND.get(), SW_CLIP_TIMER); + SW_CARDS.with_borrow_mut(|(r, ids)| { + thumbs::unregister(SWWND.get(), ids); + r.clear(); + }); + let (v, i) = SW.take(); + let target = v.get(i).copied().filter(|_| !cancel); + if let Some(w) = target { + bring(w); + } + // we took the focus and made the switcher activatable because a game was clipping the pointer: put the style back, + // return the focus to that game on Esc, and give it its mouse-look clip back when we stay on / return to it + if let Some((c, fg)) = SW_CLIP.take() { + let sw = SWWND.get(); + let ex = GetWindowLongW(sw, GWL_EXSTYLE) as u32; + SetWindowLongW(sw, GWL_EXSTYLE, (ex | WS_EX_NOACTIVATE) as i32); + if cancel { + force_fg(fg); + } + if cancel || target == Some(fg) { + ClipCursor(&c); + } + } +} + +unsafe extern "system" fn sw_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + let (x, y) = ((lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); + let at = || SW_CARDS.with_borrow(|(r, _)| thumbs::card_at(r, x, y)); + match msg { + WM_PAINT => SW.with_borrow(|(v, sel)| SW_CARDS.with_borrow(|(r, ids)| thumbs::paint(hwnd, v, r, ids, Some(*sel)))), + WM_MOUSEACTIVATE => return MA_NOACTIVATE as isize, + // the pointer picks a card, a click switches to it, a middle click or × closes it, the wheel steps through + WM_MOUSEMOVE => { + if SW_PT.get().is_some_and(|p| p == cursor()) { + return 0; + } + SW_PT.set(None); + if let Some(k) = at() { + if SW.with_borrow_mut(|(_, i)| std::mem::replace(i, k)) != k { + InvalidateRect(hwnd, null(), 0); + } + } + } + WM_LBUTTONUP | WM_MBUTTONUP => { + let Some(k) = at() else { return 0 }; + SW.with_borrow_mut(|(_, i)| *i = k); + let c = SW_CARDS.with_borrow(|(r, _)| thumbs::close_rect(&r[k])); + if msg == WM_MBUTTONUP || (x >= c.left && x < c.right && y >= c.top && y < c.bottom) { + alt_close(); + } else { + SWITCHING.store(false, Relaxed); + if GetAsyncKeyState(VK_MENU as i32) < 0 { + keys(&[0xE8]); // Alt is still down: its release must not open the menu bar of the app we switch to + } + alt_done(false); + } + } + WM_MOUSEWHEEL => alt_tab((wp >> 16) as i16 > 0), + WM_TIMER if wp == SW_CLIP_TIMER => { ClipCursor(null()); } + _ => return DefWindowProcW(hwnd, msg, wp, lp), + } + 0 +} + +unsafe fn hide_tip(bar: HWND) { + KillTimer(bar, 2); + ShowWindow(TIPWND.get(), SW_HIDE); +} + +unsafe fn set_state(hwnd: HWND, state: usize) { + let mut ab: APPBARDATA = zeroed(); + ab.cbSize = size_of::() as u32; + ab.hWnd = hwnd; + ab.lParam = state as isize; + SHAppBarMessage(ABM_SETSTATE, &mut ab); +} + +/// Hides the real taskbar and sets it to auto-hide so Windows gives its work-area strip back. +unsafe fn hide_taskbar() { + set_state(tray()[0], ABS_AUTOHIDE as usize); + for t in ours_to_hide() { + ShowWindow(t, SW_HIDE); + } +} + +/// Explorer's taskbars the bar replaces: the other monitors' ones only while it has a bar of its own there. +unsafe fn ours_to_hide() -> Vec { + let mut t = tray(); + t.truncate(if second::enabled() { usize::MAX } else { 1 }); + t.retain(|t| !t.is_null()); + t +} + +fn taskbar_state_file() -> PathBuf { + appdata_file("topbar-taskbar-state.txt") +} + +/// The taskbar mode (always on top / auto-hide bits) the user had before the bar hid it. It lives in a file so that +/// `--restore` (reshell's watchdog after a crash) puts back the user's own mode, not the Windows default. +fn saved_taskbar_state() -> Option { + std::fs::read_to_string(taskbar_state_file()).ok()?.trim().parse().ok() +} + +fn forget_taskbar_state() { + let _ = std::fs::remove_file(taskbar_state_file()); +} + +/// At start: the mode to give back later. A file left by a crashed run wins (explorer's current mode is then our own +/// auto-hide); otherwise the current mode is the user's and is written down. Without explorer's taskbar: the default. +unsafe fn remember_taskbar_state() -> usize { + if let Some(s) = saved_taskbar_state() { + return s; + } + let tb = tray()[0]; + if tb.is_null() { + return ABS_ALWAYSONTOP as usize; + } + let mut ab: APPBARDATA = zeroed(); + ab.cbSize = size_of::() as u32; + ab.hWnd = tb; + let s = SHAppBarMessage(ABM_GETSTATE, &mut ab); + let _ = std::fs::write(taskbar_state_file(), s.to_string()); + s +} + +unsafe fn show_taskbar(state: usize) { + let tb = tray()[0]; + if tb.is_null() { + // No explorer taskbar (rs-shell): start explorer to bring back the native taskbar (#302). + let _ = winrust_common::proc::start_shell_explorer(); + return; + } + set_state(tb, state); + for t in tray().into_iter().filter(|t| !t.is_null()) { + ShowWindow(t, SW_SHOWNA); + } +} + +// explorer re-shows its taskbar on hover / restart; hide it again +unsafe fn hide_taskbar_if_shown() { + if ours_to_hide().into_iter().any(|t| IsWindowVisible(t) != 0) { + hide_taskbar(); + } +} + +/// Reserves a strip on the bar's screen edge so maximized windows stay clear of it. +unsafe fn place(hwnd: HWND) { + apply_opacity(hwnd); + let (cx, cy) = (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); + let mut ab: APPBARDATA = zeroed(); + ab.cbSize = size_of::() as u32; + ab.hWnd = hwnd; + // the reserved strip: the bar itself plus the dock's gap under it + // the dock reserves nothing: maximized windows take the whole screen and the dock slides away over them + let strip = if dock() || i18n::style::autohide() { 0 } else { bar_h() }; + if vert() { + let left = i18n::style::side() == i18n::style::Side::Left; + ab.uEdge = if left { ABE_LEFT } else { ABE_RIGHT }; + ab.rc = if left { RECT { left: 0, top: 0, right: strip, bottom: cy } } else { RECT { left: cx - strip, top: 0, right: cx, bottom: cy } }; + SHAppBarMessage(ABM_QUERYPOS, &mut ab); + if left { ab.rc.left = sane_edge(ab.rc.left, cx) } else { ab.rc.right = cx - sane_edge(cx - ab.rc.right, cx) } + if left { ab.rc.right = ab.rc.left + strip } else { ab.rc.left = ab.rc.right - strip } + } else if at_top() { + ab.uEdge = ABE_TOP; + ab.rc = RECT { left: 0, top: 0, right: cx, bottom: strip }; + SHAppBarMessage(ABM_QUERYPOS, &mut ab); + ab.rc.top = sane_edge(ab.rc.top, cy); + ab.rc.bottom = ab.rc.top + strip; + } else { + ab.uEdge = ABE_BOTTOM; + ab.rc = RECT { left: 0, top: cy - strip, right: cx, bottom: cy }; + SHAppBarMessage(ABM_QUERYPOS, &mut ab); + ab.rc.bottom = cy - sane_edge(cy - ab.rc.bottom, cy); + ab.rc.top = ab.rc.bottom - strip; + } + SHAppBarMessage(ABM_SETPOS, &mut ab); + // No explorer (rs-shell / rust-explorer): nobody handles appbars, so set the work area ourselves. Without it maximized + // windows slide under the bar and, covering the whole monitor, count as "fullscreen" and hide the bar. + // Also with Explorer: it does not always honour the appbar when its own taskbar is hidden (#89). + let work = if vert() { if ab.uEdge == ABE_LEFT { RECT { left: ab.rc.right, top: 0, right: cx, bottom: cy } } else { RECT { left: 0, top: 0, right: ab.rc.left, bottom: cy } } } else if at_top() { RECT { left: 0, top: ab.rc.bottom, right: cx, bottom: cy } } else { RECT { left: 0, top: 0, right: cx, bottom: ab.rc.top } }; + BAR_WORK.set((work.left, work.top, work.right, work.bottom)); + set_work_area(work); + let (x, w) = bar_x_w(); + // the dock is a pill; the other styles a plain strip + SetWindowRgn(hwnd, if dock() { CreateRoundRectRgn(0, 0, w + 1, bar_h() + 1, bar_h(), bar_h()) } else { null_mut() }, 1); + if vert() { + SetWindowPos(hwnd, HWND_TOPMOST, bar_x(), 0, bar_h(), cy, SWP_NOACTIVATE | SWP_NOZORDER); + } else { + // SWP_NOZORDER: the bar is topmost from its creation on. Raising it again here (this runs on every display change, which + // a game switching into fullscreen causes) put it over the game and knocked that out of fullscreen, in a loop. + SetWindowPos(hwnd, HWND_TOPMOST, x, bar_y(), w, bar_h(), SWP_NOACTIVATE | SWP_NOZORDER); + } + InvalidateRect(hwnd, null(), 0); + second::sync(); +} + +/// How far from its screen edge the bar may sit after ABM_QUERYPOS (room left for other appbars). Explorer sometimes answers +/// with a far-off edge (a stale or huge appbar entry), and the work area then shrank to half the screen (#106): past a +/// quarter of the screen, or off it, the bar goes back to the edge. +fn sane_edge(offset: i32, size: i32) -> i32 { + if (0..=size / 4).contains(&offset) { offset } else { 0 } +} + +unsafe fn set_work_area(mut want: RECT) { + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + GetMonitorInfoW(MonitorFromRect(&want, MONITOR_DEFAULTTONEAREST), &mut mi); + let cur = mi.rcWork; + if (cur.left, cur.top, cur.right, cur.bottom) != (want.left, want.top, want.right, want.bottom) { + // SPIF_SENDCHANGE waits for every top-level window (took ~3 s, #94): set quietly and post the notice instead + SystemParametersInfoW(SPI_SETWORKAREA, 0, &mut want as *mut _ as *mut _, 0); + PostMessageW(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETWORKAREA as usize, 0); + EnumWindows(Some(fit_maximized), &want as *const RECT as isize); + } +} + +/// Explorer and display changes can reset the work area after the bar has already claimed its edge. +unsafe fn work_area_drifted() -> bool { + let want = BAR_WORK.get(); + if want.0 < 0 { return false; } + let mut current: RECT = zeroed(); + SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut current as *mut _ as *mut _, 0) != 0 + && (current.left, current.top, current.right, current.bottom) != want +} + +/// A window that was already maximized keeps its old height when the work area shrinks: trim it (size only, no restore). +unsafe extern "system" fn fit_maximized(h: HWND, lp: isize) -> i32 { + let want = &*(lp as *const RECT); + // the work area belongs to one monitor: a window maximized on another one would be cut to a sliver + if IsWindowVisible(h) == 0 || IsZoomed(h) == 0 || MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST) != MonitorFromRect(want, MONITOR_DEFAULTTONEAREST) { + return 1; + } + let mut r: RECT = zeroed(); + GetWindowRect(h, &mut r); + let f =GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER); // a maximized window overhangs by its border + let n = RECT { left: r.left.max(want.left - f), top: r.top.max(want.top - f), right: r.right.min(want.right + f), bottom: r.bottom.min(want.bottom + f) }; + if (n.left, n.top, n.right, n.bottom) != (r.left, r.top, r.right, r.bottom) && n.right > n.left && n.bottom > n.top { + SetWindowPos(h, null_mut(), n.left, n.top, n.right - n.left, n.bottom - n.top, SWP_NOZORDER | SWP_NOACTIVATE); + } + fit_normal(h); + 1 +} + +/// Shrink `n` (a restore rectangle) into `work`, keeping it as large as still fits. Returns true if it changed. +fn clamp_rect(n: &mut RECT, work: RECT) -> bool { + let maxw = work.right - work.left; + let maxh = work.bottom - work.top; + let nw = (n.right - n.left).min(maxw); + let nh = (n.bottom - n.top).min(maxh); + let x = n.left.max(work.left).min(work.right - nw); + let y = n.top.max(work.top).min(work.bottom - nh); + if (n.left, n.top, n.right, n.bottom) == (x, y, x + nw, y + nh) { + return false; + } + *n = RECT { left: x, top: y, right: x + nw, bottom: y + nh }; + true +} + +/// `rcNormalPosition` is in workspace coordinates: shifted by what bars take on the top and left. +fn workspace(work: RECT, monitor: RECT) -> RECT { + let (dx, dy) = (work.left - monitor.left, work.top - monitor.top); + RECT { left: work.left - dx, top: work.top - dy, right: work.right - dx, bottom: work.bottom - dy } +} + +/// A window maximized while the work area was the whole monitor keeps that size as its restore rectangle, so +/// restoring it later leaves it past the screen edge and under the bar (#268). Clamp a maximized window's normal +/// placement into its monitor's work area; the next restore then lands inside it. Only maximized windows: a +/// borderless fullscreen game or a window spanning monitors is not zoomed and is left alone. +unsafe fn fit_normal(w: HWND) { + if IsWindowVisible(w) == 0 || IsIconic(w) != 0 || IsZoomed(w) == 0 || IsHungAppWindow(w) != 0 { + return; + } + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { + return; + } + let mut wp: WINDOWPLACEMENT = zeroed(); + wp.length = size_of::() as u32; + if GetWindowPlacement(w, &mut wp) == 0 { + return; + } + if clamp_rect(&mut wp.rcNormalPosition, workspace(mi.rcWork, mi.rcMonitor)) { + wp.showCmd = 8; // SW_SHOWNA: SW_SHOWMAXIMIZED would steal the focus + wp.flags |= 4; // WPF_ASYNCWINDOWPLACEMENT: a busy app must not stall the bar + let _ = SetWindowPlacement(w, &wp); + } +} + +/// A window restored from maximized keeps the maximized frame (the monitor plus its invisible resize border), which +/// leaves it past the screen edge and under the bar (#268); being restored, fit_normal no longer sees it. Shrink exactly +/// that shape to the work area: larger than the monitor on both axes but by no more than the border. A window spanning +/// monitors or one genuinely larger is much bigger and left alone. +unsafe fn fit_restored(w: HWND) { + let framed = GetWindowLongW(w, GWL_STYLE) as u32 & (WS_CAPTION | WS_THICKFRAME) == WS_CAPTION | WS_THICKFRAME; + if !framed || IsWindowVisible(w) == 0 || IsIconic(w) != 0 || IsZoomed(w) != 0 || IsHungAppWindow(w) != 0 { + return; + } + let mut r: RECT = zeroed(); + if GetWindowRect(w, &mut r) == 0 { + return; + } + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { + return; + } + let (ww, wh) = (r.right - r.left, r.bottom - r.top); + let (mw, mh) = (mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top); + if ww < mw + 8 || wh < mh + 8 || ww > mw + 32 || wh > mh + 32 { + return; + } + let work = mi.rcWork; + SetWindowPos(w, null_mut(), work.left, work.top, work.right - work.left, work.bottom - work.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS); +} + +// ---------- data: windows, pins, tray apps, volume, wifi, battery ---------- + +thread_local! { + static EXE_CACHE: RefCell> = RefCell::new(HashMap::new()); // hwnd -> (pid, exe): refresh runs twice a second +} + +unsafe fn exe_of(h: HWND) -> String { + let mut pid = 0u32; + GetWindowThreadProcessId(h, &mut pid); + if let Some(e) = EXE_CACHE.with_borrow(|c| c.get(&(h as usize)).filter(|(p, e)| *p == pid && !e.is_empty()).map(|(_, e)| e.clone())) { + return e; + } + let p = OpenProcess(0x1000, 0, pid); // PROCESS_QUERY_LIMITED_INFORMATION + if p.is_null() { + return String::new(); + } + let (mut b, mut n) = ([0u16; 520], 520u32); + let ok = QueryFullProcessImageNameW(p, 0, b.as_mut_ptr(), &mut n); + CloseHandle(p); + let exe = if ok == 0 { String::new() } else { String::from_utf16_lossy(&b[..n as usize]).to_lowercase() }; + EXE_CACHE.with_borrow_mut(|c| { + if c.len() > 512 { + c.clear(); // closed windows never leave on their own + } + c.insert(h as usize, (pid, exe.clone())); + }); + exe +} + +unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> i32 { + let ex = GetWindowLongW(h, GWL_EXSTYLE) as u32; + let mut cloaked = 0u32; // UWP windows that are suspended / on another desktop are visible but cloaked + DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as *mut _, 4); + let mut cls = [0u16; 32]; + let n = GetClassNameW(h, cls.as_mut_ptr(), 32) as usize; + let ours = String::from_utf16_lossy(&cls[..n]) == "topbar"; + let skipped = SKIP.with_borrow(|s| s.contains(&h)); + if IsWindowVisible(h) != 0 && GetWindow(h, GW_OWNER).is_null() && cloaked == 0 && !ours && GetWindowTextLengthW(h) > 0 && (ex & WS_EX_TOOLWINDOW == 0 || ex & WS_EX_APPWINDOW != 0) && !skipped { + (*(lp as *mut Vec)).push(h); + } + 1 +} + +/// "%windir%\explorer.exe" -> "C:\Windows\explorer.exe" (unknown variables stay as they are). +/// A Run-box command ("cmd", "%appdata%", "control") as a real path the shell can draw an icon for: environment +/// variables expanded, a bare name looked up on PATH like Win+R does. Anything else comes back as it was. +unsafe fn resolve_cmd(s: &str) -> String { + use windows_sys::Win32::Storage::FileSystem::SearchPathW; + let e = expand_env(s); + if e.contains(['\\', '/', ':']) { + return e; + } + let mut b = [0u16; 520]; + let n = SearchPathW(null(), wide(&e).as_ptr(), wide(".exe").as_ptr(), b.len() as u32, b.as_mut_ptr(), null_mut()) as usize; + if n > 0 && n < b.len() { String::from_utf16_lossy(&b[..n]) } else { e } +} + +fn expand_env(s: &str) -> String { + let parts: Vec<&str> = s.split('%').collect(); + let mut out = String::new(); + for (i, p) in parts.iter().enumerate() { + match std::env::var(p) { + // odd pieces sit between two '%': a variable name + Ok(v) if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&v), + _ if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&format!("%{p}%")), + _ if i % 2 == 1 => out.push_str(&format!("%{p}")), // a lone '%' with nothing to close it + _ => out.push_str(p), + } + } + out +} + +/// Target exe of a shortcut (lower-case), "" if it has none (e.g. Store apps). +unsafe fn lnk_target(lnk: &[u16]) -> String { + (|| -> Option { + let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; + sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; + let mut b = [0u16; 520]; + sl.GetPath(&mut b, null_mut(), 0).ok()?; + let path = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]); + if !path.is_empty() { + return Some(path.to_lowercase()); + } + // shell links without a file target (the File Explorer pin) usually take their icon from the app's exe: + // "%windir%\explorer.exe,0" -> match the app's windows by that exe + let mut idx = 0; + sl.GetIconLocation(&mut b, &mut idx).ok()?; + let icon = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]); + let icon = expand_env(&icon).to_lowercase(); + icon.ends_with(".exe").then_some(icon) + })() + .unwrap_or_default() +} + +/// The target's own icon: SHGetFileInfo on the .lnk adds the shortcut arrow, so that is only the fallback. +unsafe fn lnk_icon(lnk: &[u16], target: &str) -> HICON { + let ic = item_icon(&resolve_cmd(&wstr_of(lnk)), icon_px()); + if !ic.is_null() { + return ic; + } + let mut icon: HICON = null_mut(); + if !target.is_empty() { + ExtractIconExW(wide(target).as_ptr(), 0, null_mut(), &mut icon, 1); + } + if icon.is_null() { + let mut sfi: SHFILEINFOW = zeroed(); + SHGetFileInfoW(lnk.as_ptr(), 0, &mut sfi, size_of::() as u32, SHGFI_ICON | SHGFI_SMALLICON); + icon = sfi.hIcon; + } + icon +} + +/// Size app icons are drawn at. Icons are loaded at exactly this size: +/// a 32 px icon stretched by DrawIconEx comes out jagged. +fn icon_px() -> i32 { + icon_sc(24) +} + +/// Icon of a file, shortcut (its target's icon, no arrow) or shell item ("shell:AppsFolder\") rendered by the +/// shell at exactly `px` pixels, the way Explorer gets its icons. Null if the shell has none. +unsafe fn item_icon(path: &str, px: i32) -> HICON { + use windows::Win32::{ + Foundation::SIZE, + UI::Shell::{IShellItem, IShellItemImageFactory, SHCreateItemFromParsingName, SIIGBF_ICONONLY}, + }; + let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide(path).as_ptr()), None) else { return null_mut() }; + let Ok(f) = item.cast::() else { return null_mut() }; + let Ok(bmp) = f.GetImage(SIZE { cx: px, cy: px }, SIIGBF_ICONONLY) else { return null_mut() }; + let color = bmp.0 as HBITMAP; + let mask = CreateBitmap(px, px, 1, 1, null()); // ignored: the 32-bit colour bitmap carries the alpha + let mut ii = ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color }; + let ic = CreateIconIndirect(&mut ii); + DeleteObject(mask); + DeleteObject(color); + ic +} + +thread_local! { + static EXE_ICONS: RefCell> = RefCell::new(HashMap::new()); // crisp icons of running apps, by exe +} + +/// Recreate cached app icons after the size changes so they remain crisp. +unsafe fn reload_icons() { + PINS.with_borrow_mut(|pins| { + for pin in pins.iter_mut() { + let icon = lnk_icon(&pin.lnk, &pin.target); + if !pin.icon.is_null() { DestroyIcon(pin.icon); } + pin.icon = icon; + } + }); + EXE_ICONS.with_borrow_mut(|icons| { + for icon in icons.values() { + if !icon.is_null() { DestroyIcon(*icon); } + } + icons.clear(); + }); + refresh_buttons(); +} + +/// Icon of a running window for its bar button: its exe's icon at the exact size (cached), else what the window reports. +/// Apps run by a generic host (Store apps in ApplicationFrameHost, Java games in javaw, scripts in python...) would all +/// get the host's icon: those keep the window's own icon. +unsafe fn win_icon(w: HWND) -> HICON { + let exe = exe_of(w); + let own = |w| { + let i = icon_of(w); + if i.is_null() { LoadIconW(null_mut(), IDI_APPLICATION) } else { i } // never a blank button (#91) + }; + if exe.is_empty() || is_host(&exe) { + // a Store app lives in ApplicationFrameHost: the shell draws the icon of the app id of the frame's CoreWindow + if exe.ends_with("applicationframehost.exe") { + let ic = store_icon(w); + if !ic.is_null() { + return ic; + } + } + return own(w); + } + let ic = EXE_ICONS.with_borrow_mut(|m| *m.entry(exe.clone()).or_insert_with(|| item_icon(&exe, icon_px()))); + if ic.is_null() { own(w) } else { ic } +} + +fn is_host(exe: &str) -> bool { + const HOSTS: [&str; 8] = ["applicationframehost.exe", "javaw.exe", "java.exe", "pythonw.exe", "python.exe", "mmc.exe", "rundll32.exe", "dllhost.exe"]; + HOSTS.iter().any(|h| exe.rsplit('\\').next() == Some(*h)) +} + +/// Icon of the Store app behind an ApplicationFrameHost window (cached by app id), null if it cannot be found. +unsafe fn store_icon(frame: HWND) -> HICON { + use windows_sys::Win32::Storage::Packaging::Appx::GetApplicationUserModelId; + let core = FindWindowExW(frame, null_mut(), wide("Windows.UI.Core.CoreWindow").as_ptr(), null()); + if core.is_null() { + return null_mut(); + } + let mut pid = 0u32; + GetWindowThreadProcessId(core, &mut pid); + let p = OpenProcess(windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if p.is_null() { + return null_mut(); + } + let mut buf = [0u16; 256]; + let mut len = buf.len() as u32; + let ok = GetApplicationUserModelId(p, &mut len, buf.as_mut_ptr()) == 0; + CloseHandle(p); + if !ok { + return null_mut(); + } + let id = format!(r"shell:AppsFolder\{}", wstr_of(&buf)); + EXE_ICONS.with_borrow_mut(|m| *m.entry(id.clone()).or_insert_with(|| item_icon(&id, icon_px()))) +} + +/// "c:\program files\windowsapps\claude_5.1.0.0_x64__pzs8\app\claude.exe" -> ("claude_pzs8", "app\claude.exe"): +/// the package family (name + publisher id, the same across versions) and the path inside the package folder. +fn msix_family(target: &str) -> Option<(String, String)> { + let l = target.to_lowercase(); + let (_, tail) = l.split_once(r"\windowsapps\")?; + let (folder, rest) = tail.split_once('\\')?; + let parts: Vec<&str> = folder.split('_').collect(); // name_version_arch_resourceid_publisherid + (parts.len() == 5).then(|| (format!("{}_{}", parts[0], parts[4]), rest.to_string())) +} + +/// A pin of a Store (MSIX) app points into its versioned package folder, which is gone after every app update +/// ("Windows cannot find ...\Claude_5.11492.5.0_x64__...\claude.exe"). Re-points the .lnk to the installed version. +/// Returns the new target (lower-case), None if the target exists or is not in a package. +unsafe fn fix_msix_pin(lnk: &[u16], target: &str) -> Option { + use windows_sys::Win32::Storage::Packaging::Appx::{GetPackagePathByFullName, GetPackagesByPackageFamily}; + if target.is_empty() || std::path::Path::new(target).exists() { + return None; + } + let (family, rest) = msix_family(target)?; + let fam = wide(&family); + let (mut count, mut len) = (0u32, 0u32); + GetPackagesByPackageFamily(fam.as_ptr(), &mut count, null_mut(), &mut len, null_mut()); // sizes only + if count == 0 { + return None; // the app was uninstalled + } + let (mut names, mut buf) = (vec![null_mut::(); count as usize], vec![0u16; len as usize]); + if GetPackagesByPackageFamily(fam.as_ptr(), &mut count, names.as_mut_ptr(), &mut len, buf.as_mut_ptr()) != 0 { + return None; + } + let mut path = [0u16; 520]; + let mut plen = path.len() as u32; + if GetPackagePathByFullName(names[0], &mut plen, path.as_mut_ptr()) != 0 { + return None; + } + let new = std::path::Path::new(&wstr_of(&path)).join(&rest); + if !new.exists() { + return None; + } + let new = new.to_string_lossy().to_lowercase(); + let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; + let pf = sl.cast::().ok()?; + pf.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; + sl.SetPath(PCWSTR(wide(&new).as_ptr())).ok()?; + pf.Save(PCWSTR(lnk.as_ptr()), true).ok()?; + Some(new) +} + +fn pin_order_file() -> PathBuf { + appdata_file("topbar-pin-order.txt") +} + +/// The pins' current order, as the .lnk file names, one per line. +unsafe fn save_pin_order() { + let text: String = PINS.with_borrow(|p| p.iter().map(|x| format!("{} +", std::path::Path::new(&wstr_of(&x.lnk)).file_name().unwrap_or_default().to_string_lossy())).collect()); + let _ = std::fs::write(pin_order_file(), text); +} + +/// What makes two pins the same app: the target exe and its arguments, or the app id of a Store app (no file target). +/// ("", "") when neither is known. +unsafe fn pin_key(lnk: &[u16]) -> (String, String) { + let target = lnk_target(lnk); + if !target.is_empty() { + return (target, lnk_args(lnk).to_lowercase()); + } + let id = lnk_aumid(lnk).to_lowercase(); + (if id.is_empty() { id } else { format!("aumid:{id}") }, String::new()) +} + +/// The AppUserModelID a shortcut carries (Store and web app pins), "" if none. +unsafe fn lnk_aumid(lnk: &[u16]) -> String { + use windows::{core::GUID, Win32::{Foundation::PROPERTYKEY, System::Com::{CoTaskMemFree, StructuredStorage::PropVariantToStringAlloc}, UI::Shell::PropertiesSystem::IPropertyStore}}; + (|| -> Option { + let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; + sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; + let ps: IPropertyStore = sl.cast().ok()?; + let key = PROPERTYKEY { fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3), pid: 5 }; // PKEY_AppUserModel_ID + let v = ps.GetValue(&key).ok()?; + let p = PropVariantToStringAlloc(&v).ok()?; + let s = p.to_string().ok(); + CoTaskMemFree(Some(p.0 as *const _)); + s + })() + .unwrap_or_default() +} + +/// The AppUserModelID a window carries (Store apps, installed web apps), "" if none. +unsafe fn win_aumid(h: HWND) -> String { + use windows::{core::GUID, Win32::{Foundation::{HWND as WHWND, PROPERTYKEY}, System::Com::{CoTaskMemFree, StructuredStorage::PropVariantToStringAlloc}, UI::Shell::PropertiesSystem::{IPropertyStore, SHGetPropertyStoreForWindow}}}; + (|| -> Option { + let ps: IPropertyStore = SHGetPropertyStoreForWindow(WHWND(h)).ok()?; + let key = PROPERTYKEY { fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3), pid: 5 }; // PKEY_AppUserModel_ID + let p = PropVariantToStringAlloc(&ps.GetValue(&key).ok()?).ok()?; + let s = p.to_string().ok(); + CoTaskMemFree(Some(p.0 as *const _)); + s + })() + .unwrap_or_default() + .to_lowercase() +} + +/// Taskbar pins the user removed from our bar: Windows still lists them in `FavoritesResolve`, they must not come back. +fn unpinned_file() -> PathBuf { + appdata_file(r"topbar-taskband\unpinned.txt") +} + +fn key_line(k: &(String, String)) -> String { + format!("{}|{}", k.0, k.1) +} + +/// Windows keeps every taskbar pin, in order, as serialized shortcuts in `Taskband\FavoritesResolve` (also those with no +/// .lnk in the TaskBar folder: Steam, Chrome app shortcuts, #93). Each one is written out as a .lnk of our own, named by +/// target and arguments so the name stays the same between runs. Returns (key = target + args, file) in the taskbar's order. +unsafe fn taskband_links() -> Vec<((String, String), PathBuf)> { + use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_BINARY, RegGetValueW}; + let mut n = 0u32; + let (key, val) = (wide(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband"), wide("FavoritesResolve")); + if RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), val.as_ptr(), RRF_RT_REG_BINARY, null_mut(), null_mut(), &mut n) != 0 || n == 0 { + return vec![]; + } + let mut blob = vec![0u8; n as usize]; + if RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), val.as_ptr(), RRF_RT_REG_BINARY, null_mut(), blob.as_mut_ptr().cast(), &mut n) != 0 { + return vec![]; + } + // every entry starts with the ShellLink header (size 0x4C + the shell link CLSID) + const HEAD: [u8; 20] = [0x4C, 0, 0, 0, 0x01, 0x14, 0x02, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46]; + let starts: Vec = (0..blob.len().saturating_sub(HEAD.len())).filter(|&i| blob[i..i + HEAD.len()] == HEAD).collect(); + let dir = appdata_file("topbar-taskband"); + let _ = std::fs::create_dir_all(&dir); + // copies from an earlier run: a pin removed in Windows since must not linger + std::fs::read_dir(&dir).into_iter().flatten().flatten().filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("lnk"))).for_each(|e| { + let _ = std::fs::remove_file(e.path()); + }); + let tmp = dir.join("tmp.lnk"); + let gone: Vec = std::fs::read_to_string(unpinned_file()).unwrap_or_default().lines().map(str::to_string).collect(); + let mut out = vec![]; + for (k, &a) in starts.iter().enumerate() { + let b = starts.get(k + 1).copied().unwrap_or(blob.len()); + if std::fs::write(&tmp, &blob[a..b]).is_err() { + continue; + } + let key = pin_key(&wide(&tmp.to_string_lossy())); + if key.0.is_empty() || gone.contains(&key_line(&key)) { + continue; + } + // most entries point at a .lnk (the pin's own in the TaskBar folder, or one in ImplicitAppShortcuts for a browser + // profile): that file is the pin; one whose file is gone (File Explorer replaced by rust-explorer) is no pin at all. + // The unpinned list holds the resolved key (unpin() reads it from that same file), so it is checked after resolving. + if key.0.ends_with(".lnk") { + let real = PathBuf::from(&key.0); + let rk = pin_key(&wide(&real.to_string_lossy())); + if real.is_file() && !rk.0.is_empty() && !gone.contains(&key_line(&rk)) { + out.push((rk, real)); + } + continue; + } + // a readable, stable file name: the exe's name (or the app id's) plus a hash of the whole key + let base = key.0.strip_prefix("aumid:").unwrap_or_else(|| std::path::Path::new(&key.0).file_stem().and_then(|s| s.to_str()).unwrap_or("")); + let stem: String = base.chars().map(|c| if c.is_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(40).collect(); + let h = key_line(&key).bytes().fold(5381u32, |h, c| h.wrapping_mul(33) ^ c as u32); + let file = dir.join(format!("{stem}-{h:08x}.lnk")); + if std::fs::copy(&tmp, &file).is_ok() { + out.push((key, file)); + } + } + let _ = std::fs::remove_file(tmp); + out +} + +/// Pinned apps (the .lnk files Windows keeps for the taskbar) with their icons and target exe. +unsafe fn load_pins() { + let Some(appdata) = std::env::var_os("APPDATA") else { return }; + let dir = PathBuf::from(appdata).join(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"); + let mut files: Vec<_> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("lnk"))).collect(); + files.sort(); + files.sort_by_key(|f| std::cmp::Reverse(lnk_uses(f))); // most used first (stable: ties stay alphabetical) + // the Windows taskbar's own order (#90) and the pins that have no file in the folder (#93) + let fav = taskband_links(); + let key_of = |f: &PathBuf| pin_key(&wide(&f.to_string_lossy())); + let mut keys: Vec<_> = files.iter().map(key_of).collect(); + for (k, f) in &fav { + if !keys.contains(k) { + keys.push(k.clone()); + files.push(f.clone()); + } + } + let at: HashMap = files.iter().cloned().zip(&keys).map(|(f, k)| (f, fav.iter().position(|(fk, _)| fk == k).unwrap_or(usize::MAX))).collect(); + files.sort_by_key(|f| at[f]); // stable: pins the taskbar does not list keep the most-used order, after the listed ones + // an order the user set (Move left / right) wins; pins not in it keep the order above, after the listed ones + let order: Vec = std::fs::read_to_string(pin_order_file()).unwrap_or_default().lines().map(|l| l.to_lowercase()).collect(); + files.sort_by_key(|f| order.iter().position(|n| *n == f.file_name().unwrap_or_default().to_string_lossy().to_lowercase()).unwrap_or(usize::MAX)); + for f in files { + let lnk = wide(&f.to_string_lossy()); + let target = lnk_target(&lnk); + let target = fix_msix_pin(&lnk, &target).unwrap_or(target); + let icon = lnk_icon(&lnk, &target); + let args = lnk_args(&lnk); + let aumid = lnk_aumid(&lnk).to_lowercase(); + PINS.with_borrow_mut(|p| p.push(Pin { lnk, target, args, aumid, icon })); + } + // once: a File Explorer button for the installed file manager (the marker keeps an unpinned one gone) + let marker = appdata_file("topbar-explorer-pin.txt"); + let rx = std::env::var_os("ProgramFiles").map(|pf| PathBuf::from(pf).join(r"rust-explorer\rust-explorer.exe")); + if let Some(rx) = rx.filter(|rx| rx.is_file() && !marker.exists()) { + pin_exe(&rx.to_string_lossy(), ""); + let _ = std::fs::write(marker, "1"); + } +} + +/// The exe the File Explorer pin stands for (lower-case): its icon location, "%windir%\explorer.exe". +fn file_explorer_exe() -> String { + expand_env(r"%windir%\explorer.exe").to_lowercase() +} + +/// The windows of WinRust's file manager belong to the File Explorer pin when there is one: that pin is what the user clicks +/// to open "Explorer" here, and only windows of explorer.exe matched it, so its button never showed them (a minimized +/// window looked gone and the click started a second one). Without such a pin they keep their own exe's button. +fn as_pinned_exe(exe: &str, explorer: &str, explorer_pinned: bool) -> String { + if explorer_pinned && exe.ends_with(r"\rust-explorer\rust-explorer.exe") { explorer.to_string() } else { exe.to_string() } +} + +/// `...\app-1.0.9001\discord.exe` without the version folder: Squirrel apps (Discord, Slack...) move on every update. +fn unversioned(exe: &str) -> String { + exe.split('\\').filter(|p| !p.strip_prefix("app-").is_some_and(|v| v.starts_with(|c: char| c.is_ascii_digit()))).collect::>().join(r"\") +} + +/// A window of `exe` (with AppUserModelID `id`) belongs to a pin of another exe (#198): the same AppUserModelID, a pin of +/// Squirrel's launcher (`Update.exe --processStart App.exe`) or of an older version folder. All lower-case but `args`. +fn pin_of_other_exe(target: &str, args: &str, aumid: &str, exe: &str, id: &str) -> bool { + if !aumid.is_empty() && aumid == id { + return true; + } + let args = args.to_lowercase(); + if let (Some(dir), Some(at)) = (target.strip_suffix(r"\update.exe"), args.find("--processstart")) { + let name = args[at + "--processstart".len()..].trim_start_matches(['=', ' ', '"']).split(['"', ' ']).next().unwrap_or(""); + return !name.is_empty() && exe.strip_prefix(dir).is_some_and(|r| r.starts_with('\\') && r.rsplit('\\').next() == Some(name)); + } + !exe.is_empty() && unversioned(target) == unversioned(exe) +} + +fn refresh_buttons() { + let mut wins: Vec = Vec::new(); + unsafe { EnumWindows(Some(collect), &mut wins as *mut _ as LPARAM) }; + let mut btns = vec![Btn { pin: None, wins: vec![], icon: null_mut() }]; + PINS.with_borrow(|pins| btns.extend((0..pins.len()).map(|i| Btn { pin: Some(i), wins: vec![], icon: null_mut() }))); + let mut loose: Vec = Vec::new(); + let explorer = file_explorer_exe(); + let explorer_pinned = PINS.with_borrow(|p| p.iter().any(|p| p.target == explorer)); + for w in wins { + let exe = unsafe { exe_of(w) }; + let exe = as_pinned_exe(&exe, &explorer, explorer_pinned); + // pins of one exe (two browser profiles, #132) tell their windows apart by AppUserModelID; a pin or window without one + // takes any window of its exe + let pin = PINS.with_borrow(|p| { + let mine: Vec = (0..p.len()).filter(|&i| !p[i].target.is_empty() && p[i].target == exe).collect(); + let id = unsafe { win_meta(w).0 }; + if mine.is_empty() { + return (0..p.len()).find(|&i| pin_of_other_exe(&p[i].target, &p[i].args, &p[i].aumid, &exe, &id)); + } + mine.iter().copied().find(|&i| !id.is_empty() && p[i].aumid == id).or_else(|| mine.iter().copied().find(|&i| id.is_empty() || p[i].aumid.is_empty())) + }); + match pin { + Some(i) => btns[1 + i].wins.push(w), + None => loose.push(w), + } + } + // EnumWindows lists by z-order, so clicking a window would jump its button to the front: keep the order they first appeared in + let mut keys: Vec = vec![String::new(); btns.len()]; // keys[i] belongs to btns[i]; "" matches nothing + ORDER.with_borrow_mut(|o| { + o.retain(|w| loose.contains(w)); + o.extend(loose.iter().filter(|w| !o.contains(w)).copied().collect::>()); + for &w in o.iter() { + // windows of one app share a button (a click then offers the list); generic hosts (Store apps, java...) stay apart (#90) + // the window's own AppUserModelID is part of the key: a web app installed from Brave runs as brave.exe too (#118, #117) + let exe = unsafe { exe_of(w) }; + let key = format!("{exe}|{}", unsafe { win_meta(w).0 }); + let same = (!exe.is_empty() && !is_host(&exe)).then(|| keys.iter().position(|k| *k == key)).flatten(); + match same { + Some(i) => btns[i].wins.push(w), + None => { + btns.push(Btn { pin: None, wins: vec![w], icon: unsafe { win_meta(w).1 } }); + keys.push(key); + } + } + } + }); + let keys: Vec = btns.iter().skip(1).filter_map(key_for_button).collect(); + BUTTON_ORDER.with_borrow_mut(|order| { + order.retain(|key| keys.contains(key)); + for key in &keys { if !order.contains(key) { order.push(key.clone()); } } + btns[1..].sort_by_key(|b| key_for_button(b).and_then(|key| order.iter().position(|x| *x == key)).unwrap_or(usize::MAX)); + }); + BTNS.set(btns); +} + +thread_local! { + // hwnd -> (pid, when read, AppUserModelID, icon): the AUMID is a COM call and a host app's icon up to two 40 ms + // WM_GETICON round trips, too much for every refresh; re-read after META_TTL (apps set both shortly after start) + static META: RefCell> = RefCell::new(HashMap::new()); +} +const META_TTL: u64 = 4000; + +unsafe fn win_meta(w: HWND) -> (String, HICON) { + let mut pid = 0u32; + GetWindowThreadProcessId(w, &mut pid); + let now = now_ms(); + if let Some(v) = META.with_borrow(|m| m.get(&(w as usize)).filter(|e| e.0 == pid && now.saturating_sub(e.1) < META_TTL).map(|e| (e.2.clone(), e.3))) { + return v; + } + let v = (win_aumid(w), win_icon(w)); + META.with_borrow_mut(|m| { + if m.len() > 512 { + m.clear(); // closed windows never leave on their own + } + m.insert(w as usize, (pid, now, v.0.clone(), v.1)); + }); + v +} + +/// A minimized window that Windows left as a caption stub on the desktop (it sits at the bottom left with its restore / +/// maximize / close buttons) goes off screen, as explorer's taskbar would have done. Restoring it is unaffected. +unsafe fn hide_stub(w: HWND) { + let mut r: RECT = zeroed(); + if IsIconic(w) != 0 && GetWindowRect(w, &mut r) != 0 && r.left > -30000 { + SetWindowPos(w, null_mut(), -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } +} + +fn refresh() { + refresh_windows(); + refresh_status(); +} + +/// The buttons: on window events (win_event) and every few seconds as a safety net. +fn refresh_windows() { + refresh_buttons(); + BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).for_each(|&w| unsafe { hide_stub(w); fit_normal(w); fit_restored(w) })); +} + +/// Everything polled once a second: battery, volume, wifi, explorer, dead tray icons. +fn refresh_status() { + let n = TICK.get(); + TICK.set(n + 1); + unsafe { + let mut p: SYSTEM_POWER_STATUS = zeroed(); + let ok = GetSystemPowerStatus(&mut p) != 0 && p.BatteryFlag & 128 == 0 && p.BatteryLifePercent <= 100; + BAT.set(if ok { (p.BatteryLifePercent as i32, p.ACLineStatus == 1) } else { (-1, false) }); + read_volume(); + let up = !find_other("Shell_TrayWnd").is_null(); + if EXPLORER_UP.swap(up, Relaxed) && !up { + place(BAR.load(Relaxed) as HWND); // Explorer (started for Settings) is gone and took the reserved strip with it + // icons that apps put into Explorer's (hidden) tray went with it: ask every app to register again, now with us. + // The empty-tray check below misses this when some icons already reached the bar. + announce(); + } + if TAPPS.with_borrow(|t| t.is_empty()) && n % 4 == 2 { + announce(); // no icons yet (apps started before us, or explorer restarted): ask them to register again + } + if n % 3 == 0 { + read_wifi(); + } + } + unsafe { + // icons of apps that died without NIM_DELETE + TAPPS.with_borrow_mut(|t| { + t.retain(|x| { + let alive = IsWindow(x.hwnd) != 0; + if !alive { + DestroyIcon(x.icon); + } + alive + }) + }); + // explorer re-raises its own Shell_TrayWnd now and then; ours must stay in front so apps keep finding it first + SetWindowPos(HOST.get(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } +} + +// ---------- layout / hit-testing ---------- + +// ---------- Restart and Shut down on the bar (#173): one pill between the system group and the clock ---------- + +fn power_off_marker() -> PathBuf { + appdata_file("topbar-no-power.txt") +} + +/// The buttons of the pill; none when switched off in the bar's settings (#208), and the pill takes no room then. +fn power_keys() -> &'static [i32] { + if power_off_marker().exists() { &[] } else { &[POW_R, POW_S] } +} + +pub(crate) fn power_shown() -> bool { + !power_keys().is_empty() +} + +pub(crate) fn set_power_shown(on: bool) { + let _ = if on { std::fs::remove_file(power_off_marker()) } else { std::fs::write(power_off_marker(), "1") }; +} + +/// Restart or shut down after a confirmation, so a stray click does not end the session. +unsafe fn power_click(key: i32) { + let (q, arg) = if key == POW_R { + (t!("Перезагрузить компьютер?", "Restart the computer?", ja: "コンピューターを再起動しますか?", pt: "Reiniciar o computador?", zh: "要重启计算机吗?"), "/r") + } else { + (t!("Выключить компьютер?", "Shut down the computer?", ja: "コンピューターをシャットダウンしますか?", pt: "Desligar o computador?", zh: "要关闭计算机吗?"), "/s") + }; + if MessageBoxW(BAR.load(Relaxed) as HWND, wide(q).as_ptr(), wide("WinRust").as_ptr(), MB_YESNO | MB_ICONQUESTION | MB_TOPMOST | MB_SETFOREGROUND) == IDYES { + let _ = Command::new("shutdown.exe").args([arg, "/t", "0"]).creation_flags(NO_WINDOW).spawn(); + } +} + +/// Draws the power buttons; `cell(start, len)` is the button's rectangle along the bar. +unsafe fn paint_power(dc: HDC, l: &Layout, hot: i32, f_glyph: HFONT, cell: impl Fn(i32, i32) -> RECT) { + let pill = cell(l.power.0, l.power.1 - l.power.0); + fill(dc, pill, mix(pal().bg, pal().hover, 0.6), sc(8)); + SelectObject(dc, f_glyph); + for (i, &k) in power_keys().iter().enumerate() { + let rc = cell(l.power.0 + i as i32 * sc(32), sc(32)); + glow(dc, k, hot == k, rc, mix(pal().bg, pal().hover, 0.6), mix(pal().hover, pal().accent, 0.35), sc(8)); + text(dc, if k == POW_R { "\u{E777}" } else { "\u{E7E8}" }, rc, pal().text, DT_CENTER); + } +} + +struct Layout { + gear_x: i32, // Style/Bar settings gear: far left normally, or right of Start when start_left is on + start_x: i32, // Start (Windows) button: far left corner when start_left is on, or in the main group + x0: i32, // first slot of the main group: Search, Task View, then Start (unless start_left) and apps + bw: i32, + gap: i32, + power: (i32, i32), + apps: (i32, i32), + sys: (i32, i32), + wid: (i32, i32), // the mods' widgets, between the tray icons and the system group + clock: (i32, i32), +} + +impl Layout { + fn btn_pos(&self, i: i32) -> i32 { + if i == 0 { + self.start_x + } else { + let lead = if i18n::style::start_left() { LEAD - 1 } else { LEAD }; + self.x0 + (i + lead) * (self.bw + self.gap) + } + } +} + +#[derive(Clone, PartialEq, Eq)] +enum DragButton { Pin(Vec), Window(isize) } +struct ButtonDrag { button: DragButton, start_x: i32, start_y: i32, moved: bool } +thread_local! { static BUTTON_DRAG: RefCell> = const { RefCell::new(None) }; } + +fn move_item(items: &mut Vec, from: usize, to: usize) -> bool { + if from >= items.len() || to >= items.len() || from == to { return false; } + let item = items.remove(from); + items.insert(to, item); + true +} + +fn button_key(index: i32) -> Option { + if index < 1 { return None; } + BTNS.with_borrow(|b| b.get(index as usize).and_then(key_for_button)) +} + +fn key_for_button(button: &Btn) -> Option { + match button.pin { + Some(i) => PINS.with_borrow(|pins| pins.get(i).map(|p| DragButton::Pin(p.lnk.clone()))), + None => button.wins.first().map(|w| DragButton::Window(*w as isize)), + } +} + +fn save_button_order() { + BUTTON_ORDER.with_borrow(|order| { + let pins = order.iter().filter_map(|key| match key { DragButton::Pin(path) => Some(std::path::Path::new(&wstr_of(path)).file_name().unwrap_or_default().to_string_lossy().into_owned()), _ => None }).collect::>().join("\n"); + let _ = std::fs::write(appdata_file("topbar-pin-order.txt"), pins); + }); +} + +fn reorder_buttons(from: DragButton, to: DragButton) { + let changed = BUTTON_ORDER.with_borrow_mut(|order| { + if let (Some(from), Some(to)) = (order.iter().position(|x| *x == from), order.iter().position(|x| *x == to)) { + move_item(order, from, to) + } else { + false + } + }); + if changed { + let pins: Vec> = BUTTON_ORDER.with_borrow(|order| order.iter().filter_map(|key| match key { DragButton::Pin(path) => Some(path.clone()), _ => None }).collect()); + PINS.with_borrow_mut(|items| items.sort_by_key(|item| pins.iter().position(|p| *p == item.lnk).unwrap_or(usize::MAX))); + refresh_buttons(); + } +} + +unsafe fn drag_target(hwnd: HWND, x: i32, y: i32) -> Option { + let mut rect: RECT = zeroed(); + GetClientRect(hwnd, &mut rect); + let (axis, length) = if vert() { (y, rect.bottom) } else { (x, rect.right) }; + let layout = layout(length); + let count = BTNS.with_borrow(|b| b.len()) as i32; + let lead = if i18n::style::start_left() { LEAD - 1 } else { LEAD }; // the same slots as Layout::btn_pos + drag_slot(axis, layout.x0, layout.bw, layout.gap, count, layout.apps.0, lead).and_then(button_key) +} + +/// The button under `axis`: button i sits in slot i + `lead` from x0 (Layout::btn_pos); Start (0) is never a target. +fn drag_slot(axis: i32, x0: i32, bw: i32, gap: i32, count: i32, apps_left: i32, lead: i32) -> Option { + if count <= 1 || bw <= 0 || gap < 0 || axis < x0 || axis >= apps_left { return None; } + Some(((axis - x0 + gap / 2) / (bw + gap) - lead).clamp(1, count - 1)) +} + +fn layout(w: i32) -> Layout { + let gap = sc(4); + let clock = (w - sc(6) - clock_w(), w - sc(6)); + let power = (clock.0 - sc(4) - sc(32) * power_keys().len() as i32, clock.0 - sc(4)); + let sys = (power.0 - sc(4) - sys_w(), power.0 - sc(4)); + let wid = (sys.0 - widgets::width(), sys.0); + let apps = (wid.0 - sc(24) * tray_count() as i32, wid.0); + let margin = (w - apps.0) + sc(8); // keep the button group centered and clear of both sides + let sl = i18n::style::start_left(); + let btns_len = BTNS.with_borrow(|b| b.len()) as i32; + let total_n = btns_len + LEAD; // + the search and Task View slots + let bw = (((w - 2 * margin + gap) / total_n.max(1)) - gap).clamp(sc(16), sc(44 + [-6, 0, 8][i18n::style::bar_size() as usize % 3])); + let group_n = total_n - i32::from(sl); + // centered on search + (Start if not pinned left) + pins only: opening an unpinned window adds a button on the right instead of shifting left + let fixed = (PINS.with_borrow(|p| p.len()) as i32 + LEAD + if sl { 0 } else { 1 }).min(group_n); + // ...but never so far right that the windows' buttons run into the tray: then the whole row shifts left + let right_limit = w - margin - (group_n * (bw + gap) - gap); + let centered = (w - (fixed * (bw + gap) - gap)) / 2; + let (start_left_x, gear_x) = if sl { + let sx = sc(GEAR_X.0); + (sx, sx + bw + gap) + } else { + (0, sc(GEAR_X.0)) + }; + let left_min = gear_x + sc(GEAR_X.1 + 6); + let x0 = if i18n::style::align_left() { 0 } else { centered }.min(right_limit).max(left_min); // clear of the gear (and Start if pinned left) + let start_x = if sl { start_left_x } else { x0 + LEAD * (bw + gap) }; + Layout { gear_x, start_x, x0, bw, gap, power, apps, sys, wid, clock } +} + +unsafe fn hit(hwnd: HWND, x: i32, y: i32) -> i32 { + let mut r: RECT = zeroed(); + GetClientRect(hwnd, &mut r); + // a side bar runs the same layout along its height + let (x, l) = if vert() { (y, layout(r.bottom)) } else { (x, layout(r.right)) }; + let sl = i18n::style::start_left(); + if sl { + if x < l.start_x + l.bw { + return 0; // Start reaches all the way to the screen corner + } + if x >= l.gear_x && x < l.gear_x + sc(GEAR_X.1) { + return GEAR; + } + } else if x < l.gear_x + sc(GEAR_X.1) { + return GEAR; + } + if x >= l.clock.1 { + return SHOWDESK; + } + if x >= l.clock.0 { + return CLOCK; + } + if x >= l.power.0 { + return power_keys().get(((x - l.power.0) / sc(32)) as usize).copied().unwrap_or(NONE); + } + if x >= l.sys.0 { + let d = x - l.sys.0; + let (lw, ww) = (sc(SYS_LANG), sc(SYS_WIFI)); + return if d < lw { LANG } else if d < lw + ww { WIFI_I } else if d < lw + ww + sc(SYS_VOL) { VOL_I } else if BAT.get().0 >= 0 { BAT_I } else { NONE }; + } + if x >= l.wid.0 { + return NONE; // a widget is text only + } + if x >= l.apps.0 { + return TAPP + (x - l.apps.0) / sc(24); + } + let n = BTNS.with_borrow(|b| b.len()) as i32 + LEAD - i32::from(sl); + let (d, i) = (x - l.x0, (x - l.x0) / (l.bw + l.gap)); + if d < 0 || d % (l.bw + l.gap) >= l.bw || i >= n { NONE } else if i == 0 { SEARCH } else if i == 1 { TASKVIEW } else { i - LEAD + i32::from(sl) } +} + +// ---------- animation ---------- + +fn mix(a: u32, b: u32, t: f32) -> u32 { + let ch = |s: u32| { + let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32); + (x + (y - x) * t) as u32 + }; + ch(0) | ch(8) << 8 | ch(16) << 16 +} + +fn ease(t: f32) -> f32 { + t * t * (3.0 - 2.0 * t) +} + +unsafe fn now_ms() -> u64 { + GetTickCount64() +} + +/// Eased 0..1 hover value of one element: glides toward `on` (1) / off (0) instead of jumping. Sets BUSY while it moves, +/// the painter then schedules another frame. +unsafe fn hv(key: i32, on: bool) -> f32 { + let now = now_ms(); + let target = if on { 1.0 } else { 0.0 }; + let v = HV.with_borrow_mut(|m| { + let e = m.entry(key).or_insert((0.0, now)); + let dt = now.saturating_sub(e.1).min(50) as f32; // a long pause must not make the first frame jump + e.1 = now; + e.0 = if e.0 < target { (e.0 + dt / 130.0).min(target) } else { (e.0 - dt / 180.0).max(target) }; + e.0 + }); + if v != target { + BUSY.set(true); + } + ease(v) +} + +/// Rounded highlight that fades in and out; `from` is the colour it sits on. A click also flashes it in the accent colour. +unsafe fn glow(dc: HDC, key: i32, on: bool, r: RECT, from: u32, to: u32, rad: i32) { + let t = hv(key, on); + let p = press_t(key); + if t > 0.01 || p > 0.0 { + fill(dc, r, mix(mix(from, to, t), pal().accent, 0.5 * p), rad); + } +} + +thread_local! { + static PRESS: Cell<(i32, u64)> = const { Cell::new((i32::MIN, 0)) }; // last clicked element and when + static SEEN: RefCell> = RefCell::new(HashMap::new()); // when each taskbar button first showed +} + +/// Marks `key` as just clicked / dropped on: its highlight flashes and its icon squeezes for a moment. +unsafe fn press(key: i32) { + PRESS.set((key, now_ms())); +} + +/// 1.0 right after the click, easing to 0 over 320 ms (keeps the painter running meanwhile). +unsafe fn press_t(key: i32) -> f32 { + let (k, t0) = PRESS.get(); + let t = now_ms().saturating_sub(t0) as f32 / 320.0; + if k != key || t >= 1.0 { + return 0.0; + } + BUSY.set(true); + (1.0 - t) * (1.0 - t) +} + +/// 0..1 over 260 ms after a taskbar button first appears: new windows pop in instead of snapping into place. +unsafe fn appear(key: isize) -> f32 { + let now = now_ms(); + let t0 = SEEN.with_borrow_mut(|m| { + if m.len() > 512 { + m.clear(); // shortcut: closed windows are never pruned one by one; a clear only replays the pop-in + } + *m.entry(key).or_insert(now) + }); + let t = now.saturating_sub(t0) as f32 / 260.0; + if t >= 1.0 { + return 1.0; + } + BUSY.set(true); + ease(t) +} + +/// How far the bar sits below its place: it rises in at start and drops out of the way (and back) when a fullscreen +/// window takes the screen. +fn bar_off() -> i32 { + ((1.0 - ease(BAR_P.get())) * (bar_h() + dock_gap()) as f32) as i32 +} + +unsafe fn bar_anim(hwnd: HWND) { + BAR_T.set(now_ms()); + SetTimer(hwnd, 5, 15, None); +} + +unsafe fn bar_step(hwnd: HWND) { + // hides for a fullscreen game or video, and with "auto-hide" on while the pointer is away (never otherwise: not over the desktop, not in any style) + let target = if FULLSCREEN.load(Relaxed) || (i18n::style::autohide() && DESK_HIDE.load(Relaxed)) { 0.0 } else { 1.0 }; + let now = now_ms(); + let dt = now.saturating_sub(BAR_T.replace(now)).min(50) as f32; + let p = BAR_P.get(); + let p = if p < target { (p + dt / 380.0).min(target) } else { (p - dt / 240.0).max(target) }; + BAR_P.set(p); + let shown = p > 0.0 && IsWindowVisible(hwnd) == 0; + if shown { + ShowWindow(hwnd, SW_SHOWNOACTIVATE); + } + let (px, py) = bar_pos(); + // on top of the other topmost windows only when it comes back; sliding away must not raise it over a fullscreen game + SetWindowPos(hwnd, HWND_TOPMOST, px, py, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | if shown { 0 } else { SWP_NOZORDER }); + if p == target { + KillTimer(hwnd, 5); + if p == 0.0 { + ShowWindow(hwnd, SW_HIDE); // not just moved away: a hidden bar cannot cover a game + } + } +} + +/// True when the foreground window covers the whole primary monitor (game, F11 video, presentation). +/// A maximized window does not: the bar's reserved strip keeps it below the bar. +unsafe fn fullscreen_now(bar: HWND) -> bool { + fg_covers(bar).is_some_and(|m| (m.left, m.top) == (0, 0)) +} + +/// The monitor the foreground window covers whole, if it covers one. +unsafe fn fg_covers(bar: HWND) -> Option { + let fg = GetForegroundWindow(); + if fg.is_null() || fg == bar || IsWindowVisible(fg) == 0 { + return None; + } + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mut mi); + let m = mi.rcMonitor; + // A fullscreen game brought back with Alt+Tab gets the foreground while still minimized and only then switches the screen + // over: if the bar stayed on top then, the game lost fullscreen again. The window that was fullscreen counts as such + // while it comes back, and so does any Direct3D game Windows itself reports as fullscreen. + let mut quns = 0; + if windows_sys::Win32::UI::Shell::SHQueryUserNotificationState(&mut quns) >= 0 && quns == 3 { + return Some(m); // QUNS_RUNNING_D3D_FULL_SCREEN + } + if IsIconic(fg) != 0 { + return (fg as isize == FS_WND.get()).then_some(m); + } + let mut cls = [0u16; 64]; + let n = GetClassNameW(fg, cls.as_mut_ptr(), 64).max(0) as usize; + if matches!(String::from_utf16_lossy(&cls[..n]).as_str(), "Progman" | "WorkerW" | "Shell_TrayWnd" | "Shell_SecondaryTrayWnd" | "RustExplorer") { + return None; // the desktop itself is full size (rs-shell's desktop is a rust-explorer window; a file manager is never "fullscreen") + } + let mut r: RECT = zeroed(); + GetWindowRect(fg, &mut r); + let caption = GetWindowLongW(fg, GWL_STYLE) as u32 & WS_CAPTION == WS_CAPTION; + let fs = covers_monitor(r, m, caption, IsZoomed(fg) != 0); + if fs { + FS_WND.set(fg as isize); + } + fs.then_some(m) +} + +/// A game switching into fullscreen leaves the screen without any foreground window for a moment, again and again until it +/// settles: the bar must not come back in that moment (it would land on top and knock the game out of fullscreen, which then +/// tries again, in a loop). So the bar returns only once fullscreen has been gone for 1.5 s without a break. +unsafe fn fs_settled(now_fs: bool) -> bool { + if now_fs { + FS_OFF.set(0); + return true; + } + if !FULLSCREEN.load(Relaxed) { + return false; + } + // the same window back with a frame (video left fullscreen) or gone: no game switching, no wait (#269) + let w = FS_WND.get() as HWND; + if !w.is_null() && (IsWindow(w) == 0 || (GetForegroundWindow() == w && IsIconic(w) == 0 && GetWindowLongW(w, GWL_STYLE) as u32 & WS_CAPTION == WS_CAPTION)) { + FS_OFF.set(0); + return false; + } + let now = now_ms(); + if FS_OFF.get() == 0 { + FS_OFF.set(now); + } + if now.saturating_sub(FS_OFF.get()) < 1500 { + return true; + } + FS_OFF.set(0); + false +} + +/// A framed maximized window overhangs the monitor by its border and is not fullscreen (#88); but a game in "borderless +/// window" mode that keeps its caption style while sized to the monitor (SDL, GLFW, Dota 2 and others) is. Such a window +/// can sit a pixel past the monitor edge (Minecraft: 1921 wide on a 1920 monitor), so it has to "cover", not "equal". +fn covers_monitor(r: RECT, m: RECT, caption: bool, zoomed: bool) -> bool { + if caption && zoomed { + return false; // a framed maximized window: not a game (#88) + } + if caption && (r.left < m.left - 1 || r.top < m.top - 1) { + return false; // its border overhangs: a framed window sized like a maximized one (Firefox after restore, #237) + } + r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom +} + +/// True when no app window is on screen (none open, or all minimized: Win+D): the user is looking at the desktop. +unsafe fn desktop_now() -> bool { + BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).all(|&w| IsIconic(w) != 0)) +} + +unsafe fn fs_update(hwnd: HWND) { + second::update(hwnd); + let fs = fs_settled(fullscreen_now(hwnd)); + // a fullscreen game keeps the screen: the pointer at the bottom edge does not bring the bar (games park it at the + // edges all the time); Win opens Start, which brings the bar with it + let mut pt = POINT { x: 0, y: 0 }; + GetCursorPos(&mut pt); + // desktop in front: the bar leaves 2 s after the pointer does and comes back at the bottom edge (an open flyout keeps it) + let now = now_ms(); + let sh = GetSystemMetrics(SM_CYSCREEN); + let sw = GetSystemMetrics(SM_CXSCREEN); + let over = if vert() { + if i18n::style::side() == i18n::style::Side::Left { pt.x <= 0 || (pt.x < bar_h() && BAR_P.get() > 0.0) } else { pt.x >= sw - 1 || (pt.x >= sw - bar_h() && BAR_P.get() > 0.0) } + } else if at_top() { pt.y <= 0 || (pt.y < bar_h() && BAR_P.get() > 0.0) } else { pt.y >= sh - 1 || (pt.y >= sh - bar_h() - dock_gap() && BAR_P.get() > 0.0) }; + if fs || !(i18n::style::autohide() || desktop_now() || dock_covered()) || fly::any_open() || over { + DESK_T.set(now); + } + let desk = !fs && now.saturating_sub(DESK_T.get()) >= 2000; + if DESK_HIDE.swap(desk, Relaxed) != desk { + bar_anim(hwnd); + } + if FULLSCREEN.swap(fs, Relaxed) != fs { + if fs { + fly::close_now(); + hide_tip(hwnd); + thumbs::hide_preview(); + } + bar_anim(hwnd); + } + // the 250 ms watch is only needed while the pointer decides (auto-hide, dock, desktop, bar away); otherwise + // the foreground event, ABN_FULLSCREENAPP and the 1 s tick call this + let poll = i18n::style::autohide() || dock() || desktop_now() || DESK_HIDE.load(Relaxed) || FS_OFF.get() != 0; + if FS_POLL.replace(poll) != poll { + if poll { + SetTimer(hwnd, 3, 250, None); + } else { + KillTimer(hwnd, 3); + } + } +} + +thread_local! { + static FS_POLL: Cell = const { Cell::new(true) }; // timer 3 runs (set in main) +} + +/// The dock is in the way of the window in front (one dragged down under it): it hides like over the +/// desktop and comes back when the pointer touches the bottom edge. +unsafe fn dock_covered() -> bool { + if !dock() { + return false; + } + let fg = GetForegroundWindow(); + // a maximized window never hides the dock (it could stay gone until the window was restored) + if fg.is_null() || IsIconic(fg) != 0 || IsZoomed(fg) != 0 || fg == BAR.load(Relaxed) as HWND || fly::any_open() { + return false; + } + let mut r: RECT = zeroed(); + GetWindowRect(fg, &mut r); + let (x, w) = bar_x_w(); + let top = GetSystemMetrics(SM_CYSCREEN) - bar_h() - dock_gap(); + r.bottom > top && r.right > x && r.left < x + w +} + +/// A bar that should be on screen but is hidden or off its edge (a late display change at boot) is put back (#287). +unsafe fn keep_in_place(hwnd: HWND) { + if FULLSCREEN.load(Relaxed) || i18n::style::autohide() { + return; + } + if BAR_P.get() < 1.0 { + bar_anim(hwnd); + return; + } + let mut r: RECT = zeroed(); + GetWindowRect(hwnd, &mut r); + let wrong_height = vert() && r.bottom - r.top != GetSystemMetrics(SM_CYSCREEN); + if IsWindowVisible(hwnd) == 0 || (r.left, r.top) != bar_pos() || wrong_height { + ShowWindow(hwnd, SW_SHOWNOACTIVATE); + place(hwnd); + } +} + +thread_local! { static DRAG_OVER: Cell = const { Cell::new(NONE) }; } + +/// Something dragged from another window and held over an app button brings that app forward (#265). +// shortcut: polled by the 1 s tick, so 1-2 s; an OLE drop target if that feels slow +unsafe fn drag_hover(hwnd: HWND) { + let mut p = POINT { x: 0, y: 0 }; + GetCursorPos(&mut p); + // our own presses are in BUTTON_DRAG: not a drag from outside + let held = GetAsyncKeyState(VK_LBUTTON as i32) < 0 && BUTTON_DRAG.with_borrow(|d| d.is_none()) && WindowFromPoint(p) == hwnd; + let mut h = NONE; + if held { + ScreenToClient(hwnd, &mut p); + h = hit(hwnd, p.x, p.y); + } + if DRAG_OVER.replace(h) != h || button_key(h).is_none() { return; } + let w = BTNS.with_borrow(|b| b.get(h as usize).and_then(|b| b.wins.first().copied())); + if let Some(w) = w.filter(|&w| GetForegroundWindow() != w) { bring(w); } +} + +/// SetForegroundWindow that also works when the request comes from a keyboard hook (we have not "received input" then). +unsafe fn force_fg(hw: HWND) { + winrust_common::fg::force(hw); +} + +thread_local! { + // windows topbar itself minimized while maximized: they must come back maximized even if the placement flags lost it (#268) + static WAS_MAX: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Records that `w` is being minimized from a maximized state, so `bring` returns it maximized. +unsafe fn note_minimize(w: HWND) { + WAS_MAX.with_borrow_mut(|v| { + v.retain(|&x| x != w && IsWindow(x) != 0); + if IsZoomed(w) != 0 { + v.push(w); + } + }); +} + +/// Switches to a window (Alt+Tab, its button, a preview, a menu). A maximized one comes back maximized in a single step; any +/// other minimized one goes through SwitchToThisWindow, the call Windows' own Alt+Tab makes: it activates and restores in one +/// step. Restoring first and activating after made a fullscreen game get the foreground, lose it to the previous window and +/// get it again; it then gave up on fullscreen (stayed black). +pub(crate) unsafe fn bring(w: HWND) { + // WPF_RESTORETOMAXIMIZED: the window was maximized before it was minimized, so it must come back maximized. + const RESTORE_TO_MAX: u32 = 0x0002; + let mut wp: WINDOWPLACEMENT = zeroed(); + wp.length = size_of::() as u32; + let placed = GetWindowPlacement(w, &mut wp) != 0; + let was_iconic = IsIconic(w) != 0; + let remembered = WAS_MAX.with_borrow_mut(|v| v.iter().position(|&x| x == w).map(|i| { v.swap_remove(i); })); + let was_max = was_iconic && (remembered.is_some() || (placed && wp.flags & RESTORE_TO_MAX != 0)); + if was_max && placed { + // show it maximized straight away: SwitchToThisWindow first restores it, and maximizing after visibly flickers + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(MonitorFromRect(&wp.rcNormalPosition, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 { + clamp_rect(&mut wp.rcNormalPosition, workspace(mi.rcWork, mi.rcMonitor)); + } + wp.showCmd = 3; // SW_SHOWMAXIMIZED + if SetWindowPlacement(w, &wp) == 0 { + SwitchToThisWindow(w, 1); + } + } else if was_iconic { + SwitchToThisWindow(w, 1); + if IsIconic(w) != 0 { + ShowWindow(w, SW_RESTORE); + } + } + if GetForegroundWindow() != w { + force_fg(w); // the click that called us owns the foreground, so showing it may not have taken it + } +} + +/// Fills `r` (right / bottom exclusive) in colour `c`; `rad` > 0 rounds the corners (rad = corner diameter), anti-aliased +/// through GDI+. Plain GDI for square boxes and when GDI+ is not available. +unsafe fn fill(dc: HDC, r: RECT, c: u32, rad: i32) { + let rad = if style().square() { 0 } else { rad }; + let (w, h) = ((r.right - r.left) as f32, (r.bottom - r.top) as f32); + if w <= 0.0 || h <= 0.0 { + return; + } + let mut g: *mut GpGraphics = null_mut(); + if rad <= 0 || GdipCreateFromHDC(dc, &mut g) != 0 || g.is_null() { + let b = CreateSolidBrush(c); + if rad <= 0 { + FillRect(dc, &r, b); + } else { + let (ob, op) = (SelectObject(dc, b), SelectObject(dc, GetStockObject(NULL_PEN))); + RoundRect(dc, r.left, r.top, r.right + 1, r.bottom + 1, rad, rad); + SelectObject(dc, ob); + SelectObject(dc, op); + } + DeleteObject(b); + return; + } + GdipSetSmoothingMode(g, SmoothingModeAntiAlias); + GdipSetPixelOffsetMode(g, PixelOffsetModeHalf); // pixel i spans [i, i+1): straight edges stay crisp + let (x, y, d) = (r.left as f32, r.top as f32, (rad as f32).min(w).min(h)); + let mut path: *mut GpPath = null_mut(); + GdipCreatePath(FillModeAlternate, &mut path); + GdipAddPathArc(path, x, y, d, d, 180.0, 90.0); + GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0); + GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0); + GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0); + GdipClosePathFigure(path); + let mut br: *mut GpSolidFill = null_mut(); + GdipCreateSolidFill(0xFF00_0000 | (c & 255) << 16 | (c & 0xFF00) | (c >> 16 & 255), &mut br); // COLORREF -> ARGB + GdipFillPath(g, br as *mut GpBrush, path); + GdipDeleteBrush(br as *mut GpBrush); + GdipDeletePath(path); + GdipDeleteGraphics(g); +} + +unsafe fn text(dc: HDC, s: &str, mut r: RECT, c: u32, flags: u32) { + SetTextColor(dc, c); + let w = wide(s); + DrawTextW(dc, w.as_ptr(), -1, &mut r, flags | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS); +} + +unsafe fn icon_of(h: HWND) -> HICON { + for which in [1usize, 2] { + // ICON_BIG, ICON_SMALL2 + let mut r = 0usize; + SendMessageTimeoutW(h, WM_GETICON, which, 0, SMTO_ABORTIFHUNG, 40, &mut r); + if r != 0 { + return r as HICON; + } + } + let c = GetClassLongPtrW(h, GCLP_HICON); + (if c != 0 { c } else { GetClassLongPtrW(h, GCLP_HICONSM) }) as HICON +} + +/// The app window the user is typing in: the foreground window, or, while our own bar / panel / menu holds the +/// foreground (after a right click, a closed Start...), the last app window that had it. +unsafe fn app_window() -> HWND { + let fg = GetForegroundWindow(); + let mut pid = 0u32; + GetWindowThreadProcessId(fg, &mut pid); + if !fg.is_null() && pid != std::process::id() { + APP_FG.set(fg); + return fg; + } + let last = APP_FG.get(); + if IsWindow(last) != 0 { last } else { fg } +} + +thread_local! { + static WIN_DIRTY: Cell = const { Cell::new(false) }; // a window refresh is already scheduled (timer 8) +} + +/// Repaints (GDI+, the costly part) only when something shown changed; `tick`: every 10th tick anyway as a safety net. +unsafe fn repaint_if_changed(hwnd: HWND, tick: bool) { + let (last, quiet) = SIG.get(); + let s = view_sig(); + if s != last || (tick && quiet >= 10) { + SIG.set((s, 0)); + InvalidateRect(hwnd, null(), 0); + second::invalidate(); + } else if tick { + SIG.set((s, quiet + 1)); + } +} + +/// Window events (WINEVENT_OUTOFCONTEXT: delivered on the bar's thread inside GetMessageW). Instead of enumerating every +/// window twice a second, the bar looks again ~30 ms after something that can change a button happened. +unsafe extern "system" fn win_event(_: windows_sys::Win32::UI::Accessibility::HWINEVENTHOOK, ev: u32, w: HWND, id: i32, child: i32, _: u32, _: u32) { + if id != 0 || child != 0 || w.is_null() { + return; // only whole windows (not carets, cursors, parts of controls) + } + let bar = BAR.load(Relaxed) as HWND; + if bar.is_null() { + return; + } + let known = || BTNS.with_borrow(|b| b.iter().any(|b| b.wins.contains(&w))); + let top = || GetAncestor(w, GA_PARENT) == GetDesktopWindow(); + let relevant = match ev { + 0x0003 => { + fs_update(bar); // EVENT_SYSTEM_FOREGROUND: the active button and fullscreen may change + true + } + 0x8001 => known(), // destroyed: it can no longer be asked anything, but it may be one of ours + 0x800C => !known() && top(), // title set: a window with no title had no button yet + _ => top() || known(), // created, shown, hidden, cloaked, uncloaked, minimized, restored + }; + if relevant && !WIN_DIRTY.replace(true) { + SetTimer(bar, 8, 30, None); + } +} + +/// Hash of everything the bar paints from polled state. +unsafe fn view_sig() -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + BTNS.with_borrow(|b| b.iter().for_each(|b| (b.pin, b.icon as usize, b.wins.iter().map(|&w| (w as usize, IsIconic(w))).collect::>()).hash(&mut h))); + (GetForegroundWindow() as usize, BAT.get(), VOL.get(), WIFI.get(), INET.get(), EXPLORER_UP.load(Relaxed), clock_texts(), lang_name()).hash(&mut h); + TAPPS.with_borrow(|t| t.iter().for_each(|x| (x.hwnd as usize, x.uid, x.icon as usize, x.hidden, &x.tip).hash(&mut h))); + h.finish() +} + +unsafe fn clock_texts() -> (String, String) { + clock_texts_of(0x0400) // LOCALE_USER_DEFAULT +} +/// The time and the date as `locale` (an LCID) formats them: short time without seconds, short date. +unsafe fn clock_texts_of(locale: u32) -> (String, String) { + let mut t: SYSTEMTIME = zeroed(); + GetLocalTime(&mut t); + let (mut a, mut b) = ([0u16; 40], [0u16; 40]); + let n = GetTimeFormatW(locale, 2, &t, null(), a.as_mut_ptr(), 40).max(1) as usize - 1; // TIME_NOSECONDS + let m = GetDateFormatW(locale, 1, &t, null(), b.as_mut_ptr(), 40).max(1) as usize - 1; // DATE_SHORTDATE + (String::from_utf16_lossy(&a[..n]), String::from_utf16_lossy(&b[..m])) +} + +/// The side bar: the same layout as the bottom one, run along the height (top to bottom: gear, search, Start, pins and windows, +/// tray, system, clock), icons only. +unsafe fn paint_vert(dc: HDC, cr: RECT, fonts: [HFONT; 4]) { + let [f_txt, f_small, f_glyph, f_bold] = fonts; + let l = layout(cr.bottom); + let fg = GetForegroundWindow(); + let (lft, rgt) = (sc(6), cr.right - sc(6)); + let cx = (lft + rgt) / 2; + let left = i18n::style::side() == i18n::style::Side::Left; + let hot = HOT.get(); + let active_bg = mix(pal().active, pal().accent, 0.12); + let cell = |y: i32, len: i32| RECT { left: lft, top: y, right: rgt, bottom: y + len }; + let dim = mix(pal().dim, pal().text, 0.5); + + let gr = cell(l.gear_x, sc(GEAR_X.1)); + glow(dc, GEAR, hot == GEAR, gr, pal().bg, pal().hover, sc(8)); + SelectObject(dc, f_glyph); + text(dc, "\u{E713}", gr, if hot == GEAR { pal().text } else { dim }, DT_CENTER); + + let sb = cell(l.x0, l.bw); + glow(dc, SEARCH, hot == SEARCH, sb, pal().bg, pal().hover, sc(8)); + text(dc, "\u{E721}", sb, if hot == SEARCH { pal().text } else { dim }, DT_CENTER); + let tb = cell(l.x0 + l.bw + l.gap, l.bw); + glow(dc, TASKVIEW, hot == TASKVIEW, tb, pal().bg, pal().hover, sc(8)); + text(dc, "\u{E7C4}", tb, if hot == TASKVIEW { pal().text } else { dim }, DT_CENTER); + + BTNS.with_borrow(|btns| { + for (i, b) in btns.iter().enumerate() { + let y = l.btn_pos(i as i32); + let r = cell(y, l.bw); + let mid = y + l.bw / 2; + let act = b.wins.contains(&fg); + let att = !act && FLASH.with_borrow(|f| b.wins.iter().any(|w| f.contains(w))); // flashing: lit until it is activated + let (th, ta, tp) = (hv(i as i32, hot == i as i32), hv(2000 + i as i32, act), press_t(i as i32)); + if th > 0.01 || ta > 0.01 || tp > 0.0 { + fill(dc, r, mix(mix(mix(pal().bg, pal().hover, th), active_bg, ta), pal().accent, 0.5 * tp), sc(8)); + } + if att { + fill(dc, r, mix(pal().bg, pal().accent, 0.4), sc(8)); + } + if i == 0 { + let t = ((icon_sc(8) as f32) * (1.0 + 0.12 * th) * (1.0 - 0.2 * tp)) as i32; + let g = sc(1).max(1); + let tint = [mix(pal().accent, pal().text, 0.35), mix(pal().accent, pal().text, 0.15), mix(pal().accent, pal().text, 0.15), pal().accent]; + for (k, (dx, dy)) in [(-1, -1), (0, -1), (-1, 0), (0, 0)].into_iter().enumerate() { + let (px, py) = (cx + if dx < 0 { -t - g } else { g }, mid + if dy < 0 { -t - g } else { g }); + fill(dc, RECT { left: px, top: py, right: px + t, bottom: py + t }, tint[k], sc(3)); + } + continue; + } + let ic = match b.pin { + Some(p) => PINS.with_borrow(|pins| pins.get(p).map_or(null_mut(), |p| p.icon)), + None => b.icon, + }; + let ic = if ic.is_null() { b.wins.first().map_or(ic, |&w| icon_of(w)) } else { ic }; // a pin whose icon failed to load (#91) + let key = b.pin.map(|p| -(p as isize) - 1).or_else(|| b.wins.first().map(|&w| w as isize)).unwrap_or(0); + let isz = (icon_px().min(l.bw - sc(6)) as f32 * (1.0 - 0.18 * tp) * (0.55 + 0.45 * appear(key))) as i32; + if !ic.is_null() { + DrawIconEx(dc, cx - isz / 2, mid - isz / 2, ic, isz, isz, 0, null_mut(), DI_NORMAL); + } + if !b.wins.is_empty() { + // the running-app pill stands on the edge facing the screen's border + let min = b.wins.iter().all(|&w| IsIconic(w) != 0); + let pl = sc(6) + (sc(12) as f32 * ta) as i32; + let col = if act || att { pal().accent } else if min { mix(pal().dim, pal().bg, 0.45) } else { pal().dim }; + let px = if left { sc(1) } else { cr.right - sc(4) }; + fill(dc, RECT { left: px, top: mid - pl / 2, right: px + sc(3), bottom: mid + pl / 2 }, col, sc(3)); + } + } + }); + + fill(dc, RECT { left: cx - sc(9), top: l.apps.0 - sc(5), right: cx + sc(9), bottom: l.apps.0 - sc(5) + 1 }, pal().line, 0); + + glow(dc, TAPP, hot == TAPP, cell(l.apps.0, sc(24)), pal().bg, pal().hover, sc(8)); + let turn = ease(hv(TF_KEY, IsWindowVisible(TRAYFLY.get()) != 0)); + chevron(dc, cx, l.apps.0 + sc(12), icon_sc(5), if left { 90.0 } else { 270.0 } + 180.0 * turn, mix(pal().text, pal().accent, turn)); + SelectObject(dc, f_txt); + let bar = bar_idx(); + TAPPS.with_borrow(|t| { + for (k, &ix) in bar.iter().enumerate() { + let (i, ti) = (k + 1, &t[ix]); + let y = l.apps.0 + i as i32 * sc(24); + glow(dc, TAPP + i as i32, hot == TAPP + i as i32, cell(y, sc(24)), pal().bg, pal().hover, sc(8)); + if !ti.icon.is_null() { + let size = icon_sc(16); + DrawIconEx(dc, cx - size / 2, y + (sc(24) - size) / 2, ti.icon, size, size, 0, null_mut(), DI_NORMAL); + } + } + }); + + paint_power(dc, &l, hot, f_glyph, cell); + glow(dc, LANG, hot == LANG, cell(l.sys.0, sc(SYS_LANG)), pal().bg, pal().hover, sc(8)); + let grp = cell(l.sys.0 + sc(SYS_LANG + 2), l.sys.1 - l.sys.0 - sc(SYS_LANG + 2)); + let (tg, pg) = (hv(SYS_GRP, matches!(hot, WIFI_I | VOL_I | BAT_I) || fly::is_open(fly::Kind::Quick)), press_t(WIFI_I).max(press_t(VOL_I)).max(press_t(BAT_I))); + if tg > 0.01 || pg > 0.0 { + fill(dc, grp, mix(mix(pal().bg, pal().hover, tg), pal().accent, 0.5 * pg), sc(8)); + } + text(dc, &lang_name(), cell(l.sys.0, sc(SYS_LANG)), pal().text, DT_CENTER); + let y0 = l.sys.0 + sc(SYS_LANG); + net_icon(dc, cx, y0 + sc(SYS_WIFI) / 2, icon_sc(17), f_glyph); + SelectObject(dc, f_glyph); + let (vol, muted) = VOL.get(); + let vg = if muted || vol == 0 { "\u{E74F}" } else if vol < 34 { "\u{E993}" } else if vol < 67 { "\u{E994}" } else { "\u{E995}" }; + let y1 = y0 + sc(SYS_WIFI); + text(dc, vg, cell(y1, sc(SYS_VOL)), if muted { BAD } else { pal().text }, DT_CENTER); + let (pct, ac) = BAT.get(); + if pct >= 0 { + let col = if ac { GOOD } else if pct <= 15 { BAD } else { pal().text }; + let (bw, bh) = (icon_sc(SYS_BAT_W), icon_sc(11)); + let (bx, by) = (cx - bw / 2 - sc(1), y1 + sc(SYS_VOL)); + fill(dc, RECT { left: bx, top: by, right: bx + bw, bottom: by + bh }, col, sc(4)); + fill(dc, RECT { left: bx + sc(1), top: by + sc(1), right: bx + bw - sc(1), bottom: by + bh - sc(1) }, mix(pal().bg, pal().hover, tg), sc(3)); + let fw = ((bw - sc(4)) * pct / 100).max(sc(1)); + fill(dc, RECT { left: bx + sc(2), top: by + sc(2), right: bx + sc(2) + fw, bottom: by + bh - sc(2) }, col, sc(2)); + fill(dc, RECT { left: bx + bw + sc(1), top: by + sc(3), right: bx + bw + sc(3), bottom: by + bh - sc(3) }, col, sc(1)); + SelectObject(dc, f_small); + text(dc, &format!("{pct}%"), cell(y1 + sc(SYS_VOL + SYS_BAT_W + 8), sc(18)), pal().text, DT_CENTER); + } + + let cb = cell(l.clock.0, l.clock.1 - l.clock.0); + glow(dc, CLOCK, hot == CLOCK || fly::is_open(fly::Kind::Cal), cb, pal().bg, pal().hover, sc(8)); + let (tm, dt) = clock_texts(); + let mid = (cb.top + cb.bottom) / 2; + SelectObject(dc, f_bold); + text(dc, &tm, RECT { left: cb.left, top: cb.top, right: cb.right, bottom: mid + sc(1) }, pal().text, DT_CENTER); + SelectObject(dc, f_small); + text(dc, &dt, RECT { left: cb.left, top: mid - sc(1), right: cb.right, bottom: cb.bottom }, mix(pal().dim, pal().text, 0.35), DT_CENTER); +} + +thread_local! { + static BG: Cell<(HDC, HBITMAP, u64)> = const { Cell::new((null_mut(), null_mut(), 0)) }; // cached background layer and its key + static FONTS: Cell<([HFONT; 4], u64)> = const { Cell::new(([null_mut(); 4], 0)) }; +} + +fn key_of(v: impl std::hash::Hash) -> u64 { + use std::hash::Hasher; + let mut h = std::collections::hash_map::DefaultHasher::new(); + v.hash(&mut h); + h.finish() | 1 // never 0, the "empty" key +} + +/// The bar's background for this size, side and style, redrawn only when one of them changes. +unsafe fn bg_layer(wdc: HDC, cr: RECT) -> HDC { + let h = cr.bottom; + let p = pal(); + let key = key_of((cr.right, h, vert(), at_top(), i18n::style::side() == i18n::style::Side::Left, style().light(), format!("{:?}", style()), [p.bg, p.text, p.line, p.accent], SCALE.get().to_bits())); + let (mut dc, mut bmp, k) = BG.get(); + if k == key && !dc.is_null() { + return dc; + } + if dc.is_null() { + dc = CreateCompatibleDC(wdc); + } + if !bmp.is_null() { + DeleteObject(bmp); + } + bmp = CreateCompatibleBitmap(wdc, cr.right, h); + SelectObject(dc, bmp); // the DC's first bitmap is the stock 1x1 one: nothing to give back + BG.set((dc, bmp, key)); + // frosted-glass look: a hairline on top, a faint light catch under it, then the panel colour fading in + let lit = mix(pal().bg, pal().text, 0.045); + if vert() { + fill(dc, cr, pal().bg, 0); + } else { + for y in 0..h { + fill(dc, RECT { left: 0, top: y, right: cr.right, bottom: y + 1 }, mix(lit, pal().bg, (y as f32 / sc(18) as f32).min(1.0)), 0); + } + } + winrust_common::style::backdrop(dc, cr, sc(100) as f32 / 100.0); + if vert() { + // the hairline faces the windows + let x = if i18n::style::side() == i18n::style::Side::Left { cr.right - 1 } else { 0 }; + fill(dc, RECT { left: x, top: 0, right: x + 1, bottom: h }, pal().line, 0); + } + let edge = if at_top() { h - 1 } else { 0 }; // the hairline faces the windows + if !vert() { + fill(dc, RECT { left: 0, top: edge, right: cr.right, bottom: edge + 1 }, pal().line, 0); + } + if !at_top() && !vert() { + fill(dc, RECT { left: 0, top: 1, right: cr.right, bottom: 2 }, mix(pal().bg, pal().text, 0.08), 0); + } + dc +} + +fn bar_fonts_key(scale: f32, ui: &str, icon: &str, icon_size: u8) -> u64 { + key_of((scale.to_bits(), ui, icon, icon_size)) +} + +/// The bar's four fonts, made again only when the scale, icon size or style's faces change. +unsafe fn bar_fonts() -> [HFONT; 4] { + let icon_size = i18n::style::icon_size(); + let key = bar_fonts_key(SCALE.get(), ui_face(), winrust_common::style::icon_face(), icon_size); + let (fonts, k) = FONTS.get(); + if k == key { + return fonts; + } + fonts.iter().filter(|f| !f.is_null()).for_each(|&f| { + DeleteObject(f); + }); + let (face, gface) = (wide(ui_face()), wide(winrust_common::style::icon_face())); + let font = |f: &[u16], px: i32, wt: i32| CreateFontW(-sc(px), 0, 0, 0, wt, 0, 0, 0, 1, 0, 0, 5, 0, f.as_ptr()); + let icon_px = (16.0 * icon_size as f32 / 100.0).round() as i32; + let fonts = [font(&face, 13, 400), font(&face, 12, 400), font(&gface, icon_px, 400), font(&face, 13, 600)]; + FONTS.set((fonts, key)); + fonts +} + +unsafe fn paint(hwnd: HWND) { + let mut ps: PAINTSTRUCT = zeroed(); + let wdc = BeginPaint(hwnd, &mut ps); + let mut cr: RECT = zeroed(); + GetClientRect(hwnd, &mut cr); + let h = cr.bottom; + BUSY.set(false); + let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, h)); + let old = SelectObject(dc, bmp); + // the background (gradient, facets, hairlines) is the same every frame: drawn once per size / style, then copied + BitBlt(dc, 0, 0, cr.right, h, bg_layer(wdc, cr), 0, 0, SRCCOPY); + SetBkMode(dc, TRANSPARENT as i32); + let [f_txt, f_small, f_glyph, f_bold] = bar_fonts(); + let of = SelectObject(dc, f_txt); + + 'horiz: { + + if vert() { + paint_vert(dc, cr, [f_txt, f_small, f_glyph, f_bold]); + break 'horiz; + } + let l = layout(cr.right); + let fg = GetForegroundWindow(); + let (top, bot) = (sc(4), h - sc(4)); + let mid = (top + bot) / 2; + let cell = |x: i32, w: i32| RECT { left: x, top, right: x + w, bottom: bot }; + let hot = HOT.get(); + let active_bg = mix(pal().active, pal().accent, 0.12); // the focused app's button: a hint of the accent, not plain grey + + // the gear: the Style menu + let gr = RECT { left: l.gear_x, top, right: l.gear_x + sc(GEAR_X.1), bottom: bot }; + glow(dc, GEAR, hot == GEAR, gr, pal().bg, pal().hover, sc(8)); + SelectObject(dc, f_glyph); + text(dc, "\u{E713}", gr, if hot == GEAR { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); + + // search button (left of Start) + let sb = RECT { left: l.x0, top, right: l.x0 + l.bw, bottom: bot }; + glow(dc, SEARCH, hot == SEARCH, sb, pal().bg, pal().hover, sc(8)); + SelectObject(dc, f_glyph); + text(dc, "\u{E721}", sb, if hot == SEARCH { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); + let tb = RECT { left: l.x0 + l.bw + l.gap, top, right: l.x0 + 2 * l.bw + l.gap, bottom: bot }; + glow(dc, TASKVIEW, hot == TASKVIEW, tb, pal().bg, pal().hover, sc(8)); + text(dc, "\u{E7C4}", tb, if hot == TASKVIEW { pal().text } else { mix(pal().dim, pal().text, 0.5) }, DT_CENTER); + + // Start, pinned apps, open windows (center) + BTNS.with_borrow(|btns| { + for (i, b) in btns.iter().enumerate() { + let x = l.btn_pos(i as i32); + let r = RECT { left: x, top, right: x + l.bw, bottom: bot }; + let act = b.wins.contains(&fg); + let att = !act && FLASH.with_borrow(|f| b.wins.iter().any(|w| f.contains(w))); // flashing: lit until it is activated + let (th, ta, tp) = (hv(i as i32, hot == i as i32), hv(2000 + i as i32, act), press_t(i as i32)); + if th > 0.01 || ta > 0.01 || tp > 0.0 { + fill(dc, r, mix(mix(mix(pal().bg, pal().hover, th), active_bg, ta), pal().accent, 0.5 * tp), sc(8)); + } + if att { + fill(dc, r, mix(pal().bg, pal().accent, 0.4), sc(8)); + } + if i == 0 { + // Windows logo in four tiles, lit from the top left; grows a little on hover, squeezes on click + let t = ((icon_sc(8) as f32) * (1.0 + 0.12 * th) * (1.0 - 0.2 * tp)) as i32; + let (g, cx) = (sc(1).max(1), (r.left + r.right) / 2); + let tint = [mix(pal().accent, pal().text, 0.35), mix(pal().accent, pal().text, 0.15), mix(pal().accent, pal().text, 0.15), pal().accent]; + for (k, (dx, dy)) in [(-1, -1), (0, -1), (-1, 0), (0, 0)].into_iter().enumerate() { + let (px, py) = (cx + if dx < 0 { -t - g } else { g }, mid + if dy < 0 { -t - g } else { g }); + fill(dc, RECT { left: px, top: py, right: px + t, bottom: py + t }, tint[k], sc(3)); + } + continue; + } + let ic = match b.pin { + Some(p) => PINS.with_borrow(|pins| pins.get(p).map_or(null_mut(), |p| p.icon)), + None => b.icon, + }; + let ic = if ic.is_null() { b.wins.first().map_or(ic, |&w| icon_of(w)) } else { ic }; // a pin whose icon failed to load (#91) + let key = b.pin.map(|p| -(p as isize) - 1).or_else(|| b.wins.first().map(|&w| w as isize)).unwrap_or(0); + // squeezes on click, grows in when new, lifts a pixel on hover + let isz = (icon_px().min(l.bw - sc(6)) as f32 * (1.0 - 0.18 * tp) * (0.55 + 0.45 * appear(key))) as i32; + if !ic.is_null() { + DrawIconEx(dc, x + (l.bw - isz) / 2, mid - isz / 2 - sc(2) - (sc(1) as f32 * th) as i32, ic, isz, isz, 0, null_mut(), DI_NORMAL); + } + if !b.wins.is_empty() { + let min = b.wins.iter().all(|&w| IsIconic(w) != 0); + let pw = sc(6) + (sc(12) as f32 * ta) as i32; // the running-app pill stretches when its window is active + let py = bot - sc(4); + let col = if act || att { pal().accent } else if min { mix(pal().dim, pal().bg, 0.45) } else { pal().dim }; + fill(dc, RECT { left: x + (l.bw - pw) / 2, top: py, right: x + (l.bw + pw) / 2, bottom: py + sc(3) }, col, sc(3)); + if b.wins.len() > 1 { + // a second, shorter pill: more than one window behind this button + fill(dc, RECT { left: x + (l.bw + pw) / 2 + sc(2), top: py, right: x + (l.bw + pw) / 2 + sc(5), bottom: py + sc(3) }, col, sc(3)); + } + } + } + }); + + // a hairline between the app buttons and the tray side + fill(dc, RECT { left: l.apps.0 - sc(5), top: mid - sc(9), right: l.apps.0 - sc(5) + 1, bottom: mid + sc(9) }, pal().line, 0); + + // tray apps + glow(dc, TAPP, hot == TAPP, cell(l.apps.0, sc(24)), pal().bg, pal().hover, sc(8)); + SelectObject(dc, f_glyph); + let open_tf = IsWindowVisible(TRAYFLY.get()) != 0; + let turn = ease(hv(TF_KEY, open_tf)); // the chevron turns over as the flyout opens, and back + let cc = cell(l.apps.0, sc(24)); + chevron(dc, (cc.left + cc.right) / 2, mid, icon_sc(5), if at_top() { 180.0 } else { 0.0 } + 180.0 * turn, mix(pal().text, pal().accent, turn)); + SelectObject(dc, f_txt); + let bar = bar_idx(); + TAPPS.with_borrow(|t| { + for (k, &ix) in bar.iter().enumerate() { + let (i, ti) = (k + 1, &t[ix]); + let x = l.apps.0 + i as i32 * sc(24); + glow(dc, TAPP + i as i32, hot == TAPP + i as i32, cell(x, sc(24)), pal().bg, pal().hover, sc(8)); + if !ti.icon.is_null() { + let size = icon_sc(16); + DrawIconEx(dc, x + (sc(24) - size) / 2, mid - size / 2, ti.icon, size, size, 0, null_mut(), DI_NORMAL); + } + } + }); + + widgets::paint(dc, l.wid.0, top, bot); + // system group: language on its own, then one pill for wifi + volume + battery (like Windows 11: they open one panel) + paint_power(dc, &l, hot, f_glyph, |s, len| RECT { left: s, top, right: s + len, bottom: bot }); + let tb = RECT { left: l.sys.0, top, right: l.sys.1, bottom: bot }; + glow(dc, LANG, hot == LANG, cell(tb.left, sc(SYS_LANG)), pal().bg, pal().hover, sc(8)); + let grp = RECT { left: tb.left + sc(SYS_LANG + 2), top, right: tb.right, bottom: bot }; + let (tg, pg) = (hv(SYS_GRP, matches!(hot, WIFI_I | VOL_I | BAT_I) || fly::is_open(fly::Kind::Quick)), press_t(WIFI_I).max(press_t(VOL_I)).max(press_t(BAT_I))); + if tg > 0.01 || pg > 0.0 { + fill(dc, grp, mix(mix(pal().bg, pal().hover, tg), pal().accent, 0.5 * pg), sc(8)); + } + let x = tb.left + sc(SYS_LANG); + text(dc, &lang_name(), cell(tb.left, sc(SYS_LANG)), pal().text, DT_CENTER); + net_icon(dc, x + sc(SYS_WIFI) / 2, mid, icon_sc(17), f_glyph); + SelectObject(dc, f_glyph); + let (vol, muted) = VOL.get(); + let vg = if muted || vol == 0 { "\u{E74F}" } else if vol < 34 { "\u{E993}" } else if vol < 67 { "\u{E994}" } else { "\u{E995}" }; + let xv = x + sc(SYS_WIFI); + text(dc, vg, cell(xv, sc(SYS_VOL)), if muted { BAD } else { pal().text }, DT_CENTER); + let (pct, ac) = BAT.get(); + if pct >= 0 { + let x = xv + sc(SYS_VOL); + let col = if ac { GOOD } else if pct <= 15 { BAD } else { pal().text }; + let (bw, bh) = (icon_sc(SYS_BAT_W), icon_sc(11)); + let by = mid - bh / 2; + fill(dc, RECT { left: x, top: by, right: x + bw, bottom: by + bh }, col, sc(4)); // outline + fill(dc, RECT { left: x + sc(1), top: by + sc(1), right: x + bw - sc(1), bottom: by + bh - sc(1) }, mix(pal().bg, pal().hover, tg), sc(3)); + let fw = ((bw - sc(4)) * pct / 100).max(sc(1)); + fill(dc, RECT { left: x + sc(2), top: by + sc(2), right: x + sc(2) + fw, bottom: by + bh - sc(2) }, col, sc(2)); + fill(dc, RECT { left: x + bw + sc(1), top: by + sc(3), right: x + bw + sc(3), bottom: by + bh - sc(3) }, col, sc(1)); // terminal nub + SelectObject(dc, f_txt); + text(dc, &format!("{pct}%"), cell(x + bw + sc(8), sc(SYS_BAT_PCT)), pal().text, DT_LEFT); + } + + // time (semibold) over the date (dimmed); the cell is as wide as the wider line, so both get the same air + let cb = cell(l.clock.0, l.clock.1 - l.clock.0); + glow(dc, CLOCK, hot == CLOCK || fly::is_open(fly::Kind::Cal), cb, pal().bg, pal().hover, sc(8)); + let (tm, dt) = clock_texts(); + SelectObject(dc, f_bold); + text(dc, &tm, RECT { left: cb.left, top: cb.top, right: cb.right, bottom: mid + sc(1) }, pal().text, DT_CENTER); + SelectObject(dc, f_small); + text(dc, &dt, RECT { left: cb.left, top: mid - sc(1), right: cb.right, bottom: cb.bottom }, mix(pal().dim, pal().text, 0.35), DT_CENTER); + } + + BitBlt(wdc, 0, 0, cr.right, h, dc, 0, 0, SRCCOPY); + SelectObject(dc, of); + SelectObject(dc, old); + DeleteObject(bmp); + DeleteDC(dc); + if BUSY.get() { + SetTimer(hwnd, 4, 16, None); // next animation frame + } else { + KillTimer(hwnd, 4); + } + EndPaint(hwnd, &ps); +} + +// ---------- input ---------- + +/// Presses the keys in order, releases them in reverse (e.g. Win+A). +unsafe fn keys(vks: &[u16]) { + let send = |vk: u16, up: bool| { + let mut i: INPUT = zeroed(); + i.r#type = INPUT_KEYBOARD; + i.Anonymous.ki.wVk = vk; + i.Anonymous.ki.dwFlags = if up { KEYEVENTF_KEYUP } else { 0 }; + SendInput(1, &i, size_of::() as i32); + }; + vks.iter().for_each(|&v| send(v, false)); + vks.iter().rev().for_each(|&v| send(v, true)); +} + +/// Releases `vk` alone: a swallowed key-up handed back to the shell as a synthetic one (see `run::kb_hook`). +unsafe fn key_up(vk: u16) { + let mut i: INPUT = zeroed(); + i.r#type = INPUT_KEYBOARD; + i.Anonymous.ki.wVk = vk; + i.Anonymous.ki.dwFlags = KEYEVENTF_KEYUP; + SendInput(1, &i, size_of::() as i32); +} + +/// WM_CLOSE. A window of an elevated app ignores it from our normal-rights process (UIPI), so then +/// ask for admin once (UAC) and let an elevated taskkill send the close request. +unsafe fn close_window(w: HWND) { + if PostMessageW(w, WM_CLOSE, 0, 0) == 0 { + let mut pid = 0u32; + GetWindowThreadProcessId(w, &mut pid); + ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/PID {pid}")).as_ptr(), null(), SW_HIDE); + } +} + +/// App id of the Store app a .lnk of a pin points into (its package folder), None for anything else. +unsafe fn msix_app_id(lnk: &str) -> Option { + let (family, _) = msix_family(&lnk_target(&wide(lnk)))?; + let prefix = format!("{family}!").to_lowercase(); + fly::apps_folder().into_iter().map(|a| a.1).find(|id| id.to_lowercase().starts_with(&prefix)) +} + +/// Starts a Store app by its app id. false = it did not start (the caller falls back to explorer). +unsafe fn activate_app(aumid: &str) -> bool { + use windows::Win32::UI::Shell::{ACTIVATEOPTIONS, ApplicationActivationManager, IApplicationActivationManager}; + CoCreateInstance::<_, IApplicationActivationManager>(&ApplicationActivationManager, None, CLSCTX_ALL) + .and_then(|m| m.ActivateApplication(PCWSTR(wide(aumid).as_ptr()), PCWSTR::null(), ACTIVATEOPTIONS(0))) + .is_ok() +} + +/// Opens a file, shortcut, URI or program with the desktop user's normal token: the bar itself may run elevated (see the +/// launcher), and everything started from it must not inherit that. +unsafe fn open(path: &[u16]) { + let n = path.iter().position(|&c| c == 0).unwrap_or(path.len()); + let p = String::from_utf16_lossy(&path[..n]); + // the bar never takes the foreground (WS_EX_NOACTIVATE), so what it starts (via explorer / runas) may not come to the + // front either; it did get the click, which lets it hand that right on (#207) + AllowSetForegroundWindow(u32::MAX); // ASFW_ANY + if p.to_lowercase().ends_with(".lnk") { + bump(&p); + } + if p.to_lowercase().starts_with("ms-settings:") { + return winrust_common::settings::open(&p); // needs Explorer as shell: it is started for the time Settings is open + } + // Store (MSIX) apps: by app id through the activation manager. A path into the protected package folder ("no app + // associated") and shell:AppsFolder via explorer ("class not registered" when Explorer is not the shell) both fail. + let aumid = if p.to_lowercase().starts_with(r"shell:appsfolder\") { Some(p[r"shell:appsfolder\".len()..].to_string()) } else { msix_app_id(&p) }; + if aumid.is_some_and(|id| activate_app(&id)) { + return; + } + // A program is a path to Explorer, and Explorer is not the shell on a WinRust machine: `explorer.exe wt.exe` only + // opens a folder window, so the Win+X "Terminal" item showed the file manager and a task manager never started. + if winrust_common::launch::is_program(&p) { + winrust_common::launch::program(&p); + return; + } + // Everything else through explorer.exe: it hands paths, shortcuts, shell addresses and URIs to the shell with the + // desktop user's normal token. ShellExecuteW from here would inherit this bar's admin rights, and an elevated app + // cannot receive files dragged in from normal windows (UIPI), and PrtSc / Win+Shift+S (ms-screenclip:) do not work + // when started elevated. With an argument and no explorer shell running, explorer.exe hands the target to its COM + // host and does not become a shell or raise a taskbar. + if Command::new("explorer.exe").arg(&p).spawn().is_err() { + ShellExecuteW(null_mut(), wide("open").as_ptr(), wide(&p).as_ptr(), null(), null(), SW_SHOWNORMAL); + } +} + +/// Starts the disk cleaner (rs-du, installed next to the task manager) elevated: it reads the raw volume. +/// Right-click menu of an app button, like the Windows taskbar's jump list: pin / unpin, close, end process. +fn wstr_of(w: &[u16]) -> String { + String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())]) +} + +/// "1 окно", "3 окна", "5 окон"; "1 window", "2 windows"; "3 个窗口" (no plural in Chinese). +fn windows_ru(n: usize) -> String { + use i18n::Lang; + let w = match lang!() { + Lang::En => if n == 1 { "window" } else { "windows" }, + Lang::Pt => if n == 1 { "janela" } else { "janelas" }, + Lang::Ja => "ウィンドウ", + Lang::Zh => "个窗口", + Lang::Ru => match (n % 10, n % 100) { + (1, x) if x != 11 => "окно", + (2..=4, x) if !(12..=14).contains(&x) => "окна", + _ => "окон", + }, + }; + format!("{n} {w}") +} + +/// Right-click menu of an app button, like the Windows 11 jump list: the app on top, its windows (when there are several), +/// open / pin / Start, then close and end process in red. +unsafe fn app_menu(hwnd: HWND, h: i32) { + #[derive(Clone, Copy)] + enum A { + Win(HWND), + Open, + Pin, + Left, + Right, + Start, + Close, + Kill, + } + let (wins, pin, bicon) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin, b.icon)).unwrap_or((vec![], None, null_mut()))); + let exe = wins.first().map(|&w| exe_of(w)).unwrap_or_default(); + let (lnk, picon) = pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| (wstr_of(&x.lnk), x.icon)))).unwrap_or_default(); + let launch = if lnk.is_empty() { exe.clone() } else { lnk.clone() }; + let stem = std::path::Path::new(&launch).file_stem().unwrap_or_default().to_string_lossy().to_string(); + let name: String = stem.chars().take(1).flat_map(char::to_uppercase).chain(stem.chars().skip(1)).collect(); + let sub = match (wins.len(), pin.is_some()) { + (0, _) => t!("Закреплено · не запущено", "Pinned · not running", ja: "固定済み · 未起動", pt: "Fixado · não está em execução", zh: "已固定 · 未运行").to_string(), + (n, true) => tf!("Закреплено · {}", "Pinned · {}", ja: "固定済み · {}", pt: "Fixado · {}", zh: "已固定 · {}", windows_ru(n)), + (n, false) => tf!("Запущено · {}", "Running · {}", ja: "実行中 · {}", pt: "Em execução · {}", zh: "运行中 · {}", windows_ru(n)), + }; + let icon = if picon.is_null() { bicon } else { picon }; + let mut items: Vec<(fly::MItem, A)> = Vec::new(); + if wins.len() > 1 { + for &w in wins.iter().take(6) { + let mut b = [0u16; 256]; + let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize; + items.push((fly::MItem { icon: icon_of(w), ..fly::MItem::new(String::from_utf16_lossy(&b[..n])) }, A::Win(w))); + } + } + if !launch.is_empty() { + let it = fly::MItem::new(if wins.is_empty() { t!("Открыть", "Open", ja: "開く", pt: "Abrir", zh: "打开") } else { t!("Новое окно", "New window", ja: "新しいウィンドウ", pt: "Nova janela", zh: "新建窗口") }); + items.push((if items.is_empty() { it } else { it.sep() }, A::Open)); + } + if pin.is_some() { + items.push((fly::MItem::new(t!("Открепить от панели", "Unpin from the bar", ja: "バーから固定を外す", pt: "Desafixar da barra", zh: "从任务栏取消固定")), A::Pin)); + } else if !exe.is_empty() { + items.push((fly::MItem::new(t!("Закрепить на панели", "Pin to the bar", ja: "バーに固定する", pt: "Fixar na barra", zh: "固定到任务栏")), A::Pin)); + } + if let Some(p) = pin.filter(|_| !lnk.is_empty()) { + let n = PINS.with_borrow(|p| p.len()); + if p > 0 { + items.push((fly::MItem::new(if vert() { t!("Выше", "Move up", ja: "上へ移動", pt: "Mover para cima", zh: "上移") } else { t!("Сдвинуть влево", "Move left", ja: "左へ移動", pt: "Mover para a esquerda", zh: "左移") }), A::Left)); + } + if p + 1 < n { + items.push((fly::MItem::new(if vert() { t!("Ниже", "Move down", ja: "下へ移動", pt: "Mover para baixo", zh: "下移") } else { t!("Сдвинуть вправо", "Move right", ja: "右へ移動", pt: "Mover para a direita", zh: "右移") }), A::Right)); + } + } + if !launch.is_empty() { + let s = fly::start_pinned(&launch); + items.push((fly::MItem::new(if s { t!("Убрать из Пуска", "Remove from Start", ja: "スタートから削除", pt: "Remover do Iniciar", zh: "从开始菜单移除") } else { t!("Добавить в Пуск", "Add to Start", ja: "スタートに追加", pt: "Adicionar ao Iniciar", zh: "添加到开始菜单") }), A::Start)); + } + if !wins.is_empty() { + items.push((fly::MItem::new(if wins.len() > 1 { t!("Закрыть все окна", "Close all windows", ja: "すべてのウィンドウを閉じる", pt: "Fechar todas as janelas", zh: "关闭所有窗口") } else { t!("Закрыть окно", "Close window", ja: "ウィンドウを閉じる", pt: "Fechar janela", zh: "关闭窗口") }).hint("Alt+F4").sep(), A::Close)); + items.push((fly::MItem::new(t!("Завершить процесс", "End process", ja: "プロセスを終了", pt: "Finalizar processo", zh: "结束进程")).danger(), A::Kill)); + } + let acts: Vec = items.iter().map(|x| x.1).collect(); + let items = items.into_iter().map(|x| x.0).collect(); + let first_pid = wins.first().map_or(0, |&w| { let mut pid = 0; GetWindowThreadProcessId(w, &mut pid); pid }); + fly::menu(tip_cx(&bar_layout(hwnd), h), Some((icon, "", name, sub)), items, move |i| { + match acts.get(i).copied() { + Some(A::Win(w)) => { + bring(w); + } + Some(A::Open) => open(&wide(&launch)), + Some(A::Pin) => { + // by path, not by the index seen when the menu opened: PINS may have changed meanwhile + match PINS.with_borrow(|p| p.iter().position(|x| !lnk.is_empty() && wstr_of(&x.lnk) == lnk)) { + Some(p) => unpin(p), + None if lnk.is_empty() => pin_exe(&exe, &proc_args(first_pid)), + None => {} + } + refresh_buttons(); // the buttons hold indices into PINS: a stale one would index past the end on the next paint + } + Some(a @ (A::Left | A::Right)) => { + // by path again; the new order is saved and load_pins takes it + if let Some(p) = PINS.with_borrow(|p| p.iter().position(|x| wstr_of(&x.lnk) == lnk)) { + let to = if matches!(a, A::Left) { p.wrapping_sub(1) } else { p + 1 }; + if PINS.with_borrow_mut(|v| (to < v.len()).then(|| v.swap(p, to))).is_some() { + let pins: Vec = PINS.with_borrow(|v| v.iter().map(|p| DragButton::Pin(p.lnk.clone())).collect()); + BUTTON_ORDER.with_borrow_mut(|order| { + let mut pins = pins.into_iter(); + for entry in order.iter_mut() { if matches!(entry, DragButton::Pin(_)) { if let Some(pin) = pins.next() { *entry = pin; } } } + }); + save_pin_order(); + refresh_buttons(); + } + } + } + Some(A::Start) => fly::start_toggle(&launch), + Some(A::Close) => wins.iter().for_each(|&w| close_window(w)), + Some(A::Kill) => { + let mut pids: Vec = wins + .iter() + .map(|&w| { + let mut pid = 0u32; + GetWindowThreadProcessId(w, &mut pid); + pid + }) + .collect(); + pids.sort_unstable(); + pids.dedup(); // several windows of one app: one kill (and at most one UAC prompt), not one per window + for pid in pids { + let p = OpenProcess(1, 0, pid); // PROCESS_TERMINATE; works on elevated apps when the bar itself runs elevated + if p.is_null() || TerminateProcess(p, 1) == 0 { + ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/F /T /PID {pid}")).as_ptr(), null(), SW_HIDE); + } + if !p.is_null() { + CloseHandle(p); + } + } + } + None => {} + } + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); + }); +} + +fn pin_dir() -> PathBuf { + appdata_file(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar") +} + +unsafe fn unpin(i: usize) { + let Some(p) = PINS.with_borrow_mut(|p| (i < p.len()).then(|| p.remove(i))) else { return }; + let n = p.lnk.iter().position(|&c| c == 0).unwrap_or(p.lnk.len()); + // remembered, or the next start would bring it back from the Windows taskbar's list + let key = pin_key(&p.lnk); + if !key.0.is_empty() { + let mut t = std::fs::read_to_string(unpinned_file()).unwrap_or_default(); + t.push_str(&key_line(&key)); + t.push('\n'); + let _ = std::fs::create_dir_all(appdata_file("topbar-taskband")); + let _ = std::fs::write(unpinned_file(), t); + } + let _ = std::fs::remove_file(String::from_utf16_lossy(&p.lnk[..n])); + DestroyIcon(p.icon); +} + +/// Arguments of a shortcut ("" if none). +unsafe fn lnk_args(lnk: &[u16]) -> String { + (|| -> Option { + let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; + sl.cast::().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?; + let mut b = [0u16; 2048]; + sl.GetArguments(&mut b).ok()?; + Some(wstr_of(&b)) + })() + .unwrap_or_default() +} + +/// What a running process was started with, minus the exe (e.g. `--profile-directory="Profile 2"`). +fn proc_args(pid: u32) -> String { + if pid == 0 { + return String::new(); + } + // the PEB first (microseconds); WMI only for a process that cannot be opened for reading + let cl = winrust_common::proc::cmdline(pid).or_else(|| wmi::string(r"root\cimv2", &format!("SELECT CommandLine FROM Win32_Process WHERE ProcessId={pid}"), "CommandLine")); + let cl = cl.map(|c| c.trim().to_string()).unwrap_or_default(); + let rest = match cl.strip_prefix('"') { + Some(r) => r.split_once('"').map_or("", |x| x.1), + None => cl.split_once(' ').map_or("", |x| x.1), + }; + rest.trim().to_string() +} + +/// Pins an app: a shortcut to its exe (with `args`) in the folder where Windows keeps taskbar pins. +/// A dropped .lnk is copied as it is, so its arguments (browser profile) and icon stay. Already pinned (same target and +/// arguments) = nothing. +unsafe fn pin_exe(path: &str, args: &str) { + let is_lnk = path.to_lowercase().ends_with(".lnk"); + // targets are compared with exe_of(), which is lower-case + let exe = if is_lnk { lnk_target(&wide(path)) } else { path.to_lowercase() }; + let args = if is_lnk { lnk_args(&wide(path)) } else { args.to_string() }; + let exe = exe.as_str(); + if exe.is_empty() || PINS.with_borrow(|p| p.iter().any(|p| p.target == exe && p.args == args)) { + return; + } + let stem = std::path::Path::new(if is_lnk { path } else { exe }).file_stem().unwrap_or_default().to_string_lossy().to_string(); + let name: String = stem.chars().enumerate().map(|(i, c)| if i == 0 { c.to_ascii_uppercase() } else { c }).collect(); + let _ = std::fs::create_dir_all(pin_dir()); + // a free name: two pins of one exe with different arguments (two browser profiles) must not overwrite each other + let Some(file) = (1..).map(|n| pin_dir().join(if n == 1 { format!("{name}.lnk") } else { format!("{name} ({n}).lnk") })).find(|p| !p.exists()) else { return }; + let lnk = wide(&file.to_string_lossy()); + let ok = if is_lnk && std::fs::copy(path, &file).is_ok() { + Some(()) + } else { + (|| -> Option<()> { + let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?; + sl.SetPath(PCWSTR(wide(exe).as_ptr())).ok()?; + if !args.is_empty() { + sl.SetArguments(PCWSTR(wide(&args).as_ptr())).ok()?; + } + sl.cast::().ok()?.Save(PCWSTR(lnk.as_ptr()), true).ok() + })() + }; + if ok.is_some() { + // pinned again: no longer on the unpinned list + let line = key_line(&(exe.to_string(), args.to_lowercase())); + if let Ok(t) = std::fs::read_to_string(unpinned_file()) { + let _ = std::fs::write(unpinned_file(), t.lines().filter(|l| *l != line).map(|l| format!("{l}\n")).collect::()); + } + let icon = lnk_icon(&lnk, exe); + PINS.with_borrow_mut(|p| p.push(Pin { lnk, target: exe.to_string(), args, aumid: String::new(), icon })); + } +} + +/// Files dropped on the bar: on the Start button they are added to Start (the panel opens and the new row pulses), +/// anywhere else they are pinned to the bar. +unsafe fn on_drop(hwnd: HWND, hd: HDROP) { + let mut pt: POINT = zeroed(); + DragQueryPoint(hd, &mut pt); + let n = DragQueryFileW(hd, u32::MAX, null_mut(), 0); + let files: Vec = (0..n) + .map(|i| { + let len = DragQueryFileW(hd, i, null_mut(), 0) as usize; + let mut b = vec![0u16; len + 1]; + DragQueryFileW(hd, i, b.as_mut_ptr(), b.len() as u32); + String::from_utf16_lossy(&b[..len]) + }) + .collect(); + DragFinish(hd); + let h = hit(hwnd, pt.x, pt.y); + press(if h == NONE { 0 } else { h }); + if h == 0 { + let added: Vec<&String> = files.iter().filter(|f| fly::start_pin(f)).collect(); + let name = |p: &str| std::path::Path::new(p).file_stem().unwrap_or_default().to_string_lossy().to_string(); + if !fly::is_open(fly::Kind::Start) { + fly::toggle(fly::Kind::Start); + } + fly::note(&match added.len() { + 0 => "Already in Start".to_string(), + 1 => format!("Added to Start: {}", name(added[0])), + n => format!("Added {n} items to Start"), + }); + } else { + files.iter().for_each(|f| pin_exe(f, "")); + refresh_buttons(); + } + InvalidateRect(hwnd, null(), 0); +} + +/// The junk remover (purge, installed on request): lists what it would delete and asks for YES in its own elevated console. +pub(crate) fn purge_installed() -> bool { + std::env::var_os("ProgramFiles").is_some_and(|pf| PathBuf::from(pf).join(r"purge\purge.exe").is_file()) +} + +unsafe fn open_purge() { + if let Some(pf) = std::env::var_os("ProgramFiles") { + let exe = PathBuf::from(pf).join(r"purge\purge.exe"); + ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("--ask").as_ptr(), null(), SW_SHOWNORMAL); + } +} + +unsafe fn open_cleaner() { + let Some(pf) = std::env::var_os("ProgramFiles") else { return }; + let exe = PathBuf::from(pf).join(r"rtaskmgr\rs-du.exe"); + if exe.is_file() { + ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("C: --clean --ask").as_ptr(), null(), SW_SHOWNORMAL); + } +} + +unsafe extern "system" fn find_launcher(h: HWND, lp: LPARAM) -> i32 { + let mut cls = [0u16; 32]; + let n = GetClassNameW(h, cls.as_mut_ptr(), 32).max(0) as usize; + if String::from_utf16_lossy(&cls[..n]) == "rs_launcher" { + *(lp as *mut HWND) = h; + return 0; + } + 1 +} + +/// Asks the running rs-launcher to show itself by sending the message its Alt+Space hotkey produces. +/// Faking the key presses did not reliably reach it from this (elevated) process. false = it is not running. +unsafe fn open_launcher() -> bool { + let mut h: HWND = null_mut(); + EnumWindows(Some(find_launcher), &mut h as *mut _ as LPARAM); + if h.is_null() { + return false; + } + AllowSetForegroundWindow(u32::MAX); // else no focus, so no click-outside close (#292) + PostMessageW(h, WM_HOTKEY, 1, (MOD_ALT | MOD_NOREPEAT) as isize | ((VK_SPACE as isize) << 16)); + true +} + +/// Right click on Start: the Win+X menu (Explorer's own is gone with the bar). +unsafe fn start_menu() { + let bar = BAR.load(Relaxed) as HWND; + // (label in ru/en/ja/pt/zh, target); "!" targets are actions of ours, the rest goes through `open` + let tools: [(&str, &str, &str, &str, &str, &str); 15] = [ + ("Приложения и возможности", "Apps and Features", "アプリと機能", "Aplicativos e Recursos", "应用和功能", "ms-settings:appsfeatures"), + ("Электропитание", "Power Options", "電源オプション", "Opções de Energia", "电源选项", "powercfg.cpl"), + ("Просмотр событий", "Event Viewer", "イベント ビューアー", "Visualizador de Eventos", "事件查看器", "eventvwr.msc"), + ("Система", "System", "システム", "Sistema", "系统", "ms-settings:about"), + ("Диспетчер устройств", "Device Manager", "デバイス マネージャー", "Gerenciador de Dispositivos", "设备管理器", "devmgmt.msc"), + ("Сетевые подключения", "Network Connections", "ネットワーク接続", "Conexões de Rede", "网络连接", "ms-settings:network"), + ("Управление дисками", "Disk Management", "ディスクの管理", "Gerenciamento de Disco", "磁盘管理", "diskmgmt.msc"), + ("Управление компьютером", "Computer Management", "コンピューターの管理", "Gerenciamento do Computador", "计算机管理", "compmgmt.msc"), + ("Терминал", "Terminal", "ターミナル", "Terminal", "终端", "!term"), + ("Диспетчер задач", "Task Manager", "タスク マネージャー", "Gerenciador de Tarefas", "任务管理器", "taskmgr.exe"), + ("Параметры", "Settings", "設定", "Configurações", "设置", "ms-settings:"), + ("Проводник", "File Explorer", "エクスプローラー", "Explorador de Arquivos", "文件资源管理器", "shell:MyComputerFolder"), + ("Выполнить", "Run", "ファイル名を指定して実行", "Executar", "运行", "!run"), + ("Рабочий стол", "Desktop", "デスクトップ", "Área de Trabalho", "桌面", "!desktop"), + ("Представление задач", "Task View", "タスク ビュー", "Visão de Tarefas", "任务视图", "!taskview"), + ]; + let power = [("Блокировка", "Lock", "ロック", "Bloquear", "锁定", "!lock"), ("Сон", "Sleep", "スリープ", "Suspender", "睡眠", "!sleep"), ("Перезагрузка", "Restart", "再起動", "Reiniciar", "重启", "!restart"), ("Завершение работы", "Shut down", "シャットダウン", "Desligar", "关机", "!shutdown")]; + let mut items = Vec::new(); + let mut targets = Vec::new(); + for (i, (ru, en, ja, pt, zh, to)) in tools.iter().chain(power.iter()).enumerate() { + let it = fly::MItem::new(t!(*ru, *en, ja: *ja, pt: *pt, zh: *zh)); + items.push(if i == tools.len() { it.sep() } else { it }); + targets.push(*to); + } + let head = (null_mut(), "\u{E700}", t!("Пуск", "Start", ja: "開始", pt: "Iniciar", zh: "启动").to_string(), String::new()); + fly::menu(tip_cx(&bar_layout(bar), 0), Some(head), items, move |i| { + let Some(&to) = targets.get(i) else { return }; + let quiet = |c: &mut Command| { let _ = c.creation_flags(NO_WINDOW).spawn(); }; + match to { + "!term" => { + let wt = std::env::var_os("LOCALAPPDATA").map(|b| PathBuf::from(b).join(r"Microsoft\WindowsApps\wt.exe")).filter(|p| p.is_file()); + open(&wide(if wt.is_some() { "wt.exe" } else { "powershell.exe" })); + } + "!run" => run_box(), + "!desktop" => winrust_common::desktop::toggle(), + "!taskview" => keys(&[VK_LWIN, VK_TAB]), // virtual desktops (#83) + "!lock" => quiet(Command::new("rundll32.exe").args(["user32.dll,LockWorkStation"])), + "!sleep" => fly::sleep_now(), + "!restart" => quiet(Command::new("shutdown").args(["/r", "/t", "0"])), + "!shutdown" => quiet(Command::new("shutdown").args(["/s", "/t", "0"])), + _ => open(&wide(to)), + } + }); +} + +/// Puts the open, not minimized windows side by side in the work area. +/// A window dropped with the pointer on the screen edge snaps (Windows 11 style): left / right edge = that half of the monitor's +/// work area, top edge = maximized. Only resizable windows; without Explorer nothing else does this. +unsafe extern "system" fn snap_proc(_: windows_sys::Win32::UI::Accessibility::HWINEVENTHOOK, ev: u32, w: HWND, id: i32, _: i32, _: u32, _: u32) { + if id != 0 || w.is_null() { + return; + } + if ev == 0x000A { + // the drag starts: its size, so that the end can tell a move (magnet) from a resize (left alone) + let r = frame(w); + DRAG_SIZE.set((r.right - r.left, r.bottom - r.top)); + return; + } + if IsWindowVisible(w) == 0 || IsZoomed(w) != 0 { + return; + } + if stick() && !edge_snap(w) { + let r = frame(w); + if DRAG_SIZE.get() == (r.right - r.left, r.bottom - r.top) { + magnet_window(w, r); + } + return; + } + if GetWindowLongW(w, GWL_STYLE) as u32 & WS_THICKFRAME == 0 { + return; + } + let mut pt: POINT = zeroed(); + GetCursorPos(&mut pt); + let mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST); + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(mon, &mut mi) == 0 { + return; + } + let (m, a) = (mi.rcMonitor, mi.rcWork); + let half = (a.right - a.left) / 2; + if pt.y <= m.top + 1 { + ShowWindow(w, SW_MAXIMIZE); + } else if pt.x <= m.left + 1 { + SetWindowPos(w, null_mut(), a.left, a.top, half, a.bottom - a.top, SWP_NOZORDER | SWP_NOACTIVATE); + } else if pt.x >= m.right - 2 { + SetWindowPos(w, null_mut(), a.left + half, a.top, half, a.bottom - a.top, SWP_NOZORDER | SWP_NOACTIVATE); + } +} + +// ---------- window magnet (#133): a dragged window that ends near a screen edge or another window's edge sticks to it ---------- + +thread_local! { + static DRAG_SIZE: Cell<(i32, i32)> = const { Cell::new((0, 0)) }; +} +static STICK: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0xFF); // 0 off, 1 on, 0xFF not read yet + +fn stick_file() -> PathBuf { + appdata_file("topbar-stick.txt") +} + +pub(crate) fn stick() -> bool { + if STICK.load(Relaxed) == 0xFF { + STICK.store(std::fs::read_to_string(stick_file()).is_ok_and(|s| s.trim() == "1") as u8, Relaxed); + } + STICK.load(Relaxed) == 1 +} + +pub(crate) fn set_stick(on: bool) { + STICK.store(on as u8, Relaxed); + let _ = std::fs::write(stick_file(), if on { "1" } else { "0" }); +} + +/// Would the edge snap above take this drop (the pointer on a screen edge)? +unsafe fn edge_snap(w: HWND) -> bool { + let mut pt: POINT = zeroed(); + GetCursorPos(&mut pt); + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + GetMonitorInfoW(MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 + && GetWindowLongW(w, GWL_STYLE) as u32 & WS_THICKFRAME != 0 + && (pt.y <= mi.rcMonitor.top + 1 || pt.x <= mi.rcMonitor.left + 1 || pt.x >= mi.rcMonitor.right - 2) +} + +/// The window's visible frame (without the invisible resize borders Windows 10/11 add around it). +unsafe fn frame(w: HWND) -> RECT { + let mut r: RECT = zeroed(); + if DwmGetWindowAttribute(w, 9, &mut r as *mut _ as *mut _, size_of::() as u32) != 0 { + GetWindowRect(w, &mut r); // DWMWA_EXTENDED_FRAME_BOUNDS failed + } + r +} + +/// How far to move `r` so that its nearest edge within `d` px lands on one of the edges (0 when none is that close). +/// `xs`/`ys`: the vertical / horizontal lines it may stick to. +fn magnet(r: RECT, xs: &[i32], ys: &[i32], d: i32) -> (i32, i32) { + let best = |a: i32, b: i32, es: &[i32]| es.iter().flat_map(|&e| [e - a, e - b]).filter(|v| v.abs() <= d).min_by_key(|v| v.abs()).unwrap_or(0); + (best(r.left, r.right, xs), best(r.top, r.bottom, ys)) +} + +unsafe fn magnet_window(w: HWND, r: RECT) { + let mut mi: MONITORINFO = zeroed(); + mi.cbSize = size_of::() as u32; + if GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mut mi) == 0 { + return; + } + let a = mi.rcWork; + let (mut xs, mut ys) = (vec![a.left, a.right], vec![a.top, a.bottom]); + // the other windows' edges: only those beside this one (overlapping along the other axis), so a far window does not pull + let mut v: Vec = Vec::new(); + EnumWindows(Some(collect), &mut v as *mut _ as LPARAM); + for o in v.into_iter().filter(|&o| o != w && IsIconic(o) == 0 && IsZoomed(o) == 0) { + let f = frame(o); + if f.top < r.bottom && f.bottom > r.top { + xs.extend([f.left, f.right]); + } + if f.left < r.right && f.right > r.left { + ys.extend([f.top, f.bottom]); + } + } + let (dx, dy) = magnet(r, &xs, &ys, sc(14)); + if (dx, dy) != (0, 0) { + let mut wr: RECT = zeroed(); + GetWindowRect(w, &mut wr); + SetWindowPos(w, null_mut(), wr.left + dx, wr.top + dy, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } +} + +/// Win+1..9: opens the n-th app button's pin, or brings its window up (a second press on the only window minimizes it, +/// with several windows each press moves on to the next one). +unsafe fn win_num(n: usize) { + let Some((wins, pin)) = BTNS.with_borrow(|b| b.get(n + 1).map(|b| (b.wins.clone(), b.pin))) else { return }; + if wins.is_empty() { + if let Some(l) = pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))) { + open(&l); + } + return; + } + let i = wins.iter().position(|&w| w == GetForegroundWindow()); + let w = i.map_or(wins[0], |i| wins[(i + 1) % wins.len()]); + if wins.len() == 1 && i.is_some() { + note_minimize(w); + ShowWindow(w, SW_MINIMIZE); + } else { + bring(w); + } +} + +unsafe fn tile_windows() { + let wins: Vec = BTNS.with_borrow(|b| b.iter().flat_map(|b| b.wins.iter().copied()).filter(|&w| IsIconic(w) == 0).collect()); + if wins.is_empty() { + return; + } + let mut wa: RECT = zeroed(); + SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut wa as *mut _ as *mut _, 0); + for &w in &wins { + ShowWindow(w, SW_RESTORE); // a maximized window ignores tiling + } + TileWindows(null_mut(), MDITILE_VERTICAL, &wa, wins.len() as u32, wins.as_ptr()); +} + +unsafe fn click(h: i32, left: bool, mid: bool) { + match h { + SEARCH if left => { + // our search (rs-launcher listens for Alt+Space); without it the Start panel's own search + let exe = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join(r"rs-search\rs-launcher.exe")).filter(|p| p.is_file()); + if let Some(exe) = exe { + if !open_launcher() { + // killed: restart it; faked Alt+Space opens the window menu (#291) + let _ = i18n::launch::program(&exe.to_string_lossy()); + fly::toggle(fly::Kind::Start); + } + } else { + fly::toggle(fly::Kind::Start); + } + } + // virtual desktops (#83). Task View lives in explorer's shell: without it Win+Tab does nothing (#120), so the button + // opens our window grid instead (the Alt+Tab one: click a card, arrows + Enter, Esc or the button again closes) + TASKVIEW if left && !find_other("Shell_TrayWnd").is_null() => keys(&[VK_LWIN, VK_TAB]), + TASKVIEW if left => { + if IsWindowVisible(SWWND.get()) != 0 { + SWITCHING.store(false, Relaxed); + alt_done(true); + } else { + SWITCHING.store(true, Relaxed); + alt_tab(false); + } + } + // left: the language picker; right: straight to the next one (Win+Space is explorer's, gone under rs-shell) + LANG if left => lang_menu(BAR.load(Relaxed) as HWND), + LANG => next_lang(BAR.load(Relaxed) as HWND, false), + WIFI_I => fly::toggle_click(if left { fly::Kind::Quick } else { fly::Kind::Wifi }), // right click: the network list + VOL_I | BAT_I => fly::toggle_click(fly::Kind::Quick), + CLOCK if left => fly::toggle_click(fly::Kind::Cal), + CLOCK => { + // right click: like Windows 11, a menu with the date and time and notification settings (#126) + let items = vec![ + fly::MItem::new(t!("Настройка даты и времени", "Adjust date and time", ja: "日付と時刻を調整する", pt: "Ajustar data e hora")), + fly::MItem::new(t!("Параметры уведомлений", "Notification settings", ja: "通知の設定", pt: "Configurações de notificação")), + ]; + fly::menu(tip_cx(&bar_layout(BAR.load(Relaxed) as HWND), CLOCK), None, items, |i| { + if i == 0 { + // the classic applet opens at once with or without Explorer; the Settings page needs Explorer started first + let _ = Command::new("control.exe").arg("timedate.cpl").creation_flags(NO_WINDOW).spawn(); + } else { + open(&wide("ms-settings:notifications")); + } + }); + } + SHOWDESK if left => winrust_common::desktop::toggle(), + POW_R | POW_S if left => power_click(h), + GEAR => style_menu(), + TAPP..=-900 => { + let slot = (h - TAPP) as usize; + if slot == 0 { + if left { + fly_toggle(); + } + } else if mid { + if let Some(k) = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| x.key.clone()))) { + toggle_shown(&k); // back into the flyout + } + } else { + let ti = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| (x.hwnd, x.uid, x.cb, x.ver)))); + ti.into_iter().for_each(|ti| tray_click(ti, left)); + } + } + 0 if left => fly::toggle_click(fly::Kind::Start), + 0 => start_menu(), + 1.. => { + let (wins, lnk) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))))).unwrap_or_default()); + match (wins.first(), left) { + // not running: launch the pinned app (a Store app may have updated since the pins were loaded) + (None, true) => lnk.iter().for_each(|l| { + PINS.with_borrow_mut(|p| p.iter_mut().filter(|x| x.lnk == *l).for_each(|x| x.target = fix_msix_pin(l, &x.target).unwrap_or(std::mem::take(&mut x.target)))); + open(l) + }), + (Some(&w), false) => close_window(w), // right / middle click + // several windows of one app: pick which one (the same list the right-click menu opens with) + (Some(_), true) if wins.len() > 1 => app_menu(BAR.load(Relaxed) as HWND, h), + (Some(&w), true) => { + // like the Windows taskbar: the active app's button minimizes it, a minimized one restores, any other raises + let fg = GetForegroundWindow(); + if wins.contains(&fg) && IsIconic(fg) == 0 { + note_minimize(fg); + ShowWindow(fg, SW_MINIMIZE); + } else { + bring(w); + } + } + _ => {} + } + } + _ => {} + } +} + +#[repr(C)] +struct ShellHookInfo { + hwnd: HWND, + rc: RECT, +} + +/// HSHELL_GETMINRECT: a window is minimizing / restoring and asks where its taskbar button is: the shrink animation +/// flies there instead of to the bottom left corner of the screen. +unsafe fn min_rect(info: *mut ShellHookInfo, bar: HWND) { + let (w, l) = ((*info).hwnd, bar_layout(bar)); + let exe = exe_of(w); + let i = BTNS.with_borrow(|b| b.iter().position(|b| b.wins.contains(&w)).or_else(|| b.iter().position(|b| !exe.is_empty() && b.wins.first().is_some_and(|&x| exe_of(x) == exe)))); + let x = match i { + Some(i) => l.btn_pos(i as i32), + None => (l.x0 + l.apps.0) / 2, // no button (yet): the middle of the bar + }; + if vert() { + let left = bar_x() + sc(4); + (*info).rc = RECT { left, top: x, right: left + bar_h() - sc(8), bottom: x + l.bw }; + return; + } + let (top, x) = (bar_top() + sc(4), x + bar_x_w().0); + (*info).rc = RECT { left: x, top, right: x + l.bw, bottom: top + bar_h() - sc(8) }; +} + +/// Screen x of the middle of a bar element, for its tooltip and menus. +unsafe fn tip_cx(l: &Layout, h: i32) -> i32 { + // along the bar: screen x for a bottom bar, screen y for a side bar + (if vert() { 0 } else { bar_x_w().0 }) + match h { + GEAR => l.gear_x + sc(GEAR_X.1 / 2), + SEARCH => l.x0 + l.bw / 2, + TASKVIEW => l.x0 + (l.bw + l.gap) + l.bw / 2, + CLOCK => (l.clock.0 + l.clock.1) / 2, + SHOWDESK => l.clock.1 + sc(3), + POW_R | POW_S => l.power.0 + power_keys().iter().position(|&k| k == h).unwrap_or(0) as i32 * sc(32) + sc(16), + LANG => l.sys.0 + sc(21), + WIFI_I => l.sys.0 + sc(58), + VOL_I => l.sys.0 + sc(90), + BAT_I => l.sys.0 + sc(130), + t if (TAPP..TAPP + 100).contains(&t) => l.apps.0 + (t - TAPP) * sc(24) + sc(12), + i => l.btn_pos(i) + l.bw / 2, + } +} + +unsafe fn bar_layout(hwnd: HWND) -> Layout { + let mut r: RECT = zeroed(); + GetClientRect(hwnd, &mut r); + layout(if vert() { r.bottom } else { r.right }) +} + +/// Registers the bar as an appbar with explorer (again after explorer restarts: its list starts empty). +unsafe fn appbar_new(hwnd: HWND) { + let mut ab: APPBARDATA = zeroed(); + ab.cbSize = size_of::() as u32; + ab.hWnd = hwnd; + ab.uCallbackMessage = CALLBACK; + SHAppBarMessage(ABM_NEW, &mut ab); + EXP_TRAY.set(tray()[0]); +} + +unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if msg != 0 && msg == SH_MSG.get() { + if wp == 5 && lp != 0 { + min_rect(lp as *mut ShellHookInfo, hwnd); // HSHELL_GETMINRECT + return 1; + } + let w = lp as HWND; + match wp { + 0x8006 => FLASH.with_borrow_mut(|f| if !f.contains(&w) { f.push(w) }), // HSHELL_FLASH + 4 | 0x8004 | 2 => FLASH.with_borrow_mut(|f| f.retain(|&x| x != w)), // activated (HSHELL_WINDOWACTIVATED / RUDEAPPACTIVATED), destroyed + _ => return 0, + } + InvalidateRect(hwnd, null(), 0); + second::invalidate(); + return 0; + } + if msg != 0 && msg == TB_MSG.get() { + // also our own announce(): act only when explorer's taskbar is a new window (explorer restarted / came back) + let t = tray()[0]; + if !t.is_null() && t != EXP_TRAY.get() { + appbar_new(hwnd); + hide_taskbar(); + place(hwnd); + } + return 0; + } + match msg { + WM_PAINT => paint(hwnd), + WM_ERASEBKGND => return 1, + WM_TIMER if wp == 2 => { + KillTimer(hwnd, 2); + let h = HOT.get(); + if h != NONE && !fly::any_open() { + let cx = tip_cx(&bar_layout(hwnd), h); + // an app button with windows shows their live previews (#92), anything else its tip + if !thumbs::show_preview(h, cx) { + thumbs::hide_preview(); + show_tip(tip_text(h), cx); + } + } + } + WM_TIMER if wp == 6 => hide_tip(hwnd), // the volume readout after a wheel turn + WM_TIMER if wp == 3 => fs_update(hwnd), + WM_TIMER if wp == 7 => { + KillTimer(hwnd, 7); + let (tid, before, next) = LANG_TRY.get(); + if GetKeyboardLayout(tid) as usize == before && !EXPLORER_UP.load(Relaxed) { + // no explorer, so no system switcher to fall back on: ask the app's top-level window as well (some apps + // only listen there, not on the focused child) + PostMessageW(app_window(), WM_INPUTLANGCHANGEREQUEST, 0, next as isize); + } else if GetKeyboardLayout(tid) as usize == before { + let w = app_window(); + if GetForegroundWindow() != w { + force_fg(w); // Win+Space switches the window in front: put the app back there first + } + keys(&[VK_LWIN, VK_SPACE]); // the app ignored the request: the system switcher always works (with explorer) + } + InvalidateRect(hwnd, null(), 0); // the label shows the new language right away + } + WM_TIMER if wp == 4 => { + InvalidateRect(hwnd, null(), 0); + } + WM_TIMER if wp == 5 => bar_step(hwnd), + WIN_START => fly::toggle(fly::Kind::Start), + ALT_TAB => alt_tab(wp == 1), + WIN_NUM => win_num(wp), + WIN_X => start_menu(), + WIN_V => { + let (x, w) = bar_x_w(); + hist::show(hwnd, x + w / 2); + } + 0x031D => hist::on_update(hwnd), // WM_CLIPBOARDUPDATE + NEXT_LANG => next_lang(hwnd, wp == 1), + TILE_WINDOWS => tile_windows(), + ALT_UP if wp == 2 => alt_close(), + ALT_UP => alt_done(wp == 1), + SNIP if wp == 1 => screenshot_notice(hwnd), + SNIP if wp == 2 => clip_notice(hwnd), + SNIP => clip::start(), + VOLKEY => { + if wp == 2 { toggle_mute() } else { add_volume(if wp == 0 { 4 } else { -4 }) } + KillTimer(hwnd, 2); + show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I)); + SetTimer(hwnd, 6, 1200, None); + InvalidateRect(hwnd, null(), 0); + } + WM_DROPFILES => on_drop(hwnd, wp as HDROP), + WM_TIMER if wp == 8 => { + // window events since the last look (win_event): one refresh for the whole burst + KillTimer(hwnd, 8); + WIN_DIRTY.set(false); + hide_taskbar_if_shown(); + refresh_windows(); + repaint_if_changed(hwnd, false); + } + WM_TIMER => { + hide_taskbar_if_shown(); + if work_area_drifted() { place(hwnd); } + refresh_status(); + if widgets::poll() { + // a mod's widget text changed (a file date check, once a second); this tick may run on another window + InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0); + } + if TICK.get() % 5 == 0 { + refresh_windows(); // safety net for a window event the hook did not report + } + fs_update(hwnd); // style switches (auto-hide, dock) take effect without a window event + drag_hover(hwnd); + keep_in_place(hwnd); + repaint_if_changed(hwnd, true); + } + WM_MOUSEMOVE => { + let x = (lp & 0xffff) as i16 as i32; + let y = (lp >> 16) as i16 as i32; + BUTTON_DRAG.with_borrow_mut(|d| if let Some(d) = d { if (x - d.start_x).abs() >= sc(4) || (y - d.start_y).abs() >= sc(4) { d.moved = true; } }); + let moving = BUTTON_DRAG.with_borrow(|d| d.as_ref().filter(|d| d.moved).map(|d| d.button.clone())); + if let Some(from) = moving { + if let Some(to) = drag_target(hwnd, x, y) { reorder_buttons(from, to); } + hide_tip(hwnd); + InvalidateRect(hwnd, null(), 0); + return 0; + } + let h = hit(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); + let mut tme = TRACKMOUSEEVENT { cbSize: size_of::() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 }; + TrackMouseEvent(&mut tme); + if HOT.replace(h) != h { + hide_tip(hwnd); + if h != NONE { + SetTimer(hwnd, 2, 450, None); + } + InvalidateRect(hwnd, null(), 0); + } + } + WM_MOUSELEAVE => { + hide_tip(hwnd); + HOT.set(-1); + InvalidateRect(hwnd, null(), 0); + } + WM_MOUSEWHEEL => { + add_volume(if (wp >> 16) as i16 > 0 { 2 } else { -2 }); // wheel anywhere on the bar = volume + press(VOL_I); // the speaker flashes so it is clear what the wheel changed + KillTimer(hwnd, 2); + if !fly::any_open() { + show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I)); // and the level shows above it for a moment + SetTimer(hwnd, 6, 1200, None); + } + InvalidateRect(hwnd, null(), 0); + } + WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => { + let x = (lp & 0xffff) as i16 as i32; + let y = (lp >> 16) as i16 as i32; + let h = hit(hwnd, x, y); + if msg == WM_LBUTTONDOWN { + if let Some(button) = button_key(h) { + BUTTON_DRAG.set(Some(ButtonDrag { button, start_x: x, start_y: y, moved: false })); + SetCapture(hwnd); + hide_tip(hwnd); + press(h); + InvalidateRect(hwnd, null(), 0); + return 0; + } + } + let x = if vert() { (lp >> 16) as i16 as i32 } else { x }; // position along the bar + hide_tip(hwnd); + thumbs::hide_preview(); + if h != NONE { + press(h); + } + if h == NONE && msg == WM_RBUTTONDOWN { + fly::context_menu(x); // right click on an empty spot + } else if h >= 1 && msg == WM_RBUTTONDOWN { + app_menu(hwnd, h); + } else { + click(h, msg == WM_LBUTTONDOWN, msg == WM_MBUTTONDOWN); + } + InvalidateRect(hwnd, null(), 0); + } + WM_LBUTTONUP => { + let drag = BUTTON_DRAG.take(); + if let Some(drag) = drag { + ReleaseCapture(); + let target = hit(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32); + if drag.moved { + if let Some(to) = drag_target(hwnd, (lp & 0xffff) as i16 as i32, (lp >> 16) as i16 as i32) { reorder_buttons(drag.button, to); } + save_button_order(); + } else if button_key(target).as_ref() == Some(&drag.button) { + click(target, true, false); + } + InvalidateRect(hwnd, null(), 0); + } + } + WM_CAPTURECHANGED => { if BUTTON_DRAG.take().is_some_and(|d| d.moved) { save_button_order(); } } + CALLBACK => { + if wp == ABN_FULLSCREENAPP as usize { + fs_update(hwnd); + } else if wp == ABN_POSCHANGED as usize { + place(hwnd); + } + } + WM_DISPLAYCHANGE => place(hwnd), + WM_SETTINGCHANGE if wp == SPI_SETWORKAREA as usize => { + if work_area_drifted() { place(hwnd); } + } + WM_DESTROY => { + let mut ab: APPBARDATA = zeroed(); + ab.cbSize = size_of::() as u32; + ab.hWnd = hwnd; + SHAppBarMessage(ABM_REMOVE, &mut ab); + set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // ours: give the strip back + second::release(); + show_taskbar(OLD_STATE.get()); + forget_taskbar_state(); + DestroyWindow(HOST.replace(null_mut())); + announce(); // icons go back to explorer's tray + PostQuitMessage(0); + } + _ => return DefWindowProcW(hwnd, msg, wp, lp), + } + 0 +} + +fn main() { + unsafe { + if std::env::args().any(|a| a == "--restore") { + show_taskbar(saved_taskbar_state().unwrap_or(ABS_ALWAYSONTOP as usize)); + forget_taskbar_state(); + set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // a killed bar's reserved strip + second::restore_work_areas(); + announce(); // a killed bar took its tray icons with it; apps re-register with explorer + return; + } + if std::env::args().any(|a| a == "--shot") { + SetProcessDPIAware(); + let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed()); + inp.GdiplusVersion = 1; + GdiplusStartup(&mut tok, &inp, null_mut()); + screenshot(); + return; + } + // `topbar --preview quick|wifi`: one flyout on its own (no bar, no hooks), to look at a style change; the process is closed by hand + if let Some(p) = std::env::args().skip_while(|a| a != "--preview").nth(1) { + SetProcessDPIAware(); + let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed()); + inp.GdiplusVersion = 1; + GdiplusStartup(&mut tok, &inp, null_mut()); + fly::init(GetModuleHandleW(null())); + fly::PREVIEW.store(true, Relaxed); + fly::toggle(if p == "wifi" { fly::Kind::Wifi } else { fly::Kind::Quick }); + let mut msg: MSG = zeroed(); + while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + return; + } + // Atomic single-instance guard (FindWindow alone raced when two launchers started us at once); the handle lives until exit. + let m = windows_sys::Win32::System::Threading::CreateMutexW(null(), 0, wide("Local\\topbar-single").as_ptr()); + if m.is_null() || GetLastError() == ERROR_ALREADY_EXISTS || !FindWindowW(wide("topbar").as_ptr(), null()).is_null() { + return; // already running + } + let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); + // Without explorer nobody hides minimized windows: they sit as small caption stubs at the bottom left of the screen. + // ARW_HIDE moves them off screen (this session only: fWinIni 0 does not touch the saved setting). + let mut mm: MINIMIZEDMETRICS = zeroed(); + mm.cbSize = size_of::() as u32; + if SystemParametersInfoW(SPI_GETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0) != 0 { + mm.iArrange |= ARW_HIDE as i32; + SystemParametersInfoW(SPI_SETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0); + } + let (mut gtok, mut gin): (usize, GdiplusStartupInput) = (0, zeroed()); + gin.GdiplusVersion = 1; + GdiplusStartup(&mut gtok, &gin, null_mut()); // anti-aliased shapes; fill() falls back to GDI if this failed + TB_MSG.set(RegisterWindowMessageW(wide("TaskbarCreated").as_ptr())); + SH_MSG.set(RegisterWindowMessageW(wide("SHELLHOOK").as_ptr())); + SetProcessDPIAware(); + let dc = GetDC(null_mut()); + SCALE.set(GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0); + ReleaseDC(null_mut(), dc); + SHOWN.set(std::fs::read_to_string(appdata_file("topbar-tray.txt")).ok().map(|s| s.lines().map(str::to_string).collect())); + load_pins(); + fly::init(GetModuleHandleW(null())); + thread::spawn(fly::load_apps); + thread::spawn(winrust_common::eco::auto_loop); // efficiency mode for background CPU hogs while the Game profile is on + thread::spawn(winrust_common::mem::auto_loop); // standby purge when memory runs short, switched on from the task manager's Speed page + let hi = GetModuleHandleW(null()); + let class = wide("topbar"); + let wc = WNDCLASSW { lpfnWndProc: Some(wndproc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: class.as_ptr(), ..zeroed() }; + RegisterClassW(&wc); + let hwnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE | WS_EX_LAYERED, class.as_ptr(), class.as_ptr(), WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), bar_h(), null_mut(), null_mut(), hi, null()); + // Our own Shell_TrayWnd (hidden, topmost, so apps find it before explorer's): apps register their tray icons here. + let tc = wide("Shell_TrayWnd"); + RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tray_proc), hInstance: hi, lpszClassName: tc.as_ptr(), ..zeroed() }); + HOST.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tc.as_ptr(), null(), WS_POPUP, 0, 0, 0, 0, null_mut(), null_mut(), hi, null())); + // The bar may run elevated while apps and explorer do not; UIPI would drop their messages to us (icon data, appbar callbacks). + ChangeWindowMessageFilterEx(HOST.get(), WM_COPYDATA, MSGFLT_ALLOW, null_mut()); + // ITaskbarList::HrInit reads the task band from this property of the first Shell_TrayWnd, which is ours: without it + // HrInit failed (E_NOTIMPL) for every app while the bar ran. DeleteTab / AddTab then come here (tray_proc). + SetPropW(HOST.get(), wide("TaskbandHWND").as_ptr(), HOST.get()); + ChangeWindowMessageFilterEx(HOST.get(), SH_MSG.get(), MSGFLT_ALLOW, null_mut()); + ChangeWindowMessageFilterEx(hwnd, CALLBACK, MSGFLT_ALLOW, null_mut()); + ChangeWindowMessageFilterEx(hwnd, TB_MSG.get(), MSGFLT_ALLOW, null_mut()); // explorer restarted (it runs unelevated) + // files dragged from a normal-rights app onto the (elevated) bar: Start button = add to Start, elsewhere = pin + DragAcceptFiles(hwnd, 1); + for m in [WM_DROPFILES, 0x49 /* WM_COPYGLOBALDATA */, WM_COPYDATA] { + ChangeWindowMessageFilterEx(hwnd, m, MSGFLT_ALLOW, null_mut()); + } + let fc = wide("topbar_trayfly"); + RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(fly_proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: fc.as_ptr(), ..zeroed() }); + TRAYFLY.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_LAYERED, fc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); + let tipc = wide("topbar_tip"); + RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tip_proc), hInstance: hi, lpszClassName: tipc.as_ptr(), ..zeroed() }); + TIPWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tipc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); + let swc = wide("topbar_alttab"); + RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(sw_proc), hInstance: hi, lpszClassName: swc.as_ptr(), ..zeroed() }); + SWWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, swc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); + let pvc = wide("topbar_preview"); + RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(thumbs::pv_proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: pvc.as_ptr(), ..zeroed() }); + thumbs::PVWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, pvc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null())); + OLD_STATE.set(remember_taskbar_state()); + appbar_new(hwnd); + // Without explorer nobody is the "taskman" window, so Windows treats minimized windows as loose icons and leaves + // them as caption stubs on the desktop. Becoming that window (what explorer's taskbar does) makes them hide properly + // and gets us HSHELL_GETMINRECT. Only when explorer's taskbar is absent: with it running its own registration stays. + if find_other("Shell_TrayWnd").is_null() { + if let Some(f) = GetProcAddress(GetModuleHandleW(wide("user32.dll").as_ptr()), b"SetTaskmanWindow\0".as_ptr()) { + std::mem::transmute::<_, unsafe extern "system" fn(HWND) -> i32>(f)(hwnd); + } + } + // window events for the shell (minimize target, HSHELL_FLASH): also next to explorer, whose taskbar we hide + RegisterShellHookWindow(hwnd); + hide_taskbar(); + place(hwnd); + refresh(); + announce(); // apps already running re-add their icons to us + SetTimer(hwnd, 1, 1000, None); // status poll; windows come from win_event + BAR.store(hwnd as isize, Relaxed); + hist::init(hwnd); + bar_anim(hwnd); // the bar slides in (it starts hidden above the screen) + SetTimer(hwnd, 3, 250, None); // fullscreen watch + windows_sys::Win32::UI::Accessibility::SetWinEventHook(0x000A, 0x000B, null_mut(), Some(snap_proc), 0, 0, 0); // EVENT_SYSTEM_MOVESIZESTART..END + // foreground, minimize start/end, create..hide, name, cloaked/uncloaked (2 = WINEVENT_SKIPOWNPROCESS). Not + // LOCATIONCHANGE: it fires for every caret and cursor move; a fullscreen switch comes as ABN_FULLSCREENAPP and the 1 s tick + for (a, b) in [(0x0003, 0x0003), (0x0016, 0x0017), (0x8000, 0x8003), (0x800C, 0x800C), (0x8017, 0x8018)] { + windows_sys::Win32::UI::Accessibility::SetWinEventHook(a, b, null_mut(), Some(win_event), 0, 0, 2); + } + thread::spawn(|| { + let mut hook = SetWindowsHookExW(WH_KEYBOARD_LL, Some(kb_hook), GetModuleHandleW(null()), 0); + // Windows silently drops a low-level hook that once answers too slowly (busy boot), leaving Win+R, Start and + // Alt+Tab dead with no explorer to fall back on: set it again now and then. Callbacks run only inside + // GetMessageW on this thread, so swapping here never delivers a key twice. + SetTimer(null_mut(), 0, 30_000, None); + let mut m: MSG = zeroed(); + while GetMessageW(&mut m, null_mut(), 0, 0) > 0 { + if m.message == WM_TIMER { + let new = SetWindowsHookExW(WH_KEYBOARD_LL, Some(kb_hook), GetModuleHandleW(null()), 0); + if !new.is_null() { + if !hook.is_null() { + UnhookWindowsHookEx(hook); + } + hook = new; + } + } + } + }); + let mut m: MSG = zeroed(); + while GetMessageW(&mut m, null_mut(), 0, 0) > 0 { + TranslateMessage(&m); + DispatchMessageW(&m); + } + } +} + +#[cfg(test)] +mod pin_match_tests { + use super::pin_of_other_exe; + + #[test] + fn windows_find_their_pin_across_exes() { + let up = r"c:\users\a\appdata\local\discord\update.exe"; + let app = r"c:\users\a\appdata\local\discord\app-1.0.9002\discord.exe"; + assert!(pin_of_other_exe(up, "--processStart Discord.exe", "", app, "")); + assert!(pin_of_other_exe(up, "--processStart=\"Discord.exe\"", "", app, "")); + assert!(pin_of_other_exe(r"c:\users\a\appdata\local\discord\app-1.0.9001\discord.exe", "", "", app, "")); + assert!(pin_of_other_exe(r"c:\x\launcher.exe", "", "com.app", app, "com.app")); + assert!(!pin_of_other_exe(up, "--processStart Slack.exe", "", app, "")); + assert!(!pin_of_other_exe(r"c:\x\launcher.exe", "", "", app, "")); + assert!(!pin_of_other_exe("", "", "", app, "")); + } +} + +#[cfg(test)] +mod tests { + #[test] + fn magnet_picks_the_nearest_edge_within_reach() { + let r = windows_sys::Win32::Foundation::RECT { left: 105, top: 50, right: 505, bottom: 350 }; + assert_eq!(super::magnet(r, &[100, 900], &[0, 1000], 14), (-5, 0)); // left edge to 100 + assert_eq!(super::magnet(r, &[512, 100], &[], 14), (-5, 0)); // 105->100 (5) beats 505->512 (7) + assert_eq!(super::magnet(r, &[515], &[340], 14), (10, -10)); // right edge to 515, bottom to 340 + assert_eq!(super::magnet(r, &[130, 0], &[80], 14), (0, 0)); // nothing close enough + } + + #[test] + fn a_far_off_appbar_edge_goes_back_to_the_screen_edge() { + assert_eq!(super::sane_edge(48, 1080), 48); // another bar below ours: stack above it + assert_eq!(super::sane_edge(540, 1080), 0); // half the screen (#106) + assert_eq!(super::sane_edge(-20, 1080), 0); + } + + /// The clock cell is measured from the time and the date in the bar's own fonts, so the air around the block is the + /// same in every language, and the date of a locale still fits (no ellipsis, no clipped slash). + #[test] + fn clock_cell_fits_every_locale() { + use super::*; + const LOCALES: [(u32, &str); 5] = [(0x0409, "en-US"), (0x0419, "ru-RU"), (0x0411, "ja-JP"), (0x0416, "pt-BR"), (0x0804, "zh-CN")]; + unsafe { + SCALE.set(2.0); // the 200 % case, the tightest one: everything else scales with it + let [_, f_date, _, f_time] = bar_fonts(); // the fonts the bar paints the clock with + let dc = CreateCompatibleDC(null_mut()); + for (locale, name) in LOCALES { + let (tm, dt) = clock_texts_of(locale); + let (tw, dw) = (text_size(dc, f_time, &tm).0, text_size(dc, f_date, &dt).0); + let w = clock_cell_w(tw, dw); + assert!(tw <= w - 2 * sc(CLOCK_PAD), "{name}: the time {tm} does not fit its cell"); + assert!(dw <= w - 2 * sc(CLOCK_PAD), "{name}: the date {dt} does not fit its cell"); + assert!(w >= sc(CLOCK_MIN), "{name}: the cell is narrower than the minimum"); + } + DeleteDC(dc); + } + } + + /// The right group ends where its last icon ends: a wider slot was the hole between the volume icon and the clock + /// (and a battery panel under a click on empty space). + #[test] + fn system_group_is_as_wide_as_it_draws() { + use super::*; + BAT.set((-1, false)); // a desktop: no battery in the group + assert_eq!(sys_w(), SYS_LANG + SYS_WIFI + SYS_VOL + SYS_END); + BAT.set((80, false)); + assert_eq!(sys_w(), SYS_LANG + SYS_WIFI + SYS_VOL + SYS_BAT + SYS_END); + BAT.set((-1, false)); + } + + #[test] + fn borderless_games_count_as_fullscreen() { + use super::{RECT, covers_monitor}; + let m = RECT { left: 0, top: 0, right: 1920, bottom: 1080 }; + assert!(covers_monitor(m, m, false, false)); // plain borderless / exclusive fullscreen + assert!(covers_monitor(m, m, true, false)); // borderless window that kept its caption style + // Minecraft (SDL_app): caption style, not maximized, sized one pixel past the monitor — still fullscreen + assert!(covers_monitor(RECT { left: 0, top: 0, right: 1921, bottom: 1080 }, m, true, false)); + assert!(!covers_monitor(RECT { left: -8, top: -8, right: 1928, bottom: 1088 }, m, true, true)); // framed maximized window (#88) + assert!(!covers_monitor(m, m, true, true)); // a maximized window is never a game + assert!(!covers_monitor(RECT { left: -8, top: -8, right: 1928, bottom: 1088 }, m, true, false)); // same, IsZoomed false (#237) + assert!(!covers_monitor(RECT { left: 0, top: 0, right: 1920, bottom: 1032 }, m, false, false)); // leaves the bar's strip + } + + fn pinned_and_running_items_can_be_reordered_together() { + use super::DragButton::{Pin, Window}; + let mut items = vec![Pin(vec![1]), Window(42), Pin(vec![2])]; + assert!(super::move_item(&mut items, 0, 1)); + assert!(matches!(items.as_slice(), [Window(42), Pin(_), Pin(_)])); + assert!(super::move_item(&mut items, 2, 0)); + assert!(matches!(items.as_slice(), [Pin(_), Window(42), Pin(_)])); + } + #[test] + fn drag_accepts_gaps_and_edges_without_targeting_start() { + assert_eq!(super::drag_slot(208, 100, 40, 4, 5, 400, 1), Some(1)); + assert_eq!(super::drag_slot(232, 100, 40, 4, 5, 400, 1), Some(2)); + assert_eq!(super::drag_slot(399, 100, 40, 4, 5, 400, 1), Some(4)); + assert_eq!(super::drag_slot(400, 100, 40, 4, 5, 400, 1), None); + // search and Task View before Start: the first button after Start is three slots in + assert_eq!(super::drag_slot(100 + 3 * 44, 100, 40, 4, 5, 400, 2), Some(1)); + } + #[test] + fn network_icon_state() { + use super::{INET, Link, WIFI, arcs_lit, net}; + let at = |q: i32, inet: bool| { + WIFI.set(q); + INET.set(inet); + net() + }; + assert!(at(80, true) == Link::Wifi(80)); + assert!(at(80, false) == Link::NoInternet(80)); // wifi without a way out: the warning icon + assert!(at(-1, true) == Link::Cable); + assert!(at(-1, false) == Link::Offline); // nothing at all: the crossed-out wifi icon + assert_eq!((arcs_lit(0), arcs_lit(40), arcs_lit(100)), (1, 2, 3)); + } + + #[test] + fn file_manager_windows_belong_to_the_file_explorer_pin() { + use super::as_pinned_exe; + let (rx, ex) = (r"c:\program files\rust-explorer\rust-explorer.exe", r"c:\windows\explorer.exe"); + assert_eq!(as_pinned_exe(rx, ex, true), ex); // the pin the user clicks gets the windows + assert_eq!(as_pinned_exe(rx, ex, false), rx); // no such pin: the file manager's own pin keeps them + assert_eq!(as_pinned_exe(r"c:\tools\other.exe", ex, true), r"c:\tools\other.exe"); + } + + #[test] + fn bar_fonts_key_changes_with_icon_size() { + let a = super::bar_fonts_key(1.0, "Segoe UI Variable", "Segoe Fluent Icons", 60); + let b = super::bar_fonts_key(1.0, "Segoe UI Variable", "Segoe Fluent Icons", 100); + assert_ne!(a, b); + } + + #[test] + fn mix_blends() { + assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.0), super::rgb(0, 0, 0)); + assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 1.0), super::rgb(200, 100, 50)); + assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.5), super::rgb(100, 50, 25)); + } + + #[test] + fn msix_family_from_package_path() { + let f = super::msix_family(r"C:\Program Files\WindowsApps\Claude_5.11492.5.0_x64__pzs8sxrjxfjjc\app\claude.exe"); + assert_eq!(f, Some(("claude_pzs8sxrjxfjjc".into(), r"app\claude.exe".into()))); + assert_eq!(super::msix_family(r"C:\Program Files\Steam\steam.exe"), None); + } + + #[test] + fn stale_claude_pin_resolves_to_installed_version() { + // real system check: skipped where the Claude package is not installed (CI) + let old = r"c:\program files\windowsapps\claude_5.11492.5.0_x64__pzs8sxrjxfjjc\app\claude.exe"; + let Some((fam, _)) = super::msix_family(old) else { panic!() }; + let mut n = 0u32; + let mut len = 0u32; + unsafe { windows_sys::Win32::Storage::Packaging::Appx::GetPackagesByPackageFamily(super::wide(&fam).as_ptr(), &mut n, std::ptr::null_mut(), &mut len, std::ptr::null_mut()) }; + if n == 0 { + return; + } + let tmp = std::env::temp_dir().join("topbar-msix-test.lnk"); + let _ = std::fs::remove_file(&tmp); + unsafe { + use windows::Win32::System::Com::*; + let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); + let sl: windows::Win32::UI::Shell::IShellLinkW = CoCreateInstance(&windows::Win32::UI::Shell::ShellLink, None, CLSCTX_INPROC_SERVER).unwrap(); + sl.SetPath(windows::core::PCWSTR(super::wide(old).as_ptr())).unwrap(); + windows::core::Interface::cast::(&sl).unwrap().Save(windows::core::PCWSTR(super::wide(&tmp.to_string_lossy()).as_ptr()), true).unwrap(); + let lnk = super::wide(&tmp.to_string_lossy()); + let new = super::fix_msix_pin(&lnk, old).expect("re-pointed"); + assert!(std::path::Path::new(&new).exists() && new.ends_with(r"\app\claude.exe"), "{new}"); + assert_eq!(super::lnk_target(&lnk), new); + } + let _ = std::fs::remove_file(&tmp); + } +} + +#[cfg(test)] +mod env_tests { + #[test] + fn expands_known_variables_only() { + let windir = std::env::var("windir").unwrap(); + assert_eq!(super::expand_env(r"%windir%\explorer.exe"), format!(r"{windir}\explorer.exe")); + assert_eq!(super::expand_env(r"%no_such_var_x%\a.exe"), r"%no_such_var_x%\a.exe"); + assert_eq!(super::expand_env("100% sure"), "100% sure"); + } +} + +#[cfg(test)] +mod restore_rect_tests { + use super::*; + + #[test] + fn maximized_restore_rect_fits_under_a_top_bar() { + let m = RECT { left: 0, top: 0, right: 1920, bottom: 1080 }; + let work = workspace(RECT { top: 40, ..m }, m); + let mut n = RECT { left: -8, top: -8, right: 1928, bottom: 1088 }; + assert!(clamp_rect(&mut n, work)); + assert_eq!((n.left, n.top, n.right, n.bottom), (0, 0, 1920, 1040)); + assert!(!clamp_rect(&mut n, work)); + } +}