nativefier/app/src/main.ts

426 lines
13 KiB
TypeScript
Raw Normal View History

import 'source-map-support/register';
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
2016-01-29 14:04:41 +00:00
import fs from 'fs';
import * as path from 'path';
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
import electron, {
app,
2021-02-28 15:24:14 +00:00
dialog,
globalShortcut,
2021-02-28 15:24:14 +00:00
systemPreferences,
BrowserWindow,
Event,
} from 'electron';
import electronDownload from 'electron-dl';
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
import { createLoginWindow } from './components/loginWindow';
2021-02-28 15:24:14 +00:00
import {
createMainWindow,
2021-02-28 15:24:14 +00:00
saveAppArgs,
APP_ARGS_FILE_PATH,
} from './components/mainWindow';
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
import { createTrayIcon } from './components/trayIcon';
import { isOSX, removeUserAgentSpecifics } from './helpers/helpers';
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
import { inferFlashPath } from './helpers/inferFlash';
import * as log from './helpers/loggingHelper';
import {
IS_PLAYWRIGHT,
PLAYWRIGHT_CONFIG,
safeGetEnv,
} from './helpers/playwrightHelpers';
import { setupNativefierWindow } from './helpers/windowEvents';
import {
OutputOptions,
outputOptionsToWindowOptions,
} from '../../shared/src/options/model';
2021-01-30 04:49:52 +00:00
// Entrypoint for Squirrel, a windows update framework. See https://github.com/nativefier/nativefier/pull/744
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
if (require('electron-squirrel-startup')) {
app.exit();
Support packaging nativefier applications into Squirrel-based installers (#744) [Squirrel](https://github.com/Squirrel/Squirrel.Windows) is *"an installation and update framework for Windows desktop apps "*. This PR adds `electron-squirrel-startup`, allowing to package nativefier applications into squirrel-based setup installers. Squirrel require this entrypoint to perform desktop and startup menu creations, without showing the UI on setup launches. - References: https://github.com/mongodb-js/electron-squirrel-startup - Resolves `electron-winstaller` and `electron-installer-windows` support of desktop / startup menu shortcuts for nativefier packaged applications. - The `electron-squirrel-startup` entrypoint has no effect on both Linux and Darwin, only on Windows - Supporting it directly inside `nativefier` avoids having to "hack" around the existing `main.js` and including dependencies from `electron-squirrel-startup` in an intermediate package to be included in a third layer for the final installer executable - The following script based on both `nativefier` and `electron-winstaller` templates represents a portable proof of concept for this merge request : ```js var nativefier = require('nativefier').default; var electronInstaller = require('electron-winstaller'); var options = { name: 'Web WhatsApp', targetUrl: 'http://web.whatsapp.com', platform: 'windows', arch: 'x64', version: '0.36.4', out: '.', overwrite: false, asar: false, counter: false, bounce: false, width: 1280, height: 800, showMenuBar: false, fastQuit: false, userAgent: 'Mozilla ...', ignoreCertificate: false, ignoreGpuBlacklist: false, enableEs3Apis: false, insecure: false, honest: false, zoom: 1.0, singleInstance: false, fileDownloadOptions: { saveAs: true }, processEnvs: { GOOGLE_API_KEY: '<your-google-api-key>' } }; nativefier(options, function(error, appPath) { if (error) { console.error(error); return; } console.log('App has been nativefied to', appPath); resultPromise = electronInstaller.createWindowsInstaller({ appDirectory: 'Web WhatsApp-win32-x64', outputDirectory: './', authors: 'Web WhatsApp', exe: 'Web WhatsApp.exe' }); resultPromise.then(() => console.log('It worked!'), e => console.log(`No dice: ${e.message}`)); }); ```
2019-02-08 14:57:32 +00:00
}
if (process.argv.indexOf('--verbose') > -1 || safeGetEnv('VERBOSE') === '1') {
log.setLevel('DEBUG');
process.traceDeprecation = true;
process.traceProcessWarnings = true;
process.argv.slice(1);
}
let mainWindow: BrowserWindow;
const appArgs =
IS_PLAYWRIGHT && PLAYWRIGHT_CONFIG
? (JSON.parse(PLAYWRIGHT_CONFIG) as OutputOptions)
: (JSON.parse(
fs.readFileSync(APP_ARGS_FILE_PATH, 'utf8'),
) as OutputOptions);
log.debug('appArgs', appArgs);
// Do this relatively early so that we can start storing appData with the app
if (appArgs.portable) {
log.debug(
'App was built as portable; setting appData and userData to the app folder: ',
path.resolve(path.join(__dirname, '..', 'appData')),
);
app.setPath('appData', path.join(__dirname, '..', 'appData'));
app.setPath('userData', path.join(__dirname, '..', 'appData'));
}
if (!appArgs.userAgentHonest) {
if (appArgs.userAgent) {
app.userAgentFallback = appArgs.userAgent;
} else {
app.userAgentFallback = removeUserAgentSpecifics(
app.userAgentFallback,
app.getName(),
app.getVersion(),
);
}
}
// Take in a URL on the command line as an override
if (process.argv.length > 1) {
const maybeUrl = process.argv[1];
try {
new URL(maybeUrl);
appArgs.targetUrl = maybeUrl;
log.info('Loading override URL passed as argument:', maybeUrl);
} catch (err: unknown) {
log.error(
'Not loading override URL passed as argument, because failed to parse:',
maybeUrl,
err,
);
}
}
2021-04-12 00:54:44 +00:00
// Nativefier is a browser, and an old browser is an insecure / badly-performant one.
// Given our builder/app design, we currently don't have an easy way to offer
// upgrades from the app themselves (like browsers do).
// As a workaround, we ask for a manual upgrade & re-build if the build is old.
// The period in days is chosen to be not too small to be exceedingly annoying,
// but not too large to be exceedingly insecure.
const OLD_BUILD_WARNING_THRESHOLD_DAYS = 90;
const OLD_BUILD_WARNING_THRESHOLD_MS =
OLD_BUILD_WARNING_THRESHOLD_DAYS * 24 * 60 * 60 * 1000;
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
const fileDownloadOptions = { ...appArgs.fileDownloadOptions };
electronDownload(fileDownloadOptions);
if (appArgs.processEnvs) {
// This is compatibility if just a string was passed.
if (typeof appArgs.processEnvs === 'string') {
process.env.processEnvs = appArgs.processEnvs;
} else {
Object.keys(appArgs.processEnvs)
.filter((key) => key !== undefined)
.forEach((key) => {
// @ts-expect-error TS will complain this could be undefined, but we filtered those out
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
process.env[key] = appArgs.processEnvs[key];
});
}
}
if (typeof appArgs.flashPluginDir === 'string') {
app.commandLine.appendSwitch('ppapi-flash-path', appArgs.flashPluginDir);
} else if (appArgs.flashPluginDir) {
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
const flashPath = inferFlashPath();
app.commandLine.appendSwitch('ppapi-flash-path', flashPath);
}
if (appArgs.ignoreCertificate) {
app.commandLine.appendSwitch('ignore-certificate-errors');
}
if (appArgs.disableGpu) {
app.disableHardwareAcceleration();
}
if (appArgs.ignoreGpuBlacklist) {
app.commandLine.appendSwitch('ignore-gpu-blacklist');
}
if (appArgs.enableEs3Apis) {
app.commandLine.appendSwitch('enable-es3-apis');
}
if (appArgs.diskCacheSize) {
app.commandLine.appendSwitch(
'disk-cache-size',
appArgs.diskCacheSize.toString(),
);
}
if (appArgs.basicAuthUsername) {
2018-05-24 07:02:44 +00:00
app.commandLine.appendSwitch(
'basic-auth-username',
appArgs.basicAuthUsername,
);
}
if (appArgs.basicAuthPassword) {
2018-05-24 07:02:44 +00:00
app.commandLine.appendSwitch(
'basic-auth-password',
appArgs.basicAuthPassword,
);
}
if (appArgs.lang) {
const langParts = appArgs.lang.split(',');
// Convert locales to languages, because for some reason locales don't work. Stupid Chromium
const langPartsParsed = Array.from(
// Convert to set to dedupe in case something like "en-GB,en-US" was passed
new Set(langParts.map((l) => l.split('-')[0])),
);
const langFlag = langPartsParsed.join(',');
log.debug('Setting --lang flag to', langFlag);
app.commandLine.appendSwitch('--lang', langFlag);
}
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
let currentBadgeCount = 0;
const setDockBadge = isOSX()
? (count?: number | string, bounce = false): void => {
if (count !== undefined) {
app.dock.setBadge(count.toString());
if (bounce && count > currentBadgeCount) app.dock.bounce();
currentBadgeCount = typeof count === 'number' ? count : 0;
}
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 20:50:01 +00:00
}
: (): void => undefined;
2016-01-29 14:04:41 +00:00
app.on('window-all-closed', () => {
log.debug('app.window-all-closed');
if (!isOSX() || appArgs.fastQuit || IS_PLAYWRIGHT) {
app.quit();
}
2015-07-05 06:08:13 +00:00
});
2016-01-29 14:04:41 +00:00
app.on('before-quit', () => {
log.debug('app.before-quit');
// not fired when the close button on the window is clicked
if (isOSX()) {
// need to force a quit as a workaround here to simulate the osx app hiding behaviour
// Somehow sokution at https://github.com/atom/electron/issues/444#issuecomment-76492576 does not work,
// e.prevent default appears to persist
// might cause issues in the future as before-quit and will-quit events are not called
app.exit(0);
}
});
app.on('will-quit', (event) => {
log.debug('app.will-quit', event);
});
app.on('quit', (event, exitCode) => {
log.debug('app.quit', { event, exitCode });
});
app.on('will-finish-launching', () => {
log.debug('app.will-finish-launching');
});
if (appArgs.widevine) {
// @ts-expect-error This event only appears on the widevine version of electron, which we'd see at runtime
app.on('widevine-ready', (version: string, lastVersion: string) => {
log.debug('app.widevine-ready', { version, lastVersion });
onReady().catch((err) => log.error('onReady ERROR', err));
});
app.on(
// @ts-expect-error This event only appears on the widevine version of electron, which we'd see at runtime
'widevine-update-pending',
(currentVersion: string, pendingVersion: string) => {
log.debug('app.widevine-update-pending', {
currentVersion,
pendingVersion,
});
},
);
// @ts-expect-error This event only appears on the widevine version of electron, which we'd see at runtime
app.on('widevine-error', (error: Error) => {
log.error('app.widevine-error', error);
});
} else {
app.on('ready', () => {
log.debug('ready');
onReady().catch((err) => log.error('onReady ERROR', err));
});
}
app.on('activate', (event: electron.Event, hasVisibleWindows: boolean) => {
log.debug('app.activate', { event, hasVisibleWindows });
if (isOSX() && !IS_PLAYWRIGHT) {
// this is called when the dock is clicked
if (!hasVisibleWindows) {
mainWindow.show();
}
}
});
// quit if singleInstance mode and there's already another instance running
const shouldQuit = appArgs.singleInstance && !app.requestSingleInstanceLock();
if (shouldQuit) {
app.quit();
} else {
app.on('second-instance', () => {
log.debug('app.second-instance');
if (mainWindow) {
if (!mainWindow.isVisible()) {
// try
mainWindow.show();
}
if (mainWindow.isMinimized()) {
// minimized
mainWindow.restore();
}
mainWindow.focus();
}
});
}
app.on('new-window-for-tab', () => {
log.debug('app.new-window-for-tab');
if (mainWindow) {
mainWindow.emit('new-tab');
}
});
app.on(
'login',
(
event,
webContents,
request,
authInfo,
callback: (username?: string, password?: string) => void,
) => {
log.debug('app.login', { event, request });
// for http authentication
event.preventDefault();
if (appArgs.basicAuthUsername && appArgs.basicAuthPassword) {
callback(appArgs.basicAuthUsername, appArgs.basicAuthPassword);
} else {
createLoginWindow(callback, mainWindow).catch((err) =>
log.error('createLoginWindow ERROR', err),
);
}
},
);
async function onReady(): Promise<void> {
// Warning: `mainWindow` below is the *global* unique `mainWindow`, created at init time
mainWindow = await createMainWindow(appArgs, setDockBadge);
createTrayIcon(appArgs, mainWindow);
// Register global shortcuts
if (appArgs.globalShortcuts) {
appArgs.globalShortcuts.forEach((shortcut) => {
globalShortcut.register(shortcut.key, () => {
shortcut.inputEvents.forEach((inputEvent) => {
// @ts-expect-error without including electron in our models, these will never match
mainWindow.webContents.sendInputEvent(inputEvent);
});
});
});
2021-02-28 15:24:14 +00:00
if (isOSX() && appArgs.accessibilityPrompt) {
const mediaKeys = [
'MediaPlayPause',
'MediaNextTrack',
'MediaPreviousTrack',
'MediaStop',
];
const globalShortcutsKeys = appArgs.globalShortcuts.map((g) => g.key);
const mediaKeyWasSet = globalShortcutsKeys.find((g) =>
mediaKeys.includes(g),
);
if (
mediaKeyWasSet &&
!systemPreferences.isTrustedAccessibilityClient(false)
) {
// Since we're trying to set global keyboard shortcuts for media keys, we need to prompt
// the user for permission on Mac.
// For reference:
// https://www.electronjs.org/docs/api/global-shortcut?q=MediaPlayPause#globalshortcutregisteraccelerator-callback
const accessibilityPromptResult = dialog.showMessageBoxSync(
mainWindow,
{
type: 'question',
message: 'Accessibility Permissions Needed',
buttons: ['Yes', 'No', 'No and never ask again'],
defaultId: 0,
detail:
`${appArgs.name} would like to use one or more of your keyboard's media keys (start, stop, next track, or previous track) to control it.\n\n` +
`Would you like Mac OS to ask for your permission to do so?\n\n` +
`If so, you will need to restart ${appArgs.name} after granting permissions for these keyboard shortcuts to begin working.`,
},
);
switch (accessibilityPromptResult) {
// User clicked Yes, prompt for accessibility
case 0:
systemPreferences.isTrustedAccessibilityClient(true);
break;
// User cliecked Never Ask Me Again, save that info
case 2:
appArgs.accessibilityPrompt = false;
saveAppArgs(appArgs);
break;
// User clicked No
default:
break;
2021-02-28 15:24:14 +00:00
}
}
}
}
if (
!appArgs.disableOldBuildWarning &&
new Date().getTime() - appArgs.buildDate > OLD_BUILD_WARNING_THRESHOLD_MS
) {
const oldBuildWarningText =
appArgs.oldBuildWarningText ||
'This app was built a long time ago. Nativefier uses the Chrome browser (through Electron), and it is insecure to keep using an old version of it. Please upgrade Nativefier and rebuild this app.';
dialog
.showMessageBox(mainWindow, {
type: 'warning',
message: 'Old build detected',
detail: oldBuildWarningText,
})
.catch((err) => log.error('dialog.showMessageBox ERROR', err));
}
}
app.on(
'accessibility-support-changed',
(event: Event, accessibilitySupportEnabled: boolean) => {
log.debug('app.accessibility-support-changed', {
event,
accessibilitySupportEnabled,
});
},
);
app.on(
'activity-was-continued',
(event: Event, type: string, userInfo: unknown) => {
log.debug('app.activity-was-continued', { event, type, userInfo });
},
);
app.on('browser-window-blur', (event: Event, window: BrowserWindow) => {
log.debug('app.browser-window-blur', { event, window });
});
app.on('browser-window-created', (event: Event, window: BrowserWindow) => {
log.debug('app.browser-window-created', { event, window });
setupNativefierWindow(outputOptionsToWindowOptions(appArgs), window);
});
app.on('browser-window-focus', (event: Event, window: BrowserWindow) => {
log.debug('app.browser-window-focus', { event, window });
});