Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Permissions screen + renaming of AudioRecorder
Richie McIlroy2dd5fa1dbf37
diff --git a/apps/desktop/src-tauri/icons/icon.icns b/apps/desktop/src-tauri/icons/icon.icnsindex b736cf9ce..932504206 100644Binary files a/apps/desktop/src-tauri/icons/icon.icns and b/apps/desktop/src-tauri/icons/icon.icns differdiff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex cde43c19f..e63ba3b38 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -15,11 +15,11 @@ mod recording;mod upload;mod devices;mod utils;-mod audio;+mod media;use recording::{RecordingState, start_dual_recording, stop_all_recordings};use upload::upload_file;-use audio::{enumerate_audio_devices};+use media::{enumerate_audio_devices};use ffmpeg_sidecar::{command::ffmpeg_is_installed,@@ -76,6 +76,33 @@ fn main() {.map_err(|err| err.to_string())}+ #[tauri::command]+ fn open_screen_capture_preferences() {+ #[cfg(target_os = "macos")]+ std::process::Command::new("open")+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")+ .spawn()+ .expect("failed to open system preferences");+ }++ #[tauri::command]+ fn open_mic_preferences() {+ #[cfg(target_os = "macos")]+ std::process::Command::new("open")+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")+ .spawn()+ .expect("failed to open system preferences");+ }++ #[tauri::command]+ fn open_camera_preferences() {+ #[cfg(target_os = "macos")]+ std::process::Command::new("open")+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")+ .spawn()+ .expect("failed to open system preferences");+ }+tauri::Builder::default().plugin(tauri_plugin_oauth::init()).plugin(tauri_plugin_positioner::init())@@ -95,10 +122,7 @@ fn main() {let data_directory = handle.path_resolver().app_data_dir().unwrap_or_else(|| PathBuf::new());let recording_state = RecordingState {- screen_process: None,- screen_process_stdin: None,- video_process: None,- audio_process: None,+ media_process: None,upload_handles: Mutex::new(vec![]),recording_options: None,shutdown_flag: Arc::new(AtomicBool::new(false)),@@ -116,7 +140,10 @@ fn main() {stop_all_recordings,enumerate_audio_devices,upload_file,- start_server+ start_server,+ open_screen_capture_preferences,+ open_mic_preferences,+ open_camera_preferences]).plugin(tauri_plugin_context_menu::init()).run(tauri::generate_context!())diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/media.rssimilarity index 98%rename from apps/desktop/src-tauri/src/audio.rsrename to apps/desktop/src-tauri/src/media.rsindex 2ffa79a81..6538514eb 100644--- a/apps/desktop/src-tauri/src/audio.rs+++ b/apps/desktop/src-tauri/src/media.rs@@ -9,15 +9,14 @@ use std::time::{Instant, Duration};use tokio::io::{AsyncWriteExt};use tokio::process::{Command, Child, ChildStdin};use tokio::sync::{mpsc, Mutex};-use tokio::time::{self};use crate::recording::RecordingOptions;-use crate::utils::{ffmpeg_path_as_str, monitor_and_log_recording_start};+use crate::utils::{ffmpeg_path_as_str};use capture::{Capturer, Display};const FRAME_RATE: u64 = 30;-pub struct AudioRecorder {+pub struct MediaRecorder {pub options: Option<RecordingOptions>,ffmpeg_audio_process: Option<tokio::process::Child>,ffmpeg_video_process: Option<tokio::process::Child>,@@ -32,10 +31,10 @@ pub struct AudioRecorder {should_stop: Arc<AtomicBool>,}-impl AudioRecorder {+impl MediaRecorder {pub fn new() -> Self {- AudioRecorder {+ MediaRecorder {options: None,ffmpeg_audio_process: None,ffmpeg_video_process: None,@@ -51,7 +50,7 @@ impl AudioRecorder {}}- pub async fn start_audio_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, custom_device: Option<&str>) -> Result<(), String> {+ pub async fn start_media_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, custom_device: Option<&str>) -> Result<(), String> {self.options = Some(options);let host = cpal::default_host();@@ -444,7 +443,7 @@ impl AudioRecorder {Ok(())}- pub async fn stop_audio_recording(&mut self) -> Result<(), String> {+ pub async fn stop_media_recording(&mut self) -> Result<(), String> {if let Some(ref ffmpeg_audio_stdin) = self.ffmpeg_audio_stdin {let mut audio_stdin_guard = ffmpeg_audio_stdin.lock().await;if let Some(mut audio_stdin) = audio_stdin_guard.take() {diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 281c6b738..de27df433 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,33 +1,21 @@use std::path::{Path, PathBuf};use std::collections::HashSet;-use std::io::{self, BufReader, BufRead, ErrorKind, ErrorKind::WouldBlock};+use std::io::{self, BufReader, BufRead, ErrorKind};use std::fs::File;use std::sync::{Arc, atomic::{AtomicBool, Ordering}};-use std::ops::{Deref, DerefMut};-use std::process::Stdio;-use std::time::{Instant};use tokio::sync:: {Mutex};use tokio::task::JoinHandle;use tokio::time::{Duration};-use tokio::io::{AsyncWriteExt};use serde::{Serialize, Deserialize};use tauri::State;-use tokio::process::{Command, ChildStderr, ChildStdin};-use tokio::join;use futures::future::join_all;-use crate::utils::{ffmpeg_path_as_str, monitor_and_log_recording_start};use crate::upload::upload_file;-use crate::audio::AudioRecorder;--const FRAME_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000 / 30);+use crate::media::MediaRecorder;pub struct RecordingState {- pub screen_process: Option<tokio::process::Child>,- pub screen_process_stdin: Option<Arc<Mutex<ChildStdin>>>,- pub video_process: Option<tokio::process::Child>,- pub audio_process: Option<AudioRecorder>,+ pub media_process: Option<MediaRecorder>,pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,pub recording_options: Option<RecordingOptions>,pub shutdown_flag: Arc<AtomicBool>,@@ -38,8 +26,8 @@ pub struct RecordingState {unsafe impl Send for RecordingState {}unsafe impl Sync for RecordingState {}-unsafe impl Send for AudioRecorder {}-unsafe impl Sync for AudioRecorder {}+unsafe impl Send for MediaRecorder {}+unsafe impl Sync for MediaRecorder {}#[derive(Debug, Serialize, Deserialize, Clone)]pub struct RecordingOptions {@@ -62,12 +50,6 @@ pub async fn start_dual_recording(let shutdown_flag = Arc::new(AtomicBool::new(false));- // let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(32);- // let display = Display::primary().map_err(|_| "Failed to find primary display".to_string())?;- // let (w, h) = (display.width(), display.height());- // let adjusted_height = h & !1;- // let capture_size = w * adjusted_height * 4;-let data_dir = state_guard.data_dir.as_ref().ok_or("Data directory is not set in the recording state".to_string())?.clone();@@ -84,138 +66,16 @@ pub async fn start_dual_recording(Some(options.audio_name.clone())};- // let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index, w, adjusted_height);- // let ffmpeg_screen_args = ffmpeg_screen_args_future.await.map_err(|e| e.to_string())?;-- let screenshot_output_path = data_dir.join("screen-capture.jpg").to_str().unwrap().to_string();- let ffmpeg_screen_screenshot_args = match std::env::consts::OS {- "macos" => vec![- "-y".to_string(),- "-f".to_string(),- "avfoundation".to_string(),- "-i".to_string(),- options.screen_index.clone(),- "-vframes".to_string(),- "1".to_string(),- screenshot_output_path.clone()- ],- "windows" => vec![- "-y".to_string(),- "-f".to_string(),- "gdigrab".to_string(),- "-i".to_string(),- "desktop".to_string(),- "-vframes".to_string(),- "1".to_string(),- screenshot_output_path.clone()- ],- "linux" => vec![- "-y".to_string(),- "-f".to_string(),- "x11grab".to_string(),- "-i".to_string(),- ":0.0".to_string(),- "-vframes".to_string(),- "1".to_string(),- screenshot_output_path.clone()- ],- _ => return Err("Unsupported OS".to_string()),- };-- // println!("Screen args: {:?}", ffmpeg_screen_args);-- // Prepare screen and audio recording concurrently- let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;- // let screen_recording_preparation = prepare_screen_recording(&ffmpeg_binary_path_str, &options, &screen_chunks_dir, w, adjusted_height);- let audio_recording_preparation = prepare_audio_recording(&options, &audio_chunks_dir, &video_chunks_dir, audio_name);-- let audio_recording_result = audio_recording_preparation.await.map_err(|e| e.to_string())?;+ let media_recording_preparation = prepare_media_recording(&options, &audio_chunks_dir, &video_chunks_dir, audio_name);+ let media_recording_result = media_recording_preparation.await.map_err(|e| e.to_string())?;- // Handle the results of both operations- // let (screen_child, screen_stdin) = screen_recording_result.map_err(|e| e.to_string())?;-- // let screen_stdin_arc = Arc::new(Mutex::new(screen_stdin));- // let stdin_clone = Arc::clone(&screen_stdin_arc);-- // tokio::spawn(async move {- // while let Some(frame_data) = rx.recv().await {- // let mut stdin_locked = stdin_clone.lock().await;- // if let Err(e) = stdin_locked.write_all(&frame_data).await {- // eprintln!("Failed to write frame data to FFmpeg's stdin: {}", e);- // break;- // }- // }- // });-- let options_clone = state_guard.recording_options.clone();-- // Spawn the screenshot task without directly awaiting it- tokio::spawn(async move {- if let Err(e) = take_screenshot(- ffmpeg_binary_path_str.clone(),- ffmpeg_screen_screenshot_args.clone(),- screenshot_output_path.clone(),- options_clone.clone(),- ).await {- eprintln!("Failed to take and upload screenshot: {}", e);- }- });-- // state_guard.screen_process = Some(screen_child);- // println!("Set screen child");- // state_guard.screen_process_stdin = Some(screen_stdin_arc);- // println!("Set screen stdin");- state_guard.audio_process = Some(audio_recording_result);+ state_guard.media_process = Some(media_recording_result);state_guard.upload_handles = Mutex::new(vec![]);state_guard.recording_options = Some(options.clone());state_guard.shutdown_flag = shutdown_flag.clone();state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));- // let _capturer_thread = {- // println!("Starting video capture thread...");- // let shutdown_flag = shutdown_flag.clone();- // tokio::spawn(async move {- // println!("Starting video capture...");-- // let mut safe_capturer = SafeCapturer(Capturer::new(display).expect("Failed to start capture"));- // let mut next_frame_time = Instant::now();- // while !shutdown_flag.load(Ordering::SeqCst) {- // let now = Instant::now();- // if now < next_frame_time {- // std::thread::sleep(next_frame_time - now);- // }- // next_frame_time = Instant::now() + FRAME_INTERVAL;-- // let frame_data = match safe_capturer.frame() {- // Ok(frame) => {- // let stride = frame[..capture_size].len() / adjusted_height;- // let mut frame_data = Vec::with_capacity(capture_size);- // for row in 0..adjusted_height {- // let start = row * stride;- // let end = start + stride;- // frame_data.extend_from_slice(&frame[start..end]);- // }- // Some(frame_data)- // },- // Err(error) if error.kind() == WouldBlock => {- // continue;- // },- // Err(error) => return Err(format!("Capture error: {}", error)),- // };-- // if let Some(frame_data) = frame_data {- // if let Err(e) = tx.send(frame_data).await {- // eprintln!("Failed to send frame data through channel: {}", e);- // break;- // }- // }- // }-- // Ok(())- // })- // };-let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());@@ -238,25 +98,15 @@ pub async fn start_dual_recording(#[tauri::command]pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {- println!("!!STOPPING screen recording...");-let mut guard = state.lock().await;- println!("Stopping screen recording...");+ println!("Stopping media recording...");guard.shutdown_flag.store(true, Ordering::SeqCst);- // if let Some(stdin) = guard.screen_process_stdin.take() {- // println!("Sending quit command to FFmpeg...");- // let mut stdin_locked = stdin.lock().await;- // if let Err(e) = graceful_stop_ffmpeg(&mut stdin_locked).await {- // eprintln!("Failed to send quit command to FFmpeg: {}", e);- // }- // }-- if let Some(mut audio_process) = guard.audio_process.take() {- println!("Stopping audio recording...");- audio_process.stop_audio_recording().await.expect("Failed to stop audio recording");+ if let Some(mut media_process) = guard.media_process.take() {+ println!("Stopping media recording...");+ media_process.stop_media_recording().await.expect("Failed to stop media recording");}while !guard.video_uploading_finished.load(Ordering::SeqCst)@@ -288,96 +138,6 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {}}-// async fn construct_recording_args(-// options: &RecordingOptions,-// chunks_dir: &Path,-// video_type: &str,-// input_index: &str,-// w: usize,-// adjusted_height: usize,-// ) -> Result<Vec<String>, String> {-// let output_filename_pattern = format!("{}/recording_chunk_%03d.ts", chunks_dir.display());-// let segment_list_filename = format!("{}/segment_list.txt", chunks_dir.display());--// ensure_segment_list_exists(PathBuf::from(&segment_list_filename))-// .map_err(|e| format!("Failed to ensure segment list file exists: {}", e))?;--// let fps = if video_type == "screen" { "30" } else { &options.framerate };-// let preset = "veryfast".to_string();-// let crf = "28".to_string();-// let pix_fmt = "yuv420p".to_string();-// let codec = "libx264".to_string();-// let segment_time = "3".to_string();-// let segment_list_type = "flat".to_string();--// match std::env::consts::OS {-// "macos" => {-// Ok(vec![-// "-f".to_string(), "rawvideo".to_string(),-// "-pix_fmt".to_string(), "bgra".to_string(),-// "-s".to_string(), format!("{}x{}", w, adjusted_height),-// "-r".to_string(), "30".to_string(),-// "-thread_queue_size".to_string(), "8192".to_string(),-// "-i".to_string(), "pipe:0".to_string(),-// "-c:v".to_string(), "libx264".to_string(),-// "-preset".to_string(), preset,-// "-pix_fmt".to_string(), pix_fmt,-// "-vsync".to_string(), "1".to_string(),-// "-r".to_string(), "30".to_string(),-// "-an".to_string(),-// "-f".to_string(), "segment".to_string(),-// "-segment_time".to_string(), segment_time,-// "-segment_format".to_string(), "mpegts".to_string(),-// "-segment_list".to_string(), segment_list_filename,-// "-segment_list_type".to_string(), segment_list_type,-// "-reset_timestamps".to_string(), "1".to_string(),-// "-use_wallclock_as_timestamps".to_string(), "1".to_string(),-// output_filename_pattern,-// ])-// },-// "linux" => {-// Ok(vec![-// "-f".to_string(), "x11grab".to_string(),-// "-i".to_string(), format!("{}+0,0", input_index),-// "-draw_mouse".to_string(), "1".to_string(),-// "-pix_fmt".to_string(), pix_fmt,-// "-c:v".to_string(), codec,-// "-crf".to_string(), crf,-// "-preset".to_string(), preset,-// "-r".to_string(), fps.to_string(),-// "-an".to_string(),-// "-f".to_string(), "segment".to_string(),-// "-segment_time".to_string(), segment_time,-// "-segment_format".to_string(), "mpegts".to_string(),-// "-segment_list".to_string(), segment_list_filename,-// "-segment_list_type".to_string(), segment_list_type,-// "-reset_timestamps".to_string(), "1".to_string(),-// output_filename_pattern,-// ])-// },-// "windows" => {-// Ok(vec![-// "-f".to_string(), "gdigrab".to_string(),-// "-i".to_string(), "desktop".to_string(),-// "-pixel_format".to_string(), pix_fmt,-// "-c:v".to_string(), codec,-// "-crf".to_string(), crf,-// "-preset".to_string(), preset,-// "-r".to_string(), fps.to_string(),-// "-an".to_string(), // This is the argument to skip audio recording.-// "-f".to_string(), "segment".to_string(),-// "-segment_time".to_string(), segment_time,-// "-segment_format".to_string(), "mpegts".to_string(),-// "-segment_list".to_string(), segment_list_filename,-// "-segment_list_type".to_string(), segment_list_type,-// "-reset_timestamps".to_string(), "1".to_string(),-// output_filename_pattern,-// ])-// },-// _ => Err("Unsupported OS".to_string()),-// }-// }-async fn start_upload_loop(chunks_dir: PathBuf,options: RecordingOptions,@@ -429,19 +189,6 @@ async fn start_upload_loop(Ok(())}-fn ensure_segment_list_exists(file_path: PathBuf) -> io::Result<()> {- match File::open(&file_path) {- Ok(_) => (),- Err(ref e) if e.kind() == ErrorKind::NotFound => {- File::create(&file_path)?;- },- Err(e) => {- return Err(e);- },- }- Ok(())-}-fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {let file = File::open(segment_list_path)?;let reader = BufReader::new(file);@@ -457,110 +204,15 @@ fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {Ok(segments)}-async fn take_screenshot(- ffmpeg_binary_path_str: String,- ffmpeg_screen_screenshot_args: Vec<String>,- screenshot_path: String,- options: Option<RecordingOptions>,-) -> Result<(), String> {- println!("Waiting for 3 seconds before taking the screenshot...");- tokio::time::sleep(Duration::from_secs(3)).await;-- // Start the FFmpeg process for taking a screenshot- let mut screen_screenshot_child = tokio::process::Command::new(&ffmpeg_binary_path_str)- .args(&ffmpeg_screen_screenshot_args)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .map_err(|e| e.to_string())?;-- match screen_screenshot_child.wait().await {- Ok(status) if status.success() => {- println!("Screenshot captured: {}", &screenshot_path);- if let Some(ref opts) = options {- match upload_file(Some(opts.clone()), screenshot_path.clone(), "screenshot".to_string()).await {- Ok(_) => println!("Screenshot uploaded successfully."),- Err(e) => eprintln!("Failed to upload screenshot: {}", e),- }- } else {- eprintln!("No recording options set, skipping upload.");- }- },- Ok(_) => eprintln!("Screenshot command completed, but may have failed."),- Err(e) => eprintln!("Failed to execute screenshot command: {}", e),- }-- Ok(())-}--async fn upload_jpeg_files(- dir_path: &PathBuf,- options: Option<RecordingOptions>,-) -> Result<(), String> {- let dir_entries = std::fs::read_dir(dir_path).map_err(|e| format!("Failed to read dir: {}", e))?;- for entry in dir_entries {- let entry = entry.map_err(|e| format!("Failed to process dir entry: {}", e))?;- let path = entry.path();- if path.is_file() && path.extension().map_or(false, |ext| ext == "jpeg" || ext == "jpg") {- let file_path_str = path.to_str().unwrap_or_default();- println!("Found JPEG file for upload: {}", file_path_str);- upload_file(options.clone(), file_path_str.to_string(), "screenshot".to_string()).await.map_err(|e| format!("Failed to upload JPEG: {}", e))?;- }- }-- Ok(())-}--// async fn prepare_screen_recording(-// ffmpeg_binary_path_str: &str,-// options: &RecordingOptions,-// screen_chunks_dir: &Path,-// w: usize,-// adjusted_height: usize,-// ) -> Result<(tokio::process::Child, ChildStdin), String> {-// let ffmpeg_screen_args = construct_recording_args(options, screen_chunks_dir, "screen", &options.screen_index, w, adjusted_height).await.map_err(|e| e.to_string())?;-// let (screen_child, screen_stderr, screen_stdin) = start_screen_recording_process(ffmpeg_binary_path_str, &ffmpeg_screen_args).await.map_err(|e| e.to_string())?;--// let video_id = options.video_id.clone();-// tokio::spawn(async move {-// if let Err(e) = monitor_and_log_recording_start(screen_stderr, &video_id, "video").await {-// eprintln!("Error monitoring screen recording start: {}", e);-// }-// });--// Ok((screen_child, screen_stdin))-// }--async fn prepare_audio_recording(+async fn prepare_media_recording(options: &RecordingOptions,audio_chunks_dir: &Path,video_chunks_dir: &Path,audio_name: Option<String>,-) -> Result<AudioRecorder, String> {- // Assuming `AudioRecorder::start_audio_recording` is an async function.- // Prepare your AudioRecorder and start recording- let mut audio_recorder = AudioRecorder::new();+) -> Result<MediaRecorder, String> {+ let mut media_recorder = MediaRecorder::new();let audio_file_path = audio_chunks_dir.to_str().unwrap();let video_file_path = video_chunks_dir.to_str().unwrap();- audio_recorder.start_audio_recording(options.clone(), audio_file_path, video_file_path, audio_name.as_ref().map(String::as_str)).await?;- Ok(audio_recorder)-}--// async fn start_screen_recording_process(ffmpeg_binary_path_str: &str, ffmpeg_screen_args: &[String]) -> Result<(tokio::process::Child, ChildStderr, ChildStdin), io::Error> {-// let mut child = Command::new(ffmpeg_binary_path_str)-// .args(ffmpeg_screen_args)-// .stdin(Stdio::piped())-// .stdout(Stdio::piped())-// .stderr(Stdio::piped())-// .spawn()?;--// let stderr = child.stderr.take().expect("failed to take child stdout");-// let stdin = child.stdin.take().expect("failed to take child stdin");--// Ok((child, stderr, stdin))-// }--// async fn graceful_stop_ffmpeg(stdin: &mut tokio::process::ChildStdin) -> Result<(), std::io::Error> {-// stdin.write_all(b"q\n").await?;-// Ok(())-// }\ No newline at end of file+ media_recorder.start_media_recording(options.clone(), audio_file_path, video_file_path, audio_name.as_ref().map(String::as_str)).await?;+ Ok(media_recorder)+}\ No newline at end of filediff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 7e4c7210a..1c867e14b 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -76,8 +76,8 @@"title": "Cap","label": "main","url": "/",- "width": 285,- "height": 410,+ "width": 290,+ "height": 460,"maximized": false,"resizable": false,"fullscreen": false,diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsxindex 81f4bd190..a7eb1c099 100644--- a/apps/desktop/src/app/page.tsx+++ b/apps/desktop/src/app/page.tsx@@ -4,12 +4,30 @@ import React, { useState, useEffect } from "react";import { SignIn } from "@/components/windows/inner/SignIn";import { Recorder } from "@/components/windows/inner/Recorder";import { WindowActions } from "@/components/WindowActions";+import { Permissions } from "@/components/windows/Permissions";import { LogoSpinner } from "@cap/ui";+import { getPermissions, savePermissions } from "@/utils/helpers";+import { initializeCameraWindow } from "@/utils/recording/utils";export default function CameraPage() {const [isSignedIn, setIsSignedIn] = useState(false);const [cameraWindowOpen, setCameraWindowOpen] = useState(false);const [loading, setLoading] = useState(true);+ const [permissions, setPermissions] = useState(getPermissions());++ useEffect(() => {+ const checkPermissions = setInterval(() => {+ const updatedPermissions = getPermissions();+ if (+ updatedPermissions &&+ updatedPermissions.confirmed !== permissions.confirmed+ ) {+ setPermissions(updatedPermissions);+ }+ }, 1000);++ return () => clearInterval(checkPermissions);+ }, [permissions]);useEffect(() => {const checkSession = setInterval(() => {@@ -29,45 +47,8 @@ export default function CameraPage() {useEffect(() => {if (isSignedIn && !cameraWindowOpen) {- import("@tauri-apps/api/window").then(- ({ currentMonitor, WebviewWindow }) => {- setCameraWindowOpen(true);-- currentMonitor().then((monitor) => {- const windowWidth = 230;- const windowHeight = 230;-- if (monitor && monitor.size) {- const scalingFactor = monitor.scaleFactor;- const x = 100;- const y =- monitor.size.height / scalingFactor - windowHeight - 100;-- const existingCameraWindow = WebviewWindow.getByLabel("camera");- if (existingCameraWindow) {- console.log("Camera window already open.");- existingCameraWindow.close();- } else {- new WebviewWindow("camera", {- url: "/camera",- title: "Cap Camera",- width: windowWidth,- height: windowHeight,- x: x / scalingFactor,- y: y,- maximized: false,- resizable: false,- fullscreen: false,- transparent: true,- decorations: false,- alwaysOnTop: true,- center: false,- });- }- }- });- }- );+ initializeCameraWindow();+ setCameraWindowOpen(true);}}, [isSignedIn, cameraWindowOpen]);@@ -84,7 +65,11 @@ export default function CameraPage() {{isSignedIn ? (<><WindowActions />- <Recorder />+ {!permissions || permissions.confirmed === false ? (+ <Permissions />+ ) : (+ <Recorder />+ )}</>) : (<SignIn />diff --git a/apps/desktop/src/components/WindowActions.tsx b/apps/desktop/src/components/WindowActions.tsxindex 7168a9c23..4d712f6b4 100644--- a/apps/desktop/src/components/WindowActions.tsx+++ b/apps/desktop/src/components/WindowActions.tsx@@ -7,7 +7,7 @@ export const WindowActions = () => {const actionButtonBase = "w-3 h-3 bg-gray-500 rounded-full m-0 p-0 block";return (- <div className="w-full flex items-center -mt-3">+ <div className="w-full flex items-center -mt-3 z-20 absolute top-5"><div className="flex flex-grow items-center justify-between px-3"><div className="flex space-x-2"><div>diff --git a/apps/desktop/src/components/windows/Permissions.tsx b/apps/desktop/src/components/windows/Permissions.tsxnew file mode 100644index 000000000..dfb72a5f4--- /dev/null+++ b/apps/desktop/src/components/windows/Permissions.tsx@@ -0,0 +1,127 @@+import { Button, LogoBadge } from "@cap/ui";+import { useEffect, useState } from "react";+import { savePermissions, getPermissions } from "@/utils/helpers";+import { invoke } from "@tauri-apps/api/tauri";++export const Permissions = () => {+ const [permissionsOpened, setPermissionsOpened] = useState({+ screen: false,+ camera: false,+ microphone: false,+ });++ const [permissions, setPermissions] = useState({+ screen: false,+ camera: false,+ microphone: false,+ });++ const handlePermissionOpened = (permission: string) => {+ if (permission === "screen") {+ invoke("open_screen_capture_preferences");+ } else if (permission === "camera") {+ invoke("open_camera_preferences");+ } else if (permission === "microphone") {+ invoke("open_mic_preferences");+ }++ setPermissionsOpened((prev) => ({+ ...prev,+ [permission]: !prev[permission],+ }));+ };++ const handlePermissionConfirm = async (permission: string) => {+ await savePermissions(permission, true);+ setPermissions((prev) => ({+ ...prev,+ [permission]: true,+ }));+ };++ const handleAllPermissionsEnabled = async () => {+ await savePermissions("confirmed", true);+ };++ useEffect(() => {+ const fetchPermissions = async () => {+ const fetchedPermissions = await getPermissions();+ setPermissions(+ fetchedPermissions || {+ screen: false,+ camera: false,+ microphone: false,+ }+ );+ };+ fetchPermissions();+ }, []);++ const allPermissionsEnabled = Object.entries(permissions)+ .filter(([key]) => key !== "confirmed")+ .every(([, value]) => value);++ return (+ <div data-tauri-drag-region className="w-full space-y-3 px-3">+ <div className="text-center">+ <LogoBadge className="w-12 h-auto mx-auto mb-2" />+ <h1 className="text-lg">Welcome to Cap</h1>+ <p className="text-sm">+ Enable permissions to get started. Click "Confirm" after enabling each+ permission.+ </p>+ </div>+ <div className="space-y-3">+ {Object.keys(permissionsOpened).map((permission) => (+ <div+ key={permission}+ className="w-full rounded-full bg-gray-400 bg-opacity-50 py-3 px-4 flex items-center justify-between"+ >+ <div className="flex items-center">+ <div></div>+ <div>+ <p className="font-bold text-sm capitalize">{permission}</p>+ <p className="text-xs">To share your {permission}</p>+ </div>+ </div>+ <div>+ <Button+ size="sm"+ disabled={permissions && permissions[permission] === true}+ variant={+ permissions && permissions[permission] === true+ ? "default"+ : permissionsOpened[permission] === true+ ? "default"+ : "outline"+ }+ onClick={() => {+ permissionsOpened[permission] === true+ ? handlePermissionConfirm(permission)+ : handlePermissionOpened(permission);+ }}+ >+ {permissions && permissions[permission] === true+ ? "Enabled"+ : permissionsOpened[permission] === true+ ? "Confirm"+ : "Enable"}+ </Button>+ </div>+ </div>+ ))}+ </div>+ <div>+ <Button+ onClick={() => {+ handleAllPermissionsEnabled();+ }}+ className="w-full"+ disabled={!allPermissionsEnabled}+ >+ Continue+ </Button>+ </div>+ </div>+ );+};diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 5cee58c01..59c8318fa 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -32,6 +32,7 @@ export const Recorder = () => {const [currentStoppingMessage, setCurrentStoppingMessage] =useState("Stopping Recording");const [recordingTime, setRecordingTime] = useState("00:00");+ const [canStopRecording, setCanStopRecording] = useState(false);const handleContextClick = async (option: string) => {const { showMenu } = await import("tauri-plugin-context-menu");@@ -57,6 +58,25 @@ export const Recorder = () => {},}));+ filteredDevices.push({+ label: "None",+ disabled: false,+ event: async () => {+ try {+ await emit("change-device", {+ type: option,+ device: {+ label: "None",+ index: -1,+ kind: option === "video" ? "videoinput" : "audioinput",+ },+ });+ } catch (error) {+ console.error("Failed to emit change-device event:", error);+ }+ },+ });+await showMenu({items: [...filteredDevices],...(filteredDevices.length === 0 && {@@ -151,6 +171,10 @@ export const Recorder = () => {};const handleStopAllRecordings = async () => {+ if (!canStopRecording) {+ toast.error("Recording must be for a minimum of 3 seconds.");+ return;+ }setStoppingRecording(true);try {@@ -207,12 +231,18 @@ export const Recorder = () => {if (isRecording && !startingRecording) {const startTime = Date.now();+ setTimeout(() => setCanStopRecording(true), 5000);+intervalId = setInterval(() => {const seconds = Math.floor((Date.now() - startTime) / 1000);const minutes = Math.floor(seconds / 60);const formattedSeconds =seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;setRecordingTime(`${minutes}:${formattedSeconds}`);++ if (seconds >= 600) {+ handleStopAllRecordings();+ }}, 1000);}@@ -232,7 +262,7 @@ export const Recorder = () => {)} */}<divdata-tauri-drag-region- className="pt-4 relative flex items-center justify-center"+ className="w-full h-full px-3 pt-4 relative flex items-center justify-center"><div className="w-full"><div@@ -265,7 +295,7 @@ export const Recorder = () => {</div><div><label className="text-sm font-medium">Webcam / Video</label>- <div className="space-y-1">+ <div className="space-y-2"><ActionButtonwidth="full"handler={() => handleContextClick("video")}@@ -286,7 +316,7 @@ export const Recorder = () => {</div><Button{...(isRecording && { variant: "destructive" })}- className="w-[97.6%] flex mx-auto"+ className="w-full flex mx-auto"onClick={() => {if (isRecording) {handleStopAllRecordings();@@ -304,6 +334,9 @@ export const Recorder = () => {: `Stop - ${recordingTime}`: "Start Recording"}</Button>+ <div className="text-center mt-3">+ <p className="text-sm text-gray-500">10 min recording limit</p>+ </div></div><Toaster /></div>diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.tsindex 840a2e604..8377df453 100644--- a/apps/desktop/src/utils/helpers.ts+++ b/apps/desktop/src/utils/helpers.ts@@ -47,3 +47,37 @@ export const requestMediaDevicesPermission = async () => {console.error("Permissions to access media devices were denied.", error);}};++export const getPermissions = () => {+ try {+ if (typeof window !== "undefined") {+ const permissions = localStorage.getItem("permissions");++ if (permissions) {+ return JSON.parse(permissions);+ }+ }+ } catch (error) {+ console.error("Failed to get permissions:", error);+ }++ return { camera: false, microphone: false, screen: false, confirmed: false };+};++export const savePermissions = async (permission: string, value: boolean) => {+ try {+ if (typeof window !== "undefined") {+ let permissions = await getPermissions();++ permissions = permissions+ ? permissions+ : { camera: false, microphone: false, screen: false, confirmed: false };++ permissions[permission] = value;++ localStorage.setItem("permissions", JSON.stringify(permissions));+ }+ } catch (error) {+ console.error("Failed to save permissions:", error);+ }+};diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsxindex 464fceea3..61313ba4a 100644--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx@@ -9,7 +9,11 @@ import {useRef,} from "react";import { listen } from "@tauri-apps/api/event";-import { getLocalDevices, enumerateAndStoreDevices } from "./utils";+import {+ getLocalDevices,+ enumerateAndStoreDevices,+ initializeCameraWindow,+} from "./utils";export interface Devices {index: number;@@ -119,9 +123,15 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({payload: { type: "video" | "audio"; device: Devices };}) => {if (payload && payload.device) {+ console.log("change-device event:", payload);if (payload.type === "video") {- console.log("receiving video payload:");- console.log(payload);+ import("@tauri-apps/api/window").then(({ WebviewWindow }) => {+ if (WebviewWindow.getByLabel("camera")) {+ WebviewWindow.getByLabel("camera").close();+ } else {+ initializeCameraWindow();+ }+ });if (selectedVideoDevice?.index !== payload.device.index) {setSelectedVideoDevice(payload.device);}diff --git a/apps/desktop/src/utils/recording/utils.ts b/apps/desktop/src/utils/recording/utils.tsindex bd92609d6..8146290ca 100644--- a/apps/desktop/src/utils/recording/utils.ts+++ b/apps/desktop/src/utils/recording/utils.ts@@ -49,3 +49,40 @@ export const getSelectedVideoProperties = async () => {return videoDeviceProperties;}};++export const initializeCameraWindow = async () => {+ import("@tauri-apps/api/window").then(({ currentMonitor, WebviewWindow }) => {+ currentMonitor().then((monitor) => {+ const windowWidth = 230;+ const windowHeight = 230;++ if (monitor && monitor.size) {+ const scalingFactor = monitor.scaleFactor;+ const x = 100;+ const y = monitor.size.height / scalingFactor - windowHeight - 100;++ const existingCameraWindow = WebviewWindow.getByLabel("camera");+ if (existingCameraWindow) {+ console.log("Camera window already open.");+ existingCameraWindow.close();+ } else {+ new WebviewWindow("camera", {+ url: "/camera",+ title: "Cap Camera",+ width: windowWidth,+ height: windowHeight,+ x: x / scalingFactor,+ y: y,+ maximized: false,+ resizable: false,+ fullscreen: false,+ transparent: true,+ decorations: false,+ alwaysOnTop: true,+ center: false,+ });+ }+ }+ });+ });+};diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsxindex 5d088cd89..3e311d2cb 100644--- a/packages/ui/src/components/Button.tsx+++ b/packages/ui/src/components/Button.tsx@@ -10,7 +10,7 @@ const buttonVariants = cva(variants: {variant: {default:- "group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-primary ring-2 text-white ring-primary",+ "default-button group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-primary ring-2 text-white ring-primary",destructive:"group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-red-900 ring-2 text-white ring-900",outline: "border border-input bg-white text-primary hover:bg-gray-50",@@ -18,7 +18,7 @@ const buttonVariants = cva(},size: {default: "h-10 px-5 text-base",- sm: "h-8 rounded-lg px-3 text-sm",+ sm: "h-8 px-3 text-sm",lg: "h-10 px-5 text-lg",icon: "h-10 w-10",},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a8e22f7ef..f884f9e07 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -317,6 +317,9 @@ importers:nanoid:specifier: ^5.0.4version: 5.0.4+ next:+ specifier: 14.1.0next-auth:specifier: ^4.24.5