-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
450 lines (399 loc) · 13.1 KB
/
Copy pathmain.js
File metadata and controls
450 lines (399 loc) · 13.1 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
const { app, BrowserWindow, Tray, Menu, ipcMain, globalShortcut, clipboard, nativeImage, dialog, screen, desktopCapturer } = require('electron');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
// Manejo de instancia única para abrir la ventana al seleccionar en el menú del sistema
const gotTheLock = app.requestSingleInstanceLock();
// Desactivar aceleración por hardware en Linux para solucionar pantalla negra en ventanas transparentes (overlay)
app.disableHardwareAcceleration();
app.commandLine.appendSwitch('enable-transparent-visuals');
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (editorWindow) {
if (editorWindow.isMinimized()) editorWindow.restore();
editorWindow.show();
editorWindow.focus();
}
});
}
let tray = null;
let editorWindow = null;
let overlayWindow = null;
let currentScreenshotDataUrl = null;
function getCombinedDisplayBounds() {
const displays = screen.getAllDisplays();
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
displays.forEach((display) => {
const { x, y, width, height } = display.bounds;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x + width);
maxY = Math.max(maxY, y + height);
});
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
}
function createEditorWindow() {
const primaryDisplay = screen.getPrimaryDisplay();
const { width, height } = primaryDisplay.workAreaSize;
editorWindow = new BrowserWindow({
width: Math.min(1400, width),
height: Math.min(900, height),
minWidth: 400,
minHeight: 200,
icon: path.join(__dirname, 'icon128.png'),
title: 'ScreenShot - Editor de Capturas',
show: false,
frame: false,
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false
}
});
editorWindow.loadFile(path.join(__dirname, 'index.html'));
editorWindow.on('close', (e) => {
if (!app.isQuitting) {
e.preventDefault();
editorWindow.hide();
}
});
}
// Obtener captura de pantalla cruda en vivo del escritorio completo
async function captureDesktopRaw() {
if (editorWindow && editorWindow.isVisible()) {
editorWindow.hide();
}
if (overlayWindow && !overlayWindow.isDestroyed()) {
overlayWindow.hide();
}
// Ocultar temporalmente el menú emergente del tray para no capturarlo en pantalla
if (tray) {
tray.setContextMenu(Menu.buildFromTemplate([]));
}
// Esperar 250ms para que el gestor de ventanas del SO cierre la ventana del menú contextual
await new Promise((resolve) => setTimeout(resolve, 250));
const tempFilePath = path.join(app.getPath('temp'), `screenshot_${Date.now()}.png`);
let capturedDataUrl = null;
let captured = false;
// Intento 1: Herramientas CLI del sistema que capturan la pantalla completa con todas las ventanas activas
try {
await execAsync(`import -window root "${tempFilePath}" || gnome-screenshot -f "${tempFilePath}" || maim "${tempFilePath}" || scrot --multidisp "${tempFilePath}" || scrot -z "${tempFilePath}"`);
if (fs.existsSync(tempFilePath) && fs.statSync(tempFilePath).size > 0) {
const imageBuffer = fs.readFileSync(tempFilePath);
capturedDataUrl = `data:image/png;base64,${imageBuffer.toString('base64')}`;
fs.unlinkSync(tempFilePath);
captured = true;
}
} catch (err) {
console.error('Error en captura CLI:', err);
}
// Intento 2: Fallback nativo desktopCapturer de Electron si fallan las herramientas del sistema
if (!captured) {
try {
const bounds = getCombinedDisplayBounds();
const primaryDisplay = screen.getPrimaryDisplay();
const scaleFactor = primaryDisplay.scaleFactor || 1;
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: {
width: Math.round(bounds.width * scaleFactor),
height: Math.round(bounds.height * scaleFactor)
}
});
if (sources && sources.length > 0) {
capturedDataUrl = sources[0].thumbnail.toDataURL();
captured = true;
}
} catch (err) {
console.error('Error en captura nativa desktopCapturer:', err);
}
}
// Restaurar el menú contextual del tray
if (tray) {
setupTrayMenu();
}
return captured ? capturedDataUrl : null;
}
function createOverlayWindow() {
if (overlayWindow && !overlayWindow.isDestroyed()) return;
const bounds = getCombinedDisplayBounds();
overlayWindow = new BrowserWindow({
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
hasShadow: false,
frame: false,
transparent: true,
backgroundColor: '#00000000',
alwaysOnTop: true,
skipTaskbar: true,
resizable: false,
movable: false,
show: false,
enableLargerThanScreen: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false
}
});
overlayWindow.setAlwaysOnTop(true, 'screen-saver');
overlayWindow.loadFile(path.join(__dirname, 'overlay.html'));
overlayWindow.on('close', (e) => {
if (!app.isQuitting) {
e.preventDefault();
overlayWindow.hide();
}
});
}
function showOverlayWithImage(rawDataUrl) {
const bounds = getCombinedDisplayBounds();
if (!overlayWindow || overlayWindow.isDestroyed()) {
createOverlayWindow();
overlayWindow.webContents.once('did-finish-load', () => {
overlayWindow.setBounds(bounds);
overlayWindow.webContents.send('load-overlay', rawDataUrl);
overlayWindow.show();
overlayWindow.focus();
});
} else {
overlayWindow.setBounds(bounds);
overlayWindow.webContents.send('load-overlay', rawDataUrl);
overlayWindow.show();
overlayWindow.focus();
}
}
// Captura de área interactiva (F9 / PrintScreen)
let isCapturing = false;
async function captureArea() {
if (isCapturing) return;
isCapturing = true;
try {
const rawDataUrl = await captureDesktopRaw();
if (!rawDataUrl) {
console.error('No se pudo capturar la pantalla para la selección de área.');
return;
}
showOverlayWithImage(rawDataUrl);
} finally {
isCapturing = false;
}
}
// Captura completa del escritorio sin selección previa
async function captureFullDesktop() {
const rawDataUrl = await captureDesktopRaw();
if (rawDataUrl) {
currentScreenshotDataUrl = rawDataUrl;
showEditorWithImage(currentScreenshotDataUrl);
} else {
console.error('No se pudo realizar la captura de pantalla completa.');
}
}
function showEditorWithImage(dataUrl) {
currentScreenshotDataUrl = dataUrl;
if (!editorWindow) {
createEditorWindow();
}
editorWindow.show();
editorWindow.maximize();
editorWindow.focus();
editorWindow.webContents.send('load-screenshot', dataUrl);
}
function setupTrayMenu() {
if (!tray) return;
const contextMenu = Menu.buildFromTemplate([
{
label: '✂️ Seleccionar área de captura (F9)',
click: () => captureArea()
},
{
label: '📸 Tomar captura completa',
click: () => captureFullDesktop()
},
{
label: '🎨 Abrir editor',
click: () => {
if (!editorWindow) createEditorWindow();
editorWindow.show();
editorWindow.focus();
if (currentScreenshotDataUrl) {
editorWindow.webContents.send('load-screenshot', currentScreenshotDataUrl);
}
}
},
{ type: 'separator' },
{
label: '❌ Salir',
click: () => {
app.isQuitting = true;
app.quit();
}
}
]);
tray.setContextMenu(contextMenu);
}
function createSystray() {
const iconPath = path.join(__dirname, 'icon128.png');
const trayIcon = nativeImage.createFromPath(iconPath).resize({ width: 22, height: 22 });
tray = new Tray(trayIcon);
tray.setToolTip('ScreenShot - Captura y Anotación de Pantalla');
setupTrayMenu();
tray.on('click', () => captureArea());
}
function removeAutostartLinux() {
try {
app.setLoginItemSettings({ openAtLogin: false });
if (process.platform === 'linux') {
const autostartFile = path.join(app.getPath('home'), '.config', 'autostart', 'screenshot.desktop');
if (fs.existsSync(autostartFile)) {
fs.unlinkSync(autostartFile);
}
}
} catch (err) {
console.error('Error al remover autostart:', err);
}
}
// --- Atajos globales con protección contra conflictos de XGrabKey en Linux ---
// En Linux/X11 con múltiples layouts de teclado, XGrabKey puede capturar
// keycodes no deseados (como la tecla "1"). Se registran los atajos solo
// cuando ninguna ventana de la app tiene el foco, y se liberan al enfocar.
let shortcutsRegistered = false;
function registerGlobalShortcuts() {
if (shortcutsRegistered) return;
try {
globalShortcut.register('F9', () => captureArea());
globalShortcut.register('CommandOrControl+Shift+S', () => captureArea());
shortcutsRegistered = true;
console.log('Atajo global F9 (y Ctrl+Shift+S) registrado activamente.');
} catch (err) {
console.log('Error al registrar atajos globales:', err);
}
}
app.whenReady().then(() => {
createSystray();
createEditorWindow();
removeAutostartLinux();
registerGlobalShortcuts();
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
app.on('window-all-closed', (e) => {
e.preventDefault();
});
// Handlers IPC
ipcMain.on('take-screenshot', () => {
captureArea();
});
ipcMain.on('take-area-screenshot', () => {
captureArea();
});
ipcMain.on('cropped-image-captured', (event, croppedDataUrl) => {
if (overlayWindow && !overlayWindow.isDestroyed()) {
overlayWindow.close();
overlayWindow = null;
}
showEditorWithImage(croppedDataUrl);
});
ipcMain.on('close-overlay', () => {
if (overlayWindow && !overlayWindow.isDestroyed()) {
overlayWindow.close();
overlayWindow = null;
}
});
ipcMain.on('close-editor', () => {
if (editorWindow) editorWindow.hide();
});
ipcMain.on('minimize-editor', () => {
if (editorWindow) editorWindow.minimize();
});
ipcMain.on('maximize-editor', () => {
if (editorWindow) {
if (editorWindow.isMaximized()) {
editorWindow.unmaximize();
} else {
editorWindow.maximize();
}
}
});
ipcMain.handle('copy-to-clipboard', async (event, dataUrl) => {
try {
const image = nativeImage.createFromDataURL(dataUrl);
clipboard.writeImage(image);
return { success: true };
} catch (err) {
console.error('Error al copiar al portapapeles:', err);
return { success: false, error: err.message };
}
});
ipcMain.handle('open-image-file', async () => {
try {
const { canceled, filePaths } = await dialog.showOpenDialog(editorWindow, {
title: 'Abrir Imagen para Editar',
defaultPath: app.getPath('pictures'),
properties: ['openFile'],
filters: [
{ name: 'Imágenes', extensions: ['png', 'jpg', 'jpeg', 'webp', 'bmp', 'gif'] }
]
});
if (canceled || !filePaths || filePaths.length === 0) {
return { success: false, canceled: true };
}
const filePath = filePaths[0];
const imageBuffer = fs.readFileSync(filePath);
const ext = path.extname(filePath).toLowerCase().replace('.', '');
const mimeType = ext === 'png' ? 'image/png' : (ext === 'webp' ? 'image/webp' : 'image/jpeg');
const dataUrl = `data:${mimeType};base64,${imageBuffer.toString('base64')}`;
return { success: true, dataUrl, filePath };
} catch (err) {
console.error('Error al abrir imagen desde disco:', err);
return { success: false, error: err.message };
}
});
ipcMain.handle('select-directory', async () => {
try {
const { canceled, filePaths } = await dialog.showOpenDialog(editorWindow, {
title: 'Seleccionar Carpeta para Guardar Capturas',
properties: ['openDirectory', 'createDirectory']
});
if (canceled || !filePaths || filePaths.length === 0) {
return { success: false, canceled: true };
}
return { success: true, path: filePaths[0] };
} catch (err) {
console.error('Error al seleccionar directorio:', err);
return { success: false, error: err.message };
}
});
ipcMain.handle('save-image', async (event, dataUrl, defaultDir) => {
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const defaultName = `ScreenShot_${timestamp}.png`;
const targetDir = (defaultDir && fs.existsSync(defaultDir)) ? defaultDir : app.getPath('pictures');
const { canceled, filePath } = await dialog.showSaveDialog(editorWindow, {
title: 'Guardar Captura de Pantalla',
defaultPath: path.join(targetDir, defaultName),
filters: [{ name: 'Imágenes PNG', extensions: ['png'] }]
});
if (canceled || !filePath) return { success: false, canceled: true };
const base64Data = dataUrl.replace(/^data:image\/png;base64,/, '');
fs.writeFileSync(filePath, base64Data, 'base64');
return { success: true, filePath };
} catch (err) {
console.error('Error al guardar la imagen:', err);
return { success: false, error: err.message };
}
});