Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: v1 of screenshots
Richie McIlroyf7047a0a1e66
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex e3c3f1ffa..5dc049ef2 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -2223,6 +2223,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {recording::resume_recording,recording::restart_recording,recording::delete_recording,+ recording::take_screenshot,recording::list_cameras,recording::list_capture_windows,recording::list_capture_displays,diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 1c821f87b..41089121c 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -441,6 +441,7 @@ pub async fn start_recording(}}RecordingMode::Studio => None,+ RecordingMode::Screenshot => return Err("Use take_screenshot for screenshots".to_string()),};let date_time = if cfg!(windows) {@@ -467,6 +468,9 @@ pub async fn start_recording(RecordingMode::Instant => {RecordingMetaInner::Instant(InstantRecordingMeta::InProgress { recording: true })}+ RecordingMode::Screenshot => {+ return Err("Use take_screenshot for screenshots".to_string());+ }},sharing: None,upload: None,@@ -725,6 +729,9 @@ pub async fn start_recording(camera_feed: camera_feed.clone(),})}+ RecordingMode::Screenshot => Err(anyhow!(+ "Screenshot mode should be handled via take_screenshot"+ )),}}.await;@@ -1014,6 +1021,47 @@ pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> ROk(())}+#[tauri::command(async)]+#[specta::specta]+#[tracing::instrument(name = "take_screenshot", skip(app))]+pub async fn take_screenshot(+ app: AppHandle,+ target: ScreenCaptureTarget,+) -> Result<PathBuf, String> {+ use crate::NewScreenshotAdded;+ use crate::notifications;+ use cap_recording::screenshot::capture_screenshot;++ let image = capture_screenshot(target)+ .await+ .map_err(|e| format!("Failed to capture screenshot: {e}"))?;++ let screenshots_dir = app.path().app_data_dir().unwrap().join("screenshots");++ std::fs::create_dir_all(&screenshots_dir).map_err(|e| e.to_string())?;++ let date_time = if cfg!(windows) {+ chrono::Local::now().format("%Y-%m-%d %H.%M.%S")+ } else {+ chrono::Local::now().format("%Y-%m-%d %H:%M:%S")+ };++ let file_name = format!("Screenshot {date_time}.jpg");+ let path = screenshots_dir.join(file_name);++ image+ .save_with_format(&path, image::ImageFormat::Jpeg)+ .map_err(|e| format!("Failed to save screenshot: {e}"))?;++ let _ = NewScreenshotAdded { path: path.clone() }.emit(&app);++ notifications::send_notification(&app, notifications::NotificationType::ScreenshotSaved);++ AppSounds::StopRecording.play();++ Ok(path)+}+// runs when a recording ends, whether from success or failureasync fn handle_recording_end(handle: AppHandle,diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 12cde9fef..1ea90ff01 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -49,6 +49,7 @@ pub enum CapWindowId {Upgrade,ModeSelect,Debug,+ ScreenshotEditor,}impl FromStr for CapWindowId {@@ -67,6 +68,7 @@ impl FromStr for CapWindowId {"upgrade" => Self::Upgrade,"mode-select" => Self::ModeSelect,"debug" => Self::Debug,+ "screenshot-editor" => Self::ScreenshotEditor,s if s.starts_with("editor-") => Self::Editor {id: s.replace("editor-", "")@@ -110,6 +112,7 @@ impl std::fmt::Display for CapWindowId {Self::ModeSelect => write!(f, "mode-select"),Self::Editor { id } => write!(f, "editor-{id}"),Self::Debug => write!(f, "debug"),+ Self::ScreenshotEditor => write!(f, "screenshot-editor"),}}}@@ -127,6 +130,7 @@ impl CapWindowId {Self::CaptureArea => "Cap Capture Area".to_string(),Self::RecordingControls => "Cap Recording Controls".to_string(),Self::Editor { .. } => "Cap Editor".to_string(),+ Self::ScreenshotEditor => "Cap Screenshot Editor".to_string(),Self::ModeSelect => "Cap Mode Selection".to_string(),Self::Camera => "Cap Camera".to_string(),Self::RecordingsOverlay => "Cap Recordings Overlay".to_string(),@@ -140,6 +144,7 @@ impl CapWindowId {Self::Setup| Self::Main| Self::Editor { .. }+ | Self::ScreenshotEditor| Self::Settings| Self::Upgrade| Self::ModeSelect@@ -154,7 +159,9 @@ impl CapWindowId {#[cfg(target_os = "macos")]pub fn traffic_lights_position(&self) -> Option<Option<LogicalPosition<f64>>> {match self {- Self::Editor { .. } => Some(Some(LogicalPosition::new(20.0, 32.0))),+ Self::Editor { .. } | Self::ScreenshotEditor => {+ Some(Some(LogicalPosition::new(20.0, 32.0)))+ }Self::RecordingControls => Some(Some(LogicalPosition::new(-100.0, -100.0))),Self::Camera| Self::WindowCaptureOccluder { .. }@@ -170,6 +177,7 @@ impl CapWindowId {Self::Setup => (600.0, 600.0),Self::Main => (300.0, 360.0),Self::Editor { .. } => (1275.0, 800.0),+ Self::ScreenshotEditor => (800.0, 600.0),Self::Settings => (600.0, 450.0),Self::Camera => (200.0, 200.0),Self::Upgrade => (950.0, 850.0),@@ -207,6 +215,9 @@ pub enum ShowCapWindow {},Upgrade,ModeSelect,+ ScreenshotEditor {+ path: PathBuf,+ },}impl ShowCapWindow {@@ -414,6 +425,21 @@ impl ShowCapWindow {.center().build()?}+ Self::ScreenshotEditor { path } => {+ if let Some(main) = CapWindowId::Main.get(app) {+ let _ = main.close();+ };++ self.window_builder(app, "/screenshot-editor")+ .maximizable(true)+ .inner_size(1240.0, 800.0)+ .center()+ .initialization_script(format!(+ "window.__CAP__ = window.__CAP__ ?? {{}}; window.__CAP__.screenshotPath = {:?};",+ path+ ))+ .build()?+ }Self::Upgrade => {// Hide main window when upgrade window opensif let Some(main) = CapWindowId::Main.get(app) {@@ -803,6 +829,7 @@ impl ShowCapWindow {ShowCapWindow::InProgressRecording { .. } => CapWindowId::RecordingControls,ShowCapWindow::Upgrade => CapWindowId::Upgrade,ShowCapWindow::ModeSelect => CapWindowId::ModeSelect,+ ShowCapWindow::ScreenshotEditor { .. } => CapWindowId::ScreenshotEditor,}}}diff --git a/apps/desktop/src/components/Mode.tsx b/apps/desktop/src/components/Mode.tsxindex 17a2494f1..056fb08e6 100644--- a/apps/desktop/src/components/Mode.tsx+++ b/apps/desktop/src/components/Mode.tsx@@ -63,6 +63,28 @@ const Mode = () => {</Tooltip>)}+ {!isInfoHovered() && (+ <Tooltip+ placement="top"+ content="Screenshot mode"+ openDelay={0}+ closeDelay={0}+ >+ <div+ onClick={() => {+ setOptions({ mode: "screenshot" });+ }}+ class={`flex justify-center items-center transition-all duration-200 rounded-full size-7 hover:cursor-pointer ${+ rawOptions.mode === "screenshot"+ ? "ring-2 ring-offset-1 ring-offset-gray-1 bg-gray-7 hover:bg-gray-7 ring-blue-500"+ : "bg-gray-3 hover:bg-gray-7"+ }`}+ >+ <IconCapCamera class="size-3.5 invert dark:invert-0" />+ </div>+ </Tooltip>+ )}+{isInfoHovered() && (<><div@@ -90,6 +112,19 @@ const Mode = () => {><IconCapFilmCut class="size-3.5 invert dark:invert-0" /></div>++ <div+ onClick={() => {+ setOptions({ mode: "screenshot" });+ }}+ class={`flex justify-center items-center transition-all duration-200 rounded-full size-7 hover:cursor-pointer ${+ rawOptions.mode === "screenshot"+ ? "ring-2 ring-offset-1 ring-offset-gray-1 bg-gray-5 hover:bg-gray-7 ring-blue-10"+ : "bg-gray-3 hover:bg-gray-7"+ }`}+ >+ <IconCapCamera class="size-3.5 invert dark:invert-0" />+ </div></>)}</div>diff --git a/apps/desktop/src/components/ModeSelect.tsx b/apps/desktop/src/components/ModeSelect.tsxindex 5c9535901..8ca19afb1 100644--- a/apps/desktop/src/components/ModeSelect.tsx+++ b/apps/desktop/src/components/ModeSelect.tsx@@ -68,6 +68,13 @@ const ModeSelect = (props: { onClose?: () => void; standalone?: boolean }) => {"Records at the highest quality and framerate, completely locally. Captures both your screen and camera separately for editing and exporting later.",icon: IconCapFilmCut,},+ {+ mode: "screenshot" as const,+ title: "Screenshot Mode",+ description:+ "Capture high-quality screenshots of your screen or specific windows. Annotate and share instantly.",+ icon: IconCapCamera,+ },];return (diff --git a/apps/desktop/src/routes/screenshot-editor/AspectRatioSelect.tsx b/apps/desktop/src/routes/screenshot-editor/AspectRatioSelect.tsxnew file mode 100644index 000000000..e6578fb41--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/AspectRatioSelect.tsx@@ -0,0 +1,105 @@+import { Select as KSelect } from "@kobalte/core/select";+import { createSignal, Show } from "solid-js";+import Tooltip from "~/components/Tooltip";+import type { AspectRatio } from "~/utils/tauri";+import IconCapChevronDown from "~icons/cap/chevron-down";+import IconCapCircleCheck from "~icons/cap/circle-check";+import IconCapLayout from "~icons/cap/layout";+import { ASPECT_RATIOS } from "../editor/projectConfig";+import { useScreenshotEditorContext } from "./context";+import {+ EditorButton,+ MenuItem,+ MenuItemList,+ PopperContent,+ topLeftAnimateClasses,+} from "./ui";++function AspectRatioSelect() {+ const { project, setProject } = useScreenshotEditorContext();+ const [open, setOpen] = createSignal(false);+ let triggerSelect: HTMLDivElement | undefined;++ return (+ <Tooltip content="Aspect Ratio">+ <KSelect<AspectRatio | "auto">+ open={open()}+ onOpenChange={setOpen}+ ref={triggerSelect}+ value={project.aspectRatio ?? "auto"}+ onChange={(v) => {+ if (v === null) return;+ setProject("aspectRatio", v === "auto" ? null : v);+ }}+ defaultValue="auto"+ options={+ ["auto", "wide", "vertical", "square", "classic", "tall"] as const+ }+ multiple={false}+ itemComponent={(props) => {+ const item = () =>+ props.item.rawValue === "auto"+ ? null+ : ASPECT_RATIOS[props.item.rawValue];++ return (+ <MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>+ <KSelect.ItemLabel class="flex-1">+ {props.item.rawValue === "auto"+ ? "Auto"+ : ASPECT_RATIOS[props.item.rawValue].name}+ <Show when={item()}>+ {(item) => (+ <span class="text-gray-11">+ {"⋅"}+ {item().ratio[0]}:{item().ratio[1]}+ </span>+ )}+ </Show>+ </KSelect.ItemLabel>+ <KSelect.ItemIndicator class="ml-auto">+ <IconCapCircleCheck />+ </KSelect.ItemIndicator>+ </MenuItem>+ );+ }}+ placement="top-start"+ >+ <EditorButton<typeof KSelect.Trigger>+ as={KSelect.Trigger}+ class="w-28"+ leftIcon={<IconCapLayout />}+ rightIcon={+ <KSelect.Icon>+ <IconCapChevronDown />+ </KSelect.Icon>+ }+ rightIconEnd={true}+ >+ <KSelect.Value<AspectRatio | "auto">>+ {(state) => {+ const text = () => {+ const option = state.selectedOption();+ return option === "auto" ? "Auto" : ASPECT_RATIOS[option].name;+ };+ return <>{text()}</>;+ }}+ </KSelect.Value>+ </EditorButton>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={topLeftAnimateClasses}+ >+ <MenuItemList<typeof KSelect.Listbox>+ as={KSelect.Listbox}+ class="w-[12.5rem]"+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </Tooltip>+ );+}++export default AspectRatioSelect;diff --git a/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsx b/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsxnew file mode 100644index 000000000..536fbe7a0--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsx@@ -0,0 +1,979 @@+import {+ Collapsible,+ Collapsible as KCollapsible,+} from "@kobalte/core/collapsible";+import {+ RadioGroup as KRadioGroup,+ RadioGroup,+} from "@kobalte/core/radio-group";+import { Select as KSelect } from "@kobalte/core/select";+import { Tabs as KTabs } from "@kobalte/core/tabs";+import { createEventListenerMap } from "@solid-primitives/event-listener";+import { createWritableMemo } from "@solid-primitives/memo";+import { convertFileSrc } from "@tauri-apps/api/core";+import { appDataDir, resolveResource } from "@tauri-apps/api/path";+import { BaseDirectory, writeFile } from "@tauri-apps/plugin-fs";+import { type as ostype } from "@tauri-apps/plugin-os";+import { cx } from "cva";+import {+ batch,+ createMemo,+ createResource,+ createSignal,+ For,+ onMount,+ Show,+ type ValidComponent,+} from "solid-js";+import { createStore } from "solid-js/store";+import { Dynamic } from "solid-js/web";+import toast from "solid-toast";+import colorBg from "~/assets/illustrations/color.webp";+import gradientBg from "~/assets/illustrations/gradient.webp";+import imageBg from "~/assets/illustrations/image.webp";+import transparentBg from "~/assets/illustrations/transparent.webp";+import { Toggle } from "~/components/Toggle";+import type { BackgroundSource } from "~/utils/tauri";+import IconCapBgBlur from "~icons/cap/bg-blur";+import IconCapChevronDown from "~icons/cap/chevron-down";+import IconCapCircleX from "~icons/cap/circle-x";+import IconCapCorners from "~icons/cap/corners";+import IconCapEnlarge from "~icons/cap/enlarge";+import IconCapImage from "~icons/cap/image";+import IconCapPadding from "~icons/cap/padding";+import IconCapSettings from "~icons/cap/settings";+import IconCapShadow from "~icons/cap/shadow";+import {+ DEFAULT_GRADIENT_FROM,+ DEFAULT_GRADIENT_TO,+ type RGBColor,+} from "../editor/projectConfig";+import { useScreenshotEditorContext } from "./context";+import ShadowSettings from "./ShadowSettings";+import { TextInput } from "./TextInput";+import {+ Field,+ MenuItem,+ MenuItemList,+ PopperContent,+ Slider,+ topSlideAnimateClasses,+} from "./ui";++// Constants+const BACKGROUND_SOURCES = {+ wallpaper: "Wallpaper",+ image: "Image",+ color: "Color",+ gradient: "Gradient",+} satisfies Record<BackgroundSource["type"], string>;++const BACKGROUND_ICONS = {+ wallpaper: imageBg,+ image: transparentBg,+ color: colorBg,+ gradient: gradientBg,+} satisfies Record<BackgroundSource["type"], string>;++const BACKGROUND_SOURCES_LIST = [+ "wallpaper",+ "image",+ "color",+ "gradient",+] satisfies Array<BackgroundSource["type"]>;++const BACKGROUND_COLORS = [+ "#FF0000", // Red+ "#FF4500", // Orange-Red+ "#FF8C00", // Orange+ "#FFD700", // Gold+ "#FFFF00", // Yellow+ "#ADFF2F", // Green-Yellow+ "#32CD32", // Lime Green+ "#008000", // Green+ "#00CED1", // Dark Turquoise+ "#4785FF", // Dodger Blue+ "#0000FF", // Blue+ "#4B0082", // Indigo+ "#800080", // Purple+ "#A9A9A9", // Dark Gray+ "#FFFFFF", // White+ "#000000", // Black+ "#00000000", // Transparent+];++// Copied gradients+const BACKGROUND_GRADIENTS = [+ { from: [15, 52, 67], to: [52, 232, 158] },+ { from: [34, 193, 195], to: [253, 187, 45] },+ { from: [29, 253, 251], to: [195, 29, 253] },+ { from: [69, 104, 220], to: [176, 106, 179] },+ { from: [106, 130, 251], to: [252, 92, 125] },+ { from: [131, 58, 180], to: [253, 29, 29] },+ { from: [249, 212, 35], to: [255, 78, 80] },+ { from: [255, 94, 0], to: [255, 42, 104] },+ { from: [255, 0, 150], to: [0, 204, 255] },+ { from: [0, 242, 96], to: [5, 117, 230] },+ { from: [238, 205, 163], to: [239, 98, 159] },+ { from: [44, 62, 80], to: [52, 152, 219] },+ { from: [168, 239, 255], to: [238, 205, 163] },+ { from: [74, 0, 224], to: [143, 0, 255] },+ { from: [252, 74, 26], to: [247, 183, 51] },+ { from: [0, 255, 255], to: [255, 20, 147] },+ { from: [255, 127, 0], to: [255, 255, 0] },+ { from: [255, 0, 255], to: [0, 255, 0] },+] satisfies Array<{ from: RGBColor; to: RGBColor }>;++const WALLPAPER_NAMES = [+ "macOS/tahoe-dusk-min",+ "macOS/tahoe-dawn-min",+ "macOS/tahoe-day-min",+ "macOS/tahoe-night-min",+ "macOS/tahoe-dark",+ "macOS/tahoe-light",+ "macOS/sequoia-dark",+ "macOS/sequoia-light",+ "macOS/sonoma-clouds",+ "macOS/sonoma-dark",+ "macOS/sonoma-evening",+ "macOS/sonoma-fromabove",+ "macOS/sonoma-horizon",+ "macOS/sonoma-light",+ "macOS/sonoma-river",+ "macOS/ventura-dark",+ "macOS/ventura-semi-dark",+ "macOS/ventura",+ "blue/1",+ "blue/2",+ "blue/3",+ "blue/4",+ "blue/5",+ "blue/6",+ "purple/1",+ "purple/2",+ "purple/3",+ "purple/4",+ "purple/5",+ "purple/6",+ "dark/1",+ "dark/2",+ "dark/3",+ "dark/4",+ "dark/5",+ "dark/6",+ "orange/1",+ "orange/2",+ "orange/3",+ "orange/4",+ "orange/5",+ "orange/6",+ "orange/7",+ "orange/8",+ "orange/9",+] as const;++const BACKGROUND_THEMES = {+ macOS: "macOS",+ dark: "Dark",+ blue: "Blue",+ purple: "Purple",+ orange: "Orange",+};++export type CornerRoundingType = "rounded" | "squircle";+const CORNER_STYLE_OPTIONS = [+ { name: "Squircle", value: "squircle" },+ { name: "Rounded", value: "rounded" },+] satisfies Array<{ name: string; value: CornerRoundingType }>;++export function ConfigSidebar() {+ const [selectedTab, setSelectedTab] = createSignal("background");+ let scrollRef!: HTMLDivElement;++ return (+ <KTabs+ value={selectedTab()}+ onChange={setSelectedTab}+ class="flex flex-col min-h-0 shrink-0 flex-1 max-w-[26rem] overflow-hidden rounded-xl z-10 bg-gray-1 dark:bg-gray-2 border border-gray-3"+ >+ <KTabs.List class="flex overflow-hidden sticky top-0 z-[60] flex-row items-center h-16 text-lg border-b border-gray-3 shrink-0 bg-gray-1 dark:bg-gray-2">+ <For each={[{ id: "background", icon: IconCapImage }]}>+ {(item) => (+ <KTabs.Trigger+ value={item.id}+ class={cx(+ "flex relative z-10 flex-1 justify-center items-center px-4 py-2 transition-colors group disabled:opacity-50 focus:outline-none",+ "text-gray-11 ui-selected:text-gray-12",+ )}+ >+ <div+ class={cx(+ "flex justify-center relative border-transparent border z-10 items-center rounded-md size-9 transition will-change-transform",+ selectedTab() !== item.id &&+ "group-hover:border-gray-300 group-disabled:border-none",+ )}+ >+ <Dynamic component={item.icon} />+ </div>+ </KTabs.Trigger>+ )}+ </For>++ <KTabs.Indicator class="absolute top-0 left-0 w-full h-full transition-transform duration-200 ease-in-out pointer-events-none will-change-transform">+ <div class="absolute top-1/2 left-1/2 rounded-lg transform -translate-x-1/2 -translate-y-1/2 bg-gray-3 will-change-transform size-9" />+ </KTabs.Indicator>+ </KTabs.List>++ <div+ ref={scrollRef}+ class="custom-scroll overflow-x-hidden overflow-y-scroll text-[0.875rem] flex-1 min-h-0"+ >+ <BackgroundConfig scrollRef={scrollRef} />+ </div>+ </KTabs>+ );+}++function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {+ const { project, setProject, projectHistory } = useScreenshotEditorContext();++ // Background tabs+ const [backgroundTab, setBackgroundTab] =+ createSignal<keyof typeof BACKGROUND_THEMES>("macOS");++ const [wallpapers] = createResource(async () => {+ // Only load visible wallpapers initially+ const visibleWallpaperPaths = WALLPAPER_NAMES.map(async (id) => {+ try {+ const path = await resolveResource(`assets/backgrounds/${id}.jpg`);+ return { id, path };+ } catch (err) {+ return { id, path: null };+ }+ });++ // Load initial batch+ const initialPaths = await Promise.all(visibleWallpaperPaths);++ return initialPaths+ .filter((p) => p.path !== null)+ .map(({ id, path }) => ({+ id,+ url: convertFileSrc(path!),+ rawPath: path!,+ }));+ });++ const filteredWallpapers = createMemo(() => {+ const currentTab = backgroundTab();+ return wallpapers()?.filter((wp) => wp.id.startsWith(currentTab)) || [];+ });++ const [scrollX, setScrollX] = createSignal(0);+ const [reachedEndOfScroll, setReachedEndOfScroll] = createSignal(false);+ const [backgroundRef, setBackgroundRef] = createSignal<HTMLDivElement>();++ createEventListenerMap(+ () => backgroundRef() ?? [],+ {+ scroll: () => {+ const el = backgroundRef();+ if (el) {+ setScrollX(el.scrollLeft);+ const reachedEnd = el.scrollWidth - el.clientWidth - el.scrollLeft;+ setReachedEndOfScroll(reachedEnd === 0);+ }+ },+ wheel: (e: WheelEvent) => {+ const el = backgroundRef();+ if (el) {+ e.preventDefault();+ el.scrollLeft +=+ Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;+ }+ },+ },+ { passive: false },+ );++ let fileInput!: HTMLInputElement;+ const hapticsEnabled = ostype() === "macos";++ const setProjectSource = (source: any) => {+ setProject("background", "source", source);+ };++ // Debounced set project for history+ const debouncedSetProject = (wallpaperPath: string) => {+ const resumeHistory = projectHistory.pause();+ queueMicrotask(() => {+ batch(() => {+ setProject("background", "source", {+ type: "wallpaper",+ path: wallpaperPath,+ } as const);+ resumeHistory();+ });+ });+ };++ const ensurePaddingForBackground = () => {+ if (project.background.padding === 0)+ setProject("background", "padding", 10);+ };++ return (+ <KTabs.Content value="background" class="flex flex-col gap-6 p-4">+ <Field icon={<IconCapImage class="size-4" />} name="Background Image">+ <KTabs+ value={project.background.source.type}+ onChange={(v) => {+ const tab = v as BackgroundSource["type"];+ let newSource: any;+ switch (tab) {+ case "wallpaper":+ newSource = { type: "wallpaper", path: null };+ break;+ case "image":+ newSource = { type: "image", path: null };+ break;+ case "color":+ newSource = { type: "color", value: DEFAULT_GRADIENT_FROM };+ break;+ case "gradient":+ newSource = {+ type: "gradient",+ from: DEFAULT_GRADIENT_FROM,+ to: DEFAULT_GRADIENT_TO,+ };+ break;+ }++ // Try to preserve existing if type matches+ if (project.background.source.type === tab) {+ newSource = project.background.source;+ }++ setProjectSource(newSource);+ if (tab === "wallpaper" || tab === "image" || tab === "gradient") {+ ensurePaddingForBackground();+ }+ }}+ >+ <KTabs.List class="flex flex-row gap-2 items-center rounded-[0.5rem] relative">+ <For each={BACKGROUND_SOURCES_LIST}>+ {(item) => {+ return (+ <KTabs.Trigger+ class="z-10 flex-1 py-2.5 px-2 text-xs text-gray-11 ui-selected:border-gray-3 ui-selected:bg-gray-3 ui-not-selected:hover:border-gray-7 rounded-[10px] transition-colors duration-200 outline-none border ui-selected:text-gray-12 peer"+ value={item}+ >+ {BACKGROUND_SOURCES[item]}+ </KTabs.Trigger>+ );+ }}+ </For>+ </KTabs.List>++ <div class="my-5 w-full border-t border-dashed border-gray-5" />++ <KTabs.Content value="wallpaper">+ <KTabs class="overflow-hidden relative" value={backgroundTab()}>+ <KTabs.List+ ref={setBackgroundRef}+ class="flex overflow-x-auto overscroll-contain relative z-10 flex-row gap-2 items-center mb-3 text-xs hide-scroll"+ >+ <For each={Object.entries(BACKGROUND_THEMES)}>+ {([key, value]) => (+ <KTabs.Trigger+ onClick={() =>+ setBackgroundTab(key as keyof typeof BACKGROUND_THEMES)+ }+ value={key}+ class="flex relative z-10 flex-1 justify-center items-center px-4 py-2 bg-transparent rounded-lg border transition-colors duration-200 text-gray-11 ui-not-selected:hover:border-gray-7 ui-selected:bg-gray-3 ui-selected:border-gray-3 group ui-selected:text-gray-12 disabled:opacity-50 focus:outline-none"+ >+ {value}+ </KTabs.Trigger>+ )}+ </For>+ </KTabs.List>+ </KTabs>++ <KRadioGroup+ value={+ project.background.source.type === "wallpaper"+ ? (wallpapers()?.find((w) =>+ (+ project.background.source as { path?: string }+ ).path?.includes(w.id),+ )?.url ?? undefined)+ : undefined+ }+ onChange={(photoUrl) => {+ const wallpaper = wallpapers()?.find((w) => w.url === photoUrl);+ if (wallpaper) {+ debouncedSetProject(wallpaper.rawPath);+ ensurePaddingForBackground();+ }+ }}+ class="grid grid-cols-7 gap-2 h-auto"+ >+ <For each={filteredWallpapers().slice(0, 21)}>+ {(photo) => (+ <KRadioGroup.Item+ value={photo.url!}+ class="relative aspect-square group"+ >+ <KRadioGroup.ItemInput class="peer" />+ <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-lg transition cursor-pointer ui-not-checked:ring-offset-1 ui-not-checked:ring-offset-gray-200 ui-not-checked:hover:ring-1 ui-not-checked:hover:ring-gray-400 ui-checked:ring-2 ui-checked:ring-gray-500 ui-checked:ring-offset-2 ui-checked:ring-offset-gray-200">+ <img+ src={photo.url!}+ loading="eager"+ class="object-cover w-full h-full"+ alt="Wallpaper option"+ />+ </KRadioGroup.ItemControl>+ </KRadioGroup.Item>+ )}+ </For>+ </KRadioGroup>+ </KTabs.Content>++ <KTabs.Content value="image">+ <Show+ when={+ project.background.source.type === "image" &&+ project.background.source.path+ }+ fallback={+ <button+ type="button"+ onClick={() => fileInput.click()}+ class="p-6 bg-gray-2 text-[13px] w-full rounded-[0.5rem] border border-gray-5 border-dashed flex flex-col items-center justify-center gap-[0.5rem] hover:bg-gray-3 transition-colors duration-100"+ >+ <IconCapImage class="text-gray-11 size-6" />+ <span class="text-gray-12">+ Click to select or drag and drop image+ </span>+ </button>+ }+ >+ {(source) => (+ <div class="overflow-hidden relative w-full h-48 rounded-md border border-gray-3 group">+ <img+ src={convertFileSrc(source())}+ class="object-cover w-full h-full"+ alt="Selected background"+ />+ <div class="absolute top-2 right-2">+ <button+ type="button"+ onClick={() =>+ setProjectSource({+ type: "image",+ path: null,+ })+ }+ class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70"+ >+ <IconCapCircleX class="w-4 h-4" />+ </button>+ </div>+ </div>+ )}+ </Show>+ <input+ type="file"+ ref={fileInput}+ class="hidden"+ accept="image/apng, image/avif, image/jpeg, image/png, image/webp"+ onChange={async (e) => {+ const file = e.currentTarget.files?.[0];+ if (!file) return;+ const fileName = `bg-${Date.now()}-${file.name}`;+ const arrayBuffer = await file.arrayBuffer();+ const uint8Array = new Uint8Array(arrayBuffer);++ const fullPath = `${await appDataDir()}/${fileName}`;++ await writeFile(fileName, uint8Array, {+ baseDir: BaseDirectory.AppData,+ });++ setProjectSource({+ type: "image",+ path: fullPath,+ });+ ensurePaddingForBackground();+ }}+ />+ </KTabs.Content>++ <KTabs.Content value="color">+ <div class="flex flex-col flex-wrap gap-3">+ <div class="flex flex-row items-center w-full h-10">+ <RgbInput+ value={+ project.background.source.type === "color"+ ? project.background.source.value+ : [0, 0, 0]+ }+ onChange={(v) =>+ setProjectSource({ type: "color", value: v })+ }+ />+ </div>+ <div class="flex flex-wrap gap-2">+ <For each={BACKGROUND_COLORS}>+ {(color) => (+ <label class="relative">+ <input+ type="radio"+ class="sr-only peer"+ name="colorPicker"+ onChange={(e) => {+ if (e.target.checked) {+ const rgb = hexToRgb(color);+ if (rgb)+ setProjectSource({+ type: "color",+ value: [rgb[0], rgb[1], rgb[2]],+ alpha: rgb[3],+ });+ }+ }}+ />+ <div+ class="rounded-lg transition-all duration-200 cursor-pointer size-8 peer-checked:hover:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200"+ style={{ background: color }}+ />+ </label>+ )}+ </For>+ </div>+ </div>+ </KTabs.Content>++ <KTabs.Content value="gradient">+ <Show+ when={+ project.background.source.type === "gradient" &&+ project.background.source+ }+ >+ {(source) => {+ const angle = () => source().angle ?? 90;+ return (+ <div class="flex flex-col gap-3">+ <div class="flex gap-5 h-10">+ <RgbInput+ value={source().from}+ onChange={(from) =>+ setProjectSource({ ...source(), from })+ }+ />+ <RgbInput+ value={source().to}+ onChange={(to) => setProjectSource({ ...source(), to })}+ />+ </div>+ <div class="flex flex-wrap gap-2">+ <For each={BACKGROUND_GRADIENTS}>+ {(gradient) => (+ <label class="relative">+ <input+ type="radio"+ class="sr-only peer"+ name="colorPicker"+ onChange={(e) => {+ if (e.target.checked) {+ setProjectSource({+ type: "gradient",+ from: gradient.from,+ to: gradient.to,+ });+ ensurePaddingForBackground();+ }+ }}+ />+ <div+ class="rounded-lg transition-all duration-200 cursor-pointer size-8 peer-checked:hover:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200"+ style={{+ background: `linear-gradient(${angle()}deg, rgb(${gradient.from.join(+ ",",+ )}), rgb(${gradient.to.join(",")}))`,+ }}+ />+ </label>+ )}+ </For>+ </div>+ </div>+ );+ }}+ </Show>+ </KTabs.Content>+ </KTabs>+ </Field>++ <Field name="Background Blur" icon={<IconCapBgBlur />}>+ <Slider+ value={[project.background.blur]}+ onChange={(v) => setProject("background", "blur", v[0])}+ minValue={0}+ maxValue={100}+ step={0.1}+ formatTooltip="%"+ />+ </Field>++ <div class="w-full border-t border-gray-300 border-dashed" />++ <Field name="Padding" icon={<IconCapPadding class="size-4" />}>+ <Slider+ value={[project.background.padding]}+ onChange={(v) => setProject("background", "padding", v[0])}+ minValue={0}+ maxValue={40}+ step={0.1}+ formatTooltip="%"+ />+ </Field>++ <Field name="Rounded Corners" icon={<IconCapCorners class="size-4" />}>+ <div class="flex flex-col gap-3">+ <Slider+ value={[project.background.rounding]}+ onChange={(v) => setProject("background", "rounding", v[0])}+ minValue={0}+ maxValue={100}+ step={0.1}+ formatTooltip="%"+ />+ <CornerStyleSelect+ label="Corner Style"+ value={project.background.roundingType || "squircle"}+ onChange={(v) => setProject("background", "roundingType", v)}+ />+ </div>+ </Field>++ <Field name="Shadow" icon={<IconCapShadow class="size-4" />}>+ <Slider+ value={[project.background.shadow!]}+ onChange={(v) => {+ batch(() => {+ setProject("background", "shadow", v[0]);+ if (v[0] > 0 && !project.background.advancedShadow) {+ setProject("background", "advancedShadow", {+ size: 50,+ opacity: 18,+ blur: 50,+ });+ }+ });+ }}+ minValue={0}+ maxValue={100}+ step={0.1}+ formatTooltip="%"+ />++ <ShadowSettings+ scrollRef={props.scrollRef}+ size={{+ value: [project.background.advancedShadow?.size ?? 50],+ onChange: (v) => {+ setProject("background", "advancedShadow", {+ ...(project.background.advancedShadow ?? {+ size: 50,+ opacity: 18,+ blur: 50,+ }),+ size: v[0],+ });+ },+ }}+ opacity={{+ value: [project.background.advancedShadow?.opacity ?? 18],+ onChange: (v) => {+ setProject("background", "advancedShadow", {+ ...(project.background.advancedShadow ?? {+ size: 50,+ opacity: 18,+ blur: 50,+ }),+ opacity: v[0],+ });+ },+ }}+ blur={{+ value: [project.background.advancedShadow?.blur ?? 50],+ onChange: (v) => {+ setProject("background", "advancedShadow", {+ ...(project.background.advancedShadow ?? {+ size: 50,+ opacity: 18,+ blur: 50,+ }),+ blur: v[0],+ });+ },+ }}+ />+ </Field>++ <Field+ name="Border"+ icon={<IconCapSettings class="size-4" />}+ value={+ <Toggle+ checked={project.background.border?.enabled ?? false}+ onChange={(enabled) => {+ const prev = project.background.border ?? {+ enabled: false,+ width: 5.0,+ color: [0, 0, 0],+ opacity: 50.0,+ };++ if (props.scrollRef && enabled) {+ setTimeout(+ () =>+ props.scrollRef.scrollTo({+ top: props.scrollRef.scrollHeight,+ behavior: "smooth",+ }),+ 100,+ );+ }++ setProject("background", "border", {+ ...prev,+ enabled,+ });+ }}+ />+ }+ />+ <KCollapsible open={project.background.border?.enabled ?? false}>+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up ui-expanded:animate-collapsible-down ui-expanded:opacity-100">+ <div class="flex flex-col gap-6 pb-6">+ <Field name="Border Width" icon={<IconCapEnlarge class="size-4" />}>+ <Slider+ value={[project.background.border?.width ?? 5.0]}+ onChange={(v) =>+ setProject("background", "border", {+ ...(project.background.border ?? {+ enabled: true,+ width: 5.0,+ color: [0, 0, 0],+ opacity: 50.0,+ }),+ width: v[0],+ })+ }+ minValue={1}+ maxValue={20}+ step={0.1}+ formatTooltip="px"+ />+ </Field>+ <Field name="Border Color" icon={<IconCapImage class="size-4" />}>+ <RgbInput+ value={project.background.border?.color ?? [0, 0, 0]}+ onChange={(color) =>+ setProject("background", "border", {+ ...(project.background.border ?? {+ enabled: true,+ width: 5.0,+ color: [0, 0, 0],+ opacity: 50.0,+ }),+ color,+ })+ }+ />+ </Field>+ <Field+ name="Border Opacity"+ icon={<IconCapShadow class="size-4" />}+ >+ <Slider+ value={[project.background.border?.opacity ?? 50.0]}+ onChange={(v) =>+ setProject("background", "border", {+ ...(project.background.border ?? {+ enabled: true,+ width: 5.0,+ color: [0, 0, 0],+ opacity: 50.0,+ }),+ opacity: v[0],+ })+ }+ minValue={0}+ maxValue={100}+ step={0.1}+ formatTooltip="%"+ />+ </Field>+ </div>+ </KCollapsible.Content>+ </KCollapsible>+ </KTabs.Content>+ );+}++// Utils++function CornerStyleSelect(props: {+ label?: string;+ value: CornerRoundingType;+ onChange: (value: CornerRoundingType) => void;+}) {+ return (+ <div class="flex flex-col gap-1.5">+ <Show when={props.label}>+ {(label) => (+ <span class="text-[0.65rem] uppercase tracking-wide text-gray-11">+ {label()}+ </span>+ )}+ </Show>+ <KSelect<{ name: string; value: CornerRoundingType }>+ options={CORNER_STYLE_OPTIONS}+ optionValue="value"+ optionTextValue="name"+ value={CORNER_STYLE_OPTIONS.find(+ (option) => option.value === props.value,+ )}+ onChange={(option) => option && props.onChange(option.value)}+ disallowEmptySelection+ itemComponent={(itemProps) => (+ <MenuItem<typeof KSelect.Item>+ as={KSelect.Item}+ item={itemProps.item}+ >+ <KSelect.ItemLabel class="flex-1">+ {itemProps.item.rawValue.name}+ </KSelect.ItemLabel>+ </MenuItem>+ )}+ >+ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">+ <KSelect.Value<{+ name: string;+ value: CornerRoundingType;+ }> class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal">+ {(state) => <span>{state.selectedOption().name}</span>}+ </KSelect.Value>+ <KSelect.Icon<ValidComponent>+ as={(iconProps) => (+ <IconCapChevronDown+ {...iconProps}+ class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]"+ />+ )}+ />+ </KSelect.Trigger>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={cx(topSlideAnimateClasses, "z-50")}+ >+ <MenuItemList<typeof KSelect.Listbox>+ class="overflow-y-auto max-h-32"+ as={KSelect.Listbox}+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </div>+ );+}++function RgbInput(props: {+ value: [number, number, number];+ onChange: (value: [number, number, number]) => void;+}) {+ const [text, setText] = createWritableMemo(() => rgbToHex(props.value));+ let prevHex = rgbToHex(props.value);+ let colorInput!: HTMLInputElement;++ return (+ <div class="flex flex-row items-center gap-[0.75rem] relative">+ <button+ type="button"+ class="size-[2rem] rounded-[0.5rem]"+ style={{+ "background-color": rgbToHex(props.value),+ }}+ onClick={() => colorInput.click()}+ />+ <input+ ref={colorInput}+ type="color"+ class="absolute left-0 bottom-0 w-[3rem] opacity-0"+ value={rgbToHex(props.value)}+ onChange={(e) => {+ const value = hexToRgb(e.target.value);+ if (!value) return;+ const [r, g, b] = value;+ props.onChange([r, g, b]);+ }}+ />+ <TextInput+ class="w-[4.60rem] p-[0.375rem] text-gray-12 text-[13px] border rounded-[0.5rem] bg-gray-1 outline-none focus:ring-1 transition-shadows duration-200 focus:ring-gray-500 focus:ring-offset-1 focus:ring-offset-gray-200"+ value={text()}+ onFocus={() => {+ prevHex = rgbToHex(props.value);+ }}+ onInput={(e) => {+ setText(e.currentTarget.value);+ const value = hexToRgb(e.target.value);+ if (!value) return;+ const [r, g, b] = value;+ props.onChange([r, g, b]);+ }}+ onBlur={(e) => {+ const value = hexToRgb(e.target.value);+ if (value) {+ const [r, g, b] = value;+ props.onChange([r, g, b]);+ } else {+ setText(prevHex);+ const fallbackValue = hexToRgb(text());+ if (!fallbackValue) return;+ const [r, g, b] = fallbackValue;+ props.onChange([r, g, b]);+ }+ }}+ />+ </div>+ );+}++function rgbToHex(rgb: [number, number, number]) {+ return `#${rgb+ .map((c) => c.toString(16).padStart(2, "0"))+ .join("")+ .toUpperCase()}`;+}++function hexToRgb(hex: string): [number, number, number, number] | null {+ const match = hex.match(+ /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,+ );+ if (!match) return null;+ const [, r, g, b, a] = match;+ const rgb = [+ Number.parseInt(r, 16),+ Number.parseInt(g, 16),+ Number.parseInt(b, 16),+ ] as const;+ if (a) {+ return [...rgb, Number.parseInt(a, 16)];+ }+ return [...rgb, 255];+}diff --git a/apps/desktop/src/routes/screenshot-editor/Editor.tsx b/apps/desktop/src/routes/screenshot-editor/Editor.tsxnew file mode 100644index 000000000..a39cbd5cd--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/Editor.tsx@@ -0,0 +1,292 @@+import { Button } from "@cap/ui-solid";+import { NumberField } from "@kobalte/core/number-field";+import { makePersisted } from "@solid-primitives/storage";+import { convertFileSrc } from "@tauri-apps/api/core";+import { LogicalPosition } from "@tauri-apps/api/dpi";+import { Menu } from "@tauri-apps/api/menu";+import { createSignal, Match, Show, Switch } from "solid-js";+import { Transition } from "solid-transition-group";+import {+ CROP_ZERO,+ type CropBounds,+ Cropper,+ type CropperRef,+ createCropOptionsMenuItems,+ type Ratio,+} from "~/components/Cropper";+import { composeEventHandlers } from "~/utils/composeEventHandlers";+import IconCapCircleX from "~icons/cap/circle-x";+import IconLucideMaximize from "~icons/lucide/maximize";+import IconLucideRatio from "~icons/lucide/ratio";+import { ConfigSidebar } from "./ConfigSidebar";+import { useScreenshotEditorContext } from "./context";+import { ExportDialog } from "./ExportDialog";+import { Header } from "./Header";+import { Preview } from "./Preview";+import { Dialog, DialogContent, EditorButton, Input, Subfield } from "./ui";++export function Editor() {+ return (+ <>+ <Header />+ <div+ class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-4 w-full min-h-0 leading-5 animate-in fade-in"+ data-tauri-drag-region+ >+ <div class="flex overflow-hidden flex-col flex-1 min-h-0">+ <div class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2 pb-0.5">+ <Preview />+ <ConfigSidebar />+ </div>+ </div>+ <Dialogs />+ </div>+ </>+ );+}++function Dialogs() {+ const { dialog, setDialog, project, setProject, path } =+ useScreenshotEditorContext();++ return (+ <Dialog.Root+ size={(() => {+ const d = dialog();+ if ("type" in d && d.type === "crop") return "lg";+ return "sm";+ })()}+ contentClass={(() => {+ const d = dialog();+ // if ("type" in d && d.type === "export") return "max-w-[740px]";+ return "";+ })()}+ open={dialog().open}+ onOpenChange={(o) => {+ if (!o) setDialog((d) => ({ ...d, open: false }));+ }}+ >+ <Show+ when={(() => {+ const d = dialog();+ if ("type" in d) return d;+ })()}+ >+ {(dialog) => (+ <Switch>+ <Match when={dialog().type === "export"}>+ <ExportDialog />+ </Match>+ <Match+ when={(() => {+ const d = dialog();+ if (d.type === "crop") return d;+ })()}+ >+ {(dialog) => {+ let cropperRef: CropperRef | undefined;+ const [crop, setCrop] = createSignal(CROP_ZERO);+ const [aspect, setAspect] = createSignal<Ratio | null>(null);++ const initialBounds = {+ x: dialog().position.x,+ y: dialog().position.y,+ width: dialog().size.x,+ height: dialog().size.y,+ };++ const [snapToRatio, setSnapToRatioEnabled] = makePersisted(+ createSignal(true),+ { name: "editorCropSnapToRatio" },+ );++ async function showCropOptionsMenu(+ e: UIEvent,+ positionAtCursor = false,+ ) {+ e.preventDefault();+ const items = createCropOptionsMenuItems({+ aspect: aspect(),+ snapToRatioEnabled: snapToRatio(),+ onAspectSet: setAspect,+ onSnapToRatioSet: setSnapToRatioEnabled,+ });+ const menu = await Menu.new({ items });+ let pos: LogicalPosition | undefined;+ if (!positionAtCursor) {+ const rect = (+ e.target as HTMLDivElement+ ).getBoundingClientRect();+ pos = new LogicalPosition(rect.x, rect.y + 40);+ }+ await menu.popup(pos);+ await menu.close();+ }++ function BoundInput(props: {+ field: keyof CropBounds;+ min?: number;+ max?: number;+ }) {+ return (+ <NumberField+ value={crop()[props.field]}+ minValue={props.min}+ maxValue={props.max}+ onRawValueChange={(v) => {+ cropperRef?.setCropProperty(props.field, v);+ }}+ changeOnWheel={true}+ format={false}+ >+ <NumberField.Input+ class="rounded-[0.5rem] bg-gray-2 hover:ring-1 py-[18px] hover:ring-gray-5 h-[2rem] font-normal placeholder:text-black-transparent-40 text-xs caret-gray-500 transition-shadow duration-200 focus:ring-offset-1 focus:bg-gray-3 focus:ring-offset-gray-100 focus:ring-1 focus:ring-gray-10 px-[0.5rem] w-full text-[0.875rem] outline-none text-gray-12"+ onKeyDown={composeEventHandlers<HTMLInputElement>([+ (e) => e.stopPropagation(),+ ])}+ />+ </NumberField>+ );+ }++ return (+ <>+ <Dialog.Header>+ <div class="flex flex-row space-x-[2rem]">+ <div class="flex flex-row items-center space-x-[0.75rem] text-gray-11">+ <span>Size</span>+ <div class="w-[3.25rem]">+ <BoundInput field="width" max={dialog().size.x} />+ </div>+ <span>×</span>+ <div class="w-[3.25rem]">+ <BoundInput field="height" max={dialog().size.y} />+ </div>+ </div>+ <div class="flex flex-row items-center space-x-[0.75rem] text-gray-11">+ <span>Position</span>+ <div class="w-[3.25rem]">+ <BoundInput field="x" />+ </div>+ <span>×</span>+ <div class="w-[3.25rem]">+ <BoundInput field="y" />+ </div>+ </div>+ </div>+ <div class="flex flex-row gap-3 justify-end items-center w-full">+ <div class="flex flex-row items-center space-x-[0.5rem] text-gray-11"></div>++ <Button+ variant="white"+ size="xs"+ class="flex items-center justify-center text-center rounded-full h-[2rem] w-[2rem] border focus:border-blue-9"+ onMouseDown={showCropOptionsMenu}+ onClick={showCropOptionsMenu}+ >+ <div class="relative pointer-events-none size-4">+ <Show when={!aspect()}>+ <IconLucideRatio class="group-active:scale-90 transition-transform size-4 pointer-events-none *:pointer-events-none" />+ </Show>+ <Transition+ enterClass="scale-50 opacity-0 blur-md"+ enterActiveClass="duration-200 [transition-timing-function:cubic-bezier(0.215,0.61,0.355,1)]"+ enterToClass="scale-100 opacity-100 blur-0"+ exitClass="opacity-0"+ exitActiveClass="duration-0"+ exitToClass="opacity-0"+ >+ <Show when={aspect()} keyed>+ {(ratio) => (+ <span class="flex absolute inset-0 justify-center items-center text-xs font-medium tracking-tight leading-none pointer-events-none text text-blue-10">+ {ratio[0]}:{ratio[1]}+ </span>+ )}+ </Show>+ </Transition>+ </div>+ </Button>++ <EditorButton+ leftIcon={<IconLucideMaximize />}+ onClick={() => cropperRef?.fill()}+ disabled={+ crop().width === dialog().size.x &&+ crop().height === dialog().size.y+ }+ >+ Full+ </EditorButton>+ <EditorButton+ leftIcon={<IconCapCircleX />}+ onClick={() => {+ cropperRef?.reset();+ setAspect(null);+ }}+ disabled={+ crop().x === dialog().position.x &&+ crop().y === dialog().position.y &&+ crop().width === dialog().size.x &&+ crop().height === dialog().size.y+ }+ >+ Reset+ </EditorButton>+ </div>+ </Dialog.Header>+ <Dialog.Content>+ <div class="flex flex-row justify-center">+ <div class="rounded divide-black-transparent-10">+ <Cropper+ ref={cropperRef}+ onCropChange={setCrop}+ aspectRatio={aspect() ?? undefined}+ targetSize={{+ x: dialog().size.x,+ y: dialog().size.y,+ }}+ initialCrop={initialBounds}+ snapToRatioEnabled={snapToRatio()}+ useBackdropFilter={true}+ allowLightMode={true}+ onContextMenu={(e) => showCropOptionsMenu(e, true)}+ >+ <img+ class="shadow pointer-events-none max-h-[70vh]"+ alt="screenshot"+ src={convertFileSrc(path)}+ />+ </Cropper>+ </div>+ </div>+ </Dialog.Content>+ <Dialog.Footer>+ <Button+ onClick={() => {+ const bounds = crop();+ setProject("background", "crop", {+ position: {+ x: bounds.x,+ y: bounds.y,+ },+ size: {+ x: bounds.width,+ y: bounds.height,+ },+ });+ setDialog((d) => ({ ...d, open: false }));+ }}+ >+ Save+ </Button>+ </Dialog.Footer>+ </>+ );+ }}+ </Match>+ </Switch>+ )}+ </Show>+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/ExportDialog.tsx b/apps/desktop/src/routes/screenshot-editor/ExportDialog.tsxnew file mode 100644index 000000000..bdf62dab7--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/ExportDialog.tsx@@ -0,0 +1,126 @@+import { Button } from "@cap/ui-solid";+import { convertFileSrc } from "@tauri-apps/api/core";+import { save } from "@tauri-apps/plugin-dialog";+import { createSignal, Show } from "solid-js";+import toast from "solid-toast";+import { commands } from "~/utils/tauri";+import IconCapCircleX from "~icons/cap/circle-x";+import IconCapCopy from "~icons/cap/copy";+import IconCapFile from "~icons/cap/file";+import { useScreenshotEditorContext } from "./context";+import { Dialog, DialogContent } from "./ui";++export function ExportDialog() {+ const { dialog, setDialog, path, project } = useScreenshotEditorContext();+ const [exporting, setExporting] = createSignal(false);++ const exportImage = async (destination: "file" | "clipboard") => {+ setExporting(true);+ try {+ // 1. Load the image+ const img = new Image();+ img.src = convertFileSrc(path);+ await new Promise((resolve, reject) => {+ img.onload = resolve;+ img.onerror = reject;+ });++ // 2. Create canvas with appropriate dimensions+ // We need to account for padding, crop, etc.+ // For now, let's assume simple export of the original image + background settings+ // This is a simplified implementation. A robust one would replicate the CSS effects on canvas.++ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("Could not get canvas context");++ // Calculate dimensions based on project settings+ // This logic needs to match Preview.tsx+ const padding = project.background.padding * 2; // Scale factor?+ // In Preview.tsx: padding: `${padding * 2}px`+ // But here we are working with actual pixels.+ // Let's assume padding is in pixels relative to the image size?+ // Or we need a consistent scale.+ // For simplicity, let's just use the image size + padding.++ // TODO: Implement proper rendering logic matching CSS+ // For now, we'll just export the original image to demonstrate the flow+ canvas.width = img.width;+ canvas.height = img.height;+ ctx.drawImage(img, 0, 0);++ // 3. Export+ const blob = await new Promise<Blob | null>((resolve) =>+ canvas.toBlob(resolve, "image/png"),+ );+ if (!blob) throw new Error("Failed to create blob");++ const buffer = await blob.arrayBuffer();+ const uint8Array = new Uint8Array(buffer);++ if (destination === "file") {+ const savePath = await save({+ filters: [{ name: "PNG Image", extensions: ["png"] }],+ defaultPath: "screenshot.png",+ });+ if (savePath) {+ await commands.writeFile(savePath, Array.from(uint8Array));+ toast.success("Screenshot saved!");+ }+ } else {+ // Copy to clipboard+ // We need a command for this as web API might be limited+ // commands.copyImageToClipboard(uint8Array)?+ // For now, let's use the existing command if it supports data+ // commands.copyScreenshotToClipboard(path) copies the file at path.+ // If we want to copy the *edited* image, we need to save it to a temp file first or send bytes.++ // Fallback to copying the original file for now+ await commands.copyScreenshotToClipboard(path);+ toast.success(+ "Original screenshot copied to clipboard (editing export WIP)",+ );+ }++ setDialog({ ...dialog(), open: false });+ } catch (err) {+ console.error(err);+ toast.error("Failed to export");+ } finally {+ setExporting(false);+ }+ };++ return (+ <DialogContent+ title="Export Screenshot"+ confirm={null} // Custom footer+ >+ <div class="flex flex-col gap-4">+ <p class="text-gray-11 text-sm">+ Choose where to export your screenshot.+ </p>+ <div class="flex gap-3">+ <Button+ variant="gray"+ class="flex-1 flex gap-2 items-center justify-center h-12"+ onClick={() => exportImage("file")}+ disabled={exporting()}+ >+ <IconCapFile class="size-5" />+ Save to File+ </Button>+ <Button+ variant="gray"+ class="flex-1 flex gap-2 items-center justify-center h-12"+ onClick={() => exportImage("clipboard")}+ disabled={exporting()}+ >+ <IconCapCopy class="size-5" />+ Copy to Clipboard+ </Button>+ </div>+ </div>+ </DialogContent>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/Header.tsx b/apps/desktop/src/routes/screenshot-editor/Header.tsxnew file mode 100644index 000000000..62acc9e3c--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/Header.tsx@@ -0,0 +1,174 @@+import { Button } from "@cap/ui-solid";+import { getCurrentWindow } from "@tauri-apps/api/window";+import { ask } from "@tauri-apps/plugin-dialog";+import { remove } from "@tauri-apps/plugin-fs";+import { revealItemInDir } from "@tauri-apps/plugin-opener";+import { type as ostype } from "@tauri-apps/plugin-os";+import { cx } from "cva";+import { createEffect, createSignal, Show } from "solid-js";+import Tooltip from "~/components/Tooltip";+import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";+import { commands } from "~/utils/tauri";+import IconCapTrash from "~icons/cap/trash";+import IconLucideCopy from "~icons/lucide/copy";+import IconLucideFolder from "~icons/lucide/folder";+import { useScreenshotEditorContext } from "./context";+import PresetsDropdown from "./PresetsDropdown";+import { EditorButton } from "./ui";++export function Header() {+ const { path, setDialog } = useScreenshotEditorContext();++ // Extract filename from path+ const filename = () => {+ if (!path) return "Screenshot";+ const parts = path.split(/[/\\]/);+ return parts[parts.length - 1] || "Screenshot";+ };++ return (+ <div+ data-tauri-drag-region+ class="flex relative flex-row items-center w-full h-14"+ >+ <div+ data-tauri-drag-region+ class={cx("flex flex-row flex-1 gap-2 items-center px-4 h-full")}+ >+ {ostype() === "macos" && <div class="h-full w-[4rem]" />}++ <EditorButton+ onClick={async () => {+ if (await ask("Are you sure you want to delete this screenshot?")) {+ await remove(path);+ await getCurrentWindow().close();+ }+ }}+ tooltipText="Delete screenshot"+ leftIcon={<IconCapTrash class="w-5" />}+ />+ <EditorButton+ onClick={() => {+ revealItemInDir(path);+ }}+ tooltipText="Open containing folder"+ leftIcon={<IconLucideFolder class="w-5" />}+ />++ <div class="flex flex-row items-center">+ <NameEditor name={filename()} />+ </div>+ </div>++ <div+ data-tauri-drag-region+ class="flex flex-col justify-center px-4 border-x border-black-transparent-10"+ >+ <PresetsDropdown />+ </div>++ <div+ data-tauri-drag-region+ class={cx(+ "flex-1 h-full flex flex-row items-center gap-2 pl-2 justify-end px-4",+ ostype() !== "windows" && "pr-2",+ )}+ >+ <EditorButton+ onClick={() => {+ commands.copyScreenshotToClipboard(path);+ }}+ tooltipText="Copy to Clipboard"+ leftIcon={<IconLucideCopy class="w-5" />}+ />++ <Button+ variant="dark"+ class="flex gap-1.5 justify-center h-[40px] w-full max-w-[100px]"+ onClick={() => {+ setDialog({ type: "export", open: true });+ }}+ >+ <UploadIcon class="text-gray-1 size-4" />+ Export+ </Button>+ {ostype() === "windows" && <CaptionControlsWindows11 />}+ </div>+ </div>+ );+}++const UploadIcon = (props: any) => {+ return (+ <svg+ width={20}+ height={20}+ viewBox="0 0 20 20"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <path+ d="M16.6667 10.625V14.1667C16.6667 15.5474 15.5474 16.6667 14.1667 16.6667H5.83333C4.45262 16.6667 3.33333 15.5474 3.33333 14.1667V10.625"+ stroke="currentColor"+ stroke-width={1.66667}+ stroke-linecap="round"+ stroke-linejoin="round"+ />+ <path+ d="M9.99999 3.33333V12.7083M9.99999 3.33333L13.75 7.08333M9.99999 3.33333L6.24999 7.08333"+ stroke="currentColor"+ stroke-width={1.66667}+ stroke-linecap="round"+ stroke-linejoin="round"+ />+ </svg>+ );+};++function NameEditor(props: { name: string }) {+ let prettyNameRef: HTMLInputElement | undefined;+ let prettyNameMeasureRef: HTMLSpanElement | undefined;+ const [truncated, setTruncated] = createSignal(false);+ const [prettyName, setPrettyName] = createSignal(props.name);++ createEffect(() => {+ if (!prettyNameRef || !prettyNameMeasureRef) return;+ prettyNameMeasureRef.textContent = prettyName();+ const inputWidth = prettyNameRef.offsetWidth;+ const textWidth = prettyNameMeasureRef.offsetWidth;+ setTruncated(inputWidth < textWidth);+ });++ return (+ <Tooltip disabled={!truncated()} content={props.name}>+ <div class="flex relative flex-row items-center text-sm font-normal font-inherit tracking-inherit text-gray-12">+ <input+ ref={prettyNameRef}+ class={cx(+ "absolute inset-0 px-px m-0 opacity-0 overflow-hidden focus:opacity-100 bg-transparent border-b border-transparent focus:border-gray-7 focus:outline-none peer whitespace-pre",+ truncated() && "truncate",+ (prettyName().length < 1 || prettyName().length > 100) &&+ "focus:border-red-500",+ )}+ value={prettyName()}+ readOnly // Read only for now as we don't have rename logic+ onInput={(e) => setPrettyName(e.currentTarget.value)}+ onBlur={async () => {+ setPrettyName(props.name);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === "Escape") {+ prettyNameRef?.blur();+ }+ }}+ />+ {/* Hidden span for measuring text width */}+ <span+ ref={prettyNameMeasureRef}+ class="pointer-events-none max-w-[200px] px-px m-0 peer-focus:opacity-0 border-b border-transparent truncate whitespace-pre"+ />+ </div>+ </Tooltip>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/PresetsDropdown.tsx b/apps/desktop/src/routes/screenshot-editor/PresetsDropdown.tsxnew file mode 100644index 000000000..655dca537--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/PresetsDropdown.tsx@@ -0,0 +1,55 @@+import { DropdownMenu as KDropdownMenu } from "@kobalte/core/dropdown-menu";+import { cx } from "cva";+import { Suspense } from "solid-js";+import IconCapChevronDown from "~icons/cap/chevron-down";+import IconCapCirclePlus from "~icons/cap/circle-plus";+import IconCapPresets from "~icons/cap/presets";+import {+ DropdownItem,+ EditorButton,+ MenuItemList,+ PopperContent,+ topCenterAnimateClasses,+} from "./ui";++export function PresetsDropdown() {+ return (+ <KDropdownMenu gutter={8} placement="bottom">+ <EditorButton<typeof KDropdownMenu.Trigger>+ as={KDropdownMenu.Trigger}+ leftIcon={<IconCapPresets />}+ rightIcon={<IconCapChevronDown />}+ >+ Presets+ </EditorButton>+ <KDropdownMenu.Portal>+ <Suspense>+ <PopperContent<typeof KDropdownMenu.Content>+ as={KDropdownMenu.Content}+ class={cx("w-72 max-h-56", topCenterAnimateClasses)}+ >+ <MenuItemList<typeof KDropdownMenu.Group>+ as={KDropdownMenu.Group}+ class="overflow-y-auto flex-1 scrollbar-none"+ >+ <div class="py-1 w-full text-sm text-center text-gray-11">+ No Presets+ </div>+ </MenuItemList>+ <MenuItemList<typeof KDropdownMenu.Group>+ as={KDropdownMenu.Group}+ class="border-t shrink-0"+ >+ <DropdownItem disabled>+ <span>Create new preset</span>+ <IconCapCirclePlus class="ml-auto" />+ </DropdownItem>+ </MenuItemList>+ </PopperContent>+ </Suspense>+ </KDropdownMenu.Portal>+ </KDropdownMenu>+ );+}++export default PresetsDropdown;diff --git a/apps/desktop/src/routes/screenshot-editor/Preview.tsx b/apps/desktop/src/routes/screenshot-editor/Preview.tsxnew file mode 100644index 000000000..85d0b8521--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/Preview.tsx@@ -0,0 +1,183 @@+import { convertFileSrc } from "@tauri-apps/api/core";+import { cx } from "cva";+import { createMemo, createSignal, Show } from "solid-js";+import Tooltip from "~/components/Tooltip";+import IconCapCrop from "~icons/cap/crop";+import IconCapZoomIn from "~icons/cap/zoom-in";+import IconCapZoomOut from "~icons/cap/zoom-out";+import { EditorButton, Slider } from "../editor/ui";+import AspectRatioSelect from "./AspectRatioSelect";+import { useScreenshotEditorContext } from "./context";++export function Preview() {+ const { path, project, setDialog } = useScreenshotEditorContext();+ const [zoom, setZoom] = createSignal(1);++ // Background Style Helper+ const backgroundStyle = createMemo(() => {+ const source = project.background.source;+ const blur = project.background.blur;++ const style: any = {};++ if (source.type === "color") {+ const [r, g, b] = source.value;+ const a = source.alpha ?? 255;+ style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a / 255})`;+ } else if (source.type === "gradient") {+ const { from, to, angle = 90 } = source;+ style.background = `linear-gradient(${angle}deg, rgb(${from.join(",")}), rgb(${to.join(",")}))`;+ }++ if (blur > 0) {+ style.filter = `blur(${blur}px)`;+ }++ return style;+ });++ // Image Style Helper+ const imageStyle = createMemo(() => {+ const { rounding, roundingType, shadow, advancedShadow, border } =+ project.background;++ const style: any = {};++ // Rounding+ if (rounding > 0) {+ style.borderRadius = `${rounding}px`;+ }++ // Shadow+ if (advancedShadow) {+ const { size, opacity, blur } = advancedShadow;+ style.boxShadow = `0 ${size / 2}px ${blur}px rgba(0,0,0, ${opacity / 100})`;+ } else if (shadow > 0) {+ style.boxShadow = `0 ${shadow / 2}px ${shadow}px rgba(0,0,0, ${shadow / 100})`;+ }++ // Border+ if (border?.enabled) {+ const { width, color, opacity } = border;+ const [r, g, b] = color;+ style.border = `${width}px solid rgba(${r}, ${g}, ${b}, ${opacity / 100})`;+ }++ return style;+ });++ const paddingStyle = createMemo(() => {+ const padding = project.background.padding;+ return {+ padding: `${padding * 2}px`, // Scale padding for visibility+ };+ });++ const cropDialogHandler = () => {+ const img = document.querySelector(+ "img[data-screenshot-preview]",+ ) as HTMLImageElement;+ if (img) {+ setDialog({+ open: true,+ type: "crop",+ position: {+ ...(project.background.crop?.position ?? { x: 0, y: 0 }),+ },+ size: {+ ...(project.background.crop?.size ?? {+ x: img.naturalWidth,+ y: img.naturalHeight,+ }),+ },+ });+ }+ };++ return (+ <div class="flex flex-col flex-1 rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3">+ {/* Top Toolbar */}+ <div class="flex gap-3 justify-center p-3">+ <AspectRatioSelect />+ <EditorButton+ tooltipText="Crop Image"+ onClick={cropDialogHandler}+ leftIcon={<IconCapCrop class="w-5 text-gray-12" />}+ >+ Crop+ </EditorButton>+ </div>++ {/* Preview Area */}+ <div class="flex-1 relative flex items-center justify-center bg-[--bg-subtle] overflow-hidden">+ <div+ class="relative shadow-2xl bg-white transition-transform duration-200 ease-out"+ style={{+ ...paddingStyle(),+ transform: `scale(${zoom()})`,+ }}+ >+ {/* Background Layer */}+ <div class="absolute inset-0 z-0 overflow-hidden transition-all duration-200">+ <Show+ when={+ project.background.source.type === "wallpaper" ||+ project.background.source.type === "image"+ }+ >+ <Show when={(project.background.source as any).path}>+ <img+ src={convertFileSrc((project.background.source as any).path)}+ class="w-full h-full object-cover"+ style={{ filter: `blur(${project.background.blur}px)` }}+ />+ </Show>+ </Show>+ <div class="w-full h-full" style={backgroundStyle()} />+ </div>++ {/* Content Layer */}+ <div class="relative z-10">+ <img+ data-screenshot-preview+ src={convertFileSrc(path)}+ class="max-w-full max-h-[80vh] block transition-all duration-200"+ style={imageStyle()}+ />+ </div>+ </div>+ </div>++ {/* Bottom Toolbar (Zoom) */}+ <div class="flex overflow-hidden z-10 flex-row gap-3 justify-between items-center p-5 h-[72px]">+ <div class="flex-1">{/* Left side spacer or info */}</div>++ <div class="flex flex-row flex-1 gap-4 justify-end items-center">+ <div class="flex-1" />++ <Tooltip kbd={["meta", "-"]} content="Zoom out">+ <IconCapZoomOut+ onClick={() => setZoom((z) => Math.max(0.1, z - 0.1))}+ class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70 cursor-pointer"+ />+ </Tooltip>+ <Tooltip kbd={["meta", "+"]} content="Zoom in">+ <IconCapZoomIn+ onClick={() => setZoom((z) => Math.min(3, z + 0.1))}+ class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70 cursor-pointer"+ />+ </Tooltip>+ <Slider+ class="w-24"+ minValue={0.1}+ maxValue={3}+ step={0.1}+ value={[zoom()]}+ onChange={([v]) => setZoom(v)}+ formatTooltip={(v) => `${Math.round(v * 100)}%`}+ />+ </div>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/ShadowSettings.tsx b/apps/desktop/src/routes/screenshot-editor/ShadowSettings.tsxnew file mode 100644index 000000000..b9bb7e666--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/ShadowSettings.tsx@@ -0,0 +1,90 @@+import { Collapsible as KCollapsible } from "@kobalte/core/collapsible";+import { cx } from "cva";+import { createSignal } from "solid-js";+import IconCapChevronDown from "~icons/cap/chevron-down";+import { Field, Slider } from "./ui";++interface Props {+ size: {+ value: number[];+ onChange: (v: number[]) => void;+ };+ opacity: {+ value: number[];+ onChange: (v: number[]) => void;+ };+ blur: {+ value: number[];+ onChange: (v: number[]) => void;+ };+ scrollRef?: HTMLDivElement;+}++const ShadowSettings = (props: Props) => {+ const [isOpen, setIsOpen] = createSignal(false);++ const handleToggle = () => {+ setIsOpen(!isOpen());+ setTimeout(() => {+ if (props.scrollRef) {+ props.scrollRef.scrollTo({+ top: props.scrollRef.scrollHeight,+ behavior: "smooth",+ });+ }+ }, 200);+ };++ return (+ <div class="w-full h-full">+ <button+ type="button"+ onClick={handleToggle}+ class="flex gap-1 items-center w-full font-medium text-left transition duration-200 text-gray-12 hover:text-gray-10"+ >+ <span class="text-sm">Advanced shadow settings</span>+ <IconCapChevronDown+ class={cx(+ "size-5",+ isOpen() ? "transition-transform rotate-180" : "",+ )}+ />+ </button>+ <KCollapsible open={isOpen()}>+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up ui-expanded:animate-collapsible-down ui-expanded:opacity-100">+ <div class="mt-4 space-y-6 font-medium">+ <Field name="Size">+ <Slider+ value={props.size.value}+ onChange={props.size.onChange}+ minValue={0}+ maxValue={100}+ step={0.1}+ />+ </Field>+ <Field name="Opacity">+ <Slider+ value={props.opacity.value}+ onChange={props.opacity.onChange}+ minValue={0}+ maxValue={100}+ step={0.1}+ />+ </Field>+ <Field name="Blur">+ <Slider+ value={props.blur.value}+ onChange={props.blur.onChange}+ minValue={0}+ maxValue={100}+ step={0.1}+ />+ </Field>+ </div>+ </KCollapsible.Content>+ </KCollapsible>+ </div>+ );+};++export default ShadowSettings;diff --git a/apps/desktop/src/routes/screenshot-editor/TextInput.tsx b/apps/desktop/src/routes/screenshot-editor/TextInput.tsxnew file mode 100644index 000000000..8fe37b95c--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/TextInput.tsx@@ -0,0 +1,18 @@+import type { ComponentProps } from "solid-js";+import { composeEventHandlers } from "~/utils/composeEventHandlers";++// It's important to use this instead of plain text inputs as we use global key listeners+// for keybinds+export function TextInput(props: ComponentProps<"input">) {+ return (+ <input+ {...props}+ onKeyDown={composeEventHandlers<HTMLInputElement>([+ props.onKeyDown,+ (e) => {+ e.stopPropagation();+ },+ ])}+ />+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/context.tsx b/apps/desktop/src/routes/screenshot-editor/context.tsxnew file mode 100644index 000000000..2981ceaa4--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/context.tsx@@ -0,0 +1,70 @@+import { createContextProvider } from "@solid-primitives/context";+import { createSignal } from "solid-js";+import { createStore } from "solid-js/store";+import type { AspectRatio, BackgroundConfiguration, XY } from "~/utils/tauri";+import {+ DEFAULT_GRADIENT_FROM,+ DEFAULT_GRADIENT_TO,+} from "../editor/projectConfig";++export type ScreenshotProject = {+ background: BackgroundConfiguration;+ aspectRatio: AspectRatio | null;+};++export type CurrentDialog =+ | { type: "createPreset" }+ | { type: "renamePreset"; presetIndex: number }+ | { type: "deletePreset"; presetIndex: number }+ | { type: "crop"; position: XY<number>; size: XY<number> }+ | { type: "export" };++export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);++const DEFAULT_PROJECT: ScreenshotProject = {+ background: {+ source: {+ type: "wallpaper",+ path: "macOS/sequoia-dark",+ },+ blur: 0,+ padding: 20,+ rounding: 10,+ roundingType: "squircle",+ inset: 0,+ crop: null,+ shadow: 0,+ advancedShadow: null,+ border: null,+ },+ aspectRatio: null,+};++export const [ScreenshotEditorProvider, useScreenshotEditorContext] =+ createContextProvider((props: { path: string }) => {+ const [project, setProject] =+ createStore<ScreenshotProject>(DEFAULT_PROJECT);+ const [dialog, setDialog] = createSignal<DialogState>({+ open: false,+ });++ // Mock history for now or implement if needed+ const projectHistory = {+ pause: () => () => {},+ resume: () => {},+ undo: () => {},+ redo: () => {},+ canUndo: () => false,+ canRedo: () => false,+ isPaused: () => false,+ };++ return {+ path: props.path,+ project,+ setProject,+ projectHistory,+ dialog,+ setDialog,+ };+ }, null!);diff --git a/apps/desktop/src/routes/screenshot-editor/index.tsx b/apps/desktop/src/routes/screenshot-editor/index.tsxnew file mode 100644index 000000000..491dcec89--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/index.tsx@@ -0,0 +1,49 @@+import { Effect, getCurrentWindow } from "@tauri-apps/api/window";+import { type as ostype } from "@tauri-apps/plugin-os";+import { cx } from "cva";+import { createEffect, createSignal, onMount, Show } from "solid-js";+import { AbsoluteInsetLoader } from "~/components/Loader";+import { generalSettingsStore } from "~/store";+import { commands } from "~/utils/tauri";+import { ScreenshotEditorProvider } from "./context";+import { Editor } from "./Editor";++export default function ScreenshotEditorRoute() {+ const generalSettings = generalSettingsStore.createQuery();+ const [path, setPath] = createSignal<string | null>(null);++ onMount(() => {+ // @ts-expect-error+ const initialPath = window.__CAP__?.screenshotPath;+ if (initialPath) {+ setPath(initialPath);+ }+ });++ createEffect(() => {+ const transparent = generalSettings.data?.windowTransparency ?? false;+ commands.setWindowTransparent(transparent);+ getCurrentWindow().setEffects({+ effects: transparent ? [Effect.HudWindow] : [],+ });+ });++ return (+ <div+ class={cx(+ "flex flex-col w-screen h-screen dark:bg-gray-1 bg-gray-2",+ !(+ ostype() === "windows" || !generalSettings.data?.windowTransparency+ ) && "bg-transparent-window",+ )}+ >+ <Show when={path()} fallback={<AbsoluteInsetLoader />}>+ {(p) => (+ <ScreenshotEditorProvider path={p()}>+ <Editor />+ </ScreenshotEditorProvider>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/ui.tsx b/apps/desktop/src/routes/screenshot-editor/ui.tsxnew file mode 100644index 000000000..c26ed34df--- /dev/null+++ b/apps/desktop/src/routes/screenshot-editor/ui.tsx@@ -0,0 +1,451 @@+import { Button } from "@cap/ui-solid";+import { Dialog as KDialog } from "@kobalte/core/dialog";+import { DropdownMenu } from "@kobalte/core/dropdown-menu";+import { Polymorphic, type PolymorphicProps } from "@kobalte/core/polymorphic";+import { Slider as KSlider } from "@kobalte/core/slider";+import { Tooltip as KTooltip } from "@kobalte/core/tooltip";+import { createElementBounds } from "@solid-primitives/bounds";+import { createEventListener } from "@solid-primitives/event-listener";+import { cva, cx, type VariantProps } from "cva";++import {+ type ComponentProps,+ createRoot,+ createSignal,+ type JSX,+ mergeProps,+ type ParentProps,+ splitProps,+ type ValidComponent,+} from "solid-js";+import Tooltip from "~/components/Tooltip";+import { useScreenshotEditorContext } from "./context";+import { TextInput } from "./TextInput";++export function Field(+ props: ParentProps<{+ name: string;+ icon?: JSX.Element;+ value?: JSX.Element;+ class?: string;+ disabled?: boolean;+ }>,+) {+ return (+ <div class={cx("flex flex-col gap-4", props.class)}>+ <span+ data-disabled={props.disabled}+ class="flex flex-row items-center gap-[0.375rem] text-gray-12 data-[disabled='true']:text-gray-10 font-medium text-sm"+ >+ {props.icon}+ {props.name}+ {props.value && <div class="ml-auto">{props.value}</div>}+ </span>+ {props.children}+ </div>+ );+}++export function Subfield(+ props: ParentProps<{ name: string; class?: string; required?: boolean }>,+) {+ return (+ <div class={cx("flex flex-row justify-between items-center", props.class)}>+ <span class="font-medium text-gray-12">+ {props.name}+ {props.required && (+ <span class="ml-[2px] text-xs text-blue-500">*</span>+ )}+ </span>+ {props.children}+ </div>+ );+}++export function Slider(+ props: ComponentProps<typeof KSlider> & {+ formatTooltip?: string | ((v: number) => string);+ },+) {+ const { projectHistory: history } = useScreenshotEditorContext();++ // Pause history when slider is being dragged+ let resumeHistory: (() => void) | null = null;++ const [thumbRef, setThumbRef] = createSignal<HTMLDivElement>();++ const thumbBounds = createElementBounds(thumbRef);++ const [dragging, setDragging] = createSignal(false);++ return (+ <KSlider+ {...props}+ class={cx(+ "relative px-1 h-8 flex flex-row justify-stretch items-center",+ props.class,+ )}+ onChange={(v) => {+ if (!resumeHistory) resumeHistory = history.pause();+ props.onChange?.(v);+ }}+ onChangeEnd={(e) => {+ resumeHistory?.();+ resumeHistory = null;+ props.onChangeEnd?.(e);+ }}+ >+ <KSlider.Track+ class="h-[0.3rem] cursor-pointer transition-[height] relative mx-1 bg-gray-4 rounded-full w-full before:content-[''] before:absolute before:inset-0 before:-top-3 before:-bottom-3"+ onPointerDown={() => {+ setDragging(true);+ createRoot((dispose) => {+ createEventListener(window, "mouseup", () => {+ setDragging(false);+ dispose();+ });+ });+ }}+ >+ <KSlider.Fill class="absolute -ml-2 h-full rounded-full bg-blue-9 ui-disabled:bg-gray-8" />+ <Tooltip+ open={dragging() ? true : undefined}+ getAnchorRect={() => {+ return {+ x: thumbBounds.left ?? undefined,+ y: thumbBounds.top ?? undefined,+ width: thumbBounds.width ?? undefined,+ height: thumbBounds.height ?? undefined,+ };+ }}+ content={+ props.value?.[0] !== undefined+ ? typeof props.formatTooltip === "string"+ ? `${props.value[0].toFixed(1)}${props.formatTooltip}`+ : props.formatTooltip+ ? props.formatTooltip(props.value[0])+ : props.value[0].toFixed(1)+ : undefined+ }+ >+ <KSlider.Thumb+ ref={setThumbRef}+ onPointerDown={() => {+ setDragging(true);+ }}+ onPointerUp={() => {+ setDragging(false);+ }}+ class={cx(+ "bg-gray-1 dark:bg-gray-12 border border-gray-6 shadow-md rounded-full outline-none size-4 -top-[6.3px] ui-disabled:bg-gray-9 after:content-[''] after:absolute after:inset-0 after:-m-3 after:cursor-pointer",+ )}+ />+ </Tooltip>+ </KSlider.Track>+ </KSlider>+ );+}++export function Input(props: ComponentProps<"input">) {+ return (+ <TextInput+ {...props}+ class={cx(+ props.class,+ "rounded-[0.5rem] bg-gray-2 hover:ring-1 py-[18px] hover:ring-gray-5 h-[2rem] font-normal placeholder:text-black-transparent-40 text-xs caret-gray-500 transition-shadow duration-200 focus:ring-offset-1 focus:bg-gray-3 focus:ring-offset-gray-100 focus:ring-1 focus:ring-gray-10 px-[0.5rem] w-full text-[0.875rem] outline-none text-gray-12",+ )}+ />+ );+}++export const Dialog = {+ Root(+ props: ComponentProps<typeof KDialog> & {+ hideOverlay?: boolean;+ size?: "sm" | "lg";+ contentClass?: string;+ },+ ) {+ return (+ <KDialog {...props}>+ <KDialog.Portal>+ {!props.hideOverlay && (+ <KDialog.Overlay class="fixed inset-0 z-50 bg-[#000]/80 ui-expanded:animate-in ui-expanded:fade-in ui-closed:animate-out ui-closed:fade-out" />+ )}+ <div class="flex fixed inset-0 z-50 justify-center items-center">+ <KDialog.Content+ class={cx(+ props.contentClass,+ "z-50 text-sm rounded-[1.25rem] overflow-hidden border border-gray-3 bg-gray-1 min-w-[22rem] ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 origin-top ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95",+ (props.size ?? "sm") === "sm" ? "max-w-96" : "max-w-3xl",+ )}+ >+ {props.children}+ </KDialog.Content>+ </div>+ </KDialog.Portal>+ </KDialog>+ );+ },+ CloseButton() {+ return (+ <KDialog.CloseButton as={Button} variant="gray">+ Cancel+ </KDialog.CloseButton>+ );+ },+ ConfirmButton(_props: ComponentProps<typeof Button>) {+ const props = mergeProps(+ { variant: "primary" } as ComponentProps<typeof Button>,+ _props,+ );+ return <Button {...props} />;+ },+ Footer(+ props: ComponentProps<"div"> & {+ close?: JSX.Element;+ leftFooterContent?: JSX.Element;+ },+ ) {+ return (+ <div+ class={cx(+ "h-[4rem] px-[1rem] gap-3 flex flex-row items-center",+ props.leftFooterContent ? "justify-between" : "justify-center",+ props.class,+ )}+ {...props}+ >+ {props.leftFooterContent}+ <div class="flex flex-row gap-3 items-center">{props.children}</div>+ </div>+ );+ },+ Header(props: ComponentProps<"div">) {+ return (+ <div {...props} class="h-[3.5rem] px-[1rem] flex flex-row items-center" />+ );+ },+ Content(props: ComponentProps<"div">) {+ return (+ <div+ {...props}+ class={cx("p-[1rem] flex flex-col border-y border-gray-3", props.class)}+ />+ );+ },+};++export function DialogContent(+ props: ParentProps<{+ title: string;+ confirm: JSX.Element;+ class?: string;+ close?: JSX.Element;+ leftFooterContent?: JSX.Element;+ }>,+) {+ return (+ <>+ <Dialog.Header>+ <KDialog.Title class="text-gray-12">{props.title}</KDialog.Title>+ </Dialog.Header>+ <Dialog.Content class={props.class}>{props.children}</Dialog.Content>+ <Dialog.Footer+ close={props.close}+ leftFooterContent={props.leftFooterContent}+ >+ {props.confirm}+ </Dialog.Footer>+ </>+ );+}++export function MenuItem<T extends ValidComponent = "button">(+ _props: ComponentProps<T>,+) {+ const props = mergeProps({ as: "div" } as ComponentProps<T>, _props);++ return (+ <Polymorphic+ {...props}+ class={cx(+ props.class,+ "flex flex-row shrink-0 items-center gap-[0.375rem] px-[0.675rem] py-[0.375rem] rounded-[0.5rem] outline-none text-nowrap overflow-hidden text-ellipsis w-full max-w-full",+ "text-[0.875rem] text-gray-10 disabled:text-gray-10 ui-highlighted:bg-gray-3 ui-highlighted:text-gray-12",+ )}+ />+ );+}++export function DropdownItem(props: ComponentProps<typeof DropdownMenu.Item>) {+ return (+ <MenuItem<typeof DropdownMenu.Item> as={DropdownMenu.Item} {...props} />+ );+}++export function PopperContent<T extends ValidComponent = "div">(+ props: ComponentProps<T>,+) {+ return (+ <Polymorphic {...props} class={cx(dropdownContainerClasses, props.class)} />+ );+}++export function MenuItemList<T extends ValidComponent = "div">(+ _props: ComponentProps<T>,+) {+ const props = mergeProps({ as: "div" } as ComponentProps<T>, _props);++ return (+ <Polymorphic+ {...props}+ class={cx(+ props.class,+ "space-y-[0.375rem] p-[0.375rem] overflow-y-auto outline-none",+ )}+ />+ );+}++const editorButtonStyles = cva(+ [+ "group flex flex-row items-center px-[0.375rem] gap-[0.375rem] h-[2rem] rounded-[0.5rem] text-[0.875rem]",+ "focus:outline focus:outline-2 focus:outline-offset-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 transition-colors duration-100",+ "disabled:opacity-50 disabled:text-gray-11",+ ],+ {+ variants: {+ variant: {+ primary:+ "text-gray-12 enabled:hover:ui-not-pressed:bg-gray-3 ui-expanded:bg-gray-3 outline-blue-300 focus:bg-transparent",+ danger:+ "text-gray-12 enabled:hover:ui-not-pressed:bg-gray-3 ui-expanded:bg-red-300 ui-pressed:bg-red-300 ui-expanded:text-gray-1 ui-pressed:text-gray-1 outline-red-300",+ },+ },+ defaultVariants: { variant: "primary" },+ },+);++const editorButtonLeftIconStyles = cva("transition-colors duration-100", {+ variants: {+ variant: {+ primary:+ "text-gray-12 enabled:group-hover:not-ui-group-disabled:text-gray-12 ui-group-expanded:text-gray-12",+ danger:+ "text-gray-12 enabled:group-hover:text-gray-12 ui-group-expanded:text-gray-1 ui-group-pressed:text-gray-1",+ },+ },+ defaultVariants: { variant: "primary" },+});++type EditorButtonProps<T extends ValidComponent = "button"> =+ PolymorphicProps<T> & {+ children?: JSX.Element | string;+ leftIcon?: JSX.Element;+ rightIcon?: JSX.Element;+ kbd?: string[];+ tooltipText?: string;+ comingSoon?: boolean;+ rightIconEnd?: boolean;+ } & VariantProps<typeof editorButtonStyles>;++export function EditorButton<T extends ValidComponent = "button">(+ props: EditorButtonProps<T>,+) {+ const [local, cvaProps, others] = splitProps(+ mergeProps({ variant: "primary" }, props) as unknown as EditorButtonProps,+ [+ "children",+ "leftIcon",+ "rightIcon",+ "tooltipText",+ "kbd",+ "ref",+ "comingSoon",+ "rightIconEnd",+ ],+ ["class", "variant"],+ );++ const buttonContent = (+ <>+ <span class={editorButtonLeftIconStyles({ variant: cvaProps.variant })}>+ {local.leftIcon}+ </span>+ {local.children && <span>{local.children}</span>}+ {local.rightIcon && (+ <span class={local.rightIconEnd ? "ml-auto" : ""}>+ {local.rightIcon}+ </span>+ )}+ </>+ );++ return (+ <>+ {local.tooltipText || local.comingSoon ? (+ <Tooltip+ kbd={local.kbd}+ content={local.comingSoon ? "Coming Soon" : local.tooltipText}+ >+ <Polymorphic+ as="button"+ {...others}+ class={cx(+ editorButtonStyles({ ...cvaProps, class: cvaProps.class }),+ local.rightIconEnd && "justify-between",+ )}+ disabled={local.comingSoon}+ >+ {buttonContent}+ </Polymorphic>+ </Tooltip>+ ) : (+ <Polymorphic+ as="button"+ {...others}+ class={cx(+ editorButtonStyles({ ...cvaProps, class: cvaProps.class }),+ local.rightIconEnd && "justify-between",+ )}+ >+ {buttonContent}+ </Polymorphic>+ )}+ </>+ );+}++export const dropdownContainerClasses =+ "z-10 flex flex-col rounded-[0.75rem] border border-gray-3 bg-gray-1 shadow-s overflow-y-hidden outline-none";++export const topLeftAnimateClasses =+ "ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95 origin-top-left";++export const topCenterAnimateClasses =+ "ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95 origin-top-center";++export const topRightAnimateClasses =+ "ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95 origin-top-right";++export const topSlideAnimateClasses =+ "ui-expanded:animate-in ui-expanded:fade-in ui-expanded:slide-in-from-top-1 ui-closed:animate-out ui-closed:fade-out ui-closed:slide-out-to-top-1 origin-top-center";++export function ComingSoonTooltip(+ props: ComponentProps<typeof KTooltip> & any,+) {+ const [trigger, root] = splitProps(props, ["children", "as"]);+ return (+ <KTooltip placement="top" openDelay={0} closeDelay={0} {...root}>+ <KTooltip.Trigger as={trigger.as ?? "div"}>+ {trigger.children}+ </KTooltip.Trigger>+ <KTooltip.Portal>+ <KTooltip.Content class="p-2 font-medium bg-gray-12 text-gray-1 ui-expanded:animate-in ui-expanded:slide-in-from-bottom-1 ui-expanded:fade-in ui-closed:animate-out ui-closed:slide-out-to-bottom-1 ui-closed:fade-out rounded-lg text-xs z-[1000]">+ Coming Soon+ </KTooltip.Content>+ </KTooltip.Portal>+ </KTooltip>+ );+}diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsxindex 65c3f76f8..f2d55a315 100644--- a/apps/desktop/src/routes/target-select-overlay.tsx+++ b/apps/desktop/src/routes/target-select-overlay.tsx@@ -804,6 +804,15 @@ function RecordingControls(props: {},checked: rawOptions.mode === "instant",}),+ await CheckMenuItem.new({+ text: "Screenshot Mode",+ action: () => {+ // @ts-expect-error+ setOptions("mode", "screenshot");+ },+ // @ts-expect-error+ checked: rawOptions.mode === "screenshot",+ }),],});@@ -870,7 +879,7 @@ function RecordingControls(props: {data-inactive={rawOptions.mode === "instant" && !auth.data}data-disabled={startDisabled()}class="flex flex-1 min-w-0 max-w-[15rem] overflow-hidden flex-row h-11 rounded-full text-white bg-gradient-to-r from-blue-10 via-blue-10 to-blue-11 group"- onClick={() => {+ onClick={async () => {if (rawOptions.mode === "instant" && !auth.data) {emit("start-sign-in");return;@@ -899,6 +908,21 @@ function RecordingControls(props: {props.onRecordingStart?.();+ // @ts-expect-error+ if (rawOptions.mode === "screenshot") {+ try {+ const path = await invoke<string>("take_screenshot", {+ target: props.target,+ });+ // @ts-expect-error+ commands.showWindow({ ScreenshotEditor: { path } });+ commands.closeTargetSelectOverlays();+ } catch (e) {+ console.error("Failed to take screenshot", e);+ }+ return;+ }+commands.startRecording({capture_target: props.target,mode: rawOptions.mode,@@ -913,16 +937,27 @@ function RecordingControls(props: {startDisabled(),}}>- {rawOptions.mode === "studio" ? (- <IconCapFilmCut class="size-4 flex-shrink-0" />- ) : (- <IconCapInstant class="size-4 flex-shrink-0" />- )}+ <Switch>+ <Match when={rawOptions.mode === "studio"}>+ <IconCapFilmCut class="size-4 flex-shrink-0" />+ </Match>+ <Match when={rawOptions.mode === "instant"}>+ <IconCapInstant class="size-4 flex-shrink-0" />+ </Match>+ <Match when={(rawOptions.mode as string) === "screenshot"}>+ <IconCapCamera class="size-4 flex-shrink-0" />+ </Match>+ </Switch><div class="flex flex-col mr-2 ml-3 min-w-0"><span class="text-[0.95rem] font-medium text-white text-nowrap">- {rawOptions.mode === "instant" && !auth.data- ? "Sign In To Use"- : "Start Recording"}+ {(() => {+ if (rawOptions.mode === "instant" && !auth.data)+ return "Sign In To Use";+ // @ts-expect-error+ if (rawOptions.mode === "screenshot")+ return "Take Screenshot";+ return "Start Recording";+ })()}</span><span class="text-[11px] flex items-center text-nowrap gap-1 transition-opacity duration-200 text-white/90 font-light -mt-0.5">{`${capitalize(rawOptions.mode)} Mode`}@@ -946,31 +981,33 @@ function RecordingControls(props: {</div></div></div>- <div class="p-3 rounded-2xl border border-white/30 dark:border-white/10 bg-white/70 dark:bg-gray-2/70 shadow-lg backdrop-blur-xl">- <div class="grid grid-cols-2 gap-2 w-full">- <CameraSelect- disabled={cameras.isPending}- options={cameras.data ?? []}- value={selectedCamera() ?? null}- onChange={(camera) => {- if (!camera) setCamera.mutate(null);- else if (camera.model_id)- setCamera.mutate({ ModelID: camera.model_id });- else setCamera.mutate({ DeviceID: camera.device_id });- }}- />- <MicrophoneSelect- disabled={mics.isPending}- options={mics.isPending ? [] : (mics.data ?? [])}- value={- mics.isPending- ? (rawOptions.micName ?? null)- : selectedMicName()- }- onChange={(value) => setMicInput.mutate(value)}- />+ <Show when={(rawOptions.mode as string) !== "screenshot"}>+ <div class="p-3 rounded-2xl border border-white/30 dark:border-white/10 bg-white/70 dark:bg-gray-2/70 shadow-lg backdrop-blur-xl">+ <div class="grid grid-cols-2 gap-2 w-full">+ <CameraSelect+ disabled={cameras.isPending}+ options={cameras.data ?? []}+ value={selectedCamera() ?? null}+ onChange={(camera) => {+ if (!camera) setCamera.mutate(null);+ else if (camera.model_id)+ setCamera.mutate({ ModelID: camera.model_id });+ else setCamera.mutate({ DeviceID: camera.device_id });+ }}+ />+ <MicrophoneSelect+ disabled={mics.isPending}+ options={mics.isPending ? [] : (mics.data ?? [])}+ value={+ mics.isPending+ ? (rawOptions.micName ?? null)+ : selectedMicName()+ }+ onChange={(value) => setMicInput.mutate(value)}+ />+ </div></div>- </div>+ </Show></div><div class="flex justify-center items-center w-full"><divdiff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 80ada5de5..5b8fd1dbc 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -32,6 +32,9 @@ async restartRecording() : Promise<RecordingAction> {async deleteRecording() : Promise<null> {return await TAURI_INVOKE("delete_recording");},+async takeScreenshot(target: ScreenCaptureTarget) : Promise<string> {+ return await TAURI_INVOKE("take_screenshot", { target });+},async listCameras() : Promise<CameraInfo[]> {return await TAURI_INVOKE("list_cameras");},@@ -454,7 +457,7 @@ export type RecordingEvent = { variant: "Countdown"; value: number } | { variantexport type RecordingInputKind = "microphone" | "camera"export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }export type RecordingMetaWithMetadata = ((StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null; upload?: UploadMeta | null }) & { mode: RecordingMode; status: StudioRecordingStatus }-export type RecordingMode = "studio" | "instant"+export type RecordingMode = "studio" | "instant" | "screenshot"export type RecordingOptionsChanged = nullexport type RecordingSettingsStore = { target: ScreenCaptureTarget | null; micName: string | null; cameraId: DeviceOrModelID | null; mode: RecordingMode | null; systemAudio: boolean; organizationId: string | null }export type RecordingStarted = null@@ -475,7 +478,7 @@ export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuratexport type SetCaptureAreaPending = booleanexport type ShadowConfiguration = { size: number; opacity: number; blur: number }export type SharingMeta = { id: string; link: string }-export type ShowCapWindow = "Setup" | { Main: { init_target_mode: RecordingTargetMode | null } } | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: DisplayId } } | { TargetSelectOverlay: { display_id: DisplayId } } | { CaptureArea: { screen_id: DisplayId } } | "Camera" | { InProgressRecording: { countdown: number | null } } | "Upgrade" | "ModeSelect"+export type ShowCapWindow = "Setup" | { Main: { init_target_mode: RecordingTargetMode | null } } | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: DisplayId } } | { TargetSelectOverlay: { display_id: DisplayId } } | { CaptureArea: { screen_id: DisplayId } } | "Camera" | { InProgressRecording: { countdown: number | null } } | "Upgrade" | "ModeSelect" | { ScreenshotEditor: { path: string } }export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; cursor?: string | null }export type StartRecordingInputs = { capture_target: ScreenCaptureTarget; capture_system_audio?: boolean; mode: RecordingMode; organization_id?: string | null }export type StereoMode = "stereo" | "monoL" | "monoR"diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.tomlindex fa131876a..0203e1912 100644--- a/crates/recording/Cargo.toml+++ b/crates/recording/Cargo.toml@@ -21,6 +21,7 @@ cap-camera = { path = "../camera", features = ["serde", "specta"] }cap-camera-ffmpeg = { path = "../camera-ffmpeg" }cap-enc-ffmpeg = { path = "../enc-ffmpeg" }cap-timestamp = { path = "../timestamp" }+scap-ffmpeg = { path = "../scap-ffmpeg" }specta = { workspace = true }tokio = { workspace = true }@@ -74,7 +75,6 @@ cap-mediafoundation-ffmpeg = { path = "../mediafoundation-ffmpeg" }cap-mediafoundation-utils = { path = "../mediafoundation-utils" }cap-camera-windows = { path = "../camera-windows" }scap-direct3d = { path = "../scap-direct3d" }-scap-ffmpeg = { path = "../scap-ffmpeg" }scap-cpal = { path = "../scap-cpal" }[dev-dependencies]diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex d417c5f08..0b7f01383 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -3,6 +3,7 @@ pub mod cursor;pub mod feeds;pub mod instant_recording;mod output_pipeline;+pub mod screenshot;pub mod sources;pub mod studio_recording;@@ -19,12 +20,13 @@ use thiserror::Error;use crate::{feeds::camera::CameraFeedLock, sources::screen_capture::ScreenCaptureTarget};-#[derive(specta::Type, Serialize, Deserialize, Clone, Debug, Copy, Default)]+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug, Copy, Default, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub enum RecordingMode {#[default]Studio,Instant,+ Screenshot,}#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]diff --git a/crates/recording/src/screenshot.rs b/crates/recording/src/screenshot.rsnew file mode 100644index 000000000..e6c48b012--- /dev/null+++ b/crates/recording/src/screenshot.rs@@ -0,0 +1,237 @@+use crate::sources::screen_capture::ScreenCaptureTarget;+use anyhow::{Context, anyhow};+use image::RgbImage;+#[cfg(any(target_os = "macos", target_os = "windows"))]+use scap_ffmpeg::AsFFmpeg;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::sync::oneshot;+use tracing::error;++#[cfg(target_os = "macos")]+use scap_screencapturekit::{Capturer, StreamCfgBuilder};++#[cfg(target_os = "windows")]+use scap_direct3d::{Capturer, PixelFormat, Settings};++pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<RgbImage> {+ let (tx, rx) = oneshot::channel::<anyhow::Result<RgbImage>>();+ let tx = Arc::new(Mutex::new(Some(tx)));++ #[cfg(target_os = "macos")]+ let capturer = {+ use cidre::sc;++ let content_filter = match target.clone() {+ ScreenCaptureTarget::Display { id } => {+ let display = scap_targets::Display::from_id(&id)+ .ok_or_else(|| anyhow!("Display not found"))?;++ display+ .raw_handle()+ .as_content_filter(+ sc::ShareableContent::current()+ .await+ .map_err(|e| anyhow!("Failed to get shareable content: {e}"))?,+ )+ .await+ .ok_or_else(|| anyhow!("Failed to get content filter"))?+ }+ ScreenCaptureTarget::Window { id } => {+ let window = scap_targets::Window::from_id(&id)+ .ok_or_else(|| anyhow!("Window not found"))?;++ let sc_content = sc::ShareableContent::current()+ .await+ .map_err(|e| anyhow!("Failed to get shareable content: {e}"))?;+ let sc_window = window+ .raw_handle()+ .as_sc(sc_content)+ .await+ .ok_or_else(|| anyhow!("Failed to get SCWindow"))?;++ sc::ContentFilter::with_desktop_independent_window(sc_window.as_ref())+ }+ ScreenCaptureTarget::Area { screen, .. } => {+ let display = scap_targets::Display::from_id(&screen)+ .ok_or_else(|| anyhow!("Display not found"))?;++ display+ .raw_handle()+ .as_content_filter(+ sc::ShareableContent::current()+ .await+ .map_err(|e| anyhow!("Failed to get shareable content: {e}"))?,+ )+ .await+ .ok_or_else(|| anyhow!("Failed to get content filter"))?+ }+ };++ let width = match target.clone() {+ ScreenCaptureTarget::Display { id } => scap_targets::Display::from_id(&id)+ .and_then(|d| d.physical_size())+ .map(|s| s.width())+ .unwrap_or(1920.0),+ ScreenCaptureTarget::Window { id } => scap_targets::Window::from_id(&id)+ .and_then(|w| w.physical_size())+ .map(|s| s.width())+ .unwrap_or(1920.0),+ ScreenCaptureTarget::Area { screen, .. } => scap_targets::Display::from_id(&screen)+ .and_then(|d| d.physical_size())+ .map(|s| s.width())+ .unwrap_or(1920.0),+ } as usize;++ let height = match target.clone() {+ ScreenCaptureTarget::Display { id } => scap_targets::Display::from_id(&id)+ .and_then(|d| d.physical_size())+ .map(|s| s.height())+ .unwrap_or(1080.0),+ ScreenCaptureTarget::Window { id } => scap_targets::Window::from_id(&id)+ .and_then(|w| w.physical_size())+ .map(|s| s.height())+ .unwrap_or(1080.0),+ ScreenCaptureTarget::Area { screen, .. } => scap_targets::Display::from_id(&screen)+ .and_then(|d| d.physical_size())+ .map(|s| s.height())+ .unwrap_or(1080.0),+ } as usize;++ let config = StreamCfgBuilder::default()+ .with_fps(60.0) // High FPS to get the first frame quickly+ .with_width(width)+ .with_height(height)+ .with_shows_cursor(true)+ .build();++ Capturer::builder(content_filter, config)+ .with_output_sample_buf_cb({+ let tx = tx.clone();+ move |frame| {+ if let Some(tx) = tx.lock().unwrap().take() {+ let res = (|| {+ use scap_screencapturekit::Frame;+ let Frame::Screen(video_frame) = frame else {+ return Err(anyhow!("Not a screen frame"));+ };+ // Note: This requires VideoFrame to implement AsFFmpeg trait or similar logic.+ // Since scap_screencapturekit::VideoFrame doesn't directly implement it in all contexts,+ // we might need to ensure we are using the correct types or traits.+ // Assuming scap_ffmpeg::AsFFmpeg is implemented for it if imported.+ let ff_frame = video_frame+ .as_ffmpeg()+ .map_err(|e| anyhow!("Failed to convert to ffmpeg: {e:?}"))?;+ convert_ffmpeg_frame_to_image(&ff_frame)+ })();+ let _ = tx.send(res);+ }+ }+ })+ .with_stop_with_err_cb(|_, err| {+ error!("Screenshot capture error: {err:?}");+ })+ .build()+ .map_err(|e| anyhow!("Failed to build capturer: {e:?}"))?+ };++ #[cfg(target_os = "windows")]+ let mut capturer = {+ // Windows implementation+ // TODO: Implement Windows support similar to above+ // For now return error on Windows+ return Err(anyhow!("Windows screenshot not yet implemented"));+ };++ #[cfg(target_os = "macos")]+ capturer+ .start()+ .await+ .map_err(|e| anyhow!("Failed to start capturer: {e:?}"))?;++ // Wait for frame or timeout+ let result = match tokio::time::timeout(Duration::from_secs(2), rx).await {+ Ok(Ok(res)) => res,+ Ok(Err(_)) => Err(anyhow!("Channel closed")),+ Err(_) => Err(anyhow!("Timeout waiting for screenshot")),+ };++ #[cfg(target_os = "macos")]+ capturer+ .stop()+ .await+ .map_err(|e| anyhow!("Failed to stop capturer: {e:?}"))?;++ let image = result?;++ // Handle Area cropping+ if let ScreenCaptureTarget::Area { bounds, screen } = target {+ // We need to calculate crop bounds relative to the captured image.+ // The captured image is the full display.+ // bounds are LogicalBounds.++ // On macOS, physical size is logical * scale.+ #[cfg(target_os = "macos")]+ let scale = {+ let display = scap_targets::Display::from_id(&screen)+ .ok_or_else(|| anyhow!("Display not found"))?;+ display.raw_handle().scale().unwrap_or(1.0)+ };++ #[cfg(target_os = "windows")]+ let scale = 1.0; // TODO: Windows scale++ let x = (bounds.position().x() * scale) as u32;+ let y = (bounds.position().y() * scale) as u32;+ let width = (bounds.size().width() * scale) as u32;+ let height = (bounds.size().height() * scale) as u32;++ // Ensure we don't crop out of bounds+ let img_width = image.width();+ let img_height = image.height();++ let x = x.min(img_width);+ let y = y.min(img_height);+ let width = width.min(img_width - x);+ let height = height.min(img_height - y);++ let cropped = image::imageops::crop_imm(&image, x, y, width, height).to_image();+ return Ok(cropped);+ }++ Ok(image)+}++fn convert_ffmpeg_frame_to_image(frame: &ffmpeg::frame::Video) -> anyhow::Result<RgbImage> {+ let mut scaler = ffmpeg::software::scaling::context::Context::get(+ frame.format(),+ frame.width(),+ frame.height(),+ ffmpeg::format::Pixel::RGB24,+ frame.width(),+ frame.height(),+ ffmpeg::software::scaling::flag::Flags::BILINEAR,+ )+ .context("Failed to create scaler")?;++ let mut rgb_frame = ffmpeg::frame::Video::empty();+ scaler+ .run(frame, &mut rgb_frame)+ .context("Failed to scale frame")?;++ let width = rgb_frame.width() as usize;+ let height = rgb_frame.height() as usize;+ let dst_stride = width * 3;+ let src_stride = rgb_frame.stride(0);++ let mut img_buffer = vec![0u8; height * dst_stride];++ for y in 0..height {+ let src_slice = &rgb_frame.data(0)[y * src_stride..y * src_stride + dst_stride];+ let dst_slice = &mut img_buffer[y * dst_stride..(y + 1) * dst_stride];+ dst_slice.copy_from_slice(src_slice);+ }++ RgbImage::from_raw(width as u32, height as u32, img_buffer)+ .ok_or_else(|| anyhow!("Failed to create image buffer"))+}