Use the stock Tauri NSIS template with RuneStone installer hooks
Remove the 996-line fork of the Tauri 2.11.4 template and the custom
comparator. src-tauri/windows/hooks.nsh now adds the RuneStone behavior
through bundle.windows.nsis.installerHooks:
- RuneStoneGuiInit (MUI_CUSTOMFUNCTION_GUIINIT) runs before the first
page in interactive and passive setup. It stops a downgrade with exit
code 2. It makes the stock maintenance page skip itself, so that setup
never starts the uninstaller for an upgrade or a reinstall.
- The hidden section RuneStoneVersionCheck runs before the Tauri sections
in all modes. Silent setup shows no pages, so it needs this check.
- NSIS_HOOK_POSTINSTALL writes the release version to DisplayVersion and
RuneStoneReleaseVersion, and the Windows version to
RuneStoneWindowsVersion. Installed apps now show 0.1.23a, not 0.1.23+1.
Setup compares the four-number Windows encoding with ${VersionCompare}.
An unknown installed version stops setup.
buildInstaller.mjs gives the toolchain version to Tauri through a
--config override. It writes tauri.conf.json, Cargo.toml, and Cargo.lock
only after the installer is complete. package.json changes during the
build because the Settings dialog imports its version. A failed build
restores it. Add --dry-run, which prints the plan and changes no file.
The tests compile NSIS programs with the real makensis. They simulate the
installed version in a test-only HKCU key and check /S, /P, /UPDATE, and
interactive setup. A drift check reads the template from the installed
Tauri CLI. The first real installer needs the installer checks in
docs/builds.md.
This commit is contained in:
+70
-24
@@ -22,7 +22,8 @@ Procedure, in the RuneStone repository root:
|
||||
2. Run `pnpm check`.
|
||||
3. Run `pnpm test`.
|
||||
4. Select the version with the [version policy](releases.md#versions).
|
||||
5. Run `pnpm build:installer --version <version>`.
|
||||
5. Run `pnpm build:installer --version <version> --dry-run`. Make sure that the plan shows the correct versions. A dry run changes no file.
|
||||
6. Run `pnpm build:installer --version <version>`.
|
||||
|
||||
Without `--version`, the script uses the version in `package.json`.
|
||||
|
||||
@@ -43,32 +44,37 @@ Example, from the 0.1.44 download link in the README: version `0.1.44` gives `re
|
||||
Source: `scripts/buildInstaller.mjs`.
|
||||
|
||||
1. Reads the version and makes sure that all version fields match the current version.
|
||||
2. Makes sure that downgrade protection stays on in `tauri.conf.json` and `tauri.windows.conf.json`, and that the browser runtime is staged.
|
||||
2. Makes sure that downgrade protection stays on in `tauri.conf.json` and `tauri.windows.conf.json`.
|
||||
Makes sure that `tauri.windows.conf.json` names the installer hooks and that the browser runtime is staged.
|
||||
3. Stops if the setup file or `host.json` exists in the bundle folder or in `releases/<version>/`.
|
||||
A dry run prints the plan and stops here.
|
||||
4. Saves copies of the four version files as `*.before` in `output/installer-build/<version>/<time>/`, a new folder for each attempt.
|
||||
It also writes the NSIS template and a configuration override to that folder.
|
||||
5. Writes the new version to `package.json`, `tauri.conf.json`, `Cargo.toml`, and `Cargo.lock`.
|
||||
6. Runs `tauri build --no-bundle -- --locked`. This runs `pnpm build` and compiles the release app.
|
||||
7. Runs `scripts/setWindowsVersion.ps1` to write the version resource of `runestone.exe`.
|
||||
8. Runs `tauri bundle --bundles nsis` with the RuneStone template from `src-tauri/windows/installer.nsi`.
|
||||
It also writes the configuration override `tauri.version.json` to that folder. The override sets the toolchain version, for example `{"version": "0.1.23+1"}`.
|
||||
5. Writes the new version to `package.json`. The front-end build reads this version for the Settings dialog.
|
||||
6. Runs `tauri build --no-bundle --config <override> -- --locked`. This runs `pnpm build` and compiles the release app.
|
||||
Tauri gives the override to the Rust build script and to the app. Cargo keeps the previous package version, so the app must not use `CARGO_PKG_VERSION`.
|
||||
7. Runs `scripts/setWindowsVersion.ps1`. It writes the release version to the `FileVersion` and `ProductVersion` strings of `runestone.exe`. Tauri can write only a SemVer version to these strings.
|
||||
8. Runs `tauri bundle --bundles nsis --config <override>`. Tauri uses its stock NSIS template with the [installer hooks](#installer-hooks).
|
||||
9. Moves the setup file into `releases/<version>/`, writes `host.json`, and removes the bundle-folder copy.
|
||||
10. Writes the new version to `tauri.conf.json`, `Cargo.toml`, and `Cargo.lock`.
|
||||
|
||||
### Failure and rollback
|
||||
|
||||
If a step fails, or you press Ctrl+C, the script restores the four version files.
|
||||
If a step fails, or you press Ctrl+C, the script restores `package.json`. The other version files change only in step 10. If step 10 fails, the script restores them too.
|
||||
It moves partial setup files and `host.json` into the folder of that attempt with a `.failed-<timestamp>` suffix.
|
||||
If the process is killed before this cleanup, copy the `*.before` files of the attempt back to their original names.
|
||||
|
||||
## Installer requirements
|
||||
|
||||
Keep these properties when you change the installer configuration or template:
|
||||
Keep these properties when you change the installer configuration or hooks:
|
||||
|
||||
| Requirement | Implementation |
|
||||
| --- | --- |
|
||||
| Reinstall is the default when RuneStone is installed, also for the same version. | The NSIS maintenance page preselects the reinstall option. |
|
||||
| Users do not uninstall RuneStone before an update or a reinstall. | Updates and reinstalls replace the app in place. |
|
||||
| Reinstall is the default when RuneStone is installed, also for the same version. | The hooks make the stock maintenance page skip itself. Setup replaces the app in place. |
|
||||
| Users do not uninstall RuneStone before an update or a reinstall. | Setup does not start the uninstaller of the installed version. |
|
||||
| Updates and reinstalls keep workspace files and user settings. | Workspaces stay outside the installation folder. Settings stay in application data. |
|
||||
| Older versions cannot replace a newer installation. | `allowDowngrades` is `false`. `pnpm build:installer` stops if this setting changes. |
|
||||
| Older versions cannot replace a newer installation. | The hooks stop setup with exit code 2 in all modes: interactive, passive (`/P`), silent (`/S`), and update (`/UPDATE`). An installed version with an unknown format also stops setup. `allowDowngrades` stays `false`. `pnpm build:installer` stops if this setting changes. |
|
||||
| Windows shows the release version in installed apps. | The hooks write the release version, such as `0.1.23a`, to `DisplayVersion`. |
|
||||
| The app identity stays the same across upgrades. | The identifier stays `com.runestone.app`. |
|
||||
| WebView2 is available. | The installer embeds the WebView2 bootstrapper. If the runtime is missing, setup downloads it. |
|
||||
|
||||
@@ -76,9 +82,30 @@ The installer uses the RuneStone icon, installs for the current Windows account,
|
||||
It does not register document types or start RuneStone when Windows starts.
|
||||
|
||||
Local installers are unsigned. Configure Windows code signing with [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) before public distribution.
|
||||
The NSIS template comes from Tauri CLI 2.11.4. When you update Tauri, compare the template with the new Tauri version.
|
||||
See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for packaging options.
|
||||
|
||||
### Installer hooks
|
||||
|
||||
RuneStone uses the stock NSIS template of the Tauri CLI.
|
||||
`src-tauri/windows/hooks.nsh` adds the RuneStone behavior. `tauri.windows.conf.json` names this file in `bundle.windows.nsis.installerHooks`.
|
||||
|
||||
| Hook | When it runs | What it does |
|
||||
| --- | --- | --- |
|
||||
| `RuneStoneGuiInit`, set as `MUI_CUSTOMFUNCTION_GUIINIT` | Interactive and passive (`/P`) setup, before the first page | Stops a downgrade. Makes the maintenance page skip itself. |
|
||||
| Section `-RuneStoneVersionCheck` | All modes, before the Tauri sections | Restores the current-user context. Stops a downgrade. Silent setup shows no pages, so it needs this check. |
|
||||
| `NSIS_HOOK_POSTINSTALL` | At the end of the Tauri `Install` section | Writes `DisplayVersion`, `RuneStoneReleaseVersion`, and `RuneStoneWindowsVersion`. |
|
||||
|
||||
Tauri includes the hooks file before the template variables, pages, and sections.
|
||||
Thus only the `NSIS_HOOK_*` macros can use template symbols such as `${VERSION}`.
|
||||
The other hook code reads the version of the setup file from its version resource.
|
||||
|
||||
The stock maintenance page preselects "Uninstall before installing" for an upgrade.
|
||||
In passive mode, it also starts the uninstaller for a same-version reinstall. A hook cannot change this page.
|
||||
Thus `RuneStoneGuiInit` sets the shell context to all users. The page then looks in `HKLM`, does not find the current-user installation, and skips itself.
|
||||
|
||||
`tests/unit/release/installerVersion.spec.ts` reads the template from the installed Tauri CLI. It checks the template parts that the hooks use.
|
||||
After a Tauri update, run `pnpm test`. If this check fails, adapt the hooks before you build an installer.
|
||||
|
||||
## Hotfix installer versions
|
||||
|
||||
Cargo and Tauri accept only SemVer versions. The Windows version resource accepts only four numbers.
|
||||
@@ -89,36 +116,55 @@ The suffix index counts `a` = 1 through `z` = 26, then `aa` = 27. A regular vers
|
||||
| Field | Value for `0.1.23a` |
|
||||
| --- | --- |
|
||||
| `package.json`, `[package.metadata.runestone]`, the setup file name, the version in Settings, and the executable `FileVersion` and `ProductVersion` strings | `0.1.23a` |
|
||||
| `tauri.conf.json`, the Cargo package version, and `Cargo.lock` | `0.1.23+1` |
|
||||
| The numeric Windows version resource of the executable and the installer | `0.1.23.1` |
|
||||
| Registry value `RuneStoneReleaseVersion` | `0.1.23a` |
|
||||
| Registry value `DisplayVersion`, which Windows shows in installed apps | `0.1.23+1` |
|
||||
| Registry values `DisplayVersion`, which Windows shows in installed apps, and `RuneStoneReleaseVersion` | `0.1.23a` |
|
||||
| `tauri.conf.json`, the Cargo package version, `Cargo.lock`, and the `FileVersion` and `ProductVersion` strings of the setup file | `0.1.23+1` |
|
||||
| The numeric Windows version resources of the executable and the setup file, and the registry value `RuneStoneWindowsVersion` | `0.1.23.1` |
|
||||
|
||||
During the build, Tauri gets `0.1.23+1` from a configuration override. The script writes the table values to the files only after the installer is complete.
|
||||
The NSIS template writes the version strings of the setup file. A hook cannot change them, so they keep the toolchain version.
|
||||
|
||||
Each numeric part and the suffix index must not exceed 65535. The last valid suffix is `crxo`.
|
||||
The script rejects other versions before it changes a file.
|
||||
|
||||
The installer comparison in `src-tauri/windows/versionCompare.nsh` sorts the numeric release first, then the suffix:
|
||||
Setup compares Windows versions with the NSIS function `${VersionCompare}`. Their order is the release order:
|
||||
`0.1.23 < 0.1.23a < 0.1.23b < 0.1.23z < 0.1.23aa < 0.1.24`.
|
||||
The installer reads `RuneStoneReleaseVersion` and uses `DisplayVersion` when that value is missing.
|
||||
An installed version with an unknown format counts as newer, so setup blocks replacement.
|
||||
Older RuneStone installers read `DisplayVersion` as SemVer and treat `0.1.23+1` as newer than `0.1.23`. Thus an older `0.1.23` installer does not replace the hotfix.
|
||||
Setup reads the installed version from `RuneStoneWindowsVersion`.
|
||||
If that value is missing, setup reads `DisplayVersion`. Earlier installers wrote the toolchain version there, such as `0.1.23+1`.
|
||||
An installed version with an unknown format stops setup.
|
||||
Installers from 0.1.23a to 0.1.44 read `RuneStoneReleaseVersion`, so they also detect a newer hotfix installation.
|
||||
|
||||
## Installer checks
|
||||
|
||||
Do these checks on a separate Windows test account or virtual machine. A successful build does not prove them.
|
||||
|
||||
The unit tests compile small NSIS programs with the hooks file. They do not run a real RuneStone setup file.
|
||||
Do all checks in this table for the first installer that uses the stock template and the hooks file. Do not publish that installer before all checks pass.
|
||||
|
||||
| Check | Expected result |
|
||||
| --- | --- |
|
||||
| Install on an account without Node.js or Rust | Setup completes and RuneStone opens. |
|
||||
| Install without WebView2, with internet access | Setup installs the runtime and RuneStone opens. |
|
||||
| Open RuneStone from the Start menu | The app opens without a terminal or a development server. |
|
||||
| Create a workspace outside the installation folder | Notes save and open again. |
|
||||
| Install a newer version | Setup updates the app and keeps workspace files. |
|
||||
| Install the same version again | Setup selects reinstall and keeps workspace files and settings. |
|
||||
| Install an older version | Setup blocks the downgrade. |
|
||||
| Install the new version over 0.1.44 | Setup shows no maintenance page and does not start the uninstaller. It updates the app and keeps workspace files and settings. |
|
||||
| Install the same version again | Setup shows no maintenance page and does not start the uninstaller. It keeps workspace files and settings. |
|
||||
| Install an older version, for example 0.1.44 | Setup blocks the downgrade. |
|
||||
| Silent downgrade attempt | See the procedure below this table. Setup stops with exit code 2 and changes nothing. |
|
||||
| Open **Settings → Apps → Installed apps** in Windows | The RuneStone entry shows the release version, such as `0.1.45` or `0.1.45a`. |
|
||||
| Install a hotfix over its base version | Setup updates the app. |
|
||||
| Remove RuneStone through Windows Settings | The app and shortcuts are removed. The separate workspace stays. |
|
||||
|
||||
Silent downgrade attempt, in PowerShell on the test account:
|
||||
|
||||
1. Install the new version.
|
||||
2. Simulate a newer installation:
|
||||
`Set-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\RuneStone' RuneStoneWindowsVersion '9.0.0.0'`
|
||||
3. Run the setup file in silent mode and show its exit code:
|
||||
`(Start-Process .\RuneStone_<version>_x64-setup.exe -ArgumentList '/S' -Wait -PassThru).ExitCode`
|
||||
4. Make sure that the exit code is `2` and that installed apps show the same version as before.
|
||||
5. Run the same command with `-ArgumentList '/P'`. Setup shows a message, then stops with exit code `2`.
|
||||
6. Restore the registry value: set `RuneStoneWindowsVersion` to the `windowsVersion` value in `host.json`.
|
||||
|
||||
## Build Linux packages
|
||||
|
||||
Prerequisites:
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ Development servers, test runs, and intermediate compilation output are not buil
|
||||
| RuneStone | `package.json`, `src-tauri/tauri.conf.json`, the package version and `[package.metadata.runestone]` in `src-tauri/Cargo.toml`, and the `runestone` entry in `src-tauri/Cargo.lock` |
|
||||
| Plugin | `plugin.json`, the project `package.json`, and any build metadata |
|
||||
|
||||
On Windows, `pnpm build:installer --version <version>` sets the RuneStone fields and restores them if the build fails.
|
||||
On Windows, `pnpm build:installer --version <version>` sets the RuneStone fields when the installer is complete. If the build fails, the fields keep the previous version.
|
||||
See [Build the Windows installer](builds.md#build-the-windows-installer).
|
||||
|
||||
## Hotfix versions
|
||||
|
||||
+138
-79
@@ -1,66 +1,146 @@
|
||||
// Builds the Windows installer. See docs/builds.md#build-the-windows-installer.
|
||||
// Usage: node scripts/buildInstaller.mjs [--version <version>] [--dry-run]
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { releaseVersion } from './releaseVersion.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const exists = file => fs.access(file).then(() => true, () => false);
|
||||
const files = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'].map(file => path.join(root, file));
|
||||
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
|
||||
const current = releaseVersion(JSON.parse(before[0]).version);
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length && (args.length !== 2 || args[0] !== '--version')) throw Error('Use --version followed by the release version.');
|
||||
const next = releaseVersion(args[1] ?? current.version);
|
||||
const config = JSON.parse(before[1]);
|
||||
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
|
||||
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
|
||||
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
|
||||
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
|
||||
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
|
||||
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
|
||||
const platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8'));
|
||||
if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
||||
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
||||
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
||||
export const versionFiles = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'];
|
||||
|
||||
export function parseArguments(args) {
|
||||
const options = { version: undefined, dryRun: false };
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--dry-run') options.dryRun = true;
|
||||
else if (args[i] === '--version' && args[i + 1] && !options.version) options.version = args[++i];
|
||||
else throw Error('Use --version followed by the release version, and optionally --dry-run.');
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
// Reads the version fields, checks the build preconditions, and returns the build plan. Changes no file.
|
||||
export async function planInstallerBuild(root, requestedVersion) {
|
||||
const files = versionFiles.map(file => path.join(root, file));
|
||||
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
|
||||
const current = releaseVersion(JSON.parse(before[0]).version);
|
||||
const next = releaseVersion(requestedVersion ?? current.version);
|
||||
const config = JSON.parse(before[1]);
|
||||
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
|
||||
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
|
||||
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
|
||||
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
|
||||
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
|
||||
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
|
||||
const windowsConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8')).bundle?.windows;
|
||||
if (windowsConfig?.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
||||
const hooks = windowsConfig?.nsis?.installerHooks;
|
||||
if (!hooks || !(await exists(path.join(root, 'src-tauri', hooks)))) throw Error('The installer hooks file is not configured. See src-tauri/tauri.windows.conf.json.');
|
||||
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
||||
throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.');
|
||||
}
|
||||
const bundleDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
||||
const releaseDir = path.join(root, 'releases', next.version);
|
||||
const artifacts = {
|
||||
bundled: path.join(bundleDir, `RuneStone_${next.toolchain}_x64-setup.exe`),
|
||||
renamed: path.join(bundleDir, `RuneStone_${next.version}_x64-setup.exe`),
|
||||
release: path.join(releaseDir, `RuneStone_${next.version}_x64-setup.exe`),
|
||||
metadata: path.join(releaseDir, 'host.json'),
|
||||
};
|
||||
for (const file of new Set(Object.values(artifacts))) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
||||
|
||||
const packageJson = JSON.parse(before[0]);
|
||||
packageJson.version = next.version;
|
||||
config.version = next.toolchain;
|
||||
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
|
||||
if (cargoRelease) cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
|
||||
else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
|
||||
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
|
||||
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
|
||||
// Tauri merges this override into tauri.conf.json for the build script, the app, and the bundler.
|
||||
const override = { version: next.toolchain };
|
||||
return { root, files, before, updated, current, next, override, releaseDir, artifacts };
|
||||
}
|
||||
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
||||
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
|
||||
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
|
||||
const releaseDir = path.join(root, 'releases', next.version);
|
||||
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
|
||||
const metadataPath = path.join(releaseDir, 'host.json');
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
||||
// Each attempt keeps its own backups, so a later attempt cannot replace them.
|
||||
const staging = path.join(root, 'output/installer-build', next.version, new Date().toISOString().replaceAll(':', '-'));
|
||||
await fs.mkdir(staging, { recursive: true });
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
|
||||
let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8');
|
||||
for (const [key, value] of Object.entries({ RUNESTONE_VERSION: next.version, RUNESTONE_WINDOWS_VERSION: next.windows,
|
||||
RUNESTONE_COMPARE: path.join(root, 'src-tauri/windows/versionCompare.nsh') })) {
|
||||
if (!template.includes(`@${key}@`)) throw Error('The installer template is missing ' + key);
|
||||
template = template.replaceAll(`@${key}@`, value);
|
||||
|
||||
// The commands of a build, in order. overridePath is the file with plan.override.
|
||||
export function buildCommands(plan, overridePath) {
|
||||
const cli = path.join(plan.root, 'node_modules/@tauri-apps/cli/tauri.js');
|
||||
return [
|
||||
{ step: 'compile', command: process.execPath, args: [cli, 'build', '--no-bundle', '--config', overridePath, '--', '--locked'] },
|
||||
{ step: 'version-resource', command: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||
path.join(plan.root, 'scripts/setWindowsVersion.ps1'), '-Path', path.join(plan.root, 'src-tauri/target/release/runestone.exe'),
|
||||
'-Version', plan.next.version, '-NumericVersion', plan.next.windows] },
|
||||
{ step: 'bundle', command: process.execPath, args: [cli, 'bundle', '--bundles', 'nsis', '--config', overridePath] },
|
||||
];
|
||||
}
|
||||
const templatePath = path.join(staging, 'installer.nsi');
|
||||
await fs.writeFile(templatePath, template);
|
||||
const override = path.join(staging, 'config.json');
|
||||
await fs.writeFile(override, JSON.stringify({ bundle: { windows: { allowDowngrades: false, nsis: { template: templatePath } } } }));
|
||||
const packageJson = JSON.parse(before[0]);
|
||||
packageJson.version = next.version;
|
||||
config.version = next.toolchain;
|
||||
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
|
||||
if (/\[package\.metadata\.runestone\]/.test(cargo)) {
|
||||
cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
|
||||
} else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
|
||||
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
|
||||
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
|
||||
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
|
||||
// Ctrl+C also stops the child build. Keep this process alive so that the version files are restored.
|
||||
let interrupted = false;
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; });
|
||||
async function run(command, parameters) {
|
||||
|
||||
export function describePlan(plan, overridePath = '<attempt folder>/tauri.version.json') {
|
||||
const relative = file => path.relative(plan.root, file);
|
||||
return [
|
||||
`Release version: ${plan.next.version} (current ${plan.current.version})`,
|
||||
`Toolchain version: ${plan.next.toolchain}. Windows version: ${plan.next.windows}.`,
|
||||
`Configuration override: ${JSON.stringify(plan.override)}`,
|
||||
`1. Write version ${plan.next.version} to package.json. The front-end build reads it. A failed build restores it.`,
|
||||
...buildCommands(plan, overridePath).map((entry, index) => `${index + 2}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
|
||||
`5. Move the setup file to ${relative(plan.artifacts.release)} and write ${relative(plan.artifacts.metadata)}.`,
|
||||
`6. Write the new version to ${versionFiles.slice(1).join(', ')}.`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// Runs the build. run(command, args) must reject when a command fails.
|
||||
// The tracked version files change only when the build completes, except package.json during the build.
|
||||
export async function runInstallerBuild(plan, run, staging) {
|
||||
const { files, before, updated, artifacts } = plan;
|
||||
await fs.mkdir(staging, { recursive: true });
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
|
||||
const overridePath = path.join(staging, 'tauri.version.json');
|
||||
await fs.writeFile(overridePath, JSON.stringify(plan.override, null, 2) + '\n');
|
||||
let complete = false;
|
||||
try {
|
||||
// src/lib/layout/SettingsDialog.svelte imports the version from package.json.
|
||||
await fs.writeFile(files[0], updated[0]);
|
||||
for (const { command, args } of buildCommands(plan, overridePath)) await run(command, args);
|
||||
await fs.access(artifacts.bundled);
|
||||
if (artifacts.bundled !== artifacts.renamed) await fs.rename(artifacts.bundled, artifacts.renamed);
|
||||
await fs.mkdir(plan.releaseDir, { recursive: true });
|
||||
await fs.copyFile(artifacts.renamed, artifacts.release, fs.constants.COPYFILE_EXCL);
|
||||
const bytes = await fs.readFile(artifacts.release);
|
||||
const metadata = { version: plan.next.version, toolchainVersion: plan.next.toolchain, windowsVersion: plan.next.windows,
|
||||
file: path.basename(artifacts.release), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
await fs.writeFile(artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
await fs.unlink(artifacts.renamed);
|
||||
for (let i = 1; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
|
||||
complete = true;
|
||||
return artifacts.release;
|
||||
} finally {
|
||||
if (!complete) {
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
if ((await fs.readFile(files[i], 'utf8').catch(() => null)) !== before[i]) await fs.writeFile(files[i], before[i]);
|
||||
}
|
||||
for (const file of new Set(Object.values(artifacts))) {
|
||||
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
||||
}
|
||||
console.error('The build did not complete. The version fields are restored. Backups: ' + staging);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const options = parseArguments(process.argv.slice(2));
|
||||
const plan = await planInstallerBuild(root, options.version);
|
||||
if (options.dryRun) {
|
||||
console.log(describePlan(plan));
|
||||
return;
|
||||
}
|
||||
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
||||
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
|
||||
// Ctrl+C also stops the child build. Keep this process alive so that package.json is restored.
|
||||
let interrupted = false;
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; });
|
||||
async function run(command, parameters) {
|
||||
if (interrupted) throw Error('The build was interrupted.');
|
||||
console.log(command + ' ' + parameters.join(' '));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
@@ -69,32 +149,11 @@ async function run(command, parameters) {
|
||||
});
|
||||
if (interrupted) throw Error('The build was interrupted.');
|
||||
if (code !== 0) throw Error('The build command failed with exit code ' + code);
|
||||
}
|
||||
let complete = false;
|
||||
try {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
|
||||
const cli = path.join(root, 'node_modules/@tauri-apps/cli/tauri.js');
|
||||
await run(process.execPath, [cli, 'build', '--no-bundle', '--', '--locked']);
|
||||
await run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/setWindowsVersion.ps1'),
|
||||
'-Path', path.join(root, 'src-tauri/target/release/runestone.exe'), '-Version', next.version, '-NumericVersion', next.windows]);
|
||||
await run(process.execPath, [cli, 'bundle', '--bundles', 'nsis', '--config', override]);
|
||||
await fs.access(internalArtifact);
|
||||
if (internalArtifact !== artifact) await fs.rename(internalArtifact, artifact);
|
||||
await fs.mkdir(releaseDir, { recursive: true });
|
||||
await fs.copyFile(artifact, releaseArtifact, 1);
|
||||
const bytes = await fs.readFile(releaseArtifact);
|
||||
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
|
||||
file: path.basename(releaseArtifact), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
await fs.unlink(artifact);
|
||||
complete = true;
|
||||
console.log('Installer available: ' + releaseArtifact);
|
||||
} finally {
|
||||
if (!complete) {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
|
||||
console.error('The build did not complete. The version fields are restored. Backups: ' + staging);
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
|
||||
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
||||
}
|
||||
}
|
||||
// Each attempt keeps its own backups, so a later attempt cannot replace them.
|
||||
const staging = path.join(root, 'output/installer-build', plan.next.version, new Date().toISOString().replaceAll(':', '-'));
|
||||
const installer = await runInstallerBuild(plan, run, staging);
|
||||
console.log('Installer available: ' + installer);
|
||||
}
|
||||
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) await main();
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
"installMode": "currentUser",
|
||||
"installerIcon": "icons/icon.ico",
|
||||
"uninstallerIcon": "icons/icon.ico",
|
||||
"compression": "lzma"
|
||||
"compression": "lzma",
|
||||
"installerHooks": "./windows/hooks.nsh"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,231 @@
|
||||
; RuneStone hooks for the stock Tauri NSIS template.
|
||||
; tauri.windows.conf.json names this file in bundle.windows.nsis.installerHooks.
|
||||
;
|
||||
; Tauri includes this file before the variables, pages, and sections of its template.
|
||||
; Thus only the NSIS_HOOK_* macros can use template symbols such as ${VERSION} or $UpdateMode.
|
||||
; The other code reads the version of this installer from its own version resource.
|
||||
;
|
||||
; Tauri accepts only SemVer, so scripts/releaseVersion.mjs encodes the hotfix 0.1.23a
|
||||
; as the toolchain version 0.1.23+1. Tauri writes the Windows version 0.1.23.1 into the
|
||||
; version resource. ${VersionCompare} on Windows versions gives the release order
|
||||
; 0.1.23 < 0.1.23a < 0.1.23z < 0.1.23aa < 0.1.24.
|
||||
|
||||
!include LogicLib.nsh
|
||||
!include WordFunc.nsh
|
||||
|
||||
; RuneStone installs for the current user (installMode "currentUser"), so SHCTX is HKCU.
|
||||
; This key must agree with UNINSTKEY in the Tauri template and with productName.
|
||||
!define /ifndef RUNESTONE_UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\RuneStone"
|
||||
|
||||
!ifmacrondef RUNESTONE_DOWNGRADE_NOTICE
|
||||
!macro RUNESTONE_DOWNGRADE_NOTICE
|
||||
${IfNot} ${Silent}
|
||||
MessageBox MB_ICONSTOP|MB_OK "A newer version of RuneStone is installed. This installer cannot replace it."
|
||||
${EndIf}
|
||||
!macroend
|
||||
!endif
|
||||
|
||||
; Converts a version to four numbers: 1.2.3 gives 1.2.3.0, and 1.2.3+4 or 1.2.3.4 gives 1.2.3.4.
|
||||
; Returns an empty string for other forms and for numbers above 65535.
|
||||
Function RuneStoneNumericVersion
|
||||
Exch $0 ; Input, then the result
|
||||
Push $1 ; Result so far
|
||||
Push $2 ; Character index
|
||||
Push $3 ; Character
|
||||
Push $4 ; Separators so far
|
||||
Push $5 ; Digits in the current number
|
||||
Push $6 ; Value of the current number
|
||||
Push $7 ; Value of the character
|
||||
StrCpy $1 ""
|
||||
StrCpy $2 0
|
||||
StrCpy $4 0
|
||||
StrCpy $5 0
|
||||
StrCpy $6 0
|
||||
loop:
|
||||
StrCpy $3 $0 1 $2
|
||||
IntOp $2 $2 + 1
|
||||
StrCmp $3 "" end
|
||||
StrCmp $3 "." separator
|
||||
StrCmp $3 "+" build
|
||||
; Only a digit gives the same text after the conversion to a number.
|
||||
IntOp $7 $3 + 0
|
||||
StrCmp $7 $3 0 invalid
|
||||
IntOp $6 $6 * 10
|
||||
IntOp $6 $6 + $7
|
||||
IntCmp $6 65535 0 0 invalid
|
||||
IntOp $5 $5 + 1
|
||||
StrCpy $1 "$1$3"
|
||||
Goto loop
|
||||
build:
|
||||
; A SemVer build number can follow only the third number.
|
||||
IntCmp $4 2 separator invalid invalid
|
||||
separator:
|
||||
IntCmp $5 0 invalid
|
||||
IntCmp $4 3 invalid
|
||||
IntOp $4 $4 + 1
|
||||
StrCpy $1 "$1."
|
||||
StrCpy $5 0
|
||||
StrCpy $6 0
|
||||
Goto loop
|
||||
end:
|
||||
IntCmp $5 0 invalid
|
||||
; Two separators need a fourth number. The separator check above allows at most three.
|
||||
IntCmp $4 2 0 invalid valid
|
||||
StrCpy $1 "$1.0"
|
||||
valid:
|
||||
StrCpy $0 $1
|
||||
Goto finish
|
||||
invalid:
|
||||
StrCpy $0 ""
|
||||
finish:
|
||||
Pop $7
|
||||
Pop $6
|
||||
Pop $5
|
||||
Pop $4
|
||||
Pop $3
|
||||
Pop $2
|
||||
Pop $1
|
||||
Exch $0
|
||||
FunctionEnd
|
||||
|
||||
; Converts a Windows version to the release version: 0.1.23.0 gives 0.1.23,
|
||||
; 0.1.23.1 gives 0.1.23a, and 0.1.23.27 gives 0.1.23aa.
|
||||
Function RuneStoneReleaseName
|
||||
Exch $0 ; Input, then the result
|
||||
Push $1 ; Character index
|
||||
Push $2 ; Character
|
||||
Push $3 ; Revision
|
||||
Push $4 ; Letter suffix
|
||||
StrLen $1 $0
|
||||
find_dot:
|
||||
IntOp $1 $1 - 1
|
||||
IntCmp $1 0 0 finish
|
||||
StrCpy $2 $0 1 $1
|
||||
StrCmp $2 "." 0 find_dot
|
||||
IntOp $2 $1 + 1
|
||||
StrCpy $3 $0 "" $2
|
||||
StrCpy $0 $0 $1
|
||||
StrCpy $4 ""
|
||||
letters:
|
||||
IntCmp $3 0 letters_done letters_done
|
||||
IntOp $3 $3 - 1
|
||||
IntOp $2 $3 % 26
|
||||
StrCpy $2 "abcdefghijklmnopqrstuvwxyz" 1 $2
|
||||
StrCpy $4 "$2$4"
|
||||
IntOp $3 $3 / 26
|
||||
Goto letters
|
||||
letters_done:
|
||||
StrCpy $0 "$0$4"
|
||||
finish:
|
||||
Pop $4
|
||||
Pop $3
|
||||
Pop $2
|
||||
Pop $1
|
||||
Exch $0
|
||||
FunctionEnd
|
||||
|
||||
; Returns the Windows version of this installer from its version resource, or an empty string.
|
||||
Function RuneStoneInstallerVersion
|
||||
Push $0
|
||||
Push $1
|
||||
Push $2
|
||||
Push $3
|
||||
ClearErrors
|
||||
GetDLLVersion "$EXEPATH" $0 $1
|
||||
${If} ${Errors}
|
||||
StrCpy $0 ""
|
||||
${Else}
|
||||
IntOp $2 $0 >> 16
|
||||
IntOp $2 $2 & 0xFFFF
|
||||
IntOp $0 $0 & 0xFFFF
|
||||
IntOp $3 $1 >> 16
|
||||
IntOp $3 $3 & 0xFFFF
|
||||
IntOp $1 $1 & 0xFFFF
|
||||
StrCpy $0 "$2.$0.$3.$1"
|
||||
${EndIf}
|
||||
Pop $3
|
||||
Pop $2
|
||||
Pop $1
|
||||
Exch $0
|
||||
FunctionEnd
|
||||
|
||||
; Returns the installed Windows version, an empty string when RuneStone is not installed,
|
||||
; or "unknown" when the installed value has an unknown form.
|
||||
Function RuneStoneInstalledVersion
|
||||
Push $0
|
||||
ReadRegStr $0 SHCTX "${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion"
|
||||
${If} $0 == ""
|
||||
; Earlier installers wrote only the toolchain version, such as 0.1.23+1, to DisplayVersion.
|
||||
ReadRegStr $0 SHCTX "${RUNESTONE_UNINSTKEY}" "DisplayVersion"
|
||||
${EndIf}
|
||||
${If} $0 != ""
|
||||
Push $0
|
||||
Call RuneStoneNumericVersion
|
||||
Pop $0
|
||||
${IfThen} $0 == "" ${|} StrCpy $0 "unknown" ${|}
|
||||
${EndIf}
|
||||
Exch $0
|
||||
FunctionEnd
|
||||
|
||||
; Stops setup with exit code 2 when the installed version is newer or unknown.
|
||||
Function RuneStoneCheckDowngrade
|
||||
Push $0
|
||||
Push $1
|
||||
Push $2
|
||||
Call RuneStoneInstalledVersion
|
||||
Pop $0
|
||||
${If} $0 != ""
|
||||
Call RuneStoneInstallerVersion
|
||||
Pop $1
|
||||
StrCpy $2 2
|
||||
${If} $0 != "unknown"
|
||||
${AndIf} $1 != ""
|
||||
${VersionCompare} $1 $0 $2
|
||||
${EndIf}
|
||||
${If} $2 = 2
|
||||
!insertmacro RUNESTONE_DOWNGRADE_NOTICE
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
Pop $2
|
||||
Pop $1
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
; Interactive and passive (/P) setup: Modern UI calls this function before the first page.
|
||||
!define MUI_CUSTOMFUNCTION_GUIINIT RuneStoneGuiInit
|
||||
Function RuneStoneGuiInit
|
||||
Call RuneStoneCheckDowngrade
|
||||
; The stock maintenance page looks for an installation in SHCTX. For an upgrade, it
|
||||
; preselects "Uninstall before installing". In the "all" context, SHCTX is HKLM, where
|
||||
; a current-user installation has no key. Thus the page skips itself, and setup replaces
|
||||
; the app in place. The RuneStoneVersionCheck section restores the current-user context
|
||||
; before any other section runs.
|
||||
SetShellVarContext all
|
||||
FunctionEnd
|
||||
|
||||
; All modes, also silent (/S): Tauri includes this file before its own sections,
|
||||
; so this section runs first. Silent setup shows no pages and does not call RuneStoneGuiInit.
|
||||
Section "-RuneStoneVersionCheck"
|
||||
SetShellVarContext current
|
||||
Call RuneStoneCheckDowngrade
|
||||
SectionEnd
|
||||
|
||||
; The stock template writes the toolchain version to DisplayVersion before this hook.
|
||||
!macro NSIS_HOOK_POSTINSTALL
|
||||
Push $0
|
||||
Push $1
|
||||
Call RuneStoneInstallerVersion
|
||||
Pop $0
|
||||
Push $0
|
||||
Call RuneStoneReleaseName
|
||||
Pop $1
|
||||
; Windows shows DisplayVersion in installed apps.
|
||||
WriteRegStr SHCTX "${RUNESTONE_UNINSTKEY}" "DisplayVersion" "$1"
|
||||
WriteRegStr SHCTX "${RUNESTONE_UNINSTKEY}" "RuneStoneReleaseVersion" "$1"
|
||||
; Later installers compare this value.
|
||||
WriteRegStr SHCTX "${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion" "$0"
|
||||
Pop $1
|
||||
Pop $0
|
||||
!macroend
|
||||
@@ -1,996 +0,0 @@
|
||||
; RuneStone template, adapted from Tauri CLI 2.11.4 (Apache-2.0 OR MIT).
|
||||
; https://github.com/tauri-apps/tauri/blob/tauri-cli-v2.11.4/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi
|
||||
Unicode true
|
||||
ManifestDPIAware true
|
||||
; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`)
|
||||
; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see
|
||||
; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300
|
||||
; https://github.com/tauri-apps/tauri/pull/10106
|
||||
ManifestDPIAwareness PerMonitorV2
|
||||
|
||||
!if "{{compression}}" == "none"
|
||||
SetCompress off
|
||||
!else
|
||||
; Set the compression algorithm. We default to LZMA.
|
||||
SetCompressor /SOLID "{{compression}}"
|
||||
!endif
|
||||
|
||||
; Keep above !include to stay ahead of any plugin command
|
||||
; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624
|
||||
{{#if signed_plugins_path}}
|
||||
!addplugindir "{{signed_plugins_path}}"
|
||||
{{/if}}
|
||||
|
||||
!include MUI2.nsh
|
||||
!include FileFunc.nsh
|
||||
!include x64.nsh
|
||||
!include WordFunc.nsh
|
||||
!include "utils.nsh"
|
||||
!include "FileAssociation.nsh"
|
||||
!include "Win\COM.nsh"
|
||||
!include "Win\Propkey.nsh"
|
||||
!include "StrFunc.nsh"
|
||||
${StrCase}
|
||||
${StrLoc}
|
||||
|
||||
{{#if installer_hooks}}
|
||||
!include "{{installer_hooks}}"
|
||||
{{/if}}
|
||||
|
||||
!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
|
||||
|
||||
!define MANUFACTURER "{{manufacturer}}"
|
||||
!define PRODUCTNAME "{{product_name}}"
|
||||
!define TOOLCHAINVERSION "{{version}}"
|
||||
!define VERSION "@RUNESTONE_VERSION@"
|
||||
!define VERSIONWITHBUILD "@RUNESTONE_WINDOWS_VERSION@"
|
||||
!include "@RUNESTONE_COMPARE@"
|
||||
!define HOMEPAGE "{{homepage}}"
|
||||
!define INSTALLMODE "{{install_mode}}"
|
||||
!define LICENSE "{{license}}"
|
||||
!define INSTALLERICON "{{installer_icon}}"
|
||||
!define SIDEBARIMAGE "{{sidebar_image}}"
|
||||
!define HEADERIMAGE "{{header_image}}"
|
||||
!define UNINSTALLERICON "{{uninstaller_icon}}"
|
||||
!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}"
|
||||
!define MAINBINARYNAME "{{main_binary_name}}"
|
||||
!define MAINBINARYSRCPATH "{{main_binary_path}}"
|
||||
!define BUNDLEID "{{bundle_id}}"
|
||||
!define COPYRIGHT "{{copyright}}"
|
||||
!define OUTFILE "{{out_file}}"
|
||||
!define ARCH "{{arch}}"
|
||||
!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}"
|
||||
!define ALLOWDOWNGRADES "{{allow_downgrades}}"
|
||||
!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}"
|
||||
!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}"
|
||||
!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}"
|
||||
!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}"
|
||||
!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}"
|
||||
!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}"
|
||||
!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"
|
||||
!define MANUKEY "Software\${MANUFACTURER}"
|
||||
!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}"
|
||||
!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}"
|
||||
!define ESTIMATEDSIZE "{{estimated_size}}"
|
||||
!define STARTMENUFOLDER "{{start_menu_folder}}"
|
||||
|
||||
Var PassiveMode
|
||||
Var UpdateMode
|
||||
Var NoShortcutMode
|
||||
Var WixMode
|
||||
Var OldMainBinaryName
|
||||
|
||||
Name "${PRODUCTNAME}"
|
||||
BrandingText "${COPYRIGHT}"
|
||||
OutFile "${OUTFILE}"
|
||||
|
||||
; We don't actually use this value as default install path,
|
||||
; it's just for nsis to append the product name folder in the directory selector
|
||||
; https://nsis.sourceforge.io/Reference/InstallDir
|
||||
!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}"
|
||||
InstallDir "${PLACEHOLDER_INSTALL_DIR}"
|
||||
|
||||
VIProductVersion "${VERSIONWITHBUILD}"
|
||||
VIAddVersionKey "ProductName" "${PRODUCTNAME}"
|
||||
VIAddVersionKey "FileDescription" "${PRODUCTNAME}"
|
||||
VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"
|
||||
VIAddVersionKey "FileVersion" "${VERSION}"
|
||||
VIAddVersionKey "ProductVersion" "${VERSION}"
|
||||
|
||||
# additional plugins
|
||||
!addplugindir "${ADDITIONALPLUGINSPATH}"
|
||||
|
||||
; Uninstaller signing command
|
||||
!if "${UNINSTALLERSIGNCOMMAND}" != ""
|
||||
!uninstfinalize '${UNINSTALLERSIGNCOMMAND}'
|
||||
!endif
|
||||
|
||||
; Handle install mode, `perUser`, `perMachine` or `both`
|
||||
!if "${INSTALLMODE}" == "perMachine"
|
||||
RequestExecutionLevel admin
|
||||
!endif
|
||||
|
||||
!if "${INSTALLMODE}" == "currentUser"
|
||||
RequestExecutionLevel user
|
||||
!endif
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!define MULTIUSER_MUI
|
||||
!define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"
|
||||
!define MULTIUSER_INSTALLMODE_COMMANDLINE
|
||||
!if "${ARCH}" == "x64"
|
||||
!define MULTIUSER_USE_PROGRAMFILES64
|
||||
!else if "${ARCH}" == "arm64"
|
||||
!define MULTIUSER_USE_PROGRAMFILES64
|
||||
!endif
|
||||
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"
|
||||
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser"
|
||||
!define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME
|
||||
!define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation
|
||||
!define MULTIUSER_EXECUTIONLEVEL Highest
|
||||
!include MultiUser.nsh
|
||||
!endif
|
||||
|
||||
; Installer icon
|
||||
!if "${INSTALLERICON}" != ""
|
||||
!define MUI_ICON "${INSTALLERICON}"
|
||||
!endif
|
||||
|
||||
; Installer sidebar image
|
||||
!if "${SIDEBARIMAGE}" != ""
|
||||
!define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"
|
||||
!endif
|
||||
|
||||
; Enable header images for installer and uninstaller pages when either image is configured.
|
||||
!if "${HEADERIMAGE}" != ""
|
||||
!define MUI_HEADERIMAGE
|
||||
!else if "${UNINSTALLERHEADERIMAGE}" != ""
|
||||
!define MUI_HEADERIMAGE
|
||||
!endif
|
||||
|
||||
; Installer header image
|
||||
!if "${HEADERIMAGE}" != ""
|
||||
!define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"
|
||||
!endif
|
||||
|
||||
; Uninstaller header image
|
||||
!if "${UNINSTALLERHEADERIMAGE}" != ""
|
||||
!define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}"
|
||||
!endif
|
||||
|
||||
; Uninstaller icon
|
||||
!if "${UNINSTALLERICON}" != ""
|
||||
!define MUI_UNICON "${UNINSTALLERICON}"
|
||||
!endif
|
||||
|
||||
; Define registry key to store installer language
|
||||
!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
|
||||
!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"
|
||||
!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
|
||||
|
||||
; Installer pages, must be ordered as they appear
|
||||
; 1. Welcome Page
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
|
||||
; 2. License Page (if defined)
|
||||
!if "${LICENSE}" != ""
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_LICENSE "${LICENSE}"
|
||||
!endif
|
||||
|
||||
; 3. Install mode (if it is set to `both`)
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MULTIUSER_PAGE_INSTALLMODE
|
||||
!endif
|
||||
|
||||
; 4. Custom page to ask user if he wants to reinstall/uninstall
|
||||
; only if a previous installation was detected
|
||||
Var ReinstallPageCheck
|
||||
Page custom PageReinstall PageLeaveReinstall
|
||||
Function PageReinstall
|
||||
; Uninstall previous WiX installation if exists.
|
||||
;
|
||||
; A WiX installer stores the installation info in registry
|
||||
; using a UUID and so we have to loop through all keys under
|
||||
; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`
|
||||
; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}
|
||||
;
|
||||
; This has a potential issue that there maybe another installation that matches
|
||||
; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,
|
||||
; however, this should be fine since the user will have to confirm the uninstallation
|
||||
; and they can chose to abort it if doesn't make sense.
|
||||
StrCpy $0 0
|
||||
wix_loop:
|
||||
EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0
|
||||
StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on
|
||||
IntOp $0 $0 + 1
|
||||
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"
|
||||
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"
|
||||
StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop
|
||||
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"
|
||||
${StrCase} $R1 $R0 "L"
|
||||
${StrLoc} $R0 $R1 "msiexec" ">"
|
||||
StrCmp $R0 0 0 wix_loop_done
|
||||
StrCpy $WixMode 1
|
||||
StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"
|
||||
Goto compare_version
|
||||
wix_loop_done:
|
||||
|
||||
; Check if there is an existing installation, if not, abort the reinstall page
|
||||
ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""
|
||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||
${IfThen} "$R0$R1" == "" ${|} Abort ${|}
|
||||
|
||||
; Compare this installar version with the existing installation
|
||||
; and modify the messages presented to the user accordingly
|
||||
compare_version:
|
||||
StrCpy $R4 "$(older)"
|
||||
${If} $WixMode = 1
|
||||
ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
|
||||
${Else}
|
||||
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "RuneStoneReleaseVersion"
|
||||
${If} $R0 == ""
|
||||
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
|
||||
|
||||
Push "${VERSION}"
|
||||
Push $R0
|
||||
Call RuneStoneCompareVersions
|
||||
Pop $R0
|
||||
!if "${ALLOWDOWNGRADES}" == "false"
|
||||
${If} $R0 = -1
|
||||
${IfNot} ${Silent}
|
||||
MessageBox MB_ICONSTOP "$(dontUninstallDowngrade)"
|
||||
${EndIf}
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
${EndIf}
|
||||
!endif
|
||||
; Reinstalling the same version
|
||||
${If} $R0 = 0
|
||||
StrCpy $R1 "$(alreadyInstalledLong)"
|
||||
StrCpy $R2 "$(addOrReinstall)"
|
||||
StrCpy $R3 "$(uninstallApp)"
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"
|
||||
; Upgrading
|
||||
${ElseIf} $R0 = 1
|
||||
StrCpy $R1 "$(olderOrUnknownVersionInstalled)"
|
||||
StrCpy $R2 "$(addOrReinstall)"
|
||||
StrCpy $R3 "$(uninstallApp)"
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
|
||||
; Downgrading
|
||||
${ElseIf} $R0 = -1
|
||||
StrCpy $R1 "$(newerVersionInstalled)"
|
||||
StrCpy $R2 "$(uninstallBeforeInstalling)"
|
||||
!if "${ALLOWDOWNGRADES}" == "true"
|
||||
StrCpy $R3 "$(dontUninstall)"
|
||||
!else
|
||||
StrCpy $R3 "$(dontUninstallDowngrade)"
|
||||
!endif
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
|
||||
${Else}
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
; Skip showing the page if passive
|
||||
;
|
||||
; Note that we don't call this earlier at the begining
|
||||
; of this function because we need to populate some variables
|
||||
; related to current installed version if detected and whether
|
||||
; we are downgrading or not.
|
||||
${If} $PassiveMode = 1
|
||||
Call PageLeaveReinstall
|
||||
${Else}
|
||||
nsDialogs::Create 1018
|
||||
Pop $R4
|
||||
${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
|
||||
|
||||
${NSD_CreateLabel} 0 0 100% 24u $R1
|
||||
Pop $R1
|
||||
|
||||
${NSD_CreateRadioButton} 30u 50u -30u 8u $R2
|
||||
Pop $R2
|
||||
${NSD_OnClick} $R2 PageReinstallUpdateSelection
|
||||
|
||||
${NSD_CreateRadioButton} 30u 70u -30u 8u $R3
|
||||
Pop $R3
|
||||
; Disable this radio button if downgrading and downgrades are disabled
|
||||
!if "${ALLOWDOWNGRADES}" == "false"
|
||||
${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|}
|
||||
!endif
|
||||
${NSD_OnClick} $R3 PageReinstallUpdateSelection
|
||||
|
||||
; Check the first radio button if this the first time
|
||||
; we enter this page or if the second button wasn't
|
||||
; selected the last time we were on this page
|
||||
${If} $ReinstallPageCheck <> 2
|
||||
SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${Else}
|
||||
SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${EndIf}
|
||||
|
||||
${NSD_SetFocus} $R2
|
||||
nsDialogs::Show
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
Function PageReinstallUpdateSelection
|
||||
${NSD_GetState} $R2 $R1
|
||||
${If} $R1 == ${BST_CHECKED}
|
||||
StrCpy $ReinstallPageCheck 1
|
||||
${Else}
|
||||
StrCpy $ReinstallPageCheck 2
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
Function PageLeaveReinstall
|
||||
${NSD_GetState} $R2 $R1
|
||||
|
||||
; If migrating from Wix, always uninstall
|
||||
${If} $WixMode = 1
|
||||
Goto reinst_uninstall
|
||||
${EndIf}
|
||||
|
||||
; In update mode, always proceeds without uninstalling
|
||||
${If} $UpdateMode = 1
|
||||
Goto reinst_done
|
||||
${EndIf}
|
||||
|
||||
; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version
|
||||
; $R1 holds the radio buttons state:
|
||||
; 1 => first choice was selected
|
||||
; 0 => second choice was selected
|
||||
${If} $R0 = 0 ; Same version, proceed
|
||||
${If} $R1 = 1 ; User chose to add/reinstall
|
||||
Goto reinst_done
|
||||
${Else} ; User chose to uninstall
|
||||
Goto reinst_uninstall
|
||||
${EndIf}
|
||||
${ElseIf} $R0 = 1 ; Upgrading
|
||||
${If} $R1 = 1
|
||||
Goto reinst_done
|
||||
${Else}
|
||||
Goto reinst_uninstall
|
||||
${EndIf}
|
||||
${ElseIf} $R0 = -1 ; Downgrading
|
||||
${If} $R1 = 1 ; User chose to uninstall
|
||||
Goto reinst_uninstall
|
||||
${Else}
|
||||
Goto reinst_done ; User chose NOT to uninstall
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
reinst_uninstall:
|
||||
HideWindow
|
||||
ClearErrors
|
||||
|
||||
${If} $WixMode = 1
|
||||
ReadRegStr $R1 HKLM "$R6" "UninstallString"
|
||||
ExecWait '$R1' $0
|
||||
${Else}
|
||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
||||
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
||||
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
||||
ExecWait '$R1' $0
|
||||
${EndIf}
|
||||
|
||||
BringToFront
|
||||
|
||||
${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code
|
||||
|
||||
${If} $0 <> 0
|
||||
${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
; User cancelled wix uninstaller? return to select un/reinstall page
|
||||
${If} $WixMode = 1
|
||||
${AndIf} $0 = 1602
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
; User cancelled NSIS uninstaller? return to select un/reinstall page
|
||||
${If} $0 = 1
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
; Other erros? show generic error message and return to select un/reinstall page
|
||||
MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)"
|
||||
Abort
|
||||
${EndIf}
|
||||
reinst_done:
|
||||
FunctionEnd
|
||||
|
||||
; 5. Choose install directory page
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
|
||||
; 6. Start menu shortcut page
|
||||
Var AppStartMenuFolder
|
||||
!if "${STARTMENUFOLDER}" != ""
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}"
|
||||
!else
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE Skip
|
||||
!endif
|
||||
!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
|
||||
|
||||
; 7. Installation page
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
|
||||
; 8. Finish page
|
||||
;
|
||||
; Don't auto jump to finish page after installation page,
|
||||
; because the installation page has useful info that can be used debug any issues with the installer.
|
||||
!define MUI_FINISHPAGE_NOAUTOCLOSE
|
||||
; Use show readme button in the finish page as a button create a desktop shortcut
|
||||
!define MUI_FINISHPAGE_SHOWREADME
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut
|
||||
; Show run app after installation.
|
||||
!define MUI_FINISHPAGE_RUN
|
||||
!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
Function RunMainBinary
|
||||
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""
|
||||
FunctionEnd
|
||||
|
||||
; Uninstaller Pages
|
||||
; 1. Confirm uninstall page
|
||||
Var DeleteAppDataCheckbox
|
||||
Var DeleteAppDataCheckboxState
|
||||
!define /ifndef WS_EX_LAYOUTRTL 0x00400000
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
|
||||
Function un.ConfirmShow ; Add add a `Delete app data` check box
|
||||
; $1 inner dialog HWND
|
||||
; $2 window DPI
|
||||
; $3 style
|
||||
; $4 x
|
||||
; $5 y
|
||||
; $6 width
|
||||
; $7 height
|
||||
FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
|
||||
System::Call "user32::GetDpiForWindow(p r1) i .r2"
|
||||
${If} $(^RTL) = 1
|
||||
StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"
|
||||
IntOp $4 50 * $2
|
||||
${Else}
|
||||
StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"
|
||||
IntOp $4 0 * $2
|
||||
${EndIf}
|
||||
IntOp $5 100 * $2
|
||||
IntOp $6 400 * $2
|
||||
IntOp $7 25 * $2
|
||||
IntOp $4 $4 / 96
|
||||
IntOp $5 $5 / 96
|
||||
IntOp $6 $6 / 96
|
||||
IntOp $7 $7 / 96
|
||||
System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'
|
||||
Pop $DeleteAppDataCheckbox
|
||||
SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
|
||||
SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
|
||||
FunctionEnd
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
|
||||
Function un.ConfirmLeave
|
||||
SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
|
||||
FunctionEnd
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
|
||||
; 2. Uninstalling Page
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
;Languages
|
||||
{{#each languages}}
|
||||
!insertmacro MUI_LANGUAGE "{{this}}"
|
||||
{{/each}}
|
||||
!insertmacro MUI_RESERVEFILE_LANGDLL
|
||||
{{#each language_files}}
|
||||
!include "{{this}}"
|
||||
{{/each}}
|
||||
|
||||
Function .onInit
|
||||
${GetOptions} $CMDLINE "/P" $PassiveMode
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $PassiveMode 1
|
||||
${EndIf}
|
||||
|
||||
${GetOptions} $CMDLINE "/NS" $NoShortcutMode
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $NoShortcutMode 1
|
||||
${EndIf}
|
||||
|
||||
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $UpdateMode 1
|
||||
${EndIf}
|
||||
|
||||
!if "${DISPLAYLANGUAGESELECTOR}" == "true"
|
||||
!insertmacro MUI_LANGDLL_DISPLAY
|
||||
!endif
|
||||
|
||||
!insertmacro SetContext
|
||||
|
||||
${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}"
|
||||
; Set default install location
|
||||
!if "${INSTALLMODE}" == "perMachine"
|
||||
${If} ${RunningX64}
|
||||
!if "${ARCH}" == "x64"
|
||||
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
|
||||
!else if "${ARCH}" == "arm64"
|
||||
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
|
||||
!else
|
||||
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
|
||||
!endif
|
||||
${Else}
|
||||
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
|
||||
${EndIf}
|
||||
!else if "${INSTALLMODE}" == "currentUser"
|
||||
StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}"
|
||||
!endif
|
||||
|
||||
Call RestorePreviousInstallLocation
|
||||
${EndIf}
|
||||
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!insertmacro MULTIUSER_INIT
|
||||
!endif
|
||||
FunctionEnd
|
||||
|
||||
|
||||
Section EarlyChecks
|
||||
; Abort silent installer if downgrades is disabled
|
||||
!if "${ALLOWDOWNGRADES}" == "false"
|
||||
${If} ${Silent}
|
||||
; If downgrading
|
||||
${If} $R0 = -1
|
||||
System::Call 'kernel32::AttachConsole(i -1)i.r0'
|
||||
${If} $0 <> 0
|
||||
System::Call 'kernel32::GetStdHandle(i -11)i.r0'
|
||||
System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
|
||||
FileWrite $0 "$(silentDowngrades)"
|
||||
${EndIf}
|
||||
Abort
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
!endif
|
||||
|
||||
SectionEnd
|
||||
|
||||
Section WebView2
|
||||
; Check if Webview2 is already installed and skip this section
|
||||
${If} ${RunningX64}
|
||||
ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
|
||||
${Else}
|
||||
ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
|
||||
${EndIf}
|
||||
${If} $4 == ""
|
||||
ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
|
||||
${EndIf}
|
||||
|
||||
${If} $4 == ""
|
||||
; Webview2 installation
|
||||
;
|
||||
; Skip if updating
|
||||
${If} $UpdateMode <> 1
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"
|
||||
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
DetailPrint "$(webview2Downloading)"
|
||||
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Pop $0
|
||||
${If} $0 == "success"
|
||||
DetailPrint "$(webview2DownloadSuccess)"
|
||||
${Else}
|
||||
DetailPrint "$(webview2DownloadError)"
|
||||
Abort "$(webview2AbortError)"
|
||||
${EndIf}
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"
|
||||
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"
|
||||
DetailPrint "$(installingWebview2)"
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"
|
||||
Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
|
||||
File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"
|
||||
DetailPrint "$(installingWebview2)"
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
Goto webview2_done
|
||||
|
||||
install_webview2:
|
||||
DetailPrint "$(installingWebview2)"
|
||||
; $6 holds the path to the webview2 installer
|
||||
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
|
||||
${If} $1 = 0
|
||||
DetailPrint "$(webview2InstallSuccess)"
|
||||
${Else}
|
||||
DetailPrint "$(webview2InstallError)"
|
||||
Abort "$(webview2AbortError)"
|
||||
${EndIf}
|
||||
webview2_done:
|
||||
${EndIf}
|
||||
${Else}
|
||||
!if "${MINIMUMWEBVIEW2VERSION}" != ""
|
||||
${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0
|
||||
${If} $R0 = 1
|
||||
update_webview:
|
||||
DetailPrint "$(installingWebview2)"
|
||||
${If} ${RunningX64}
|
||||
ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path"
|
||||
${Else}
|
||||
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path"
|
||||
${EndIf}
|
||||
${If} $R1 == ""
|
||||
ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path"
|
||||
${EndIf}
|
||||
${If} $R1 != ""
|
||||
; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md
|
||||
; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
|
||||
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
|
||||
${If} $1 = 0
|
||||
DetailPrint "$(webview2InstallSuccess)"
|
||||
${Else}
|
||||
MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
|
||||
Quit
|
||||
ignore:
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
!endif
|
||||
${EndIf}
|
||||
SectionEnd
|
||||
|
||||
Section Install
|
||||
SetOutPath $INSTDIR
|
||||
|
||||
!ifmacrodef NSIS_HOOK_PREINSTALL
|
||||
!insertmacro NSIS_HOOK_PREINSTALL
|
||||
!endif
|
||||
|
||||
!insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||
|
||||
; Copy main executable
|
||||
File "${MAINBINARYSRCPATH}"
|
||||
|
||||
; Copy resources
|
||||
{{#each resources_dirs}}
|
||||
CreateDirectory "$INSTDIR\\{{this}}"
|
||||
{{/each}}
|
||||
{{#each resources}}
|
||||
File /a "/oname={{this.[1]}}" "{{no-escape @key}}"
|
||||
{{/each}}
|
||||
|
||||
; Copy external binaries
|
||||
{{#each binaries}}
|
||||
File /a "/oname={{this}}" "{{no-escape @key}}"
|
||||
{{/each}}
|
||||
|
||||
; Create file associations
|
||||
{{#each file_associations as |association| ~}}
|
||||
{{#each association.ext as |ext| ~}}
|
||||
!insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""
|
||||
{{/each}}
|
||||
{{/each}}
|
||||
|
||||
; Register deep links
|
||||
{{#each deep_link_protocols as |protocol| ~}}
|
||||
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" ""
|
||||
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol"
|
||||
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0"
|
||||
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
|
||||
{{/each}}
|
||||
|
||||
; Create uninstaller
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
|
||||
; Save $INSTDIR in registry for future installations
|
||||
WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
; Save install mode to be selected by default for the next installation such as updating
|
||||
; or when uninstalling
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1
|
||||
!endif
|
||||
|
||||
; Remove old main binary if it doesn't match new main binary name
|
||||
ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
|
||||
${If} $OldMainBinaryName != ""
|
||||
${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"
|
||||
Delete "$INSTDIR\$OldMainBinaryName"
|
||||
${EndIf}
|
||||
|
||||
; Save current MAINBINARYNAME for future updates
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"
|
||||
|
||||
; Registry information for add/remove programs
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${TOOLCHAINVERSION}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "RuneStoneReleaseVersion" "${VERSION}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"
|
||||
|
||||
${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2
|
||||
IntOp $0 $0 + ${ESTIMATEDSIZE}
|
||||
IntFmt $0 "0x%08X" $0
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0"
|
||||
|
||||
!if "${HOMEPAGE}" != ""
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}"
|
||||
!endif
|
||||
|
||||
; Create start menu shortcut
|
||||
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
|
||||
Call CreateOrUpdateStartMenuShortcut
|
||||
!insertmacro MUI_STARTMENU_WRITE_END
|
||||
|
||||
; Create desktop shortcut for silent and passive installers
|
||||
; because finish page will be skipped
|
||||
${If} $PassiveMode = 1
|
||||
${OrIf} ${Silent}
|
||||
Call CreateOrUpdateDesktopShortcut
|
||||
${EndIf}
|
||||
|
||||
!ifmacrodef NSIS_HOOK_POSTINSTALL
|
||||
!insertmacro NSIS_HOOK_POSTINSTALL
|
||||
!endif
|
||||
|
||||
; Auto close this page for passive mode
|
||||
${If} $PassiveMode = 1
|
||||
SetAutoClose true
|
||||
${EndIf}
|
||||
SectionEnd
|
||||
|
||||
Function .onInstSuccess
|
||||
; Check for `/R` flag only in silent and passive installers because
|
||||
; GUI installer has a toggle for the user to (re)start the app
|
||||
${If} $PassiveMode = 1
|
||||
${OrIf} ${Silent}
|
||||
${GetOptions} $CMDLINE "/R" $R0
|
||||
${IfNot} ${Errors}
|
||||
${GetOptions} $CMDLINE "/ARGS" $R0
|
||||
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function un.onInit
|
||||
!insertmacro SetContext
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!insertmacro MULTIUSER_UNINIT
|
||||
!endif
|
||||
|
||||
!insertmacro MUI_UNGETLANGUAGE
|
||||
|
||||
${GetOptions} $CMDLINE "/P" $PassiveMode
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $PassiveMode 1
|
||||
${EndIf}
|
||||
|
||||
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
|
||||
${IfNot} ${Errors}
|
||||
StrCpy $UpdateMode 1
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Section Uninstall
|
||||
|
||||
!ifmacrodef NSIS_HOOK_PREUNINSTALL
|
||||
!insertmacro NSIS_HOOK_PREUNINSTALL
|
||||
!endif
|
||||
|
||||
!insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||
|
||||
; Delete the app directory and its content from disk
|
||||
; Copy main executable
|
||||
Delete "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
|
||||
; Delete resources
|
||||
{{#each resources}}
|
||||
Delete "$INSTDIR\\{{this.[1]}}"
|
||||
{{/each}}
|
||||
|
||||
; Delete external binaries
|
||||
{{#each binaries}}
|
||||
Delete "$INSTDIR\\{{this}}"
|
||||
{{/each}}
|
||||
|
||||
; Delete app associations
|
||||
{{#each file_associations as |association| ~}}
|
||||
{{#each association.ext as |ext| ~}}
|
||||
!insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}"
|
||||
{{/each}}
|
||||
{{/each}}
|
||||
|
||||
; Delete deep links
|
||||
{{#each deep_link_protocols as |protocol| ~}}
|
||||
ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" ""
|
||||
${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
|
||||
DeleteRegKey SHCTX "Software\Classes\\{{protocol}}"
|
||||
${EndIf}
|
||||
{{/each}}
|
||||
|
||||
|
||||
; Delete uninstaller
|
||||
Delete "$INSTDIR\uninstall.exe"
|
||||
|
||||
{{#each resources_ancestors}}
|
||||
RMDir /REBOOTOK "$INSTDIR\\{{this}}"
|
||||
{{/each}}
|
||||
RMDir "$INSTDIR"
|
||||
|
||||
; Remove shortcuts if not updating
|
||||
${If} $UpdateMode <> 1
|
||||
!insertmacro DeleteAppUserModelId
|
||||
|
||||
; Remove start menu shortcut
|
||||
!insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder
|
||||
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
|
||||
Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
|
||||
RMDir "$SMPROGRAMS\$AppStartMenuFolder"
|
||||
${EndIf}
|
||||
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk"
|
||||
Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk"
|
||||
${EndIf}
|
||||
|
||||
; Remove desktop shortcuts
|
||||
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk"
|
||||
Delete "$DESKTOP\${PRODUCTNAME}.lnk"
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
; Remove registry information for add/remove programs
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
DeleteRegKey SHCTX "${UNINSTKEY}"
|
||||
!else if "${INSTALLMODE}" == "perMachine"
|
||||
DeleteRegKey HKLM "${UNINSTKEY}"
|
||||
!else
|
||||
DeleteRegKey HKCU "${UNINSTKEY}"
|
||||
!endif
|
||||
|
||||
; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists.
|
||||
; This ensures the program does not launch automatically after uninstallation if it exists.
|
||||
; If it doesn't exist, it does nothing.
|
||||
; We do this when not updating (to preserve the registry value on updates)
|
||||
${If} $UpdateMode <> 1
|
||||
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
||||
${EndIf}
|
||||
|
||||
; Delete app data if the checkbox is selected
|
||||
; and if not updating
|
||||
${If} $DeleteAppDataCheckboxState = 1
|
||||
${AndIf} $UpdateMode <> 1
|
||||
; Clear the install location $INSTDIR from registry
|
||||
DeleteRegKey SHCTX "${MANUPRODUCTKEY}"
|
||||
DeleteRegKey /ifempty SHCTX "${MANUKEY}"
|
||||
|
||||
; Clear the install language from registry
|
||||
DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language"
|
||||
DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}"
|
||||
DeleteRegKey /ifempty HKCU "${MANUKEY}"
|
||||
|
||||
SetShellVarContext current
|
||||
RmDir /r "$APPDATA\${BUNDLEID}"
|
||||
RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
|
||||
${EndIf}
|
||||
|
||||
!ifmacrodef NSIS_HOOK_POSTUNINSTALL
|
||||
!insertmacro NSIS_HOOK_POSTUNINSTALL
|
||||
!endif
|
||||
|
||||
; Auto close if passive mode or updating
|
||||
${If} $PassiveMode = 1
|
||||
${OrIf} $UpdateMode = 1
|
||||
SetAutoClose true
|
||||
${EndIf}
|
||||
SectionEnd
|
||||
|
||||
Function RestorePreviousInstallLocation
|
||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||
StrCmp $4 "" +2 0
|
||||
StrCpy $INSTDIR $4
|
||||
FunctionEnd
|
||||
|
||||
Function Skip
|
||||
Abort
|
||||
FunctionEnd
|
||||
|
||||
Function SkipIfPassive
|
||||
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
|
||||
FunctionEnd
|
||||
Function un.SkipIfPassive
|
||||
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
|
||||
FunctionEnd
|
||||
|
||||
Function CreateOrUpdateStartMenuShortcut
|
||||
; We used to use product name as MAINBINARYNAME
|
||||
; migrate old shortcuts to target the new MAINBINARYNAME
|
||||
StrCpy $R0 0
|
||||
|
||||
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
StrCpy $R0 1
|
||||
${EndIf}
|
||||
|
||||
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
StrCpy $R0 1
|
||||
${EndIf}
|
||||
|
||||
${If} $R0 = 1
|
||||
Return
|
||||
${EndIf}
|
||||
|
||||
; Skip creating shortcut if in update mode or no shortcut mode
|
||||
; but always create if migrating from wix
|
||||
${If} $WixMode = 0
|
||||
${If} $UpdateMode = 1
|
||||
${OrIf} $NoShortcutMode = 1
|
||||
Return
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
!if "${STARTMENUFOLDER}" != ""
|
||||
CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"
|
||||
CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
|
||||
!else
|
||||
CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"
|
||||
!endif
|
||||
FunctionEnd
|
||||
|
||||
Function CreateOrUpdateDesktopShortcut
|
||||
; We used to use product name as MAINBINARYNAME
|
||||
; migrate old shortcuts to target the new MAINBINARYNAME
|
||||
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
|
||||
Pop $0
|
||||
${If} $0 = 1
|
||||
!insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
Return
|
||||
${EndIf}
|
||||
|
||||
; Skip creating shortcut if in update mode or no shortcut mode
|
||||
; but always create if migrating from wix
|
||||
${If} $WixMode = 0
|
||||
${If} $UpdateMode = 1
|
||||
${OrIf} $NoShortcutMode = 1
|
||||
Return
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
!insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"
|
||||
FunctionEnd
|
||||
@@ -1,124 +0,0 @@
|
||||
; Compare numeric releases and lowercase hotfix suffixes in release order.
|
||||
; Return an empty string for an invalid version. Callers block that comparison.
|
||||
Function RuneStoneNormalizeVersion
|
||||
Exch $0
|
||||
Push $1
|
||||
Push $2
|
||||
Push $3
|
||||
Push $4
|
||||
Push $5
|
||||
Push $6
|
||||
Push $7
|
||||
Push $8
|
||||
StrCpy $1 ""
|
||||
StrCpy $2 0
|
||||
StrCpy $3 0
|
||||
StrCpy $4 0
|
||||
StrCpy $5 0
|
||||
StrCpy $6 0
|
||||
StrCpy $8 0
|
||||
rs_normalize_loop:
|
||||
StrCpy $7 $0 1 $2
|
||||
StrCmp $7 "" rs_normalize_end
|
||||
IntOp $2 $2 + 1
|
||||
StrCmp $7 "." rs_normalize_dot
|
||||
; Decimal digits cannot follow a letter suffix.
|
||||
StrCmp $7 "0" rs_normalize_digit
|
||||
StrCmp $7 "1" rs_normalize_digit
|
||||
StrCmp $7 "2" rs_normalize_digit
|
||||
StrCmp $7 "3" rs_normalize_digit
|
||||
StrCmp $7 "4" rs_normalize_digit
|
||||
StrCmp $7 "5" rs_normalize_digit
|
||||
StrCmp $7 "6" rs_normalize_digit
|
||||
StrCmp $7 "7" rs_normalize_digit
|
||||
StrCmp $7 "8" rs_normalize_digit
|
||||
StrCmp $7 "9" rs_normalize_digit
|
||||
StrCmp $3 2 0 rs_normalize_invalid
|
||||
StrCmp $4 0 rs_normalize_invalid
|
||||
StrCpy $6 1
|
||||
; Find the lowercase letter's one-based index without locale conversion.
|
||||
Push $0
|
||||
StrCpy $0 0
|
||||
rs_letter_loop:
|
||||
StrCpy $4 "abcdefghijklmnopqrstuvwxyz" 1 $0
|
||||
StrCmpS $7 $4 rs_letter_found
|
||||
IntOp $0 $0 + 1
|
||||
IntCmp $0 26 rs_letter_invalid rs_letter_loop rs_letter_invalid
|
||||
rs_letter_invalid:
|
||||
Pop $0
|
||||
Goto rs_normalize_invalid
|
||||
rs_letter_found:
|
||||
IntOp $0 $0 + 1
|
||||
IntOp $5 $5 * 26
|
||||
IntOp $5 $5 + $0
|
||||
Pop $0
|
||||
IntCmp $5 65535 rs_letter_ok rs_letter_ok rs_normalize_invalid
|
||||
rs_letter_ok:
|
||||
StrCpy $4 1
|
||||
Goto rs_normalize_loop
|
||||
rs_normalize_digit:
|
||||
StrCmp $6 0 0 rs_normalize_invalid
|
||||
IntOp $8 $8 * 10
|
||||
IntOp $8 $8 + $7
|
||||
IntCmp $8 65535 rs_digit_ok rs_digit_ok rs_normalize_invalid
|
||||
rs_digit_ok:
|
||||
StrCpy $1 "$1$7"
|
||||
IntOp $4 $4 + 1
|
||||
Goto rs_normalize_loop
|
||||
rs_normalize_dot:
|
||||
StrCmp $6 0 0 rs_normalize_invalid
|
||||
StrCmp $4 0 rs_normalize_invalid
|
||||
IntOp $3 $3 + 1
|
||||
IntCmp $3 2 rs_dot_ok rs_dot_ok rs_normalize_invalid
|
||||
rs_dot_ok:
|
||||
StrCpy $1 "$1."
|
||||
StrCpy $4 0
|
||||
StrCpy $8 0
|
||||
Goto rs_normalize_loop
|
||||
rs_normalize_end:
|
||||
StrCmp $3 2 0 rs_normalize_invalid
|
||||
StrCmp $4 0 rs_normalize_invalid
|
||||
StrCpy $0 "$1.$5"
|
||||
Goto rs_normalize_return
|
||||
rs_normalize_invalid:
|
||||
StrCpy $0 ""
|
||||
rs_normalize_return:
|
||||
Pop $8
|
||||
Pop $7
|
||||
Pop $6
|
||||
Pop $5
|
||||
Pop $4
|
||||
Pop $3
|
||||
Pop $2
|
||||
Pop $1
|
||||
Exch $0
|
||||
FunctionEnd
|
||||
|
||||
Function RuneStoneCompareVersions
|
||||
Exch $1
|
||||
Exch
|
||||
Exch $0
|
||||
Push $2
|
||||
Push $0
|
||||
Call RuneStoneNormalizeVersion
|
||||
Pop $0
|
||||
Push $1
|
||||
Call RuneStoneNormalizeVersion
|
||||
Pop $1
|
||||
StrCmp $0 "" rs_compare_invalid
|
||||
StrCmp $1 "" rs_compare_invalid
|
||||
${VersionCompare} $0 $1 $2
|
||||
StrCmp $2 2 rs_compare_older
|
||||
StrCpy $0 $2
|
||||
Goto rs_compare_return
|
||||
rs_compare_older:
|
||||
StrCpy $0 -1
|
||||
Goto rs_compare_return
|
||||
rs_compare_invalid:
|
||||
StrCpy $0 -1
|
||||
rs_compare_return:
|
||||
Pop $2
|
||||
Exch $0
|
||||
Exch
|
||||
Pop $1
|
||||
FunctionEnd
|
||||
@@ -0,0 +1,121 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, readFile, writeFile, copyFile, readdir, rm, access } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { buildCommands, describePlan, parseArguments, planInstallerBuild, runInstallerBuild, versionFiles } from '../../../scripts/buildInstaller.mjs';
|
||||
import { nextHotfix, releaseVersion } from '../../../scripts/releaseVersion.mjs';
|
||||
|
||||
const repository = path.resolve('.');
|
||||
const exists = (file: string) => access(file).then(() => true, () => false);
|
||||
|
||||
// A copy of the files that the installer script reads, with a placeholder Browser runtime.
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-build-'));
|
||||
for (const file of [...versionFiles, 'src-tauri/tauri.windows.conf.json', 'src-tauri/windows/hooks.nsh']) {
|
||||
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
|
||||
await copyFile(path.join(repository, file), path.join(root, file));
|
||||
}
|
||||
await mkdir(path.join(root, 'src-tauri/browser-engine'), { recursive: true });
|
||||
await writeFile(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe'), '');
|
||||
const before = await Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
|
||||
const current = releaseVersion(JSON.parse(before[0]).version);
|
||||
return { root, before, current, next: releaseVersion(nextHotfix(current.version)) };
|
||||
}
|
||||
|
||||
const contents = (root: string) => Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
|
||||
|
||||
async function withFixture(body: (setup: Awaited<ReturnType<typeof fixture>>) => Promise<void>) {
|
||||
const setup = await fixture();
|
||||
try { await body(setup); } finally { await rm(setup.root, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
test('the installer script reads --version and --dry-run', () => {
|
||||
assert.deepEqual(parseArguments([]), { version: undefined, dryRun: false });
|
||||
assert.deepEqual(parseArguments(['--version', '0.1.44a', '--dry-run']), { version: '0.1.44a', dryRun: true });
|
||||
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.45']), { version: '0.1.45', dryRun: true });
|
||||
for (const args of [['--version'], ['0.1.45'], ['--version', '0.1.45', '--version', '0.1.46'], ['--force']]) assert.throws(() => parseArguments(args));
|
||||
});
|
||||
|
||||
test('a completed build sets the version fields only after the installer exists', () => withFixture(async ({ root, before, next }) => {
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
assert.deepEqual(await contents(root), before, 'Planning must not change a file.');
|
||||
assert.deepEqual(plan.override, { version: next.toolchain });
|
||||
const plain = describePlan(plan);
|
||||
assert.match(plain, new RegExp(`Configuration override: \\{"version":"${next.toolchain.replace('+', '\\+')}"\\}`));
|
||||
assert.match(plain, /compile: .* build --no-bundle --config .* -- --locked/);
|
||||
const staging = path.join(root, 'output/attempt');
|
||||
const overridePath = path.join(staging, 'tauri.version.json');
|
||||
const calls: { command: string, args: string[], files: string[] }[] = [];
|
||||
const installer = await runInstallerBuild(plan, async (command: string, args: string[]) => {
|
||||
calls.push({ command, args, files: await contents(root) });
|
||||
if (args.includes('bundle')) {
|
||||
assert.deepEqual(JSON.parse(await readFile(overridePath, 'utf8')), { version: next.toolchain });
|
||||
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
|
||||
await writeFile(plan.artifacts.bundled, 'setup');
|
||||
}
|
||||
}, staging);
|
||||
assert.deepEqual(calls.map(({ command, args }) => ({ command, args })),
|
||||
buildCommands(plan, overridePath).map(({ command, args }) => ({ command, args })));
|
||||
for (const call of calls) {
|
||||
// The front end reads package.json. Tauri, Cargo, and the bundler get the version from the override.
|
||||
assert.equal(JSON.parse(call.files[0]).version, next.version);
|
||||
assert.deepEqual(call.files.slice(1), before.slice(1), 'Only package.json changes during the build.');
|
||||
}
|
||||
assert.equal(installer, path.join(root, 'releases', next.version, `RuneStone_${next.version}_x64-setup.exe`));
|
||||
assert.equal(await readFile(installer, 'utf8'), 'setup');
|
||||
assert.equal(await exists(plan.artifacts.bundled), false);
|
||||
assert.equal(await exists(plan.artifacts.renamed), false);
|
||||
const metadata = JSON.parse(await readFile(plan.artifacts.metadata, 'utf8'));
|
||||
assert.deepEqual([metadata.version, metadata.toolchainVersion, metadata.windowsVersion, metadata.bytes], [next.version, next.toolchain, next.windows, 5]);
|
||||
const after = await contents(root);
|
||||
assert.deepEqual(after, plan.updated);
|
||||
assert.equal(JSON.parse(after[0]).version, next.version);
|
||||
assert.equal(JSON.parse(after[1]).version, next.toolchain);
|
||||
assert.match(after[2], new RegExp(`^version = "${next.toolchain.replace('+', '\\+')}"`, 'm'));
|
||||
assert.match(after[2], new RegExp(`\\[package\\.metadata\\.runestone\\]\\r?\\nversion = "${next.version}"`));
|
||||
assert.match(after[3], new RegExp(`name = "runestone"\\r?\\nversion = "${next.toolchain.replace('+', '\\+')}"`));
|
||||
}));
|
||||
|
||||
test('a failed build leaves the version fields unchanged', () => withFixture(async ({ root, before, next }) => {
|
||||
for (const failure of ['compile', 'version-resource', 'bundle', 'missing setup file']) {
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
const staging = path.join(root, 'output', failure.replaceAll(' ', '-'));
|
||||
const steps = buildCommands(plan, path.join(staging, 'tauri.version.json'));
|
||||
let index = 0;
|
||||
await assert.rejects(runInstallerBuild(plan, async () => {
|
||||
if (steps[index++].step === failure) throw Error('The build command failed with exit code 1');
|
||||
}, staging));
|
||||
assert.deepEqual(await contents(root), before, 'A failure during ' + failure + ' must restore the version fields.');
|
||||
assert.equal(await exists(plan.artifacts.release), false);
|
||||
assert.equal(await exists(plan.artifacts.metadata), false);
|
||||
assert.ok((await readdir(staging)).includes('package.json.before'));
|
||||
}
|
||||
}));
|
||||
|
||||
test('the plan stops before a build that breaks the release rules', () => withFixture(async ({ root, before, current, next }) => {
|
||||
const tauriConfig = path.join(root, 'src-tauri/tauri.conf.json');
|
||||
const windowsConfig = path.join(root, 'src-tauri/tauri.windows.conf.json');
|
||||
const windowsBefore = await readFile(windowsConfig, 'utf8');
|
||||
await assert.rejects(planInstallerBuild(root, '0.1.44-rc1'), /release version such as/);
|
||||
await writeFile(tauriConfig, before[1].replace(`"version": "${current.toolchain}"`, '"version": "9.9.9"'));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /do not match/);
|
||||
await writeFile(tauriConfig, before[1]);
|
||||
const windows = JSON.parse(windowsBefore);
|
||||
windows.bundle.windows.allowDowngrades = true;
|
||||
await writeFile(windowsConfig, JSON.stringify(windows));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /Downgrade protection/);
|
||||
windows.bundle.windows.allowDowngrades = false;
|
||||
delete windows.bundle.windows.nsis.installerHooks;
|
||||
await writeFile(windowsConfig, JSON.stringify(windows));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /installer hooks/);
|
||||
await writeFile(windowsConfig, windowsBefore);
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
await mkdir(plan.releaseDir, { recursive: true });
|
||||
await writeFile(plan.artifacts.release, 'existing');
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /already exists/);
|
||||
await rm(plan.releaseDir, { recursive: true });
|
||||
await rm(path.join(root, 'src-tauri/browser-engine'), { recursive: true });
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /browser runtime is not staged/);
|
||||
assert.deepEqual(await contents(root), before);
|
||||
}));
|
||||
@@ -1,13 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import { mkdtemp, readFile, writeFile, copyFile, rm } from 'node:fs/promises';
|
||||
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { releaseVersion, nextHotfix, compareReleases } from '../../../scripts/releaseVersion.mjs';
|
||||
|
||||
const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24'];
|
||||
const hooks = path.resolve('src-tauri/windows/hooks.nsh');
|
||||
|
||||
test('hotfix versions retain their release identity and advance in letter order', () => {
|
||||
assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' });
|
||||
@@ -16,62 +18,227 @@ test('hotfix versions retain their release identity and advance in letter order'
|
||||
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j));
|
||||
});
|
||||
|
||||
const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe');
|
||||
const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; run pnpm build:installer once to download it';
|
||||
test('the Windows configuration uses the RuneStone hooks with the stock template', async () => {
|
||||
const config = JSON.parse(await readFile('src-tauri/tauri.conf.json', 'utf8'));
|
||||
const windows = JSON.parse(await readFile('src-tauri/tauri.windows.conf.json', 'utf8')).bundle.windows;
|
||||
assert.equal(windows.allowDowngrades, false);
|
||||
assert.equal(windows.nsis.template, undefined, 'Use the stock Tauri template. Put RuneStone behavior in the hooks.');
|
||||
assert.equal(path.resolve('src-tauri', windows.nsis.installerHooks), hooks);
|
||||
// The hooks read SHCTX as HKCU and use the uninstall key of the product name.
|
||||
assert.equal(windows.nsis.installMode, 'currentUser');
|
||||
const source = await readFile(hooks, 'utf8');
|
||||
assert.ok(source.includes(`!define /ifndef RUNESTONE_UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${config.productName}"`));
|
||||
});
|
||||
|
||||
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: nsisSkip }, async () => {
|
||||
// The Tauri CLI embeds its NSIS template. These checks fail when a Tauri update changes what the hooks rely on.
|
||||
function stockTemplate() {
|
||||
const cli = createRequire(realpathSync('node_modules/@tauri-apps/cli/package.json'));
|
||||
let binary: string;
|
||||
try { binary = cli.resolve('@tauri-apps/cli-win32-x64-msvc'); } catch { return null; }
|
||||
const bytes = readFileSync(binary);
|
||||
const start = bytes.indexOf('Unicode true\r\nManifestDPIAware true');
|
||||
assert.ok(start >= 0, 'The Tauri CLI no longer contains the expected NSIS template.');
|
||||
let end = start;
|
||||
while (end < bytes.length && (bytes[end] === 9 || bytes[end] === 10 || bytes[end] === 13 || (bytes[end] >= 32 && bytes[end] < 127))) end++;
|
||||
return bytes.subarray(start, end).toString('latin1').replaceAll('\r\n', '\n');
|
||||
}
|
||||
const template = process.platform === 'win32' ? stockTemplate() : null;
|
||||
|
||||
test('the stock Tauri template still provides what the hooks rely on', { skip: template ? false : 'needs the Windows Tauri CLI' }, () => {
|
||||
const text = template!;
|
||||
const at = (fragment: string) => {
|
||||
const index = text.indexOf(fragment);
|
||||
assert.ok(index >= 0, 'The stock template no longer contains: ' + fragment);
|
||||
return index;
|
||||
};
|
||||
const include = at('!include "{{installer_hooks}}"');
|
||||
assert.ok(include < at('!insertmacro MUI_PAGE_WELCOME'), 'Tauri must include the hooks before the first page.');
|
||||
assert.ok(include < at('\nSection EarlyChecks'), 'Tauri must include the hooks before its first section.');
|
||||
assert.ok(include < at('\nVar '), 'The hooks file cannot use the template variables.');
|
||||
at('!define UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${PRODUCTNAME}"');
|
||||
// RuneStoneInstallerVersion reads the version resource.
|
||||
at('VIProductVersion "${VERSIONWITHBUILD}"');
|
||||
assert.ok(!text.includes('VIFileVersion'));
|
||||
assert.ok(!text.includes('MUI_CUSTOMFUNCTION_GUIINIT') && !text.includes('.onGUIInit'), 'The hooks define the GUI initialization function.');
|
||||
// RuneStoneGuiInit makes the maintenance page skip itself. That page must look for the installation in SHCTX.
|
||||
const page = text.slice(at('Function PageReinstall\n'), at('Function PageReinstallUpdateSelection'));
|
||||
for (const line of ['ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""', 'ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"', '${IfThen} "$R0$R1" == "" ${|} Abort ${|}']) {
|
||||
assert.ok(page.includes(line), 'PageReinstall no longer contains: ' + line);
|
||||
}
|
||||
// No installer code may change the context between RuneStoneGuiInit and the RuneStoneVersionCheck section.
|
||||
const install = text.slice(0, at('Function un.onInit'));
|
||||
assert.ok(!install.includes('SetShellVarContext'), 'The installer part of the template now changes the shell context.');
|
||||
assert.ok(text.slice(at('Function .onInit'), at('Section EarlyChecks')).includes('!insertmacro SetContext'));
|
||||
const section = text.slice(at('Section Install\n'), at('Function .onInstSuccess'));
|
||||
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') >= 0);
|
||||
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') < section.indexOf('!insertmacro NSIS_HOOK_POSTINSTALL'), 'The hook must write DisplayVersion after the template.');
|
||||
});
|
||||
|
||||
const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe');
|
||||
const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; Tauri downloads it during the first installer build';
|
||||
|
||||
function compile(script: string, source: string) {
|
||||
const built = spawnSync(makensis, ['/V2', script], { input: undefined, encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(built.status, 0, source + '\n' + built.stdout + built.stderr);
|
||||
}
|
||||
|
||||
test('the hook functions convert versions in release order', { skip: nsisSkip }, async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
|
||||
try {
|
||||
const checks: string[] = [];
|
||||
checks.push('StrCpy $0 "keep0"\nStrCpy $1 "keep1"\nPush "0.1.23a"\nPush "0.1.23"\nCall RuneStoneCompareVersions\nPop $2\nStrCmp $0 "keep0" saved0\nSetErrorLevel 1\nQuit\nsaved0:\nStrCmp $1 "keep1" saved1\nSetErrorLevel 1\nQuit\nsaved1:');
|
||||
let index = 0;
|
||||
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) {
|
||||
checks.push(`Push "${ordering[i]}"\nPush "${ordering[j]}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 ${Math.sign(i - j)} check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
const results = path.join(root, 'results.txt');
|
||||
const valid = new Map<string, string>([['65535.0.0.65535', '65535.0.0.65535'], ['0.1.23', '0.1.23.0']]);
|
||||
for (const version of ordering) {
|
||||
const { toolchain, windows } = releaseVersion(version);
|
||||
valid.set(toolchain, windows);
|
||||
valid.set(windows, windows);
|
||||
}
|
||||
for (const version of ['0.1.23A', '0.1.23a1', '0.1.a', '0.1.23-rc', '0.1.23aaaaa', '4294967296.0.0']) {
|
||||
checks.push(`Push "0.1.23a"\nPush "${version}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 -1 check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
const invalid = ['', '0.1.23a', '0.1.23A', '0.1.23-rc', '0.1', '0.1.', '.1.2', '1..2.3', '0.1.23+', '0.1.23+1.2', '1.2+3',
|
||||
'0.1.23.1.0', '0.1.65536', '0.1.23+65536', '0.1.23.65536', 'garbage', ' 0.1.23', '0.1.23 ', '0x1.2.3'];
|
||||
const lines = ['FileOpen $9 "' + results + '" w'];
|
||||
for (const input of [...valid.keys(), ...invalid]) lines.push(`Push "${input}"`, 'Call RuneStoneNumericVersion', 'Pop $0', `FileWrite $9 "numeric|${input}|$0$\\n"`);
|
||||
for (const version of ordering) lines.push(`Push "${releaseVersion(version).windows}"`, 'Call RuneStoneReleaseName', 'Pop $0', `FileWrite $9 "release|${version}|$0$\\n"`);
|
||||
for (const left of ordering) for (const right of ordering) {
|
||||
lines.push(`\${VersionCompare} "${releaseVersion(left).windows}" "${releaseVersion(right).windows}" $0`, `FileWrite $9 "compare|${left}|${right}|$0$\\n"`);
|
||||
}
|
||||
const executable = path.join(root, 'compare.exe');
|
||||
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone version check"\nOutFile "${executable}"\n!include LogicLib.nsh\n!include WordFunc.nsh\n!include "${path.resolve('src-tauri/windows/versionCompare.nsh')}"\nSection\n${checks.join('\n')}\nSetErrorLevel 0\nSectionEnd\n`;
|
||||
const script = path.join(root, 'compare.nsi');
|
||||
lines.push('FileClose $9');
|
||||
const executable = path.join(root, 'functions.exe');
|
||||
const script = path.join(root, 'functions.nsi');
|
||||
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone hook functions"\nOutFile "${executable}"\n` +
|
||||
`!define RUNESTONE_UNINSTKEY "Software\\RuneStoneInstallerTest-${path.basename(root)}"\n!include "${hooks}"\nSection\n${lines.join('\n')}\nSectionEnd\n`;
|
||||
await writeFile(script, source);
|
||||
const compiler = makensis;
|
||||
const built = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(built.status, 0, built.stdout + built.stderr);
|
||||
compile(script, source);
|
||||
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(checked.status, 0, checked.stdout + checked.stderr);
|
||||
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', executable, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(checked.status, 0);
|
||||
const output = (await readFile(results, 'utf8')).trim().split('\n').map(line => line.split('|'));
|
||||
const numeric = new Map(output.filter(row => row[0] === 'numeric').map(row => [row[1], row[2]]));
|
||||
for (const [input, expected] of valid) assert.equal(numeric.get(input), expected, 'RuneStoneNumericVersion ' + input);
|
||||
for (const input of invalid) assert.equal(numeric.get(input), '', 'RuneStoneNumericVersion must reject ' + JSON.stringify(input));
|
||||
for (const row of output.filter(row => row[0] === 'release')) assert.equal(row[2], row[1], 'RuneStoneReleaseName ' + row[1]);
|
||||
for (const [, left, right, result] of output.filter(row => row[0] === 'compare')) {
|
||||
// VersionCompare returns 0 for equal versions, 1 when the first is newer, and 2 when the second is newer.
|
||||
assert.equal(result, String([0, 1, 2].at(compareReleases(left, right))), `VersionCompare ${left} ${right}`);
|
||||
}
|
||||
assert.equal(output.filter(row => row[0] === 'compare').length, ordering.length ** 2);
|
||||
// Tauri cannot write a letter suffix into the version strings of the app executable.
|
||||
const patchedExe = path.join(root, 'patched.exe');
|
||||
await copyFile(executable, patchedExe);
|
||||
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', patchedExe, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(patched.status, 0, patched.stdout + patched.stderr);
|
||||
assert.match(patched.stdout, /0\.1\.23a/);
|
||||
// Git can check the template out with CRLF line endings on Windows.
|
||||
const template = (await readFile('src-tauri/windows/installer.nsi', 'utf8')).replaceAll('\r\n', '\n');
|
||||
assert.ok(template.includes('Call RuneStoneCompareVersions'));
|
||||
assert.ok(!template.includes('nsis_tauri_utils::SemverCompare'));
|
||||
assert.match(template, /SetErrorLevel 2\n\s+Quit/);
|
||||
const guard = / !if "\$\{ALLOWDOWNGRADES\}" == "false"\n \$\{If\} \$R0 = -1[\s\S]+? !endif/.exec(template)?.[0];
|
||||
assert.ok(guard, 'The downgrade guard must precede reinstall and update actions.');
|
||||
const blockExe = path.join(root, 'block.exe');
|
||||
const blockScript = path.join(root, 'block.nsi');
|
||||
await writeFile(blockScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone downgrade check"\nOutFile "${blockExe}"\n!include LogicLib.nsh\n!define ALLOWDOWNGRADES "false"\nLangString dontUninstallDowngrade 1033 "Older versions cannot replace this installation."\nSection\nStrCpy $R0 -1\n${guard}\nSetErrorLevel 1\nSectionEnd\n`);
|
||||
const blockBuilt = spawnSync(compiler, ['/V2', blockScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(blockBuilt.status, 0, blockBuilt.stdout + blockBuilt.stderr);
|
||||
for (const flags of [['/S'], ['/S', '/P'], ['/S', '/UPDATE']]) {
|
||||
const blocked = spawnSync(blockExe, flags, { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(blocked.status, 2, 'The installer must block a downgrade with ' + flags.join(' '));
|
||||
}
|
||||
assert.match(template, /\$\{ElseIf\} \$R0 = 1 ; Upgrading\n\s+\$\{If\} \$R1 = 1\n\s+Goto reinst_done/);
|
||||
assert.ok(template.includes('"RuneStoneReleaseVersion" "${VERSION}"'));
|
||||
assert.ok(template.includes('"DisplayVersion" "${TOOLCHAINVERSION}"'));
|
||||
const legacyExe = path.join(root, 'legacy.exe');
|
||||
const legacyScript = path.join(root, 'legacy.nsi');
|
||||
const pluginPath = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/Plugins/x86-unicode/additional');
|
||||
await writeFile(legacyScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone legacy version check"\nOutFile "${legacyExe}"\n!addplugindir "${pluginPath}"\nSection\nnsis_tauri_utils::SemverCompare "0.1.23" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_ok\nSetErrorLevel 1\nQuit\nlegacy_ok:\nnsis_tauri_utils::SemverCompare "0.1.22" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_older_ok\nSetErrorLevel 1\nQuit\nlegacy_older_ok:\nnsis_tauri_utils::SemverCompare "0.1.24" "0.1.23+1"\nPop $0\nStrCmp $0 1 legacy_newer_ok\nSetErrorLevel 1\nQuit\nlegacy_newer_ok:\nSetErrorLevel 0\nSectionEnd\n`);
|
||||
const legacyBuilt = spawnSync(compiler, ['/V2', legacyScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(legacyBuilt.status, 0, legacyBuilt.stdout + legacyBuilt.stderr);
|
||||
const legacyChecked = spawnSync(legacyExe, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(legacyChecked.status, 0, 'Older installers must detect the encoded hotfix as newer.');
|
||||
} finally {
|
||||
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// Each test installer has the version resource that Tauri writes for its version, and the stock template
|
||||
// layout: Modern UI, then the hooks, then the pages and an Install section that ends with NSIS_HOOK_POSTINSTALL.
|
||||
// The installed version comes from a test-only registry key. Nothing forces an internal variable.
|
||||
test('the hooks block downgrades in every installer mode', { skip: nsisSkip }, async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-hooks-'));
|
||||
const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root);
|
||||
const reg = (...args: string[]) => spawnSync('reg', args, { encoding: 'utf8', windowsHide: true });
|
||||
const installed = () => {
|
||||
const result = reg('query', 'HKCU\\' + key);
|
||||
const values: Record<string, string> = {};
|
||||
if (result.status === 0) for (const match of result.stdout.matchAll(/^\s+(\S+)\s+REG_SZ\s+(.*?)\s*$/gm)) values[match[1]] = match[2];
|
||||
return values;
|
||||
};
|
||||
const setInstalled = (values: Record<string, string>) => {
|
||||
reg('delete', 'HKCU\\' + key, '/f');
|
||||
for (const [name, value] of Object.entries(values)) assert.equal(reg('add', 'HKCU\\' + key, '/v', name, '/d', value, '/f').status, 0);
|
||||
};
|
||||
const installers = new Map<string, string>();
|
||||
const installer = async (version: string) => {
|
||||
if (installers.has(version)) return installers.get(version)!;
|
||||
const { toolchain, windows } = releaseVersion(version);
|
||||
const executable = path.join(root, `setup-${version}.exe`);
|
||||
const script = path.join(root, `setup-${version}.nsi`);
|
||||
const source = `Unicode true
|
||||
RequestExecutionLevel user
|
||||
Name "RuneStone hook test"
|
||||
OutFile "${executable}"
|
||||
InstallDir "$TEMP"
|
||||
AutoCloseWindow true
|
||||
VIProductVersion "${windows}"
|
||||
VIAddVersionKey "ProductName" "RuneStone hook test"
|
||||
VIAddVersionKey "FileDescription" "RuneStone hook test"
|
||||
VIAddVersionKey "LegalCopyright" "Test"
|
||||
VIAddVersionKey "FileVersion" "${toolchain}"
|
||||
VIAddVersionKey "ProductVersion" "${toolchain}"
|
||||
!define RUNESTONE_UNINSTKEY "${key}"
|
||||
; Record the notice instead of opening a message box.
|
||||
!macro RUNESTONE_DOWNGRADE_NOTICE
|
||||
\${IfNot} \${Silent}
|
||||
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestNotice" "shown"
|
||||
\${EndIf}
|
||||
!macroend
|
||||
!include MUI2.nsh
|
||||
!include "${hooks}"
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipPage
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
; In the stock template, the maintenance page that can start the uninstaller follows the first page.
|
||||
; That page skips itself when it cannot find the installation in SHCTX.
|
||||
Function SkipPage
|
||||
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestFirstPage" "shown"
|
||||
ReadRegStr $0 SHCTX "\${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion"
|
||||
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestPageFound" "[$0]"
|
||||
Abort
|
||||
FunctionEnd
|
||||
Section Install
|
||||
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "DisplayVersion" "${toolchain}"
|
||||
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "TestLocalAppData" "$LOCALAPPDATA"
|
||||
!insertmacro NSIS_HOOK_POSTINSTALL
|
||||
SectionEnd
|
||||
`;
|
||||
await writeFile(script, source);
|
||||
compile(script, source);
|
||||
installers.set(version, executable);
|
||||
return executable;
|
||||
};
|
||||
const install = async (version: string, flags: string[]) =>
|
||||
spawnSync(await installer(version), flags, { encoding: 'utf8', windowsHide: true, timeout: 60000 }).status;
|
||||
const silent = (flags: readonly string[]) => flags.includes('/S');
|
||||
try {
|
||||
// Installer 0.1.23a over 0.1.23b. Without /S, the check runs before the first page.
|
||||
for (const flags of [['/S'], ['/S', '/UPDATE'], ['/S', '/P'], ['/P'], ['/P', '/UPDATE'], []]) {
|
||||
setInstalled({ RuneStoneWindowsVersion: '0.1.23.2', DisplayVersion: '0.1.23b' });
|
||||
assert.equal(await install('0.1.23a', flags), 2, 'A downgrade must stop with exit code 2: ' + (flags.join(' ') || 'interactive'));
|
||||
const values = installed();
|
||||
assert.equal(values.DisplayVersion, '0.1.23b', 'A blocked setup must not install.');
|
||||
assert.equal(values.TestNotice, silent(flags) ? undefined : 'shown');
|
||||
assert.equal(values.TestFirstPage, undefined, 'Setup must stop before the first page.');
|
||||
}
|
||||
// Earlier installers wrote only the toolchain version to DisplayVersion.
|
||||
for (const [previous, version, code] of [['0.1.24', '0.1.23z', 2], ['0.1.23+1', '0.1.23', 2], ['0.1.23+1', '0.1.23a', 0], ['0.1.23+1', '0.1.23b', 0]] as const) {
|
||||
setInstalled({ DisplayVersion: previous });
|
||||
assert.equal(await install(version, ['/S']), code, `${version} over ${previous}`);
|
||||
}
|
||||
// An unknown installed version blocks setup.
|
||||
for (const values of [{ RuneStoneWindowsVersion: '0.1.23b' }, { DisplayVersion: '0.1.23b' }, { DisplayVersion: '0.1.23-beta' }, { DisplayVersion: 'garbage' }] as Record<string, string>[]) {
|
||||
setInstalled(values);
|
||||
assert.equal(await install('0.1.24', ['/S']), 2, 'Unknown installed version ' + JSON.stringify(values));
|
||||
}
|
||||
// Same version, upgrade, and first installation. Each writes the literal release version.
|
||||
for (const [previous, version, flags] of [['0.1.23.1', '0.1.23a', ['/S']], ['0.1.23.1', '0.1.23a', []], ['0.1.23.26', '0.1.23aa', ['/P', '/UPDATE']], [null, '0.1.24', ['/S']]] as const) {
|
||||
setInstalled(previous ? { RuneStoneWindowsVersion: previous } : {});
|
||||
assert.equal(await install(version, [...flags]), 0, `${version} over ${previous ?? 'no installation'} with ${flags.join(' ') || 'interactive'}`);
|
||||
const values = installed();
|
||||
assert.equal(values.DisplayVersion, version, 'Installed apps must show the release version.');
|
||||
assert.equal(values.RuneStoneReleaseVersion, version);
|
||||
assert.equal(values.RuneStoneWindowsVersion, releaseVersion(version).windows);
|
||||
assert.equal(values.TestNotice, undefined);
|
||||
// Without /S, the pages must not find the installation, so that setup replaces it in place.
|
||||
assert.equal(values.TestPageFound, silent(flags) ? undefined : '[]');
|
||||
// RuneStoneGuiInit switches to the "all" context. The sections must run in the current-user context again.
|
||||
assert.equal(values.TestLocalAppData?.toLowerCase(), process.env.LOCALAPPDATA!.toLowerCase());
|
||||
}
|
||||
} finally {
|
||||
reg('delete', 'HKCU\\' + key, '/f');
|
||||
assert.equal(reg('query', 'HKCU\\' + key).status, 1, 'The test registry key must be removed.');
|
||||
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-hooks-')), true);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user