-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain2.js
955 lines (804 loc) · 27.9 KB
/
main2.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
'use strict';
// Active: (package.json, line 15)
/////////////////////////////////// main2.js //////////////////////////////////////
// //
// Running "Non-Tor Browser" (nav buttons and flash) currently only in sub-windows //
// //
/////////////////////////////////////////////////////////////////////////////////////
// loads Zeronet default homepage
var HelloZeronet = 'http://localhost:43210/';
///////////////////// Electron ///////////////////
const electron = require('electron');
const { app, crashReporter, dialog, globalShortcut, ipcMain, protocol, remote,
BrowserWindow, Menu, MenuItem, Tray } = require('electron');
const devtools = require('electron-devtools-installer');
// const ip = require("ip");
// Constants
const fs = require('fs');
const os = require('os');
const url = require('url');
const path = require('path');
const winston = require('winston');
const dir = require('node-dir');
const session = require('electron').session;
const EventEmitter = require('events').EventEmitter;
// Global app
let window = {}
window._ = require('underscore');
global.__app = {
basePath: __dirname,
dataPath: path.join(electron.app.getPath('userData')),
logPath: path.join(electron.app.getPath('userData'), 'logs'),
logger: null
};
// Create log path
if (!fs.existsSync(global.__app.logPath)) {
fs.mkdirSync(global.__app.logPath);
}
// Create logger
global.__app.logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'silly' }),
new (winston.transports.File)({
filename: path.join(global.__app.logPath, 'app.log'),
level: 'info'
})
]
});
// Dependencies
var _exist = require("is-there");
var program = require('commander');
var monogamous = require('monogamous');
var Configstore = require('configstore');
var spawn = require('electron-spawn');
// Processes
const spawnChild = require('child_process').spawn;
const ChildProcess = require('child_process');
const MainProcess = new MainProcessController();
MainProcess.start();
// Utils
const appLogger = require('./hub/logger');
const Store = require('./hub/store');
// Icons
var appIcons = require('./gfx/icons');
// User browser history
var userDP = app.getPath('userData');
var historyPath = userDP + '/userdata/history.json';
var extensionsPath = userDP.replace(/\\/g, '/') + '/userdata/extensions';
var userdataPath = userDP + '/userdata';
var configPath = userDP + '/personal.config';
var logPath = userDP + '/verbose.log';
// Persistant Storage
// ...
const windowManager = require(global.__app.basePath + "/js/WindowManager");
const GlobalShortcuts = require(global.__app.basePath + "/js/GlobalShortcuts");
const IPCMain = require(global.__app.basePath + "/js/IPCMain");
// MainProcessController
function MainProcessController() {
var _this = this;
var ipcHandler;
var mainProcessEventEmitter;
var init = function() {
// attempt to enable Pepper Flash Player plugin
// binary for pepper flash file is saved in {app-directory}/binaries/
enablePepperFlashPlayer();
attachEventHandlers();
};
var attachEventHandlers = function() {
app.on("window-all-closed", function() {
console.log("window-all-closed, quitting");
if (process.platform != "darwin") {
console.log("quitting app");
app.quit();
}
});
app.on("ready", function() {
session.defaultSession.on("will-download", handleWillDownload);
// check if .data directory exists
fs.exists(global.__app.dataPath, function(exists) {
if (exists === false) {
// create directory if .data directory doesn't exist
// TODO: check directory create permissions on Linux
fs.mkdir(global.__app.dataPath, function(err) {
if (err) {
// TODO: show error messagebox and quit app
dialog.showMessageBox({
type: "info",
buttons: ["ok"],
title: global.__app.dataPath,
message: JSON.stringify(err),
detail: JSON.stringify(err)
});
app.quit();
} else {
// startBrowser();
}
});
} else {
// startBrowser();
}
});
});
};
/**
* attempt to enable flash with Pepper Flash player
*
* supported OS versions
* Windows 7 64-bit, Mac OS 64-bit
*/
var enablePepperFlashPlayer = function() {
var ppapi_flash_path = null;
// specify flash path based on OS
if(process.platform == 'win32'){
ppapi_flash_path = path.join(global.__app.basePath, 'bin', 'pepflashplayer64_25_0_0_127.dll');
} else if (process.platform == 'darwin') {
// Mac OS
ppapi_flash_path = path.join(global.__app.basePath, 'bin', 'PepperFlashPlayer.plugin');
}
// in case ppapi_flash_path is set
if (ppapi_flash_path) {
app.commandLine.appendSwitch('ppapi-flash-path', ppapi_flash_path);
app.commandLine.appendSwitch('ppapi-flash-version', '25.0.0.127');
}
};
/**
* Start the browser and open a new window
*/
var startBrowser = function() {
// create a shared EventEmitter for windowManager to communicate with ipcHandler
mainProcessEventEmitter = new EventEmitter();
ipcHandler = new IPCMain(_this);
var shortcutHandler = new GlobalShortcuts(windowManager);
// register all global shortcuts
shortcutHandler.registerAll();
windowManager.openNewWindow();
};
var handleWillDownload = function(event, item, webContents) {
item.on("done", function(e, state) {
if (state === "completed") {
var itemInfoObj = {
type: "file-download",
fileSize: item.getTotalBytes(),
fileURL: item.getURL(),
fileName: item.getFilename(),
fileMimeType: item.getMimeType()
};
}
});
};
_this.start = function() {
init();
};
_this.getMainProcessEventEmitter = function() {
return mainProcessEventEmitter;
};
_this.getWindowManager = function() {
return windowManager;
};
}
module.exports = MainProcessController;
// End MainProcessController
// Save windowbounds
const store = new Store({
// We'll call our data file 'user-preferences'
configName: 'user-preferences',
defaults: {
// 800x600 is the default size of our window
windowBounds: { width: 800, height: 600 }
}
});
// Load app info
var pkg = require('./package.json');
// Define config constructor
function Config(cliOverrides, cliInfo) {
// Create config
this.config = new Configstore(pkg.name, { });
this.cliOverrides = cliOverrides;
// Generate IPC bindings for config and its info
var that = this;
ipcMain.on('get-config-sync', function handleGetConfigSync (evt) {
evt.returnValue = JSON.stringify(that.getAll());
});
ipcMain.on('get-config-info-sync', function handleGetConfigInfoSync (evt) {
evt.returnValue = JSON.stringify(cliInfo);
});
ipcMain.on('get-config-overrides-sync', function handleGetConfigInfoSync (evt) {
evt.returnValue = JSON.stringify(cliOverrides);
});
ipcMain.on('set-config-item-sync', function handleSetConfigItemSync (evt, key, val) {
that.set(key, val);
evt.returnValue = JSON.stringify({success: true});
});
}
Config.prototype = {
getAll: function () {
return window._.defaults({}, this.cliOverrides, this.config.all);
},
get: function (key) {
var all = this.getAll();
return all[key];
},
set: function (key, val) {
return this.config.set(key, val);
},
del: function (key) {
return this.config.del(key);
},
clear: function () {
return this.config.clear();
}
};
// Check configs
if (fs.existsSync(configPath)) {
var configs = require(configPath);
if (typeof configs === "object") {
configs = JSON.stringify(configs);
configs = JSON.parse(configs);
if (configs.enable_proxy) {
for (var key in configs.proxy) {
if (configs.proxy.hasOwnProperty(key) && configs.proxy[key]) {
app.commandLine.appendSwitch("proxy-" + key, configs.proxy[key]);
}
}
}
}
}
// Define CLI parser
program
.version(pkg.version)
.option('-S, --skip-taskbar', 'Skip showing the application in the taskbar')
.option('--minimize-to-tray', 'Hide window to tray instead of minimizing')
.option('--hide-via-tray', 'Hide window to tray instead of minimizing (only for tray icon)')
.option('--allow-multiple-instances', 'Allow multiple instances of `Fuzium` to run')
.option('--verbose', 'Display verbose log output in stdout')
.allowUnknownOption(); // Allow unknown Chromium flags
// Specify keys that can be used by config if CLI isn't provided
var cliConfigKeys = ['skip-taskbar', 'minimize-to-tray', 'hide-via-tray', 'allow-multiple-instances'];
var cliInfo = window._.object(cliConfigKeys.map(function generateCliInfo (key) {
return [key, window._.findWhere(program.options, {long: '--' + key})];
}));
// Generate a logger
var logger = appLogger({ verbose: program.verbose + '' }); // adding a '' activates debug logging.
logger.info('\n\n Writing all logs to "%s"', logPath);
// Amend attributes
program._cliConfigKeys = cliConfigKeys;
program._cliInfo = cliInfo;
// Check camelcase
function camelcase(flag) {
return flag.split('-').reduce(function (str, word) {
return str + word[0].toUpperCase() + word.slice(1);
});
}
// CLI config defaults
var cliConfig = window._.object(program._cliConfigKeys.map(function getCliValue (dashCaseKey) {
var camelCaseKey = camelcase(dashCaseKey);
return [dashCaseKey, program[camelCaseKey]];
}));
// Generate config based on CLI arguments
// logger.debug('CLI options overriding config \n', cliConfig, '\n');
var config = new Config(cliConfig, program._cliInfo, '\n');
logger.debug('Config options \n', config.getAll(), '\n');
////////////// Window ready ////////////////
app.on('ready', function() {
if (booter) {
booter.boot();
} else {
let { width, height } = store.get('windowBounds');
windowInfo.width = width;
windowInfo.height = height;
// const state = store.getState();
// localStorage.myAppState = JSON.stringify(state);
startApp();
}
});
app.on('resize', () => {
// saveWindowBounds();
// testing..
let { width, height } = func.browserWindow.getBounds();
store.set('windowBounds', { width, height });
});
// Windows are closed
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
var windows_built = false;
var open_url;
// Open URL
app.on("open-url", function(event, url) {
event.preventDefault();
open_url = url;
console.log(open_url);
if (windows_built) {
add_open_url_tab(url);
}
});
//////////// Functions for main window ////////////
var logo = appIcons['logo'];
let func = {
browserWindow: null,
config: config,
logger: logger,
// About window
openAboutWindow: function () {
var info = [
'<style type="text/css">',
'body { background: #252020; color: #E0C0C0; font-family: "Arial", "sans-serif"; }',
'p { color: orange; }',
'</style>',
'<div style="text-align: center; font-family: \'Helvetica Neue\', \'Arial\', \'sans-serif\'">',
'<h3>About</h3>',
'<p>',
'Fuzium: ' + pkg.version,
'<br/>',
'Zeronet: 0.5.3',
'<br/>',
'Electron version: ' + process.versions.electron,
'<br/>',
'Node.js version: ' + process.versions.node,
'<br/>',
'Pepper Flash Player version: 25.0.0.127',
'<br/>',
'Chromium version: ' + process.versions.chrome,
'</p>',
'<p>App: <script>document.write(require(\'electron\').remote.process.argv)</script></p>',
'<br>',
'<img src="' + logo + '">',
'</div>'
].join('');
var aboutWindow = new BrowserWindow({
title: 'About',
width: 540,
height: 360,
autoHideMenuBar: true,
titleBarStyle: 'hidden-inset',
icon: appIcons['info-32']
});
aboutWindow.loadURL('data:text/html,' + info);
logger.debug('Show app info');
},
// Config window
openConfigWindow: function () {
var configWindow = new BrowserWindow({
title: 'Prefs',
width: 620,
height: 330,
autoHideMenuBar: true,
titleBarStyle: 'hidden-inset',
icon: appIcons['info-32']
});
// Load config options
var configPage = __dirname + '/hub/config.htm';
configWindow.loadURL(configPage);
logger.debug('Show config; ' + configPage);
},
// New window
openSubWindow: function () {
var subWindow = new BrowserWindow({
title: 'Fuzium',
width: 1000,
height: 800,
autoHideMenuBar: false,
titleBarStyle: 'hidden-inset',
icon: appIcons['info-32']
});
var subWindowPage = __dirname + '/hub/browser.htm';
subWindow.loadURL(subWindowPage);
logger.debug('New Window; ' + subWindowPage);
},
// Quit application
quitApplication: function () {
logger.debug('Exiting');
app.quit();
},
// Reload
reloadWindow: function () {
logger.debug('Reloading');
BrowserWindow.getFocusedWindow().reload();
},
// Show views
showMinimizedWindow: function () {
// (focus is necessary when there is no taskbar and we have lost focus for the app)
func.browserWindow.restore();
func.browserWindow.focus();
logger.debug('Browser focus');
},
showInvisibleWindow: function () {
func.browserWindow.show();
},
// Toggle devtools
toggleDevTools: function () {
logger.debug('Toggle developer tools');
BrowserWindow.getFocusedWindow().toggleDevTools();
},
// Toggle fullscreen
toggleFullScreen: function () {
var focusedWindow = BrowserWindow.getFocusedWindow();
// Move to other full screen state (e.g. true -> false)
var wasFullScreen = focusedWindow.isFullScreen();
var toggledFullScreen = !wasFullScreen;
logger.debug('Toggle focused window size; \n', {
wasFullScreen: wasFullScreen,
toggledFullScreen: toggledFullScreen
});
focusedWindow.setFullScreen(toggledFullScreen);
},
// Toggle minimize
toggleMinimize: function () {
if (func.browserWindow) {
var isMinimized = func.browserWindow.isMinimized();
logger.debug('Toggle browser window minimization', {
isMinimized: isMinimized
});
if (isMinimized) {
func.showMinimizedWindow();
} else {
func.browserWindow.minimize();
}
} else {
logger.debug('Window minimization toggle requested but browser window not found');
}
},
// Toggle visibility
toggleVisibility: function () {
if (func.browserWindow) {
var isVisible = func.browserWindow.isVisible();
logger.debug('Toggling browser window visibility', {
isVisible: isVisible
});
if (isVisible) {
func.browserWindow.hide();
} else {
func.showInvisibleWindow();
}
} else {
logger.debug('Window visibility toggle requested but browser window not found');
}
}
};
// Create paths if none exist
checkPaths();
function checkPaths() {
// Check if directory called userdata exists
if (!_exist(userdataPath)) {
fs.mkdir(userdataPath);
}
// Check if directory called extensions exists
if (!_exist(extensionsPath)) {
fs.mkdir(extensionsPath);
}
// Check if file called history.json exists
if (!_exist(historyPath)) {
fs.writeFile(historyPath, '{"history":[]}');
}
}
// Assign tray click behavior
func.onTrayClick = (config.get('hide-via-tray') || config.get('minimize-to-tray')) ?
func.toggleVisibility : func.toggleMinimize;
func.onRaise = (config.get('hide-via-tray') || config.get('minimize-to-tray')) ?
func.showInvisibleWindow : func.showMinimizedWindow;
// Shorten tooltips
function truncateStr(str, len) {
// If the string is over the length then truncate it
// (go 1 under length so there's room for ellipses)
if (str.length > len) {
return str.slice(0, len - 2) + '…';
}
return str;
}
// If we are only allowing single instances
var booter;
if (!config.get('allow-multiple-instances')) {
// Start up/connect to a monogamous server (detects other instances)
booter = monogamous({sock: pkg.name});
// If we are the first instance, start up func
booter.on('boot', startApp);
// Otherwise, focus it
booter.on('reboot', func.onRaise);
// If we encounter an error, log it and start anyway
booter.on('error', function handleError (err) {
logger.info('Ignoring boot error ' + err + ' while connecting to monogamous server');
startApp();
});
}
///////////////////////// Create Main Window /////////////////////////
function startApp() {
// Load some default Chrome extensions
/*
REACT_PERF
REDUX_DEVTOOLS
VUEJS_DEVTOOLS
ANGULARJS_BATARANG
JQUERY_DEBUGGER
BACKBONE_DEBUGGER
REACT_DEVELOPER_TOOLS
EMBER_INSPECTOR
+ (zeronetExt)
*/
// Testing (default)
devtools.default(devtools.REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}` + '\n'))
.catch((err) => console.log('An error occurred: ', err + '\n'));
// Chrome Zeronet Extension
// var zeronetExtID = 'cpkpdcdljfbnepgfejplkhdnopniieop';
// var zeronetExtName = 'ZeroNet Protocol';
// Testing (new default)
devtools.default(devtools.zeronetExt)
.then((name) => console.log(`Added Extension: ${name}` + '\n'))
.catch((err) => console.log('An error occurred: ', err + '\n'));
// Get window info
var windowInfo = config.get('window-info') || {};
// Set window options
var windowOpts = {
frame: true,
resizable: true,
//transparent: true,
autoHideMenuBar: false,
titleBarStyle: 'hidden-inset',
width: windowInfo.width || 1000,
height: windowInfo.height || 900,
x: windowInfo.x || null,
y: windowInfo.y || null,
icon: appIcons['icon-32'],
preload: __dirname + '/hub/browser.js',
title: 'Fuzium'
};
// Define main browser window
func.browserWindow = new BrowserWindow(windowOpts);
// Todo: Set window resizable and focus
// func.browserWindow.setResizable(true);
// func.browserWindow.focus();
// func.browserWindow.loadURL('https://google.com');
// Logger info
logger.info('\n\n App is ready:', {
version: pkg.version,
platform: process.platform,
options: windowOpts,
processVersions: process.versions
});
// Minimize to tray
if (config.get('minimize-to-tray')) {
func.browserWindow.on('minimize', func.toggleVisibility);
}
// Save window position after moving
function saveWindowInfo() {
config.set('window-info', func.browserWindow.getBounds());
}
func.browserWindow.on('move', window._.debounce(function handleWindowMove () {
// logger.debug('Browser window moved, saving window info in config.');
saveWindowInfo();
}, 250));
// Save the window size after resizing
func.browserWindow.on('resize', window._.debounce(function handleWindowResize () {
// logger.debug('Browser window resized, saving window info in config.');
saveWindowInfo();
}, 250));
// When window is closed, clean up the reference to window
func.browserWindow.on('closed', function handleWindowClose () {
logger.debug('Fuzium shutting down.');
func.browserWindow = null;
if (fuzium) { fuzium.kill('SIGINT'); }
});
// Set download folder
func.browserWindow.webContents.session.on('will-download', (event, item, webContents) => {
// Set the save path, so electron doesn't prompt a save dialog
item.setSavePath('files/'+item.getFilename());
// Track download progress
var bytes, dl = 0;
item.on('updated', (event, state) => {
if (state === 'interrupted') {
console.log('Download interrupted but can be resumed');
} else if (state === 'progressing') {
if (item.isPaused()) {
console.log('Download is paused');
} else {
dl = parseInt(`${item.getReceivedBytes()}`);
if (bytes != dl) {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
bytes = parseInt(`${item.getReceivedBytes()}`);
}
}
}
});
// Download completed
item.once('done', (event, state) => {
if (state === 'completed') {
console.log('Completed. Check your app download folder')
} else {
console.log(`Download failed: ${state}`)
}
});
});
// Init menu & tray
var menuTemplate = require('./json/menus/' + process.platform + '.json');
bindMenuItems(menuTemplate.menu);
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate.menu));
// Assign tray click behavior
func.onTrayClick = (config.get('hide-via-tray') || config.get('minimize-to-tray')) ?
func.toggleVisibility : func.toggleMinimize;
func.onRaise = (config.get('hide-via-tray') || config.get('minimize-to-tray')) ?
func.showInvisibleWindow : func.showMinimizedWindow;
// Tray icon menu
var trayMenu = new Menu();
trayMenu.append(new MenuItem({
label: 'Show/hide',
click: func.onTrayClick
}));
trayMenu.append(new MenuItem({
type: 'separator'
}));
trayMenu.append(new MenuItem({
label: 'Restart',
click: function() { ipcRenderer.send('restart', 'true' ); console.log('restarting..'); }
}));
trayMenu.append(new MenuItem({
label: 'Quit',
click: func.quitApplication
}));
// App tray icon
var appIcon = new Tray( appIcons['icon-32'] );
appIcon.setContextMenu(trayMenu);
appIcon.setToolTip('Fuzium');
// Tray clicked; toggle visibility
appIcon.on('clicked', func.onTrayClick);
// State change; update tooltip
ipcMain.on('change:state', function handlestateChange(evt, stateInfo) {
func.logger.debug('Updating tray tooltip', {
stateInfo: stateInfo
});
// Max length of 127 chars on Windows
var infoStr = [
truncateStr('Zeronet :', 9),
truncateStr('Electron:', 9)
].join('\n');
appIcon.setToolTip(infoStr);
});
// Config change; update icon
ipcMain.on('change:config', function handlePlaybackChange(evt, configState) {
func.logger.debug('Updating tray icon; Config -', {
configState: configState
});
// var icon = appIcons['updated-icon-32'];
// appIcon.setImage(icon);
});
// Timing bootup.
// Getting Electron's and Zeronet's timing right will depend on each device.
// Of course Electron should be ready first while Zeronet is booting.
// Timing is improving as more things get added anyway.
if (func.browserWindow) {
// Hopefully Zeronet is ready to go after a few seconds.
setTimeout(function() { func.browserWindow.loadURL(HelloZeronet); }, 3000);
enablePepperFlashPlayer();
// But if not, a delayed reload also works fine.
// setTimeout(function(){ func.browserWindow.reload(); }, 4000);
// For now we'll assume it's loading okay.
console.log('\n Electron is ready, load Zeronet.. \n');
// But worst case may happen on slow or busy device.
// Then we might also need Zeronet to inform the browser.
// So tell the user to reload the app manually...
// console.log('\n Press [CTRL-R] to reload browser.');
// Testing Dev and Release as they behave quite differently!
// var devOnly = spawnChild(path.resolve(__dirname + '/bin/zeronet.exe'), ['--open_browser', '']);
// ..or..
// var forApp = path.resolve(path.dirname(process.execPath), '..', __dirname + '/bin/zeronet.exe');
// var packaged = spawnChild(forApp, { detached: false } ); // { stdio: 'inherit' }
// (note: our "fuzium.kill" process needs fixing now there's an installer)
var fuzium = startZeronet();
// console.log('\n fuzium = ' + fuzium + '\n');
// Spawn Zeronet as child of Electron
function startZeronet() {
// process.env.PATH
var detatch = true;
// Check args (dev or release)
if (process.argv.length === 1) {
var ZeronetApp = app.getAppPath() + '\\bin\\zeronet.exe';
// With installer we seem to lose our console even if it's detatched
// (and Zeronet now fails to start...)
// return spawn(ZeronetApp, { detached: true } ); // ['--open_browser', '']);
var electron = ChildProcess.spawn(ZeronetApp, ['--open_browser', ''], ['--homepage', '1LANDERvVWbShpNWpsrbBvfqSK1PabXtwv'] );
electron.stderr.on('data', function (data) {
console.error(data.toString())
});
electron.stdout.on('data', function (data) {
console.log(data.toString())
});
}
// Show any processes
for (var i = 0; i < process.argv.length; i++) {
console.log('process #' + i + ' = ' + process.argv[i]);
}
// Show paths
var appName = path.basename(process.execPath)
console.log('appName = ' + appName + '\n');
var electronApp = path.resolve(process.execPath);
console.log('electronApp = ' + electronApp);
var distFolder = path.resolve(process.execPath, '..');
console.log('distFolder = ' + distFolder);
var appFolder = path.resolve(distFolder, '..');
console.log('appFolder = ' + appFolder);
var appNet = path.resolve(path.join(__dirname, '/bin/zeronet.exe') );
console.log('appNet = ' + appNet);
// Spawn Zeronet
return spawnChild( appNet, ['--open_browser', ''], ['--homepage', '1LANDERvVWbShpNWpsrbBvfqSK1PabXtwv'] ); // { detached: false }
// return spawn( appNet, { detached: true }, ['--open_browser', ''] ); // { detached: false }
// Todo: try to respawn zeronet if closed.
let respawn = function(command, args) {
var spawnedProcess, error;
try {
spawnedProcess = ChildProcess.spawn(command, args, {detached: false } );
} catch (error) {};
return spawnedProcess;
};
};
};
};
// Pepper Flash Player (64bit-Win7+Mac)
var enablePepperFlashPlayer = function() {
var ppapi_flash_path = null;
// specify flash path based on OS
if(process.platform == 'win32'){
ppapi_flash_path = path.join(global.__app.basePath, 'bin', 'pepflashplayer64_25_0_0_127.dll');
} else if (process.platform == 'darwin') {
// Mac OS
ppapi_flash_path = path.join(global.__app.basePath, 'bin', 'PepperFlashPlayer.plugin');
}
// in case ppapi_flash_path is set
if (ppapi_flash_path) {
app.commandLine.appendSwitch('ppapi-flash-path', ppapi_flash_path);
app.commandLine.appendSwitch('ppapi-flash-version', '25.0.0.127');
}
};
// Handle Downloads (testing..)
var handleWillDownload = function(event, item, webContents) {
item.on("done", function(e, state) {
if (state === "completed") {
var itemInfoObj = {
type: "file-download",
fileSize: item.getTotalBytes(),
fileURL: item.getURL(),
fileName: item.getFilename(),
fileMimeType: item.getMimeType()
};
}
});
};
// Bind menus
function bindMenuItems(menuItems) {
menuItems.forEach(function bindMenuItemFn (menuItem) {
// If there is a role, continue
if (menuItem.role !== undefined) {
return;
}
// If there is a separator, continue
if (menuItem.type === 'separator') {
return;
}
// If there is a submenu, recurse it
if (menuItem.submenu) {
bindMenuItems(menuItem.submenu);
return;
}
// else find the function for command
var cmd = menuItem.command;
if (cmd === 'application:about') {
menuItem.click = func.openAboutWindow;
} else if (cmd === 'application:show-settings') {
menuItem.click = func.openConfigWindow;
} else if (cmd === 'application:new-window') {
menuItem.click = func.openSubWindow;
} else if (cmd === 'application:quit') {
menuItem.click = func.quitApplication;
} else if (cmd === 'window:reload') {
menuItem.click = func.reloadWindow;
} else if (cmd === 'window:toggle-dev-tools') {
menuItem.click = func.toggleDevTools;
} else if (cmd === 'window:toggle-full-screen') {
menuItem.click = func.toggleFullScreen;
} else {
throw new Error('Could not find function for menu command "' + cmd + '" ' +
'under label "' + menuItem.label + '"');
}
});
};
/////////////////////////////////////////////////////////////////////////////////////////////