app.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. /* jshint esversion: 6 */
  2. const electron = require('electron');
  3. const updater = require('electron-updater');
  4. const fs = require('fs');
  5. const os = require('os');
  6. const path = require('path');
  7. const process = require('process');
  8. const url = require('url');
  9. class Application {
  10. constructor() {
  11. this._views = new ViewCollection();
  12. this._configuration = new ConfigurationService();
  13. this._menu = new MenuService();
  14. this._openFileQueue = [];
  15. electron.app.setAppUserModelId('com.lutzroeder.netron');
  16. electron.app.allowRendererProcessReuse = true;
  17. if (!electron.app.requestSingleInstanceLock()) {
  18. electron.app.quit();
  19. return;
  20. }
  21. electron.app.on('second-instance', (event, commandLine, workingDirectory) => {
  22. const currentDirectory = process.cwd();
  23. process.chdir(workingDirectory);
  24. const open = this._parseCommandLine(commandLine);
  25. process.chdir(currentDirectory);
  26. if (!open) {
  27. if (this._views.count > 0) {
  28. const view = this._views.item(0);
  29. if (view) {
  30. view.restore();
  31. }
  32. }
  33. }
  34. });
  35. electron.ipcMain.on('open-file-dialog', () => {
  36. this._openFileDialog();
  37. });
  38. electron.ipcMain.on('drop-files', (e, data) => {
  39. const files = data.files.filter((file) => fs.statSync(file).isFile());
  40. this._dropFiles(e.sender, files);
  41. });
  42. electron.app.on('will-finish-launching', () => {
  43. electron.app.on('open-file', (e, path) => {
  44. this._openFile(path);
  45. });
  46. });
  47. electron.app.on('ready', () => {
  48. this._ready();
  49. });
  50. electron.app.on('window-all-closed', () => {
  51. if (process.platform !== 'darwin') {
  52. electron.app.quit();
  53. }
  54. });
  55. electron.app.on('will-quit', () => {
  56. this._configuration.save();
  57. });
  58. this._parseCommandLine(process.argv);
  59. this._checkForUpdates();
  60. }
  61. _parseCommandLine(argv) {
  62. let open = false;
  63. if (argv.length > 1) {
  64. for (const arg of argv.slice(1)) {
  65. if (!arg.startsWith('-')) {
  66. const extension = arg.split('.').pop().toLowerCase();
  67. if (extension != '' && extension != 'js' && fs.existsSync(arg) && fs.statSync(arg).isFile()) {
  68. this._openFile(arg);
  69. open = true;
  70. }
  71. }
  72. }
  73. }
  74. return open;
  75. }
  76. _ready() {
  77. this._configuration.load();
  78. if (!this._configuration.has('userId')) {
  79. this._configuration.set('userId', this._uuid());
  80. }
  81. if (this._openFileQueue) {
  82. const queue = this._openFileQueue;
  83. this._openFileQueue = null;
  84. while (queue.length > 0) {
  85. const file = queue.shift();
  86. this._openFile(file);
  87. }
  88. }
  89. if (this._views.count == 0) {
  90. this._views.openView();
  91. }
  92. this._resetMenu();
  93. this._views.on('active-view-changed', () => {
  94. this._updateMenu();
  95. });
  96. this._views.on('active-view-updated', () => {
  97. this._updateMenu();
  98. });
  99. }
  100. _uuid() {
  101. const buffer = new Uint8Array(16);
  102. require("crypto").randomFillSync(buffer);
  103. buffer[6] = buffer[6] & 0x0f | 0x40;
  104. buffer[8] = buffer[8] & 0x3f | 0x80;
  105. const text = Array.from(buffer).map((value) => value < 0x10 ? '0' + value.toString(16) : value.toString(16)).join('');
  106. return text.slice(0, 8) + '-' + text.slice(8, 12) + '-' + text.slice(12, 16) + '-' + text.slice(16, 20) + '-' + text.slice(20, 32);
  107. }
  108. _openFileDialog() {
  109. const showOpenDialogOptions = {
  110. properties: [ 'openFile' ],
  111. filters: [
  112. { name: 'All Model Files', extensions: [
  113. 'onnx', 'pb',
  114. 'h5', 'hd5', 'hdf5', 'json', 'keras',
  115. 'mlmodel',
  116. 'caffemodel',
  117. 'model', 'dnn', 'cmf', 'mar', 'params',
  118. 'meta',
  119. 'tflite', 'lite', 'tfl',
  120. 'armnn', 'mnn', 'nn', 'uff', 'uff.txt', 'rknn',
  121. 'ncnn', 'param', 'tnnproto', 'tmfile', 'ms',
  122. 'pt', 'pth', 't7',
  123. 'pkl', 'joblib',
  124. 'pbtxt', 'prototxt',
  125. 'cfg', 'xml' ] }
  126. ]
  127. };
  128. const selectedFiles = electron.dialog.showOpenDialogSync(showOpenDialogOptions);
  129. if (selectedFiles) {
  130. for (const file of selectedFiles) {
  131. this._openFile(file);
  132. }
  133. }
  134. }
  135. _openFile(file) {
  136. if (this._openFileQueue) {
  137. this._openFileQueue.push(file);
  138. return;
  139. }
  140. if (file && file.length > 0 && fs.existsSync(file) && fs.statSync(file).isFile()) {
  141. // find existing view for this file
  142. let view = this._views.find(file);
  143. // find empty welcome window
  144. if (view == null) {
  145. view = this._views.find(null);
  146. }
  147. // create new window
  148. if (view == null) {
  149. view = this._views.openView();
  150. }
  151. this._loadFile(file, view);
  152. }
  153. }
  154. _loadFile(file, view) {
  155. const recents = this._configuration.get('recents').filter(recent => file != recent.path);
  156. view.open(file);
  157. recents.unshift({ path: file });
  158. if (recents.length > 9) {
  159. recents.splice(9);
  160. }
  161. this._configuration.set('recents', recents);
  162. this._resetMenu();
  163. }
  164. _dropFiles(sender, files) {
  165. let view = this._views.from(sender);
  166. for (const file of files) {
  167. if (view) {
  168. this._loadFile(file, view);
  169. view = null;
  170. }
  171. else {
  172. this._openFile(file);
  173. }
  174. }
  175. }
  176. _export() {
  177. const view = this._views.activeView;
  178. if (view && view.path) {
  179. let defaultPath = 'Untitled';
  180. const file = view.path;
  181. const lastIndex = file.lastIndexOf('.');
  182. if (lastIndex != -1) {
  183. defaultPath = file.substring(0, lastIndex);
  184. }
  185. const owner = electron.BrowserWindow.getFocusedWindow();
  186. const showSaveDialogOptions = {
  187. title: 'Export',
  188. defaultPath: defaultPath,
  189. buttonLabel: 'Export',
  190. filters: [
  191. { name: 'PNG', extensions: [ 'png' ] },
  192. { name: 'SVG', extensions: [ 'svg' ] }
  193. ]
  194. };
  195. const selectedFile = electron.dialog.showSaveDialogSync(owner, showSaveDialogOptions);
  196. if (selectedFile) {
  197. view.execute('export', { 'file': selectedFile });
  198. }
  199. }
  200. }
  201. service(name) {
  202. if (name == 'configuration') {
  203. return this._configuration;
  204. }
  205. return undefined;
  206. }
  207. execute(command, data) {
  208. const view = this._views.activeView;
  209. if (view) {
  210. view.execute(command, data || {});
  211. }
  212. this._updateMenu();
  213. }
  214. _reload() {
  215. const view = this._views.activeView;
  216. if (view && view.path) {
  217. this._loadFile(view.path, view);
  218. }
  219. }
  220. _checkForUpdates() {
  221. if (!electron.app.isPackaged) {
  222. return;
  223. }
  224. const autoUpdater = updater.autoUpdater;
  225. if (autoUpdater.app && autoUpdater.app.appUpdateConfigPath && !fs.existsSync(autoUpdater.app.appUpdateConfigPath)) {
  226. return;
  227. }
  228. const promise = autoUpdater.checkForUpdates();
  229. if (promise) {
  230. promise.catch((error) => {
  231. console.log(error.message);
  232. });
  233. }
  234. }
  235. get package() {
  236. if (!this._package) {
  237. const file = path.join(path.dirname(__dirname), 'package.json');
  238. const data = fs.readFileSync(file);
  239. this._package = JSON.parse(data);
  240. this._package.date = new Date(fs.statSync(file).mtime);
  241. }
  242. return this._package;
  243. }
  244. _about() {
  245. let dialog = null;
  246. const options = {
  247. show: false,
  248. backgroundColor: electron.nativeTheme.shouldUseDarkColors ? '#2d2d2d' : '#e6e6e6',
  249. width: 400,
  250. height: 250,
  251. center: true,
  252. minimizable: false,
  253. maximizable: false,
  254. useContentSize: true,
  255. resizable: true,
  256. fullscreenable: false,
  257. webPreferences: {
  258. nodeIntegration: true,
  259. contextIsolation: true,
  260. worldSafeExecuteJavaScript: true
  261. }
  262. };
  263. if (process.platform === 'darwin') {
  264. options.title = '';
  265. dialog = Application._aboutDialog;
  266. }
  267. else {
  268. options.title = 'About ' + electron.app.name;
  269. options.parent = electron.BrowserWindow.getFocusedWindow();
  270. options.modal = true;
  271. options.showInTaskbar = false;
  272. }
  273. if (process.platform === 'win32') {
  274. options.type = 'toolbar';
  275. }
  276. if (!dialog) {
  277. dialog = new electron.BrowserWindow(options);
  278. if (process.platform === 'darwin') {
  279. Application._aboutDialog = dialog;
  280. }
  281. dialog.removeMenu();
  282. dialog.excludedFromShownWindowsMenu = true;
  283. dialog.webContents.on('new-window', (event, url) => {
  284. if (url.startsWith('http://') || url.startsWith('https://')) {
  285. event.preventDefault();
  286. electron.shell.openExternal(url);
  287. }
  288. });
  289. let content = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf-8');
  290. content = content.replace('{version}', this.package.version);
  291. content = content.replace('<title>Netron</title>', '');
  292. content = content.replace('<body class="welcome spinner">', '<body class="about desktop">');
  293. content = content.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
  294. content = content.replace(/<link.*>/gi, '');
  295. dialog.once('ready-to-show', () => {
  296. dialog.resizable = false;
  297. dialog.show();
  298. });
  299. dialog.on('close', function() {
  300. electron.globalShortcut.unregister('Escape');
  301. Application._aboutDialog = null;
  302. });
  303. dialog.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(content));
  304. electron.globalShortcut.register('Escape', function() {
  305. dialog.close();
  306. });
  307. }
  308. else {
  309. dialog.show();
  310. }
  311. }
  312. _updateMenu() {
  313. const window = electron.BrowserWindow.getFocusedWindow();
  314. this._menu.update({
  315. window: window,
  316. webContents: window ? window.webContents : null,
  317. view: this._views.activeView
  318. }, this._views.views.map((view) => view.window));
  319. }
  320. _resetMenu() {
  321. const menuRecentsTemplate = [];
  322. if (this._configuration.has('recents')) {
  323. let recents = this._configuration.get('recents');
  324. recents = recents.filter(recent => fs.existsSync(recent.path) && fs.statSync(recent.path).isFile());
  325. if (recents.length > 9) {
  326. recents.splice(9);
  327. }
  328. this._configuration.set('recents', recents);
  329. for (let i = 0; i < recents.length; i++) {
  330. const recent = recents[i];
  331. menuRecentsTemplate.push({
  332. file: recent.path,
  333. label: Application.minimizePath(recent.path),
  334. accelerator: ((process.platform === 'darwin') ? 'Cmd+' : 'Ctrl+') + (i + 1).toString(),
  335. click: (item) => { this._openFile(item.file); }
  336. });
  337. }
  338. }
  339. const menuTemplate = [];
  340. if (process.platform === 'darwin') {
  341. menuTemplate.unshift({
  342. label: electron.app.name,
  343. submenu: [
  344. {
  345. label: 'About ' + electron.app.name,
  346. click: () => this._about()
  347. },
  348. { type: 'separator' },
  349. { role: 'hide' },
  350. { role: 'hideothers' },
  351. { role: 'unhide' },
  352. { type: 'separator' },
  353. { role: 'quit' }
  354. ]
  355. });
  356. }
  357. menuTemplate.push({
  358. label: '&File',
  359. submenu: [
  360. {
  361. label: '&Open...',
  362. accelerator: 'CmdOrCtrl+O',
  363. click: () => { this._openFileDialog(); }
  364. },
  365. {
  366. label: 'Open &Recent',
  367. submenu: menuRecentsTemplate
  368. },
  369. { type: 'separator' },
  370. {
  371. id: 'file.export',
  372. label: '&Export...',
  373. accelerator: 'CmdOrCtrl+Shift+E',
  374. click: () => this._export(),
  375. },
  376. { type: 'separator' },
  377. { role: 'close' },
  378. ]
  379. });
  380. if (process.platform !== 'darwin') {
  381. menuTemplate.slice(-1)[0].submenu.push(
  382. { type: 'separator' },
  383. { role: 'quit' }
  384. );
  385. }
  386. if (process.platform == 'darwin') {
  387. electron.systemPreferences.setUserDefault('NSDisabledDictationMenuItem', 'boolean', true);
  388. electron.systemPreferences.setUserDefault('NSDisabledCharacterPaletteMenuItem', 'boolean', true);
  389. }
  390. menuTemplate.push({
  391. label: '&Edit',
  392. submenu: [
  393. {
  394. id: 'edit.cut',
  395. label: 'Cu&t',
  396. accelerator: 'CmdOrCtrl+X',
  397. click: () => this.execute('cut', null),
  398. },
  399. {
  400. id: 'edit.copy',
  401. label: '&Copy',
  402. accelerator: 'CmdOrCtrl+C',
  403. click: () => this.execute('copy', null),
  404. },
  405. {
  406. id: 'edit.paste',
  407. label: '&Paste',
  408. accelerator: 'CmdOrCtrl+V',
  409. click: () => this.execute('paste', null),
  410. },
  411. {
  412. id: 'edit.select-all',
  413. label: 'Select &All',
  414. accelerator: 'CmdOrCtrl+A',
  415. click: () => this.execute('selectall', null),
  416. },
  417. { type: 'separator' },
  418. {
  419. id: 'edit.find',
  420. label: '&Find...',
  421. accelerator: 'CmdOrCtrl+F',
  422. click: () => this.execute('find', null),
  423. }
  424. ]
  425. });
  426. const viewTemplate = {
  427. label: '&View',
  428. submenu: [
  429. {
  430. id: 'view.show-attributes',
  431. accelerator: 'CmdOrCtrl+D',
  432. click: () => this.execute('toggle-attributes', null),
  433. },
  434. {
  435. id: 'view.show-initializers',
  436. accelerator: 'CmdOrCtrl+I',
  437. click: () => this.execute('toggle-initializers', null),
  438. },
  439. {
  440. id: 'view.show-names',
  441. accelerator: 'CmdOrCtrl+U',
  442. click: () => this.execute('toggle-names', null),
  443. },
  444. {
  445. id: 'view.show-horizontal',
  446. accelerator: 'CmdOrCtrl+K',
  447. click: () => this.execute('toggle-direction', null),
  448. },
  449. { type: 'separator' },
  450. {
  451. id: 'view.reload',
  452. label: '&Reload',
  453. accelerator: (process.platform === 'darwin') ? 'Cmd+R' : 'F5',
  454. click: () => this._reload(),
  455. },
  456. { type: 'separator' },
  457. {
  458. id: 'view.reset-zoom',
  459. label: 'Actual &Size',
  460. accelerator: 'Shift+Backspace',
  461. click: () => this.execute('reset-zoom', null),
  462. },
  463. {
  464. id: 'view.zoom-in',
  465. label: 'Zoom &In',
  466. accelerator: 'Shift+Up',
  467. click: () => this.execute('zoom-in', null),
  468. },
  469. {
  470. id: 'view.zoom-out',
  471. label: 'Zoom &Out',
  472. accelerator: 'Shift+Down',
  473. click: () => this.execute('zoom-out', null),
  474. },
  475. { type: 'separator' },
  476. {
  477. id: 'view.show-properties',
  478. label: '&Properties...',
  479. accelerator: 'CmdOrCtrl+Enter',
  480. click: () => this.execute('show-properties', null),
  481. }
  482. ]
  483. };
  484. if (!electron.app.isPackaged) {
  485. viewTemplate.submenu.push({ type: 'separator' });
  486. viewTemplate.submenu.push({ role: 'toggledevtools' });
  487. }
  488. menuTemplate.push(viewTemplate);
  489. if (process.platform === 'darwin') {
  490. menuTemplate.push({
  491. role: 'window',
  492. submenu: [
  493. { role: 'minimize' },
  494. { role: 'zoom' },
  495. { type: 'separator' },
  496. { role: 'front'}
  497. ]
  498. });
  499. }
  500. const helpSubmenu = [
  501. {
  502. label: '&Search Feature Requests',
  503. click: () => { electron.shell.openExternal('https://www.github.com/' + this.package.repository + '/issues'); }
  504. },
  505. {
  506. label: 'Report &Issues',
  507. click: () => { electron.shell.openExternal('https://www.github.com/' + this.package.repository + '/issues/new'); }
  508. }
  509. ];
  510. if (process.platform != 'darwin') {
  511. helpSubmenu.push({ type: 'separator' });
  512. helpSubmenu.push({
  513. label: 'About ' + electron.app.name,
  514. click: () => this._about()
  515. });
  516. }
  517. menuTemplate.push({
  518. role: 'help',
  519. submenu: helpSubmenu
  520. });
  521. const commandTable = new Map();
  522. commandTable.set('file.export', {
  523. enabled: (context) => { return context.view && context.view.path ? true : false; }
  524. });
  525. commandTable.set('edit.cut', {
  526. enabled: (context) => { return context.view && context.view.path ? true : false; }
  527. });
  528. commandTable.set('edit.copy', {
  529. enabled: (context) => { return context.view && context.view.path ? true : false; }
  530. });
  531. commandTable.set('edit.paste', {
  532. enabled: (context) => { return context.view && context.view.path ? true : false; }
  533. });
  534. commandTable.set('edit.select-all', {
  535. enabled: (context) => { return context.view && context.view.path ? true : false; }
  536. });
  537. commandTable.set('edit.find', {
  538. enabled: (context) => { return context.view && context.view.path ? true : false; }
  539. });
  540. commandTable.set('view.show-attributes', {
  541. enabled: (context) => { return context.view && context.view.path ? true : false; },
  542. label: (context) => { return !context.view || !context.view.get('show-attributes') ? 'Show &Attributes' : 'Hide &Attributes'; }
  543. });
  544. commandTable.set('view.show-initializers', {
  545. enabled: (context) => { return context.view && context.view.path ? true : false; },
  546. label: (context) => { return !context.view || !context.view.get('show-initializers') ? 'Show &Initializers' : 'Hide &Initializers'; }
  547. });
  548. commandTable.set('view.show-names', {
  549. enabled: (context) => { return context.view && context.view.path ? true : false; },
  550. label: (context) => { return !context.view || !context.view.get('show-names') ? 'Show &Names' : 'Hide &Names'; }
  551. });
  552. commandTable.set('view.show-horizontal', {
  553. enabled: (context) => { return context.view && context.view.path ? true : false; },
  554. label: (context) => { return !context.view || !context.view.get('show-horizontal') ? 'Show &Horizontal' : 'Show &Vertical'; }
  555. });
  556. commandTable.set('view.reload', {
  557. enabled: (context) => { return context.view && context.view.path ? true : false; }
  558. });
  559. commandTable.set('view.reset-zoom', {
  560. enabled: (context) => { return context.view && context.view.path ? true : false; }
  561. });
  562. commandTable.set('view.zoom-in', {
  563. enabled: (context) => { return context.view && context.view.path ? true : false; }
  564. });
  565. commandTable.set('view.zoom-out', {
  566. enabled: (context) => { return context.view && context.view.path ? true : false; }
  567. });
  568. commandTable.set('view.show-properties', {
  569. enabled: (context) => { return context.view && context.view.path ? true : false; }
  570. });
  571. this._menu.build(menuTemplate, commandTable, this._views.views.map((view) => view.window));
  572. this._updateMenu();
  573. }
  574. static minimizePath(file) {
  575. if (process.platform != 'win32') {
  576. const homeDir = os.homedir();
  577. if (file.startsWith(homeDir)) {
  578. return '~' + file.substring(homeDir.length);
  579. }
  580. }
  581. return file;
  582. }
  583. }
  584. class View {
  585. constructor(owner) {
  586. this._owner = owner;
  587. this._ready = false;
  588. this._path = null;
  589. this._properties = new Map();
  590. const size = electron.screen.getPrimaryDisplay().workAreaSize;
  591. const options = {
  592. show: false,
  593. title: electron.app.name,
  594. backgroundColor: electron.nativeTheme.shouldUseDarkColors ? '#1d1d1d' : '#e6e6e6',
  595. icon: electron.nativeImage.createFromPath(path.join(__dirname, 'icon.png')),
  596. minWidth: 600,
  597. minHeight: 400,
  598. width: size.width > 1024 ? 1024 : size.width,
  599. height: size.height > 768 ? 768 : size.height,
  600. webPreferences: {
  601. preload: path.join(__dirname, 'electron.js'),
  602. nodeIntegration: true,
  603. contextIsolation: true,
  604. worldSafeExecuteJavaScript: true,
  605. enableRemoteModule: true
  606. }
  607. };
  608. if (this._owner.count > 0 && View._position && View._position.length == 2) {
  609. options.x = View._position[0] + 30;
  610. options.y = View._position[1] + 30;
  611. if (options.x + options.width > size.width) {
  612. options.x = 0;
  613. }
  614. if (options.y + options.height > size.height) {
  615. options.y = 0;
  616. }
  617. }
  618. this._window = new electron.BrowserWindow(options);
  619. View._position = this._window.getPosition();
  620. this._updateCallback = (e, data) => {
  621. if (e.sender == this._window.webContents) {
  622. this.update(data.name, data.value);
  623. this._raise('updated');
  624. }
  625. };
  626. electron.ipcMain.on('update', this._updateCallback);
  627. this._window.on('closed', () => {
  628. electron.ipcMain.removeListener('update', this._updateCallback);
  629. this._owner.closeView(this);
  630. });
  631. this._window.on('focus', () => {
  632. this._raise('activated');
  633. });
  634. this._window.on('blur', () => {
  635. this._raise('deactivated');
  636. });
  637. this._window.webContents.on('did-finish-load', () => {
  638. this._didFinishLoad = true;
  639. });
  640. this._window.webContents.on('new-window', (event, url) => {
  641. if (url.startsWith('http://') || url.startsWith('https://')) {
  642. event.preventDefault();
  643. electron.shell.openExternal(url);
  644. }
  645. });
  646. this._window.once('ready-to-show', () => {
  647. this._window.show();
  648. });
  649. const location = url.format({ protocol: 'file:', slashes: true, pathname: path.join(__dirname, 'electron.html') });
  650. this._window.loadURL(location);
  651. }
  652. get window() {
  653. return this._window;
  654. }
  655. get path() {
  656. return this._path;
  657. }
  658. open(file) {
  659. this._openPath = file;
  660. if (this._didFinishLoad) {
  661. this._window.webContents.send('open', { file: file });
  662. }
  663. else {
  664. this._window.webContents.on('did-finish-load', () => {
  665. this._window.webContents.send('open', { file: file });
  666. });
  667. const location = url.format({ protocol: 'file:', slashes: true, pathname: path.join(__dirname, 'electron.html') });
  668. this._window.loadURL(location);
  669. }
  670. }
  671. restore() {
  672. if (this._window) {
  673. if (this._window.isMinimized()) {
  674. this._window.restore();
  675. }
  676. this._window.show();
  677. }
  678. }
  679. match(path) {
  680. if (this._openPath) {
  681. if (path === null) {
  682. return false;
  683. }
  684. if (path === this._openPath) {
  685. return true;
  686. }
  687. }
  688. return this._path == path;
  689. }
  690. execute(command, data) {
  691. if (this._window && this._window.webContents) {
  692. this._window.webContents.send(command, data);
  693. }
  694. }
  695. update(name, value) {
  696. if (name === 'path') {
  697. if (value) {
  698. this._path = value;
  699. const title = Application.minimizePath(this._path);
  700. this._window.setTitle(process.platform !== 'darwin' ? title + ' - ' + electron.app.name : title);
  701. this._window.focus();
  702. }
  703. this._openPath = null;
  704. return;
  705. }
  706. this._properties.set(name, value);
  707. }
  708. get(name) {
  709. return this._properties.get(name);
  710. }
  711. on(event, callback) {
  712. this._events = this._events || {};
  713. this._events[event] = this._events[event] || [];
  714. this._events[event].push(callback);
  715. }
  716. _raise(event, data) {
  717. if (this._events && this._events[event]) {
  718. for (const callback of this._events[event]) {
  719. callback(this, data);
  720. }
  721. }
  722. }
  723. }
  724. class ViewCollection {
  725. constructor() {
  726. this._views = [];
  727. }
  728. get views() {
  729. return this._views;
  730. }
  731. get count() {
  732. return this._views.length;
  733. }
  734. item(index) {
  735. return this._views[index];
  736. }
  737. openView() {
  738. const view = new View(this);
  739. view.on('activated', (sender) => {
  740. this._activeView = sender;
  741. this._raise('active-view-changed', { activeView: this._activeView });
  742. });
  743. view.on('updated', () => {
  744. this._raise('active-view-updated', { activeView: this._activeView });
  745. });
  746. view.on('deactivated', () => {
  747. this._activeView = null;
  748. this._raise('active-view-changed', { activeView: this._activeView });
  749. });
  750. this._views.push(view);
  751. this._updateActiveView();
  752. return view;
  753. }
  754. closeView(view) {
  755. for (let i = this._views.length - 1; i >= 0; i--) {
  756. if (this._views[i] == view) {
  757. this._views.splice(i, 1);
  758. }
  759. }
  760. this._updateActiveView();
  761. }
  762. find(path) {
  763. return this._views.find(view => view.match(path));
  764. }
  765. from(contents) {
  766. return this._views.find(view => view && view.window && view.window.webContents && view.window.webContents == contents);
  767. }
  768. get activeView() {
  769. return this._activeView;
  770. }
  771. on(event, callback) {
  772. this._events = this._events || {};
  773. this._events[event] = this._events[event] || [];
  774. this._events[event].push(callback);
  775. }
  776. _raise(event, data) {
  777. if (this._events && this._events[event]) {
  778. for (const callback of this._events[event]) {
  779. callback(this, data);
  780. }
  781. }
  782. }
  783. _updateActiveView() {
  784. const window = electron.BrowserWindow.getFocusedWindow();
  785. const view = this._views.find(view => view.window == window) || null;
  786. if (view != this._activeView) {
  787. this._activeView = view;
  788. this._raise('active-view-changed', { activeView: this._activeView });
  789. }
  790. }
  791. }
  792. class ConfigurationService {
  793. load() {
  794. this._data = { 'recents': [] };
  795. const dir = electron.app.getPath('userData');
  796. if (dir && dir.length > 0) {
  797. const file = path.join(dir, 'configuration.json');
  798. if (fs.existsSync(file)) {
  799. const data = fs.readFileSync(file);
  800. if (data) {
  801. try {
  802. this._data = JSON.parse(data);
  803. }
  804. catch (error) {
  805. // continue regardless of error
  806. }
  807. }
  808. }
  809. }
  810. }
  811. save() {
  812. if (this._data) {
  813. const data = JSON.stringify(this._data, null, 2);
  814. if (data) {
  815. const dir = electron.app.getPath('userData');
  816. if (dir && dir.length > 0) {
  817. const file = path.join(dir, 'configuration.json');
  818. fs.writeFileSync(file, data);
  819. }
  820. }
  821. }
  822. }
  823. has(name) {
  824. return this._data && Object.prototype.hasOwnProperty.call(this._data, name);
  825. }
  826. set(name, value) {
  827. this._data[name] = value;
  828. }
  829. get(name) {
  830. return this._data[name];
  831. }
  832. }
  833. class MenuService {
  834. build(menuTemplate, commandTable, windows) {
  835. this._menuTemplate = menuTemplate;
  836. this._commandTable = commandTable;
  837. this._itemTable = new Map();
  838. for (const menu of menuTemplate) {
  839. for (const item of menu.submenu) {
  840. if (item.id) {
  841. if (!item.label) {
  842. item.label = '';
  843. }
  844. this._itemTable.set(item.id, item);
  845. }
  846. }
  847. }
  848. this._rebuild(windows);
  849. }
  850. update(context, windows) {
  851. if (!this._menu && !this._commandTable) {
  852. return;
  853. }
  854. if (this._updateLabel(context)) {
  855. this._rebuild(windows);
  856. }
  857. this._updateEnabled(context);
  858. }
  859. _rebuild(windows) {
  860. this._menu = electron.Menu.buildFromTemplate(this._menuTemplate);
  861. if (process.platform === 'darwin') {
  862. electron.Menu.setApplicationMenu(this._menu);
  863. }
  864. else {
  865. for (const window of windows) {
  866. window.setMenu(this._menu);
  867. }
  868. }
  869. }
  870. _updateLabel(context) {
  871. let rebuild = false;
  872. for (const entry of this._commandTable.entries()) {
  873. const menuItem = this._menu.getMenuItemById(entry[0]);
  874. const command = entry[1];
  875. if (command && command.label) {
  876. const label = command.label(context);
  877. if (label != menuItem.label) {
  878. if (this._itemTable.has(entry[0])) {
  879. this._itemTable.get(entry[0]).label = label;
  880. rebuild = true;
  881. }
  882. }
  883. }
  884. }
  885. return rebuild;
  886. }
  887. _updateEnabled(context) {
  888. for (const entry of this._commandTable.entries()) {
  889. const menuItem = this._menu.getMenuItemById(entry[0]);
  890. if (menuItem) {
  891. const command = entry[1];
  892. if (command.enabled) {
  893. menuItem.enabled = command.enabled(context);
  894. }
  895. }
  896. }
  897. }
  898. }
  899. global.application = new Application();