Add proper Electron launcher and building process #6

Merged
grey merged 6 commits from electron into master 2022-11-15 18:28:59 +01:00
Showing only changes of commit de22ec5c3a - Show all commits

View File

@ -1,104 +1,127 @@
const { app, BrowserWindow, ipcMain, Tray, Menu, nativeImage, MenuItem, dialog } = require('electron') const { app, BrowserWindow, ipcMain, Tray, Menu, MenuItem, dialog } = require('electron')
const path = require('path') const path = require('path')
const fs = require('fs') const fs = require('fs')
const _ = require("underscore") const _ = require("underscore")
const open = require('open'); const open = require('open');
const childProcess = require('child_process'); const childProcess = require('child_process');
const http = require('http');
const packageJson = JSON.parse(fs.readFileSync("package.json")) const packageJson = JSON.parse(fs.readFileSync("package.json"))
// a minimal config // a minimal config
let configObject = { let configObject = {
language: "en_uk", language: "en_uk",
startMinimised: false, startMinimised: false,
port: 3000 port: 3000
} }
if (!fs.existsSync("config.json")) { if (!fs.existsSync("config.json")) {
fs.writeFileSync("config.json", "{}"); fs.writeFileSync("config.json", "{}");
} }
const tempJsonText = JSON.parse(fs.readFileSync("config.json", "utf8")); const tempJsonText = JSON.parse(fs.readFileSync("config.json", "utf8"));
configObject = _.extend(configObject, tempJsonText); configObject = _.extend(configObject, tempJsonText);
fs.writeFileSync("config.json", JSON.stringify(configObject)); fs.writeFileSync("config.json", JSON.stringify(configObject));
let serverStatus = "Starting"
const processArgs = process.argv; const processArgs = process.argv;
// Check if --headless is passed as an argument // Check if --headless is passed as an argument
if (processArgs.includes("--headless")) { if (processArgs.includes("--headless")) {
startServer() startServer()
} else { } else {
// Start electron // Start electron
app.whenReady().then(() => { app.whenReady().then(() => {
startServer() startServer()
createTray() createTray()
createWindow() createWindow()
}) setInterval(() => {
http.get('http://127.0.0.1:' + configObject.port + "/api/v1/system", (resp) => {
let data = '';
ipcMain.on('info', function () { // A chunk of data has been received.
if (win) { resp.on('data', (chunk) => {
win.webContents.send('info', { "appStatus": "Testing", "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port }) data += chunk;
} });
})
ipcMain.on('skeleton-close', function (req, cb) { // The whole response has been received. Print out the result.
trayQuit() resp.on('end', () => {
}) let parsed = JSON.parse(data)
serverStatus = "Running"
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}, 1000);
})
ipcMain.on('skeleton-minimize', function (req, cb) { ipcMain.on('info', function () {
win.hide() if (win) {
}) win.webContents.send('info', { "appStatus": serverStatus, "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port })
}
})
ipcMain.on('skeleton-launch-gui', function () { ipcMain.on('skeleton-close', function (req, cb) {
launchUI() trayQuit()
}) })
ipcMain.on('skeleton-start-minimised', function (e, msg) { ipcMain.on('skeleton-minimize', function (req, cb) {
configObject.startMinimised = msg win.hide()
fs.writeFileSync("config.json", JSON.stringify(configObject)); })
})
ipcMain.on('skeleton-bind-port', function (e, msg) { ipcMain.on('skeleton-launch-gui', function () {
configObject.port = msg launchUI()
console.log("Update port") })
fs.writeFileSync("config.json", JSON.stringify(configObject));
dialog.showMessageBoxSync({ ipcMain.on('skeleton-start-minimised', function (e, msg) {
message: "Port changed. Restart openCountdown to apply change.", configObject.startMinimised = msg
buttons: ["OK"]}) fs.writeFileSync("config.json", JSON.stringify(configObject));
}) })
ipcMain.on('skeleton-bind-port', function (e, msg) {
configObject.port = msg
console.log("Update port")
fs.writeFileSync("config.json", JSON.stringify(configObject));
dialog.showMessageBoxSync({
message: "Port changed. Restart openCountdown to apply change.",
buttons: ["OK"]
})
})
} }
var win, tray = null; var win, tray = null;
const createWindow = () => { const createWindow = () => {
win = new BrowserWindow({ win = new BrowserWindow({
width: 370, width: 370,
height: 500, height: 500,
transparent: true, transparent: true,
frame: false, frame: false,
resizable: false, resizable: false,
icon: path.join(__dirname, 'static/logo/faviconLogo.svg'), icon: path.join(__dirname, 'static/logo/faviconLogo.svg'),
webPreferences: { webPreferences: {
pageVisibility: true, pageVisibility: true,
nodeIntegration: true, nodeIntegration: true,
contextIsolation: true, contextIsolation: true,
preload: path.join(__dirname, 'electronAssets/windowPreload.js'), preload: path.join(__dirname, 'electronAssets/windowPreload.js'),
} }
}) })
win.loadFile('electronAssets/index.html') win.loadFile('electronAssets/index.html')
if (configObject.startMinimised) { if (configObject.startMinimised) {
win.hide() win.hide()
} }
} }
function createTray() { function createTray() {
tray = new Tray('static/logo/faviconLogo.png') tray = new Tray('static/logo/faviconLogo.png')
tray.setIgnoreDoubleClickEvents(true) tray.setIgnoreDoubleClickEvents(true)
const menu = new Menu() const menu = new Menu()
menu.append( menu.append(
new MenuItem({ new MenuItem({
label: 'Show window', label: 'Show window',
@ -114,78 +137,78 @@ function createTray() {
menu.append( menu.append(
new MenuItem({ new MenuItem({
label: 'Quit', label: 'Quit',
accelerator: 'Command+Q', accelerator: 'Command+Q',
click: trayQuit, click: trayQuit,
}) })
) )
tray.setToolTip('openCountdown ' + packageJson.version) tray.setToolTip('openCountdown ' + packageJson.version)
tray.setContextMenu(menu) tray.setContextMenu(menu)
tray.on('click', function (e) { tray.on('click', function (e) {
if (win.isVisible()) { if (win.isVisible()) {
win.hide() win.hide()
} else { } else {
win.show() win.show()
} }
}); });
} }
function showScreen(){ function showScreen() {
win.show() win.show()
} }
function launchUI(){ function launchUI() {
open("http://127.0.0.1:" + configObject.port) open("http://127.0.0.1:" + configObject.port)
} }
function trayQuit(){ function trayQuit() {
let options = { let options = {
buttons: ["Yes","No"], buttons: ["Yes", "No"],
message: "Do you really want to quit openCountdown?" message: "Do you really want to quit openCountdown?"
} }
let response = dialog.showMessageBoxSync(options) let response = dialog.showMessageBoxSync(options)
if(response == 0){ if (response == 0) {
srvProc.kill("SIGINT") srvProc.kill("SIGINT")
setTimeout(app.quit, 1000) setTimeout(app.quit, 1000)
} }
} }
// taken from https://stackoverflow.com/a/22649812/11317151 // taken from https://stackoverflow.com/a/22649812/11317151
function runScript(scriptPath, callback, valueCb) { function runScript(scriptPath, callback, valueCb) {
// keep track of whether callback has been invoked to prevent multiple invocations // keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false; var invoked = false;
var process = childProcess.fork(scriptPath); var process = childProcess.fork(scriptPath);
valueCb(process) valueCb(process)
// listen for errors as they may prevent the exit event from firing // listen for errors as they may prevent the exit event from firing
process.on('error', function (err) { process.on('error', function (err) {
if (invoked) return; if (invoked) return;
invoked = true; invoked = true;
callback(err); callback(err);
}); });
// execute the callback once the process has finished running // execute the callback once the process has finished running
process.on('exit', function (code) { process.on('exit', function (code) {
if (invoked) return; if (invoked) return;
invoked = true; invoked = true;
// var err = code === 0 ? null : new Error('exit code ' + code); // var err = code === 0 ? null : new Error('exit code ' + code);
callback(code); callback(code);
}); });
} }
srvProc = null; srvProc = null;
function setServer(process){ function setServer(process) {
srvProc = process srvProc = process
} }
function startServer(){ function startServer() {
runScript(path.join(__dirname, 'index.js'), function (err) { runScript(path.join(__dirname, 'index.js'), function (err) {
if (err) throw err; if (err) throw err;
}, setServer) }, setServer)
} }