Skip to content

Commit

Permalink
Fix stream closing when computer sleeps (#67)
Browse files Browse the repository at this point in the history
We use `<img>` tag to display MJPEG stream of simulator frames. It
appears that after computer goes to sleep, connection between `<img>`
and simulator server is dropped.

This change periodically tries to check if `<img>` contents is decodable
and if not, remounts the image to establish a new connection.

Note: there's similar problem with Vite HMR server. It's easier to test
this change by using production build.

Ref:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode

Fixes #41.
  • Loading branch information
jakub-gonet authored Apr 5, 2024
1 parent 18a064d commit 9856f51
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/vscode-extension/src/webview/components/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ function Preview({ isInspecting, setIsInspecting }: Props) {
const [isPressing, setIsPressing] = useState(false);
const previewRef = useRef<HTMLImageElement>(null);

// used for reestablishing connection to mjpeg stream
const [previewRefreshKey, setPreviewRefreshKey] = useState(0);

const { projectState, project } = useProject();

const hasBuildError = projectState?.status === "buildError";
Expand All @@ -55,6 +58,27 @@ function Preview({ isInspecting, setIsInspecting }: Props) {

const previewURL = projectState?.previewURL;

useEffect(() => {
let timer: NodeJS.Timeout;

async function checkIfImageLoaded() {
try {
if (previewRef.current !== null && previewURL !== undefined) {
// waits until image is ready to be displayed
await previewRef.current.decode();
}
} catch {
// Stream connection was dropped
setPreviewRefreshKey((previousKey) => previousKey + 1);
} finally {
timer = setTimeout(checkIfImageLoaded, 2_000);
}
}
checkIfImageLoaded();

return () => clearTimeout(timer);
}, [previewURL, previewRef]);

const isStarting =
hasBundleError || hasIncrementalBundleError || debugException
? false
Expand Down Expand Up @@ -189,6 +213,7 @@ function Preview({ isInspecting, setIsInspecting }: Props) {
{!isStarting && !hasBuildError && (
<div className="phone-content" {...touchHandlers}>
<img
key={previewRefreshKey}
src={previewURL}
ref={previewRef}
style={{
Expand Down

0 comments on commit 9856f51

Please sign in to comment.