forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindowManager.js
More file actions
462 lines (406 loc) · 12.5 KB
/
Copy pathwindowManager.js
File metadata and controls
462 lines (406 loc) · 12.5 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
import { app, BrowserWindow, ipcMain } from 'electron'
import EventEmitter from 'events'
import log from 'electron-log'
import Watcher, { WATCHER_STABILITY_THRESHOLD, WATCHER_STABILITY_POLL_INTERVAL } from '../filesystem/watcher'
import { WindowType } from '../windows/base'
class WindowActivityList {
constructor () {
// Oldest Newest
// <number>, ... , <number>
this._buf = []
}
getNewest () {
const { _buf } = this
if (_buf.length) {
return _buf[_buf.length - 1]
}
return null
}
getSecondNewest () {
const { _buf } = this
if (_buf.length >= 2) {
return _buf[_buf.length - 2]
}
return null
}
setNewest (id) {
// I think we do not need a linked list for only a few windows.
const { _buf } = this
const index = _buf.indexOf(id)
if (index !== -1) {
const lastIndex = _buf.length - 1
if (index === lastIndex) {
return
}
_buf.splice(index, 1)
}
_buf.push(id)
}
delete (id) {
const { _buf } = this
const index = _buf.indexOf(id)
if (index !== -1) {
_buf.splice(index, 1)
}
}
}
class WindowManager extends EventEmitter {
/**
*
* @param {AppMenu} appMenu The application menu instance.
* @param {Preference} preferences The preference instance.
*/
constructor (appMenu, preferences) {
super()
this._appMenu = appMenu
this._activeWindowId = null
this._windows = new Map()
this._windowActivity = new WindowActivityList()
// TODO(need::refactor): Please see #1035.
this._watcher = new Watcher(preferences)
this._listenForIpcMain()
}
/**
* Add the given window to the window list.
*
* @param {IApplicationWindow} window The application window. We take ownership!
*/
add (window) {
const { id: windowId } = window
this._windows.set(windowId, window)
if (!this._appMenu.has(windowId)) {
this._appMenu.addDefaultMenu(windowId)
}
if (this.windowCount === 1) {
this.setActiveWindow(windowId)
}
window.on('window-focus', () => {
this.setActiveWindow(windowId)
})
window.on('window-closed', () => {
this.remove(windowId)
this._watcher.unwatchByWindowId(windowId)
})
}
/**
* Return the application window by id.
*
* @param {string} windowId The window id.
* @returns {BaseWindow} The application window or undefined.
*/
get (windowId) {
return this._windows.get(windowId)
}
/**
* Return the BrowserWindow by id.
*
* @param {string} windowId The window id.
* @returns {Electron.BrowserWindow} The window or undefined.
*/
getBrowserWindow (windowId) {
const window = this.get(windowId)
if (window) {
return window.browserWindow
}
return undefined
}
/**
* Remove the given window by id.
*
* NOTE: All window "window-focus" events listeners are removed!
*
* @param {string} windowId The window id.
* @returns {IApplicationWindow} Returns the application window. We no longer take ownership.
*/
remove (windowId) {
const { _windows } = this
const window = this.get(windowId)
if (window) {
window.removeAllListeners('window-focus')
this._windowActivity.delete(windowId)
const nextWindowId = this._windowActivity.getNewest()
this.setActiveWindow(nextWindowId)
_windows.delete(windowId)
}
return window
}
setActiveWindow (windowId) {
if (this._activeWindowId !== windowId) {
this._activeWindowId = windowId
this._windowActivity.setNewest(windowId)
if (windowId != null) {
// windowId is null when all windows are closed (e.g. when gracefully closed).
this._appMenu.setActiveWindow(windowId)
}
this.emit('activeWindowChanged', windowId)
}
}
/**
* Returns the active window or null if no window is registered.
* @returns {BaseWindow|undefined}
*/
getActiveWindow () {
return this._windows.get(this._activeWindowId)
}
/**
* Returns the active window id or null if no window is registered.
* @returns {number|null}
*/
getActiveWindowId () {
return this._activeWindowId
}
/**
* Returns the (last) active editor window or null if no editor is registered.
* @returns {EditorWindow|undefined}
*/
getActiveEditor () {
let win = this.getActiveWindow()
if (win && win.type !== WindowType.EDITOR) {
win = this._windows.get(this._windowActivity.getSecondNewest())
if (win && win.type === WindowType.EDITOR) {
return win
}
return undefined
}
return win
}
/**
* Returns the (last) active editor window id or null if no editor is registered.
* @returns {number|null}
*/
getActiveEditorId () {
const win = this.getActiveEditor()
return win ? win.id : null
}
/**
*
* @param {WindowType} type the WindowType one of ['base', 'editor', 'settings']
* @returns {{id: number, win: BaseWindow}[]} Return the windows of the given {type}
*/
getWindowsByType (type) {
if (!WindowType[type.toUpperCase()]) {
console.error(`"${type}" is not a valid window type.`)
}
const { windows } = this
const result = []
for (var [key, value] of windows) {
if (value.type === type) {
result.push({
id: key,
win: value
})
}
}
return result
}
/**
* Find the best window to open the files in.
*
* @param {string[]} fileList File full paths.
* @returns {{windowId: string, fileList: string[]}[]} An array of files mapped to a window id or null to open in a new window.
*/
findBestWindowToOpenIn (fileList) {
if (!fileList || !Array.isArray(fileList) || !fileList.length) return []
const { windows } = this
const lastActiveEditorId = this.getActiveEditorId() // editor id or null
if (this.windowCount <= 1) {
return [{ windowId: lastActiveEditorId, fileList }]
}
// Array of scores, same order like fileList.
let filePathScores = null
for (const window of windows.values()) {
if (window.type === WindowType.EDITOR) {
const scores = window.getCandidateScores(fileList)
if (!filePathScores) {
filePathScores = scores
} else {
const len = filePathScores.length
for (let i = 0; i < len; ++i) {
// Update score only if the file is not already opened.
if (filePathScores[i].score !== -1 && filePathScores[i].score < scores[i].score) {
filePathScores[i] = scores[i]
}
}
}
}
}
const buf = []
const len = filePathScores.length
for (let i = 0; i < len; ++i) {
let { id: windowId, score } = filePathScores[i]
if (score === -1) {
// Skip files that already opened.
continue
} else if (score === 0) {
// There is no best window to open the file(s) in.
windowId = lastActiveEditorId
}
let item = buf.find(w => w.windowId === windowId)
if (!item) {
item = { windowId, fileList: [] }
buf.push(item)
}
item.fileList.push(fileList[i])
}
return buf
}
get windows () {
return this._windows
}
get windowCount () {
return this._windows.size
}
// --- helper ---------------------------------
closeWatcher () {
this._watcher.close()
}
/**
* Closes the browser window and associated application window without asking to save documents.
*
* @param {Electron.BrowserWindow} browserWindow The browser window.
*/
forceClose (browserWindow) {
if (!browserWindow) {
return false
}
const { id: windowId } = browserWindow
const { _appMenu, _windows } = this
// Free watchers used by this window
this._watcher.unwatchByWindowId(windowId)
// Application clearup and remove listeners
_appMenu.removeWindowMenu(windowId)
const window = this.remove(windowId)
// Destroy window wrapper and browser window
if (window) {
window.destroy()
} else {
log.error('Something went wrong: Cannot find associated application window!')
browserWindow.destroy()
}
// Quit application on macOS if not windows are opened.
if (_windows.size === 0) {
app.quit()
}
return true
}
/**
* Closes the application window and associated browser window without asking to save documents.
*
* @param {number} windowId The application window or browser window id.
*/
forceCloseById (windowId) {
const browserWindow = this.getBrowserWindow(windowId)
if (browserWindow) {
return this.forceClose(browserWindow)
}
return false
}
// --- private --------------------------------
_listenForIpcMain () {
// HACK: Don't use this event! Please see #1034 and #1035
ipcMain.on('mt::window-add-file-path', (e, filePath) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (!editor) {
log.error(`Cannot find window id "${win.id}" to add opened file.`)
return
}
editor.addToOpenedFiles(filePath)
})
// Force close a BrowserWindow
ipcMain.on('mt::close-window', e => {
const win = BrowserWindow.fromWebContents(e.sender)
this.forceClose(win)
})
ipcMain.on('mt::open-file', (e, filePath, options) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (!editor) {
log.error(`Cannot find window id "${win.id}" to open file.`)
return
}
editor.openTab(filePath, options, true)
})
ipcMain.on('mt::window-tab-closed', (e, pathname) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (editor) {
editor.removeFromOpenedFiles(pathname)
}
})
ipcMain.on('mt::window-toggle-always-on-top', e => {
const win = BrowserWindow.fromWebContents(e.sender)
const flag = !win.isAlwaysOnTop()
win.setAlwaysOnTop(flag)
this._appMenu.updateAlwaysOnTopMenu(win.id, flag)
})
// --- local events ---------------
ipcMain.on('watcher-unwatch-all-by-id', windowId => {
this._watcher.unwatchByWindowId(windowId)
})
ipcMain.on('watcher-watch-file', (win, filePath) => {
this._watcher.watch(win, filePath, 'file')
})
ipcMain.on('watcher-watch-directory', (win, pathname) => {
this._watcher.watch(win, pathname, 'dir')
})
ipcMain.on('watcher-unwatch-file', (win, filePath) => {
this._watcher.unwatch(win, filePath, 'file')
})
ipcMain.on('watcher-unwatch-directory', (win, pathname) => {
this._watcher.unwatch(win, pathname, 'dir')
})
ipcMain.on('window-add-file-path', (windowId, filePath) => {
const editor = this.get(windowId)
if (!editor) {
log.error(`Cannot find window id "${windowId}" to add opened file.`)
return
}
editor.addToOpenedFiles(filePath)
})
ipcMain.on('window-change-file-path', (windowId, pathname, oldPathname) => {
const editor = this.get(windowId)
if (!editor) {
log.error(`Cannot find window id "${windowId}" to change file path.`)
return
}
editor.changeOpenedFilePath(pathname, oldPathname)
})
ipcMain.on('window-file-saved', (windowId, pathname) => {
// A changed event is emitted earliest after the stability threshold.
const duration = WATCHER_STABILITY_THRESHOLD + (WATCHER_STABILITY_POLL_INTERVAL * 2)
this._watcher.ignoreChangedEvent(windowId, pathname, duration)
})
ipcMain.on('window-close-by-id', id => {
this.forceCloseById(id)
})
ipcMain.on('window-reload-by-id', id => {
const window = this.get(id)
if (window) {
window.reload()
}
})
ipcMain.on('window-toggle-always-on-top', win => {
const flag = !win.isAlwaysOnTop()
win.setAlwaysOnTop(flag)
this._appMenu.updateAlwaysOnTopMenu(win.id, flag)
})
ipcMain.on('broadcast-preferences-changed', prefs => {
// We can not dynamic change the title bar style, so do not need to send it to renderer.
if (typeof prefs.titleBarStyle !== 'undefined') {
delete prefs.titleBarStyle
}
if (Object.keys(prefs).length > 0) {
for (const { browserWindow } of this._windows.values()) {
browserWindow.webContents.send('mt::user-preference', prefs)
}
}
})
ipcMain.on('broadcast-user-data-changed', userData => {
for (const { browserWindow } of this._windows.values()) {
browserWindow.webContents.send('mt::user-preference', userData)
}
})
}
}
export default WindowManager