diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rs index dd338d1b2fd..edf34aa4268 100644 --- a/apps/desktop-gpui/src/deeplink.rs +++ b/apps/desktop-gpui/src/deeplink.rs @@ -124,6 +124,10 @@ pub enum DeepLinkAction { capture_system_audio: bool, mode: cap_recording::RecordingMode, }, + StartDefaultRecording { + #[serde(default)] + mode: Option, + }, StopRecording, #[cfg(debug_assertions)] PauseRecording, @@ -303,6 +307,20 @@ pub fn init(cx: &mut App) { .detach(); } +fn resolve_screen_capture_target( + name: &str, + primary_display: impl FnOnce() -> scap_targets::DisplayId, + cursor_display: impl FnOnce() -> Option, + named_display: impl FnOnce() -> Option, +) -> Result { + let id = match name { + "default" | "primary" => primary_display(), + "cursor" => cursor_display().unwrap_or_else(primary_display), + _ => named_display().ok_or_else(|| format!("No screen with name \"{name}\""))?, + }; + Ok(ScreenCaptureTarget::Display { id }) +} + fn dispatch_recording_stop( phase: Phase, clean_capture_owned: bool, @@ -334,11 +352,17 @@ impl DeepLinkAction { // The name -> target resolution, verbatim from // `deeplink_actions.rs:200-231`. let capture_target: ScreenCaptureTarget = match capture_mode { - CaptureMode::Screen(name) => cap_recording::screen_capture::list_displays() - .into_iter() - .find(|(s, _)| s.name == name) - .map(|(s, _)| ScreenCaptureTarget::Display { id: s.id }) - .ok_or(format!("No screen with name \"{}\"", name))?, + CaptureMode::Screen(name) => resolve_screen_capture_target( + &name, + || scap_targets::Display::primary().id(), + || scap_targets::Display::get_containing_cursor().map(|d| d.id()), + || { + cap_recording::screen_capture::list_displays() + .into_iter() + .find(|(s, _)| s.name == name) + .map(|(s, _)| s.id) + }, + )?, CaptureMode::Window(name) => cap_recording::screen_capture::list_windows() .into_iter() .find(|(w, _)| w.name == name) @@ -442,6 +466,21 @@ impl DeepLinkAction { }); Ok(()) } + DeepLinkAction::StartDefaultRecording { mode } => { + let mode = match mode { + Some(cap_recording::RecordingMode::Studio) => { + Some(crate::main_window::Mode::Studio) + } + Some(cap_recording::RecordingMode::Instant) => { + Some(crate::main_window::Mode::Instant) + } + Some(cap_recording::RecordingMode::Screenshot) => { + return Err("Use take_screenshot for screenshots".to_string()); + } + None => None, + }; + crate::hotkeys::start_default_recording(mode, cx) + } DeepLinkAction::StopRecording => { let main = cx.global::().main; let _ = main.update(cx, |view, _, cx| { @@ -831,6 +870,139 @@ mod tests { ); } + #[test] + fn parses_start_default_recording_action_urls() { + let default_url = Url::parse( + "cap-desktop://action?value=%7B%22start_default_recording%22%3A%7B%7D%7D", + ) + .unwrap(); + assert_eq!( + DeepLinkAction::try_from(&default_url), + Ok(DeepLinkAction::StartDefaultRecording { mode: None }) + ); + + let studio_url = Url::parse( + "cap-desktop://action?value=%7B%22start_default_recording%22%3A%7B%22mode%22%3A%22studio%22%7D%7D", + ) + .unwrap(); + assert_eq!( + DeepLinkAction::try_from(&studio_url), + Ok(DeepLinkAction::StartDefaultRecording { + mode: Some(cap_recording::RecordingMode::Studio), + }) + ); + } + + #[test] + fn resolves_screen_aliases_and_cursor_fallback() { + let display_id = |id: &str| -> scap_targets::DisplayId { id.parse().unwrap() }; + let target_json = |target: &ScreenCaptureTarget| serde_json::to_value(target).unwrap(); + let expected = |id: &str| { + serde_json::json!({ + "variant": "display", + "id": display_id(id), + }) + }; + + for alias in ["default", "primary"] { + let target = resolve_screen_capture_target( + alias, + || display_id("1"), + || panic!("cursor lookup should not run for {alias}"), + || panic!("named lookup should not run for {alias}"), + ) + .unwrap(); + assert_eq!(target_json(&target), expected("1")); + } + + let cursor_target = resolve_screen_capture_target( + "cursor", + || panic!("primary fallback should not run when cursor display exists"), + || Some(display_id("2")), + || panic!("named lookup should not run for cursor"), + ) + .unwrap(); + assert_eq!(target_json(&cursor_target), expected("2")); + + let fallback_target = resolve_screen_capture_target( + "cursor", + || display_id("1"), + || None, + || panic!("named lookup should not run for cursor"), + ) + .unwrap(); + assert_eq!(target_json(&fallback_target), expected("1")); + + let named_target = resolve_screen_capture_target( + "Odyssey G93SC", + || panic!("primary lookup should not run for named screen"), + || panic!("cursor lookup should not run for named screen"), + || Some(display_id("3")), + ) + .unwrap(); + assert_eq!(target_json(&named_target), expected("3")); + + let Err(missing) = resolve_screen_capture_target( + "Missing Display", + || display_id("1"), + || None, + || None, + ) else { + panic!("expected missing display error"); + }; + assert_eq!(missing, "No screen with name \"Missing Display\""); + } + + #[test] + fn parses_start_recording_action_url_default_and_cursor_screen() { + let display_id = |id: &str| -> scap_targets::DisplayId { id.parse().unwrap() }; + let target_json = |target: &ScreenCaptureTarget| serde_json::to_value(target).unwrap(); + let expected = |id: &str| { + serde_json::json!({ + "variant": "display", + "id": display_id(id), + }) + }; + + for (screen_alias, cursor_id, expected_id) in [ + ("default", Some("2"), "1"), + ("primary", Some("2"), "1"), + ("cursor", Some("2"), "2"), + ("cursor", None, "1"), + ] { + let value = serde_json::json!({ + "start_recording": { + "capture_mode": { "screen": screen_alias }, + "camera": null, + "mic_label": null, + "capture_system_audio": true, + "mode": "instant" + } + }) + .to_string(); + let url = Url::parse_with_params("cap-desktop://action", &[("value", value)]).unwrap(); + let Ok(DeepLinkAction::StartRecording { + capture_mode: CaptureMode::Screen(name), + camera: None, + mic_label: None, + capture_system_audio: true, + mode: cap_recording::RecordingMode::Instant, + }) = DeepLinkAction::try_from(&url) + else { + panic!("expected start recording screen action for {screen_alias}"); + }; + + let target = resolve_screen_capture_target( + &name, + || display_id("1"), + || cursor_id.map(display_id), + || panic!("named lookup should not run for {screen_alias}"), + ) + .unwrap(); + assert_eq!(target_json(&target), expected(expected_id)); + } + } + #[test] fn parses_start_recording_action_url() { let url = Url::parse( diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs index 7527717ae4a..2b118c994b9 100644 --- a/apps/desktop-gpui/src/hotkeys.rs +++ b/apps/desktop-gpui/src/hotkeys.rs @@ -28,7 +28,7 @@ use gpui::{App, Global, PromptButton, PromptLevel}; use crate::{ app_windows, i18n::tr, - main_window::{Mode, TargetType}, + main_window::{Mode, RecordingStartPermit, TargetType}, session::{Phase, RecordingSession}, store, }; @@ -994,6 +994,11 @@ fn dispatch(action: HotkeyAction, pressed_at: std::time::Instant, cx: &mut App) HotkeyAction::StartStudioRecording => start_from_hotkey(Mode::Studio, cx), HotkeyAction::StartInstantRecording => start_from_hotkey(Mode::Instant, cx), HotkeyAction::StopRecording => { + let main = cx.global::().main; + let _ = main.update(cx, |view, _, cx| { + view.cancel_deep_link_start(); + cx.notify(); + }); RecordingSession::global(cx).update(cx, |session, cx| session.stop(cx)); } HotkeyAction::RestartRecording => { @@ -1073,26 +1078,32 @@ fn microphone_available(name: &str) -> bool { /// where it was. Deliberate: this app's start path reads the window's mode, /// and a recording visibly in Studio mode with the pill saying Instant is the /// worse mismatch. -fn start_from_hotkey(mode: Mode, cx: &mut App) { - app_windows::set_recording_mode(mode, cx); +pub(crate) fn start_default_recording(mode: Option, cx: &mut App) -> Result<(), String> { + let resolved_mode = match mode.unwrap_or_else(Mode::from_store) { + Mode::Studio => Mode::Studio, + Mode::Instant | Mode::Screenshot => Mode::Instant, + }; let main = cx.global::().main; + let can_set_mode = RecordingSession::global(cx).read(cx).phase == Phase::Idle + && !app_windows::clean_capture_owned(cx) + && main + .read(cx) + .is_ok_and(|view| !view.is_preparing_recording()); + if can_set_mode { + app_windows::set_recording_mode(resolved_mode, cx); + } + let permit = main + .update(cx, |view, _, cx| view.prepare_default_recording_start(cx)) + .map_err(|_| "The recording window is unavailable".to_string())??; let armed = main.read(cx).ok().and_then(|view| view.armed_target()); let stored = stored_target(); - - // `is_recording_active_or_pending` (`hotkeys.rs:162-170` over there): an - // active session skips the confirm -- the re-start is a no-op either way, - // `start_recording_with_target`'s phase check here and `start_recording`'s - // over there. - let idle = RecordingSession::global(cx).read(cx).phase == Phase::Idle; - let confirm = idle && store::GeneralSettings::load().confirm_without_microphone; + let confirm = store::GeneralSettings::load().confirm_without_microphone; let mic_name = main.read(cx).ok().and_then(|view| { view.microphone_selection() .map(|microphone| microphone.name.clone()) }); cx.spawn(async move |cx| { - // Window and display lookups enumerate the system, so they run off - // the main thread along with the microphone probe below. let target = cx .background_executor() .spawn(async move { @@ -1103,15 +1114,13 @@ fn start_from_hotkey(mode: Mode, cx: &mut App) { }) }) .await; + if !cx.update(|cx| default_start_is_current(main, &permit, cx)) { + return; + } if !confirm { - cx.update(|cx| start_now(main, mode, target, cx)); + cx.update(|cx| start_default_now(main, target, false, permit, cx)); return; } - // The availability probe the Tauri confirm runs. On macOS that is a - // name match (`microphone_available_for_confirmation` over there): - // `MicrophoneFeed::list()` reads every input device's configuration, - // which held the hotkey start for over 100 ms. No selection means no - // microphone, which needs no enumeration to know. let available = match mic_name { Some(name) => { cx.background_executor() @@ -1120,15 +1129,17 @@ fn start_from_hotkey(mode: Mode, cx: &mut App) { } None => false, }; + if !cx.update(|cx| default_start_is_current(main, &permit, cx)) { + return; + } if available { - cx.update(|cx| start_now(main, mode, target, cx)); + cx.update(|cx| start_default_now(main, target, false, permit, cx)); return; } - // The Tauri dialog, word for word - // (`confirm_direct_recording_without_microphone`). gpui prompts are - // window sheets rather than free-standing alerts, so the main window - // comes forward to host it. let receiver = cx.update(|cx| { + if !default_start_is_current(main, &permit, cx) { + return None; + } app_windows::show_main_window(cx); cx.activate(true); main.update(cx, |_, window, cx| { @@ -1143,17 +1154,24 @@ fn start_from_hotkey(mode: Mode, cx: &mut App) { cx, ) }) + .ok() }); - let Ok(receiver) = receiver else { + let Some(receiver) = receiver else { + cx.update(|cx| finish_default_start(main, &permit, cx)); return; }; - // `receiver.await.unwrap_or(false)`: a dismissed sheet records - // nothing. if receiver.await == Ok(0) { - cx.update(|cx| start_now(main, mode, target, cx)); + cx.update(|cx| start_default_now(main, target, true, permit, cx)); + } else { + cx.update(|cx| finish_default_start(main, &permit, cx)); } }) .detach(); + Ok(()) +} + +fn start_from_hotkey(mode: Mode, cx: &mut App) { + let _ = start_default_recording(Some(mode), cx); } /// What a Start shortcut records: the target selected in the main window, @@ -1192,22 +1210,54 @@ fn target_is_live(target: &ScreenCaptureTarget) -> bool { } } -fn start_now( +fn default_start_is_current( + main: gpui::WindowHandle, + permit: &RecordingStartPermit, + cx: &mut App, +) -> bool { + let current = main + .read(cx) + .is_ok_and(|view| view.recording_start_is_current(permit, cx)); + if !current { + finish_default_start(main, permit, cx); + } + current +} + +fn finish_default_start( + main: gpui::WindowHandle, + permit: &RecordingStartPermit, + cx: &mut App, +) { + if main + .update(cx, |view, _, _| view.finish_deep_link_start(permit)) + .is_err() + { + permit.cancel(); + } +} + +fn start_default_now( main: gpui::WindowHandle, - mode: Mode, target: ScreenCaptureTarget, + confirmed_without_microphone: bool, + permit: RecordingStartPermit, cx: &mut App, ) { - // The start waited on the target lookup (and maybe the microphone - // prompt); another Start or Cycle shortcut can change the mode meanwhile, - // and the start path reads the window's mode. - if RecordingSession::global(cx).read(cx).phase == Phase::Idle { - app_windows::set_recording_mode(mode, cx); - } - main.update(cx, |view, window, cx| { - view.start_recording_with_target(target, Vec::new(), window, cx) - }) - .ok(); + if main + .update(cx, |view, _, cx| { + view.start_recording_with_target_and_permit( + target, + Vec::new(), + confirmed_without_microphone, + permit.clone(), + cx, + ) + }) + .is_err() + { + permit.cancel(); + } } /// `RecordingSettingsStore.target`, straight off the shared store's JSON. A diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 928b64406e1..9fa71b94b91 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -2509,6 +2509,133 @@ impl MainWindow { self.start_recording_config(config, cx); } + pub(crate) fn start_recording_with_target_and_permit( + &mut self, + target: ScreenCaptureTarget, + excluded_windows: Vec, + confirmed_without_microphone: bool, + permit: RecordingStartPermit, + cx: &mut Context, + ) { + if !self.recording_start_is_current(&permit, cx) { + self.finish_recording_start(&permit); + return; + } + let editor_flow = self.session.read(cx).editor_recording_target().is_some(); + let mode = if editor_flow { + recording::RecordingMode::Studio + } else { + match self.recording_mode(cx) { + Some(mode) => mode, + None => { + self.finish_recording_start(&permit); + return; + } + } + }; + if mode == recording::RecordingMode::Instant && !crate::store::auth_snapshot().signed_in() { + self.finish_recording_start(&permit); + let kind = match &target { + ScreenCaptureTarget::Display { .. } => TargetType::Display, + ScreenCaptureTarget::Window { .. } => TargetType::Window, + ScreenCaptureTarget::Area { .. } => TargetType::Area, + ScreenCaptureTarget::CameraOnly => TargetType::CameraOnly, + }; + self.show_sign_in_prompt(kind, cx); + cx.defer(app_windows::show_main_window); + return; + } + if matches!(target, ScreenCaptureTarget::CameraOnly) && self.camera.is_none() { + self.finish_recording_start(&permit); + self.session.update(cx, |session, cx| { + session.error = Some(tr::main::error::camera_only_needs_camera().into()); + cx.notify(); + }); + if editor_flow { + cx.defer(app_windows::abort_editor_recording_flow); + } + return; + } + if self.enumerating + || self.device_format_pending.is_some() + || self.pending_device_restore.camera_id.is_some() + || self.pending_device_restore.microphone_name.is_some() + { + self.finish_recording_start(&permit); + self.session.update(cx, |session, cx| { + session.error = Some(tr::main::error::devices_not_ready().into()); + cx.notify(); + }); + return; + } + + let (camera_feed, mic_feed, mic_meter, input_readiness, device_settings) = { + let feeds = Feeds::global(cx); + feeds.update(cx, |feeds, cx| feeds.resume_camera_preview(cx)); + let feeds = feeds.read(cx); + ( + feeds.camera_actor(), + feeds.mic_actor(), + feeds.mic_meter(), + feeds.input_readiness(), + feeds.requested_device_settings(), + ) + }; + let (microphone, mic_feed) = if confirmed_without_microphone { + (None, None) + } else { + ( + self.microphone.as_ref().map(|mic| mic.name.clone()), + mic_feed, + ) + }; + let config = recording::StartConfig { + mode, + target, + device_settings, + input_readiness, + microphone, + camera: self.camera_id.clone(), + system_audio: self.system_audio, + excluded_windows, + camera_feed, + mic_feed, + mic_meter, + #[cfg(target_os = "linux")] + linux_instant_camera: None, + start_gate: None, + }; + + if let Ok(value) = serde_json::to_value(&config.target) + && !crate::store::set_store_setting(crate::store::RECORDING_SETTINGS, "target", value) + { + tracing::warn!("saving the last recording target failed"); + } + + if !confirmed_without_microphone { + let microphone_available = config.microphone.as_ref().is_some_and(|name| { + self.devices + .microphones + .iter() + .any(|device| &device.name == name) + }); + if !microphone_available + && crate::store::GeneralSettings::load().confirm_without_microphone + { + self.microphone_warning = Some(MicrophoneWarning { + config, + permit, + dont_show_again: false, + error: None, + }); + cx.defer(app_windows::show_main_window); + cx.notify(); + return; + } + } + self.check_storage_before_start(config, false, permit, cx); + } + pub(crate) fn start_recording_config( &mut self, config: recording::StartConfig, @@ -2567,6 +2694,32 @@ impl MainWindow { Ok(permit) } + pub(crate) fn prepare_default_recording_start( + &mut self, + cx: &mut Context, + ) -> Result { + if self.enumerating + || self.device_format_pending.is_some() + || self.pending_device_restore.camera_id.is_some() + || self.pending_device_restore.microphone_name.is_some() + { + let message: String = tr::main::error::devices_not_ready().into(); + self.session.update(cx, |session, cx| { + session.error = Some(message.clone()); + cx.notify(); + }); + return Err(message); + } + let permit = RecordingStartPermit::prepare( + self.session.read(cx).phase, + app_windows::clean_capture_owned(cx), + self.checking_storage || self.deep_link_start.is_some(), + )?; + self.checking_storage = true; + self.deep_link_start = Some(permit.clone()); + Ok(permit) + } + pub(crate) fn cancel_deep_link_start(&mut self) { self.microphone_warning = None; if RecordingStartPermit::cancel_current(&mut self.deep_link_start) { @@ -2606,7 +2759,11 @@ impl MainWindow { self.check_storage_before_start(config, false, permit, cx); } - fn recording_start_is_current(&self, permit: &RecordingStartPermit, cx: &gpui::App) -> bool { + pub(crate) fn recording_start_is_current( + &self, + permit: &RecordingStartPermit, + cx: &gpui::App, + ) -> bool { self.session.read(cx).phase == Phase::Idle && self .deep_link_start diff --git a/extensions/raycast/README.md b/extensions/raycast/README.md new file mode 100644 index 00000000000..eafc9229301 --- /dev/null +++ b/extensions/raycast/README.md @@ -0,0 +1,15 @@ +# Cap Raycast Extension + +Official Raycast extension for [Cap](https://cap.so) — the open-source Loom alternative. + +## Commands + +- **Start Recording:** Start a recording session using your saved Cap desktop defaults (target, camera, microphone, system audio, and mode), with an optional argument to override Instant or Studio mode. +- **Stop Recording:** Stop the active Cap recording session (automatically copies the shareable video link to the clipboard in Instant mode). +- **Open Dashboard:** Open your Cap web dashboard (respects self-hosted `serverUrl` configured in Cap desktop or Raycast preferences). +- **Open Cap Settings:** Open the Cap desktop settings window. + +## Prerequisites + +- [Cap Desktop App](https://cap.so/download) installed and running. +- [Raycast](https://raycast.com) installed. diff --git a/extensions/raycast/icon.png b/extensions/raycast/icon.png new file mode 100644 index 00000000000..718226caf20 Binary files /dev/null and b/extensions/raycast/icon.png differ diff --git a/extensions/raycast/package.json b/extensions/raycast/package.json new file mode 100644 index 00000000000..001dbd8d7e9 --- /dev/null +++ b/extensions/raycast/package.json @@ -0,0 +1,83 @@ +{ + "$schema": "https://www.raycast.com/schemas/extension.json", + "name": "cap", + "title": "Cap", + "description": "Start and stop screen recordings with Cap and open your dashboard.", + "icon": "icon.png", + "author": "CapSoftware", + "categories": [ + "Productivity", + "Media" + ], + "license": "MIT", + "preferences": [ + { + "name": "serverUrl", + "type": "textfield", + "required": false, + "title": "Cap Server URL", + "description": "Custom self-hosted Cap server URL (defaults to your Cap desktop setting or https://cap.so).", + "placeholder": "https://cap.so" + } + ], + "commands": [ + { + "name": "start-recording", + "title": "Start Recording", + "description": "Start recording with your saved Cap default settings", + "mode": "no-view", + "arguments": [ + { + "name": "mode", + "type": "dropdown", + "placeholder": "Recording Mode", + "required": false, + "data": [ + { + "title": "Default (Saved in Cap)", + "value": "default" + }, + { + "title": "Instant Mode", + "value": "instant" + }, + { + "title": "Studio Mode", + "value": "studio" + } + ] + } + ] + }, + { + "name": "stop-recording", + "title": "Stop Recording", + "description": "Stop the active Cap recording and copy the shareable link", + "mode": "no-view" + }, + { + "name": "open-dashboard", + "title": "Open Dashboard", + "description": "Open your Cap web dashboard", + "mode": "no-view" + }, + { + "name": "open-settings", + "title": "Open Cap Settings", + "description": "Open Cap desktop settings", + "mode": "no-view" + } + ], + "dependencies": { + "@raycast/api": "^1.88.0" + }, + "devDependencies": { + "@types/node": "20.8.10", + "@types/react": "18.2.27", + "typescript": "^5.4.5" + }, + "scripts": { + "build": "ray build -e dist", + "dev": "ray develop" + } +} diff --git a/extensions/raycast/src/open-dashboard.ts b/extensions/raycast/src/open-dashboard.ts new file mode 100644 index 00000000000..7add93c0a14 --- /dev/null +++ b/extensions/raycast/src/open-dashboard.ts @@ -0,0 +1,14 @@ +import { closeMainWindow, open, showHUD } from "@raycast/api"; +import { getConfiguredDashboardUrl } from "./utils"; + +export default async function Command() { + await closeMainWindow(); + + const dashboardUrl = getConfiguredDashboardUrl(); + try { + await open(dashboardUrl); + await showHUD("🌐 Opening Cap Dashboard..."); + } catch { + await showHUD("âš ī¸ Failed to open Cap Dashboard."); + } +} diff --git a/extensions/raycast/src/open-settings.ts b/extensions/raycast/src/open-settings.ts new file mode 100644 index 00000000000..51e087d161a --- /dev/null +++ b/extensions/raycast/src/open-settings.ts @@ -0,0 +1,13 @@ +import { closeMainWindow, showHUD } from "@raycast/api"; +import { triggerCapAction } from "./utils"; + +export default async function Command() { + await closeMainWindow(); + + try { + await triggerCapAction({ open_settings: { page: null } }); + await showHUD("âš™ī¸ Opening Cap Settings..."); + } catch { + await showHUD("âš ī¸ Failed to open Cap Settings."); + } +} diff --git a/extensions/raycast/src/start-recording.ts b/extensions/raycast/src/start-recording.ts new file mode 100644 index 00000000000..97b365271c2 --- /dev/null +++ b/extensions/raycast/src/start-recording.ts @@ -0,0 +1,28 @@ +import { closeMainWindow, type LaunchProps, showHUD } from "@raycast/api"; +import { + buildStartDefaultRecordingAction, + type RecordingModeOverride, + triggerCapAction, +} from "./utils"; + +interface StartRecordingArguments { + mode?: RecordingModeOverride; +} + +export default async function Command( + props: LaunchProps<{ arguments: StartRecordingArguments }>, +) { + await closeMainWindow(); + + const mode = props.arguments?.mode; + const action = buildStartDefaultRecordingAction(mode); + + try { + await triggerCapAction(action); + await showHUD("đŸŽĨ Starting Cap recording..."); + } catch { + await showHUD( + "âš ī¸ Failed to trigger Cap recording. Make sure Cap is installed and running.", + ); + } +} diff --git a/extensions/raycast/src/stop-recording.ts b/extensions/raycast/src/stop-recording.ts new file mode 100644 index 00000000000..71ff9ab1caf --- /dev/null +++ b/extensions/raycast/src/stop-recording.ts @@ -0,0 +1,13 @@ +import { closeMainWindow, showHUD } from "@raycast/api"; +import { triggerCapAction } from "./utils"; + +export default async function Command() { + await closeMainWindow(); + + try { + await triggerCapAction("stop_recording"); + await showHUD("âšī¸ Stopping Cap recording (link copied in Instant mode)..."); + } catch { + await showHUD("âš ī¸ Failed to stop Cap recording."); + } +} diff --git a/extensions/raycast/src/utils.ts b/extensions/raycast/src/utils.ts new file mode 100644 index 00000000000..62d47a36432 --- /dev/null +++ b/extensions/raycast/src/utils.ts @@ -0,0 +1,119 @@ +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { getPreferenceValues, open } from "@raycast/api"; + +export type RecordingModeOverride = "default" | "instant" | "studio"; + +interface ExtensionPreferences { + serverUrl?: string; +} + +export function buildDeepLink( + actionPayload: unknown, + scheme: "cap-desktop" | "cap" = "cap-desktop", +): string { + const value = JSON.stringify(actionPayload); + return `${scheme}://action?value=${encodeURIComponent(value)}`; +} + +export function buildStartDefaultRecordingAction( + mode?: RecordingModeOverride, +): { + start_default_recording: { mode?: "instant" | "studio" }; +} { + if (mode === "instant" || mode === "studio") { + return { start_default_recording: { mode } }; + } + return { start_default_recording: {} }; +} + +export async function triggerCapAction(actionPayload: unknown): Promise { + try { + await open(buildDeepLink(actionPayload, "cap-desktop")); + } catch { + await open(buildDeepLink(actionPayload, "cap")); + } +} + +export function resolveCapStorePath(): string { + const overridePath = process.env.CAP_GPUI_TAURI_STORE?.trim(); + if (overridePath) { + return overridePath; + } + const appDataOverride = process.env.CAP_GPUI_APP_DATA_DIR?.trim(); + if (appDataOverride) { + return join(appDataOverride, "store"); + } + if (process.platform === "darwin") { + return join( + homedir(), + "Library", + "Application Support", + "so.cap.desktop", + "store", + ); + } + if (process.platform === "win32") { + const appData = process.env.APPDATA || homedir(); + return join(appData, "so.cap.desktop", "store"); + } + const xdgData = + process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"); + return join(xdgData, "so.cap.desktop", "store"); +} + +export function readStoredServerUrl( + storePath = resolveCapStorePath(), +): string | undefined { + try { + const raw = readFileSync(storePath, "utf8"); + const parsed = JSON.parse(raw) as unknown; + if (typeof parsed !== "object" || parsed === null) { + return undefined; + } + const general = (parsed as Record).general_settings; + if (typeof general !== "object" || general === null) { + return undefined; + } + const serverUrl = (general as Record).serverUrl; + if (typeof serverUrl === "string" && serverUrl.trim().length > 0) { + return serverUrl.trim(); + } + } catch { + return undefined; + } + return undefined; +} + +export function normalizeServerOrigin(value?: string): string | undefined { + const trimmed = value?.trim(); + if (!trimmed) { + return undefined; + } + try { + const url = new URL(trimmed); + if (url.protocol !== "http:" && url.protocol !== "https:") { + return undefined; + } + return url.origin; + } catch { + return undefined; + } +} + +export function resolveDashboardUrl( + preferenceServerUrl?: string, + storedServerUrl?: string, +): string { + const origin = + normalizeServerOrigin(preferenceServerUrl) ?? + normalizeServerOrigin(storedServerUrl) ?? + "https://cap.so"; + return `${origin}/dashboard`; +} + +export function getConfiguredDashboardUrl(): string { + const preferences = getPreferenceValues(); + return resolveDashboardUrl(preferences.serverUrl, readStoredServerUrl()); +} diff --git a/extensions/raycast/tsconfig.json b/extensions/raycast/tsconfig.json new file mode 100644 index 00000000000..b1d2ad2c3ac --- /dev/null +++ b/extensions/raycast/tsconfig.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "lib": ["ES2023"], + "module": "commonjs", + "target": "ES2022", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-jsx" + }, + "include": ["src/**/*"] +}