add desktop app

This commit is contained in:
Anton Bracke
2022-02-17 18:09:57 +01:00
parent 8dc31c9e06
commit 31a0d7d452
20 changed files with 4601 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
import { app, BrowserWindow } from "electron";
import { createWindow, getWindow } from "./window";
import { createTray } from "./tray";
// import * as autoUpdater from "./auto-updater";
import updateAutoLaunch from "./update-auto-launch";
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.on("ready", () => {
// autoUpdater.init();
// enable auto launch
updateAutoLaunch();
// load ipc handler
// ipc();
// Don't show the app in the doc
// if (app.dock) {
// app.dock.hide();
// }
createWindow();
createTray();
});
// 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
});
}
export default {
init,
};
+94
View File
@@ -0,0 +1,94 @@
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;
}
export 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.isQuiting = true;
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);
}
+66
View File
@@ -0,0 +1,66 @@
import { dialog, shell } from "electron";
import electronIsDev from "electron-is-dev";
import log from "electron-log";
import settings from "./settings";
function onError(e: Error) {
try {
log.error(e);
dialog.showErrorBox(
"WorkAdventure - A JavaScript error occurred",
e.stack || ""
);
} catch (logError) {
// eslint-disable-next-line no-console
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() {
const logLevel = settings.get("log_level", "info");
log.transports.file.level = logLevel;
log.transports.console.level = logLevel;
// eslint-disable-next-line no-console
console.log = log.log.bind(log);
if (!electronIsDev) {
log.transports.file.fileName = "work-adventure.log";
} else {
console.log("Log file is disabled in dev. Using console output instead.");
}
process.on("uncaughtException", onError);
process.on("unhandledRejection", onRejection);
}
export async function openLog() {
const logFilePath = log.transports.file.getFile().path;
await shell.openPath(logFilePath);
}
export default {
init,
};
+11
View File
@@ -0,0 +1,11 @@
import app from "./app";
import log from "./log";
import settings from "./settings";
async function start() {
await settings.init();
log.init();
}
start();
app.init();
+24
View File
@@ -0,0 +1,24 @@
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;
}
+42
View File
@@ -0,0 +1,42 @@
import ElectronLog from "electron-log";
import Settings from "electron-settings";
type SettingsData = {
log_level: ElectronLog.LogLevel;
auto_launch_enabled: boolean;
};
let settings: SettingsData;
async function init() {
settings = (await Settings.get()) as SettingsData;
}
function get<T extends keyof SettingsData>(
key: T,
fallback?: SettingsData[T]
): SettingsData[T] {
if (settings === null) {
throw new Error("Settings not initialized");
}
return settings[key];
}
export function set<T extends keyof SettingsData>(
key: T,
value: SettingsData[T]
) {
if (settings === null) {
throw new Error("Settings not initialized");
}
settings[key] = value;
void Settings.set(settings);
}
export default {
init,
get,
set,
};
+80
View File
@@ -0,0 +1,80 @@
import { app, Tray, Menu } from "electron";
import * as 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: "Open / Close",
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(__dirname, "..", "assets", "icons", "logo.png"),
copyright: "Copyright © WorkAdventure",
});
},
},
{
label: "Quit",
click() {
app.isQuiting = true;
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();
});
return tray;
}
+41
View File
@@ -0,0 +1,41 @@
import AutoLaunch from "auto-launch";
import * as isDev from "electron-is-dev";
import { app } from "electron";
import settings from "./settings";
export default async () => {
let isAutoLaunchEnabled = settings.get("auto_launch_enabled");
// set default to enabled
if (isAutoLaunchEnabled === null) {
settings.set("auto_launch_enabled", true);
isAutoLaunchEnabled = true;
}
// Don't run this in development
if (isDev) {
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,
});
};
+81
View File
@@ -0,0 +1,81 @@
import { BrowserWindow } from "electron";
import windowStateKeeper from "electron-window-state";
import { getTray } from "./tray";
let mainWindow: BrowserWindow | undefined;
const url = process.env.PLAY_URL; // TODO
export function getWindow() {
return mainWindow;
}
export 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,
title: "WorkAdventure",
webPreferences: {
// allowRunningInsecureContent: false,
// contextIsolation: true, // TODO: remove in electron 12
// nodeIntegration: false,
// sandbox: true,
},
});
// 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("show", () => {
// TODO
});
mainWindow.on("closed", () => {
mainWindow = undefined;
});
mainWindow.once("ready-to-show", () => {
mainWindow?.show();
});
// 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;
// }
// });
// and load the index.html of the app.
if (url) {
mainWindow.loadURL(url); // TODO: load app on demand
}
}