|
| 1 | +import { randomUUID } from 'node:crypto'; |
| 2 | + |
| 3 | +const pending = new Map(); |
| 4 | +export function registerGlassMenuIPC({ handle }) { |
| 5 | + handle('glass-menu:choice', (event, value) => { |
| 6 | + const entry = pending.get(event.sender.id); |
| 7 | + if (!entry || event.senderFrame !== event.sender.mainFrame || value?.id !== entry.id) |
| 8 | + return false; |
| 9 | + const item = value.item === null ? null : entry.items.get(value.item); |
| 10 | + if (value.item !== null && (!item || item.enabled === false || item.type === 'separator')) |
| 11 | + return false; |
| 12 | + try { |
| 13 | + if (item?.role === 'copy') event.sender.copy(); |
| 14 | + else if (item?.role === 'selectAll') event.sender.selectAll(); |
| 15 | + else item?.click?.(item, entry.target); |
| 16 | + } finally { |
| 17 | + entry.finish(); |
| 18 | + } |
| 19 | + return true; |
| 20 | + }); |
| 21 | +} |
| 22 | + |
| 23 | +// Keep commands and file paths in the main process. The renderer receives only |
| 24 | +// presentation data and can choose one item from its own outstanding menu. |
| 25 | +export function popupGlassMenu({ target, template, enabled, Menu, callback, x, y }) { |
| 26 | + if (!enabled || process.platform !== 'darwin') return false; |
| 27 | + const wc = target.webContents; |
| 28 | + pending.get(wc.id)?.finish(); |
| 29 | + const nativeItems = Menu.buildFromTemplate(template).items; |
| 30 | + const id = randomUUID(); |
| 31 | + const items = new Map(template.map((item, index) => [String(index), item])); |
| 32 | + const finish = () => { |
| 33 | + if (pending.get(wc.id)?.id !== id) return; |
| 34 | + pending.delete(wc.id); |
| 35 | + wc.removeListener('destroyed', finish); |
| 36 | + wc.removeListener('did-start-navigation', finish); |
| 37 | + if (!wc.isDestroyed()) wc.send('glass-menu:closed', id); |
| 38 | + callback?.(); |
| 39 | + }; |
| 40 | + pending.set(wc.id, { id, items, target, finish }); |
| 41 | + wc.once('destroyed', finish); |
| 42 | + wc.once('did-start-navigation', finish); |
| 43 | + wc.send('glass-menu:open', { |
| 44 | + id, |
| 45 | + x, |
| 46 | + y, |
| 47 | + items: template.map((item, index) => ({ |
| 48 | + id: String(index), |
| 49 | + label: nativeItems[index]?.label || item.label || item.role, |
| 50 | + type: item.type || 'normal', |
| 51 | + enabled: item.enabled !== false, |
| 52 | + })), |
| 53 | + }); |
| 54 | + return true; |
| 55 | +} |
0 commit comments