-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
282 lines (239 loc) · 8.16 KB
/
main.js
File metadata and controls
282 lines (239 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const { app, BrowserWindow, ipcMain, desktopCapturer, screen } = require('electron');
const { exec, execFile } = require('child_process');
const path = require('path');
const fs = require('fs');
let mainWindow;
let overlayWindow;
const pythonExe = '..\\.venv\\Scripts\\python.exe';
let ocrInProgress = false;
function runLatexOCR(imagePath, callback) {
if (ocrInProgress) {
console.log('OCR already in progress, skipping...');
callback(null);
return;
}
ocrInProgress = true;
const scriptPath = path.join(__dirname, 'ocr', 'ocr.py');
if (!fs.existsSync(scriptPath)) {
console.error('OCR script not found at:', scriptPath);
ocrInProgress = false;
callback(null);
return;
}
if (!fs.existsSync(imagePath)) {
console.error('Image file not found at:', imagePath);
ocrInProgress = false;
callback(null);
return;
}
if (!fs.existsSync(pythonExe)) {
console.error('Python executable not found at:', pythonExe);
ocrInProgress = false;
callback(null);
return;
}
const stats = fs.statSync(imagePath);
console.log('🔍 DEBUG: Image file size:', stats.size, 'bytes');
console.log('🔍 DEBUG: Executing Python script...');
const timeout = setTimeout(() => {
console.error('❌ OCR timeout - killing process');
ocrInProgress = false;
callback(null);
}, 30000);
execFile(pythonExe, [scriptPath, imagePath], { timeout: 25000 }, (error, stdout, stderr) => {
clearTimeout(timeout);
ocrInProgress = false;
console.log('🔍 DEBUG: Python execution completed');
if (error) {
console.error('❌ OCR Error:', error.message);
console.error('❌ Error code:', error.code);
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'OCR processing failed. Please try a different area or ensure the image contains clear text/math.',
errorCode: error.code
});
}
callback(null);
return;
}
if (stderr && !stderr.includes('Pydantic serializer warnings') && !stderr.includes('Expected `dict')) {
console.warn('⚠️ OCR Warning:', stderr);
}
if (!stdout || stdout.trim().length === 0) {
console.error('❌ OCR returned empty result');
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'No text/math detected in the selected area. Please try selecting a larger area with clearer content.',
errorCode: 'EMPTY_RESULT'
});
}
callback(null);
return;
}
console.log('✅ OCR Success - Result:', stdout.trim());
callback(stdout.trim());
});
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
const isDev = !app.isPackaged;
const devUrl = 'http://localhost:5173';
const prodUrl = path.join(__dirname, 'dist/index.html');
if (isDev) {
mainWindow.loadURL(devUrl);
} else {
mainWindow.loadFile(prodUrl);
}
}
app.whenReady().then(() => {
exec('wsl.exe', (err) => {
if (err) console.error('⚠️ Failed to start WSL:', err);
});
createWindow();
ipcMain.handle('start-area-screenshot', () => {
const { width, height } = screen.getPrimaryDisplay().bounds;
overlayWindow = new BrowserWindow({
width,
height,
transparent: true,
frame: false,
alwaysOnTop: true,
fullscreen: true,
skipTaskbar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
},
});
overlayWindow.loadFile(path.join(__dirname, 'public', 'overlay.html'));
});
ipcMain.on('cancel-screenshot', () => {
console.log('Screenshot cancelled by user');
if (overlayWindow) {
overlayWindow.close();
overlayWindow = null;
}
if (mainWindow?.webContents) {
mainWindow.webContents.send('screenshot-cancelled');
}
});
ipcMain.on('area-selected', async (event, rect) => {
if (overlayWindow) {
overlayWindow.close();
overlayWindow = null;
}
try {
const display = screen.getPrimaryDisplay();
const dpr = rect.dpr || display.scaleFactor || 1;
const fullW = Math.round(display.bounds.width * dpr);
const fullH = Math.round(display.bounds.height * dpr);
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: { width: fullW, height: fullH },
});
const screenSource = sources[0];
if (!screenSource) {
console.error('No screen source found');
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'Failed to capture screen. Please try again.',
errorCode: 'NO_SCREEN_SOURCE'
});
}
return;
}
let cropped;
try {
cropped = screenSource.thumbnail.crop({
x: Math.round(rect.x * dpr),
y: Math.round(rect.y * dpr),
width: Math.round(rect.width * dpr),
height: Math.round(rect.height * dpr),
});
} catch (e) {
console.warn('Crop failed, using full screenshot');
cropped = screenSource.thumbnail;
}
const buffer = cropped.toPNG();
const tempImagePath = path.join(app.getPath('temp'), 'ocr_capture.png');
console.log('🔍 DEBUG: Saving image to:', tempImagePath);
console.log('🔍 DEBUG: Buffer size:', buffer.length, 'bytes');
try {
fs.writeFileSync(tempImagePath, buffer);
console.log('Image saved successfully');
if (fs.existsSync(tempImagePath)) {
const stats = fs.statSync(tempImagePath);
console.log('🔍 DEBUG: Saved file size:', stats.size, 'bytes');
} else {
console.error('Failed to save image file');
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'Failed to save screenshot. Please try again.',
errorCode: 'SAVE_FAILED'
});
}
return;
}
} catch (saveError) {
console.error('Error saving image:', saveError);
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'Failed to save screenshot. Please try again.',
errorCode: 'SAVE_ERROR'
});
}
return;
}
runLatexOCR(tempImagePath, (latex) => {
if (latex) {
console.log('✅ Area screenshot OCR completed successfully');
if (mainWindow?.webContents) {
mainWindow.webContents.send('screenshot-captured', {
img: `data:image/png;base64,${buffer.toString('base64')}`,
latex,
});
} else {
console.error('mainWindow not ready');
}
} else {
console.error('Area screenshot OCR failed');
// CRITICAL: Always send an event to reset loading state
if (mainWindow?.webContents) {
// If no error was already sent, send a generic one
mainWindow.webContents.send('ocr-error', {
message: 'No text or mathematical content detected in the selected area. Please try selecting a different area.',
errorCode: 'NO_CONTENT_DETECTED'
});
}
}
});
} catch (error) {
console.error('Error during area selection processing:', error);
if (mainWindow?.webContents) {
mainWindow.webContents.send('ocr-error', {
message: 'An unexpected error occurred. Please try again.',
errorCode: 'PROCESSING_ERROR'
});
}
}
});
ipcMain.handle('capture-area', async () => {
const sources = await desktopCapturer.getSources({ types: ['screen'] });
const screenSource = sources[0];
if (!screenSource) return null;
return screenSource.thumbnail.toDataURL();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});