Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

(WIP) Cap for Windows (#110)

Ilya0220ac452205
diff --git a/.env.example b/.env.example
index 8fdb5fe45..7231f53d1 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,7 @@
# --aws
# --resend
+# - OPTIONAL
# - MISC
#### COPY THIS FILE TO .env AND UPDATE THE VALUES ####
@@ -62,6 +63,10 @@ DEEPGRAM_API_KEY=
## For use with email authentication (sign up, sign in, forgot password)
RESEND_API_KEY=
+# - OPTIONAL, NOT REQUIRED ****************
+RUST_BACKTRACE=full
+
+
# - MISC, NOT REQUIRED FOR DEV ****************
NEXT_LOOPS_KEY=
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 82cb5bb77..c84b16de8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -53,3 +53,10 @@ You can run cap in "local mode", which means that no auth is required for the de
### How do I view the screen recording segments locally?
The video segments are stored in your app data directory, under the folder `so.cap.desktop`. You should see a directory called `chunks`, which will contain both `video` and `audio` directories. You can find the relevant segments in either of those.
+
+### Notes for development on Windows:
+
+<!-- TODO: Update instructions once setupSidecar handles this -->
+
+Required dlls: `avutil`, `avformat`, `avcodec`, `avdevice`.
+Put the full version of ffmpeg for the target arch into `target/binaries`.
diff --git a/Cargo.lock b/Cargo.lock
index 7ec0ef688..3d2abed57 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -130,6 +130,15 @@ dependencies = [
"yansi-term",
]
+[[package]]
+name = "ansi_term"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "anyhow"
version = "1.0.86"
@@ -365,6 +374,17 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi 0.1.19",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "autocfg"
version = "1.3.0"
@@ -380,7 +400,7 @@ dependencies = [
"anyhow",
"arrayvec",
"log",
- "nom",
+ "nom 7.1.3",
"num-rational",
"v_frame",
]
@@ -479,6 +499,29 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "bindgen"
+version = "0.56.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2da379dbebc0b76ef63ca68d8fc6e71c0f13e59432e0987e508c1820e6ab5239"
+dependencies = [
+ "bitflags 1.3.2",
+ "cexpr 0.4.0",
+ "clang-sys",
+ "clap",
+ "env_logger",
+ "lazy_static",
+ "lazycell",
+ "log",
+ "peeking_take_while",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash 1.1.0",
+ "shlex 0.1.1",
+ "which",
+]
+
[[package]]
name = "bindgen"
version = "0.69.4"
@@ -487,7 +530,7 @@ checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0"
dependencies = [
"annotate-snippets",
"bitflags 2.6.0",
- "cexpr",
+ "cexpr 0.6.0",
"clang-sys",
"itertools",
"lazy_static",
@@ -496,7 +539,7 @@ dependencies = [
"quote",
"regex",
"rustc-hash 1.1.0",
- "shlex",
+ "shlex 1.3.0",
"syn 2.0.85",
]
@@ -507,14 +550,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
dependencies = [
"bitflags 2.6.0",
- "cexpr",
+ "cexpr 0.6.0",
"clang-sys",
"itertools",
"proc-macro2",
"quote",
"regex",
"rustc-hash 1.1.0",
- "shlex",
+ "shlex 1.3.0",
"syn 2.0.85",
]
@@ -767,6 +810,7 @@ dependencies = [
"tempfile",
"thiserror",
"tracing",
+ "windows 0.52.0",
]
[[package]]
@@ -806,7 +850,8 @@ name = "cap-utils"
version = "0.1.0"
dependencies = [
"nix 0.29.0",
- "winapi",
+ "tokio",
+ "windows 0.58.0",
]
[[package]]
@@ -850,7 +895,7 @@ checksum = "50d2eb3cd3d1bf4529e31c215ee6f93ec5a3d536d9f578f93d9d33ee19562932"
dependencies = [
"jobserver",
"libc",
- "shlex",
+ "shlex 1.3.0",
]
[[package]]
@@ -859,13 +904,22 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+[[package]]
+name = "cexpr"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4aedb84272dbe89af497cf81375129abda4fc0a9e7c5d317498c15cc30c0d27"
+dependencies = [
+ "nom 5.1.3",
+]
+
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
- "nom",
+ "nom 7.1.3",
]
[[package]]
@@ -939,6 +993,21 @@ dependencies = [
"libloading 0.8.5",
]
+[[package]]
+name = "clap"
+version = "2.34.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
+dependencies = [
+ "ansi_term",
+ "atty",
+ "bitflags 1.3.2",
+ "strsim 0.8.0",
+ "textwrap",
+ "unicode-width",
+ "vec_map",
+]
+
[[package]]
name = "claxon"
version = "0.4.3"
@@ -1457,7 +1526,7 @@ dependencies = [
"ident_case",
"proc-macro2",
"quote",
- "strsim",
+ "strsim 0.11.1",
"syn 2.0.85",
]
@@ -1582,6 +1651,7 @@ dependencies = [
"objc",
"objc2-app-kit",
"png",
+ "rand 0.8.5",
"reqwest",
"rodio",
"scap 0.0.5 (git+https://github.com/CapSoftware/scap?rev=691bd88798d3)",
@@ -1611,6 +1681,8 @@ dependencies = [
"tracing",
"uuid",
"wgpu",
+ "windows 0.52.0",
+ "windows-capture",
]
[[package]]
@@ -1882,6 +1954,19 @@ dependencies = [
"syn 2.0.85",
]
+[[package]]
+name = "env_logger"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3"
+dependencies = [
+ "atty",
+ "humantime",
+ "log",
+ "regex",
+ "termcolor",
+]
+
[[package]]
name = "equivalent"
version = "1.0.1"
@@ -2151,7 +2236,7 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db9c27b72f19a99a895f8ca89e2d26e4ef31013376e56fdafef697627306c3e4"
dependencies = [
- "nom",
+ "nom 7.1.3",
"thiserror",
]
@@ -2776,6 +2861,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hermit-abi"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "hermit-abi"
version = "0.3.9"
@@ -2872,6 +2966,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+[[package]]
+name = "humantime"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
+
[[package]]
name = "hyper"
version = "1.4.1"
@@ -3432,7 +3532,7 @@ dependencies = [
"libc",
"libspa-sys",
"nix 0.27.1",
- "nom",
+ "nom 7.1.3",
"system-deps",
]
@@ -3922,13 +4022,25 @@ source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d5
dependencies = [
"flume 0.10.14",
"image 0.24.9",
+ "nokhwa-bindings-linux",
"nokhwa-bindings-macos",
+ "nokhwa-bindings-windows",
"nokhwa-core",
"paste",
"serde",
"thiserror",
]
+[[package]]
+name = "nokhwa-bindings-linux"
+version = "0.1.0"
+source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"
+dependencies = [
+ "nokhwa-core",
+ "v4l",
+ "v4l2-sys-mit",
+]
+
[[package]]
name = "nokhwa-bindings-macos"
version = "0.2.0"
@@ -3944,6 +4056,16 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "nokhwa-bindings-windows"
+version = "0.4.0"
+source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"
+dependencies = [
+ "nokhwa-core",
+ "once_cell",
+ "windows 0.43.0",
+]
+
[[package]]
name = "nokhwa-core"
version = "0.1.0"
@@ -3956,6 +4078,16 @@ dependencies = [
"thiserror",
]
+[[package]]
+name = "nom"
+version = "5.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08959a387a676302eebf4ddbcbc611da04285579f76f88ee0506c63b1a61dd4b"
+dependencies = [
+ "memchr",
+ "version_check",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -4555,6 +4687,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
+[[package]]
+name = "peeking_take_while"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
+
[[package]]
name = "percent-encoding"
version = "2.3.1"
@@ -5839,6 +5977,12 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "shlex"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7fdf1b9db47230893d76faad238fd6097fd6d6a9245cd7a4d90dbd639536bbd2"
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -6058,6 +6202,12 @@ dependencies = [
"quote",
]
+[[package]]
+name = "strsim"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
+
[[package]]
name = "strsim"
version = "0.11.1"
@@ -6837,6 +6987,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "unicode-width",
+]
+
[[package]]
name = "thin-slice"
version = "0.1.1"
@@ -7345,6 +7504,26 @@ dependencies = [
"serde",
]
+[[package]]
+name = "v4l"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd9946a2fda19c7a729dc72e28b9fd9c653e9b7de954ffe3aecaf51977f88762"
+dependencies = [
+ "bitflags 1.3.2",
+ "libc",
+ "v4l2-sys-mit",
+]
+
+[[package]]
+name = "v4l2-sys-mit"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0c932c06df4af1dfb229f604214f2a87993784596ff33ffdadcba1b5519254e"
+dependencies = [
+ "bindgen 0.56.0",
+]
+
[[package]]
name = "v_frame"
version = "0.3.8"
@@ -7362,6 +7541,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+[[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
[[package]]
name = "version-compare"
version = "0.2.0"
@@ -7776,6 +7961,15 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "which"
+version = "3.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d011071ae14a2f6671d0b74080ae0cd8ebf3a6f8c9589a2cd45f23126fe29724"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "widestring"
version = "1.1.0"
@@ -7826,6 +8020,21 @@ dependencies = [
"windows-version",
]
+[[package]]
+name = "windows"
+version = "0.43.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
[[package]]
name = "windows"
version = "0.48.0"
@@ -7887,14 +8096,14 @@ dependencies = [
[[package]]
name = "windows-capture"
-version = "1.3.2"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bddf8852a6eab219e7ce2593d7075ede60af306f6575b905346ef4aa4a7ecbe2"
+checksum = "15e2f94b43842205eb84814f505badade792e7b8cd132e436636ccbf7baa08fc"
dependencies = [
"parking_lot",
"rayon",
"thiserror",
- "windows 0.58.0",
+ "windows 0.56.0",
]
[[package]]
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 6a46cedbb..ede86a6bb 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -2,7 +2,7 @@
"name": "@cap/desktop",
"type": "module",
"scripts": {
- "dev": "RUST_BACKTRACE=full dotenv -e ../../.env -- tauri dev",
+ "dev": "dotenv -e ../../.env -- tauri dev",
"localdev": "vinxi dev --port 3001",
"build": "vinxi build",
"tauri": "tauri"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 2c8878c81..1847eabb0 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -13,6 +13,8 @@ crate-type = ["lib", "cdylib", "staticlib"]
[build-dependencies]
tauri-build = { version = "2.0.0-rc", features = [] }
+
+[target.'cfg(target_os = "macos")'.build-dependencies]
swift-rs = { version = "1.0.6", features = ["build"] }
[dependencies]
@@ -78,6 +80,7 @@ reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }
dotenvy_macro = "0.15.7"
global-hotkey = "0.6.3"
tauri-plugin-http = "2.0.0-rc.0"
+rand = "0.8.5"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
@@ -85,6 +88,21 @@ core-foundation = "0.10.0"
objc2-app-kit = { version = "0.2.2", features = ["NSWindow", "NSResponder"] }
cocoa = "0.26.0"
objc = "0.2.7"
+swift-rs = "1.0.6"
+tauri-nspanel = { git = "https://github.com/ahkohd/tauri-nspanel", branch = "v2" }
+
+[target.'cfg(target_os= "windows")'.dependencies]
+windows = { version = "0.52.0", features = [
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_UI_WindowsAndMessaging",
+] }
+# Lock the version of windows-capture used by scap@691bd88798d3
+# TODO: Remove this once scap uses the latest version of `windows` and `windows-capture`
+windows-capture = "=1.2.0"
+
+[target.'cfg(unix)'.dependencies]
+nix = { version = "0.29.0", features = ["fs"] }
# Optimize for smaller binary size
[profile.release]
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 46cb06071..d5da08b8d 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -4,9 +4,9 @@ mod camera;
mod flags;
mod general_settings;
mod hotkeys;
-mod macos;
mod notifications;
mod permissions;
+mod platform;
mod recording;
// mod resource;
mod tray;
@@ -29,7 +29,6 @@ use cap_project::{
};
use cap_rendering::ProjectUniforms;
use cap_utils::create_named_pipe;
-use cocoa::foundation::{NSBundle, NSString};
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use image::{ImageBuffer, Rgba};
@@ -54,7 +53,6 @@ use std::{
time::Duration,
};
use tauri::{AppHandle, Manager, Runtime, State, WindowEvent};
-use tauri_nspanel::ManagerExt;
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
@@ -66,6 +64,12 @@ use tokio::{
use upload::{get_s3_config, upload_image, upload_video, S3UploadMeta};
use windows::{CapWindow, CapWindowId};
+#[cfg(target_os = "macos")]
+use cocoa::foundation::{NSBundle, NSString};
+
+#[cfg(target_os = "macos")]
+use tauri_nspanel::ManagerExt;
+
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RecordingOptions {
@@ -435,7 +439,10 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
}
std::fs::create_dir_all(recording.recording_dir.join("screenshots")).ok();
- let display_screenshot = recording.recording_dir.join("screenshots/display.jpg");
+ let display_screenshot = recording
+ .recording_dir
+ .join("screenshots")
+ .join("display.jpg");
create_screenshot(
recording.display_output_path.clone(),
display_screenshot.clone(),
@@ -444,7 +451,10 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
.await?;
// Create thumbnail
- let thumbnail = recording.recording_dir.join("screenshots/thumbnail.png");
+ let thumbnail = recording
+ .recording_dir
+ .join("screenshots")
+ .join("thumbnail.png");
create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;
let recording_dir = recording.recording_dir.clone();
@@ -509,7 +519,7 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
if let Some(pre_created_video) = state.pre_created_video.take() {
// Copy link to clipboard
#[cfg(target_os = "macos")]
- macos::write_string_to_pasteboard(&pre_created_video.link);
+ platform::write_string_to_pasteboard(&pre_created_video.link);
// Send notification for shareable link
notifications::send_notification(
@@ -755,7 +765,10 @@ async fn get_rendered_video_impl(
editor_instance: Arc<EditorInstance>,
project: ProjectConfiguration,
) -> Result<PathBuf, String> {
- let output_path = editor_instance.project_path.join("output/result.mp4");
+ let output_path = editor_instance
+ .project_path
+ .join("output")
+ .join("result.mp4");
if !output_path.exists() {
render_to_file_impl(&editor_instance, project, output_path.clone(), |_| {}).await?;
@@ -950,7 +963,8 @@ async fn render_to_file_impl(
let video_tx = {
let pipe_path = video_dir.path().join("video.pipe");
- create_named_pipe(&pipe_path).unwrap();
+ #[cfg(target_os = "macos")]
+ cap_utils::create_named_pipe(&pipe_path).unwrap();
ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
width: output_size.0,
@@ -977,7 +991,9 @@ async fn render_to_file_impl(
};
let audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {
let pipe_path = audio_dir.path().join("audio.pipe");
- create_named_pipe(&pipe_path).unwrap();
+
+ #[cfg(target_os = "macos")]
+ cap_utils::create_named_pipe(&pipe_path).unwrap();
ffmpeg.add_input(cap_ffmpeg::FFmpegRawAudioInput {
input: pipe_path.clone().into_os_string(),
@@ -1132,7 +1148,7 @@ async fn render_to_file_impl(
ffmpeg_handle.await.ok();
println!("Copying file to {:?}", recording_dir);
- let result_path = recording_dir.join("output/result.mp4");
+ let result_path = recording_dir.join("output").join("result.mp4");
// Function to check if the file is a valid MP4
fn is_valid_mp4(path: &std::path::Path) -> bool {
if let Ok(file) = std::fs::File::open(path) {
@@ -1362,8 +1378,10 @@ async fn get_video_metadata(
.join("recordings")
.join(format!("{}.cap", video_id));
- let screen_video_path = video_dir.join("content/display.mp4");
- let output_video_path = video_dir.join("output/result.mp4");
+ let screen_video_path = video_dir.join("content").join("display.mp4");
+ let output_video_path = video_dir.join("output").join("result.mp4");
+
+ println!("video_dir: {:?} \n video_id: {:?}", video_dir, video_id);
let video_path = match video_type {
Some(VideoType::Screen) => {
@@ -1377,8 +1395,8 @@ async fn get_video_metadata(
screen_video_path
}
Some(VideoType::Output) | None => {
+ println!("Using output video path: {:?}", output_video_path);
if output_video_path.exists() {
- println!("Using output video path: {:?}", output_video_path);
output_video_path
} else {
println!(
@@ -1509,7 +1527,7 @@ fn show_previous_recordings_window(app: AppHandle) {
};
let window_position = window.outer_position().unwrap();
- let mouse_position = window.cursor_position().unwrap();
+ let mouse_position = window.cursor_position().unwrap(); // TODO(Ilya): Panics on Windows
let scale_factor = window.scale_factor().unwrap();
let mut ignore = true;
@@ -1551,16 +1569,19 @@ fn open_editor(app: AppHandle, id: String) {
#[tauri::command(async)]
#[specta::specta]
fn close_previous_recordings_window(app: AppHandle) {
- if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {
- panel.released_when_closed(true);
- panel.close();
+ #[cfg(target_os = "macos")]
+ {
+ if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {
+ panel.released_when_closed(true);
+ panel.close();
+ }
}
}
#[tauri::command(async)]
#[specta::specta]
fn focus_captures_panel(app: AppHandle) {
- if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {
+ if let Ok(panel) = app.get_webview_panel(&CapWindow::PrevRecordings.label()) {
panel.make_key_window();
}
}
@@ -1841,7 +1862,7 @@ async fn upload_rendered_video(
};
#[cfg(target_os = "macos")]
- macos::write_string_to_pasteboard(&share_link);
+ platform::write_string_to_pasteboard(&share_link);
Ok(UploadResult::Success(share_link))
}
@@ -1921,7 +1942,7 @@ async fn upload_screenshot(
println!("Copying to clipboard: {:?}", share_link);
#[cfg(target_os = "macos")]
- macos::write_string_to_pasteboard(&share_link);
+ platform::write_string_to_pasteboard(&share_link);
// Send notification after successful upload and clipboard copy
notifications::send_notification(&app, notifications::NotificationType::ShareableLinkCopied);
@@ -2283,17 +2304,20 @@ async fn delete_auth_open_signin(app: AppHandle) -> Result<(), String> {
#[tauri::command]
#[specta::specta]
async fn reset_camera_permissions(_app: AppHandle) -> Result<(), ()> {
- #[cfg(debug_assertions)]
- let bundle_id = "com.apple.Terminal";
- #[cfg(not(debug_assertions))]
- let bundle_id = "so.cap.desktop";
-
- Command::new("tccutil")
- .arg("reset")
- .arg("Camera")
- .arg(bundle_id)
- .output()
- .expect("Failed to reset camera permissions");
+ #[cfg(target_os = "macos")]
+ {
+ #[cfg(debug_assertions)]
+ let bundle_id = "com.apple.Terminal";
+ #[cfg(not(debug_assertions))]
+ let bundle_id = "so.cap.desktop";
+
+ Command::new("tccutil")
+ .arg("reset")
+ .arg("Camera")
+ .arg(bundle_id)
+ .output()
+ .expect("Failed to reset camera permissions");
+ }
Ok(())
}
@@ -2302,7 +2326,7 @@ async fn reset_camera_permissions(_app: AppHandle) -> Result<(), ()> {
#[specta::specta]
async fn reset_microphone_permissions(_app: AppHandle) -> Result<(), ()> {
#[cfg(debug_assertions)]
- let bundle_id = "dev.warp.Warp-Stable";
+ let bundle_id = "com.apple.Terminal";
#[cfg(not(debug_assertions))]
let bundle_id = "so.cap.desktop";
@@ -2462,9 +2486,16 @@ pub async fn run() {
tauri::async_runtime::set(tokio::runtime::Handle::current());
- tauri::Builder::default()
+ #[allow(unused_mut)]
+ let mut builder = tauri::Builder::default();
+
+ #[cfg(target_os = "macos")]
+ {
+ builder = builder.plugin(tauri_nspanel::init());
+ }
+
+ builder
.plugin(tauri_plugin_shell::init())
- .plugin(tauri_nspanel::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_store::Builder::new().build())
.plugin(tauri_plugin_os::init())
diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rs
index 77dcc3d24..dd7a62986 100644
--- a/apps/desktop/src-tauri/src/permissions.rs
+++ b/apps/desktop/src-tauri/src/permissions.rs
@@ -3,8 +3,11 @@ use tauri::AppHandle;
#[cfg(target_os = "macos")]
use cap_media::platform::{AVAuthorizationStatus, AVMediaType};
+#[cfg(target_os = "macos")]
use core_foundation::boolean::CFBoolean;
+#[cfg(target_os = "macos")]
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; // Import CFDictionaryRef
+#[cfg(target_os = "macos")]
use core_foundation::string::CFString;
use crate::windows::CapWindow;
@@ -161,7 +164,7 @@ pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {
microphone: OSPermissionStatus::NotNeeded,
camera: OSPermissionStatus::NotNeeded,
accessibility: OSPermissionStatus::NotNeeded,
- };
+ }
}
}
diff --git a/apps/desktop/src-tauri/src/platform/macos/delegates.rs b/apps/desktop/src-tauri/src/platform/macos/delegates.rs
new file mode 100644
index 000000000..0a6869700
--- /dev/null
+++ b/apps/desktop/src-tauri/src/platform/macos/delegates.rs
@@ -0,0 +1,358 @@
+// TODO(Ilya): Re-write all macos code to use `objc2` crates n
+///
+/// Credit to @haasal, @charrondev, Hoppscotch app, Electron, Zed Editor
+///
+/// https://github.com/haasal
+/// https://gist.github.com/charrondev
+/// https://github.com/hoppscotch/hoppscotch
+/// https://github.com/clearlysid/tauri-plugin-decorum/
+/// (Issue) https://github.com/tauri-apps/tauri/issues/4789
+/// (Gist) https://gist.github.com/charrondev/43150e940bd2771b1ea88256d491c7a9
+/// (Hoppscotch) https://github.com/hoppscotch/hoppscotch/blob/286fcd2bb08a84f027b10308d1e18da368f95ebf/packages/hoppscotch-selfhost-desktop/src-tauri/src/mac/window.rs
+/// (Electron) https://github.com/electron/electron/blob/38512efd25a159ddc64a54c22ef9eb6dd60064ec/shell/browser/native_window_mac.mm#L1454
+///
+use objc::{msg_send, sel, sel_impl};
+use rand::{distributions::Alphanumeric, Rng};
+use tauri::{Emitter, LogicalPosition, Runtime, Window};
+
+pub struct UnsafeWindowHandle(pub *mut std::ffi::c_void);
+unsafe impl Send for UnsafeWindowHandle {}
+unsafe impl Sync for UnsafeWindowHandle {}
+
+#[derive(Debug)]
+struct WindowState<R: Runtime> {
+ window: Window<R>,
+ controls_inset: LogicalPosition<f64>,
+}
+
+// TODO: Respect RTL display language
+// TODO: Update Height, consider supporting the scenario where the buttons are hidden by the system due to screen sharing of the window
+// https://developer.apple.com/documentation/appkit/nsapplication/1428556-userinterfacelayoutdirection?language=objc
+pub fn position_window_controls(
+ ns_window_handle: UnsafeWindowHandle,
+ inset: &LogicalPosition<f64>,
+) {
+ use cocoa::{
+ appkit::{NSView, NSWindow, NSWindowButton},
+ base::id,
+ foundation::NSRect,
+ };
+
+ let ns_window = ns_window_handle.0 as id;
+ unsafe {
+ let close = ns_window.standardWindowButton_(NSWindowButton::NSWindowCloseButton);
+ let minimize = ns_window.standardWindowButton_(NSWindowButton::NSWindowMiniaturizeButton);
+ let zoom = ns_window.standardWindowButton_(NSWindowButton::NSWindowZoomButton);
+
+ let title_bar_container_view = close.superview().superview();
+
+ let close_rect: NSRect = msg_send![close, frame];
+ let button_height = close_rect.size.height;
+
+ let title_bar_frame_height = button_height + inset.y;
+ let mut title_bar_rect = NSView::frame(title_bar_container_view);
+ title_bar_rect.size.height = title_bar_frame_height;
+ title_bar_rect.origin.y = NSView::frame(ns_window).size.height - title_bar_frame_height;
+ let _: () = msg_send![title_bar_container_view, setFrame: title_bar_rect];
+
+ let window_buttons = vec![close, minimize, zoom];
+ let space_between = NSView::frame(minimize).origin.x - NSView::frame(close).origin.x;
+ let vertical_offset = 4.0; // Adjust this value to push buttons down
+
+ for (i, button) in window_buttons.into_iter().enumerate() {
+ let mut rect: NSRect = NSView::frame(button);
+ rect.origin.x = inset.x + (i as f64 * space_between);
+ rect.origin.y = ((title_bar_frame_height - button_height) / 2.0) - vertical_offset;
+ button.setFrameOrigin(rect.origin);
+ }
+ }
+}
+
+pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>) {
+ use cocoa::appkit::NSWindow;
+ use cocoa::base::{id, BOOL};
+ use cocoa::foundation::NSUInteger;
+ use objc::runtime::{Object, Sel};
+ use std::ffi::c_void;
+
+ let ns_win = window.ns_window().expect("Failed to create window handle");
+
+ // Do the initial positioning
+ position_window_controls(UnsafeWindowHandle(ns_win), &controls_inset);
+
+ // Ensure they stay in place while resizing the window.
+ fn with_window_state<R: Runtime, F: FnOnce(&mut WindowState<R>) -> T, T>(
+ this: &Object,
+ func: F,
+ ) {
+ let ptr = unsafe {
+ let x: *mut c_void = *this.get_ivar("app_box");
+ &mut *(x as *mut WindowState<R>)
+ };
+ func(ptr);
+ }
+
+ unsafe {
+ let ns_win_id = ns_win as id;
+ let current_delegate: id = ns_win_id.delegate();
+
+ extern "C" fn on_window_should_close(this: &Object, _cmd: Sel, sender: id) -> BOOL {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ msg_send![super_del, windowShouldClose: sender]
+ }
+ }
+ extern "C" fn on_window_will_close(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowWillClose: notification];
+ }
+ }
+ extern "C" fn on_window_did_resize<R: Runtime>(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ with_window_state(&*this, |state: &mut WindowState<R>| {
+ position_window_controls(
+ UnsafeWindowHandle(
+ state
+ .window
+ .ns_window()
+ .expect("Failed to get handle to NSWindow"),
+ ),
+ &state.controls_inset,
+ );
+ });
+
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidResize: notification];
+ }
+ }
+ extern "C" fn on_window_did_move(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidMove: notification];
+ }
+ }
+ extern "C" fn on_window_did_change_backing_properties(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidChangeBackingProperties: notification];
+ }
+ }
+ extern "C" fn on_window_did_become_key(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidBecomeKey: notification];
+ }
+ }
+ extern "C" fn on_window_did_resign_key(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidResignKey: notification];
+ }
+ }
+ extern "C" fn on_dragging_entered(this: &Object, _cmd: Sel, notification: id) -> BOOL {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ msg_send![super_del, draggingEntered: notification]
+ }
+ }
+ extern "C" fn on_prepare_for_drag_operation(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) -> BOOL {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ msg_send![super_del, prepareForDragOperation: notification]
+ }
+ }
+ extern "C" fn on_perform_drag_operation(this: &Object, _cmd: Sel, sender: id) -> BOOL {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ msg_send![super_del, performDragOperation: sender]
+ }
+ }
+ extern "C" fn on_conclude_drag_operation(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, concludeDragOperation: notification];
+ }
+ }
+ extern "C" fn on_dragging_exited(this: &Object, _cmd: Sel, notification: id) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, draggingExited: notification];
+ }
+ }
+ extern "C" fn on_window_will_use_full_screen_presentation_options(
+ this: &Object,
+ _cmd: Sel,
+ window: id,
+ proposed_options: NSUInteger,
+ ) -> NSUInteger {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ msg_send![super_del, window: window willUseFullScreenPresentationOptions: proposed_options]
+ }
+ }
+ extern "C" fn on_window_did_enter_full_screen<R: Runtime>(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ with_window_state(&*this, |state: &mut WindowState<R>| {
+ state
+ .window
+ .emit("did-enter-fullscreen", ())
+ .expect("Failed to emit event");
+ });
+
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidEnterFullScreen: notification];
+ }
+ }
+ extern "C" fn on_window_will_enter_full_screen<R: Runtime>(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ with_window_state(&*this, |state: &mut WindowState<R>| {
+ state
+ .window
+ .emit("will-enter-fullscreen", ())
+ .expect("Failed to emit event");
+ });
+
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowWillEnterFullScreen: notification];
+ }
+ }
+ extern "C" fn on_window_did_exit_full_screen<R: Runtime>(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ with_window_state(&*this, |state: &mut WindowState<R>| {
+ state
+ .window
+ .emit("did-exit-fullscreen", ())
+ .expect("Failed to emit event");
+
+ position_window_controls(
+ UnsafeWindowHandle(
+ state
+ .window
+ .ns_window()
+ .expect("Failed to get handle to NSWindow"),
+ ),
+ &state.controls_inset,
+ );
+ });
+
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidExitFullScreen: notification];
+ }
+ }
+ extern "C" fn on_window_will_exit_full_screen<R: Runtime>(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ with_window_state(&*this, |state: &mut WindowState<R>| {
+ state
+ .window
+ .emit("will-exit-fullscreen", ())
+ .expect("Failed to emit event");
+ });
+
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowWillExitFullScreen: notification];
+ }
+ }
+ extern "C" fn on_window_did_fail_to_enter_full_screen(
+ this: &Object,
+ _cmd: Sel,
+ window: id,
+ ) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, windowDidFailToEnterFullScreen: window];
+ }
+ }
+ extern "C" fn on_effective_appearance_did_change(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![super_del, effectiveAppearanceDidChange: notification];
+ }
+ }
+ extern "C" fn on_effective_appearance_did_changed_on_main_thread(
+ this: &Object,
+ _cmd: Sel,
+ notification: id,
+ ) {
+ unsafe {
+ let super_del: id = *this.get_ivar("super_delegate");
+ let _: () = msg_send![
+ super_del,
+ effectiveAppearanceDidChangedOnMainThread: notification
+ ];
+ }
+ }
+
+ let window_label = window.label().to_string();
+
+ let app_state = WindowState {
+ window,
+ controls_inset,
+ };
+ let app_box = Box::into_raw(Box::new(app_state)) as *mut c_void;
+ let random_str: String = rand::thread_rng()
+ .sample_iter(&Alphanumeric)
+ .take(20)
+ .map(char::from)
+ .collect();
+
+ // We need to ensure we have a unique delegate name, otherwise we will panic while trying to create a duplicate
+ // delegate with the same name.
+ let delegate_name = format!("windowDelegate_cap_{}_{}", window_label, random_str);
+
+ ns_win_id.setDelegate_(cocoa::delegate!(&delegate_name, {
+ window: id = ns_win_id,
+ app_box: *mut c_void = app_box,
+ toolbar: id = cocoa::base::nil,
+ super_delegate: id = current_delegate,
+ (windowShouldClose:) => on_window_should_close as extern fn(&Object, Sel, id) -> BOOL,
+ (windowWillClose:) => on_window_will_close as extern fn(&Object, Sel, id),
+ (windowDidResize:) => on_window_did_resize::<R> as extern fn(&Object, Sel, id),
+ (windowDidMove:) => on_window_did_move as extern fn(&Object, Sel, id),
+ (windowDidChangeBackingProperties:) => on_window_did_change_backing_properties as extern fn(&Object, Sel, id),
+ (windowDidBecomeKey:) => on_window_did_become_key as extern fn(&Object, Sel, id),
+ (windowDidResignKey:) => on_window_did_resign_key as extern fn(&Object, Sel, id),
+ (draggingEntered:) => on_dragging_entered as extern fn(&Object, Sel, id) -> BOOL,
+ (prepareForDragOperation:) => on_prepare_for_drag_operation as extern fn(&Object, Sel, id) -> BOOL,
+ (performDragOperation:) => on_perform_drag_operation as extern fn(&Object, Sel, id) -> BOOL,
+ (concludeDragOperation:) => on_conclude_drag_operation as extern fn(&Object, Sel, id),
+ (draggingExited:) => on_dragging_exited as extern fn(&Object, Sel, id),
+ (window:willUseFullScreenPresentationOptions:) => on_window_will_use_full_screen_presentation_options as extern fn(&Object, Sel, id, NSUInteger) -> NSUInteger,
+ (windowDidEnterFullScreen:) => on_window_did_enter_full_screen::<R> as extern fn(&Object, Sel, id),
+ (windowWillEnterFullScreen:) => on_window_will_enter_full_screen::<R> as extern fn(&Object, Sel, id),
+ (windowDidExitFullScreen:) => on_window_did_exit_full_screen::<R> as extern fn(&Object, Sel, id),
+ (windowWillExitFullScreen:) => on_window_will_exit_full_screen::<R> as extern fn(&Object, Sel, id),
+ (windowDidFailToEnterFullScreen:) => on_window_did_fail_to_enter_full_screen as extern fn(&Object, Sel, id),
+ (effectiveAppearanceDidChange:) => on_effective_appearance_did_change as extern fn(&Object, Sel, id),
+ (effectiveAppearanceDidChangedOnMainThread:) => on_effective_appearance_did_changed_on_main_thread as extern fn(&Object, Sel, id)
+ }))
+ }
+}
diff --git a/apps/desktop/src-tauri/src/macos.rs b/apps/desktop/src-tauri/src/platform/macos/mod.rs
similarity index 94%
rename from apps/desktop/src-tauri/src/macos.rs
rename to apps/desktop/src-tauri/src/platform/macos/mod.rs
index 5d966fd01..5e079c67c 100644
--- a/apps/desktop/src-tauri/src/macos.rs
+++ b/apps/desktop/src-tauri/src/platform/macos/mod.rs
@@ -5,6 +5,9 @@ use core_graphics::{
display::{CFDictionaryRef, CGRect},
window::{kCGWindowBounds, kCGWindowOwnerPID},
};
+use objc::{msg_send, sel, sel_impl};
+
+pub mod delegates;
#[derive(Debug)]
pub struct Window {
@@ -23,6 +26,16 @@ pub struct Bounds {
pub height: u32,
}
+pub fn set_window_level(window: tauri::Window, level: u32) {
+ let c_window = window.clone();
+ window.run_on_main_thread(move || unsafe {
+ let ns_win = c_window
+ .ns_window()
+ .expect("Failed to get native window handle") as cocoa::base::id;
+ let _: () = msg_send![ns_win, setLevel: level];
+ });
+}
+
pub fn get_on_screen_windows() -> Vec<Window> {
use core_foundation::{
array::CFArrayGetCount,
diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs
new file mode 100644
index 000000000..f80a6a402
--- /dev/null
+++ b/apps/desktop/src-tauri/src/platform/mod.rs
@@ -0,0 +1,11 @@
+#[cfg(target_os = "windows")]
+pub mod win;
+
+#[cfg(target_os = "windows")]
+pub use win::*;
+
+#[cfg(target_os = "macos")]
+pub mod macos;
+
+#[cfg(target_os = "macos")]
+pub use macos::*;
diff --git a/apps/desktop/src-tauri/src/platform/win.rs b/apps/desktop/src-tauri/src/platform/win.rs
new file mode 100644
index 000000000..e69de29bb
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index e4a1c14d8..f3380166a 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,8 +1,6 @@
use cap_flags::FLAGS;
use cap_media::{encoders::*, feeds::*, filters::*, pipeline::*, sources::*, MediaError};
use cap_project::CursorEvent;
-use cocoa::base::{id, nil};
-use cocoa::foundation::NSUInteger;
use device_query::{DeviceQuery, DeviceState};
use serde::Serialize;
use specta::Type;
@@ -14,8 +12,15 @@ use std::time::{SystemTime, UNIX_EPOCH};
use std::{path::PathBuf, time::Duration};
use tokio::sync::{oneshot, Mutex};
+#[cfg(target_os = "macos")]
+use cocoa::base::{id, nil};
+#[cfg(target_os = "macos")]
+use cocoa::foundation::{NSData, NSUInteger};
+#[cfg(target_os = "macos")]
use objc::rc::autoreleasepool;
+#[cfg(target_os = "macos")]
use objc::runtime::Class;
+#[cfg(target_os = "macos")]
use objc::*;
use crate::RecordingOptions;
@@ -389,6 +394,12 @@ pub async fn start(
})
}
+#[cfg(windows)]
+fn get_cursor_image_data() -> Option<Vec<u8>> {
+ todo!()
+}
+
+#[cfg(target_os = "macos")]
fn get_cursor_image_data() -> Option<Vec<u8>> {
autoreleasepool(|| {
let nscursor_class = match Class::get("NSCursor") {
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 6e29d1316..67a3e2eb8 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -1,6 +1,9 @@
+#![allow(unused_mut)]
use std::path::PathBuf;
-use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry};
+use tauri::{
+ AppHandle, LogicalPosition, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry,
+};
pub enum CapWindow {
Main,
@@ -185,25 +188,38 @@ impl CapWindow {
Ok(match self {
Self::Main => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/")
.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()?;
+ .shadow(true);
+
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .shadow(true);
+ }
- apply_window_chrome(&window);
+ #[cfg(target_os = "windows")]
+ {
+ window_builder = window_builder.decorations(false).shadow(false);
+ }
+
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
Self::Settings { page } => {
- let window = self
+ let mut window_builder = self
.window_builder(
app,
format!("/settings/{}", page.clone().unwrap_or_default()),
@@ -211,21 +227,33 @@ impl CapWindow {
.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()?;
+ .transparent(true);
+
+ #[cfg(target_os = "windows")]
+ {
+ window_builder = window_builder.decorations(false).shadow(false);
+ }
- apply_window_chrome(&window);
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .shadow(true);
+ }
+
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
Self::Camera { ws_port } => {
const WINDOW_SIZE: f64 = 230.0 * 2.0;
- let window = self
+ let mut window_builder = self
.window_builder(app, "/camera")
.maximized(false)
.resizable(false)
@@ -237,6 +265,7 @@ impl CapWindow {
.visible_on_all_workspaces(true)
.min_inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
.inner_size(WINDOW_SIZE, WINDOW_SIZE * 2.0)
+ .skip_taskbar(true)
.position(
100.0,
(monitor.size().height as f64) / monitor.scale_factor()
@@ -249,19 +278,14 @@ impl CapWindow {
window.__CAP__.cameraWsPort = {ws_port};
",
))
- .build()?;
+ .transparent(true);
- #[cfg(target_os = "macos")]
- {
- use tauri_plugin_decorum::WebviewWindowExt;
-
- window.make_transparent().ok();
- }
+ let window = window_builder.build()?;
window
}
Self::WindowCaptureOccluder => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/window-capture-occluder")
.maximized(false)
.resizable(false)
@@ -271,25 +295,24 @@ impl CapWindow {
.always_on_top(true)
.visible_on_all_workspaces(true)
.content_protected(true)
+ .skip_taskbar(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();
+ .transparent(true);
+
+ let window = window_builder.build()?;
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();
+ crate::platform::set_window_level(
+ window.as_ref().window(),
+ objc2_app_kit::NSScreenSaverWindowLevel as u32,
+ );
}
window
@@ -300,10 +323,7 @@ impl CapWindow {
let width = 160.0;
let height = 40.0;
-
-
- self
- .window_builder(app, "/in-progress-recording")
+ self.window_builder(app, "/in-progress-recording")
.title(self.title())
.maximized(false)
.resizable(false)
@@ -336,6 +356,7 @@ impl CapWindow {
.visible_on_all_workspaces(true)
.content_protected(true)
.inner_size(350.0, 350.0)
+ .skip_taskbar(true)
.position(
(monitor.size().width as f64) / monitor.scale_factor() - 350.0,
0.0,
@@ -348,7 +369,7 @@ impl CapWindow {
window
}
Self::PrevRecordings => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/prev-recordings")
.maximized(false)
.resizable(false)
@@ -363,14 +384,14 @@ impl CapWindow {
350.0,
(monitor.size().height as f64) / monitor.scale_factor(),
)
+ .skip_taskbar(true)
.position(0.0, 0.0)
- .build()?;
+ .transparent(true);
+
+ let window = window_builder.build()?;
#[cfg(target_os = "macos")]
{
- use tauri_plugin_decorum::WebviewWindowExt;
- window.make_transparent().ok();
-
app.run_on_main_thread({
let window = window.clone();
move || {
@@ -399,89 +420,141 @@ impl CapWindow {
window
}
Self::Editor { project_id } => {
- let window = self
+ let mut window_builder = self
.window_builder(app, format!("/editor?id={project_id}"))
.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()?;
+ .theme(Some(tauri::Theme::Light));
#[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_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
}
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, Some(LogicalPosition::new(20.0, 48.0)));
+
window
}
Self::Permissions => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/permissions")
+ .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()?;
+ .transparent(true);
+
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ window_builder = window_builder.decorations(false);
+ }
+
+ let window = window_builder.build()?;
- apply_window_chrome(&window);
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
Self::Feedback => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/feedback")
+ .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()?;
+ .transparent(true);
+
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ window_builder = window_builder.decorations(false);
+ }
- apply_window_chrome(&window);
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
Self::Upgrade => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/upgrade")
+ .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()?;
+ .transparent(true);
+
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
+ }
- apply_window_chrome(&window);
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
Self::Changelog => {
- let window = self
+ let mut window_builder = self
.window_builder(app, "/changelog")
+ .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()?;
+ .transparent(true);
- apply_window_chrome(&window);
+ #[cfg(target_os = "macos")]
+ {
+ window_builder = window_builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ window_builder = window_builder.decorations(false);
+ }
+
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ setup_delegates(&window, None);
window
}
@@ -499,11 +572,32 @@ impl CapWindow {
}
}
-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();
- }
+#[cfg(target_os = "macos")]
+fn setup_delegates(window: &WebviewWindow<Wry>, controls_inset: Option<LogicalPosition<f64>>) {
+ use crate::platform::delegates;
+
+ let target_window = window.clone();
+ window
+ .run_on_main_thread(move || {
+ delegates::setup(
+ target_window.as_ref().window(),
+ controls_inset.unwrap_or(LogicalPosition::new(14.0, 22.0)),
+ );
+
+ let c_win = target_window.clone();
+ target_window.on_window_event(move |event| match event {
+ tauri::WindowEvent::ThemeChanged(..) => {
+ delegates::position_window_controls(
+ delegates::UnsafeWindowHandle(
+ c_win
+ .ns_window()
+ .expect("Failed to get native window handle"),
+ ),
+ &controls_inset.unwrap_or(LogicalPosition::new(14.0, 22.0)),
+ );
+ }
+ _ => (),
+ });
+ })
+ .ok();
}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 3ddeeaec2..11e9986a0 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -3,9 +3,9 @@
"productName": "Cap - Development",
"identifier": "so.cap.desktop.dev",
"build": {
- "beforeDevCommand": "node scripts/prepareSidecars.js && pnpm localdev",
+ "beforeDevCommand": "pnpm localdev",
"devUrl": "http://localhost:3001",
- "beforeBuildCommand": "node scripts/prepareSidecars.js && pnpm build",
+ "beforeBuildCommand": "pnpm build",
"frontendDist": "../.output/public"
},
"app": {
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
index 71e720a1e..26590084e 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
@@ -54,7 +54,8 @@ export default function Recordings() {
};
const handleOpenEditor = (id: string) => {
- const fileName = id.split("/").pop() || "";
+ const normalizedPath = id.replace(/\\/g, "/");
+ const fileName = normalizedPath.split("/").pop() || "";
commands.openEditor(fileName.replace(".cap", ""));
};
diff --git a/apps/desktop/src/routes/permissions.tsx b/apps/desktop/src/routes/permissions.tsx
index 0d31e4d7d..fed02fff3 100644
--- a/apps/desktop/src/routes/permissions.tsx
+++ b/apps/desktop/src/routes/permissions.tsx
@@ -15,7 +15,7 @@ import { Transition } from "solid-transition-group";
import Header from "../components/Header";
-function isPermitted(status?: OSPermissionStatus): boolean {
+export function isPermitted(status?: OSPermissionStatus): boolean {
return status === "granted" || status === "notNeeded";
}
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index fcf252236..8b512d997 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -95,13 +95,14 @@ export default function () {
<For each={allMedia()}>
{(media) => {
const [ref, setRef] = createSignal<HTMLElement | null>(null);
- console.log(media);
- const mediaId = media.path.split("/").pop()?.split(".")[0]!;
+ const normalizedPath = media.path.replace(/\\/g, "/");
+ const mediaId = normalizedPath.split("/").pop()?.split(".")[0]!;
+
const type = media.type ?? "recording";
const fileId =
type === "recording"
? mediaId
- : media.path
+ : normalizedPath
.split("screenshots/")[1]
.split("/")[0]
.replace(".cap", "");
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 29302a97a..3fe5937e2 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -1,739 +1,494 @@
+
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
/** user-defined commands **/
+
export const commands = {
- async getRecordingOptions(): Promise<Result<RecordingOptions, null>> {
+async getRecordingOptions() : Promise<Result<RecordingOptions, null>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("get_recording_options"),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async setRecordingOptions(
- options: RecordingOptions
- ): Promise<Result<null, null>> {
+ return { status: "ok", data: await TAURI_INVOKE("get_recording_options") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async setRecordingOptions(options: RecordingOptions) : Promise<Result<null, null>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("set_recording_options", { options }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async startRecording(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("set_recording_options", { options }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async startRecording() : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("start_recording") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async stopRecording(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("start_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async stopRecording() : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("stop_recording") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async pauseRecording(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("stop_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async pauseRecording() : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("pause_recording") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async resumeRecording(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("pause_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async resumeRecording() : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("resume_recording") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async takeScreenshot(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("resume_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async takeScreenshot() : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("take_screenshot") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async listCameras(): Promise<string[]> {
+ return { status: "ok", data: await TAURI_INVOKE("take_screenshot") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async listCameras() : Promise<string[]> {
return await TAURI_INVOKE("list_cameras");
- },
- async listCaptureWindows(): Promise<CaptureWindow[]> {
+},
+async listCaptureWindows() : Promise<CaptureWindow[]> {
return await TAURI_INVOKE("list_capture_windows");
- },
- async listCaptureScreens(): Promise<CaptureScreen[]> {
+},
+async listCaptureScreens() : Promise<CaptureScreen[]> {
return await TAURI_INVOKE("list_capture_screens");
- },
- async listAudioDevices(): Promise<Result<string[], null>> {
+},
+async listAudioDevices() : Promise<Result<string[], null>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("list_audio_devices") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async showPreviousRecordingsWindow(): Promise<void> {
+ return { status: "ok", data: await TAURI_INVOKE("list_audio_devices") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async showPreviousRecordingsWindow() : Promise<void> {
await TAURI_INVOKE("show_previous_recordings_window");
- },
- async closePreviousRecordingsWindow(): Promise<void> {
+},
+async closePreviousRecordingsWindow() : Promise<void> {
await TAURI_INVOKE("close_previous_recordings_window");
- },
- async setFakeWindowBounds(
- name: string,
- bounds: Bounds
- ): Promise<Result<null, string>> {
+},
+async setFakeWindowBounds(name: string, bounds: Bounds) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("set_fake_window_bounds", { name, bounds }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async removeFakeWindow(name: string): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("set_fake_window_bounds", { name, bounds }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async removeFakeWindow(name: string) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("remove_fake_window", { name }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async focusCapturesPanel(): Promise<void> {
+ return { status: "ok", data: await TAURI_INVOKE("remove_fake_window", { name }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async focusCapturesPanel() : Promise<void> {
await TAURI_INVOKE("focus_captures_panel");
- },
- async getCurrentRecording(): Promise<
- Result<JsonValue<InProgressRecording | null>, null>
- > {
+},
+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 };
- }
- },
- async renderToFile(
- outputPath: string,
- videoId: string,
- project: ProjectConfiguration,
- progressChannel: TAURI_CHANNEL<RenderProgress>
- ): Promise<void> {
- await TAURI_INVOKE("render_to_file", {
- outputPath,
- videoId,
- project,
- progressChannel,
- });
- },
- async getRenderedVideo(
- videoId: string,
- project: ProjectConfiguration
- ): Promise<Result<string, string>> {
+ 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 };
+}
+},
+async renderToFile(outputPath: string, videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<void> {
+ await TAURI_INVOKE("render_to_file", { outputPath, videoId, project, progressChannel });
+},
+async getRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<Result<string, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("get_rendered_video", { videoId, project }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async copyFileToPath(
- src: string,
- dst: string
- ): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("get_rendered_video", { videoId, project }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async copyFileToPath(src: string, dst: string) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("copy_file_to_path", { src, dst }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async copyRenderedVideoToClipboard(
- videoId: string,
- project: ProjectConfiguration
- ): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("copy_file_to_path", { src, dst }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async copyRenderedVideoToClipboard(videoId: string, project: ProjectConfiguration) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("copy_rendered_video_to_clipboard", {
- videoId,
- project,
- }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async copyScreenshotToClipboard(path: string): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("copy_rendered_video_to_clipboard", { videoId, project }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async copyScreenshotToClipboard(path: string) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("copy_screenshot_to_clipboard", { path }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async openFilePath(path: string): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("copy_screenshot_to_clipboard", { path }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async openFilePath(path: string) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("open_file_path", { path }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async getVideoMetadata(
- videoId: string,
- videoType: VideoType | null
- ): Promise<Result<[number, number], string>> {
+ return { status: "ok", data: await TAURI_INVOKE("open_file_path", { path }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<Result<[number, number], string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("get_video_metadata", { videoId, videoType }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async createEditorInstance(
- videoId: string
- ): Promise<Result<SerializedEditorInstance, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("get_video_metadata", { videoId, videoType }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async createEditorInstance(videoId: string) : Promise<Result<SerializedEditorInstance, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("create_editor_instance", { videoId }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async startPlayback(videoId: string): Promise<void> {
+ return { status: "ok", data: await TAURI_INVOKE("create_editor_instance", { videoId }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async startPlayback(videoId: string) : Promise<void> {
await TAURI_INVOKE("start_playback", { videoId });
- },
- async stopPlayback(videoId: string): Promise<void> {
+},
+async stopPlayback(videoId: string) : Promise<void> {
await TAURI_INVOKE("stop_playback", { videoId });
- },
- async setPlayheadPosition(
- videoId: string,
- frameNumber: number
- ): Promise<void> {
+},
+async setPlayheadPosition(videoId: string, frameNumber: number) : Promise<void> {
await TAURI_INVOKE("set_playhead_position", { videoId, frameNumber });
- },
- async openInFinder(path: string): Promise<void> {
+},
+async openInFinder(path: string) : Promise<void> {
await TAURI_INVOKE("open_in_finder", { path });
- },
- async setProjectConfig(
- videoId: string,
- config: ProjectConfiguration
- ): Promise<void> {
+},
+async setProjectConfig(videoId: string, config: ProjectConfiguration) : Promise<void> {
await TAURI_INVOKE("set_project_config", { videoId, config });
- },
- async openEditor(id: string): Promise<void> {
+},
+async openEditor(id: string) : Promise<void> {
await TAURI_INVOKE("open_editor", { id });
- },
- async openMainWindow(): Promise<void> {
+},
+async openMainWindow() : Promise<void> {
await TAURI_INVOKE("open_main_window");
- },
- async openPermissionSettings(permission: OSPermission): Promise<void> {
+},
+async openPermissionSettings(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("open_permission_settings", { permission });
- },
- async doPermissionsCheck(initialCheck: boolean): Promise<OSPermissionsCheck> {
+},
+async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {
return await TAURI_INVOKE("do_permissions_check", { initialCheck });
- },
- async requestPermission(permission: OSPermission): Promise<void> {
+},
+async requestPermission(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("request_permission", { permission });
- },
- async uploadRenderedVideo(
- videoId: string,
- project: ProjectConfiguration,
- preCreatedVideo: PreCreatedVideo | null
- ): Promise<Result<UploadResult, string>> {
+},
+async uploadRenderedVideo(videoId: string, project: ProjectConfiguration, preCreatedVideo: PreCreatedVideo | null) : Promise<Result<UploadResult, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("upload_rendered_video", {
- videoId,
- project,
- preCreatedVideo,
- }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async uploadScreenshot(
- screenshotPath: string
- ): Promise<Result<UploadResult, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("upload_rendered_video", { videoId, project, preCreatedVideo }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async uploadScreenshot(screenshotPath: string) : Promise<Result<UploadResult, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("upload_screenshot", { screenshotPath }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async getRecordingMeta(id: string, fileType: string): Promise<RecordingMeta> {
+ return { status: "ok", data: await TAURI_INVOKE("upload_screenshot", { screenshotPath }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMeta> {
return await TAURI_INVOKE("get_recording_meta", { id, fileType });
- },
- async openFeedbackWindow(): Promise<void> {
+},
+async openFeedbackWindow() : Promise<void> {
await TAURI_INVOKE("open_feedback_window");
- },
- async openSettingsWindow(page: string): Promise<void> {
+},
+async openSettingsWindow(page: string) : Promise<void> {
await TAURI_INVOKE("open_settings_window", { page });
- },
- async openChangelogWindow(): Promise<void> {
+},
+async openChangelogWindow() : Promise<void> {
await TAURI_INVOKE("open_changelog_window");
- },
- async openUpgradeWindow(): Promise<void> {
+},
+async openUpgradeWindow() : Promise<void> {
await TAURI_INVOKE("open_upgrade_window");
- },
- async saveFileDialog(
- fileName: string,
- fileType: string
- ): Promise<Result<string | null, string>> {
+},
+async saveFileDialog(fileName: string, fileType: string) : Promise<Result<string | null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("save_file_dialog", { fileName, fileType }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async listRecordings(): Promise<
- Result<[string, string, RecordingMeta][], string>
- > {
+ return { status: "ok", data: await TAURI_INVOKE("save_file_dialog", { fileName, fileType }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async listRecordings() : Promise<Result<([string, string, RecordingMeta])[], string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("list_recordings") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async listScreenshots(): Promise<
- Result<[string, string, RecordingMeta][], string>
- > {
+ return { status: "ok", data: await TAURI_INVOKE("list_recordings") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async listScreenshots() : Promise<Result<([string, string, RecordingMeta])[], string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("list_screenshots") };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async checkUpgradedAndUpdate(): Promise<Result<boolean, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("list_screenshots") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async checkUpgradedAndUpdate() : Promise<Result<boolean, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("check_upgraded_and_update"),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async openExternalLink(url: string): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("check_upgraded_and_update") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async openExternalLink(url: string) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("open_external_link", { url }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async setHotkey(
- action: HotkeyAction,
- hotkey: Hotkey | null
- ): Promise<Result<null, null>> {
+ return { status: "ok", data: await TAURI_INVOKE("open_external_link", { url }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<Result<null, null>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("set_hotkey", { action, hotkey }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async setGeneralSettings(
- settings: GeneralSettingsStore
- ): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("set_hotkey", { action, hotkey }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async setGeneralSettings(settings: GeneralSettingsStore) : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("set_general_settings", { settings }),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async deleteAuthOpenSignin(): Promise<Result<null, string>> {
+ return { status: "ok", data: await TAURI_INVOKE("set_general_settings", { settings }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async deleteAuthOpenSignin() : Promise<Result<null, string>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("delete_auth_open_signin"),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async resetCameraPermissions(): Promise<Result<null, null>> {
+ return { status: "ok", data: await TAURI_INVOKE("delete_auth_open_signin") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async resetCameraPermissions() : Promise<Result<null, null>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("reset_camera_permissions"),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async resetMicrophonePermissions(): Promise<Result<null, null>> {
+ return { status: "ok", data: await TAURI_INVOKE("reset_camera_permissions") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async resetMicrophonePermissions() : Promise<Result<null, null>> {
try {
- return {
- status: "ok",
- data: await TAURI_INVOKE("reset_microphone_permissions"),
- };
- } catch (e) {
- if (e instanceof Error) throw e;
- else return { status: "error", error: e as any };
- }
- },
- async isCameraWindowOpen(): Promise<boolean> {
+ return { status: "ok", data: await TAURI_INVOKE("reset_microphone_permissions") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async isCameraWindowOpen() : Promise<boolean> {
return await TAURI_INVOKE("is_camera_window_open");
- },
- async seekTo(videoId: string, frameNumber: number): Promise<void> {
+},
+async seekTo(videoId: string, frameNumber: number) : Promise<void> {
await TAURI_INVOKE("seek_to", { videoId, frameNumber });
- },
-};
+}
+}
/** user-defined events **/
+
export const events = __makeEvents__<{
- authenticationInvalid: AuthenticationInvalid;
- currentRecordingChanged: CurrentRecordingChanged;
- editorStateChanged: EditorStateChanged;
- newNotification: NewNotification;
- newRecordingAdded: NewRecordingAdded;
- newScreenshotAdded: NewScreenshotAdded;
- recordingMetaChanged: RecordingMetaChanged;
- recordingOptionsChanged: RecordingOptionsChanged;
- recordingStarted: RecordingStarted;
- recordingStopped: RecordingStopped;
- renderFrameEvent: RenderFrameEvent;
- requestNewScreenshot: RequestNewScreenshot;
- requestOpenSettings: RequestOpenSettings;
- requestRestartRecording: RequestRestartRecording;
- requestStartRecording: RequestStartRecording;
- requestStopRecording: RequestStopRecording;
- showCapturesPanel: ShowCapturesPanel;
+authenticationInvalid: AuthenticationInvalid,
+currentRecordingChanged: CurrentRecordingChanged,
+editorStateChanged: EditorStateChanged,
+newNotification: NewNotification,
+newRecordingAdded: NewRecordingAdded,
+newScreenshotAdded: NewScreenshotAdded,
+recordingMetaChanged: RecordingMetaChanged,
+recordingOptionsChanged: RecordingOptionsChanged,
+recordingStarted: RecordingStarted,
+recordingStopped: RecordingStopped,
+renderFrameEvent: RenderFrameEvent,
+requestNewScreenshot: RequestNewScreenshot,
+requestOpenSettings: RequestOpenSettings,
+requestRestartRecording: RequestRestartRecording,
+requestStartRecording: RequestStartRecording,
+requestStopRecording: RequestStopRecording,
+showCapturesPanel: ShowCapturesPanel
}>({
- authenticationInvalid: "authentication-invalid",
- currentRecordingChanged: "current-recording-changed",
- editorStateChanged: "editor-state-changed",
- newNotification: "new-notification",
- newRecordingAdded: "new-recording-added",
- newScreenshotAdded: "new-screenshot-added",
- recordingMetaChanged: "recording-meta-changed",
- recordingOptionsChanged: "recording-options-changed",
- recordingStarted: "recording-started",
- recordingStopped: "recording-stopped",
- renderFrameEvent: "render-frame-event",
- requestNewScreenshot: "request-new-screenshot",
- requestOpenSettings: "request-open-settings",
- requestRestartRecording: "request-restart-recording",
- requestStartRecording: "request-start-recording",
- requestStopRecording: "request-stop-recording",
- showCapturesPanel: "show-captures-panel",
-});
+authenticationInvalid: "authentication-invalid",
+currentRecordingChanged: "current-recording-changed",
+editorStateChanged: "editor-state-changed",
+newNotification: "new-notification",
+newRecordingAdded: "new-recording-added",
+newScreenshotAdded: "new-screenshot-added",
+recordingMetaChanged: "recording-meta-changed",
+recordingOptionsChanged: "recording-options-changed",
+recordingStarted: "recording-started",
+recordingStopped: "recording-stopped",
+renderFrameEvent: "render-frame-event",
+requestNewScreenshot: "request-new-screenshot",
+requestOpenSettings: "request-open-settings",
+requestRestartRecording: "request-restart-recording",
+requestStartRecording: "request-start-recording",
+requestStopRecording: "request-stop-recording",
+showCapturesPanel: "show-captures-panel"
+})
/** user-defined constants **/
+
+
/** user-defined types **/
-export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall";
-export type Audio = { duration: number; sample_rate: number; channels: number };
-export type AudioConfiguration = { mute: boolean; improve: boolean };
-export type AudioMeta = { path: string };
-export type AuthStore = { token: string; expires: number; plan: Plan | null };
-export type AuthenticationInvalid = null;
-export type BackgroundConfiguration = {
- source: BackgroundSource;
- blur: number;
- padding: number;
- rounding: number;
- inset: number;
- crop: Crop | null;
-};
-export type BackgroundSource =
- | { type: "wallpaper"; id: number }
- | { type: "image"; path: string | null }
- | { type: "color"; value: [number, number, number] }
- | {
- type: "gradient";
- from: [number, number, number];
- to: [number, number, number];
- angle?: number;
- };
-export type Bounds = { x: number; y: number; width: number; height: number };
-export type CameraConfiguration = {
- hide: boolean;
- mirror: boolean;
- position: CameraPosition;
- rounding: number;
- shadow: number;
- size: number;
-};
-export type CameraMeta = { path: string };
-export type CameraPosition = { x: CameraXPosition; y: CameraYPosition };
-export type CameraXPosition = "left" | "center" | "right";
-export type CameraYPosition = "top" | "bottom";
-export type CaptureScreen = { id: number; name: string };
-export type CaptureWindow = { id: number; name: string; bounds: Bounds };
-export type Crop = { position: XY<number>; size: XY<number> };
-export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>;
-export type CursorConfiguration = {
- hideWhenIdle: boolean;
- size: number;
- type: CursorType;
-};
-export type CursorType = "pointer" | "circle";
-export type Display = { path: string };
-export type EditorStateChanged = { playhead_position: number };
-export type Flags = {
- recordMouse: boolean;
- split: boolean;
- pauseResume: boolean;
- zoom: boolean;
-};
-export type GeneralSettingsStore = {
- upload_individual_files: boolean;
- open_editor_after_recording: boolean;
- hide_dock_icon?: boolean;
- auto_create_shareable_link?: boolean;
- enable_notifications?: boolean;
-};
-export type Hotkey = {
- code: string;
- meta: boolean;
- ctrl: boolean;
- alt: boolean;
- shift: boolean;
-};
-export type HotkeyAction =
- | "startRecording"
- | "stopRecording"
- | "restartRecording"
- | "takeScreenshot";
-export type HotkeysConfiguration = { show: boolean };
-export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } };
-export type InProgressRecording = {
- recordingDir: string;
- displaySource: ScreenCaptureTarget;
- segments: number[];
-};
-export type JsonValue<T> = [T];
-export type NewNotification = {
- title: string;
- body: string;
- is_error: boolean;
-};
-export type NewRecordingAdded = { path: string };
-export type NewScreenshotAdded = { path: string };
-export type OSPermission =
- | "screenRecording"
- | "camera"
- | "microphone"
- | "accessibility";
-export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied";
-export type OSPermissionsCheck = {
- screenRecording: OSPermissionStatus;
- microphone: OSPermissionStatus;
- camera: OSPermissionStatus;
- accessibility: OSPermissionStatus;
-};
-export type Plan = { upgraded: boolean; last_checked: number };
-export type PreCreatedVideo = {
- id: string;
- link: string;
- config: S3UploadMeta;
-};
-export type ProjectConfiguration = {
- aspectRatio: AspectRatio | null;
- background: BackgroundConfiguration;
- camera: CameraConfiguration;
- audio: AudioConfiguration;
- cursor: CursorConfiguration;
- hotkeys: HotkeysConfiguration;
- timeline?: TimelineConfiguration | null;
-};
-export type ProjectRecordings = {
- display: Video;
- camera: Video | null;
- audio: Audio | null;
-};
-export type RecordingMeta = {
- pretty_name: string;
- sharing?: SharingMeta | null;
- display: Display;
- camera?: CameraMeta | null;
- audio?: AudioMeta | null;
- segments?: RecordingSegment[];
- cursor: string | null;
-};
-export type RecordingMetaChanged = { id: string };
-export type RecordingOptions = {
- captureTarget: ScreenCaptureTarget;
- cameraLabel: string | null;
- audioInputName: string | null;
-};
-export type RecordingOptionsChanged = null;
-export type RecordingSegment = { start: number; end: number };
-export type RecordingStarted = null;
-export type RecordingStopped = { path: string };
-export type RenderFrameEvent = { frame_number: number };
-export type RenderProgress =
- | { type: "Starting"; total_frames: number }
- | { type: "EstimatedTotalFrames"; total_frames: number }
- | { type: "FrameRendered"; current_frame: number };
-export type RequestNewScreenshot = null;
-export type RequestOpenSettings = { page: string };
-export type RequestRestartRecording = null;
-export type RequestStartRecording = null;
-export type RequestStopRecording = null;
-export type S3UploadMeta = {
- id: string;
- user_id: string;
- aws_region: string;
- aws_bucket: string;
-};
-export type ScreenCaptureTarget =
- | ({ variant: "window" } & CaptureWindow)
- | ({ variant: "screen" } & CaptureScreen);
-export type SerializedEditorInstance = {
- framesSocketUrl: string;
- recordingDuration: number;
- savedProjectConfig: ProjectConfiguration;
- recordings: ProjectRecordings;
- path: string;
- prettyName: string;
-};
-export type SharingMeta = { id: string; link: string };
-export type ShowCapturesPanel = null;
-export type TimelineConfiguration = {
- segments: TimelineSegment[];
- zoomSegments?: ZoomSegment[];
-};
-export type TimelineSegment = { timescale: number; start: number; end: number };
-export type UploadResult =
- | { Success: string }
- | "NotAuthenticated"
- | "PlanCheckFailed"
- | "UpgradeRequired";
-export type Video = {
- duration: number;
- width: number;
- height: number;
- fps: number;
-};
-export type VideoType = "screen" | "output";
-export type XY<T> = { x: T; y: T };
-export type ZoomSegment = { start: number; end: number; amount: number };
+export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall"
+export type Audio = { duration: number; sample_rate: number; channels: number }
+export type AudioConfiguration = { mute: boolean; improve: boolean }
+export type AudioMeta = { path: string }
+export type AuthStore = { token: string; expires: number; plan: Plan | null }
+export type AuthenticationInvalid = null
+export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null }
+export type BackgroundSource = { type: "wallpaper"; id: number } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
+export type Bounds = { x: number; y: number; width: number; height: number }
+export type CameraConfiguration = { hide: boolean; mirror: boolean; position: CameraPosition; rounding: number; shadow: number; size: number }
+export type CameraMeta = { path: string }
+export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
+export type CameraXPosition = "left" | "center" | "right"
+export type CameraYPosition = "top" | "bottom"
+export type CaptureScreen = { id: number; name: string }
+export type CaptureWindow = { id: number; name: string; bounds: Bounds }
+export type Crop = { position: XY<number>; size: XY<number> }
+export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>
+export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType }
+export type CursorType = "pointer" | "circle"
+export type Display = { path: string }
+export type EditorStateChanged = { playhead_position: number }
+export type Flags = { recordMouse: boolean; split: boolean; pauseResume: boolean; zoom: boolean }
+export type GeneralSettingsStore = { upload_individual_files: boolean; open_editor_after_recording: boolean; hide_dock_icon?: boolean; auto_create_shareable_link?: boolean; enable_notifications?: boolean }
+export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
+export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"
+export type HotkeysConfiguration = { show: boolean }
+export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
+export type InProgressRecording = { recordingDir: string; displaySource: ScreenCaptureTarget; segments: number[] }
+export type JsonValue<T> = [T]
+export type NewNotification = { title: string; body: string; is_error: boolean }
+export type NewRecordingAdded = { path: string }
+export type NewScreenshotAdded = { path: string }
+export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessibility"
+export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
+export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }
+export type Plan = { upgraded: boolean; last_checked: number }
+export type PreCreatedVideo = { id: string; link: string; config: S3UploadMeta }
+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
+export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
+export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; segments?: RecordingSegment[]; cursor: string | null }
+export type RecordingMetaChanged = { id: string }
+export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null }
+export type RecordingOptionsChanged = null
+export type RecordingSegment = { start: number; end: number }
+export type RecordingStarted = null
+export type RecordingStopped = { path: string }
+export type RenderFrameEvent = { frame_number: number }
+export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "EstimatedTotalFrames"; total_frames: number } | { type: "FrameRendered"; current_frame: number }
+export type RequestNewScreenshot = null
+export type RequestOpenSettings = { page: string }
+export type RequestRestartRecording = null
+export type RequestStartRecording = null
+export type RequestStopRecording = null
+export type S3UploadMeta = { id: string; user_id: string; aws_region: string; aws_bucket: string }
+export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ variant: "screen" } & CaptureScreen)
+export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }
+export type SharingMeta = { id: string; link: string }
+export type ShowCapturesPanel = null
+export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments?: ZoomSegment[] }
+export type TimelineSegment = { timescale: number; start: number; end: number }
+export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
+export type Video = { duration: number; width: number; height: number; fps: number }
+export type VideoType = "screen" | "output"
+export type XY<T> = { x: T; y: T }
+export type ZoomSegment = { start: number; end: number; amount: number }
/** tauri-specta globals **/
import {
- invoke as TAURI_INVOKE,
- Channel as TAURI_CHANNEL,
+ invoke as TAURI_INVOKE,
+ Channel as TAURI_CHANNEL,
} from "@tauri-apps/api/core";
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
type __EventObj__<T> = {
- listen: (
- cb: TAURI_API_EVENT.EventCallback<T>
- ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
- once: (
- cb: TAURI_API_EVENT.EventCallback<T>
- ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
- emit: null extends T
- ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
- : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
+ listen: (
+ cb: TAURI_API_EVENT.EventCallback<T>,
+ ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
+ once: (
+ cb: TAURI_API_EVENT.EventCallback<T>,
+ ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
+ emit: null extends T
+ ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
+ : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
};
export type Result<T, E> =
- | { status: "ok"; data: T }
- | { status: "error"; error: E };
+ | { status: "ok"; data: T }
+ | { status: "error"; error: E };
function __makeEvents__<T extends Record<string, any>>(
- mappings: Record<keyof T, string>
+ mappings: Record<keyof T, string>,
) {
- return new Proxy(
- {} as unknown as {
- [K in keyof T]: __EventObj__<T[K]> & {
- (handle: __WebviewWindow__): __EventObj__<T[K]>;
- };
- },
- {
- get: (_, event) => {
- const name = mappings[event as keyof T];
+ return new Proxy(
+ {} as unknown as {
+ [K in keyof T]: __EventObj__<T[K]> & {
+ (handle: __WebviewWindow__): __EventObj__<T[K]>;
+ };
+ },
+ {
+ get: (_, event) => {
+ const name = mappings[event as keyof T];
- return new Proxy((() => {}) as any, {
- apply: (_, __, [window]: [__WebviewWindow__]) => ({
- listen: (arg: any) => window.listen(name, arg),
- once: (arg: any) => window.once(name, arg),
- emit: (arg: any) => window.emit(name, arg),
- }),
- get: (_, command: keyof __EventObj__<any>) => {
- switch (command) {
- case "listen":
- return (arg: any) => TAURI_API_EVENT.listen(name, arg);
- case "once":
- return (arg: any) => TAURI_API_EVENT.once(name, arg);
- case "emit":
- return (arg: any) => TAURI_API_EVENT.emit(name, arg);
- }
- },
- });
- },
- }
- );
+ return new Proxy((() => {}) as any, {
+ apply: (_, __, [window]: [__WebviewWindow__]) => ({
+ listen: (arg: any) => window.listen(name, arg),
+ once: (arg: any) => window.once(name, arg),
+ emit: (arg: any) => window.emit(name, arg),
+ }),
+ get: (_, command: keyof __EventObj__<any>) => {
+ switch (command) {
+ case "listen":
+ return (arg: any) => TAURI_API_EVENT.listen(name, arg);
+ case "once":
+ return (arg: any) => TAURI_API_EVENT.once(name, arg);
+ case "emit":
+ return (arg: any) => TAURI_API_EVENT.emit(name, arg);
+ }
+ },
+ });
+ },
+ },
+ );
}
diff --git a/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs b/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs
deleted file mode 100644
index da9d40137..000000000
--- a/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs
+++ /dev/null
@@ -1,11 +0,0 @@
-// vite.config.ts
-import { defineConfig } from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/index.js";
-import solid from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected]_@[email protected][email protected]_/node_modules/vite-plugin-solid/dist/esm/index.mjs";
-import capUIPlugin from "file:///Users/macbookuser/Documents/GitHub/cap/packages/ui-solid/vite.js";
-var vite_config_default = defineConfig({
- plugins: [solid(), capUIPlugin]
-});
-export {
- vite_config_default as default
-};
-//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2tcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9tYWNib29rdXNlci9Eb2N1bWVudHMvR2l0SHViL2NhcC9hcHBzL3N0b3J5Ym9vay92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2svdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xuaW1wb3J0IHNvbGlkIGZyb20gXCJ2aXRlLXBsdWdpbi1zb2xpZFwiO1xuaW1wb3J0IGNhcFVJUGx1Z2luIGZyb20gXCJAY2FwL3VpLXNvbGlkL3ZpdGVcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgcGx1Z2luczogW3NvbGlkKCksIGNhcFVJUGx1Z2luXSxcbn0pO1xuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUFvVixTQUFTLG9CQUFvQjtBQUNqWCxPQUFPLFdBQVc7QUFDbEIsT0FBTyxpQkFBaUI7QUFFeEIsSUFBTyxzQkFBUSxhQUFhO0FBQUEsRUFDMUIsU0FBUyxDQUFDLE1BQU0sR0FBRyxXQUFXO0FBQ2hDLENBQUM7IiwKICAibmFtZXMiOiBbXQp9Cg==
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index 836a0a44a..c860a4905 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -15,4 +15,4 @@ serde_json = "1.0.128"
axum = { version = "0.7.5", features = ["ws"] }
ffmpeg.workspace = true
specta.workspace = true
-serde = { version = "1", features = ["derive"] }
+serde = { version = "1", features = ["derive"] }
\ No newline at end of file
diff --git a/crates/ffmpeg/Cargo.toml b/crates/ffmpeg/Cargo.toml
index d2f93af7d..8f5d99fab 100644
--- a/crates/ffmpeg/Cargo.toml
+++ b/crates/ffmpeg/Cargo.toml
@@ -8,4 +8,6 @@ ffmpeg-sidecar = "1.1.0"
cap-utils = { path = "../utils" }
tauri = { workspace = true }
tauri-plugin-shell = "2.0.0"
+
+[target.'cfg(unix)'.dependencies]
nix = { version = "0.29.0", features = ["signal"] }
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index 90834ba4e..6048f8523 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -14,7 +14,7 @@ ffmpeg-sys-next.workspace = true
flume = "0.11.0"
indexmap = "2.5.0"
nokhwa = { git = "https://github.com/capsoftware/nokhwa", rev = "6ce1e8270d57", features = [
- "input-avfoundation",
+ "input-native",
"serialize",
] }
scap = { git = "https://github.com/filleduchaos/scap", rev = "8eb00ce1b9bcf" }
@@ -33,3 +33,11 @@ objc = "0.2.7"
objc-foundation = "0.1.1"
objc2-foundation = { version = "0.2.2", features = ["NSValue"] }
nokhwa-bindings-macos = { git = "https://github.com/capsoftware/nokhwa", rev = "6ce1e8270d57" }
+
+[target.'cfg(target_os = "windows")'.dependencies]
+windows = { version = "0.52.0", features = [
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_UI_WindowsAndMessaging",
+ "Win32_Graphics_Dwm",
+] }
diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rs
index 0e1fc4e6f..5f0c6de6c 100644
--- a/crates/media/src/platform/mod.rs
+++ b/crates/media/src/platform/mod.rs
@@ -5,6 +5,10 @@ use specta::Type;
#[path = "macos.rs"]
mod platform_impl;
+#[cfg(target_os = "windows")]
+#[path = "win.rs"]
+mod platform_impl;
+
pub use platform_impl::*;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type)]
@@ -15,6 +19,17 @@ pub struct Bounds {
pub height: f64,
}
+impl Default for Bounds {
+ fn default() -> Self {
+ Bounds {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ }
+ }
+}
+
#[derive(Debug)]
pub struct Window {
pub window_id: u32,
@@ -23,3 +38,71 @@ pub struct Window {
pub process_id: u32,
pub bounds: Bounds,
}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type, PartialEq, Eq, PartialOrd, Ord)]
+pub enum CursorShape {
+ /// Windows: IDC_ARROW
+ Arrow,
+ /// Windows: IDC_IBEAM
+ IBeam,
+ /// Windows: IDC_CROSS
+ Crosshair,
+ /// macOS Only. Windows not supported.
+ ClosedHand,
+ /// macOS Only. Windows not supported.
+ OpenHand,
+ /// macOS Only. Windows not supported.
+ PointingHand,
+ /// macOS Only. Windows not supported.
+ ResizeLeft,
+ /// macOS Only. Windows not supported.
+ ResizeRight,
+ /// Windows: IDC_SIZEWE
+ ResizeLeftRight,
+ /// Windows: IDC_UPARROW
+ ResizeUp,
+ /// macOS Only. Windows not supported.
+ ResizeDown,
+ /// Windows: IDC_SIZENS
+ ResizeUpDown,
+ /// Windows: IDC_SIZENWSE
+ ///
+ /// Windows only. macOS not supported.
+ ResizeUpLeftAndDownRight,
+ /// Windows: IDC_SIZENESW
+ ///
+ /// Windows only. macOS not supported.
+ ResizeUpRightAndDownLeft,
+ /// Windows: IDC_SIZEALL
+ ///
+ /// Windows only. macOS not supported.
+ ResizeAll,
+ /// macOS Only. Windows not supported.
+ DisappearingItem,
+ /// macOS Only. Windows not supported.
+ VerticalIBeam,
+ /// Windows: IDC_NO
+ NotAllowed,
+ /// macOS Only. Windows not supported.
+ DragLink,
+ /// macOS Only. Windows not supported.
+ DragCopy,
+ /// macOS Only. Windows not supported.
+ ContextualMenu,
+ /// Windows only. macOS not supported.
+ Appstarting,
+ /// Windows: IDC_WAIT
+ ///
+ /// Windows only. macOS not supported.
+ Wait,
+ /// Windows: IDC_HELP
+ ///
+ /// Windows only. macOS not supported.
+ Help,
+ /// Windows only. macOS not supported.
+ ///
+ /// Indicates the cursor is not visible.
+ Hidden,
+ /// Couldn't get the cursor shape.
+ Unknown,
+}
diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rs
new file mode 100644
index 000000000..ffbecf35c
--- /dev/null
+++ b/crates/media/src/platform/win.rs
@@ -0,0 +1,328 @@
+use std::collections::HashMap;
+use std::ffi::OsString;
+use std::os::windows::ffi::OsStringExt;
+use std::path::PathBuf;
+
+use super::{Bounds, CursorShape, Window};
+
+use windows::core::PCWSTR;
+use windows::Win32::Foundation::{CloseHandle, BOOL, FALSE, HWND, LPARAM, RECT, TRUE};
+use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED};
+use windows::Win32::Graphics::Gdi::{
+ EnumDisplayDevicesW, EnumDisplayMonitors, GetMonitorInfoW, DISPLAY_DEVICEW, HDC, HMONITOR,
+ MONITORINFO, MONITORINFOEXW,
+};
+use windows::Win32::System::Threading::{
+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION,
+};
+use windows::Win32::UI::HiDpi::GetDpiForWindow;
+use windows::Win32::UI::WindowsAndMessaging::{
+ EnumWindows, GetCursorInfo, GetWindowRect, GetWindowTextLengthW, GetWindowTextW,
+ GetWindowThreadProcessId, IsWindowVisible, LoadCursorW, SetForegroundWindow, CURSORINFO,
+ IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO, IDC_PERSON,
+ IDC_PIN, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_UPARROW,
+ IDC_WAIT,
+};
+
+#[inline]
+pub fn bring_window_to_focus(window_id: u32) {
+ let _ = unsafe { SetForegroundWindow(HWND(window_id as isize)) };
+}
+
+pub fn get_cursor_shape(cursors: &DefaultCursors) -> CursorShape {
+ let mut cursor_info = CURSORINFO {
+ cbSize: std::mem::size_of::<CURSORINFO>() as u32,
+ ..Default::default()
+ };
+ match unsafe { GetCursorInfo(&mut cursor_info) } {
+ Ok(_) => match cursor_info.hCursor.0 {
+ ptr if ptr == cursors.arrow => CursorShape::Arrow,
+ ptr if ptr == cursors.ibeam => CursorShape::IBeam,
+ ptr if ptr == cursors.wait => CursorShape::Wait,
+ ptr if ptr == cursors.cross => CursorShape::Crosshair,
+ ptr if ptr == cursors.up_arrow => CursorShape::ResizeUp,
+ ptr if ptr == cursors.size_we => CursorShape::ResizeLeftRight,
+ ptr if ptr == cursors.size_ns => CursorShape::ResizeUpDown,
+ ptr if ptr == cursors.size_nwse => CursorShape::ResizeUpLeftAndDownRight,
+ ptr if ptr == cursors.size_nesw => CursorShape::ResizeUpRightAndDownLeft,
+ ptr if ptr == cursors.size_all => CursorShape::ResizeAll,
+ ptr if ptr == cursors.hand => CursorShape::OpenHand,
+ ptr if ptr == cursors.no => CursorShape::NotAllowed,
+ ptr if ptr == cursors.appstarting => CursorShape::Appstarting,
+ ptr if ptr == cursors.help => CursorShape::Help,
+ ptr if ptr == cursors.pin || ptr == cursors.person => CursorShape::OpenHand,
+ // Usually 0, meaning the cursor is hidden. On Windows 8+, a value of 2 means the cursor is supressed
+ // as the user is using touch input instead.
+ _ => CursorShape::Hidden,
+ },
+ Err(_) => CursorShape::Unknown,
+ }
+}
+
+/// Keeps handles to default cursor.
+/// Read more: [MS Doc - About Cursors](https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors)
+pub struct DefaultCursors {
+ arrow: isize,
+ ibeam: isize,
+ wait: isize,
+ cross: isize,
+ up_arrow: isize,
+ size_nwse: isize,
+ size_nesw: isize,
+ size_we: isize,
+ size_ns: isize,
+ size_all: isize,
+ no: isize,
+ hand: isize,
+ appstarting: isize,
+ help: isize,
+ pin: isize,
+ person: isize,
+}
+
+impl Default for DefaultCursors {
+ fn default() -> Self {
+ #[inline]
+ fn load_cursor(lpcursorname: PCWSTR) -> isize {
+ unsafe { LoadCursorW(None, lpcursorname) }
+ .expect("Failed to load default system cursors")
+ .0
+ }
+
+ DefaultCursors {
+ arrow: load_cursor(IDC_ARROW),
+ ibeam: load_cursor(IDC_IBEAM),
+ cross: load_cursor(IDC_CROSS),
+ hand: load_cursor(IDC_HAND),
+ help: load_cursor(IDC_HELP),
+ no: load_cursor(IDC_NO),
+ size_all: load_cursor(IDC_SIZEALL),
+ size_ns: load_cursor(IDC_SIZENS),
+ size_we: load_cursor(IDC_SIZEWE),
+ size_nwse: load_cursor(IDC_SIZENWSE),
+ size_nesw: load_cursor(IDC_SIZENESW),
+ up_arrow: load_cursor(IDC_UPARROW),
+ wait: load_cursor(IDC_WAIT),
+ appstarting: load_cursor(IDC_APPSTARTING),
+ pin: load_cursor(IDC_PIN),
+ person: load_cursor(IDC_PERSON),
+ }
+ }
+}
+
+unsafe fn pid_to_exe_path(pid: u32) -> Result<PathBuf, windows::core::Error> {
+ let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)?;
+ if handle.is_invalid() || handle.0 == 0 {
+ tracing::error!("Invalid PID {}", pid);
+ }
+ let mut lpexename = [0u16; 1024];
+ let mut lpdwsize = lpexename.len() as u32;
+
+ let query = QueryFullProcessImageNameW(
+ handle,
+ PROCESS_NAME_FORMAT::default(),
+ windows::core::PWSTR(lpexename.as_mut_ptr()),
+ &mut lpdwsize,
+ );
+ CloseHandle(handle).ok();
+ query?;
+
+ let os_str = &OsString::from_wide(&lpexename[..lpdwsize as usize]);
+ Ok(PathBuf::from(os_str))
+}
+
+pub fn get_on_screen_windows() -> Vec<Window> {
+ let mut windows = Vec::<Window>::new();
+
+ unsafe extern "system" fn enum_window_proc(hwnd: HWND, lparam: LPARAM) -> BOOL {
+ if hwnd.0 == 0 {
+ return TRUE;
+ }
+ let windows = &mut *(lparam.0 as *mut Vec<Window>);
+
+ if !IsWindowVisible(hwnd).as_bool() {
+ return TRUE;
+ }
+
+ let mut pvattribute_cloaked = 0u32;
+ DwmGetWindowAttribute(
+ hwnd,
+ DWMWA_CLOAKED,
+ &mut pvattribute_cloaked as *mut _ as *mut std::ffi::c_void,
+ std::mem::size_of::<u32>() as u32,
+ )
+ .ok();
+
+ if pvattribute_cloaked != 0 {
+ return TRUE;
+ }
+
+ let mut process_id = 0;
+ let _thrad_id = GetWindowThreadProcessId(hwnd, Some(&mut process_id));
+
+ let wnamelen = GetWindowTextLengthW(hwnd);
+ if wnamelen == 0 {
+ return TRUE;
+ }
+ let mut wname = [0u16; 512];
+ let len = GetWindowTextW(hwnd, &mut wname);
+
+ let owner_process_path = match pid_to_exe_path(process_id) {
+ Ok(path) => path,
+ Err(_) => return TRUE,
+ };
+
+ if owner_process_path.starts_with("C:\\Windows\\SystemApps") {
+ return TRUE;
+ }
+
+ let owner_name = match owner_process_path.file_stem() {
+ Some(exe_name) => exe_name.to_string_lossy().into_owned(),
+ None => owner_process_path.to_string_lossy().into_owned(),
+ };
+
+ // Windows 10 build 1607 or later
+ // Credits: TAO src/platform_impl/windows/dpi.rs
+ const BASE_DPI: u32 = 96;
+ let dpi = match GetDpiForWindow(hwnd) {
+ 0 => BASE_DPI,
+ dpi => dpi,
+ } as i32;
+
+ let scale_factor = dpi as f64 / BASE_DPI as f64;
+ let mut rect = RECT::default();
+ GetWindowRect(hwnd, &mut rect).ok();
+
+ let lpos_x = rect.left as f64 / scale_factor;
+ let lpos_y = rect.top as f64 / scale_factor;
+
+ let window = Window {
+ window_id: hwnd.0 as u32,
+ name: String::from_utf16_lossy(&wname[..len as usize]),
+ owner_name,
+ process_id,
+ bounds: Bounds {
+ x: match lpos_x {
+ x if x.is_sign_negative() => 0.0,
+ _ => lpos_x,
+ },
+ y: match lpos_y {
+ y if y.is_sign_negative() => 0.0,
+ _ => lpos_y,
+ },
+ width: (rect.right - rect.left) as f64 / scale_factor,
+ height: (rect.bottom - rect.top) as f64 / scale_factor,
+ },
+ };
+
+ windows.push(window);
+ TRUE
+ }
+
+ let _ = unsafe {
+ EnumWindows(
+ Some(enum_window_proc),
+ LPARAM(core::ptr::addr_of_mut!(windows) as isize),
+ )
+ };
+ windows
+}
+
+pub fn monitor_bounds(id: u32) -> Bounds {
+ let bounds = Bounds::default();
+ let idx = 0u32;
+ let lparams = (id, idx, bounds);
+ unsafe extern "system" fn enum_monitor_proc(
+ hmonitor: HMONITOR,
+ _hdc: HDC,
+ _lprc_clip: *mut RECT,
+ lparam: LPARAM,
+ ) -> BOOL {
+ let (target_id, idx, bounds) = &mut *(lparam.0 as *mut (u32, u32, Bounds));
+
+ let mut minfo = MONITORINFOEXW::default();
+ minfo.monitorInfo.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
+ if !GetMonitorInfoW(
+ hmonitor,
+ &mut minfo as *mut MONITORINFOEXW as *mut MONITORINFO,
+ )
+ .as_bool()
+ {
+ return TRUE;
+ };
+
+ *idx += 1;
+ if idx != target_id {
+ return TRUE;
+ }
+
+ let mi = minfo.monitorInfo;
+ *bounds = Bounds {
+ x: mi.rcMonitor.left as f64,
+ y: mi.rcMonitor.top as f64,
+ width: (mi.rcMonitor.right - mi.rcMonitor.left) as f64,
+ height: (mi.rcMonitor.bottom - mi.rcMonitor.top) as f64,
+ };
+
+ FALSE
+ }
+
+ let _ = unsafe {
+ EnumDisplayMonitors(
+ None,
+ None,
+ Some(enum_monitor_proc),
+ LPARAM(std::ptr::addr_of!(lparams) as isize),
+ );
+ };
+ bounds
+}
+
+pub fn window_names() -> HashMap<u32, String> {
+ let mut names = HashMap::new();
+ unsafe extern "system" fn monitor_enum_proc(
+ hmonitor: HMONITOR,
+ _hdc: HDC,
+ _lprc_clip: *mut RECT,
+ lparam: LPARAM,
+ ) -> BOOL {
+ let monitors = &mut *(lparam.0 as *mut HashMap<u32, String>);
+
+ let mut minfo = MONITORINFOEXW::default();
+ minfo.monitorInfo.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
+ if !GetMonitorInfoW(
+ hmonitor,
+ &mut minfo as *mut MONITORINFOEXW as *mut MONITORINFO,
+ )
+ .as_bool()
+ {
+ return TRUE;
+ };
+
+ let mut display_device = DISPLAY_DEVICEW::default();
+ display_device.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as u32;
+
+ if !EnumDisplayDevicesW(PCWSTR(minfo.szDevice.as_ptr()), 0, &mut display_device, 0)
+ .as_bool()
+ {
+ return TRUE;
+ };
+
+ let device_name = OsString::from_wide(&display_device.DeviceName)
+ .to_string_lossy()
+ .into_owned();
+ let num = monitors.len() as u32;
+ monitors.insert(num, device_name);
+ TRUE
+ }
+
+ let _ = unsafe {
+ EnumDisplayMonitors(
+ None,
+ None,
+ Some(monitor_enum_proc),
+ LPARAM(core::ptr::addr_of_mut!(names) as isize),
+ )
+ };
+ names
+}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 59edbec51..34582330e 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -154,13 +154,11 @@ impl ScreenCaptureSource {
_ => None,
});
- #[cfg(target_os = "macos")]
let names = crate::platform::window_names();
- #[cfg(not(target_os = "macos"))]
- let names = HashMap::new();
for (idx, screen) in screens.into_iter().enumerate() {
// Handle Target::Screen variant (assuming this is how it's structured in scap)
+ #[cfg(target_os = "macos")]
targets.push(CaptureScreen {
id: screen.id,
name: names
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 060641336..05d740bf2 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -16,9 +16,11 @@ cap-ffmpeg = { path = "../ffmpeg" }
cap-project = { path = "../project" }
cap-flags = { path = "../flags" }
tokio.workspace = true
-nix = { version = "0.29.0", features = ["fs"] }
serde_json = "1.0.127"
ffmpeg.workspace = true
lru = "0.12.4"
ffmpeg-sys-next.workspace = true
futures = "0.3.30"
+
+[target.'cfg(unix)'.dependencies]
+nix = { version = "0.29.0", features = ["fs"] }
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 1df3af976..2c0e25c3d 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -100,6 +100,7 @@ impl RecordingDecoders {
self.screen.get_frame(frame_number),
OptionFuture::from(self.camera.as_ref().map(|d| d.get_frame(frame_number)))
);
+ println!("-t Got Frame? {frame_number}: {}", &screen_frame.is_some());
screen_frame.map(|f| (f, camera_frame.flatten()))
}
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
index 33a11bc23..fb4186db2 100644
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@ -3,8 +3,17 @@ name = "cap-utils"
version = "0.1.0"
edition = "2021"
-[dependencies]
+[target.'cfg(unix)'.dependencies]
nix = { version = "0.29.0", features = ["fs"] }
-[target.'cfg(target_os = "windows")'.dependencies]
-winapi = "0.3.9"
+[target.'cfg(windows)'.dependencies]
+tokio.workspace = true
+windows = { version = "0.58.0", features = [
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_System_WindowsProgramming",
+ "Win32_Security",
+ "Win32_Storage_FileSystem",
+ "Win32_System_Pipes",
+ "Win32_System_Diagnostics_Debug",
+] }
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 5e096d381..a209962d5 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -1,7 +1,8 @@
-use std::path::Path;
+#[cfg(windows)]
+use tokio::net::windows::named_pipe;
#[cfg(unix)]
-pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
+pub fn create_named_pipe(path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
use nix::sys::stat;
use nix::unistd;
std::fs::remove_file(path).ok();
@@ -10,30 +11,38 @@ pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>>
}
#[cfg(windows)]
-pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
- use std::os::windows::ffi::OsStrExt;
- use std::ptr::null_mut;
- use winapi::um::winbase::{CreateNamedPipeA, PIPE_ACCESS_DUPLEX, PIPE_READMODE_BYTE, PIPE_TYPE_BYTE, PIPE_WAIT};
- use winapi::um::handleapi::INVALID_HANDLE_VALUE;
+pub fn get_last_win32_error_formatted() -> String {
+ format_error_message(unsafe { windows::Win32::Foundation::GetLastError().0 })
+}
- let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
- let path_narrow: Vec<i8> = path_wide.iter().map(|&c| c as i8).collect();
- let handle = unsafe {
- CreateNamedPipeA(
- path_narrow.as_ptr(),
- PIPE_ACCESS_DUPLEX,
- PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
- 1,
- 4096,
- 4096,
- 0,
- null_mut(),
- )
+#[cfg(windows)]
+pub fn format_error_message(error_code: u32) -> String {
+ use windows::{
+ core::PWSTR,
+ Win32::System::Diagnostics::Debug::{FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM},
};
- if handle == INVALID_HANDLE_VALUE {
- return Err("Failed to create named pipe".into());
+ let mut buffer = vec![0u16; 1024];
+ match unsafe {
+ FormatMessageW(
+ FORMAT_MESSAGE_FROM_SYSTEM,
+ None,
+ error_code,
+ 0,
+ PWSTR(buffer.as_mut_ptr()),
+ buffer.len() as u32,
+ None,
+ )
+ } {
+ 0 => format!("Unknown error: {}", error_code),
+ len => String::from_utf16_lossy(&buffer[..len as usize])
+ .trim()
+ .to_string(),
}
+}
- Ok(())
-}
\ No newline at end of file
+// Windows named pipes must be in the format "\\.\pipe\name"
+#[cfg(windows)]
+fn named_pipe_to_path(name: &str) -> std::ffi::OsString {
+ format!(r"\\.\pipe\{}", name).into()
+}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index b85717c51..85c266bb7 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -6,58 +6,58 @@
// biome-ignore lint: disable
export {}
declare global {
- const IconCapArrows: typeof import("~icons/cap/arrows.jsx")["default"];
- const IconCapAudioOn: typeof import("~icons/cap/audio-on.jsx")["default"];
- const IconCapBell: typeof import("~icons/cap/bell.jsx")["default"];
- const IconCapBlur: typeof import("~icons/cap/blur.jsx")["default"];
- const IconCapCamera: typeof import("~icons/cap/camera.jsx")["default"];
- const IconCapChevronDown: typeof import("~icons/cap/chevron-down.jsx")["default"];
- const IconCapCircle: typeof import("~icons/cap/circle.jsx")["default"];
- const IconCapCircleCheck: typeof import("~icons/cap/circle-check.jsx")["default"];
- const IconCapCirclePlus: typeof import("~icons/cap/circle-plus.jsx")["default"];
- const IconCapCircleX: typeof import("~icons/cap/circle-x.jsx")["default"];
- const IconCapCopy: typeof import("~icons/cap/copy.jsx")["default"];
- const IconCapCorners: typeof import("~icons/cap/corners.jsx")["default"];
- const IconCapCrop: typeof import("~icons/cap/crop.jsx")["default"];
- const IconCapCursor: typeof import("~icons/cap/cursor.jsx")["default"];
- const IconCapEditor: typeof import("~icons/cap/editor.jsx")["default"];
- const IconCapEnlarge: typeof import("~icons/cap/enlarge.jsx")["default"];
- const IconCapEye: typeof import("~icons/cap/eye.jsx")["default"];
- const IconCapFrameFirst: typeof import("~icons/cap/frame-first.jsx")["default"];
- const IconCapFrameLast: typeof import("~icons/cap/frame-last.jsx")["default"];
- const IconCapHotkeys: typeof import("~icons/cap/hotkeys.jsx")["default"];
- const IconCapImage: typeof import("~icons/cap/image.jsx")["default"];
- const IconCapInset: typeof import("~icons/cap/inset.jsx")["default"];
- const IconCapLayout: typeof import("~icons/cap/layout.jsx")["default"];
- const IconCapLogo: typeof import("~icons/cap/logo.jsx")["default"];
- const IconCapLogoFull: typeof import("~icons/cap/logo-full.jsx")["default"];
- const IconCapMessageBubble: typeof import("~icons/cap/message-bubble.jsx")["default"];
- const IconCapMicrophone: typeof import("~icons/cap/microphone.jsx")["default"];
- const IconCapMoreVertical: typeof import("~icons/cap/more-vertical.jsx")["default"];
- const IconCapPadding: typeof import("~icons/cap/padding.jsx")["default"];
- const IconCapPauseCircle: typeof import("~icons/cap/pause-circle.jsx")["default"];
- const IconCapPlayCircle: typeof import("~icons/cap/play-circle.jsx")["default"];
- const IconCapPresets: typeof import("~icons/cap/presets.jsx")["default"];
- const IconCapRedo: typeof import("~icons/cap/redo.jsx")["default"];
- const IconCapRestart: typeof import("~icons/cap/restart.jsx")["default"];
- const IconCapScissors: typeof import("~icons/cap/scissors.jsx")["default"];
- const IconCapSettings: typeof import("~icons/cap/settings.jsx")["default"];
- const IconCapShadow: typeof import("~icons/cap/shadow.jsx")["default"];
- const IconCapSquare: typeof import("~icons/cap/square.jsx")["default"];
- const IconCapStopCircle: typeof import("~icons/cap/stop-circle.jsx")["default"];
- const IconCapTrash: typeof import("~icons/cap/trash.jsx")["default"];
- const IconCapUndo: typeof import("~icons/cap/undo.jsx")["default"];
- const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"];
- const IconLucideBell: typeof import("~icons/lucide/bell.jsx")["default"];
- const IconLucideCamera: typeof import("~icons/lucide/camera.jsx")["default"];
- const IconLucideCheck: typeof import("~icons/lucide/check.jsx")["default"];
- const IconLucideEdit: typeof import("~icons/lucide/edit.jsx")["default"];
- const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"];
- const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"];
- const IconLucideFoler: typeof import("~icons/lucide/foler.jsx")["default"];
- const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"];
- const IconLucideRewind: typeof import("~icons/lucide/rewind.jsx")["default"];
- const IconLucideSettings: typeof import("~icons/lucide/settings.jsx")["default"];
- const IconLucideSmile: typeof import("~icons/lucide/smile.jsx")["default"];
- const IconLucideVideo: typeof import("~icons/lucide/video.jsx")["default"];
+ const IconCapArrows: typeof import('~icons/cap/arrows.jsx')['default']
+ const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default']
+ const IconCapBell: typeof import("~icons/cap/bell.jsx")["default"]
+ const IconCapBlur: typeof import('~icons/cap/blur.jsx')['default']
+ const IconCapCamera: typeof import('~icons/cap/camera.jsx')['default']
+ const IconCapChevronDown: typeof import('~icons/cap/chevron-down.jsx')['default']
+ const IconCapCircle: typeof import('~icons/cap/circle.jsx')['default']
+ const IconCapCircleCheck: typeof import('~icons/cap/circle-check.jsx')['default']
+ const IconCapCirclePlus: typeof import('~icons/cap/circle-plus.jsx')['default']
+ const IconCapCircleX: typeof import('~icons/cap/circle-x.jsx')['default']
+ const IconCapCopy: typeof import('~icons/cap/copy.jsx')['default']
+ const IconCapCorners: typeof import('~icons/cap/corners.jsx')['default']
+ const IconCapCrop: typeof import('~icons/cap/crop.jsx')['default']
+ const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default']
+ const IconCapEditor: typeof import('~icons/cap/editor.jsx')['default']
+ const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default']
+ const IconCapEye: typeof import("~icons/cap/eye.jsx")["default"]
+ const IconCapFrameFirst: typeof import('~icons/cap/frame-first.jsx')['default']
+ const IconCapFrameLast: typeof import('~icons/cap/frame-last.jsx')['default']
+ const IconCapHotkeys: typeof import('~icons/cap/hotkeys.jsx')['default']
+ const IconCapImage: typeof import('~icons/cap/image.jsx')['default']
+ const IconCapInset: typeof import('~icons/cap/inset.jsx')['default']
+ const IconCapLayout: typeof import('~icons/cap/layout.jsx')['default']
+ const IconCapLogo: typeof import('~icons/cap/logo.jsx')['default']
+ const IconCapLogoFull: typeof import('~icons/cap/logo-full.jsx')['default']
+ const IconCapMessageBubble: typeof import('~icons/cap/message-bubble.jsx')['default']
+ const IconCapMicrophone: typeof import('~icons/cap/microphone.jsx')['default']
+ const IconCapMoreVertical: typeof import('~icons/cap/more-vertical.jsx')['default']
+ const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default']
+ const IconCapPauseCircle: typeof import('~icons/cap/pause-circle.jsx')['default']
+ const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default']
+ const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']
+ const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']
+ const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default']
+ const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']
+ const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']
+ const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default']
+ const IconCapSquare: typeof import('~icons/cap/square.jsx')['default']
+ const IconCapStopCircle: typeof import('~icons/cap/stop-circle.jsx')['default']
+ const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default']
+ const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']
+ const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default']
+ const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']
+ const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']
+ const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
+ const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']
+ const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']
+ const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']
+ const IconLucideFoler: typeof import("~icons/lucide/foler.jsx")["default"]
+ const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']
+ const IconLucideRewind: typeof import("~icons/lucide/rewind.jsx")["default"]
+ const IconLucideSettings: typeof import("~icons/lucide/settings.jsx")["default"]
+ const IconLucideSmile: typeof import("~icons/lucide/smile.jsx")["default"]
+ const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
}
diff --git a/packages/ui-solid/vite.js b/packages/ui-solid/vite.js
index f2cea4754..a9dbeb38d 100644
--- a/packages/ui-solid/vite.js
+++ b/packages/ui-solid/vite.js
@@ -5,6 +5,8 @@ import Icons from "unplugin-icons/vite";
import { FileSystemIconLoader } from "unplugin-icons/loaders";
import Unfonts from "unplugin-fonts/vite";
+const ABSOLUTE_PATH = /^\/|^[a-zA-Z]:\//;
+
export default [
VinxiAutoImport({
resolvers: [
@@ -34,6 +36,9 @@ export default [
];
// Workaround for https://github.com/solidjs/solid-start/issues/1374
+/**
+ * @param {import("unplugin-auto-import/dist/types.d.ts").Options} options
+ */
function VinxiAutoImport(options) {
const autoimport = AutoImport(options);
@@ -42,10 +47,10 @@ function VinxiAutoImport(options) {
transform(src, id) {
let pathname = id;
- if (id.startsWith("/")) {
+ if (ABSOLUTE_PATH.test(id)) {
pathname = new URL(`file://${id}`).pathname;
}
-
+
return autoimport.transform(src, pathname);
},
};