init.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { Buffer } from 'buffer';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as util from 'util';
  5. const Module = require('module');
  6. // We modified the original process.argv to let node.js load the init.js,
  7. // we need to restore it here.
  8. process.argv.splice(1, 1);
  9. // Clear search paths.
  10. require('../common/reset-search-paths');
  11. // Import common settings.
  12. require('@electron/internal/common/init');
  13. if (process.platform === 'win32') {
  14. // Redirect node's console to use our own implementations, since node can not
  15. // handle console output when running as GUI program.
  16. const consoleLog = (...args: any[]) => {
  17. // @ts-ignore this typing is incorrect; 'format' is an optional parameter
  18. // See https://nodejs.org/api/util.html#util_util_format_format_args
  19. return process.log(util.format(...args) + '\n');
  20. };
  21. const streamWrite: NodeJS.WritableStream['write'] = function (chunk: Buffer | string, encoding?: any, callback?: Function) {
  22. if (Buffer.isBuffer(chunk)) {
  23. chunk = chunk.toString(encoding);
  24. }
  25. process.log(chunk);
  26. if (callback) {
  27. callback();
  28. }
  29. return true;
  30. };
  31. console.log = console.error = console.warn = consoleLog;
  32. process.stdout.write = process.stderr.write = streamWrite;
  33. }
  34. // Don't quit on fatal error.
  35. process.on('uncaughtException', function (error) {
  36. // Do nothing if the user has a custom uncaught exception handler.
  37. if (process.listenerCount('uncaughtException') > 1) {
  38. return;
  39. }
  40. // Show error in GUI.
  41. // We can't import { dialog } at the top of this file as this file is
  42. // responsible for setting up the require hook for the "electron" module
  43. // so we import it inside the handler down here
  44. import('electron')
  45. .then(({ dialog }) => {
  46. const stack = error.stack ? error.stack : `${error.name}: ${error.message}`;
  47. const message = 'Uncaught Exception:\n' + stack;
  48. dialog.showErrorBox('A JavaScript error occurred in the main process', message);
  49. });
  50. });
  51. // Emit 'exit' event on quit.
  52. const { app } = require('electron');
  53. app.on('quit', function (event, exitCode) {
  54. process.emit('exit', exitCode);
  55. });
  56. if (process.platform === 'win32') {
  57. // If we are a Squirrel.Windows-installed app, set app user model ID
  58. // so that users don't have to do this.
  59. //
  60. // Squirrel packages are always of the form:
  61. //
  62. // PACKAGE-NAME
  63. // - Update.exe
  64. // - app-VERSION
  65. // - OUREXE.exe
  66. //
  67. // Squirrel itself will always set the shortcut's App User Model ID to the
  68. // form `com.squirrel.PACKAGE-NAME.OUREXE`. We need to call
  69. // app.setAppUserModelId with a matching identifier so that renderer processes
  70. // will inherit this value.
  71. const updateDotExe = path.join(path.dirname(process.execPath), '..', 'update.exe');
  72. if (fs.existsSync(updateDotExe)) {
  73. const packageDir = path.dirname(path.resolve(updateDotExe));
  74. const packageName = path.basename(packageDir).replace(/\s/g, '');
  75. const exeName = path.basename(process.execPath).replace(/\.exe$/i, '').replace(/\s/g, '');
  76. app.setAppUserModelId(`com.squirrel.${packageName}.${exeName}`);
  77. }
  78. }
  79. // Map process.exit to app.exit, which quits gracefully.
  80. process.exit = app.exit as () => never;
  81. // Load the RPC server.
  82. require('@electron/internal/browser/rpc-server');
  83. // Load the guest view manager.
  84. require('@electron/internal/browser/guest-view-manager');
  85. require('@electron/internal/browser/guest-window-manager');
  86. // Now we try to load app's package.json.
  87. let packagePath = null;
  88. let packageJson = null;
  89. const searchPaths = ['app', 'app.asar', 'default_app.asar'];
  90. if (process.resourcesPath) {
  91. for (packagePath of searchPaths) {
  92. try {
  93. packagePath = path.join(process.resourcesPath, packagePath);
  94. packageJson = Module._load(path.join(packagePath, 'package.json'));
  95. break;
  96. } catch {
  97. continue;
  98. }
  99. }
  100. }
  101. if (packageJson == null) {
  102. process.nextTick(function () {
  103. return process.exit(1);
  104. });
  105. throw new Error('Unable to find a valid app');
  106. }
  107. // Set application's version.
  108. if (packageJson.version != null) {
  109. app.setVersion(packageJson.version);
  110. }
  111. // Set application's name.
  112. if (packageJson.productName != null) {
  113. app.name = `${packageJson.productName}`.trim();
  114. } else if (packageJson.name != null) {
  115. app.name = `${packageJson.name}`.trim();
  116. }
  117. // Set application's desktop name.
  118. if (packageJson.desktopName != null) {
  119. app.setDesktopName(packageJson.desktopName);
  120. } else {
  121. app.setDesktopName(`${app.name}.desktop`);
  122. }
  123. // Set v8 flags, delibrately lazy load so that apps that do not use this
  124. // feature do not pay the price
  125. if (packageJson.v8Flags != null) {
  126. require('v8').setFlagsFromString(packageJson.v8Flags);
  127. }
  128. app._setDefaultAppPaths(packagePath);
  129. // Load the chrome devtools support.
  130. require('@electron/internal/browser/devtools');
  131. // Load the chrome extension support.
  132. require('@electron/internal/browser/chrome-extension');
  133. // Load protocol module to ensure it is populated on app ready
  134. require('@electron/internal/browser/api/protocol');
  135. // Set main startup script of the app.
  136. const mainStartupScript = packageJson.main || 'index.js';
  137. const KNOWN_XDG_DESKTOP_VALUES = ['Pantheon', 'Unity:Unity7', 'pop:GNOME'];
  138. function currentPlatformSupportsAppIndicator () {
  139. if (process.platform !== 'linux') return false;
  140. const currentDesktop = process.env.XDG_CURRENT_DESKTOP;
  141. if (!currentDesktop) return false;
  142. if (KNOWN_XDG_DESKTOP_VALUES.includes(currentDesktop)) return true;
  143. // ubuntu based or derived session (default ubuntu one, communitheme…) supports
  144. // indicator too.
  145. if (/ubuntu/ig.test(currentDesktop)) return true;
  146. return false;
  147. }
  148. // Workaround for electron/electron#5050 and electron/electron#9046
  149. if (currentPlatformSupportsAppIndicator()) {
  150. process.env.XDG_CURRENT_DESKTOP = 'Unity';
  151. }
  152. // Quit when all windows are closed and no other one is listening to this.
  153. app.on('window-all-closed', () => {
  154. if (app.listenerCount('window-all-closed') === 1) {
  155. app.quit();
  156. }
  157. });
  158. const { setDefaultApplicationMenu } = require('@electron/internal/browser/default-menu');
  159. // Create default menu.
  160. //
  161. // Note that the task must be added before loading any app, so we can make sure
  162. // the call is maded before any user window is created, otherwise the default
  163. // menu may show even when user explicitly hides the menu.
  164. app.once('ready', setDefaultApplicationMenu);
  165. if (packagePath) {
  166. // Finally load app's main.js and transfer control to C++.
  167. process._firstFileName = Module._resolveFilename(path.join(packagePath, mainStartupScript), null, false);
  168. Module._load(path.join(packagePath, mainStartupScript), Module, true);
  169. } else {
  170. console.error('Failed to locate a valid package to load (app, app.asar or default_app.asar)');
  171. console.error('This normally means you\'ve damaged the Electron package somehow');
  172. }