Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve captures panel

Brendan Allan82abdbcfeb96
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
index 24a3f6e46..14e499801 100644
--- a/apps/desktop-solid/src-tauri/src/display.rs
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -1,8 +1,4 @@
-use std::{
- io::Write,
- path::{Path, PathBuf},
- sync::atomic::Ordering,
-};
+use std::{io::Write, path::PathBuf, sync::atomic::Ordering};
use scap::{
capturer::{Area, Capturer, Options, Point, Resolution, Size},
@@ -12,10 +8,15 @@ use scap::{
use serde::{Deserialize, Serialize};
use specta::Type;
-use crate::{
- ffmpeg::{FFmpegRawVideoInput, NamedPipeCapture},
- macos, Bounds,
-};
+use crate::{ffmpeg::NamedPipeCapture, macos};
+
+#[derive(Type, Serialize, Deserialize, Debug, Clone)]
+pub struct Bounds {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
#[derive(Type, Serialize)]
pub struct CaptureWindow {
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 90dd1f508..566ae3616 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -8,16 +8,11 @@ mod utils;
use objc2_app_kit::{NSPopUpMenuWindowLevel, NSScreenSaverWindowLevel};
use recording::{DisplaySource, InProgressRecording};
// use macos::Bounds;
-use scap::Target;
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
use std::{
- collections::HashMap,
- marker::PhantomData,
- path::PathBuf,
- process::{Command, Stdio},
- sync::Arc,
+ collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
time::Duration,
};
use tauri::{AppHandle, Manager, State, WebviewWindow};
@@ -27,7 +22,7 @@ use tauri_specta::Event;
use tokio::{sync::RwLock, time::sleep};
use camera::{create_camera_window, get_cameras};
-use display::{get_capture_windows, CaptureTarget};
+use display::{get_capture_windows, Bounds, CaptureTarget};
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -38,25 +33,108 @@ pub struct RecordingOptions {
#[derive(specta::Type, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct AppState {
+pub struct App {
start_recording_options: RecordingOptions,
#[serde(skip)]
+ handle: AppHandle,
+ #[serde(skip)]
current_recording: Option<InProgressRecording>,
prev_recordings: Vec<PathBuf>,
}
+const WINDOW_CAPTURE_OCCLUDER_LABEL: &str = "window-capture-occluder";
+
+impl App {
+ pub fn set_current_recording(&mut self, new_value: InProgressRecording) {
+ let current_recording = self.current_recording.insert(new_value);
+
+ if let DisplaySource::Window { .. } = &current_recording.display_source {
+ match self
+ .handle
+ .get_webview_window(WINDOW_CAPTURE_OCCLUDER_LABEL)
+ {
+ None => {
+ let monitor = self.handle.primary_monitor().unwrap().unwrap();
+
+ let occluder_window = WebviewWindow::builder(
+ &self.handle,
+ WINDOW_CAPTURE_OCCLUDER_LABEL,
+ tauri::WebviewUrl::App("/window-capture-occluder".into()),
+ )
+ .title("Cap Window Capture Occluder")
+ .maximized(false)
+ .resizable(false)
+ .fullscreen(false)
+ .decorations(false)
+ .shadow(false)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true)
+ .content_protected(true)
+ .inner_size(
+ monitor.size().width as f64 / monitor.scale_factor(),
+ monitor.size().height as f64 / monitor.scale_factor(),
+ )
+ .position(0.0, 0.0)
+ .build()
+ .unwrap();
+
+ occluder_window
+ .set_window_level(NSScreenSaverWindowLevel as u32)
+ .unwrap();
+ occluder_window.set_ignore_cursor_events(true).unwrap();
+ occluder_window.make_transparent().unwrap();
+ }
+ Some(w) => {
+ w.show();
+ }
+ }
+ } else {
+ self.close_occluder_window();
+ }
+ }
+
+ pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
+ self.close_occluder_window();
+
+ self.current_recording.take()
+ }
+
+ fn close_occluder_window(&self) {
+ self.handle
+ .get_webview_window(WINDOW_CAPTURE_OCCLUDER_LABEL)
+ .map(|window| window.close().ok());
+ }
+
+ fn set_start_recording_options(&mut self, new_value: RecordingOptions) {
+ self.start_recording_options = new_value;
+ let options = &self.start_recording_options;
+
+ match self.handle.get_webview_window(camera::WINDOW_LABEL) {
+ Some(window) if options.camera_label.is_none() => {
+ window.close().ok();
+ }
+ None if options.camera_label.is_some() => {
+ create_camera_window(self.handle.clone());
+ }
+ _ => {}
+ };
+
+ RecordingOptionsChanged.emit(&self.handle).ok();
+ }
+}
+
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
pub struct RecordingOptionsChanged;
// dedicated event + command used as panel must be accessed on main thread
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
-pub struct FocusCapturesPanel;
+pub struct ShowCapturesPanel;
type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;
#[tauri::command]
#[specta::specta]
-async fn get_recording_options(state: MutableState<'_, AppState>) -> Result<RecordingOptions, ()> {
+async fn get_recording_options(state: MutableState<'_, App>) -> Result<RecordingOptions, ()> {
let state = state.read().await;
Ok(state.start_recording_options.clone())
}
@@ -64,14 +142,10 @@ async fn get_recording_options(state: MutableState<'_, AppState>) -> Result<Reco
#[tauri::command]
#[specta::specta]
async fn set_recording_options(
- app: AppHandle,
- state: MutableState<'_, AppState>,
+ state: MutableState<'_, App>,
options: RecordingOptions,
) -> Result<(), ()> {
- let mut state = state.write().await;
- state.start_recording_options = options;
-
- on_recording_options_change(&app, &state.start_recording_options);
+ state.write().await.set_start_recording_options(options);
Ok(())
}
@@ -93,7 +167,7 @@ impl<T: Serialize> JsonValue<T> {
#[tauri::command]
#[specta::specta]
async fn get_current_recording(
- state: MutableState<'_, AppState>,
+ state: MutableState<'_, App>,
) -> Result<JsonValue<Option<InProgressRecording>>, ()> {
let state = state.read().await;
Ok(JsonValue::new(&state.current_recording))
@@ -101,18 +175,15 @@ async fn get_current_recording(
#[tauri::command]
#[specta::specta]
-async fn get_prev_recordings(state: MutableState<'_, AppState>) -> Result<Vec<PathBuf>, ()> {
+async fn get_prev_recordings(state: MutableState<'_, App>) -> Result<Vec<PathBuf>, ()> {
let state = state.read().await;
Ok(state.prev_recordings.clone())
}
#[tauri::command]
#[specta::specta]
-async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> Result<(), String> {
+async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
- let recording_options = &state.start_recording_options;
-
- dbg!(&recording_options);
let id = uuid::Uuid::new_v4().to_string();
@@ -123,50 +194,18 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> R
.join("recordings")
.join(format!("{id}.cap"));
- let current_recording = recording::start(recording_dir, recording_options).await;
- let current_recording = state.current_recording.insert(current_recording);
-
- if let DisplaySource::Window { .. } = &current_recording.display_source {
- let monitor = app.primary_monitor().unwrap().unwrap();
-
- let occluder_window = WebviewWindow::builder(
- &app,
- "window-capture-occluder",
- tauri::WebviewUrl::App("/window-capture-occluder".into()),
- )
- .title("Cap Window Capture Occluder")
- .maximized(false)
- .resizable(false)
- .fullscreen(false)
- .decorations(false)
- .shadow(false)
- .always_on_top(true)
- .visible_on_all_workspaces(true)
- .content_protected(true)
- .inner_size(
- monitor.size().width as f64 / monitor.scale_factor(),
- monitor.size().height as f64 / monitor.scale_factor(),
- )
- .position(0.0, 0.0)
- .build()
- .unwrap();
-
- occluder_window
- .set_window_level(NSScreenSaverWindowLevel as u32)
- .unwrap();
- occluder_window.set_ignore_cursor_events(true).unwrap();
- occluder_window.make_transparent().unwrap();
- }
+ let recording = recording::start(recording_dir, &state.start_recording_options).await;
+ state.set_current_recording(recording);
Ok(())
}
#[tauri::command]
#[specta::specta]
-async fn stop_recording(app: AppHandle, state: MutableState<'_, AppState>) -> Result<(), String> {
+async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
- let Some(mut current_recording) = state.current_recording.take() else {
+ let Some(mut current_recording) = state.clear_current_recording() else {
return Err("Recording not in progress".to_string());
};
@@ -184,35 +223,18 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, AppState>) -> Re
.recording_dir
.join("screenshots/display.jpg"),
)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
.output()
.unwrap();
state.prev_recordings.push(current_recording.recording_dir);
- show_previous_recordings_window(app);
+ ShowCapturesPanel.emit(&app);
Ok(())
}
-#[tauri::command]
-#[specta::specta]
-fn open_previous_recordings_window(app: AppHandle) {
- show_previous_recordings_window(app);
-}
-
struct FakeWindowBounds(pub Arc<RwLock<HashMap<String, HashMap<String, Bounds>>>>);
-#[derive(Type, Serialize, Deserialize, Debug, Clone)]
-struct Bounds {
- pub x: f64,
- pub y: f64,
- pub width: f64,
- pub height: f64,
-}
-
#[tauri::command]
#[specta::specta]
async fn set_fake_window_bounds(
@@ -252,6 +274,8 @@ async fn remove_fake_window(
const PREV_RECORDINGS_WINDOW: &str = "prev-recordings";
+#[tauri::command]
+#[specta::specta]
fn show_previous_recordings_window(app: AppHandle) {
if let Some(window) = app.get_webview_window(PREV_RECORDINGS_WINDOW) {
window.show().ok();
@@ -337,7 +361,7 @@ fn show_previous_recordings_window(app: AppHandle) {
&& mouse_position.y <= y_max
{
ignore = false;
- FocusCapturesPanel.emit(&app).ok();
+ ShowCapturesPanel.emit(&app).ok();
break;
}
}
@@ -380,7 +404,7 @@ pub fn run() {
get_cameras,
get_capture_windows,
get_prev_recordings,
- open_previous_recordings_window,
+ show_previous_recordings_window,
set_fake_window_bounds,
remove_fake_window,
focus_captures_panel,
@@ -388,7 +412,7 @@ pub fn run() {
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
- FocusCapturesPanel,
+ ShowCapturesPanel,
]);
#[cfg(debug_assertions)] // <- Only export on non-release builds
@@ -406,7 +430,8 @@ pub fn run() {
.setup(move |app| {
specta_builder.mount_events(app);
- app.manage(Arc::new(RwLock::new(AppState {
+ app.manage(Arc::new(RwLock::new(App {
+ handle: app.handle().clone(),
start_recording_options: RecordingOptions {
capture_target: CaptureTarget::Screen,
camera_label: None,
diff --git a/apps/desktop-solid/src/routes/index.tsx b/apps/desktop-solid/src/routes/index.tsx
index 181cb190b..770bd4504 100644
--- a/apps/desktop-solid/src/routes/index.tsx
+++ b/apps/desktop-solid/src/routes/index.tsx
@@ -3,7 +3,7 @@ import { For, Show, Suspense, createSignal } from "solid-js";
import { createCameraForLabel, createCameras } from "../utils/media";
import { createOptionsQuery, createWindowsQuery } from "../utils/queries";
-import { commands } from "../utils/tauri";
+import { commands, events } from "../utils/tauri";
export default function () {
const cameras = createCameras();
@@ -15,11 +15,15 @@ export default function () {
// temporary
const [isRecording, setIsRecording] = createSignal(false);
+ events.showCapturesPanel.listen(() => {
+ commands.showPreviousRecordingsWindow();
+ });
+
return (
<>
<button
type="button"
- onClick={() => commands.openPreviousRecordingsWindow()}
+ onClick={() => commands.showPreviousRecordingsWindow()}
>
Open prev recordings window
</button>
@@ -78,14 +82,14 @@ export default function () {
type="button"
class={cx(
"flex-1",
- "display" === options().captureTarget
+ "screen" === options().captureTarget
? "bg-neutral-200"
: "bg-neutral-100"
)}
onClick={() =>
commands.setRecordingOptions({
...options(),
- captureTarget: "display",
+ captureTarget: "screen",
})
}
>
@@ -97,7 +101,7 @@ export default function () {
type="button"
class={cx(
"flex-1",
- options().captureTarget !== "display"
+ options().captureTarget !== "screen"
? "bg-neutral-200"
: "bg-neutral-100"
)}
@@ -123,7 +127,7 @@ export default function () {
<Show
when={(() => {
const captureTarget = options().captureTarget;
- if (captureTarget === "display") return;
+ if (captureTarget === "screen") return;
return {
windows: windows.data,
diff --git a/apps/desktop-solid/src/routes/prev-recordings.tsx b/apps/desktop-solid/src/routes/prev-recordings.tsx
index 4f03e832f..0c0da847a 100644
--- a/apps/desktop-solid/src/routes/prev-recordings.tsx
+++ b/apps/desktop-solid/src/routes/prev-recordings.tsx
@@ -28,8 +28,8 @@ export default function () {
// if (e.deltaX === 0) closingRecording = null;
// });
- events.focusCapturesPanel.listen(() => {
- commands.focusCapturesPanel();
+ events.showCapturesPanel.listen(() => {
+ recordings.refetch();
});
return (
diff --git a/apps/desktop-solid/src/utils/queries.ts b/apps/desktop-solid/src/utils/queries.ts
index aef76c03f..dc1a95f25 100644
--- a/apps/desktop-solid/src/utils/queries.ts
+++ b/apps/desktop-solid/src/utils/queries.ts
@@ -17,7 +17,7 @@ const getOptions = queryOptions({
});
export const getCurrentRecording = queryOptions({
- queryKey: ["recordingOptions"] as const,
+ queryKey: ["currentRecording"] as const,
queryFn: async () => {
const o = await commands.getCurrentRecording();
if (o.status === "ok") return o.data;
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index a27e5ca50..71f4c5501 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -54,8 +54,8 @@ async getPrevRecordings() : Promise<Result<string[], null>> {
else return { status: "error", error: e as any };
}
},
-async openPreviousRecordingsWindow() : Promise<void> {
- await TAURI_INVOKE("open_previous_recordings_window");
+async showPreviousRecordingsWindow() : Promise<void> {
+ await TAURI_INVOKE("show_previous_recordings_window");
},
async setFakeWindowBounds(name: string, bounds: Bounds) : Promise<Result<null, string>> {
try {
@@ -90,11 +90,11 @@ async getCurrentRecording() : Promise<Result<JsonValue<InProgressRecording | nul
export const events = __makeEvents__<{
-focusCapturesPanel: FocusCapturesPanel,
-recordingOptionsChanged: RecordingOptionsChanged
+recordingOptionsChanged: RecordingOptionsChanged,
+showCapturesPanel: ShowCapturesPanel
}>({
-focusCapturesPanel: "focus-captures-panel",
-recordingOptionsChanged: "recording-options-changed"
+recordingOptionsChanged: "recording-options-changed",
+showCapturesPanel: "show-captures-panel"
})
/** user-defined constants **/
@@ -107,11 +107,11 @@ export type Bounds = { x: number; y: number; width: number; height: number }
export type CaptureTarget = "screen" | { window: number }
export type CaptureWindow = { id: number; name: string }
export type DisplaySource = { variant: "screen" } | { variant: "window"; bounds: Bounds }
-export type FocusCapturesPanel = null
export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource }
export type JsonValue<T> = [T]
export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null }
export type RecordingOptionsChanged = null
+export type ShowCapturesPanel = null
/** tauri-specta globals **/
diff --git a/apps/desktop/src-tauri/capabilities/migrated.json b/apps/desktop/src-tauri/capabilities/migrated.json
index e169e27f0..7babac0ab 100644
--- a/apps/desktop/src-tauri/capabilities/migrated.json
+++ b/apps/desktop/src-tauri/capabilities/migrated.json
@@ -22,6 +22,9 @@
"fs:allow-resource-read-recursive",
"fs:default",
"decorum:allow-show-snap-overlay",
- "os:default"
+ "os:default",
+ "oauth:default",
+ "oauth:allow-start",
+ "oauth:allow-cancel"
]
}
diff --git a/apps/desktop/src-tauri/gen/schemas/capabilities.json b/apps/desktop/src-tauri/gen/schemas/capabilities.json
index 2e3da0d28..183e3bc3a 100644
--- a/apps/desktop/src-tauri/gen/schemas/capabilities.json
+++ b/apps/desktop/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main","camera"],"permissions":["core:default","core:window:allow-close","core:window:allow-hide","core:window:allow-show","core:window:allow-center","core:window:allow-minimize","core:window:allow-unminimize","core:window:allow-maximize","core:window:allow-set-size","core:window:allow-set-focus","core:window:allow-start-dragging","core:window:allow-set-position","core:webview:allow-create-webview-window","shell:default","fs:allow-read-text-file","fs:allow-resource-read-recursive","fs:default","decorum:allow-show-snap-overlay","os:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main","camera"],"permissions":["core:default","core:window:allow-close","core:window:allow-hide","core:window:allow-show","core:window:allow-center","core:window:allow-minimize","core:window:allow-unminimize","core:window:allow-maximize","core:window:allow-set-size","core:window:allow-set-focus","core:window:allow-start-dragging","core:window:allow-set-position","core:webview:allow-create-webview-window","shell:default","fs:allow-read-text-file","fs:allow-resource-read-recursive","fs:default","decorum:allow-show-snap-overlay","os:default","oauth:default","oauth:allow-start","oauth:allow-cancel"]}}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 91e57d899..981e3ef6f 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -151,6 +151,7 @@ fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
+ .plugin(tauri_plugin_oauth::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_global_shortcut::Builder::new().build())