electron.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. var host = host || {};
  2. const electron = require('electron');
  3. const fs = require('fs');
  4. const http = require('http');
  5. const https = require('https');
  6. const process = require('process');
  7. const path = require('path');
  8. const querystring = require('querystring');
  9. host.ElectronHost = class {
  10. constructor() {
  11. process.on('uncaughtException', (err) => {
  12. this.exception(err, true);
  13. });
  14. this._document = window.document;
  15. this._window = window;
  16. this._window.eval = global.eval = () => {
  17. throw new Error('window.eval() not supported.');
  18. };
  19. this._window.addEventListener('unload', () => {
  20. if (typeof __coverage__ !== 'undefined') {
  21. const file = path.join('.nyc_output', path.basename(window.location.pathname, '.html')) + '.json';
  22. /* eslint-disable no-undef */
  23. fs.writeFileSync(file, JSON.stringify(__coverage__));
  24. /* eslint-enable no-undef */
  25. }
  26. });
  27. this._environment = electron.ipcRenderer.sendSync('get-environment', {});
  28. this._queue = [];
  29. }
  30. get window() {
  31. return this._window;
  32. }
  33. get document() {
  34. return this._document;
  35. }
  36. get version() {
  37. return this._environment.version;
  38. }
  39. get type() {
  40. return 'Electron';
  41. }
  42. get agent() {
  43. return 'any';
  44. }
  45. initialize(view) {
  46. this._view = view;
  47. electron.ipcRenderer.on('open', (_, data) => {
  48. this._openPath(data.path);
  49. });
  50. return new Promise((resolve /*, reject */) => {
  51. const age = (new Date() - new Date(this._environment.date)) / ( 24 * 60 * 60 * 1000);
  52. if (age > 180) {
  53. this._message('Please update to the newest version.', 'Download', () => {
  54. const link = this.document.getElementById('logo-github').href;
  55. this.openURL(link);
  56. }, true);
  57. }
  58. else {
  59. const telemetry = () => {
  60. if (this._environment.packaged) {
  61. this._telemetry = new host.Telemetry('UA-54146-13', this._getConfiguration('userId'), navigator.userAgent, this.type, this.version);
  62. }
  63. resolve();
  64. };
  65. const consent = () => {
  66. this._message('This app uses cookies to report errors and anonymous usage information.', 'Accept', () => {
  67. this._setConfiguration('consent', Date.now());
  68. telemetry();
  69. });
  70. };
  71. const time = this._getConfiguration('consent');
  72. if (time && (Date.now() - time) < 30 * 24 * 60 * 60 * 1000) {
  73. telemetry();
  74. }
  75. else {
  76. this._request('https://ipinfo.io/json', { 'Content-Type': 'application/json' }, 2000).then((text) => {
  77. try {
  78. const json = JSON.parse(text);
  79. const countries = ['AT', 'BE', 'BG', 'HR', 'CZ', 'CY', 'DK', 'EE', 'FI', 'FR', 'DE', 'EL', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'NO', 'PL', 'PT', 'SK', 'ES', 'SE', 'GB', 'UK', 'GR', 'EU', 'RO'];
  80. if (json && json.country && !countries.indexOf(json.country) !== -1) {
  81. this._setConfiguration('consent', Date.now());
  82. telemetry();
  83. }
  84. else {
  85. consent();
  86. }
  87. }
  88. catch (err) {
  89. consent();
  90. }
  91. }).catch(() => {
  92. consent();
  93. });
  94. }
  95. }
  96. });
  97. }
  98. start() {
  99. if (this._queue) {
  100. const queue = this._queue;
  101. delete this._queue;
  102. if (queue.length > 0) {
  103. const path = queue.pop();
  104. this._openPath(path);
  105. }
  106. }
  107. electron.ipcRenderer.on('export', (_, data) => {
  108. this._view.export(data.file);
  109. });
  110. electron.ipcRenderer.on('cut', () => {
  111. this._view.cut();
  112. });
  113. electron.ipcRenderer.on('copy', () => {
  114. this._view.copy();
  115. });
  116. electron.ipcRenderer.on('paste', () => {
  117. this._view.paste();
  118. });
  119. electron.ipcRenderer.on('selectall', () => {
  120. this._view.selectAll();
  121. });
  122. electron.ipcRenderer.on('toggle', (sender, name) => {
  123. this._view.toggle(name);
  124. this._update(Object.assign({}, this._view.options));
  125. });
  126. electron.ipcRenderer.on('zoom-in', () => {
  127. this.document.getElementById('zoom-in-button').click();
  128. });
  129. electron.ipcRenderer.on('zoom-out', () => {
  130. this.document.getElementById('zoom-out-button').click();
  131. });
  132. electron.ipcRenderer.on('reset-zoom', () => {
  133. this._view.resetZoom();
  134. });
  135. electron.ipcRenderer.on('show-properties', () => {
  136. this.document.getElementById('menu-button').click();
  137. });
  138. electron.ipcRenderer.on('find', () => {
  139. this._view.find();
  140. });
  141. this.document.getElementById('menu-button').addEventListener('click', () => {
  142. this._view.showModelProperties();
  143. });
  144. const openFileButton = this.document.getElementById('open-file-button');
  145. if (openFileButton) {
  146. openFileButton.style.opacity = 1;
  147. openFileButton.addEventListener('click', () => {
  148. electron.ipcRenderer.send('open-file-dialog', {});
  149. });
  150. }
  151. const githubButton = this.document.getElementById('github-button');
  152. const githubLink = this.document.getElementById('logo-github');
  153. if (githubButton && githubLink) {
  154. githubButton.style.opacity = 1;
  155. githubButton.addEventListener('click', () => {
  156. this.openURL(githubLink.href);
  157. });
  158. }
  159. this.document.addEventListener('dragover', (e) => {
  160. e.preventDefault();
  161. });
  162. this.document.addEventListener('drop', (e) => {
  163. e.preventDefault();
  164. });
  165. this.document.body.addEventListener('drop', (e) => {
  166. e.preventDefault();
  167. const paths = Array.from(e.dataTransfer.files).map(((file) => file.path));
  168. if (paths.length > 0) {
  169. electron.ipcRenderer.send('drop-paths', { paths: paths });
  170. }
  171. return false;
  172. });
  173. this._view.show('welcome');
  174. }
  175. environment(name) {
  176. return this._environment[name];
  177. }
  178. error(message, detail) {
  179. electron.ipcRenderer.sendSync('show-message-box', {
  180. type: 'error',
  181. message: message,
  182. detail: detail,
  183. });
  184. }
  185. confirm(message, detail) {
  186. const result = electron.ipcRenderer.sendSync('show-message-box', {
  187. type: 'question',
  188. message: message,
  189. detail: detail,
  190. buttons: ['Yes', 'No'],
  191. defaultId: 0,
  192. cancelId: 1
  193. });
  194. return result === 0;
  195. }
  196. require(id) {
  197. try {
  198. return Promise.resolve(require(id));
  199. }
  200. catch (error) {
  201. return Promise.reject(error);
  202. }
  203. }
  204. save(name, extension, defaultPath, callback) {
  205. const selectedFile = electron.ipcRenderer.sendSync('show-save-dialog', {
  206. title: 'Export Tensor',
  207. defaultPath: defaultPath,
  208. buttonLabel: 'Export',
  209. filters: [ { name: name, extensions: [ extension ] } ]
  210. });
  211. if (selectedFile) {
  212. callback(selectedFile);
  213. }
  214. }
  215. export(file, blob) {
  216. const reader = new FileReader();
  217. reader.onload = (e) => {
  218. const data = new Uint8Array(e.target.result);
  219. fs.writeFile(file, data, null, (err) => {
  220. if (err) {
  221. this.exception(err, false);
  222. this.error('Error writing file.', err.message);
  223. }
  224. });
  225. };
  226. let err = null;
  227. if (!blob) {
  228. err = new Error("Export blob is '" + JSON.stringify(blob) + "'.");
  229. }
  230. else if (!(blob instanceof Blob)) {
  231. err = new Error("Export blob type is '" + (typeof blob) + "'.");
  232. }
  233. if (err) {
  234. this.exception(err, false);
  235. this.error('Error exporting image.', err.message);
  236. }
  237. else {
  238. reader.readAsArrayBuffer(blob);
  239. }
  240. }
  241. request(file, encoding, base) {
  242. return new Promise((resolve, reject) => {
  243. const pathname = path.join(base || __dirname, file);
  244. fs.stat(pathname, (err, stat) => {
  245. if (err && err.code === 'ENOENT') {
  246. reject(new Error("The file '" + file + "' does not exist."));
  247. }
  248. else if (err) {
  249. reject(err);
  250. }
  251. else if (!stat.isFile()) {
  252. reject(new Error("The path '" + file + "' is not a file."));
  253. }
  254. else if (stat && stat.size < 0x7ffff000) {
  255. fs.readFile(pathname, encoding, (err, data) => {
  256. if (err) {
  257. reject(err);
  258. }
  259. else {
  260. resolve(encoding ? data : new host.ElectronHost.BinaryStream(data));
  261. }
  262. });
  263. }
  264. else if (encoding) {
  265. reject(new Error("The file '" + file + "' size (" + stat.size.toString() + ") for encoding '" + encoding + "' is greater than 2 GB."));
  266. }
  267. else {
  268. resolve(new host.ElectronHost.FileStream(pathname, 0, stat.size, stat.mtimeMs));
  269. }
  270. });
  271. });
  272. }
  273. openURL(url) {
  274. electron.shell.openExternal(url);
  275. }
  276. exception(error, fatal) {
  277. if (this._telemetry && error && error.telemetry !== false) {
  278. try {
  279. const name = error && error.name ? error.name + ': ' : '';
  280. const message = error && error.message ? error.message : JSON.stringify(error);
  281. const description = [ name + message ];
  282. if (error.stack) {
  283. const format = (file, line, column) => {
  284. return file.split('\\').join('/').split('/').pop() + ':' + line + ':' + column;
  285. };
  286. const match = error.stack.match(/\n {4}at (.*) \((.*):(\d*):(\d*)\)/);
  287. if (match) {
  288. description.push(match[1] + ' (' + format(match[2], match[3], match[4]) + ')');
  289. }
  290. else {
  291. const match = error.stack.match(/\n {4}at (.*):(\d*):(\d*)/);
  292. if (match) {
  293. description.push('(' + format(match[1], match[2], match[3]) + ')');
  294. }
  295. else {
  296. const match = error.stack.match(/.*\n\s*(.*)\s*/);
  297. description.push(match ? match[1] : error.stack.split('\n').shift());
  298. }
  299. }
  300. }
  301. this._telemetry.exception(description.join(' @ '), fatal);
  302. }
  303. catch (e) {
  304. // continue regardless of error
  305. }
  306. }
  307. }
  308. screen(name) {
  309. if (this._telemetry) {
  310. try {
  311. this._telemetry.screenview(name);
  312. }
  313. catch (e) {
  314. // continue regardless of error
  315. }
  316. }
  317. }
  318. event(category, action, label, value) {
  319. if (this._telemetry) {
  320. try {
  321. this._telemetry.event(category, action, label, value);
  322. }
  323. catch (e) {
  324. // continue regardless of error
  325. }
  326. }
  327. }
  328. _context(location) {
  329. const basename = path.basename(location);
  330. const stat = fs.statSync(location);
  331. if (stat.isFile()) {
  332. const dirname = path.dirname(location);
  333. return this.request(basename, null, dirname).then((stream) => {
  334. return new host.ElectronHost.ElectronContext(this, dirname, basename, stream);
  335. });
  336. }
  337. else if (stat.isDirectory()) {
  338. const entries = new Map();
  339. const walk = (dir) => {
  340. for (const item of fs.readdirSync(dir)) {
  341. const pathname = path.join(dir, item);
  342. const stat = fs.statSync(pathname);
  343. if (stat.isDirectory()) {
  344. walk(pathname);
  345. }
  346. else if (stat.isFile()) {
  347. const stream = new host.ElectronHost.FileStream(pathname, 0, stat.size, stat.mtimeMs);
  348. const name = pathname.split(path.sep).join(path.posix.sep);
  349. entries.set(name, stream);
  350. }
  351. }
  352. };
  353. walk(location);
  354. return Promise.resolve(new host.ElectronHost.ElectronContext(this, location, basename, null, entries));
  355. }
  356. throw new Error("Unsupported path stat '" + JSON.stringify(stat) + "'.");
  357. }
  358. _openPath(path) {
  359. if (this._queue) {
  360. this._queue.push(path);
  361. return;
  362. }
  363. if (path && this._view.accept(path)) {
  364. this._view.show('welcome spinner');
  365. this._context(path).then((context) => {
  366. this._view.open(context).then((model) => {
  367. this._view.show(null);
  368. const options = Object.assign({}, this._view.options);
  369. if (model) {
  370. options.path = path;
  371. }
  372. this._update(options);
  373. }).catch((error) => {
  374. const options = Object.assign({}, this._view.options);
  375. if (error) {
  376. this._view.error(error, null, null);
  377. options.path = null;
  378. }
  379. this._update(options);
  380. });
  381. }).catch((error) => {
  382. this._view.error(error, 'Error while reading file.', null);
  383. this._update({ path: null });
  384. });
  385. }
  386. }
  387. _request(location, headers, timeout) {
  388. return new Promise((resolve, reject) => {
  389. const url = new URL(location);
  390. const protocol = url.protocol === 'https:' ? https : http;
  391. const options = {};
  392. options.headers = headers;
  393. if (timeout) {
  394. options.timeout = timeout;
  395. }
  396. const request = protocol.request(location, options, (response) => {
  397. if (response.statusCode !== 200) {
  398. const err = new Error("The web request failed with status code " + response.statusCode + " at '" + location + "'.");
  399. err.type = 'error';
  400. err.url = location;
  401. err.status = response.statusCode;
  402. reject(err);
  403. }
  404. else {
  405. let data = '';
  406. response.on('data', (chunk) => {
  407. data += chunk;
  408. });
  409. response.on('err', (err) => {
  410. reject(err);
  411. });
  412. response.on('end', () => {
  413. resolve(data);
  414. });
  415. }
  416. });
  417. request.on("error", (err) => {
  418. reject(err);
  419. });
  420. request.on("timeout", () => {
  421. request.destroy();
  422. const error = new Error("The web request timed out at '" + location + "'.");
  423. error.type = 'timeout';
  424. error.url = url;
  425. reject(error);
  426. });
  427. request.end();
  428. });
  429. }
  430. _getConfiguration(name) {
  431. return electron.ipcRenderer.sendSync('get-configuration', { name: name });
  432. }
  433. _setConfiguration(name, value) {
  434. electron.ipcRenderer.sendSync('set-configuration', { name: name, value: value });
  435. }
  436. _update(data) {
  437. electron.ipcRenderer.send('update', data);
  438. }
  439. _message(message, action, callback, modal) {
  440. const messageText = this.document.getElementById('message');
  441. if (messageText) {
  442. messageText.innerText = message;
  443. }
  444. const messageButton = this.document.getElementById('message-button');
  445. if (messageButton) {
  446. if (action && callback) {
  447. messageButton.style.removeProperty('display');
  448. messageButton.innerText = action;
  449. messageButton.onclick = () => {
  450. if (!modal) {
  451. messageButton.onclick = null;
  452. }
  453. callback();
  454. };
  455. }
  456. else {
  457. messageButton.style.display = 'none';
  458. messageButton.onclick = null;
  459. }
  460. }
  461. this._view.show('welcome message');
  462. }
  463. };
  464. host.Telemetry = class {
  465. constructor(trackingId, clientId, userAgent, applicationName, applicationVersion) {
  466. this._params = {
  467. aip: '1', // anonymizeIp
  468. tid: trackingId,
  469. cid: clientId,
  470. ua: userAgent,
  471. an: applicationName,
  472. av: applicationVersion
  473. };
  474. }
  475. screenview(screenName) {
  476. const params = Object.assign({}, this._params);
  477. params.cd = screenName;
  478. this._send('screenview', params);
  479. }
  480. event(category, action, label, value) {
  481. const params = Object.assign({}, this._params);
  482. params.ec = category;
  483. params.ea = action;
  484. params.el = label;
  485. params.ev = value;
  486. this._send('event', params);
  487. }
  488. exception(description, fatal) {
  489. const params = Object.assign({}, this._params);
  490. params.exd = description;
  491. if (fatal) {
  492. params.exf = '1';
  493. }
  494. this._send('exception', params);
  495. }
  496. _send(type, params) {
  497. params.t = type;
  498. params.v = '1';
  499. for (const param in params) {
  500. if (params[param] === null || params[param] === undefined) {
  501. delete params[param];
  502. }
  503. }
  504. const body = querystring.stringify(params);
  505. const options = {
  506. method: 'POST',
  507. host: 'www.google-analytics.com',
  508. path: '/collect',
  509. headers: { 'Content-Length': Buffer.byteLength(body) }
  510. };
  511. const request = https.request(options, (response) => {
  512. response.on('error', (/* error */) => {});
  513. });
  514. request.setTimeout(5000, () => {
  515. request.destroy();
  516. });
  517. request.on('error', (/* error */) => {});
  518. request.write(body);
  519. request.end();
  520. }
  521. };
  522. host.ElectronHost.BinaryStream = class {
  523. constructor(buffer) {
  524. this._buffer = buffer;
  525. this._length = buffer.length;
  526. this._position = 0;
  527. }
  528. get position() {
  529. return this._position;
  530. }
  531. get length() {
  532. return this._length;
  533. }
  534. stream(length) {
  535. const buffer = this.read(length);
  536. return new host.ElectronHost.BinaryStream(buffer.slice(0));
  537. }
  538. seek(position) {
  539. this._position = position >= 0 ? position : this._length + position;
  540. if (this._position > this._buffer.length) {
  541. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  542. }
  543. }
  544. skip(offset) {
  545. this._position += offset;
  546. if (this._position > this._buffer.length) {
  547. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  548. }
  549. }
  550. peek(length) {
  551. if (this._position === 0 && length === undefined) {
  552. return this._buffer;
  553. }
  554. const position = this._position;
  555. this.skip(length !== undefined ? length : this._length - this._position);
  556. const end = this._position;
  557. this.seek(position);
  558. return this._buffer.subarray(position, end);
  559. }
  560. read(length) {
  561. if (this._position === 0 && length === undefined) {
  562. this._position = this._length;
  563. return this._buffer;
  564. }
  565. const position = this._position;
  566. this.skip(length !== undefined ? length : this._length - this._position);
  567. return this._buffer.subarray(position, this._position);
  568. }
  569. byte() {
  570. const position = this._position;
  571. this.skip(1);
  572. return this._buffer[position];
  573. }
  574. };
  575. host.ElectronHost.FileStream = class {
  576. constructor(file, start, length, mtime) {
  577. this._file = file;
  578. this._start = start;
  579. this._length = length;
  580. this._position = 0;
  581. this._mtime = mtime;
  582. }
  583. get position() {
  584. return this._position;
  585. }
  586. get length() {
  587. return this._length;
  588. }
  589. stream(length) {
  590. const file = new host.ElectronHost.FileStream(this._file, this._position, length, this._mtime);
  591. this.skip(length);
  592. return file;
  593. }
  594. seek(position) {
  595. this._position = position >= 0 ? position : this._length + position;
  596. }
  597. skip(offset) {
  598. this._position += offset;
  599. if (this._position > this._length) {
  600. throw new Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  601. }
  602. }
  603. peek(length) {
  604. length = length !== undefined ? length : this._length - this._position;
  605. if (length < 0x10000000) {
  606. const position = this._fill(length);
  607. this._position -= length;
  608. return this._buffer.subarray(position, position + length);
  609. }
  610. const position = this._position;
  611. this.skip(length);
  612. this.seek(position);
  613. const buffer = new Uint8Array(length);
  614. this._read(buffer, position);
  615. return buffer;
  616. }
  617. read(length) {
  618. length = length !== undefined ? length : this._length - this._position;
  619. if (length < 0x10000000) {
  620. const position = this._fill(length);
  621. return this._buffer.subarray(position, position + length);
  622. }
  623. const position = this._position;
  624. this.skip(length);
  625. const buffer = new Uint8Array(length);
  626. this._read(buffer, position);
  627. return buffer;
  628. }
  629. byte() {
  630. const position = this._fill(1);
  631. return this._buffer[position];
  632. }
  633. _fill(length) {
  634. if (this._position + length > this._length) {
  635. throw new Error('Expected ' + (this._position + length - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  636. }
  637. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  638. this._offset = this._position;
  639. this._buffer = new Uint8Array(Math.min(0x10000000, this._length - this._offset));
  640. this._read(this._buffer, this._offset);
  641. }
  642. const position = this._position;
  643. this._position += length;
  644. return position - this._offset;
  645. }
  646. _read(buffer, offset) {
  647. const descriptor = fs.openSync(this._file, 'r');
  648. const stat = fs.statSync(this._file);
  649. if (stat.mtimeMs != this._mtime) {
  650. throw new Error("File '" + this._file + "' last modified time changed.");
  651. }
  652. try {
  653. fs.readSync(descriptor, buffer, 0, buffer.length, offset + this._start);
  654. }
  655. finally {
  656. fs.closeSync(descriptor);
  657. }
  658. }
  659. };
  660. host.ElectronHost.ElectronContext = class {
  661. constructor(host, folder, identifier, stream, entries) {
  662. this._host = host;
  663. this._folder = folder;
  664. this._identifier = identifier;
  665. this._stream = stream;
  666. this._entries = entries || new Map();
  667. }
  668. get identifier() {
  669. return this._identifier;
  670. }
  671. get stream() {
  672. return this._stream;
  673. }
  674. get entries() {
  675. return this._entries;
  676. }
  677. request(file, encoding, base) {
  678. return this._host.request(file, encoding, base === undefined ? this._folder : base);
  679. }
  680. require(id) {
  681. return this._host.require(id);
  682. }
  683. exception(error, fatal) {
  684. this._host.exception(error, fatal);
  685. }
  686. };
  687. window.addEventListener('load', () => {
  688. global.protobuf = require('./protobuf');
  689. global.flatbuffers = require('./flatbuffers');
  690. const view = require('./view');
  691. window.__host__ = new host.ElectronHost();
  692. window.__view__ = new view.View(window.__host__);
  693. });