Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

Use selection-only capture picker across desktop platforms

webadderallc8475a49fc68
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index b9bc587c..246521f9 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -254,6 +254,7 @@ interface Window {
getCapturePickerContext: (displayId: number) => Promise<{
displayBounds: CaptureArea | null;
lastArea: CaptureArea | null;
+ allowArea: boolean;
/** On-screen windows on this display, front to back. */
windows: CapturePickerWindow[];
cursor: { x: number; y: number } | null;
diff --git a/electron/ipc/capturePickerSources.test.ts b/electron/ipc/capturePickerSources.test.ts
new file mode 100644
index 00000000..d7e0d8d5
--- /dev/null
+++ b/electron/ipc/capturePickerSources.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ exec: vi.fn(),
+ sources: vi.fn(),
+ mac: vi.fn(),
+ linux: vi.fn(),
+ dip: vi.fn(),
+}));
+vi.mock("node:util", () => ({ promisify: () => mocks.exec }));
+vi.mock("./cursor/bounds", () => ({
+ getNativeMacWindowsFrontToBack: mocks.mac,
+ resolveLinuxWindowBounds: mocks.linux,
+}));
+vi.mock("./register/sources", () => ({ getDesktopSources: mocks.sources }));
+vi.mock("./utils", () => ({
+ parseWindowId: (id?: string) => Number(id?.split(":")[1]),
+ getScreen: () => ({ screenToDipRect: mocks.dip }),
+}));
+import { listCapturePickerWindows, parseStackingOrder } from "./capturePickerSources";
+const platform = process.platform;
+afterEach(() => Object.defineProperty(process, "platform", { value: platform }));
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.sources.mockResolvedValue([
+ { id: "window:101:0", name: "Front" },
+ { id: "window:102:0", name: "Back" },
+ ]);
+});
+describe("capture picker source adapters", () => {
+ it("reads X11 stacking from topmost to bottommost", async () => {
+ Object.defineProperty(process, "platform", { value: "linux" });
+ mocks.exec.mockResolvedValue({
+ stdout: "_NET_CLIENT_LIST_STACKING(WINDOW): window id # 0x66, 0x65",
+ });
+ mocks.linux.mockResolvedValue({ x: 0, y: 0, width: 400, height: 300 });
+ expect(parseStackingOrder("0x66, 0x65")).toEqual([101, 102]);
+ expect((await listCapturePickerWindows()).map((entry) => entry.id)).toEqual([
+ "window:101:0",
+ "window:102:0",
+ ]);
+ });
+ it("matches Windows handles to real capture IDs and converts physical bounds to DIP", async () => {
+ Object.defineProperty(process, "platform", { value: "win32" });
+ mocks.exec.mockResolvedValue({
+ stdout: JSON.stringify([
+ { id: 999, x: 0, y: 0, width: 20, height: 20 },
+ { id: 101, x: -1600, y: 0, width: 800, height: 600 },
+ ]),
+ });
+ mocks.dip.mockReturnValue({ x: -800, y: 0, width: 400, height: 300 });
+ expect(await listCapturePickerWindows()).toEqual([
+ {
+ id: "window:101:0",
+ appName: "",
+ title: "Front",
+ display_id: undefined,
+ x: -800,
+ y: 0,
+ width: 400,
+ height: 300,
+ },
+ ]);
+ expect(mocks.dip).toHaveBeenCalledWith(null, expect.objectContaining({ x: -1600 }));
+ });
+ it("excludes Recordly's own macOS windows and invalid geometry", async () => {
+ Object.defineProperty(process, "platform", { value: "darwin" });
+ mocks.mac.mockResolvedValue([
+ { id: "window:1:0", ownerPid: process.pid, x: 0, y: 0, width: 10, height: 10 },
+ { id: "window:2:0", ownerPid: 99, name: "Other", x: 0, y: 0, width: 400, height: 300 },
+ { id: "window:3:0", width: Number.NaN },
+ ]);
+ expect((await listCapturePickerWindows()).map((entry) => entry.id)).toEqual(["window:2:0"]);
+ });
+});
diff --git a/electron/ipc/capturePickerSources.ts b/electron/ipc/capturePickerSources.ts
new file mode 100644
index 00000000..a24bdc0b
--- /dev/null
+++ b/electron/ipc/capturePickerSources.ts
@@ -0,0 +1,136 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { getNativeMacWindowsFrontToBack, resolveLinuxWindowBounds } from "./cursor/bounds";
+import type { CapturePickerWindow, SelectedSource } from "./types";
+import { getScreen, parseWindowId } from "./utils";
+import { getDesktopSources } from "./register/sources";
+
+const exec = promisify(execFile);
+
+export function parseStackingOrder(text: string): number[] {
+ return [...text.matchAll(/0x[0-9a-f]+/gi)]
+ .map((match) => Number.parseInt(match[0], 16))
+ .reverse();
+}
+
+// GetTopWindow/GetWindow walks front to back. Restrict the result to Electron's
+// capturable sources rather than inventing source IDs or changing capture routes.
+const WINDOWS_SCRIPT = `Add-Type -TypeDefinition @"
+using System; using System.Runtime.InteropServices; using System.Collections.Generic;
+public static class RecordlyPickerWindows {
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
+ [DllImport("user32.dll")] static extern IntPtr GetTopWindow(IntPtr h);
+ [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint command);
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
+ [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);
+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT rect);
+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
+ [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attribute, out RECT rect, int size);
+ public class Entry { public long id; public int x, y, width, height; }
+ public static Entry[] List() {
+ SetThreadDpiAwarenessContext(new IntPtr(-4));
+ var list = new List<Entry>(); var seen = new HashSet<long>();
+ for (var h = GetTopWindow(IntPtr.Zero); h != IntPtr.Zero && seen.Add(h.ToInt64()); h = GetWindow(h, 2)) {
+ if (!IsWindowVisible(h) || IsIconic(h)) continue;
+ RECT rect;
+ if (DwmGetWindowAttribute(h, 9, out rect, Marshal.SizeOf(typeof(RECT))) != 0 && !GetWindowRect(h, out rect)) continue;
+ if (rect.Right <= rect.Left || rect.Bottom <= rect.Top) continue;
+ list.Add(new Entry { id = h.ToInt64(), x = rect.Left, y = rect.Top, width = rect.Right - rect.Left, height = rect.Bottom - rect.Top });
+ }
+ return list.ToArray();
+ }
+}
+"@
+ConvertTo-Json -InputObject @([RecordlyPickerWindows]::List()) -Compress`;
+
+export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]> {
+ if (process.platform === "darwin") {
+ const entries = await getNativeMacWindowsFrontToBack();
+ return entries
+ .filter(
+ (entry) =>
+ entry.ownerPid !== process.pid &&
+ [entry.x, entry.y, entry.width, entry.height].every(Number.isFinite) &&
+ (entry.width ?? 0) > 0 &&
+ (entry.height ?? 0) > 0,
+ )
+ .map((entry) => ({
+ id: entry.id,
+ appName: entry.appName ?? "",
+ title: entry.windowTitle ?? entry.name,
+ display_id: entry.display_id,
+ x: entry.x!,
+ y: entry.y!,
+ width: entry.width!,
+ height: entry.height!,
+ }));
+ }
+ const sources = await getDesktopSources({
+ types: ["window"],
+ thumbnailSize: { width: 0, height: 0 },
+ fetchWindowIcons: false,
+ });
+ const capturable = sources.filter(
+ (source): source is SelectedSource & { id: string } =>
+ typeof source.id === "string" && source.id.startsWith("window:"),
+ );
+ const byId = new Map(capturable.map((source) => [parseWindowId(source.id), source]));
+ if (process.platform === "win32") {
+ const { stdout } = await exec(
+ "powershell.exe",
+ ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT],
+ { timeout: 10000, maxBuffer: 4 * 1024 * 1024 },
+ );
+ const entries: unknown = JSON.parse(stdout);
+ if (!Array.isArray(entries)) throw new Error("Unable to read window positions.");
+ return entries.flatMap((entry) => {
+ const source = byId.get(entry.id);
+ if (
+ !source ||
+ ![entry.x, entry.y, entry.width, entry.height].every(Number.isFinite) ||
+ entry.width <= 0 ||
+ entry.height <= 0
+ )
+ return [];
+ const bounds = getScreen().screenToDipRect(null, entry);
+ return [
+ {
+ ...bounds,
+ id: source.id,
+ appName: "",
+ title: source.name,
+ display_id: source.display_id,
+ },
+ ];
+ });
+ }
+ const { stdout } = await exec("xprop", ["-root", "_NET_CLIENT_LIST_STACKING"], {
+ timeout: 3000,
+ });
+ const ordered = parseStackingOrder(stdout).flatMap((id) => {
+ const source = byId.get(id);
+ return source ? [source] : [];
+ });
+ const windows: CapturePickerWindow[] = [];
+ // Bound the number of simultaneous X11 helper processes.
+ for (let offset = 0; offset < ordered.length; offset += 8) {
+ const batch = await Promise.all(
+ ordered.slice(offset, offset + 8).map(async (source) => {
+ const bounds = await resolveLinuxWindowBounds(source);
+ return bounds
+ ? {
+ ...bounds,
+ id: source.id,
+ appName: "",
+ title: source.name,
+ display_id: source.display_id,
+ }
+ : null;
+ }),
+ );
+ windows.push(
+ ...batch.filter((entry): entry is NonNullable<typeof entry> => entry !== null),
+ );
+ }
+ return windows;
+}
diff --git a/electron/ipc/register/capturePicker.test.ts b/electron/ipc/register/capturePicker.test.ts
new file mode 100644
index 00000000..380037b6
--- /dev/null
+++ b/electron/ipc/register/capturePicker.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ list: vi.fn(),
+ selected: vi.fn(),
+ create: vi.fn(),
+ close: vi.fn(),
+ overlay: {},
+ outsider: {},
+ windows: [] as object[],
+}));
+vi.mock("electron", () => ({
+ ipcMain: {
+ handle: (name: string, handler: (...args: unknown[]) => unknown) =>
+ mocks.handlers.set(name, handler),
+ },
+ BrowserWindow: { fromWebContents: (sender: unknown) => sender },
+}));
+vi.mock("../../windows", () => ({
+ createCapturePickerWindows: mocks.create,
+ closeCapturePickerWindows: mocks.close,
+ getCapturePickerWindows: () => mocks.windows,
+}));
+vi.mock("../capturePickerSources", () => ({ listCapturePickerWindows: mocks.list }));
+vi.mock("../cursor/bounds", () => ({ stopWindowBoundsCapture: vi.fn() }));
+vi.mock("../state", () => ({ setSelectedSource: mocks.selected }));
+vi.mock("../utils", () => ({
+ getScreen: () => ({
+ getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0, width: 1440, height: 1000 } }],
+ getPrimaryDisplay: () => ({ id: 1 }),
+ getCursorScreenPoint: () => ({ x: 0, y: 0 }),
+ }),
+}));
+vi.mock("./sources", () => ({
+ bringSelectedWindowForward: vi.fn(),
+ broadcastSelectedSourceChange: vi.fn(),
+ getDesktopSources: vi.fn().mockResolvedValue([{ id: "screen:1:0", display_id: "1" }]),
+}));
+import { registerCapturePickerHandlers } from "./capturePicker";
+const platform = process.platform;
+afterEach(() => {
+ Object.defineProperty(process, "platform", { value: platform });
+ vi.unstubAllEnvs();
+});
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.handlers.clear();
+ mocks.windows = [mocks.overlay];
+ Object.defineProperty(process, "platform", { value: "darwin" });
+ mocks.list.mockResolvedValue([]);
+ registerCapturePickerHandlers();
+});
+const call = (name: string, sender: object, input?: unknown) =>
+ mocks.handlers.get(name)!({ sender }, input);
+describe("selection-only picker IPC", () => {
+ it("ignores completion from other windows and forces selection-only completion", async () => {
+ const pending = call("pick-capture-target", mocks.outsider);
+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());
+ await call("complete-capture-pick", mocks.outsider, {
+ kind: "screen",
+ displayId: 1,
+ record: true,
+ });
+ expect(mocks.selected).not.toHaveBeenCalled();
+ await call("complete-capture-pick", mocks.overlay, {
+ kind: "screen",
+ displayId: 1,
+ record: true,
+ });
+ expect(await pending).toMatchObject({ success: true, source: { id: "screen:1:0" } });
+ expect(await pending).not.toHaveProperty("record");
+ });
+ it("coalesces simultaneous opens into one picker", async () => {
+ const first = call("pick-capture-target", mocks.outsider);
+ const second = call("pick-capture-target", mocks.outsider);
+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());
+ await call("complete-capture-pick", mocks.overlay, null);
+ expect(await first).toEqual({ success: false, canceled: true });
+ expect(await second).toEqual({ success: false, canceled: true });
+ });
+ it("keeps Wayland on the existing portal path without overlays or geometry probes", async () => {
+ Object.defineProperty(process, "platform", { value: "linux" });
+ vi.stubEnv("XDG_SESSION_TYPE", "wayland");
+ expect(await call("pick-capture-target", mocks.outsider)).toMatchObject({
+ success: true,
+ source: { id: "screen:linux-portal" },
+ });
+ expect(mocks.create).not.toHaveBeenCalled();
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+});
diff --git a/electron/ipc/register/capturePicker.ts b/electron/ipc/register/capturePicker.ts
index 236d7e55..c541172d 100644
--- a/electron/ipc/register/capturePicker.ts
+++ b/electron/ipc/register/capturePicker.ts
@@ -1,54 +1,40 @@
-import { ipcMain } from "electron";
-import { closeCapturePickerWindows, createCapturePickerWindows } from "../../windows";
-import { getNativeMacWindowsFrontToBack, stopWindowBoundsCapture } from "../cursor/bounds";
+import { listCapturePickerWindows } from "../capturePickerSources";
+import { BrowserWindow, ipcMain } from "electron";
+import {
+ closeCapturePickerWindows,
+ createCapturePickerWindows,
+ getCapturePickerWindows,
+} from "../../windows";
+import { stopWindowBoundsCapture } from "../cursor/bounds";
import { setSelectedSource } from "../state";
import { createAreaSource, createWindowSource, normalizeCapturePick } from "../sourceArea";
import type { AreaCapturePick, CapturePick, CapturePickerWindow, SelectedSource } from "../types";
import { getScreen } from "../utils";
-import { getScreenSourceIdForDisplay } from "./sourceMapping";
-import { bringSelectedWindowForward, broadcastSelectedSourceChange } from "./sources";
-
-/** Windows the picker can offer, front to back, without Recordly's own. */
-async function listPickableWindows(): Promise<CapturePickerWindow[]> {
- const entries = await getNativeMacWindowsFrontToBack();
- return entries.flatMap((entry) => {
- const { x, y, width, height } = entry;
- if (
- entry.ownerPid === process.pid ||
- typeof x !== "number" ||
- typeof y !== "number" ||
- typeof width !== "number" ||
- typeof height !== "number" ||
- width <= 0 ||
- height <= 0
- ) {
- return [];
- }
- return [
- {
- id: entry.id,
- appName: entry.appName ?? "",
- title: entry.windowTitle ?? entry.name,
- display_id: entry.display_id,
- x,
- y,
- width,
- height,
- },
- ];
- });
-}
+import { getScreenSourceIdForDisplay, isLikelyLinuxWaylandSession } from "./sourceMapping";
+import {
+ bringSelectedWindowForward,
+ broadcastSelectedSourceChange,
+ getDesktopSources,
+} from "./sources";
/** The same source the screen list offers for this display. */
-function createScreenSource(displayId: number): SelectedSource | null {
+async function createScreenSource(displayId: number): Promise<SelectedSource | null> {
const displays = getScreen().getAllDisplays();
const index = displays.findIndex((display) => display.id === displayId);
if (index < 0) return null;
+ const sources = await getDesktopSources({
+ types: ["screen"],
+ thumbnailSize: { width: 0, height: 0 },
+ });
+ const matched =
+ sources.find((source) => source.display_id === String(displayId)) ??
+ (sources.length === displays.length ? sources[index] : undefined);
const isPrimary = getScreen().getPrimaryDisplay().id === displayId;
return {
id: getScreenSourceIdForDisplay({
displayId: String(displayId),
platform: process.platform,
+ matchedSourceId: matched?.id,
}),
name: isPrimary ? `Screen ${index + 1} (Primary)` : `Screen ${index + 1}`,
display_id: String(displayId),
@@ -72,14 +58,28 @@ export function registerCapturePickerHandlers() {
resolve?.(pick);
};
- ipcMain.handle("pick-capture-target", async () => {
- if (process.platform !== "darwin") {
- return { success: false, message: "Picking on screen is available on macOS." };
+ let activePick: Promise<unknown> | null = null;
+ const pickTarget = async () => {
+ if (process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)) {
+ // Preserve the existing portal recording path: its system picker opens
+ // when recording starts; overlay selection cannot identify Wayland windows.
+ const source = {
+ id: "screen:linux-portal",
+ name: "System picker",
+ sourceType: "screen" as const,
+ };
+ setSelectedSource(source);
+ broadcastSelectedSourceChange();
+ return {
+ success: true,
+ source,
+ message: "Choose a screen or window in the system picker when you start recording.",
+ };
}
finishPick(null);
// List windows before the overlays cover them.
- pickableWindows = listPickableWindows();
+ pickableWindows = Promise.resolve(await listCapturePickerWindows());
const pick = await new Promise<CapturePick | null>((resolve) => {
resolvePendingPick = resolve;
// Closing an overlay without confirming cancels the pick.
@@ -98,7 +98,7 @@ export function registerCapturePickerHandlers() {
const window = (await pickableWindows).find((entry) => entry.id === pick.windowId);
source = window ? createWindowSource(window) : null;
} else {
- source = createScreenSource(pick.displayId);
+ source = await createScreenSource(pick.displayId);
}
if (!source) {
return { success: false, message: "That window or screen is no longer available." };
@@ -112,10 +112,39 @@ export function registerCapturePickerHandlers() {
setSelectedSource(source);
broadcastSelectedSourceChange();
stopWindowBoundsCapture();
- return { success: true, source, record: pick.record };
+ return { success: true, source };
+ };
+ ipcMain.handle("pick-capture-target", () => {
+ if (!activePick) {
+ activePick = pickTarget()
+ .catch((error) => {
+ finishPick(null);
+ closeCapturePickerWindows();
+ return {
+ success: false,
+ message:
+ error instanceof Error
+ ? error.message
+ : "Unable to open the source picker.",
+ };
+ })
+ .finally(() => {
+ activePick = null;
+ });
+ }
+ return activePick;
});
- ipcMain.handle("complete-capture-pick", async (_, input: unknown) => {
+ ipcMain.handle("complete-capture-pick", async (event, input: unknown) => {
+ if (!getCapturePickerWindows().includes(BrowserWindow.fromWebContents(event.sender)!))
+ return;
+ if (
+ input &&
+ typeof input === "object" &&
+ (input as { kind?: unknown }).kind === "area" &&
+ process.platform !== "darwin"
+ )
+ return;
if (!input) {
finishPick(null);
return;
@@ -123,15 +152,29 @@ export function registerCapturePickerHandlers() {
const displays = getScreen()
.getAllDisplays()
.map((display) => ({ id: display.id, bounds: display.bounds }));
- finishPick(normalizeCapturePick(input, displays, await pickableWindows));
+ finishPick(
+ normalizeCapturePick(
+ input && typeof input === "object" ? { ...input, record: false } : input,
+ displays,
+ await pickableWindows,
+ ),
+ );
});
- ipcMain.handle("get-capture-picker-context", async (_, displayId: unknown) => {
+ ipcMain.handle("get-capture-picker-context", async (event, displayId: unknown) => {
+ if (!getCapturePickerWindows().includes(BrowserWindow.fromWebContents(event.sender)!))
+ throw new Error("Unknown picker window.");
const display = getScreen()
.getAllDisplays()
.find((entry) => entry.id === Number(displayId));
if (!display) {
- return { displayBounds: null, lastArea: null, windows: [], cursor: null };
+ return {
+ displayBounds: null,
+ lastArea: null,
+ allowArea: process.platform === "darwin",
+ windows: [],
+ cursor: null,
+ };
}
const { x, y, width, height } = display.bounds;
const windows = (await pickableWindows).filter(
@@ -144,6 +187,7 @@ export function registerCapturePickerHandlers() {
const previous = lastArea?.displayId === display.id ? lastArea : null;
return {
displayBounds: display.bounds,
+ allowArea: process.platform === "darwin",
lastArea: previous
? { x: previous.x, y: previous.y, width: previous.width, height: previous.height }
: null,
diff --git a/electron/ipc/register/sources.ts b/electron/ipc/register/sources.ts
index bf80a5a2..38ec0ccd 100644
--- a/electron/ipc/register/sources.ts
+++ b/electron/ipc/register/sources.ts
@@ -28,7 +28,7 @@ const SOURCE_LIST_CACHE_TTL_MS = 1200;
let sourceListCache: {
key: string;
expiresAt: number;
- value: Array<Record<string, unknown>>;
+ value: SelectedSource[];
} | null = null;
function normalizeDesktopSourceName(value: string) {
@@ -117,277 +117,276 @@ export async function bringSelectedWindowForward(
return null;
}
-export function registerSourceHandlers({
- createEditorWindow,
- createSourceSelectorWindow,
- getSourceSelectorWindow,
-}: {
- createEditorWindow: () => void;
- createSourceSelectorWindow: () => BrowserWindow;
- getSourceSelectorWindow: () => BrowserWindow | null;
-}) {
- const recordingNavigation = createRecordingEditorNavigation(createEditorWindow);
- ipcMain.handle("get-sources", async (_, opts) => {
- const cacheKey = JSON.stringify({
- types: opts?.types,
- thumbnailSize: opts?.thumbnailSize,
- fetchWindowIcons: opts?.fetchWindowIcons,
- });
- if (
- sourceListCache &&
- sourceListCache.key === cacheKey &&
- sourceListCache.expiresAt > Date.now()
- ) {
- return sourceListCache.value;
- }
+export async function getDesktopSources(opts?: Electron.SourcesOptions): Promise<SelectedSource[]> {
+ const cacheKey = JSON.stringify({
+ types: opts?.types,
+ thumbnailSize: opts?.thumbnailSize,
+ fetchWindowIcons: opts?.fetchWindowIcons,
+ });
+ if (
+ sourceListCache &&
+ sourceListCache.key === cacheKey &&
+ sourceListCache.expiresAt > Date.now()
+ ) {
+ return sourceListCache.value;
+ }
- const includeScreens = Array.isArray(opts?.types) ? opts.types.includes("screen") : true;
- const includeWindows = Array.isArray(opts?.types) ? opts.types.includes("window") : true;
- const includeWindowIcons = Boolean(opts?.fetchWindowIcons);
- const electronTypes = [
- ...(includeScreens ? ["screen" as const] : []),
- ...(includeWindows ? ["window" as const] : []),
- ];
- const electronSources =
- electronTypes.length > 0
- ? await desktopCapturer
- .getSources({
- ...opts,
- types: electronTypes,
- })
- .catch((error) => {
- console.warn(
- "desktopCapturer.getSources failed (screen recording permission may be missing):",
- error,
- );
- return [];
- })
- : [];
- const ownWindowNames = new Set(
- [
- app.getName(),
- "Recordly",
- ...BrowserWindow.getAllWindows().flatMap((win) => {
- const title = win.getTitle().trim();
- return title ? [title] : [];
- }),
- ]
- .map((name) => normalizeDesktopSourceName(name))
- .filter(Boolean),
- );
- const ownAppName = normalizeDesktopSourceName(app.getName());
-
- const displays = includeScreens
- ? [...getScreen().getAllDisplays()].sort(
- (left, right) =>
- left.bounds.x - right.bounds.x ||
- left.bounds.y - right.bounds.y ||
- left.id - right.id,
- )
+ const includeScreens = Array.isArray(opts?.types) ? opts.types.includes("screen") : true;
+ const includeWindows = Array.isArray(opts?.types) ? opts.types.includes("window") : true;
+ const includeWindowIcons = Boolean(opts?.fetchWindowIcons);
+ const electronTypes = [
+ ...(includeScreens ? ["screen" as const] : []),
+ ...(includeWindows ? ["window" as const] : []),
+ ];
+ const electronSources =
+ electronTypes.length > 0
+ ? await desktopCapturer
+ .getSources({
+ ...opts,
+ types: electronTypes,
+ })
+ .catch((error) => {
+ console.warn(
+ "desktopCapturer.getSources failed (screen recording permission may be missing):",
+ error,
+ );
+ return [];
+ })
: [];
- const primaryDisplayId = includeScreens ? String(getScreen().getPrimaryDisplay().id) : "";
- const electronScreenSourcesByDisplayId = new Map(
- electronSources
- .filter((source) => source.id.startsWith("screen:"))
- .map((source) => [String(source.display_id ?? ""), source] as const),
- );
- // On Linux, desktopCapturer display_id values may not match screen.getAllDisplays() IDs.
- // Keep an ordered list so we can fall back to position-based matching.
- const electronScreenSourcesByIndex = electronSources.filter((source) =>
- source.id.startsWith("screen:"),
- );
-
- const screenSources = displays.map((display, index) => {
- const displayId = String(display.id);
- const matchedSource =
- electronScreenSourcesByDisplayId.get(displayId) ??
- (electronScreenSourcesByIndex.length === displays.length
- ? electronScreenSourcesByIndex[index]
- : undefined);
- const displayName =
- displayId === primaryDisplayId
- ? `Screen ${index + 1} (Primary)`
- : `Screen ${index + 1}`;
-
- return {
- id: getScreenSourceIdForDisplay({
- displayId,
- env: process.env,
- matchedSourceId: matchedSource?.id,
- platform: process.platform,
- }),
- name: displayName,
- originalName: matchedSource?.name ?? displayName,
- display_id: displayId,
- thumbnail: matchedSource?.thumbnail ? matchedSource.thumbnail.toDataURL() : null,
- appIcon: null,
- sourceType: "screen" as const,
- };
- });
-
- if (process.platform !== "darwin" || !includeWindows) {
- const windowSources = electronSources
- .filter((source) => source.id.startsWith("window:"))
- .filter((source) => {
- const normalizedName = normalizeDesktopSourceName(source.name);
- if (!normalizedName) {
- return true;
- }
-
- if (ALLOW_RECORDLY_WINDOW_CAPTURE && normalizedName.includes("recordly")) {
- return true;
- }
-
- for (const ownName of ownWindowNames) {
- if (!ownName) continue;
- if (normalizedName === ownName) {
- return false;
- }
- }
+ const ownWindowNames = new Set(
+ [
+ app.getName(),
+ "Recordly",
+ ...BrowserWindow.getAllWindows().flatMap((win) => {
+ const title = win.getTitle().trim();
+ return title ? [title] : [];
+ }),
+ ]
+ .map((name) => normalizeDesktopSourceName(name))
+ .filter(Boolean),
+ );
+ const ownAppName = normalizeDesktopSourceName(app.getName());
+
+ const displays = includeScreens
+ ? [...getScreen().getAllDisplays()].sort(
+ (left, right) =>
+ left.bounds.x - right.bounds.x ||
+ left.bounds.y - right.bounds.y ||
+ left.id - right.id,
+ )
+ : [];
+ const primaryDisplayId = includeScreens ? String(getScreen().getPrimaryDisplay().id) : "";
+ const electronScreenSourcesByDisplayId = new Map(
+ electronSources
+ .filter((source) => source.id.startsWith("screen:"))
+ .map((source) => [String(source.display_id ?? ""), source] as const),
+ );
+ // On Linux, desktopCapturer display_id values may not match screen.getAllDisplays() IDs.
+ // Keep an ordered list so we can fall back to position-based matching.
+ const electronScreenSourcesByIndex = electronSources.filter((source) =>
+ source.id.startsWith("screen:"),
+ );
+
+ const screenSources = displays.map((display, index) => {
+ const displayId = String(display.id);
+ const matchedSource =
+ electronScreenSourcesByDisplayId.get(displayId) ??
+ (electronScreenSourcesByIndex.length === displays.length
+ ? electronScreenSourcesByIndex[index]
+ : undefined);
+ const displayName =
+ displayId === primaryDisplayId
+ ? `Screen ${index + 1} (Primary)`
+ : `Screen ${index + 1}`;
+
+ return {
+ id: getScreenSourceIdForDisplay({
+ displayId,
+ env: process.env,
+ matchedSourceId: matchedSource?.id,
+ platform: process.platform,
+ }),
+ name: displayName,
+ originalName: matchedSource?.name ?? displayName,
+ display_id: displayId,
+ thumbnail: matchedSource?.thumbnail ? matchedSource.thumbnail.toDataURL() : null,
+ appIcon: null,
+ sourceType: "screen" as const,
+ };
+ });
+ if (process.platform !== "darwin" || !includeWindows) {
+ const windowSources = electronSources
+ .filter((source) => source.id.startsWith("window:"))
+ .filter((source) => {
+ const normalizedName = normalizeDesktopSourceName(source.name);
+ if (!normalizedName) {
return true;
- })
- .map((source) => ({
- id: source.id,
- name: source.name,
- originalName: source.name,
- display_id: source.display_id,
- thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : null,
- appIcon:
- includeWindowIcons && source.appIcon ? source.appIcon.toDataURL() : null,
- sourceType: "window" as const,
- }));
- const result = [...screenSources, ...windowSources];
- sourceListCache = {
- key: cacheKey,
- expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
- value: result,
- };
- return result;
- }
+ }
- try {
- const nativeWindowSources = await getNativeMacWindowSources();
- const electronWindowSourceMap = new Map(
- electronSources
- .filter((source) => source.id.startsWith("window:"))
- .map((source) => [source.id, source] as const),
- );
-
- const mergedWindowSources = nativeWindowSources
- .filter((source) => {
- const normalizedWindowName = normalizeDesktopSourceName(
- source.windowTitle ?? source.name,
- );
- const normalizedAppName = normalizeDesktopSourceName(source.appName ?? "");
+ if (ALLOW_RECORDLY_WINDOW_CAPTURE && normalizedName.includes("recordly")) {
+ return true;
+ }
- if (
- !ALLOW_RECORDLY_WINDOW_CAPTURE &&
- normalizedAppName &&
- normalizedAppName === ownAppName
- ) {
+ for (const ownName of ownWindowNames) {
+ if (!ownName) continue;
+ if (normalizedName === ownName) {
return false;
}
+ }
- if (
- ALLOW_RECORDLY_WINDOW_CAPTURE &&
- (normalizedAppName === "recordly" ||
- normalizedWindowName?.includes("recordly"))
- ) {
- return true;
- }
+ return true;
+ })
+ .map((source) => ({
+ id: source.id,
+ name: source.name,
+ originalName: source.name,
+ display_id: source.display_id,
+ thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : null,
+ appIcon: includeWindowIcons && source.appIcon ? source.appIcon.toDataURL() : null,
+ sourceType: "window" as const,
+ }));
+ const result = [...screenSources, ...windowSources];
+ sourceListCache = {
+ key: cacheKey,
+ expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
+ value: result,
+ };
+ return result;
+ }
- if (!normalizedWindowName) {
- return true;
- }
+ try {
+ const nativeWindowSources = await getNativeMacWindowSources();
+ const electronWindowSourceMap = new Map(
+ electronSources
+ .filter((source) => source.id.startsWith("window:"))
+ .map((source) => [source.id, source] as const),
+ );
- for (const ownName of ownWindowNames) {
- if (!ownName) continue;
- if (normalizedWindowName === ownName) {
- return false;
- }
- }
+ const mergedWindowSources = nativeWindowSources
+ .filter((source) => {
+ const normalizedWindowName = normalizeDesktopSourceName(
+ source.windowTitle ?? source.name,
+ );
+ const normalizedAppName = normalizeDesktopSourceName(source.appName ?? "");
+
+ if (
+ !ALLOW_RECORDLY_WINDOW_CAPTURE &&
+ normalizedAppName &&
+ normalizedAppName === ownAppName
+ ) {
+ return false;
+ }
+ if (
+ ALLOW_RECORDLY_WINDOW_CAPTURE &&
+ (normalizedAppName === "recordly" || normalizedWindowName?.includes("recordly"))
+ ) {
return true;
- })
- .map((source) => {
- const electronWindowSource = electronWindowSourceMap.get(source.id);
- return {
- id: source.id,
- name: source.name,
- originalName: source.name,
- display_id: source.display_id ?? electronWindowSource?.display_id ?? "",
- thumbnail: electronWindowSource?.thumbnail
- ? electronWindowSource.thumbnail.toDataURL()
- : null,
- appIcon: includeWindowIcons
- ? (source.appIcon ??
- (electronWindowSource?.appIcon
- ? electronWindowSource.appIcon.toDataURL()
- : null))
- : null,
- appName: source.appName,
- windowTitle: source.windowTitle,
- bundleId: source.bundleId,
- sourceType: "window" as const,
- };
- });
-
- const result = [...screenSources, ...mergedWindowSources];
- sourceListCache = {
- key: cacheKey,
- expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
- value: result,
- };
- return result;
- } catch (error) {
- console.warn("Falling back to Electron window enumeration on macOS:", error);
-
- const windowSources = electronSources
- .filter((source) => source.id.startsWith("window:"))
- .filter((source) => {
- const normalizedName = normalizeDesktopSourceName(source.name);
- if (!normalizedName) {
- return true;
- }
+ }
- if (ALLOW_RECORDLY_WINDOW_CAPTURE && normalizedName.includes("recordly")) {
- return true;
- }
+ if (!normalizedWindowName) {
+ return true;
+ }
- for (const ownName of ownWindowNames) {
- if (!ownName) continue;
- if (
- normalizedName === ownName ||
- normalizedName.includes(ownName) ||
- ownName.includes(normalizedName)
- ) {
- return false;
- }
+ for (const ownName of ownWindowNames) {
+ if (!ownName) continue;
+ if (normalizedWindowName === ownName) {
+ return false;
}
+ }
- return true;
- })
- .map((source) => ({
+ return true;
+ })
+ .map((source) => {
+ const electronWindowSource = electronWindowSourceMap.get(source.id);
+ return {
id: source.id,
name: source.name,
originalName: source.name,
- display_id: source.display_id,
- thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : null,
- appIcon:
- includeWindowIcons && source.appIcon ? source.appIcon.toDataURL() : null,
+ display_id: source.display_id ?? electronWindowSource?.display_id ?? "",
+ thumbnail: electronWindowSource?.thumbnail
+ ? electronWindowSource.thumbnail.toDataURL()
+ : null,
+ appIcon: includeWindowIcons
+ ? (source.appIcon ??
+ (electronWindowSource?.appIcon
+ ? electronWindowSource.appIcon.toDataURL()
+ : null))
+ : null,
+ appName: source.appName,
+ windowTitle: source.windowTitle,
+ bundleId: source.bundleId,
sourceType: "window" as const,
- }));
-
- const result = [...screenSources, ...windowSources];
- sourceListCache = {
- key: cacheKey,
- expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
- value: result,
- };
- return result;
- }
- });
+ };
+ });
+
+ const result = [...screenSources, ...mergedWindowSources];
+ sourceListCache = {
+ key: cacheKey,
+ expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
+ value: result,
+ };
+ return result;
+ } catch (error) {
+ console.warn("Falling back to Electron window enumeration on macOS:", error);
+
+ const windowSources = electronSources
+ .filter((source) => source.id.startsWith("window:"))
+ .filter((source) => {
+ const normalizedName = normalizeDesktopSourceName(source.name);
+ if (!normalizedName) {
+ return true;
+ }
+
+ if (ALLOW_RECORDLY_WINDOW_CAPTURE && normalizedName.includes("recordly")) {
+ return true;
+ }
+
+ for (const ownName of ownWindowNames) {
+ if (!ownName) continue;
+ if (
+ normalizedName === ownName ||
+ normalizedName.includes(ownName) ||
+ ownName.includes(normalizedName)
+ ) {
+ return false;
+ }
+ }
+
+ return true;
+ })
+ .map((source) => ({
+ id: source.id,
+ name: source.name,
+ originalName: source.name,
+ display_id: source.display_id,
+ thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : null,
+ appIcon: includeWindowIcons && source.appIcon ? source.appIcon.toDataURL() : null,
+ sourceType: "window" as const,
+ }));
+
+ const result = [...screenSources, ...windowSources];
+ sourceListCache = {
+ key: cacheKey,
+ expiresAt: Date.now() + SOURCE_LIST_CACHE_TTL_MS,
+ value: result,
+ };
+ return result;
+ }
+}
+
+export function registerSourceHandlers({
+ createEditorWindow,
+ createSourceSelectorWindow,
+ getSourceSelectorWindow,
+}: {
+ createEditorWindow: () => void;
+ createSourceSelectorWindow: () => BrowserWindow;
+ getSourceSelectorWindow: () => BrowserWindow | null;
+}) {
+ const recordingNavigation = createRecordingEditorNavigation(createEditorWindow);
+ ipcMain.handle("get-sources", (_, opts) => getDesktopSources(opts));
ipcMain.handle("select-source", async (_, source: SelectedSource) => {
if (source.id?.startsWith("window:")) {
diff --git a/electron/windows.ts b/electron/windows.ts
index 1b60bd11..6e3ab99d 100644
--- a/electron/windows.ts
+++ b/electron/windows.ts
@@ -1253,6 +1253,10 @@ export function createCapturePickerWindows(onClosed: () => void): BrowserWindow[
return capturePickerWindows;
}
+export function getCapturePickerWindows(): BrowserWindow[] {
+ return [...capturePickerWindows];
+}
+
export function closeCapturePickerWindows(): void {
const windows = capturePickerWindows;
capturePickerWindows = [];
diff --git a/src/components/capture-picker/CapturePicker.tsx b/src/components/capture-picker/CapturePicker.tsx
index ec7f6195..cc23f2b6 100644
--- a/src/components/capture-picker/CapturePicker.tsx
+++ b/src/components/capture-picker/CapturePicker.tsx
@@ -1,443 +1,217 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import type { CSSProperties, PointerEvent as ReactPointerEvent } from "react";
-import { useScopedT } from "@/contexts/I18nContext";
-import {
- AREA_HANDLES,
- type AreaHandle,
- type AreaRect,
- frontmostAt,
- MIN_AREA_SIZE,
- moveAreaRect,
- normalizeAreaRect,
- rectContains,
- resizeAreaRect,
-} from "./areaGeometry";
+import type { PointerEvent as ReactPointerEvent } from "react";
+import { frontmostAt, MIN_AREA_SIZE, normalizeAreaRect, type AreaRect } from "./areaGeometry";
-type PickerWindow = { window: CapturePickerWindow; rect: AreaRect };
-
-/** Something a click picks: the window under the cursor, or the whole screen. */
type Target =
| { kind: "window"; window: CapturePickerWindow; rect: AreaRect }
- | { kind: "screen"; rect: AreaRect };
-
-type Selection = Target | { kind: "area"; rect: AreaRect };
-
-type Drag =
- | { kind: "press"; startX: number; startY: number }
- | { kind: "draw"; originX: number; originY: number }
- | { kind: "move"; startX: number; startY: number; rect: AreaRect }
- | { kind: "resize"; handle: AreaHandle; startX: number; startY: number; rect: AreaRect };
-
-const TOOLBAR_HEIGHT = 44;
-const TOOLBAR_GAP = 12;
-/** A press that travels this far draws an area instead of clicking. */
-const DRAG_THRESHOLD = 4;
-const DIM = "rgba(0,0,0,0.38)";
-const HIGHLIGHT = "rgba(10,132,255,0.95)";
-
-const HANDLE_POSITIONS: Record<AreaHandle, { left: string; top: string; cursor: string }> = {
- nw: { left: "0%", top: "0%", cursor: "nwse-resize" },
- n: { left: "50%", top: "0%", cursor: "ns-resize" },
- ne: { left: "100%", top: "0%", cursor: "nesw-resize" },
- e: { left: "100%", top: "50%", cursor: "ew-resize" },
- se: { left: "100%", top: "100%", cursor: "nwse-resize" },
- s: { left: "50%", top: "100%", cursor: "ns-resize" },
- sw: { left: "0%", top: "100%", cursor: "nesw-resize" },
- w: { left: "0%", top: "50%", cursor: "ew-resize" },
-};
+ | { kind: "screen"; rect: AreaRect }
+ | { kind: "area"; rect: AreaRect };
-function viewport() {
- return { width: window.innerWidth, height: window.innerHeight };
+function screenRect() {
+ return { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight };
}
-function screenRect(): AreaRect {
- return { x: 0, y: 0, ...viewport() };
-}
-
-/** Converts a global rectangle to this overlay's coordinates, clipped to it. */
-function toLocal(rect: CaptureArea): AreaRect {
- return normalizeAreaRect(
- {
- x: rect.x - window.screenX,
- y: rect.y - window.screenY,
- width: rect.width,
- height: rect.height,
- },
- viewport(),
- );
-}
-
-function sizeLabel(rect: AreaRect) {
- return `${Math.round(rect.width)} × ${Math.round(rect.height)}`;
-}
-
-/**
- * Full-display overlay for picking what to record, one per display. Hovering
- * highlights the window under the cursor; a click picks it, or the whole screen
- * over the desktop; a drag draws an area. Moving or resizing a pick turns it into
- * an area. Enter or double-click records, Escape cancels.
- */
+/** Chooses a source only. Recording remains controlled by the existing HUD. */
export function CapturePicker() {
- const t = useScopedT("launch");
- const [displayId] = useState(() =>
- Number(new URLSearchParams(window.location.search).get("displayId")),
- );
- const [selection, setSelection] = useState<Selection | null>(null);
- const [hover, setHover] = useState<Target | null>(null);
- const [dragging, setDragging] = useState(false);
- const dragRef = useRef<Drag | null>(null);
- const selectionRef = useRef<Selection | null>(null);
- selectionRef.current = selection;
- const windowsRef = useRef<PickerWindow[]>([]);
-
+ const displayId = Number(new URLSearchParams(window.location.search).get("displayId"));
+ const [target, setTarget] = useState<Target | null>(null);
+ const [allowArea, setAllowArea] = useState(false);
+ const windows = useRef<{ window: CapturePickerWindow; rect: AreaRect }[]>([]);
+ const origin = useRef({ x: window.screenX, y: window.screenY });
+ const current = useRef<Target | null>(null);
+ const press = useRef<{ x: number; y: number; drawing: boolean } | null>(null);
+ const completed = useRef(false);
const targetAt = useCallback((x: number, y: number): Target => {
- const hit = frontmostAt(windowsRef.current, x, y);
+ const hit = frontmostAt(windows.current, x, y);
return hit
? { kind: "window", window: hit.window, rect: hit.rect }
: { kind: "screen", rect: screenRect() };
}, []);
-
- useEffect(() => {
- let cancelled = false;
- // Reveal the window only after a frame with the picker's real state.
- const reveal = () =>
- requestAnimationFrame(() =>
- requestAnimationFrame(() => window.electronAPI.capturePickerReady()),
+ const update = (next: Target) => {
+ current.current = next;
+ setTarget(next);
+ };
+ const finish = useCallback(
+ (pick: Target | null) => {
+ if (completed.current) return;
+ if (
+ pick?.kind === "area" &&
+ (pick.rect.width < MIN_AREA_SIZE || pick.rect.height < MIN_AREA_SIZE)
+ )
+ return;
+ completed.current = true;
+ const common = { displayId, record: false };
+ void window.electronAPI.completeCapturePick(
+ !pick
+ ? null
+ : pick.kind === "window"
+ ? { ...common, kind: "window", windowId: pick.window.id }
+ : pick.kind === "screen"
+ ? { ...common, kind: "screen" }
+ : {
+ ...common,
+ kind: "area",
+ ...pick.rect,
+ x: origin.current.x + pick.rect.x,
+ y: origin.current.y + pick.rect.y,
+ },
);
- window.electronAPI
+ },
+ [displayId],
+ );
+ useEffect(() => {
+ let disposed = false;
+ void window.electronAPI
.getCapturePickerContext(displayId)
.then((context) => {
- if (cancelled) return;
- windowsRef.current = context.windows
- .map((entry) => ({ window: entry, rect: toLocal(entry) }))
+ if (disposed) return;
+ if (context.displayBounds) origin.current = context.displayBounds;
+ setAllowArea(context.allowArea === true);
+ windows.current = context.windows
+ .map((entry) => ({
+ window: entry,
+ rect: normalizeAreaRect(
+ {
+ ...entry,
+ x: entry.x - origin.current.x,
+ y: entry.y - origin.current.y,
+ },
+ screenRect(),
+ ),
+ }))
.filter((entry) => entry.rect.width > 0 && entry.rect.height > 0);
- if (context.lastArea && !selectionRef.current) {
- setSelection({ kind: "area", rect: toLocal(context.lastArea) });
- } else if (context.cursor) {
- const x = context.cursor.x - window.screenX;
- const y = context.cursor.y - window.screenY;
- if (rectContains(screenRect(), x, y)) setHover(targetAt(x, y));
- }
+ const next =
+ context.lastArea && context.allowArea
+ ? {
+ kind: "area" as const,
+ rect: normalizeAreaRect(
+ {
+ ...context.lastArea,
+ x: context.lastArea.x - origin.current.x,
+ y: context.lastArea.y - origin.current.y,
+ },
+ screenRect(),
+ ),
+ }
+ : context.cursor
+ ? targetAt(
+ context.cursor.x - origin.current.x,
+ context.cursor.y - origin.current.y,
+ )
+ : null;
+ current.current = next;
+ setTarget(next);
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ if (!disposed) window.electronAPI.capturePickerReady();
+ }),
+ );
})
- .finally(reveal);
+ .catch(() => {
+ if (!disposed) finish(null);
+ });
return () => {
- cancelled = true;
+ disposed = true;
};
- }, [displayId, targetAt]);
-
- const finish = useCallback(
- (record: boolean | null) => {
- const current = selectionRef.current;
- if (record === null || !current) {
- void window.electronAPI.completeCapturePick(null);
- return;
- }
- if (current.kind === "window") {
- void window.electronAPI.completeCapturePick({
- kind: "window",
- windowId: current.window.id,
- displayId,
- record,
- });
- return;
- }
- if (current.kind === "screen") {
- void window.electronAPI.completeCapturePick({ kind: "screen", displayId, record });
- return;
- }
- const { rect } = current;
- if (rect.width < MIN_AREA_SIZE || rect.height < MIN_AREA_SIZE) return;
- void window.electronAPI.completeCapturePick({
- kind: "area",
- x: window.screenX + rect.x,
- y: window.screenY + rect.y,
- width: rect.width,
- height: rect.height,
- displayId,
- record,
- });
- },
- [displayId],
- );
-
+ }, [displayId, targetAt, finish]);
useEffect(() => {
- const onKeyDown = (event: KeyboardEvent) => {
+ const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
finish(null);
- } else if (event.key === "Enter") {
+ }
+ if (event.key === "Enter") {
event.preventDefault();
- finish(true);
+ if (current.current) finish(current.current);
}
};
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
}, [finish]);
-
- const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
- if (event.button !== 0) return;
- const target = event.target as HTMLElement;
- if (target.closest("[data-picker-toolbar]")) return;
- event.currentTarget.setPointerCapture(event.pointerId);
- const handle = target.closest<HTMLElement>("[data-picker-handle]")?.dataset.pickerHandle as
- | AreaHandle
- | undefined;
- const current = selectionRef.current;
- if (handle && current) {
- dragRef.current = {
- kind: "resize",
- handle,
- startX: event.clientX,
- startY: event.clientY,
- rect: current.rect,
- };
- } else if (current && rectContains(current.rect, event.clientX, event.clientY)) {
- dragRef.current = {
- kind: "move",
- startX: event.clientX,
- startY: event.clientY,
- rect: current.rect,
- };
- } else {
- dragRef.current = { kind: "press", startX: event.clientX, startY: event.clientY };
- }
- };
-
- const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
- const drag = dragRef.current;
- const bounds = viewport();
- if (!drag) {
- const current = selectionRef.current;
- setHover(
- current && rectContains(current.rect, event.clientX, event.clientY)
- ? null
- : targetAt(event.clientX, event.clientY),
- );
- return;
- }
-
- if (drag.kind === "press") {
- const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
- if (distance < DRAG_THRESHOLD) return;
- dragRef.current = { kind: "draw", originX: drag.startX, originY: drag.startY };
- setHover(null);
- }
-
- const active = dragRef.current;
- if (!active || active.kind === "press") return;
- if (active.kind === "draw") {
- setDragging(true);
- setSelection({
+ const onMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const start = press.current;
+ if (
+ start &&
+ allowArea &&
+ (start.drawing || Math.hypot(event.clientX - start.x, event.clientY - start.y) >= 4)
+ ) {
+ start.drawing = true;
+ update({
kind: "area",
rect: normalizeAreaRect(
{
- x: active.originX,
- y: active.originY,
- width: event.clientX - active.originX,
- height: event.clientY - active.originY,
+ x: start.x,
+ y: start.y,
+ width: event.clientX - start.x,
+ height: event.clientY - start.y,
},
- bounds,
+ screenRect(),
),
});
- return;
- }
-
- const dx = event.clientX - active.startX;
- const dy = event.clientY - active.startY;
- // A click inside a picked window keeps it; only real movement turns it into an area.
- if (!dragging && Math.hypot(dx, dy) < DRAG_THRESHOLD / 2) return;
- setDragging(true);
- setSelection({
- kind: "area",
- rect:
- active.kind === "move"
- ? moveAreaRect(active.rect, dx, dy, bounds)
- : resizeAreaRect(active.rect, active.handle, dx, dy, bounds),
- });
- };
-
- const handlePointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {
- if (event.currentTarget.hasPointerCapture(event.pointerId)) {
- event.currentTarget.releasePointerCapture(event.pointerId);
- }
- const drag = dragRef.current;
- dragRef.current = null;
- setDragging(false);
- if (drag?.kind === "press") {
- // A click picks the window under the cursor, or the screen over the desktop.
- setSelection(targetAt(drag.startX, drag.startY));
- setHover(null);
- return;
- }
- const current = selectionRef.current;
- if (
- drag?.kind === "draw" &&
- current &&
- (current.rect.width < DRAG_THRESHOLD || current.rect.height < DRAG_THRESHOLD)
- ) {
- setSelection(null);
- }
+ } else if (!start) update(targetAt(event.clientX, event.clientY));
};
-
- const describe = (pick: Selection) =>
- pick.kind === "window"
- ? [pick.window.appName, pick.window.title].filter(Boolean).join(" — ")
- : pick.kind === "screen"
- ? t("capturePicker.entireScreen", "Entire screen")
- : "";
-
- const tooSmall =
- selection?.kind === "area" &&
- (selection.rect.width < MIN_AREA_SIZE || selection.rect.height < MIN_AREA_SIZE);
- const rect = selection?.rect ?? null;
- const toolbarTop = rect
- ? rect.y + rect.height + TOOLBAR_GAP + TOOLBAR_HEIGHT <= window.innerHeight
- ? rect.y + rect.height + TOOLBAR_GAP
- : rect.y - TOOLBAR_GAP - TOOLBAR_HEIGHT >= 0
- ? rect.y - TOOLBAR_GAP - TOOLBAR_HEIGHT
- : rect.y + rect.height - TOOLBAR_HEIGHT - TOOLBAR_GAP
- : 0;
- const placeLabel = (target: AreaRect): CSSProperties =>
- target.y >= 30 ? { top: -26, left: 0 } : { top: 6, left: 6 };
-
+ const label =
+ target?.kind === "window"
+ ? [target.window.appName, target.window.title].filter(Boolean).join(" — ")
+ : target?.kind === "screen"
+ ? "Entire screen"
+ : "Area";
return (
<div
className="fixed inset-0 select-none overflow-hidden"
- style={{
- cursor: "crosshair",
- background: selection || hover ? "transparent" : DIM,
+ style={{ cursor: "crosshair", background: target ? "transparent" : "rgba(0,0,0,0.38)" }}
+ onPointerMove={onMove}
+ onPointerDown={(event) => {
+ if (event.button !== 0) return;
+ press.current = { x: event.clientX, y: event.clientY, drawing: false };
+ event.currentTarget.setPointerCapture(event.pointerId);
}}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerUp}
- onPointerLeave={() => {
- if (!dragRef.current) setHover(null);
+ onPointerUp={(event) => {
+ if (event.button !== 0 || !press.current) return;
+ const start = press.current;
+ press.current = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId))
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ finish(start.drawing ? current.current : targetAt(event.clientX, event.clientY));
}}
- onDoubleClick={(event) => {
- const current = selectionRef.current;
- if (current && rectContains(current.rect, event.clientX, event.clientY))
- finish(true);
+ onPointerCancel={() => {
+ press.current = null;
}}
onContextMenu={(event) => {
event.preventDefault();
finish(null);
}}
>
- {hover && !dragging && (
+ {target && (
<div
className="pointer-events-none absolute"
style={{
- left: hover.rect.x,
- top: hover.rect.y,
- width: hover.rect.width,
- height: hover.rect.height,
- background: selection ? "transparent" : "rgba(10,132,255,0.16)",
- boxShadow: selection
- ? `inset 0 0 0 2px ${HIGHLIGHT}`
- : `inset 0 0 0 2px ${HIGHLIGHT}, 0 0 0 100vmax ${DIM}`,
+ left: target.rect.x,
+ top: target.rect.y,
+ width: target.rect.width,
+ height: target.rect.height,
+ background: "rgba(10,132,255,0.16)",
+ boxShadow: "0 0 0 100vmax rgba(0,0,0,0.38)",
+ outline: "2px solid #0a84ff",
+ outlineOffset: -2,
}}
>
<div
- className="absolute max-w-[min(520px,90%)] truncate whitespace-nowrap rounded-md px-2 py-0.5 text-[11px] font-medium text-white"
- style={{ ...placeLabel(hover.rect), background: HIGHLIGHT }}
+ className="absolute whitespace-nowrap rounded-md bg-blue-600 px-2 py-1 text-xs text-white"
+ style={{ top: target.rect.y >= 30 ? -28 : 6, left: 6 }}
>
- {describe(hover)} · {sizeLabel(hover.rect)}
+ {label} · {Math.round(target.rect.width)} × {Math.round(target.rect.height)}
</div>
</div>
)}
-
- {selection === null ? (
- <div className="pointer-events-none absolute inset-x-0 bottom-24 flex justify-center">
- <div className="rounded-full bg-[rgba(18,18,22,0.88)] px-4 py-2 text-[13px] font-medium text-white/90 shadow-lg ring-1 ring-white/10 backdrop-blur-md">
- {t(
- "capturePicker.hint",
- "Click a window or the desktop, or drag an area · Esc to cancel",
- )}
- </div>
+ <div className="pointer-events-none absolute inset-x-0 bottom-24 flex justify-center">
+ <div className="rounded-full bg-black/80 px-4 py-2 text-sm text-white">
+ {allowArea
+ ? "Click a window or the desktop, or drag an area · Esc to cancel"
+ : "Click a window or the desktop · Esc to cancel"}
</div>
- ) : (
- <>
- <div
- className="absolute"
- style={{
- left: selection.rect.x,
- top: selection.rect.y,
- width: selection.rect.width,
- height: selection.rect.height,
- cursor: dragging ? "grabbing" : "move",
- boxShadow: `0 0 0 100vmax ${DIM}`,
- outline: "1px solid rgba(255,255,255,0.95)",
- outlineOffset: selection.kind === "screen" ? -1 : 0,
- }}
- >
- {AREA_HANDLES.map((handle) => (
- <div
- key={handle}
- data-picker-handle={handle}
- className="absolute h-[11px] w-[11px] rounded-full border border-black/30 bg-white shadow"
- style={{
- left: HANDLE_POSITIONS[handle].left,
- top: HANDLE_POSITIONS[handle].top,
- transform: "translate(-50%, -50%)",
- cursor: HANDLE_POSITIONS[handle].cursor,
- }}
- />
- ))}
- <div
- className="pointer-events-none absolute max-w-[min(520px,90%)] truncate whitespace-nowrap rounded-md bg-[rgba(18,18,22,0.88)] px-2 py-0.5 text-[11px] font-medium tabular-nums text-white/90"
- style={placeLabel(selection.rect)}
- >
- {selection.kind === "area"
- ? sizeLabel(selection.rect)
- : `${describe(selection)} · ${sizeLabel(selection.rect)}`}
- </div>
- </div>
- {!dragging && (
- <div
- data-picker-toolbar
- className="absolute flex items-center gap-1 rounded-full bg-[rgba(18,18,22,0.92)] p-1 text-[13px] font-medium text-white shadow-xl ring-1 ring-white/10 backdrop-blur-md"
- style={{
- top: toolbarTop,
- left: Math.min(
- Math.max(selection.rect.x + selection.rect.width / 2, 160),
- window.innerWidth - 160,
- ),
- height: TOOLBAR_HEIGHT,
- transform: "translateX(-50%)",
- cursor: "default",
- }}
- >
- <button
- type="button"
- className="h-full rounded-full px-4 text-white/80 hover:bg-white/10 hover:text-white"
- onClick={() => finish(null)}
- >
- {t("capturePicker.cancel", "Cancel")}
- </button>
- <button
- type="button"
- disabled={tooSmall}
- className="h-full rounded-full px-4 text-white/80 hover:bg-white/10 hover:text-white disabled:opacity-40"
- onClick={() => finish(false)}
- >
- {t("capturePicker.select", "Select")}
- </button>
- <button
- type="button"
- disabled={tooSmall}
- className="flex h-full items-center gap-2 rounded-full bg-[#e5484d] px-4 text-white hover:bg-[#ec5d62] disabled:opacity-40"
- onClick={() => finish(true)}
- >
- <span className="h-2.5 w-2.5 rounded-full bg-white" />
- {t("capturePicker.record", "Record")}
- </button>
- </div>
- )}
- </>
- )}
+ </div>
</div>
);
}
-
export default CapturePicker;
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx
index e83e6cfb..7ba926ff 100644
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@ -1,6 +1,5 @@
import {
ArrowClockwiseIcon,
- CaretUpIcon,
House,
DotsThreeVerticalIcon,
MicrophoneIcon,
@@ -13,7 +12,7 @@ import {
XIcon,
} from "@/components/ui/icons";
import { AnimatePresence, motion } from "motion/react";
-import { useEffect, useRef } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { Separator } from "@/components/ui/separator";
import { useScopedT } from "../../contexts/I18nContext";
import { useMicrophoneDevices } from "../../hooks/useMicrophoneDevices";
@@ -36,7 +35,7 @@ import {
useLaunchPopoverCoordinator,
} from "./popovers/LaunchPopoverCoordinator";
import { MicPopover } from "./popovers/MicPopover";
-import { SourcePopover } from "./popovers/SourcePopover";
+import { toast } from "@/components/ui/toast";
import { WebcamPopover } from "./popovers/WebcamPopover";
import { RecordingControls } from "./RecordingControls";
@@ -50,7 +49,7 @@ export function LaunchWindow() {
function LaunchWindowContent() {
const t = useScopedT("launch");
- const { openId, requestOpen } = useLaunchPopoverCoordinator();
+ const { openId } = useLaunchPopoverCoordinator();
const {
recording,
@@ -80,8 +79,7 @@ function LaunchWindowContent() {
const hudContentRef = useRef<HTMLDivElement>(null);
const hudBarRef = useRef<HTMLDivElement>(null);
- const { selectedSource, hasSelectedSource, handleSourceSelect, syncSelectedSource } =
- useLaunchWindowActions();
+ const { selectedSource, hasSelectedSource, syncSelectedSource } = useLaunchWindowActions();
const showWebcamControls = webcamEnabled && !recording;
const { devices, selectedDeviceId, setSelectedDeviceId } = useMicrophoneDevices(
@@ -164,14 +162,47 @@ function LaunchWindowContent() {
webcamPreviewDragStartRef,
});
+ const hudStateTransition = {
+ duration: 0.24,
+ ease: [0.22, 1, 0.36, 1] as const,
+ };
+
+ const pickerPending = useRef(false);
+ const handlePickOnScreen = useCallback(async () => {
+ if (pickerPending.current || recording) return;
+ pickerPending.current = true;
+ beginInteractiveHudAction();
+ try {
+ const result = await window.electronAPI.pickCaptureTarget();
+ if (result.success && result.source) syncSelectedSource(result.source);
+ if (result.message && !result.canceled) {
+ if (result.success) toast.info(result.message);
+ else toast.error(result.message);
+ }
+ } catch {
+ toast.error("Unable to open the source picker.");
+ } finally {
+ pickerPending.current = false;
+ }
+ }, [recording, beginInteractiveHudAction, syncSelectedSource]);
+
+ const initialSourceChecked = useRef(false);
useEffect(() => {
let mounted = true;
+ let selectionEventSeen = false;
void window.electronAPI.getSelectedSource().then((source) => {
- if (mounted) syncSelectedSource(source);
+ if (mounted && !selectionEventSeen) {
+ syncSelectedSource(source);
+ if (!initialSourceChecked.current) {
+ initialSourceChecked.current = true;
+ if (!source && !recording) void handlePickOnScreen();
+ }
+ }
});
const cleanup = window.electronAPI.onSelectedSourceChanged((source) => {
+ selectionEventSeen = true;
if (mounted) syncSelectedSource(source);
});
@@ -179,22 +210,7 @@ function LaunchWindowContent() {
mounted = false;
cleanup?.();
};
- }, [syncSelectedSource]);
-
- const hudStateTransition = {
- duration: 0.24,
- ease: [0.22, 1, 0.36, 1] as const,
- };
-
- const handlePickOnScreen = async () => {
- const result = await window.electronAPI.pickCaptureTarget();
- if (!result.success) return;
- if (result.record) {
- toggleRecording();
- } else if (result.source) {
- void window.electronAPI.showSourceHighlight?.(result.source);
- }
- };
+ }, [syncSelectedSource, recording, handlePickOnScreen]);
const openHome = () => {
localStorage.setItem("recordly.open-dashboard", String(Date.now()));
@@ -229,41 +245,20 @@ function LaunchWindowContent() {
const idleControls = (
<>
- {platform !== "linux" && (
- <>
- <SourcePopover
- selectedSource={selectedSource}
- onSourceSelect={handleSourceSelect}
- onPickOnScreen={platform === "darwin" ? handlePickOnScreen : undefined}
- onOpen={beginInteractiveHudAction}
- trigger={
- <Button
- variant="ghost"
- size="lg"
- className={` ${styles.electronNoDrag} group gap-2 px-3 min-w-0 max-w-[180px] shrink-0 ${openId === "sources" ? "border-[var(--launch-border-strong)] bg-[var(--launch-hover)]" : ""} `}
- title={selectedSource}
- >
- <MonitorIcon
- weight={openId === "sources" ? "fill" : "regular"}
- size={18}
- className="size-5 shrink-0"
- />
- <div className="flex-1 min-w-0 overflow-hidden">
- <MarqueeText text={selectedSource} />
- </div>
- <CaretUpIcon
- size={10}
- className={`text-[#6b6b78] ml-0.5 shrink-0 transition-transform duration-200 ${
- openId === "sources" ? "" : "rotate-180"
- }`}
- />
- </Button>
- }
- />
-
- <Separator orientation="vertical" className="mx-[5px] h-6 self-center" />
- </>
- )}
+ <Button
+ variant="ghost"
+ size="lg"
+ className={`${styles.electronNoDrag} gap-2 px-3 min-w-0 max-w-[180px] shrink-0`}
+ title={selectedSource}
+ aria-label="Choose recording source"
+ onClick={() => void handlePickOnScreen()}
+ >
+ <MonitorIcon size={18} className="size-5 shrink-0" />
+ <div className="flex-1 min-w-0 overflow-hidden">
+ <MarqueeText text={selectedSource} />
+ </div>
+ </Button>
+ <Separator orientation="vertical" className="mx-[5px] h-6 self-center" />
<MicPopover
disabled={recording}
@@ -372,14 +367,7 @@ function LaunchWindowContent() {
variant="destructive"
size="icon"
className={styles.electronNoDrag}
- onClick={
- hasSelectedSource || platform === "linux"
- ? toggleRecording
- : () => {
- beginInteractiveHudAction();
- requestOpen("sources");
- }
- }
+ onClick={hasSelectedSource ? toggleRecording : () => void handlePickOnScreen()}
disabled={countdownActive}
title={t("recording.record")}
>
diff --git a/src/components/launch/SourceSelector.tsx b/src/components/launch/SourceSelector.tsx
index fcc865bb..ad7f100b 100644
--- a/src/components/launch/SourceSelector.tsx
+++ b/src/components/launch/SourceSelector.tsx
@@ -1,392 +1,21 @@
-import { ToggleButton } from "@heroui/react";
-import { AppWindowIcon, CaretUpIcon, Crop, MonitorIcon } from "@/components/ui/icons";
-import * as React from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Button } from "@/components/ui/button";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { useScopedT } from "@/contexts/I18nContext";
-import { cn } from "@/lib/utils";
-import {
- type DesktopSource,
- isScreenSource,
- isWindowSource,
- mapRawSource,
-} from "./popovers/launchPopoverTypes";
-import "./launchTheme.css";
-import "./SourceSelector.css";
-import { useHudInteraction } from "./contexts/HudInteractionContext";
-import { MarqueeText } from "./MarqueeText";
+import { useEffect, useRef } from "react";
+import { toast } from "@/components/ui/toast";
-interface SourceSelectorProps {
- /** List of available screen sources */
- screenSources?: DesktopSource[];
- /** List of available window sources */
- windowSources?: DesktopSource[];
- /** Currently selected source name */
- selectedSource?: string;
- /** Loading state */
- loading?: boolean;
- /** Callback when a source is selected */
- onSourceSelect?: (source: DesktopSource) => void;
- /** Opens the on-screen picker for an area or window; omitted where unsupported */
- onPickOnScreen?: () => void;
- /** Callback to fetch sources */
- onFetchSources?: () => Promise<void>;
- /** Whether the popover is open */
- open?: boolean;
- /** Callback when open state changes */
- onOpenChange?: (open: boolean) => void;
- /** Optional custom trigger element */
- children?: React.ReactNode;
-}
-
-/**
- * SourceSelectorContent - The actual list of sources
- */
-export const SourceSelectorContent = ({
- screenSources = [],
- windowSources = [],
- selectedSource = "Screen",
- loading = false,
- onSourceSelect = () => undefined,
- onPickOnScreen,
-}: Pick<
- SourceSelectorProps,
- | "screenSources"
- | "windowSources"
- | "selectedSource"
- | "loading"
- | "onSourceSelect"
- | "onPickOnScreen"
->) => {
- const t = useScopedT("launch");
- const renderSourceItem = (source: DesktopSource, index: number) => {
- const isSelected = selectedSource === source.name;
- return (
- <ToggleButton
- variant="ghost"
- isSelected={isSelected}
- key={`${source.id}-${index}`}
- className={cn(
- "source-selector-item group min-h-[46px] w-full px-3 py-2.5 text-left flex items-center justify-start gap-3",
- isSelected && "source-selector-item-selected",
- )}
- onClick={() => onSourceSelect(source)}
- >
- <div className="relative flex-shrink-0">
- {source.thumbnail ? (
- <img
- src={source.thumbnail}
- alt=""
- className="w-12 h-8 rounded-[8px] object-cover bg-black/50"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = "none";
- }}
- />
- ) : (
- <div className="source-selector-thumb-fallback w-12 h-8 rounded-[8px] flex items-center justify-center">
- {source.sourceType === "window" ? (
- <AppWindowIcon className="w-5 h-5 source-selector-muted" />
- ) : (
- <MonitorIcon className="w-5 h-5 source-selector-muted" />
- )}
- </div>
- )}
- </div>
-
- <div className="flex-1 min-w-0 flex flex-col items-start text-left">
- <div className="text-sm font-medium source-selector-text w-full">
- <MarqueeText text={source.windowTitle || source.name} />
- </div>
- <div className="text-xs source-selector-subtle truncate w-full text-left">
- {source.sourceType === "screen"
- ? t("recording.screen")
- : t("recording.window")}
- </div>
- </div>
- </ToggleButton>
- );
- };
-
- const hasAnySources = screenSources.length > 0 || windowSources.length > 0;
- const pickOnScreenItem = onPickOnScreen ? (
- <div className="p-2 pb-0">
- <ToggleButton
- variant="ghost"
- isSelected={selectedSource.startsWith("Area ")}
- className={cn(
- "source-selector-item group min-h-[46px] w-full px-3 py-2.5 text-left flex items-center justify-start gap-3",
- selectedSource.startsWith("Area ") && "source-selector-item-selected",
- )}
- onClick={onPickOnScreen}
- >
- <div className="source-selector-thumb-fallback w-12 h-8 rounded-[8px] flex items-center justify-center flex-shrink-0">
- <Crop className="w-5 h-5 source-selector-muted" />
- </div>
- <div className="flex-1 min-w-0 flex flex-col items-start text-left">
- <div className="text-sm font-medium source-selector-text w-full">
- {t("recording.pickOnScreen", "Select area or window")}
- </div>
- <div className="text-xs source-selector-subtle truncate w-full text-left">
- {selectedSource.startsWith("Area ")
- ? selectedSource
- : t("recording.pickOnScreenHint", "Drag an area, or click a window")}
- </div>
- </div>
- </ToggleButton>
- </div>
- ) : null;
-
- if (loading && !hasAnySources) {
- return (
- <>
- {pickOnScreenItem}
- <div className="flex items-center justify-center py-8">
- <div className="animate-spin rounded-full h-5 w-5 border-b-2 source-selector-accent-border" />
- </div>
- </>
- );
- }
-
- return (
- <>
- {pickOnScreenItem}
- <div className="max-h-[320px] overflow-y-auto overflow-x-hidden p-2 source-selector-scroll">
- {hasAnySources ? (
- <>
- {screenSources.length > 0 ? (
- <div className="space-y-1">
- <div className="px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] source-selector-label flex items-center gap-2">
- {t("recording.screens")}
- <span
- className={cn(
- "normal-case tracking-normal text-[10px] source-selector-muted transition-opacity duration-150",
- loading ? "opacity-100" : "opacity-0",
- )}
- >
- {t("common.loading", "Refreshing...")}
- </span>
- </div>
- <div className="space-y-0.5">
- {screenSources.map((source, index) =>
- renderSourceItem(source, index),
- )}
- </div>
- </div>
- ) : null}
- {windowSources.length > 0 ? (
- <div className="space-y-1">
- <div className="px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] source-selector-label">
- {t("recording.windows")}
- </div>
- <div className="space-y-0.5">
- {windowSources.map((source, index) =>
- renderSourceItem(source, index),
- )}
- </div>
- </div>
- ) : null}
- </>
- ) : (
- <div className="text-center py-8 text-sm source-selector-muted">
- {t("recording.noSourcesFound")}
- </div>
- )}
- </div>
- </>
- );
-};
-
-/**
- * SourceSelector - A rich source selection component with thumbnails
- * Uses the shared HeroUI popover for positioning and accessibility
- */
-export const SourceSelector = React.memo(function SourceSelector({
- screenSources: propsScreenSources,
- windowSources: propsWindowSources,
- selectedSource: propsSelectedSource,
- loading: propsLoading,
- onSourceSelect: propsOnSourceSelect,
- onPickOnScreen,
- onFetchSources: propsOnFetchSources,
- open: propsOpen,
- onOpenChange: propsOnOpenChange,
- children,
-}: SourceSelectorProps) {
- // Internal state for standalone/uncontrolled use
- const [internalOpen, setInternalOpen] = useState(false);
- const [internalSources, setInternalSources] = useState<DesktopSource[]>([]);
- const [internalLoading, setInternalLoading] = useState(false);
- const [internalSelectedSource, setInternalSelectedSource] = useState("Screen");
-
- // Determine if we should use internal or external state/logic
- const isAutonomous = propsOpen === undefined;
- const open = propsOpen ?? internalOpen;
- const onOpenChange = propsOnOpenChange ?? setInternalOpen;
- const loading = propsLoading ?? internalLoading;
- const selectedSource = propsSelectedSource ?? internalSelectedSource;
-
- // Default fetching logic
- const defaultFetchSources = useCallback(async () => {
- if (!window.electronAPI) return;
- setInternalLoading(true);
- try {
- const rawSources = await window.electronAPI.getSources({
- types: ["screen", "window"],
- thumbnailSize: { width: 160, height: 90 },
- fetchWindowIcons: true,
- });
- setInternalSources(rawSources.map((s) => mapRawSource(s as DesktopSource)));
- } catch (error) {
- console.error("Failed to fetch sources:", error);
- } finally {
- setInternalLoading(false);
- }
- }, []);
-
- const onFetchSources = propsOnFetchSources ?? defaultFetchSources;
-
- // Default selection logic
- const onSourceSelect = useCallback(
- async (source: DesktopSource) => {
- if (propsOnSourceSelect) {
- propsOnSourceSelect(source);
- return;
- }
- if (!window.electronAPI) return;
- try {
- const result = await window.electronAPI.selectSource(source);
- if (result) {
- setInternalSelectedSource(source.name);
- await window.electronAPI.showSourceHighlight?.(source);
- }
- } catch (error) {
- console.error("Failed to select source:", error);
- }
- },
- [propsOnSourceSelect],
- );
-
- // Split sources for internal use
- const internalScreenSources = useMemo(
- () => internalSources.filter(isScreenSource),
- [internalSources],
- );
- const internalWindowSources = useMemo(
- () => internalSources.filter(isWindowSource),
- [internalSources],
- );
-
- const screenSources = propsScreenSources ?? internalScreenSources;
- const windowSources = propsWindowSources ?? internalWindowSources;
-
- const hasPrefetchedRef = useRef(false);
- const fetchInFlightRef = useRef(false);
- const lastFetchedAtRef = useRef(0);
-
- const fetchSourcesOnce = useCallback(
- async (allowRecentSkip: boolean) => {
- if (fetchInFlightRef.current) {
- return;
- }
- if (allowRecentSkip && Date.now() - lastFetchedAtRef.current < 750) {
- return;
- }
- fetchInFlightRef.current = true;
- try {
- await onFetchSources();
- lastFetchedAtRef.current = Date.now();
- } finally {
- fetchInFlightRef.current = false;
- }
- },
- [onFetchSources],
- );
-
- const prefetchSources = React.useCallback(() => {
- if (hasPrefetchedRef.current) {
- return;
- }
- hasPrefetchedRef.current = true;
- void fetchSourcesOnce(false);
- }, [fetchSourcesOnce]);
-
- // Fetch sources when popover opens
- useEffect(() => {
- if (open) {
- void fetchSourcesOnce(true);
- }
- }, [open, fetchSourcesOnce]);
-
- // In autonomous mode, we might want to start open
+export function SourceSelector() {
+ const started = useRef(false);
useEffect(() => {
- if (isAutonomous) {
- setInternalOpen(true);
- }
- }, [isAutonomous]);
-
- const trigger = children ? (
- React.isValidElement(children) ? (
- React.cloneElement(children as React.ReactElement<React.HTMLAttributes<HTMLElement>>, {
- onPointerEnter: prefetchSources,
- onFocusCapture: prefetchSources,
+ if (started.current) return;
+ started.current = true;
+ void window.electronAPI
+ .pickCaptureTarget()
+ .then((result) => {
+ if (result.message && !result.canceled) toast.info(result.message);
+ window.close();
})
- ) : (
- children
- )
- ) : (
- <Button
- variant="ghost"
- size="lg"
- onPointerEnter={prefetchSources}
- onFocusCapture={prefetchSources}
- className={cn(
- "group gap-2 px-3 min-w-0 max-w-[180px] [ -webkit-app-region:no-drag ] shrink-0",
- )}
- title={selectedSource}
- >
- <MonitorIcon size={16} className="shrink-0" />
- <div className="flex-1 min-w-0">
- <MarqueeText text={selectedSource} />
- </div>
- <CaretUpIcon
- size={10}
- className={cn(
- "text-[#6b6b78] ml-0.5 shrink-0 transition-transform duration-200",
- open ? "" : "rotate-180",
- )}
- />
- </Button>
- );
-
- const { onMouseEnter } = useHudInteraction();
-
- return (
- <Popover open={open} onOpenChange={onOpenChange} modal={true}>
- <PopoverTrigger asChild>{trigger}</PopoverTrigger>
- <PopoverContent
- className="launch-theme w-80 p-0 source-selector-popover"
- unstyled
- align="start"
- sideOffset={8}
- side="top"
- alignOffset={-8}
- avoidCollisions={true}
- collisionPadding={10}
- usePortal={false}
- onMouseEnter={onMouseEnter}
- >
- <SourceSelectorContent
- screenSources={screenSources}
- windowSources={windowSources}
- selectedSource={selectedSource}
- loading={loading}
- onSourceSelect={onSourceSelect}
- onPickOnScreen={onPickOnScreen}
- />
- </PopoverContent>
- </Popover>
- );
-});
-
-SourceSelector.displayName = "SourceSelector";
+ .catch(() => {
+ toast.error("Unable to open the source picker.");
+ window.close();
+ });
+ }, []);
+ return null;
+}
diff --git a/src/components/launch/popovers/SourcePopover.tsx b/src/components/launch/popovers/SourcePopover.tsx
deleted file mode 100644
index f4b56a0f..00000000
--- a/src/components/launch/popovers/SourcePopover.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { useCallback, useMemo, type ReactNode, useState } from "react";
-import { SourceSelector } from "../SourceSelector";
-import { useLaunchPopoverCoordinator } from "./LaunchPopoverCoordinator";
-import {
- mapRawSource,
- isScreenSource,
- isWindowSource,
- type DesktopSource,
-} from "./launchPopoverTypes";
-
-const POPOVER_ID = "sources";
-
-export function SourcePopover({
- trigger,
- selectedSource,
- onSourceSelect,
- onPickOnScreen,
- onOpen,
-}: {
- trigger: ReactNode;
- selectedSource: string;
- onSourceSelect: (source: DesktopSource) => Promise<void> | void;
- /** Opens the on-screen picker for an area or window; omitted where unsupported */
- onPickOnScreen?: () => Promise<void> | void;
- onOpen?: () => void;
-}) {
- const { isOpen, requestOpen, requestClose } = useLaunchPopoverCoordinator();
- const [sources, setSources] = useState<DesktopSource[]>([]);
- const [loading, setLoading] = useState(false);
- const open = isOpen(POPOVER_ID);
-
- const fetchSources = useCallback(async () => {
- if (!window.electronAPI) return;
- setLoading(true);
- try {
- const rawSources = await window.electronAPI.getSources({
- types: ["screen", "window"],
- thumbnailSize: { width: 160, height: 90 },
- fetchWindowIcons: true,
- });
- setSources(rawSources.map((s) => mapRawSource(s as DesktopSource)));
- } catch (error) {
- console.error("Failed to fetch sources:", error);
- } finally {
- setLoading(false);
- }
- }, []);
-
- const screenSources = useMemo(() => sources.filter(isScreenSource), [sources]);
- const windowSources = useMemo(() => sources.filter(isWindowSource), [sources]);
-
- return (
- <SourceSelector
- screenSources={screenSources}
- windowSources={windowSources}
- selectedSource={selectedSource}
- loading={loading}
- onSourceSelect={async (source) => {
- try {
- await onSourceSelect(source);
- requestClose(POPOVER_ID);
- } catch (error) {
- console.error("Failed to select source:", error);
- }
- }}
- onPickOnScreen={
- onPickOnScreen
- ? () => {
- requestClose(POPOVER_ID);
- void onPickOnScreen();
- }
- : undefined
- }
- onFetchSources={fetchSources}
- open={open}
- onOpenChange={(nextOpen) => {
- if (!nextOpen) {
- requestClose(POPOVER_ID);
- return;
- }
- onOpen?.();
- requestOpen(POPOVER_ID);
- }}
- >
- {trigger}
- </SourceSelector>
- );
-}
diff --git a/tests/ui/capture-picker.spec.ts b/tests/ui/capture-picker.spec.ts
index 8e32093f..621af051 100644
--- a/tests/ui/capture-picker.spec.ts
+++ b/tests/ui/capture-picker.spec.ts
@@ -25,25 +25,29 @@ const windows = [
},
];
-async function openPicker(page: Page) {
+async function openPicker(page: Page, allowArea = true) {
await installDesktopBridge(page);
- await page.addInitScript((pickerWindows) => {
- const api = (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI;
- Object.assign(api, {
- getCapturePickerContext: async () => ({
- displayBounds: { x: 0, y: 0, width: 1440, height: 1000 },
- lastArea: null,
- windows: pickerWindows,
- cursor: null,
- }),
- completeCapturePick: async (pick: unknown) => {
- document.documentElement.dataset.pick = JSON.stringify(pick);
- },
- capturePickerReady: () => {
- document.documentElement.dataset.pickerReady = "true";
- },
- });
- }, windows);
+ await page.addInitScript(
+ ({ pickerWindows, allowArea }) => {
+ const api = (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI;
+ Object.assign(api, {
+ getCapturePickerContext: async () => ({
+ displayBounds: { x: 0, y: 0, width: 1440, height: 1000 },
+ lastArea: null,
+ allowArea,
+ windows: pickerWindows,
+ cursor: null,
+ }),
+ completeCapturePick: async (pick: unknown) => {
+ document.documentElement.dataset.pick = JSON.stringify(pick);
+ },
+ capturePickerReady: () => {
+ document.documentElement.dataset.pickerReady = "true";
+ },
+ });
+ },
+ { pickerWindows: windows, allowArea },
+ );
await page.goto("/?windowType=capture-picker&displayId=1");
await expect(page.locator("html")).toHaveAttribute("data-picker-ready", "true");
}
@@ -59,12 +63,11 @@ test("hovering highlights the frontmost window and a click picks it", async ({ p
await expect(page.getByText("Notes — Launch checklist · 620 × 460")).toBeVisible();
await page.mouse.click(600, 300);
- await page.getByRole("button", { name: "Record" }).click();
expect(await pick(page)).toEqual({
kind: "window",
windowId: "window:101:0",
displayId: 1,
- record: true,
+ record: false,
});
});
@@ -74,7 +77,6 @@ test("a click on the desktop picks the whole screen", async ({ page }) => {
await expect(page.getByText("Entire screen · 1440 × 1000")).toBeVisible();
await page.mouse.click(1380, 60);
- await page.getByRole("button", { name: "Select" }).click();
expect(await pick(page)).toEqual({ kind: "screen", displayId: 1, record: false });
});
@@ -86,13 +88,12 @@ test("a drag draws an area", async ({ page }) => {
await page.mouse.up();
await expect(page.getByText("400 × 250")).toBeVisible();
- await page.keyboard.press("Enter");
expect(await pick(page)).toMatchObject({
kind: "area",
width: 400,
height: 250,
displayId: 1,
- record: true,
+ record: false,
});
});
@@ -101,3 +102,81 @@ test("Escape cancels", async ({ page }) => {
await page.keyboard.press("Escape");
expect(await pick(page)).toBeNull();
});
+
+test("selection has no recording toolbar", async ({ page }) => {
+ await openPicker(page);
+ await page.mouse.click(600, 300);
+ await expect(page.getByRole("button", { name: "Record", exact: true })).toHaveCount(0);
+ expect(await pick(page)).toMatchObject({ kind: "window", record: false });
+});
+
+test("platforms without area capture keep drag selection on an existing screen", async ({
+ page,
+}) => {
+ await openPicker(page, false);
+ await page.mouse.move(1300, 100);
+ await page.mouse.down();
+ await page.mouse.move(1380, 180, { steps: 8 });
+ await page.mouse.up();
+ expect(await pick(page)).toMatchObject({ kind: "screen", record: false });
+});
+
+for (const selected of [false, true]) {
+ test(`HUD ${selected ? "keeps the selected source and reopens on click" : "opens the picker once when no source exists"}`, async ({
+ page,
+ }) => {
+ await installDesktopBridge(page);
+ await page.addInitScript((selected) => {
+ Object.assign(window.electronAPI, {
+ getSelectedSource: async () =>
+ selected ? { id: "screen:1:0", name: "Existing screen" } : null,
+ pickCaptureTarget: async () => {
+ const html = document.documentElement;
+ html.dataset.pickerCalls = String(Number(html.dataset.pickerCalls ?? 0) + 1);
+ return {
+ success: true,
+ source: { id: "window:101:0", name: "Selected window" },
+ };
+ },
+ });
+ }, selected);
+ await page.goto("/?windowType=hud-overlay");
+ const control = page.getByRole("button", { name: "Choose recording source" });
+ await expect(control).toBeVisible();
+ if (selected) {
+ await expect(control).toContainText("Existing screen");
+ await expect(page.locator("html")).not.toHaveAttribute("data-picker-calls");
+ await control.click();
+ }
+ await expect(page.locator("html")).toHaveAttribute("data-picker-calls", "1");
+ await expect(control).toContainText("Selected window");
+ await expect(page.getByRole("button", { name: "Record", exact: true })).toBeVisible();
+ });
+}
+
+test("a newer selected-source event wins over the startup response", async ({ page }) => {
+ await installDesktopBridge(page);
+ await page.addInitScript(() => {
+ Object.assign(window.electronAPI, {
+ getSelectedSource: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ document.documentElement.dataset.sourceResolved = "true";
+ return null;
+ },
+ onSelectedSourceChanged: (listener: (source: { name: string }) => void) => {
+ const timer = setTimeout(() => listener({ name: "Newer window" }), 10);
+ return () => clearTimeout(timer);
+ },
+ pickCaptureTarget: async () => {
+ document.documentElement.dataset.pickerCalls = "1";
+ return { success: false, canceled: true };
+ },
+ });
+ });
+ await page.goto("/?windowType=hud-overlay");
+ await expect(page.locator("html")).toHaveAttribute("data-source-resolved", "true");
+ await expect(page.getByRole("button", { name: "Choose recording source" })).toContainText(
+ "Newer window",
+ );
+ await expect(page.locator("html")).not.toHaveAttribute("data-picker-calls");
+});