-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
356 lines (300 loc) · 8.7 KB
/
main.js
File metadata and controls
356 lines (300 loc) · 8.7 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
const {
app,
Tray,
Menu,
nativeImage,
clipboard,
BrowserWindow,
ipcMain,
globalShortcut,
dialog,
shell,
} = require("electron");
const fs = require("fs");
const path = require("path");
let tray;
let managerWindow;
let editorWindow;
let isLinkModeActive = false; // Estado da funcionalidade de links
// Caminho para o snippets.json fora do ASAR no build
const dataPath = app.isPackaged
? path.join(process.resourcesPath, "app.asar.unpacked", "snippets.json")
: path.join(__dirname, "snippets.json");
// Função para extrair links do texto
function extractLinks(text) {
const urlRegex = /(https?:\/\/[^\s]+)/g;
const matches = text.match(urlRegex);
return matches ? matches.slice(0, 200) : []; // Máximo 200 links
}
// Função para criar preview dos links
function createLinkPreview(links) {
if (links.length === 0) return 'Nenhum link encontrado no clipboard.';
const totalLinks = links.length;
const previewLinks = links.slice(0, 10); // Mostrar apenas os primeiros 10 no preview
let preview = `Encontrados ${totalLinks} link(s) total`;
if (totalLinks > 10) {
preview += ` (mostrando primeiros 10)`;
}
preview += `:\n\n`;
previewLinks.forEach((link, index) => {
const shortLink = link.length > 60 ? link.substring(0, 60) + '...' : link;
preview += `${index + 1}. ${shortLink}\n`;
});
if (totalLinks > 10) {
preview += `\n... e mais ${totalLinks - 10} link(s)`;
}
return preview;
}
// Função para abrir links
function openLinks(links) {
links.forEach(link => {
shell.openExternal(link);
});
}
// Função para processar clipboard e abrir links
function processClipboard() {
if (!isLinkModeActive) return;
const clipboardText = clipboard.readText();
if (!clipboardText) {
dialog.showMessageBox({
type: 'info',
title: 'Clipboard vazio',
message: 'Não há texto no clipboard.',
buttons: ['OK']
});
return;
}
const links = extractLinks(clipboardText);
if (links.length === 0) {
dialog.showMessageBox({
type: 'info',
title: 'Nenhum link encontrado',
message: 'Não foram encontrados links no clipboard.',
buttons: ['OK']
});
return;
}
const preview = createLinkPreview(links);
const response = dialog.showMessageBoxSync({
type: 'question',
title: 'Abrir links do clipboard?',
message: preview,
buttons: ['Abrir todos', 'Cancelar'],
defaultId: 0,
cancelId: 1
});
if (response === 0) {
openLinks(links);
}
}
// Função para alternar modo de links
function toggleLinkMode() {
isLinkModeActive = !isLinkModeActive;
updateTrayIcon();
const status = isLinkModeActive ? 'ativado' : 'desativado';
console.log(`Modo de links ${status}`);
}
// Função para atualizar o ícone do tray baseado no estado
function updateTrayIcon() {
// Criar ícone colorido baseado no estado
const iconPath = isLinkModeActive
? path.join(__dirname, "public", "green_circle.png")
: path.join(__dirname, "public", "red_circle.png");
// Se não existir logo_active.png, criar um ícone verde programaticamente
let icon;
if (fs.existsSync(iconPath)) {
icon = nativeImage.createFromPath(iconPath);
} else {
// Usar o ícone padrão e adicionar um overlay visual no tooltip
icon = nativeImage.createFromPath(path.join(__dirname, "public", "logo.png"));
}
tray.setImage(icon);
const baseTooltip = "SnipDeck by nIcory";
const linkStatus = isLinkModeActive ? " | Links: ATIVO 🟢" : " | Links: INATIVO 🔴";
tray.setToolTip(baseTooltip + linkStatus);
}
function buildContextMenu() {
let dynamicItems = [];
try {
const jsonData = fs.readFileSync(dataPath, "utf-8");
const items = JSON.parse(jsonData);
dynamicItems = items.map((item) => ({
label: item.name,
click: () => {
clipboard.writeText(item.content);
console.log(`Copied "${item.name}" to clipboard`);
},
}));
} catch (error) {
console.error("Erro ao ler snippets.json:", error);
}
const fixedItems = [
{ type: "separator" },
{
label: `Modo Links: ${isLinkModeActive ? 'ATIVO 🟢' : 'INATIVO 🔴'}`,
click: toggleLinkMode,
},
{
label: "Processar Clipboard (Alt+Ctrl+Shift+Space)",
click: processClipboard,
enabled: isLinkModeActive,
},
{ type: "separator" },
{
label: "Update Snippets",
click: () => {
createManagerWindow();
},
},
{
label: "Quit",
click: () => app.quit(),
},
];
const contextMenu = Menu.buildFromTemplate([...dynamicItems, ...fixedItems]);
tray.setContextMenu(contextMenu);
}
function createManagerWindow() {
if (managerWindow) {
managerWindow.focus();
return;
}
managerWindow = new BrowserWindow({
width: 900,
height: 700,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
resizable: true,
title: "SnipDeck Manager",
autoHideMenuBar: true,
frame: true,
});
managerWindow.loadFile("manager.html");
managerWindow.on("closed", () => {
managerWindow = null;
});
}
function createEditorWindow(snippet = null, isEdit = false) {
if (editorWindow) {
editorWindow.focus();
return;
}
editorWindow = new BrowserWindow({
width: 600,
height: 500,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
resizable: true,
title: isEdit ? "Editar Snippet" : "Adicionar Snippet",
parent: managerWindow,
modal: true,
autoHideMenuBar: true,
frame: true,
});
editorWindow.loadFile("editor.html");
editorWindow.webContents.once("did-finish-load", () => {
if (snippet) {
editorWindow.webContents.send("load-snippet", snippet);
}
});
editorWindow.on("closed", () => {
editorWindow = null;
});
}
// IPC Handlers
ipcMain.handle("get-snippets", () => {
try {
const jsonData = fs.readFileSync(dataPath, "utf-8");
return JSON.parse(jsonData);
} catch (error) {
console.error("Erro ao ler snippets.json:", error);
return [];
}
});
ipcMain.handle("delete-snippet", (event, index) => {
try {
const jsonData = fs.readFileSync(dataPath, "utf-8");
const snippets = JSON.parse(jsonData);
snippets.splice(index, 1);
fs.writeFileSync(dataPath, JSON.stringify(snippets, null, 2));
buildContextMenu(); // Atualiza o menu do tray
return true;
} catch (error) {
console.error("Erro ao deletar snippet:", error);
return false;
}
});
ipcMain.handle("save-snippet", (event, snippet, index = null) => {
try {
const jsonData = fs.readFileSync(dataPath, "utf-8");
const snippets = JSON.parse(jsonData);
if (index !== null) {
// Editar snippet existente
snippets[index] = snippet;
} else {
// Adicionar novo snippet
snippets.push(snippet);
}
fs.writeFileSync(dataPath, JSON.stringify(snippets, null, 2));
buildContextMenu(); // Atualiza o menu do tray
return true;
} catch (error) {
console.error("Erro ao salvar snippet:", error);
return false;
}
});
ipcMain.on("open-editor", (event, snippet = null, index = null) => {
createEditorWindow(snippet ? { ...snippet, index } : null, snippet !== null);
});
ipcMain.on("close-editor", () => {
if (editorWindow) {
editorWindow.close();
}
});
ipcMain.on("refresh-manager", () => {
if (managerWindow) {
managerWindow.webContents.send("refresh-snippets");
}
});
app.whenReady().then(() => {
const icon = nativeImage.createFromPath(
path.join(__dirname, "public", "logo.png")
);
tray = new Tray(icon);
// Definir tooltip inicial
updateTrayIcon();
buildContextMenu();
// Registrar atalhos globais
globalShortcut.register("Control+Alt+C", () => {
toggleLinkMode();
buildContextMenu(); // Atualizar menu após mudança de estado
});
globalShortcut.register("Alt+Control+Shift+Space", () => {
processClipboard();
});
console.log('SnipDeck iniciado com funcionalidade de links!');
console.log('Atalhos:');
console.log('- Ctrl + Alt + C: Ativar/Desativar modo de links');
console.log('- Alt + Ctrl + Shift + Space: Processar clipboard (quando ativo)');
// 🚀 Hot reload: escuta alterações no JSON
fs.watchFile(dataPath, { interval: 1000 }, () => {
console.log("snippets.json modificado — atualizando menu...");
buildContextMenu();
// Atualiza a janela do manager se estiver aberta
if (managerWindow) {
managerWindow.webContents.send("refresh-snippets");
}
});
});
app.on("window-all-closed", (event) => {
// Previne que o app feche quando todas as janelas são fechadas
event.preventDefault();
});
app.on("will-quit", () => {
// Limpar todos os atalhos globais quando o app for fechado
globalShortcut.unregisterAll();
});