diff --git a/components/remoteDesktop/RdpCanvasView.tsx b/components/remoteDesktop/RdpCanvasView.tsx index 1fea82b97..57ee2cd5d 100644 --- a/components/remoteDesktop/RdpCanvasView.tsx +++ b/components/remoteDesktop/RdpCanvasView.tsx @@ -108,7 +108,7 @@ function extractAuthTokenFromWsUrl(wsUrl: string): string { } } -export const RdpCanvasView = forwardRef( +export const RdpCanvasView = React.memo(forwardRef( function RdpCanvasView( { wsUrl, @@ -141,6 +141,10 @@ export const RdpCanvasView = forwardRef(null); const canvasRef = useRef(null); + const cachedCanvasRectRef = useRef(null); + const pendingPointerRef = useRef<{ x: number; y: number } | null>(null); + const pointerRafRef = useRef(null); + const lastSentPointerRef = useRef<{ x: number; y: number } | null>(null); const imeInputRef = useRef(null); const sessionRef = useRef(null); const modRef = useRef(null); @@ -1122,23 +1126,67 @@ export const RdpCanvasView = forwardRef { + // Keep cached canvas DOMRect in sync so high-frequency pointer moves avoid forced layout reads + useEffect(() => { + const canvas = canvasRef.current; + const container = containerRef.current; + const refreshRect = () => { + cachedCanvasRectRef.current = canvasRef.current?.getBoundingClientRect() ?? null; + }; + refreshRect(); + const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(refreshRect) : null; + if (observer && canvas) observer.observe(canvas); + if (observer && container) observer.observe(container); + window.addEventListener('resize', refreshRect, { passive: true }); + container?.addEventListener('scroll', refreshRect, { passive: true }); + return () => { + observer?.disconnect(); + window.removeEventListener('resize', refreshRect); + container?.removeEventListener('scroll', refreshRect); + if (pointerRafRef.current !== null) { + window.cancelAnimationFrame(pointerRafRef.current); + pointerRafRef.current = null; + } + }; + }, [displayMode, isVisible, remoteSize.height, remoteSize.width]); + + const mapPointerCoords = useCallback((clientX: number, clientY: number, forceMeasure = false) => { const canvas = canvasRef.current; if (!canvas) return { x: 0, y: 0 }; - const rect = canvas.getBoundingClientRect(); + let rect = forceMeasure ? null : cachedCanvasRectRef.current; + if (!rect || rect.width <= 0 || rect.height <= 0) { + rect = canvas.getBoundingClientRect(); + cachedCanvasRectRef.current = rect; + } if (rect.width <= 0 || rect.height <= 0) return { x: 0, y: 0 }; const x = Math.max(0, Math.min(canvas.width - 1, Math.round(((clientX - rect.left) / rect.width) * canvas.width))); const y = Math.max(0, Math.min(canvas.height - 1, Math.round(((clientY - rect.top) / rect.height) * canvas.height))); return { x, y }; }, []); + const flushPendingPointerMove = useCallback(() => { + if (pointerRafRef.current !== null) { + window.cancelAnimationFrame(pointerRafRef.current); + pointerRafRef.current = null; + } + const pending = pendingPointerRef.current; + if (!pending) return; + pendingPointerRef.current = null; + const lastSent = lastSentPointerRef.current; + if (lastSent && lastSent.x === pending.x && lastSent.y === pending.y) return; + lastSentPointerRef.current = pending; + applyDeviceEvents((mod) => [mod.DeviceEvent.mouseMove(pending.x, pending.y)]); + }, [applyDeviceEvents]); + const handleMouseMove = useCallback( (e: React.MouseEvent) => { if (propsRef.current.viewOnly) return; - const { x, y } = mapPointerCoords(e.clientX, e.clientY); - applyDeviceEvents((mod) => [mod.DeviceEvent.mouseMove(x, y)]); + pendingPointerRef.current = mapPointerCoords(e.clientX, e.clientY); + if (pointerRafRef.current === null) { + pointerRafRef.current = window.requestAnimationFrame(flushPendingPointerMove); + } }, - [applyDeviceEvents, mapPointerCoords], + [flushPendingPointerMove, mapPointerCoords], ); const handleMouseDown = useCallback( @@ -1147,7 +1195,13 @@ export const RdpCanvasView = forwardRef [ mod.DeviceEvent.mouseMove(x, y), mod.DeviceEvent.mouseButtonPressed(e.button), @@ -1160,7 +1214,13 @@ export const RdpCanvasView = forwardRef) => { if (propsRef.current.viewOnly) return; e.preventDefault(); + if (pointerRafRef.current !== null) { + window.cancelAnimationFrame(pointerRafRef.current); + pointerRafRef.current = null; + } + pendingPointerRef.current = null; const { x, y } = mapPointerCoords(e.clientX, e.clientY); + lastSentPointerRef.current = { x, y }; applyDeviceEvents((mod) => [ mod.DeviceEvent.mouseMove(x, y), mod.DeviceEvent.mouseButtonReleased(e.button), @@ -1173,6 +1233,7 @@ export const RdpCanvasView = forwardRef) => { if (propsRef.current.viewOnly) return; e.preventDefault(); + flushPendingPointerMove(); const vertical = Math.abs(e.deltaY) >= Math.abs(e.deltaX); const rawDelta = vertical ? -e.deltaY : e.deltaX; if (rawDelta === 0) return; @@ -1190,7 +1251,7 @@ export const RdpCanvasView = forwardRef ); }, -); +)); diff --git a/components/remoteDesktop/RemoteDesktopPane.tsx b/components/remoteDesktop/RemoteDesktopPane.tsx index b8499cf3b..d1ec2202d 100644 --- a/components/remoteDesktop/RemoteDesktopPane.tsx +++ b/components/remoteDesktop/RemoteDesktopPane.tsx @@ -119,7 +119,7 @@ function formatBackendStage(stage: string, isRdp: boolean): string { } } -export const RemoteDesktopPane: React.FC = ({ +export const RemoteDesktopPane: React.FC = React.memo(({ sessionId, workspaceId, protocol, @@ -821,6 +821,115 @@ export const RemoteDesktopPane: React.FC = ({ setConnectAttempt((n) => n + 1); }, []); + const handleToggleKeyboardGrab = useCallback(() => { + applyKeyboardGrab(!keyboardGrabActive); + }, [applyKeyboardGrab, keyboardGrabActive]); + + const handleSendSpecialKey = useCallback((id: RemoteDesktopSpecialKeyId) => { + canvasHandleRef.current?.sendSpecialKey(id); + }, []); + + const handleTypeClipboardClick = useCallback(() => { + void handleTypeClipboard(); + }, [handleTypeClipboard]); + + const handleToggleAudioMute = useCallback(() => { + setAudioMuted((m) => !m); + }, []); + + const handleChangeAudioVolume = useCallback((vol: number) => { + setAudioVolume(vol); + if (vol > 0) setAudioMuted(false); + }, []); + + const handleDismissClipboardTransfer = useCallback(() => { + setClipboardTransfer(null); + setClipboardFileTransferStatus(null); + }, []); + + const handleDownloadClipboardFile = useCallback((idx: number) => { + void canvasHandleRef.current?.downloadRemoteClipboardFile?.(idx); + }, []); + + const handleUploadLocalClipboardFiles = useCallback((files: FileList | File[]) => { + void canvasHandleRef.current?.uploadLocalClipboardFiles?.(files); + }, []); + + const handleAskAiFullClick = useCallback(() => { + void handleAskAiFull(); + }, [handleAskAiFull]); + + const toggleRecording = recorder.toggleRecording; + const handleToggleRecordingClick = useCallback(() => { + void toggleRecording(); + }, [toggleRecording]); + + const handleScreenshotCopyClick = useCallback(() => { + void handleScreenshotCopy(); + }, [handleScreenshotCopy]); + + const handleScreenshotSaveClick = useCallback(() => { + void handleScreenshotSave(); + }, [handleScreenshotSave]); + + const handlePopOutClick = useCallback(() => { + onPopOut?.(sessionId); + }, [onPopOut, sessionId]); + + const handleOpenSystemClientClick = useCallback(() => { + void handleOpenSystemClient(); + }, [handleOpenSystemClient]); + + const handleVncConnected = useCallback( + (info: { width: number; height: number; name?: string; encrypted?: boolean }) => { + setResolution({ width: info.width, height: info.height }); + if (info.name) setDesktopTitle(info.name); + setEncrypted(Boolean(info.encrypted)); + setStageMessage('Desktop connected'); + updateStatus('connected'); + }, + [updateStatus], + ); + + const handleRdpConnected = useCallback( + (info: { width: number; height: number; encrypted?: boolean }) => { + setResolution({ width: info.width, height: info.height }); + setEncrypted(Boolean(info.encrypted)); + setStageMessage('Desktop connected'); + updateStatus('connected'); + }, + [updateStatus], + ); + + const handleRemoteClipboardFilesChange = useCallback( + (files: RemoteDesktopClipboardFileOffer[]) => { + setRemoteClipboardFiles(files); + if (files.length > 0) { + toast.info( + tr( + t, + 'remoteDesktop.clipboard.filesAvailable', + '{{count}} remote file(s) copied — click the clipboard icon in the toolbar to save.', + { count: files.length }, + ), + ); + } + }, + [t], + ); + + const handleGetSnipCanvasRect = useCallback( + () => canvasHandleRef.current?.getCanvasRect?.() ?? null, + [], + ); + + const handleSnipSelectClick = useCallback( + (rect: RemoteDesktopSnipRect) => { + void handleSnipSelect(rect); + }, + [handleSnipSelect], + ); + const showRemoteAppNotice = isRdp && Boolean(spec.rdpConfig?.remoteApplicationMode) && !remoteAppBannerDismissed; @@ -846,37 +955,31 @@ export const RemoteDesktopPane: React.FC = ({ fps={fps} isFullscreen={isFullscreen} keyboardGrabActive={keyboardGrabActive} - onToggleKeyboardGrab={() => applyKeyboardGrab(!keyboardGrabActive)} - onSendSpecialKey={(id: RemoteDesktopSpecialKeyId) => canvasHandleRef.current?.sendSpecialKey(id)} - onTypeClipboard={() => void handleTypeClipboard()} + onToggleKeyboardGrab={handleToggleKeyboardGrab} + onSendSpecialKey={handleSendSpecialKey} + onTypeClipboard={handleTypeClipboardClick} displayMode={displayMode} onChangeDisplayMode={setDisplayMode} audioEnabled={isRdp && Boolean(spec.rdpConfig?.audioEnabled)} audioMuted={audioMuted} audioVolume={audioVolume} - onToggleAudioMute={() => setAudioMuted((m) => !m)} - onChangeAudioVolume={(vol) => { - setAudioVolume(vol); - if (vol > 0 && audioMuted) setAudioMuted(false); - }} + onToggleAudioMute={handleToggleAudioMute} + onChangeAudioVolume={handleChangeAudioVolume} clipboardSyncEnabled={clipboardSyncEnabled} onToggleClipboardSync={setClipboardSyncEnabled} remoteClipboardFiles={remoteClipboardFiles} clipboardFileTransferStatus={clipboardFileTransferStatus} clipboardTransfer={clipboardTransfer} - onDismissClipboardTransfer={() => { - setClipboardTransfer(null); - setClipboardFileTransferStatus(null); - }} - onDownloadClipboardFile={(idx) => void canvasHandleRef.current?.downloadRemoteClipboardFile?.(idx)} + onDismissClipboardTransfer={handleDismissClipboardTransfer} + onDownloadClipboardFile={handleDownloadClipboardFile} onUploadLocalClipboardFiles={ isRdp && spec.rdpConfig?.clipboardFilesEnabled - ? (files) => void canvasHandleRef.current?.uploadLocalClipboardFiles?.(files) + ? handleUploadLocalClipboardFiles : undefined } onOpenSftp={onOpenSftp ? handleOpenSftpClick : undefined} isSftpOpen={isSftpOpen} - onAskAiFull={onAskAi ? () => void handleAskAiFull() : undefined} + onAskAiFull={onAskAi ? handleAskAiFullClick : undefined} onAskAiRegion={onAskAi ? handleStartAskAiRegion : undefined} onOpenAiChat={onAskAi ? handleOpenAiChat : undefined} aiReadBlocked={aiReadBlocked} @@ -884,16 +987,16 @@ export const RemoteDesktopPane: React.FC = ({ isRecording={recorder.isRecording} recordingElapsedLabel={recorder.formattedElapsed} recordingSupported={recorder.isSupported} - onToggleRecording={() => void recorder.toggleRecording()} + onToggleRecording={handleToggleRecordingClick} quality={quality} onChangeQuality={setQuality} viewOnly={viewOnly} onToggleViewOnly={setViewOnly} - onScreenshotCopy={() => void handleScreenshotCopy()} - onScreenshotSave={() => void handleScreenshotSave()} + onScreenshotCopy={handleScreenshotCopyClick} + onScreenshotSave={handleScreenshotSaveClick} onToggleFullscreen={handleToggleFullscreen} - onPopOut={onPopOut ? () => onPopOut(sessionId) : undefined} - onOpenSystemClient={() => void handleOpenSystemClient()} + onPopOut={onPopOut ? handlePopOutClick : undefined} + onOpenSystemClient={handleOpenSystemClientClick} onReconnect={handleReconnect} onDisconnect={handleDisconnect} /> @@ -946,13 +1049,7 @@ export const RemoteDesktopPane: React.FC = ({ showRemoteCursor={spec.vncConfig?.showRemoteCursor ?? true} keyboardGrabActive={keyboardGrabActive} onRequestReleaseGrab={releaseKeyboardGrab} - onConnected={(info) => { - setResolution({ width: info.width, height: info.height }); - if (info.name) setDesktopTitle(info.name); - setEncrypted(Boolean(info.encrypted)); - setStageMessage('Desktop connected'); - updateStatus('connected'); - }} + onConnected={handleVncConnected} onDesktopResize={setResolution} onDesktopName={setDesktopTitle} onFpsChange={setFps} @@ -980,26 +1077,9 @@ export const RemoteDesktopPane: React.FC = ({ audioVolume={audioVolume} keyboardGrabActive={keyboardGrabActive} onRequestReleaseGrab={releaseKeyboardGrab} - onConnected={(info) => { - setResolution({ width: info.width, height: info.height }); - setEncrypted(Boolean(info.encrypted)); - setStageMessage('Desktop connected'); - updateStatus('connected'); - }} + onConnected={handleRdpConnected} onDesktopResize={setResolution} - onRemoteClipboardFilesChange={(files) => { - setRemoteClipboardFiles(files); - if (files.length > 0) { - toast.info( - tr( - t, - 'remoteDesktop.clipboard.filesAvailable', - '{{count}} remote file(s) copied — click the clipboard icon in the toolbar to save.', - { count: files.length }, - ), - ); - } - }} + onRemoteClipboardFilesChange={handleRemoteClipboardFilesChange} onClipboardFileTransferStatus={setClipboardFileTransferStatus} onClipboardTransferChange={handleClipboardTransferChange} onNegotiationFallbackNeeded={handleNegotiationFallback} @@ -1046,8 +1126,8 @@ export const RemoteDesktopPane: React.FC = ({ open={isSnipping && status === 'connected'} naturalWidth={resolution?.width || 1280} naturalHeight={resolution?.height || 800} - getCanvasRect={() => canvasHandleRef.current?.getCanvasRect?.() ?? null} - onSelect={(rect) => void handleSnipSelect(rect)} + getCanvasRect={handleGetSnipCanvasRect} + onSelect={handleSnipSelectClick} onCancel={() => setIsSnipping(false)} /> @@ -1304,6 +1384,7 @@ export const RemoteDesktopPane: React.FC = ({ ); -}; +}); +RemoteDesktopPane.displayName = 'RemoteDesktopPane'; export default RemoteDesktopPane; diff --git a/components/remoteDesktop/RemoteDesktopSnipOverlay.tsx b/components/remoteDesktop/RemoteDesktopSnipOverlay.tsx index a12c6bd51..299bf8944 100644 --- a/components/remoteDesktop/RemoteDesktopSnipOverlay.tsx +++ b/components/remoteDesktop/RemoteDesktopSnipOverlay.tsx @@ -123,11 +123,28 @@ export const RemoteDesktopSnipOverlay: React.FC = }) => { const { t } = useI18n(); const overlayRef = useRef(null); - const dragStartRef = useRef<{ x: number; y: number; pointerId: number } | null>(null); + const dragStartRef = useRef<{ + x: number; + y: number; + pointerId: number; + overlayRect: SnipClientRect; + canvasRect: SnipClientRect; + } | null>(null); + const pendingDragPointRef = useRef<{ x: number; y: number } | null>(null); + const dragRafRef = useRef(null); const [selection, setSelection] = useState(null); + const cancelPendingDragRaf = useCallback(() => { + if (dragRafRef.current !== null) { + window.cancelAnimationFrame(dragRafRef.current); + dragRafRef.current = null; + } + pendingDragPointRef.current = null; + }, []); + useEffect(() => { if (!open) { + cancelPendingDragRaf(); dragStartRef.current = null; setSelection(null); return; @@ -136,71 +153,90 @@ export const RemoteDesktopSnipOverlay: React.FC = if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); + cancelPendingDragRaf(); dragStartRef.current = null; setSelection(null); onCancel(); } }; window.addEventListener('keydown', handleKeyDown, true); - return () => window.removeEventListener('keydown', handleKeyDown, true); - }, [open, onCancel]); - - const computeFromPoints = useCallback(( - start: { x: number; y: number }, - current: { x: number; y: number }, - ): ComputedSnipSelection | null => { - const overlayEl = overlayRef.current; - if (!overlayEl) return null; - const overlayRect = overlayEl.getBoundingClientRect(); - const canvasRect = getCanvasRect?.() ?? overlayRect; - return computeSnipSelectionRect( - start, - current, - overlayRect, - canvasRect, - naturalWidth, - naturalHeight, - ); - }, [getCanvasRect, naturalWidth, naturalHeight]); + return () => { + cancelPendingDragRaf(); + window.removeEventListener('keydown', handleKeyDown, true); + }; + }, [cancelPendingDragRaf, open, onCancel]); const handlePointerDown = useCallback((event: React.PointerEvent) => { if (event.button !== 0) return; if ((event.target as HTMLElement | null)?.closest('[data-snip-control="true"]')) { return; } + const overlayEl = overlayRef.current; + if (!overlayEl) return; event.preventDefault(); event.stopPropagation(); + const overlayRect = overlayEl.getBoundingClientRect(); + const canvasRect = getCanvasRect?.() ?? overlayRect; dragStartRef.current = { x: event.clientX, y: event.clientY, pointerId: event.pointerId, + overlayRect, + canvasRect, }; setSelection(null); event.currentTarget.setPointerCapture(event.pointerId); - }, []); + }, [getCanvasRect]); const handlePointerMove = useCallback((event: React.PointerEvent) => { const start = dragStartRef.current; if (!start || start.pointerId !== event.pointerId) return; event.preventDefault(); - setSelection(computeFromPoints(start, { x: event.clientX, y: event.clientY })); - }, [computeFromPoints]); + pendingDragPointRef.current = { x: event.clientX, y: event.clientY }; + if (dragRafRef.current === null) { + dragRafRef.current = window.requestAnimationFrame(() => { + dragRafRef.current = null; + const activeStart = dragStartRef.current; + const currentPoint = pendingDragPointRef.current; + pendingDragPointRef.current = null; + if (!activeStart || !currentPoint) return; + setSelection( + computeSnipSelectionRect( + activeStart, + currentPoint, + activeStart.overlayRect, + activeStart.canvasRect, + naturalWidth, + naturalHeight, + ), + ); + }); + } + }, [naturalHeight, naturalWidth]); const finishDrag = useCallback((event: React.PointerEvent, commit: boolean) => { const start = dragStartRef.current; if (!start || start.pointerId !== event.pointerId) return; + cancelPendingDragRaf(); dragStartRef.current = null; if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } const finalSelection = commit - ? computeFromPoints(start, { x: event.clientX, y: event.clientY }) + ? computeSnipSelectionRect( + start, + { x: event.clientX, y: event.clientY }, + start.overlayRect, + start.canvasRect, + naturalWidth, + naturalHeight, + ) : null; setSelection(null); if (commit && finalSelection) { onSelect(finalSelection.normalizedRect); } - }, [computeFromPoints, onSelect]); + }, [cancelPendingDragRaf, naturalHeight, naturalWidth, onSelect]); if (!open) return null; diff --git a/components/remoteDesktop/RemoteDesktopToolbar.tsx b/components/remoteDesktop/RemoteDesktopToolbar.tsx index 8608c580e..d71042e25 100644 --- a/components/remoteDesktop/RemoteDesktopToolbar.tsx +++ b/components/remoteDesktop/RemoteDesktopToolbar.tsx @@ -229,7 +229,7 @@ const QUALITY_OPTIONS: ReadonlyArray<{ { id: 'lossless', fallback: 'Lossless', badge: 'Raw' }, ]; -export const RemoteDesktopToolbar: React.FC = ({ +export const RemoteDesktopToolbar: React.FC = React.memo(({ protocol, hostLabel, status, @@ -1196,4 +1196,4 @@ export const RemoteDesktopToolbar: React.FC = ({ ); -}; +}); diff --git a/components/remoteDesktop/VncCanvasView.tsx b/components/remoteDesktop/VncCanvasView.tsx index de81231ad..8e27cb286 100644 --- a/components/remoteDesktop/VncCanvasView.tsx +++ b/components/remoteDesktop/VncCanvasView.tsx @@ -131,7 +131,7 @@ function buildRefreshFrame(incremental: boolean): Uint8Array { return new Uint8Array([C2S.REFRESH, incremental ? 1 : 0]); } -export const VncCanvasView = forwardRef( +export const VncCanvasView = React.memo(forwardRef( function VncCanvasView( { wsUrl, @@ -153,6 +153,13 @@ export const VncCanvasView = forwardRef(null); const canvasRef = useRef(null); + const ctxRef = useRef(null); + const cursorCanvasRef = useRef(null); + const lastCursorCacheRef = useRef<{ key: string; css: string } | null>(null); + const cachedCanvasRectRef = useRef(null); + const pendingPointerRef = useRef<{ x: number; y: number } | null>(null); + const pointerRafRef = useRef(null); + const lastSentPointerRef = useRef<{ x: number; y: number; buttons: number } | null>(null); const imeInputRef = useRef(null); const wsRef = useRef(null); const supportsRef = useRef<{ extendedDesktopSize?: boolean; qemuExtendedKeyEvent?: boolean }>({}); @@ -163,9 +170,22 @@ export const VncCanvasView = forwardRef>(Promise.resolve()); const frameCountRef = useRef(0); + const lastReportedFpsRef = useRef(null); const [remoteSize, setRemoteSize] = useState<{ width: number; height: number }>({ width: 1280, height: 800 }); const [cursorCss, setCursorCss] = useState('default'); + const getCanvasContext = useCallback((): CanvasRenderingContext2D | null => { + const canvas = canvasRef.current; + if (!canvas) { + ctxRef.current = null; + return null; + } + if (!ctxRef.current || ctxRef.current.canvas !== canvas) { + ctxRef.current = canvas.getContext('2d', { alpha: false }) ?? canvas.getContext('2d'); + } + return ctxRef.current; + }, []); + // Keep latest callbacks in refs so WS effect never tears down on re-renders. const callbacksRef = useRef({ onConnected, @@ -318,11 +338,14 @@ export const VncCanvasView = forwardRef