π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
feat(capture-native): look up the focused window and the window under a point
Luis Ortiz7e55a3f47d5c
diff --git a/packages/capture-native/Cargo.toml b/packages/capture-native/Cargo.tomlindex eef8b00..566385f 100644--- a/packages/capture-native/Cargo.toml+++ b/packages/capture-native/Cargo.toml@@ -14,7 +14,11 @@ napi-derive = "3"[target.'cfg(windows)'.dependencies]windows = { version = "0.62", features = ["Win32_Foundation",+ "Win32_Graphics_Dwm",+ "Win32_Graphics_Gdi",+ "Win32_Storage_FileSystem","Win32_System_Com",+ "Win32_System_Threading","Win32_UI_Accessibility","Win32_UI_Input_KeyboardAndMouse","Win32_UI_WindowsAndMessaging",diff --git a/packages/capture-native/index.d.ts b/packages/capture-native/index.d.tsindex 692334d..6fa7c1e 100644--- a/packages/capture-native/index.d.ts+++ b/packages/capture-native/index.d.ts@@ -9,6 +9,18 @@*/export declare const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-wasip1'+export declare function activeWindow(): ActiveWindow | null++export interface ActiveWindow {+ title?: string+ appName: string+ appPath?: string+ x: number+ y: number+ width: number+ height: number+}+export declare function clearDeadKey(): voidexport declare function elementAtPoint(x: number, y: number): Promise<UiElement | null>@@ -44,3 +56,5 @@ export interface UiElement {ancestors: Array<ElementNode>children: Array<ElementNode>}++export declare function windowAt(x: number, y: number): ActiveWindow | nulldiff --git a/packages/capture-native/index.js b/packages/capture-native/index.jsindex 3e20ef3..9f8697f 100644--- a/packages/capture-native/index.js+++ b/packages/capture-native/index.js@@ -778,9 +778,11 @@ function __napiStampBindingTarget(exportsObject, target) {// linked import resolves to `undefined`.module.exports.__napiBindingTarget = __napiStampBindingTarget(nativeBinding, __napiLoadedBindingTarget)module.exports = nativeBinding+module.exports.activeWindow = nativeBinding.activeWindowmodule.exports.clearDeadKey = nativeBinding.clearDeadKeymodule.exports.elementAtPoint = nativeBinding.elementAtPointmodule.exports.focusedElement = nativeBinding.focusedElementmodule.exports.isSupported = nativeBinding.isSupportedmodule.exports.keyLabel = nativeBinding.keyLabelmodule.exports.resolveKey = nativeBinding.resolveKey+module.exports.windowAt = nativeBinding.windowAtdiff --git a/packages/capture-native/src/lib.rs b/packages/capture-native/src/lib.rsindex e32ddb2..2075856 100644--- a/packages/capture-native/src/lib.rs+++ b/packages/capture-native/src/lib.rs@@ -8,6 +8,8 @@ use napi_derive::napi;mod hit;#[cfg(windows)]mod win;+#[cfg(any(windows, test))]+mod window;#[napi(object)]pub struct ElementRect {@@ -36,6 +38,17 @@ pub struct UiElement {pub children: Vec<ElementNode>,}+#[napi(object)]+pub struct ActiveWindow {+ pub title: Option<String>,+ pub app_name: String,+ pub app_path: Option<String>,+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+}+pub struct ElementLookup {at: Option<(i32, i32)>,}@@ -94,6 +107,25 @@ pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<S}}+#[napi]+pub fn active_window() -> Option<ActiveWindow> {+ #[cfg(windows)]+ return win::active_window();+ #[cfg(not(windows))]+ None+}++#[napi]+pub fn window_at(x: i32, y: i32) -> Option<ActiveWindow> {+ #[cfg(windows)]+ return win::window_at(x, y);+ #[cfg(not(windows))]+ {+ let _ = (x, y);+ None+ }+}+#[napi]pub fn clear_dead_key() {#[cfg(windows)]diff --git a/packages/capture-native/src/win.rs b/packages/capture-native/src/win.rsindex aa28eef..9852af4 100644--- a/packages/capture-native/src/win.rs+++ b/packages/capture-native/src/win.rs@@ -1,21 +1,34 @@use std::cell::RefCell;+use std::ffi::c_void;+use std::path::Path;use napi::Result;-use windows::core::{Interface, BSTR};-use windows::Win32::Foundation::POINT;+use windows::core::{Interface, BOOL, BSTR, PCWSTR, PWSTR};+use windows::Win32::Foundation::{CloseHandle, HWND, LPARAM, POINT, RECT};+use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS};+use windows::Win32::Graphics::Gdi::{EnumDisplayMonitors, GetMonitorInfoW, HDC, HMONITOR, MONITORINFO};+use windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW};use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,};+use windows::Win32::System::Threading::{+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,+};use windows::Win32::UI::Accessibility::*;use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, ToUnicodeEx, HKL, MAPVK_VK_TO_VSC, MAPVK_VSC_TO_VK_EX,VK_BACK, VK_CAPITAL, VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_F1, VK_F24, VK_HOME, VK_INSERT,VK_LEFT, VK_MENU, VK_NEXT, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SHIFT, VK_SPACE, VK_TAB, VK_UP,};-use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};+use windows::Win32::UI::WindowsAndMessaging::{+ EnumWindows, GetAncestor, GetClassNameW, GetForegroundWindow, GetWindow, GetWindowLongPtrW, GetWindowRect,+ GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible, WindowFromPoint, GA_ROOT, GWL_EXSTYLE,+ GWL_STYLE, GW_OWNER, WS_CAPTION, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_POPUP, WS_SYSMENU,+};use crate::hit::smallest_under;-use crate::{ElementNode, ElementRect, UiElement};+use crate::window::{covers_most_of_the_screen, is_popup, Traits};+use crate::{ActiveWindow, ElementNode, ElementRect, UiElement};const ROLES: &[(UIA_CONTROLTYPE_ID, &str)] = &[(UIA_ButtonControlTypeId, "button"),@@ -326,3 +339,239 @@ pub fn clear_dead_key() {}}}++fn area(rect: &RECT) -> f64 {+ f64::from((rect.right - rect.left).max(0)) * f64::from((rect.bottom - rect.top).max(0))+}++fn window_rect(window: HWND) -> Option<RECT> {+ let mut rect = RECT::default();+ unsafe { GetWindowRect(window, &mut rect) }.ok()?;+ Some(rect)+}++fn frame_rect(window: HWND) -> Option<RECT> {+ let mut rect = RECT::default();+ let framed = unsafe {+ DwmGetWindowAttribute(+ window,+ DWMWA_EXTENDED_FRAME_BOUNDS,+ (&mut rect as *mut RECT).cast::<c_void>(),+ size_of::<RECT>() as u32,+ )+ };+ if framed.is_ok() && area(&rect) > 0.0 {+ Some(rect)+ } else {+ window_rect(window)+ }+}++fn monitor_areas() -> Vec<f64> {+ unsafe extern "system" fn collect(monitor: HMONITOR, _: HDC, _: *mut RECT, data: LPARAM) -> BOOL {+ let areas = unsafe { &mut *(data.0 as *mut Vec<f64>) };+ let mut info = MONITORINFO {+ cbSize: size_of::<MONITORINFO>() as u32,+ ..Default::default()+ };+ if unsafe { GetMonitorInfoW(monitor, &mut info) }.as_bool() {+ areas.push(area(&info.rcMonitor));+ }+ true.into()+ }+ let mut areas: Vec<f64> = Vec::new();+ let _ = unsafe {+ EnumDisplayMonitors(+ None,+ None,+ Some(collect),+ LPARAM(&mut areas as *mut Vec<f64> as isize),+ )+ };+ areas+}++fn text_of(read: impl FnOnce(&mut [u16]) -> i32) -> Option<String> {+ let mut buffer = [0u16; 512];+ let length = read(&mut buffer);+ if length <= 0 {+ return None;+ }+ clean(String::from_utf16_lossy(&buffer[..length as usize]))+}++fn style(window: HWND) -> u32 {+ unsafe { GetWindowLongPtrW(window, GWL_STYLE) as u32 }+}++fn owned(window: HWND) -> bool {+ unsafe { GetWindow(window, GW_OWNER) }.is_ok_and(|owner| !owner.is_invalid())+}++fn cloaked(window: HWND) -> bool {+ let mut flag = 0u32;+ let read = unsafe {+ DwmGetWindowAttribute(+ window,+ DWMWA_CLOAKED,+ (&mut flag as *mut u32).cast::<c_void>(),+ size_of::<u32>() as u32,+ )+ };+ read.is_ok() && flag != 0+}++fn popup(window: HWND) -> bool {+ let class = text_of(|buffer| unsafe { GetClassNameW(window, buffer) }).unwrap_or_default();+ let style = style(window);+ let extended = unsafe { GetWindowLongPtrW(window, GWL_EXSTYLE) as u32 };+ is_popup(&Traits {+ class: &class,+ owned: owned(window),+ no_activate: extended & WS_EX_NOACTIVATE.0 != 0,+ tool_window: extended & WS_EX_TOOLWINDOW.0 != 0,+ captionless_popup: style & WS_POPUP.0 != 0 && style & WS_CAPTION.0 != WS_CAPTION.0,+ })+}++fn process_of(window: HWND) -> u32 {+ let mut process = 0u32;+ unsafe { GetWindowThreadProcessId(window, Some(&mut process)) };+ process+}++fn main_window_of(process: u32) -> Option<HWND> {+ struct Search {+ process: u32,+ best: Option<(f64, HWND)>,+ }+ unsafe extern "system" fn visit(window: HWND, data: LPARAM) -> BOOL {+ let search = unsafe { &mut *(data.0 as *mut Search) };+ let style = style(window);+ let candidate = process_of(window) == search.process+ && unsafe { IsWindowVisible(window) }.as_bool()+ && !cloaked(window)+ && !owned(window)+ && style & WS_CAPTION.0 != 0+ && style & WS_SYSMENU.0 != 0;+ if let Some(rect) = window_rect(window).filter(|_| candidate) {+ let size = area(&rect);+ if search.best.is_none_or(|(largest, _)| size > largest) {+ search.best = Some((size, window));+ }+ }+ true.into()+ }+ let mut search = Search { process, best: None };+ let _ = unsafe { EnumWindows(Some(visit), LPARAM(&mut search as *mut Search as isize)) };+ search.best.map(|(_, window)| window)+}++fn process_path(process: u32) -> Option<String> {+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process) }.ok()?;+ let mut buffer = [0u16; 1024];+ let mut length = buffer.len() as u32;+ let named = unsafe {+ QueryFullProcessImageNameW(+ handle,+ PROCESS_NAME_WIN32,+ PWSTR(buffer.as_mut_ptr()),+ &mut length,+ )+ };+ let _ = unsafe { CloseHandle(handle) };+ named.ok()?;+ clean(String::from_utf16_lossy(&buffer[..length as usize]))+}++fn wide(text: &str) -> Vec<u16> {+ text.encode_utf16().chain(Some(0)).collect()+}++fn file_description(path: &str) -> Option<String> {+ let file = wide(path);+ let size = unsafe { GetFileVersionInfoSizeW(PCWSTR(file.as_ptr()), None) };+ if size == 0 {+ return None;+ }+ let mut data = vec![0u8; size as usize];+ unsafe { GetFileVersionInfoW(PCWSTR(file.as_ptr()), None, size, data.as_mut_ptr().cast()) }.ok()?;+ let query = |key: &str| -> Option<(*const u16, usize)> {+ let key = wide(key);+ let mut found: *mut c_void = std::ptr::null_mut();+ let mut length = 0u32;+ let hit = unsafe {+ VerQueryValueW(+ data.as_ptr().cast(),+ PCWSTR(key.as_ptr()),+ &mut found,+ &mut length,+ )+ };+ (hit.as_bool() && length > 0 && !found.is_null()).then_some((found as *const u16, length as usize))+ };+ let (translation, _) = query("\\VarFileInfo\\Translation")?;+ let (language, codepage) = unsafe { (*translation, *translation.add(1)) };+ let (text, length) = query(&format!(+ "\\StringFileInfo\\{language:04x}{codepage:04x}\\FileDescription"+ ))?;+ let characters = unsafe { std::slice::from_raw_parts(text, length) };+ clean(+ String::from_utf16_lossy(characters)+ .trim_end_matches('\0')+ .to_string(),+ )+}++pub fn active_window() -> Option<ActiveWindow> {+ framed(unsafe { GetForegroundWindow() })+}++pub fn window_at(x: i32, y: i32) -> Option<ActiveWindow> {+ let hit = unsafe { WindowFromPoint(POINT { x, y }) };+ if hit.is_invalid() {+ return None;+ }+ framed(unsafe { GetAncestor(hit, GA_ROOT) })+}++fn framed(front: HWND) -> Option<ActiveWindow> {+ if front.is_invalid() {+ return None;+ }+ let process = process_of(front);+ let bounds = frame_rect(front)?;+ let monitors = monitor_areas();+ let largest = monitors.iter().copied().fold(0.0, f64::max);+ let desktop: f64 = monitors.iter().sum();+ let window = if !covers_most_of_the_screen(area(&bounds), largest, desktop) && popup(front) {+ main_window_of(process).unwrap_or(front)+ } else {+ front+ };+ let rect = if window == front {+ bounds+ } else {+ frame_rect(window)?+ };+ let path = process_path(process);+ let app_name = path+ .as_deref()+ .and_then(file_description)+ .or_else(|| {+ path+ .as_deref()+ .and_then(|found| Path::new(found).file_stem())+ .map(|stem| stem.to_string_lossy().into_owned())+ })+ .unwrap_or_default();+ Some(ActiveWindow {+ title: text_of(|buffer| unsafe { GetWindowTextW(window, buffer) }),+ app_name,+ app_path: path,+ x: f64::from(rect.left),+ y: f64::from(rect.top),+ width: f64::from(rect.right - rect.left),+ height: f64::from(rect.bottom - rect.top),+ })+}diff --git a/packages/capture-native/src/window.rs b/packages/capture-native/src/window.rsnew file mode 100644index 0000000..648edc9--- /dev/null+++ b/packages/capture-native/src/window.rs@@ -0,0 +1,90 @@+const POPUP_CLASSES: &[&str] = &["#32768", "#32770", "Auto-Suggest Dropdown", "tooltips_class32"];+const POPUP_FRAGMENTS: &[&str] = &["Popup", "DropDown", "ComboLBox"];+const MOST_OF_THE_SCREEN: f64 = 0.8;++pub struct Traits<'a> {+ pub class: &'a str,+ pub owned: bool,+ pub no_activate: bool,+ pub tool_window: bool,+ pub captionless_popup: bool,+}++pub fn is_popup(traits: &Traits) -> bool {+ POPUP_CLASSES.contains(&traits.class)+ || POPUP_FRAGMENTS+ .iter()+ .any(|fragment| traits.class.contains(fragment))+ || traits.owned+ || traits.no_activate+ || traits.tool_window+ || traits.captionless_popup+}++pub fn covers_most_of_the_screen(window: f64, largest_monitor: f64, desktop: f64) -> bool {+ window > largest_monitor * MOST_OF_THE_SCREEN || window > desktop * MOST_OF_THE_SCREEN+}++#[cfg(test)]+mod tests {+ use super::{covers_most_of_the_screen, is_popup, Traits};++ fn plain(class: &str) -> Traits<'_> {+ Traits {+ class,+ owned: false,+ no_activate: false,+ tool_window: false,+ captionless_popup: false,+ }+ }++ #[test]+ fn menus_dropdowns_and_dialogs_are_popups() {+ for class in [+ "#32768",+ "#32770",+ "Auto-Suggest Dropdown",+ "tooltips_class32",+ "Net UI Popup",+ "ComboLBox",+ ] {+ assert!(is_popup(&plain(class)), "{class}");+ }+ }++ #[test]+ fn an_ordinary_top_level_window_is_not_a_popup() {+ assert!(!is_popup(&plain("Chrome_WidgetWin_1")));+ assert!(!is_popup(&plain("CabinetWClass")));+ }++ #[test]+ fn owned_tool_and_captionless_windows_are_popups() {+ assert!(is_popup(&Traits {+ owned: true,+ ..plain("Chrome_WidgetWin_1")+ }));+ assert!(is_popup(&Traits {+ tool_window: true,+ ..plain("Chrome_WidgetWin_1")+ }));+ assert!(is_popup(&Traits {+ no_activate: true,+ ..plain("Chrome_WidgetWin_1")+ }));+ assert!(is_popup(&Traits {+ captionless_popup: true,+ ..plain("Chrome_WidgetWin_1")+ }));+ }++ #[test]+ fn most_of_the_screen_is_measured_by_area() {+ let monitor = 1920.0 * 1080.0;+ assert!(covers_most_of_the_screen(1900.0 * 1000.0, monitor, monitor));+ assert!(!covers_most_of_the_screen(400.0 * 300.0, monitor, monitor));+ assert!(covers_most_of_the_screen(1800.0 * 1000.0, monitor, monitor * 2.0));+ assert!(covers_most_of_the_screen(10.0, 0.0, 0.0));+ }+}