diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts index c2769e56e..f776c1058 100644 --- a/src/main/browser/browser-manager.ts +++ b/src/main/browser/browser-manager.ts @@ -471,7 +471,7 @@ class BrowserManager { // overlay visible so the highlight box persists while the renderer // shows the copy menu. Teardown happens later when the renderer calls // setGrabMode(false) or re-arms with a fresh armAndAwait cycle. - op.cleanup(result.kind === 'selected') + op.cleanup(result.kind === 'selected' || result.kind === 'context-selected') this.activeGrabOps.delete(browserTabId) resolve(result) } @@ -487,12 +487,24 @@ class BrowserManager { settleOnce({ opId, kind: 'cancelled', reason: 'user' }) return } - const payload = clampGrabPayload(rawPayload) + // Why: the guest wraps right-click results in { __orcaContextMenu, payload } + // so the renderer can show the full action dropdown instead of auto-copying. + const isContextMenu = + '__orcaContextMenu' in (rawPayload as Record) && + (rawPayload as Record).__orcaContextMenu === true + const payloadSource = isContextMenu + ? (rawPayload as Record).payload + : rawPayload + const payload = clampGrabPayload(payloadSource) if (!payload) { settleOnce({ opId, kind: 'error', reason: 'Guest returned invalid payload structure' }) return } - settleOnce({ opId, kind: 'selected', payload }) + settleOnce({ + opId, + kind: isContextMenu ? 'context-selected' : 'selected', + payload + }) } catch (err) { const message = err instanceof Error ? err.message : 'Selection failed' // Distinguish cancellation from errors @@ -605,7 +617,25 @@ class BrowserManager { height: safeN(rect.height) } - const image = await guest.capturePage() + // Why: hide the grab overlay before capturing so the highlight box and + // label don't appear in the screenshot. The overlay is restored after. + // Wrapped in try/finally so the overlay is always restored even if + // capturePage() throws (e.g., guest destroyed mid-capture). + await guest + .executeJavaScript( + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = 'none'; })()` + ) + .catch(() => {}) + let image: Electron.NativeImage + try { + image = await guest.capturePage() + } finally { + await guest + .executeJavaScript( + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = ''; })()` + ) + .catch(() => {}) + } if (image.isEmpty()) { return null } diff --git a/src/main/browser/grab-guest-script.ts b/src/main/browser/grab-guest-script.ts index 8f64e6b2d..d65579726 100644 --- a/src/main/browser/grab-guest-script.ts +++ b/src/main/browser/grab-guest-script.ts @@ -441,10 +441,24 @@ const AWAIT_CLICK_SCRIPT = `new Promise(function(resolve, reject) { } function onContext(e) { - // Block right-click while armed + // Why: right-click resolves with the payload wrapped in a context-menu + // marker so the renderer can show the full action dropdown instead of + // auto-copying. This gives users a deliberate path to screenshot and + // other secondary actions while keeping left-click as the fast copy path. e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); + grab.host.removeEventListener('click', onClick, true); + grab.host.removeEventListener('contextmenu', onContext, true); + var el = grab.getCurrentElement(); + if (!el) { + grab.cleanup(); + reject(new Error('cancelled')); + return; + } + var payload = grab.extractPayload(el); + grab.freezeHighlight(); + resolve({ __orcaContextMenu: true, payload: payload }); } grab.host.addEventListener('click', onClick, true); diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index c3b9b1854..bfa22f1fb 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -135,10 +135,16 @@ export function registerClipboardHandlers(): void { // Why: only accept validated PNG data URIs to prevent writing arbitrary // data to the clipboard. The renderer already validates the prefix, but // defense-in-depth applies here too. - if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/png;base64,')) { + const prefix = 'data:image/png;base64,' + if (typeof dataUrl !== 'string' || !dataUrl.startsWith(prefix)) { return } - const image = nativeImage.createFromDataURL(dataUrl) + // Why: use createFromBuffer instead of createFromDataURL — the latter + // silently returns an empty image on some macOS + Electron combinations + // when the data URL is large (>500KB). Decoding the base64 manually and + // using createFromBuffer is more reliable. + const buffer = Buffer.from(dataUrl.slice(prefix.length), 'base64') + const image = nativeImage.createFromBuffer(buffer) if (image.isEmpty()) { return } diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index 1dd844bc9..8745240fc 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -3,16 +3,17 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { ArrowLeft, ArrowRight, + CircleCheck, Copy, Crosshair, ExternalLink, Globe, Image, Loader2, + OctagonX, RefreshCw, SquareCode } from 'lucide-react' -import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { @@ -273,6 +274,82 @@ export default function BrowserPane({ const [resourceNotice, setResourceNotice] = useState(null) const grab = useGrabMode(browserTab.id) + // Inline toast that appears near the grabbed element instead of the global + // bottom-right toaster, so feedback feels spatially connected to the action. + // Why: positioned below (or above, if near viewport bottom) so it doesn't + // occlude the element the user just selected. + const [grabToast, setGrabToast] = useState<{ + message: string + type: 'success' | 'error' + x: number + y: number + below: boolean + payload: BrowserGrabPayload | null + } | null>(null) + const grabToastTimerRef = useRef>(undefined) + // Why: clear the toast auto-dismiss timer on unmount so it cannot fire + // after the component is destroyed (prevents setState-on-unmounted warnings + // and stale rearm calls). + useEffect(() => { + return () => clearTimeout(grabToastTimerRef.current) + }, []) + const grabRef = useRef(grab) + grabRef.current = grab + + const dismissGrabToast = useCallback(() => { + clearTimeout(grabToastTimerRef.current) + setGrabToast(null) + // Why: only rearm if the grab state is still 'confirming', meaning the + // auto-copy toast is dismissing naturally. If the user already triggered + // a shortcut (C/S) that called rearm, the state will be 'armed' and we + // skip to avoid a double-rearm race. + if (grabRef.current.state === 'confirming') { + grabRef.current.rearm() + } + }, []) + + const showGrabToast = useCallback( + (message: string, type: 'success' | 'error', payload?: BrowserGrabPayload | null) => { + let x = 0 + let y = 0 + let below = true + const containerRect = containerRef.current?.getBoundingClientRect() + if (payload) { + const rect = payload.target.rectViewport + const webview = webviewRef.current + const webviewRect = webview?.getBoundingClientRect() + const offsetX = (webviewRect?.left ?? 0) - (containerRect?.left ?? 0) + const offsetY = (webviewRect?.top ?? 0) - (containerRect?.top ?? 0) + x = offsetX + rect.x + rect.width / 2 + const elementBottom = offsetY + rect.y + rect.height + const elementTop = offsetY + rect.y + const containerHeight = containerRect?.height ?? 0 + // Show below the element unless it's too close to the bottom edge + below = elementBottom + 52 < containerHeight + y = below ? elementBottom : elementTop + } else if (containerRect) { + x = containerRect.width / 2 + y = containerRect.height / 2 + } + clearTimeout(grabToastTimerRef.current) + setGrabToast({ message, type, x, y, below, payload: payload ?? null }) + grabToastTimerRef.current = setTimeout(() => dismissGrabToast(), 2000) + }, + [dismissGrabToast] + ) + + // Why: auto-copy element context when the user left-clicks to select in + // grab mode. One-click-to-copy is the primary action. Right-click + // (contextMenu=true) skips auto-copy and shows the full action dropdown + // so the user can choose between copy and screenshot. + useEffect(() => { + if (grab.state === 'confirming' && grab.payload && !grab.contextMenu) { + const text = formatGrabPayloadAsText(grab.payload) + void window.api.ui.writeClipboardText(text) + showGrabToast('Copied', 'success', grab.payload) + } + }, [grab.state, grab.payload, grab.contextMenu, showGrabToast]) + useEffect(() => { setAddressBarValue(toDisplayUrl(browserTab.url)) }, [browserTab.url]) @@ -594,11 +671,23 @@ export default function BrowserPane({ return () => window.clearInterval(intervalId) }, [browserTab.id, browserTab.loading]) - // CmdOrCtrl+Shift+G toggles grab mode + // CmdOrCtrl+C toggles grab mode + // Why: Cmd+C is deliberately repurposed inside the browser pane so that the + // most natural "copy" gesture enters grab mode, letting the user visually + // pick and copy an element. Normal text copy inside the webview guest is + // handled by the guest page itself (Chromium's built-in Cmd+C) and never + // reaches the host renderer keydown listener. useEffect(() => { const handleKeyDown = (e: KeyboardEvent): void => { + // Why: let native Cmd+C work in text inputs (address bar, search fields, + // contentEditable regions). Only intercept when focus is on a non-input + // element so grab-mode toggle doesn't swallow copy in form controls. + const tag = (e.target as HTMLElement)?.tagName + if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement)?.isContentEditable) { + return + } const isMod = navigator.userAgent.includes('Mac') ? e.metaKey : e.ctrlKey - if (isMod && e.shiftKey && e.key.toLowerCase() === 'g') { + if (isMod && !e.shiftKey && e.key.toLowerCase() === 'c') { e.preventDefault() grab.toggle() } @@ -635,25 +724,34 @@ export default function BrowserPane({ if (key === 'c') { const text = formatGrabPayloadAsText(payload) void window.api.ui.writeClipboardText(text) - toast.success('Copied element context to clipboard') + showGrabToast('Copied', 'success', payload) } else { const dataUrl = payload.screenshot?.dataUrl if (dataUrl?.startsWith('data:image/png;base64,')) { void window.api.ui.writeClipboardImage(dataUrl) - toast.success('Copied screenshot to clipboard') + showGrabToast('Screenshotted', 'success', payload) } else { - toast.error('No screenshot available') + showGrabToast('No screenshot available', 'error', payload) } } } if (grab.state === 'confirming') { - // Already have the payload from the click selection - const currentPayload = grabPayloadRef.current - if (currentPayload) { - copyFromPayload(currentPayload) + // Why: left-click auto-copies, so only S (screenshot) is useful. + // But right-click (contextMenu) skips auto-copy, so C must still work. + if (grab.contextMenu && key === 'c') { + const currentPayload = grabPayloadRef.current + if (currentPayload) { + copyFromPayload(currentPayload) + } + grab.rearm() + } else if (key === 's') { + const currentPayload = grabPayloadRef.current + if (currentPayload) { + copyFromPayload(currentPayload) + } + grab.rearm() } - grab.rearm() } else { // armed/awaiting — extract hovered element via IPC without clicking void (async () => { @@ -661,7 +759,7 @@ export default function BrowserPane({ browserTabId: browserTabIdRef.current }) if (!result.ok) { - toast.error('No element hovered') + showGrabToast('No element hovered', 'error') return } const payload = result.payload as BrowserGrabPayload @@ -687,29 +785,40 @@ export default function BrowserPane({ } window.addEventListener('keydown', handleKeyDown, true) return () => window.removeEventListener('keydown', handleKeyDown, true) - }, [grab]) + }, [grab, showGrabToast]) - // Why: the copy handlers do NOT call grab.rearm() themselves. Rearm is - // triggered by onOpenChange(false) when the dropdown menu closes after - // item selection. This prevents a double-rearm race that would cause the - // second grab selection's dropdown to fail to appear. + // Why: Radix DropdownMenu fires onOpenChange(false) before onSelect, so + // the rearm in onOpenChange would clear the payload before the handler runs. + // This ref lets onOpenChange skip the rearm when a menu action was taken. + const grabMenuActionTakenRef = useRef(false) + + // Handlers for the right-click context dropdown menu const handleGrabCopy = useCallback(() => { - if (!grab.payload) { + grabMenuActionTakenRef.current = true + const payload = grabPayloadRef.current + if (!payload) { return } - const text = formatGrabPayloadAsText(grab.payload) + const text = formatGrabPayloadAsText(payload) void window.api.ui.writeClipboardText(text) - toast.success('Copied element context to clipboard') - }, [grab]) + showGrabToast('Copied', 'success', payload) + grab.rearm() + }, [grab, showGrabToast]) const handleGrabCopyScreenshot = useCallback(() => { - const dataUrl = grab.payload?.screenshot?.dataUrl + grabMenuActionTakenRef.current = true + const payload = grabPayloadRef.current + if (!payload) { + return + } + const dataUrl = payload.screenshot?.dataUrl if (!dataUrl?.startsWith('data:image/png;base64,')) { return } void window.api.ui.writeClipboardImage(dataUrl) - toast.success('Copied screenshot to clipboard') - }, [grab]) + showGrabToast('Screenshotted', 'success', payload) + grab.rearm() + }, [grab, showGrabToast]) const submitAddressBar = (): void => { const nextUrl = normalizeBrowserNavigationUrl(addressBarValue) @@ -826,7 +935,7 @@ export default function BrowserPane({ variant={grab.state !== 'idle' ? 'default' : 'ghost'} className={`h-8 w-8 ${grab.state !== 'idle' ? 'bg-foreground/80 text-background hover:bg-foreground/90' : ''}`} onClick={grab.toggle} - title={`Grab page element (${navigator.userAgent.includes('Mac') ? '⌘⇧G' : 'Ctrl+Shift+G'})`} + title={`Grab page element (${navigator.userAgent.includes('Mac') ? '⌘C' : 'Ctrl+C'})`} disabled={isBlankTab} > @@ -870,8 +979,8 @@ export default function BrowserPane({ {grab.state === 'error' ? `Grab failed: ${grab.error ?? 'Unknown error'}` : grab.state === 'confirming' - ? 'Element selected — C to copy, S for screenshot' - : 'Hover and press C to copy, S for screenshot, or click to select'} + ? 'Copied — press S for screenshot, or click another element' + : 'Click to copy, or hover and press C. S for screenshot.'} + + + { + const dataUrl = grabToast.payload?.screenshot?.dataUrl + if (dataUrl?.startsWith('data:image/png;base64,')) { + void window.api.ui.writeClipboardImage(dataUrl) + setGrabToast((prev) => + prev ? { ...prev, message: 'Screenshotted' } : null + ) + } + }} + disabled={ + !grabToast.payload?.screenshot?.dataUrl?.startsWith('data:image/png;base64,') + } + > + + Copy Screenshot + S + + + + + + ) : null} ) diff --git a/src/renderer/src/components/browser-pane/useGrabMode.ts b/src/renderer/src/components/browser-pane/useGrabMode.ts index fc271f99e..8289c0d4d 100644 --- a/src/renderer/src/components/browser-pane/useGrabMode.ts +++ b/src/renderer/src/components/browser-pane/useGrabMode.ts @@ -14,6 +14,9 @@ export type GrabModeHook = { state: GrabModeState payload: BrowserGrabPayload | null error: string | null + /** True when the user right-clicked to select, signalling the renderer + * should show the full action menu instead of auto-copying. */ + contextMenu: boolean toggle: () => void cancel: () => void /** Called after Copy — re-arms grab for another pick. */ @@ -37,6 +40,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { const [state, setState] = useState('idle') const [payload, setPayload] = useState(null) const [error, setError] = useState(null) + const [contextMenu, setContextMenu] = useState(false) const activeOpIdRef = useRef(null) const browserTabIdRef = useRef(browserTabId) @@ -88,7 +92,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { activeOpIdRef.current = null - if (result.kind === 'selected') { + if (result.kind === 'selected' || result.kind === 'context-selected') { // Capture screenshot for the selected element let screenshot: BrowserGrabScreenshot | null = null try { @@ -103,6 +107,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { // Screenshot failure is non-fatal } + setContextMenu(result.kind === 'context-selected') setPayload({ ...result.payload, screenshot }) setState('confirming') } else if (result.kind === 'cancelled') { @@ -118,6 +123,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { if (state === 'idle' || state === 'error') { setError(null) setPayload(null) + setContextMenu(false) void armAndAwait() } else { // Disable grab mode @@ -134,6 +140,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { setState('idle') setPayload(null) setError(null) + setContextMenu(false) } }, [state, armAndAwait]) @@ -151,6 +158,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { setState('idle') setPayload(null) setError(null) + setContextMenu(false) }, []) // Why: Copy re-arms so the user can quickly pick another element without @@ -163,6 +171,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { setState('armed') setPayload(null) setError(null) + setContextMenu(false) void armAndAwait() }, [armAndAwait]) @@ -177,6 +186,7 @@ export function useGrabMode(browserTabId: string): GrabModeHook { setState('idle') setPayload(null) setError(null) + setContextMenu(false) }, []) // Keyboard shortcut: Esc cancels grab mode @@ -192,5 +202,5 @@ export function useGrabMode(browserTabId: string): GrabModeHook { return () => window.removeEventListener('keydown', handleKeyDown, true) }, [state, cancel]) - return { state, payload, error, toggle, cancel, rearm, exit } + return { state, payload, error, contextMenu, toggle, cancel, rearm, exit } } diff --git a/src/shared/browser-grab-types.ts b/src/shared/browser-grab-types.ts index 6fe1c191a..fda0ea865 100644 --- a/src/shared/browser-grab-types.ts +++ b/src/shared/browser-grab-types.ts @@ -94,6 +94,7 @@ export type BrowserGrabCancelReason = 'user' | 'tab-inactive' | 'navigation' | ' /** Discriminated union for the result of a single grab operation. */ export type BrowserGrabResult = | { opId: string; kind: 'selected'; payload: BrowserGrabPayload } + | { opId: string; kind: 'context-selected'; payload: BrowserGrabPayload } | { opId: string; kind: 'cancelled'; reason: BrowserGrabCancelReason } | { opId: string; kind: 'error'; reason: string }