move electron folder

This commit is contained in:
Anton Bracke
2022-02-22 10:41:55 +01:00
parent ac18aab773
commit 41be011d5e
36 changed files with 19 additions and 18 deletions
+90
View File
@@ -0,0 +1,90 @@
import { app, BrowserWindow, globalShortcut } from "electron";
import { createWindow, getWindow } from "./window";
import { createTray } from "./tray";
import autoUpdater from "./auto-updater";
import { updateAutoLaunch } from "./auto-launch";
import ipc from "./ipc";
import settings from "./settings";
import { setLogLevel } from "./log";
import "./serve"; // prepare custom url scheme
import { loadShortcuts } from "./shortcuts";
function init() {
const appLock = app.requestSingleInstanceLock();
if (!appLock) {
console.log("Application already running");
app.quit();
return;
}
app.on("second-instance", () => {
// re-create window if closed
createWindow();
const mainWindow = getWindow();
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
}
});
// This method will be called when Electron has finished loading
app.whenReady().then(async () => {
await settings.init();
setLogLevel(settings.get("log_level") || "info");
autoUpdater.init();
// enable auto launch
updateAutoLaunch();
// load ipc handler
ipc();
// Don't show the app in the doc
// if (app.dock) {
// app.dock.hide();
// }
await createWindow();
createTray();
loadShortcuts();
});
// Quit when all windows are closed.
app.on("window-all-closed", () => {
// macOs users have to press Cmd + Q to stop the app
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
app.on("quit", () => {
// TODO
});
app.on("will-quit", () => {
globalShortcut.unregisterAll();
});
}
export default {
init,
};
+41
View File
@@ -0,0 +1,41 @@
import AutoLaunch from "auto-launch";
import { app } from "electron";
import electronIsDev from "electron-is-dev";
import settings from "./settings";
export async function updateAutoLaunch() {
let isAutoLaunchEnabled = settings.get("auto_launch_enabled");
// set default to enabled
if (isAutoLaunchEnabled === undefined) {
settings.set("auto_launch_enabled", true);
isAutoLaunchEnabled = true;
}
// Don't run this in development
if (electronIsDev) {
return;
}
// `setLoginItemSettings` doesn't support linux
if (process.platform === "linux") {
const autoLauncher = new AutoLaunch({
name: "WorkAdventure",
isHidden: true,
});
if (isAutoLaunchEnabled) {
await autoLauncher.enable();
} else {
await autoLauncher.disable();
}
return;
}
app.setLoginItemSettings({
openAtLogin: isAutoLaunchEnabled,
openAsHidden: true,
});
}
+96
View File
@@ -0,0 +1,96 @@
import { app, dialog } from "electron";
import { autoUpdater } from "electron-updater";
import log from "electron-log";
import * as isDev from "electron-is-dev";
import * as util from "util";
import { createAndShowNotification } from "./notification";
const sleep = util.promisify(setTimeout);
let isCheckPending = false;
let isManualRequestedUpdate = false;
export async function checkForUpdates() {
if (isCheckPending) {
return;
}
// Don't do auto-updates in development
if (isDev) {
return;
}
// check for updates right away
await autoUpdater.checkForUpdates();
isCheckPending = false;
}
export async function manualRequestUpdateCheck() {
isManualRequestedUpdate = true;
createAndShowNotification({
body: "Checking for updates ...",
});
await checkForUpdates();
isManualRequestedUpdate = false;
}
function init() {
autoUpdater.logger = log;
autoUpdater.on("update-downloaded", ({ releaseNotes, releaseName }) => {
(async () => {
const dialogOpts = {
type: "question",
buttons: ["Install and Restart", "Install Later"],
defaultId: 0,
title: "WorkAdventure - Update",
message: process.platform === "win32" ? releaseNotes : releaseName,
detail: "A new version has been downloaded. Restart the application to apply the updates.",
};
const { response } = await dialog.showMessageBox(dialogOpts);
if (response === 0) {
await sleep(1000);
autoUpdater.quitAndInstall();
// Force app to quit. This is just a workaround, ideally autoUpdater.quitAndInstall() should relaunch the app.
// app.confirmedExitPrompt = true;
app.quit();
}
})();
});
if (process.platform === "linux" && !process.env.APPIMAGE) {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
autoUpdater.on("update-available", () => {
createAndShowNotification({
title: "WorkAdventure - Update available",
body: "Please go to our website and install the newest version",
});
});
}
autoUpdater.on("update-not-available", () => {
if (isManualRequestedUpdate) {
createAndShowNotification({
body: "No update available.",
});
}
});
checkForUpdates();
// run update check every hour again
setInterval(() => checkForUpdates, 1000 * 60 * 1);
}
export default {
init,
};
+98
View File
@@ -0,0 +1,98 @@
import { ipcMain, app } from "electron";
import electronIsDev from "electron-is-dev";
import { createAndShowNotification } from "./notification";
import { Server } from "./preload-local-app/types";
import settings from "./settings";
import { saveShortcut } from "./shortcuts";
import { getWindow, hideAppView, showAppView } from "./window";
export function emitMuteToggle() {
const mainWindow = getWindow();
if (!mainWindow) {
throw new Error("Main window not found");
}
mainWindow.webContents.send("app:on-camera-toggle");
}
export function emitCameraToggle() {
const mainWindow = getWindow();
if (!mainWindow) {
throw new Error("Main window not found");
}
mainWindow.webContents.send("app:on-mute-toggle");
}
export default () => {
ipcMain.handle("is-development", () => electronIsDev);
ipcMain.handle("get-version", () => (electronIsDev ? "dev" : app.getVersion()));
// app ipc
ipcMain.on("app:notify", (event, txt) => {
createAndShowNotification({ body: txt });
});
// local-app ipc
ipcMain.handle("local-app:showLocalApp", () => {
hideAppView();
});
ipcMain.handle("local-app:getServers", () => {
return (
settings.get("servers") || [
// TODO: remove this default server
{
_id: "1",
name: "WA Demo",
url: "https://play.staging.workadventu.re/@/tcm/workadventure/wa-village",
},
]
);
});
ipcMain.handle("local-app:selectServer", (event, serverId: string) => {
const servers = settings.get("servers") || [];
const selectedServer = servers.find((s) => s._id === serverId);
if (!selectedServer) {
return new Error("Server not found");
}
showAppView(selectedServer.url);
return true;
});
ipcMain.handle("local-app:addServer", async (event, server: Omit<Server, "_id">) => {
const servers = settings.get("servers") || [];
try {
// TODO: add proper test to see if server url is valid and points to a real WA server
await fetch(`${server.url}/iframe_api.js`);
} catch (e) {
console.error(e);
return new Error("Invalid server url");
}
const newServer = {
...server,
_id: `${servers.length + 1}`,
};
servers.push(newServer);
settings.set("servers", servers);
return newServer;
});
ipcMain.handle("local-app:removeServer", (event, server: Server) => {
const servers = settings.get("servers") || [];
settings.set(
"servers",
servers.filter((s) => s._id !== server._id)
);
return true;
});
ipcMain.handle("local-app:saveShortcut", (event, shortcut, key) => saveShortcut(shortcut, key));
ipcMain.handle("local-app:getShortcuts", (event) => settings.get("shortcuts") || {});
};
+54
View File
@@ -0,0 +1,54 @@
import { dialog, shell } from "electron";
import ElectronLog from "electron-log";
import log from "electron-log";
function onError(e: Error) {
try {
log.error(e);
dialog.showErrorBox("WorkAdventure - A JavaScript error occurred", e.stack || "");
} catch (logError) {
console.error(e);
}
}
function onRejection(reason: Error) {
if (reason instanceof Error) {
let _reason = reason;
const errPrototype = Object.getPrototypeOf(reason);
const nameProperty = Object.getOwnPropertyDescriptor(errPrototype, "name");
if (!nameProperty || !nameProperty.writable) {
_reason = new Error(reason.message);
}
_reason.name = `UnhandledRejection ${_reason.name}`;
onError(_reason);
return;
}
const error = new Error(JSON.stringify(reason));
error.name = "UnhandledRejection";
onError(error);
}
function init() {
console.log = log.log.bind(log);
process.on("uncaughtException", onError);
process.on("unhandledRejection", onRejection);
}
export async function openLog() {
const logFilePath = log.transports.file.getFile().path;
await shell.openPath(logFilePath);
}
export function setLogLevel(logLevel: ElectronLog.LogLevel) {
log.transports.console.level = logLevel;
log.transports.file.level = logLevel;
}
export default {
init,
};
+5
View File
@@ -0,0 +1,5 @@
import app from "./app";
import log from "./log";
log.init();
app.init();
+20
View File
@@ -0,0 +1,20 @@
import path from "path";
import { Notification, NotificationConstructorOptions } from "electron";
export function createNotification(options: Partial<NotificationConstructorOptions>) {
const notification = new Notification({
title: "WorkAdventure",
icon: path.join(__dirname, "..", "assets", "icons", "logo.png"),
...(options || {}),
});
return notification;
}
export function createAndShowNotification(options: Partial<NotificationConstructorOptions>) {
const notification = createNotification(options);
notification.show();
return notification;
}
@@ -0,0 +1,14 @@
import { contextBridge, ipcRenderer, IpcRendererEvent } from "electron";
import { SettingsData } from "src/settings";
import type { WorkAdventureDesktopApi } from "./types";
const api: WorkAdventureDesktopApi = {
desktop: true,
isDevelopment: () => ipcRenderer.invoke("is-development"),
getVersion: () => ipcRenderer.invoke("get-version"),
notify: (txt: string) => ipcRenderer.send("app:notify", txt),
onMuteToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-mute-toggle", callback),
onCameraToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-camera-toggle", callback),
};
contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api);
+10
View File
@@ -0,0 +1,10 @@
import type { IpcRendererEvent } from "electron";
export type WorkAdventureDesktopApi = {
desktop: boolean;
isDevelopment: () => Promise<boolean>;
getVersion: () => Promise<string>;
notify: (txt: string) => void;
onMuteToggle: (callback: (event: IpcRendererEvent) => void) => void;
onCameraToggle: (callback: (event: IpcRendererEvent) => void) => void;
};
@@ -0,0 +1,19 @@
import { contextBridge, ipcRenderer } from "electron";
import { SettingsData } from "src/settings";
import type { Server, WorkAdventureLocalAppApi } from "./types";
const api: WorkAdventureLocalAppApi = {
desktop: true,
isDevelopment: () => ipcRenderer.invoke("is-development"),
getVersion: () => ipcRenderer.invoke("get-version"),
showLocalApp: () => ipcRenderer.invoke("local-app:showLocalApp"),
getServers: () => ipcRenderer.invoke("local-app:getServers"),
selectServer: (serverId: string) => ipcRenderer.invoke("local-app:selectServer", serverId),
addServer: (server: Omit<Server, "_id">) => ipcRenderer.invoke("local-app:addServer", server),
removeServer: (serverId: Server["_id"]) => ipcRenderer.invoke("local-app:removeServer", serverId),
saveShortcut: (shortcut: keyof SettingsData["shortcuts"], key: string | null) =>
ipcRenderer.invoke("local-app:saveShortcut", shortcut, key),
getShortcuts: () => ipcRenderer.invoke("local-app:getShortcuts"),
};
contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api);
@@ -0,0 +1,20 @@
import { SettingsData } from "src/settings";
export type Server = {
_id: string;
name: string;
url: string;
};
export type WorkAdventureLocalAppApi = {
desktop: boolean;
isDevelopment: () => Promise<boolean>;
getVersion: () => Promise<string>;
showLocalApp: () => Promise<void>;
getServers: () => Promise<Server[]>;
selectServer: (serverId: string) => Promise<Error | boolean>;
addServer: (server: Omit<Server, "_id">) => Promise<Server>;
removeServer: (serverId: Server["_id"]) => Promise<boolean>;
saveShortcut: (shortcut: keyof SettingsData["shortcuts"], key: string | null) => Promise<void>;
getShortcuts: () => Promise<SettingsData["shortcuts"]>;
};
+9
View File
@@ -0,0 +1,9 @@
import { BrowserWindow } from "electron";
import serve from "electron-serve";
import path from "path";
let customScheme = serve({ directory: path.resolve(__dirname, "..", "local-app", "dist") });
export async function loadCustomScheme(window: BrowserWindow) {
await customScheme(window);
}
+39
View File
@@ -0,0 +1,39 @@
import ElectronLog from "electron-log";
import Settings from "electron-settings";
import type { Server } from "./preload-local-app/types";
export type SettingsData = {
log_level: ElectronLog.LogLevel;
auto_launch_enabled: boolean;
servers: Server[];
shortcuts: Record<"mute_toggle" | "camera_toggle", string | null>;
};
let settings: SettingsData;
async function init() {
settings = (await Settings.get()) as SettingsData;
}
function get<T extends keyof SettingsData>(key: T): SettingsData[T] | undefined {
if (settings === undefined) {
throw new Error("Settings not initialized");
}
return settings?.[key];
}
export function set<T extends keyof SettingsData>(key: T, value: SettingsData[T]) {
if (settings === undefined) {
throw new Error("Settings not initialized");
}
settings[key] = value;
void Settings.set(settings);
}
export default {
init,
get,
set,
};
+29
View File
@@ -0,0 +1,29 @@
import { globalShortcut } from "electron";
import settings, { SettingsData } from "./settings";
import { emitCameraToggle, emitMuteToggle } from "./ipc";
export function loadShortcuts() {
globalShortcut.unregisterAll();
const shortcuts = settings.get("shortcuts");
// // mute key
if (shortcuts?.mute_toggle && shortcuts.mute_toggle.length > 0) {
globalShortcut.register(shortcuts.mute_toggle, () => {
emitMuteToggle();
});
}
if (shortcuts?.camera_toggle && shortcuts.camera_toggle.length > 0) {
globalShortcut.register(shortcuts.camera_toggle, () => {
emitCameraToggle();
});
}
}
export function saveShortcut(shortcut: keyof SettingsData["shortcuts"], key: string | null) {
const shortcuts = settings.get("shortcuts") || <SettingsData["shortcuts"]>{};
shortcuts[shortcut] = key;
settings.set("shortcuts", shortcuts);
loadShortcuts();
}
+77
View File
@@ -0,0 +1,77 @@
import { app, Tray, Menu } from "electron";
import path from "path";
import { showAboutWindow } from "electron-util";
import * as autoUpdater from "./auto-updater";
import * as log from "./log";
import { getWindow } from "./window";
let tray: Tray | undefined;
const assetsDirectory = path.join(__dirname, "..", "assets");
export function getTray() {
return tray;
}
export function createTray() {
tray = new Tray(path.join(assetsDirectory, "icons", "logo.png"));
const trayContextMenu = Menu.buildFromTemplate([
{
id: "open",
label: "Show / Hide",
click() {
const mainWindow = getWindow();
if (!mainWindow) {
throw new Error("Main window not found");
}
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
mainWindow.show();
}
},
},
{
label: "Check for updates",
async click() {
await autoUpdater.manualRequestUpdateCheck();
},
},
{
label: "Open Logs",
click() {
log.openLog();
},
},
{
label: "About",
click() {
showAboutWindow({
icon: path.join(assetsDirectory, "icons", "logo.png"),
copyright: "Copyright © WorkAdventure",
});
},
},
{
label: "Quit",
click() {
// app.confirmedExitPrompt = true;
app.quit();
},
},
]);
tray.setContextMenu(trayContextMenu);
tray.on("double-click", () => {
const mainWindow = getWindow();
if (!mainWindow) {
throw new Error("Main window not found");
}
mainWindow.show();
});
}
+140
View File
@@ -0,0 +1,140 @@
import { BrowserView, BrowserWindow } from "electron";
import electronIsDev from "electron-is-dev";
import windowStateKeeper from "electron-window-state";
import path from "path";
import { loadCustomScheme } from "./serve";
let mainWindow: BrowserWindow | undefined;
let appView: BrowserView | undefined;
const sidebarWidth = 70;
export function getWindow() {
return mainWindow;
}
export function getAppView() {
return appView;
}
export async function createWindow() {
// do not re-create window if still existing
if (mainWindow) {
return;
}
// Load the previous state with fallback to defaults
const windowState = windowStateKeeper({
defaultWidth: 1000,
defaultHeight: 800,
maximize: true,
});
mainWindow = new BrowserWindow({
x: windowState.x,
y: windowState.y,
width: windowState.width,
height: windowState.height,
autoHideMenuBar: true,
show: false,
webPreferences: {
preload: path.resolve(__dirname, "..", "dist", "preload-local-app", "preload.js"),
},
});
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
windowState.manage(mainWindow);
mainWindow.on("closed", () => {
mainWindow = undefined;
});
// mainWindow.on('close', async (event) => {
// if (!app.confirmedExitPrompt) {
// event.preventDefault(); // Prevents the window from closing
// const choice = await dialog.showMessageBox(getMainWindow(), {
// type: 'question',
// buttons: ['Yes', 'Abort'],
// title: 'Confirm',
// message: 'Are you sure you want to quit?',
// });
// if (choice.response === 0) {
// app.confirmedExitPrompt = true;
// mainWindow.close();
// }
// } else {
// app.confirmedExitPrompt = false;
// }
// });
appView = new BrowserView({
webPreferences: {
preload: path.resolve(__dirname, "..", "dist", "preload-app", "preload.js"),
},
});
appView.setBounds({
x: sidebarWidth,
y: 0,
width: mainWindow.getBounds().width - sidebarWidth,
height: mainWindow.getBounds().height,
});
appView.setAutoResize({
width: true,
height: true,
});
mainWindow.once("ready-to-show", () => {
mainWindow?.show();
if (electronIsDev) {
// appView?.webContents.openDevTools({
// mode: "detach",
// });
mainWindow?.webContents.openDevTools({ mode: "detach" });
}
});
mainWindow.webContents.on("did-finish-load", () => {
mainWindow?.setTitle("WorkAdventure Desktop");
});
if (electronIsDev && process.env.LOCAL_APP_URL) {
await mainWindow.loadURL(process.env.LOCAL_APP_URL);
} else {
// load custom url scheme app://
await loadCustomScheme(mainWindow);
await mainWindow.loadURL("app://-");
}
}
export function showAppView(url?: string) {
if (!appView) {
throw new Error("App view not found");
}
if (!mainWindow) {
throw new Error("Main window not found");
}
if (mainWindow.getBrowserView()) {
mainWindow.removeBrowserView(appView);
}
mainWindow.addBrowserView(appView);
if (url) {
appView.webContents.loadURL(url);
}
}
export function hideAppView() {
if (!appView) {
throw new Error("App view not found");
}
if (!mainWindow) {
throw new Error("Main window not found");
}
mainWindow.removeBrowserView(appView);
}