Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf: reuse backend media sort timestamps

Richie McIlroy9a48e3eb506d
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 825157c4f..fbb9eb0b0 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3793,10 +3793,11 @@ pub struct RecordingMetaWithMetadata {
pub status: StudioRecordingStatus,
// Number of recorded takes (segments) the recording is made up of.
pub clip_count: u32,
+ pub sort_time_millis: f64,
}
impl RecordingMetaWithMetadata {
- fn new(inner: RecordingMeta) -> Self {
+ fn new(inner: RecordingMeta, sort_time_millis: f64) -> Self {
Self {
mode: match &inner.inner {
RecordingMetaInner::Studio(_) => RecordingMode::Studio,
@@ -3829,11 +3830,19 @@ impl RecordingMetaWithMetadata {
StudioRecordingStatus::Complete
}
},
+ sort_time_millis,
inner,
}
}
}
+#[derive(Serialize, specta::Type)]
+pub struct ScreenshotMetaWithMetadata {
+ #[serde(flatten)]
+ pub inner: RecordingMeta,
+ pub sort_time_millis: f64,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Type, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FileType {
@@ -3848,8 +3857,9 @@ fn get_recording_meta(
path: PathBuf,
_file_type: FileType,
) -> Result<RecordingMetaWithMetadata, String> {
+ let sort_time_millis = media_sort_time_millis(&path);
RecordingMeta::load_for_project(&path)
- .map(RecordingMetaWithMetadata::new)
+ .map(|meta| RecordingMetaWithMetadata::new(meta, sort_time_millis))
.map_err(|e| format!("Failed to load recording meta: {e}"))
}
@@ -3864,6 +3874,14 @@ fn media_sort_time(path: &Path) -> SystemTime {
.unwrap_or(UNIX_EPOCH)
}
+fn media_sort_time_millis(path: &Path) -> f64 {
+ media_sort_time(path)
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs_f64()
+ * 1000.0
+}
+
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
@@ -3890,7 +3908,7 @@ fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithMeta
}
}
- result.sort_by_cached_key(|(path, _)| std::cmp::Reverse(media_sort_time(path)));
+ result.sort_by(|(_, a), (_, b)| b.sort_time_millis.total_cmp(&a.sort_time_millis));
Ok(result)
}
@@ -3945,7 +3963,7 @@ async fn delete_recording_directory(app: AppHandle, path: PathBuf) -> Result<(),
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
-fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, String> {
+fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, ScreenshotMetaWithMetadata)>, String> {
let screenshots_dir = screenshots_path(&app);
let mut result = std::fs::read_dir(&screenshots_dir)
@@ -3965,14 +3983,21 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Str
.find(|e| e.path().extension().and_then(|s| s.to_str()) == Some("png"))
.map(|e| e.path())?;
- Some((png_path, meta))
+ let sort_time_millis = media_sort_time_millis(&png_path);
+ Some((
+ png_path,
+ ScreenshotMetaWithMetadata {
+ inner: meta,
+ sort_time_millis,
+ },
+ ))
} else {
None
}
})
.collect::<Vec<_>>();
- result.sort_by_cached_key(|(path, _)| std::cmp::Reverse(media_sort_time(path)));
+ result.sort_by(|(_, a), (_, b)| b.sort_time_millis.total_cmp(&a.sort_time_millis));
Ok(result)
}
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
index 2d072cacc..c01e68f75 100644
--- a/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
@@ -18,8 +18,8 @@ import {
type CaptureDisplayWithThumbnail,
type CaptureWindowWithThumbnail,
commands,
- type RecordingMeta,
type RecordingMetaWithMetadata,
+ type ScreenshotMetaWithMetadata,
} from "~/utils/tauri";
import IconCapLink from "~icons/cap/link";
import IconCapTrash from "~icons/cap/trash";
@@ -35,7 +35,7 @@ import IconMdiMonitor from "~icons/mdi/monitor";
import IconPhWarningBold from "~icons/ph/warning-bold";
export type RecordingWithPath = RecordingMetaWithMetadata & { path: string };
-export type ScreenshotWithPath = RecordingMeta & { path: string };
+export type ScreenshotWithPath = ScreenshotMetaWithMetadata & { path: string };
function formatResolution(width?: number, height?: number) {
if (!width || !height) return undefined;
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
index c468f7382..fa3418853 100644
--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
@@ -19,7 +19,6 @@ import {
PhysicalPosition,
} from "@tauri-apps/api/window";
import * as dialog from "@tauri-apps/plugin-dialog";
-import { stat } from "@tauri-apps/plugin-fs";
import { relaunch } from "@tauri-apps/plugin-process";
import * as shell from "@tauri-apps/plugin-shell";
import { cx } from "cva";
@@ -2218,15 +2217,10 @@ function Page() {
.slice(0, RECENT_MEDIA_LIMIT)
.map((target) => ({ kind: "screenshot" as const, target })),
];
- const datedCandidates = await Promise.all(
- candidates.map(async (candidate) => {
- const fileInfo = await stat(candidate.target.path).catch(() => null);
- return {
- candidate,
- createdAt: (fileInfo?.birthtime ?? fileInfo?.mtime)?.getTime() ?? 0,
- };
- }),
- );
+ const datedCandidates = candidates.map((candidate) => ({
+ candidate,
+ createdAt: candidate.target.sort_time_millis,
+ }));
return datedCandidates
.sort((a, b) => b.createdAt - a.createdAt)
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 537e3f566..dd1ac221d 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -266,7 +266,7 @@ async saveFileDialog(fileName: string, fileType: string) : Promise<string | null
async listRecordings() : Promise<([string, RecordingMetaWithMetadata])[]> {
return await TAURI_INVOKE("list_recordings");
},
-async listScreenshots() : Promise<([string, RecordingMeta])[]> {
+async listScreenshots() : Promise<([string, ScreenshotMetaWithMetadata])[]> {
return await TAURI_INVOKE("list_screenshots");
},
async checkUpgradedAndUpdate() : Promise<boolean> {
@@ -862,7 +862,7 @@ export type RecordingDeleted = { path: string }
export type RecordingEvent = { variant: "Countdown"; value: number } | { variant: "Started" } | { variant: "Stopped" } | { variant: "Paused" } | { variant: "Resumed" } | { variant: "Failed"; error: string } | { variant: "StartFailed"; error: string } | { variant: "InputLost"; input: RecordingInputKind } | { variant: "InputRestored"; input: RecordingInputKind } | { variant: "Degraded"; reason: string } | { variant: "Recovered" }
export type RecordingInputKind = "microphone" | "camera"
export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }
-export type RecordingMetaWithMetadata = ((StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }) & { mode: RecordingMode; status: StudioRecordingStatus; clip_count: number }
+export type RecordingMetaWithMetadata = ((StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }) & { mode: RecordingMode; status: StudioRecordingStatus; clip_count: number; sort_time_millis: number }
export type RecordingMode = "studio" | "instant" | "screenshot"
export type RecordingOptionsChanged = null
export type RecordingSettingsStore = { target: ScreenCaptureTarget | null; micName: string | null; cameraId: DeviceOrModelID | null; mode: RecordingMode | null; systemAudio: boolean; organizationId: string | null; cameraDeviceSettings: { [key in string]: CameraDeviceSettings }; microphoneDeviceSettings: { [key in string]: MicrophoneDeviceSettings } }
@@ -891,6 +891,7 @@ export type SceneMode = "default" | "cameraOnly" | "hideCamera" | "splitScreen"
export type SceneSegment = { start: number; end: number; mode?: SceneMode; splitLayout?: SplitLayout | null; transitionIn?: number; transitionOut?: number }
export type ScreenCaptureTarget = { variant: "window"; id: WindowId } | { variant: "display"; id: DisplayId } | { variant: "area"; screen: DisplayId; bounds: LogicalBounds } | { variant: "cameraOnly" }
export type ScreenMovementSpring = { stiffness: number; damping: number; mass: number }
+export type ScreenshotMetaWithMetadata = ((StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }) & { sort_time_millis: number }
export type ScreenshotOcrLine = { text: string; confidence: number | null; bounds: ScreenshotOcrRegion }
export type ScreenshotOcrRegion = { x: number; y: number; width: number; height: number }
export type ScreenshotOcrResult = { text: string; lines: ScreenshotOcrLine[]; engine: string }