perf(remote-desktop): coalesce pointer/snip events, zero-copy VNC paint, and memoize views

This commit is contained in:
bincxz committed 2026-11-26 18:17:12 +08:00
1 parent 645d7a4f5d
commit 8ae0e17501
7 files changed
+401 -116

No files matched your search

+70 -9
View File
@@ -108,7 +108,7 @@ function extractAuthTokenFromWsUrl(wsUrl: string): string {
}
}
export const RdpCanvasView = forwardRef<RemoteDesktopCanvasHandle, RdpCanvasViewProps>(
export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, RdpCanvasViewProps>(
function RdpCanvasView(
{
wsUrl,
@@ -141,6 +141,10 @@ export const RdpCanvasView = forwardRef<RemoteDesktopCanvasHandle, RdpCanvasView
const { t } = useI18n();
const containerRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const cachedCanvasRectRef = useRef<DOMRect | null>(null);
const pendingPointerRef = useRef<{ x: number; y: number } | null>(null);
const pointerRafRef = useRef<number | null>(null);
const lastSentPointerRef = useRef<{ x: number; y: number } | null>(null);
const imeInputRef = useRef<HTMLTextAreaElement | null>(null);
const sessionRef = useRef<IronSession | null>(null);
const modRef = useRef<IronRdpModule | null>(null);
@@ -1122,23 +1126,67 @@ export const RdpCanvasView = forwardRef<RemoteDesktopCanvasHandle, RdpCanvasView
};
}, [displayMode, remoteSize.height, remoteSize.width]);
const mapPointerCoords = useCallback((clientX: number, clientY: number) => {
// 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<HTMLCanvasElement>) => {
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<RemoteDesktopCanvasHandle, RdpCanvasView
audioPlayerRef.current?.resume();
if (propsRef.current.viewOnly) return;
e.preventDefault();
const { x, y } = mapPointerCoords(e.clientX, e.clientY);
if (pointerRafRef.current !== null) {
window.cancelAnimationFrame(pointerRafRef.current);
pointerRafRef.current = null;
}
pendingPointerRef.current = null;
const { x, y } = mapPointerCoords(e.clientX, e.clientY, true);
lastSentPointerRef.current = { x, y };
applyDeviceEvents((mod) => [
mod.DeviceEvent.mouseMove(x, y),
mod.DeviceEvent.mouseButtonPressed(e.button),
@@ -1160,7 +1214,13 @@ export const RdpCanvasView = forwardRef<RemoteDesktopCanvasHandle, RdpCanvasView
(e: React.MouseEvent<HTMLCanvasElement>) => {
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<RemoteDesktopCanvasHandle, RdpCanvasView
(e: React.WheelEvent<HTMLCanvasElement>) => {
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<RemoteDesktopCanvasHandle, RdpCanvasView
return [mod.DeviceEvent.wheelRotations(vertical, amount, unit)];
});
},
[applyDeviceEvents],
[applyDeviceEvents, flushPendingPointerMove],
);
const handleKeyDown = useCallback(
@@ -1517,4 +1578,4 @@ export const RdpCanvasView = forwardRef<RemoteDesktopCanvasHandle, RdpCanvasView
</div>
);
},
);
));
+131 -50
View File
@@ -119,7 +119,7 @@ function formatBackendStage(stage: string, isRdp: boolean): string {
}
}
export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = ({
export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
sessionId,
workspaceId,
protocol,
@@ -821,6 +821,115 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
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<RemoteDesktopPaneProps> = ({
</div>
</div>
);
};
});
RemoteDesktopPane.displayName = 'RemoteDesktopPane';
export default RemoteDesktopPane;
@@ -123,11 +123,28 @@ export const RemoteDesktopSnipOverlay: React.FC<RemoteDesktopSnipOverlayProps> =
}) => {
const { t } = useI18n();
const overlayRef = useRef<HTMLDivElement>(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<number | null>(null);
const [selection, setSelection] = useState<ComputedSnipSelection | null>(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<RemoteDesktopSnipOverlayProps> =
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
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<HTMLDivElement>, 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;
@@ -229,7 +229,7 @@ const QUALITY_OPTIONS: ReadonlyArray<{
{ id: 'lossless', fallback: 'Lossless', badge: 'Raw' },
];
export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = ({
export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.memo(({
protocol,
hostLabel,
status,
@@ -1196,4 +1196,4 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = ({
</div>
</div>
);
};
});
+123 -25
View File
@@ -131,7 +131,7 @@ function buildRefreshFrame(incremental: boolean): Uint8Array {
return new Uint8Array([C2S.REFRESH, incremental ? 1 : 0]);
}
export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasViewProps>(
export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, VncCanvasViewProps>(
function VncCanvasView(
{
wsUrl,
@@ -153,6 +153,13 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
) {
const containerRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const cursorCanvasRef = useRef<HTMLCanvasElement | null>(null);
const lastCursorCacheRef = useRef<{ key: string; css: string } | null>(null);
const cachedCanvasRectRef = useRef<DOMRect | null>(null);
const pendingPointerRef = useRef<{ x: number; y: number } | null>(null);
const pointerRafRef = useRef<number | null>(null);
const lastSentPointerRef = useRef<{ x: number; y: number; buttons: number } | null>(null);
const imeInputRef = useRef<HTMLTextAreaElement | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const supportsRef = useRef<{ extendedDesktopSize?: boolean; qemuExtendedKeyEvent?: boolean }>({});
@@ -163,9 +170,22 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
const lastAltRightUpRef = useRef(0);
const paintChainRef = useRef<Promise<void>>(Promise.resolve());
const frameCountRef = useRef(0);
const lastReportedFpsRef = useRef<number | null>(null);
const [remoteSize, setRemoteSize] = useState<{ width: number; height: number }>({ width: 1280, height: 800 });
const [cursorCss, setCursorCss] = useState<string>('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<RemoteDesktopCanvasHandle, VncCanvasView
],
);
// FPS telemetry ticker
// FPS telemetry ticker (skips hidden tabs and deduplicates unchanged values)
useEffect(() => {
const timer = window.setInterval(() => {
const frames = frameCountRef.current;
frameCountRef.current = 0;
if (!propsRef.current.isVisible) return;
if (lastReportedFpsRef.current === frames) return;
lastReportedFpsRef.current = frames;
callbacksRef.current.onFpsChange?.(frames);
}, 1000);
return () => window.clearInterval(timer);
@@ -411,12 +434,12 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
const h = view.getUint16(7, false);
const expectedLen = w * h * 4;
if (w === 0 || h === 0 || bytes.byteLength < 9 + expectedLen) break;
const pixelCopy = new Uint8ClampedArray(bytes.subarray(9, 9 + expectedLen));
// Zero-copy view over the owned WebSocket ArrayBuffer
const pixelView = new Uint8ClampedArray(event.data, 9, expectedLen);
enqueuePaint(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
const ctx = getCanvasContext();
if (!ctx) return;
const imgData = new ImageData(pixelCopy, w, h);
const imgData = new ImageData(pixelView, w, h);
ctx.putImageData(imgData, x, y);
});
break;
@@ -433,7 +456,7 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
if (w === 0 || h === 0) break;
enqueuePaint(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
const ctx = getCanvasContext();
if (!canvas || !ctx) return;
ctx.drawImage(canvas, srcX, srcY, w, h, x, y, w, h);
});
@@ -447,15 +470,14 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
const w = view.getUint16(5, false);
const h = view.getUint16(7, false);
if (w === 0 || h === 0) break;
const jpegBlob = new Blob([bytes.slice(9)], { type: 'image/jpeg' });
const jpegBlob = new Blob([bytes.subarray(9)], { type: 'image/jpeg' });
const bitmapPromise = createImageBitmap(jpegBlob).catch(() => null);
enqueuePaint(async () => {
const bitmap = await bitmapPromise;
if (!bitmap) return;
try {
if (disposed) return;
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
const ctx = getCanvasContext();
if (!ctx) return;
ctx.drawImage(bitmap, x, y, w, h);
} finally {
@@ -472,24 +494,39 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
const w = view.getUint16(5, false);
const h = view.getUint16(7, false);
if (!propsRef.current.showRemoteCursor) {
setCursorCss('default');
setCursorCss((prev) => (prev === 'default' ? prev : 'default'));
break;
}
if (w === 0 || h === 0) {
setCursorCss('none');
setCursorCss((prev) => (prev === 'none' ? prev : 'none'));
break;
}
const expectedLen = w * h * 4;
if (bytes.byteLength < 9 + expectedLen) break;
const offscreen = document.createElement('canvas');
offscreen.width = w;
offscreen.height = h;
// Fast FNV-1a fingerprint avoids re-encoding identical remote cursor bitmaps
let hash = 0x811c9dc5;
for (let i = 9; i < 9 + expectedLen; i += 4) {
hash ^= bytes[i] ^ (bytes[i + 1] << 8) ^ (bytes[i + 2] << 16) ^ (bytes[i + 3] << 24);
hash = Math.imul(hash, 0x01000193);
}
const cursorKey = `${w}x${h}:${hotX},${hotY}:${hash >>> 0}`;
if (lastCursorCacheRef.current?.key === cursorKey) {
const cachedCss = lastCursorCacheRef.current.css;
setCursorCss((prev) => (prev === cachedCss ? prev : cachedCss));
break;
}
const offscreen = cursorCanvasRef.current ?? document.createElement('canvas');
cursorCanvasRef.current = offscreen;
if (offscreen.width !== w) offscreen.width = w;
if (offscreen.height !== h) offscreen.height = h;
const offCtx = offscreen.getContext('2d');
if (offCtx) {
const imgData = new ImageData(new Uint8ClampedArray(bytes.subarray(9, 9 + expectedLen)), w, h);
const imgData = new ImageData(new Uint8ClampedArray(event.data, 9, expectedLen), w, h);
offCtx.putImageData(imgData, 0, 0);
const url = offscreen.toDataURL('image/png');
setCursorCss(`url("${url}") ${hotX} ${hotY}, auto`);
const css = `url("${url}") ${hotX} ${hotY}, auto`;
lastCursorCacheRef.current = { key: cursorKey, css };
setCursorCss((prev) => (prev === css ? prev : css));
}
break;
}
@@ -568,7 +605,31 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
ws.close();
} catch { /* ignore */ }
};
}, [resizeBackingCanvas, wsUrl]);
}, [getCanvasContext, resizeBackingCanvas, wsUrl]);
// 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]);
// Debounced dynamic resize when container size changes
useEffect(() => {
@@ -615,16 +676,37 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
.catch(() => {});
}, [sendBinary]);
const mapPointerCoords = useCallback((clientX: number, clientY: number) => {
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 buttons = buttonsMaskRef.current;
const lastSent = lastSentPointerRef.current;
if (lastSent && lastSent.x === pending.x && lastSent.y === pending.y && lastSent.buttons === buttons) {
return;
}
lastSentPointerRef.current = { x: pending.x, y: pending.y, buttons };
sendBinary(buildPointerFrame(pending.x, pending.y, buttons));
}, [sendBinary]);
const updateButtonBit = (button: number, down: boolean) => {
let bit = 0;
if (button === 0) bit = 1;
@@ -640,9 +722,12 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
if (propsRef.current.viewOnly) return;
const pos = mapPointerCoords(e.clientX, e.clientY);
lastPointerPosRef.current = pos;
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
pendingPointerRef.current = pos;
if (pointerRafRef.current === null) {
pointerRafRef.current = window.requestAnimationFrame(flushPendingPointerMove);
}
},
[mapPointerCoords, sendBinary],
[flushPendingPointerMove, mapPointerCoords],
);
const handleMouseDown = useCallback(
@@ -650,9 +735,15 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
imeInputRef.current?.focus({ preventScroll: true });
if (propsRef.current.viewOnly) return;
e.preventDefault();
const pos = mapPointerCoords(e.clientX, e.clientY);
if (pointerRafRef.current !== null) {
window.cancelAnimationFrame(pointerRafRef.current);
pointerRafRef.current = null;
}
pendingPointerRef.current = null;
const pos = mapPointerCoords(e.clientX, e.clientY, true);
lastPointerPosRef.current = pos;
updateButtonBit(e.button, true);
lastSentPointerRef.current = { x: pos.x, y: pos.y, buttons: buttonsMaskRef.current };
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
},
[mapPointerCoords, sendBinary],
@@ -662,9 +753,15 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
(e: React.MouseEvent<HTMLCanvasElement>) => {
if (propsRef.current.viewOnly) return;
e.preventDefault();
if (pointerRafRef.current !== null) {
window.cancelAnimationFrame(pointerRafRef.current);
pointerRafRef.current = null;
}
pendingPointerRef.current = null;
const pos = mapPointerCoords(e.clientX, e.clientY);
lastPointerPosRef.current = pos;
updateButtonBit(e.button, false);
lastSentPointerRef.current = { x: pos.x, y: pos.y, buttons: buttonsMaskRef.current };
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
},
[mapPointerCoords, sendBinary],
@@ -674,6 +771,7 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
(e: React.WheelEvent<HTMLCanvasElement>) => {
if (propsRef.current.viewOnly) return;
e.preventDefault();
flushPendingPointerMove();
const pos = mapPointerCoords(e.clientX, e.clientY);
lastPointerPosRef.current = pos;
let wheelBit = 0;
@@ -686,7 +784,7 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current | wheelBit));
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
},
[mapPointerCoords, sendBinary],
[flushPendingPointerMove, mapPointerCoords, sendBinary],
);
const handleKeyDown = useCallback(
@@ -831,4 +929,4 @@ export const VncCanvasView = forwardRef<RemoteDesktopCanvasHandle, VncCanvasView
</div>
);
},
);
));
@@ -283,7 +283,7 @@ export function useRemoteDesktopRecorder({
};
}, []);
// Elapsed timer while recording
// Elapsed timer while recording (1s granularity avoids redundant React re-renders)
useEffect(() => {
if (!isRecording) {
setElapsedMs(0);
@@ -292,9 +292,12 @@ export function useRemoteDesktopRecorder({
const timer = window.setInterval(() => {
const run = activeRunRef.current;
if (run) {
setElapsedMs(Math.max(0, Date.now() - run.startedAt));
const nextMs = Math.max(0, Date.now() - run.startedAt);
setElapsedMs((prev) =>
Math.floor(prev / 1000) === Math.floor(nextMs / 1000) ? prev : nextMs,
);
}
}, 500);
}, 1000);
return () => window.clearInterval(timer);
}, [isRecording]);
@@ -1803,6 +1803,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
},
[session.id],
);
const handleRemoteDesktopStatusChange = useCallback(
(sid: string, nextStatus: 'connecting' | 'connected' | 'disconnected') => {
onStatusChange(sid, nextStatus);
},
[onStatusChange],
);
return (
<div
@@ -1843,7 +1849,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
isVisible={isVisible}
isFocused={isFocusedPane}
inWorkspace={keepsWorkspacePresentation}
onStatusChange={(sid, nextStatus) => onStatusChange(sid, nextStatus)}
onStatusChange={handleRemoteDesktopStatusChange}
onCloseSession={onCloseSession}
onPopOut={onCopySessionToNewWindow}
onOpenSftp={canOpenCompanionSftp ? handleOpenCompanionSftp : undefined}