Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

refactor windows and tray

Brendan Allan9f5ffc2382b6
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index 0fdc66ff8..c5e3e208e 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -14,54 +14,6 @@ use crate::{
encoder::{uyvy422_frame, H264Encoder},
};
-pub const WINDOW_LABEL: &str = "camera";
-const CAMERA_ROUTE: &str = "/camera";
-const WINDOW_SIZE: f64 = 230.0 * 2.0;
-
-pub fn create_camera_window(app: AppHandle, ws_port: u16) {
- if let Some(window) = app.get_webview_window(WINDOW_LABEL) {
- window.set_focus().ok();
- } else {
- let monitor = app.primary_monitor().unwrap().unwrap();
-
- let window = tauri::webview::WebviewWindow::builder(
- &app,
- WINDOW_LABEL,
- WebviewUrl::App(CAMERA_ROUTE.into()),
- )
- .title("Cap")
- .maximized(false)
- .resizable(false)
- .shadow(false)
- .fullscreen(false)
- .decorations(false)
- .always_on_top(true)
- .content_protected(true)
- .visible_on_all_workspaces(true)
- .min_inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
- .inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
- .position(
- 100.0,
- (monitor.size().height as f64) / monitor.scale_factor() - WINDOW_SIZE - 100.0,
- )
- .initialization_script(&format!(
- "
- window.__CAP__ = window.__CAP__ ?? {{}};
- window.__CAP__.cameraWsPort = {ws_port};
- ",
- ))
- .build()
- .unwrap();
-
- #[cfg(target_os = "macos")]
- {
- use tauri_plugin_decorum::WebviewWindowExt;
-
- window.make_transparent().ok();
- }
- }
-}
-
#[tauri::command(async)]
#[specta::specta]
pub fn list_cameras() -> Vec<String> {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 25eea8d20..520e31fa0 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -8,17 +8,17 @@ mod flags;
mod general_settings;
mod hotkeys;
mod macos;
-mod main_window;
mod notifications;
mod permissions;
mod recording;
mod tray;
mod upload;
mod web_api;
+mod windows;
use audio::AppSounds;
use auth::AuthStore;
-use camera::{create_camera_window, list_cameras, CameraFeed};
+use camera::{list_cameras, CameraFeed};
use cap_editor::{AudioData, EditorState, ProjectRecordings};
use cap_editor::{EditorInstance, FRAMES_WS_PATH};
use cap_ffmpeg::FFmpeg;
@@ -30,10 +30,8 @@ use cap_utils::create_named_pipe;
use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use image::{ImageBuffer, Rgba};
-use main_window::create_main_window;
use mp4::Mp4Reader;
use num_traits::ToBytes;
-use objc2_app_kit::NSScreenSaverWindowLevel;
use png::{ColorType, Encoder};
use recording::{DisplaySource, InProgressRecording};
use scap::capturer::Capturer;
@@ -49,9 +47,8 @@ use std::{
collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
time::Duration,
};
-use tauri::{AppHandle, Manager, State, WebviewUrl, WebviewWindow, WindowEvent};
-use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};
-use tauri_plugin_decorum::WebviewWindowExt;
+use tauri::{AppHandle, Manager, Runtime, State, WindowEvent};
+use tauri_nspanel::ManagerExt;
use tauri_plugin_notification::PermissionState;
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
@@ -62,6 +59,7 @@ use tokio::{
time::sleep,
};
use upload::{upload_image, upload_individual_file, upload_video};
+use windows::CapWindow;
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -111,9 +109,6 @@ enum UploadResult {
UpgradeRequired,
}
-const WINDOW_CAPTURE_OCCLUDER_LABEL: &str = "window-capture-occluder";
-const IN_PROGRESS_RECORDINGS_LABEL: &str = "in-progress-recordings";
-
impl App {
pub fn set_current_recording(&mut self, new_value: InProgressRecording) {
let option = Some(new_value);
@@ -126,45 +121,7 @@ impl App {
CurrentRecordingChanged(json).emit(&self.handle).ok();
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();
- }
- }
+ CapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
self.close_occluder_window();
}
@@ -177,20 +134,24 @@ impl App {
}
fn close_occluder_window(&self) {
- self.handle
- .get_webview_window(WINDOW_CAPTURE_OCCLUDER_LABEL)
- .map(|window| window.close().ok());
+ if let Some(window) = CapWindow::WindowCaptureOccluder.get(&self.handle) {
+ window.close().ok();
+ }
}
async fn set_start_recording_options(&mut self, new_options: RecordingOptions) {
- match self.handle.get_webview_window(camera::WINDOW_LABEL) {
+ match (CapWindow::Camera { ws_port: 0 }).get(&self.handle) {
Some(window) if new_options.camera_label.is_none() => {
println!("closing camera window");
window.close().ok();
}
None if new_options.camera_label.is_some() => {
println!("creating camera window");
- create_camera_window(self.handle.clone(), self.camera_ws_port);
+ CapWindow::Camera {
+ ws_port: self.camera_ws_port,
+ }
+ .show(&self.handle)
+ .ok();
}
_ => {}
}
@@ -339,15 +300,14 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result
state.set_current_recording(recording);
- if let Some(window) = app.get_webview_window("main") {
+ if let Some(window) = CapWindow::Main.get(&app) {
window.minimize().ok();
}
- let window = app
- .get_webview_window(IN_PROGRESS_RECORDINGS_LABEL)
- .unwrap();
- window.eval("window.location.reload()").unwrap();
- window.show().unwrap();
+ if let Some(window) = (CapWindow::InProgressRecording { position: None }).get(&app) {
+ window.eval("window.location.reload()").unwrap();
+ window.show().unwrap();
+ }
AppSounds::StartRecording.play();
@@ -390,38 +350,6 @@ async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
Ok(())
}
-fn create_in_progress_recording_window(app: &AppHandle) {
- let monitor = app.primary_monitor().unwrap().unwrap();
-
- let width = 160.0;
- let height = 40.0;
-
- WebviewWindow::builder(
- app,
- IN_PROGRESS_RECORDINGS_LABEL,
- tauri::WebviewUrl::App("/in-progress-recording".into()),
- )
- .title("Cap In Progress Recording")
- .maximized(false)
- .resizable(false)
- .fullscreen(false)
- .decorations(false)
- .shadow(true)
- .always_on_top(true)
- .transparent(true)
- .visible_on_all_workspaces(true)
- .content_protected(true)
- .accept_first_mouse(true)
- .inner_size(width, height)
- .position(
- ((monitor.size().width as f64) / monitor.scale_factor() - width) / 2.0,
- (monitor.size().height as f64) / monitor.scale_factor() - height - 120.0,
- )
- .visible(false)
- .build()
- .ok();
-}
-
#[tauri::command]
#[specta::specta]
async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
@@ -439,12 +367,11 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
current_recording.stop();
println!("Recording stopped");
- let window = app
- .get_webview_window(IN_PROGRESS_RECORDINGS_LABEL)
- .unwrap();
- window.hide().unwrap();
+ if let Some(window) = (CapWindow::InProgressRecording { position: None }).get(&app) {
+ window.hide().unwrap();
+ }
- if let Some(window) = app.get_webview_window("main") {
+ if let Some(window) = CapWindow::Main.get(&app) {
window.unminimize().ok();
}
@@ -1179,78 +1106,10 @@ async fn remove_fake_window(
Ok(())
}
-const PREV_RECORDINGS_WINDOW: &str = "prev-recordings";
-
#[tauri::command(async)]
#[specta::specta]
fn show_previous_recordings_window(app: AppHandle) {
- if let Some(window) = app.get_webview_window(PREV_RECORDINGS_WINDOW) {
- window.show().ok();
- return;
- }
- if let Ok(panel) = app.get_webview_panel(PREV_RECORDINGS_WINDOW) {
- if !panel.is_visible() {
- panel.show();
- }
- return;
- };
-
- let Some(monitor) = app.primary_monitor().ok().flatten() else {
- return;
- };
-
- let Some(window) = WebviewWindow::builder(
- &app,
- PREV_RECORDINGS_WINDOW,
- tauri::WebviewUrl::App("/prev-recordings".into()),
- )
- .title("Cap")
- .maximized(false)
- .resizable(false)
- .fullscreen(false)
- .decorations(false)
- .shadow(false)
- .always_on_top(true)
- .visible_on_all_workspaces(true)
- .accept_first_mouse(true)
- .content_protected(true)
- .inner_size(
- 350.0,
- (monitor.size().height as f64) / monitor.scale_factor(),
- )
- .position(0.0, 0.0)
- .build()
- .ok() else {
- return;
- };
-
- use tauri_plugin_decorum::WebviewWindowExt;
- window.make_transparent().ok();
-
- app.run_on_main_thread({
- let window = window.clone();
- move || {
- use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;
- use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;
-
- let panel = window.to_panel().unwrap();
-
- panel.set_level(NSMainMenuWindowLevel);
-
- panel.set_collection_behaviour(
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient
- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace
- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
- | NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle,
- );
-
- // seems like this doesn't work properly -_-
- #[allow(non_upper_case_globals)]
- const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;
- panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);
- }
- })
- .ok();
+ let window = CapWindow::PrevRecordings.show(&app).unwrap();
tokio::spawn(async move {
let state = app.state::<FakeWindowBounds>();
@@ -1296,29 +1155,14 @@ fn show_previous_recordings_window(app: AppHandle) {
#[specta::specta]
fn open_editor(app: AppHandle, id: String) {
println!("Opening editor for recording: {}", id);
- let window = WebviewWindow::builder(
- &app,
- format!("editor-{id}"),
- WebviewUrl::App(format!("/editor?id={id}").into()),
- )
- .inner_size(1150.0, 800.0)
- .title("Cap Editor")
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .accept_first_mouse(true)
- .theme(Some(tauri::Theme::Light))
- .build()
- .unwrap();
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(20.0, 48.0).unwrap();
+ CapWindow::Editor { project_id: id }.show(&app).unwrap();
}
#[tauri::command(async)]
#[specta::specta]
fn close_previous_recordings_window(app: AppHandle) {
- if let Ok(panel) = app.get_webview_panel(PREV_RECORDINGS_WINDOW) {
+ if let Ok(panel) = app.get_webview_panel(&CapWindow::PrevRecordings.label()) {
panel.released_when_closed(true);
panel.close();
}
@@ -1327,8 +1171,9 @@ fn close_previous_recordings_window(app: AppHandle) {
#[tauri::command(async)]
#[specta::specta]
fn focus_captures_panel(app: AppHandle) {
- let panel = app.get_webview_panel(PREV_RECORDINGS_WINDOW).unwrap();
- panel.make_key_window();
+ if let Ok(panel) = app.get_webview_panel(&CapWindow::PrevRecordings.label()) {
+ panel.make_key_window();
+ }
}
#[derive(Serialize, Deserialize, specta::Type, Clone)]
@@ -1442,105 +1287,31 @@ fn open_main_window(app: AppHandle) {
return;
}
- create_main_window(app);
+ CapWindow::Main.show(&app).ok();
}
#[tauri::command]
#[specta::specta]
async fn open_feedback_window(app: AppHandle) {
- let window =
- WebviewWindow::builder(&app, "feedback", tauri::WebviewUrl::App("/feedback".into()))
- .title("Cap Feedback")
- .inner_size(400.0, 400.0)
- .resizable(false)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
-
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ CapWindow::Feedback.show(&app).ok();
}
#[tauri::command]
#[specta::specta]
async fn open_upgrade_window(app: AppHandle) {
- if let Some(window) = app.get_webview_window("upgrade") {
- window.set_focus().ok();
- return;
- }
-
- let window = WebviewWindow::builder(&app, "upgrade", tauri::WebviewUrl::App("/upgrade".into()))
- .title("Cap Upgrade")
- .inner_size(800.0, 850.0)
- .resizable(false)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
-
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ CapWindow::Upgrade.show(&app).ok();
}
#[tauri::command]
#[specta::specta]
async fn open_changelog_window(app: AppHandle) {
- let window = WebviewWindow::builder(
- &app,
- "changelog",
- tauri::WebviewUrl::App("/changelog".into()),
- )
- .title("Cap Changelog")
- .inner_size(600.0, 450.0)
- .resizable(true)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
-
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ CapWindow::Changelog.show(&app);
}
#[tauri::command]
#[specta::specta]
async fn open_settings_window(app: AppHandle, page: String) {
- let window = WebviewWindow::builder(
- &app,
- "settings",
- tauri::WebviewUrl::App(format!("/settings?page={page}").into()),
- )
- .title("Cap Settings")
- .inner_size(600.0, 450.0)
- .resizable(true)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
-
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ CapWindow::Settings { page: Some(page) }.show(&app);
}
#[tauri::command]
@@ -1812,7 +1583,7 @@ async fn take_screenshot(app: AppHandle, state: MutableState<'_, App>) -> Result
..Default::default()
};
- if let Some(window) = app.get_webview_window("main") {
+ if let Some(window) = CapWindow::Main.get(&app) {
window.hide().ok();
}
@@ -1870,7 +1641,7 @@ async fn take_screenshot(app: AppHandle, state: MutableState<'_, App>) -> Result
AppSounds::Screenshot.play();
- if let Some(window) = app.get_webview_window("main") {
+ if let Some(window) = CapWindow::Main.get(&app) {
window.show().ok();
}
@@ -2116,11 +1887,11 @@ async fn delete_auth_open_signin(app: AppHandle) -> Result<(), String> {
window.close().ok();
}
- if let Some(window) = app.get_webview_window("main") {
+ if let Some(window) = CapWindow::Main.get(&app) {
window.close().ok();
}
- while app.get_webview_window("main").is_some() {
+ while CapWindow::Main.get(&app).is_some() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
@@ -2309,7 +2080,9 @@ pub async fn run() {
tray::create_tray(&app_handle).unwrap();
- create_in_progress_recording_window(app.app_handle());
+ CapWindow::InProgressRecording { position: None }
+ .show(app.app_handle())
+ .ok();
let app_handle_clone = app_handle.clone();
RequestStartRecording::listen_any(app, move |_| {
@@ -2394,12 +2167,11 @@ pub async fn run() {
})
.on_window_event(|window, event| {
let label = window.label();
- if label.starts_with("editor-") {
+ if let CapWindow::Editor { project_id } = CapWindow::from_label(label) {
if let WindowEvent::CloseRequested { .. } = event {
- let id = label.strip_prefix("editor-").unwrap().to_string();
let app = window.app_handle().clone();
tokio::spawn(async move {
- if let Some(editor) = remove_editor_instance(&app, id.clone()).await {
+ if let Some(editor) = remove_editor_instance(&app, project_id).await {
editor.dispose().await;
}
});
@@ -2410,8 +2182,8 @@ pub async fn run() {
match event {
WindowEvent::Destroyed => {
- if window.label() == "main" {
- if let Some(w) = app.get_webview_window(camera::WINDOW_LABEL) {
+ if let CapWindow::Main = CapWindow::from_label(window.label()) {
+ if let Some(w) = (CapWindow::Camera { ws_port: 0 }).get(app) {
w.close().ok();
}
}
@@ -2421,7 +2193,7 @@ pub async fn run() {
&& app
.webview_windows()
.keys()
- .all(|label| !window_activates_dock(label))
+ .all(|label| !CapWindow::from_label(label).activates_dock())
{
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory)
@@ -2430,7 +2202,7 @@ pub async fn run() {
}
}
WindowEvent::Focused(focused) if *focused => {
- if window_activates_dock(label) {
+ if CapWindow::from_label(label).activates_dock() {
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Regular)
.ok();
@@ -2448,14 +2220,10 @@ pub async fn run() {
});
}
-fn window_activates_dock(label: &str) -> bool {
- label == "main" || label.starts_with("editor-") || label == "settings"
-}
-
type EditorInstancesState = Arc<Mutex<HashMap<String, Arc<EditorInstance>>>>;
pub async fn remove_editor_instance(
- app: &AppHandle,
+ app: &AppHandle<impl Runtime>,
video_id: String,
) -> Option<Arc<EditorInstance>> {
let map = match app.try_state::<EditorInstancesState>() {
diff --git a/apps/desktop/src-tauri/src/main_window.rs b/apps/desktop/src-tauri/src/main_window.rs
deleted file mode 100644
index 0fd4f7fb2..000000000
--- a/apps/desktop/src-tauri/src/main_window.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use tauri::{AppHandle, Manager, WebviewWindow};
-
-pub fn create_main_window(app: AppHandle) -> WebviewWindow {
- if let Some(window) = app.get_webview_window("main") {
- println!("Main window already exists, setting focus");
- window.set_focus().ok();
- return window;
- }
-
- println!("Creating new main window");
- let window = WebviewWindow::builder(&app, "main", tauri::WebviewUrl::App("/".into()))
- .title("Cap")
- .inner_size(300.0, 375.0)
- .resizable(false)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .theme(Some(tauri::Theme::Light))
- .build()
- .unwrap();
-
- #[cfg(target_os = "macos")]
- {
- use tauri_plugin_decorum::WebviewWindowExt;
-
- println!("Creating overlay titlebar");
- window.create_overlay_titlebar().unwrap();
-
- println!("Setting traffic lights inset for macOS");
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
- }
-
- println!("Showing main window");
- window.show().unwrap();
- println!("Main window opened successfully");
-
- window
-}
diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rs
index f8d2aebe4..72b161c92 100644
--- a/apps/desktop/src-tauri/src/permissions.rs
+++ b/apps/desktop/src-tauri/src/permissions.rs
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
-use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindow};
-use tauri_plugin_decorum::WebviewWindowExt;
+use tauri::AppHandle;
use core_foundation::boolean::CFBoolean;
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; // Import CFDictionaryRef
@@ -8,6 +7,8 @@ use core_foundation::string::CFString;
#[cfg(target_os = "macos")]
use nokhwa_bindings_macos::{AVAuthorizationStatus, AVMediaType};
+use crate::windows::CapWindow;
+
#[cfg(target_os = "macos")]
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
@@ -214,26 +215,5 @@ pub fn request_accessibility_permission() {
#[tauri::command]
#[specta::specta]
pub fn open_permissions_window(app: AppHandle) {
- if let Some(window) = app.get_webview_window("permissions") {
- window.set_focus().ok();
- return;
- }
-
- let window =
- WebviewWindow::builder(&app, "permissions", WebviewUrl::App("/permissions".into()))
- .title("Cap")
- .inner_size(300.0, 350.0)
- .resizable(false)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
-
- window.create_overlay_titlebar().unwrap();
- #[cfg(target_os = "macos")]
- window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ CapWindow::Permissions.show(&app).ok();
}
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index 3cd12da56..1797b5e2d 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -1,72 +1,103 @@
+use crate::windows::CapWindow;
use crate::{
RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,
RequestStartRecording, RequestStopRecording,
};
-use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
+use tauri::menu::{MenuId, PredefinedMenuItem};
use tauri::{
image::Image,
- menu::{IsMenuItem, Menu, MenuItem},
+ menu::{Menu, MenuItem},
tray::TrayIconBuilder,
- AppHandle, Manager, Runtime, WebviewWindow,
+ AppHandle,
};
use tauri_specta::Event;
-pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
- // Add version menu item as the first item
- let version = env!("CARGO_PKG_VERSION");
- let version_i = MenuItem::with_id(
- app,
- "version",
- format!("Cap v{}", version),
- false,
- None::<&str>,
- )?;
-
- let new_recording_i = MenuItem::with_id(
- app,
- "new_recording",
- "Start New Recording",
- true,
- None::<&str>,
- )?;
-
- let take_screenshot_i = MenuItem::with_id(
- app,
- "take_screenshot",
- "Take Screenshot",
- true,
- None::<&str>,
- )?;
-
- let previous_recordings_i = MenuItem::with_id(
- app,
- "previous_recordings",
- "Previous Recordings",
- true,
- None::<&str>,
- )?;
+pub enum TrayItem {
+ OpenCap,
+ StartNewRecording,
+ TakeScreenshot,
+ PreviousRecordings,
+ PreviousScreenshots,
+ OpenSettings,
+ Quit,
+}
- let previous_screenshots_i = MenuItem::with_id(
- app,
- "previous_screenshots",
- "Previous Screenshots",
- true,
- None::<&str>,
- )?;
+impl From<TrayItem> for MenuId {
+ fn from(value: TrayItem) -> Self {
+ match value {
+ TrayItem::OpenCap => "open_cap",
+ TrayItem::StartNewRecording => "new_recording",
+ TrayItem::TakeScreenshot => "take_screenshot",
+ TrayItem::PreviousRecordings => "previous_recordings",
+ TrayItem::PreviousScreenshots => "previous_screenshots",
+ TrayItem::OpenSettings => "open_settings",
+ TrayItem::Quit => "quit",
+ }
+ .into()
+ }
+}
- let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;
+impl From<MenuId> for TrayItem {
+ fn from(value: MenuId) -> Self {
+ match value.0.as_str() {
+ "open_cap" => TrayItem::OpenCap,
+ "new_recording" => TrayItem::StartNewRecording,
+ "take_screenshot" => TrayItem::TakeScreenshot,
+ "previous_recordings" => TrayItem::PreviousRecordings,
+ "previous_screenshots" => TrayItem::PreviousScreenshots,
+ "open_settings" => TrayItem::OpenSettings,
+ "quit" => TrayItem::Quit,
+ value => unreachable!("Invalid tray item id {value}"),
+ }
+ }
+}
+pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
let menu = Menu::with_items(
app,
&[
- &version_i,
- &new_recording_i,
- &take_screenshot_i,
- &previous_recordings_i,
- &previous_screenshots_i,
- &quit_i,
+ &MenuItem::with_id(
+ app,
+ "version",
+ format!("Cap v{}", env!("CARGO_PKG_VERSION")),
+ false,
+ None::<&str>,
+ )?,
+ &MenuItem::with_id(app, TrayItem::OpenCap, "Open Cap", true, None::<&str>)?,
+ &PredefinedMenuItem::separator(app)?,
+ &MenuItem::with_id(
+ app,
+ TrayItem::StartNewRecording,
+ "Start New Recording",
+ true,
+ None::<&str>,
+ )?,
+ &MenuItem::with_id(
+ app,
+ TrayItem::TakeScreenshot,
+ "Take Screenshot",
+ true,
+ None::<&str>,
+ )?,
+ &MenuItem::with_id(
+ app,
+ TrayItem::PreviousRecordings,
+ "Previous Recordings",
+ true,
+ None::<&str>,
+ )?,
+ &MenuItem::with_id(
+ app,
+ TrayItem::PreviousScreenshots,
+ "Previous Screenshots",
+ true,
+ None::<&str>,
+ )?,
+ &PredefinedMenuItem::separator(app)?,
+ &MenuItem::with_id(app, TrayItem::OpenSettings, "Settings", true, None::<&str>)?,
+ &MenuItem::with_id(app, TrayItem::Quit, "Quit Cap", true, None::<&str>)?,
],
)?;
let app_handle = app.clone();
@@ -79,60 +110,35 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
.menu_on_left_click(true)
.on_menu_event({
let app_handle = app_handle.clone();
- move |app: &AppHandle<R>, event| {
- match event.id.as_ref() {
- "new_recording" => {
- if let Some(window) = app.get_webview_window("main") {
- window.set_focus().ok();
- } else {
- let Some(_window) = WebviewWindow::builder(
- &app.clone(),
- "main",
- tauri::WebviewUrl::App("/".into()),
- )
- .title("Cap")
- .inner_size(300.0, 375.0)
- .resizable(false)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .theme(Some(tauri::Theme::Light))
- .build()
- .ok() else {
- return;
- };
- }
-
- let _ = RequestStartRecording.emit(&app_handle);
+ move |app: &AppHandle, event| match TrayItem::from(event.id) {
+ TrayItem::OpenCap => {
+ CapWindow::Main.show(&app_handle);
+ }
+ TrayItem::StartNewRecording => {
+ CapWindow::Main.show(&app_handle);
- // window.create_overlay_titlebar().unwrap();
- // #[cfg(target_os = "macos")]
- // window.set_traffic_lights_inset(14.0, 22.0).unwrap();
- }
- "take_screenshot" => {
- let _ = RequestNewScreenshot.emit(&app_handle);
- }
- "previous_recordings" => {
- let _ = RequestOpenSettings {
- page: "recordings".to_string(),
- }
- .emit(&app_handle);
- }
- "previous_screenshots" => {
- let _ = RequestOpenSettings {
- page: "screenshots".to_string(),
- }
- .emit(&app_handle);
- }
- "quit" => {
- app.exit(0);
+ let _ = RequestStartRecording.emit(&app_handle);
+ }
+ TrayItem::TakeScreenshot => {
+ let _ = RequestNewScreenshot.emit(&app_handle);
+ }
+ TrayItem::PreviousRecordings => {
+ let _ = RequestOpenSettings {
+ page: "recordings".to_string(),
}
- _ => {
- println!("Unhandled menu item clicked: {:?}", event);
+ .emit(&app_handle);
+ }
+ TrayItem::PreviousScreenshots => {
+ let _ = RequestOpenSettings {
+ page: "screenshots".to_string(),
}
+ .emit(&app_handle);
+ }
+ TrayItem::OpenSettings => {
+ CapWindow::Settings { page: None }.show(&app_handle);
+ }
+ TrayItem::Quit => {
+ app.exit(0);
}
}
})
@@ -191,61 +197,3 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
Ok(())
}
-
-fn handle_new_recording_added<R: Runtime>(app: &AppHandle<R>, path: PathBuf) -> tauri::Result<()> {
- if let Some(tray_handle) = app.tray_by_id("tray") {
- // Recreate the entire menu
- let version = env!("CARGO_PKG_VERSION");
- let version_i = MenuItem::with_id(
- app,
- "version",
- format!("Cap v{}", version),
- false,
- None::<&str>,
- )?;
- let new_recording_i = MenuItem::with_id(
- app,
- "new_recording",
- "Start New Recording",
- true,
- None::<&str>,
- )?;
- let take_screenshot_i = MenuItem::with_id(
- app,
- "take_screenshot",
- "Take Screenshot",
- true,
- None::<&str>,
- )?;
- let previous_recordings_i = MenuItem::with_id(
- app,
- "previous_recordings",
- "Previous Recordings",
- true,
- None::<&str>,
- )?;
- let previous_screenshots_i = MenuItem::with_id(
- app,
- "previous_screenshots",
- "Previous Screenshots",
- true,
- None::<&str>,
- )?;
- let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;
-
- let menu_items: Vec<&dyn IsMenuItem<R>> = vec![
- &version_i,
- &new_recording_i,
- &take_screenshot_i,
- &previous_recordings_i,
- &previous_screenshots_i,
- &quit_i,
- ];
- let menu = Menu::with_items(app, &menu_items)?;
-
- // Set the updated menu
- tray_handle.set_menu(Some(menu))?;
- }
-
- Ok(())
-}
diff --git a/apps/desktop/src-tauri/src/web_api.rs b/apps/desktop/src-tauri/src/web_api.rs
index a0b4c5fad..d2e6055a6 100644
--- a/apps/desktop/src-tauri/src/web_api.rs
+++ b/apps/desktop/src-tauri/src/web_api.rs
@@ -2,11 +2,7 @@ use reqwest::StatusCode;
use tauri::{Emitter, Manager, Runtime};
use tauri_specta::Event;
-use crate::{
- auth::{AuthStore, AuthenticationInvalid},
- main_window::create_main_window,
- open_main_window,
-};
+use crate::auth::{AuthStore, AuthenticationInvalid};
pub fn make_url(pathname: impl AsRef<str>) -> String {
let server_url_base = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
new file mode 100644
index 000000000..e42b381a3
--- /dev/null
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -0,0 +1,403 @@
+use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindow, Wry};
+
+pub enum CapWindow {
+ Main,
+ Settings { page: Option<String> },
+ Editor { project_id: String },
+ Permissions,
+ PrevRecordings,
+ WindowCaptureOccluder,
+ Camera { ws_port: u16 },
+ InProgressRecording { position: Option<(f64, f64)> },
+ Feedback,
+ Upgrade,
+ Changelog,
+}
+
+impl CapWindow {
+ pub fn from_label(label: &str) -> Self {
+ match label {
+ "main" => Self::Main,
+ "settings" => Self::Settings { page: None },
+ "camera" => Self::Camera { ws_port: 0 },
+ "window-capture-occluder" => Self::WindowCaptureOccluder,
+ "in-progress-recording" => Self::InProgressRecording { position: None },
+ "prev-recordings" => Self::PrevRecordings,
+ "permission" => Self::Permissions,
+ "feedback" => Self::Feedback,
+ "upgrade" => Self::Upgrade,
+ "changelog" => Self::Changelog,
+ s if s.starts_with("editor-") => Self::Editor {
+ project_id: s.replace("editor-", ""),
+ },
+ _ => unreachable!("unknown window label: {}", label),
+ }
+ }
+
+ pub fn label(&self) -> String {
+ match self {
+ Self::Main => "main".to_string(),
+ Self::Settings { .. } => "settings".to_string(),
+ Self::Camera { .. } => "camera".to_string(),
+ Self::WindowCaptureOccluder => "window-capture-occluder".to_string(),
+ Self::InProgressRecording { .. } => "in-progress-recording".to_string(),
+ Self::PrevRecordings => "prev-recordings".to_string(),
+ Self::Editor { project_id } => format!("editor-{}", project_id),
+ Self::Permissions => "permissions".to_string(),
+ Self::Feedback => "feedback".to_string(),
+ Self::Upgrade => "upgrade".to_string(),
+ Self::Changelog => "changelog".to_string(),
+ }
+ }
+
+ pub fn title(&self) -> String {
+ match self {
+ Self::Settings { .. } => "Cap Settings".to_string(),
+ Self::WindowCaptureOccluder => "Cap Window Capture Occluder".to_string(),
+ Self::InProgressRecording { .. } => "Cap In Progress Recording".to_string(),
+ Self::Editor { .. } => "Cap Editor".to_string(),
+ Self::Permissions => "Cap Permissions".to_string(),
+ Self::Changelog => "Cap Changelog".to_string(),
+ _ => "Cap".to_string(),
+ }
+ }
+
+ pub fn activates_dock(&self) -> bool {
+ match self {
+ CapWindow::Main => true,
+ CapWindow::Editor { .. } => true,
+ CapWindow::Settings { .. } => true,
+ CapWindow::Permissions => true,
+ CapWindow::Feedback => true,
+ CapWindow::Upgrade => true,
+ CapWindow::Changelog => true,
+ _ => false,
+ }
+ }
+
+ pub fn get(&self, app: &AppHandle<Wry>) -> Option<WebviewWindow> {
+ let label = self.label();
+ app.get_webview_window(&label)
+ }
+
+ pub fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {
+ let label = self.label();
+
+ if let Some(window) = self.get(app) {
+ window.show().ok();
+ window.set_focus().ok();
+
+ return Ok(window);
+ }
+
+ let monitor = app.primary_monitor()?.unwrap();
+
+ Ok(match self {
+ Self::Main => {
+ let window = WebviewWindow::builder(app, label, WebviewUrl::App("/".into()))
+ .title(self.title())
+ .inner_size(300.0, 375.0)
+ .resizable(false)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .theme(Some(tauri::Theme::Light))
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ Self::Settings { page } => {
+ let window = WebviewWindow::builder(
+ app,
+ label,
+ WebviewUrl::App(
+ format!("/settings/{}", page.clone().unwrap_or_default()).into(),
+ ),
+ )
+ .title(self.title())
+ .min_inner_size(600.0, 450.0)
+ .resizable(true)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ Self::Camera { ws_port } => {
+ const WINDOW_SIZE: f64 = 230.0 * 2.0;
+
+ let window = tauri::webview::WebviewWindow::builder(
+ app,
+ label,
+ WebviewUrl::App("/camera".into()),
+ )
+ .title("Cap")
+ .maximized(false)
+ .resizable(false)
+ .shadow(false)
+ .fullscreen(false)
+ .decorations(false)
+ .always_on_top(true)
+ .content_protected(true)
+ .visible_on_all_workspaces(true)
+ .min_inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
+ .inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
+ .position(
+ 100.0,
+ (monitor.size().height as f64) / monitor.scale_factor() - WINDOW_SIZE - 100.0,
+ )
+ .initialization_script(&format!(
+ "
+ window.__CAP__ = window.__CAP__ ?? {{}};
+ window.__CAP__.cameraWsPort = {ws_port};
+ ",
+ ))
+ .build()?;
+
+ #[cfg(target_os = "macos")]
+ {
+ use tauri_plugin_decorum::WebviewWindowExt;
+
+ window.make_transparent().ok();
+ }
+
+ window
+ }
+ Self::WindowCaptureOccluder => {
+ let window = WebviewWindow::builder(
+ app,
+ label,
+ WebviewUrl::App("/window-capture-occluder".into()),
+ )
+ .title(self.title())
+ .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();
+
+ window.set_ignore_cursor_events(true).unwrap();
+
+ #[cfg(target_os = "macos")]
+ {
+ use objc2_app_kit::NSScreenSaverWindowLevel;
+ use tauri_plugin_decorum::WebviewWindowExt;
+
+ window
+ .set_window_level(NSScreenSaverWindowLevel as u32)
+ .unwrap();
+ window.make_transparent().unwrap();
+ }
+
+ window
+ }
+ Self::InProgressRecording { position } => {
+ let width = 160.0;
+ let height = 40.0;
+
+ let window = WebviewWindow::builder(
+ app,
+ label,
+ tauri::WebviewUrl::App("/in-progress-recording".into()),
+ )
+ .title("Cap In Progress Recording")
+ .maximized(false)
+ .resizable(false)
+ .fullscreen(false)
+ .decorations(false)
+ .shadow(true)
+ .always_on_top(true)
+ .transparent(true)
+ .visible_on_all_workspaces(true)
+ .content_protected(true)
+ .accept_first_mouse(true)
+ .inner_size(width, height)
+ .position(
+ ((monitor.size().width as f64) / monitor.scale_factor() - width) / 2.0,
+ (monitor.size().height as f64) / monitor.scale_factor() - height - 120.0,
+ )
+ .visible(false)
+ .build()?;
+
+ window
+ }
+ Self::PrevRecordings => {
+ let window =
+ WebviewWindow::builder(app, &label, WebviewUrl::App("/prev-recordings".into()))
+ .title(self.title())
+ .maximized(false)
+ .resizable(false)
+ .fullscreen(false)
+ .decorations(false)
+ .shadow(false)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true)
+ .accept_first_mouse(true)
+ .content_protected(true)
+ .inner_size(
+ 350.0,
+ (monitor.size().height as f64) / monitor.scale_factor(),
+ )
+ .position(0.0, 0.0)
+ .build()?;
+
+ #[cfg(target_os = "macos")]
+ {
+ use tauri_plugin_decorum::WebviewWindowExt;
+ window.make_transparent().ok();
+
+ app.run_on_main_thread({
+ let window = window.clone();
+ move || {
+ use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;
+ use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;
+
+ let panel = window.to_panel().unwrap();
+
+ panel.set_level(cocoa::appkit::NSMainMenuWindowLevel);
+
+ panel.set_collection_behaviour(
+ NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle,
+ );
+
+ // seems like this doesn't work properly -_-
+ #[allow(non_upper_case_globals)]
+ const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;
+ panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);
+ }
+ }).ok();
+ }
+
+ window
+ }
+ Self::Editor { project_id } => {
+ let window = WebviewWindow::builder(
+ app,
+ label,
+ WebviewUrl::App(format!("/editor?id={project_id}").into()),
+ )
+ .inner_size(1150.0, 800.0)
+ .title(self.title())
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .accept_first_mouse(true)
+ .theme(Some(tauri::Theme::Light))
+ .build()?;
+
+ #[cfg(target_os = "macos")]
+ {
+ use tauri_plugin_decorum::WebviewWindowExt;
+ window.create_overlay_titlebar().unwrap();
+ window.set_traffic_lights_inset(20.0, 48.0).unwrap();
+ }
+
+ window
+ }
+ Self::Permissions => {
+ let window =
+ WebviewWindow::builder(app, label, WebviewUrl::App("/permissions".into()))
+ .title(self.title())
+ .inner_size(300.0, 350.0)
+ .resizable(false)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ Self::Feedback => {
+ let window =
+ WebviewWindow::builder(app, label, tauri::WebviewUrl::App("/feedback".into()))
+ .title(self.title())
+ .inner_size(400.0, 400.0)
+ .resizable(false)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ Self::Upgrade => {
+ let window =
+ WebviewWindow::builder(app, label, tauri::WebviewUrl::App("/upgrade".into()))
+ .title(self.title())
+ .inner_size(800.0, 850.0)
+ .resizable(false)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ Self::Changelog => {
+ let window =
+ WebviewWindow::builder(app, label, tauri::WebviewUrl::App("/changelog".into()))
+ .title(self.title())
+ .inner_size(600.0, 450.0)
+ .resizable(true)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()?;
+
+ apply_window_chrome(&window);
+
+ window
+ }
+ })
+ }
+}
+
+fn apply_window_chrome(window: &WebviewWindow<Wry>) {
+ #[cfg(target_os = "macos")]
+ {
+ use tauri_plugin_decorum::WebviewWindowExt;
+ window.create_overlay_titlebar().unwrap();
+ window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+ }
+}