Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Screen Crop (#247)

Ilya4bfc7637c597
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index da67824b1..753aab1d4 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -87,7 +87,7 @@ dirs = "6.0.0"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
core-foundation = "0.10.0"
-objc2-app-kit = { version = "0.2.2", features = ["NSWindow", "NSResponder"] }
+objc2-app-kit = { version = "0.2.2", features = ["NSWindow", "NSResponder", "NSHapticFeedback"] }
cocoa = "0.26.0"
objc = "0.2.7"
swift-rs = "1.0.6"
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index cfa329c41..4a92bdb42 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -5,8 +5,10 @@
"windows": ["*"],
"permissions": [
"core:event:default",
+ "core:menu:default",
"core:window:default",
"core:window:allow-close",
+ "core:window:allow-destroy",
"core:window:allow-hide",
"core:window:allow-show",
"core:window:allow-center",
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 4f7d91db5..055bf9b29 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -15,6 +15,8 @@ pub struct GeneralSettingsStore {
pub open_editor_after_recording: bool,
#[serde(default)]
pub hide_dock_icon: bool,
+ #[serde(default = "true_b")]
+ pub haptics_enabled: bool,
#[serde(default)]
pub auto_create_shareable_link: bool,
#[serde(default = "true_b")]
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index c5e7ea9a7..a518525a8 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -127,7 +127,7 @@ impl App {
if matches!(
current_recording.options.capture_target,
- ScreenCaptureTarget::Window(_)
+ ScreenCaptureTarget::Window(_) | ScreenCaptureTarget::Area(_)
) {
let _ = ShowCapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
@@ -159,6 +159,7 @@ impl App {
match options.capture_target {
ScreenCaptureTarget::Screen(screen) => screen.name,
ScreenCaptureTarget::Window(window) => window.owner_name,
+ ScreenCaptureTarget::Area(area) => area.screen.name,
}
.into(),
);
@@ -2006,6 +2007,7 @@ pub async fn run() {
show_window,
write_clipboard_string,
get_editor_total_frames,
+ platform::perform_haptic_feedback
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2082,6 +2084,7 @@ pub async fn run() {
.with_denylist(&[
CapWindowId::Setup.label().as_str(),
CapWindowId::WindowCaptureOccluder.label().as_str(),
+ CapWindowId::CaptureArea.label().as_str(),
CapWindowId::Camera.label().as_str(),
CapWindowId::RecordingsOverlay.label().as_str(),
CapWindowId::InProgressRecording.label().as_str(),
diff --git a/apps/desktop/src-tauri/src/platform/macos/mod.rs b/apps/desktop/src-tauri/src/platform/macos/mod.rs
index 28d368c31..7a0c86349 100644
--- a/apps/desktop/src-tauri/src/platform/macos/mod.rs
+++ b/apps/desktop/src-tauri/src/platform/macos/mod.rs
@@ -12,30 +12,14 @@ use objc::{class, msg_send, sel, sel_impl};
pub mod delegates;
-#[derive(Debug)]
-pub struct Window {
- pub window_number: u32,
- pub name: String,
- pub owner_name: String,
- pub process_id: u32,
- pub bounds: Bounds,
-}
-
-#[derive(Debug)]
-pub struct Bounds {
- pub x: u32,
- pub y: u32,
- pub width: u32,
- pub height: u32,
-}
-
-pub fn set_window_level(window: tauri::Window, level: u32) {
+pub fn set_window_level(window: tauri::Window, level: objc2_app_kit::NSWindowLevel) {
let c_window = window.clone();
- window.run_on_main_thread(move || unsafe {
+ _ = 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];
+ .expect("Failed to get native window handle")
+ as *const objc2_app_kit::NSWindow;
+ (*ns_win).setLevel(level);
});
}
diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs
index f80a6a402..3fee95932 100644
--- a/apps/desktop/src-tauri/src/platform/mod.rs
+++ b/apps/desktop/src-tauri/src/platform/mod.rs
@@ -1,3 +1,5 @@
+use serde::{Deserialize, Serialize};
+use specta::Type;
#[cfg(target_os = "windows")]
pub mod win;
@@ -9,3 +11,45 @@ pub mod macos;
#[cfg(target_os = "macos")]
pub use macos::*;
+
+#[derive(Debug, Serialize, Deserialize, Type, Default)]
+#[repr(isize)]
+pub enum HapticPattern {
+ Alignment = 0,
+ LevelChange = 1,
+ #[default]
+ Generic = 2,
+}
+
+#[derive(Debug, Serialize, Deserialize, Type, Default)]
+#[repr(usize)]
+pub enum HapticPerformanceTime {
+ Default = 0,
+ #[default]
+ Now = 1,
+ DrawCompleted = 2,
+}
+
+#[tauri::command]
+#[specta::specta]
+pub fn perform_haptic_feedback(
+ pattern: Option<HapticPattern>,
+ time: Option<HapticPerformanceTime>,
+) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ unsafe {
+ use objc2_app_kit::{
+ NSHapticFeedbackManager, NSHapticFeedbackPattern, NSHapticFeedbackPerformanceTime,
+ NSHapticFeedbackPerformer,
+ };
+
+ NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern_performanceTime(
+ NSHapticFeedbackPattern(pattern.unwrap_or_default() as isize),
+ NSHapticFeedbackPerformanceTime(time.unwrap_or_default() as usize),
+ );
+ Ok(())
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ Err("Haptics are only supported on macOS.".into())
+}
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index 8114e20c0..c5f32f1dc 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -39,17 +39,19 @@ impl From<TrayItem> for MenuId {
}
}
-impl From<MenuId> for TrayItem {
- fn from(value: MenuId) -> Self {
+impl TryFrom<MenuId> for TrayItem {
+ type Error = String;
+
+ fn try_from(value: MenuId) -> Result<Self, Self::Error> {
match value.0.as_str() {
- "open_cap" => TrayItem::OpenCap,
- "new_recording" => TrayItem::StartNewRecording,
- "take_screenshot" => TrayItem::TakeScreenshot,
- "previous_recordings" => TrayItem::PreviousRecordings,
- "previous_screenshots" => TrayItem::PreviousScreenshots,
- "open_settings" => TrayItem::OpenSettings,
- "quit" => TrayItem::Quit,
- value => unreachable!("Invalid tray item id {value}"),
+ "open_cap" => Ok(TrayItem::OpenCap),
+ "new_recording" => Ok(TrayItem::StartNewRecording),
+ "take_screenshot" => Ok(TrayItem::TakeScreenshot),
+ "previous_recordings" => Ok(TrayItem::PreviousRecordings),
+ "previous_screenshots" => Ok(TrayItem::PreviousScreenshots),
+ "open_settings" => Ok(TrayItem::OpenSettings),
+ "quit" => Ok(TrayItem::Quit),
+ value => Err(format!("Invalid tray item id {value}")),
}
}
}
@@ -107,39 +109,40 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
"../icons/tray-default-icon.png"
))?)
.menu(&menu)
- .menu_on_left_click(true)
+ .show_menu_on_left_click(true)
.on_menu_event({
let app_handle = app.clone();
- move |app: &AppHandle, event| match TrayItem::from(event.id) {
- TrayItem::OpenCap => {
+ move |app: &AppHandle, event| match TrayItem::try_from(event.id) {
+ Ok(TrayItem::OpenCap) => {
ShowCapWindow::Main.show(&app_handle).ok();
}
- TrayItem::StartNewRecording => {
+ Ok(TrayItem::StartNewRecording) => {
let _ = RequestStartRecording.emit(&app_handle);
}
- TrayItem::TakeScreenshot => {
+ Ok(TrayItem::TakeScreenshot) => {
let _ = RequestNewScreenshot.emit(&app_handle);
}
- TrayItem::PreviousRecordings => {
+ Ok(TrayItem::PreviousRecordings) => {
let _ = RequestOpenSettings {
page: "recordings".to_string(),
}
.emit(&app_handle);
}
- TrayItem::PreviousScreenshots => {
+ Ok(TrayItem::PreviousScreenshots) => {
let _ = RequestOpenSettings {
page: "screenshots".to_string(),
}
.emit(&app_handle);
}
- TrayItem::OpenSettings => {
+ Ok(TrayItem::OpenSettings) => {
ShowCapWindow::Settings { page: None }
.show(&app_handle)
.ok();
}
- TrayItem::Quit => {
+ Ok(TrayItem::Quit) => {
app.exit(0);
}
+ _ => {}
}
})
.on_tray_icon_event({
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 45d4a618c..ecd1aa383 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -3,11 +3,13 @@
use crate::{fake_window, general_settings::AppTheme};
use cap_flags::FLAGS;
+use cap_media::sources::CaptureScreen;
use serde::Deserialize;
use specta::Type;
use std::{path::PathBuf, str::FromStr};
use tauri::{
- AppHandle, LogicalPosition, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry,
+ AppHandle, LogicalPosition, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl,
+ WebviewWindow, WebviewWindowBuilder, Wry,
};
#[cfg(target_os = "macos")]
@@ -22,6 +24,7 @@ pub enum CapWindowId {
Editor { project_id: String },
RecordingsOverlay,
WindowCaptureOccluder,
+ CaptureArea,
Camera,
InProgressRecording,
Upgrade,
@@ -38,6 +41,7 @@ impl FromStr for CapWindowId {
"settings" => Self::Settings,
"camera" => Self::Camera,
"window-capture-occluder" => Self::WindowCaptureOccluder,
+ "capture-area" => Self::CaptureArea,
"in-progress-recording" => Self::InProgressRecording,
"recordings-overlay" => Self::RecordingsOverlay,
"upgrade" => Self::Upgrade,
@@ -58,6 +62,7 @@ impl std::fmt::Display for CapWindowId {
Self::Settings => write!(f, "settings"),
Self::Camera => write!(f, "camera"),
Self::WindowCaptureOccluder => write!(f, "window-capture-occluder"),
+ Self::CaptureArea => write!(f, "capture-area"),
Self::InProgressRecording => write!(f, "in-progress-recording"),
Self::RecordingsOverlay => write!(f, "recordings-overlay"),
Self::Upgrade => write!(f, "upgrade"),
@@ -77,6 +82,7 @@ impl CapWindowId {
Self::Setup => "Cap Setup".to_string(),
Self::Settings => "Cap Settings".to_string(),
Self::WindowCaptureOccluder => "Cap Window Capture Occluder".to_string(),
+ Self::CaptureArea => "Cap Capture Area".to_string(),
Self::InProgressRecording => "Cap In Progress Recording".to_string(),
Self::Editor { .. } => "Cap Editor".to_string(),
Self::SignIn => "Cap Sign In".to_string(),
@@ -107,7 +113,10 @@ impl CapWindowId {
Self::Editor { .. } => Some(Some(LogicalPosition::new(20.0, 40.0))),
Self::Setup => Some(Some(LogicalPosition::new(14.0, 24.0))),
Self::InProgressRecording => Some(Some(LogicalPosition::new(-100.0, -100.0))),
- Self::Camera | Self::WindowCaptureOccluder | Self::RecordingsOverlay => None,
+ Self::Camera
+ | Self::WindowCaptureOccluder
+ | Self::CaptureArea
+ | Self::RecordingsOverlay => None,
_ => Some(None),
}
}
@@ -133,6 +142,7 @@ pub enum ShowCapWindow {
Editor { project_id: String },
PrevRecordings,
WindowCaptureOccluder,
+ CaptureArea { screen: CaptureScreen },
Camera { ws_port: u16 },
InProgressRecording { position: Option<(f64, f64)> },
Upgrade,
@@ -253,12 +263,63 @@ impl ShowCapWindow {
{
crate::platform::set_window_level(
window.as_ref().window(),
- objc2_app_kit::NSScreenSaverWindowLevel as u32,
+ objc2_app_kit::NSScreenSaverWindowLevel,
);
}
window
}
+ Self::CaptureArea { screen } => {
+ let mut window_builder = self
+ .window_builder(app, "/capture-area")
+ .maximized(false)
+ .fullscreen(false)
+ .shadow(false)
+ .always_on_top(true)
+ .content_protected(true)
+ .skip_taskbar(true)
+ .closable(true)
+ .decorations(false)
+ .transparent(true);
+
+ let screen_bounds = cap_media::platform::monitor_bounds(screen.id);
+ let target_monitor = app
+ .monitor_from_point(screen_bounds.x, screen_bounds.y)
+ .ok()
+ .flatten()
+ .unwrap_or(monitor);
+
+ let size = target_monitor.size();
+ let scale_factor = target_monitor.scale_factor();
+ let pos = target_monitor.position();
+ window_builder = window_builder
+ .inner_size(
+ (size.width as f64) / scale_factor,
+ (size.height as f64) / scale_factor,
+ )
+ .position(pos.x as f64, pos.y as f64);
+
+ let window = window_builder.build()?;
+
+ #[cfg(target_os = "macos")]
+ crate::platform::set_window_level(
+ window.as_ref().window(),
+ objc2_app_kit::NSScreenSaverWindowLevel,
+ );
+
+ // Hide the main window if the target monitor is the same
+ if let Some(main_window) = CapWindowId::Main.get(&app) {
+ if let (Ok(outer_pos), Ok(outer_size)) =
+ (main_window.outer_position(), main_window.outer_size())
+ {
+ if target_monitor.intersects(outer_pos, outer_size) {
+ let _ = main_window.minimize();
+ }
+ };
+ }
+
+ window
+ }
Self::InProgressRecording {
position: _position,
} => {
@@ -398,6 +459,7 @@ impl ShowCapWindow {
},
ShowCapWindow::PrevRecordings => CapWindowId::RecordingsOverlay,
ShowCapWindow::WindowCaptureOccluder => CapWindowId::WindowCaptureOccluder,
+ ShowCapWindow::CaptureArea { .. } => CapWindowId::CaptureArea,
ShowCapWindow::Camera { .. } => CapWindowId::Camera,
ShowCapWindow::InProgressRecording { .. } => CapWindowId::InProgressRecording,
ShowCapWindow::Upgrade => CapWindowId::Upgrade,
@@ -483,3 +545,32 @@ fn position_traffic_lights_impl(
})
.ok();
}
+
+// Credits: tauri-plugin-window-state
+trait MonitorExt {
+ fn intersects(&self, position: PhysicalPosition<i32>, size: PhysicalSize<u32>) -> bool;
+}
+
+impl MonitorExt for Monitor {
+ fn intersects(&self, position: PhysicalPosition<i32>, size: PhysicalSize<u32>) -> bool {
+ let PhysicalPosition { x, y } = *self.position();
+ let PhysicalSize { width, height } = *self.size();
+
+ let left = x;
+ let right = x + width as i32;
+ let top = y;
+ let bottom = y + height as i32;
+
+ [
+ (position.x, position.y),
+ (position.x + size.width as i32, position.y),
+ (position.x, position.y + size.height as i32),
+ (
+ position.x + size.width as i32,
+ position.y + size.height as i32,
+ ),
+ ]
+ .into_iter()
+ .any(|(x, y)| x >= left && x < right && y >= top && y < bottom)
+ }
+}
diff --git a/apps/desktop/src/components/CropAreaRenderer.tsx b/apps/desktop/src/components/CropAreaRenderer.tsx
new file mode 100644
index 000000000..38f23b211
--- /dev/null
+++ b/apps/desktop/src/components/CropAreaRenderer.tsx
@@ -0,0 +1,289 @@
+import type { Bounds } from "~/utils/tauri";
+import {
+ onMount,
+ onCleanup,
+ createEffect,
+ type ParentProps,
+ createSignal,
+} from "solid-js";
+import { createHiDPICanvasContext } from "~/utils/canvas";
+
+type DrawContext = {
+ ctx: CanvasRenderingContext2D;
+ bounds: Bounds;
+ radius: number;
+ prefersDark: boolean;
+ highlighted: boolean;
+ selected: boolean;
+};
+
+function drawHandles({
+ ctx,
+ bounds,
+ radius,
+ highlighted,
+ selected,
+}: DrawContext) {
+ const { x, y, width, height } = bounds;
+ const minSizeForSideHandles = 100;
+
+ ctx.strokeStyle = selected
+ ? "rgba(255, 255, 255, 1)"
+ : highlighted
+ ? "rgba(60, 150, 280, 1)"
+ : "rgba(255, 255, 255, 0.8)";
+
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.roundRect(x, y, width, height, radius);
+ ctx.stroke();
+
+ ctx.lineWidth = 5;
+ ctx.lineCap = "round";
+ ctx.setLineDash([]);
+
+ const cornerHandleLength = radius === 0 ? 20 : 10;
+
+ // Corner handles
+ const adjustedRadius = Math.min(radius, width / 2, height / 2);
+
+ const x2 = x + width;
+ const y2 = y + height;
+
+ // top left
+ ctx.beginPath();
+
+ ctx.moveTo(x, y + adjustedRadius + cornerHandleLength);
+ ctx.arcTo(x, y, x2, y, adjustedRadius);
+ ctx.lineTo(x + adjustedRadius + cornerHandleLength, y);
+
+ // top right
+ ctx.moveTo(x2 - adjustedRadius - cornerHandleLength, y);
+ ctx.arcTo(x2, y, x2, y2, adjustedRadius);
+ ctx.lineTo(x2, y + adjustedRadius + cornerHandleLength);
+
+ // bottom left
+ ctx.moveTo(x + adjustedRadius + cornerHandleLength, y2);
+ ctx.arcTo(x, y2, x, y, adjustedRadius);
+ ctx.lineTo(x, y2 - adjustedRadius - cornerHandleLength);
+
+ // bottom right
+ ctx.moveTo(x2, y2 - adjustedRadius - cornerHandleLength);
+ ctx.arcTo(x2, y2, x, y2, adjustedRadius);
+ ctx.lineTo(x2 - adjustedRadius - cornerHandleLength, y2);
+
+ ctx.stroke();
+
+ // Only draw side handles if there's enough space.
+ if (!(width > minSizeForSideHandles && height > minSizeForSideHandles)) {
+ return;
+ }
+
+ // Center handles
+ const handleLength = 35;
+ const sideHandleDistance = 0;
+ const centerX = bounds.x + bounds.width / 2;
+ const centerY = bounds.y + bounds.height / 2;
+
+ ctx.beginPath();
+
+ // top center
+ ctx.moveTo(centerX - handleLength / 2, bounds.y - sideHandleDistance);
+ ctx.lineTo(centerX + handleLength / 2, bounds.y - sideHandleDistance);
+
+ // bottom center
+ ctx.moveTo(
+ centerX - handleLength / 2,
+ bounds.y + bounds.height + sideHandleDistance,
+ );
+ ctx.lineTo(
+ centerX + handleLength / 2,
+ bounds.y + bounds.height + sideHandleDistance,
+ );
+
+ // left center
+ ctx.moveTo(bounds.x - sideHandleDistance, centerY - handleLength / 2);
+ ctx.lineTo(bounds.x - sideHandleDistance, centerY + handleLength / 2);
+
+ // right center
+ ctx.moveTo(
+ bounds.x + bounds.width + sideHandleDistance,
+ centerY - handleLength / 2,
+ );
+ ctx.lineTo(
+ bounds.x + bounds.width + sideHandleDistance,
+ centerY + handleLength / 2,
+ );
+
+ ctx.stroke();
+}
+
+// Rule of thirds guide lines and center crosshair
+function drawGuideLines({ ctx, bounds, prefersDark }: DrawContext) {
+ ctx.strokeStyle = prefersDark
+ ? "rgba(255, 255, 255, 0.5)"
+ : "rgba(0, 0, 0, 0.5)";
+ ctx.lineWidth = 1;
+ ctx.setLineDash([5, 2]);
+
+ // Rule of thirds
+ ctx.beginPath();
+ for (let i = 1; i < 3; i++) {
+ const x = bounds.x + (bounds.width * i) / 3;
+ ctx.moveTo(x, bounds.y);
+ ctx.lineTo(x, bounds.y + bounds.height);
+ }
+ ctx.stroke();
+
+ ctx.beginPath();
+ for (let i = 1; i < 3; i++) {
+ const y = bounds.y + (bounds.height * i) / 3;
+ ctx.moveTo(bounds.x, y);
+ ctx.lineTo(bounds.x + bounds.width, y);
+ }
+ ctx.stroke();
+
+ // Center crosshair
+ const centerX = Math.round(bounds.x + bounds.width / 2);
+ const centerY = Math.round(bounds.y + bounds.height / 2);
+
+ ctx.setLineDash([]);
+ ctx.lineWidth = 2;
+ const crosshairLength = 7;
+
+ ctx.beginPath();
+ ctx.moveTo(centerX - crosshairLength, centerY);
+ ctx.lineTo(centerX + crosshairLength, centerY);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.moveTo(centerX, centerY - crosshairLength);
+ ctx.lineTo(centerX, centerY + crosshairLength);
+ ctx.stroke();
+}
+
+// Main draw function
+function draw(
+ ctx: CanvasRenderingContext2D,
+ bounds: Bounds,
+ radius: number,
+ guideLines: boolean,
+ showHandles: boolean,
+ highlighted: boolean,
+ selected: boolean,
+ prefersDark: boolean,
+) {
+ if (bounds.width <= 0 || bounds.height <= 0) return;
+ const drawContext: DrawContext = {
+ ctx,
+ bounds,
+ radius,
+ prefersDark,
+ highlighted,
+ selected,
+ };
+
+ ctx.save();
+ ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
+
+ ctx.fillStyle = "rgba(0, 0, 0, 0.65)";
+ ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
+
+ // Shadow
+ ctx.save();
+ ctx.shadowColor = "rgba(0, 0, 0, 0.8)";
+ ctx.shadowBlur = 200;
+ ctx.shadowOffsetY = 25;
+ ctx.beginPath();
+ ctx.roundRect(bounds.x, bounds.y, bounds.width, bounds.height, radius);
+ ctx.fill();
+ ctx.restore();
+
+ if (showHandles) drawHandles(drawContext);
+
+ ctx.beginPath();
+ ctx.roundRect(bounds.x, bounds.y, bounds.width, bounds.height, radius);
+ ctx.clip();
+ ctx.clearRect(bounds.x, bounds.y, bounds.width, bounds.height);
+
+ if (guideLines) drawGuideLines(drawContext);
+
+ ctx.restore();
+}
+
+export default function CropAreaRenderer(
+ props: ParentProps<{
+ bounds: Bounds;
+ guideLines?: boolean;
+ handles?: boolean;
+ borderRadius?: number;
+ highlighted?: boolean;
+ selected?: boolean;
+ }>,
+) {
+ let canvasRef: HTMLCanvasElement | undefined;
+ const [prefersDarkScheme, setPrefersDarkScheme] = createSignal(false);
+
+ onMount(() => {
+ if (!canvasRef) {
+ console.error("Canvas ref was not setup");
+ return;
+ }
+
+ const colorSchemeQuery = window.matchMedia("(prefers-color-scheme: dark)");
+ setPrefersDarkScheme(colorSchemeQuery.matches);
+ const handleChange = (e: MediaQueryListEvent) =>
+ setPrefersDarkScheme(e.matches);
+ colorSchemeQuery.addEventListener("change", handleChange);
+
+ const hidpiCanvas = createHiDPICanvasContext(canvasRef, (ctx) =>
+ draw(
+ ctx,
+ props.bounds,
+ props.borderRadius || 0,
+ props.guideLines || false,
+ props.handles || false,
+ props.highlighted || false,
+ props.selected || false,
+ prefersDarkScheme(),
+ ),
+ );
+ const ctx = hidpiCanvas?.ctx;
+ if (!ctx) return;
+
+ let lastAnimationFrameId: number | undefined;
+ createEffect(() => {
+ if (lastAnimationFrameId) cancelAnimationFrame(lastAnimationFrameId);
+
+ const { x, y, width, height } = props.bounds;
+ const { guideLines, handles, borderRadius, highlighted, selected } = props;
+
+ const prefersDark = prefersDarkScheme();
+ lastAnimationFrameId = requestAnimationFrame(() =>
+ draw(
+ ctx,
+ { x, y, width, height },
+ borderRadius || 0,
+ guideLines || false,
+ handles || false,
+ highlighted || false,
+ selected || false,
+ prefersDark,
+ ),
+ );
+ });
+
+ onCleanup(() => {
+ if (lastAnimationFrameId) cancelAnimationFrame(lastAnimationFrameId);
+ hidpiCanvas.cleanup();
+ colorSchemeQuery.removeEventListener("change", handleChange);
+ });
+ });
+
+ return (
+ <div class="*:h-full *:w-full">
+ <canvas ref={canvasRef} class="pointer-events-none absolute" />
+ <div>{props.children}</div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/Cropper.tsx b/apps/desktop/src/components/Cropper.tsx
new file mode 100644
index 000000000..d6841a6d6
--- /dev/null
+++ b/apps/desktop/src/components/Cropper.tsx
@@ -0,0 +1,760 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import {
+ type ParentProps,
+ batch,
+ createEffect,
+ createMemo,
+ createResource,
+ createRoot,
+ createSignal,
+ For,
+ on,
+ onCleanup,
+ onMount,
+ Show,
+} from "solid-js";
+import CropAreaRenderer from "./CropAreaRenderer";
+import Box from "~/utils/box";
+import { type XY, type Crop, commands } from "~/utils/tauri";
+import { createStore } from "solid-js/store";
+import { type as ostype } from "@tauri-apps/plugin-os";
+import { generalSettingsStore } from "~/store";
+import { type CheckMenuItemOptions, Menu } from "@tauri-apps/api/menu";
+import { makePersisted } from "@solid-primitives/storage";
+import { Transition } from "solid-transition-group";
+
+type Direction = "n" | "e" | "s" | "w" | "nw" | "ne" | "se" | "sw";
+type HandleSide = {
+ x: "l" | "r" | "c";
+ y: "t" | "b" | "c";
+ direction: Direction;
+ cursor: "ew" | "ns" | "nesw" | "nwse";
+};
+
+const HANDLES: HandleSide[] = [
+ { x: "l", y: "t", direction: "nw", cursor: "nwse" },
+ { x: "r", y: "t", direction: "ne", cursor: "nesw" },
+ { x: "l", y: "b", direction: "sw", cursor: "nesw" },
+ { x: "r", y: "b", direction: "se", cursor: "nwse" },
+ { x: "c", y: "t", direction: "n", cursor: "ns" },
+ { x: "c", y: "b", direction: "s", cursor: "ns" },
+ { x: "l", y: "c", direction: "w", cursor: "ew" },
+ { x: "r", y: "c", direction: "e", cursor: "ew" },
+];
+
+type Ratio = [number, number];
+const COMMON_RATIOS: Ratio[] = [
+ [1, 1], [4, 3], [3, 2], [16, 9], [2, 1], [21, 9]
+];
+
+const KEY_MAPPINGS = new Map([
+ ["ArrowRight", "e"],
+ ["ArrowDown", "s"],
+ ["ArrowLeft", "w"],
+ ["ArrowUp", "n"],
+]);
+
+const ORIGIN_CENTER: XY<number> = { x: 0.5, y: 0.5 };
+
+function clamp(n: number, min = 0, max = 1) {
+ return Math.max(min, Math.min(max, n));
+}
+
+function distanceOf(firstPoint: Touch, secondPoint: Touch): number {
+ const dx = firstPoint.clientX - secondPoint.clientX;
+ const dy = firstPoint.clientY - secondPoint.clientY;
+ return Math.sqrt(dx * dx + dy * dy);
+}
+
+export function cropToFloor(value: Crop): Crop {
+ return {
+ size: {
+ x: Math.floor(value.size.x),
+ y: Math.floor(value.size.y),
+ },
+ position: {
+ x: Math.floor(value.position.x),
+ y: Math.floor(value.position.y),
+ },
+ };
+}
+
+export default function Cropper(
+ props: ParentProps<{
+ class?: string,
+ onCropChange: (value: Crop) => void;
+ value: Crop;
+ mappedSize?: XY<number>;
+ minSize?: XY<number>;
+ initialSize?: XY<number>;
+ aspectRatio?: number;
+ showGuideLines?: boolean;
+ }>,
+) {
+ const crop = props.value;
+
+ const [containerSize, setContainerSize] = createSignal({ x: 0, y: 0 });
+ const mappedSize = createMemo(() => props.mappedSize || containerSize());
+ const minSize = createMemo(() => {
+ const mapped = mappedSize();
+ return {
+ x: Math.min(100, mapped.x * 0.1),
+ y: Math.min(100, mapped.y * 0.1),
+ };
+ });
+
+ const containerToMappedSizeScale = createMemo(() => {
+ const container = containerSize();
+ const mapped = mappedSize();
+ return {
+ x: container.x / mapped.x,
+ y: container.y / mapped.y,
+ };
+ });
+
+ const displayScaledCrop = createMemo(() => {
+ const mapped = mappedSize();
+ const container = containerSize();
+ return {
+ x: (crop.position.x / mapped.x) * container.x,
+ y: (crop.position.y / mapped.y) * container.y,
+ width: (crop.size.x / mapped.x) * container.x,
+ height: (crop.size.y / mapped.y) * container.y,
+ };
+ });
+
+ let containerRef: HTMLDivElement | undefined;
+ onMount(() => {
+ if (!containerRef) return;
+
+ const updateContainerSize = () => {
+ setContainerSize({
+ x: containerRef!.clientWidth,
+ y: containerRef!.clientHeight,
+ });
+ };
+
+ updateContainerSize();
+ const resizeObserver = new ResizeObserver(updateContainerSize);
+ resizeObserver.observe(containerRef);
+ onCleanup(() => resizeObserver.disconnect());
+
+ const mapped = mappedSize();
+ const initial = props.initialSize || {
+ x: mapped.x / 2,
+ y: mapped.y / 2,
+ };
+
+ let width = clamp(initial.x, minSize().x, mapped.x);
+ let height = clamp(initial.y, minSize().y, mapped.y);
+
+ const box = Box.from(
+ { x: (mapped.x - width) / 2, y: (mapped.y - height) / 2 },
+ { x: width, y: height },
+ );
+ box.constrainAll(box, containerSize(), ORIGIN_CENTER, props.aspectRatio);
+
+ setCrop({
+ size: { x: width, y: height },
+ position: {
+ x: (mapped.x - width) / 2,
+ y: (mapped.y - height) / 2,
+ },
+ });
+ });
+
+ createEffect(
+ on(
+ () => props.aspectRatio,
+ () => {
+ if (!props.aspectRatio) return;
+ const box = Box.from(crop.position, crop.size);
+ box.constrainToRatio(props.aspectRatio, ORIGIN_CENTER);
+ box.constrainToBoundary(mappedSize().x, mappedSize().y, ORIGIN_CENTER);
+ setCrop(box.toBounds());
+ },
+ ),
+ );
+
+ const [snapToRatioEnabled, setSnapToRatioEnabled] = makePersisted(
+ createSignal(true),
+ { name: "cropSnapsToRatio" }
+ );
+ const [snappedRatio, setSnappedRatio] = createSignal<Ratio | null>(null);
+ const [dragging, setDragging] = createSignal(false);
+ const [gestureState, setGestureState] = createStore<{
+ isTrackpadGesture: boolean;
+ lastTouchCenter: XY<number> | null;
+ initialPinchDistance: number;
+ initialSize: { width: number; height: number };
+ }>({
+ isTrackpadGesture: false,
+ lastTouchCenter: null,
+ initialPinchDistance: 0,
+ initialSize: { width: 0, height: 0 },
+ });
+
+ function handleDragStart(event: MouseEvent) {
+ if (gestureState.isTrackpadGesture) return; // Don't start drag if we're in a trackpad gesture
+ event.stopPropagation();
+ setDragging(true);
+ let lastValidPos = { x: event.clientX, y: event.clientY };
+ const box = Box.from(crop.position, crop.size);
+ const scaleFactors = containerToMappedSizeScale();
+
+ createRoot((dispose) => {
+ const mapped = mappedSize();
+ createEventListenerMap(window, {
+ mouseup: () => {
+ setDragging(false);
+ dispose();
+ },
+ mousemove: (e) => {
+ requestAnimationFrame(() => {
+ const dx = (e.clientX - lastValidPos.x) / scaleFactors.x;
+ const dy = (e.clientY - lastValidPos.y) / scaleFactors.y;
+
+ box.move(
+ clamp(box.x + dx, 0, mapped.x - box.width),
+ clamp(box.y + dy, 0, mapped.y - box.height),
+ );
+
+ const newBox = box;
+ if (newBox.x !== crop.position.x || newBox.y !== crop.position.y) {
+ lastValidPos = { x: e.clientX, y: e.clientY };
+ setCrop(newBox.toBounds());
+ }
+ });
+ },
+ });
+ });
+ }
+
+ function handleWheel(event: WheelEvent) {
+ event.preventDefault();
+ const box = Box.from(crop.position, crop.size);
+ const mapped = mappedSize();
+
+ if (event.ctrlKey) {
+ setGestureState("isTrackpadGesture", true);
+
+ const velocity = Math.max(0.001, Math.abs(event.deltaY) * 0.001);
+ const scale = 1 - event.deltaY * velocity;
+
+ box.resize(
+ clamp(box.width * scale, minSize().x, mapped.x),
+ clamp(box.height * scale, minSize().y, mapped.y),
+ ORIGIN_CENTER,
+ );
+ box.constrainAll(box, mapped, ORIGIN_CENTER, props.aspectRatio);
+ setTimeout(() => setGestureState("isTrackpadGesture", false), 100);
+ setSnappedRatio(null);
+ } else {
+ const velocity = Math.max(1, Math.abs(event.deltaY) * 0.01);
+ const scaleFactors = containerToMappedSizeScale();
+ const dx = (-event.deltaX * velocity) / scaleFactors.x;
+ const dy = (-event.deltaY * velocity) / scaleFactors.y;
+
+ box.move(
+ clamp(box.x + dx, 0, mapped.x - box.width),
+ clamp(box.y + dy, 0, mapped.y - box.height),
+ );
+ }
+
+ setCrop(box.toBounds());
+ }
+
+ function handleTouchStart(event: TouchEvent) {
+ if (event.touches.length === 2) {
+ // Initialize pinch zoom
+ const distance = distanceOf(event.touches[0], event.touches[1]);
+
+ // Initialize touch center
+ const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;
+ const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;
+
+ batch(() => {
+ setGestureState("initialPinchDistance", distance);
+ setGestureState("initialSize", {
+ width: crop.size.x,
+ height: crop.size.y,
+ });
+ setGestureState("lastTouchCenter", { x: centerX, y: centerY });
+ });
+ } else if (event.touches.length === 1) {
+ // Handle single touch as drag
+ batch(() => {
+ setDragging(true);
+ setGestureState("lastTouchCenter", {
+ x: event.touches[0].clientX,
+ y: event.touches[0].clientY,
+ });
+ });
+ }
+ }
+
+ function handleTouchMove(event: TouchEvent) {
+ if (event.touches.length === 2) {
+ // Handle pinch zoom
+ const currentDistance = distanceOf(event.touches[0], event.touches[1]);
+ const scale = currentDistance / gestureState.initialPinchDistance;
+
+ const box = Box.from(crop.position, crop.size);
+ const mapped = mappedSize();
+
+ // Calculate new dimensions while maintaining aspect ratio
+ const currentRatio = crop.size.x / crop.size.y;
+ let newWidth = clamp(
+ gestureState.initialSize.width * scale,
+ minSize().x,
+ mapped.x,
+ );
+ let newHeight = newWidth / currentRatio;
+
+ // Adjust if height exceeds bounds
+ if (newHeight < minSize().y || newHeight > mapped.y) {
+ newHeight = clamp(newHeight, minSize().y, mapped.y);
+ newWidth = newHeight * currentRatio;
+ }
+
+ // Resize from center
+ box.resize(newWidth, newHeight, ORIGIN_CENTER);
+
+ // Handle two-finger pan
+ const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;
+ const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;
+
+ if (gestureState.lastTouchCenter) {
+ const scaleFactors = containerToMappedSizeScale();
+ const dx = (centerX - gestureState.lastTouchCenter.x) / scaleFactors.x;
+ const dy = (centerY - gestureState.lastTouchCenter.y) / scaleFactors.y;
+
+ box.move(
+ clamp(box.x + dx, 0, mapped.x - box.width),
+ clamp(box.y + dy, 0, mapped.y - box.height),
+ );
+ }
+
+ setGestureState("lastTouchCenter", { x: centerX, y: centerY });
+ setCrop(box.toBounds());
+ } else if (event.touches.length === 1 && dragging()) {
+ // Handle single touch drag
+ const box = Box.from(crop.position, crop.size);
+ const scaleFactors = containerToMappedSizeScale();
+ const mapped = mappedSize();
+
+ if (gestureState.lastTouchCenter) {
+ const dx =
+ (event.touches[0].clientX - gestureState.lastTouchCenter.x) /
+ scaleFactors.x;
+ const dy =
+ (event.touches[0].clientY - gestureState.lastTouchCenter.y) /
+ scaleFactors.y;
+
+ box.move(
+ clamp(box.x + dx, 0, mapped.x - box.width),
+ clamp(box.y + dy, 0, mapped.y - box.height),
+ );
+ }
+
+ setGestureState("lastTouchCenter", {
+ x: event.touches[0].clientX,
+ y: event.touches[0].clientY,
+ });
+ setCrop(box.toBounds());
+ }
+ }
+
+ function handleTouchEnd(event: TouchEvent) {
+ if (event.touches.length === 0) {
+ setDragging(false);
+ setGestureState("lastTouchCenter", null);
+ } else if (event.touches.length === 1) {
+ setGestureState("lastTouchCenter", {
+ x: event.touches[0].clientX,
+ y: event.touches[0].clientY,
+ });
+ }
+ }
+
+ function handleResizeStartTouch(event: TouchEvent, dir: Direction) {
+ if (event.touches.length !== 1) return;
+ event.stopPropagation();
+ const touch = event.touches[0];
+ handleResizeStart(touch.clientX, touch.clientY, dir);
+ }
+
+ function findClosestRatio(
+ width: number,
+ height: number,
+ threshold = 0.01,
+ ): Ratio | null {
+ if (props.aspectRatio) return null;
+ const currentRatio = width / height;
+ for (const ratio of COMMON_RATIOS) {
+ if (Math.abs(currentRatio - ratio[0] / ratio[1]) < threshold) {
+ return [ratio[0], ratio[1]];
+ }
+ if (Math.abs(currentRatio - ratio[1] / ratio[0]) < threshold) {
+ return [ratio[1], ratio[0]];
+ }
+ }
+ return null;
+ }
+
+ function handleResizeStart(clientX: number, clientY: number, dir: Direction) {
+ const origin: XY<number> = {
+ x: dir.includes("w") ? 1 : 0,
+ y: dir.includes("n") ? 1 : 0,
+ };
+
+ let lastValidPos = { x: clientX, y: clientY };
+ const box = Box.from(crop.position, crop.size);
+ const scaleFactors = containerToMappedSizeScale();
+ const mapped = mappedSize();
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mouseup: dispose,
+ touchend: dispose,
+ touchmove: (e) =>
+ requestAnimationFrame(() => {
+ if (e.touches.length !== 1) return;
+ handleResizeMove(e.touches[0].clientX, e.touches[0].clientY);
+ }),
+ mousemove: (e) =>
+ requestAnimationFrame(() =>
+ handleResizeMove(e.clientX, e.clientY, e.altKey),
+ ),
+ });
+ });
+
+ const [hapticsEnabled, hapticsEnabledOptions] = createResource(async () =>
+ (await generalSettingsStore.get())?.hapticsEnabled && ostype() === "macos"
+ );
+ generalSettingsStore.listen(() => hapticsEnabledOptions.refetch());
+
+ function handleResizeMove(
+ moveX: number,
+ moveY: number,
+ centerOrigin = false,
+ ) {
+ const dx = (moveX - lastValidPos.x) / scaleFactors.x;
+ const dy = (moveY - lastValidPos.y) / scaleFactors.y;
+
+ const scaleMultiplier = centerOrigin ? 2 : 1;
+ const currentBox = box.toBounds();
+
+ let newWidth =
+ dir.includes("e") || dir.includes("w")
+ ? clamp(
+ dir.includes("w")
+ ? currentBox.size.x - dx * scaleMultiplier
+ : currentBox.size.x + dx * scaleMultiplier,
+ minSize().x,
+ mapped.x,
+ )
+ : currentBox.size.x;
+
+ let newHeight =
+ dir.includes("n") || dir.includes("s")
+ ? clamp(
+ dir.includes("n")
+ ? currentBox.size.y - dy * scaleMultiplier
+ : currentBox.size.y + dy * scaleMultiplier,
+ minSize().y,
+ mapped.y,
+ )
+ : currentBox.size.y;
+
+ const closest = findClosestRatio(newWidth, newHeight);
+ if (dir.length === 2 && snapToRatioEnabled() && closest) {
+ const ratio = closest[0] / closest[1];
+ if (dir.includes("n") || dir.includes("s")) {
+ newWidth = newHeight * ratio;
+ } else {
+ newHeight = newWidth / ratio;
+ }
+ if (!snappedRatio() && hapticsEnabled()) {
+ commands.performHapticFeedback("Alignment", "Now");
+ }
+ setSnappedRatio(closest);
+ } else {
+ setSnappedRatio(null);
+ }
+
+ const newOrigin = centerOrigin ? ORIGIN_CENTER : origin;
+ box.resize(newWidth, newHeight, newOrigin);
+
+ if (props.aspectRatio) {
+ box.constrainToRatio(
+ props.aspectRatio,
+ newOrigin,
+ dir.includes("n") || dir.includes("s") ? "width" : "height",
+ );
+ }
+ box.constrainToBoundary(mapped.x, mapped.y, newOrigin);
+
+ const newBox = box.toBounds();
+ if (
+ newBox.size.x !== crop.size.x ||
+ newBox.size.y !== crop.size.y ||
+ newBox.position.x !== crop.position.x ||
+ newBox.position.y !== crop.position.y
+ ) {
+ lastValidPos = { x: moveX, y: moveY };
+ props.onCropChange(newBox);
+ }
+ }
+ }
+
+ function setCrop(value: Crop) {
+ props.onCropChange(value);
+ }
+
+ let pressedKeys = new Set<string>([]);
+ let lastKeyHandleFrame: number | null = null;
+ function handleKeyDown(event: KeyboardEvent) {
+ if (dragging()) return;
+ const dir = KEY_MAPPINGS.get(event.key);
+ if (!dir) return;
+ event.preventDefault();
+ pressedKeys.add(event.key);
+
+ if (lastKeyHandleFrame) return;
+ lastKeyHandleFrame = requestAnimationFrame(() => {
+ const box = Box.from(crop.position, crop.size);
+ const mapped = mappedSize();
+ const scaleFactors = containerToMappedSizeScale();
+
+ const moveDelta = event.shiftKey ? 20 : 5;
+ const origin = event.altKey ? ORIGIN_CENTER : { x: 0, y: 0 };
+
+ for (const key of pressedKeys) {
+ const dir = KEY_MAPPINGS.get(key);
+ if (!dir) continue;
+
+ const isUpKey = dir === "n";
+ const isLeftKey = dir === "w";
+ const isDownKey = dir === "s";
+ const isRightKey = dir === "e";
+
+ if (event.metaKey || event.ctrlKey) {
+ const scaleMultiplier = event.altKey ? 2 : 1;
+ const currentBox = box.toBounds();
+
+ let newWidth = currentBox.size.x;
+ let newHeight = currentBox.size.y;
+
+ if (isLeftKey || isRightKey) {
+ newWidth = clamp(
+ isLeftKey
+ ? currentBox.size.x - moveDelta * scaleMultiplier
+ : currentBox.size.x + moveDelta * scaleMultiplier,
+ minSize().x,
+ mapped.x,
+ );
+ }
+
+ if (isUpKey || isDownKey) {
+ newHeight = clamp(
+ isUpKey
+ ? currentBox.size.y - moveDelta * scaleMultiplier
+ : currentBox.size.y + moveDelta * scaleMultiplier,
+ minSize().y,
+ mapped.y,
+ );
+ }
+
+ box.resize(newWidth, newHeight, origin);
+ } else {
+ const dx =
+ (isRightKey ? moveDelta : isLeftKey ? -moveDelta : 0) /
+ scaleFactors.x;
+ const dy =
+ (isDownKey ? moveDelta : isUpKey ? -moveDelta : 0) / scaleFactors.y;
+
+ box.move(
+ clamp(box.x + dx, 0, mapped.x - box.width),
+ clamp(box.y + dy, 0, mapped.y - box.height),
+ );
+ }
+ }
+
+ if (props.aspectRatio) box.constrainToRatio(props.aspectRatio, origin);
+ box.constrainToBoundary(mapped.x, mapped.y, origin);
+ setCrop(box.toBounds());
+
+ pressedKeys.clear();
+ lastKeyHandleFrame = null;
+ });
+ }
+
+ return (
+ <div
+ aria-label="Crop area"
+ ref={containerRef}
+ class={`relative h-full w-full overflow-hidden overscroll-contain *:overscroll-none ${props.class}`}
+ onWheel={handleWheel}
+ onTouchStart={handleTouchStart}
+ onTouchMove={handleTouchMove}
+ onTouchEnd={handleTouchEnd}
+ onKeyDown={handleKeyDown}
+ tabIndex={0}
+ onContextMenu={async (e) => {
+ e.preventDefault();
+ const menu = await Menu.new({
+ id: "crop-options",
+ items: [
+ {
+ id: "enableRatioSnap",
+ text: "Snap to aspect ratios",
+ checked: snapToRatioEnabled(),
+ action: () => {
+ setSnapToRatioEnabled((v) => !v);
+ },
+ } satisfies CheckMenuItemOptions
+ ]
+ });
+ menu.popup();
+ }}
+ >
+ <CropAreaRenderer
+ bounds={{
+ x: displayScaledCrop().x,
+ y: displayScaledCrop().y,
+ width: displayScaledCrop().width,
+ height: displayScaledCrop().height,
+ }}
+ borderRadius={9}
+ guideLines={props.showGuideLines}
+ handles={true}
+ highlighted={snappedRatio() !== null}
+ >
+ {props.children}
+ </CropAreaRenderer>
+ <div
+ class="absolute"
+ style={{
+ top: `${displayScaledCrop().y}px`,
+ left: `${displayScaledCrop().x}px`,
+ width: `${displayScaledCrop().width}px`,
+ height: `${displayScaledCrop().height}px`,
+ cursor: dragging() ? "grabbing" : "grab",
+ }}
+ onMouseDown={handleDragStart}
+ >
+ <div class="relative w-full">
+ <Transition
+ name="slide"
+ onEnter={(el, done) => {
+ const animation = el.animate(
+ [
+ { opacity: 0, transform: 'translateY(-8px)' },
+ { opacity: 0.65, transform: 'translateY(0)' }
+ ],
+ {
+ duration: 100,
+ easing: 'ease-out',
+ }
+ );
+ animation.finished.then(done);
+ }}
+ onExit={(el, done) => {
+ const animation = el.animate(
+ [
+ { opacity: 0.65, transform: 'translateY(0)' },
+ { opacity: 0, transform: 'translateY(-8px)' }
+ ],
+ {
+ duration: 100,
+ easing: 'ease-in',
+ }
+ );
+ animation.finished.then(done);
+ }}
+ >
+ <Show when={snappedRatio() !== null}>
+ <div class="absolute left-0 right-0 mx-auto top-2 bg-gray-200 opacity-80 h-6 w-10 rounded-[7px] text-center text-blue-400 text-sm border border-gray-50 dark:border-gray-300 outline outline-1 outline-[#dedede] dark:outline-[#000]">
+ {snappedRatio()![0]}:{snappedRatio()![1]}
+ </div>
+ </Show>
+ </Transition>
+ </div>
+ <For each={HANDLES}>
+ {(handle) => {
+ const isCorner = handle.x !== "c" && handle.y !== "c";
+
+ return isCorner ? (
+ <div
+ role="slider"
+ class="absolute z-10 flex h-[30px] w-[30px] items-center justify-center"
+ style={{
+ ...(handle.x === "l"
+ ? { left: "-12px" }
+ : handle.x === "r"
+ ? { right: "-12px" }
+ : { left: "50%", transform: "translateX(-50%)" }),
+ ...(handle.y === "t"
+ ? { top: "-12px" }
+ : handle.y === "b"
+ ? { bottom: "-12px" }
+ : { top: "50%", transform: "translateY(-50%)" }),
+ cursor: dragging() ? "grabbing" : `${handle.cursor}-resize`,
+ }}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ handleResizeStart(e.clientX, e.clientY, handle.direction);
+ }}
+ onTouchStart={(e) =>
+ handleResizeStartTouch(e, handle.direction)
+ }
+ />
+ ) : (
+ <div
+ role="slider"
+ class="absolute"
+ style={{
+ ...(handle.x === "l"
+ ? {
+ left: "0",
+ width: "16px",
+ transform: "translateX(-50%)",
+ }
+ : handle.x === "r"
+ ? {
+ right: "0",
+ width: "16px",
+ transform: "translateX(50%)",
+ }
+ : {
+ left: "0",
+ right: "0",
+ transform: "translateY(50%)",
+ }),
+ ...(handle.y === "t"
+ ? {
+ top: "0",
+ height: "16px",
+ transform: "translateY(-50%)",
+ }
+ : handle.y === "b"
+ ? { bottom: "0", height: "16px" }
+ : { top: "0", bottom: "0" }),
+ cursor: `${handle.cursor}-resize`,
+ }}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ handleResizeStart(e.clientX, e.clientY, handle.direction);
+ }}
+ onTouchStart={(e) =>
+ handleResizeStartTouch(e, handle.direction)
+ }
+ />
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 082b0ab9a..06629d7e3 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -167,11 +167,10 @@ export default function () {
await commands.showWindow("Upgrade");
}
}}
- class={`text-[0.6rem] ${
- isUpgraded()
+ class={`text-[0.6rem] ${isUpgraded()
? "bg-[--blue-400] text-gray-50 dark:text-gray-500"
: "bg-gray-200 cursor-pointer hover:bg-gray-300"
- } rounded-lg px-1.5 py-0.5`}
+ } rounded-lg px-1.5 py-0.5`}
>
{isUpgraded() ? "Pro" : "Upgrade to Pro"}
</span>
@@ -292,9 +291,14 @@ function useRequestPermission() {
import * as dialog from "@tauri-apps/plugin-dialog";
import * as updater from "@tauri-apps/plugin-updater";
import { makePersisted } from "@solid-primitives/storage";
-import titlebarState, { setTitlebar } from "~/utils/titlebar-state";
+import { setTitlebar } from "~/utils/titlebar-state";
import { type as ostype } from "@tauri-apps/plugin-os";
import { apiClient, protectedHeaders } from "~/utils/web-api";
+import { Transition } from "solid-transition-group";
+import {
+ getCurrentWebviewWindow,
+ WebviewWindow,
+} from "@tauri-apps/api/webviewWindow";
let hasChecked = false;
function createUpdateCheck() {
@@ -326,64 +330,230 @@ function TargetSelects(props: {
}) {
const screens = createQuery(() => listScreens);
const windows = createQuery(() => listWindows);
+ const [selectedScreen, setSelectedScreen] =
+ createSignal<CaptureScreen | null>(screens?.data?.[0] ?? null);
+
+ const isTargetScreenOrArea = createMemo(
+ () =>
+ props.options?.captureTarget.variant === "screen" ||
+ props.options?.captureTarget.variant === "area"
+ );
+ const isTargetCaptureArea = createMemo(
+ () => props.options?.captureTarget.variant === "area"
+ );
+
+ const [areaSelection, setAreaSelection] = createStore({
+ pending: false,
+ screen: selectedScreen(),
+ });
+
+ async function closeAreaSelection() {
+ setAreaSelection({ pending: false, screen: null });
+ (await WebviewWindow.getByLabel("capture-area"))?.close();
+ }
+
+ onMount(async () => {
+ const unlistenCaptureAreaWindow =
+ await getCurrentWebviewWindow().listen<boolean>(
+ "cap-window://capture-area/state/pending",
+ (event) => setAreaSelection("pending", event.payload)
+ );
+ onCleanup(unlistenCaptureAreaWindow);
+ });
+
+ let shouldAnimateAreaSelect = false;
+ createEffect(async () => {
+ const target = props.options?.captureTarget;
+ if (!target) return;
+
+ if (target.variant === "screen") {
+ if (target.id !== areaSelection.screen?.id) {
+ closeAreaSelection();
+ }
+ setSelectedScreen(target);
+ } else if (target.variant === "window") {
+ if (areaSelection.screen) closeAreaSelection();
+ shouldAnimateAreaSelect = true;
+ }
+ });
+
+ async function handleAreaSelectButtonClick() {
+ const targetScreen = selectedScreen();
+ if (!targetScreen) return;
+
+ closeAreaSelection();
+ if (isTargetCaptureArea() && props.options) {
+ commands.setRecordingOptions({
+ ...props.options,
+ captureTarget: { ...targetScreen, variant: "screen" },
+ });
+ return;
+ }
+
+ setAreaSelection({ pending: false, screen: targetScreen });
+ commands.showWindow({
+ CaptureArea: { screen: targetScreen },
+ });
+ }
return (
- <div class="flex flex-row items-center rounded-[0.5rem] relative border">
+ <div>
+ <Tooltip.Root openDelay={500}>
+ <Tooltip.Trigger class="fixed flex flex-row items-center w-8 h-8">
+ <Transition
+ onEnter={(el, done) => {
+ if (shouldAnimateAreaSelect)
+ el.animate(
+ [
+ {
+ transform: "scale(0.5)",
+ opacity: 0,
+ width: "0.2rem",
+ height: "0.2rem",
+ },
+ {
+ transform: "scale(1)",
+ opacity: 1,
+ width: "2rem",
+ height: "2rem",
+ },
+ ],
+ {
+ duration: 450,
+ easing: "cubic-bezier(0.65, 0, 0.35, 1)",
+ }
+ ).finished.then(done);
+ shouldAnimateAreaSelect = true;
+ }}
+ onExit={(el, done) =>
+ el
+ .animate(
+ [
+ {
+ transform: "scale(1)",
+ opacity: 1,
+ width: "2rem",
+ height: "2rem",
+ },
+ {
+ transform: "scale(0)",
+ opacity: 0,
+ width: "0.2rem",
+ height: "0.2rem",
+ },
+ ],
+ {
+ duration: 500,
+ easing: "ease-in-out",
+ }
+ )
+ .finished.then(done)
+ }
+ >
+ <Show when={isTargetScreenOrArea()}>
+ {(targetScreenOrArea) =>
+ <button
+ type="button"
+ disabled={!targetScreenOrArea}
+ onClick={handleAreaSelectButtonClick}
+ class={cx(
+ "flex items-center justify-center flex-shrink-0 w-full h-full rounded-[0.5rem] transition-all duration-200",
+ "hover:bg-gray-200 disabled:bg-gray-100 disabled:text-gray-400",
+ "focus-visible:outline font-[200] text-[0.875rem]",
+ isTargetCaptureArea()
+ ? "bg-gray-100 text-blue-400 border border-blue-200"
+ : "bg-gray-100 text-gray-400"
+ )}
+ >
+ <IconCapCrop
+ class={`w-[1rem] h-[1rem] ${areaSelection.pending
+ ? "animate-gentle-bounce duration-1000 text-gray-500 mt-1"
+ : ""
+ }`}
+ />
+ </button>
+ }
+ </Show>
+ </Transition>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">
+ {isTargetCaptureArea()
+ ? "Remove selection"
+ : areaSelection.pending
+ ? "Selecting area..."
+ : "Select area"}
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+
<div
- class="w-1/2 absolute flex p-px inset-0 transition-transform peer-focus-visible:outline outline-2 outline-blue-300 outline-offset-2 rounded-[0.6rem] overflow-hidden"
+ class={`flex flex-row items-center rounded-[0.5rem] relative border h-8 transition-all duration-500 ${isTargetScreenOrArea() ? "ml-[2.4rem]" : ""
+ }`}
style={{
- transform:
- props.options?.captureTarget.variant === "window"
- ? "translateX(100%)"
- : undefined,
+ "transition-timing-function":
+ "cubic-bezier(0.785, 0.135, 0.15, 0.86)",
}}
>
- <div class="bg-gray-100 flex-1" />
+ <div
+ class="w-1/2 absolute flex p-px inset-0 transition-transform peer-focus-visible:outline outline-2 outline-blue-300 outline-offset-2 rounded-[0.6rem] overflow-hidden"
+ style={{
+ transform:
+ props.options?.captureTarget.variant === "window"
+ ? "translateX(100%)"
+ : undefined,
+ }}
+ >
+ <div class="bg-gray-100 flex-1" />
+ </div>
+ <TargetSelect<CaptureScreen>
+ options={screens.data ?? []}
+ onChange={(value) => {
+ if (!value || !props.options) return;
+
+ commands.setRecordingOptions({
+ ...props.options,
+ captureTarget: { ...value, variant: "screen" },
+ });
+ }}
+ value={
+ props.options?.captureTarget.variant === "screen"
+ ? props.options.captureTarget
+ : null
+ }
+ placeholder="Screen"
+ optionsEmptyText="No screens found"
+ selected={isTargetScreenOrArea()}
+ />
+ <TargetSelect<CaptureWindow>
+ options={windows.data ?? []}
+ onChange={(value) => {
+ if (!props.options) return;
+
+ commands.setRecordingOptions({
+ ...props.options,
+ captureTarget: { ...value, variant: "window" },
+ });
+ }}
+ value={
+ props.options?.captureTarget.variant === "window"
+ ? props.options.captureTarget
+ : null
+ }
+ placeholder="Window"
+ optionsEmptyText="No windows found"
+ selected={props.options?.captureTarget.variant === "window"}
+ itemComponent={(props) => (
+ <div class="flex-1 flex flex-col overflow-x-hidden">
+ <div class="w-full truncate">{props.item.rawValue?.name}</div>
+ <div class="w-full text-xs">
+ {props.item.rawValue?.owner_name}
+ </div>
+ </div>
+ )}
+ />
</div>
- <TargetSelect<CaptureScreen>
- options={screens.data ?? []}
- onChange={(value) => {
- if (!value || !props.options) return;
-
- commands.setRecordingOptions({
- ...props.options,
- captureTarget: { ...value, variant: "screen" },
- });
- }}
- value={
- props.options?.captureTarget.variant === "screen"
- ? props.options.captureTarget
- : null
- }
- placeholder="Screen"
- optionsEmptyText="No screens found"
- selected={props.options?.captureTarget.variant === "screen"}
- />
- <TargetSelect<CaptureWindow>
- options={windows.data ?? []}
- onChange={(value) => {
- if (!props.options) return;
-
- commands.setRecordingOptions({
- ...props.options,
- captureTarget: { ...value, variant: "window" },
- });
- }}
- value={
- props.options?.captureTarget.variant === "window"
- ? props.options.captureTarget
- : null
- }
- placeholder="Window"
- optionsEmptyText="No windows found"
- selected={props.options?.captureTarget.variant === "window"}
- itemComponent={(props) => (
- <div class="flex-1 flex flex-col overflow-x-hidden">
- <div class="w-full truncate">{props.item.rawValue?.name}</div>
- <div class="w-full text-xs">{props.item.rawValue?.owner_name}</div>
- </div>
- )}
- />
</div>
);
}
@@ -703,16 +873,16 @@ function TargetSelect<T extends { id: number; name: string }>(props: {
as={
props.options.length <= 1
? (p) => (
- <button
- onClick={() => {
- props.onChange(props.options[0]);
- }}
- data-selected={props.selected}
- class={p.class}
- >
- <span class="truncate">{props.placeholder}</span>
- </button>
- )
+ <button
+ onClick={() => {
+ props.onChange(props.options[0]);
+ }}
+ data-selected={props.selected}
+ class={p.class}
+ >
+ <span class="truncate">{props.placeholder}</span>
+ </button>
+ )
: undefined
}
class="flex-1 text-gray-400 py-1 z-10 data-[selected='true']:text-gray-500 peer focus:outline-none transition-colors duration-100 w-full text-nowrap overflow-hidden px-2 flex gap-2 items-center justify-center"
@@ -786,8 +956,8 @@ function TargetSelectInfoPill<T>(props: {
{!props.permissionGranted
? "Request Permission"
: props.value !== null
- ? "On"
- : "Off"}
+ ? "On"
+ : "Off"}
</button>
);
}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index 2e864c578..153b2dea5 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -2,7 +2,6 @@ import { A, type RouteSectionProps } from "@solidjs/router";
import { createResource, For, Show, Suspense } from "solid-js";
import { Button } from "@cap/ui-solid";
import { getVersion } from "@tauri-apps/api/app";
-import { getCurrentWindow } from "@tauri-apps/api/window";
import "@total-typescript/ts-reset/filter-boolean";
import { commands } from "~/utils/tauri";
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index a857512f7..d81e4e4bb 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -40,6 +40,12 @@ const settingsList: Array<{
description:
"The dock icon will be hidden when there are no windows available to close.",
},
+ {
+ key: "hapticsEnabled",
+ label: "Enable Haptics",
+ platforms: ["macos"],
+ description: "Use haptics on Force Touch™ trackpads",
+ },
{
key: "autoCreateShareableLink",
label: "Automatically create shareable link after recording",
diff --git a/apps/desktop/src/routes/capture-area.tsx b/apps/desktop/src/routes/capture-area.tsx
new file mode 100644
index 000000000..5982dd4c1
--- /dev/null
+++ b/apps/desktop/src/routes/capture-area.tsx
@@ -0,0 +1,149 @@
+import { createSignal, onCleanup, onMount, Show } from "solid-js";
+import { createOptionsQuery } from "~/utils/queries";
+import { getCurrentWebviewWindow, WebviewWindow } from "@tauri-apps/api/webviewWindow";
+import Cropper from "~/components/Cropper";
+import { createStore } from "solid-js/store";
+import { type Crop } from "~/utils/tauri";
+import { makePersisted } from "@solid-primitives/storage";
+import { Tooltip } from "@kobalte/core";
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { Transition } from "solid-transition-group";
+
+export default function CaptureArea() {
+ const { options, setOptions } = createOptionsQuery();
+ const webview = getCurrentWebviewWindow();
+
+ const [state, setState] = makePersisted(createStore({
+ showGrid: true,
+ }), { name: "captureArea" });
+
+ const setPendingState = (pending: boolean) =>
+ webview.emitTo("main", "cap-window://capture-area/state/pending", pending);
+
+ let unlisten: () => void | undefined;
+ onMount(async () => {
+ setPendingState(true);
+ unlisten = await webview.onCloseRequested(() => setPendingState(false));
+ });
+ onCleanup(() => unlisten?.());
+
+ const [windowSize, setWindowSize] = createSignal({
+ x: window.innerWidth,
+ y: window.innerHeight,
+ });
+
+ onMount(() => {
+ createEventListenerMap(window, {
+ resize: () =>
+ setWindowSize({ x: window.innerWidth, y: window.innerHeight }),
+ keydown: (e) => {
+ if (e.key === "Escape") close();
+ else if (e.key === "Enter") handleConfirm();
+ },
+ });
+ });
+
+ const [crop, setCrop] = createStore<Crop>({
+ size: { x: 0, y: 0 },
+ position: { x: 0, y: 0 },
+ });
+
+ async function handleConfirm() {
+ const target = options.data?.captureTarget;
+ if (!options.data || !target || target.variant !== "screen") return;
+ setPendingState(false);
+
+ setOptions.mutate({
+ ...options.data,
+ captureTarget: {
+ variant: "area",
+ screen: target,
+ bounds: {
+ x: crop.position.x,
+ y: crop.position.y,
+ width: crop.size.x,
+ height: crop.size.y,
+ },
+ },
+ });
+
+ close();
+ }
+
+ const [visible, setVisible] = createSignal(true);
+ function close() {
+ setVisible(false);
+ setTimeout(async () => {
+ (await WebviewWindow.getByLabel("main"))?.unminimize();
+ setPendingState(false);
+ webview.close();
+ }, 250);
+ }
+
+ return (
+ <div class="w-screen h-screen overflow-hidden bg-black bg-opacity-25">
+ <div class="fixed w-full z-50 flex items-center justify-center">
+ <Transition
+ appear
+ enterActiveClass="fade-in animate-in slide-in-from-top-6"
+ exitActiveClass="fade-out animate-out slide-out-to-top-6"
+ >
+ <Show when={visible()}>
+ <div class="transition-all ease-out duration-300 absolute w-auto h-10 bg-gray-50 rounded-[12px] drop-shadow-2xl overflow-visible border border-gray-50 dark:border-gray-300 outline outline-1 outline-[#dedede] dark:outline-[#000] flex justify-around p-1 top-11">
+ <button
+ class="py-[0.25rem] px-2 text-gray-400 gap-[0.25rem] flex flex-row items-center rounded-[8px] ml-0 right-auto"
+ type="button"
+ onClick={close}
+ >
+ <IconCapCircleX class="size-5" />
+ </button>
+ <Tooltip.Root openDelay={500}>
+ <Tooltip.Trigger tabIndex={-1}>
+ <button
+ class={`py-[0.25rem] px-2 gap-[0.25rem] mr-2 hover:bg-gray-200 flex flex-row items-center rounded-[8px] transition-colors duration-200 ${state.showGrid ? "bg-gray-200 text-blue-300" : "text-gray-500 opacity-50"}`}
+ type="button"
+ onClick={() => setState("showGrid", (v) => !v)}
+ >
+ <IconCapPadding class="size-5" />
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in delay-1000 duration-500">
+ Rule of Thirds
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ <div class="flex flex-row flex-grow justify-center gap-2">
+ <button
+ class="text-blue-300 px-2 dark:text-blue-300 gap-[0.25rem] hover:bg-blue-50 flex flex-row items-center rounded-[8px] grow justify-center transition-colors duration-200"
+ type="button"
+ onClick={handleConfirm}
+ >
+ <IconCapCircleCheck class="size-5" />
+ <span class="font-[500] text-[0.875rem]">Confirm selection</span>
+ </button>
+ </div>
+ </div>
+ </Show>
+ </Transition>
+ </div>
+
+ <Transition
+ appear
+ enterActiveClass="fade-in animate-in"
+ exitActiveClass="fade-out animate-out"
+ >
+ <Show when={visible()}>
+ <Cropper
+ class="transition-all duration-300"
+ value={crop}
+ onCropChange={setCrop}
+ showGuideLines={state.showGrid}
+ mappedSize={{ x: windowSize().x, y: windowSize().y }}
+ />
+ </Show>
+ </Transition>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 3f1310746..378e018ba 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -4,16 +4,17 @@ import {
} from "@kobalte/core/radio-group";
import { Tabs as KTabs } from "@kobalte/core/tabs";
import { cx } from "cva";
-import { batch, type Component, createRoot, For, Show } from "solid-js";
+import { batch, type Component, createResource, createRoot, createSignal, For, Show } from "solid-js";
import { Dynamic } from "solid-js/web";
import { createWritableMemo } from "@solid-primitives/memo";
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { produce } from "solid-js/store";
-import type {
- BackgroundSource,
- CursorType,
- CursorAnimationStyle,
+import {
+ type BackgroundSource,
+ type CursorType,
+ type CursorAnimationStyle,
+ commands,
} from "~/utils/tauri";
import { useEditorContext } from "./context";
import {
@@ -29,6 +30,8 @@ import {
DEFAULT_GRADIENT_TO,
DEFAULT_PROJECT_CONFIG,
} from "./projectConfig";
+import { generalSettingsStore } from "~/store";
+import { type as ostype } from "@tauri-apps/plugin-os";
const BACKGROUND_SOURCES = {
wallpaper: "Wallpaper",
@@ -83,6 +86,12 @@ export function ConfigSidebar() {
},
};
+ const [previousAngle, setPreviousAngle] = createSignal(0);
+ const [hapticsEnabled, hapticsEnabledOptions] = createResource(async () =>
+ (await generalSettingsStore.get())?.hapticsEnabled && ostype() === "macos"
+ );
+ generalSettingsStore.listen(() => hapticsEnabledOptions.refetch());
+
return (
<KTabs
value={selectedTab()}
@@ -178,7 +187,7 @@ export function ConfigSidebar() {
BACKGROUND_SOURCES_LIST.indexOf(
project.background.source.type
) ===
- i + 1
+ i + 1
? "bg-gray-50"
: "bg-gray-200"
)}
@@ -325,12 +334,19 @@ export function ConfigSidebar() {
const rawNewAngle =
Math.round(
start +
- (downEvent.clientY - moveEvent.clientY)
+ (downEvent.clientY - moveEvent.clientY)
) % max;
const newAngle = moveEvent.shiftKey
? rawNewAngle
: Math.round(rawNewAngle / 45) * 45;
+ if (!moveEvent.shiftKey && hapticsEnabled() && project.background.source.type === "gradient") {
+ if (previousAngle() !== newAngle) {
+ commands.performHapticFeedback("Alignment", "Now");
+ }
+ setPreviousAngle(newAngle);
+ }
+
setProject("background", "source", {
type: "gradient",
angle:
@@ -436,8 +452,8 @@ export function ConfigSidebar() {
item.x === "left"
? "left-2"
: item.x === "right"
- ? "right-2"
- : "left-1/2 transform -translate-x-1/2",
+ ? "right-2"
+ : "left-1/2 transform -translate-x-1/2",
item.y === "top" ? "top-2" : "bottom-2"
)}
onClick={() => setProject("camera", "position", item)}
@@ -468,15 +484,14 @@ export function ConfigSidebar() {
<Field
name="Size During Zoom"
icon={<IconCapEnlarge />}
- value={`${
- project.camera.zoom_size ??
+ value={`${project.camera.zoom_size ??
DEFAULT_PROJECT_CONFIG.camera.zoom_size
- }%`}
+ }%`}
>
<Slider
value={[
project.camera.zoom_size ??
- DEFAULT_PROJECT_CONFIG.camera.zoom_size,
+ DEFAULT_PROJECT_CONFIG.camera.zoom_size,
]}
onChange={(v) => setProject("camera", "zoom_size", v[0])}
minValue={10}
@@ -489,7 +504,7 @@ export function ConfigSidebar() {
<Slider
value={[
project.camera.rounding ??
- DEFAULT_PROJECT_CONFIG.camera.rounding,
+ DEFAULT_PROJECT_CONFIG.camera.rounding,
]}
onChange={(v) => setProject("camera", "rounding", v[0])}
minValue={0}
@@ -723,7 +738,7 @@ export function ConfigSidebar() {
<KTabs.Trigger
value="manual"
class="flex-1 text-gray-400 py-1 z-10 ui-selected:text-gray-500 peer outline-none transition-colors duration-100"
- // onClick={() => setSelectedTab(item.id)}
+ // onClick={() => setSelectedTab(item.id)}
>
Manual
</KTabs.Trigger>
@@ -761,7 +776,7 @@ export function ConfigSidebar() {
x: Math.max(
Math.min(
(moveEvent.clientX - bounds.left) /
- bounds.width,
+ bounds.width,
1
),
0
@@ -769,7 +784,7 @@ export function ConfigSidebar() {
y: Math.max(
Math.min(
(moveEvent.clientY - bounds.top) /
- bounds.height,
+ bounds.height,
1
),
0
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 673b719a1..ae67f156c 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -3,24 +3,20 @@ import { trackDeep } from "@solid-primitives/deep";
import { throttle } from "@solid-primitives/scheduled";
import { useSearchParams } from "@solidjs/router";
import {
- For,
Match,
Show,
Switch,
- batch,
createEffect,
createMemo,
- createRoot,
createSignal,
on,
onMount,
} from "solid-js";
import { createStore } from "solid-js/store";
import { createMutation } from "@tanstack/solid-query";
-import { createEventListenerMap } from "@solid-primitives/event-listener";
import { convertFileSrc } from "@tauri-apps/api/core";
-import { events } from "~/utils/tauri";
+import { type Crop, events } from "~/utils/tauri";
import {
EditorContextProvider,
EditorInstanceContextProvider,
@@ -41,6 +37,9 @@ import { Header } from "./Header";
import { Player } from "./Player";
import { ConfigSidebar } from "./ConfigSidebar";
import { Timeline } from "./Timeline";
+import Cropper, { cropToFloor } from "~/components/Cropper";
+import { makePersisted } from "@solid-primitives/storage";
+import { Tooltip } from "@kobalte/core";
export function Editor() {
const [params] = useSearchParams<{ id: string }>();
@@ -285,62 +284,65 @@ function Dialogs() {
{(dialog) => {
const { setProject: setState, editorInstance } =
useEditorContext();
- const [crop, setCrop] = createStore({
+ const [crop, setCrop] = createStore<Crop>({
position: dialog().position,
size: dialog().size,
});
+ const [cropOptions, setCropOptions] = makePersisted(createStore({
+ showGrid: false
+ }), { name: "cropOptionsState" });
const display = editorInstance.recordings.segments[0].display;
- const styles = createMemo(() => {
- return {
- left: `${(crop.position.x / display.width) * 100}%`,
- top: `${(crop.position.y / display.height) * 100}%`,
- right: `calc(${
- ((display.width - crop.size.x - crop.position.x) /
- display.width) *
- 100
- }%)`,
- bottom: `calc(${
- ((display.height - crop.size.y - crop.position.y) /
- display.height) *
- 100
- }%)`,
- };
- });
-
- let cropAreaRef!: HTMLDivElement;
- let cropTargetRef!: HTMLDivElement;
+ const adjustedCrop = createMemo(() => cropToFloor(crop));
return (
<>
<Dialog.Header>
<div class="flex flex-row space-x-[0.75rem]">
- {/*<AspectRatioSelect />*/}
<div class="flex flex-row items-center space-x-[0.5rem] text-gray-400">
<span>Size</span>
<div class="w-[3.25rem]">
- <Input value={crop.size.x} disabled />
+ <Input class="bg-transparent dark:!text-[#ababab]" value={adjustedCrop().size.x} disabled />
</div>
<span>x</span>
<div class="w-[3.25rem]">
- <Input value={crop.size.y} disabled />
+ <Input class="bg-transparent dark:!text-[#ababab]" value={adjustedCrop().size.y} disabled />
</div>
</div>
<div class="flex flex-row items-center space-x-[0.5rem] text-gray-400">
<span>Position</span>
<div class="w-[3.25rem]">
- <Input value={crop.position.x} disabled />
+ <Input class="bg-transparent dark:!text-[#ababab]" value={adjustedCrop().position.x} disabled />
</div>
<span>x</span>
<div class="w-[3.25rem]">
<Input
- class="w-[3.25rem]"
- value={crop.position.y}
+ class="w-[3.25rem] bg-transparent dark:!text-[#ababab]"
+ value={adjustedCrop().position.y}
disabled
/>
</div>
</div>
+ <div class="flex flex-row items-center space-x-[0.5rem] text-gray-400">
+ <Tooltip.Root openDelay={500}>
+ <Tooltip.Trigger class="fixed flex flex-row items-center w-8 h-8" tabIndex={-1}>
+ <button
+ type="button"
+ class={`flex items-center justify-center text-center rounded-[0.5rem] h-[2rem] w-[2rem] border text-[0.875rem] focus:border-blue-300 outline-none transition-colors duration-200 ${cropOptions.showGrid ? "bg-gray-200 text-blue-300" : "text-gray-500"}`}
+ onClick={() => setCropOptions("showGrid", (s) => !s)}
+ >
+ <IconCapPadding class="w-4" />
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">
+ Rule of Thirds
+ <Tooltip.Arrow class="fill-gray-500" />
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </div>
</div>
<EditorButton
leftIcon={<IconCapCircleX />}
@@ -360,8 +362,16 @@ function Dialogs() {
</Dialog.Header>
<Dialog.Content>
<div class="flex flex-row justify-center">
- <div class="relative bg-blue-200" ref={cropAreaRef}>
- <div class="divide-black-transparent-10 overflow-hidden rounded-lg">
+ <div class="divide-black-transparent-10 overflow-hidden rounded">
+ <Cropper
+ value={crop}
+ onCropChange={setCrop}
+ mappedSize={{
+ x: display.width,
+ y: display.height,
+ }}
+ showGuideLines={cropOptions.showGrid}
+ >
<img
class="shadow pointer-events-none max-h-[70vh]"
alt="screenshot"
@@ -369,223 +379,14 @@ function Dialogs() {
`${editorInstance.path}/screenshots/display.jpg`
)}
/>
- </div>
- <div
- class="bg-white-transparent-20 absolute cursor-move"
- ref={cropTargetRef}
- style={styles()}
- onMouseDown={(downEvent) => {
- const original = {
- position: { ...crop.position },
- size: { ...crop.size },
- };
-
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mouseup: () => dispose(),
- mousemove: (moveEvent) => {
- const diff = {
- x:
- ((moveEvent.clientX -
- downEvent.clientX) /
- cropAreaRef.clientWidth) *
- display.width,
- y:
- ((moveEvent.clientY -
- downEvent.clientY) /
- cropAreaRef.clientHeight) *
- display.height,
- };
-
- const x = Math.floor(
- (() => {
- if (original.position.x + diff.x < 0)
- return 0;
- if (
- original.position.x + diff.x >
- display.width - crop.size.x
- )
- return display.width - crop.size.x;
-
- return original.position.x + diff.x;
- })()
- );
-
- const y = Math.floor(
- (() => {
- if (original.position.y + diff.y < 0)
- return 0;
- if (
- original.position.y + diff.y >
- display.height - crop.size.y
- )
- return display.height - crop.size.y;
-
- return original.position.y + diff.y;
- })()
- );
-
- setCrop("position", { x, y });
- },
- });
- });
- }}
- >
- <For
- each={Array.from({ length: 4 }, (_, i) => ({
- x: i < 2 ? ("l" as const) : ("r" as const),
- y:
- i % 2 === 0 ? ("t" as const) : ("b" as const),
- }))}
- >
- {(pos) => {
- const behaviours = {
- x:
- pos.x === "l"
- ? ("both" as const)
- : ("resize" as const),
- y:
- pos.y === "t"
- ? ("both" as const)
- : ("resize" as const),
- };
-
- return (
- <button
- type="button"
- class="absolute"
- style={{
- ...(pos.x === "l"
- ? { left: "0px" }
- : { right: "0px" }),
- ...(pos.y === "t"
- ? { top: "0px" }
- : { bottom: "0px" }),
- }}
- onMouseDown={(downEvent) => {
- downEvent.stopPropagation();
-
- const original = {
- position: { ...crop.position },
- size: { ...crop.size },
- };
-
- const MIN_SIZE = 100;
-
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mouseup: () => dispose(),
- mousemove: (moveEvent) => {
- batch(() => {
- const diff = {
- x:
- ((moveEvent.clientX -
- downEvent.clientX) /
- cropAreaRef.clientWidth) *
- display.width,
- y:
- ((moveEvent.clientY -
- downEvent.clientY) /
- cropAreaRef.clientHeight) *
- display.height,
- };
-
- if (behaviours.x === "resize") {
- setCrop(
- "size",
- "x",
- Math.floor(
- clamp(
- original.size.x + diff.x,
- MIN_SIZE,
- display.width -
- crop.position.x
- )
- )
- );
- } else {
- setCrop(
- "position",
- "x",
- Math.floor(
- clamp(
- original.position.x +
- diff.x,
- 0,
- display.width - MIN_SIZE
- )
- )
- );
- setCrop(
- "size",
- "x",
- Math.floor(
- clamp(
- original.size.x - diff.x,
- MIN_SIZE,
- display.width
- )
- )
- );
- }
-
- if (behaviours.y === "resize") {
- setCrop(
- "size",
- "y",
- Math.floor(
- clamp(
- original.size.y + diff.y,
- MIN_SIZE,
- display.height -
- crop.position.y
- )
- )
- );
- } else {
- setCrop(
- "position",
- "y",
- Math.floor(
- clamp(
- original.position.y +
- diff.y,
- 0,
- display.height - MIN_SIZE
- )
- )
- );
- setCrop(
- "size",
- "y",
- Math.floor(
- clamp(
- original.size.y - diff.y,
- MIN_SIZE,
- display.height
- )
- )
- );
- }
- });
- },
- });
- });
- }}
- >
- <div class="size-[1rem] bg-gray-500 border border-gray-50 rounded-full absolute -top-[0.5rem] -left-[0.5rem]" />
- </button>
- );
- }}
- </For>
- </div>
+ </Cropper>
</div>
</div>
</Dialog.Content>
<Dialog.Footer>
<Button
onClick={() => {
- setState("background", "crop", crop);
+ setState("background", "crop", adjustedCrop());
setDialog((d) => ({ ...d, open: false }));
}}
>
@@ -602,7 +403,3 @@ function Dialogs() {
</Dialog.Root>
);
}
-
-function clamp(n: number, min = 0, max = 1) {
- return Math.max(min, Math.min(max, n));
-}
diff --git a/apps/desktop/src/routes/window-capture-occluder.tsx b/apps/desktop/src/routes/window-capture-occluder.tsx
index 4c159e207..7500f803d 100644
--- a/apps/desktop/src/routes/window-capture-occluder.tsx
+++ b/apps/desktop/src/routes/window-capture-occluder.tsx
@@ -1,4 +1,6 @@
+import { type as ostype } from "@tauri-apps/plugin-os";
import { Show, Suspense } from "solid-js";
+import CropAreaRenderer from "~/components/CropAreaRenderer";
import { createCurrentRecordingQuery } from "~/utils/queries";
export default function () {
@@ -9,39 +11,15 @@ export default function () {
<Show
when={
currentRecording.data &&
- currentRecording.data.captureTarget.variant === "window" &&
+ (currentRecording.data.captureTarget.variant !== "screen") &&
currentRecording.data.captureTarget.bounds
}
>
{(bounds) => (
- <div class="w-screen h-screen relative animate-in fade-in">
- <div
- class="bg-black-transparent-40 absolute inset-x-0 top-0"
- style={{ height: `${bounds().y}px` }}
- />
- <div
- class="bg-black-transparent-40 absolute left-0"
- style={{
- top: `${bounds().y}px`,
- height: `${bounds().height}px`,
- width: `${bounds().x}px`,
- }}
- />
- <div
- class="bg-black-transparent-40 absolute right-0"
- style={{
- top: `${bounds().y}px`,
- height: `${bounds().height}px`,
- width: `calc(100vw - ${bounds().x + bounds().width}px)`,
- }}
- />
- <div
- class="bg-black-transparent-40 absolute inset-x-0 bottom-0"
- style={{
- height: `calc(100vh - ${bounds().y + bounds().height}px)`,
- }}
- />
- </div>
+ <CropAreaRenderer
+ bounds={bounds()}
+ borderRadius={ostype() === "macos" ? 9 : 7}
+ />
)}
</Show>
</Suspense>
diff --git a/apps/desktop/src/utils/box.ts b/apps/desktop/src/utils/box.ts
new file mode 100644
index 000000000..3081afa63
--- /dev/null
+++ b/apps/desktop/src/utils/box.ts
@@ -0,0 +1,187 @@
+// Attribution to area-selection (MIT License) by 7anshuai
+// https://github.com/7anshuai/area-selection
+
+type XY = { x: number, y: number };
+
+export type Bounds = { size: XY, position: XY };
+
+export default class Box {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+
+ private constructor(x: number, y: number, width: number, height: number) {
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ }
+
+ static from(position: XY, size: XY): Box {
+ return new Box(position.x, position.y, size.x, size.y);
+ }
+
+ toBounds(): Bounds {
+ return {
+ position: { x: this.x, y: this.y },
+ size: { x: this.width, y: this.height }
+ };
+ }
+
+ resize(newWidth: number, newHeight: number, origin: XY): Box {
+ const fromX = this.x + this.width * origin.x;
+ const fromY = this.y + this.height * origin.y;
+
+ this.x = fromX - newWidth * origin.x;
+ this.y = fromY - newHeight * origin.y;
+ this.width = newWidth;
+ this.height = newHeight;
+
+ return this;
+ }
+
+ scale(factor: number, origin: XY): Box {
+ const newWidth = this.width * factor;
+ const newHeight = this.height * factor;
+ return this.resize(newWidth, newHeight, origin);
+ }
+
+ move(x: number | null, y: number | null): Box {
+ if (x !== null) {
+ this.x = x;
+ }
+ if (y !== null) {
+ this.y = y;
+ }
+ return this;
+ }
+
+ getAbsolutePoint(point: XY): XY {
+ return {
+ x: this.x + this.width * point.x,
+ y: this.y + this.height * point.y,
+ };
+ }
+
+ constrainAll(box: Box, mapped: XY, origin: XY, aspectRatio?: number) {
+ if (aspectRatio) this.constrainToRatio(aspectRatio, origin);
+ this.constrainToBoundary(mapped.x, mapped.y, origin);
+ return box;
+ }
+
+ constrainToRatio(
+ ratio: number,
+ origin: XY,
+ grow: "width" | "height" = "height"
+ ): Box {
+ if (!ratio) return this;
+
+ switch (grow) {
+ case "height":
+ return this.resize(this.width, this.width / ratio, origin);
+ case "width":
+ return this.resize(this.height * ratio, this.height, origin);
+ default:
+ return this.resize(this.width, this.width / ratio, origin);
+ }
+ }
+
+ constrainToBoundary(
+ boundaryWidth: number,
+ boundaryHeight: number,
+ origin: XY
+ ): Box {
+ const originPoint = this.getAbsolutePoint(origin);
+
+ const directionX = -2 * origin.x + 1;
+ const directionY = -2 * origin.y + 1;
+
+ let maxWidth: number;
+ let maxHeight: number;
+
+ switch (directionX) {
+ case -1:
+ maxWidth = originPoint.x;
+ break;
+ case 0:
+ maxWidth = Math.min(originPoint.x, boundaryWidth - originPoint.x) * 2;
+ break;
+ case 1:
+ maxWidth = boundaryWidth - originPoint.x;
+ break;
+ default:
+ maxWidth = boundaryWidth;
+ }
+
+ switch (directionY) {
+ case -1:
+ maxHeight = originPoint.y;
+ break;
+ case 0:
+ maxHeight = Math.min(originPoint.y, boundaryHeight - originPoint.y) * 2;
+ break;
+ case 1:
+ maxHeight = boundaryHeight - originPoint.y;
+ break;
+ default:
+ maxHeight = boundaryHeight;
+ }
+
+ if (this.width > maxWidth) {
+ const factor = maxWidth / this.width;
+ this.scale(factor, origin);
+ }
+ if (this.height > maxHeight) {
+ const factor = maxHeight / this.height;
+ this.scale(factor, origin);
+ }
+
+ return this;
+ }
+
+ constrainToSize(
+ maxWidth: number | null,
+ maxHeight: number | null,
+ minWidth: number | null,
+ minHeight: number | null,
+ origin: XY,
+ ratio: number | null = null
+ ): Box {
+ if (ratio) {
+ if (ratio > 1) {
+ maxWidth = maxHeight ? maxHeight / ratio : maxWidth;
+ minHeight = minWidth ? minWidth * ratio : minHeight;
+ } else if (ratio < 1) {
+ maxHeight = maxWidth ? maxWidth * ratio : maxHeight;
+ minWidth = minHeight ? minHeight / ratio : minWidth;
+ }
+ }
+
+ if (maxWidth && this.width > maxWidth) {
+ const newWidth = maxWidth;
+ const newHeight = ratio === null ? this.height : maxHeight!;
+ this.resize(newWidth, newHeight, origin);
+ }
+
+ if (maxHeight && this.height > maxHeight) {
+ const newWidth = ratio === null ? this.width : maxWidth!;
+ const newHeight = maxHeight;
+ this.resize(newWidth, newHeight, origin);
+ }
+
+ if (minWidth && this.width < minWidth) {
+ const newWidth = minWidth;
+ const newHeight = ratio === null ? this.height : minHeight!;
+ this.resize(newWidth, newHeight, origin);
+ }
+
+ if (minHeight && this.height < minHeight) {
+ const newWidth = ratio === null ? this.width : minWidth!;
+ const newHeight = minHeight;
+ this.resize(newWidth, newHeight, origin);
+ }
+
+ return this;
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/src/utils/canvas.ts b/apps/desktop/src/utils/canvas.ts
new file mode 100644
index 000000000..ea81c7acd
--- /dev/null
+++ b/apps/desktop/src/utils/canvas.ts
@@ -0,0 +1,71 @@
+/**
+ * Creates a high DPI canvas context and sets up a resize observer to handle
+ * redrawing the canvas when its size changes.
+ *
+ * @param canvas - The HTML canvas element to create the context for.
+ * @param drawOnResizeCallback - A callback function that is called whenever the canvas is resized.
+ * It receives the 2D rendering context as an argument.
+ * @returns An object containing the 2D rendering context and a cleanup function to disconnect the resize observer,
+ * or null if the context could not be obtained.
+ */
+export function createHiDPICanvasContext(
+ canvas: HTMLCanvasElement,
+ drawOnResizeCallback: (ctx: CanvasRenderingContext2D) => void
+): {
+ ctx: CanvasRenderingContext2D;
+ cleanup: () => void;
+} | null {
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+ polyfillCanvasContextRoundRect();
+
+ const scale = (rect: DOMRect) => {
+ const dpr = window.devicePixelRatio || 1;
+ canvas.width = rect.width * dpr;
+ canvas.height = rect.height * dpr;
+ ctx.scale(dpr, dpr);
+ drawOnResizeCallback(ctx);
+ };
+
+ const observer = new ResizeObserver(([entry]) => scale(entry.contentRect));
+ observer.observe(canvas);
+
+ return {
+ ctx,
+ cleanup: () => observer.disconnect(),
+ };
+}
+
+// TODO: May not be needed depending on the minimum macOS version.
+// https://stackoverflow.com/questions/51232811/canvas-clearrect-with-rounded-corners
+function polyfillCanvasContextRoundRect() {
+ if ("roundRect" in CanvasRenderingContext2D) return;
+ CanvasRenderingContext2D.prototype.roundRect = function (
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ radii?: number | DOMPointInit | Iterable<number | DOMPointInit>
+ ) {
+ this.beginPath();
+ let radius = typeof radii === "number" ? radii : 0;
+
+ if (typeof radii === "object") {
+ if (Symbol.iterator in radii) {
+ const radiiArray = Array.from(radii) as number[];
+ radius = radiiArray[0] || 0;
+ } else if ("x" in radii && "y" in radii) {
+ radius = radii.x!;
+ }
+ }
+
+ const adjustedRadius = Math.min(radius, w / 2, h / 2);
+
+ this.moveTo(x + adjustedRadius, y);
+ this.arcTo(x + w, y, x + w, y + h, adjustedRadius);
+ this.arcTo(x + w, y + h, x, y + h, adjustedRadius);
+ this.arcTo(x, y + h, x, y, adjustedRadius);
+ this.arcTo(x, y, x + w, y, adjustedRadius);
+ this.closePath();
+ };
+}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 2ceeb9fec..897ae6a07 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -166,6 +166,9 @@ async writeClipboardString(text: string) : Promise<null> {
},
async getEditorTotalFrames(videoId: string, fps: number) : Promise<number> {
return await TAURI_INVOKE("get_editor_total_frames", { videoId, fps });
+},
+async performHapticFeedback(pattern: HapticPattern | null, time: HapticPerformanceTime | null) : Promise<null> {
+ return await TAURI_INVOKE("perform_haptic_feedback", { pattern, time });
}
}
@@ -234,6 +237,7 @@ export type CameraMeta = { path: string; fps?: number }
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
+export type CaptureArea = { screen: CaptureScreen; bounds: Bounds }
export type CaptureScreen = { id: number; name: string; refresh_rate: number }
export type CaptureWindow = { id: number; owner_name: string; name: string; bounds: Bounds; refresh_rate: number }
export type Crop = { position: XY<number>; size: XY<number> }
@@ -245,7 +249,9 @@ export type Display = { path: string; fps?: number }
export type EditorStateChanged = { playhead_position: number }
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
export type Flags = { recordMouse: boolean; split: boolean; pauseResume: boolean; zoom: boolean }
-export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
+export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
+export type HapticPattern = "Alignment" | "LevelChange" | "Generic"
+export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"
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 }
@@ -280,11 +286,11 @@ export type RequestStartRecording = null
export type RequestStopRecording = null
export type Resolution = { width: number; height: number }
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 ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ variant: "screen" } & CaptureScreen) | ({ variant: "area" } & CaptureArea)
export type SegmentRecordings = { display: Video; camera: Video | null; audio: Audio | null }
export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }
export type SharingMeta = { id: string; link: string }
-export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "PrevRecordings" | "WindowCaptureOccluder" | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn"
+export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "PrevRecordings" | "WindowCaptureOccluder" | { CaptureArea: { screen: CaptureScreen } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn"
export type SingleSegment = { display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; cursor?: string | null }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }
export type TimelineSegment = { recordingSegment: number | null; timescale: number; start: number; end: number }
diff --git a/apps/desktop/tailwind.config.js b/apps/desktop/tailwind.config.js
index 4b7a359a3..74bd29d20 100644
--- a/apps/desktop/tailwind.config.js
+++ b/apps/desktop/tailwind.config.js
@@ -10,14 +10,14 @@ module.exports = {
keyframes: {
...baseConfig.theme?.extend?.keyframes,
gentleBounce: {
- '0%, 100%': { transform: 'translateY(0)' },
- '50%': { transform: 'translateY(-4px)' },
- }
+ "0%, 100%": { transform: "translateY(0)" },
+ "50%": { transform: "translateY(-4px)" },
+ },
},
animation: {
...baseConfig.theme?.extend?.animation,
- 'gentle-bounce': 'gentleBounce 1.5s ease-in-out infinite',
- }
- }
- }
+ "gentle-bounce": "gentleBounce 1.5s ease-in-out infinite",
+ },
+ },
+ },
};
diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rs
index 5f0c6de6c..063d45ca1 100644
--- a/crates/media/src/platform/mod.rs
+++ b/crates/media/src/platform/mod.rs
@@ -11,7 +11,7 @@ mod platform_impl;
pub use platform_impl::*;
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type)]
+#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Type)]
pub struct Bounds {
pub x: f64,
pub y: f64,
@@ -19,17 +19,6 @@ 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,
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 45026ef29..0cda2b965 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -42,11 +42,18 @@ pub struct CaptureScreen {
pub refresh_rate: u32,
}
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct CaptureArea {
+ pub screen: CaptureScreen,
+ pub bounds: Bounds,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", tag = "variant")]
pub enum ScreenCaptureTarget {
Window(CaptureWindow),
Screen(CaptureScreen),
+ Area(CaptureArea),
}
impl PartialEq<Target> for ScreenCaptureTarget {
@@ -55,11 +62,15 @@ impl PartialEq<Target> for ScreenCaptureTarget {
(Self::Window(capture_window), Target::Window(window)) => {
window.id == capture_window.id
}
+ (ScreenCaptureTarget::Area(capture_area), Target::Display(display)) => {
+ display.id == capture_area.screen.id
+ }
(ScreenCaptureTarget::Screen(capture_screen), Target::Display(display)) => {
display.id == capture_screen.id
}
(&ScreenCaptureTarget::Window(_), &scap::Target::Display(_))
- | (&ScreenCaptureTarget::Screen(_), &scap::Target::Window(_)) => todo!(),
+ | (&ScreenCaptureTarget::Screen(_), &scap::Target::Window(_))
+ | (&ScreenCaptureTarget::Area(_), &scap::Target::Window(_)) => todo!(),
}
}
}
@@ -69,6 +80,7 @@ impl ScreenCaptureTarget {
match self {
ScreenCaptureTarget::Window(window) => window.refresh_rate,
ScreenCaptureTarget::Screen(screen) => screen.refresh_rate,
+ ScreenCaptureTarget::Area(area) => area.screen.refresh_rate,
}
.min(MAX_FPS)
}
@@ -144,6 +156,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
ScreenCaptureTarget::Screen(capture_screen) => {
platform::monitor_bounds(capture_screen.id)
}
+ ScreenCaptureTarget::Area(capture_area) => capture_area.bounds,
}
}
@@ -171,6 +184,16 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
},
}),
ScreenCaptureTarget::Screen(_) => None,
+ ScreenCaptureTarget::Area(capture_area) => Some(Area {
+ size: Size {
+ width: capture_area.bounds.width,
+ height: capture_area.bounds.height,
+ },
+ origin: Point {
+ x: capture_area.bounds.x,
+ y: capture_area.bounds.y,
+ },
+ }),
};
let target = match &self.target {
@@ -211,6 +234,13 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
_ => false,
})
.cloned(),
+ ScreenCaptureTarget::Area(capture_area) => targets
+ .iter()
+ .find(|t| match t {
+ Target::Display(display) => display.id == capture_area.screen.id,
+ _ => false,
+ })
+ .cloned(),
}
.expect("Capture target not found");
@@ -495,7 +525,7 @@ pub fn list_windows() -> Vec<(CaptureWindow, Target)> {
owner_name: platform_window.owner_name.clone(),
name: platform_window.name.clone(),
bounds: platform_window.bounds,
- refresh_rate: get_target_fps(&target).unwrap(),
+ refresh_rate: get_target_fps(&target).unwrap_or_default(),
},
target,
)