Distribution
This guide describes how to package a CPUI app into installers for distribution. CPUI does not package apps itself. The desktop steps use cargo-packager, which produces:
.appand.dmgon macOS.exe(NSIS) and.msi(WiX) on Windows.deb, AppImage and Pacman packages on Linux
The guide also covers code signing and macOS notarization. The examples package dirsize, a
disk usage viewer built with CPUI. Sections 6 and 7 cover iOS and Android.
1. Before packaging
Section titled “1. Before packaging”Release build
Section titled “Release build”A CPUI app is a single executable with no additional files: fonts come from the system and icons are drawn in code. The following release profile minimizes its size:
[profile.release]lto = "fat"codegen-units = 1strip = truepanic = "abort"With these settings the hello example is under 2 MB. panic = "abort" is optional; omit it if
your app catches panics.
No console window on Windows
Section titled “No console window on Windows”On Windows, a Rust executable opens a console window unless it declares the GUI subsystem. Add
the first line of the example below to the top of main.rs. Debug builds keep the console, so
eprintln! output remains visible:
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use cpui::{App, Options, Ui};
struct Notes;
impl App for Notes { fn ui(&mut self, ui: &mut Ui<'_>) { ui.text("Hello"); }}
fn main() -> Result<(), cpui::Error> { cpui::run(Options::new("Notes"), Notes)}An app has two icons:
- The application icon appears in Finder, the Start menu, the taskbar and launchers. It is part of the package, so list it in the packager configuration (section 2).
- The window icon appears in the title bar on Windows and Linux. Set it with
Options::icon. macOS has no window icon and shows the application icon instead.
To create the application icon:
- Start from a square PNG of at least 512×512 pixels.
- Create an
.icnsfile for macOS and an.icofile for Windows. Any icon generator produces both from the PNG. On a Mac, the built-in tools suffice: resize the PNG into anicon.iconsetfolder withsips, then runiconutil -c icns icon.iconset. - For Linux, also list 128, 256 and 512 pixel PNG files. Linux packages install each PNG under its size, and the fallback icon theme used by launchers has no 1024 pixel folder.
For the window icon, add a small PNG next to the others and decode it with the png feature:
use cpui::{Bitmap, Options};
// In `main`: `with_window_icon(options, include_bytes!("../icons/window.png"))`.fn with_window_icon(options: Options, png: &[u8]) -> Options { match Bitmap::from_png(png) { Ok(icon) => options.icon(icon), // A broken icon should not stop the application from starting. Err(_) => options, }}2. Configuring cargo-packager
Section titled “2. Configuring cargo-packager”Install it once:
cargo install cargo-packager --lockedPut the configuration under [package.metadata.packager] in your app’s Cargo.toml, or in a
Packager.toml next to it. The configuration for dirsize:
[package.metadata.packager]product-name = "DirSize"identifier = "dev.example.dirsize"description = "See which folders take up disk space."long-description = """DirSize scans a folder in the background and lists what each item inside takes up, largestfirst. Open a folder to look inside it, or reveal an item in the file manager."""authors = ["Example"]category = "Utility"icons = [ "icons/128x128.png", "icons/256x256.png", "icons/512x512.png", "icons/icon.png", "icons/icon.icns", "icons/icon.ico",]before-packaging-command = "cargo build --release -p dirsize"
[package.metadata.packager.macos]minimum-system-version = "13.0"
[package.metadata.packager.deb]package-name = "dirsize"depends = [ "libx11-6", "libx11-xcb1", "libxcb1", "libxkbcommon0", "libxkbcommon-x11-0", "libwayland-client0", "fontconfig",]identifieris the app’s reverse-domain name. macOS stores the app’s permissions and preferences under it; do not change it after release.- The version defaults to the package’s
version. Setversionhere to override it. before-packaging-commandbuilds the executable. Without it, cargo-packager builds nothing.minimum-system-versionis macOS 13, the oldest version CPUI supports.package-nameis the nameaptuses to install and remove the package. If omitted, it isproduct-namein kebab case (dir-sizehere), which differs from the executable name.long-descriptionis the paragraph package managers show below the one-linedescription.
Then build. The first command produces the platform’s default formats; the second selects one:
cargo packager --release -p dirsizecargo packager --release -p dirsize --formats dmgOn a Mac, cargo packager --release -p dirsize --formats app,dmg with this configuration
produces DirSize.app (2.2 MB) and DirSize_0.1.0_aarch64.dmg (1.2 MB). The disk image contains
the app, a link to Applications and the volume icon.
Packages are written to target/release/, or to target/<target>/release/ with --target. Use
--out-dir to choose another directory.
Packages are normally built on their target platform: .dmg on macOS, .msi and .exe on
Windows, .deb and AppImage on Linux. A CI service with macOS, Windows and Linux runners can
build all of them in one run.
3. macOS
Section titled “3. macOS”--formats app produces the .app bundle and --formats dmg the disk image described in
section 2.
Architecture
Section titled “Architecture”By default the package targets the build machine’s architecture. To support both Apple Silicon and Intel Macs, either:
- Build one package per architecture, with
--target aarch64-apple-darwinand--target x86_64-apple-darwin. - Combine both into one executable with
lipobefore packaging.
Signing and notarization
Section titled “Signing and notarization”macOS refuses to open a downloaded app unless it is signed and notarized. Both require a paid Apple Developer account.
-
Create a Developer ID Application certificate in your developer account and install it in the login keychain.
security find-identity -v -p codesigningshows its name. -
Set that name as the signing identity:
[package.metadata.packager.macos]minimum-system-version = "13.0"signing-identity = "Developer ID Application: Example Ltd (TEAMID1234)" -
Provide notarization credentials through environment variables, using one of these sets:
APPLE_KEYCHAIN_PROFILE: a profile saved withxcrun notarytool store-credentials.APPLE_API_KEY,APPLE_API_ISSUERandAPPLE_API_KEY_PATH: an App Store Connect API key. Recommended for CI.APPLE_ID,APPLE_PASSWORD(an app-specific password, not the account password) andAPPLE_TEAM_ID.
With an identity set, cargo-packager signs the bundle with the hardened runtime, submits it for notarization and staples the notarization ticket to it. Without credentials, it signs the bundle, prints a warning and skips notarization.
CI runners have no login keychain. Export the certificate as a .p12 file, base64-encode it into
APPLE_CERTIFICATE, and put its password in APPLE_CERTIFICATE_PASSWORD.
To verify the result, run spctl --assess --type execute --verbose DirSize.app. It should report
source=Notarized Developer ID.
CPUI requires no entitlements, because it does not use the network, the camera or other
protected resources. If your app does, add an entitlements file.
4. Windows
Section titled “4. Windows”--formats nsis produces a setup .exe and --formats wix an .msi. The NSIS installer
installs for the current user by default and requires no administrator rights. Organizations
that deploy through group policy usually require the .msi.
Signing
Section titled “Signing”Windows shows a SmartScreen warning for unsigned installers. To sign, obtain a code-signing certificate from a certificate authority and add:
[package.metadata.packager.windows]certificate-thumbprint = "A1B2C3D4E5F6..."digest-algorithm = "sha256"timestamp-url = "http://timestamp.digicert.com"certificate-thumbprint is the SHA-1 hash of a certificate in your user certificate store. The
timestamp keeps the signature valid after the certificate expires.
If the certificate is stored in a cloud service or on a hardware token, use sign-command
instead. It runs the provider’s signing tool, with %1 standing for the file:
[package.metadata.packager.windows]sign-command = "provider-sign-tool sign --file %1"Even with a signed installer, a new certificate must build SmartScreen reputation over its first downloads.
5. Linux
Section titled “5. Linux”--formats deb produces a package for Debian and Ubuntu, --formats appimage a single file that
runs on most distributions, and --formats pacman a package for Arch Linux.
Runtime libraries
Section titled “Runtime libraries”The executable links only to the C runtime libraries and loads the windowing libraries at
startup. Desktop installations include them; on minimal installations, the depends list from
section 2 installs them:
| Library | Purpose | Debian package |
|---|---|---|
libX11, libX11-xcb, libxcb |
X11 windows | libx11-6, libx11-xcb1, libxcb1 |
libxkbcommon, libxkbcommon-x11 |
Keyboard layouts | libxkbcommon0, libxkbcommon-x11-0 |
libwayland-client |
Wayland windows | libwayland-client0 |
fc-match |
Finding the system fonts | fontconfig |
Two further dependencies are optional:
- File dialogs use
zenity(GNOME and others) orkdialog(KDE). With neither installed,ui.show_file_dialoghas no result. - Chinese, Japanese and Korean text requires a CJK font such as
fonts-noto-cjk.
Most desktops install both. Mention them on your download page rather than declaring them as package dependencies.
glibc version
Section titled “glibc version”An executable runs only on systems whose glibc is at least as new as the one it was built against. CPUI supports glibc 2.28, so build release packages on a distribution of that age, such as Debian 10 or AlmaLinux 8, or in a container based on one. This also applies to AppImage, which bundles libraries but not glibc.
To find the glibc version a build requires, list the glibc symbol versions it imports. The highest one is the minimum:
objdump -T target/release/dirsize | grep -o 'GLIBC_[0-9.]*' | sort -uV | tail -1Result
Section titled “Result”Running cargo packager --release -p dirsize --formats deb in the rust:latest container
(Debian 13, arm64) produces dirsize_0.1.0_arm64.deb (2.7 MB), which contains:
- the executable in
/usr/bin - a
.desktopentry in/usr/share/applications - the icons under
/usr/share/icons/hicolor
Its control file lists the depends above. An executable built in that container requires glibc
2.39 and does not start on Debian 12 or Ubuntu 22.04, which is why release builds belong on an
older distribution.
6. iOS
Section titled “6. iOS”cargo-packager does not build iOS apps; Xcode does. The Rust code is compiled into a static library, a few lines of C call into it, and Xcode links, signs and installs the app.
The CPUI repository contains such a project for its component gallery in
tools/mobile-gallery/ios. To start a new app, copy it and change the names.
Differences from the desktop:
- The entry point is a library function, not
main(see below). - The window always fills the screen.
Options::size,position,min_sizeandiconare ignored, and content stays within the safe area. - Text input goes through the system keyboard, including its input methods.
- Suggestions and autocorrect on letter keyboards are disabled.
- When the user pastes text copied from another app through CPUI’s touch edit menu, iOS asks for permission. Only the system’s own edit menu and paste button avoid the prompt.
- Xcode.
- XcodeGen, which generates the Xcode project from a
short specification:
brew install xcodegen. - The Rust targets:
rustup target add aarch64-apple-ios aarch64-apple-ios-sim. Addx86_64-apple-iosfor simulators on Intel Macs.
The library
Section titled “The library”Build the app as a staticlib that exports one function to run it:
[lib]crate-type = ["staticlib"]use cpui::{App, Options, Ui};
struct Notes;
impl App for Notes { fn ui(&mut self, ui: &mut Ui<'_>) { ui.text("Hello"); }}
#[unsafe(no_mangle)]extern "C" fn notes_main() { if let Err(error) = cpui::run(Options::new("Notes"), Notes) { eprintln!("notes: {error}"); }}If the crate also targets the desktop, put this code in lib.rs behind
#[cfg(target_os = "ios")] and keep main.rs for the desktop. If it also targets Android, list
both crate types: crate-type = ["cdylib", "staticlib"].
The project
Section titled “The project”The project consists of three files next to the crate:
ios/ project.yml the project, for XcodeGen main.c the entry point: calls notes_main build-rust.sh a build phase: runs Cargo for what Xcode is buildingmain.c is the only non-Rust code in the app:
void notes_main(void);
int main(void) { notes_main(); return 0;}The parts of project.yml specific to a Rust app:
targets: Notes: type: application platform: iOS sources: [main.c] settings: base: PRODUCT_BUNDLE_IDENTIFIER: dev.example.notes LIBRARY_SEARCH_PATHS: $(RUST_LIBRARY_DIR) OTHER_LDFLAGS: [-lnotes, -liconv, -framework UIKit, -framework Foundation, -framework CoreFoundation, -framework CoreGraphics, -framework CoreText, -framework QuartzCore, -framework IOSurface] ENABLE_USER_SCRIPT_SANDBOXING: false preBuildScripts: - name: Build the Rust library script: '"$SRCROOT/build-rust.sh"' basedOnDependencyAnalysis: falseOTHER_LDFLAGSnames the Rust library and the system libraries it uses. To list them for your crate, runcargo rustc --lib --target aarch64-apple-ios -- --print native-static-libs.- The build phase runs before compilation. It maps Xcode’s platform and architectures to Rust targets, builds each target and combines the results into one library. Cargo reads and writes outside the project, so the script sandbox must be disabled.
UILaunchScreenin the project’sinfosection is required for a full-screen app. Without it, iOS runs the app in a letterboxed compatibility mode.- The deployment target is 16.0, the oldest iOS version CPUI supports. Xcode passes it to Cargo.
Building and running
Section titled “Building and running”Generate the project, then open and run it in Xcode:
cd iosxcodegen generate # writes Notes.xcodeproj; run again after editing project.ymlopen Notes.xcodeproj # then choose a simulator or a device and press RunAlternatively, build and run in the simulator from the command line:
xcodebuild -project Notes.xcodeproj -scheme Notes -configuration Release \ -sdk iphonesimulator -derivedDataPath build buildxcrun simctl install booted build/Build/Products/Release-iphonesimulator/Notes.appxcrun simctl launch booted dev.example.notesKeep the generated .xcodeproj out of version control; project.yml is the source.
Running on a device
Section titled “Running on a device”- Set
DEVELOPMENT_TEAMinproject.ymlto your team identifier, or select the team under Signing & Capabilities in Xcode. Xcode then creates the certificate and the provisioning profile, signs the app and installs it. - Enable Developer Mode on the device (Settings > Privacy & Security > Developer Mode).
App Store and TestFlight
Section titled “App Store and TestFlight”- Add the app icon as an asset catalog (a single 1024×1024 PNG suffices) and list it under
sources. - In Xcode, choose Product > Archive.
- Upload the archive from the Organizer window.
Increase CFBundleVersion for every upload.
7. Android
Section titled “7. Android”cargo-packager does not build Android apps either; Gradle does. cargo-ndk compiles the Rust code into one shared library per ABI, and Gradle compiles CPUI’s Java classes, then packages, signs and installs the app.
The CPUI repository contains such a project for its component gallery in
tools/mobile-gallery/android. To start a new app, copy it and change the names.
Differences from the desktop:
- The entry point is
android_mainin a library, notmain(see below). - The window always fills the screen.
Options::size,position,min_sizeandiconare ignored, and content stays clear of the system bars, the display cutout and the keyboard. - While the app is in the background, its window and renderer are released. The interface state is kept, and the window is recreated when the app returns to the foreground.
- Text input goes through the system keyboard and its input methods only if the manifest names
dev.cpui.CpuiActivity. With the plainNativeActivity, key events still arrive, but composed text such as pinyin does not. - Suggestions and autocorrect on letter keyboards are disabled, as on iOS.
ui.show_file_dialoghas no result yet.
-
The Android SDK command-line tools, with these packages:
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.1.0" "ndk;28.2.13676358" -
JDK 17 or newer, to run Gradle. Gradle itself need not be installed: the project includes a wrapper that downloads it.
-
cargo-ndk, which configures Cargo to use the NDK compilers:
cargo install cargo-ndk. -
The Rust target:
rustup target add aarch64-linux-android. Addx86_64-linux-androidfor emulators on Intel machines.
The library
Section titled “The library”Build the app as a cdylib whose android_main passes the activity to cpui::run:
[lib]crate-type = ["cdylib"]use cpui::{AndroidApp, App, Options, Ui};
struct Notes;
impl App for Notes { fn ui(&mut self, ui: &mut Ui<'_>) { ui.text("Hello"); }}
#[unsafe(no_mangle)]fn android_main(android: AndroidApp) { if let Err(error) = cpui::run(android, Options::new("Notes"), Notes) { eprintln!("notes: {error}"); }}If the crate also targets the desktop, put this code in lib.rs behind
#[cfg(target_os = "android")] and keep main.rs for the desktop.
The project
Section titled “The project”android/ settings.gradle.kts, build.gradle.kts, gradle.properties gradlew, gradlew.bat, gradle/wrapper/ Gradle's wrapper app/ build.gradle.kts the app: identifiers, versions, the Rust build src/main/AndroidManifest.xml src/main/res/ the icon and other resourcesapp/build.gradle.kts holds the values to change for a release:
android { namespace = "dev.example.notes" compileSdk = 36 ndkVersion = "28.2.13676358" defaultConfig { applicationId = "dev.example.notes" minSdk = 26 targetSdk = 36 versionCode = 1 versionName = "0.1.0" }}applicationIdidentifies the app to Google Play and the system. Do not change it after release.versionCodemust increase with every release.versionNameis the version shown to users.minSdk26 (Android 8) is the oldest version CPUI supports. SettargetSdkto the newest platform; Google Play rejects apps that target an outdated one.
The same file performs two steps specific to CPUI apps:
- It builds the Rust library before any other task. A task runs
cargo ndk --target arm64-v8a --platform 26 --output-dir … build --release, and the output is packaged.cpui.abisingradle.propertieslists the ABIs to build. - It compiles CPUI’s Java classes,
CpuiActivityand its input view, which ship as source in thecpuicrate underandroid/java/. The project locates the crate withcargo metadataand adds that directory to its sources.
gradle.properties disables the Kotlin runtime that the Android plugin would otherwise package.
The runtime is about 2 MB and unused by apps without Kotlin.
The manifest
Section titled “The manifest”<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:label="Notes" android:icon="@mipmap/ic_launcher" android:extractNativeLibs="false"> <activity android:name="dev.cpui.CpuiActivity" android:exported="true" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|uiMode|density" android:windowSoftInputMode="adjustResize"> <meta-data android:name="android.app.lib_name" android:value="notes"/> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>android.app.lib_nameis the library name without thelibprefix and the.sosuffix.configChangeskeeps the activity alive when the device rotates, the keyboard appears or dark mode changes. CPUI handles these changes itself.extractNativeLibs="false"lets the system map the library directly from the package. Gradle stores it uncompressed and aligned to the 16 KB memory pages of recent devices, as Google Play requires. NDK r28 and newer build the library with this alignment.
The icon
Section titled “The icon”The launcher icon is an image resource. Place a square PNG at
app/src/main/res/mipmap-xxxhdpi/ic_launcher.png (192×192 pixels covers most phones). Without an
icon, remove android:icon from the manifest; the launcher then shows a generic icon.
Building and running
Section titled “Building and running”Use the emulator or a device with USB debugging enabled (Settings > About phone, tap Build number seven times, then Developer options > USB debugging):
cd android./gradlew installDebugadb shell am start -n dev.example.notes/dev.cpui.CpuiActivityadb logcat --pid=$(adb shell pidof dev.example.notes)Gradle locates the SDK through ANDROID_HOME or through sdk.dir in a local.properties file,
which Android Studio writes. The project can also be opened in Android Studio.
Signing a release
Section titled “Signing a release”Every package must be signed. Debug builds use the debug key in ~/.android/debug.keystore. For
releases, create a key once and store it securely, because all updates must be signed with the
same key:
keytool -genkeypair -keystore release.jks -alias notes -keyalg RSA -keysize 2048 -validity 10000Reference the key in a keystore.properties file next to the project; the build reads the file
if it exists. Keep the file and the key out of version control:
storeFile=release.jksstorePassword=…keyAlias=noteskeyPassword=…Then build the release package:
./gradlew assembleRelease # app/build/outputs/apk/release/app-release.apkUsers who download the APK directly must allow installation from that source when Android prompts them.
Google Play
Section titled “Google Play”Google Play accepts Android App Bundles, not APKs:
./gradlew bundleRelease # app/build/outputs/bundle/release/app-release.aabUpload the bundle in the Play Console. Play signs the packages it delivers.
8. Before a release
Section titled “8. Before a release”-
Increase
versioninCargo.toml. The packages, the.appbundle and the installers take their version from it. On Android, increaseversionCodeandversionNameinapp/build.gradle.kts. On iOS, increaseCFBundleShortVersionStringandCFBundleVersioninproject.yml. -
Install each package on a clean machine or virtual machine that has never had a development build. Launch the app from Finder, the Start menu or the launcher, not from a terminal.
-
On macOS, download the
.dmgthrough a browser before opening it. This sets the quarantine flag that triggers the notarization check. -
Include the license notices of your dependencies. CPUI and the crates it depends on are under permissive licenses (MIT, Apache-2.0, BSD, Zlib, Unicode-3.0 and similar) that require their copyright and license text to accompany a distributed program. Generate the list with cargo-about and ship it with the app, for example in the package or behind an About window:
cargo install --locked cargo-about --features clicargo about initcargo about generate about.hbs > THIRD-PARTY-LICENSES.htmlFonts that the app embeds carry their own licenses, usually the SIL Open Font License, which must be included as well.
-
CPUI does not handle updating an installed app in place. cargo-packager provides an updater library for this.