app.js 34 KB

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