forked from rotki/rotki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
316 lines (279 loc) · 10.6 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
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
const electron = require('electron');
const app = electron.app;
const Menu = electron.Menu;
const ipcMain = electron.ipcMain;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const fs = require('fs');
let executable_name = null;
let to_kill_pids = null;
/*************************************************************
* window management
*************************************************************/
let mainWindow = null;
function disableAnimationsForTest() {
if (process.env.ROTKEHLCHEN_ENVIRONMENT === 'test') {
let webContents = mainWindow.webContents;
webContents.once('dom-ready', () => {
let code = `
$(document.body).addClass('no-animations');
window.jQuery.fx.off = true;
let pluginDefaults = window.jconfirm.pluginDefaults;
pluginDefaults.animation = 'none';
pluginDefaults.closeAnimation = 'none';
pluginDefaults.backgroundDismissAnimation = 'none';
pluginDefaults.animationSpeed = 0;
pluginDefaults.animationBounce = 0;
`;
mainWindow.webContents.executeJavaScript(code, true)
.then(value => console.log(value));
});
}
}
function setupInspectMenu() {
if (process.env.ROTKEHLCHEN_ENVIRONMENT === 'development') {
let rightClickPosition = null;
const menu = new electron.Menu();
const menuItem = new electron.MenuItem({
label: 'Inspect Element',
click: () => {
mainWindow.inspectElement(rightClickPosition.x, rightClickPosition.y);
}
});
menu.append(menuItem);
mainWindow.webContents.on('context-menu', (e, params) => {
e.preventDefault();
rightClickPosition = {x: params.x, y: params.y};
menu.popup(mainWindow);
}, false);
}
}
const createWindow = () => {
mainWindow = new BrowserWindow({width: 800, height: 600});
disableAnimationsForTest();
mainWindow.loadURL(require('url').format({
pathname: path.join(__dirname, 'ui', 'index.html'),
protocol: 'file:',
slashes: true
}));
// open external links with default browser and not inside our electron app
// https://stackoverflow.com/a/32427579/110395
// Note for this to work anchor must have target="_blank"
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
electron.shell.openExternal(url);
});
// uncomment for the final app to have dev tools opened
// mainWindow.webContents.openDevTools();
// Check if we are on a MAC
if (process.platform === 'darwin') {
// Create our menu entries so that we can use MAC shortcuts
Menu.setApplicationMenu(Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' }
]
}
]));
}
mainWindow.on('closed', () => {
mainWindow = null;
});
setupInspectMenu();
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
app.quit();
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
/*************************************************************
* py process
*************************************************************/
const PY_DIST_FOLDER = 'rotkehlchen_py_dist';
let pyProc = null;
let pyPort = null;
const guessPackaged = () => {
const fullPath = path.join(__dirname, PY_DIST_FOLDER);
return fs.existsSync(fullPath);
};
const selectPort = () => {
// TODO: Perhaps find free port and return it here?
pyPort = 4242;
return pyPort;
};
var pyproc_fail_notifier = null;
// Listen for ack messages from renderer process
ipcMain.on('ack', (event, arg) => {
// when ack is received stop the pyproc fail notifier
clearInterval(pyproc_fail_notifier);
});
function log_and_quit(msg) {
electron_log(msg);
app.quit();
}
let logspath;
if (process.platform === 'linux') {
logspath = app.getPath("appData");
} else {
logspath = app.getPath("logs");
}
ELECTRON_LOG_PATH = logspath + "rotki_electron.log";
fs.writeFileSync(ELECTRON_LOG_PATH, "Rotki Electron Log initialization\n");
function electron_log(msg) {
console.log(msg);
fs.appendFileSync(ELECTRON_LOG_PATH, msg + "\n");
}
const createPyProc = () => {
let port = '' + selectPort();
let args = [];
// try to see if there is a configfile
if (fs.existsSync('rotki_config.json')) {
let raw_data = fs.readFileSync('rotki_config.json');
let no_errors = true;
try {
let jsondata = JSON.parse(raw_data);
if (jsondata.hasOwnProperty('loglevel')) {
args.push('--loglevel', jsondata['loglevel']);
}
if (jsondata.hasOwnProperty('logfromothermodules')) {
if (jsondata['logfromothermodules'] == true) {
args.push('--logfromothermodules');
}
}
if (jsondata.hasOwnProperty('logfile')) {
args.push('--logfile', jsondata['logfile']);
}
if (jsondata.hasOwnProperty('data-dir')) {
args.push('--data-dir', jsondata['data-dir']);
}
if (jsondata.hasOwnProperty('sleep-secs')) {
args.push('--sleep-secs', jsondata['sleep-secs']);
}
} catch(e) {
// do nothing, act as if there is no config given
// TODO: Perhaps in the future warn the user inside
// the app that there is a config file with invalid json
electron_log(`Could not read the rotki_config.json file due to: "${e}". Proceeding normally without a config file ....`);
}
}
if (guessPackaged()) {
let dist_dir = path.join(__dirname, PY_DIST_FOLDER);
let files = fs.readdirSync(dist_dir);
if (files.length === 0) {
log_and_quit('No files found in the dist directory');
} else if (files.length !== 1) {
log_and_quit('Found more than one file in the dist directory');
}
let executable = files[0];
if (!executable.startsWith('rotkehlchen-')) {
log_and_quit('Unexpected executable name "' + executable + '" in the dist directory');
}
executable_name = executable;
executable = path.join(dist_dir, executable);
args.push("--zerorpc-port", port);
args.push("--logfile", logspath + "/rotkehlchen.log");
electron_log('Calling python backend with: ' + executable + ' ' + args.join(' '));
pyProc = require('child_process').execFile(executable, args);
} else {
args.unshift("-m", "rotkehlchen");
args.push("--zerorpc-port", port);
if (process.env.ROTKEHLCHEN_ENVIRONMENT === 'test') {
let tempPath = path.join(app.getPath('temp'), 'rotkehlchen');
if (!fs.existsSync(tempPath)) {
fs.mkdirSync(tempPath);
}
args.push('--data-dir', tempPath);
}
electron_log('Calling python backend with: python ' + args.join(' '));
pyProc = require('child_process').spawn('python', args);
}
pyProc.on('error', (err) => {
electron_log(err);
electron_log("Failed to start python subprocess");
console.error(err);
});
pyProc.on('exit', function (code, signal) {
electron_log("python subprocess killed with signal " + signal + " and code " + code);
if (code !== 0) {
// Notify main window every 2 seconds until it acks the notification
pyproc_fail_notifier = setInterval(function () {
mainWindow.webContents.send('failed', 'failed');
}, 2000);
}
});
// Only for debugging if there is serious problems with python packend at release mode.
// Writes any stdout given by the python backend to electron log
//pyProc.stdout.on('data', function (data) {
// electron_log(data.toString());
//});
if (pyProc != null) {
electron_log('child process success on port ' + port);
}
electron_log("CREATED PYPROCESS");
};
const exitPyProc = (event) => {
electron_log("KILLING PYPROCESS");
if (process.platform === 'win32') {
// For win32 we got two problems:
// 1. pyProc.kill() does not work due to SIGTERM not really being a signal
// in Windows
// 2. the onefile pyinstaller packaging creates two executables.
// https://github.com/pyinstaller/pyinstaller/issues/2483
//
// So the solution is to not let the application close, get all
// pids and kill them before we close the app
const tasklist = require('tasklist');
electron_log('Detecting Windows pids');
tasklist().then(function(tasks){
electron_log('In tasklist result for executable_name: ' + executable_name);
to_kill_pids = [];
for (var i = 0; i < tasks.length; i++) {
if (tasks[i]['imageName'] === executable_name) {
to_kill_pids.push(tasks[i]['pid']);
electron_log('adding pid ' + tasks[i]['pid']);
}
}
// now that we have all the pids gathered, call taskkill on them
electron_log('Calling taskkill for Windows pids');
var spawn = require('child_process').spawn;
args = ['/f', '/t'];
for (var i = 0; i < to_kill_pids.length; i++) {
args.push('/PID');
args.push(to_kill_pids[i]);
}
electron_log('command is: taskkill and args: ' + JSON.stringify(args, null, 4));
killProc = spawn('taskkill', args);
killProc.on('exit', function (code, signal) {
electron_log("Kill proc on exit");
app.exit();
});
killProc.on('error', (err) => {
electron_log("Kill proc on error:" + err);
app.exit();
});
});
pyProc.kill();
// Do not allow the app to quit. Instead wait for killProc to occur
// which will quit the app itself.
event.preventDefault();
} else {
pyProc.kill();
}
pyProc = null;
pyPort = null;
};
app.on('ready', createPyProc);
app.on('will-quit', exitPyProc);