I have a web app that runs under Tauri. The app is mostly a 2D Canvas that draws itself scaled to the window
. It listens for resize
events to respond to changes to the window size. It works pretty well.
Now I’ve decided I want to save the window’s size and position when they are changed, and restore them when the app is started. I’ve implemented a solution in the Rust code that nearly works. It successfully handles storing the size and position when they change and reading those values and moving/sizing the window when it starts. The problem is that the app’s contents are not scaled to the size that is set in the Rust code. (I expected Tauri to send the DOM a ‘resize’ event, which the Typescript is listening for, when the wrapper’s size changed, but it doesn’t.)
I thought I might be able to emit a custom event from the Tauri side when the size is initialized and then listen for it in the Typescript, but I can’t seem to work out how to do it.
The Rust code gets the main window and sends the event like this:
fn setup_window(window: &Window) {
if let Some(window_settings) = Config::window_settings() {
window.set_size(window_settings.size()).unwrap();
window.set_position(window_settings.position()).unwrap();
window.emit("setsize", window_settings).expect("Couldn't send setsize event to window");
}
}
I tried the following code in main.ts
, but it doesn’t work. Specifically, it prevents the contents of the window from being drawn at all.
import { appWindow } from "@tauri-apps/api/window";
let unlisten = await appWindow.once("setsize", ({ event, payload }) => {
console.log(`event payload: ${payload}`);
set_size();
});
unlisten();
I thought deferring the code until the other code was set up might help, so I tried this:
window.addEventListener("DOMContentLoaded", async () => {
let canvas = document.querySelector("#canvas") as HTMLCanvasElement;
g_app = new App(canvas);
run();
let unlisten = await appWindow.once("setsize", ({ event, payload }) => {
console.log(`event payload: ${payload}`);
set_size();
});
unlisten();
function run() {
g_app?.render();
requestAnimationFrame(run);
}
});
That at least doesn’t prevent the canvas from being rendered, but the event is never recieved–the window isn’t resized and the console isn’t logged to.
The information I’ve found online seems to imply that what I’m trying to do is valid, but stops short of demonstrating how to actually do it, so I’m asking for guidance.