Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
window capture occluder
Brendan Allan1b04f66a711c
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rsindex 25217c992..24a3f6e46 100644--- a/apps/desktop-solid/src-tauri/src/display.rs+++ b/apps/desktop-solid/src-tauri/src/display.rs@@ -14,7 +14,7 @@ use specta::Type;use crate::{ffmpeg::{FFmpegRawVideoInput, NamedPipeCapture},- macos,+ macos, Bounds,};#[derive(Type, Serialize)]@@ -26,7 +26,7 @@ pub struct CaptureWindow {#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub enum CaptureTarget {- Display,+ Screen,Window(u32),}@@ -65,22 +65,15 @@ pub fn start_capturing(dbg!(capture_target);let mut capturer = {let crop_area = match capture_target {- CaptureTarget::Window(id) => {- let windows = macos::get_on_screen_windows();-- let window = windows- .into_iter()- .find(|w| w.window_number == *id)- .unwrap();-- Some(Area {+ CaptureTarget::Window(window_number) => {+ get_window_bounds(*window_number).map(|bounds| Area {size: Size {- width: window.bounds.width as f64,- height: window.bounds.height as f64,+ width: bounds.width,+ height: bounds.height,},origin: Point {- x: window.bounds.x as f64,- y: window.bounds.y as f64,+ x: bounds.x,+ y: bounds.y,},})}@@ -127,3 +120,18 @@ pub fn start_capturing(((width, height), capture)}++pub fn get_window_bounds(window_number: u32) -> Option<Bounds> {+ let windows = macos::get_on_screen_windows();++ let window = windows+ .into_iter()+ .find(|w| w.window_number == window_number)?;++ Some(Bounds {+ width: window.bounds.width as f64,+ height: window.bounds.height as f64,+ x: window.bounds.x as f64,+ y: window.bounds.y as f64,+ })+}diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rsindex 73e63ea43..90dd1f508 100644--- a/apps/desktop-solid/src-tauri/src/lib.rs+++ b/apps/desktop-solid/src-tauri/src/lib.rs@@ -5,12 +5,16 @@ mod macos;mod recording;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,@@ -18,6 +22,7 @@ use std::{};use tauri::{AppHandle, Manager, State, WebviewWindow};use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};+use tauri_plugin_decorum::WebviewWindowExt;use tauri_specta::Event;use tokio::{sync::RwLock, time::sleep};@@ -36,7 +41,7 @@ pub struct RecordingOptions {pub struct AppState {start_recording_options: RecordingOptions,#[serde(skip)]- current_recording: Option<recording::InProgressRecording>,+ current_recording: Option<InProgressRecording>,prev_recordings: Vec<PathBuf>,}@@ -71,6 +76,29 @@ async fn set_recording_options(Ok(())}+type Bruh<T> = (T,);++#[derive(Serialize, Type)]+struct JsonValue<T>(+ #[serde(skip)] PhantomData<T>,+ #[specta(type = Bruh<T>)] serde_json::Value,+);++impl<T: Serialize> JsonValue<T> {+ fn new(value: &T) -> Self {+ Self(PhantomData, json!(value))+ }+}++#[tauri::command]+#[specta::specta]+async fn get_current_recording(+ state: MutableState<'_, AppState>,+) -> Result<JsonValue<Option<InProgressRecording>>, ()> {+ let state = state.read().await;+ Ok(JsonValue::new(&state.current_recording))+}+#[tauri::command]#[specta::specta]async fn get_prev_recordings(state: MutableState<'_, AppState>) -> Result<Vec<PathBuf>, ()> {@@ -95,20 +123,42 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> R.join("recordings").join(format!("{id}.cap"));- state.current_recording = Some(recording::start(recording_dir, recording_options).await);+ let current_recording = recording::start(recording_dir, recording_options).await;+ let current_recording = state.current_recording.insert(current_recording);- Ok(())-}+ if let DisplaySource::Window { .. } = ¤t_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();-fn get_target_for_window(window: &WebviewWindow) -> Option<Target> {- let window_number = macos::get_ns_window_number(window.ns_window().unwrap());+ occluder_window+ .set_window_level(NSScreenSaverWindowLevel as u32)+ .unwrap();+ occluder_window.set_ignore_cursor_events(true).unwrap();+ occluder_window.make_transparent().unwrap();+ }- scap::get_all_targets()- .into_iter()- .find(|target| match target {- Target::Window(window) => window.raw_handle as isize == window_number,- _ => false,- })+ Ok(())}#[tauri::command]@@ -149,18 +199,18 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, AppState>) -> Re#[tauri::command]#[specta::specta]-fn open_dat_shit(app: AppHandle) {+fn open_previous_recordings_window(app: AppHandle) {show_previous_recordings_window(app);}struct FakeWindowBounds(pub Arc<RwLock<HashMap<String, HashMap<String, Bounds>>>>);-#[derive(Type, Deserialize, Debug)]+#[derive(Type, Serialize, Deserialize, Debug, Clone)]struct Bounds {- x: f64,- y: f64,- width: f64,- height: f64,+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,}#[tauri::command]@@ -330,10 +380,11 @@ pub fn run() {get_cameras,get_capture_windows,get_prev_recordings,- open_dat_shit,+ open_previous_recordings_window,set_fake_window_bounds,remove_fake_window,- focus_captures_panel+ focus_captures_panel,+ get_current_recording]).events(tauri_specta::collect_events![RecordingOptionsChanged,@@ -357,7 +408,7 @@ pub fn run() {app.manage(Arc::new(RwLock::new(AppState {start_recording_options: RecordingOptions {- capture_target: CaptureTarget::Display,+ capture_target: CaptureTarget::Screen,camera_label: None,},current_recording: None,diff --git a/apps/desktop-solid/src-tauri/src/recording.rs b/apps/desktop-solid/src-tauri/src/recording.rsindex f0bf94760..17ee613ae 100644--- a/apps/desktop-solid/src-tauri/src/recording.rs+++ b/apps/desktop-solid/src-tauri/src/recording.rs@@ -1,13 +1,31 @@+use serde::Serialize;+use specta::Type;use std::path::PathBuf;-use scap::Target;--use crate::{camera, display, ffmpeg::*, RecordingOptions};+use crate::{+ camera,+ display::{self, get_window_bounds, CaptureTarget},+ ffmpeg::*,+ Bounds, RecordingOptions,+};++#[derive(Clone, Type, Serialize)]+#[serde(rename_all = "camelCase", tag = "variant")]+pub enum DisplaySource {+ Screen,+ Window { bounds: Bounds },+}+#[derive(Type, Serialize)]+#[serde(rename_all = "camelCase")]pub struct InProgressRecording {pub recording_dir: PathBuf,+ #[serde(skip)]pub ffmpeg_process: FFmpegProcess,+ #[serde(skip)]pub display: FFmpegCaptureOutput<FFmpegRawVideoInput>,+ pub display_source: DisplaySource,+ #[serde(skip)]pub camera: Option<FFmpegCaptureOutput<FFmpegRawVideoInput>>,}@@ -38,7 +56,7 @@ pub async fn start(let mut ffmpeg = FFmpeg::new();- let camera = start_camera_recording(&content_dir, &recording_options, &mut ffmpeg).await;+ let camera = start_camera_recording(&content_dir, recording_options, &mut ffmpeg).await;let display = start_display_recording(&content_dir, recording_options, &mut ffmpeg).await;let ffmpeg_process = ffmpeg.start();@@ -47,6 +65,12 @@ pub async fn start(recording_dir,ffmpeg_process,display,+ display_source: match recording_options.capture_target {+ CaptureTarget::Screen => DisplaySource::Screen,+ CaptureTarget::Window(window_number) => DisplaySource::Window {+ bounds: get_window_bounds(window_number).unwrap(),+ },+ },camera,}}diff --git a/apps/desktop-solid/src/routes/index.tsx b/apps/desktop-solid/src/routes/index.tsxindex 83341bfa5..181cb190b 100644--- a/apps/desktop-solid/src/routes/index.tsx+++ b/apps/desktop-solid/src/routes/index.tsx@@ -17,7 +17,10 @@ export default function () {return (<>- <button type="button" onClick={() => commands.openDatShit()}>+ <button+ type="button"+ onClick={() => commands.openPreviousRecordingsWindow()}+ >Open prev recordings window</button><Suspense fallback="LOADING">@@ -184,58 +187,3 @@ export default function () {</>);}--// <key>CFBundleDocumentTypes</key>-// <array>-// <dict>-// <key>CFBundleDocumentTypes</key>-// <array>-// <dict>-// <key>CFBundleTypeName</key>-// <string>LSTypeIsPackage</string>-// <key>LSHandlerRank</key>-// <string>Default</string>-// </dict>-// </array>-// <key>CFBundleTypeExtensions</key>-// <array>-// <string>cap</string>-// </array>-// <key>CFBundleTypeName</key>-// <string>Unique Extension</string>-// <key>CFBundleTypeRole</key>-// <string>Editor</string>-// <key>LSHandlerRank</key>-// <string>Default</string>-// <key>LSItemContentTypes</key>-// <array>-// <string>so.cap.recording</string>-// </array>-// <key>NSDocumentClass</key>-// <string>$(PRODUCT_MODULE_NAME).Document</string>-// </dict>-// <dict/>-// </array>-// <key>UTExportedTypeDeclarations</key>-// <array>-// <dict>-// <key>UTTypeConformsTo</key>-// <array>-// <string>com.apple.package</string>-// <string>public.composite-content</string>-// </array>-// <key>UTTypeDescription</key>-// <string>Unique Extension</string>-// <key>UTTypeIcons</key>-// <dict/>-// <key>UTTypeIdentifier</key>-// <string>com.buddhiman.Unique-Extension</string>-// <key>UTTypeTagSpecification</key>-// <dict>-// <key>public.filename-extension</key>-// <array>-// <string>cap</string>-// </array>-// </dict>-// </dict>-// </array>diff --git a/apps/desktop-solid/src/routes/window-capture-occluder.tsx b/apps/desktop-solid/src/routes/window-capture-occluder.tsxnew file mode 100644index 000000000..fed409293--- /dev/null+++ b/apps/desktop-solid/src/routes/window-capture-occluder.tsx@@ -0,0 +1,50 @@+import { createQuery } from "@tanstack/solid-query";+import { createEffect, Show, Suspense } from "solid-js";+import { getCurrentRecording } from "../utils/queries";++export default function () {+ const currentRecording = createQuery(() => getCurrentRecording);++ return (+ <Suspense>+ <Show+ when={+ currentRecording.data?.[0] &&+ currentRecording.data[0].displaySource.variant === "window" &&+ currentRecording.data[0].displaySource.bounds+ }+ >+ {(bounds) => (+ <div class="w-screen h-screen relative animate-in fade-in">+ <div+ class="bg-black/40 absolute inset-x-0 top-0"+ style={{ height: `${bounds().y}px` }}+ />+ <div+ class="bg-black/40 absolute left-0"+ style={{+ top: `${bounds().y}px`,+ height: `${bounds().height}px`,+ width: `${bounds().x}px`,+ }}+ />+ <div+ class="bg-black/40 absolute right-0"+ style={{+ top: `${bounds().y}px`,+ height: `${bounds().height}px`,+ width: `calc(100vw - ${bounds().x + bounds().width}px)`,+ }}+ />+ <div+ class="bg-black/40 absolute inset-x-0 bottom-0"+ style={{+ height: `calc(100vh - ${bounds().y + bounds().height}px)`,+ }}+ />+ </div>+ )}+ </Show>+ </Suspense>+ );+}diff --git a/apps/desktop-solid/src/utils/queries.ts b/apps/desktop-solid/src/utils/queries.tsindex 0f28ead7f..aef76c03f 100644--- a/apps/desktop-solid/src/utils/queries.ts+++ b/apps/desktop-solid/src/utils/queries.ts@@ -16,6 +16,14 @@ const getOptions = queryOptions({},});+export const getCurrentRecording = queryOptions({+ queryKey: ["recordingOptions"] as const,+ queryFn: async () => {+ const o = await commands.getCurrentRecording();+ if (o.status === "ok") return o.data;+ },+});+export function createOptionsQuery() {const options = createQuery(() => getOptions);createQueryInvalidate(options, "recordingOptionsChanged");diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.tsindex 5012bdccd..a27e5ca50 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 openDatShit() : Promise<void> {- await TAURI_INVOKE("open_dat_shit");+async openPreviousRecordingsWindow() : Promise<void> {+ await TAURI_INVOKE("open_previous_recordings_window");},async setFakeWindowBounds(name: string, bounds: Bounds) : Promise<Result<null, string>> {try {@@ -75,6 +75,14 @@ async removeFakeWindow(name: string) : Promise<Result<null, string>> {},async focusCapturesPanel() : Promise<void> {await TAURI_INVOKE("focus_captures_panel");+},+async getCurrentRecording() : Promise<Result<JsonValue<InProgressRecording | null>, null>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("get_current_recording") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}}}@@ -96,9 +104,12 @@ recordingOptionsChanged: "recording-options-changed"/** user-defined types **/export type Bounds = { x: number; y: number; width: number; height: number }-export type CaptureTarget = "display" | { window: 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