Files
MarkLite/main.js
T

283 lines
7.3 KiB
JavaScript

const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
let mainWindow = null;
let activeFilePath = null; // Currently active tab's file path
let pendingFilePath = null;
let fileWatcher = null;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
icon: path.join(__dirname, 'assets', 'icon.ico'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
},
titleBarStyle: 'default',
show: false
});
mainWindow.webContents.on('did-finish-load', () => {
if (pendingFilePath) {
openFileInTab(pendingFilePath);
pendingFilePath = null;
}
});
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.setMenu(null);
// Unsaved changes warning on close
mainWindow.on('close', (e) => {
e.preventDefault();
try {
mainWindow.webContents.send('window:confirmClose');
} catch (err) {
mainWindow.removeAllListeners('close');
mainWindow.close();
return;
}
setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.removeAllListeners('close');
mainWindow.close();
}
}, 5000);
});
mainWindow.on('closed', () => {
stopWatching();
mainWindow = null;
});
}
// File watcher
function startWatching(filePath) {
stopWatching();
if (!filePath) return;
try {
fileWatcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change' && mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('file:externallyModified', filePath);
}
});
} catch (err) {
// Silently ignore
}
}
function stopWatching() {
if (fileWatcher) {
fileWatcher.close();
fileWatcher = null;
}
}
async function showOpenDialog() {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Markdown 文件', extensions: ['md', 'markdown', 'txt'] },
{ name: '所有文件', extensions: ['*'] }
]
});
if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths;
}
return null;
}
function readFileContent(filePath) {
return fs.readFileSync(filePath, 'utf-8');
}
// Open file in a new tab (renderer manages tabs)
function openFileInTab(filePath) {
try {
const content = readFileContent(filePath);
activeFilePath = filePath;
startWatching(filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
mainWindow.webContents.send('file:openInTab', { filePath, content });
} catch (err) {
dialog.showErrorBox('错误', `无法读取文件: ${err.message}`);
}
}
// Switch active file (for tab switching)
function switchActiveFile(filePath) {
activeFilePath = filePath || null;
startWatching(filePath);
if (filePath) {
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
} else {
mainWindow.setTitle('MarkLite');
}
}
// IPC Handlers
// Open single file via dialog
ipcMain.handle('dialog:openFile', async () => {
try {
const files = await showOpenDialog();
if (files && files.length > 0) {
const content = readFileContent(files[0]);
activeFilePath = files[0];
startWatching(files[0]);
mainWindow.setTitle(`MarkLite - ${path.basename(files[0])}`);
return { filePath: files[0], content };
}
return null;
} catch (err) {
return { error: err.message };
}
});
ipcMain.handle('file:read', async (event, filePath) => {
try {
const content = readFileContent(filePath);
return { success: true, content };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('file:save', async (event, { filePath, content }) => {
try {
if (filePath) {
stopWatching();
fs.writeFileSync(filePath, content, 'utf-8');
activeFilePath = filePath;
startWatching(filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(filePath)}`);
return { success: true, filePath };
} else {
const result = await dialog.showSaveDialog(mainWindow, {
filters: [
{ name: 'Markdown 文件', extensions: ['md'] },
{ name: '文本文件', extensions: ['txt'] }
]
});
if (!result.canceled) {
stopWatching();
fs.writeFileSync(result.filePath, content, 'utf-8');
activeFilePath = result.filePath;
startWatching(result.filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(result.filePath)}`);
return { success: true, filePath: result.filePath };
}
return { success: false, canceled: true };
}
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('file:saveAs', async (event, { content }) => {
try {
const result = await dialog.showSaveDialog(mainWindow, {
filters: [
{ name: 'Markdown 文件', extensions: ['md'] },
{ name: '文本文件', extensions: ['txt'] }
]
});
if (!result.canceled) {
stopWatching();
fs.writeFileSync(result.filePath, content, 'utf-8');
activeFilePath = result.filePath;
startWatching(result.filePath);
mainWindow.setTitle(`MarkLite - ${path.basename(result.filePath)}`);
return { success: true, filePath: result.filePath };
}
return { success: false, canceled: true };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('file:getCurrentPath', () => {
return activeFilePath;
});
ipcMain.handle('file:stats', async (event, filePath) => {
try {
const stats = fs.statSync(filePath);
return { success: true, size: stats.size, mtime: stats.mtime.toISOString() };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('file:reload', async () => {
if (!activeFilePath) return { success: false, error: '没有打开的文件' };
try {
const content = readFileContent(activeFilePath);
return { success: true, content, filePath: activeFilePath };
} catch (err) {
return { success: false, error: err.message };
}
});
// Tab switched - update active file tracking
ipcMain.handle('tab:switched', (event, filePath) => {
switchActiveFile(filePath);
});
ipcMain.handle('window:forceClose', () => {
stopWatching();
mainWindow.removeAllListeners('close');
mainWindow.close();
});
// Command line file
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;
}
// App lifecycle
app.whenReady().then(() => {
app.on('open-file', (event, filePath) => {
event.preventDefault();
if (mainWindow && mainWindow.webContents.isLoading()) {
pendingFilePath = filePath;
} else if (mainWindow) {
openFileInTab(filePath);
} else {
pendingFilePath = filePath;
}
});
createWindow();
const fileToOpen = getCommandLineFile();
if (fileToOpen) {
pendingFilePath = fileToOpen;
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});