Skip to content

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:

  • .app and .dmg on 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.

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 = 1
strip = true
panic = "abort"

With these settings the hello example is under 2 MB. panic = "abort" is optional; omit it if your app catches panics.

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:

  1. Start from a square PNG of at least 512×512 pixels.
  2. Create an .icns file for macOS and an .ico file for Windows. Any icon generator produces both from the PNG. On a Mac, the built-in tools suffice: resize the PNG into an icon.iconset folder with sips, then run iconutil -c icns icon.iconset.
  3. 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,
}
}

Install it once:

cargo install cargo-packager --locked

Put 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, largest
first. 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",
]
  • identifier is 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. Set version here to override it.
  • before-packaging-command builds the executable. Without it, cargo-packager builds nothing.
  • minimum-system-version is macOS 13, the oldest version CPUI supports.
  • package-name is the name apt uses to install and remove the package. If omitted, it is product-name in kebab case (dir-size here), which differs from the executable name.
  • long-description is the paragraph package managers show below the one-line description.

Then build. The first command produces the platform’s default formats; the second selects one:

cargo packager --release -p dirsize
cargo packager --release -p dirsize --formats dmg

On 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.

--formats app produces the .app bundle and --formats dmg the disk image described in section 2.

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-darwin and --target x86_64-apple-darwin.
  • Combine both into one executable with lipo before packaging.

macOS refuses to open a downloaded app unless it is signed and notarized. Both require a paid Apple Developer account.

  1. Create a Developer ID Application certificate in your developer account and install it in the login keychain. security find-identity -v -p codesigning shows its name.

  2. Set that name as the signing identity:

    [package.metadata.packager.macos]
    minimum-system-version = "13.0"
    signing-identity = "Developer ID Application: Example Ltd (TEAMID1234)"
  3. Provide notarization credentials through environment variables, using one of these sets:

    • APPLE_KEYCHAIN_PROFILE: a profile saved with xcrun notarytool store-credentials.
    • APPLE_API_KEY, APPLE_API_ISSUER and APPLE_API_KEY_PATH: an App Store Connect API key. Recommended for CI.
    • APPLE_ID, APPLE_PASSWORD (an app-specific password, not the account password) and APPLE_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.

--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.

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.

--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.

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) or kdialog (KDE). With neither installed, ui.show_file_dialog has 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.

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 -1

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 .desktop entry 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.

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_size and icon are 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. Add x86_64-apple-ios for simulators on Intel Macs.

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 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 building

main.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: false
  • OTHER_LDFLAGS names the Rust library and the system libraries it uses. To list them for your crate, run cargo 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.
  • UILaunchScreen in the project’s info section 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.

Generate the project, then open and run it in Xcode:

cd ios
xcodegen generate # writes Notes.xcodeproj; run again after editing project.yml
open Notes.xcodeproj # then choose a simulator or a device and press Run

Alternatively, build and run in the simulator from the command line:

xcodebuild -project Notes.xcodeproj -scheme Notes -configuration Release \
-sdk iphonesimulator -derivedDataPath build build
xcrun simctl install booted build/Build/Products/Release-iphonesimulator/Notes.app
xcrun simctl launch booted dev.example.notes

Keep the generated .xcodeproj out of version control; project.yml is the source.

  1. Set DEVELOPMENT_TEAM in project.yml to 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.
  2. Enable Developer Mode on the device (Settings > Privacy & Security > Developer Mode).
  1. Add the app icon as an asset catalog (a single 1024×1024 PNG suffices) and list it under sources.
  2. In Xcode, choose Product > Archive.
  3. Upload the archive from the Organizer window.

Increase CFBundleVersion for every upload.

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_main in a library, not main (see below).
  • The window always fills the screen. Options::size, position, min_size and icon are 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 plain NativeActivity, 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_dialog has 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. Add x86_64-linux-android for emulators on Intel machines.

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.

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 resources

app/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"
}
}
  • applicationId identifies the app to Google Play and the system. Do not change it after release.
  • versionCode must increase with every release. versionName is the version shown to users.
  • minSdk 26 (Android 8) is the oldest version CPUI supports. Set targetSdk to 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.abis in gradle.properties lists the ABIs to build.
  • It compiles CPUI’s Java classes, CpuiActivity and its input view, which ship as source in the cpui crate under android/java/. The project locates the crate with cargo metadata and 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.

<?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_name is the library name without the lib prefix and the .so suffix.
  • configChanges keeps 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 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.

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 installDebug
adb shell am start -n dev.example.notes/dev.cpui.CpuiActivity
adb 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.

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 10000

Reference 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.jks
storePassword=…
keyAlias=notes
keyPassword=…

Then build the release package:

./gradlew assembleRelease # app/build/outputs/apk/release/app-release.apk

Users who download the APK directly must allow installation from that source when Android prompts them.

Google Play accepts Android App Bundles, not APKs:

./gradlew bundleRelease # app/build/outputs/bundle/release/app-release.aab

Upload the bundle in the Play Console. Play signs the packages it delivers.

  • Increase version in Cargo.toml. The packages, the .app bundle and the installers take their version from it. On Android, increase versionCode and versionName in app/build.gradle.kts. On iOS, increase CFBundleShortVersionString and CFBundleVersion in project.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 .dmg through 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 cli
    cargo about init
    cargo about generate about.hbs > THIRD-PARTY-LICENSES.html

    Fonts 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.