Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
New recording flow (#831)
Oscar Beaumont88ae2670d823
diff --git a/Cargo.lock b/Cargo.lockindex 6362f5186..72749058e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -188,7 +188,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "55f533f8e0af236ffe5eb979b99381df3258853f00ba2e44b6e1955292c75227"dependencies = ["clipboard-win",- "image",+ "image 0.25.6","log","objc2 0.6.1","objc2-app-kit",@@ -980,6 +980,7 @@ dependencies = ["bytemuck","cap-audio","cap-camera",+ "cap-displays","cap-editor","cap-export","cap-fail",@@ -1004,7 +1005,7 @@ dependencies = ["futures","futures-intrusive","global-hotkey",- "image",+ "image 0.25.6","keyed_priority_queue","lazy_static","log",@@ -1064,7 +1065,13 @@ dependencies = [name = "cap-displays"version = "0.1.0"dependencies = [+ "cocoa 0.26.1",+ "core-foundation 0.10.1","core-graphics 0.24.0",+ "image 0.24.9",+ "objc",+ "serde",+ "specta","windows 0.60.0","windows-sys 0.59.0",]@@ -1106,7 +1113,7 @@ dependencies = ["clap","ffmpeg-next","futures",- "image",+ "image 0.25.6","inquire","mp4","serde",@@ -1164,7 +1171,7 @@ dependencies = ["flume","futures","gif",- "image",+ "image 0.25.6","indexmap 2.10.0","inquire","kameo",@@ -1248,7 +1255,7 @@ dependencies = ["flume","futures","hex",- "image",+ "image 0.25.6","objc","objc2-app-kit","relative-path",@@ -1286,7 +1293,7 @@ dependencies = ["futures","futures-intrusive","glyphon",- "image",+ "image 0.25.6","log","pretty_assertions","reactive_graph",@@ -1538,7 +1545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "afede46921767868c5c7f8f55202bdd8bec0bab6bc9605174200f45924f93c62"dependencies = ["clipboard-win",- "image",+ "image 0.25.6","objc2 0.6.1","objc2-app-kit","objc2-foundation 0.3.1",@@ -3810,6 +3817,24 @@ dependencies = ["icu_properties",]+[[package]]+name = "image"+version = "0.24.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5690139d2f55868e080017335e4b94cb7414274c74f1669c84fb5feba2c9f69d"+dependencies = [+ "bytemuck",+ "byteorder",+ "color_quant",+ "exr",+ "gif",+ "jpeg-decoder",+ "num-traits",+ "png",+ "qoi",+ "tiff",+]+[[package]]name = "image"version = "0.25.6"@@ -4071,6 +4096,9 @@ name = "jpeg-decoder"version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"+dependencies = [+ "rayon",+][[package]]name = "js-sys"@@ -7896,7 +7924,7 @@ dependencies = ["heck 0.5.0","http","http-range",- "image",+ "image 0.25.6","jni","libc","log",diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 625c6cab0..11df6dd64 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -28,6 +28,7 @@"@solid-primitives/event-listener": "^2.3.3","@solid-primitives/history": "^0.1.5","@solid-primitives/memo": "^1.4.2",+ "@solid-primitives/mouse": "^2.1.2","@solid-primitives/refs": "^1.0.8","@solid-primitives/resize-observer": "^2.0.26","@solid-primitives/scheduled": "^1.4.3",diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex d6b39d985..4b585db18 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -88,6 +88,8 @@ cap-media = { path = "../../../crates/media" }cap-flags = { path = "../../../crates/flags" }cap-recording = { path = "../../../crates/recording" }cap-export = { path = "../../../crates/export" }+cap-displays = { path = "../../../crates/displays" }+flume.workspace = truetracing-subscriber = "0.3.19"tracing-appender = "0.2.3"diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rsindex 62252e295..67a39e4c5 100644--- a/apps/desktop/src-tauri/src/general_settings.rs+++ b/apps/desktop/src-tauri/src/general_settings.rs@@ -80,18 +80,38 @@ pub struct GeneralSettingsStore {pub server_url: String,#[serde(default)]pub recording_countdown: Option<u32>,- #[serde(default, alias = "open_editor_after_recording")]- #[deprecated]- _open_editor_after_recording: bool,- #[deprecated = "can be removed when native camera preview is ready"]- #[serde(default)]+ // #[deprecated = "can be removed when native camera preview is ready"]+ #[serde(+ default = "default_enable_native_camera_preview",+ skip_serializing_if = "no"+ )]pub enable_native_camera_preview: bool,#[serde(default)]pub auto_zoom_on_clicks: bool,+ // #[deprecated = "can be removed when new recording flow is the default"]+ #[serde(+ default = "default_enable_new_recording_flow",+ skip_serializing_if = "no"+ )]+ pub enable_new_recording_flow: bool,#[serde(default)]pub post_deletion_behaviour: PostDeletionBehaviour,}+fn default_enable_native_camera_preview() -> bool {+ // TODO:+ // cfg!(target_os = "macos")+ false+}++fn default_enable_new_recording_flow() -> bool {+ cfg!(debug_assertions)+}++fn no(_: &bool) -> bool {+ false+}+fn default_server_url() -> String {std::option_env!("VITE_SERVER_URL").unwrap_or("https://cap.so")@@ -127,9 +147,9 @@ impl Default for GeneralSettingsStore {custom_cursor_capture: false,server_url: default_server_url(),recording_countdown: Some(3),- _open_editor_after_recording: false,- enable_native_camera_preview: false,+ enable_native_camera_preview: default_enable_native_camera_preview(),auto_zoom_on_clicks: false,+ enable_new_recording_flow: default_enable_new_recording_flow(),post_deletion_behaviour: PostDeletionBehaviour::DoNothing,}}diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rsindex d4f5a99ac..0247fdd58 100644--- a/apps/desktop/src-tauri/src/hotkeys.rs+++ b/apps/desktop/src-tauri/src/hotkeys.rs@@ -65,6 +65,9 @@ impl HotkeysStore {}}+#[derive(Serialize, Type, tauri_specta::Event, Debug, Clone)]+pub struct OnEscapePress;+pub type HotkeysState = Mutex<HotkeysStore>;pub fn init(app: &AppHandle) {app.plugin(@@ -74,6 +77,10 @@ pub fn init(app: &AppHandle) {return;}+ if shortcut.key == Code::Escape {+ OnEscapePress.emit(app).ok();+ }+let state = app.state::<HotkeysState>();let store = state.lock().unwrap();@@ -90,7 +97,6 @@ pub fn init(app: &AppHandle) {let store = HotkeysStore::get(app).unwrap().unwrap_or_default();let global_shortcut = app.global_shortcut();-for hotkey in store.hotkeys.values() {global_shortcut.register(Shortcut::from(*hotkey)).ok();}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex fb38f62dd..1003710bd 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -16,6 +16,7 @@ mod permissions;mod platform;mod presets;mod recording;+mod target_select_overlay;mod tray;mod upload;mod web_api;@@ -69,6 +70,7 @@ use tauri::Window;use tauri::{AppHandle, Manager, State, WindowEvent};use tauri_plugin_deep_link::DeepLinkExt;use tauri_plugin_dialog::DialogExt;+use tauri_plugin_global_shortcut::GlobalShortcutExt;use tauri_plugin_notification::{NotificationExt, PermissionState};use tauri_plugin_opener::OpenerExt;use tauri_plugin_shell::ShellExt;@@ -1758,7 +1760,7 @@ async fn get_system_audio_waveforms(#[tauri::command]#[specta::specta]async fn show_window(app: AppHandle, window: ShowCapWindow) -> Result<(), String> {- window.show(&app).await.unwrap();+ let _ = window.show(&app).await;Ok(())}@@ -1951,7 +1953,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) {captions::download_whisper_model,captions::check_model_exists,captions::delete_whisper_model,- captions::export_captions_srt+ captions::export_captions_srt,+ target_select_overlay::open_target_select_overlays,+ target_select_overlay::close_target_select_overlays,]).events(tauri_specta::collect_events![RecordingOptionsChanged,@@ -1971,7 +1975,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) {UploadProgress,captions::DownloadProgress,recording::RecordingEvent,- RecordingDeleted+ RecordingDeleted,+ target_select_overlay::TargetUnderCursor,+ hotkeys::OnEscapePress]).error_handling(tauri_specta::ErrorHandlingMode::Throw).typ::<ProjectConfiguration>()@@ -2042,6 +2048,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {.with_denylist(&[CapWindowId::Setup.label().as_str(),"window-capture-occluder",+ "target-select-overlay",CapWindowId::CaptureArea.label().as_str(),CapWindowId::Camera.label().as_str(),CapWindowId::RecordingsOverlay.label().as_str(),@@ -2053,6 +2060,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {label if label.starts_with("window-capture-occluder-") => {"window-capture-occluder"}+ label if label.starts_with("target-select-overlay") => "target-select-overlay",_ => label,}).build(),@@ -2064,6 +2072,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {hotkeys::init(&app);general_settings::init(&app);fake_window::init(&app);+ app.manage(target_select_overlay::WindowFocusManager::default());app.manage(EditorWindowIds::default());if let Ok(Some(auth)) = AuthStore::load(&app) {@@ -2197,6 +2206,10 @@ pub async fn run(recording_logging_handle: LoggingHandle) {}return;}+ CapWindowId::TargetSelectOverlay { display_id } => {+ app.state::<target_select_overlay::WindowFocusManager>()+ .destroy(&display_id, app.global_shortcut());+ }_ => {}};}@@ -2256,7 +2269,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) {}} else {let handle = handle.clone();- tokio::spawn(async move { ShowCapWindow::Main.show(&handle).await });+ tokio::spawn(async move {+ let _ = ShowCapWindow::Main.show(&handle).await;+ });}}tauri::RunEvent::ExitRequested { code, api, .. } => {diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rsnew file mode 100644index 000000000..a9bf72810--- /dev/null+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs@@ -0,0 +1,206 @@+use std::{+ collections::HashMap,+ str::FromStr,+ sync::{Mutex, PoisonError},+ time::Duration,+};++use base64::prelude::*;++use crate::windows::{CapWindowId, ShowCapWindow};+use cap_displays::{+ DisplayId, WindowId,+ bounds::{LogicalBounds, PhysicalSize},+};+use serde::Serialize;+use specta::Type;+use tauri::{AppHandle, Manager, WebviewWindow};+use tauri_plugin_global_shortcut::{GlobalShortcut, GlobalShortcutExt};+use tauri_specta::Event;+use tokio::task::JoinHandle;+use tracing::error;++#[derive(tauri_specta::Event, Serialize, Type, Clone)]+pub struct TargetUnderCursor {+ display_id: Option<DisplayId>,+ window: Option<WindowUnderCursor>,+ screen: Option<ScreenUnderCursor>,+}++#[derive(Serialize, Type, Clone)]+pub struct WindowUnderCursor {+ id: WindowId,+ app_name: String,+ bounds: LogicalBounds,+ icon: Option<String>,+}++#[derive(Serialize, Type, Clone)]+pub struct ScreenUnderCursor {+ name: String,+ physical_size: PhysicalSize,+ refresh_rate: String,+}++#[specta::specta]+#[tauri::command]+pub async fn open_target_select_overlays(+ app: AppHandle,+ state: tauri::State<'_, WindowFocusManager>,+) -> Result<(), String> {+ let displays = cap_displays::Display::list()+ .into_iter()+ .map(|d| d.id())+ .collect::<Vec<_>>();+ for display_id in displays {+ let _ = ShowCapWindow::TargetSelectOverlay { display_id }+ .show(&app)+ .await;+ }++ let handle = tokio::spawn({+ let app = app.clone();+ async move {+ loop {+ let display = cap_displays::Display::get_containing_cursor();+ let window = cap_displays::Window::get_topmost_at_cursor();++ let _ = TargetUnderCursor {+ display_id: display.map(|d| d.id()),+ window: window.and_then(|w| {+ Some(WindowUnderCursor {+ id: w.id(),+ bounds: w.bounds()?,+ app_name: w.owner_name()?,+ icon: w.app_icon().map(|bytes| {+ format!("data:image/png;base64,{}", BASE64_STANDARD.encode(&bytes))+ }),+ })+ }),+ screen: display.map(|d| ScreenUnderCursor {+ name: d.name(),+ physical_size: d.physical_size(),+ refresh_rate: d.refresh_rate().to_string(),+ }),+ }+ .emit(&app);++ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ }+ });++ if let Some(task) = state+ .task+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .replace(handle)+ {+ task.abort();+ } else {+ // If task is already set we know we have already registered this.+ app.global_shortcut()+ .register("Escape")+ .map_err(|err| error!("Error registering global keyboard shortcut for Escape: {err}"))+ .ok();+ }++ Ok(())+}++#[specta::specta]+#[tauri::command]+pub async fn close_target_select_overlays(+ app: AppHandle,+ // state: tauri::State<'_, WindowFocusManager>,+) -> Result<(), String> {+ for (id, window) in app.webview_windows() {+ if let Ok(CapWindowId::TargetSelectOverlay { .. }) = CapWindowId::from_str(&id) {+ let _ = window.close();+ }+ }++ Ok(())+}++// Windows doesn't have a proper concept of window z-index's so we implement them in userspace :(+#[derive(Default)]+pub struct WindowFocusManager {+ task: Mutex<Option<JoinHandle<()>>>,+ tasks: Mutex<HashMap<String, JoinHandle<()>>>,+}++impl WindowFocusManager {+ /// Called when a window is created to spawn it's task+ pub fn spawn(&self, id: &DisplayId, window: WebviewWindow) {+ let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);+ tasks.insert(+ id.to_string(),+ tokio::spawn(async move {+ let app = window.app_handle();+ loop {+ let Some(cap_main) = CapWindowId::Main.get(app) else {+ window.close().ok();+ break;+ };++ // If the main window is minimized or not visible, close the overlay+ //+ // This is a workaround for the fact that the Cap main window+ // is minimized when opening settings, etc instead of it being+ // closed.+ if cap_main.is_minimized().ok().unwrap_or_default()+ || cap_main.is_visible().map(|v| !v).ok().unwrap_or_default()+ {+ window.close().ok();+ break;+ }++ #[cfg(windows)]+ {+ let should_refocus = cap_main.is_focused().ok().unwrap_or_default()+ || window.is_focused().unwrap_or_default();++ // If a Cap window is not focused we know something is trying to steal the focus.+ // We need to move the overlay above it. We don't use `always_on_top` on the overlay because we need the Cap window to stay above it.+ if !should_refocus {+ window.set_focus().ok();+ }+ }++ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ }+ }),+ );+ }++ /// Called when a specific overlay window is destroyed to cleanup it's resources+ pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {+ let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(task) = tasks.remove(&id.to_string()) {+ let _ = task.abort();+ }++ // When all overlay windows are closed cleanup shared resources.+ if tasks.is_empty() {+ // Unregister keyboard shortcut+ // This messes with other applications if we don't remove it.+ global_shortcut+ .unregister("Escape")+ .map_err(|err| {+ error!("Error unregistering global keyboard shortcut for Escape: {err}")+ })+ .ok();++ // Shutdown the cursor tracking task+ if let Some(task) = self+ .task+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .take()+ {+ task.abort();+ }+ }+ }+}diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rsindex 3d76112f8..dced37786 100644--- a/apps/desktop/src-tauri/src/tray.rs+++ b/apps/desktop/src-tauri/src/tray.rs@@ -3,8 +3,10 @@ use crate::{RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings, recording,};-use std::sync::Arc;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};use tauri::Manager;use tauri::menu::{MenuId, PredefinedMenuItem};use tauri::{@@ -99,7 +101,9 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {move |app: &AppHandle, event| match TrayItem::try_from(event.id) {Ok(TrayItem::OpenCap) => {let app = app.clone();- tokio::spawn(async move { ShowCapWindow::Main.show(&app).await });+ tokio::spawn(async move {+ let _ = ShowCapWindow::Main.show(&app).await;+ });}Ok(TrayItem::TakeScreenshot) => {let _ = RequestNewScreenshot.emit(&app_handle);diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex f9d47b996..41b4ad79c 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -1,8 +1,13 @@#![allow(unused_mut)]#![allow(unused_imports)]-use crate::{App, ArcLock, fake_window, general_settings::AppTheme, permissions};-use cap_flags::FLAGS;+use crate::{+ App, ArcLock, fake_window,+ general_settings::{AppTheme, GeneralSettingsStore},+ permissions,+ target_select_overlay::WindowFocusManager,+};+use cap_displays::DisplayId;use cap_media::{platform::logical_monitor_bounds, sources::CaptureScreen};use futures::pin_mut;use serde::Deserialize;@@ -23,7 +28,7 @@ use tracing::debug;#[cfg(target_os = "macos")]const DEFAULT_TRAFFIC_LIGHTS_INSET: LogicalPosition<f64> = LogicalPosition::new(12.0, 12.0);-#[derive(Clone)]+#[derive(Clone, Deserialize, Type)]pub enum CapWindowId {// Contains onboarding + permissionsSetup,@@ -32,6 +37,7 @@ pub enum CapWindowId {Editor { id: u32 },RecordingsOverlay,WindowCaptureOccluder { screen_id: u32 },+ TargetSelectOverlay { display_id: DisplayId },CaptureArea,Camera,InProgressRecording,@@ -67,6 +73,12 @@ impl FromStr for CapWindowId {.parse::<u32>().map_err(|e| e.to_string())?,},+ s if s.starts_with("target-select-overlay-") => Self::TargetSelectOverlay {+ display_id: s+ .replace("target-select-overlay-", "")+ .parse::<DisplayId>()+ .map_err(|e| e.to_string())?,+ },_ => return Err(format!("unknown window label: {s}")),})}@@ -83,6 +95,9 @@ impl std::fmt::Display for CapWindowId {write!(f, "window-capture-occluder-{screen_id}")}Self::CaptureArea => write!(f, "capture-area"),+ Self::TargetSelectOverlay { display_id } => {+ write!(f, "target-select-overlay-{display_id}")+ }Self::InProgressRecording => write!(f, "in-progress-recording"),Self::RecordingsOverlay => write!(f, "recordings-overlay"),Self::Upgrade => write!(f, "upgrade"),@@ -138,7 +153,8 @@ impl CapWindowId {Self::Camera| Self::WindowCaptureOccluder { .. }| Self::CaptureArea- | Self::RecordingsOverlay => None,+ | Self::RecordingsOverlay+ | Self::TargetSelectOverlay { .. } => None,_ => Some(None),}}@@ -165,6 +181,7 @@ pub enum ShowCapWindow {Editor { project_path: PathBuf },RecordingsOverlay,WindowCaptureOccluder { screen_id: u32 },+ TargetSelectOverlay { display_id: DisplayId },CaptureArea { screen_id: u32 },Camera,InProgressRecording { countdown: Option<u32> },@@ -174,7 +191,7 @@ pub enum ShowCapWindow {impl ShowCapWindow {pub async fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {- if let Self::Editor { project_path } = self {+ if let Self::Editor { project_path } = &self {let state = app.state::<EditorWindowIds>();let mut s = state.ids.lock().unwrap();if !s.iter().any(|(path, _)| path == project_path) {@@ -207,18 +224,68 @@ impl ShowCapWindow {.build()?,Self::Main => {if permissions::do_permissions_check(false).necessary_granted() {- self.window_builder(app, "/")+ let new_recording_flow = GeneralSettingsStore::get(&app)+ .ok()+ .flatten()+ .map(|s| s.enable_new_recording_flow)+ .unwrap_or_default();++ let window = self+ .window_builder(app, if new_recording_flow { "/new-main" } else { "/" }).resizable(false).maximized(false).maximizable(false).always_on_top(true).visible_on_all_workspaces(true).center()- .build()?+ .build()?;++ if new_recording_flow {+ #[cfg(target_os = "macos")]+ crate::platform::set_window_level(window.as_ref().window(), 50);+ }++ window} else {Box::pin(Self::Setup.show(app)).await?}}+ Self::TargetSelectOverlay { display_id } => {+ let Some(display) = cap_displays::Display::from_id(display_id.clone()) else {+ return Err(tauri::Error::WindowNotFound);+ };++ let size = display.raw_handle().logical_size();+ let position = display.raw_handle().logical_position();++ let mut window_builder = self+ .window_builder(+ app,+ format!("/target-select-overlay?displayId={display_id}"),+ )+ .maximized(false)+ .resizable(false)+ .fullscreen(false)+ .shadow(false)+ .always_on_top(cfg!(target_os = "macos"))+ .visible_on_all_workspaces(true)+ .skip_taskbar(true)+ .inner_size(size.width(), size.height())+ .position(position.x(), position.y())+ .transparent(true);++ let window = window_builder.build()?;++ app.state::<WindowFocusManager>()+ .spawn(display_id, window.clone());++ #[cfg(target_os = "macos")]+ {+ crate::platform::set_window_level(window.as_ref().window(), 45);+ }++ window+ }Self::Settings { page } => {// Hide main window when settings window opensif let Some(main) = CapWindowId::Main.get(app) {@@ -554,6 +621,9 @@ impl ShowCapWindow {CapWindowId::Editor { id }}ShowCapWindow::RecordingsOverlay => CapWindowId::RecordingsOverlay,+ ShowCapWindow::TargetSelectOverlay { display_id } => CapWindowId::TargetSelectOverlay {+ display_id: display_id.clone(),+ },ShowCapWindow::WindowCaptureOccluder { screen_id } => {CapWindowId::WindowCaptureOccluder {screen_id: *screen_id,diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsxindex 37010abad..ec198a941 100644--- a/apps/desktop/src/App.tsx+++ b/apps/desktop/src/App.tsx@@ -27,6 +27,9 @@ import { CapErrorBoundary } from "./components/CapErrorBoundary";const queryClient = new QueryClient({defaultOptions: {+ queries: {+ experimental_prefetchInRender: true,+ },mutations: {onError: (e) => {message(`Error\n${e}`);diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex d446c8bc4..81f96855e 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -64,6 +64,13 @@ function Page() {const currentRecording = createCurrentRecordingQuery();const generalSettings = generalSettingsStore.createQuery();+ // We do this on focus so the window doesn't get revealed when toggling the setting+ const navigate = useNavigate();+ createEventListener(window, "focus", () => {+ if (generalSettings.data?.enableNewRecordingFlow === true)+ navigate("/new-main");+ });+const isRecording = () => !!currentRecording.data;const license = createLicenseQuery();@@ -489,7 +496,6 @@ function useRequestPermission() {if (type === "camera") {await commands.resetCameraPermissions();} else if (type === "microphone") {- console.log("wowzers");await commands.resetMicrophonePermissions();}await commands.requestPermission(type);@@ -522,6 +528,7 @@ import {useRecordingOptions,} from "./OptionsContext";import { createTauriEventListener } from "~/utils/createEventListener";+import { createEventListener } from "@solid-primitives/event-listener";let hasChecked = false;function createUpdateCheck() {diff --git a/apps/desktop/src/routes/(window-chrome)/new-main.tsx b/apps/desktop/src/routes/(window-chrome)/new-main.tsxnew file mode 100644index 000000000..22cc15844--- /dev/null+++ b/apps/desktop/src/routes/(window-chrome)/new-main.tsx@@ -0,0 +1,751 @@+import { useNavigate } from "@solidjs/router";+import {+ createMutation,+ createQuery,+ useQueryClient,+} from "@tanstack/solid-query";+import { getVersion } from "@tauri-apps/api/app";+import {+ getCurrentWindow,+ LogicalSize,+ primaryMonitor,+ Window,+} from "@tauri-apps/api/window";+import { cx } from "cva";+import {+ ComponentProps,+ createEffect,+ createResource,+ createSignal,+ onCleanup,+ onMount,+ Show,+} from "solid-js";+import { createStore, reconcile } from "solid-js/store";++import Tooltip from "~/components/Tooltip";+import { trackEvent } from "~/utils/analytics";+import {+ createCameraMutation,+ createCurrentRecordingQuery,+ createLicenseQuery,+ getPermissions,+ listAudioDevices,+ listScreens,+ listVideoDevices,+ listWindows,+} from "~/utils/queries";+import {+ CameraInfo,+ type CaptureScreen,+ commands,+ DeviceOrModelID,+ events,+ ScreenCaptureTarget,+} from "~/utils/tauri";++function getWindowSize() {+ return {+ width: 270,+ height: 255,+ };+}++const findCamera = (cameras: CameraInfo[], id: DeviceOrModelID) => {+ return cameras.find((c) => {+ if (!id) return false;+ return "DeviceID" in id+ ? id.DeviceID === c.device_id+ : id.ModelID === c.model_id;+ });+};++export default function () {+ const generalSettings = generalSettingsStore.createQuery();++ // We do this on focus so the window doesn't get revealed when toggling the setting+ const navigate = useNavigate();+ createEventListener(window, "focus", () => {+ if (generalSettings.data?.enableNewRecordingFlow === false) navigate("/");+ });++ return (+ <RecordingOptionsProvider>+ <Page />+ </RecordingOptionsProvider>+ );+}++function Page() {+ const { rawOptions, setOptions } = useRecordingOptions();++ const license = createLicenseQuery();++ createUpdateCheck();++ onMount(async () => {+ // Enforce window size with multiple safeguards+ const currentWindow = getCurrentWindow();++ // We resize the window on mount as the user could be switching to the new recording flow+ // which has a differently sized window.+ const size = getWindowSize();+ currentWindow.setSize(new LogicalSize(size.width, size.height));++ // Check size when app regains focus+ const unlistenFocus = currentWindow.onFocusChanged(+ ({ payload: focused }) => {+ if (focused) {+ const size = getWindowSize();++ currentWindow.setSize(new LogicalSize(size.width, size.height));+ }+ }+ );++ // Listen for resize events+ const unlistenResize = currentWindow.onResized(() => {+ const size = getWindowSize();++ currentWindow.setSize(new LogicalSize(size.width, size.height));+ });++ onCleanup(async () => {+ (await unlistenFocus)?.();+ (await unlistenResize)?.();+ });++ const monitor = await primaryMonitor();+ if (!monitor) return;+ });++ createEffect(() => {+ if (rawOptions.targetMode) commands.openTargetSelectOverlays();+ else commands.closeTargetSelectOverlays();+ });++ const screens = createQuery(() => listScreens);+ const windows = createQuery(() => listWindows);+ const cameras = createQuery(() => listVideoDevices);+ const mics = createQuery(() => listAudioDevices);++ cameras.promise.then((cameras) => {+ if (rawOptions.cameraID && findCamera(cameras, rawOptions.cameraID)) {+ setOptions("cameraLabel", null);+ }+ });++ mics.promise.then((mics) => {+ if (rawOptions.micName && !mics.includes(rawOptions.micName)) {+ setOptions("micName", null);+ }+ });++ // these options take the raw config values and combine them with the available options,+ // allowing us to define fallbacks if the selected options aren't actually available+ const options = {+ screen: () => {+ let screen;++ if (rawOptions.captureTarget.variant === "screen") {+ const screenId = rawOptions.captureTarget.id;+ screen =+ screens.data?.find((s) => s.id === screenId) ?? screens.data?.[0];+ } else if (rawOptions.captureTarget.variant === "area") {+ const screenId = rawOptions.captureTarget.screen;+ screen =+ screens.data?.find((s) => s.id === screenId) ?? screens.data?.[0];+ }++ return screen;+ },+ window: () => {+ let win;++ if (rawOptions.captureTarget.variant === "window") {+ const windowId = rawOptions.captureTarget.id;+ win = windows.data?.find((s) => s.id === windowId) ?? windows.data?.[0];+ }++ return win;+ },+ camera: () => {+ if (!rawOptions.cameraID) return undefined;+ return findCamera(cameras.data || [], rawOptions.cameraID);+ },++ micName: () => mics.data?.find((name) => name === rawOptions.micName),+ target: (): ScreenCaptureTarget => {+ switch (rawOptions.captureTarget.variant) {+ case "screen":+ return { variant: "screen", id: options.screen()?.id ?? -1 };+ case "window":+ return { variant: "window", id: options.window()?.id ?? -1 };+ case "area":+ return {+ variant: "area",+ bounds: rawOptions.captureTarget.bounds,+ screen: options.screen()?.id ?? -1,+ };+ }+ },+ };++ // if target is window and no windows are available, switch to screen capture+ createEffect(() => {+ if (options.target().variant === "window" && windows.data?.length === 0) {+ setOptions(+ "captureTarget",+ reconcile({+ variant: "screen",+ id: options.screen()?.id ?? -1,+ })+ );+ }+ });++ const setMicInput = createMutation(() => ({+ mutationFn: async (name: string | null) => {+ await commands.setMicInput(name);+ setOptions("micName", name);+ },+ }));++ const setCamera = createCameraMutation();++ onMount(() => {+ if (rawOptions.cameraID && "ModelID" in rawOptions.cameraID)+ setCamera.mutate({ ModelID: rawOptions.cameraID.ModelID });+ else if (rawOptions.cameraID && "DeviceID" in rawOptions.cameraID)+ setCamera.mutate({ DeviceID: rawOptions.cameraID.DeviceID });+ else setCamera.mutate(null);+ });++ return (+ <div class="flex justify-center flex-col p-[0.75rem] gap-[0.75rem] text-[0.875rem] font-[400] h-full text-[--text-primary]">+ <WindowChromeHeader hideMaximize>+ <div+ dir={ostype() === "windows" ? "rtl" : "rtl"}+ class="flex gap-1 items-center mx-2"+ >+ <Tooltip content={<span>Settings</span>}>+ <button+ type="button"+ onClick={async () => {+ await commands.showWindow({ Settings: { page: "general" } });+ getCurrentWindow().hide();+ }}+ class="flex items-center justify-center w-5 h-5 -ml-[1.5px]"+ >+ <IconCapSettings class="text-gray-11 size-5 hover:text-gray-12" />+ </button>+ </Tooltip>+ <Tooltip content={<span>Previous Recordings</span>}>+ <button+ type="button"+ onClick={async () => {+ await commands.showWindow({ Settings: { page: "recordings" } });+ getCurrentWindow().hide();+ }}+ class="flex justify-center items-center w-5 h-5"+ >+ <IconLucideSquarePlay class="text-gray-11 size-5 hover:text-gray-12" />+ </button>+ </Tooltip>++ <ChangelogButton />++ <Show when={!license.isLoading && license.data?.type === "personal"}>+ <button+ type="button"+ onClick={() => commands.showWindow("Upgrade")}+ class="flex relative justify-center items-center w-5 h-5"+ >+ <IconLucideGift class="text-gray-11 size-5 hover:text-gray-12" />+ <div+ style={{ "background-color": "#FF4747" }}+ class="block z-10 absolute top-0 right-0 size-1.5 rounded-full animate-bounce"+ />+ </button>+ </Show>++ {import.meta.env.DEV && (+ <button+ type="button"+ onClick={() => {+ new WebviewWindow("debug", { url: "/debug" });+ }}+ class="flex justify-center items-center w-5 h-5"+ >+ <IconLucideBug class="text-gray-11 size-5 hover:text-gray-12" />+ </button>+ )}+ </div>+ </WindowChromeHeader>+ <div class="flex flex-row items-stretch gap-1.5 w-full text-xs text-gray-11">+ <TargetTypeButton+ selected={rawOptions.targetMode === "screen"}+ Component={IconMdiMonitor}+ onClick={() =>+ setOptions("targetMode", (v) => (v === "screen" ? null : "screen"))+ }+ name="Screen"+ />+ <TargetTypeButton+ selected={rawOptions.targetMode === "window"}+ Component={IconLucideAppWindowMac}+ onClick={() =>+ setOptions("targetMode", (v) => (v === "window" ? null : "window"))+ }+ name="Window"+ />+ <TargetTypeButton+ selected={rawOptions.targetMode === "area"}+ Component={IconMaterialSymbolsScreenshotFrame2Rounded}+ onClick={() =>+ setOptions("targetMode", (v) => (v === "area" ? null : "area"))+ }+ name="Area"+ />+ </div>+ <CameraSelect+ disabled={cameras.isPending}+ options={cameras.data ?? []}+ value={options.camera() ?? null}+ onChange={(c) => {+ if (!c) setCamera.mutate(null);+ else if (c.model_id) setCamera.mutate({ ModelID: c.model_id });+ else setCamera.mutate({ DeviceID: c.device_id });+ }}+ />+ <MicrophoneSelect+ disabled={mics.isPending}+ options={mics.isPending ? [] : mics.data ?? []}+ // this prevents options.micName() from suspending on initial load+ value={mics.isPending ? rawOptions.micName : options.micName() ?? null}+ onChange={(v) => setMicInput.mutate(v)}+ />+ <SystemAudio />+ </div>+ );+}++function useRequestPermission() {+ const queryClient = useQueryClient();++ async function requestPermission(type: "camera" | "microphone") {+ try {+ if (type === "camera") {+ await commands.resetCameraPermissions();+ } else if (type === "microphone") {+ await commands.resetMicrophonePermissions();+ }+ await commands.requestPermission(type);+ await queryClient.refetchQueries(getPermissions);+ } catch (error) {+ console.error(`Failed to get ${type} permission:`, error);+ }+ }++ return requestPermission;+}++import { makePersisted } from "@solid-primitives/storage";+import { CheckMenuItem, Menu, PredefinedMenuItem } from "@tauri-apps/api/menu";+import { WebviewWindow } from "@tauri-apps/api/webviewWindow";+import * as dialog from "@tauri-apps/plugin-dialog";+import { type as ostype } from "@tauri-apps/plugin-os";+import * as updater from "@tauri-apps/plugin-updater";++import { generalSettingsStore } from "~/store";+import { apiClient } from "~/utils/web-api";+import {+ RecordingOptionsProvider,+ useRecordingOptions,+} from "./OptionsContext";+import type { Component } from "solid-js";+import { WindowChromeHeader } from "./Context";+import { createEventListener } from "@solid-primitives/event-listener";++let hasChecked = false;+function createUpdateCheck() {+ if (import.meta.env.DEV) return;++ const navigate = useNavigate();++ onMount(async () => {+ if (hasChecked) return;+ hasChecked = true;++ await new Promise((res) => setTimeout(res, 1000));++ const update = await updater.check();+ if (!update) return;++ const shouldUpdate = await dialog.confirm(+ `Version ${update.version} of Cap is available, would you like to install it?`,+ { title: "Update Cap", okLabel: "Update", cancelLabel: "Ignore" }+ );++ if (!shouldUpdate) return;+ navigate("/update");+ });+}++const NO_CAMERA = "No Camera";++function CameraSelect(props: {+ disabled?: boolean;+ options: CameraInfo[];+ value: CameraInfo | null;+ onChange: (camera: CameraInfo | null) => void;+}) {+ const currentRecording = createCurrentRecordingQuery();+ const permissions = createQuery(() => getPermissions);+ const requestPermission = useRequestPermission();++ const permissionGranted = () =>+ permissions?.data?.camera === "granted" ||+ permissions?.data?.camera === "notNeeded";++ const onChange = (cameraLabel: CameraInfo | null) => {+ if (!cameraLabel && permissions?.data?.camera !== "granted")+ return requestPermission("camera");++ props.onChange(cameraLabel);++ trackEvent("camera_selected", {+ camera_name: cameraLabel?.display_name ?? null,+ enabled: !!cameraLabel,+ });+ };++ return (+ <div class="flex flex-col gap-[0.25rem] items-stretch text-[--text-primary]">+ <button+ disabled={!!currentRecording.data || props.disabled}+ class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-3 w-full disabled:text-gray-11 transition-colors KSelect"+ onClick={() => {+ Promise.all([+ CheckMenuItem.new({+ text: NO_CAMERA,+ checked: props.value === null,+ action: () => onChange(null),+ }),+ PredefinedMenuItem.new({ item: "Separator" }),+ ...props.options.map((o) =>+ CheckMenuItem.new({+ text: o.display_name,+ checked: o === props.value,+ action: () => onChange(o),+ })+ ),+ ])+ .then((items) => Menu.new({ items }))+ .then((m) => {+ m.popup();+ });+ }}+ >+ <IconCapCamera class="text-gray-11 size-[1.25rem]" />+ <span class="flex-1 text-left truncate">+ {props.value?.display_name ?? NO_CAMERA}+ </span>+ <TargetSelectInfoPill+ value={props.value}+ permissionGranted={permissionGranted()}+ requestPermission={() => requestPermission("camera")}+ onClick={(e) => {+ if (!props.options) return;+ if (props.value !== null) {+ e.stopPropagation();+ props.onChange(null);+ }+ }}+ />+ </button>+ </div>+ );+}++const NO_MICROPHONE = "No Microphone";++function MicrophoneSelect(props: {+ disabled?: boolean;+ options: string[];+ value: string | null;+ onChange: (micName: string | null) => void;+}) {+ const DB_SCALE = 40;++ const permissions = createQuery(() => getPermissions);+ const currentRecording = createCurrentRecordingQuery();++ const [dbs, setDbs] = createSignal<number | undefined>();+ const [isInitialized, setIsInitialized] = createSignal(false);++ const requestPermission = useRequestPermission();++ const permissionGranted = () =>+ permissions?.data?.microphone === "granted" ||+ permissions?.data?.microphone === "notNeeded";++ type Option = { name: string };++ const handleMicrophoneChange = async (item: Option | null) => {+ if (!props.options) return;+ props.onChange(item ? item.name : null);+ if (!item) setDbs();++ trackEvent("microphone_selected", {+ microphone_name: item?.name ?? null,+ enabled: !!item,+ });+ };++ const result = events.audioInputLevelChange.listen((dbs) => {+ if (!props.value) setDbs();+ else setDbs(dbs.payload);+ });++ onCleanup(() => result.then((unsub) => unsub()));++ // visual audio level from 0 -> 1+ const audioLevel = () =>+ Math.pow(1 - Math.max((dbs() ?? 0) + DB_SCALE, 0) / DB_SCALE, 0.5);++ // Initialize audio input if needed - only once when component mounts+ onMount(() => {+ if (!props.value || !permissionGranted() || isInitialized()) return;++ setIsInitialized(true);+ });++ return (+ <div class="flex flex-col gap-[0.25rem] items-stretch text-[--text-primary]">+ <button+ disabled={!!currentRecording.data || props.disabled}+ class="relative flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-3 w-full disabled:text-gray-11 transition-colors KSelect overflow-hidden z-10"+ onClick={() => {+ Promise.all([+ CheckMenuItem.new({+ text: NO_MICROPHONE,+ checked: props.value === null,+ action: () => handleMicrophoneChange(null),+ }),+ PredefinedMenuItem.new({ item: "Separator" }),+ ...(props.options ?? []).map((name) =>+ CheckMenuItem.new({+ text: name,+ checked: name === props.value,+ action: () => handleMicrophoneChange({ name: name }),+ })+ ),+ ])+ .then((items) => Menu.new({ items }))+ .then((m) => {+ m.popup();+ });+ }}+ >+ <Show when={dbs()}>+ {(_) => (+ <div+ class="bg-blue-100 opacity-50 left-0 inset-y-0 absolute -z-10 transition-[right] duration-100"+ style={{+ right: `${audioLevel() * 100}%`,+ }}+ />+ )}+ </Show>+ <IconCapMicrophone class="text-gray-11 size-[1.25rem]" />+ <span class="flex-1 text-left truncate">+ {props.value ?? NO_MICROPHONE}+ </span>+ <TargetSelectInfoPill+ value={props.value}+ permissionGranted={permissionGranted()}+ requestPermission={() => requestPermission("microphone")}+ onClick={(e) => {+ if (props.value !== null) {+ e.stopPropagation();+ props.onChange(null);+ }+ }}+ />+ </button>+ </div>+ );+}++function SystemAudio() {+ const { rawOptions, setOptions } = useRecordingOptions();+ const currentRecording = createCurrentRecordingQuery();++ return (+ <button+ onClick={() => {+ if (!rawOptions) return;+ setOptions({ captureSystemAudio: !rawOptions.captureSystemAudio });+ }}+ disabled={!!currentRecording.data}+ class="relative flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-3 w-full disabled:text-gray-11 transition-colors KSelect overflow-hidden z-10"+ >+ <div class="size-[1.25rem] flex items-center justify-center">+ <IconPhMonitorBold class="text-gray-11 stroke-2 size-[1.2rem]" />+ </div>+ <span class="flex-1 text-left truncate">+ {rawOptions.captureSystemAudio+ ? "Record System Audio"+ : "No System Audio"}+ </span>+ <InfoPill variant={rawOptions.captureSystemAudio ? "blue" : "red"}>+ {rawOptions.captureSystemAudio ? "On" : "Off"}+ </InfoPill>+ </button>+ );+}++function TargetSelectInfoPill<T>(props: {+ value: T | null;+ permissionGranted: boolean;+ requestPermission: () => void;+ onClick: (e: MouseEvent) => void;+}) {+ return (+ <InfoPill+ variant={props.value !== null && props.permissionGranted ? "blue" : "red"}+ onPointerDown={(e) => {+ if (!props.permissionGranted || props.value === null) return;++ e.stopPropagation();+ }}+ onClick={(e) => {+ if (!props.permissionGranted) {+ props.requestPermission();+ return;+ }++ props.onClick(e);+ }}+ >+ {!props.permissionGranted+ ? "Request Permission"+ : props.value !== null+ ? "On"+ : "Off"}+ </InfoPill>+ );+}++function InfoPill(+ props: ComponentProps<"button"> & { variant: "blue" | "red" }+) {+ return (+ <button+ {...props}+ type="button"+ class={cx(+ "px-[0.375rem] rounded-full text-[0.75rem]",+ props.variant === "blue"+ ? "bg-blue-3 text-blue-9"+ : "bg-red-3 text-red-9"+ )}+ />+ );+}++function ChangelogButton() {+ const [changelogState, setChangelogState] = makePersisted(+ createStore({+ hasUpdate: false,+ lastOpenedVersion: "",+ changelogClicked: false,+ }),+ { name: "changelogState" }+ );++ const [currentVersion] = createResource(() => getVersion());++ const [changelogStatus] = createResource(+ () => currentVersion(),+ async (version) => {+ if (!version) {+ return { hasUpdate: false };+ }+ const response = await apiClient.desktop.getChangelogStatus({+ query: { version },+ });+ if (response.status === 200) return response.body;+ return null;+ }+ );++ const handleChangelogClick = () => {+ commands.showWindow({ Settings: { page: "changelog" } });+ getCurrentWindow().hide();+ const version = currentVersion();+ if (version) {+ setChangelogState({+ hasUpdate: false,+ lastOpenedVersion: version,+ changelogClicked: true,+ });+ }+ };++ createEffect(() => {+ if (changelogStatus.state === "ready" && currentVersion()) {+ const hasUpdate = changelogStatus()?.hasUpdate || false;+ if (+ hasUpdate === true &&+ changelogState.lastOpenedVersion !== currentVersion()+ ) {+ setChangelogState({+ hasUpdate: true,+ lastOpenedVersion: currentVersion(),+ changelogClicked: false,+ });+ }+ }+ });++ return (+ <Tooltip openDelay={0} content="Changelog">+ <button+ type="button"+ onClick={handleChangelogClick}+ class="flex relative justify-center items-center w-5 h-5"+ >+ <IconLucideBell class="text-gray-11 size-5 hover:text-gray-12" />+ {changelogState.hasUpdate && (+ <div+ style={{ "background-color": "#FF4747" }}+ class="block z-10 absolute top-0 right-0 size-1.5 rounded-full animate-bounce"+ />+ )}+ </button>+ </Tooltip>+ );+}++function TargetTypeButton(+ props: {+ selected: boolean;+ Component: Component<ComponentProps<"svg">>;+ name: string;+ } & ComponentProps<"div">+) {+ return (+ <div+ {...props}+ class={cx(+ "flex-1 text-center flex flex-col items-center justify-end gap-1 py-1.5 rounded-lg transition-colors duration-100",+ props.selected && "bg-gray-3 text-white"+ )}+ >+ <props.Component class="size-6" />+ <span>{props.name}</span>+ </div>+ );+}diff --git a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsxindex 5db9e0d30..d9c2e3363 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx@@ -2,8 +2,9 @@ import { createResource, Show } from "solid-js";import { createStore } from "solid-js/store";import { generalSettingsStore } from "~/store";-import { type GeneralSettingsStore } from "~/utils/tauri";+import { commands, type GeneralSettingsStore } from "~/utils/tauri";import { ToggleSetting } from "./Setting";+import { getAllWindows } from "@tauri-apps/api/window";export default function ExperimentalSettings() {const [store] = createResource(() => generalSettingsStore.get());@@ -19,11 +20,11 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {const [settings, setSettings] = createStore<GeneralSettingsStore>(props.initialStore ?? {uploadIndividualFiles: false,- openEditorAfterRecording: false,hideDockIcon: false,autoCreateShareableLink: false,enableNotifications: true,enableNativeCameraPreview: false,+ enableNewRecordingFlow: false,autoZoomOnClicks: false,});@@ -51,27 +52,52 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {expected.</p></div>- <div class="px-3 rounded-xl border divide-y divide-gray-3 border-gray-3 bg-gray-2">- <ToggleSetting- label="Custom cursor capture in Studio Mode"- description="Studio Mode recordings will capture cursor state separately for customisation (size, smoothing) in the editor. Currently experimental as cursor events may not be captured accurately."- value={!!settings.customCursorCapture}- onChange={(value) => handleChange("customCursorCapture", value)}- />- <ToggleSetting- label="Native camera preview"- description="Show the camera preview using a native GPU surface instead of rendering it within the webview. This is not functional on certain Windows systems so your mileage may vary."- value={!!settings.enableNativeCameraPreview}- onChange={(value) =>- handleChange("enableNativeCameraPreview", value)- }- />- <ToggleSetting- label="Auto zoom on clicks"- description="Automatically generate zoom segments around mouse clicks during Studio Mode recordings. This helps highlight important interactions in your recordings."- value={!!settings.autoZoomOnClicks}- onChange={(value) => handleChange("autoZoomOnClicks", value)}- />+ <div class="space-y-3">+ <h3 class="text-sm text-gray-12 w-fit">Recording Features</h3>+ <div class="px-3 rounded-xl border divide-y divide-gray-3 border-gray-3 bg-gray-2">+ <ToggleSetting+ label="Custom cursor capture in Studio Mode"+ description="Studio Mode recordings will capture cursor state separately for customisation (size, smoothing) in the editor. Currently experimental as cursor events may not be captured accurately."+ value={!!settings.customCursorCapture}+ onChange={(value) => handleChange("customCursorCapture", value)}+ />+ <ToggleSetting+ label="Native camera preview"+ description="Show the camera preview using a native GPU surface instead of rendering it within the webview. This is not functional on certain Windows systems so your mileage may vary."+ value={!!settings.enableNativeCameraPreview}+ onChange={(value) =>+ handleChange("enableNativeCameraPreview", value)+ }+ />+ <ToggleSetting+ label="Auto zoom on clicks"+ description="Automatically generate zoom segments around mouse clicks during Studio Mode recordings. This helps highlight important interactions in your recordings."+ value={!!settings.autoZoomOnClicks}+ onChange={(value) => {+ handleChange("autoZoomOnClicks", value);+ // This is bad code, but I just want the UI to not jank and can't seem to find the issue.+ setTimeout(+ () => window.scrollTo({ top: 0, behavior: "instant" }),+ 5+ );+ }}+ />+ {/*{import.meta.env.DEV && (+ <ToggleSetting+ label="New recording flow"+ description="New and improved flow for starting a recording! You may need to restart the app for this to take effect."+ value={!!settings.enableNewRecordingFlow}+ onChange={(value) => {+ handleChange("enableNewRecordingFlow", value);+ // This is bad code, but I just want the UI to not jank and can't seem to find the issue.+ setTimeout(+ () => window.scrollTo({ top: 0, behavior: "instant" }),+ 5+ );+ }}+ />+ )}*/}+ </div></div></div></div>diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsxindex 7add49fed..9fe97ec8b 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx@@ -112,11 +112,11 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {const [settings, setSettings] = createStore<GeneralSettingsStore>(props.initialStore ?? {uploadIndividualFiles: false,- openEditorAfterRecording: false,hideDockIcon: false,autoCreateShareableLink: false,enableNotifications: true,enableNativeCameraPreview: false,+ enableNewRecordingFlow: false,autoZoomOnClicks: false,});diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsxnew file mode 100644index 000000000..b3e02a3ac--- /dev/null+++ b/apps/desktop/src/routes/target-select-overlay.tsx@@ -0,0 +1,600 @@+import { Button } from "@cap/ui-solid";+import {+ ComponentProps,+ createEffect,+ createRoot,+ createSignal,+ JSX,+ Match,+ onCleanup,+ Show,+ Switch,+} from "solid-js";+import { useSearchParams } from "@solidjs/router";+import { createStore, reconcile } from "solid-js/store";+import {+ createEventListener,+ createEventListenerMap,+} from "@solid-primitives/event-listener";+import { cx } from "cva";++import { createOptionsQuery } from "~/utils/queries";+import {+ commands,+ events,+ ScreenCaptureTarget,+ TargetUnderCursor,+} from "~/utils/tauri";+import { getCurrentWindow } from "@tauri-apps/api/window";++export default function () {+ const [params] = useSearchParams<{ displayId: string }>();+ const { rawOptions, setOptions } = createOptionsQuery();++ const [targetUnderCursor, setTargetUnderCursor] =+ createStore<TargetUnderCursor>({+ display_id: null,+ window: null,+ screen: null,+ });++ const unsubTargetUnderCursor = events.targetUnderCursor.listen((event) => {+ setTargetUnderCursor(reconcile(event.payload));+ });+ onCleanup(() => unsubTargetUnderCursor.then((unsub) => unsub()));++ const [bounds, _setBounds] = createStore({+ position: { x: 0, y: 0 },+ size: { width: 400, height: 300 },+ });++ const setBounds = (newBounds: typeof bounds) => {+ newBounds.position.x = Math.max(0, newBounds.position.x);+ newBounds.position.y = Math.max(0, newBounds.position.y);+ newBounds.size.width = Math.min(+ window.innerWidth - newBounds.position.x,+ newBounds.size.width+ );+ newBounds.size.height = Math.min(+ window.innerHeight - newBounds.position.y,+ newBounds.size.height+ );++ _setBounds(newBounds);+ };++ // We do this so any Cap window, (or external in the case of a bug) that are focused can trigger the close shortcut+ const unsubOnEscapePress = events.onEscapePress.listen(() =>+ setOptions("targetMode", null)+ );+ onCleanup(() => unsubOnEscapePress.then((f) => f()));++ createEffect(() => {+ if (rawOptions.captureTarget === undefined) getCurrentWindow().close();+ });++ // This prevents browser keyboard shortcuts from firing.+ // Eg. on Windows Ctrl+P would open the print dialog without this+ createEventListener(document, "keydown", (e) => e.preventDefault());++ return (+ <Switch>+ <Match when={rawOptions.targetMode === "screen"}>+ {(_) => (+ <Show when={targetUnderCursor.screen} keyed>+ {(screenUnderCursor) => (+ <div+ data-over={targetUnderCursor.display_id === params.displayId}+ class="w-screen h-screen flex flex-col items-center justify-center bg-black/50 data-[over='true']:bg-blue-600/40 transition-colors"+ >+ <span class="text-3xl font-semibold mb-2">+ {screenUnderCursor.name}+ </span>+ <span class="text-xs mb-2">+ {`${screenUnderCursor.physical_size.width}x${screenUnderCursor.physical_size.height} · ${screenUnderCursor.refresh_rate}FPS`}+ </span>++ <RecordingControls+ target={{+ variant: "screen",+ id: getDisplayId(params.displayId),+ }}+ />+ </div>+ )}+ </Show>+ )}+ </Match>+ <Match+ when={+ rawOptions.targetMode === "window" &&+ targetUnderCursor.display_id === params.displayId+ }+ >+ <Show when={targetUnderCursor.window} keyed>+ {(windowUnderCursor) => (+ <div+ data-over={targetUnderCursor.display_id === params.displayId}+ class="w-screen h-screen bg-black/50 relative"+ >+ <div+ class="bg-blue-600/40 absolute flex flex-col items-center justify-center"+ style={{+ width: `${windowUnderCursor.bounds.size.width}px`,+ height: `${windowUnderCursor.bounds.size.height}px`,+ left: `${windowUnderCursor.bounds.position.x}px`,+ top: `${windowUnderCursor.bounds.position.y}px`,+ }}+ >+ <div class="flex flex-col items-center justify-center">+ <Show when={windowUnderCursor.icon}>+ {(icon) => (+ <img+ src={icon()}+ alt={`${windowUnderCursor.app_name} icon`}+ class="w-32 h-32 mb-3 rounded-lg"+ />+ )}+ </Show>+ <span class="text-3xl font-semibold mb-2">+ {windowUnderCursor.app_name}+ </span>+ <span class="text-xs mb-2">+ {`${windowUnderCursor.bounds.size.width}x${windowUnderCursor.bounds.size.height}`}+ </span>+ </div>+ <RecordingControls+ target={{+ variant: "window",+ id: Number(windowUnderCursor.id),+ }}+ />++ <Button+ variant="primary"+ size="sm"+ class="mt-4"+ onClick={() => {+ setBounds(windowUnderCursor.bounds);+ setOptions({+ targetMode: "area",+ });+ }}+ >+ Adjust recording area+ </Button>+ </div>+ </div>+ )}+ </Show>+ </Match>+ <Match when={rawOptions.targetMode === "area"}>+ {(_) => {+ const [dragging, setDragging] = createSignal(false);++ function createOnMouseDown(+ onDrag: (+ startBounds: typeof bounds,+ delta: { x: number; y: number }+ ) => void+ ) {+ return (downEvent: MouseEvent) => {+ const startBounds = {+ position: { ...bounds.position },+ size: { ...bounds.size },+ };++ createRoot((dispose) => {+ createEventListenerMap(window, {+ mouseup: () => dispose(),+ mousemove: (moveEvent) => {+ onDrag(startBounds, {+ x: Math.max(+ -startBounds.position.x,+ moveEvent.clientX - downEvent.clientX+ ),+ y: Math.max(+ -startBounds.position.y,+ moveEvent.clientY - downEvent.clientY+ ),+ });+ },+ });+ });+ };+ }++ function ResizeHandles() {+ return (+ <>+ {/* Top Left Button */}+ <ResizeHandle+ class="cursor-nw-resize"+ style={{+ left: `${bounds.position.x + 1}px`,+ top: `${bounds.position.y + 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const width = startBounds.size.width - delta.x;+ const limitedWidth = Math.max(width, 150);++ const height = startBounds.size.height - delta.y;+ const limitedHeight = Math.max(height, 150);++ setBounds({+ position: {+ x:+ startBounds.position.x ++ delta.x -+ (limitedWidth - width),+ y:+ startBounds.position.y ++ delta.y -+ (limitedHeight - height),+ },+ size: {+ width: limitedWidth,+ height: limitedHeight,+ },+ });+ })}+ />++ {/* Top Right Button */}+ <ResizeHandle+ class="cursor-ne-resize"+ style={{+ left: `${bounds.position.x + bounds.size.width - 1}px`,+ top: `${bounds.position.y + 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const width = startBounds.size.width + delta.x;+ const limitedWidth = Math.max(width, 150);++ const height = startBounds.size.height - delta.y;+ const limitedHeight = Math.max(height, 150);++ setBounds({+ position: {+ x: startBounds.position.x,+ y:+ startBounds.position.y ++ delta.y -+ (limitedHeight - height),+ },+ size: {+ width: limitedWidth,+ height: limitedHeight,+ },+ });+ })}+ />++ {/* Bottom Left Button */}+ <ResizeHandle+ class="cursor-sw-resize"+ style={{+ left: `${bounds.position.x + 1}px`,+ top: `${bounds.position.y + bounds.size.height - 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const width = startBounds.size.width - delta.x;+ const limitedWidth = Math.max(width, 150);++ const height = startBounds.size.height + delta.y;+ const limitedHeight = Math.max(height, 150);++ setBounds({+ position: {+ x:+ startBounds.position.x ++ delta.x -+ (limitedWidth - width),+ y: startBounds.position.y,+ },+ size: {+ width: limitedWidth,+ height: limitedHeight,+ },+ });+ })}+ />++ {/* Bottom Right Button */}+ <ResizeHandle+ class="cursor-se-resize"+ style={{+ left: `${bounds.position.x + bounds.size.width - 1}px`,+ top: `${bounds.position.y + bounds.size.height - 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const width = startBounds.size.width + delta.x;+ const limitedWidth = Math.max(width, 150);++ const height = startBounds.size.height + delta.y;+ const limitedHeight = Math.max(height, 150);++ setBounds({+ position: {+ x: startBounds.position.x,+ y: startBounds.position.y,+ },+ size: {+ width: limitedWidth,+ height: limitedHeight,+ },+ });+ })}+ />++ {/* Top Edge Button */}+ <ResizeHandle+ class="cursor-n-resize"+ style={{+ left: `${bounds.position.x + bounds.size.width / 2}px`,+ top: `${bounds.position.y + 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const height = startBounds.size.height - delta.y;+ const limitedHeight = Math.max(height, 150);++ setBounds({+ position: {+ x: startBounds.position.x,+ y:+ startBounds.position.y ++ delta.y -+ (limitedHeight - height),+ },+ size: {+ width: startBounds.size.width,+ height: limitedHeight,+ },+ });+ })}+ />++ {/* Right Edge Button */}+ <ResizeHandle+ class="cursor-e-resize"+ style={{+ left: `${bounds.position.x + bounds.size.width - 1}px`,+ top: `${bounds.position.y + bounds.size.height / 2}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ setBounds({+ position: {+ x: startBounds.position.x,+ y: startBounds.position.y,+ },+ size: {+ width: Math.max(150, startBounds.size.width + delta.x),+ height: startBounds.size.height,+ },+ });+ })}+ />++ {/* Bottom Edge Button */}+ <ResizeHandle+ class="cursor-s-resize"+ style={{+ left: `${bounds.position.x + bounds.size.width / 2}px`,+ top: `${bounds.position.y + bounds.size.height - 1}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ setBounds({+ position: {+ x: startBounds.position.x,+ y: startBounds.position.y,+ },+ size: {+ width: startBounds.size.width,+ height: Math.max(+ 150,+ startBounds.size.height + delta.y+ ),+ },+ });+ })}+ />++ {/* Left Edge Button */}+ <ResizeHandle+ class="cursor-w-resize"+ style={{+ left: `${bounds.position.x + 1}px`,+ top: `${bounds.position.y + bounds.size.height / 2}px`,+ }}+ onMouseDown={createOnMouseDown((startBounds, delta) => {+ const width = startBounds.size.width - delta.x;+ const limitedWidth = Math.max(150, width);++ setBounds({+ position: {+ x:+ startBounds.position.x ++ delta.x -+ (limitedWidth - width),+ y: startBounds.position.y,+ },+ size: {+ width: limitedWidth,+ height: startBounds.size.height,+ },+ });+ })}+ />+ </>+ );+ }++ function Occluders() {+ return (+ <>+ {/* Left */}+ <div+ class="bg-black/50 absolute top-0 left-0 bottom-0"+ style={{ width: `${bounds.position.x}px` }}+ />+ {/* Right */}+ <div+ class="bg-black/50 absolute top-0 right-0 bottom-0"+ style={{+ width: `${+ window.innerWidth -+ (bounds.size.width + bounds.position.x)+ }px`,+ }}+ />+ {/* Top center */}+ <div+ class="bg-black/50 absolute top-0"+ style={{+ left: `${bounds.position.x}px`,+ width: `${bounds.size.width}px`,+ height: `${bounds.position.y}px`,+ }}+ />+ {/* Bottom center */}+ <div+ class="bg-black/50 absolute bottom-0"+ style={{+ left: `${bounds.position.x}px`,+ width: `${bounds.size.width}px`,+ height: `${+ window.innerHeight -+ (bounds.size.height + bounds.position.y)+ }px`,+ }}+ />+ </>+ );+ }++ return (+ <div class="w-screen h-screen flex flex-col items-center justify-center data-[over='true']:bg-blue-600/40 transition-colors relative cursor-crosshair">+ <Occluders />++ <div+ class={cx(+ "absolute flex flex-col items-center",+ dragging() ? "cursor-grabbing" : "cursor-grab"+ )}+ style={{+ width: `${bounds.size.width}px`,+ height: `${bounds.size.height}px`,+ left: `${bounds.position.x}px`,+ top: `${bounds.position.y}px`,+ }}+ onMouseDown={(downEvent) => {+ setDragging(true);+ const startPosition = { ...bounds.position };++ createRoot((dispose) => {+ createEventListenerMap(window, {+ mousemove: (moveEvent) => {+ const newPosition = {+ x:+ startPosition.x ++ moveEvent.clientX -+ downEvent.clientX,+ y:+ startPosition.y ++ moveEvent.clientY -+ downEvent.clientY,+ };++ if (newPosition.x < 0) newPosition.x = 0;+ if (newPosition.y < 0) newPosition.y = 0;+ if (+ newPosition.x + bounds.size.width >+ window.innerWidth+ )+ newPosition.x = window.innerWidth - bounds.size.width;+ if (+ newPosition.y + bounds.size.height >+ window.innerHeight+ )+ newPosition.y =+ window.innerHeight - bounds.size.height;++ _setBounds("position", newPosition);+ },+ mouseup: () => {+ setDragging(false);+ dispose();+ },+ });+ });+ }}+ >+ <div+ class="absolute top-full flex flex-col items-center m-2"+ style={{ width: `${bounds.size.width}px` }}+ >+ <RecordingControls+ target={{+ variant: "area",+ screen: Number(params.displayId),+ bounds: {+ x: bounds.position.x,+ y: bounds.position.y,+ width: bounds.size.width,+ height: bounds.size.height,+ },+ }}+ />+ </div>+ </div>++ <ResizeHandles />++ <span class="text-xl z-10">Click and drag area to record</span>+ </div>+ );+ }}+ </Match>+ </Switch>+ );+}++function RecordingControls(props: { target: ScreenCaptureTarget }) {+ const { rawOptions } = createOptionsQuery();++ return (+ <Button+ size="lg"+ onClick={() => {+ commands.startRecording({+ capture_target: props.target,+ mode: rawOptions.mode,+ capture_system_audio: rawOptions.captureSystemAudio,+ });+ }}+ >+ Start Recording+ </Button>+ );+}++function ResizeHandle(+ props: Omit<ComponentProps<"button">, "style"> & { style?: JSX.CSSProperties }+) {+ return (+ <button+ {...props}+ class={cx(+ "size-3 bg-black rounded-full absolute border-[1.2px] border-white",+ props.class+ )}+ style={{ ...props.style, transform: "translate(-50%, -50%)" }}+ />+ );+}++function getDisplayId(displayId: string | undefined) {+ const id = Number(displayId);+ if (Number.isNaN(id)) return 0;+ return id;+}diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.tsindex f0c9fb10f..34491c423 100644--- a/apps/desktop/src/utils/queries.ts+++ b/apps/desktop/src/utils/queries.ts@@ -51,7 +51,7 @@ const getCurrentRecording = queryOptions({queryFn: () => commands.getCurrentRecording().then((d) => d[0]),});-const listVideoDevices = queryOptions({+export const listVideoDevices = queryOptions({queryKey: ["videoDevices"] as const,queryFn: () => commands.listCameras(),refetchInterval: 1000,@@ -87,23 +87,29 @@ export const getPermissions = queryOptions({export function createOptionsQuery() {const PERSIST_KEY = "recording-options-query";- const [state, setState] = makePersisted(- createStore<{- captureTarget: ScreenCaptureTarget;- micName: string | null;- mode: RecordingMode;- captureSystemAudio?: boolean;- cameraID?: DeviceOrModelID | null;- /** @deprecated */- cameraLabel: string | null;- }>({- captureTarget: { variant: "screen", id: 0 },- micName: null,- cameraLabel: null,- mode: "studio",- }),- { name: PERSIST_KEY }- );+ const [_state, _setState] = createStore<{+ captureTarget: ScreenCaptureTarget;+ micName: string | null;+ mode: RecordingMode;+ captureSystemAudio?: boolean;+ targetMode?: "screen" | "window" | "area" | null;+ cameraID?: DeviceOrModelID | null;+ /** @deprecated */+ cameraLabel: string | null;+ }>({+ captureTarget: { variant: "screen", id: 0 },+ micName: null,+ cameraLabel: null,+ mode: "studio",+ });++ createEventListener(window, "storage", (e) => {+ if (e.key === PERSIST_KEY) _setState(JSON.parse(e.newValue ?? "{}"));+ });++ const [state, setState] = makePersisted([_state, _setState], {+ name: PERSIST_KEY,+ });createEventListener(window, "storage", (e) => {if (e.key === PERSIST_KEY) setState(JSON.parse(e.newValue ?? "{}"));@@ -122,7 +128,7 @@ export function createCurrentRecordingQuery() {export function createLicenseQuery() {const query = createQuery(() => ({- queryKey: ["bruh"],+ queryKey: ["licenseQuery"],queryFn: async () => {const settings = await generalSettingsStore.get();const auth = await authStore.get();diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex f8d5ca6b9..9e54d4dcd 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -250,6 +250,12 @@ async deleteWhisperModel(modelPath: string) : Promise<null> {*/async exportCaptionsSrt(videoId: string) : Promise<string | null> {return await TAURI_INVOKE("export_captions_srt", { videoId });+},+async openTargetSelectOverlays() : Promise<null> {+ return await TAURI_INVOKE("open_target_select_overlays");+},+async closeTargetSelectOverlays() : Promise<null> {+ return await TAURI_INVOKE("close_target_select_overlays");}}@@ -265,6 +271,7 @@ editorStateChanged: EditorStateChanged,newNotification: NewNotification,newScreenshotAdded: NewScreenshotAdded,newStudioRecordingAdded: NewStudioRecordingAdded,+onEscapePress: OnEscapePress,recordingDeleted: RecordingDeleted,recordingEvent: RecordingEvent,recordingOptionsChanged: RecordingOptionsChanged,@@ -274,6 +281,7 @@ renderFrameEvent: RenderFrameEvent,requestNewScreenshot: RequestNewScreenshot,requestOpenSettings: RequestOpenSettings,requestStartRecording: RequestStartRecording,+targetUnderCursor: TargetUnderCursor,uploadProgress: UploadProgress}>({audioInputLevelChange: "audio-input-level-change",@@ -284,6 +292,7 @@ editorStateChanged: "editor-state-changed",newNotification: "new-notification",newScreenshotAdded: "new-screenshot-added",newStudioRecordingAdded: "new-studio-recording-added",+onEscapePress: "on-escape-press",recordingDeleted: "recording-deleted",recordingEvent: "recording-event",recordingOptionsChanged: "recording-options-changed",@@ -293,6 +302,7 @@ renderFrameEvent: "render-frame-event",requestNewScreenshot: "request-new-screenshot",requestOpenSettings: "request-open-settings",requestStartRecording: "request-start-recording",+targetUnderCursor: "target-under-cursor",uploadProgress: "upload-progress"})@@ -344,6 +354,7 @@ export type CursorMeta = { imagePath: string; hotspot: XY<number>; shape?: strinexport type CursorType = "pointer" | "circle"export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }export type DeviceOrModelID = { DeviceID: string } | { ModelID: ModelIDType }+export type DisplayId = stringexport type DownloadProgress = { progress: number; message: string }export type EditorStateChanged = { playhead_position: number }export type ExportCompression = "Minimal" | "Social" | "Web" | "Potato"@@ -352,15 +363,7 @@ export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ formatexport type FileType = "recording" | "screenshot"export type Flags = { captions: boolean }export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string; recordingCountdown?: number | null;-/**- * @deprecated- */-openEditorAfterRecording?: boolean;-/**- * @deprecated can be removed when native camera preview is ready- */-enableNativeCameraPreview?: boolean; autoZoomOnClicks?: boolean; postDeletionBehaviour?: PostDeletionBehaviour }+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour }export type GifExportSettings = { fps: number; resolution_base: XY<number> }export type HapticPattern = "Alignment" | "LevelChange" | "Generic"export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"@@ -370,6 +373,9 @@ export type HotkeysConfiguration = { show: boolean }export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }export type InstantRecordingMeta = { fps: number; sample_rate: number | null }export type JsonValue<T> = [T]+export type LogicalBounds = { position: LogicalPosition; size: LogicalSize }+export type LogicalPosition = { x: number; y: number }+export type LogicalSize = { width: number; height: number }export type MainWindowRecordingStartBehaviour = "close" | "minimise"export type ModelIDType = stringexport type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }@@ -381,6 +387,8 @@ export type NewStudioRecordingAdded = { path: string }export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessibility"export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }+export type OnEscapePress = null+export type PhysicalSize = { width: number; height: number }export type Plan = { upgraded: boolean; manual: boolean; last_checked: number }export type Platform = "MacOS" | "Windows"export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"@@ -404,15 +412,17 @@ export type RequestOpenSettings = { page: string }export type RequestStartRecording = nullexport type S3UploadMeta = { id: string }export type ScreenCaptureTarget = { variant: "window"; id: number } | { variant: "screen"; id: number } | { variant: "area"; screen: number; bounds: Bounds }+export type ScreenUnderCursor = { name: string; physical_size: PhysicalSize; refresh_rate: string }export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string }export type ShadowConfiguration = { size: number; opacity: number; blur: number }export type SharingMeta = { id: string; link: string }-export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: number } } | { CaptureArea: { screen_id: number } } | "Camera" | { InProgressRecording: { countdown: number | null } } | "Upgrade" | "ModeSelect"+export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: number } } | { TargetSelectOverlay: { display_id: DisplayId } } | { CaptureArea: { screen_id: number } } | "Camera" | { InProgressRecording: { countdown: number | null } } | "Upgrade" | "ModeSelect"export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; cursor?: string | null }export type StartRecordingInputs = { capture_target: ScreenCaptureTarget; capture_system_audio?: boolean; mode: RecordingMode }export type StereoMode = "stereo" | "monoL" | "monoR"export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }+export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null; screen: ScreenUnderCursor | null }export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"@@ -426,6 +436,8 @@ export type VideoMeta = { path: string; fps?: number;start_time?: number | null }export type VideoRecordingMetadata = { duration: number; size: number }export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }+export type WindowId = string+export type WindowUnderCursor = { id: WindowId; app_name: string; bounds: LogicalBounds; icon: string | null }export type XY<T> = { x: T; y: T }export type ZoomMode = "auto" | { manual: { x: number; y: number } }export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode }diff --git a/apps/web/app/queries.ts b/apps/web/app/queries.tsdeleted file mode 100644index e69de29bb..000000000diff --git a/crates/displays/Cargo.toml b/crates/displays/Cargo.tomlindex 4b42eed0c..8f4ffd5a8 100644--- a/crates/displays/Cargo.toml+++ b/crates/displays/Cargo.toml@@ -7,15 +7,29 @@ edition = "2024"workspace = true[dependencies]+serde = { version = "1.0.219", features = ["derive"] }+specta.workspace = true+image = "0.24"[target.'cfg(target_os = "macos")'.dependencies]core-graphics = "0.24.0"+core-foundation = "0.10.0"+cocoa = "0.26.0"+objc = "0.2.7"[target.'cfg(target_os= "windows")'.dependencies]windows = { workspace = true, features = [- "Win32_Foundation",- "Win32_System",- "Win32_UI_WindowsAndMessaging",- "Win32_Graphics_Gdi",+ "Win32_Foundation",+ "Win32_System",+ "Win32_System_Threading",+ "Win32_System_Registry",+ "Win32_System_Com",+ "Win32_System_Wmi",+ "Win32_UI_WindowsAndMessaging",+ "Win32_UI_Shell",+ "Win32_UI_HiDpi",+ "Win32_Graphics_Gdi",+ "Win32_Storage_FileSystem",+ "Win32_Devices_Display",] }windows-sys = { workspace = true }diff --git a/crates/displays/src/bounds.rs b/crates/displays/src/bounds.rsnew file mode 100644index 000000000..724ba59e1--- /dev/null+++ b/crates/displays/src/bounds.rs@@ -0,0 +1,101 @@+use serde::Serialize;+use specta::Type;++#[derive(Clone, Copy, Debug, Type, Serialize)]+pub struct LogicalBounds {+ pub(crate) position: LogicalPosition,+ pub(crate) size: LogicalSize,+}++impl LogicalBounds {+ pub fn new(position: LogicalPosition, size: LogicalSize) -> Self {+ Self { position, size }+ }++ pub fn position(&self) -> LogicalPosition {+ self.position+ }++ pub fn size(&self) -> LogicalSize {+ self.size+ }++ pub fn contains_point(&self, point: LogicalPosition) -> bool {+ point.x() >= self.position.x()+ && point.x() < self.position.x() + self.size.width()+ && point.y() >= self.position.y()+ && point.y() < self.position.y() + self.size.height()+ }+}++#[derive(Clone, Copy, Debug, Type, Serialize)]+pub struct LogicalSize {+ pub(crate) width: f64,+ pub(crate) height: f64,+}++impl LogicalSize {+ pub fn width(&self) -> f64 {+ self.width+ }++ pub fn height(&self) -> f64 {+ self.height+ }+}++#[derive(Clone, Copy, Debug, Type, Serialize)]+pub struct PhysicalSize {+ pub(crate) width: f64,+ pub(crate) height: f64,+}++impl PhysicalSize {+ pub fn new(width: f64, height: f64) -> Self {+ Self { width, height }+ }++ pub fn width(&self) -> f64 {+ self.width+ }++ pub fn height(&self) -> f64 {+ self.height+ }+}++#[derive(Clone, Copy, Debug, Type, Serialize)]+pub struct LogicalPosition {+ pub(crate) x: f64,+ pub(crate) y: f64,+}++impl LogicalPosition {+ pub fn x(&self) -> f64 {+ self.x+ }++ pub fn y(&self) -> f64 {+ self.y+ }+}++#[derive(Clone, Copy, Debug, Type, Serialize)]+pub struct PhysicalPosition {+ pub(crate) x: f64,+ pub(crate) y: f64,+}++impl PhysicalPosition {+ pub fn new(x: f64, y: f64) -> Self {+ Self { x, y }+ }++ pub fn x(&self) -> f64 {+ self.x+ }++ pub fn y(&self) -> f64 {+ self.y+ }+}diff --git a/crates/displays/src/lib.rs b/crates/displays/src/lib.rsindex 69572f3e5..9ad6b69d2 100644--- a/crates/displays/src/lib.rs+++ b/crates/displays/src/lib.rs@@ -1,6 +1,12 @@-mod platform;+pub mod bounds;+pub mod platform;-pub use platform::DisplayImpl;+use std::str::FromStr;++use bounds::{LogicalBounds, PhysicalSize};+pub use platform::{DisplayIdImpl, DisplayImpl, WindowIdImpl, WindowImpl};+use serde::{Deserialize, Serialize};+use specta::Type;#[derive(Clone, Copy)]pub struct Display(DisplayImpl);@@ -13,4 +19,152 @@ impl Display {pub fn raw_handle(&self) -> &DisplayImpl {&self.0}++ pub fn id(&self) -> DisplayId {+ DisplayId(self.0.raw_id())+ }++ pub fn from_id(id: DisplayId) -> Option<Self> {+ Self::list().into_iter().find(|d| d.id() == id)+ }++ pub fn get_containing_cursor() -> Option<Self> {+ DisplayImpl::get_containing_cursor().map(Self)+ }++ pub fn name(&self) -> String {+ self.0.name()+ }++ pub fn physical_size(&self) -> PhysicalSize {+ self.0.physical_size()+ }++ pub fn refresh_rate(&self) -> f64 {+ self.0.refresh_rate()+ }+}++#[derive(Serialize, Deserialize, Type, Clone, PartialEq)]+pub struct DisplayId(+ #[serde(with = "serde_display_id")]+ #[specta(type = String)]+ DisplayIdImpl,+);++impl std::fmt::Display for DisplayId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for DisplayId {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse::<DisplayIdImpl>().map(Self)+ }+}++mod serde_display_id {+ use serde::{Deserialize, Deserializer, Serializer};++ use crate::platform::DisplayIdImpl;++ pub fn serialize<S>(this: &DisplayIdImpl, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(&this.to_string())+ }++ pub fn deserialize<'de, D>(deserializer: D) -> Result<DisplayIdImpl, D::Error>+ where+ D: Deserializer<'de>,+ {+ let s = String::deserialize(deserializer)?;+ s.parse::<DisplayIdImpl>().map_err(serde::de::Error::custom)+ }+}++#[derive(Clone, Copy)]+pub struct Window(WindowImpl);++impl Window {+ pub fn list() -> Vec<Self> {+ WindowImpl::list().into_iter().map(Self).collect()+ }++ pub fn list_containing_cursor() -> Vec<Self> {+ WindowImpl::list_containing_cursor()+ .into_iter()+ .map(Self)+ .collect()+ }++ pub fn get_topmost_at_cursor() -> Option<Self> {+ WindowImpl::get_topmost_at_cursor().map(Self)+ }++ pub fn id(&self) -> WindowId {+ WindowId(self.0.id())+ }++ pub fn bounds(&self) -> Option<LogicalBounds> {+ self.0.bounds()+ }++ pub fn owner_name(&self) -> Option<String> {+ self.0.owner_name()+ }++ pub fn app_icon(&self) -> Option<Vec<u8>> {+ self.0.app_icon()+ }++ pub fn raw_handle(&self) -> &WindowImpl {+ &self.0+ }+}++#[derive(Serialize, Deserialize, Type, Clone, PartialEq)]+pub struct WindowId(+ #[serde(with = "serde_window_id")]+ #[specta(type = String)]+ WindowIdImpl,+);++impl std::fmt::Display for WindowId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for WindowId {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse::<WindowIdImpl>().map(Self)+ }+}++mod serde_window_id {+ use serde::{Deserialize, Deserializer, Serializer};++ use crate::WindowIdImpl;++ pub fn serialize<S>(this: &WindowIdImpl, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(&this.to_string())+ }++ pub fn deserialize<'de, D>(deserializer: D) -> Result<WindowIdImpl, D::Error>+ where+ D: Deserializer<'de>,+ {+ let s = String::deserialize(deserializer)?;+ s.parse::<WindowIdImpl>().map_err(serde::de::Error::custom)+ }}diff --git a/crates/displays/src/main.rs b/crates/displays/src/main.rsindex e7a11a969..1d04899e2 100644--- a/crates/displays/src/main.rs+++ b/crates/displays/src/main.rs@@ -1,3 +1,132 @@+use std::time::Duration;+fn main() {- println!("Hello, world!");+ // Test display functionality+ println!("=== Display Information ===");+ for (index, display) in cap_displays::Display::list().iter().enumerate() {+ println!("Display {}: {}", index + 1, display.name());+ println!(" ID: {}", display.id());++ let logical_size = display.raw_handle().logical_size();+ let physical_size = display.physical_size();+ let refresh_rate = display.refresh_rate();++ println!(+ " Logical Resolution: {}x{}",+ logical_size.width(),+ logical_size.height()+ );+ println!(+ " Physical Resolution: {}x{}",+ physical_size.width(),+ physical_size.height()+ );++ if refresh_rate > 0.0 {+ println!(" Refresh Rate: {} Hz", refresh_rate);+ } else {+ println!(" Refresh Rate: Unknown");+ }++ // Check if this is the main display+ let main_display_id = cap_displays::Display::list().get(0).map(|d| d.id());++ if let Some(main_id) = main_display_id {+ if display.id() == main_id {+ println!(" Type: Primary Display");+ } else {+ println!(" Type: Secondary Display");+ }+ } else {+ println!(" Type: Unknown");+ }++ println!();+ }++ if let Some(cursor_display) = cap_displays::Display::get_containing_cursor() {+ println!("🖱️ Cursor is currently on: {}", cursor_display.name());+ println!();+ }++ // Test window functionality+ println!("=== Windows Under Cursor ===");+ let windows = cap_displays::Window::list_containing_cursor();++ if windows.is_empty() {+ println!("No windows found under cursor");+ } else {+ println!("Found {} window(s) under cursor:", windows.len());+ for (index, window) in windows.iter().take(5).enumerate() {+ // Limit to first 5 windows+ println!("\nWindow {}: {}", index + 1, window.id());++ if let Some(bounds) = window.bounds() {+ println!(+ " Bounds: {}x{} at ({}, {})",+ bounds.size().width(),+ bounds.size().height(),+ bounds.position().x(),+ bounds.position().y()+ );+ }++ if let Some(owner) = window.owner_name() {+ println!(" Application: {}", owner);+ } else {+ println!(" Application: Unknown");+ }++ // Test icon functionality+ match window.app_icon() {+ Some(icon_data) => {+ println!(" Icon (Standard): {} bytes", icon_data.len());+ println!(" Format: PNG (Raw bytes)");+ println!(" Size: {} bytes", icon_data.len());+ }+ None => println!(" Icon (Standard): Not available"),+ }+ }+ }++ println!("\n=== Topmost Window Icon Test ===");+ if let Some(topmost) = cap_displays::Window::get_topmost_at_cursor() {+ if let Some(owner) = topmost.owner_name() {+ println!("Testing icon extraction for: {}", owner);++ match topmost.app_icon() {+ Some(icon_data) => {+ println!(" ✅ Icon found: {} bytes", icon_data.len());+ println!(" Format: PNG (Raw bytes)");+ println!(" Size: {} bytes", icon_data.len());+ }+ None => println!(" ❌ No icon found"),+ }+ }+ }++ println!("\n=== Live Monitoring (Press Ctrl+C to exit) ===");+ println!("Monitoring window levels under cursor...\n");++ loop {+ let mut relevant_windows = cap_displays::WindowImpl::list_containing_cursor()+ .into_iter()+ .filter_map(|window| {+ let level = window.level()?;+ level.lt(&5).then_some((window, level))+ })+ .collect::<Vec<_>>();++ relevant_windows.sort_by(|a, b| b.1.cmp(&a.1));++ // Print current topmost window info+ if let Some((topmost_window, level)) = relevant_windows.first() {+ if let Some(owner) = topmost_window.owner_name() {+ print!("\rTopmost: {} (level: {}) ", owner, level);+ std::io::Write::flush(&mut std::io::stdout()).unwrap();+ }+ }++ std::thread::sleep(Duration::from_millis(100));+ }}diff --git a/crates/displays/src/platform/macos.rs b/crates/displays/src/platform/macos.rsindex 4d6d62b65..324036ef1 100644--- a/crates/displays/src/platform/macos.rs+++ b/crates/displays/src/platform/macos.rs@@ -1,4 +1,15 @@-use core_graphics::display::CGDisplay;+use std::{ffi::c_void, str::FromStr};++use core_foundation::{base::FromVoid, number::CFNumber, string::CFString};+use core_graphics::{+ display::{+ CFDictionary, CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode,+ CGRect, kCGWindowListOptionIncludingWindow,+ },+ window::{CGWindowID, kCGWindowBounds, kCGWindowLayer, kCGWindowNumber, kCGWindowOwnerName},+};++use crate::bounds::{LogicalBounds, LogicalPosition, LogicalSize, PhysicalSize};#[derive(Clone, Copy)]pub struct DisplayImpl(CGDisplay);@@ -19,4 +30,370 @@ impl DisplayImpl {pub fn inner(&self) -> CGDisplay {self.0}++ pub fn raw_id(&self) -> DisplayIdImpl {+ DisplayIdImpl(self.0.id)+ }++ pub fn from_id(id: String) -> Option<Self> {+ let parsed_id = id.parse::<u32>().ok()?;+ Self::list().into_iter().find(|d| d.0.id == parsed_id)+ }++ pub fn logical_size(&self) -> LogicalSize {+ let rect = unsafe { CGDisplayBounds(self.0.id) };++ LogicalSize {+ width: rect.size.width,+ height: rect.size.height,+ }+ }++ pub fn logical_position(&self) -> LogicalPosition {+ let rect = unsafe { CGDisplayBounds(self.0.id) };++ LogicalPosition {+ x: rect.origin.x,+ y: rect.origin.y,+ }+ }++ pub fn get_containing_cursor() -> Option<Self> {+ let cursor = get_cursor_position()?;++ Self::list().into_iter().find(|display| {+ let bounds = LogicalBounds {+ position: display.logical_position(),+ size: display.logical_size(),+ };+ bounds.contains_point(cursor)+ })+ }++ pub fn physical_size(&self) -> PhysicalSize {+ let mode = unsafe { CGDisplayCopyDisplayMode(self.0.id) };+ if mode.is_null() {+ return PhysicalSize {+ width: 0.0,+ height: 0.0,+ };+ }++ let width = unsafe { core_graphics::display::CGDisplayModeGetWidth(mode) };+ let height = unsafe { core_graphics::display::CGDisplayModeGetHeight(mode) };++ unsafe { core_graphics::display::CGDisplayModeRelease(mode) };++ PhysicalSize {+ width: width as f64,+ height: height as f64,+ }+ }++ pub fn refresh_rate(&self) -> f64 {+ let mode = unsafe { CGDisplayCopyDisplayMode(self.0.id) };+ if mode.is_null() {+ return 0.0;+ }++ let refresh_rate = unsafe { core_graphics::display::CGDisplayModeGetRefreshRate(mode) };++ unsafe { core_graphics::display::CGDisplayModeRelease(mode) };++ refresh_rate+ }++ pub fn name(&self) -> String {+ use cocoa::appkit::NSScreen;+ use cocoa::base::{id, nil};+ use cocoa::foundation::{NSArray, NSDictionary, NSString};+ use objc::{msg_send, *};+ use std::ffi::CStr;++ unsafe {+ let screens = NSScreen::screens(nil);+ let screen_count = NSArray::count(screens);++ for i in 0..screen_count {+ let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);++ let device_description = NSScreen::deviceDescription(screen);+ let num = NSDictionary::valueForKey_(+ device_description,+ NSString::alloc(nil).init_str("NSScreenNumber"),+ ) as id;++ let num_value: u32 = msg_send![num, unsignedIntValue];++ if num_value == self.0.id {+ let name: id = msg_send![screen, localizedName];+ if !name.is_null() {+ let name = CStr::from_ptr(NSString::UTF8String(name))+ .to_string_lossy()+ .to_string();+ return name;+ }+ }+ }++ // Fallback to generic name with display ID+ format!("Display {}", self.0.id)+ }+ }+}++fn get_cursor_position() -> Option<LogicalPosition> {+ let event_source = core_graphics::event_source::CGEventSource::new(+ core_graphics::event_source::CGEventSourceStateID::Private,+ )+ .ok()?;++ let event = core_graphics::event::CGEvent::new(event_source).ok()?;+ let location = event.location();++ Some(LogicalPosition {+ x: location.x,+ y: location.y,+ })+}++#[derive(Clone, Copy)]+pub struct WindowImpl(CGWindowID);++impl WindowImpl {+ pub fn list() -> Vec<Self> {+ use core_graphics::window::{+ kCGNullWindowID, kCGWindowListExcludeDesktopElements, kCGWindowListOptionOnScreenOnly,+ };++ let windows = core_graphics::window::copy_window_info(+ kCGWindowListExcludeDesktopElements | kCGWindowListOptionOnScreenOnly,+ kCGNullWindowID,+ );++ let Some(windows) = windows else {+ return vec![];+ };++ let mut ret = vec![];++ for window in windows.iter() {+ let window_dict =+ unsafe { CFDictionary::<CFString, *const c_void>::from_void(*window) };++ let Some(number) = (unsafe {+ window_dict+ .find(kCGWindowNumber)+ .and_then(|v| CFNumber::from_void(*v).to_i64().map(|v| v as u32))+ }) else {+ continue;+ };++ ret.push(WindowImpl(number));+ }++ ret+ }++ pub fn list_containing_cursor() -> Vec<Self> {+ let Some(cursor) = get_cursor_position() else {+ return vec![];+ };++ Self::list()+ .into_iter()+ .filter_map(|window| {+ let bounds = window.bounds()?;+ bounds.contains_point(cursor).then_some(window)+ })+ .collect()+ }++ pub fn get_topmost_at_cursor() -> Option<Self> {+ let mut windows_with_level = Self::list_containing_cursor()+ .into_iter()+ .filter_map(|window| {+ let level = window.level()?;+ if level > 5 {+ return None;+ }+ Some((window, level))+ })+ .collect::<Vec<_>>();++ windows_with_level.sort_by(|a, b| b.1.cmp(&a.1));++ windows_with_level.first().map(|(window, _)| *window)+ }++ pub fn id(&self) -> WindowIdImpl {+ WindowIdImpl(self.0)+ }++ pub fn level(&self) -> Option<i32> {+ let windows =+ core_graphics::window::copy_window_info(kCGWindowListOptionIncludingWindow, self.0)?;++ let window_dict =+ unsafe { CFDictionary::<CFString, *const c_void>::from_void(*windows.get(0)?) };++ unsafe {+ window_dict+ .find(kCGWindowLayer)+ .and_then(|v| CFNumber::from_void(*v).to_i32())+ }+ }++ pub fn owner_name(&self) -> Option<String> {+ let windows =+ core_graphics::window::copy_window_info(kCGWindowListOptionIncludingWindow, self.0)?;++ let window_dict =+ unsafe { CFDictionary::<CFString, *const c_void>::from_void(*windows.get(0)?) };++ unsafe {+ window_dict+ .find(kCGWindowOwnerName)+ .map(|v| CFString::from_void(*v).to_string())+ }+ }++ pub fn bounds(&self) -> Option<LogicalBounds> {+ let windows =+ core_graphics::window::copy_window_info(kCGWindowListOptionIncludingWindow, self.0)?;++ let window_dict =+ unsafe { CFDictionary::<CFString, *const c_void>::from_void(*windows.get(0)?) };++ unsafe {+ window_dict+ .find(kCGWindowBounds)+ .and_then(|v| CGRect::from_dict_representation(&*CFDictionary::from_void(*v)))+ }+ .map(|rect| LogicalBounds {+ position: LogicalPosition {+ x: rect.origin.x,+ y: rect.origin.y,+ },+ size: LogicalSize {+ width: rect.size.width,+ height: rect.size.height,+ },+ })+ }++ pub fn app_icon(&self) -> Option<Vec<u8>> {+ use cocoa::base::{id, nil};+ use cocoa::foundation::{NSArray, NSAutoreleasePool, NSString};+ use objc::{class, msg_send, sel, sel_impl};++ let owner_name = self.owner_name()?;++ unsafe {+ let pool = NSAutoreleasePool::new(nil);++ let workspace_class = class!(NSWorkspace);+ let workspace: id = msg_send![workspace_class, sharedWorkspace];+ let running_apps: id = msg_send![workspace, runningApplications];+ let app_count = NSArray::count(running_apps);++ let result = (0..app_count).find_map(|i| {+ let app: id = running_apps.objectAtIndex(i);+ let localized_name: id = msg_send![app, localizedName];++ if localized_name.is_null() {+ return None;+ }++ let name_str = NSString::UTF8String(localized_name);+ if name_str.is_null() {+ return None;+ }++ let name = std::ffi::CStr::from_ptr(name_str)+ .to_string_lossy()+ .to_string();++ if name != owner_name {+ return None;+ }++ let icon: id = msg_send![app, icon];+ if icon.is_null() {+ return None;+ }++ let tiff_data: id = msg_send![icon, TIFFRepresentation];+ if tiff_data.is_null() {+ return None;+ }++ let bitmap_rep_class = class!(NSBitmapImageRep);+ let bitmap_rep: id = msg_send![bitmap_rep_class, imageRepWithData: tiff_data];+ if bitmap_rep.is_null() {+ return None;+ }++ let png_data: id = msg_send![+ bitmap_rep,+ representationUsingType: 4u64 // NSBitmapImageFileTypePNG+ properties: nil+ ];+ if png_data.is_null() {+ return None;+ }++ let length: usize = msg_send![png_data, length];+ let bytes_ptr: *const u8 = msg_send![png_data, bytes];++ if bytes_ptr.is_null() || length == 0 {+ return None;+ }++ let bytes = std::slice::from_raw_parts(bytes_ptr, length);+ Some(bytes.to_vec())+ });++ pool.drain();+ result+ }+ }+}++#[derive(Clone, PartialEq, Debug)]+pub struct DisplayIdImpl(CGDirectDisplayID);++impl std::fmt::Display for DisplayIdImpl {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for DisplayIdImpl {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse()+ .map(Self)+ .map_err(|_| "Invalid display ID".to_string())+ }+}++#[derive(Clone, PartialEq, Debug)]+pub struct WindowIdImpl(CGWindowID);++impl std::fmt::Display for WindowIdImpl {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for WindowIdImpl {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse()+ .map(Self)+ .map_err(|_| "Invalid window ID".to_string())+ }}diff --git a/crates/displays/src/platform/mod.rs b/crates/displays/src/platform/mod.rsindex c257c96e5..bfe03249b 100644--- a/crates/displays/src/platform/mod.rs+++ b/crates/displays/src/platform/mod.rs@@ -1,9 +1,9 @@#[cfg(target_os = "macos")]mod macos;#[cfg(target_os = "macos")]-pub use macos::DisplayImpl;+pub use macos::*;#[cfg(windows)]mod win;#[cfg(windows)]-pub use win::DisplayImpl;+pub use win::*;diff --git a/crates/displays/src/platform/win.rs b/crates/displays/src/platform/win.rsindex db78e9959..a09ea60a3 100644--- a/crates/displays/src/platform/win.rs+++ b/crates/displays/src/platform/win.rs@@ -1,15 +1,79 @@+use std::{mem, str::FromStr};+use windows::{Win32::{- Foundation::{FALSE, LPARAM, RECT},- Graphics::Gdi::{EnumDisplayMonitors, GetMonitorInfoW, HDC, HMONITOR, MONITORINFOEXW},+ Devices::Display::{+ DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME,+ DISPLAYCONFIG_DEVICE_INFO_HEADER, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO,+ DISPLAYCONFIG_SOURCE_DEVICE_NAME, DISPLAYCONFIG_TARGET_DEVICE_NAME,+ DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS, DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY,+ DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS,+ QueryDisplayConfig,+ },+ Foundation::{CloseHandle, HWND, LPARAM, POINT, RECT, TRUE, WIN32_ERROR, WPARAM},+ Graphics::Gdi::{+ BI_RGB, BITMAP, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleBitmap,+ CreateCompatibleDC, CreateSolidBrush, DEVMODEW, DIB_RGB_COLORS, DeleteDC, DeleteObject,+ ENUM_CURRENT_SETTINGS, EnumDisplayMonitors, EnumDisplaySettingsW, FillRect, GetDC,+ GetDIBits, GetMonitorInfoW, GetObjectA, HBRUSH, HDC, HGDIOBJ, HMONITOR,+ MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITORINFOEXW, MonitorFromPoint,+ ReleaseDC, SelectObject,+ },+ Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW},+ System::{+ Registry::{+ HKEY, HKEY_LOCAL_MACHINE, KEY_READ, REG_BINARY, REG_SZ, RegCloseKey, RegEnumKeyExW,+ RegOpenKeyExW, RegQueryValueExW,+ },+ Threading::{+ GetCurrentProcessId, OpenProcess, PROCESS_NAME_FORMAT,+ PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,+ },+ },+ UI::{+ HiDpi::GetDpiForWindow,+ Shell::ExtractIconExW,+ WindowsAndMessaging::{+ DI_FLAGS, DestroyIcon, DrawIconEx, EnumWindows, GCLP_HICON, GW_HWNDNEXT,+ GWL_EXSTYLE, GetClassLongPtrW, GetClassNameW, GetCursorPos, GetIconInfo,+ GetLayeredWindowAttributes, GetWindow, GetWindowLongW, GetWindowRect,+ GetWindowThreadProcessId, HICON, ICONINFO, IsIconic, IsWindowVisible, SendMessageW,+ WM_GETICON, WS_EX_LAYERED, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WindowFromPoint,+ },+ },},- core::BOOL,+ core::{BOOL, PCWSTR, PWSTR},};+use crate::bounds::{LogicalBounds, LogicalPosition, LogicalSize, PhysicalSize};+#[derive(Clone, Copy)]pub struct DisplayImpl(HMONITOR);impl DisplayImpl {+ pub fn primary() -> Self {+ // Find the primary monitor by checking the MONITORINFOF_PRIMARY flag+ const MONITORINFOF_PRIMARY: u32 = 1u32;++ for display in Self::list() {+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ if GetMonitorInfoW(display.0, &mut info as *mut _ as *mut _).as_bool() {+ if (info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY) != 0 {+ return display;+ }+ }+ }+ }++ // Fallback to the old method if no primary monitor is found+ let point = POINT { x: 0, y: 0 };+ let monitor = unsafe { MonitorFromPoint(point, MONITOR_DEFAULTTONEAREST) };+ Self(monitor)+ }+pub fn list() -> Vec<Self> {unsafe extern "system" fn monitor_enum_proc(hmonitor: HMONITOR,@@ -17,13 +81,9 @@ impl DisplayImpl {_lprc_clip: *mut RECT,lparam: LPARAM,) -> BOOL {- unsafe {- let list = &mut *(lparam.0 as *mut Vec<DisplayImpl>);-- list.push(DisplayImpl(hmonitor));-- FALSE- }+ let list = unsafe { &mut *(lparam.0 as *mut Vec<DisplayImpl>) };+ list.push(DisplayImpl(hmonitor));+ TRUE}let mut list = vec![];@@ -32,25 +92,1286 @@ impl DisplayImpl {None,None,Some(monitor_enum_proc),- LPARAM(core::ptr::addr_of_mut!(list) as isize),+ LPARAM(std::ptr::addr_of_mut!(list) as isize),);- };+ }list}- pub fn bounds(&self) -> Option<RECT> {- let mut minfo = MONITORINFOEXW::default();+ pub fn inner(&self) -> HMONITOR {+ self.0+ }++ pub fn raw_id(&self) -> DisplayIdImpl {+ DisplayIdImpl(self.0.0 as u64)+ }++ pub fn from_id(id: String) -> Option<Self> {+ let parsed_id = id.parse::<u64>().ok()?;+ Self::list().into_iter().find(|d| d.raw_id().0 == parsed_id)+ }++ pub fn logical_size(&self) -> LogicalSize {+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ if GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ let rect = info.monitorInfo.rcMonitor;+ LogicalSize {+ width: (rect.right - rect.left) as f64,+ height: (rect.bottom - rect.top) as f64,+ }+ } else {+ LogicalSize {+ width: 0.0,+ height: 0.0,+ }+ }+ }+ }++ pub fn logical_position(&self) -> LogicalPosition {+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ if GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ let rect = info.monitorInfo.rcMonitor;+ LogicalPosition {+ x: rect.left as f64,+ y: rect.top as f64,+ }+ } else {+ LogicalPosition { x: 0.0, y: 0.0 }+ }+ }+ }++ pub fn get_containing_cursor() -> Option<Self> {+ let cursor = get_cursor_position()?;+ let point = POINT {+ x: cursor.x() as i32,+ y: cursor.y() as i32,+ };++ let monitor = unsafe { MonitorFromPoint(point, MONITOR_DEFAULTTONULL) };+ if monitor.0 as usize != 0 {+ Some(Self(monitor))+ } else {+ None+ }+ }++ pub fn physical_size(&self) -> PhysicalSize {+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;- minfo.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;unsafe {- GetMonitorInfoW(self.0, &mut minfo as *mut MONITORINFOEXW as *mut _)+ if GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ let device_name = info.szDevice;+ let mut devmode = DEVMODEW::default();+ devmode.dmSize = mem::size_of::<DEVMODEW>() as u16;++ if EnumDisplaySettingsW(+ PCWSTR(device_name.as_ptr()),+ ENUM_CURRENT_SETTINGS,+ &mut devmode,+ ).as_bool()- .then_some(minfo.monitorInfo.rcMonitor)+ {+ PhysicalSize {+ width: devmode.dmPelsWidth as f64,+ height: devmode.dmPelsHeight as f64,+ }+ } else {+ PhysicalSize {+ width: 0.0,+ height: 0.0,+ }+ }+ } else {+ PhysicalSize {+ width: 0.0,+ height: 0.0,+ }+ }+ }+ }++ pub fn refresh_rate(&self) -> f64 {+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ if GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ let device_name = info.szDevice;+ let mut devmode = DEVMODEW::default();+ devmode.dmSize = mem::size_of::<DEVMODEW>() as u16;++ if EnumDisplaySettingsW(+ PCWSTR(device_name.as_ptr()),+ ENUM_CURRENT_SETTINGS,+ &mut devmode,+ )+ .as_bool()+ {+ devmode.dmDisplayFrequency as f64+ } else {+ 0.0+ }+ } else {+ 0.0+ }+ }+ }++ pub fn name(&self) -> String {+ // First try the modern DisplayConfig API for friendly names+ if let Some(friendly_name) = self.get_friendly_name_from_displayconfig() {+ return friendly_name;+ }++ // Try WMI query for better localized names+ if let Some(wmi_name) = self.get_friendly_name_from_wmi() {+ return wmi_name;+ }++ // Fallback to the existing registry method+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ if GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ // Convert the device name from wide string to String+ let device_name = &info.szDevice;+ let null_pos = device_name+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(device_name.len());+ let device_name_str = String::from_utf16_lossy(&device_name[..null_pos]);++ // Try to get friendly name from registry+ if let Some(friendly_name) = self.get_friendly_name_from_registry(&device_name_str)+ {+ return friendly_name;+ }++ // Try EDID-based name lookup as final fallback before device name+ if let Some(edid_name) = self.get_friendly_name_from_edid(&device_name_str) {+ return edid_name;+ }++ // Final fallback to device name+ device_name_str+ } else {+ format!("Unknown Display")+ }+ }+ }++ fn get_friendly_name_from_displayconfig(&self) -> Option<String> {+ unsafe {+ // Get the device name first+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ if !GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ return None;+ }++ let device_name = &info.szDevice;+ let null_pos = device_name+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(device_name.len());+ let device_name_str = String::from_utf16_lossy(&device_name[..null_pos]);++ // Get display configuration+ let mut num_paths = 0u32;+ let mut num_modes = 0u32;++ if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut num_paths, &mut num_modes)+ != WIN32_ERROR(0)+ {+ return None;+ }++ let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); num_paths as usize];+ let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); num_modes as usize];++ if QueryDisplayConfig(+ QDC_ONLY_ACTIVE_PATHS,+ &mut num_paths,+ paths.as_mut_ptr(),+ &mut num_modes,+ modes.as_mut_ptr(),+ None,+ ) != WIN32_ERROR(0)+ {+ return None;+ }++ // Find the matching path for our monitor+ for path in &paths {+ // Get source device name to match with our monitor+ let mut source_name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {+ header: DISPLAYCONFIG_DEVICE_INFO_HEADER {+ r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,+ size: mem::size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,+ adapterId: path.sourceInfo.adapterId,+ id: path.sourceInfo.id,+ },+ viewGdiDeviceName: [0; 32],+ };++ if DisplayConfigGetDeviceInfo(&mut source_name.header as *mut _ as *mut _) != 0 {+ continue;+ }++ let source_device_name = String::from_utf16_lossy(&source_name.viewGdiDeviceName);+ let source_null_pos = source_device_name+ .chars()+ .position(|c| c == '\0')+ .unwrap_or(source_device_name.len());+ let source_trimmed = &source_device_name[..source_null_pos];++ // Check if this matches our monitor+ if source_trimmed == device_name_str {+ // Get the target (monitor) friendly name+ let mut target_name = DISPLAYCONFIG_TARGET_DEVICE_NAME {+ header: DISPLAYCONFIG_DEVICE_INFO_HEADER {+ r#type: DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME,+ size: mem::size_of::<DISPLAYCONFIG_TARGET_DEVICE_NAME>() as u32,+ adapterId: path.sourceInfo.adapterId,+ id: path.targetInfo.id,+ },+ flags: DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS::default(),+ outputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY::default(),+ edidManufactureId: 0,+ edidProductCodeId: 0,+ connectorInstance: 0,+ monitorFriendlyDeviceName: [0; 64],+ monitorDevicePath: [0; 128],+ };++ if DisplayConfigGetDeviceInfo(&mut target_name.header as *mut _ as *mut _) == 0+ {+ let friendly_name =+ String::from_utf16_lossy(&target_name.monitorFriendlyDeviceName);+ let null_pos = friendly_name+ .chars()+ .position(|c| c == '\0')+ .unwrap_or(friendly_name.len());+ let trimmed_name = friendly_name[..null_pos].trim();++ if !trimmed_name.is_empty() && trimmed_name != "Generic PnP Monitor" {+ return Some(trimmed_name.to_string());+ }+ }+ }+ }}++ None}- pub fn id(&self) -> u32 {- self.0.0 as u32+ fn get_friendly_name_from_wmi(&self) -> Option<String> {+ unsafe {+ // Get the device name first for matching+ let mut info = MONITORINFOEXW::default();+ info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32;++ if !GetMonitorInfoW(self.0, &mut info as *mut _ as *mut _).as_bool() {+ return None;+ }++ let device_name = &info.szDevice;+ let null_pos = device_name+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(device_name.len());+ let device_name_str = String::from_utf16_lossy(&device_name[..null_pos]);++ // Try alternative registry paths for monitor information+ let alt_registry_paths = [+ format!(+ "SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers\\Configuration\\{}",+ device_name_str.replace("\\\\.\\", "")+ ),+ format!(+ "SYSTEM\\CurrentControlSet\\Hardware Profiles\\Current\\System\\CurrentControlSet\\Control\\VIDEO\\{}",+ device_name_str.replace("\\\\.\\DISPLAY", "")+ ),+ ];++ for registry_path in &alt_registry_paths {+ let registry_path_wide: Vec<u16> = registry_path+ .encode_utf16()+ .chain(std::iter::once(0))+ .collect();++ let mut key: HKEY = HKEY::default();+ if RegOpenKeyExW(+ HKEY_LOCAL_MACHINE,+ PCWSTR(registry_path_wide.as_ptr()),+ Some(0),+ KEY_READ,+ &mut key,+ )+ .is_ok()+ {+ // Try to get monitor description from alternative locations+ let value_names = ["Monitor_Name", "Description", "FriendlyName"];++ for value_name in &value_names {+ let value_name_wide = format!("{}\0", value_name)+ .encode_utf16()+ .collect::<Vec<u16>>();+ let mut buffer = [0u16; 512];+ let mut buffer_size = (buffer.len() * 2) as u32;+ let mut value_type = REG_SZ;++ if RegQueryValueExW(+ key,+ PCWSTR(value_name_wide.as_ptr()),+ None,+ Some(&mut value_type),+ Some(buffer.as_mut_ptr() as *mut u8),+ Some(&mut buffer_size),+ )+ .is_ok()+ {+ let null_pos =+ buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());+ let desc = String::from_utf16_lossy(&buffer[..null_pos]);+ let cleaned_name = desc.trim().to_string();++ if !cleaned_name.is_empty() && cleaned_name != "Default Monitor" {+ let _ = RegCloseKey(key);+ return Some(cleaned_name);+ }+ }+ }+ let _ = RegCloseKey(key);+ }+ }+ }+ None+ }++ fn get_friendly_name_from_registry(&self, device_name: &str) -> Option<String> {+ unsafe {+ // Try multiple registry paths for better name resolution+ let registry_paths = [+ format!(+ "SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\{}",+ device_name.replace("\\\\.\\", "")+ ),+ format!(+ "SYSTEM\\CurrentControlSet\\Control\\Class\\{{4d36e96e-e325-11ce-bfc1-08002be10318}}"+ ),+ ];++ for registry_path in ®istry_paths {+ let registry_path_wide: Vec<u16> = registry_path+ .encode_utf16()+ .chain(std::iter::once(0))+ .collect();++ let mut key: HKEY = HKEY::default();+ if RegOpenKeyExW(+ HKEY_LOCAL_MACHINE,+ PCWSTR(registry_path_wide.as_ptr()),+ Some(0),+ KEY_READ,+ &mut key,+ )+ .is_ok()+ {+ // Try multiple value names for better localization+ let value_names = ["FriendlyName", "DeviceDesc", "DriverDesc"];++ for value_name in &value_names {+ let value_name_wide = format!("{}\0", value_name)+ .encode_utf16()+ .collect::<Vec<u16>>();+ let mut buffer = [0u16; 512];+ let mut buffer_size = (buffer.len() * 2) as u32;+ let mut value_type = REG_SZ;++ if RegQueryValueExW(+ key,+ PCWSTR(value_name_wide.as_ptr()),+ None,+ Some(&mut value_type),+ Some(buffer.as_mut_ptr() as *mut u8),+ Some(&mut buffer_size),+ )+ .is_ok()+ {+ let null_pos =+ buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());+ let desc = String::from_utf16_lossy(&buffer[..null_pos]);++ // Clean up the description+ let cleaned_name = if let Some(semicolon_pos) = desc.rfind(';') {+ desc[semicolon_pos + 1..].trim().to_string()+ } else {+ desc.trim().to_string()+ };++ if !cleaned_name.is_empty()+ && !cleaned_name.contains("PCI\\VEN_")+ && cleaned_name != "Generic PnP Monitor"+ {+ let _ = RegCloseKey(key);+ return Some(cleaned_name);+ }+ }+ }+ let _ = RegCloseKey(key);+ }+ }+ }+ None+ }++ fn get_friendly_name_from_edid(&self, device_name: &str) -> Option<String> {+ unsafe {+ // Registry path for EDID data+ let edid_path = format!(+ "SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\{}",+ device_name.replace("\\\\.\\", "")+ );+ let edid_path_wide: Vec<u16> =+ edid_path.encode_utf16().chain(std::iter::once(0)).collect();++ let mut key: HKEY = HKEY::default();+ if RegOpenKeyExW(+ HKEY_LOCAL_MACHINE,+ PCWSTR(edid_path_wide.as_ptr()),+ Some(0),+ KEY_READ,+ &mut key,+ )+ .is_ok()+ {+ // Enumerate subkeys to find device instances+ let mut index = 0;+ loop {+ let mut subkey_name = [0u16; 256];+ let mut subkey_size = subkey_name.len() as u32;++ if RegEnumKeyExW(+ key,+ index,+ Some(PWSTR(subkey_name.as_mut_ptr())),+ &mut subkey_size,+ None,+ Some(PWSTR::null()),+ None,+ None,+ )+ .is_err()+ {+ break;+ }++ // Open device parameters subkey+ let subkey_str = String::from_utf16_lossy(&subkey_name[..subkey_size as usize]);+ let params_path = format!("{}\\Device Parameters", subkey_str);+ let params_path_wide: Vec<u16> = params_path+ .encode_utf16()+ .chain(std::iter::once(0))+ .collect();++ let mut params_key: HKEY = HKEY::default();+ if RegOpenKeyExW(+ key,+ PCWSTR(params_path_wide.as_ptr()),+ Some(0),+ KEY_READ,+ &mut params_key,+ )+ .is_ok()+ {+ // Read EDID data+ let edid_value = "EDID\0".encode_utf16().collect::<Vec<u16>>();+ let mut edid_buffer = [0u8; 256];+ let mut edid_size = edid_buffer.len() as u32;+ let mut value_type = REG_BINARY;++ if RegQueryValueExW(+ params_key,+ PCWSTR(edid_value.as_ptr()),+ None,+ Some(&mut value_type),+ Some(edid_buffer.as_mut_ptr()),+ Some(&mut edid_size),+ )+ .is_ok()+ && edid_size >= 128+ {+ // Parse EDID for monitor name (descriptor blocks start at offset 54)+ for i in (54..126).step_by(18) {+ if i + 18 > edid_buffer.len() {+ break;+ }+ if edid_buffer[i] == 0+ && edid_buffer[i + 1] == 0+ && edid_buffer[i + 2] == 0+ && edid_buffer[i + 3] == 0xFC+ {+ // Monitor name descriptor found+ if i + 18 <= edid_buffer.len() {+ let name_bytes = &edid_buffer[i + 5..i + 18];+ let name_str = String::from_utf8_lossy(name_bytes);+ let name =+ name_str.trim_end_matches('\0').trim().to_string();++ if !name.is_empty() {+ let _ = RegCloseKey(params_key);+ let _ = RegCloseKey(key);+ return Some(name);+ }+ }+ }+ }+ }+ let _ = RegCloseKey(params_key);+ }+ index += 1;+ }+ let _ = RegCloseKey(key);+ }+ }+ None+ }+}++fn get_cursor_position() -> Option<LogicalPosition> {+ let mut point = POINT { x: 0, y: 0 };+ unsafe {+ if GetCursorPos(&mut point).is_ok() {+ Some(LogicalPosition {+ x: point.x as f64,+ y: point.y as f64,+ })+ } else {+ None+ }+ }+}++#[derive(Clone, Copy)]+pub struct WindowImpl(HWND);++impl WindowImpl {+ pub fn list() -> Vec<Self> {+ struct EnumContext {+ list: Vec<WindowImpl>,+ current_process_id: u32,+ }++ unsafe extern "system" fn enum_windows_proc(hwnd: HWND, lparam: LPARAM) -> BOOL {+ let context = unsafe { &mut *(lparam.0 as *mut EnumContext) };++ if is_window_valid_for_enumeration(hwnd, context.current_process_id) {+ context.list.push(WindowImpl(hwnd));+ }++ TRUE+ }++ let mut context = EnumContext {+ list: vec![],+ current_process_id: unsafe { GetCurrentProcessId() },+ };++ unsafe {+ let _ = EnumWindows(+ Some(enum_windows_proc),+ LPARAM(std::ptr::addr_of_mut!(context) as isize),+ );+ }++ context.list+ }++ pub fn get_topmost_at_cursor() -> Option<Self> {+ let cursor = get_cursor_position()?;+ let point = POINT {+ x: cursor.x() as i32,+ y: cursor.y() as i32,+ };++ unsafe {+ // Use WindowFromPoint first as a quick check+ let hwnd_at_point = WindowFromPoint(point);+ if hwnd_at_point != HWND(std::ptr::null_mut()) {+ let current_process_id = GetCurrentProcessId();++ // Walk up the Z-order chain to find the topmost valid window+ let mut current_hwnd = hwnd_at_point;++ loop {+ // Check if this window is valid for our purposes+ if is_window_valid_for_topmost_selection(+ current_hwnd,+ current_process_id,+ point,+ ) {+ return Some(Self(current_hwnd));+ }++ // Move to the next window in Z-order (towards background)+ current_hwnd =+ GetWindow(current_hwnd, GW_HWNDNEXT).unwrap_or(HWND(std::ptr::null_mut()));+ if current_hwnd == HWND(std::ptr::null_mut()) {+ break;+ }++ // Check if this window still contains the point+ if !is_point_in_window(current_hwnd, point) {+ continue;+ }+ }+ }++ // Fallback to enumeration if WindowFromPoint fails+ Self::get_topmost_at_cursor_fallback(point)+ }+ }++ fn get_topmost_at_cursor_fallback(point: POINT) -> Option<Self> {+ struct HitTestData {+ pt: POINT,+ candidates: Vec<HWND>,+ current_process_id: u32,+ }++ unsafe extern "system" fn enum_windows_proc(hwnd: HWND, lparam: LPARAM) -> BOOL {+ let data = unsafe { &mut *(lparam.0 as *mut HitTestData) };++ if is_window_valid_for_topmost_selection(hwnd, data.current_process_id, data.pt) {+ data.candidates.push(hwnd);+ }++ TRUE+ }++ let mut data = HitTestData {+ pt: point,+ candidates: Vec::new(),+ current_process_id: unsafe { GetCurrentProcessId() },+ };++ unsafe {+ let _ = EnumWindows(+ Some(enum_windows_proc),+ LPARAM(std::ptr::addr_of_mut!(data) as isize),+ );++ // Sort candidates by Z-order (topmost first)+ data.candidates.sort_by(|&a, &b| {+ // Use GetWindowLong to check topmost status+ let a_topmost = (GetWindowLongW(a, GWL_EXSTYLE) & WS_EX_TOPMOST.0 as i32) != 0;+ let b_topmost = (GetWindowLongW(b, GWL_EXSTYLE) & WS_EX_TOPMOST.0 as i32) != 0;++ match (a_topmost, b_topmost) {+ (true, false) => std::cmp::Ordering::Less, // a is more topmost+ (false, true) => std::cmp::Ordering::Greater, // b is more topmost+ _ => std::cmp::Ordering::Equal, // Same topmost level+ }+ });++ data.candidates.first().map(|&hwnd| Self(hwnd))+ }+ }++ pub fn list_containing_cursor() -> Vec<Self> {+ let Some(cursor) = get_cursor_position() else {+ return vec![];+ };++ Self::list()+ .into_iter()+ .filter_map(|window| {+ let bounds = window.bounds()?;+ bounds.contains_point(cursor).then_some(window)+ })+ .collect()+ }++ pub fn id(&self) -> WindowIdImpl {+ WindowIdImpl(self.0.0 as u64)+ }++ pub fn level(&self) -> Option<i32> {+ unsafe {+ // Windows doesn't have the same level concept as macOS, but we can approximate+ // using extended window styles and z-order information+ let ex_style = GetWindowLongW(self.0, GWL_EXSTYLE);++ // Check if window has topmost style+ if (ex_style & WS_EX_TOPMOST.0 as i32) != 0 {+ Some(3) // Higher level for topmost windows+ } else {+ Some(0) // Normal level for regular windows+ }+ }+ }++ pub fn owner_name(&self) -> Option<String> {+ unsafe {+ let mut process_id = 0u32;+ GetWindowThreadProcessId(self.0, Some(&mut process_id));++ if process_id == 0 {+ return None;+ }++ let process_handle =+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process_id).ok()?;++ let mut buffer = [0u16; 1024];+ let mut buffer_size = buffer.len() as u32;++ let result = QueryFullProcessImageNameW(+ process_handle,+ PROCESS_NAME_FORMAT::default(),+ PWSTR(buffer.as_mut_ptr()),+ &mut buffer_size,+ );++ let _ = CloseHandle(process_handle);++ if result.is_ok() && buffer_size > 0 {+ let path_str = String::from_utf16_lossy(&buffer[..buffer_size as usize]);++ // Try to get the friendly name from version info first+ if let Some(friendly_name) = self.get_file_description(&path_str) {+ return Some(friendly_name);+ }++ // Fallback to file stem+ std::path::Path::new(&path_str)+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+ } else {+ None+ }+ }+ }++ fn get_file_description(&self, file_path: &str) -> Option<String> {+ unsafe {+ let wide_path: Vec<u16> = file_path.encode_utf16().chain(std::iter::once(0)).collect();++ let size = GetFileVersionInfoSizeW(PCWSTR(wide_path.as_ptr()), None);+ if size == 0 {+ return None;+ }++ let mut buffer = vec![0u8; size as usize];+ if !GetFileVersionInfoW(+ PCWSTR(wide_path.as_ptr()),+ Some(0),+ size,+ buffer.as_mut_ptr() as *mut _,+ )+ .is_ok()+ {+ return None;+ }++ let mut len = 0u32;+ let mut value_ptr: *mut u16 = std::ptr::null_mut();++ let query = "\\StringFileInfo\\040904B0\\FileDescription\0"+ .encode_utf16()+ .collect::<Vec<u16>>();++ if VerQueryValueW(+ buffer.as_ptr() as *const _,+ PCWSTR(query.as_ptr()),+ &mut value_ptr as *mut _ as *mut *mut _,+ &mut len,+ )+ .as_bool()+ && !value_ptr.is_null()+ && len > 0+ {+ let slice = std::slice::from_raw_parts(value_ptr, len as usize - 1);+ Some(String::from_utf16_lossy(slice))+ } else {+ None+ }+ }+ }++ pub fn app_icon(&self) -> Option<Vec<u8>> {+ unsafe {+ // Try multiple approaches to get the highest quality icon+ let mut best_result = None;+ let mut best_size = 0;++ // Method 1: Try to get the window's large icon first+ let large_icon = SendMessageW(+ self.0,+ WM_GETICON,+ Some(WPARAM(1usize)),+ Some(LPARAM(0isize)),+ ); // ICON_BIG = 1++ if large_icon.0 != 0 {+ if let Some(result) = self.hicon_to_png_bytes_high_res(HICON(large_icon.0 as _)) {+ best_result = Some(result.0);+ best_size = result.1;+ }+ }++ // Method 2: Try executable file extraction with priority on larger icons+ if let Some(exe_path) = self.get_executable_path() {+ let wide_path: Vec<u16> =+ exe_path.encode_utf16().chain(std::iter::once(0)).collect();++ // Try extracting icons from multiple indices+ for icon_index in 0..6 {+ let mut large_icon: HICON = HICON::default();+ let mut small_icon: HICON = HICON::default();++ let extracted = ExtractIconExW(+ PCWSTR(wide_path.as_ptr()),+ icon_index,+ Some(&mut large_icon),+ Some(&mut small_icon),+ 1,+ );++ if extracted > 0 {+ // Try large icon first+ if !large_icon.is_invalid() {+ if let Some(result) = self.hicon_to_png_bytes_high_res(large_icon) {+ if result.1 > best_size {+ best_result = Some(result.0);+ best_size = result.1;+ }+ }+ let _ = DestroyIcon(large_icon);+ }++ // Try small icon if we haven't found anything good yet+ if !small_icon.is_invalid() && best_size < 64 {+ if let Some(result) = self.hicon_to_png_bytes_high_res(small_icon) {+ if result.1 > best_size {+ best_result = Some(result.0);+ best_size = result.1;+ }+ }+ let _ = DestroyIcon(small_icon);+ }+ }+ }+ }++ // Method 3: Try small window icon if we still don't have anything good+ if best_size < 32 {+ let small_icon = SendMessageW(+ self.0,+ WM_GETICON,+ Some(WPARAM(0usize)),+ Some(LPARAM(0isize)),+ ); // ICON_SMALL = 0++ if small_icon.0 != 0 {+ if let Some(result) = self.hicon_to_png_bytes_high_res(HICON(small_icon.0 as _))+ {+ if result.1 > best_size {+ best_result = Some(result.0);+ best_size = result.1;+ }+ }+ }+ }++ // Method 4: Try class icon as last resort+ if best_size < 32 {+ let class_icon = GetClassLongPtrW(self.0, GCLP_HICON) as isize;+ if class_icon != 0 {+ if let Some(result) = self.hicon_to_png_bytes_high_res(HICON(class_icon as _)) {+ if result.1 > best_size {+ best_result = Some(result.0);+ }+ }+ }+ }++ best_result+ }+ }++ fn get_executable_path(&self) -> Option<String> {+ unsafe {+ let mut process_id = 0u32;+ GetWindowThreadProcessId(self.0, Some(&mut process_id));++ if process_id == 0 {+ return None;+ }++ let process_handle =+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process_id).ok()?;++ let mut buffer = [0u16; 1024];+ let mut buffer_size = buffer.len() as u32;++ let result = QueryFullProcessImageNameW(+ process_handle,+ PROCESS_NAME_FORMAT::default(),+ PWSTR(buffer.as_mut_ptr()),+ &mut buffer_size,+ );++ let _ = CloseHandle(process_handle);++ if result.is_ok() && buffer_size > 0 {+ Some(String::from_utf16_lossy(&buffer[..buffer_size as usize]))+ } else {+ None+ }+ }+ }++ fn get_icon_size(&self, icon: HICON) -> Option<(i32, i32)> {+ unsafe {+ let mut icon_info = ICONINFO::default();+ if !GetIconInfo(icon, &mut icon_info).is_ok() {+ return None;+ }++ // Get bitmap info to determine actual size+ let mut bitmap_info = BITMAP::default();+ let result = GetObjectA(+ HGDIOBJ(icon_info.hbmColor.0),+ mem::size_of::<BITMAP>() as i32,+ Some(&mut bitmap_info as *mut _ as *mut _),+ );++ // Clean up bitmap handles+ let _ = DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmMask.into());++ if result > 0 {+ Some((bitmap_info.bmWidth, bitmap_info.bmHeight))+ } else {+ None+ }+ }+ }++ fn hicon_to_png_bytes_high_res(&self, icon: HICON) -> Option<(Vec<u8>, i32)> {+ unsafe {+ // Get icon info to determine actual size+ let mut icon_info = ICONINFO::default();+ if !GetIconInfo(icon, &mut icon_info).is_ok() {+ return None;+ }++ // Get device context+ let screen_dc = GetDC(Some(HWND::default()));+ let mem_dc = CreateCompatibleDC(Some(screen_dc));++ // Get the native icon size to prioritize it+ let native_size = self.get_icon_size(icon);++ // Always try for the highest resolution possible, starting with the largest sizes+ let mut sizes = vec![2048, 1024, 512, 256, 128, 96, 64, 48, 32, 24, 16];++ // If we have native size info, prioritize it+ if let Some((width, height)) = native_size {+ let native_dim = width.max(height);+ const MAX_SIZE: i32 = 4096;+ if !sizes.contains(&native_dim) && native_dim > 0 && native_dim <= MAX_SIZE {+ sizes.insert(0, native_dim);+ }+ }++ let mut best_result = None;+ let mut best_size = 0;++ for &size in &sizes {+ let width = size;+ let height = size;++ // Create bitmap info for this size+ let mut bitmap_info = BITMAPINFO {+ bmiHeader: BITMAPINFOHEADER {+ biSize: mem::size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: width,+ biHeight: -height, // Top-down DIB+ biPlanes: 1,+ biBitCount: 32, // 32 bits per pixel (BGRA)+ biCompression: BI_RGB.0,+ biSizeImage: 0,+ biXPelsPerMeter: 0,+ biYPelsPerMeter: 0,+ biClrUsed: 0,+ biClrImportant: 0,+ },+ bmiColors: [Default::default(); 1],+ };++ // Create a bitmap+ let bitmap = CreateCompatibleBitmap(screen_dc, width, height);+ if bitmap.is_invalid() {+ continue;+ }++ let old_bitmap = SelectObject(mem_dc, bitmap.into());++ // Fill with transparent background+ let brush = CreateSolidBrush(windows::Win32::Foundation::COLORREF(0));+ let rect = RECT {+ left: 0,+ top: 0,+ right: width,+ bottom: height,+ };+ let _ = FillRect(mem_dc, &rect, brush);+ let _ = DeleteObject(brush.into());++ // Draw the icon onto the bitmap with proper scaling+ let draw_result = DrawIconEx(+ mem_dc,+ 0,+ 0,+ icon,+ width,+ height,+ 0,+ Some(HBRUSH::default()),+ DI_FLAGS(0x0003), // DI_NORMAL+ );++ if draw_result.is_ok() {+ // Get bitmap bits+ let mut buffer = vec![0u8; (width * height * 4) as usize];+ let result = GetDIBits(+ mem_dc,+ bitmap,+ 0,+ height as u32,+ Some(buffer.as_mut_ptr() as *mut _),+ &mut bitmap_info,+ DIB_RGB_COLORS,+ );++ if result > 0 {+ // Check if we have any non-transparent pixels+ let has_content = buffer.chunks_exact(4).any(|chunk| chunk[3] != 0);++ if has_content {+ // Convert BGRA to RGBA+ for chunk in buffer.chunks_exact_mut(4) {+ chunk.swap(0, 2); // Swap B and R+ }++ // Create PNG using the image crate+ if let Some(img) =+ image::RgbaImage::from_raw(width as u32, height as u32, buffer)+ {+ let mut png_data = Vec::new();+ if img+ .write_to(+ &mut std::io::Cursor::new(&mut png_data),+ image::ImageFormat::Png,+ )+ .is_ok()+ {+ // Keep the result if it's our first success or if this size is larger+ if best_result.is_none() || size > best_size {+ best_result = Some((png_data, size));+ best_size = size;+ }+ }+ }+ }+ }+ }++ // Cleanup for this iteration+ let _ = SelectObject(mem_dc, old_bitmap);+ let _ = DeleteObject(bitmap.into());+ }++ // Cleanup+ let _ = DeleteDC(mem_dc);+ let _ = ReleaseDC(Some(HWND::default()), screen_dc);+ let _ = DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmMask.into());++ best_result+ }+ }++ pub fn bounds(&self) -> Option<LogicalBounds> {+ let mut rect = RECT::default();+ unsafe {+ if GetWindowRect(self.0, &mut rect).is_ok() {+ // Get DPI scaling factor to convert physical to logical coordinates+ const BASE_DPI: f64 = 96.0;+ let dpi = match GetDpiForWindow(self.0) {+ 0 => BASE_DPI as u32,+ dpi => dpi,+ } as f64;+ let scale_factor = dpi / BASE_DPI;++ Some(LogicalBounds {+ position: LogicalPosition {+ x: rect.left as f64 / scale_factor,+ y: rect.top as f64 / scale_factor,+ },+ size: LogicalSize {+ width: (rect.right - rect.left) as f64 / scale_factor,+ height: (rect.bottom - rect.top) as f64 / scale_factor,+ },+ })+ } else {+ None+ }+ }+ }+}++fn is_window_valid_for_enumeration(hwnd: HWND, current_process_id: u32) -> bool {+ unsafe {+ // Skip invisible or minimized windows+ if !IsWindowVisible(hwnd).as_bool() || IsIconic(hwnd).as_bool() {+ return false;+ }++ // Skip own process windows+ let mut process_id = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut process_id));+ process_id != current_process_id+ }+}++fn is_window_valid_for_topmost_selection(+ hwnd: HWND,+ current_process_id: u32,+ point: POINT,+) -> bool {+ unsafe {+ // Skip invisible or minimized windows+ if !IsWindowVisible(hwnd).as_bool() || IsIconic(hwnd).as_bool() {+ return false;+ }++ // Skip own process windows (includes overlays)+ let mut process_id = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut process_id));+ if process_id == current_process_id {+ return false;+ }++ // Check if point is actually in this window+ if !is_point_in_window(hwnd, point) {+ return false;+ }++ // Skip certain window classes that should be ignored+ let mut class_name = [0u16; 256];+ let len = GetClassNameW(hwnd, &mut class_name);+ if len > 0 {+ let class_name_str = String::from_utf16_lossy(&class_name[..len as usize]);+ match class_name_str.as_str() {+ "Shell_TrayWnd" | "Button" | "Tooltip" | "ToolTips_Class32" => return false,+ _ => {}+ }+ }++ // Skip windows with certain extended styles+ let ex_style = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;+ if (ex_style & WS_EX_TRANSPARENT.0) != 0 || (ex_style & WS_EX_LAYERED.0) != 0 {+ // Allow layered windows only if they have proper alpha+ if (ex_style & WS_EX_LAYERED.0) != 0 {+ let mut alpha = 0u8;+ let mut color_key = 0u32;+ let mut flags = 0u32;+ if GetLayeredWindowAttributes(+ hwnd,+ Some(&mut color_key as *mut u32 as *mut _),+ Some(&mut alpha),+ Some(&mut flags as *mut u32 as *mut _),+ )+ .is_ok()+ {+ if alpha < 50 {+ // Skip nearly transparent windows+ return false;+ }+ }+ } else {+ return false; // Skip fully transparent windows+ }+ }++ true+ }+}++fn is_point_in_window(hwnd: HWND, point: POINT) -> bool {+ unsafe {+ let mut rect = RECT::default();+ if GetWindowRect(hwnd, &mut rect).is_ok() {+ point.x >= rect.left+ && point.x < rect.right+ && point.y >= rect.top+ && point.y < rect.bottom+ } else {+ false+ }+ }+}++#[derive(Clone, PartialEq, Debug)]+pub struct DisplayIdImpl(u64);++impl std::fmt::Display for DisplayIdImpl {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for DisplayIdImpl {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse()+ .map(Self)+ .map_err(|_| "Invalid display ID".to_string())+ }+}++#[derive(Clone, PartialEq, Debug)]+pub struct WindowIdImpl(u64);++impl std::fmt::Display for WindowIdImpl {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for WindowIdImpl {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse()+ .map(Self)+ .map_err(|_| "Invalid window ID".to_string())}}diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex 4c6411161..213389089 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -90,7 +90,7 @@ impl CameraFeed {SetupCameraError::Initialisation);- let camera_info = find_camera(&selected_camera).unwrap();+ let camera_info = find_camera(&selected_camera).ok_or(SetupCameraError::CameraNotFound)?;let (control, control_receiver) = flume::bounded(1);let (ready_tx, ready_rx) = oneshot::channel();diff --git a/packages/ui-solid/src/Button.tsx b/packages/ui-solid/src/Button.tsxindex 983bed47b..c7b286d98 100644--- a/packages/ui-solid/src/Button.tsx+++ b/packages/ui-solid/src/Button.tsx@@ -12,7 +12,7 @@ const styles = cva(variant: {blue: "bg-blue-9 text-white hover:bg-blue-10 disabled:bg-gray-6 disabled:text-gray-9 outline-blue-300 disabled:outline-blue-10",primary:- "bg-gray-12 text-gray-1 hover:bg-gray-11 disabled:bg-gray-6 disabled:text-gray-9 outline-blue-300 disabled:bg-gray-4 disabled:dark:text-gray-9",+ "bg-gray-12 text-gray-1 hover:bg-gray-11 enabled:hover:bg-blue-8 disabled:bg-gray-6 disabled:text-gray-9 outline-blue-300 disabled:bg-gray-4 disabled:dark:text-gray-9",secondary:"bg-gray-4 enabled:hover:bg-gray-5 text-gray-500 disabled:bg-gray-6 disabled:text-gray-9 outline-blue-300 disabled:outline-blue-10",destructive:diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex 6d1f4abd4..b36055084 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -57,7 +57,11 @@ declare global {const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default']const IconCapZoomIn: typeof import('~icons/cap/zoom-in.jsx')['default']const IconCapZoomOut: typeof import('~icons/cap/zoom-out.jsx')['default']+ const IconFa6SolidDisplay: typeof import('~icons/fa6-solid/display.jsx')['default']const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default']+ const IconIcBaselineMonitor: typeof import("~icons/ic/baseline-monitor.jsx")["default"]+ const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"]+ const IconLucideAppWindowMac: typeof import('~icons/lucide/app-window-mac.jsx')['default']const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default']const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']@@ -79,5 +83,10 @@ declare global {const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default']const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']+ const IconLucideX: typeof import('~icons/lucide/x.jsx')['default']+ const IconMaterialSymbolsLightScreenshotFrame2: typeof import('~icons/material-symbols-light/screenshot-frame2.jsx')['default']+ const IconMaterialSymbolsLightScreenshotFrame2MaterialSymbolsScreenshotFrame2Rounded: typeof import('~icons/material-symbols-light/screenshot-frame2-material-symbols-screenshot-frame2-rounded.jsx')['default']+ const IconMaterialSymbolsScreenshotFrame2Rounded: typeof import('~icons/material-symbols/screenshot-frame2-rounded.jsx')['default']+ const IconMdiMonitor: typeof import('~icons/mdi/monitor.jsx')['default']const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default']}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7672780d3..556d9c4bc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -80,6 +80,9 @@ importers:'@solid-primitives/memo':specifier: ^1.4.2version: 1.4.2([email protected])+ '@solid-primitives/mouse':+ specifier: ^2.1.2+ version: 2.1.2([email protected])'@solid-primitives/refs':specifier: ^1.0.8version: 1.1.1([email protected])@@ -5365,6 +5368,11 @@ packages:peerDependencies:solid-js: ^1.6.12+ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-ov4K3eQCybN0bN4ZzBA3mFGuj2AJmgP9kOJaGZtTtjJ6uvI6LYd8pfv+Tm6gb3BlaIlVurLMuOU30mapSaJjhA==}+ peerDependencies:+ solid-js: ^1.6.12+'@solid-primitives/[email protected]':resolution: {integrity: sha512-SuTuCctLLZbUL1QyWamQGWSWPIgoc/gXt5kL8P2yLhb51f9Dj+WHxU0shXBjzx7z+hDc5KtheQgM4NnJqQJi2A==}peerDependencies:@@ -18547,6 +18555,14 @@ snapshots:'@solid-primitives/utils': 6.3.1([email protected])solid-js: 1.9.6+ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/event-listener': 2.4.1([email protected])+ '@solid-primitives/rootless': 1.5.1([email protected])+ '@solid-primitives/static-store': 0.1.1([email protected])+ '@solid-primitives/utils': 6.3.1([email protected])+ solid-js: 1.9.6+'@solid-primitives/[email protected]([email protected])':dependencies:'@solid-primitives/utils': 6.3.1([email protected])@@ -21778,8 +21794,8 @@ snapshots:eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 4.6.2([email protected]([email protected]))@@ -21807,33 +21823,33 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.0([email protected])- eslint: 8.57.1+ eslint: 9.30.1([email protected])get-tsconfig: 4.10.0is-bun-module: 2.0.0stable-hash: 0.0.5tinyglobby: 0.2.13unrs-resolver: 1.7.2optionalDependencies:- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-colordependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.0([email protected])- eslint: 9.30.1([email protected])+ eslint: 8.57.1get-tsconfig: 4.10.0is-bun-module: 2.0.0stable-hash: 0.0.5tinyglobby: 0.2.13unrs-resolver: 1.7.2optionalDependencies:- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -21848,14 +21864,14 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -21899,7 +21915,7 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.8@@ -21910,7 +21926,7 @@ snapshots:doctrine: 2.1.0eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3