Files
Time4Midi/main.js
T
jhartworks c396a0f249 Add smoke tests for project file handling and UI interactions
- Implemented a smoke test for project file operations in `project-file-smoke.cjs`, verifying save and load functionality.
- Created a preload script for UI smoke tests in `ui-smoke-preload.cjs`, exposing necessary APIs to the renderer process.
- Developed comprehensive UI smoke tests in `ui-smoke.cjs`, covering various user interactions and ensuring expected behavior.
2026-11-25 09:44:17 +01:00

577 lines
16 KiB
JavaScript

const { app, BrowserWindow, dialog, ipcMain, powerSaveBlocker } = require("electron");
const { spawnSync } = require("node:child_process");
const fs = require("node:fs/promises");
const path = require("node:path");
const WINDOWS_ELEVATION_FLAG = "--time4midi-elevated";
const WINDOWS_FIREWALL_RULES = [
{ displayName: "Time4Midi Inbound", direction: "Inbound" },
{ displayName: "Time4Midi Outbound", direction: "Outbound" }
];
ensureWindowsElevation();
app.commandLine.appendSwitch("enable-blink-features", "WebMidi");
let mainWindow = null;
let diagnosticsWindow = null;
let splashWindow = null;
let mainWindowCloseApproved = false;
let showPowerBlockerId = null;
function escapePowerShellString(value) {
return "'" + String(value).replace(/'/g, "''") + "'";
}
function isWindowsAdministrator() {
if (process.platform !== "win32") {
return true;
}
const result = spawnSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
"$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()); if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { 'true' } else { 'false' }"
],
{ encoding: "utf8", windowsHide: true }
);
return result.status === 0 && result.stdout.trim().toLowerCase() === "true";
}
function relaunchAsAdministrator() {
const nextArgs = process.argv.slice(1);
if (!nextArgs.includes(WINDOWS_ELEVATION_FLAG)) {
nextArgs.push(WINDOWS_ELEVATION_FLAG);
}
const powershellArgs = nextArgs.length > 0
? "@(" + nextArgs.map((value) => escapePowerShellString(value)).join(", ") + ")"
: "@()";
const result = spawnSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
`Start-Process -FilePath ${escapePowerShellString(process.execPath)} -ArgumentList ${powershellArgs} -Verb RunAs`
],
{ stdio: "ignore", windowsHide: true }
);
return result.status === 0;
}
function ensureWindowsElevation() {
if (process.platform !== "win32" || isWindowsAdministrator()) {
return;
}
if (process.argv.includes(WINDOWS_ELEVATION_FLAG)) {
dialog.showErrorBox(
"Administratorrechte erforderlich",
"Time4Midi konnte nicht mit Administratorrechten gestartet werden. Unter Windows sind diese Rechte fuer mehrere Protokolle und die Firewall-Freigaben erforderlich."
);
process.exit(1);
}
const relaunched = relaunchAsAdministrator();
if (!relaunched) {
dialog.showErrorBox(
"Administratorrechte erforderlich",
"Time4Midi muss unter Windows mit Administratorrechten gestartet werden, damit alle Protokolle und Firewall-Regeln korrekt funktionieren."
);
}
process.exit(relaunched ? 0 : 1);
}
function ensureWindowsFirewallRules() {
if (process.platform !== "win32" || !app.isPackaged) {
return;
}
const serializedRules = JSON.stringify(WINDOWS_FIREWALL_RULES);
const script = [
`$programPath = ${escapePowerShellString(process.execPath)}` ,
`$rules = ConvertFrom-Json -InputObject ${escapePowerShellString(serializedRules)}` ,
"",
"foreach ($rule in $rules) {",
" $matchingRule = Get-NetFirewallRule -DisplayName $rule.displayName -ErrorAction SilentlyContinue | Where-Object { $_.Direction -eq $rule.direction }",
" $hasMatchingProgram = $false",
"",
" if ($matchingRule) {",
" $programFilter = $matchingRule | Get-NetFirewallApplicationFilter -ErrorAction SilentlyContinue | Where-Object { $_.Program -eq $programPath }",
" if ($programFilter) {",
" $hasMatchingProgram = $true",
" } else {",
" $matchingRule | Remove-NetFirewallRule -ErrorAction SilentlyContinue | Out-Null",
" }",
" }",
"",
" if (-not $hasMatchingProgram) {",
" New-NetFirewallRule -DisplayName $rule.displayName -Direction $rule.direction -Program $programPath -Action Allow -Profile Any | Out-Null",
" }",
"}"
].join("\n");
const result = spawnSync(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
{ encoding: "utf8", windowsHide: true }
);
if (result.status !== 0) {
console.warn("Failed to ensure Windows Firewall rules:", result.stderr || result.stdout || `exit ${result.status}`);
}
}
const diagnosticsState = {
artnet: { universes: {} },
sacn: { universes: {} },
mqtt: { topics: {} },
knx: { groupAddresses: {} },
recentEvents: []
};
function rememberRecentEvent(entry) {
diagnosticsState.recentEvents.unshift(entry);
diagnosticsState.recentEvents = diagnosticsState.recentEvents.slice(0, 200);
}
function sameChannelValues(left, right) {
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
return false;
}
for (let index = 0; index < left.length; index += 1) {
if (Number(left[index] || 0) !== Number(right[index] || 0)) {
return false;
}
}
return true;
}
function updateDmxDiagnostics(transport, record) {
const safeTransport = transport === "artnet" ? "artnet" : "sacn";
const previous = diagnosticsState[safeTransport].universes[String(record.universe)];
const nextValues = Array.isArray(record.values) ? record.values.slice(0, 512) : [];
const changed = !previous || !sameChannelValues(previous.values, nextValues);
diagnosticsState[safeTransport].universes[String(record.universe)] = {
universe: Number(record.universe) || 0,
values: nextValues,
updatedAt: record.timestamp
};
if (changed) {
rememberRecentEvent({
kind: "dmx-frame",
transport: safeTransport,
universe: Number(record.universe) || 0,
activeChannels: nextValues.filter((value) => Number(value) > 0).length,
timestamp: record.timestamp
});
}
}
function updateMqttDiagnostics(record) {
diagnosticsState.mqtt.topics[String(record.topic || "")] = {
topic: String(record.topic || ""),
value: String(record.value ?? ""),
updatedAt: record.timestamp
};
rememberRecentEvent({
kind: "mqtt-publish",
topic: String(record.topic || ""),
value: String(record.value ?? ""),
timestamp: record.timestamp
});
}
function updateKnxDiagnostics(record) {
const key = `${record.groupAddress || ""}:${record.dpt || ""}`;
diagnosticsState.knx.groupAddresses[key] = {
groupAddress: String(record.groupAddress || ""),
dpt: String(record.dpt || ""),
value: record.value,
updatedAt: record.timestamp
};
rememberRecentEvent({
kind: "knx-write",
groupAddress: String(record.groupAddress || ""),
dpt: String(record.dpt || ""),
value: record.value,
timestamp: record.timestamp
});
}
function applyDiagnosticsRecord(record) {
if (!record || typeof record !== "object") {
return;
}
if (record.kind === "dmx-frame") {
updateDmxDiagnostics(record.transport, record);
} else if (record.kind === "mqtt-publish") {
updateMqttDiagnostics(record);
} else if (record.kind === "knx-write") {
updateKnxDiagnostics(record);
}
}
function sendDiagnosticsUpdate(record) {
if (!diagnosticsWindow || diagnosticsWindow.isDestroyed()) {
return;
}
diagnosticsWindow.webContents.send("diagnostics:update", record);
}
function closeSplashWindow() {
if (!splashWindow || splashWindow.isDestroyed()) {
splashWindow = null;
return;
}
splashWindow.close();
splashWindow = null;
}
function createSplashWindow() {
if (splashWindow && !splashWindow.isDestroyed()) {
return splashWindow;
}
splashWindow = new BrowserWindow({
width: 680,
height: 520,
frame: false,
resizable: false,
minimizable: false,
maximizable: false,
movable: true,
show: true,
center: true,
backgroundColor: "#0f1117",
icon: path.join(__dirname, "time4midi.png"),
webPreferences: {
contextIsolation: true,
sandbox: false
}
});
splashWindow.on("closed", () => {
splashWindow = null;
});
splashWindow.loadFile(path.join(__dirname, "src", "splash.html"));
return splashWindow;
}
function createWindow() {
mainWindowCloseApproved = false;
mainWindow = new BrowserWindow({
width: 1760,
height: 1020,
minWidth: 1320,
minHeight: 760,
frame: process.platform !== "win32",
thickFrame: true,
backgroundColor: "#0f1117",
icon: path.join(__dirname, "time4midi.png"),
show: false,
webPreferences: {
contextIsolation: true,
sandbox: false,
backgroundThrottling: false,
preload: path.join(__dirname, "preload.js")
}
});
mainWindow.on("close", (event) => {
if (mainWindowCloseApproved || mainWindow.webContents.isLoadingMainFrame()) {
return;
}
event.preventDefault();
mainWindow.webContents.send("window:close-requested");
});
mainWindow.on("maximize", () => {
mainWindow?.webContents.send("window:maximized-changed", true);
});
mainWindow.on("unmaximize", () => {
mainWindow?.webContents.send("window:maximized-changed", false);
});
mainWindow.on("closed", () => {
setShowPowerBlocker(false);
mainWindow = null;
});
mainWindow.once("ready-to-show", () => {
setTimeout(() => {
closeSplashWindow();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.show();
}
}, 650);
});
mainWindow.loadFile(path.join(__dirname, "src", "index.html"));
}
function setShowPowerBlocker(active) {
if (active && showPowerBlockerId === null) {
showPowerBlockerId = powerSaveBlocker.start("prevent-app-suspension");
} else if (!active && showPowerBlockerId !== null) {
powerSaveBlocker.stop(showPowerBlockerId);
showPowerBlockerId = null;
}
}
ipcMain.handle("show:setActive", (event, active) => {
if (BrowserWindow.fromWebContents(event.sender) === mainWindow) {
setShowPowerBlocker(Boolean(active));
}
});
ipcMain.handle("window:minimize", (event) => {
if (BrowserWindow.fromWebContents(event.sender) === mainWindow) {
mainWindow.minimize();
}
});
ipcMain.handle("window:toggleMaximize", (event) => {
if (BrowserWindow.fromWebContents(event.sender) !== mainWindow) {
return false;
}
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
return mainWindow.isMaximized();
});
ipcMain.handle("window:requestClose", (event) => {
if (BrowserWindow.fromWebContents(event.sender) === mainWindow) {
mainWindow.close();
}
});
ipcMain.handle("window:confirmClose", (event) => {
if (BrowserWindow.fromWebContents(event.sender) === mainWindow) {
mainWindowCloseApproved = true;
mainWindow.close();
}
});
function createDiagnosticsWindow() {
if (diagnosticsWindow && !diagnosticsWindow.isDestroyed()) {
diagnosticsWindow.focus();
return diagnosticsWindow;
}
diagnosticsWindow = new BrowserWindow({
width: 1100,
height: 820,
minWidth: 900,
minHeight: 640,
backgroundColor: "#0f1117",
icon: path.join(__dirname, "time4midi.png"),
title: "Time4Midi Diagnose",
webPreferences: {
contextIsolation: true,
sandbox: false,
preload: path.join(__dirname, "preload.js")
}
});
diagnosticsWindow.on("closed", () => {
diagnosticsWindow = null;
});
diagnosticsWindow.loadFile(path.join(__dirname, "src", "diagnostics.html"));
return diagnosticsWindow;
}
ipcMain.handle("project:save", async (_event, payload) => {
if (payload?.filePath) {
const filePath = path.extname(payload.filePath).toLowerCase() === ".json"
? payload.filePath.slice(0, -5) + ".t4m"
: payload.filePath;
await fs.writeFile(filePath, payload.data, "utf8");
await rememberProject(filePath);
return { canceled: false, filePath };
}
const result = await dialog.showSaveDialog({
defaultPath: payload?.defaultPath || "time4midi-project.t4m",
filters: [
{ name: "Time4Midi Project", extensions: ["t4m"] }
]
});
if (result.canceled || !result.filePath) {
return { canceled: true };
}
const parsedPath = path.parse(result.filePath);
const filePath = parsedPath.ext.toLowerCase() === ".t4m"
? result.filePath
: path.join(parsedPath.dir, `${parsedPath.name}.t4m`);
await fs.writeFile(filePath, payload.data, "utf8");
await rememberProject(filePath);
return { canceled: false, filePath };
});
const lastProjectStatePath = () => path.join(app.getPath("userData"), "last-project.json");
async function rememberProject(filePath) {
try {
await fs.mkdir(app.getPath("userData"), { recursive: true });
await fs.writeFile(lastProjectStatePath(), JSON.stringify({ filePath }), "utf8");
} catch (error) {
console.warn("Last project could not be remembered:", error);
}
}
async function readRecentProject() {
try {
const { filePath } = JSON.parse(await fs.readFile(lastProjectStatePath(), "utf8"));
if (typeof filePath !== "string" || !filePath) return { canceled: true };
const data = await fs.readFile(filePath, "utf8");
return { canceled: false, filePath, data };
} catch (error) {
if (error.code === "ENOENT") return { canceled: true };
throw error;
}
}
ipcMain.handle("project:loadRecent", readRecentProject);
ipcMain.handle("project:load", async () => {
const result = await dialog.showOpenDialog({
properties: ["openFile"],
filters: [
{ name: "Time4Midi Project", extensions: ["t4m", "json"] }
]
});
if (result.canceled || result.filePaths.length === 0) {
return { canceled: true };
}
const filePath = result.filePaths[0];
const data = await fs.readFile(filePath, "utf8");
JSON.parse(data);
await rememberProject(filePath);
return { canceled: false, filePath, data };
});
ipcMain.handle("audio:pickFile", async () => {
const result = await dialog.showOpenDialog({
properties: ["openFile"],
filters: [
{ name: "Audio", extensions: ["mp3", "m4a", "flac", "wma"] }
]
});
if (result.canceled || result.filePaths.length === 0) {
return { canceled: true };
}
return {
canceled: false,
filePath: result.filePaths[0]
};
});
ipcMain.handle("app:getUserDataPath", () => {
return app.getPath("userData");
});
ipcMain.handle("mappingLibrary:pickLoadFile", async (_event, payload) => {
const result = await dialog.showOpenDialog({
properties: ["openFile"],
defaultPath: payload?.defaultPath || "time4midi-mappings.json",
filters: [
{ name: "Time4Midi Mapping", extensions: ["json"] }
]
});
if (result.canceled || result.filePaths.length === 0) {
return { canceled: true };
}
return {
canceled: false,
filePath: result.filePaths[0]
};
});
ipcMain.handle("mappingLibrary:pickSaveFile", async (_event, payload) => {
const result = await dialog.showSaveDialog({
defaultPath: payload?.defaultPath || "time4midi-mappings.json",
filters: [
{ name: "Time4Midi Mapping", extensions: ["json"] }
]
});
if (result.canceled || !result.filePath) {
return { canceled: true };
}
return {
canceled: false,
filePath: result.filePath
};
});
ipcMain.handle("diagnostics:openWindow", () => {
createDiagnosticsWindow();
return { ok: true };
});
ipcMain.handle("diagnostics:getSnapshot", () => {
return diagnosticsState;
});
ipcMain.on("diagnostics:record", (_event, record) => {
const normalizedRecord = {
...record,
timestamp: Number(record?.timestamp) || Date.now()
};
applyDiagnosticsRecord(normalizedRecord);
sendDiagnosticsUpdate(normalizedRecord);
});
app.whenReady().then(() => {
ensureWindowsFirewallRules();
createSplashWindow();
createWindow();
app.on("activate", () => {
if (!mainWindow || mainWindow.isDestroyed()) {
createSplashWindow();
createWindow();
}
});
});
app.on("window-all-closed", () => {
closeSplashWindow();
if (process.platform !== "darwin") {
app.quit();
}
});