-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
357 lines (331 loc) · 13.7 KB
/
Copy pathmain.js
File metadata and controls
357 lines (331 loc) · 13.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
357
const { app, BrowserWindow, ipcMain, clipboard, dialog, nativeImage, shell, Tray, Menu, globalShortcut, screen } = require('electron');
const fs = require('fs');
const path = require('path');
const { getIconData, iconToSVG, iconToHTML, replaceIDs } = require('@iconify/utils');
const { buildIndex, DEV_PATHS } = require('./build-index');
const { ensureIconifyData, hasIconData } = require('./iconify-data');
const DRAG_DIR = path.join(app.getPath('temp'), 'iconopolis-drags');
let win;
// Dev runs use node_modules/@iconify/json; the packaged app downloads the
// collection to userData on first launch and keeps its index there too.
let P = null;
function resolvePaths() {
if (P) return P;
if (fs.existsSync(DEV_PATHS.jsonDir)) {
P = { ...DEV_PATHS, downloadRoot: null };
} else {
const root = path.join(app.getPath('userData'), 'iconify');
P = {
jsonDir: path.join(root, 'json'),
collectionsFile: path.join(root, 'collections.json'),
outFile: path.join(app.getPath('userData'), 'data', 'index.json'),
downloadRoot: root,
};
}
return P;
}
// ---- Icon set cache (LRU, max 12 sets in memory) ----
const setCache = new Map();
function loadSet(prefix) {
if (setCache.has(prefix)) {
const v = setCache.get(prefix);
setCache.delete(prefix);
setCache.set(prefix, v); // refresh recency
return v;
}
const file = path.join(resolvePaths().jsonDir, `${prefix}.json`);
if (!fs.existsSync(file)) return null;
const data = JSON.parse(fs.readFileSync(file, 'utf8'));
setCache.set(prefix, data);
if (setCache.size > 12) setCache.delete(setCache.keys().next().value);
return data;
}
function renderIconSVG(prefix, name) {
const set = loadSet(prefix);
if (!set) return null;
const data = getIconData(set, name);
if (!data) return null;
const r = iconToSVG(data, { height: 'auto' });
return iconToHTML(replaceIDs(r.body, `${prefix}-${name}-`), r.attributes);
}
// ---- IPC ----
ipcMain.handle('index:get', async () => {
const paths = resolvePaths();
const report = (p) => { if (win) win.webContents.send('setup:progress', p); };
if (paths.downloadRoot && !hasIconData(paths.downloadRoot)) {
await ensureIconifyData(paths.downloadRoot, report);
}
if (!fs.existsSync(paths.outFile)) {
buildIndex(paths, (done, total) => {
if (done % 20 === 0) report({ phase: 'index', pct: Math.round((done / total) * 100) });
});
}
return fs.readFileSync(paths.outFile, 'utf8');
});
ipcMain.handle('icons:render', (_e, prefix, names) => {
const out = {};
for (const name of names) out[name] = renderIconSVG(prefix, name);
return out;
});
ipcMain.handle('clip:text', (_e, text) => clipboard.writeText(text));
// Settings persist to a real file — localStorage can lose writes on fast quits.
const SETTINGS_FILE = () => path.join(app.getPath('userData'), 'settings.json');
ipcMain.handle('settings:load', () => {
try { return JSON.parse(fs.readFileSync(SETTINGS_FILE(), 'utf8')); } catch { return null; }
});
ipcMain.handle('settings:save', (_e, obj) => {
fs.mkdirSync(path.dirname(SETTINGS_FILE()), { recursive: true });
fs.writeFileSync(SETTINGS_FILE(), JSON.stringify(obj, null, 2));
});
// Favorites & collections live in their own file.
const FAVS_FILE = () => path.join(app.getPath('userData'), 'favorites.json');
ipcMain.handle('favs:load', () => {
try { return JSON.parse(fs.readFileSync(FAVS_FILE(), 'utf8')); } catch { return null; }
});
ipcMain.handle('favs:save', (_e, obj) => {
fs.mkdirSync(path.dirname(FAVS_FILE()), { recursive: true });
fs.writeFileSync(FAVS_FILE(), JSON.stringify(obj, null, 2));
});
// Bulk export of a collection into a chosen folder.
ipcMain.handle('export:pickfolder', async () => {
const res = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory'],
message: 'Choose a folder for the exported icons',
});
return res.canceled ? null : res.filePaths[0];
});
ipcMain.handle('export:write', (_e, { dir, items }) => {
fs.mkdirSync(dir, { recursive: true });
let n = 0;
for (const it of items) {
const file = path.join(dir, `${it.filename}.${it.format}`);
if (it.format === 'svg') fs.writeFileSync(file, it.svg, 'utf8');
else fs.writeFileSync(file, nativeImage.createFromDataURL(it.pngDataURL).toPNG());
n++;
}
shell.openPath(dir);
return n;
});
// "Copy Icon": write image flavors only (public.svg-image + public.png) so visual apps
// like PowerPoint paste the icon, never the code. Electron can't write custom pasteboard
// types, so a JXA one-liner does it via NSPasteboard. Returns the resulting flavor list.
const { execFile } = require('child_process');
const JXA_CLIP = `function run(argv) {
ObjC.import('AppKit');
const svgPath = argv[0], pngPath = argv[1];
const pb = $.NSPasteboard.generalPasteboard;
pb.clearContents;
const item = $.NSPasteboardItem.alloc.init;
if (svgPath) {
item.setDataForType($.NSData.dataWithContentsOfFile(svgPath), 'public.svg-image');
var url = $.NSURL.fileURLWithPath(svgPath);
item.setStringForType(url.absoluteString, 'public.file-url');
}
if (pngPath) item.setDataForType($.NSData.dataWithContentsOfFile(pngPath), 'public.png');
pb.writeObjects($.NSArray.arrayWithObject(item));
return pb.types.js.map(function(t){return t.js}).join(',');
}`;
ipcMain.handle('clip:icon', async (_e, { svg, pngDataURL, includeSVG }) => {
const tmp = path.join(app.getPath('temp'), 'iconopolis-clip');
fs.mkdirSync(tmp, { recursive: true });
const pngPath = path.join(tmp, 'icon.png');
fs.writeFileSync(pngPath, nativeImage.createFromDataURL(pngDataURL).toPNG());
let svgPath = '';
if (includeSVG) {
svgPath = path.join(tmp, 'icon.svg');
fs.writeFileSync(svgPath, svg, 'utf8');
}
try {
return await new Promise((resolve, reject) =>
execFile('osascript', ['-l', 'JavaScript', '-e', JXA_CLIP, svgPath, pngPath],
(err, stdout) => (err ? reject(err) : resolve(stdout.trim()))));
} catch {
clipboard.writeImage(nativeImage.createFromDataURL(pngDataURL)); // plain PNG fallback
return 'fallback:image/png';
}
});
ipcMain.handle('clip:png', (_e, dataURL) => {
clipboard.writeImage(nativeImage.createFromDataURL(dataURL));
});
ipcMain.handle('save', async (_e, { name, format, svg, pngDataURL }) => {
const res = await dialog.showSaveDialog(win, {
defaultPath: path.join(app.getPath('downloads'), `${name}.${format}`),
filters: format === 'svg'
? [{ name: 'SVG image', extensions: ['svg'] }]
: [{ name: 'PNG image', extensions: ['png'] }],
});
if (res.canceled || !res.filePath) return false;
if (format === 'svg') fs.writeFileSync(res.filePath, svg, 'utf8');
else fs.writeFileSync(res.filePath, nativeImage.createFromDataURL(pngDataURL).toPNG());
return true;
});
// Drag out: write a real file, then hand it to the OS drag session.
ipcMain.on('drag:start', (event, { name, format, svg, pngDataURL }) => {
fs.mkdirSync(DRAG_DIR, { recursive: true });
const file = path.join(DRAG_DIR, `${name}.${format}`);
if (format === 'svg') fs.writeFileSync(file, svg, 'utf8');
else fs.writeFileSync(file, nativeImage.createFromDataURL(pngDataURL).toPNG());
let icon = nativeImage.createFromDataURL(pngDataURL);
if (icon.getSize().width > 64) icon = icon.resize({ width: 64 });
event.sender.startDrag({ file, icon });
});
function createWindow() {
win = new BrowserWindow({
width: 1120,
height: 780,
minWidth: 720,
minHeight: 480,
titleBarStyle: 'hiddenInset',
trafficLightPosition: { x: 16, y: 16 },
backgroundColor: '#00000000',
vibrancy: 'sidebar',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
},
});
win.loadFile('index.html');
win.on('closed', () => { win = null; });
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Headless verification: ICONOPOLIS_SHOT=/path.png [ICONOPOLIS_QUERY=cat] -> screenshot then quit.
if (process.env.ICONOPOLIS_SHOT) {
win.webContents.once('did-finish-load', async () => {
// Wait for the index (first run may download the icon collection first).
for (let i = 0; i < 360; i++) {
const n = await win.webContents.executeJavaScript('window.state ? state.sets.length : (typeof state !== "undefined" ? state.sets.length : 0)').catch(() => 0);
if (n > 0) break;
await new Promise((r) => setTimeout(r, 2000));
}
await new Promise((r) => setTimeout(r, 1500));
if (process.env.ICONOPOLIS_QUERY) {
await win.webContents.executeJavaScript(
`(function(){const s=document.getElementById('search');s.value=${JSON.stringify(process.env.ICONOPOLIS_QUERY)};s.dispatchEvent(new Event('input'));})()`
);
await new Promise((r) => setTimeout(r, 2500));
const searchState = await win.webContents.executeJavaScript(
`JSON.stringify({ query: state.query, results: state.results.length,
first: state.results.slice(0, 10).map((r) => r.prefix + ':' + r.name) })`
);
console.log('SEARCH ' + searchState);
}
if (process.env.ICONOPOLIS_JS) {
try {
await win.webContents.executeJavaScript(`(async () => { ${process.env.ICONOPOLIS_JS} })()`);
} catch (e) {
console.error('ICONOPOLIS_JS failed:', e.message);
}
await new Promise((r) => setTimeout(r, 2000));
}
const img = await win.webContents.capturePage();
fs.writeFileSync(process.env.ICONOPOLIS_SHOT, img.toPNG());
if (process.env.ICONOPOLIS_TEST) {
const res = await win.webContents.executeJavaScript(`(async () => {
const out = await window.vault.renderIcons('mdi', ['home']);
const svg = out.home;
const png = await svgToPNG(svg, 256);
const flavors = await window.vault.copyIcon({
svg: svg.replaceAll('currentColor', '#E8562A'), pngDataURL: png, includeSVG: true,
});
return { svgOk: svg.includes('<svg'), pngDataURL: png, flavors };
})()`);
const pngBuf = nativeImage.createFromDataURL(res.pngDataURL);
console.log(JSON.stringify({
svgOk: res.svgOk,
pngSize: pngBuf.getSize(),
pasteboardFlavors: res.flavors,
electronSeesImage: !clipboard.readImage().isEmpty(),
}));
fs.writeFileSync(process.env.ICONOPOLIS_SHOT.replace('.png', '-export.png'), pngBuf.toPNG());
}
app.quit();
});
}
}
/* ---------- Quick Search: tray + global hotkey + Spotlight-style panel ---------- */
let quickWin = null;
let tray = null;
function createQuickWindow() {
quickWin = new BrowserWindow({
width: 640,
height: 424,
show: false,
frame: false,
resizable: false,
transparent: true,
alwaysOnTop: true,
skipTaskbar: true,
hasShadow: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
},
});
quickWin.loadFile('quick.html');
quickWin.on('blur', () => { if (!process.env.ICONOPOLIS_QUICKSHOT) quickWin.hide(); });
quickWin.on('closed', () => { quickWin = null; });
}
function toggleQuick() {
if (!quickWin) createQuickWindow();
if (quickWin.isVisible()) { quickWin.hide(); return; }
const d = screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
const [w] = quickWin.getSize();
quickWin.setPosition(
Math.round(d.workArea.x + (d.workArea.width - w) / 2),
Math.round(d.workArea.y + d.workArea.height * 0.18));
quickWin.show();
quickWin.focus();
quickWin.webContents.send('quick:shown');
}
ipcMain.on('quick:hide', () => quickWin?.hide());
function openMainWindow() {
if (win && !win.isDestroyed()) { win.show(); win.focus(); }
else createWindow();
}
function createTray() {
const img = nativeImage.createFromPath(path.join(__dirname, 'assets', 'trayTemplate.png'));
img.setTemplateImage(true);
tray = new Tray(img);
tray.setToolTip('Iconopolis');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Open Iconopolis', click: openMainWindow },
{ label: 'Quick Search', accelerator: 'Cmd+Shift+I', click: toggleQuick },
{ type: 'separator' },
{ label: 'Quit Iconopolis', role: 'quit' },
]));
}
app.whenReady().then(() => {
createWindow();
createQuickWindow();
try { createTray(); } catch (e) { console.error('tray:', e.message); }
if (!globalShortcut.register('CommandOrControl+Shift+I', toggleQuick)) {
console.error('Global shortcut Cmd+Shift+I is taken by another app');
}
// Headless verification of the quick panel: ICONOPOLIS_QUICKSHOT=/path.png [ICONOPOLIS_QUERY=word]
if (process.env.ICONOPOLIS_QUICKSHOT) {
setTimeout(async () => {
toggleQuick();
await new Promise((r) => setTimeout(r, 3000));
if (process.env.ICONOPOLIS_QUERY) {
await quickWin.webContents.executeJavaScript(
`(function(){const i=document.getElementById('qinput');i.value=${JSON.stringify(process.env.ICONOPOLIS_QUERY)};i.dispatchEvent(new Event('input'));})()`);
await new Promise((r) => setTimeout(r, 2500));
const info = await quickWin.webContents.executeJavaScript(
`JSON.stringify({results: results.length, first: results.slice(0,5).map((r)=>r.prefix+':'+r.name)})`);
console.log('QUICK ' + info);
}
const img = await quickWin.webContents.capturePage();
fs.writeFileSync(process.env.ICONOPOLIS_QUICKSHOT, img.toPNG());
app.quit();
}, 4000);
}
});
// Keep running in the menu bar when all windows close (standard Mac behavior).
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
app.on('activate', openMainWindow);
app.on('will-quit', () => globalShortcut.unregisterAll());
app.on('quit', () => {
try { fs.rmSync(DRAG_DIR, { recursive: true, force: true }); } catch {}
});