const { app, BrowserWindow, Menu, dialog, ipcMain, shell } = require('electron'); const path = require('path'); const fs = require('fs'); const { exec } = require('child_process'); const XLSX = require('xlsx'); // Get the system Pandoc path function getPandocPath() { // Check common Pandoc installation locations on Windows const commonPaths = [ 'pandoc', // System PATH path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'Pandoc', 'pandoc.exe'), path.join('C:', 'Program Files', 'Pandoc', 'pandoc.exe'), path.join('C:', 'Program Files (x86)', 'Pandoc', 'pandoc.exe'), ]; // Try each path and return the first one that exists for (const pandocPath of commonPaths) { if (pandocPath === 'pandoc') { // For system PATH, we'll check in checkPandocAvailable() return pandocPath; } else if (fs.existsSync(pandocPath)) { return `"${pandocPath}"`; } } // Fallback to system pandoc return 'pandoc'; } // Check if Pandoc is available function checkPandocAvailable() { return new Promise((resolve) => { const pandocPath = getPandocPath(); exec(`${pandocPath} --version`, (error) => { resolve(!error); }); }); } // Simple storage implementation to replace electron-store const settingsPath = path.join(app.getPath('userData'), 'settings.json'); const store = { get: (key, defaultValue) => { try { const data = fs.readFileSync(settingsPath, 'utf-8'); const settings = JSON.parse(data); return settings[key] || defaultValue; } catch { return defaultValue; } }, set: (key, value) => { let settings = {}; try { const data = fs.readFileSync(settingsPath, 'utf-8'); settings = JSON.parse(data); } catch {} settings[key] = value; fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); } }; let mainWindow; let currentFile = null; // This will now represent the active tab's file let pandocAvailable = null; // Cache pandoc availability check // Check if pandoc is available function checkPandocAvailability() { return new Promise((resolve) => { if (pandocAvailable !== null) { resolve(pandocAvailable); return; } exec('pandoc --version', (error, stdout, stderr) => { pandocAvailable = !error; resolve(pandocAvailable); }); }); } function createWindow() { mainWindow = new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true, contextIsolation: false }, icon: path.join(__dirname, '../assets/icon.png') }); mainWindow.loadFile(path.join(__dirname, 'index.html')); createMenu(); mainWindow.on('closed', () => { mainWindow = null; }); // Handle pending file from file association will be handled by renderer-ready event } function buildRecentFilesMenu() { const recentFiles = getRecentFiles(); if (recentFiles.length === 0) { return [ { label: 'No recent files', enabled: false } ]; } const recentFileItems = recentFiles.map(filePath => ({ label: filePath.split(/[\\/]/).pop(), // Get filename only click: () => { if (fs.existsSync(filePath)) { currentFile = filePath; const content = fs.readFileSync(filePath, 'utf-8'); mainWindow.webContents.send('file-opened', { path: filePath, content }); } else { dialog.showErrorBox('File Not Found', `The file "${filePath}" could not be found.`); } }, toolTip: filePath // Show full path in tooltip })); return [ ...recentFileItems, { type: 'separator' }, { label: 'Clear Recent Files', click: () => { mainWindow.webContents.send('clear-recent-files'); } } ]; } function getRecentFiles() { try { const recentFiles = JSON.parse(fs.readFileSync(path.join(app.getPath('userData'), 'recent-files.json'), 'utf-8')); return recentFiles.filter(file => fs.existsSync(file)); } catch (e) { return []; } } function createMenu() { const template = [ { label: 'File', submenu: [ { label: 'New', accelerator: 'CmdOrCtrl+N', click: () => mainWindow.webContents.send('file-new') }, { label: 'Open', accelerator: 'CmdOrCtrl+O', click: openFile }, { label: 'Save', accelerator: 'CmdOrCtrl+S', click: () => mainWindow.webContents.send('file-save') }, { label: 'Save As', accelerator: 'CmdOrCtrl+Shift+S', click: saveAsFile }, { type: 'separator' }, { label: 'Recent Files', submenu: buildRecentFilesMenu() }, { type: 'separator' }, { label: 'Import Document...', accelerator: 'CmdOrCtrl+I', click: importDocument }, { label: 'Export', submenu: [ { label: 'HTML', click: () => exportFile('html') }, { label: 'PDF', click: () => exportFile('pdf') }, { label: 'DOCX', click: () => exportFile('docx') }, { label: 'LaTeX', click: () => exportFile('latex') }, { label: 'RTF', click: () => exportFile('rtf') }, { label: 'ODT', click: () => exportFile('odt') }, { label: 'EPUB', click: () => exportFile('epub') }, { type: 'separator' }, { label: 'PowerPoint (PPTX)', click: () => exportFile('pptx') }, { label: 'OpenDocument Presentation (ODP)', click: () => exportFile('odp') }, { type: 'separator' }, { label: 'CSV (Tables)', click: () => exportSpreadsheet('csv') }, { label: 'XLSX (Tables)', click: () => exportSpreadsheet('xlsx') } ] }, { type: 'separator' }, { label: 'Quit', accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q', click: () => app.quit() } ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'CmdOrCtrl+Shift+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectAll' }, { type: 'separator' }, { label: 'Find & Replace', accelerator: 'CmdOrCtrl+F', click: () => mainWindow.webContents.send('toggle-find') } ] }, { label: 'View', submenu: [ { label: 'Toggle Preview', accelerator: 'CmdOrCtrl+P', click: () => mainWindow.webContents.send('toggle-preview') }, { label: 'Theme', submenu: [ { label: 'Light', click: () => setTheme('light') }, { label: 'Dark', click: () => setTheme('dark') }, { label: 'Solarized', click: () => setTheme('solarized') }, { label: 'Monokai', click: () => setTheme('monokai') }, { label: 'GitHub', click: () => setTheme('github') } ] }, { type: 'separator' }, { label: 'Font Size', submenu: [ { label: 'Increase Font Size', accelerator: 'CmdOrCtrl+Shift+Plus', click: () => mainWindow.webContents.send('adjust-font-size', 'increase') }, { label: 'Decrease Font Size', accelerator: 'CmdOrCtrl+Shift+-', click: () => mainWindow.webContents.send('adjust-font-size', 'decrease') }, { label: 'Reset Font Size', accelerator: 'CmdOrCtrl+Shift+0', click: () => mainWindow.webContents.send('adjust-font-size', 'reset') } ] }, { type: 'separator' }, { label: 'Reload', accelerator: 'CmdOrCtrl+R', role: 'reload' }, { label: 'Toggle DevTools', accelerator: 'F12', role: 'toggleDevTools' }, { type: 'separator' }, { label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' }, { label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' }, { label: 'Reset Zoom', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' } ] }, { label: 'Batch', submenu: [ { label: 'Convert Folder...', click: () => showBatchConversionDialog() } ] }, { label: 'Help', submenu: [ { label: 'About', click: () => { dialog.showMessageBox(mainWindow, { type: 'info', title: 'About PanConverter', message: 'PanConverter', detail: 'A cross-platform Markdown editor and converter using Pandoc.\n\nVersion: 1.5.0\nAuthor: Amit Haridas\nEmail: amit.wh@gmail.com\nLicense: MIT\n\nFeatures:\n• Windows Explorer context menu integration\n• Tabbed interface for multiple files\n• Advanced markdown editing with live preview\n• Enhanced PDF export with built-in Electron fallback\n• File association support for .md files\n• Command-line interface for batch conversion\n• Advanced export options with templates and metadata\n• Batch file conversion with progress tracking\n• Improved preview typography and spacing\n• Adjustable font sizes via menu (Ctrl+Shift+Plus/Minus)\n• Complete theme support including Monokai fixes\n• Find & replace with match highlighting\n• Line numbers and auto-indentation\n• Export to multiple formats via Pandoc\n• PowerPoint & presentation export\n• Export tables to Excel/ODS spreadsheets\n• Document import & conversion\n• Table creation helper\n• Multiple themes support\n• Undo/redo functionality\n• Live word count and statistics', buttons: ['OK'] }); } }, { label: 'Documentation', click: () => shell.openExternal('https://github.com/amitwh/pan-converter') } ] } ]; const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); } function openFile() { const files = dialog.showOpenDialogSync(mainWindow, { properties: ['openFile'], filters: [ { name: 'Markdown', extensions: ['md', 'markdown'] }, { name: 'All Files', extensions: ['*'] } ] }); if (files && files[0]) { currentFile = files[0]; const content = fs.readFileSync(currentFile, 'utf-8'); mainWindow.webContents.send('file-opened', { path: currentFile, content }); } } function saveAsFile() { const file = dialog.showSaveDialogSync(mainWindow, { defaultExt: '.md', filters: [ { name: 'Markdown', extensions: ['md', 'markdown'] }, { name: 'All Files', extensions: ['*'] } ] }); if (file) { currentFile = file; mainWindow.webContents.send('get-content-for-save', file); } } function exportFile(format) { if (!currentFile) { dialog.showErrorBox('Error', 'Please save the file first'); return; } // Show export options dialog showExportOptionsDialog(format); } function showExportOptionsDialog(format) { mainWindow.webContents.send('show-export-dialog', format); } function showBatchConversionDialog() { mainWindow.webContents.send('show-batch-dialog'); } function performExportWithOptions(format, options) { const outputFile = dialog.showSaveDialogSync(mainWindow, { defaultPath: currentFile.replace(/\.[^/.]+$/, `.${format}`), filters: [ { name: format.toUpperCase(), extensions: [format] } ] }); if (!outputFile) return; // User cancelled console.log(`Attempting to export ${format} to:`, outputFile); // Check pandoc availability first checkPandocAvailability().then((hasPandoc) => { console.log('Pandoc available:', hasPandoc); if (!hasPandoc) { // Handle formats that don't require pandoc if (format === 'html') { console.log('Using built-in HTML export'); exportToHTML(outputFile); return; } else if (format === 'pdf') { console.log('Using built-in PDF export'); exportToPDFElectron(outputFile); return; } else { dialog.showErrorBox('Export Error', `Pandoc is required for ${format.toUpperCase()} export but is not installed or not found in PATH.\n\n` + `Please install Pandoc from: https://pandoc.org/installing.html\n\n` + `Alternatively, you can export to HTML or PDF using the built-in converters.` ); return; } } // Use pandoc for export with advanced options console.log('Using Pandoc for export'); let pandocCmd = `${getPandocPath()} "${currentFile}" -o "${outputFile}"`; // Add template if specified if (options.template && options.template !== 'default') { pandocCmd += ` --template="${options.template}"`; } // Add metadata if (options.metadata) { for (const [key, value] of Object.entries(options.metadata)) { if (value.trim()) { pandocCmd += ` -M ${key}="${value.replace(/"/g, '\\"')}"`; } } } // Add variables if (options.variables) { for (const [key, value] of Object.entries(options.variables)) { if (value.trim()) { pandocCmd += ` -V ${key}="${value.replace(/"/g, '\\"')}"`; } } } // Add other options if (options.toc) pandocCmd += ' --toc'; if (options.tocDepth) pandocCmd += ` --toc-depth=${options.tocDepth}`; if (options.numberSections) pandocCmd += ' --number-sections'; if (options.citeproc) pandocCmd += ' --citeproc'; if (options.bibliography) pandocCmd += ` --bibliography="${options.bibliography}"`; if (options.csl) pandocCmd += ` --csl="${options.csl}"`; // Add specific options for PDF export to ensure proper generation if (format === 'pdf') { const pdfEngine = options.pdfEngine || 'xelatex'; const geometry = options.geometry || 'margin=1in'; pandocCmd += ` --pdf-engine=${pdfEngine} -V geometry:${geometry}`; // Try with specified PDF engine exec(pandocCmd, (error, stdout, stderr) => { if (error) { // Try fallback engines if the specified one fails const fallbackEngines = ['pdflatex', 'lualatex']; tryPdfFallback(currentFile, outputFile, fallbackEngines, 0, options, error); } else { showExportSuccess(outputFile); } }); } else if (format === 'docx') { pandocCmd = `${getPandocPath()} "${currentFile}" -t docx -o "${outputFile}"`; exportWithPandoc(pandocCmd, outputFile, format); } else if (format === 'html') { pandocCmd = `${getPandocPath()} "${currentFile}" -t html5 --standalone -o "${outputFile}"`; exportWithPandoc(pandocCmd, outputFile, format); } else if (format === 'latex') { pandocCmd = `${getPandocPath()} "${currentFile}" -t latex -o "${outputFile}"`; exportWithPandoc(pandocCmd, outputFile, format); } else { // Generic export for other formats exportWithPandoc(pandocCmd, outputFile, format); } }).catch((error) => { console.error('Error checking pandoc availability:', error); dialog.showErrorBox('Export Error', `Error checking system requirements: ${error.message}`); }); } function tryPdfFallback(inputFile, outputFile, engines, index, options, lastError) { if (index >= engines.length) { dialog.showErrorBox('PDF Export Error', `Failed to export PDF with all available engines. Please ensure you have one of the following installed:\n` + `• XeLaTeX (recommended): sudo apt-get install texlive-xetex\n` + `• PDFLaTeX: sudo apt-get install texlive-latex-base\n` + `• LuaLaTeX: sudo apt-get install texlive-luatex\n\n` + `Last error: ${lastError.message}` ); return; } const engine = engines[index]; const geometry = options.geometry || 'margin=1in'; let pandocCmd = `${getPandocPath()} "${inputFile}" --pdf-engine=${engine} -V geometry:${geometry} -o "${outputFile}"`; // Add all other options if (options.template && options.template !== 'default') { pandocCmd += ` --template="${options.template}"`; } if (options.metadata) { for (const [key, value] of Object.entries(options.metadata)) { if (value.trim()) { pandocCmd += ` -M ${key}="${value.replace(/"/g, '\\"')}"`; } } } exec(pandocCmd, (error, stdout, stderr) => { if (error) { tryPdfFallback(inputFile, outputFile, engines, index + 1, options, error); } else { showExportSuccess(outputFile); } }); } function showExportSuccess(outputFile) { dialog.showMessageBox(mainWindow, { type: 'info', title: 'Export Complete', message: `File exported successfully to ${outputFile}`, buttons: ['OK'] }); } // Helper function to export with pandoc (general) function exportWithPandoc(pandocCmd, outputFile, format) { console.log(`Executing Pandoc command: ${pandocCmd}`); exec(pandocCmd, (error, stdout, stderr) => { if (error) { console.error(`Pandoc error for ${format}:`, error); console.error(`Pandoc stderr:`, stderr); console.error(`Pandoc stdout:`, stdout); // Provide more specific error messages let errorMessage = `Failed to export to ${format.toUpperCase()}`; if (error.message.includes('not found') || error.message.includes('not recognized')) { errorMessage += '\n\nPandoc is not installed or not found in PATH.'; errorMessage += '\nPlease install Pandoc from: https://pandoc.org/installing.html'; } else if (stderr) { errorMessage += `\n\nError details: ${stderr}`; } else { errorMessage += `\n\nError details: ${error.message}`; } errorMessage += `\n\nCommand used: ${pandocCmd}`; dialog.showErrorBox('Export Error', errorMessage); } else { console.log(`Successfully exported to ${format}:`, outputFile); console.log(`Pandoc stdout:`, stdout); if (stderr) { console.warn(`Pandoc stderr (non-fatal):`, stderr); } showExportSuccess(outputFile); } }); } // Helper function to export PDF with pandoc (with fallbacks) function exportWithPandocPDF(pandocCmd, outputFile) { exec(pandocCmd, (error, stdout, stderr) => { if (error) { console.log('XeLaTeX failed, trying PDFLaTeX...'); // Fallback to pdflatex const fallbackCmd = pandocCmd.replace('--pdf-engine=xelatex', '--pdf-engine=pdflatex'); exec(fallbackCmd, (fallbackError, fallbackStdout, fallbackStderr) => { if (fallbackError) { console.log('PDFLaTeX failed, trying Electron PDF...'); // Final fallback to Electron PDF exportToPDFElectron(outputFile); } else { console.log('Successfully exported PDF with PDFLaTeX'); showExportSuccess(outputFile); } }); } else { console.log('Successfully exported PDF with XeLaTeX'); showExportSuccess(outputFile); } }); } // Export to HTML using marked (no pandoc required) function exportToHTML(outputFile) { try { const marked = require('marked'); const markdownContent = fs.readFileSync(currentFile, 'utf8'); const htmlContent = marked.parse(markdownContent); const fullHtml = `