forked from stratisproject/CirrusCore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
325 lines (273 loc) · 8.56 KB
/
main.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
import { app, BrowserWindow, ipcMain, Menu, nativeImage, Tray, screen } from 'electron';
import * as path from 'path';
import * as url from 'url';
import * as os from 'os';
// Initialize remote module
require('@electron/remote/main').initialize();
if (os.arch() === 'arm') {
app.disableHardwareAcceleration();
}
var daemonName = 'Stratis.CirrusD';
var applicationName = 'Cirrus Core';
const args = process.argv.slice(1);
const serve = args.some(val => val === '--serve' || val === '-serve');
const testnet = args.some(val => val === '--testnet' || val === '-testnet');
const devmode = args.some(val => val === '--devmode' || val === '-devmode');
if (devmode) {
daemonName = 'Stratis.CirrusMinerD';
applicationName = 'Cirrus Core - Developer Mode';
}
let nodaemon = args.some(val => val === '--nodaemon' || val === '-nodaemon');
const devtools = args.some(val => val === '--devtools' || val === '-devtools');
if (os.platform() === 'darwin') {
args.push('-dbtype=rocksdb');
}
// Set default API port according to network
let apiPortDefault;
if (testnet || devmode) {
apiPortDefault = 38223;
} else {
apiPortDefault = 37223;
}
// Sets default arguments
const coreargs = require('minimist')(args, {
default: {
daemonip: 'localhost',
apiport: apiPortDefault
},
});
// Apply arguments to override default daemon IP and port
const daemonIP = coreargs.daemonip;
const apiPort = coreargs.apiport;
// Prevents daemon from starting if connecting to remote daemon.
if (daemonIP !== 'localhost') {
nodaemon = true;
}
ipcMain.on('get-port', (event) => {
event.returnValue = apiPort;
});
ipcMain.on('get-testnet', (event) => {
event.returnValue = testnet;
});
ipcMain.on('get-daemonip', (event) => {
event.returnValue = daemonIP;
});
require('electron-context-menu')({
showInspectElement: serve
});
function writeLog(msg): void {
console.log(msg);
}
function writeError(msg: string): void {
console.log(`Error: ${msg}`);
}
function createMenu() {
const menuTemplate = [{
label: app.getName(),
submenu: [
{ label: 'About ' + app.getName(), selector: 'orderFrontStandardAboutPanel:' },
{
label: 'Quit', accelerator: 'Command+Q', click: function (): void {
app.quit();
}
}
]
}, {
label: 'Edit',
submenu: [
{ label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:' },
{ label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:' },
{ label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:' },
{ label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' },
{ label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' },
{ label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:' }
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate));
}
function shutdownDaemon(daemonAddr, portNumber): void {
writeLog('Sending POST request to shut down daemon.');
const http = require('http');
const options = {
hostname: daemonAddr,
port: portNumber,
path: '/api/node/shutdown',
method: 'POST'
};
const req = http.request(options);
req.on('response', (res) => {
if (res.statusCode === 200) {
writeLog('Request to shutdown daemon returned HTTP success code.');
} else {
writeError(`Request to shutdown daemon returned HTTP failure code: ${Number(res.statusCode)}`);
}
});
req.on('error', () => {
writeError('Request to shutdown daemon failed.');
});
req.setHeader('content-type', 'application/json-patch+json');
req.write('true');
req.end();
}
function startDaemon(): void {
const spawnDaemon = require('child_process').spawn;
let daemonPath: string;
if (os.platform() === 'win32') {
daemonPath = path.resolve(__dirname, '..\\..\\resources\\daemon\\' + daemonName + '.exe');
} else if (os.platform() === 'linux') {
daemonPath = path.resolve(__dirname, '..//..//resources//daemon//' + daemonName);
} else {
daemonPath = path.resolve(__dirname, '..//..//resources//daemon//' + daemonName);
}
const spawnArgs = args.filter(arg => arg.startsWith('-'))
.join('&').replace(/--/g, '-').split('&');
console.log(`Starting daemon ${daemonPath}`);
console.log(spawnArgs);
const daemonProcess = spawnDaemon(daemonPath, spawnArgs, {
detached: false
});
daemonProcess.stdout.on('data', (data: string) => {
writeLog(`Stratis: ${data}`);
});
}
function createTray(): void {
// Put the app in system tray
const iconPath = 'cirrus/icon-16.png';
let trayIcon;
if (serve) {
trayIcon = nativeImage.createFromPath('./src/assets/images/' + iconPath);
} else {
trayIcon = nativeImage.createFromPath(path.resolve(__dirname, '../../resources/src/assets/images/' + iconPath));
}
const systemTray = new Tray(trayIcon);
const contextMenu = Menu.buildFromTemplate([
{
label: 'Hide/Show',
click: function (): void {
mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
}
},
{
label: 'Exit',
click: function (): void {
app.quit();
}
}
]);
systemTray.setToolTip(applicationName);
systemTray.setContextMenu(contextMenu);
systemTray.on('click', function (): void {
if (!mainWindow.isVisible()) {
mainWindow.show();
}
if (!mainWindow.isFocused()) {
mainWindow.focus();
}
});
app.on('window-all-closed', function (): void {
if (systemTray) {
systemTray.destroy();
}
});
}
// 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 = null;
function createWindow(): void {
// Create the browser window.
const height = screen.getPrimaryDisplay().bounds.height - 100;
const width = Math.round(height * 1.1);
mainWindow = new BrowserWindow({
width: width,
height: height,
frame: true,
minWidth: 900,
minHeight: 800,
title: applicationName,
webPreferences: {
nodeIntegration: true,
allowRunningInsecureContent: (serve) ? true : false,
contextIsolation: false, // false if you want to run 2e2 test with Spectron
enableRemoteModule: true // true if you want to run 2e2 test with Spectron or use remote module in renderer context (ie. Angular)
},
});
if (serve) {
require('electron-reload')(__dirname, {
electron: require(`${__dirname}/node_modules/electron`)
});
mainWindow.loadURL('http://localhost:4200');
} else {
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'dist/index.html'),
protocol: 'file:',
slashes: true
}));
}
if (serve || devtools) {
mainWindow.webContents.openDevTools();
}
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store window
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
// Remove menu, new from Electron 5
mainWindow.removeMenu();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
if (serve) {
console.log('Cirrus UI was started in development mode. This requires the user to be running the StratisFullNode daemon himself.');
} else {
if (!nodaemon) {
startDaemon();
}
}
createTray();
createWindow();
if (os.platform() === 'darwin') {
createMenu();
}
});
var delayExecuted = false;
/* 'before-quit' is emitted when Electron receives
* the signal to exit and wants to start closing windows */
app.on('before-quit', (event) => {
if (!delayExecuted) {
if (!serve && !nodaemon) {
shutdownDaemon(daemonIP, apiPort);
console.log('Executing shutdown delay to ensure that the node is disposed properly.');
setTimeout(function () { delayExecutionComplete(); }, 10000);
event.preventDefault();
}
}
else {
console.log('Quitting...');
}
});
function delayExecutionComplete() {
console.log('Delay execution completed.');
delayExecuted = true;
app.quit();
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
writeLog("All windows closed, quitting application.");
app.quit();
});
// Quit when all windows are closed.
app.on('window-all-closed', () => {
app.quit();
});
app.on('activate', () => {
// On OS X 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();
}
});