forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
571 lines (516 loc) · 16.9 KB
/
index.js
File metadata and controls
571 lines (516 loc) · 16.9 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import fs from 'fs'
import path from 'path'
import { app, ipcMain, Menu } from 'electron'
import log from 'electron-log'
import { ensureDirSync, isDirectory2, isFile2 } from 'common/filesystem'
import { isLinux, isOsx, isWindows } from '../config'
import { parseMenu } from '../keyboard/shortcutHandler'
import { updateSidebarMenu } from '../menu/actions/edit'
import { updateFormatMenu } from '../menu/actions/format'
import { updateSelectionMenus } from '../menu/actions/paragraph'
import { viewLayoutChanged } from '../menu/actions/view'
import configureMenu, { configSettingMenu } from '../menu/templates'
const RECENTLY_USED_DOCUMENTS_FILE_NAME = 'recently-used-documents.json'
const MAX_RECENTLY_USED_DOCUMENTS = 12
export const MenuType = {
DEFAULT: 0,
EDITOR: 1,
SETTINGS: 2
}
class AppMenu {
/**
* @param {Preference} preferences The preferences instances.
* @param {Keybindings} keybindings The keybindings instances.
* @param {string} userDataPath The user data path.
*/
constructor (preferences, keybindings, userDataPath) {
this._preferences = preferences
this._keybindings = keybindings
this._userDataPath = userDataPath
this.RECENTS_PATH = path.join(userDataPath, RECENTLY_USED_DOCUMENTS_FILE_NAME)
this.isOsxOrWindows = isOsx || isWindows
this.activeWindowId = -1
this.windowMenus = new Map()
this._listenForIpcMain()
}
/**
* Add the file or directory path to the recently used documents.
*
* @param {string} filePath The file or directory full path.
*/
addRecentlyUsedDocument (filePath) {
const { isOsxOrWindows, RECENTS_PATH } = this
if (isOsxOrWindows) app.addRecentDocument(filePath)
if (isOsx) return
const recentDocuments = this.getRecentlyUsedDocuments()
const index = recentDocuments.indexOf(filePath)
let needSave = index !== 0
if (index > 0) {
recentDocuments.splice(index, 1)
}
if (index !== 0) {
recentDocuments.unshift(filePath)
}
if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {
needSave = true
recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)
}
this.updateAppMenu(recentDocuments)
if (needSave) {
ensureDirSync(this._userDataPath)
const json = JSON.stringify(recentDocuments, null, 2)
fs.writeFileSync(RECENTS_PATH, json, 'utf-8')
}
}
/**
* Returns a list of all recently used documents and folders.
*
* @returns {string[]}
*/
getRecentlyUsedDocuments () {
const { RECENTS_PATH } = this
if (!isFile2(RECENTS_PATH)) {
return []
}
try {
const recentDocuments = JSON.parse(fs.readFileSync(RECENTS_PATH, 'utf-8'))
.filter(f => f && (isFile2(f) || isDirectory2(f)))
if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {
recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)
}
return recentDocuments
} catch (err) {
log.error('Error while read recently used documents:', err)
return []
}
}
/**
* Clear recently used documents.
*/
clearRecentlyUsedDocuments () {
const { isOsxOrWindows, RECENTS_PATH } = this
if (isOsxOrWindows) app.clearRecentDocuments()
if (isOsx) return
const recentDocuments = []
this.updateAppMenu(recentDocuments)
const json = JSON.stringify(recentDocuments, null, 2)
ensureDirSync(this._userDataPath)
fs.writeFileSync(RECENTS_PATH, json, 'utf-8')
}
/**
* Add a default menu to the given window.
*
* @param {number} windowId The window id.
*/
addDefaultMenu (windowId) {
const { windowMenus } = this
const menu = this._buildSettingMenu() // Setting menu is also the fallback menu.
windowMenus.set(windowId, menu)
}
/**
* Add the settings menu to the given window.
*
* @param {BrowserWindow} window The settings browser window.
*/
addSettingMenu (window) {
const { windowMenus } = this
const menu = this._buildSettingMenu()
windowMenus.set(window.id, menu)
}
/**
* Add the editor menu to the given window.
*
* @param {BrowserWindow} window The editor browser window.
* @param {[*]} options The menu options.
*/
addEditorMenu (window, options = {}) {
const isSourceMode = !!options.sourceCodeModeEnabled
const { windowMenus } = this
windowMenus.set(window.id, this._buildEditorMenu(true))
const { menu, shortcutMap } = windowMenus.get(window.id)
// Set source-code editor if preferred.
const sourceCodeModeMenuItem = menu.getMenuItemById('sourceCodeModeMenuItem')
sourceCodeModeMenuItem.checked = isSourceMode
if (isSourceMode) {
const typewriterModeMenuItem = menu.getMenuItemById('typewriterModeMenuItem')
const focusModeMenuItem = menu.getMenuItemById('focusModeMenuItem')
typewriterModeMenuItem.enabled = false
focusModeMenuItem.enabled = false
}
this._keybindings.registerKeyHandlers(window, shortcutMap)
}
/**
* Remove menu from the given window.
*
* @param {number} windowId The window id.
*/
removeWindowMenu (windowId) {
// NOTE: Shortcut handler is automatically unregistered when window is closed.
const { activeWindowId } = this
this.windowMenus.delete(windowId)
if (activeWindowId === windowId) {
this.activeWindowId = -1
}
}
/**
* Returns the window menu.
*
* @param {number} windowId The window id.
* @returns {Electron.Menu} The menu.
*/
getWindowMenuById (windowId) {
const menu = this.windowMenus.get(windowId)
if (!menu) {
log.error(`getWindowMenuById: Cannot find window menu for window id ${windowId}.`)
throw new Error(`Cannot find window menu for id ${windowId}.`)
}
return menu.menu
}
/**
* Check whether the given window has a menu.
*
* @param {number} windowId The window id.
*/
has (windowId) {
return this.windowMenus.has(windowId)
}
/**
* Set the given window as last active.
*
* @param {number} windowId The window id.
*/
setActiveWindow (windowId) {
if (this.activeWindowId !== windowId) {
// Change application menu to the current window menu.
this._setApplicationMenu(this.getWindowMenuById(windowId))
this.activeWindowId = windowId
}
}
/**
* Updates all window menus.
*
* NOTE: We need this method to add or remove menu items at runtime.
*
* @param {[string[]]} recentUsedDocuments
*/
updateAppMenu (recentUsedDocuments) {
if (!recentUsedDocuments) {
recentUsedDocuments = this.getRecentlyUsedDocuments()
}
// "we don't support changing menu object after calling setMenu, the behavior
// is undefined if user does that." That mean we have to recreate the editor
// application menu each time.
// rebuild all window menus
this.windowMenus.forEach((value, key) => {
const { menu: oldMenu, type } = value
if (type !== MenuType.EDITOR) return
const { menu: newMenu } = this._buildEditorMenu(false, recentUsedDocuments)
// all other menu items are set automatically
updateMenuItem(oldMenu, newMenu, 'sourceCodeModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'typewriterModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'focusModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'sideBarMenuItem')
updateMenuItem(oldMenu, newMenu, 'tabBarMenuItem')
// update window menu
value.menu = newMenu
// update application menu if necessary
const { activeWindowId } = this
if (activeWindowId === key) {
this._setApplicationMenu(newMenu)
}
})
}
/**
* Update line ending menu items.
*
* @param {number} windowId The window id.
* @param {string} lineEnding Either >lf< or >crlf<.
*/
updateLineEndingMenu (windowId, lineEnding) {
const menus = this.getWindowMenuById(windowId)
const crlfMenu = menus.getMenuItemById('crlfLineEndingMenuEntry')
const lfMenu = menus.getMenuItemById('lfLineEndingMenuEntry')
if (lineEnding === 'crlf') {
crlfMenu.checked = true
} else {
lfMenu.checked = true
}
}
/**
* Update always on top menu item.
*
* @param {number} windowId The window id.
* @param {boolean} lineEnding Always on top.
*/
updateAlwaysOnTopMenu (windowId, flag) {
const menus = this.getWindowMenuById(windowId)
const menu = menus.getMenuItemById('alwaysOnTopMenuItem')
menu.checked = flag
}
/**
* Update all theme entries from editor menus to the selected one.
*/
updateThemeMenu = theme => {
this.windowMenus.forEach(value => {
const { menu, type } = value
if (type !== MenuType.EDITOR) {
return
}
const themeMenus = menu.getMenuItemById('themeMenu')
if (!themeMenus) {
return
}
themeMenus.submenu.items.forEach(item => (item.checked = false))
themeMenus.submenu.items
.forEach(item => {
if (item.id && item.id === theme) {
item.checked = true
}
})
})
}
/**
* Update all auto save entries from editor menus to the given state.
*/
updateAutoSaveMenu = autoSave => {
this.windowMenus.forEach(value => {
const { menu, type } = value
if (type !== MenuType.EDITOR) {
return
}
const autoSaveMenu = menu.getMenuItemById('autoSaveMenuItem')
if (!autoSaveMenu) {
return
}
autoSaveMenu.checked = autoSave
})
}
/**
* Append misc shortcuts the the given shortcut map.
*
* @param {*} lineEnding The shortcut map.
*/
_appendMiscShortcuts = shortcutMap => {
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.cycle-forward'),
click: (menuItem, win) => {
win.webContents.send('mt::tabs-cycle-right')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.cycle-backward'),
click: (menuItem, win) => {
win.webContents.send('mt::tabs-cycle-left')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-left'),
click: (menuItem, win) => {
win.webContents.send('mt::tabs-cycle-left')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-right'),
click: (menuItem, win) => {
win.webContents.send('mt::tabs-cycle-right')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-first'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-first-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-second'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-second-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-third'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-third-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-fourth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-fourth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-fifth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-fifth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-sixth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-sixth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-seventh'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-seventh-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-eighth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-eighth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-ninth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-ninth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('tabs.switch-to-tenth'),
click: (menuItem, win) => {
win.webContents.send('mt::switch-tenth-tab')
},
id: null
})
shortcutMap.push({
accelerator: this._keybindings.getAccelerator('file.quick-open'),
click: (menuItem, win) => {
win.webContents.send('mt::execute-command-by-id', 'file.quick-open')
},
id: null
})
if (isWindows) {
// WORKAROUND: Window close event isn't triggered on Windows if `setIgnoreMenuShortcuts(true)` is used (Electron#32674).
// NB: Remove this immediately if upstream is fixed because the event may be emitted twice.
shortcutMap.push({
accelerator: 'Alt+F4',
click: (menuItem, win) => {
if (win && !win.isDestroyed()) {
win.close()
}
},
id: null
})
}
}
_buildEditorMenu (createShortcutMap, recentUsedDocuments = null) {
if (!recentUsedDocuments) {
recentUsedDocuments = this.getRecentlyUsedDocuments()
}
const menuTemplate = configureMenu(this._keybindings, this._preferences, recentUsedDocuments)
const menu = Menu.buildFromTemplate(menuTemplate)
let shortcutMap = null
if (createShortcutMap) {
shortcutMap = parseMenu(menuTemplate)
this._appendMiscShortcuts(shortcutMap)
}
return {
shortcutMap,
menu,
type: MenuType.EDITOR
}
}
_buildSettingMenu () {
if (isOsx) {
const menuTemplate = configSettingMenu(this._keybindings)
const menu = Menu.buildFromTemplate(menuTemplate)
return { menu, type: MenuType.SETTINGS }
}
return { menu: null, type: MenuType.SETTINGS }
}
_setApplicationMenu (menu) {
if (isLinux && !menu) {
// WORKAROUND for Electron#16521: We cannot hide the (application) menu on Linux.
const dummyMenu = Menu.buildFromTemplate([])
Menu.setApplicationMenu(dummyMenu)
} else {
Menu.setApplicationMenu(menu)
}
}
_listenForIpcMain () {
ipcMain.on('mt::add-recently-used-document', (e, pathname) => {
this.addRecentlyUsedDocument(pathname)
})
ipcMain.on('mt::update-line-ending-menu', (e, windowId, lineEnding) => {
this.updateLineEndingMenu(windowId, lineEnding)
})
ipcMain.on('mt::update-format-menu', (e, windowId, formats) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateFormatMenu(this.getWindowMenuById(windowId), formats)
})
ipcMain.on('mt::update-sidebar-menu', (e, windowId, value) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateSidebarMenu(this.getWindowMenuById(windowId), value)
})
ipcMain.on('mt::view-layout-changed', (e, windowId, viewSettings) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
viewLayoutChanged(this.getWindowMenuById(windowId), viewSettings)
})
ipcMain.on('mt::editor-selection-changed', (e, windowId, changes) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateSelectionMenus(this.getWindowMenuById(windowId), changes)
})
ipcMain.on('menu-add-recently-used', pathname => {
this.addRecentlyUsedDocument(pathname)
})
ipcMain.on('menu-clear-recently-used', () => {
this.clearRecentlyUsedDocuments()
})
ipcMain.on('broadcast-preferences-changed', prefs => {
if (prefs.theme !== undefined) {
this.updateThemeMenu(prefs.theme)
}
if (prefs.autoSave !== undefined) {
this.updateAutoSaveMenu(prefs.autoSave)
}
})
}
}
const updateMenuItem = (oldMenus, newMenus, id) => {
const oldItem = oldMenus.getMenuItemById(id)
const newItem = newMenus.getMenuItemById(id)
newItem.checked = oldItem.checked
}
// ----------------------------------------------
// HACKY: We have one application menu per window and switch the menu when
// switching windows, so we can access and change the menu items via Electron.
/**
* Return the menu from the application menu.
*
* @param {string} menuId Menu ID
* @returns {Electron.Menu} Returns the menu or null.
*/
export const getMenuItemById = menuId => {
const menus = Menu.getApplicationMenu()
return menus.getMenuItemById(menuId)
}
export default AppMenu