-
Notifications
You must be signed in to change notification settings - Fork 365
/
Copy pathMenubar.ts
326 lines (280 loc) · 8.94 KB
/
Menubar.ts
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
import { EventEmitter } from 'events';
import fs from 'fs';
import path from 'path';
import { BrowserWindow, Tray } from 'electron';
import Positioner from 'electron-positioner';
import type { Options } from './types';
import { cleanOptions } from './util/cleanOptions';
import { getWindowPosition } from './util/getWindowPosition';
/**
* The main Menubar class.
*
* @noInheritDoc
*/
export class Menubar extends EventEmitter {
private _app: Electron.App;
private _browserWindow?: BrowserWindow;
private _blurTimeout: NodeJS.Timeout | null = null; // track blur events with timeout
private _isVisible: boolean; // track visibility
private _cachedBounds?: Electron.Rectangle; // _cachedBounds are needed for double-clicked event
private _options: Options;
private _positioner: Positioner | undefined;
private _tray?: Tray;
constructor(app: Electron.App, options?: Partial<Options>) {
super();
this._app = app;
this._options = cleanOptions(options);
this._isVisible = false;
if (app.isReady()) {
// See https://github.com/maxogden/menubar/pull/151
process.nextTick(() =>
this.appReady().catch((err) => console.error('menubar: ', err)),
);
} else {
app.on('ready', () => {
this.appReady().catch((err) => console.error('menubar: ', err));
});
}
}
/**
* The Electron [App](https://electronjs.org/docs/api/app)
* instance.
*/
get app(): Electron.App {
return this._app;
}
/**
* The [electron-positioner](https://github.com/jenslind/electron-positioner)
* instance.
*/
get positioner(): Positioner {
if (!this._positioner) {
throw new Error(
'Please access `this.positioner` after the `after-create-window` event has fired.',
);
}
return this._positioner;
}
/**
* The Electron [Tray](https://electronjs.org/docs/api/tray) instance.
*/
get tray(): Tray {
if (!this._tray) {
throw new Error(
'Please access `this.tray` after the `ready` event has fired.',
);
}
return this._tray;
}
/**
* The Electron [BrowserWindow](https://electronjs.org/docs/api/browser-window)
* instance, if it's present.
*/
get window(): BrowserWindow | undefined {
return this._browserWindow;
}
/**
* Retrieve a menubar option.
*
* @param key - The option key to retrieve, see {@link Options}.
*/
getOption<K extends keyof Options>(key: K): Options[K] {
return this._options[key];
}
/**
* Hide the menubar window.
*/
hideWindow(): void {
if (!this._browserWindow || !this._isVisible) {
return;
}
this.emit('hide');
this._browserWindow.hide();
this.emit('after-hide');
this._isVisible = false;
if (this._blurTimeout) {
clearTimeout(this._blurTimeout);
this._blurTimeout = null;
}
}
/**
* Change an option after menubar is created.
*
* @param key - The option key to modify, see {@link Options}.
* @param value - The value to set.
*/
setOption<K extends keyof Options>(key: K, value: Options[K]): void {
this._options[key] = value;
}
/**
* Show the menubar window.
*
* @param trayPos - The bounds to show the window in.
*/
async showWindow(trayPos?: Electron.Rectangle): Promise<void> {
if (!this.tray) {
throw new Error('Tray should have been instantiated by now');
}
if (!this._browserWindow) {
await this.createWindow();
}
// Use guard for TypeScript, to avoid ! everywhere
if (!this._browserWindow) {
throw new Error('Window has been initialized just above. qed.');
}
// 'Windows' taskbar: sync windows position each time before showing
// https://github.com/maxogden/menubar/issues/232
if (['win32', 'linux'].includes(process.platform)) {
// Fill in this._options.windowPosition when taskbar position is available
this._options.windowPosition = getWindowPosition(this.tray);
}
this.emit('show');
if (trayPos && trayPos.x !== 0) {
// Cache the bounds
this._cachedBounds = trayPos;
} else if (this._cachedBounds) {
// Cached value will be used if showWindow is called without bounds data
trayPos = this._cachedBounds;
} else if (this.tray.getBounds) {
// Get the current tray bounds
trayPos = this.tray.getBounds();
}
// Default the window to the right if `trayPos` bounds are undefined or null.
let noBoundsPosition = undefined;
if (
(trayPos === undefined || trayPos.x === 0) &&
this._options.windowPosition &&
this._options.windowPosition.startsWith('tray')
) {
noBoundsPosition =
process.platform === 'win32' ? 'bottomRight' : 'topRight';
}
const position = this.positioner.calculate(
this._options.windowPosition || noBoundsPosition,
trayPos,
) as { x: number; y: number };
// Not using `||` because x and y can be zero.
const x =
this._options.browserWindow.x !== undefined
? this._options.browserWindow.x
: position.x;
const y =
this._options.browserWindow.y !== undefined
? this._options.browserWindow.y
: position.y;
// `.setPosition` crashed on non-integers
// https://github.com/maxogden/menubar/issues/233
this._browserWindow.setPosition(Math.round(x), Math.round(y));
this._browserWindow.show();
this._isVisible = true;
this.emit('after-show');
return;
}
private async appReady(): Promise<void> {
if (this.app.dock && !this._options.showDockIcon) {
this.app.dock.hide();
}
if (this._options.activateWithApp) {
this.app.on('activate', (_event, hasVisibleWindows) => {
if (!hasVisibleWindows) {
this.showWindow().catch(console.error);
}
});
}
let trayImage =
this._options.icon || path.join(this._options.dir, 'IconTemplate.png');
if (typeof trayImage === 'string' && !fs.existsSync(trayImage)) {
trayImage = path.join(__dirname, '..', 'assets', 'IconTemplate.png'); // Default cat icon
}
const defaultClickEvent = this._options.showOnRightClick
? 'right-click'
: 'click';
this._tray = this._options.tray || new Tray(trayImage);
// Type guards for TS not to complain
if (!this.tray) {
throw new Error('Tray has been initialized above');
}
this.tray.on(
defaultClickEvent as Parameters<Tray['on']>[0],
this.clicked.bind(this),
);
this.tray.on('double-click', this.clicked.bind(this));
this.tray.setToolTip(this._options.tooltip);
if (!this._options.windowPosition) {
this._options.windowPosition = getWindowPosition(this.tray);
}
if (this._options.preloadWindow) {
await this.createWindow();
}
this.emit('ready');
}
/**
* Callback on tray icon click or double-click.
*
* @param e
* @param bounds
*/
private async clicked(
event?: Electron.KeyboardEvent,
bounds?: Electron.Rectangle,
): Promise<void> {
if (event && (event.shiftKey || event.ctrlKey || event.metaKey)) {
return this.hideWindow();
}
// if blur was invoked clear timeout
if (this._blurTimeout) {
clearInterval(this._blurTimeout);
}
if (this._browserWindow && this._isVisible) {
return this.hideWindow();
}
this._cachedBounds = bounds || this._cachedBounds;
await this.showWindow(this._cachedBounds);
}
private async createWindow(): Promise<void> {
this.emit('create-window');
// We add some default behavior for menubar's browserWindow, to make it
// look like a menubar
const defaults = {
show: false, // Don't show it at first
frame: false, // Remove window frame
};
this._browserWindow = new BrowserWindow({
...defaults,
...this._options.browserWindow,
});
this._positioner = new Positioner(this._browserWindow);
this._browserWindow.on('blur', () => {
if (!this._browserWindow) {
return;
}
// hack to close if icon clicked when open
this._browserWindow.isAlwaysOnTop()
? this.emit('focus-lost')
: (this._blurTimeout = setTimeout(() => {
this.hideWindow();
}, 100));
});
if (this._options.showOnAllWorkspaces !== false) {
// https://github.com/electron/electron/issues/37832#issuecomment-1497882944
this._browserWindow.setVisibleOnAllWorkspaces(true, {
skipTransformProcessType: true, // Avoid damaging the original visible state of app.dock
});
}
this._browserWindow.on('close', this.windowClear.bind(this));
this.emit('before-load');
// If the user explicity set options.index to false, we don't loadURL
// https://github.com/maxogden/menubar/issues/255
if (this._options.index !== false) {
await this._browserWindow.loadURL(
this._options.index,
this._options.loadUrlOptions,
);
}
this.emit('after-create-window');
}
private windowClear(): void {
this._browserWindow = undefined;
this.emit('after-close');
}
}