Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: prev recordings progress overlay + Editor reupload button

Richie McIlroyb262621d31ed
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index e14d899a3..cfb2767a3 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -353,7 +353,7 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result
if let Ok(Some(auth)) = AuthStore::get(&app) {
if auth.is_upgraded() {
// Pre-create the video and get the shareable link
- if let Ok(s3_config) = get_s3_config(&app, false).await {
+ if let Ok(s3_config) = get_s3_config(&app, false, None).await {
let link = web_api::make_url(format!("/s/{}", s3_config.id()));
state.pre_created_video = Some(PreCreatedVideo {
@@ -816,23 +816,25 @@ async fn get_rendered_video(
project: ProjectConfiguration,
) -> Result<PathBuf, String> {
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
-
- get_rendered_video_impl(editor_instance, project).await
+ get_rendered_video_impl(editor_instance, project, false).await
}
async fn get_rendered_video_impl(
editor_instance: Arc<EditorInstance>,
project: ProjectConfiguration,
+ force_render: bool,
) -> Result<PathBuf, String> {
let output_path = editor_instance
.project_path
.join("output")
.join("result.mp4");
- if !output_path.exists() {
- render_to_file_impl(&editor_instance, project, output_path.clone(), |_| {}).await?;
+ if !force_render && output_path.exists() {
+ return Ok(output_path);
}
+ render_to_file_impl(&editor_instance, project, output_path.clone(), |_| {}).await?;
+
Ok(output_path)
}
@@ -1301,7 +1303,7 @@ async fn copy_rendered_video_to_clipboard(
println!("copying");
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
- let output_path = match get_rendered_video_impl(editor_instance, project).await {
+ let output_path = match get_rendered_video_impl(editor_instance, project, false).await {
Ok(path) => {
println!("Successfully retrieved rendered video path: {:?}", path);
path
@@ -1761,21 +1763,16 @@ async fn upload_rendered_video(
// Check if user has an upgraded plan
if !auth.is_upgraded() {
- // Fetch and update plan information
match AuthStore::fetch_and_update_plan(&app).await {
- Ok(_) => {
- // Refresh auth information after update
- match AuthStore::get(&app) {
- Ok(Some(updated_auth)) => {
- auth = updated_auth;
- }
- Ok(None) => {
- // Auth was invalidated during plan check
- return Ok(UploadResult::NotAuthenticated);
- }
- Err(e) => return Err(format!("Failed to refresh auth: {}", e)),
+ Ok(_) => match AuthStore::get(&app) {
+ Ok(Some(updated_auth)) => {
+ auth = updated_auth;
}
- }
+ Ok(None) => {
+ return Ok(UploadResult::NotAuthenticated);
+ }
+ Err(e) => return Err(format!("Failed to refresh auth: {}", e)),
+ },
Err(e) => {
if e.contains("Authentication expired") {
return Ok(UploadResult::NotAuthenticated);
@@ -1793,99 +1790,91 @@ async fn upload_rendered_video(
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
let mut meta = editor_instance.meta();
- if let Some(sharing) = meta.sharing {
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
- Ok(UploadResult::Success(sharing.link))
- } else {
- // Emit initial rendering progress
- UploadProgress {
- stage: "rendering".to_string(),
- progress: 0.0,
- message: "Preparing video...".to_string(),
- }
- .emit(&app)
- .ok();
+ // Emit initial rendering progress
+ UploadProgress {
+ stage: "rendering".to_string(),
+ progress: 0.0,
+ message: "Preparing video...".to_string(),
+ }
+ .emit(&app)
+ .ok();
- let output_path = match get_rendered_video_impl(editor_instance.clone(), project).await {
- Ok(path) => {
- // Emit rendering complete
- UploadProgress {
- stage: "rendering".to_string(),
- progress: 1.0,
- message: "Rendering complete".to_string(),
- }
- .emit(&app)
- .ok();
- path
- }
- Err(e) => {
- notifications::send_notification(
- &app,
- notifications::NotificationType::UploadFailed,
- );
- return Err(format!("Failed to get rendered video: {}", e));
+ let output_path = match get_rendered_video_impl(editor_instance.clone(), project, false).await {
+ Ok(path) => {
+ // Emit rendering complete
+ UploadProgress {
+ stage: "rendering".to_string(),
+ progress: 1.0,
+ message: "Rendering complete".to_string(),
}
- };
-
- // Start upload progress
- UploadProgress {
- stage: "uploading".to_string(),
- progress: 0.0,
- message: "Starting upload...".to_string(),
+ .emit(&app)
+ .ok();
+ path
}
- .emit(&app)
- .ok();
+ Err(e) => {
+ notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
+ return Err(format!("Failed to get rendered video: {}", e));
+ }
+ };
- let result = match upload_video(
- &app,
- video_id.clone(),
- output_path,
- false,
- pre_created_video.map(|v| v.config),
- )
- .await
- {
- Ok(uploaded_video) => {
- // Emit upload complete
- UploadProgress {
- stage: "uploading".to_string(),
- progress: 1.0,
- message: "Upload complete!".to_string(),
- }
- .emit(&app)
- .ok();
+ // Start upload progress
+ UploadProgress {
+ stage: "uploading".to_string(),
+ progress: 0.0,
+ message: "Starting upload...".to_string(),
+ }
+ .emit(&app)
+ .ok();
- meta.sharing = Some(SharingMeta {
- link: uploaded_video.link.clone(),
- id: uploaded_video.id.clone(),
- });
- meta.save_for_project();
- RecordingMetaChanged { id: video_id }.emit(&app).ok();
+ let s3_config = if let Some(pre_created) = pre_created_video {
+ pre_created.config
+ } else {
+ get_s3_config(&app, false, None).await?
+ };
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
+ let result = match upload_video(
+ &app,
+ video_id.clone(),
+ output_path,
+ false,
+ Some(s3_config.clone()),
+ )
+ .await
+ {
+ Ok(uploaded_video) => {
+ // Emit upload complete
+ UploadProgress {
+ stage: "uploading".to_string(),
+ progress: 1.0,
+ message: "Upload complete!".to_string(),
+ }
+ .emit(&app)
+ .ok();
- #[cfg(target_os = "macos")]
- platform::write_string_to_pasteboard(&uploaded_video.link);
+ meta.sharing = Some(SharingMeta {
+ link: uploaded_video.link.clone(),
+ id: uploaded_video.id.clone(),
+ });
+ meta.save_for_project();
+ RecordingMetaChanged { id: video_id }.emit(&app).ok();
- Ok(UploadResult::Success(uploaded_video.link))
- }
- Err(e) => {
- notifications::send_notification(
- &app,
- notifications::NotificationType::UploadFailed,
- );
- Err(e)
- }
- };
+ notifications::send_notification(
+ &app,
+ notifications::NotificationType::ShareableLinkCopied,
+ );
- result
- }
+ #[cfg(target_os = "macos")]
+ platform::write_string_to_pasteboard(&uploaded_video.link);
+
+ Ok(UploadResult::Success(uploaded_video.link))
+ }
+ Err(e) => {
+ notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
+ Err(e)
+ }
+ };
+
+ result
}
#[tauri::command]
@@ -2466,6 +2455,7 @@ pub async fn run() {
seek_to,
send_feedback_request,
windows::position_traffic_lights,
+ reupload_rendered_video,
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2858,3 +2848,120 @@ async fn send_feedback_request(app: AppHandle, feedback: String) -> Result<(), S
Ok(())
}
+
+#[tauri::command]
+#[specta::specta]
+async fn reupload_rendered_video(
+ app: AppHandle,
+ video_id: String,
+ project: ProjectConfiguration,
+) -> Result<UploadResult, String> {
+ let Ok(Some(mut auth)) = AuthStore::get(&app) else {
+ AuthStore::set(&app, None).map_err(|e| e.to_string())?;
+ return Ok(UploadResult::NotAuthenticated);
+ };
+
+ // Check if user has an upgraded plan
+ if !auth.is_upgraded() {
+ match AuthStore::fetch_and_update_plan(&app).await {
+ Ok(_) => match AuthStore::get(&app) {
+ Ok(Some(updated_auth)) => {
+ auth = updated_auth;
+ }
+ Ok(None) => {
+ return Ok(UploadResult::NotAuthenticated);
+ }
+ Err(e) => return Err(format!("Failed to refresh auth: {}", e)),
+ },
+ Err(e) => {
+ if e.contains("Authentication expired") {
+ return Ok(UploadResult::NotAuthenticated);
+ }
+ return Ok(UploadResult::PlanCheckFailed);
+ }
+ }
+
+ if !auth.is_upgraded() {
+ open_upgrade_window(app).await;
+ return Ok(UploadResult::UpgradeRequired);
+ }
+ }
+
+ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
+ let meta = editor_instance.meta();
+
+ let Some(sharing) = meta.sharing.clone() else {
+ return Err("No sharing metadata found".to_string());
+ };
+
+ // Emit initial rendering progress
+ UploadProgress {
+ stage: "rendering".to_string(),
+ progress: 0.0,
+ message: "Preparing video...".to_string(),
+ }
+ .emit(&app)
+ .ok();
+
+ // Pass true to force_render to ensure we create a new video
+ let output_path = match get_rendered_video_impl(editor_instance.clone(), project, true).await {
+ Ok(path) => {
+ // Emit rendering complete
+ UploadProgress {
+ stage: "rendering".to_string(),
+ progress: 1.0,
+ message: "Rendering complete".to_string(),
+ }
+ .emit(&app)
+ .ok();
+ path
+ }
+ Err(e) => {
+ notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
+ return Err(format!("Failed to get rendered video: {}", e));
+ }
+ };
+
+ // Start upload progress
+ UploadProgress {
+ stage: "uploading".to_string(),
+ progress: 0.0,
+ message: "Starting upload...".to_string(),
+ }
+ .emit(&app)
+ .ok();
+
+ // Get S3 config with the existing video ID
+ let s3_config = get_s3_config(&app, false, Some(sharing.id)).await?;
+
+ let result = match upload_video(&app, video_id.clone(), output_path, false, Some(s3_config))
+ .await
+ {
+ Ok(uploaded_video) => {
+ // Emit upload complete
+ UploadProgress {
+ stage: "uploading".to_string(),
+ progress: 1.0,
+ message: "Upload complete!".to_string(),
+ }
+ .emit(&app)
+ .ok();
+
+ notifications::send_notification(
+ &app,
+ notifications::NotificationType::ShareableLinkCopied,
+ );
+
+ #[cfg(target_os = "macos")]
+ platform::write_string_to_pasteboard(&uploaded_video.link);
+
+ Ok(UploadResult::Success(sharing.link)) // Use existing sharing link
+ }
+ Err(e) => {
+ notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
+ Err(e)
+ }
+ };
+
+ result
+}
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 46ccdcc0b..3ddecdbf3 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -39,6 +39,15 @@ impl S3UploadMeta {
pub fn aws_bucket(&self) -> &str {
&self.aws_bucket
}
+
+ pub fn new(id: String, user_id: String, aws_region: String, aws_bucket: String) -> Self {
+ Self {
+ id,
+ user_id,
+ aws_region,
+ aws_bucket,
+ }
+ }
}
#[derive(serde::Serialize)]
@@ -114,7 +123,7 @@ pub async fn upload_video(
let client = reqwest::Client::new();
let s3_config = match existing_config {
Some(config) => config,
- None => get_s3_config(app, false).await?,
+ None => get_s3_config(app, false, Some(video_id)).await?,
};
let file_key = if is_individual {
@@ -278,8 +287,7 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploade
.to_string();
let client = reqwest::Client::new();
-
- let s3_config = get_s3_config(app, true).await?;
+ let s3_config = get_s3_config(app, true, None).await?;
let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);
@@ -345,8 +353,7 @@ pub async fn upload_audio(app: &AppHandle, file_path: PathBuf) -> Result<Uploade
.to_string();
let client = reqwest::Client::new();
-
- let s3_config = get_s3_config(app, false).await?;
+ let s3_config = get_s3_config(app, false, None).await?;
let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);
@@ -412,9 +419,18 @@ pub async fn upload_audio(app: &AppHandle, file_path: PathBuf) -> Result<Uploade
))
}
-pub async fn get_s3_config(app: &AppHandle, is_screenshot: bool) -> Result<S3UploadMeta, String> {
+pub async fn get_s3_config(
+ app: &AppHandle,
+ is_screenshot: bool,
+ video_id: Option<String>,
+) -> Result<S3UploadMeta, String> {
let origin = "http://tauri.localhost";
- let config_url = web_api::make_url(if is_screenshot {
+ let config_url = web_api::make_url(if let Some(id) = video_id {
+ format!(
+ "/api/desktop/video/create?origin={}&recordingMode=desktopMP4&videoId={}",
+ origin, id
+ )
+ } else if is_screenshot {
format!(
"/api/desktop/video/create?origin={}&recordingMode=desktopMP4&isScreenshot=true",
origin
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 1775e776a..13f15b249 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -20,6 +20,7 @@ import {
} from "solid-js";
import { createStore, produce } from "solid-js/store";
import { fetch } from "@tauri-apps/plugin-http";
+import { Tooltip } from "@kobalte/core";
import { authStore } from "~/store";
import { clientEnv } from "~/utils/env";
@@ -127,12 +128,41 @@ export default function () {
<div class="flex justify-center flex-col p-[1rem] gap-[0.75rem] text-[0.875rem] font-[400] bg-gray-50 h-full">
<div class="flex items-center justify-between pb-[0.25rem]">
<IconCapLogoFull class="w-[90px] h-auto" />
- <button
- type="button"
- onClick={() => commands.openSettingsWindow("general")}
- >
- <IconCapSettings class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" />
- </button>
+ <div class="flex items-center space-x-2">
+ <Tooltip.Root openDelay={0}>
+ <Tooltip.Trigger>
+ <button
+ type="button"
+ onClick={() => commands.openSettingsWindow("recordings")}
+ >
+ <IconLucideSquarePlay class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" />
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">
+ Previous Recordings
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+
+ <Tooltip.Root openDelay={0}>
+ <Tooltip.Trigger>
+ <button
+ type="button"
+ onClick={() => commands.openSettingsWindow("general")}
+ >
+ <IconCapSettings class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" />
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">
+ Settings
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </div>
</div>
<TargetSelects options={options.data} />
<CameraSelect options={options.data} setOptions={setOptions} />
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index ba8244268..2a21af58d 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -23,7 +23,7 @@ export default function Settings(props: RouteSectionProps) {
{
href: "recordings",
name: "Previous Recordings",
- icon: IconLucideVideo,
+ icon: IconLucideSquarePlay,
},
{
href: "screenshots",
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 76bb0fa04..262b6854a 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -10,11 +10,18 @@ import {
} from "solid-js";
import { type as ostype } from "@tauri-apps/plugin-os";
import { createStore, reconcile } from "solid-js/store";
+import { Tooltip } from "@kobalte/core";
import { type RenderProgress, commands } from "~/utils/tauri";
import { useEditorContext } from "./context";
import { Dialog, DialogContent } from "./ui";
+import {
+ ProgressState,
+ progressState,
+ setProgressState,
+} from "~/store/progress";
+import { events } from "~/utils/tauri";
export function Header() {
let unlistenTitlebar: () => void | undefined;
@@ -47,7 +54,135 @@ export function Header() {
</div>
);
- return <Titlebar />;
+ return (
+ <>
+ <Titlebar />
+ <Dialog.Root
+ open={progressState.type !== "idle"}
+ onOpenChange={() => {}} // Empty handler prevents closing
+ >
+ <DialogContent
+ title={
+ progressState.type === "copying"
+ ? "Link Copied"
+ : progressState.type === "uploading"
+ ? "Creating Shareable Link"
+ : "Exporting Recording"
+ }
+ confirm={<></>}
+ >
+ <Switch>
+ <Match when={progressState.type === "copying"}>
+ {(when) => {
+ const state = progressState as Extract<
+ ProgressState,
+ { type: "copying" }
+ >;
+ return (
+ <div class="w-[80%] text-center mx-auto">
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Copying to clipboard"}
+ </h3>
+
+ <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
+ <div
+ class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"
+ style={{
+ width: `${
+ state.stage === "rendering"
+ ? Math.min(
+ ((state.renderProgress || 0) /
+ (state.totalFrames || 1)) *
+ 100,
+ 100
+ )
+ : Math.min(state.progress || 0, 100)
+ }%`,
+ }}
+ />
+ </div>
+
+ <p class="text-xs text-gray-50 mt-2">{state.message}</p>
+ </div>
+ );
+ }}
+ </Match>
+ <Match when={progressState.type === "saving"}>
+ {(when) => {
+ const state = progressState as Extract<
+ ProgressState,
+ { type: "saving" }
+ >;
+ return (
+ <div class="w-[80%] text-center mx-auto">
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Saving file"}
+ </h3>
+
+ <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
+ <div
+ class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"
+ style={{
+ width: `${
+ state.stage === "rendering"
+ ? Math.min(
+ ((state.renderProgress || 0) /
+ (state.totalFrames || 1)) *
+ 100,
+ 100
+ )
+ : Math.min(state.progress || 0, 100)
+ }%`,
+ }}
+ />
+ </div>
+
+ <p class="text-xs text-gray-50 mt-2">{state.message}</p>
+ </div>
+ );
+ }}
+ </Match>
+ <Match when={progressState.type === "uploading"}>
+ {(when) => {
+ const state = progressState as Extract<
+ ProgressState,
+ { type: "uploading" }
+ >;
+ return (
+ <div class="w-[80%] text-center mx-auto">
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Creating shareable link"}
+ </h3>
+
+ <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
+ <div
+ class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"
+ style={{
+ width: `${
+ state.stage === "rendering"
+ ? Math.min(state.renderProgress || 0, 100)
+ : Math.min(state.uploadProgress || 0, 100)
+ }%`,
+ }}
+ />
+ </div>
+
+ <p class="text-xs text-gray-50 mt-2">{state.message}</p>
+ </div>
+ );
+ }}
+ </Match>
+ </Switch>
+ </DialogContent>
+ </Dialog.Root>
+ </>
+ );
}
import { Channel } from "@tauri-apps/api/core";
@@ -60,14 +195,6 @@ import { initializeTitlebar, setTitlebar } from "~/utils/titlebar-state";
function ExportButton() {
const { videoId, project, prettyName } = useEditorContext();
- const [state, setState] = createStore<
- | { open: false; type: "idle" }
- | ({ open: boolean } & (
- | { type: "inProgress"; progress: number; totalFrames: number }
- | { type: "finished"; path: string }
- ))
- >({ open: false, type: "idle" });
-
return (
<>
<Button
@@ -80,110 +207,166 @@ function ExportButton() {
}).then((p) => {
if (!p) return;
- setState(
- reconcile({
- open: true,
- type: "inProgress",
- progress: 0,
- totalFrames: 0,
- })
- );
+ setProgressState({
+ type: "saving",
+ progress: 0,
+ renderProgress: 0,
+ totalFrames: 0,
+ message: "Preparing to render...",
+ mediaPath: p,
+ stage: "rendering",
+ });
const progress = new Channel<RenderProgress>();
progress.onmessage = (p) => {
- if (p.type === "FrameRendered" && state.type === "inProgress")
- setState({ progress: p.current_frame });
+ if (
+ p.type === "FrameRendered" &&
+ progressState.type === "saving"
+ ) {
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
+ });
+ }
if (
p.type === "EstimatedTotalFrames" &&
- state.type === "inProgress"
+ progressState.type === "saving"
) {
- console.log("Total frames: ", p.total_frames);
- setState({ totalFrames: p.total_frames });
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
}
};
return commands
.renderToFile(p, videoId, project, progress)
.then(() => {
- setState({ ...state, type: "finished", path: p });
+ setProgressState({
+ type: "saving",
+ progress: 100,
+ message: "Saved successfully!",
+ mediaPath: p,
+ });
+
+ setTimeout(() => {
+ setProgressState({ type: "idle" });
+ }, 1500);
});
});
}}
>
Export
</Button>
- <Dialog.Root
- open={state.open}
- onOpenChange={(o) => {
- if (state.type !== "inProgress" && !o) {
- setState(reconcile({ ...state, open: false }));
- }
- }}
- >
- <DialogContent
- title="Export Recording"
- confirm={
- <Show when={state.type === "finished" && state}>
- {(state) => (
- <Button
- onClick={() => {
- commands.openInFinder(state().path);
- }}
- >
- Open in Finder
- </Button>
- )}
- </Show>
- }
- >
- <Switch>
- <Match when={state.type === "finished"}>Finished exporting</Match>
- <Match when={state.type === "inProgress" && state}>
- {(state) => (
- <>
- <div class="w-full bg-gray-200 rounded-full h-2.5">
- <div
- class="bg-blue-300 h-2.5 rounded-full"
- style={{
- width: `${Math.min(
- (state().progress / (state().totalFrames || 1)) * 100,
- 100
- )}%`,
- }}
- />
- </div>
- </>
- )}
- </Match>
- </Switch>
- </DialogContent>
- </Dialog.Root>
</>
);
}
function ShareButton() {
const { videoId, project, presets } = useEditorContext();
- const [meta, metaActions] = createResource(() =>
+ const [recordingMeta, metaActions] = createResource(() =>
commands.getRecordingMeta(videoId, "recording")
);
const uploadVideo = createMutation(() => ({
mutationFn: async () => {
- await commands.uploadRenderedVideo(
- videoId,
- project
- ? project
- : presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
- null
+ if (!recordingMeta()) return;
+
+ if (recordingMeta()?.sharing) {
+ // Use reupload for existing shares
+ return await commands.reuploadRenderedVideo(
+ videoId,
+ project
+ ? project
+ : presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ );
+ }
+
+ setProgressState({
+ type: "uploading",
+ renderProgress: 0,
+ uploadProgress: 0,
+ message: "Preparing to render...",
+ mediaPath: videoId,
+ stage: "rendering",
+ totalFrames: 0,
+ });
+
+ // Listen for upload progress events
+ const unlisten = await events.uploadProgress.listen(
+ (event: {
+ payload: { stage: string; progress: number; message: string };
+ }) => {
+ if (progressState.type === "uploading") {
+ if (event.payload.stage === "rendering") {
+ setProgressState({
+ type: "uploading",
+ renderProgress: Math.round(event.payload.progress * 100),
+ uploadProgress: 0,
+ message: event.payload.message,
+ mediaPath: videoId,
+ stage: "rendering",
+ totalFrames: progressState.totalFrames,
+ });
+ } else {
+ setProgressState({
+ type: "uploading",
+ renderProgress: 100,
+ uploadProgress: Math.round(event.payload.progress * 100),
+ message: event.payload.message,
+ mediaPath: videoId,
+ stage: "uploading",
+ totalFrames: progressState.totalFrames,
+ });
+ }
+ }
+ }
);
+
+ try {
+ const result = await commands.uploadRenderedVideo(
+ videoId,
+ project
+ ? project
+ : presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
+ null
+ );
+
+ unlisten();
+
+ if (result === "NotAuthenticated") {
+ throw new Error("Not authenticated");
+ }
+ if (result === "PlanCheckFailed") {
+ throw new Error("Plan check failed");
+ }
+ if (result === "UpgradeRequired") {
+ throw new Error("Upgrade required");
+ }
+
+ return result;
+ } catch (error) {
+ unlisten();
+ setProgressState({ type: "idle" });
+ throw error;
+ }
+ },
+ onSuccess: () => {
+ metaActions.refetch();
+ // Don't immediately set to idle - let the progress show for a moment
+ setTimeout(() => {
+ setProgressState({ type: "idle" });
+ }, 1500);
+ },
+ onError: (error) => {
+ console.error("Upload error:", error);
+ setProgressState({ type: "idle" });
},
- onSuccess: () => metaActions.refetch(),
}));
return (
<Show
- when={meta()?.sharing}
+ when={recordingMeta()?.sharing}
fallback={
<Button
disabled={uploadVideo.isPending}
@@ -206,17 +389,43 @@ function ShareButton() {
const url = () => new URL(sharing().link);
return (
- <a
- class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"
- href={sharing().link}
- target="_blank"
- rel="noreferrer"
- >
- <span class="text-[0.875rem] text-gray-500">
- {url().host}
- {url().pathname}
- </span>
- </a>
+ <div class="flex flex-row items-center gap-2">
+ <Tooltip.Root openDelay={0} closeDelay={0}>
+ <Tooltip.Trigger>
+ <Button
+ disabled={uploadVideo.isPending}
+ onClick={() => uploadVideo.mutate()}
+ variant="secondary"
+ class="flex items-center space-x-1"
+ >
+ {uploadVideo.isPending ? (
+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />
+ ) : (
+ <IconLucideRotateCcw class="size-[1rem]" />
+ )}
+ </Button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">
+ {uploadVideo.isPending
+ ? "Reuploading video"
+ : "Reupload video"}
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ <a
+ class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"
+ href={sharing().link}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <span class="text-[0.875rem] text-gray-500">
+ {url().host}
+ {url().pathname}
+ </span>
+ </a>
+ </div>
);
}}
</Show>
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index 4c2b7e283..509be368d 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -21,12 +21,20 @@ import Tooltip from "@corvu/tooltip";
import { Button } from "@cap/ui-solid";
import { createElementBounds } from "@solid-primitives/bounds";
import { TransitionGroup } from "solid-transition-group";
-import { createStore, produce } from "solid-js/store";
import { makePersisted } from "@solid-primitives/storage";
+import { Channel } from "@tauri-apps/api/core";
-import { commands, events, Result, UploadResult } from "~/utils/tauri";
+import {
+ commands,
+ events,
+ Result,
+ UploadResult,
+ type RenderProgress,
+} from "~/utils/tauri";
import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";
import { createPresets } from "~/utils/createPresets";
+import { progressState, setProgressState } from "~/store/progress";
+import { createStore, produce } from "solid-js/store";
type MediaEntry = {
path: string;
@@ -35,26 +43,6 @@ type MediaEntry = {
type?: "recording" | "screenshot";
};
-type ProgressState =
- | {
- type: "idle";
- }
- | {
- type: "copying" | "saving";
- progress: number;
- message: string;
- mediaPath?: string;
- stage?: "rendering";
- }
- | {
- type: "uploading";
- renderProgress: number;
- uploadProgress: number;
- message: string;
- mediaPath?: string;
- stage: "rendering" | "uploading";
- };
-
export default function () {
const presets = createPresets();
const [recordings, setRecordings] = makePersisted(
@@ -65,12 +53,12 @@ export default function () {
createStore<MediaEntry[]>([]),
{ name: "screenshots-store" }
);
- const [progressState, setProgressState] = createStore<ProgressState>({
- type: "idle",
- });
onMount(async () => {
+ console.log("Setting up event listeners");
+
const unlisten = await events.uploadProgress.listen((event) => {
+ console.log("Upload progress event:", event.payload);
if (progressState.type === "uploading") {
if (event.payload.stage === "rendering") {
setProgressState({
@@ -94,13 +82,14 @@ export default function () {
if (event.payload.progress === 1) {
setTimeout(() => {
setProgressState({ type: "idle" });
- }, 1000);
+ }, 1500);
}
}
}
});
onCleanup(() => {
+ console.log("Cleaning up event listeners");
unlisten();
});
});
@@ -188,6 +177,8 @@ export default function () {
setProgressState({
type: "copying",
progress: 0,
+ renderProgress: 0,
+ totalFrames: 0,
message: "Preparing to render...",
mediaPath: media.path,
stage: "rendering",
@@ -195,15 +186,66 @@ export default function () {
try {
if (isRecording) {
- await commands.getRenderedVideo(
+ const output_path = await commands.getRenderedVideo(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
);
- await commands.copyRenderedVideoToClipboard(
- mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
+ if (output_path) {
+ await commands.copyRenderedVideoToClipboard(
+ mediaId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ );
+ } else {
+ console.log("Setting up render progress channel");
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ console.log("Progress channel message:", p);
+ if (
+ p.type === "FrameRendered" &&
+ progressState.type === "copying"
+ ) {
+ console.log(
+ "Frame rendered in copy:",
+ p.current_frame,
+ "Current state:",
+ progressState
+ );
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
+ });
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "copying"
+ ) {
+ console.log(
+ "Got total frames in copy:",
+ p.total_frames
+ );
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
+ }
+ };
+
+ console.log("Starting render to file");
+ await commands.renderToFile(
+ output_path,
+ mediaId,
+ presets.getDefaultConfig() ??
+ DEFAULT_PROJECT_CONFIG,
+ progress
+ );
+ console.log("Render to file completed");
+
+ await commands.copyRenderedVideoToClipboard(
+ mediaId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ );
+ }
} else {
await commands.copyScreenshotToClipboard(media.path);
}
@@ -217,8 +259,9 @@ export default function () {
setTimeout(() => {
setProgressState({ type: "idle" });
- }, 1000);
+ }, 1500);
} catch (error) {
+ console.error("Error in copy media:", error);
setProgressState({ type: "idle" });
throw error;
}
@@ -230,6 +273,8 @@ export default function () {
setProgressState({
type: "saving",
progress: 0,
+ renderProgress: 0,
+ totalFrames: 0,
message: "Preparing to render...",
mediaPath: media.path,
stage: "rendering",
@@ -264,16 +309,42 @@ export default function () {
}
if (isRecording) {
- const renderedPath = await commands.getRenderedVideo(
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ if (
+ p.type === "FrameRendered" &&
+ progressState.type === "saving"
+ ) {
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
+ });
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "saving"
+ ) {
+ console.log("Total frames: ", p.total_frames);
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
+ }
+ };
+
+ const output_path = await commands.getRenderedVideo(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
);
- if (!renderedPath) {
- throw new Error("Failed to get rendered video path");
- }
+ await commands.renderToFile(
+ output_path,
+ mediaId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
+ progress
+ );
- await commands.copyFileToPath(renderedPath, savePath);
+ await commands.copyFileToPath(output_path, savePath);
} else {
await commands.copyFileToPath(media.path, savePath);
}
@@ -287,7 +358,7 @@ export default function () {
setTimeout(() => {
setProgressState({ type: "idle" });
- }, 1000);
+ }, 1500);
return true;
} catch (error) {
@@ -308,7 +379,7 @@ export default function () {
setTimeout(() => {
setProgressState({ type: "idle" });
- }, 1000);
+ }, 1500);
return;
}
@@ -325,11 +396,55 @@ export default function () {
try {
let res: UploadResult;
if (isRecording) {
- await commands.getRenderedVideo(
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ console.log("Upload render progress:", p);
+ if (
+ p.type === "FrameRendered" &&
+ progressState.type === "uploading"
+ ) {
+ console.log(
+ "Frame rendered in upload:",
+ p.current_frame,
+ "Current state:",
+ progressState
+ );
+ setProgressState({
+ ...progressState,
+ renderProgress: Math.round(
+ (p.current_frame /
+ (progressState.totalFrames || 1)) *
+ 100
+ ),
+ });
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "uploading"
+ ) {
+ console.log(
+ "Got total frames in upload:",
+ p.total_frames
+ );
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
+ }
+ };
+
+ const output_path = await commands.getRenderedVideo(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
);
+ await commands.renderToFile(
+ output_path,
+ mediaId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
+ progress
+ );
+
res = await commands.uploadRenderedVideo(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
@@ -441,36 +556,75 @@ export default function () {
<Match
when={progressState.type === "copying"}
>
- {progressState.stage === "rendering"
- ? "Rendering video"
- : "Copying to clipboard"}
+ {(state) => (
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Copying to clipboard"}
+ </h3>
+ )}
</Match>
<Match when={progressState.type === "saving"}>
- {progressState.stage === "rendering"
- ? "Rendering video"
- : "Saving file"}
+ {(state) => (
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Saving file"}
+ </h3>
+ )}
</Match>
<Match
when={progressState.type === "uploading"}
>
- {progressState.stage === "rendering"
- ? "Rendering video"
- : "Creating shareable link"}
+ {(state) => (
+ <h3 class="text-sm font-medium mb-3 text-gray-50">
+ {state.stage === "rendering"
+ ? "Rendering video"
+ : "Creating shareable link"}
+ </h3>
+ )}
</Match>
</Switch>
</h3>
- <div class="w-full bg-gray-700 rounded-full h-1.5 mb-2">
+ <div class="w-full bg-gray-200/20 rounded-full h-2.5 mb-2">
<div
- class="bg-blue-300 h-1.5 rounded-full transition-all duration-200"
+ class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"
style={{
- width: `${
- progressState.type === "uploading"
- ? progressState.stage === "rendering"
- ? progressState.renderProgress
- : progressState.uploadProgress
- : progressState.progress
- }%`,
+ width: `${(() => {
+ if (
+ !progressState ||
+ progressState.type === "idle"
+ )
+ return 0;
+
+ if (progressState.type === "uploading") {
+ return progressState.stage ===
+ "rendering"
+ ? Math.min(
+ progressState.renderProgress || 0,
+ 100
+ )
+ : Math.min(
+ progressState.uploadProgress || 0,
+ 100
+ );
+ }
+
+ if (progressState.stage === "rendering") {
+ return Math.min(
+ ((progressState.renderProgress || 0) /
+ (progressState.totalFrames || 1)) *
+ 100,
+ 100
+ );
+ }
+
+ return Math.min(
+ progressState.progress || 0,
+ 100
+ );
+ })()}%`,
}}
/>
</div>
@@ -556,7 +710,6 @@ export default function () {
? "Copying to Clipboard"
: "Copy to Clipboard"
}
- forceOpen={copyMedia.isPending}
tooltipPlacement="left"
onClick={() => copyMedia.mutate()}
disabled={
@@ -593,7 +746,6 @@ export default function () {
? "Upgrade Required"
: "Create Shareable Link"
}
- forceOpen={showUpgradeTooltip()}
tooltipPlacement="left"
onClick={() => {
uploadMedia.mutate(undefined, {
@@ -719,7 +871,6 @@ const TooltipIconButton = (
props: ComponentProps<"button"> & {
tooltipText: string;
tooltipPlacement: string;
- forceOpen?: boolean;
}
) => {
const [isOpen, setIsOpen] = createSignal(false);
@@ -729,7 +880,7 @@ const TooltipIconButton = (
placement={props.tooltipPlacement as "top" | "bottom" | "left" | "right"}
openDelay={0}
closeDelay={0}
- open={props.forceOpen || isOpen()}
+ open={isOpen()}
onOpenChange={setIsOpen}
hoverableContent={false}
floatingOptions={{
diff --git a/apps/desktop/src/store/progress.ts b/apps/desktop/src/store/progress.ts
new file mode 100644
index 000000000..b11e3ce18
--- /dev/null
+++ b/apps/desktop/src/store/progress.ts
@@ -0,0 +1,39 @@
+import { createStore } from "solid-js/store";
+
+export type ProgressState =
+ | {
+ type: "idle";
+ }
+ | {
+ type: "copying";
+ progress: number;
+ message: string;
+ mediaPath?: string;
+ stage: "rendering" | undefined;
+ renderProgress?: number;
+ totalFrames?: number;
+ }
+ | {
+ type: "saving";
+ progress: number;
+ message: string;
+ mediaPath?: string;
+ stage: "rendering" | undefined;
+ renderProgress?: number;
+ totalFrames?: number;
+ }
+ | {
+ type: "uploading";
+ renderProgress: number;
+ uploadProgress: number;
+ message: string;
+ mediaPath?: string;
+ stage: "rendering" | "uploading";
+ totalFrames?: number;
+ };
+
+const [progressState, setProgressState] = createStore<ProgressState>({
+ type: "idle",
+});
+
+export { progressState, setProgressState };
\ No newline at end of file
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 82fc6d6a0..9b595ced1 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -163,6 +163,9 @@ async sendFeedbackRequest(feedback: string) : Promise<null> {
},
async positionTrafficLights(controlsInset: [number, number] | null) : Promise<void> {
await TAURI_INVOKE("position_traffic_lights", { controlsInset });
+},
+async reuploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<UploadResult> {
+ return await TAURI_INVOKE("reupload_rendered_video", { videoId, project });
}
}
diff --git a/apps/web/app/api/desktop/video/create/route.ts b/apps/web/app/api/desktop/video/create/route.ts
index ff360abd9..978f6ff8d 100644
--- a/apps/web/app/api/desktop/video/create/route.ts
+++ b/apps/web/app/api/desktop/video/create/route.ts
@@ -95,6 +95,55 @@ export async function GET(req: NextRequest) {
month: "long",
})} ${date.getFullYear()}`;
+ const videoId = params.get("videoId");
+
+ if (videoId) {
+ const [video] = await db
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+
+ if (!video) {
+ return new Response(JSON.stringify({ error: "Video not found" }), {
+ status: 404,
+ headers: {
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, sentry-trace, baggage",
+ },
+ });
+ }
+
+ return new Response(
+ JSON.stringify({
+ id: video.id,
+ user_id: user.id,
+ aws_region: video.awsRegion,
+ aws_bucket: video.awsBucket,
+ }),
+ {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, sentry-trace, baggage",
+ },
+ }
+ );
+ }
+
await db.insert(videos).values({
id: id,
name: `Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`,
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index d71ef69e0..f8407a2c2 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -54,7 +54,9 @@ declare global {
const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']
const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']
const IconLucideRabbit: typeof import('~icons/lucide/rabbit.jsx')['default']
+ const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
+ const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']
const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']