-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
249 lines (217 loc) · 7.38 KB
/
main.js
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
const path = require("path");
const { app, BrowserWindow, ipcMain } = require("electron");
/**
* Block the current process's execution for the given number of milliseconds
* WARNING: THIS FUNCTION IS VERY VERY BAD PRACTICE AND SHOULD NEVER BE USED IN PRODUCTION CODE
* @param {number} ms number of milliseconds during which to block the process
*/
function blockProcess(ms) {
ms += new Date().getTime();
while (new Date() < ms) {}
}
/**
* Block the current process's execution for the given number of milliseconds
* WARNING: THIS FUNCTION IS VERY VERY BAD PRACTICE AND SHOULD NEVER BE USED IN PRODUCTION CODE
* @param {number} ms number of milliseconds during which to block the process
*/
function blockProcessAsync(ms) {
return new Promise((resolve) => {
blockProcess(ms);
resolve();
});
}
/** ELECTRON SETUP */
const versionArg = process.argv.find((argv) =>
argv.startsWith("--dotnetversion=")
);
const version = versionArg?.replace("--dotnetversion=", "") || "";
// Keep a global reference of the window object. If you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1052,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
mainWindow.maximize();
// and load the index.html of the app.
mainWindow.loadURL(
`file://${__dirname}/index.html?version=${version}&electron-version=${process.versions.electron}`
);
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// Quit when all windows are closed.
app.on("window-all-closed", function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
//if (process.platform !== 'darwin') {
app.quit();
//}
});
/** EDGE SETUP */
const namespace =
"QuickStart." + version.charAt(0).toUpperCase() + version.substr(1);
const baseNetAppPath = path.join(
__dirname,
"/src/" + namespace + "/bin/Debug/net7.0"
);
process.env.EDGE_USE_CORECLR = 1;
if (version !== "standard") process.env.EDGE_APP_ROOT = baseNetAppPath;
const edge = require("electron-edge-js");
const baseDll = path.join(baseNetAppPath, namespace + ".dll");
/** Map of generated and wrapped edge functions to call on invoking edge functions */
const edgeFuncs = new Map([
[
`${namespace}.LocalMethods.LongAsyncElectronMethod`,
async () => {
console.log("LongAsyncElectronMethod Start!");
await new Promise((resolve) => {
setTimeout(() => resolve(), 2000);
});
console.log("LongAsyncElectronMethod Done Delaying!");
return "LongAsyncElectronMethod finished";
},
],
[
`${namespace}.LocalMethods.LongBlockingElectronMethod`,
async () => {
console.log("LongBlockingElectronMethod Start!");
blockProcessAsync(2000);
console.log("LongBlockingElectronMethod Done Sleeping!");
return "LongBlockingElectronMethod finished";
},
],
[
`${namespace}.LocalMethods.ShortAsynchronousElectronMethod`,
async () => {
console.log("ShortAsynchronousElectronMethod called!");
return "ShortAsynchronousElectronMethod finished";
},
],
[
`${namespace}.LocalMethods.ShortSynchronousElectronMethod`,
() => {
console.log("ShortSynchronousElectronMethod called!");
return "ShortSynchronousElectronMethod finished";
},
],
]);
/**
* Creates an edge function that asynchronously calls C# and returns a promise
* @param {string} ns namespace for edge function
* @param {string} className class name for edge function
* @param {string} method method name for edge function
* @returns promise that resolves with the results of the edge function call and rejects on exceptions
*/
function createEdgeFunc(ns, className, method) {
const methodForceSynced = method.endsWith("Synced");
// Load up an edge function with the specs provided
const edgeFunc = edge.func({
assemblyFile: baseDll,
typeName: `${ns}.${className}`,
methodName: methodForceSynced ? method.replace("Synced", "") : method,
});
// Wrap the edge function in a promise function
return (args) => {
if (methodForceSynced) return edgeFunc(args, true);
return new Promise((resolve, reject) => {
try {
edgeFunc(args, (error, result) => {
if (error) {
console.error(
"Error in callback! Under what conditions does this occur?",
error
);
reject(error);
}
resolve(result);
});
} catch (e) {
// C# exceptions are caught here
reject(e);
}
});
};
}
/**
* Invokes an edge method
* @param {string} classMethod Class name and method to call in dot notation like ClassName.Method
* @param {any} args arguments to pass into the method
* @returns Promise that resolves with the return from the called method
*/
async function invoke(classMethod, args) {
if (!classMethod) throw Error("No method provided");
const addressParts = classMethod.split(".", 3);
if (addressParts.length < 2)
throw Error("Must provide class and method like Class.Method");
// Namespace has a default, but the classMethod can provide one if desired
let ns = namespace;
let className = "";
let method = "";
// Namespace provided
if (addressParts.length === 3) {
[ns, className, method] = addressParts;
} else {
[className, method] = addressParts;
}
// fully specified namespace, class, and method
const fullClassMethod = `${ns}.${className}.${method}`;
// See if we can find an existing edgefunc for this Namespace.Class.Method
let edgeFunc = edgeFuncs.get(fullClassMethod);
if (!edgeFunc) {
// Didn't find an edgeFunc, so create one
edgeFunc = createEdgeFunc(ns, className, method);
edgeFuncs.set(fullClassMethod, edgeFunc);
}
if (
method === "ShortAsynchronousMethod" ||
method === "ShortAsynchronousElectronMethod" ||
method === "LongAsyncMethod" ||
method === "LongAsyncElectronMethod" ||
method === "LongBlockingMethod" ||
method === "LongBlockingElectronMethod"
) {
console.log(`---\n${method} about to invoke`);
const edgeFuncPromise = edgeFunc(args).then((result) => {
console.log(`${method} finished and promise resolved`);
return result;
});
console.log(`${method} invoking finished`);
return edgeFuncPromise;
}
return edgeFunc(args);
}
/** IPC HANDLING SETUP */
/** Map from ipc channel to handler function */
const ipcHandlers = {
"electronAPI.edge.invoke": (event, classMethod, args) =>
invoke(classMethod, args),
};
//app.enableSandbox();
app
.whenReady()
.then(() => {
// Set up ipc handlers
Object.keys(ipcHandlers).forEach((ipcHandle) =>
ipcMain.handle(ipcHandle, ipcHandlers[ipcHandle])
);
createWindow();
app.on("activate", () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createWindow();
});
})
.catch(console.log);