Skip to content

Commit

Permalink
[electron] Auto-detect multiple instances running the same app files …
Browse files Browse the repository at this point in the history
…and auto-quit the older ones
  • Loading branch information
jeremyfa committed Dec 28, 2024
1 parent dc54213 commit 66178a5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
47 changes: 45 additions & 2 deletions runner/app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,55 @@

const path = require('path');
const fs = require('fs');

const crypto = require('crypto');
const os = require('os');
const express = require('express')
const { detect } = require('detect-port')

const spawn = require('child_process').spawn;

const remoteMain = require('@electron/remote/main');
remoteMain.initialize();

function getInstanceLockFilePath(appFilesPath) {
// Create a hash of the app files path to use in the lock file name
const hash = crypto.createHash('md5').update(appFilesPath).digest('hex');
const ceramicDir = path.join(os.homedir(), '.ceramic');

// Ensure .ceramic directory exists
if (!fs.existsSync(ceramicDir)) {
fs.mkdirSync(ceramicDir, { recursive: true });
}

return path.join(ceramicDir, `instance-${hash}.lock`);
}

function setupInstanceManager(appFilesPath) {
const lockFile = getInstanceLockFilePath(appFilesPath);

// Touch the lock file to signal our presence
fs.writeFileSync(lockFile, String(process.pid), 'utf8');

// Watch for changes to the lock file
fs.watchFile(lockFile, { interval: 1000 }, (curr, prev) => {
if (curr.mtime > prev.mtime) {
console.log('New instance detected, shutting down...');
app.quit();
}
});

// Clean up on exit
app.on('will-quit', () => {
fs.unwatchFile(lockFile);
try {
if (fs.readFileSync(lockFile, 'utf8') === String(process.pid)) {
fs.unlinkSync(lockFile);
}
} catch (err) {
console.error('Error cleaning up lock file:', err);
}
});
}

// Electron
const electron = require('electron');
// Module to control application life.
Expand Down Expand Up @@ -68,6 +108,9 @@ if (!fs.existsSync(appFiles)) {
process.exit(1);
}

// Set up instance management immediately after validating appFiles
setupInstanceManager(appFiles);

// Set cwd to appFiles
process.chdir(appFiles);

Expand Down
2 changes: 0 additions & 2 deletions runner/electron.cmd

This file was deleted.

2 changes: 1 addition & 1 deletion tools/src/tools/Helpers.hx
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ class Helpers {

public static function node(args:Array<String>, ?options:{ ?cwd:String, ?mute:Bool, ?detached:Bool, ?tick:()->Void }) {

var node = Path.join([context.ceramicToolsPath, '../node/node_modules/.bin/node']);
var node = 'node';
if (Sys.systemName() == 'Windows')
node += '.cmd';
return command(node, args, options);
Expand Down

0 comments on commit 66178a5

Please sign in to comment.