Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Windows installer

Bee4659bd9d162d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f968ed6..eb0f3e8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -70,6 +70,24 @@ jobs:
run: cargo test --locked -p nectarlink-desktop
- name: Release build
run: cargo build --locked --release -p nectarlink-desktop
+ - name: Install NSIS
+ shell: pwsh
+ run: |
+ if (-not (Get-Command makensis -ErrorAction SilentlyContinue) -and
+ -not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) {
+ choco install nsis --yes --no-progress
+ }
+ - name: Installer
+ shell: pwsh
+ run: ./scripts/package.ps1 -SkipBuild
+ - name: Install, run and uninstall it
+ shell: pwsh
+ run: ./scripts/smoke-installer.ps1
+ - uses: actions/upload-artifact@v7
+ with:
+ name: nectarlink-windows-x64
+ path: target/package/*-setup.exe
+ retention-days: 14
desktop-arm64:
name: Windows app (ARM64 cross build)
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..f00612f
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,60 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+# A tag like v0.1.0 builds the Windows installer and puts it on a draft
+# GitHub release, which a maintainer reviews and publishes.
+name: Release
+
+on:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: write
+
+env:
+ CARGO_TERM_COLOR: always
+ QT_VERSION: "6.12.0"
+
+jobs:
+ windows:
+ name: Windows installer (x64)
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v7
+ - name: The tag matches the version
+ shell: pwsh
+ run: |
+ $version = (Select-String -Path Cargo.toml -Pattern '^version = "([^"]+)"' | Select-Object -First 1).Matches[0].Groups[1].Value
+ if ("v$version" -ne "${{ github.ref_name }}") { throw "tag ${{ github.ref_name }} but Cargo.toml says $version" }
+ - name: Install the pinned Rust toolchain
+ run: rustup show active-toolchain || rustup toolchain install
+ - name: Install Qt
+ uses: jurplel/install-qt-action@v4
+ with:
+ version: ${{ env.QT_VERSION }}
+ host: windows
+ target: desktop
+ arch: win64_msvc2022_64
+ cache: true
+ aqtsource: git+https://github.com/miurahr/aqtinstall.git
+ - name: Install NSIS
+ shell: pwsh
+ run: |
+ if (-not (Get-Command makensis -ErrorAction SilentlyContinue) -and
+ -not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) {
+ choco install nsis --yes --no-progress
+ }
+ - name: Build the installer
+ shell: pwsh
+ run: ./scripts/package.ps1
+ - name: Check it installs and uninstalls
+ shell: pwsh
+ run: ./scripts/smoke-installer.ps1
+ - name: Draft the release
+ shell: pwsh
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ $setup = (Get-ChildItem target/package/*-setup.exe).FullName
+ $hash = (Get-FileHash $setup -Algorithm SHA256).Hash.ToLower()
+ "$hash $(Split-Path -Leaf $setup)" | Set-Content target/package/SHA256SUMS.txt
+ gh release create "${{ github.ref_name }}" $setup target/package/SHA256SUMS.txt --draft --generate-notes --title "Nectarlink ${{ github.ref_name }}"
diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/LICENSES/LGPL-3.0-only.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index ec153c4..de76d77 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -141,6 +141,18 @@ Item {
width: parent.width
Column {
width: parent.width
+ ListRow {
+ width: parent.width
+ iconPath: Icons.power
+ title: qsTr("Start with Windows")
+ description: qsTr("Nectarlink starts in the notification area when you sign in, so your phone can reach this PC right away.")
+ Toggle {
+ label: qsTr("Start with Windows")
+ checked: Preferences.startWithWindows
+ onToggled: (on) => Preferences.startWithWindows = on
+ }
+ }
+ Divider { width: parent.width }
ListRow {
width: parent.width
iconPath: Icons.power
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index da3b50b..8ad382f 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -43,6 +43,8 @@ pub mod qobject {
#[qproperty(bool, auto_clipboard)]
/// Paired phones in Explorer's "Send to" menu.
#[qproperty(bool, send_to_menu)]
+ /// Start when the user signs in.
+ #[qproperty(bool, start_with_windows)]
type Preferences = super::PreferencesRust;
}
@@ -58,6 +60,9 @@ pub struct PreferencesRust {
close_to_tray: bool,
auto_clipboard: bool,
send_to_menu: bool,
+ start_with_windows: bool,
+ /// What the user chose (`start_with_windows` shows the default until then).
+ start_choice: Option<bool>,
}
impl cxx_qt::Initialize for qobject::Preferences {
@@ -78,6 +83,8 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().set_auto_clipboard(settings.auto_clipboard);
crate::clipboard::set_auto_send(settings.auto_clipboard);
self.as_mut().set_send_to_menu(settings.send_to_menu);
+ self.as_mut().set_start_with_windows(crate::startup::effective(settings.start_with_windows));
+ self.as_mut().rust_mut().start_choice = settings.start_with_windows;
// Save after any change (connected after loading, so loading doesn't
// rewrite the file).
@@ -98,6 +105,14 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_start_with_windows_changed(|mut p| {
+ let on = p.start_with_windows;
+ p.as_mut().rust_mut().start_choice = Some(on);
+ crate::startup::apply(on);
+ p.save();
+ })
+ .release();
}
}
@@ -116,6 +131,7 @@ impl qobject::Preferences {
close_to_tray: p.close_to_tray,
auto_clipboard: p.auto_clipboard,
send_to_menu: p.send_to_menu,
+ start_with_windows: p.start_choice,
};
save_in_background(settings);
}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 7c19bd0..4324ec4 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -22,6 +22,7 @@ mod palette;
mod qr;
mod send_to;
mod settings;
+mod startup;
mod state;
mod transfers;
mod win;
@@ -155,6 +156,7 @@ fn uninstall() {
tracing::warn!(error = %e, "can't remove the Send to entries");
}
win::toast::unregister();
+ startup::remove();
}
fn install_panic_logging() {
@@ -219,10 +221,13 @@ fn main() -> ExitCode {
clipboard::start();
win::smtc::start(media::on_flyout);
win::media_sessions::start(media::local_changed);
- send_to::set_enabled(settings::Settings::load(&data_dir).send_to_menu);
- // A test instance (own data folder) leaves the user's menu alone.
+ let settings = settings::Settings::load(&data_dir);
+ send_to::set_enabled(settings.send_to_menu);
+ // A test instance (own data folder) leaves the user's menu and sign-in
+ // alone.
if options.data_dir.is_none() {
send_to::start();
+ startup::start(settings.start_with_windows);
}
// Requests left while no instance was running, then this launch's own.
for waiting in launch::drain(&data_dir) {
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 0164c96..ad88309 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -45,6 +45,11 @@ pub struct Settings {
pub auto_clipboard: bool,
/// Paired phones in Explorer's "Send to" menu.
pub send_to_menu: bool,
+ /// Start when the user signs in. Unset until the user chooses: then an
+ /// installed copy starts with Windows and a build run from its folder
+ /// doesn't.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub start_with_windows: Option<bool>,
}
impl Default for Settings {
@@ -57,6 +62,7 @@ impl Default for Settings {
close_to_tray: true,
auto_clipboard: true,
send_to_menu: true,
+ start_with_windows: None,
}
}
}
@@ -118,6 +124,7 @@ mod tests {
close_to_tray: false,
auto_clipboard: false,
send_to_menu: false,
+ start_with_windows: Some(true),
};
settings.save(dir.path()).unwrap();
assert_eq!(Settings::load(dir.path()), settings);
diff --git a/desktop/app/src/startup.rs b/desktop/app/src/startup.rs
new file mode 100644
index 0000000..38be386
--- /dev/null
+++ b/desktop/app/src/startup.rs
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! "Start with Windows": an installed copy starts with Windows unless the
+//! user turns it off; a build run from its folder only when turned on. Only
+//! the instance with the usual data folder manages this (a test instance
+//! with its own leaves it alone).
+
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use crate::win::autostart;
+
+static MANAGED: AtomicBool = AtomicBool::new(false);
+
+/// Whether the app starts with Windows, given what the user chose (if
+/// anything).
+pub fn effective(choice: Option<bool>) -> bool {
+ choice.unwrap_or_else(|| std::env::current_exe().is_ok_and(|exe| autostart::is_installed(&exe)))
+}
+
+/// Brings the `Run` entry in line with the setting, from now on.
+pub fn start(choice: Option<bool>) {
+ MANAGED.store(true, Ordering::Relaxed);
+ apply(effective(choice));
+}
+
+/// Starts this copy with Windows, or stops doing so.
+pub fn apply(on: bool) {
+ if !MANAGED.load(Ordering::Relaxed) {
+ return;
+ }
+ let Ok(exe) = std::env::current_exe() else { return };
+ if let Err(e) = autostart::set(on, &exe) {
+ tracing::warn!(error = %e, "can't change starting with Windows");
+ }
+}
+
+/// Removes the entry (when uninstalling).
+pub fn remove() {
+ if let Ok(exe) = std::env::current_exe()
+ && let Err(e) = autostart::set(false, &exe)
+ {
+ tracing::warn!(error = %e, "can't stop starting with Windows");
+ }
+}
diff --git a/desktop/app/src/win/autostart.rs b/desktop/app/src/win/autostart.rs
new file mode 100644
index 0000000..288a3ad
--- /dev/null
+++ b/desktop/app/src/win/autostart.rs
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Starting Nectarlink when the user signs in, so phones can reach this PC
+//! without opening it first: a value under the user's `Run` key that starts
+//! it in the tray.
+
+use std::path::Path;
+
+use windows::{
+ Win32::{
+ Foundation::ERROR_FILE_NOT_FOUND,
+ System::Registry::{
+ HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW,
+ RegSetValueExW,
+ },
+ },
+ core::HSTRING,
+};
+
+const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
+const VALUE: &str = "Nectarlink";
+
+/// The command the `Run` value holds.
+pub fn command(exe: &Path) -> String {
+ format!("\"{}\" --minimized", exe.display())
+}
+
+/// Starts this copy of the app at sign-in, or stops doing so.
+pub fn set(enabled: bool, exe: &Path) -> windows::core::Result<()> {
+ let mut key = HKEY::default();
+ // SAFETY: opens a key under HKCU with a valid path; closed below.
+ unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, &HSTRING::from(RUN_KEY), None, KEY_SET_VALUE, &mut key) }
+ .ok()?;
+ let result = if enabled {
+ let wide: Vec<u16> = command(exe).encode_utf16().chain(std::iter::once(0)).collect();
+ // SAFETY: the data is a null-terminated UTF-16 string of the given size.
+ unsafe {
+ RegSetValueExW(
+ key,
+ &HSTRING::from(VALUE),
+ None,
+ REG_SZ,
+ Some(std::slice::from_raw_parts(wide.as_ptr().cast::<u8>(), wide.len() * 2)),
+ )
+ }
+ .ok()
+ } else {
+ // SAFETY: deletes one value of the open key.
+ let deleted = unsafe { RegDeleteValueW(key, &HSTRING::from(VALUE)) };
+ if deleted == ERROR_FILE_NOT_FOUND { Ok(()) } else { deleted.ok() }
+ };
+ // SAFETY: the key was opened above.
+ unsafe {
+ let _ = RegCloseKey(key);
+ }
+ result
+}
+
+/// Whether an executable is an installed copy (under Program Files), as
+/// opposed to a build being run from its folder.
+pub fn is_installed(exe: &Path) -> bool {
+ let exe = exe.to_string_lossy().to_lowercase();
+ ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"]
+ .iter()
+ .filter_map(|var| std::env::var(var).ok())
+ .any(|dir| exe.starts_with(&format!("{}\\", dir.to_lowercase().trim_end_matches('\\'))))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn starts_minimized_from_the_exe() {
+ assert_eq!(
+ command(Path::new(r"C:\Program Files\Nectarlink\nectarlink-desktop.exe")),
+ r#""C:\Program Files\Nectarlink\nectarlink-desktop.exe" --minimized"#
+ );
+ }
+
+ #[test]
+ fn builds_are_not_installed_copies() {
+ assert!(!is_installed(Path::new(
+ r"C:\Users\me\src\nectarlink\target\release\nectarlink-desktop.exe"
+ )));
+ if let Ok(dir) = std::env::var("ProgramFiles") {
+ assert!(is_installed(&Path::new(&dir).join("Nectarlink").join("nectarlink-desktop.exe")));
+ }
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 7f437fb..a987198 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -5,6 +5,7 @@
#![allow(unsafe_code)]
+pub mod autostart;
pub mod clipboard;
pub mod icon;
pub mod image;
diff --git a/desktop/installer/nectarlink.nsi b/desktop/installer/nectarlink.nsi
new file mode 100644
index 0000000..876ca5a
--- /dev/null
+++ b/desktop/installer/nectarlink.nsi
@@ -0,0 +1,163 @@
+; SPDX-License-Identifier: GPL-3.0-or-later
+;
+; The Nectarlink installer for Windows (built by scripts/package.ps1).
+;
+; Installs for every user of the PC (one UAC prompt), so it can allow the
+; app through Windows Firewall: otherwise Windows asks on first use, and
+; people often say no. User data stays in each user's
+; %LOCALAPPDATA%\Nectarlink, and is kept when uninstalling.
+;
+; Defines passed in: VERSION (numbers only, e.g. 0.0.1), DISPLAY_VERSION
+; (e.g. 0.0.1-beta.2), ARCH (x64 or arm64), STAGE (the
+; folder with the app and its Qt files), ICON, OUTFILE.
+
+Unicode true
+ManifestDPIAware true
+SetCompressor /SOLID lzma
+
+!include "MUI2.nsh"
+!include "x64.nsh"
+!include "LogicLib.nsh"
+!include "FileFunc.nsh"
+
+!define APP "Nectarlink"
+!define EXE "nectarlink-desktop.exe"
+!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APP}"
+!define FIREWALL_RULE "Nectarlink"
+
+Name "${APP}"
+OutFile "${OUTFILE}"
+RequestExecutionLevel admin
+InstallDir "$PROGRAMFILES64\${APP}"
+InstallDirRegKey HKLM "Software\${APP}" "InstallDir"
+BrandingText "${APP} ${DISPLAY_VERSION}"
+
+VIProductVersion "${VERSION}.0"
+VIAddVersionKey "ProductName" "${APP}"
+VIAddVersionKey "FileDescription" "${APP} Setup"
+VIAddVersionKey "CompanyName" "The Nectarlink contributors"
+VIAddVersionKey "LegalCopyright" "GPL-3.0-or-later"
+VIAddVersionKey "FileVersion" "${VERSION}"
+VIAddVersionKey "ProductVersion" "${DISPLAY_VERSION}"
+
+!define MUI_ICON "${ICON}"
+!define MUI_UNICON "${ICON}"
+!define MUI_ABORTWARNING
+!define MUI_FINISHPAGE_RUN
+!define MUI_FINISHPAGE_RUN_TEXT "Open ${APP}"
+!define MUI_FINISHPAGE_RUN_FUNCTION OpenApp
+
+!insertmacro MUI_PAGE_WELCOME
+!insertmacro MUI_PAGE_LICENSE "${STAGE}\LICENSE.txt"
+!insertmacro MUI_PAGE_INSTFILES
+!insertmacro MUI_PAGE_FINISH
+
+!insertmacro MUI_UNPAGE_CONFIRM
+!insertmacro MUI_UNPAGE_INSTFILES
+
+!insertmacro MUI_LANGUAGE "English"
+
+Function .onInit
+ ${If} "${ARCH}" == "x64"
+ ${IfNot} ${IsNativeAMD64}
+ MessageBox MB_ICONSTOP "This copy of ${APP} is for x64 PCs. Download the ARM64 version for this PC." /SD IDOK
+ Abort
+ ${EndIf}
+ ${ElseIf} "${ARCH}" == "arm64"
+ ${IfNot} ${IsNativeARM64}
+ MessageBox MB_ICONSTOP "This copy of ${APP} is for ARM64 PCs. Download the x64 version for this PC." /SD IDOK
+ Abort
+ ${EndIf}
+ ${EndIf}
+ SetRegView 64
+ SetShellVarContext all
+FunctionEnd
+
+Function un.onInit
+ SetRegView 64
+ SetShellVarContext all
+FunctionEnd
+
+; Asks a running copy to quit (it closes its connections cleanly), and waits
+; for it, so its files can be replaced or removed.
+!macro QuitRunningApp
+ ${If} ${FileExists} "$INSTDIR\${EXE}"
+ ExecWait '"$INSTDIR\${EXE}" --quit'
+ ${EndIf}
+ StrCpy $R0 0
+ ${Do}
+ nsExec::Exec 'cmd /c tasklist /FI "IMAGENAME eq ${EXE}" /NH | find /I "${EXE}"'
+ Pop $R1
+ ${If} $R1 != 0
+ ${Break}
+ ${EndIf}
+ ${If} $R0 >= 25
+ ; Other users' copies, or one that's stuck.
+ nsExec::Exec 'taskkill /F /IM ${EXE}'
+ Sleep 500
+ ${Break}
+ ${EndIf}
+ Sleep 200
+ IntOp $R0 $R0 + 1
+ ${Loop}
+!macroend
+
+Function OpenApp
+ ; Through Explorer, so the app runs as the user and not elevated.
+ Exec '"$WINDIR\explorer.exe" "$INSTDIR\${EXE}"'
+FunctionEnd
+
+Section "Install"
+ !insertmacro QuitRunningApp
+
+ ; A clean copy: nothing left over from an older version.
+ RMDir /r "$INSTDIR\qml"
+ RMDir /r "$INSTDIR\platforms"
+ SetOutPath "$INSTDIR"
+ File /r "${STAGE}\*.*"
+ WriteUninstaller "$INSTDIR\uninstall.exe"
+
+ CreateShortCut "$SMPROGRAMS\${APP}.lnk" "$INSTDIR\${EXE}" "" "$INSTDIR\${EXE}" 0 "" "" "Your phone, on your PC"
+
+ ; Phones reach this PC over UDP (QUIC) and find it with mDNS.
+ nsExec::Exec 'netsh advfirewall firewall delete rule name="${FIREWALL_RULE}"'
+ nsExec::Exec 'netsh advfirewall firewall add rule name="${FIREWALL_RULE}" dir=in action=allow program="$INSTDIR\${EXE}" enable=yes profile=private,domain description="Lets paired phones connect to Nectarlink."'
+
+ WriteRegStr HKLM "Software\${APP}" "InstallDir" "$INSTDIR"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayName" "${APP}"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayVersion" "${DISPLAY_VERSION}"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "Publisher" "The Nectarlink contributors"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${EXE}"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "URLInfoAbout" "https://github.com/thtbee/nectarlink"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\uninstall.exe"'
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S'
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoModify" 1
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoRepair" 1
+ ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "EstimatedSize" $0
+SectionEnd
+
+Section "Uninstall"
+ !insertmacro QuitRunningApp
+ ; What the app set up for this user: Send to entries, sign-in start,
+ ; notification registration. (Data stays, for a reinstall.)
+ ${If} ${FileExists} "$INSTDIR\${EXE}"
+ ExecWait '"$INSTDIR\${EXE}" --uninstall'
+ ${EndIf}
+
+ nsExec::Exec 'netsh advfirewall firewall delete rule name="${FIREWALL_RULE}"'
+ Delete "$SMPROGRAMS\${APP}.lnk"
+ ; Only ever a folder of our own (a silent install can be pointed
+ ; anywhere with /D): never everything in, say, C:\.
+ ${GetFileName} "$INSTDIR" $0
+ ${If} $0 == "${APP}"
+ RMDir /r "$INSTDIR"
+ ${Else}
+ Delete "$INSTDIR\${EXE}"
+ Delete "$INSTDIR\uninstall.exe"
+ ${EndIf}
+
+ DeleteRegKey HKLM "${UNINSTALL_KEY}"
+ DeleteRegKey HKLM "Software\${APP}"
+SectionEnd
diff --git a/scripts/package.ps1 b/scripts/package.ps1
new file mode 100644
index 0000000..d3de20a
--- /dev/null
+++ b/scripts/package.ps1
@@ -0,0 +1,121 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+<#
+.SYNOPSIS
+ Builds the Windows app and packs it into an installer.
+
+.DESCRIPTION
+ 1. Builds the release app (unless -SkipBuild).
+ 2. Stages it with the Qt libraries, plugins and QML modules it uses
+ (windeployqt), the Microsoft C++ runtime, and the license notices.
+ 3. Packs the folder into target\package\Nectarlink-<version>-x64-setup.exe
+ with NSIS (unless -StageOnly).
+
+ Needs Qt (qmake on PATH, or QT_ROOT_DIR / -QtRoot) and, for the
+ installer, NSIS (makensis on PATH or in its usual folder).
+
+.EXAMPLE
+ .\scripts\package.ps1
+ .\scripts\package.ps1 -StageOnly # just the folder, to try the app as shipped
+#>
+param(
+ [string]$QtRoot,
+ [switch]$SkipBuild,
+ [switch]$StageOnly
+)
+
+$ErrorActionPreference = 'Stop'
+$root = Split-Path -Parent $PSScriptRoot
+Set-Location $root
+
+function Step($name) { Write-Host "`n==> $name" -ForegroundColor Cyan }
+
+# Runs a native command, showing its output; fails on a non-zero exit.
+# (Windows PowerShell treats anything on stderr as an error otherwise.)
+function Invoke-Native([string]$what, [scriptblock]$command) {
+ $saved = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try { & $command 2>&1 | ForEach-Object { Write-Host "$_" } }
+ finally { $ErrorActionPreference = $saved }
+ if ($LASTEXITCODE -ne 0) { throw "$what failed (exit code $LASTEXITCODE)" }
+}
+
+# ---- Version, from the workspace manifest ----
+$version = (Select-String -Path Cargo.toml -Pattern '^version = "([^"]+)"' | Select-Object -First 1).Matches[0].Groups[1].Value
+if (-not $version) { throw "can't read the version from Cargo.toml" }
+# Windows file versions are numbers only: 0.0.1-beta.2 -> 0.0.1.
+$numeric = ($version -split '[-+]')[0]
+
+# ---- Qt ----
+if (-not $QtRoot) { $QtRoot = $env:QT_ROOT_DIR }
+if (-not $QtRoot) {
+ $qmake = Get-Command qmake6, qmake -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($qmake) { $QtRoot = Split-Path -Parent (Split-Path -Parent $qmake.Source) }
+}
+if (-not $QtRoot) { $QtRoot = 'C:\Qt\6.12.0\msvc2022_64' }
+$windeployqt = Join-Path $QtRoot 'bin\windeployqt.exe'
+if (-not (Test-Path $windeployqt)) { throw "windeployqt not found under $QtRoot; pass -QtRoot" }
+
+# ---- Build ----
+if (-not $SkipBuild) {
+ Step "Build"
+ $env:PATH = "$(Join-Path $QtRoot 'bin');$env:PATH"
+ Invoke-Native "the build" { cargo build --locked --release -p nectarlink-desktop }
+}
+$exe = Join-Path $root 'target\release\nectarlink-desktop.exe'
+if (-not (Test-Path $exe)) { throw "no release build at $exe" }
+
+# ---- Stage ----
+Step "Stage"
+$package = Join-Path $root 'target\package'
+$stage = Join-Path $package 'Nectarlink'
+if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
+New-Item -ItemType Directory -Force $stage | Out-Null
+Copy-Item $exe $stage
+
+Invoke-Native "windeployqt" {
+ & $windeployqt --verbose 0 --release --qmldir (Join-Path $root 'desktop\app\qml') --no-translations `
+ --no-system-d3d-compiler --no-opengl-sw --no-compiler-runtime --dir $stage (Join-Path $stage 'nectarlink-desktop.exe')
+}
+
+# QtQuick.Dialogs brings every Controls style along. The file picker is
+# Windows' own dialog; only Basic, Windows and FluentWinUI3 (the default
+# style on Windows) can ever be loaded, so the rest is left out.
+foreach ($style in 'Fusion', 'Imagine', 'Material', 'Universal') {
+ Remove-Item (Join-Path $stage "Qt6QuickControls2$style*.dll") -Force
+ Remove-Item (Join-Path $stage "qml\QtQuick\Controls\$style") -Recurse -Force -ErrorAction SilentlyContinue
+}
+
+# The C++ runtime, next to the app (Microsoft allows this app-local copy),
+# so it runs on PCs without the Visual C++ Redistributable.
+$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
+$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+$crt = Get-ChildItem (Join-Path $vs 'VC\Redist\MSVC') -Directory |
+ Where-Object { $_.Name -match '^\d' } | Sort-Object { [version]$_.Name } -Descending |
+ ForEach-Object { Get-ChildItem (Join-Path $_.FullName 'x64') -Directory -Filter 'Microsoft.VC*.CRT' -ErrorAction SilentlyContinue } |
+ Select-Object -First 1
+if (-not $crt) { throw "can't find the Visual C++ runtime to ship" }
+Copy-Item (Join-Path $crt.FullName '*.dll') $stage
+
+# Licenses.
+Copy-Item (Join-Path $root 'LICENSE') (Join-Path $stage 'LICENSE.txt')
+Invoke-Native "writing the notices" { cargo xtask notices (Join-Path $stage 'THIRD-PARTY-NOTICES.txt') }
+
+$size = (Get-ChildItem $stage -Recurse -File | Measure-Object Length -Sum).Sum / 1MB
+Write-Host ("Staged {0:N1} MB in {1}" -f $size, $stage)
+if ($StageOnly) { return }
+
+# ---- Installer ----
+Step "Installer"
+$makensis = (Get-Command makensis -ErrorAction SilentlyContinue).Source
+if (-not $makensis) { $makensis = Join-Path ${env:ProgramFiles(x86)} 'NSIS\makensis.exe' }
+if (-not (Test-Path $makensis)) { throw "NSIS (makensis) not found" }
+# The icon build.rs drew for the .exe.
+$icon = Get-ChildItem (Join-Path $root 'target\release\build') -Recurse -Filter 'nectarlink.ico' |
+ Sort-Object LastWriteTime -Descending | Select-Object -First 1
+if (-not $icon) { throw "the app icon isn't built" }
+$out = Join-Path $package "Nectarlink-$version-x64-setup.exe"
+Invoke-Native "makensis" {
+ & $makensis /V2 "/DVERSION=$numeric" "/DDISPLAY_VERSION=$version" /DARCH=x64 "/DSTAGE=$stage" `
+ "/DICON=$($icon.FullName)" "/DOUTFILE=$out" (Join-Path $root 'desktop\installer\nectarlink.nsi')
+}
+Write-Host ("Installer: {0} ({1:N1} MB)" -f $out, ((Get-Item $out).Length / 1MB))
diff --git a/scripts/smoke-installer.ps1 b/scripts/smoke-installer.ps1
new file mode 100644
index 0000000..36f69cc
--- /dev/null
+++ b/scripts/smoke-installer.ps1
@@ -0,0 +1,49 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+<#
+.SYNOPSIS
+ Installs, starts, quits and uninstalls the packaged app silently, checking
+ each step. For CI (needs admin; changes this PC), not for everyday use.
+#>
+param([string]$Setup = (Get-ChildItem (Join-Path $PSScriptRoot '..\target\package\*-setup.exe') | Select-Object -First 1).FullName)
+
+$ErrorActionPreference = 'Stop'
+$dir = Join-Path $env:ProgramFiles 'Nectarlink'
+$exe = Join-Path $dir 'nectarlink-desktop.exe'
+$uninstallKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Nectarlink'
+$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\Nectarlink.lnk'
+$data = Join-Path $env:RUNNER_TEMP 'nectarlink-smoke'
+if (-not $env:RUNNER_TEMP) { $data = Join-Path $env:TEMP 'nectarlink-smoke' }
+
+function Check($what, [bool]$ok) {
+ if (-not $ok) { throw "FAILED: $what" }
+ Write-Host "ok: $what"
+}
+function FirewallRule { (netsh advfirewall firewall show rule name=Nectarlink) -match 'Nectarlink' }
+
+Write-Host "Installing $Setup"
+Start-Process $Setup -ArgumentList '/S' -Wait
+Check "the app is installed" (Test-Path $exe)
+Check "an uninstaller is installed" (Test-Path (Join-Path $dir 'uninstall.exe'))
+Check "it's in Apps (uninstall entry)" (Test-Path $uninstallKey)
+Check "it's in the Start menu" (Test-Path $shortcut)
+Check "the firewall lets phones in" ([bool](FirewallRule))
+Check "license notices are included" ((Get-Item (Join-Path $dir 'THIRD-PARTY-NOTICES.txt')).Length -gt 100KB)
+
+# The installed copy starts on its own files and quits when asked.
+$app = Start-Process $exe -ArgumentList '--minimized', '--data-dir', $data -PassThru
+Start-Sleep 8
+Check "the installed app keeps running" (-not $app.HasExited)
+Start-Process $exe -ArgumentList '--quit', '--data-dir', $data -Wait
+Check "the app quits when asked" ($app.WaitForExit(15000))
+Check "it shut down cleanly" ($app.ExitCode -eq 0)
+
+Write-Host "Uninstalling"
+Start-Process (Join-Path $dir 'uninstall.exe') -ArgumentList '/S' -Wait
+# The uninstaller runs from a copy in %TEMP%, so it returns before it's done.
+$deadline = (Get-Date).AddSeconds(60)
+while ((Test-Path $dir) -and (Get-Date) -lt $deadline) { Start-Sleep 1 }
+Check "the app folder is gone" (-not (Test-Path $dir))
+Check "the uninstall entry is gone" (-not (Test-Path $uninstallKey))
+Check "the Start menu shortcut is gone" (-not (Test-Path $shortcut))
+Check "the firewall rule is gone" (-not (FirewallRule))
+Write-Host "Installer smoke test passed."
diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs
index 0955ccb..cf03dfe 100644
--- a/tools/xtask/src/main.rs
+++ b/tools/xtask/src/main.rs
@@ -5,6 +5,9 @@
//! (`desktop/app/qml/Tokens.qml`, `android/.../ui/theme/Tokens.kt`) from
//! `docs/design/tokens.json`, the single source of truth.
//! - `tokens --check`: fails if the generated files are out of date (CI).
+//! - `notices <out>`: the third-party notices shipped with the Windows app.
+
+mod notices;
use std::{
fs,
@@ -24,8 +27,9 @@ fn main() -> ExitCode {
let result = match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
["tokens"] => tokens(false),
["tokens", "--check"] => tokens(true),
+ ["notices", rest @ ..] => notices::run(rest),
_ => {
- eprintln!("usage: cargo xtask tokens [--check]");
+ eprintln!("usage: cargo xtask tokens [--check] | notices <out> [--target <triple>]");
return ExitCode::from(2);
}
};
diff --git a/tools/xtask/src/notices.rs b/tools/xtask/src/notices.rs
new file mode 100644
index 0000000..05cbf14
--- /dev/null
+++ b/tools/xtask/src/notices.rs
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `cargo xtask notices <out> [--target <triple>]`: the third-party notices
+//! shipped with the Windows app. Every crate compiled into the app (normal
+//! dependencies for that target; not build or dev ones) with its license
+//! and the license files it ships, then Qt and the bundled fonts.
+
+use std::{
+ collections::{BTreeMap, BTreeSet, VecDeque},
+ fmt::Write as _,
+ fs,
+ path::{Path, PathBuf},
+ process::Command,
+};
+
+use anyhow::{Context, Result, bail};
+use serde_json::Value;
+
+const ROOT_PACKAGE: &str = "nectarlink-desktop";
+const DEFAULT_TARGET: &str = "x86_64-pc-windows-msvc";
+
+/// License-ish files a crate ships.
+fn is_license_file(name: &str) -> bool {
+ let upper = name.to_uppercase();
+ ["LICENSE", "LICENCE", "COPYING", "NOTICE", "UNLICENSE"].iter().any(|p| upper.starts_with(p))
+}
+
+struct Crate {
+ name: String,
+ version: String,
+ license: String,
+ repository: String,
+ files: Vec<(String, String)>,
+}
+
+pub fn run(args: &[&str]) -> Result<()> {
+ let (out, target) = match args {
+ [out] => (*out, DEFAULT_TARGET),
+ [out, "--target", target] => (*out, *target),
+ _ => bail!("usage: cargo xtask notices <out file> [--target <triple>]"),
+ };
+ let root = crate::repo_root();
+ let output = Command::new(env_cargo())
+ .args(["metadata", "--format-version", "1", "--locked", "--filter-platform", target])
+ .current_dir(&root)
+ .output()
+ .context("running cargo metadata")?;
+ if !output.status.success() {
+ bail!("cargo metadata failed: {}", String::from_utf8_lossy(&output.stderr));
+ }
+ let metadata: Value = serde_json::from_slice(&output.stdout).context("parsing cargo metadata")?;
+ let crates = shipped_crates(&metadata)?;
+
+ let mut text = String::new();
+ writeln!(text, "Nectarlink for Windows: third-party notices")?;
+ writeln!(text, "{}", "=".repeat(43))?;
+ writeln!(
+ text,
+ "\nNectarlink is free software under the GNU General Public License, version 3\n\
+ or later (LICENSE.txt). It includes the software below, under these terms.\n"
+ )?;
+ write_qt(&mut text, &root)?;
+ write_fonts(&mut text, &root)?;
+ writeln!(text, "\nRust crates ({} in this build)\n{}", crates.len(), "-".repeat(30))?;
+ for c in &crates {
+ writeln!(text, "\n{} {} · {}", c.name, c.version, c.license)?;
+ if !c.repository.is_empty() {
+ writeln!(text, "{}", c.repository)?;
+ }
+ for (file, body) in &c.files {
+ writeln!(text, "\n--- {} ({file}) ---\n{}", c.name, body.trim_end())?;
+ }
+ }
+ let out = PathBuf::from(out);
+ if let Some(dir) = out.parent() {
+ fs::create_dir_all(dir)?;
+ }
+ fs::write(&out, text).with_context(|| format!("writing {}", out.display()))?;
+ println!("wrote {} ({} crates)", out.display(), crates.len());
+ Ok(())
+}
+
+fn env_cargo() -> String {
+ std::env::var("CARGO").unwrap_or_else(|_| "cargo".into())
+}
+
+/// The crates in the app's normal dependency graph, workspace crates left
+/// out (they're Nectarlink's own).
+fn shipped_crates(metadata: &Value) -> Result<Vec<Crate>> {
+ let packages: BTreeMap<&str, &Value> = metadata["packages"]
+ .as_array()
+ .context("no packages")?
+ .iter()
+ .filter_map(|p| Some((p["id"].as_str()?, p)))
+ .collect();
+ let workspace: BTreeSet<&str> = metadata["workspace_members"]
+ .as_array()
+ .context("no members")?
+ .iter()
+ .filter_map(Value::as_str)
+ .collect();
+ let nodes: BTreeMap<&str, &Value> = metadata["resolve"]["nodes"]
+ .as_array()
+ .context("no resolve graph")?
+ .iter()
+ .filter_map(|n| Some((n["id"].as_str()?, n)))
+ .collect();
+ let start = packages
+ .iter()
+ .find(|(_, p)| p["name"] == ROOT_PACKAGE)
+ .map(|(id, _)| *id)
+ .context("the desktop app isn't in the workspace")?;
+
+ let mut seen = BTreeSet::from([start]);
+ let mut queue = VecDeque::from([start]);
+ while let Some(id) = queue.pop_front() {
+ let Some(node) = nodes.get(id) else { continue };
+ for dep in node["deps"].as_array().into_iter().flatten() {
+ // Only what's linked into the app: not build scripts or tests.
+ let normal = dep["dep_kinds"].as_array().into_iter().flatten().any(|k| k["kind"].is_null());
+ if let Some(dep_id) = dep["pkg"].as_str()
+ && normal
+ && seen.insert(dep_id)
+ {
+ queue.push_back(dep_id);
+ }
+ }
+ }
+
+ let mut crates: Vec<Crate> = seen
+ .into_iter()
+ .filter(|id| !workspace.contains(id))
+ .filter_map(|id| packages.get(id))
+ .map(|p| {
+ let dir =
+ Path::new(p["manifest_path"].as_str().unwrap_or_default()).parent().map(Path::to_path_buf);
+ let mut files: Vec<(String, String)> = dir
+ .and_then(|d| fs::read_dir(d).ok())
+ .into_iter()
+ .flatten()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().is_file() && is_license_file(&e.file_name().to_string_lossy()))
+ .filter_map(|e| {
+ Some((e.file_name().to_string_lossy().into_owned(), fs::read_to_string(e.path()).ok()?))
+ })
+ .collect();
+ files.sort();
+ Crate {
+ name: p["name"].as_str().unwrap_or_default().to_owned(),
+ version: p["version"].as_str().unwrap_or_default().to_owned(),
+ license: p["license"].as_str().unwrap_or("see its files").to_owned(),
+ repository: p["repository"].as_str().unwrap_or_default().to_owned(),
+ files,
+ }
+ })
+ .collect();
+ crates.sort_by(|a, b| (&a.name, &a.version).cmp(&(&b.name, &b.version)));
+ Ok(crates)
+}
+
+fn write_qt(text: &mut String, root: &Path) -> Result<()> {
+ writeln!(text, "Qt\n--")?;
+ writeln!(
+ text,
+ "This app uses the Qt framework (https://www.qt.io), version 6, under the GNU\n\
+ Lesser General Public License version 3 (below). Qt's libraries are the\n\
+ separate Qt6*.dll files and plugins in this folder; you may replace them with\n\
+ your own builds of the same version. Qt's source code is available from\n\
+ https://download.qt.io/official_releases/qt/ and https://code.qt.io.\n"
+ )?;
+ let lgpl = fs::read_to_string(root.join("LICENSES/LGPL-3.0-only.txt")).context("reading the LGPL")?;
+ writeln!(text, "{}\n", lgpl.trim_end())?;
+ Ok(())
+}
+
+fn write_fonts(text: &mut String, root: &Path) -> Result<()> {
+ writeln!(text, "\nFonts\n-----")?;
+ writeln!(text, "Figtree, Instrument Serif and Space Mono, under the SIL Open Font License 1.1:")?;
+ let mut ofl: Vec<PathBuf> = fs::read_dir(root.join("assets/fonts"))?
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("OFL-")))
+ .collect();
+ ofl.sort();
+ for path in ofl {
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ writeln!(text, "\n--- {name} ---\n{}", fs::read_to_string(&path)?.trim_end())?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn recognizes_license_files() {
+ for name in ["LICENSE", "LICENSE-MIT", "license-apache", "COPYING", "NOTICE.md", "UNLICENSE"] {
+ assert!(is_license_file(name), "{name}");
+ }
+ for name in ["README.md", "Cargo.toml", "src"] {
+ assert!(!is_license_file(name), "{name}");
+ }
+ }
+}