Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add configurable recording countdown feature (#809)

Richie McIlroy9951d20ec306
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index f7acc911b..73f201c90 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -5,7 +5,7 @@ use tauri::{AppHandle, Wry};
use tauri_plugin_store::StoreExt;
use uuid::Uuid;
-#[derive(Default, Serialize, Deserialize, Type, Debug)]
+#[derive(Default, Serialize, Deserialize, Type, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub enum PostStudioRecordingBehaviour {
#[default]
@@ -13,7 +13,7 @@ pub enum PostStudioRecordingBehaviour {
ShowOverlay,
}
-#[derive(Default, Serialize, Deserialize, Type, Debug)]
+#[derive(Default, Serialize, Deserialize, Type, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub enum MainWindowRecordingStartBehaviour {
#[default]
@@ -21,7 +21,19 @@ pub enum MainWindowRecordingStartBehaviour {
Minimise,
}
-#[derive(Serialize, Deserialize, Type, Debug)]
+impl MainWindowRecordingStartBehaviour {
+ pub fn perform(&self, window: &tauri::WebviewWindow) -> tauri::Result<()> {
+ match self {
+ Self::Close => window.close(),
+ Self::Minimise => window.minimize(),
+ }
+ }
+}
+
+// When adding fields here, #[serde(default)] defines the value to use for existing configurations,
+// and `Default::default` defines the value to use for new configurations.
+// Things that affect the user experience should only be enabled by default for new configurations.
+#[derive(Serialize, Deserialize, Type, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GeneralSettingsStore {
#[serde(default = "uuid::Uuid::new_v4")]
@@ -57,6 +69,8 @@ pub struct GeneralSettingsStore {
pub custom_cursor_capture: bool,
#[serde(default = "default_server_url")]
pub server_url: String,
+ #[serde(default)]
+ pub recording_countdown: Option<u32>,
#[serde(default, alias = "open_editor_after_recording")]
#[deprecated]
_open_editor_after_recording: bool,
@@ -68,7 +82,7 @@ fn default_server_url() -> String {
.to_string()
}
-#[derive(Serialize, Deserialize, Type, Debug)]
+#[derive(Serialize, Deserialize, Type, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CommercialLicense {
license_key: String,
@@ -96,6 +110,7 @@ impl Default for GeneralSettingsStore {
main_window_recording_start_behaviour: MainWindowRecordingStartBehaviour::Close,
custom_cursor_capture: false,
server_url: default_server_url(),
+ recording_countdown: Some(3),
_open_editor_after_recording: false,
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 11151bf4a..cf70796b4 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -151,6 +151,22 @@ impl App {
}
}
}
+
+ async fn add_recording_logging_handle(&mut self, path: &PathBuf) -> Result<(), String> {
+ let logfile =
+ std::fs::File::create(path).map_err(|e| format!("Failed to create logfile: {e}"))?;
+
+ self.recording_logging_handle
+ .reload(Some(Box::new(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .with_target(true)
+ .with_writer(logfile),
+ ) as DynLoggingLayer))
+ .map_err(|e| format!("Failed to reload logging layer: {e}"))?;
+
+ Ok(())
+ }
}
#[tauri::command]
@@ -1882,6 +1898,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
audio_meter::AudioInputLevelChange,
UploadProgress,
captions::DownloadProgress,
+ recording::RecordingEvent
])
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
.typ::<ProjectConfiguration>()
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 6eabf8894..f6f6afed0 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -6,9 +6,7 @@ use crate::{
audio::AppSounds,
auth::AuthStore,
create_screenshot,
- general_settings::{
- GeneralSettingsStore, MainWindowRecordingStartBehaviour, PostStudioRecordingBehaviour,
- },
+ general_settings::{GeneralSettingsStore, PostStudioRecordingBehaviour},
open_external_link,
presets::PresetsStore,
upload::{
@@ -202,6 +200,15 @@ pub struct StartRecordingInputs {
pub mode: RecordingMode,
}
+#[derive(tauri_specta::Event, specta::Type, Clone, Debug, serde::Serialize)]
+#[serde(tag = "variant")]
+pub enum RecordingEvent {
+ Countdown { value: u32 },
+ Started,
+ Stopped,
+ Failed { error: String },
+}
+
#[tauri::command]
#[specta::specta]
#[tracing::instrument(name = "recording", skip_all)]
@@ -211,6 +218,8 @@ pub async fn start_recording(
inputs: StartRecordingInputs,
) -> Result<(), String> {
let id = uuid::Uuid::new_v4().to_string();
+ let general_settings = GeneralSettingsStore::get(&app).ok().flatten();
+ let general_settings = general_settings.as_ref();
let recording_dir = app
.path()
@@ -220,20 +229,11 @@ pub async fn start_recording(
.join(format!("{id}.cap"));
ensure_dir(&recording_dir).map_err(|e| format!("Failed to create recording directory: {e}"))?;
- let logfile = std::fs::File::create(recording_dir.join("recording-logs.log"))
- .map_err(|e| format!("Failed to create logfile: {e}"))?;
-
state_mtx
.write()
.await
- .recording_logging_handle
- .reload(Some(Box::new(
- tracing_subscriber::fmt::layer()
- .with_ansi(false)
- .with_target(true)
- .with_writer(logfile),
- ) as DynLoggingLayer))
- .map_err(|e| format!("Failed to reload logging layer: {e}"))?;
+ .add_recording_logging_handle(&recording_dir.join("recording-logs.log"))
+ .await?;
let target_name = {
let title = inputs.capture_target.get_title();
@@ -325,6 +325,28 @@ pub async fn start_recording(
_ => {}
}
+ if let Some(window) = CapWindowId::Main.get(&app) {
+ let _ = general_settings
+ .map(|v| v.main_window_recording_start_behaviour)
+ .unwrap_or_default()
+ .perform(&window);
+ }
+
+ let countdown = general_settings.and_then(|v| v.recording_countdown);
+ let _ = ShowCapWindow::InProgressRecording { countdown }
+ .show(&app)
+ .await;
+
+ if let Some(countdown) = countdown {
+ for t in 0..countdown {
+ let _ = RecordingEvent::Countdown {
+ value: countdown - t,
+ }
+ .emit(&app);
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+
let (finish_upload_tx, finish_upload_rx) = flume::bounded(1);
let progressive_upload = video_upload_info
.as_ref()
@@ -344,7 +366,7 @@ pub async fn start_recording(
// done in spawn to catch panics just in case
let actor_done_rx = spawn_actor({
let state_mtx = Arc::clone(&state_mtx);
- let app = app.clone();
+ let general_settings = general_settings.cloned();
async move {
fail!("recording::spawn_actor");
let mut state = state_mtx.write().await;
@@ -362,9 +384,7 @@ pub async fn start_recording(
recording_dir.clone(),
base_inputs,
state.camera_feed.clone(),
- GeneralSettingsStore::get(&app)
- .ok()
- .flatten()
+ general_settings
.map(|s| s.custom_cursor_capture)
.unwrap_or_default(),
)
@@ -423,6 +443,8 @@ pub async fn start_recording(
.await
.map_err(|e| format!("Failed to spawn recording actor: {}", e))??;
+ let _ = RecordingEvent::Started.emit(&app);
+
spawn_actor({
let app = app.clone();
let state_mtx = Arc::clone(&state_mtx);
@@ -431,11 +453,14 @@ pub async fn start_recording(
match actor_done_rx.await {
Ok(Ok(_)) => {
let _ = finish_upload_tx.send(());
+ let _ = RecordingEvent::Stopped.emit(&app);
return;
}
Ok(Err(e)) => {
let mut state = state_mtx.write().await;
+ let _ = RecordingEvent::Failed { error: e.clone() }.emit(&app);
+
let mut dialog = MessageDialogBuilder::new(
app.dialog().clone(),
format!("An error occurred"),
@@ -457,30 +482,6 @@ pub async fn start_recording(
}
});
- if let Some(window) = CapWindowId::Main.get(&app) {
- match GeneralSettingsStore::get(&app)
- .ok()
- .flatten()
- .map(|s| s.main_window_recording_start_behaviour)
- .unwrap_or_default()
- {
- MainWindowRecordingStartBehaviour::Close => {
- let _ = window.close();
- }
- MainWindowRecordingStartBehaviour::Minimise => {
- let _ = window.minimize();
- }
- }
- }
-
- if let Some(window) = CapWindowId::InProgressRecording.get(&app) {
- window.eval("window.location.reload()").ok();
- } else {
- let _ = ShowCapWindow::InProgressRecording { position: None }
- .show(&app)
- .await;
- }
-
AppSounds::StartRecording.play();
RecordingStarted.emit(&app).ok();
@@ -594,8 +595,11 @@ async fn handle_recording_end(
// Clear current recording, just in case :)
app.current_recording.take();
- if let Some(recording) = recording {
- handle_recording_finish(&handle, recording).await?;
+ let res = if let Some(recording) = recording {
+ // we delay reporting errors here so that everything else happens first
+ Some(handle_recording_finish(&handle, recording).await)
+ } else {
+ None
};
let _ = RecordingStopped.emit(&handle);
@@ -618,6 +622,10 @@ async fn handle_recording_end(
CurrentRecordingChanged.emit(&handle).ok();
+ if let Some(res) = res {
+ res?;
+ }
+
Ok(())
}
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index bcc1f578c..c6c19aa6f 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -178,7 +178,7 @@ pub enum ShowCapWindow {
WindowCaptureOccluder { screen_id: u32 },
CaptureArea { screen_id: u32 },
Camera,
- InProgressRecording { position: Option<(f64, f64)> },
+ InProgressRecording { countdown: Option<u32> },
Upgrade,
ModeSelect,
}
@@ -436,9 +436,7 @@ impl ShowCapWindow {
window
}
- Self::InProgressRecording {
- position: _position,
- } => {
+ Self::InProgressRecording { countdown } => {
let width = 244.0;
let height = 40.0;
@@ -458,6 +456,10 @@ impl ShowCapWindow {
(monitor.size().height as f64) / monitor.scale_factor() - height - 120.0,
)
.skip_taskbar(true)
+ .initialization_script(format!(
+ "window.COUNTDOWN = {};",
+ countdown.unwrap_or_default()
+ ))
.build()?;
#[cfg(target_os = "macos")]
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index e1f8c808b..76f011803 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -3,7 +3,7 @@ import { useNavigate } from "@solidjs/router";
import {
createMutation,
createQuery,
- useQueryClient
+ useQueryClient,
} from "@tanstack/solid-query";
import { getVersion } from "@tauri-apps/api/app";
import { getCurrentWindow, LogicalSize } from "@tauri-apps/api/window";
@@ -192,7 +192,7 @@ function Page() {
mutationFn: async () => {
if (!isRecording()) {
await commands.startRecording({
- capture_target: options.target(),
+ capture_target: rawOptions.captureTarget,
mode: rawOptions.mode,
capture_system_audio: rawOptions.captureSystemAudio,
});
@@ -296,16 +296,18 @@ function Page() {
await commands.showWindow("Upgrade");
}
}}
- class={`text-[0.6rem] ${license.data?.type === "pro"
- ? "bg-[--blue-400] text-gray-1 dark:text-gray-12"
- : "bg-gray-3 cursor-pointer hover:bg-gray-5"
- } rounded-lg px-1.5 py-0.5`}
+ class={cx(
+ "text-[0.6rem] rounded-lg px-1 py-0.5",
+ license.data?.type === "pro"
+ ? "bg-[--blue-400] text-gray-1 dark:text-gray-12"
+ : "bg-gray-3 cursor-pointer hover:bg-gray-5"
+ )}
>
{license.data?.type === "commercial"
? "Commercial"
: license.data?.type === "pro"
- ? "Pro"
- : "Personal"}
+ ? "Pro"
+ : "Personal"}
</span>
</Suspense>
</ErrorBoundary>
@@ -336,7 +338,7 @@ function Page() {
"flex flex-row items-center rounded-[0.5rem] relative border h-8 transition-all duration-500",
(rawOptions.captureTarget.variant === "screen" ||
rawOptions.captureTarget.variant === "area") &&
- "ml-[2.4rem]"
+ "ml-[2.4rem]"
)}
style={{
"transition-timing-function":
@@ -441,9 +443,19 @@ function Page() {
) : (
<>
{rawOptions.mode === "instant" ? (
- <IconCapInstant class={cx("size-[0.8rem] mr-1.5", toggleRecording.isPending ? "opacity-50" : "opacity-100")} />
+ <IconCapInstant
+ class={cx(
+ "size-[0.8rem] mr-1.5",
+ toggleRecording.isPending ? "opacity-50" : "opacity-100"
+ )}
+ />
) : (
- <IconCapFilmCut class={cx("size-[0.8rem] mr-2 -mt-[1.5px]", toggleRecording.isPending ? "opacity-50" : "opacity-100")} />
+ <IconCapFilmCut
+ class={cx(
+ "size-[0.8rem] mr-2 -mt-[1.5px]",
+ toggleRecording.isPending ? "opacity-50" : "opacity-100"
+ )}
+ />
)}
Start Recording
</>
@@ -575,8 +587,8 @@ function AreaSelectButton(props: {
props.targetVariant === "area"
? "Remove selection"
: areaSelection.pending
- ? "Selecting area..."
- : "Select area"
+ ? "Selecting area..."
+ : "Select area"
}
childClass="flex fixed flex-row items-center w-8 h-8"
>
@@ -647,7 +659,7 @@ function AreaSelectButton(props: {
class={cx(
"w-[1rem] h-[1rem]",
areaSelection.pending &&
- "animate-gentle-bounce duration-1000 text-gray-12 mt-1"
+ "animate-gentle-bounce duration-1000 text-gray-12 mt-1"
)}
/>
</button>
@@ -971,8 +983,8 @@ function TargetSelectInfoPill<T>(props: {
{!props.permissionGranted
? "Request Permission"
: props.value !== null
- ? "On"
- : "Off"}
+ ? "On"
+ : "Off"}
</InfoPill>
);
}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index e370a45cd..0e6c9a313 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -17,7 +17,6 @@ import {
type MainWindowRecordingStartBehaviour,
type PostStudioRecordingBehaviour,
} from "~/utils/tauri";
-// import { themeStore } from "~/store/theme";
import { CheckMenuItem, Menu } from "@tauri-apps/api/menu";
import { confirm } from "@tauri-apps/plugin-dialog";
import { cx } from "cva";
@@ -74,7 +73,8 @@ function AppearanceSection(props: {
class={cx(
`w-24 h-[4.8rem] rounded-md overflow-hidden focus:outline-none ring-offset-gray-50 transition-all duration-200`,
{
- "ring-2 ring-gray-12 ring-offset-2": props.currentTheme === theme.id,
+ "ring-2 ring-gray-12 ring-offset-2":
+ props.currentTheme === theme.id,
"group-hover:ring-2 ring-offset-2 group-hover:ring-gray-5":
props.currentTheme !== theme.id,
}
@@ -143,8 +143,13 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
label: string;
type: "select";
description: string;
- value: MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour;
- onChange: (value: MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour) => void | Promise<void>;
+ value:
+ | MainWindowRecordingStartBehaviour
+ | PostStudioRecordingBehaviour
+ | number;
+ onChange: (
+ value: MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour
+ ) => void | Promise<void>;
};
type SettingItem = ToggleSettingItem | SelectSettingItem;
@@ -159,14 +164,19 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
const settingsGroups: SettingsGroup[] = [
{
title: "Cap Pro",
- titleStyling: "bg-blue-500 py-1.5 mb-4 text-white text-xs px-2 rounded-lg",
+ titleStyling:
+ "bg-blue-500 py-1.5 mb-4 text-white text-xs px-2 rounded-lg",
items: [
{
label: "Disable automatic link opening",
type: "toggle",
- description: "When enabled, Cap will not automatically open links in your browser (e.g. after creating a shareable link).",
- get value() { return !!settings.disableAutoOpenLinks; },
- onChange: (value: boolean) => handleChange("disableAutoOpenLinks", value),
+ description:
+ "When enabled, Cap will not automatically open links in your browser (e.g. after creating a shareable link).",
+ get value() {
+ return !!settings.disableAutoOpenLinks;
+ },
+ onChange: (value: boolean) =>
+ handleChange("disableAutoOpenLinks", value),
},
],
},
@@ -177,16 +187,22 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
label: "Hide dock icon",
type: "toggle",
os: "macos",
- description: "The dock icon will be hidden when there are no windows available to close.",
- get value() { return !!settings.hideDockIcon; },
+ description:
+ "The dock icon will be hidden when there are no windows available to close.",
+ get value() {
+ return !!settings.hideDockIcon;
+ },
onChange: (value: boolean) => handleChange("hideDockIcon", value),
},
{
label: "Enable system notifications",
type: "toggle",
os: "macos",
- description: "Show system notifications for events like copying to clipboard, saving files, and more. You may need to manually allow Cap access via your system's notification settings.",
- get value() { return !!settings.enableNotifications; },
+ description:
+ "Show system notifications for events like copying to clipboard, saving files, and more. You may need to manually allow Cap access via your system's notification settings.",
+ get value() {
+ return !!settings.enableNotifications;
+ },
onChange: async (value: boolean) => {
if (value) {
// Check current permission state
@@ -214,29 +230,63 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
type: "toggle",
os: "macos",
description: "Use haptics on Force Touch™ trackpads",
- get value() { return !!settings.hapticsEnabled; },
+ get value() {
+ return !!settings.hapticsEnabled;
+ },
onChange: (value: boolean) => handleChange("hapticsEnabled", value),
- }
+ },
],
},
{
title: "Recording",
items: [
+ {
+ label: "Recording countdown",
+ description: "Countdown before recording starts",
+ type: "select",
+ get value() {
+ return settings.recordingCountdown ?? 0;
+ },
+ onChange: (
+ value:
+ | MainWindowRecordingStartBehaviour
+ | PostStudioRecordingBehaviour
+ | number
+ ) => handleChange("recordingCountdown", value as number),
+ },
{
label: "Main window recording start behaviour",
description: "The main window recording start behaviour",
type: "select",
- get value() { return settings.mainWindowRecordingStartBehaviour ?? "close"; },
- onChange: (value: MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour) =>
- handleChange("mainWindowRecordingStartBehaviour", value as MainWindowRecordingStartBehaviour),
+ get value() {
+ return settings.mainWindowRecordingStartBehaviour ?? "close";
+ },
+ onChange: (
+ value:
+ | MainWindowRecordingStartBehaviour
+ | PostStudioRecordingBehaviour
+ ) =>
+ handleChange(
+ "mainWindowRecordingStartBehaviour",
+ value as MainWindowRecordingStartBehaviour
+ ),
},
{
label: "Studio recording finish behaviour",
description: "The studio recording finish behaviour",
type: "select",
- get value() { return settings.postStudioRecordingBehaviour ?? "openEditor"; },
- onChange: (value: MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour) =>
- handleChange("postStudioRecordingBehaviour", value as PostStudioRecordingBehaviour),
+ get value() {
+ return settings.postStudioRecordingBehaviour ?? "openEditor";
+ },
+ onChange: (
+ value:
+ | MainWindowRecordingStartBehaviour
+ | PostStudioRecordingBehaviour
+ ) =>
+ handleChange(
+ "postStudioRecordingBehaviour",
+ value as PostStudioRecordingBehaviour
+ ),
},
],
},
@@ -246,7 +296,10 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
const renderRecordingSelect = (
label: string,
description: string,
- getValue: () => MainWindowRecordingStartBehaviour | PostStudioRecordingBehaviour,
+ getValue: () =>
+ | MainWindowRecordingStartBehaviour
+ | PostStudioRecordingBehaviour
+ | number,
onChange: (value: any) => void,
options: { text: string; value: any }[]
) => {
@@ -256,7 +309,7 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
class="flex flex-row gap-1 text-xs bg-gray-3 items-center px-2.5 py-1.5 rounded-md border border-gray-4"
onClick={async () => {
const currentValue = getValue();
- const items = options.map(option =>
+ const items = options.map((option) =>
CheckMenuItem.new({
text: option.text,
checked: currentValue === option.value,
@@ -272,7 +325,7 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
>
{(() => {
const currentValue = getValue();
- const option = options.find(opt => opt.value === currentValue);
+ const option = options.find((opt) => opt.value === currentValue);
return option ? option.text : currentValue;
})()}
<IconCapChevronDown class="size-4" />
@@ -296,12 +349,23 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
<For each={settingsGroups}>
{(group) => (
<div>
- <h3 class={cx("mb-3 text-sm text-gray-12 w-fit", group.titleStyling)}>{group.title}</h3>
+ <h3
+ class={cx(
+ "mb-3 text-sm text-gray-12 w-fit",
+ group.titleStyling
+ )}
+ >
+ {group.title}
+ </h3>
<div class="px-3 rounded-xl border divide-y divide-gray-3 border-gray-3 bg-gray-2">
<For each={group.items}>
{(item) => {
// Check OS compatibility
- if (item.type === "toggle" && item.os && item.os !== ostype) {
+ if (
+ item.type === "toggle" &&
+ item.os &&
+ item.os !== ostype
+ ) {
return null;
}
@@ -316,7 +380,9 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
/>
);
} else if (item.type === "select") {
- if (item.label === "Main window recording start behaviour") {
+ if (
+ item.label === "Main window recording start behaviour"
+ ) {
return renderRecordingSelect(
item.label,
item.description,
@@ -327,7 +393,9 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
{ text: "Minimise", value: "minimise" },
]
);
- } else if (item.label === "Studio recording finish behaviour") {
+ } else if (
+ item.label === "Studio recording finish behaviour"
+ ) {
return renderRecordingSelect(
item.label,
item.description,
@@ -345,9 +413,10 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
() => item.value,
item.onChange,
[
- { text: "Off", value: "off" },
- { text: "3 seconds", value: "three" },
- { text: "5 seconds", value: "five" },
+ { text: "Off", value: 0 },
+ { text: "3 seconds", value: 3 },
+ { text: "5 seconds", value: 5 },
+ { text: "10 seconds", value: 10 },
]
);
}
diff --git a/apps/desktop/src/routes/debug.tsx b/apps/desktop/src/routes/debug.tsx
index 99a7406ec..d07cd292e 100644
--- a/apps/desktop/src/routes/debug.tsx
+++ b/apps/desktop/src/routes/debug.tsx
@@ -20,6 +20,14 @@ export default function Debug() {
>
Show Setup Window
</button>
+ <button
+ class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded"
+ onClick={() =>
+ commands.showWindow({ InProgressRecording: { countdown: 3 } })
+ }
+ >
+ Show In Progress Recording Window
+ </button>
</div>
<h2 class="text-2xl font-bold">Fail Points</h2>
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index ccc4aca66..0973571d4 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -4,23 +4,49 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
import * as dialog from "@tauri-apps/plugin-dialog";
import { type as ostype } from "@tauri-apps/plugin-os";
import { cx } from "cva";
-import { createEffect, createSignal, type ComponentProps } from "solid-js";
+import {
+ createEffect,
+ createSignal,
+ type ComponentProps,
+ Show,
+ onCleanup,
+} from "solid-js";
import { createStore, produce } from "solid-js/store";
+import createPresence from "solid-presence";
import {
createCurrentRecordingQuery,
createOptionsQuery,
} from "~/utils/queries";
import { commands, events } from "~/utils/tauri";
+import { createMemo } from "solid-js";
+
+type State =
+ | { variant: "countdown"; from: number; current: number }
+ | { variant: "recording" }
+ | { variant: "paused" }
+ | { variant: "stopped" };
-type State = "recording" | "paused" | "stopped";
+declare global {
+ interface Window {
+ COUNTDOWN: number;
+ }
+}
export default function () {
- const start = Date.now();
+ const [state, setState] = createSignal<State>(
+ window.COUNTDOWN === 0
+ ? { variant: "recording" }
+ : {
+ variant: "countdown",
+ from: window.COUNTDOWN,
+ current: window.COUNTDOWN,
+ }
+ );
+ const [start, setStart] = createSignal(Date.now());
const [time, setTime] = createSignal(Date.now());
- const [state, setState] = createSignal<State>("recording");
const currentRecording = createCurrentRecordingQuery();
- const { rawOptions } = createOptionsQuery();
+ const optionsQuery = createOptionsQuery();
const audioLevel = createAudioInputLevel();
@@ -32,9 +58,24 @@ export default function () {
]
>([]);
+ const unlisten = events.recordingEvent.listen((data) => {
+ const payload = data.payload;
+ if (payload.variant === "Countdown") {
+ setState((s) => {
+ if (s.variant === "countdown") return { ...s, current: payload.value };
+
+ return s;
+ });
+ } else if (payload.variant === "Started") {
+ setState({ variant: "recording" });
+ setStart(Date.now());
+ }
+ });
+ onCleanup(() => unlisten.then((f) => f()));
+
createTimer(
() => {
- if (state() !== "recording") return;
+ if (state().variant !== "recording") return;
setTime(Date.now());
},
100,
@@ -43,6 +84,7 @@ export default function () {
createEffect(() => {
if (
+ state().variant === "stopped" &&
!currentRecording.isPending &&
(currentRecording.data === undefined || currentRecording.data === null)
)
@@ -51,14 +93,14 @@ export default function () {
const stopRecording = createMutation(() => ({
mutationFn: async () => {
- setState("stopped");
+ setState({ variant: "stopped" });
await commands.stopRecording();
},
}));
const togglePause = createMutation(() => ({
mutationFn: async () => {
- if (state() === "paused") {
+ if (state().variant === "paused") {
await commands.resumeRecording();
setPauseResumes(
produce((a) => {
@@ -66,11 +108,11 @@ export default function () {
a[a.length - 1].resume = Date.now();
})
);
- setState("recording");
+ setState({ variant: "recording" });
} else {
await commands.pauseRecording();
setPauseResumes((a) => [...a, { pause: Date.now() }]);
- setState("paused");
+ setState({ variant: "paused" });
}
setTime(Date.now());
},
@@ -87,7 +129,7 @@ export default function () {
await commands.restartRecording();
- setState("recording");
+ setState({ variant: "recording" });
setTime(Date.now());
},
}));
@@ -103,20 +145,50 @@ export default function () {
await commands.deleteRecording();
- setState("stopped");
+ setState({ variant: "stopped" });
},
}));
const adjustedTime = () => {
- let t = time() - start;
+ if (state().variant === "countdown") return 0;
+ let t = time() - start();
for (const { pause, resume } of pauseResumes) {
if (pause && resume) t -= resume - pause;
}
return t;
};
+ let [countdownRef, setCountdownRef] = createSignal<HTMLDivElement | null>(
+ null
+ );
+ const showCountdown = () => state().variant === "countdown";
+ const countdownPresence = createPresence({
+ show: showCountdown,
+ element: countdownRef,
+ });
+ const countdownState = createMemo<
+ Extract<State, { variant: "countdown" }> | undefined
+ >((prev) => {
+ const s = state();
+ if (s.variant === "countdown") return s;
+ if (prev && countdownPresence.present()) return prev;
+ });
+
return (
<div class="flex flex-row items-stretch w-full h-full bg-gray-1 animate-in fade-in">
+ <Show when={countdownState()}>
+ {(state) => (
+ <div
+ ref={setCountdownRef}
+ class={cx(
+ "transition-opacity",
+ showCountdown() ? "opacity-100" : "opacity-0"
+ )}
+ >
+ <Countdown from={state().from} current={state().current} />
+ </div>
+ )}
+ </Show>
<div class="flex flex-row justify-between p-[0.25rem] flex-1">
<button
disabled={stopRecording.isPending}
@@ -132,7 +204,7 @@ export default function () {
<div class="flex gap-1 items-center">
<div class="flex relative justify-center items-center w-8 h-8">
- {rawOptions.micName != null ? (
+ {optionsQuery.rawOptions.micName != null ? (
<>
<IconCapMicrophone class="size-5 text-gray-12" />
<div class="absolute bottom-1 left-1 right-1 h-0.5 bg-gray-10 overflow-hidden rounded-full">
@@ -158,7 +230,7 @@ export default function () {
disabled={togglePause.isPending}
onClick={() => togglePause.mutate()}
>
- {state() === "paused" ? (
+ {state().variant === "paused" ? (
<IconCapPlayCircle />
) : (
<IconCapPauseCircle />
@@ -195,9 +267,10 @@ function ActionButton(props: ComponentProps<"button">) {
<button
{...props}
class={cx(
- "p-[0.25rem] rounded-lg transition-colors",
+ "p-[0.25rem] rounded-lg transition-all",
"text-gray-11",
"h-8 w-8 flex items-center justify-center",
+ "disabled:opacity-50 disabled:cursor-not-allowed",
props.class
)}
type="button"
@@ -229,3 +302,46 @@ function createAudioInputLevel() {
return level;
}
+
+function Countdown(props: { from: number; current: number }) {
+ const [animation, setAnimation] = createSignal(1);
+ setTimeout(() => setAnimation(0), 10);
+
+ return (
+ <div class="flex flex-row justify-between p-[0.25rem] flex-1 bg-gray-1 fixed inset-0 z-10">
+ <div class="flex flex-1 gap-3 items-center px-3">
+ <div class="flex-1 text-[13px] text-gray-11">Recording starting...</div>
+ <div class="relative w-5 h-5 text-red-300">
+ <svg class="absolute inset-0 w-5 h-5 -rotate-90" viewBox="0 0 20 20">
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.5"
+ opacity="0.2"
+ />
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.5"
+ stroke-dasharray={`${animation() * 50.265} 50.265`}
+ stroke-linecap="round"
+ class="transition-all duration-1000 ease-linear"
+ style={{
+ "transition-duration": `${props.from * 1000}ms`,
+ }}
+ />
+ </svg>
+ <span class="flex absolute inset-0 justify-center items-center text-[11px]">
+ {props.current}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index e0c7f03e1..81e6170fa 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -97,7 +97,6 @@ export function createOptionsQuery() {
);
createEventListener(window, "storage", (e) => {
- console.log(e);
if (e.key === PERSIST_KEY) setState(JSON.parse(e.newValue ?? "{}"));
});
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index c1c4df699..8b8ab9dae 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -259,6 +259,7 @@ editorStateChanged: EditorStateChanged,
newNotification: NewNotification,
newScreenshotAdded: NewScreenshotAdded,
newStudioRecordingAdded: NewStudioRecordingAdded,
+recordingEvent: RecordingEvent,
recordingOptionsChanged: RecordingOptionsChanged,
recordingStarted: RecordingStarted,
recordingStopped: RecordingStopped,
@@ -276,6 +277,7 @@ editorStateChanged: "editor-state-changed",
newNotification: "new-notification",
newScreenshotAdded: "new-screenshot-added",
newStudioRecordingAdded: "new-studio-recording-added",
+recordingEvent: "recording-event",
recordingOptionsChanged: "recording-options-changed",
recordingStarted: "recording-started",
recordingStopped: "recording-stopped",
@@ -339,7 +341,7 @@ export type ExportEstimates = { duration_seconds: number; estimated_time_seconds
export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings)
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;
+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
*/
@@ -370,6 +372,7 @@ export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; captions?: CaptionsData | null }
export type ProjectRecordingsMeta = { segments: SegmentRecordings[] }
+export type RecordingEvent = { variant: "Countdown"; value: number } | { variant: "Started" } | { variant: "Stopped" } | { variant: "Failed"; error: string }
export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null }
export type RecordingMetaWithType = ((StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null }) & { type: RecordingType }
export type RecordingMode = "studio" | "instant"
@@ -387,7 +390,7 @@ export type SegmentRecordings = { display: Video; camera: Video | null; mic: Aud
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: { position: [number, number] | null } } | "Upgrade" | "ModeSelect"
+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 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"