diff --git a/plugins/rust-search/src/bin/rs-launcher.rs b/plugins/rust-search/src/bin/rs-launcher.rs index b2a64162..5fa7522f 100644 --- a/plugins/rust-search/src/bin/rs-launcher.rs +++ b/plugins/rust-search/src/bin/rs-launcher.rs @@ -305,6 +305,7 @@ unsafe fn step(h: HWND) { ShowWindow(h, SW_HIDE); KillTimer(h, T_ANIM); KillTimer(h, T_CARET); + release_buf(); } else if !moving { KillTimer(h, T_ANIM); } @@ -1728,6 +1729,38 @@ unsafe fn ensure_icons(h: HWND) { }); } +thread_local! { + static PAINT_BUF: std::cell::Cell<(HDC, HBITMAP, i32, i32)> = const { std::cell::Cell::new((null_mut(), null_mut(), 0, 0)) }; +} + +unsafe fn paint_buf(dc: HDC, w: i32, h: i32) -> HDC { + let (mut mem, mut bmp, bw, bh) = PAINT_BUF.get(); + if !mem.is_null() && bw >= w && bh >= h { + return mem; + } + if mem.is_null() { + mem = CreateCompatibleDC(dc); + } + if !bmp.is_null() { + DeleteObject(bmp); + } + let (nw, nh) = (w.max(bw), h.max(bh)); + bmp = CreateCompatibleBitmap(dc, nw, nh); + SelectObject(mem, bmp); + PAINT_BUF.set((mem, bmp, nw, nh)); + mem +} + +unsafe fn release_buf() { + let (mem, bmp, _, _) = PAINT_BUF.replace((null_mut(), null_mut(), 0, 0)); + if !bmp.is_null() { + DeleteObject(bmp); + } + if !mem.is_null() { + DeleteDC(mem); + } +} + unsafe fn paint(h: HWND) { ensure_icons(h); let v = st(|s| View { @@ -1756,14 +1789,9 @@ unsafe fn paint(h: HWND) { let mut rc: RECT = zeroed(); GetClientRect(h, &mut rc); let (w, hgt) = (rc.right, rc.bottom); - let mem = CreateCompatibleDC(dc); - let bmp = CreateCompatibleBitmap(dc, w, hgt); - let old = SelectObject(mem, bmp); + let mem = paint_buf(dc, w, hgt); draw(mem, w, hgt, &v); BitBlt(dc, 0, 0, w, hgt, mem, 0, 0, SRCCOPY); - SelectObject(mem, old); - DeleteObject(bmp); - DeleteDC(mem); EndPaint(h, &ps); } diff --git a/plugins/topbar/src/fly.rs b/plugins/topbar/src/fly.rs index 07109775..259715fb 100644 --- a/plugins/topbar/src/fly.rs +++ b/plugins/topbar/src/fly.rs @@ -1,10 +1,10 @@ // Own flyouts instead of the stock Windows ones: Start (search + all apps + power), Wi-Fi, volume, battery // (+ brightness), calendar. One popup window; what it shows depends on `Kind`. use super::*; -use std::sync::Mutex; -use std::{ - collections::HashMap, - sync::atomic::{AtomicI32, Ordering::Relaxed}, +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{ + Condvar, Mutex, OnceLock, + atomic::{AtomicBool, AtomicI32, AtomicIsize, AtomicU64, Ordering::{Acquire, Relaxed, Release}}, }; #[derive(Clone, Copy, PartialEq)] @@ -105,11 +105,99 @@ fn phy_name(t: i32) -> &'static str { } } -static APPS: Mutex)>> = Mutex::new(Vec::new()); // Start menu shortcuts: (name, .lnk path) -pub static PREVIEW: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); // `--preview`: stays open without focus +#[derive(Clone)] +struct AppEntry { + name: String, + lower: String, + initials: String, + path: Vec, + is_store: bool, + loose: bool, +} + +impl AppEntry { + fn new(name: String, path: Vec, loose: bool) -> Self { + let lower = name.to_lowercase(); + let initials: String = lower.split(|c: char| !c.is_alphanumeric()).filter_map(|w| w.chars().next()).collect(); + let is_store = wstr(&path).starts_with("shell:"); + Self { name, lower, initials, path, is_store, loose } + } +} + +static APPS: Mutex> = Mutex::new(Vec::new()); // Start menu shortcuts + precomputed search keys +static APPS_GEN: AtomicU64 = AtomicU64::new(0); +static LAST_APPS_LOAD: AtomicU64 = AtomicU64::new(0); +static APPS_LOADING: AtomicBool = AtomicBool::new(false); +static START_HW: AtomicIsize = AtomicIsize::new(0); // current open Start HWND for background worker notifications +pub static PREVIEW: AtomicBool = AtomicBool::new(false); // `--preview`: stays open without focus static BRIGHT: AtomicI32 = AtomicI32::new(-1); // -1 = no controllable display (desktop PC) const ROWS: usize = 10; const LIST_Y: i32 = 128; // the app list starts under the store banner +const WM_APP_ICON: u32 = WM_APP + 20; +const WM_APP_APPS: u32 = WM_APP + 21; +const ICON_CACHE_CAP: usize = 256; + +struct IconQueue { + fifo: VecDeque<(Vec, i32)>, + queued: HashSet>, +} + +static ICON_WORK: OnceLock<(Mutex, Condvar)> = OnceLock::new(); +static ICON_DONE: Mutex, isize)>> = Mutex::new(Vec::new()); +static ICON_POSTED: AtomicBool = AtomicBool::new(false); + +fn icon_worker() -> &'static (Mutex, Condvar) { + ICON_WORK.get_or_init(|| { + let pair = (Mutex::new(IconQueue { fifo: VecDeque::new(), queued: HashSet::new() }), Condvar::new()); + std::thread::spawn(|| unsafe { + let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); + let (lock, cvar) = ICON_WORK.get().unwrap(); + loop { + let item = { + let mut q = lock.lock().unwrap(); + while q.fifo.is_empty() { + q = cvar.wait(q).unwrap(); + } + let it = q.fifo.pop_front().unwrap(); + q.queued.remove(&it.0); + it + }; + let ic = lnk_icon_at(&item.0, item.1); + ICON_DONE.lock().unwrap().push((item.0, ic as isize)); + let hw = START_HW.load(Relaxed); + if hw != 0 && !ICON_POSTED.swap(true, Release) { + PostMessageW(hw as HWND, WM_APP_ICON, 0, 0); + } + } + }); + pair + }) +} + +fn enqueue_icon(path: Vec, px: i32) { + let (lock, cvar) = icon_worker(); + let mut q = lock.lock().unwrap(); + if q.queued.insert(path.clone()) { + q.fifo.push_back((path, px)); + cvar.notify_one(); + } +} + +/// Clears cached Start icons (e.g. when the user changes icon size) so they reload at the new size. +pub unsafe fn clear_icons() { + ICONS.with_borrow_mut(|m| { + for (_, ic) in m.drain() { + if !ic.is_null() { + DestroyIcon(ic); + } + } + }); + for (_, ic) in ICON_DONE.lock().unwrap().drain(..) { + if ic != 0 { + DestroyIcon(ic as HICON); + } + } +} thread_local! { static FLY: Cell> = const { Cell::new(None) }; @@ -123,9 +211,15 @@ thread_local! { static CONNECTING: RefCell> = const { RefCell::new(None) }; // the network being joined and since when: its row animates static CTX: RefCell> = const { RefCell::new(None) }; // Wi-Fi right-click menu: network (by name: the list reorders), x, y (px), opened at static QUERY: RefCell = const { RefCell::new(String::new()) }; + static QUERY_GEN: Cell = const { Cell::new(0) }; + static PINNED_GEN: Cell = const { Cell::new(0) }; + static FILTER_CACHE: RefCell)>> = const { RefCell::new(None) }; static SCROLL: Cell = const { Cell::new(0) }; static SELALL: Cell = const { Cell::new(false) }; // Ctrl+A in the search: the next key replaces the query static ICONS: RefCell, HICON>> = RefCell::new(HashMap::new()); // by path: the app list is reloaded and reordered + static FLY_FONTS: Cell<([HFONT; 7], u64)> = const { Cell::new(([null_mut(); 7], 0)) }; + static FLY_BG: Cell<(HDC, HBITMAP, u64)> = const { Cell::new((null_mut(), null_mut(), 0)) }; + static FLY_BUF: Cell<(HDC, HBITMAP, i32, i32)> = const { Cell::new((null_mut(), null_mut(), 0, 0)) }; static SEL: Cell = const { Cell::new(0) }; // Start: the row Enter opens (arrow keys move it) static OVER: Cell> = const { Cell::new(None) }; static DRAG: Cell = const { Cell::new(0) }; // 0 none, 1 volume slider, 2 brightness slider @@ -178,17 +272,23 @@ fn weekday_initials() -> [&'static str; 7] { // ---------- data ---------- -/// Background: collects the Start menu shortcuts once. +static ICON_PX_ATOM: AtomicI32 = AtomicI32::new(24); + +/// Background: collects the Start menu shortcuts and precomputes search keys. pub fn load_apps() { - fn walk(dir: &std::path::Path, depth: u8, out: &mut Vec<(String, Vec)>) { + if APPS_LOADING.swap(true, Acquire) { + return; + } + fn walk(dir: &std::path::Path, depth: u8, out: &mut Vec) { for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { let p = e.path(); if p.is_dir() && depth < 4 { walk(&p, depth + 1, out); } else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("lnk")) { let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); - if !name.to_lowercase().contains("uninstall") { - out.push((name, wide(&p.to_string_lossy()))); + let entry = AppEntry::new(name, wide(&p.to_string_lossy()), false); + if !entry.lower.contains("uninstall") { + out.push(entry); } } } @@ -200,11 +300,14 @@ pub fn load_apps() { } } // Store apps (Settings, Calculator, Terminal, Photos...) have no .lnk: the shell's Apps folder lists them - let have: std::collections::HashSet = v.iter().map(|a| a.0.to_lowercase()).collect(); + let have: HashSet = v.iter().map(|a| a.lower.clone()).collect(); for (name, id) in apps_folder() { - let ok = id.contains('!') || id.to_lowercase().ends_with(".exe") || id.starts_with("Microsoft.Windows."); // apps, not docs / web links - if ok && !have.contains(&name.to_lowercase()) && !name.to_lowercase().contains("uninstall") { - v.push((name, wide(&format!(r"shell:AppsFolder\{id}")))); + let ok = id.contains('!') || id.len() >= 4 && id[id.len() - 4..].eq_ignore_ascii_case(".exe") || id.starts_with("Microsoft.Windows."); // apps, not docs / web links + if ok { + let entry = AppEntry::new(name, wide(&format!(r"shell:AppsFolder\{id}")), false); + if !have.contains(&entry.lower) && !entry.lower.contains("uninstall") { + v.push(entry); + } } } // the classic panels Windows' own search finds and neither list above has (#307) @@ -216,11 +319,31 @@ pub fn load_apps() { (t!("Сетевые подключения", "Network Connections", ja: "ネットワーク接続", pt: "Conexões de Rede", zh: "网络连接"), "ncpa.cpl"), (t!("Свойства системы", "System Properties", ja: "システムのプロパティ", pt: "Propriedades do Sistema", zh: "系统属性"), "sysdm.cpl"), ] { - v.push((name.to_string(), wide(&format!(r"{sys}\System32\{file}")))); + v.push(AppEntry::new(name.to_string(), wide(&format!(r"{sys}\System32\{file}")), false)); } - v.sort_by_key(|a| a.0.to_lowercase()); - v.dedup_by(|a, b| a.0.eq_ignore_ascii_case(&b.0)); + v.sort_unstable_by(|a, b| a.lower.cmp(&b.lower)); + v.dedup_by(|a, b| a.lower == b.lower); + // Pre-warm icons for the first visible rows so opening Start shows icons immediately with zero UI stutter. + let px = ICON_PX_ATOM.load(Relaxed).max(16); + let warm: Vec> = { + let pinned = PINNED.lock().unwrap(); + if pinned.is_empty() { + v.iter().take(ROWS).map(|a| a.path.clone()).collect() + } else { + pinned.iter().take(ROWS).map(|p| wide(p)).collect() + } + }; *APPS.lock().unwrap() = v; + APPS_GEN.fetch_add(1, Release); + LAST_APPS_LOAD.store(unsafe { now_ms() }, Relaxed); + APPS_LOADING.store(false, Release); + for path in warm { + enqueue_icon(path, px); + } + let hw = START_HW.load(Relaxed); + if hw != 0 { + unsafe { PostMessageW(hw as HWND, WM_APP_APPS, 0, 0) }; + } } /// (display name, app id) of everything in the shell's Apps folder (what the Windows Start menu lists). @@ -256,36 +379,46 @@ pub fn apps_folder() -> Vec<(String, String)> { out } -const EN_KEYS: &str = "qwertyuiop[]asdfghjkl;'zxcvbnm,.`"; -const RU_KEYS: &str = "йцукенгшщзхъфывапролджэячсмитьбюё"; +const EN_CHARS: [char; 33] = [ + 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '`', +]; +const RU_CHARS: [char; 33] = [ + 'й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ', 'з', 'х', 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л', 'д', 'ж', 'э', 'я', 'ч', 'с', 'м', 'и', 'т', 'ь', 'б', 'ю', 'ё', +]; /// The same keys typed in the other layout: "сркщьу" -> "chrome", "ntktuhfv" -> "телеграм". fn flip_layout(q: &str) -> String { - let (en, ru): (Vec, Vec) = (EN_KEYS.chars().collect(), RU_KEYS.chars().collect()); - q.chars().map(|c| en.iter().position(|&x| x == c).map(|i| ru[i]).or_else(|| ru.iter().position(|&x| x == c).map(|i| en[i])).unwrap_or(c)).collect() + q.chars() + .map(|c| EN_CHARS.iter().position(|&x| x == c).map(|i| RU_CHARS[i]).or_else(|| RU_CHARS.iter().position(|&x| x == c).map(|i| EN_CHARS[i])).unwrap_or(c)) + .collect() } -/// How well an app name matches the query (both lower-case): 0 the name starts with it, 1 a word does, 2 the word -/// initials do ("vsc" = Visual Studio Code), 3 it is somewhere inside; None = no match. -fn score(name: &str, q: &str) -> Option { +/// Zero-allocation scorer on precomputed lowercase name and word initials. +fn score_pre(lower: &str, initials: &str, q: &str, q_chars: usize) -> Option { if q.is_empty() { return None; } - let words: Vec<&str> = name.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect(); - let initials: String = words.iter().filter_map(|w| w.chars().next()).collect(); - if name.starts_with(q) { + if lower.starts_with(q) { Some(0) - } else if words.iter().any(|w| w.starts_with(q)) { + } else if lower.split(|c: char| !c.is_alphanumeric()).any(|w| !w.is_empty() && w.starts_with(q)) { Some(1) - } else if q.chars().count() >= 2 && initials.starts_with(q) { + } else if q_chars >= 2 && initials.starts_with(q) { Some(2) - } else if name.contains(q) { + } else if lower.contains(q) { Some(3) } else { None } } +/// How well an app name matches the query (both lower-case): 0 the name starts with it, 1 a word does, 2 the word +/// initials do ("vsc" = Visual Studio Code), 3 it is somewhere inside; None = no match. +#[cfg_attr(not(test), allow(dead_code))] +fn score(name: &str, q: &str) -> Option { + let initials: String = name.split(|c: char| !c.is_alphanumeric()).filter_map(|w| w.chars().next()).collect(); + score_pre(name, &initials, q, q.chars().count()) +} + // ---------- apps pinned to the Start panel (empty at first; added from right-click menus) ---------- static PINNED: Mutex> = Mutex::new(Vec::new()); // paths of .lnk / .exe files, in the order they were added @@ -295,7 +428,12 @@ fn pin_file() -> PathBuf { } fn pinned_load() { - *PINNED.lock().unwrap() = std::fs::read_to_string(pin_file()).map(|s| s.lines().filter(|l| !l.is_empty()).map(str::to_string).collect()).unwrap_or_default(); + let next: Vec = std::fs::read_to_string(pin_file()).map(|s| s.lines().filter(|l| !l.is_empty()).map(str::to_string).collect()).unwrap_or_default(); + let mut g = PINNED.lock().unwrap(); + if *g != next { + *g = next; + PINNED_GEN.set(PINNED_GEN.get().wrapping_add(1)); + } } fn wstr(w: &[u16]) -> String { @@ -360,85 +498,150 @@ pub fn start_toggle(path: &str) { Some(i) => drop(p.remove(i)), None => p.push(path.to_string()), } + PINNED_GEN.set(PINNED_GEN.get().wrapping_add(1)); let _ = std::fs::write(pin_file(), p.join("\n")); } -static EXE_GEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +static EXE_GEN: AtomicU64 = AtomicU64::new(0); +static LOOSE_WORK: OnceLock<(Mutex>, Condvar)> = OnceLock::new(); + +fn loose_worker() -> &'static (Mutex>, Condvar) { + LOOSE_WORK.get_or_init(|| { + let pair = (Mutex::new(None), Condvar::new()); + std::thread::spawn(|| { + let rs = PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_default()).join(r"rs-search\rs.exe"); + let (lock, cvar) = LOOSE_WORK.get().unwrap(); + let mut last_done = 0u64; + loop { + let (gen_, q, hw) = { + let mut g = lock.lock().unwrap(); + loop { + if let Some((gn, ref qs, h)) = *g { + if gn != last_done { + break (gn, qs.clone(), h); + } + } + g = cvar.wait(g).unwrap(); + } + }; + // Debounce 150ms: if another keystroke arrives during the wait, wake up and restart on the newer query. + let (g, _) = cvar.wait_timeout_while(lock.lock().unwrap(), std::time::Duration::from_millis(150), |req| { + req.as_ref().is_none_or(|(gn, ..)| *gn == gen_) + }).unwrap(); + if g.as_ref().is_some_and(|(gn, ..)| *gn != gen_) { + continue; + } + drop(g); + last_done = gen_; + if q.chars().count() < 2 || !rs.is_file() { + continue; + } + // straight to the service's pipe: no rs.exe process per query (and no full disk scan when the service is down) + let found = winrust_common::search::ask_all(&q); + if EXE_GEN.load(Relaxed) != gen_ { + continue; + } + let mut apps = APPS.lock().unwrap(); + apps.retain(|a| !a.loose); + let mut added = false; + for line in found.iter().filter(|l| l.len() >= 4 && l[l.len() - 4..].eq_ignore_ascii_case(".exe")).take(12) { + let w = wide(line); + if apps.iter().any(|a| a.path == w) { + continue; + } + let name = std::path::Path::new(line).file_stem().unwrap_or_default().to_string_lossy().to_string(); + apps.push(AppEntry::new(name, w, true)); + added = true; + } + drop(apps); + if added { + APPS_GEN.fetch_add(1, Release); + if START_HW.load(Relaxed) == hw { + unsafe { PostMessageW(hw as HWND, WM_APP_APPS, 0, 0) }; + } + } + } + }); + pair + }) +} /// Programs that have no Start menu shortcut (a loose loliland.exe): asks rust-search for .exe files matching what is typed -/// and adds them to the app list, where the normal ranking picks them up. Debounced; the panel repaints when they arrive. +/// and adds them to the app list, where the normal ranking picks them up. Debounced on a single worker thread; never blocks UI. fn find_loose_exes(hw: HWND) { let q = QUERY.with_borrow(|q| q.trim().to_string()); let gen_ = EXE_GEN.fetch_add(1, Relaxed) + 1; - let rs = PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_default()).join(r"rs-search\rs.exe"); - if q.chars().count() < 2 || !rs.is_file() { + if q.chars().count() < 2 { return; } - let hw = hw as isize; - std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(200)); - if EXE_GEN.load(Relaxed) != gen_ { - return; // typed on: a newer search is coming - } - // straight to the service's pipe: no rs.exe process per query (and no full disk scan when the service is down) - let found = winrust_common::search::ask_all(&q); - let mut apps = APPS.lock().unwrap(); - let mut added = false; - for line in found.iter().filter(|l| l.to_lowercase().ends_with(".exe")).take(12) { - let w = wide(line); - if apps.iter().any(|a| a.1 == w) { - continue; - } - let name = std::path::Path::new(line).file_stem().unwrap_or_default().to_string_lossy().to_string(); - apps.push((name, w)); - added = true; - } - drop(apps); - if added { - unsafe { InvalidateRect(hw as HWND, null(), 0) }; - } - }); + let (lock, cvar) = loose_worker(); + *lock.lock().unwrap() = Some((gen_, q, hw as isize)); + cvar.notify_one(); } fn filtered() -> Vec { + let key = (QUERY_GEN.get(), APPS_GEN.load(Acquire), PINNED_GEN.get()); + if let Some(cached) = FILTER_CACHE.with_borrow(|c| c.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v.clone())) { + return cached; + } let q = QUERY.with_borrow(|q| q.to_lowercase()); let mut apps = APPS.lock().unwrap(); - if q.is_empty() { + let res: Vec = if q.is_empty() { let pinned = PINNED.lock().unwrap(); // nothing pinned yet: every app, A to Z, like Windows' "All apps" (an empty Start read as "no apps found", #72) if pinned.is_empty() { - return (0..apps.len()).collect(); + apps.iter().enumerate().filter(|(_, a)| !a.loose).map(|(i, _)| i).collect() + } else { + // nothing typed: what the user pinned (an app that is not a Start menu shortcut joins the list on demand), then the + // rest, so one pinned app does not hide all the others (#273) + let mut v: Vec = pinned + .iter() + .map(|p| { + let w = wide(p); + apps.iter().position(|a| a.path == w).unwrap_or_else(|| { + let stem = std::path::Path::new(p).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(); + apps.push(AppEntry::new(name, w, false)); + apps.len() - 1 + }) + }) + .collect(); + let rest: Vec = apps.iter().enumerate().filter(|(i, a)| !a.loose && !v.contains(i)).map(|(i, _)| i).collect(); + v.extend(rest); + v } - // nothing typed: what the user pinned (an app that is not a Start menu shortcut joins the list on demand), then the - // rest, so one pinned app does not hide all the others (#273) - let mut v: Vec = pinned + } else { + // typed in the wrong layout: those matches come after the direct ones + let fq = flip_layout(&q); + let q_chars = q.chars().count(); + let fq_chars = fq.chars().count(); + let same_layout = fq == q; + // lock USAGE once for the whole scan instead of per app + let mut usage_guard = USAGE.lock().unwrap(); + let usage_map = usage_guard.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() + }); + let mut v: Vec<(u8, u32, usize)> = apps .iter() - .map(|p| { - let w = wide(p); - apps.iter().position(|a| a.1 == w).unwrap_or_else(|| { - let stem = std::path::Path::new(p).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(); - apps.push((name, w)); - apps.len() - 1 - }) + .enumerate() + .filter_map(|(i, a)| { + let s = score_pre(&a.lower, &a.initials, &q, q_chars) + .or_else(|| if same_layout { None } else { score_pre(&a.lower, &a.initials, &fq, fq_chars).map(|s| s + 4) })?; + let u = usage_map.get(&a.lower).copied().unwrap_or(0); + Some((s, u32::MAX - u, i)) }) .collect(); - v.extend((0..apps.len()).filter(|i| !v.contains(i)).collect::>()); - return v; - } - // typed in the wrong layout: those matches come after the direct ones - let fq = flip_layout(&q); - let mut v: Vec<(u8, u32, usize)> = apps - .iter() - .enumerate() - .filter_map(|(i, a)| { - let n = a.0.to_lowercase(); - let s = score(&n, &q).or_else(|| score(&n, &fq).map(|s| s + 4))?; - Some((s, u32::MAX - uses(&n), i)) - }) - .collect(); - v.sort_unstable(); // best match, then most launched, then alphabetical (the list is sorted by name) - v.into_iter().map(|x| x.2).collect() + drop(usage_guard); + v.sort_unstable(); // best match, then most launched, then alphabetical (the list is sorted by name) + v.into_iter().map(|x| x.2).collect() + }; + FILTER_CACHE.set(Some((key, res.clone()))); + res } /// The built-in panel through the video driver (`\\.\LCD`, what Windows' own slider talks to): needs no admin rights and no @@ -1080,6 +1283,7 @@ pub fn context_menu(x: i32) { pub fn close() { let h = FH.replace(null_mut()); FLY.set(None); + START_HW.store(0, Relaxed); if h.is_null() { return; } @@ -1098,11 +1302,31 @@ pub fn close_now() { unsafe { kill_ghost() }; } +unsafe fn release_surfaces() { + let (dc, bmp, _) = FLY_BG.replace((null_mut(), null_mut(), 0)); + if !bmp.is_null() { + DeleteObject(bmp); + } + if !dc.is_null() { + DeleteDC(dc); + } + let (dc, bmp, _, _) = FLY_BUF.replace((null_mut(), null_mut(), 0, 0)); + if !bmp.is_null() { + DeleteObject(bmp); + } + if !dc.is_null() { + DeleteDC(dc); + } +} + unsafe fn kill_ghost() { let (g, _, _) = GHOST.replace((null_mut(), 0, (0, 0))); if !g.is_null() { DestroyWindow(g); } + if FH.get().is_null() { + release_surfaces(); + } } /// One frame of a flyout fade: opening rises up from the bar while fading in, closing fades out while sinking back down. @@ -1167,6 +1391,7 @@ pub fn toggle(k: Kind) { HV.with_borrow_mut(|m| m.retain(|k, _| *k < 1_000_000)); // flyout keys are >= 1_000_000: no stale glow from the last panel CTX.set(None); QUERY.set(String::new()); + QUERY_GEN.set(QUERY_GEN.get().wrapping_add(1)); SELALL.set(false); SCROLL.set(0); SEL.set(0); @@ -1174,6 +1399,7 @@ pub fn toggle(k: Kind) { NOTE.set(String::new()); CONFIRM.set(-1); OVER.set(None); + ICON_PX_ATOM.store(icon_px(), Relaxed); let mut t: SYSTEMTIME = zeroed(); GetLocalTime(&mut t); CAL.set((t.wYear as i32, t.wMonth as i32)); @@ -1190,7 +1416,11 @@ pub fn toggle(k: Kind) { Kind::Cal => crate::notif::refresh(), Kind::Start => { pinned_load(); // the search card (rs-launcher) can add to this list from another process - std::thread::spawn(load_apps); // apps installed since the last open show up (the panel repaints every second) + let empty = APPS.lock().unwrap().is_empty(); + let stale = now_ms().saturating_sub(LAST_APPS_LOAD.load(Relaxed)) >= 60_000; + if empty || stale { + std::thread::spawn(load_apps); // refresh at most once a minute, never blocking Start open + } } _ => {} } @@ -1213,6 +1443,8 @@ pub fn toggle(k: Kind) { for m in [WM_DROPFILES, 0x49 /* WM_COPYGLOBALDATA */, WM_COPYDATA] { ChangeWindowMessageFilterEx(hw, m, MSGFLT_ALLOW, null_mut()); } + START_HW.store(hw as isize, Relaxed); + drain_ready_icons(); // absorb any icons pre-warmed at startup before the first paint } FIN.set((x, fy)); T0.set(now_ms()); @@ -1221,7 +1453,9 @@ pub fn toggle(k: Kind) { FLY.set(Some(k)); ShowWindow(hw, SW_SHOW); force_fg(hw); - SetTimer(hw, 1, 1000, None); + if matches!(k, Kind::Quick | Kind::Wifi | Kind::Cal) { + SetTimer(hw, 1, 1000, None); + } SetTimer(hw, 3, 15, None); } } @@ -1253,16 +1487,16 @@ unsafe fn wifi_radio_wlan(on: bool) { /// Starts the i-th app of the filtered Start list and counts the launch (search ranks by it). false = no such row. unsafe fn launch(i: usize) -> bool { let Some(app) = filtered().get(i).and_then(|&ai| APPS.lock().unwrap().get(ai).cloned()) else { return false }; - if wstr(&app.1).starts_with("shell:") { - bump_name(&app.0); // open() counts only .lnk files + if app.is_store { + bump_name(&app.name); // open() counts only .lnk files } - open(&app.1); + open(&app.path); true } /// Right-click menu of a Start app: open, open as administrator, show the shortcut's folder. unsafe fn app_menu(hw: HWND, i: usize, x: i32, y: i32) { - let Some(lnk) = filtered().get(i).and_then(|&ai| APPS.lock().unwrap().get(ai).map(|a| a.1.clone())) else { return }; + let Some(lnk) = filtered().get(i).and_then(|&ai| APPS.lock().unwrap().get(ai).map(|a| a.path.clone())) else { return }; let m = CreatePopupMenu(); let path = wstr(&lnk); let file = !path.starts_with("shell:"); // Store apps have no file to run elevated or to show in a folder @@ -1499,22 +1733,112 @@ fn inset(rc: RECT, d: i32) -> RECT { RECT { left: rc.left + d, top: rc.top + d, right: rc.right - d, bottom: rc.bottom - d } } +unsafe fn drain_ready_icons() -> bool { + let ready: Vec<(Vec, isize)> = { + let mut g = ICON_DONE.lock().unwrap(); + if g.is_empty() { + return false; + } + std::mem::take(&mut *g) + }; + ICONS.with_borrow_mut(|m| { + if m.len() + ready.len() > ICON_CACHE_CAP { + for (_, ic) in m.drain() { + if !ic.is_null() { + DestroyIcon(ic); + } + } + } + for (path, raw) in ready { + let ic = raw as HICON; + if let Some(old) = m.insert(path, ic) { + if !old.is_null() && old != ic { + DestroyIcon(old); + } + } + } + }); + true +} + +/// Cached flyout fonts: recreated only when scale or font faces change. +unsafe fn fly_fonts() -> [HFONT; 7] { + let key = key_of((SCALE.get().to_bits(), ui_face(), winrust_common::style::icon_face())); + let (fonts, k) = FLY_FONTS.get(); + if k == key && !fonts[0].is_null() { + return fonts; + } + for f in fonts { + if !f.is_null() { + 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 fonts = [ + font(&face, 13, 400), + font(&face, 12, 400), + font(&gface, 16, 400), + font(&face, 15, 600), + font(&face, 13, 600), + font(&gface, 11, 400), + font(&face, 12, 600), + ]; + FLY_FONTS.set((fonts, key)); + fonts +} + +/// Cached flyout background (border + fill + backdrop): drawn once per size/style. +unsafe fn fly_bg(wdc: HDC, cr: RECT) -> HDC { + let p = pal(); + let key = key_of((cr.right, cr.bottom, style().light(), style().square(), format!("{:?}", style()), [p.bg, p.text, p.dim, p.accent], SCALE.get().to_bits())); + let (mut dc, mut bmp, k) = FLY_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, cr.bottom); + SelectObject(dc, bmp); + FLY_BG.set((dc, bmp, key)); + fill(dc, cr, if style().light() { mix(p.bg, p.dim, 0.3) } else { mix(p.bg, p.text, 0.12) }, sc(16)); + fill(dc, inset(cr, 1), p.bg, sc(16)); + winrust_common::style::backdrop(dc, inset(cr, 1), sc(100) as f32 / 100.0); + dc +} + +/// Reusable offscreen backbuffer for flyout painting (avoids kernel GDI bitmap alloc/free on every frame). +unsafe fn fly_buf(wdc: HDC, w: i32, h: i32) -> HDC { + let (mut dc, mut bmp, bw, bh) = FLY_BUF.get(); + if !dc.is_null() && bw == w && bh == h { + return dc; + } + if dc.is_null() { + dc = CreateCompatibleDC(wdc); + } + if !bmp.is_null() { + DeleteObject(bmp); + } + bmp = CreateCompatibleBitmap(wdc, w, h); + SelectObject(dc, bmp); + FLY_BUF.set((dc, bmp, w, h)); + dc +} + unsafe fn paint(hw: HWND, k: Kind) { let mut ps: PAINTSTRUCT = zeroed(); let wdc = BeginPaint(hw, &mut ps); let mut cr: RECT = zeroed(); GetClientRect(hw, &mut cr); BUSY.set(false); - let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, cr.bottom)); - let old = SelectObject(dc, bmp); - fill(dc, cr, if style().light() { mix(pal().bg, pal().dim, 0.3) } else { mix(pal().bg, pal().text, 0.12) }, sc(16)); - fill(dc, inset(cr, 1), pal().bg, sc(16)); - winrust_common::style::backdrop(dc, inset(cr, 1), sc(100) as f32 / 100.0); + let dc = fly_buf(wdc, cr.right, cr.bottom); + BitBlt(dc, 0, 0, cr.right, cr.bottom, fly_bg(wdc, cr), 0, 0, SRCCOPY); SetBkMode(dc, TRANSPARENT as i32); - 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 (f_txt, f_small, f_glyph, f_title, f_big) = (font(&face, 13, 400), font(&face, 12, 400), font(&gface, 16, 400), font(&face, 15, 600), font(&face, 34, 600)); - let (f_semi, f_head, f_gs, f_label) = (font(&face, 13, 600), font(&face, 18, 700), font(&gface, 11, 400), font(&face, 12, 600)); + let [f_txt, f_small, f_glyph, f_title, f_semi, f_gs, f_label] = fly_fonts(); let card = card(); let of = SelectObject(dc, f_txt); let (w, h) = size(k); @@ -1968,6 +2292,7 @@ unsafe fn paint(hw: HWND, k: Kind) { }); } Kind::Start => { + let rs = rects(k); surface(dc, r(20, 20, w - 20, 56), card, sc(36)); SelectObject(dc, f_glyph); text(dc, "\u{E721}", r(28, 20, 56, 56), pal().dim, DT_CENTER); @@ -1985,13 +2310,13 @@ unsafe fn paint(hw: HWND, k: Kind) { } let cx = (sc(64) + tr.right).min(sc(w - 64)) + sc(1); fill(dc, RECT { left: cx, top: sc(28), right: cx + sc(1).max(1), bottom: sc(48) }, pal().accent, 0); - if let Some((kr, ka)) = rects(k).into_iter().find(|(_, a)| *a == Act::Keyboard) { + if let Some(&(kr, ka)) = rs.iter().find(|(_, a)| *a == Act::Keyboard) { g(ka, kr, card, mix(card, pal().text, 0.1), sc(14)); SelectObject(dc, f_glyph); text(dc, "\u{E765}", kr, if hot(ka) { pal().text } else { pal().dim }, DT_CENTER); // keyboard SelectObject(dc, f_txt); } - if let Some((sr, sa)) = rects(k).into_iter().find(|(_, a)| *a == Act::Store) { + if let Some(&(sr, sa)) = rs.iter().find(|(_, a)| *a == Act::Store) { let tint = mix(card, pal().accent, 0.16); g(sa, sr, tint, mix(tint, pal().accent, 0.12), sc(12)); fill(dc, RECT { left: sr.left, top: sr.top + sc(12), right: sr.left + sc(3), bottom: sr.bottom - sc(12) }, pal().accent, sc(3)); @@ -2014,7 +2339,7 @@ unsafe fn paint(hw: HWND, k: Kind) { text(dc, t!("Приложения не найдены", "No apps found", ja: "アプリが見つかりません", pt: "Nenhum app encontrado", zh: "未找到应用"), r(24, LIST_Y, w - 24, LIST_Y + 40), pal().dim, DT_LEFT); } } - let rs = rects(k); + let px = icon_px(); let apps = APPS.lock().unwrap(); for (rc, a) in &rs { match *a { @@ -2024,7 +2349,7 @@ unsafe fn paint(hw: HWND, k: Kind) { // the row that was just pinned pulses in the accent colour for a moment let pulse = JUST.with_borrow(|j| { let age = now_ms().saturating_sub(j.1) as f32 / 1200.0; - if age < 1.0 && !j.0.is_empty() && app.1 == wide(&j.0) { (1.0 - age) * (1.0 - age) } else { 0.0 } + if age < 1.0 && !j.0.is_empty() && app.path == wide(&j.0) { (1.0 - age) * (1.0 - age) } else { 0.0 } }); let sel = i == SEL.get(); // what Enter opens if pulse > 0.0 || sel { @@ -2035,19 +2360,22 @@ unsafe fn paint(hw: HWND, k: Kind) { if sel { fill(dc, RECT { left: rc.left, top: rc.top + sc(10), right: rc.left + sc(3), bottom: rc.bottom - sc(10) }, pal().accent, sc(3)); } + // Never extract icons synchronously in WM_PAINT: queue missing ones to the background worker. let ic = ICONS.with_borrow_mut(|m| { - *m.entry(app.1.clone()).or_insert_with(|| { - let t = lnk_target(&app.1); - lnk_icon(&app.1, &t) - }) + if let Some(&ic) = m.get(&app.path) { + ic + } else { + m.insert(app.path.clone(), null_mut()); + enqueue_icon(app.path.clone(), px); + null_mut() + } }); if !ic.is_null() { - DrawIconEx(dc, rc.left + sc(13), (rc.top + rc.bottom - icon_px()) / 2, ic, icon_px(), icon_px(), 0, null_mut(), DI_NORMAL); // at its loaded size: no stretching + DrawIconEx(dc, rc.left + sc(13), (rc.top + rc.bottom - px) / 2, ic, px, px, 0, null_mut(), DI_NORMAL); // at its loaded size: no stretching } - let store = wstr(&app.1).starts_with("shell:"); - text(dc, &app.0, RECT { left: rc.left + sc(52), top: rc.top, right: rc.right - sc(110), bottom: rc.bottom }, pal().text, DT_LEFT); + text(dc, &app.name, RECT { left: rc.left + sc(52), top: rc.top, right: rc.right - sc(110), bottom: rc.bottom }, pal().text, DT_LEFT); SelectObject(dc, f_small); - let kind = if sel && !q.is_empty() { "Enter ↵" } else if store { t!("Приложение", "App", ja: "アプリ", pt: "App", zh: "应用") } else { "" }; + let kind = if sel && !q.is_empty() { "Enter ↵" } else if app.is_store { t!("Приложение", "App", ja: "アプリ", pt: "App", zh: "应用") } else { "" }; text(dc, kind, RECT { left: rc.right - sc(110), top: rc.top, right: rc.right - sc(14), bottom: rc.bottom }, pal().dim, DT_RIGHT); SelectObject(dc, f_txt); } @@ -2074,12 +2402,6 @@ unsafe fn paint(hw: HWND, k: Kind) { BitBlt(wdc, 0, 0, cr.right, cr.bottom, dc, 0, 0, SRCCOPY); SelectObject(dc, of); - for f in [f_txt, f_small, f_glyph, f_title, f_big, f_semi, f_head, f_gs, f_label] { - DeleteObject(f); - } - SelectObject(dc, old); - DeleteObject(bmp); - DeleteDC(dc); if BUSY.get() { SetTimer(hw, 2, 16, None); // next animation frame } else { @@ -2103,6 +2425,15 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR match msg { WM_PAINT => paint(hw, k), WM_ERASEBKGND => return 1, + WM_APP_ICON => { + ICON_POSTED.store(false, Release); + if drain_ready_icons() { + InvalidateRect(hw, null(), 0); + } + } + WM_APP_APPS => { + InvalidateRect(hw, null(), 0); + } WM_ACTIVATE if wp & 0xffff == 0 && !PREVIEW.load(Relaxed) => { // A file drag that began elsewhere (desktop icon, folder window) deactivates this panel with the button still // down: keep Start open so the drop can land on it, and close once the button is up (timer 6). @@ -2248,6 +2579,7 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR PASS.set(None); } else if k == Kind::Start && QUERY.with_borrow(|q| !q.is_empty()) { QUERY.set(String::new()); // Esc clears the search first, the next one closes + QUERY_GEN.set(QUERY_GEN.get().wrapping_add(1)); SCROLL.set(0); SEL.set(0); } else { @@ -2291,6 +2623,7 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR return 0; } } else { + let mut changed = false; QUERY.with_borrow_mut(|q| { let all = SELALL.replace(false); if c == 1 { @@ -2298,16 +2631,22 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR } else if c == 127 { // Ctrl+Backspace: the last word if all { q.clear() } else { let t = q.trim_end().len(); q.truncate(q[..t].rfind(' ').map_or(0, |i| i + 1)); } + changed = true; } else if c == 8 { if all { q.clear() } else { q.pop(); } + changed = true; } else if let Some(ch) = char::from_u32(c).filter(|_| c >= 32) { if all { q.clear() } q.push(ch); + changed = true; } }); - SCROLL.set(0); - SEL.set(0); - find_loose_exes(hw); + if changed { + QUERY_GEN.set(QUERY_GEN.get().wrapping_add(1)); + SCROLL.set(0); + SEL.set(0); + find_loose_exes(hw); + } } } InvalidateRect(hw, null(), 0); diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rs index f70b9d09..97f41fe0 100644 --- a/plugins/topbar/src/main.rs +++ b/plugins/topbar/src/main.rs @@ -1094,15 +1094,29 @@ unsafe fn exe_of(h: HWND) -> String { exe } +const TOPBAR_CLASS_W: [u16; 6] = [b't' as u16, b'o' as u16, b'p' as u16, b'b' as u16, b'a' as u16, b'r' as u16]; + unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> i32 { + // Cheap checks first: >95% of top-level windows are invisible, owned, or tool windows. + // Avoiding DwmGetWindowAttribute (IPC to dwm.exe) and GetClassNameW for them saves hundreds of calls per event. + if IsWindowVisible(h) == 0 || !GetWindow(h, GW_OWNER).is_null() { + return 1; + } 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); + if (ex & WS_EX_TOOLWINDOW != 0 && ex & WS_EX_APPWINDOW == 0) || GetWindowTextLengthW(h) <= 0 { + return 1; + } + if SKIP.with_borrow(|s| s.contains(&h)) { + return 1; + } 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 { + if n == TOPBAR_CLASS_W.len() && cls[..n] == TOPBAR_CLASS_W { + return 1; + } + 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); + if cloaked == 0 { (*(lp as *mut Vec)).push(h); } 1 @@ -1159,6 +1173,26 @@ unsafe fn lnk_target(lnk: &[u16]) -> String { .unwrap_or_default() } +/// Like `lnk_icon`, but takes an explicit pixel size (safe from background threads) and only resolves `lnk_target` +/// via COM if `item_icon` returns null. +unsafe fn lnk_icon_at(lnk: &[u16], px: i32) -> HICON { + let ic = item_icon(&resolve_cmd(&wstr_of(lnk)), px); + if !ic.is_null() { + return ic; + } + let target = lnk_target(lnk); + 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 +} + /// 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()); @@ -1221,6 +1255,7 @@ unsafe fn reload_icons() { } icons.clear(); }); + fly::clear_icons(); refresh_buttons(); } @@ -1521,17 +1556,17 @@ fn refresh_buttons() { 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 mut loose: Vec<(HWND, String, String, HICON)> = 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); + let raw_exe = unsafe { exe_of(w) }; + let exe = as_pinned_exe(&raw_exe, &explorer, explorer_pinned); + let (id, icon) = unsafe { win_meta(w) }; // 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)); } @@ -1539,24 +1574,28 @@ fn refresh_buttons() { }); match pin { Some(i) => btns[1 + i].wins.push(w), - None => loose.push(w), + None => loose.push((w, raw_exe, id, icon)), } } // 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::>()); + o.retain(|w| loose.iter().any(|l| l.0 == *w)); + for l in &loose { + if !o.contains(&l.0) { + o.push(l.0); + } + } 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(); + let Some((_, exe, id, icon)) = loose.iter().find(|l| l.0 == w) else { continue }; + let key = format!("{exe}|{id}"); + 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 } }); + btns.push(Btn { pin: None, wins: vec![w], icon: *icon }); keys.push(key); } } @@ -1576,13 +1615,21 @@ thread_local! { // 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; +const META_TTL_WARM: u64 = 30_000; +const META_TTL_COLD: u64 = 4_000; 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))) { + if let Some(v) = META.with_borrow(|m| { + m.get(&(w as usize)) + .filter(|e| { + let ttl = if e.3.is_null() { META_TTL_COLD } else { META_TTL_WARM }; + e.0 == pid && now.saturating_sub(e.1) < ttl + }) + .map(|e| (e.2.clone(), e.3)) + }) { return v; } let v = (win_aumid(w), win_icon(w)); @@ -2406,11 +2453,11 @@ 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. +/// Repaints (GDI+, the costly part) only when something shown changed; `tick`: every 60th 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) { + if s != last || (tick && quiet >= 60) { SIG.set((s, 0)); InvalidateRect(hwnd, null(), 0); second::invalidate(); @@ -2588,9 +2635,27 @@ unsafe fn paint_vert(dc: HDC, cr: RECT, fonts: [HFONT; 4]) { thread_local! { static BG: Cell<(HDC, HBITMAP, u64)> = const { Cell::new((null_mut(), null_mut(), 0)) }; // cached background layer and its key + static BAR_BUF: Cell<(HDC, HBITMAP, i32, i32)> = const { Cell::new((null_mut(), null_mut(), 0, 0)) }; // reusable offscreen backbuffer static FONTS: Cell<([HFONT; 4], u64)> = const { Cell::new(([null_mut(); 4], 0)) }; } +unsafe fn bar_buf(wdc: HDC, w: i32, h: i32) -> HDC { + let (mut dc, mut bmp, bw, bh) = BAR_BUF.get(); + if !dc.is_null() && bw == w && bh == h { + return dc; + } + if dc.is_null() { + dc = CreateCompatibleDC(wdc); + } + if !bmp.is_null() { + DeleteObject(bmp); + } + bmp = CreateCompatibleBitmap(wdc, w, h); + SelectObject(dc, bmp); + BAR_BUF.set((dc, bmp, w, h)); + dc +} + fn key_of(v: impl std::hash::Hash) -> u64 { use std::hash::Hasher; let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -2672,8 +2737,7 @@ unsafe fn paint(hwnd: HWND) { 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); + let dc = bar_buf(wdc, cr.right, h); // 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); @@ -2815,9 +2879,6 @@ unsafe fn paint(hwnd: HWND) { 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 { diff --git a/plugins/topbar/src/second.rs b/plugins/topbar/src/second.rs index 136970e5..bcda960d 100644 --- a/plugins/topbar/src/second.rs +++ b/plugins/topbar/src/second.rs @@ -164,13 +164,33 @@ unsafe fn hit(w: HWND, x: i32) -> i32 { if d < 0 || d % step >= bw || d / step >= n { NONE } else { d / step } } +thread_local! { + static SEC_BUF: Cell<(HDC, HBITMAP, i32, i32)> = const { Cell::new((null_mut(), null_mut(), 0, 0)) }; +} + +unsafe fn sec_buf(wdc: HDC, w: i32, h: i32) -> HDC { + let (mut dc, mut bmp, bw, bh) = SEC_BUF.get(); + if !dc.is_null() && bw == w && bh == h { + return dc; + } + if dc.is_null() { + dc = CreateCompatibleDC(wdc); + } + if !bmp.is_null() { + DeleteObject(bmp); + } + bmp = CreateCompatibleBitmap(wdc, w, h); + SelectObject(dc, bmp); + SEC_BUF.set((dc, bmp, w, h)); + dc +} + 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 (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, cr.bottom)); - let old = SelectObject(dc, bmp); + let dc = sec_buf(wdc, cr.right, cr.bottom); SetBkMode(dc, TRANSPARENT as i32); let [f_txt, f_small, _, f_bold] = bar_fonts(); let of = SelectObject(dc, f_txt); @@ -232,9 +252,6 @@ unsafe fn paint(hwnd: HWND) { BitBlt(wdc, 0, 0, cr.right, cr.bottom, dc, 0, 0, SRCCOPY); SelectObject(dc, of); - SelectObject(dc, old); - DeleteObject(bmp); - DeleteDC(dc); EndPaint(hwnd, &ps); }