diff --git a/main.js b/main.js index 86d3d24..7e32490 100644 --- a/main.js +++ b/main.js @@ -8,6 +8,41 @@ let pendingFilePath = null; let fileWatcher = null; let closeTimeout = null; +// ===== Single Instance Lock ===== +const gotTheLock = app.requestSingleInstanceLock(); + +if (!gotTheLock) { + app.quit(); +} else { + app.on('second-instance', (event, commandLine, workingDirectory) => { + // A second instance was launched (e.g. double-clicking a .md file) + // Focus the existing window and open the file in it + if (mainWindow) { + if (mainWindow.isMinimized()) mainWindow.restore(); + mainWindow.focus(); + + // Extract file path from the second instance's command line args + const filePath = getFilePathFromArgs(commandLine); + if (filePath) { + openFileInTab(filePath); + } + } + }); +} + +// Extract a valid file path from command line arguments (skip Electron flags) +function getFilePathFromArgs(args) { + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + if (!arg.startsWith('--') && !arg.startsWith('-')) { + try { + if (fs.existsSync(arg)) return arg; + } catch (e) { /* ignore */ } + } + } + return null; +} + function createWindow() { mainWindow = new BrowserWindow({ width: 1200, @@ -252,14 +287,9 @@ ipcMain.handle('window:cancelClose', () => { } }); -// Command line file +// Command line file (first instance) function getCommandLineFile() { - const args = process.argv.slice(1); - if (args.length > 0 && !args[0].startsWith('--')) { - const filePath = args[0]; - if (fs.existsSync(filePath)) return filePath; - } - return null; + return getFilePathFromArgs(process.argv); } // App lifecycle