Add Tauri v2 desktop app alongside Electron
- New tauri/ project: frameless 1280x800 window, loads the Vite dev server in dev and tauri/frontend_build in release builds. - Starts the backend on launch (node server.js in dev, pkg backend.exe sidecar in release) and stops it on exit through a Windows job object; reuses a backend already listening on port 4000. - Custom title bar works in Tauri (minimize, maximize, close, drag region) with the matching window capabilities. - react_frontend: dev:tauri / build:tauri scripts, shared platform flags so Electron and Tauri builds both use the local API and hash router. Web and Electron builds are unchanged. - tauri/README.md: prerequisites, dev, build, and gaps vs Electron.
This commit is contained in:
1 parent
06bf902ad3
commit
3144bd96c9
30 files changed
+5121
-14
No files matched your search
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
frontend_build
|
||||
src-tauri/target
|
||||
src-tauri/gen
|
||||
src-tauri/binaries/*
|
||||
!src-tauri/binaries/.gitkeep
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
# Showy — Tauri desktop app
|
||||
|
||||
A Tauri v2 shell for Showy, built side by side with the Electron app in `../electron`
|
||||
(which stays untouched). It loads the React frontend from `../react_frontend` and
|
||||
starts the Node backend from `../backend` alongside the window.
|
||||
|
||||
```
|
||||
tauri/
|
||||
├─ package.json # Tauri CLI + scripts
|
||||
├─ scripts/prepare-sidecar.mjs # copies dist/backend/backend.exe into src-tauri/binaries
|
||||
├─ frontend_build/ # output of `pnpm build:tauri` (git-ignored)
|
||||
└─ src-tauri/
|
||||
├─ tauri.conf.json # window, dev URL, frontend dist, bundle
|
||||
├─ tauri.bundle.conf.json # adds the backend sidecar; merged in only for `pnpm build`
|
||||
├─ capabilities/default.json # window permissions for the custom title bar
|
||||
├─ icons/ # generated from electron/assets/icon.ico
|
||||
└─ src/
|
||||
├─ lib.rs # app setup, stops the backend on exit
|
||||
└─ backend.rs # starts/stops the backend process
|
||||
```
|
||||
|
||||
## Prerequisites (Windows)
|
||||
|
||||
- **Rust** (stable, MSVC toolchain): install with [rustup](https://rustup.rs/), target
|
||||
`x86_64-pc-windows-msvc`.
|
||||
- **Microsoft C++ Build Tools**: "Desktop development with C++" workload from Visual Studio
|
||||
Build Tools (needed by the MSVC Rust toolchain).
|
||||
- **WebView2 runtime**: preinstalled on Windows 11. On Windows 10 install the Evergreen
|
||||
runtime from Microsoft.
|
||||
- **Node.js** (22.x is used here) and **pnpm**.
|
||||
- **Tauri CLI**: installed per project as `@tauri-apps/cli` (`pnpm install` in this folder).
|
||||
`cargo install tauri-cli --version "^2"` also works if you prefer `cargo tauri ...`.
|
||||
- For the backend: a running **MySQL** and `backend/settings.json` (see
|
||||
`backend/settings.json.example`), with dependencies installed in `backend/`.
|
||||
|
||||
## Run in dev
|
||||
|
||||
```bash
|
||||
cd react_frontend && pnpm install
|
||||
cd ../backend && pnpm install
|
||||
cd ../tauri && pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
`pnpm dev` (= `tauri dev`) does the following:
|
||||
|
||||
1. Runs `pnpm --dir ../react_frontend dev:tauri`: Vite on `http://localhost:4200` with
|
||||
`VITE_TAURI=true` (API base `http://localhost:4000/api/v1`, hash router, custom title bar).
|
||||
2. Builds and starts the Rust app, which opens the window on the dev server (with hot reload)
|
||||
and opens DevTools, like Electron's dev mode (set `SHOWY_NO_DEVTOOLS=1` to skip).
|
||||
3. Starts the backend with `node server.js` in `../backend`. Its output shows in the same
|
||||
terminal. When the window closes the backend is stopped, and so is anything it spawned (a
|
||||
Windows job object kills the process tree, even if the app crashes).
|
||||
|
||||
If something already listens on port 4000 (e.g. you run `pnpm dev` in `backend/` yourself), the
|
||||
app does **not** start a second backend and uses the one that is running.
|
||||
|
||||
Environment overrides:
|
||||
|
||||
| Variable | Effect |
|
||||
| --- | --- |
|
||||
| `SHOWY_SKIP_BACKEND=1` | never start a backend |
|
||||
| `SHOWY_BACKEND_DIR=<path>` | backend folder for dev builds (default `../backend`) |
|
||||
| `SHOWY_BACKEND_EXE=<path>` | run this executable as the backend (dev or release) |
|
||||
| `SHOWY_NO_DEVTOOLS=1` | don't open DevTools in dev builds |
|
||||
|
||||
The first `tauri dev` compiles all Rust dependencies, which takes several minutes. Later runs
|
||||
take seconds.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
cd backend && npm run package # pkg -> dist/backend/backend.exe
|
||||
cd ../tauri && pnpm build-backend # copies it to src-tauri/binaries/backend-x86_64-pc-windows-msvc.exe
|
||||
pnpm build # tauri build (runs `pnpm build:tauri` in react_frontend first)
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
- `src-tauri/target/release/showy.exe`: the app (the sidecar must sit next to it as `backend.exe`).
|
||||
- `src-tauri/target/release/bundle/nsis/Showy_2.0.0_x64-setup.exe`: an installer that puts
|
||||
`showy.exe` and `backend.exe` side by side.
|
||||
|
||||
In release builds the backend runs without a console, and its output goes to
|
||||
`%LOCALAPPDATA%\x4lo.showy\logs\backend.log`.
|
||||
|
||||
The frontend build for Tauri goes to `tauri/frontend_build`. The web build (`pnpm build`) and
|
||||
the Electron build (`pnpm build:electron`) are unchanged.
|
||||
|
||||
## Frontend changes
|
||||
|
||||
- `react_frontend/src/lib/platform.ts`: `isTauri`, `isElectron`, `isDesktop`, `isDesktopBuild`.
|
||||
- `api.ts` and `router.tsx` use `isDesktopBuild` (Electron **or** Tauri build), so both desktop
|
||||
builds talk to `localhost:4000` and use the hash router.
|
||||
- `TitleBar.tsx`: on Tauri the buttons call `@tauri-apps/api/window` (`minimize`,
|
||||
`toggleMaximize`, `close`), which is loaded lazily. Dragging uses `data-tauri-drag-region`.
|
||||
Electron keeps using `window.electron.windowControls` and `-webkit-app-region`.
|
||||
- `vite.config.ts`: `base: './'`, `strictPort` and no screen clearing when `VITE_TAURI=true`.
|
||||
- New scripts: `dev:tauri`, `build:tauri`.
|
||||
|
||||
## Status / missing compared with Electron
|
||||
|
||||
Tested on Windows 11 in dev mode: the window opens on the Vite dev server, the backend starts
|
||||
and answers the webview on port 4000, the title-bar window commands (minimize, maximize/restore,
|
||||
close) work, and closing the window stops the backend.
|
||||
|
||||
Not done yet / differences:
|
||||
|
||||
- **The release build has not been tested yet.** It needs `dist/backend/backend.exe`, and there
|
||||
is a known problem with the pkg backend: `configService.getUserDataPath()` uses `__dirname`,
|
||||
which points inside pkg's read-only snapshot. So the packaged backend cannot find or create
|
||||
`settings.json`. The backend needs to read its settings next to the executable
|
||||
(`path.dirname(process.execPath)` when `process.pkg` is set) or from a folder the shell passes
|
||||
in, e.g. via `PARENT_PROCESS.tauri_path` (the app data dir, already sent). `sharp` and
|
||||
`ffmpeg-static` native files also need checking in the pkg build.
|
||||
- **Backend model**: Electron `require`s `server.js` in its own process. Tauri runs it as a
|
||||
separate process (`node` in dev, the pkg `backend.exe` in release).
|
||||
- **`PARENT_PROCESS`**: Electron sends `{ electron_path: userData }`. Tauri sends
|
||||
`{ tauri_path: <app data dir> }`. The backend doesn't read either today.
|
||||
- **Generic IPC**: Electron's preload also exposes `window.electron.ipcRenderer`. The frontend
|
||||
doesn't use it, so Tauri has no equivalent (only window controls).
|
||||
- **Title bar on the login page**: the window has no native frame, and the login page renders
|
||||
outside `AppLayout`, so there is no title bar to drag or close the window until you log in.
|
||||
Electron behaves the same way.
|
||||
- **Dev API target**: Electron's `npm run dev` loads the plain `vite` dev server, which proxies
|
||||
`/api` to the remote backend. Tauri dev uses the local backend on port 4000.
|
||||
- No auto-update, tray icon, single-instance lock or code signing (Electron has none of these
|
||||
either). The bundle target is NSIS. Electron produces an unpacked `dir` build instead.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "showy_tauri",
|
||||
"version": "2.0.0",
|
||||
"private": true,
|
||||
"description": "Showy Desktop App (Tauri)",
|
||||
"scripts": {
|
||||
"tauri": "tauri",
|
||||
"dev": "tauri dev",
|
||||
"build-front": "pnpm --dir ../react_frontend build:tauri",
|
||||
"build-backend": "node scripts/prepare-sidecar.mjs",
|
||||
"build": "tauri build --config src-tauri/tauri.bundle.conf.json",
|
||||
"icons": "tauri icon ../electron/assets/icon.ico"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.9.0"
|
||||
}
|
||||
}
|
||||
Generated
+140
@@ -0,0 +1,140 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
'@tauri-apps/cli':
|
||||
specifier: ^2.9.0
|
||||
version: 2.12.4
|
||||
|
||||
packages:
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.12.4':
|
||||
resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.12.4':
|
||||
resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
|
||||
resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
|
||||
resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
|
||||
resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
|
||||
resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
|
||||
resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.12.4':
|
||||
resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
|
||||
resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
|
||||
resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
|
||||
resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli@2.12.4':
|
||||
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
|
||||
engines: {node: '>= 10'}
|
||||
hasBin: true
|
||||
|
||||
snapshots:
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli@2.12.4':
|
||||
optionalDependencies:
|
||||
'@tauri-apps/cli-darwin-arm64': 2.12.4
|
||||
'@tauri-apps/cli-darwin-x64': 2.12.4
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.12.4
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.12.4
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.4
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.12.4
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.12.4
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.12.4
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.12.4
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.12.4
|
||||
@@ -0,0 +1,36 @@
|
||||
// Copies the pkg-packaged backend (dist/backend/backend.exe) into
|
||||
// src-tauri/binaries/ under the name Tauri expects for an external binary:
|
||||
// backend-<rust target triple>[.exe].
|
||||
//
|
||||
// Build the backend first: cd backend && npm run package
|
||||
import { execSync } from "node:child_process";
|
||||
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = resolve(here, "..", "..");
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
const source = join(repoRoot, "dist", "backend", `backend${ext}`);
|
||||
|
||||
const triple = execSync("rustc -vV", { encoding: "utf8" })
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("host:"))
|
||||
?.slice("host:".length)
|
||||
.trim();
|
||||
|
||||
if (!triple) {
|
||||
console.error("Could not read the Rust host triple from `rustc -vV`.");
|
||||
process.exit(1);
|
||||
}
|
||||
if (!existsSync(source)) {
|
||||
console.error(`Backend executable not found: ${source}`);
|
||||
console.error("Build it first: cd backend && npm run package");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const targetDir = resolve(here, "..", "src-tauri", "binaries");
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const target = join(targetDir, `backend-${triple}${ext}`);
|
||||
copyFileSync(source, target);
|
||||
console.log(`Copied ${source} -> ${target}`);
|
||||
Generated
+4376
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "showy"
|
||||
version = "2.0.0"
|
||||
description = "Showy Desktop App"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "showy_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
serde_json = "1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = "s"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions for the main Showy window (custom title bar controls).",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-internal-toggle-maximize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-start-dragging"
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.5 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 83 KiB |
@@ -0,0 +1,222 @@
|
||||
//! Starts the Showy Node backend next to the Tauri window and stops it on exit.
|
||||
//!
|
||||
//! - Debug builds (`tauri dev`) run `node server.js` from the repo's `backend/` folder.
|
||||
//! - Release builds run the `pkg`-packaged `backend.exe` sidecar that the bundler
|
||||
//! places next to the app executable.
|
||||
//! - If something already listens on the backend port, nothing is spawned and the
|
||||
//! app talks to that process (handy when the backend runs in its own terminal).
|
||||
//!
|
||||
//! Environment overrides:
|
||||
//! - `SHOWY_SKIP_BACKEND=1` never spawn a backend
|
||||
//! - `SHOWY_BACKEND_DIR=<path>` backend folder used in debug builds
|
||||
//! - `SHOWY_BACKEND_EXE=<path>` run this executable instead (any build)
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
/// The frontend calls `http://localhost:4000/api/v1` in desktop builds.
|
||||
pub const BACKEND_PORT: u16 = 4000;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BackendState {
|
||||
child: Mutex<Option<Child>>,
|
||||
#[cfg(windows)]
|
||||
job: Mutex<Option<job::Job>>,
|
||||
}
|
||||
|
||||
impl BackendState {
|
||||
pub fn stop(&self) {
|
||||
if let Some(mut child) = self.child.lock().unwrap().take() {
|
||||
log(&format!("stopping backend (pid {})", child.id()));
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
// Closing the job handle kills anything the backend spawned (e.g. ffmpeg).
|
||||
#[cfg(windows)]
|
||||
drop(self.job.lock().unwrap().take());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(app: &AppHandle) -> BackendState {
|
||||
let state = BackendState::default();
|
||||
|
||||
if std::env::var_os("SHOWY_SKIP_BACKEND").is_some() {
|
||||
log("SHOWY_SKIP_BACKEND is set, not starting the backend");
|
||||
return state;
|
||||
}
|
||||
if port_in_use(BACKEND_PORT) {
|
||||
log(&format!(
|
||||
"port {BACKEND_PORT} is already in use, using the backend that is already running"
|
||||
));
|
||||
return state;
|
||||
}
|
||||
|
||||
let mut cmd = match backend_command() {
|
||||
Ok(cmd) => cmd,
|
||||
Err(err) => {
|
||||
log(&format!("cannot start backend: {err}"));
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
// Same contract as the Electron shell: tell the backend where the desktop
|
||||
// app keeps its own data.
|
||||
let data_dir = app.path().app_data_dir().ok();
|
||||
cmd.env(
|
||||
"PARENT_PROCESS",
|
||||
serde_json::json!({ "tauri_path": data_dir }).to_string(),
|
||||
);
|
||||
|
||||
if cfg!(debug_assertions) {
|
||||
// Backend logs go to the same terminal as `tauri dev`.
|
||||
cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
|
||||
} else {
|
||||
// No console in release builds: write the backend output to a log file.
|
||||
let log_file = app.path().app_log_dir().ok().and_then(|dir| {
|
||||
fs::create_dir_all(&dir).ok()?;
|
||||
File::create(dir.join("backend.log")).ok()
|
||||
});
|
||||
match log_file.and_then(|f| f.try_clone().ok().map(|f2| (f, f2))) {
|
||||
Some((out, err)) => {
|
||||
cmd.stdout(out).stderr(err);
|
||||
}
|
||||
None => {
|
||||
cmd.stdout(Stdio::null()).stderr(Stdio::null());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
}
|
||||
cmd.stdin(Stdio::null());
|
||||
|
||||
match cmd.spawn() {
|
||||
Ok(child) => {
|
||||
log(&format!("backend started (pid {})", child.id()));
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = job::Job::kill_on_close() {
|
||||
if job.assign(&child) {
|
||||
*state.job.lock().unwrap() = Some(job);
|
||||
}
|
||||
}
|
||||
*state.child.lock().unwrap() = Some(child);
|
||||
}
|
||||
Err(err) => log(&format!("failed to spawn backend: {err}")),
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fn backend_command() -> Result<Command, String> {
|
||||
if let Some(exe) = std::env::var_os("SHOWY_BACKEND_EXE") {
|
||||
let exe = PathBuf::from(exe);
|
||||
return exe_command(exe);
|
||||
}
|
||||
|
||||
if cfg!(debug_assertions) {
|
||||
let dir = std::env::var_os("SHOWY_BACKEND_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../backend")
|
||||
});
|
||||
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
if !dir.join("server.js").is_file() {
|
||||
return Err(format!("no server.js in {}", dir.display()));
|
||||
}
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg("server.js").current_dir(dir);
|
||||
Ok(cmd)
|
||||
} else {
|
||||
let exe_dir = std::env::current_exe()
|
||||
.map_err(|e| e.to_string())?
|
||||
.parent()
|
||||
.map(PathBuf::from)
|
||||
.ok_or("cannot resolve the app folder")?;
|
||||
let name = if cfg!(windows) { "backend.exe" } else { "backend" };
|
||||
exe_command(exe_dir.join(name))
|
||||
}
|
||||
}
|
||||
|
||||
fn exe_command(exe: PathBuf) -> Result<Command, String> {
|
||||
if !exe.is_file() {
|
||||
return Err(format!("backend executable not found: {}", exe.display()));
|
||||
}
|
||||
let mut cmd = Command::new(&exe);
|
||||
if let Some(dir) = exe.parent() {
|
||||
cmd.current_dir(dir);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn port_in_use(port: u16) -> bool {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok()
|
||||
}
|
||||
|
||||
fn log(msg: &str) {
|
||||
eprintln!("[showy] {msg}");
|
||||
}
|
||||
|
||||
/// A Windows job object that kills every process in it when its handle closes,
|
||||
/// including when the app crashes, so the backend never outlives the window.
|
||||
#[cfg(windows)]
|
||||
mod job {
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::process::Child;
|
||||
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
|
||||
use windows_sys::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
|
||||
SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
|
||||
pub struct Job(HANDLE);
|
||||
|
||||
// The handle is only used behind a Mutex and closed once.
|
||||
unsafe impl Send for Job {}
|
||||
|
||||
impl Job {
|
||||
pub fn kill_on_close() -> Option<Job> {
|
||||
unsafe {
|
||||
let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());
|
||||
if handle.is_null() {
|
||||
return None;
|
||||
}
|
||||
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
let ok = SetInformationJobObject(
|
||||
handle,
|
||||
JobObjectExtendedLimitInformation,
|
||||
&info as *const _ as *const _,
|
||||
std::mem::size_of_val(&info) as u32,
|
||||
);
|
||||
if ok == 0 {
|
||||
CloseHandle(handle);
|
||||
return None;
|
||||
}
|
||||
Some(Job(handle))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn assign(&self, child: &Child) -> bool {
|
||||
unsafe { AssignProcessToJobObject(self.0, child.as_raw_handle() as HANDLE) != 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Job {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
mod backend;
|
||||
|
||||
use tauri::{Manager, RunEvent};
|
||||
|
||||
pub fn run() {
|
||||
let app = tauri::Builder::default()
|
||||
.setup(|app| {
|
||||
let state = backend::start(app.handle());
|
||||
app.manage(state);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if std::env::var("SHOWY_NO_DEVTOOLS").is_err() {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
window.open_devtools();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building the Showy Tauri app");
|
||||
|
||||
app.run(|handle, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
if let Some(state) = handle.try_state::<backend::BackendState>() {
|
||||
state.stop();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents an additional console window on Windows in release builds.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
showy_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"bundle": {
|
||||
"externalBin": ["binaries/backend"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Showy",
|
||||
"version": "2.0.0",
|
||||
"identifier": "x4lo.showy",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm --dir ../react_frontend dev:tauri",
|
||||
"devUrl": "http://localhost:4200",
|
||||
"beforeBuildCommand": "pnpm --dir ../react_frontend build:tauri",
|
||||
"frontendDist": "../frontend_build"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Showy",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"minWidth": 900,
|
||||
"minHeight": 600,
|
||||
"decorations": false,
|
||||
"backgroundColor": "#09090b",
|
||||
"center": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["nsis"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user