-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathapp.ts
323 lines (273 loc) · 10.2 KB
/
app.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
// node imports
import * as pathlib from "path";
// electron imports
import { app, ipcMain, IpcMainInvokeEvent } from "electron";
import { enforceMacOSAppLocation } from 'electron-util';
import { EventEmitter } from "events";
// project imports
import MainWindow from "./windows/main";
import Window from "./windows/window";
import {
MainIpc_FileHandlers, MainIpc_TagHandlers, MainIpc_DialogHandlers,
MainIpc_LifecycleHandlers, MainIpc_ThemeHandlers, MainIpc_ShellHandlers,
MainIpcHandlers, MainIpcChannel, MainIpc_OutlineHandlers,
MainIpc_MetadataHandlers,
MainIpc_NavigationHandlers,
MainIpc_CitationHandlers,
MainIpcChannelName
} from "./MainIPC";
import { FSAL } from "./fsal/fsal";
import { invokerFor, FunctionPropertyNames } from "@common/ipc";
import { IDirEntryMeta } from "@common/files";
import { AppEvents, IpcEvents } from "@common/events";
import { RendererIpcHandlers } from "@renderer/RendererIPC";
import { WorkspaceService, WorkspaceEvent } from "./workspace/workspace-service";
import { ThemeService, ThemeEvent } from "./theme/theme-service";
import { PluginService } from "./plugins/plugin-service";
import NewFileWindow from "./windows/newFileWindow";
////////////////////////////////////////////////////////////
export default class NoteworthyApp extends EventEmitter {
window: Window | undefined;
/** proxy for SENDING events to the render process */
_renderProxy: null | RendererIpcHandlers;
/** handlers for events RECEIVED from the render process */
_eventHandlers: MainIpcHandlers;
constructor(
/** file system abstraction layer */
private _fsal: FSAL,
private _workspaceService:WorkspaceService,
private _pluginService:PluginService,
private _themeService:ThemeService
){
super();
this._renderProxy = null;
// bind event handlers
this._eventHandlers = this.makeHandlers();
this.handleFileTreeChanged = this.handleFileTreeChanged.bind(this);
this.handleThemeChanged = this.handleThemeChanged.bind(this);
this.init();
this.attachEvents();
}
// INITIALIZATION //////////////////////////////////////
init(){
ipcMain.handle(
"command",
<C extends MainIpcChannelName>(
evt: IpcMainInvokeEvent, channel: C,
key: FunctionPropertyNames<MainIpcHandlers[C]>, data: any
) => {
console.log(`MainIPC :: handling event :: ${channel} ${key}`);
return this.handle(channel, key, data);
}
);
}
/** @todo (9/13/20) re-visit ipc dependency injection
*
* Here, we perform a kind of manual dependency injection.
*
* In a larger codebase, a dependency injection framework
* might be appropriate, but our dependence structure is
* simple enough for us to manage dependencies manually.
*/
makeHandlers(): MainIpcHandlers {
// handlers with no dependencies
let lifecycleHandlers = new MainIpc_LifecycleHandlers(this);
let shellHandlers = new MainIpc_ShellHandlers();
// handlers with a single dependency
let fileHandlers = new MainIpc_FileHandlers(this, this._fsal, this._workspaceService);
let tagHandlers = new MainIpc_TagHandlers(this, this._workspaceService, this._pluginService);
let navigationHandlers = new MainIpc_NavigationHandlers(this, this._workspaceService, this._pluginService);
let dialogHandlers = new MainIpc_DialogHandlers(this, this._fsal, this._workspaceService);
let outlineHandlers = new MainIpc_OutlineHandlers(this._pluginService);
let themeHandlers = new MainIpc_ThemeHandlers(this._themeService);
let metadataHandlers = new MainIpc_MetadataHandlers(this._pluginService);
let citationHandlers = new MainIpc_CitationHandlers(this, this._pluginService);
return {
lifecycle: lifecycleHandlers,
file: fileHandlers,
theme: themeHandlers,
shell: shellHandlers,
dialog: dialogHandlers,
tag: tagHandlers,
outline: outlineHandlers,
metadata: metadataHandlers,
navigation: navigationHandlers,
citations: citationHandlers
}
}
// == Quitting ====================================== //
/**
* Perform all steps needed to shut down the application.
* @caution Actually shuts down! Doesn't ask about unsaved changes!)
*/
quit(){
// announce globally that we're actually quitting!
global.isQuitting = true;
// clean up
/** @todo (9/13/20) these are global services,
* is it actually appropriate to destroy them here?
*/
this.detach__beforeQuit();
this._workspaceService.closeWorkspace()
this._fsal.close();
app.quit();
}
load(){
if(this.window){
/** @todo handle window exists? */
}
console.log("app :: load")
this.window = new MainWindow("main", this);
this.window.init();
this._renderProxy = invokerFor<RendererIpcHandlers>(
this.window, // object to proxy
IpcEvents.RENDERER_INVOKE, // channel
"main->render" // log prefix
);
}
// == File Types ==================================== //
/**
* @returns a string representing the default contents
* of a file with the given extension and name.
* @param fileExt A string like ".md", ".txt", etc.
* @param fileName `fileExt` will be stripped from name, if present.
*/
getDefaultFileContents(fileExt:string, fileName:string):string {
/** @todo (6/27/20) don't use file ext to determine file type
* (user should be able to e.g. specify a different editor type
* than the default for .md files)
*/
/** @todo (9/14/20) this function does not belong in NoteworthyApp */
if(fileExt == ".md" || fileExt == ".txt"){
let name = pathlib.basename(fileName, fileExt);
return `# ${name}`;
} else {
return "";
}
}
// EVENTS //////////////////////////////////////////////
/** @todo (9/13/20) ideally we would write something like this:
*
* async handle<S extends MainIpcChannel, T extends MainIpcEvents[S]>
*
* where MainIpcEvents is a mapped type
*
* export type MainIpcEvents = {
* [K in (keyof MainIpcHandlers)] : FunctionPropertyNames<MainIpcHandlers[K]>
* }
*
* this would let us modify the notion of "what constitutes an event name"
* without having to manually update the signature of handle().
*
* However, this won't typecheck! We need correlated record types yet again!!!
*/
async handle<C extends MainIpcChannelName, T extends FunctionPropertyNames<MainIpcHandlers[C]>>(
channel: C,
name: T,
/** @todo now we only take the FIRST parameter of each handler -- should we take them all? */
data?: Parameters<MainIpcHandlers[C][T]>[0]
) {
/** @remark (6/25/20) cannot properly type-check this call
* without support for "correlated record types", see e.g.
* (https://github.com/Microsoft/TypeScript/issues/30581)
*/
return this._eventHandlers[channel][name](data as any);
}
async handleFileTreeChanged(fileTree: IDirEntryMeta[]): Promise<void> {
await this._renderProxy?.fileTreeChanged(fileTree);
}
async handleThemeChanged(cssString:string): Promise<void> {
await this._renderProxy?.applyThemeCss(cssString);
}
attachEvents(){
this.attachWindowEvents();
/** @todo (9/13/20) type-checked workspace events */
this._workspaceService.on(WorkspaceEvent.FILETREE_CHANGED, this.handleFileTreeChanged );
this._themeService.on(ThemeEvent.THEME_CHANGED, this.handleThemeChanged);
}
detachEvents(){
this._workspaceService.off(WorkspaceEvent.FILETREE_CHANGED, this.handleFileTreeChanged);
this._themeService.off(ThemeEvent.THEME_CHANGED, this.handleThemeChanged);
this.detachWindowEvents();
}
// Attach / Detach Events ------------------------------
/** @todo (6/28/20) all this window boilerplate should be somewhere else */
attachWindowEvents() {
this.attach__windowAllClosed();
this.attach__activate();
this.attach__beforeQuit();
this.attach__forceQuit();
this.attach__ready();
this.attach__cwdChanged();
this.attach__updaterCheck();
}
detachWindowEvents() {
/** @todo (6/28/20) any need to detach window events? */
}
attach__windowAllClosed = () =>
{ app.on("window-all-closed", this.__windowAllClosed); }
attach__activate = () =>
{ app.on("activate", this.__activate); }
attach__beforeQuit = () =>
{ app.on("before-quit", this.__beforeQuit); }
detach__beforeQuit = () =>
{ app.removeListener("before-quit", this.__beforeQuit); }
attach__forceQuit = () =>
{ ipcMain.on("force-quit", this.__forceQuit); }
attach__ready = () =>
{ app.on("ready", this.__ready); }
attach__cwdChanged = () =>
{ ipcMain.on("cwd-changed", this.__cwdChanged); }
attach__updaterCheck = () =>
{ ipcMain.on("updater-check", this.__updaterCheck); }
// Event Handlers --------------------------------------
__windowAllClosed = () => {
console.log("app :: __windowAllClosed");
/** @todo (9/13/20) why is this here? */
//if(is.macos){ return this.initMenu(); };
this.quit();
}
__activate = () => {
console.log("app :: __activate");
if(this.window && this.window.window) return;
this.load();
}
__beforeQuit = () => {
console.log("app :: __beforeQuit")
if (!this.window || !this.window.window) { return; }
// TODO: this line comes from Notable, but it seems to
// prevent the application from actually closing. Why was it here?
//event.preventDefault();
this.window.window.webContents.send(AppEvents.APP_QUIT)
}
__forceQuit = () => {
console.log("app :: __forceQuit")
this.quit();
}
__ready = () => {
enforceMacOSAppLocation();
this.load();
}
__cwdChanged = () => {
if(this.window && this.window.window){
this.window.window.once("closed", this.load.bind(this));
this.window.window.close();
} else {
this.load();
}
}
__updaterCheck = () => {
/** @todo (7/12/20) automatic updates */
// updater.removeAllListeners();
// if (notifications === true) {
// updater.on('update-available', () => Notification.show('A new update is available', 'Downloading it right now...'));
// updater.on('update-not-available', () => Notification.show('No update is available', 'You\'re already using the latest version'));
// updater.on('error', err => {
// Notification.show('An error occurred', err.message);
// Notification.show('Update manually', 'Download the new version manually to update the app');
// shell.openExternal(pkg['download'].url);
// });
// }
// updater.checkForUpdatesAndNotify();
}
}