Jank-hunt perf feature: FR/STG/DECODE instrumentation, off by default

Residual scroll jank at 120 Hz (suspected Slint event-loop bug) needs
per-frame + per-stage timing the logcat ring buffer can't hold. New
cargo feature `perf` (default OFF — all sites are cfg-gated, zero
overhead when off):

- FR: per-frame app-side render cost + frame gap, from the rendering
  notifier (BeforeRendering/AfterRendering).
- STG: event-loop stage costs (wake/timers/events/poll/lastrender) from
  timestamps instrumented into the pinned vendor copy of
  i-slint-backend-android-activity (stg.rs; Cargo.toml now depends on
  it directly + optional under `perf`).
- DECODE: per-thumbnail-job cost on the workers.
- All lines mirrored to /sdcard/Download/.gallery_perf.log (logcat
  rotates too fast at ~120 lines/s).

Format + reading guide: docs/BUGS/scroll-jank-120hz.md.
This commit is contained in:
Greg Pomerantz 2026-10-29 08:11:51 -04:00
parent ec9fd7c189
commit d5bbb41bbd
21 changed files with 7556 additions and 2 deletions

3
Cargo.lock generated
View File

@ -1544,6 +1544,7 @@ dependencies = [
name = "gallery" name = "gallery"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"i-slint-backend-android-activity",
"image", "image",
"kamadak-exif", "kamadak-exif",
"libc", "libc",
@ -1864,8 +1865,6 @@ dependencies = [
[[package]] [[package]]
name = "i-slint-backend-android-activity" name = "i-slint-backend-android-activity"
version = "1.18.1" version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70d538003a566d7312572ac1435be0704934e46a63d55abdabede513f72332cb"
dependencies = [ dependencies = [
"android-activity 0.5.2", "android-activity 0.5.2",
"android-activity 0.6.1", "android-activity 0.6.1",

View File

@ -22,6 +22,18 @@ sha1 = "0.11.0"
turbojpeg = { version = "1.5.1", features = ["cmake"] } turbojpeg = { version = "1.5.1", features = ["cmake"] }
image = { version = "0.25.10", default-features = false, features = ["png"] } image = { version = "0.25.10", default-features = false, features = ["png"] }
kamadak-exif = "0.6.1" kamadak-exif = "0.6.1"
# STG event-loop stage timestamps, read by the jank-hunt `perf` feature
# (docs/BUGS/scroll-jank-120hz.md). Already in the graph transitively via
# slint; direct + optional so `perf` can read its `stg` module.
i-slint-backend-android-activity = { version = "1.18.1", optional = true }
[features]
# Jank-hunt instrumentation: per-frame frame-gap + render cost (FR),
# event-loop stage costs (STG), and per-job decode cost (DECODE), mirrored
# to a file on Android. OFF by default — dead-code-eliminated, zero runtime
# overhead. To capture, build with `--features perf` (format + analysis:
# docs/BUGS/scroll-jank-120hz.md).
perf = ["dep:i-slint-backend-android-activity"]
[build-dependencies] [build-dependencies]
slint-build = "1.18.1" slint-build = "1.18.1"
@ -76,3 +88,6 @@ name = "android.permission.MANAGE_EXTERNAL_STORAGE"
# docs/BUGS/slint-skia-final-flush-jank.md). Pinned to the 1.18.1 source; # docs/BUGS/slint-skia-final-flush-jank.md). Pinned to the 1.18.1 source;
# re-apply the one hunk when bumping Slint. # re-apply the one hunk when bumping Slint.
i-slint-renderer-skia = { path = "vendor/i-slint-renderer-skia" } i-slint-renderer-skia = { path = "vendor/i-slint-renderer-skia" }
# STG (jank-hunt): event-loop stage timestamps, read by the `perf` feature
# (docs/BUGS/scroll-jank-120hz.md). Pinned to the 1.18.1 source.
i-slint-backend-android-activity = { path = "vendor/i-slint-backend-android-activity-1.18.1" }

View File

@ -0,0 +1,56 @@
# Residual scroll jank at 120 Hz — `perf` instrumentation
Status (2026-10-29): the two *known* jank sources are fixed
(GPU-resident thumbnails, §8.7 of HANDOFF.md; thread priorities). A small
amount of residual jank remains on the phone (Mali G715) — suspected Slint
event-loop bug, not yet proven. This doc describes the instrumentation used
to hunt it.
## The `perf` cargo feature (off by default)
`cargo apk2 build --release --features perf --target x86_64-linux-android`
With `perf` off every instrumentation site is behind `#[cfg(feature = "perf")]`
— the code is eliminated, zero runtime overhead. With `perf` on, three
families of lines are logged (tag `gallery`) and mirrored to
`/sdcard/Download/.gallery_perf.log` (the logcat ring buffer rotates too fast
to be useful at ~120 lines/s). Only lines starting with `FR `, `STG `,
`DECODE ` or `gallery: [W` are mirrored; logcat gets everything as before.
## Line formats
- `FR <t_ms> d=<µs> gap=<ms>` — once per presented frame, from the
rendering notifier on the UI thread. `t` = ms since process start
(monotonic), `d` = app-side render cost (BeforeRendering→AfterRendering,
i.e. everything Slint does in its render pass), `gap` = ms since the
previous frame (120 Hz → 8.33 ms; a hitch = gap >> 8.33).
- `STG wake=<µs> timers=<µs> events=<µs> n=<events> poll=<µs> lastrender=<µs>`
— cost of the event-loop *stages* of the iteration just completed, from
timestamps instrumented into the vendored `i-slint-backend-android-activity`
(`vendor/i-slint-backend-android-activity-1.18.1/stg.rs`, `stg::snapshot()`):
`wake` = time from the previous iteration's poll-end to the first
Choreographer event (waker/wakeup latency), `timers` =
`update_timers_and_animations`, `events` = `process_event`, `n` = number of
polled events, `poll` = whole `poll_events`, `lastrender` = whole
`do_render` of the previous frame (draw + wgpu surface tail).
- `DECODE <ms> <hit|miss> <path>` — per-thumbnail-job cost on the worker
threads; correlates decode bursts against FR gap spikes.
## How to read a capture
1. `adb pull /sdcard/Download/.gallery_perf.log`.
2. Find hitched frames: `gap > ~20 ms` on `FR` lines.
3. For each hitch look at the same-frame `STG` line:
- big `wake` → the Choreographer waker was starved/delayed (the fixed
nice-+10 bug had exactly this signature);
- big `lastrender` → the previous frame's render tail (wgpu submit /
surface present) ran long;
- big `timers`/`events` → Slint-side event processing (our tick is
budgeted; a spike here that correlates with `DECODE` bursts is
cross-thread pressure).
4. If none of the stages explains the gap, the delay is *inside* wgpu/Vulkan
or in Slint's surface handling (the suspected-bug class).
The `STG` timestamps come from the pinned vendor crate; re-apply
`vendor/i-slint-backend-android-activity-1.18.1` (including `stg.rs`) when
bumping Slint.

View File

@ -573,11 +573,70 @@ fn install_render_notifier(window: &Main, wid: u32) {
log::info!("gputex: [W{wid}] wgpu device captured"); log::info!("gputex: [W{wid}] wgpu device captured");
} }
} }
// Jank-hunt instrumentation (`perf` feature; see
// docs/BUGS/scroll-jank-120hz.md). FR = app-side render cost
// (BeforeRendering->AfterRendering) + frame gap; STG = event-loop
// stage costs. With `perf` off these arms are empty — zero
// overhead.
slint::RenderingState::BeforeRendering => {
#[cfg(feature = "perf")]
FR_BEFORE_US.store(now_us(), std::sync::atomic::Ordering::Relaxed);
}
slint::RenderingState::AfterRendering => {
#[cfg(feature = "perf")]
{
let now = now_us();
let before = FR_BEFORE_US.load(std::sync::atomic::Ordering::Relaxed);
let last = FR_LAST_US.swap(now, std::sync::atomic::Ordering::Relaxed);
let d_us = now.saturating_sub(before);
let gap_ms = if last == 0 { 0.0 } else { (now - last) as f64 / 1000.0 };
log::info!("FR {:11.2} d={:6}us gap={:7.2}", now_ms(), d_us, gap_ms);
// STG: stage costs for the iteration just completed. wake
// = Choreographer latency, timers =
// update_timers_and_animations, events = process_event,
// poll = full poll_events, lastrender = full do_render of
// the previous frame (draw + wgpu surface tail).
#[cfg(target_os = "android")]
{
let (s0, s1, s2, _s3, _s4, stm, sev, nev) =
i_slint_backend_android_activity::stg::snapshot();
let wake = if s1 == 0 { 0 } else { s1.saturating_sub(s0) };
let poll = s2.saturating_sub(s0);
let lastrender = i_slint_backend_android_activity::stg::S_LAST_RENDER_US
.load(std::sync::atomic::Ordering::Relaxed);
log::info!(
"STG wake={wake}us timers={stm}us events={sev}us n={nev} poll={poll}us lastrender={lastrender}us"
);
}
}
}
_ => {} _ => {}
} }
}); });
} }
// Jank-hunt instrumentation (`perf` feature) — per-frame clock + frame
// bookkeeping. See docs/BUGS/scroll-jank-120hz.md.
#[cfg(feature = "perf")]
static FR_BEFORE_US: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(feature = "perf")]
static FR_LAST_US: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Monotonic ms since process start (wall clock could jump on NTP).
#[cfg(feature = "perf")]
static NOW_T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
#[cfg(feature = "perf")]
#[inline]
fn now_ms() -> f64 {
let t0 = NOW_T0.get_or_init(std::time::Instant::now);
t0.elapsed().as_secs_f64() * 1000.0
}
#[cfg(feature = "perf")]
fn now_us() -> u64 {
NOW_T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
}
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
mod nblog { mod nblog {
//! Non-blocking logger. `log` calls on the UI thread must NEVER block: //! Non-blocking logger. `log` calls on the UI thread must NEVER block:
@ -585,6 +644,7 @@ mod nblog {
//! UI thread for 10–40 ms. Records are formatted at the call site and //! UI thread for 10–40 ms. Records are formatted at the call site and
//! pushed into a bounded channel; a drain thread does the real //! pushed into a bounded channel; a drain thread does the real
//! `__android_log_write` and DROPS records when saturated. //! `__android_log_write` and DROPS records when saturated.
use std::io::Write as _;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc; use std::sync::mpsc;
use log::{Level, Log, Metadata, Record}; use log::{Level, Log, Metadata, Record};
@ -604,7 +664,55 @@ mod nblog {
std::thread::Builder::new() std::thread::Builder::new()
.name("log-drain".into()) .name("log-drain".into())
.spawn(move || { .spawn(move || {
// Jank-hunt (`perf` feature): mirror FR/STG/DECODE lines
// to a file — the logcat ring buffer rotates every few
// seconds. See docs/BUGS/scroll-jank-120hz.md.
#[cfg(feature = "perf")]
let mut perf: Option<std::io::BufWriter<std::fs::File>> =
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open("/sdcard/Download/.gallery_perf.log")
.ok()
.map(std::io::BufWriter::new);
#[cfg(feature = "perf")]
let mut n = 0usize;
for (prio, msg) in rx { for (prio, msg) in rx {
#[cfg(feature = "perf")]
{
if perf.is_none()
&& (msg.starts_with("FR ")
|| msg.starts_with("STG ")
|| msg.starts_with("DECODE ")
|| msg.starts_with("gallery: [W"))
{
// The file may not have been openable at
// thread start (e.g. MANAGE_EXTERNAL_STORAGE
// granted later). Retry until it opens.
if let Ok(f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open("/sdcard/Download/.gallery_perf.log")
{
perf = Some(std::io::BufWriter::new(f));
}
}
if let Some(w) = perf.as_mut() {
if msg.starts_with("FR ")
|| msg.starts_with("STG ")
|| msg.starts_with("DECODE ")
|| msg.starts_with("gallery: [W")
{
let _ = std::io::Write::write_all(w, msg.as_bytes());
let _ = w.write_all(b"\n");
n += 1;
if n >= 32 {
let _ = w.flush();
n = 0;
}
}
}
}
let b = msg.into_bytes(); let b = msg.into_bytes();
let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
let mut safe: Vec<u8> = let mut safe: Vec<u8> =

View File

@ -439,6 +439,17 @@ fn worker_loop(
let t0 = Instant::now(); let t0 = Instant::now();
let (ok, thumb, from_cache) = process(&job, &cache_dir, target, &hits, &errs); let (ok, thumb, from_cache) = process(&job, &cache_dir, target, &hits, &errs);
let elapsed = t0.elapsed().as_millis(); let elapsed = t0.elapsed().as_millis();
// Jank-hunt (`perf` feature): per-job decode cost, correlated
// against FR gap spikes. See docs/BUGS/scroll-jank-120hz.md.
#[cfg(feature = "perf")]
{
log::info!(
"DECODE {}ms {} {}",
elapsed,
if from_cache { "hit" } else { "miss" },
job.path
);
}
if let Some(ref mut c) = conn { if let Some(ref mut c) = conn {
if let Some(ref t) = thumb { if let Some(ref t) = thumb {

View File

@ -0,0 +1 @@
{"v":1}

View File

@ -0,0 +1,6 @@
{
"git": {
"sha1": "372cf0ee5577c3dfec309a45e7b778ba4e81b734"
},
"path_in_vcs": "internal/backends/android-activity"
}

3617
vendor/i-slint-backend-android-activity-1.18.1/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,114 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.92"
name = "i-slint-backend-android-activity"
version = "1.18.1"
authors = ["Slint Developers <info@slint.dev>"]
build = "build.rs"
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "OpenGL rendering backend for Slint"
homepage = "https://slint.dev"
readme = "README.md"
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
repository = "https://github.com/slint-ui/slint"
[package.metadata.docs.rs]
targets = [
"aarch64-linux-android",
"armv7-linux-androideabi",
"i686-linux-android",
"x86_64-linux-android",
]
features = [
"native-activity",
"aa-06",
]
rustdoc-args = ["--generate-link-to-definition"]
[features]
aa-05 = [
"android-activity-05",
"ndk-08",
]
aa-06 = [
"android-activity-06",
"ndk-09",
]
game-activity = [
"android-activity-06?/game-activity",
"android-activity-05?/game-activity",
]
native-activity = [
"android-activity-06?/native-activity",
"android-activity-05?/native-activity",
]
unstable-wgpu-29 = ["i-slint-renderer-skia/unstable-wgpu-29"]
unstable-wgpu-30 = ["i-slint-renderer-skia/unstable-wgpu-30"]
[lib]
name = "i_slint_backend_android_activity"
path = "lib.rs"
[build-dependencies.android-build]
version = "0.1.2"
[target.'cfg(target_os = "android")'.dependencies.android-activity-05]
version = "0.5"
optional = true
package = "android-activity"
[target.'cfg(target_os = "android")'.dependencies.android-activity-06]
version = "0.6"
optional = true
package = "android-activity"
[target.'cfg(target_os = "android")'.dependencies.i-slint-common]
version = "=1.18.1"
default-features = false
[target.'cfg(target_os = "android")'.dependencies.i-slint-core]
version = "=1.18.1"
features = [
"std",
"image-decoders",
"svg",
]
default-features = false
[target.'cfg(target_os = "android")'.dependencies.i-slint-renderer-skia]
version = "=1.18.1"
default-features = false
[target.'cfg(target_os = "android")'.dependencies.jni]
version = "0.22"
[target.'cfg(target_os = "android")'.dependencies.ndk-08]
version = "0.8.0"
features = ["rwh_06"]
optional = true
package = "ndk"
[target.'cfg(target_os = "android")'.dependencies.ndk-09]
version = "0.9.0"
features = ["rwh_06"]
optional = true
default-features = false
package = "ndk"
[target.'cfg(target_os = "android")'.dependencies.raw-window-handle]
version = "0.6"

View File

@ -0,0 +1,46 @@
# Copyright © SixtyFPS GmbH <info@slint.dev>
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
# cSpell: ignore androideabi
[package]
name = "i-slint-backend-android-activity"
description = "OpenGL rendering backend for Slint"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
[lib]
path = "lib.rs"
[features]
game-activity = ["android-activity-06?/game-activity", "android-activity-05?/game-activity"]
native-activity = ["android-activity-06?/native-activity", "android-activity-05?/native-activity"]
aa-06 = ["android-activity-06", "ndk-09"]
aa-05 = ["android-activity-05", "ndk-08"]
unstable-wgpu-29 = ["i-slint-renderer-skia/unstable-wgpu-29"]
unstable-wgpu-30 = ["i-slint-renderer-skia/unstable-wgpu-30"]
[target.'cfg(target_os = "android")'.dependencies]
i-slint-renderer-skia = { workspace = true }
i-slint-core = { workspace = true, features = ["std", "image-decoders", "svg"] }
i-slint-common = { workspace = true }
raw-window-handle = { version = "0.6" }
android-activity-05 = { package = "android-activity", version = "0.5", optional = true }
android-activity-06 = { package = "android-activity", version = "0.6", optional = true }
jni = { version = "0.22" }
# We only depends on the NDK directly to enable raw-window-handle 0.6 which we need for the skia renderer
ndk-08 = { package = "ndk", version = "0.8.0", optional = true, features = ["rwh_06"] }
ndk-09 = { package = "ndk", version = "0.9.0", optional = true, features = ["rwh_06"], default-features = false }
[build-dependencies]
android-build = "0.1.2"
[package.metadata.docs.rs]
targets = ["aarch64-linux-android", "armv7-linux-androideabi", "i686-linux-android", "x86_64-linux-android"]
features = ["native-activity", "aa-06"]
rustdoc-args = ["--generate-link-to-definition"]

View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU 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 Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,43 @@
# Slint Royalty-free Desktop, Mobile, and Web Applications License
Version 2.0
## Preamble
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Royalty-free Desktop, Mobile, and Web Applications License** is suitable for those who develop desktop, mobile, or web applications and do not want to use open source components under copyleft licenses.
## 1. Grant of Rights
SixtyFPS hereby grants You a world-wide, royalty-free, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application.
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
## 2. License Conditions - Attribution
You may distribute the Software as part of an Application, modified or unmodified, provided that You do either of the following:
(a) Display the [`AboutSlint`](https://docs.slint.dev/latest/docs/slint/reference/std-widgets/misc/aboutslint/) widget in an "About" screen or dialog that is accessible from the top level menu of the Application. In the absence of such a screen or dialog, display the widget in the "Splash Screen" of the Application.
(b) Display the [Slint attribution badge](https://github.com/slint-ui/slint/tree/master/logo/MadeWithSlint-logo-whitebg.png) on a public webpage, preferably where the binaries of your Application can be downloaded from, in such a way that it can be easily found by any visitor to that page.
## 3. Limitations
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application. For this purpose you may use the Software under the GNU General Public License, version 3.
The License does not permit the use of the Software within Embedded Systems. An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
## 4. Warranty and Liability
SixtyFPS is only liable for conflicting rights of third parties if SixtyFPS was aware of these rights without informing you. Unless required by applicable law or agreed to in writing, SixtyFPS provides the Software on an "as is" basis, without warranties or conditions of any kind, either express or implied, including, without limitation, any warranties or conditions of merchantability, or fitness for a particular purpose.
Unless required by law, SixtyFPS won't be liable for any direct, indirect, incidental, or consequential damages arising in any way out of the use of the Software.

View File

@ -0,0 +1,117 @@
# Slint Software License
Version 3.0.5
## Preamble
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Software License** is suitable for those who do not want to use open source components under copyleft licenses.
## 1. Grant of Rights
SixtyFPS hereby grants You a world-wide, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application or as part of an Embedded System (each of which is defined below).
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
## 2. License Conditions
The grant of rights in section 1 are conditional, provided that You do all of the following:
(a) You have purchased an appropriate **Paid License Plan** ([see Annex 1](#annex-1-paid-license-plans)) and the required amount of seats to cover all individual users of the Software associated with the designing, developing, or testing your Application or Embedded System. For clarity, each individual user is counted as one seat.
(b) In the case that You are distributing the Software as part of an Embedded System, You have purchased an appropriate quantity of **Royalties**, one Royalty for each Embedded System. Royalties become due and payable upon manufacture of the Embedded System, regardless of whether such is subsequently sold, shipped, returned, replaced under warranty, or recalled. Payment of royalties is non-refundable under any circumstances. Royalties are not necessary for non-commercial projects, personal projects, and open source projects.
## 3. Limitations
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application or into an Embedded System. For this purpose you may use the Software under the GNU General Public License, version 3.
The License is limited to only the versions of Software that were made available to you under the Paid License Plan. For all other versions, you may use the Software under either the GNU General Public License, version 3 or the Slint Royalty-free Desktop, Mobile, and Web Applications License.
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
## 4. Audit Rights
SixtyFPS or an independent certified auditor on SixtyFPS's behalf, may, upon its reasonable request, with 30 (thirty) days written notice, and at its sole expense, examine your books and records solely with respect to your use of the Software. Any such audit shall be conducted during regular business hours at your facilities and shall not unreasonably interfere with your business activities. The auditor shall not remove, copy, or redistribute any electronic material during an audit. If an audit reveals that you are using the Software in a way that is in material violation of the terms of this License, then you shall pay SixtyFPS reasonable costs of conducting the audit. The auditor shall only be allowed to report violations of the terms of this License, with a copy to you. You shall be provided the right to provide comments to the report before it is finalized.
## 5. Termination
(a) SixtyFPS may terminate this License if You materially breach any obligation hereunder, provided You have been provided notice of such breach and an opportunity to cure such breach during a period of not less than sixty (60) days following such notice.
(b) You may terminate this License with or without cause upon no less than thirty (30) days advance written notice to SixtyFPS.
(c) Upon termination of this License, You will immediately cease using, reproducing, making available, modifying, displaying, performing, distributing the Software and pay immediately any unpaid Fees and contractual penalties.
(d) Sections 3 through 8 of this License will survive any termination of the License to the extent necessary to implement their objectives.
## 6. Assignment
You may assign this License, in whole or in part (whether by operation of law or otherwise), with prior consent from SixtyFPS, which shall not be unreasonably withheld or delayed. SixtyFPS may assign any of its rights or delegate any of its obligations hereunder with prior notice to You, provided that the successor maintains at least the same level of security, confidentiality, and data protection measures as in place at the time of assignment or delegation. Any attempt to assign this License other than in accordance with this Section 6 shall be null and void.
## 7. Severability
In the event that any provision of this License will, for any reason, be determined by any court of competent jurisdiction to be invalid, illegal or unenforceable in any respect, such invalidity, illegality or unenforceability will be interpreted as closely as possible so as not affect any other provision of this License, and such provision will further be modified by said court to permit its enforcement to the maximum extent permitted by law.
## 8. Governing Law
This Agreement shall be construed, interpreted, and governed by the laws of the Federal Republic of Germany.
## Annex 1: Paid License Plans
### Enterprise Plan
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
(d) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(e) GUI Test Framework.
### Small Enterprise Plan
This plan is limited to individual companies with a staff headcount of upto 50 and either a turnover or balance sheet total of 10 million EUR or less. If You are a Small Enterprise, You are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
The following can be purchased as an Add-On
(a) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(b) GUI Test Framework.
### Startup & Individual Plan
This plan is limited to individuals and individual companies with a staff headcount of less than 10 and either a turnover or balance sheet total of 2 million EUR or less. If You are a Startup, you are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
The following can be purchased as an Add-On
(a) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
(b) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(c) GUI Test Framework.

View File

@ -0,0 +1,14 @@
**NOTE**: This library is an **internal** crate of the [Slint project](https://slint.dev).
**WARNING**: This crate does not follow the semver convention for versioning and can
only be used with `version = "=x.y.z"` in Cargo.toml.
# Slint Android Activity Backend
This crate implements the Android backend/platform for Slint.
It uses the [android-activity](https://github.com/rust-mobile/android-activity) crate
to initialize the app and provide events handling.
It can be used by using functions from the [slint::android](https://slint.dev/docs/rust/slint/android/) module

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,86 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore Dexer multidex
use std::env;
use std::path::PathBuf;
use android_build::{Dexer, JavaBuild};
fn main() {
println!("cargo:rustc-check-cfg=cfg(slint_nightly_test)");
if !env::var("TARGET").unwrap().contains("android") {
return;
}
let release_mode = env::var("PROFILE").as_ref().map(|s| s.as_str()) == Ok("release");
// This is the only Java source file
let java_src = "SlintAndroidJavaHelper.java";
let java_src_path = format!("java/{java_src}");
let slint_path: PathBuf = ["dev", "slint", "android-activity"].iter().collect();
let out_dir: PathBuf = env::var_os("OUT_DIR").unwrap().into();
let mut out_class_dir = out_dir.clone();
out_class_dir.push("java");
out_class_dir.push(slint_path);
if out_class_dir.try_exists().unwrap_or(false) {
let _ = std::fs::remove_dir_all(&out_class_dir);
}
std::fs::create_dir_all(&out_class_dir)
.unwrap_or_else(|e| panic!("Cannot create output directory {out_class_dir:?} - {e}"));
let android_jar = android_build::android_jar(None).expect("No Android platforms found");
// Compile the Java file into .class files
let o = JavaBuild::new()
.file(&java_src_path)
.class_path(&android_jar)
.classes_out_dir(&out_class_dir)
.java_source_version(8)
.java_target_version(8)
.debug_info(android_build::DebugInfo {
line_numbers: !release_mode,
variables: !release_mode,
source_files: !release_mode,
})
.command()
.unwrap_or_else(|e| panic!("Could not generate the java compiler command: {e}"))
.args(["-encoding", "UTF-8"])
.output()
.unwrap_or_else(|e| panic!("Could not run the java compiler: {e}"));
if !o.status.success() {
panic!("Java compilation failed: {}", String::from_utf8_lossy(&o.stderr));
}
let o = Dexer::new()
.android_jar(&android_jar)
.class_path(&out_class_dir)
.collect_classes(&out_class_dir)
.unwrap()
.release(release_mode)
.android_min_api(20) // disable multidex for single dex file output
.out_dir(out_dir)
.command()
.unwrap_or_else(|e| panic!("Could not generate the D8 command: {e}"))
.output()
.unwrap_or_else(|e| panic!("Error running D8: {e}"));
if !o.status.success() {
eprintln!("Dex conversion failed: {}", String::from_utf8_lossy(&o.stderr));
let java_home = android_build::java_home().unwrap();
let java_ver = android_build::check_javac_version(&java_home).unwrap();
if java_ver >= 21 {
eprintln!("WARNING: JDK version 21 is known to cause an error with older android SDK");
eprintln!("See https://github.com/slint-ui/slint/issues/4973");
eprintln!(
"Try downgrading your version of Java to something like JDK 17, or upgrade to the SDK build tools 35"
);
}
panic!("Dex conversion failed");
}
println!("cargo:rerun-if-changed={java_src_path}");
}

View File

@ -0,0 +1,731 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell:ignore Spannable tbstart tbend
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowInsetsAnimation;
import android.view.WindowMetrics;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.BlendMode;
import android.graphics.BlendModeColorFilter;
import android.graphics.Insets;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.app.Activity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.view.inputmethod.BaseInputConnection;
import android.os.Build;
import android.window.OnBackInvokedCallback;
import android.window.OnBackInvokedDispatcher;
class InputHandle extends ImageView {
private PopupWindow mPopupWindow;
private float mPressedX;
private float mPressedY;
private SlintInputView mRootView;
private int cursorX;
private int cursorY;
private int attr;
public InputHandle(SlintInputView rootView, int attr) {
super(rootView.getContext());
this.attr = attr;
mRootView = rootView;
Context ctx = rootView.getContext();
mPopupWindow = new PopupWindow(ctx, null, android.R.attr.textSelectHandleWindowStyle);
mPopupWindow.setSplitTouchEnabled(true);
mPopupWindow.setClippingEnabled(false);
int[] attrs = { attr };
Drawable drawable = ctx.getTheme().obtainStyledAttributes(attrs).getDrawable(0);
mPopupWindow.setWidth(drawable.getIntrinsicWidth());
mPopupWindow.setHeight(drawable.getIntrinsicHeight());
this.setImageDrawable(drawable);
mPopupWindow.setContentView(this);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
mPressedX = ev.getRawX() - cursorX;
mPressedY = ev.getRawY() - cursorY;
break;
}
case MotionEvent.ACTION_MOVE: {
mRootView.hideActionMenu(ActionMode.DEFAULT_HIDE_DURATION);
int id = attr == android.R.attr.textSelectHandleLeft ? 1
: attr == android.R.attr.textSelectHandleRight ? 2 : 0;
SlintAndroidJavaHelper.moveCursorHandle(id, Math.round(ev.getRawX() - mPressedX),
Math.round(ev.getRawY() - mPressedY));
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
public void setPosition(int x, int y) {
cursorX = x;
cursorY = y;
if (attr == android.R.attr.textSelectHandleLeft) {
x -= 3 * mPopupWindow.getWidth() / 4;
} else if (attr == android.R.attr.textSelectHandleRight) {
x -= mPopupWindow.getWidth() / 4;
} else {
x -= mPopupWindow.getWidth() / 2;
}
mPopupWindow.showAtLocation(mRootView, 0, x, y);
mPopupWindow.update(x, y, -1, -1);
}
public void hide() {
mPopupWindow.dismiss();
}
public void setHandleColor(int color) {
Drawable drawable = getDrawable();
if (drawable != null) {
if (android.os.Build.VERSION.SDK_INT >= 29) {
drawable.setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_IN));
} else {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
setImageDrawable(drawable);
}
}
}
class SlintInputView extends View {
private String mText = "";
private int mCursorPosition = 0;
private int mAnchorPosition = 0;
private int mPreeditStart = 0;
private int mPreeditEnd = 0;
private int mInputType = EditorInfo.TYPE_CLASS_TEXT;
private int mInBatch = 0;
private boolean mPending = false;
private SlintEditable mEditable;
public class SlintEditable extends SpannableStringBuilder {
public SlintEditable() {
super(mText);
}
@Override
public SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend) {
super.replace(start, end, tb, tbstart, tbend);
setCursorPos(0, 0, 0, 0, 0, 0);
if (mInBatch == 0) {
update();
} else {
mPending = true;
}
return this;
}
public void update() {
mPending = false;
mText = toString();
mCursorPosition = Selection.getSelectionStart(this);
mAnchorPosition = Selection.getSelectionEnd(this);
mPreeditStart = BaseInputConnection.getComposingSpanStart(this);
mPreeditEnd = BaseInputConnection.getComposingSpanEnd(this);
SlintAndroidJavaHelper.updateText(mText, mCursorPosition, mAnchorPosition, mPreeditStart, mPreeditEnd);
}
}
public SlintInputView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
mEditable = new SlintEditable();
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.inputType = mInputType;
outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI;
outAttrs.initialSelStart = mCursorPosition;
outAttrs.initialSelEnd = mAnchorPosition;
return new BaseInputConnection(this, true) {
@Override
public Editable getEditable() {
return mEditable;
}
@Override
public boolean beginBatchEdit() {
mInBatch += 1;
return super.beginBatchEdit();
}
@Override
public boolean endBatchEdit() {
mInBatch -= 1;
if (mInBatch == 0 && mPending) {
mEditable.update();
}
return super.endBatchEdit();
}
};
}
public void setText(String text, int cursorPosition, int anchorPosition, int preeditStart, int preeditEnd,
int inputType) {
boolean typeChanged = mInputType != inputType;
boolean textChanged = !mText.equals(text);
boolean selectionChanged = mCursorPosition != cursorPosition || mAnchorPosition != anchorPosition;
mText = text;
mCursorPosition = cursorPosition;
mAnchorPosition = anchorPosition;
mPreeditStart = preeditStart;
mPreeditEnd = preeditEnd;
mInputType = inputType;
if (typeChanged) {
mEditable = new SlintEditable();
Selection.setSelection(mEditable, cursorPosition, anchorPosition);
InputMethodManager imm = (InputMethodManager) this.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.restartInput(this);
} else if (textChanged || selectionChanged) {
InputMethodManager imm = (InputMethodManager) this.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
mInBatch += 1;
try {
if (textChanged) {
mEditable.replace(0, mEditable.length(), text);
}
if (Selection.getSelectionStart(mEditable) != cursorPosition
|| Selection.getSelectionEnd(mEditable) != anchorPosition) {
Selection.setSelection(mEditable, cursorPosition, anchorPosition);
}
} finally {
mInBatch -= 1;
mPending = false;
}
imm.updateSelection(this, cursorPosition, anchorPosition, preeditStart, preeditEnd);
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int currentNightMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
SlintAndroidJavaHelper.setNightMode(currentNightMode);
SlintAndroidJavaHelper.setFontScale(newConfig.fontScale);
}
private InputHandle mCursorHandle;
private InputHandle mLeftHandle;
private InputHandle mRightHandle;
public Rect selectionRect = new Rect();
// num_handles: 0=hidden, 1=cursor handle, 2=selection handles
public void setCursorPos(int left_x, int left_y, int right_x, int right_y, int cursor_height, int num_handles) {
int handleHeight = 0;
if (num_handles == 1) {
if (mLeftHandle != null) {
mLeftHandle.hide();
}
if (mRightHandle != null) {
mRightHandle.hide();
}
if (left_x != -1) {
if (mCursorHandle == null) {
mCursorHandle = new InputHandle(this, android.R.attr.textSelectHandle);
}
mCursorHandle.setPosition(left_x, left_y);
handleHeight = mCursorHandle.getHeight();
} else if (mCursorHandle != null) {
mCursorHandle.hide();
}
} else if (num_handles == 2) {
if (left_x != -1) {
if (mLeftHandle == null) {
mLeftHandle = new InputHandle(this, android.R.attr.textSelectHandleLeft);
}
mLeftHandle.setPosition(left_x, left_y);
handleHeight = mLeftHandle.getHeight();
} else {
if (mLeftHandle != null) {
mLeftHandle.hide();
}
}
if (right_x != -1) {
if (mRightHandle == null) {
mRightHandle = new InputHandle(this, android.R.attr.textSelectHandleRight);
}
mRightHandle.setPosition(right_x, right_y);
handleHeight = mRightHandle.getHeight();
} else {
if (mRightHandle != null) {
mRightHandle.hide();
}
}
if (mCursorHandle != null) {
mCursorHandle.hide();
}
showActionMenu();
} else {
if (mCursorHandle != null) {
handleHeight = mCursorHandle.getHeight();
mCursorHandle.hide();
}
if (mLeftHandle != null) {
mLeftHandle.hide();
}
if (mRightHandle != null) {
mRightHandle.hide();
}
hideActionMenu(-1);
}
selectionRect.set(Math.min(left_x, right_x), Math.min(left_y, right_y) - cursor_height,
Math.max(left_x, right_x), Math.max(left_y, right_y) + handleHeight);
if (mCurrentActionMode != null) {
mCurrentActionMode.invalidateContentRect();
}
}
public void setHandleColor(int color) {
if (mCursorHandle != null) {
mCursorHandle.setHandleColor(color);
}
if (mLeftHandle != null) {
mLeftHandle.setHandleColor(color);
}
if (mRightHandle != null) {
mRightHandle.setHandleColor(color);
}
}
private ActionMode mCurrentActionMode;
public void showActionMenu() {
if (mCurrentActionMode != null) {
mCurrentActionMode.hide(0);
return;
}
ActionMode.Callback2 action = new ActionMode.Callback2() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle(null);
mode.setSubtitle(null);
mode.setTitleOptionalHint(true);
if (android.os.Build.VERSION.SDK_INT >= 28) {
menu.setGroupDividerEnabled(true);
}
final TypedArray a = getContext().obtainStyledAttributes(new int[] {
android.R.attr.actionModeCutDrawable,
android.R.attr.actionModeCopyDrawable,
android.R.attr.actionModePasteDrawable,
android.R.attr.actionModeSelectAllDrawable,
});
// Note: the ids are used in Java_SlintAndroidJavaHelper_popupMenuAction
menu.add(Menu.FIRST, 0, 0, android.R.string.cut)
.setAlphabeticShortcut('x')
.setIcon(a.getDrawable(0));
menu.add(Menu.FIRST, 1, 1, android.R.string.copy)
.setAlphabeticShortcut('c')
.setIcon(a.getDrawable(1));
menu.add(Menu.FIRST, 2, 2, android.R.string.paste)
.setAlphabeticShortcut('v')
.setIcon(a.getDrawable(2));
menu.add(Menu.FIRST, 3, 3, android.R.string.selectAll)
.setAlphabeticShortcut('a')
.setIcon(a.getDrawable(3));
a.recycle();
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
SlintAndroidJavaHelper.popupMenuAction(item.getItemId());
mode.finish();
return true;
}
@Override
public void onDestroyActionMode(ActionMode action) {
}
// Introduced in API level 23
@Override
public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
outRect.set(selectionRect);
if (outRect.top < 0) {
// FIXME: I don't know why this is the case, but without that, the menu doesn't
// show at the right position when there is no room on top.
// Looks like the menu is always shown at outRect.top.
outRect.top = outRect.bottom;
}
}
};
mCurrentActionMode = startActionMode(action, ActionMode.TYPE_FLOATING);
}
public void hideActionMenu(int duration) {
if (mCurrentActionMode != null) {
if (duration < 0) {
mCurrentActionMode.finish();
mCurrentActionMode = null;
} else {
mCurrentActionMode.hide(duration);
}
}
}
}
public class SlintAndroidJavaHelper {
Activity mActivity;
SlintInputView mInputView;
private OnBackInvokedCallback mBackCallback;
public SlintAndroidJavaHelper(Activity activity) {
this.mActivity = activity;
this.mInputView = new SlintInputView(activity);
this.mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
mActivity.addContentView(mInputView, params);
mInputView.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
mActivity.getWindow().getDecorView().getRootView()
.setOnApplyWindowInsetsListener((v, insets) -> dispatchInsets(insets));
// Attach the IME animation callback to the input view rather than the
// decor root: some OEM ROMs fail to render the IME surface when an
// animation callback is installed on the window's root view.
mInputView.setWindowInsetsAnimationCallback(
new WindowInsetsAnimation.Callback(
WindowInsetsAnimation.Callback.DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
@Override
public WindowInsets onProgress(WindowInsets insets,
java.util.List<WindowInsetsAnimation> runningAnimations) {
return dispatchInsets(insets);
}
});
}
// On API 34+, Back arrives via OnBackInvokedDispatcher; forward
// it into Slint's key-event pipeline.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && mBackCallback == null) {
mBackCallback = () -> SlintAndroidJavaHelper.onBackInvoked();
mActivity.getOnBackInvokedDispatcher().registerOnBackInvokedCallback(
OnBackInvokedDispatcher.PRIORITY_DEFAULT, mBackCallback);
}
}
});
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
activity.getWindow().getDecorView().getRootView().getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Rect windowRect = get_view_rect();
Rect safeAreaRect = get_safe_area();
// This is only an approximation, because SDK level < 30 doesn't provide
// a way to get the keyboard area directly.
Rect visibleRect = new Rect();
mActivity.getWindow().getDecorView().getRootView()
.getWindowVisibleDisplayFrame(visibleRect);
int keyboardBottom = windowRect.bottom - visibleRect.bottom;
int keyboardLeft = windowRect.left - visibleRect.left;
int keyboardTop = windowRect.top - visibleRect.top;
int keyboardRight = windowRect.right - visibleRect.right;
int max = Math.max(keyboardBottom, Math.max(keyboardLeft,
Math.max(keyboardTop, keyboardRight)));
// only take the largest value (it's probably always going to be bottom)
if (max == keyboardBottom) {
keyboardTop = 0;
keyboardLeft = 0;
keyboardRight = 0;
} else if (max == keyboardLeft) {
keyboardTop = 0;
keyboardRight = 0;
keyboardBottom = 0;
} else if (max == keyboardTop) {
keyboardLeft = 0;
keyboardRight = 0;
keyboardBottom = 0;
} else {
keyboardTop = 0;
keyboardLeft = 0;
keyboardBottom = 0;
}
SlintAndroidJavaHelper.setInsets(
windowRect.top, windowRect.left,
windowRect.bottom, windowRect.right,
safeAreaRect.top, safeAreaRect.left,
safeAreaRect.bottom, safeAreaRect.right,
keyboardTop, keyboardLeft,
keyboardBottom, keyboardRight);
}
});
}
});
}
}
private WindowInsets dispatchInsets(WindowInsets insets) {
// The listener-supplied `insets` reflects what reaches the decor view
// AFTER any ancestor has consumed insets, so in edge-to-edge mode the
// system bars and the display cutout often arrive as zero. Read those
// straight from the WindowManager, which always returns the unconsumed
// values — matching what get_safe_area() does. The IME inset still
// comes from the listener stream so keyboard show/hide animates.
Insets sysBars;
Insets cutout;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsets src = mActivity.getWindowManager().getCurrentWindowMetrics().getWindowInsets();
sysBars = src.getInsets(WindowInsets.Type.systemBars());
cutout = src.getInsets(WindowInsets.Type.displayCutout());
} else {
sysBars = insets.getInsets(WindowInsets.Type.systemBars());
cutout = insets.getInsets(WindowInsets.Type.displayCutout());
}
Insets safeAreaInsets = Insets.max(sysBars, cutout);
Insets keyboardAreaInsets = insets.getInsets(WindowInsets.Type.ime());
Rect windowRect = get_view_rect();
SlintAndroidJavaHelper.setInsets(
windowRect.top, windowRect.left,
windowRect.bottom, windowRect.right,
safeAreaInsets.top, safeAreaInsets.left,
safeAreaInsets.bottom, safeAreaInsets.right,
keyboardAreaInsets.top, keyboardAreaInsets.left,
keyboardAreaInsets.bottom, keyboardAreaInsets.right);
return insets;
}
public void show_keyboard() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mInputView.requestFocus();
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mInputView, 0);
}
});
}
public void hide_keyboard() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInputView.getWindowToken(), 0);
mInputView.clearFocus();
mInputView.setCursorPos(0, 0, 0, 0, 0, 0);
}
});
}
// Called from Rust when an OnBackInvokedCallback fires and Slint's key
// dispatch reports the Back key as unhandled — preserves the legacy
// Back-closes-the-activity default.
public void finish_activity() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mActivity.finish();
}
});
}
static public native void updateText(String text, int cursorPosition, int anchorPosition, int preeditStart,
int preeditOffset);
static public native void setNightMode(int nightMode);
static public native void setFontScale(float fontScale);
static public native void onBackInvoked();
static public native void moveCursorHandle(int id, int pos_x, int pos_y);
static public native void popupMenuAction(int id);
static public native void setInsets(int window_top, int window_left, int window_bottom, int window_right,
int safe_area_top, int safe_area_left, int safe_area_bottom, int safe_area_right,
int keyboard_top, int keyboard_left, int keyboard_bottom, int keyboard_right);
public void set_imm_data(String text, int cursor_position, int anchor_position, int preedit_start, int preedit_end,
int cur_x, int cur_y, int anchor_x, int anchor_y, int cursor_height, int input_type,
boolean show_cursor_handles) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
int selStart = Math.min(cursor_position, anchor_position);
int selEnd = Math.max(cursor_position, anchor_position);
mInputView.setText(text, selStart, selEnd, preedit_start, preedit_end, input_type);
int num_handles = 0;
if (show_cursor_handles) {
num_handles = cursor_position == anchor_position ? 1 : 2;
}
if (cursor_position < anchor_position) {
mInputView.setCursorPos(cur_x, cur_y, anchor_x, anchor_y, cursor_height, num_handles);
} else {
mInputView.setCursorPos(anchor_x, anchor_y, cur_x, cur_y, cursor_height, num_handles);
}
}
});
}
public void set_handle_color(int color) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mInputView.setHandleColor(color);
}
});
}
public int color_scheme() {
int nightModeFlags = mActivity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
return nightModeFlags;
}
public float font_scale() {
return mActivity.getResources().getConfiguration().fontScale;
}
public int accent_color() {
TypedValue typedValue = new TypedValue();
if (mActivity.getTheme().resolveAttribute(android.R.attr.colorAccent, typedValue, true)) {
return mActivity.getColor(typedValue.resourceId);
}
return 0;
}
// Get the size of the window
public Rect get_view_rect() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// On Android 11 and above, we can get the window bounds directly
WindowMetrics metrics = mActivity.getWindowManager().getCurrentWindowMetrics();
return metrics.getBounds();
} else {
View rootView = mActivity.getWindow().getDecorView().getRootView();
return new Rect(rootView.getLeft(), rootView.getTop(), rootView.getRight(), rootView.getBottom());
}
}
// On SDK level < 30, returns the inset for the safe area and the keyboard.
// On SDK level >= 30, returns the inset for the safe area only.
public Rect get_safe_area() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics metrics = mActivity.getWindowManager().getCurrentWindowMetrics();
WindowInsets insets = metrics.getWindowInsets();
Insets safeArea = Insets.max(
insets.getInsets(WindowInsets.Type.systemBars()),
insets.getInsets(WindowInsets.Type.displayCutout()));
return new Rect(safeArea.left, safeArea.top, safeArea.right, safeArea.bottom);
} else {
View decorView = mActivity.getWindow().getDecorView();
// Note: `View.getRootWindowInsets` requires API level 23 or above
WindowInsets insets = decorView.getRootView().getRootWindowInsets();
if (insets != null) {
return new Rect(
insets.getStableInsetLeft(),
insets.getStableInsetTop(),
insets.getStableInsetRight(),
insets.getStableInsetBottom());
}
return new Rect(0, 0, 0, 0);
}
}
public void show_action_menu() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mInputView.showActionMenu();
}
});
}
public String get_clipboard() {
FutureTask<String> future = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
return item.getText().toString();
}
return "";
}
});
mActivity.runOnUiThread(future);
try {
return future.get(); // Wait for the result and return it
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public void set_clipboard(String text) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(null, text);
clipboard.setPrimaryClip(clip);
}
});
}
}

View File

@ -0,0 +1,855 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore dalvik jboolean jfloat jint
use super::*;
use i_slint_common::unicode_utils::{
byte_offset_to_utf16_offset, utf16_offset_to_byte_offset_clamped,
};
use i_slint_core::SharedString;
use i_slint_core::api::{PhysicalPosition, PhysicalSize};
use i_slint_core::graphics::{Color, euclid};
use i_slint_core::input::{InternalKeyEvent, KeyEvent, KeyEventType};
use i_slint_core::item_rendering::HasFont;
use i_slint_core::items::{CapitalizationMode, ColorScheme, InputType};
use i_slint_core::lengths::{LogicalLength, PhysicalEdges};
use i_slint_core::platform::{Key, WindowAdapter, WindowEvent, WindowEventDispatchResult};
use jni::objects::{JClass, JClassLoader, JString, LoaderContext};
use jni::sys::{jfloat, jint};
use jni::{Env, JavaVM, bind_java_type};
use std::sync::OnceLock;
use std::time::Duration;
/// Maps an Android `Configuration.fontScale` to a Slint default font size.
/// 14 LP = Material Design body-text size at `fontScale = 1.0`.
pub(crate) fn font_scale_to_logical_length(font_scale: f32) -> Option<LogicalLength> {
(font_scale.is_finite() && font_scale > 0.0).then(|| LogicalLength::new(14.0 * font_scale))
}
const DEX_DATA: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/classes.dex"));
bind_java_type! {
SlintAndroidJavaHelper => ".SlintAndroidJavaHelper",
type_map = {
AndroidActivity => "android.app.Activity",
AndroidRect => "android.graphics.Rect",
},
constructors {
fn new(activity: AndroidActivity),
},
methods {
fn accent_color {
name = "accent_color",
sig = () -> jint,
},
fn color_scheme {
name = "color_scheme",
sig = () -> jint,
},
fn font_scale {
name = "font_scale",
sig = () -> jfloat,
},
fn get_clipboard {
name = "get_clipboard",
sig = () -> JString,
},
fn get_safe_area {
name = "get_safe_area",
sig = () -> AndroidRect,
},
fn get_view_rect {
name = "get_view_rect",
sig = () -> AndroidRect,
},
fn finish_activity {
name = "finish_activity",
sig = (),
},
fn hide_keyboard {
name = "hide_keyboard",
sig = (),
},
fn set_clipboard {
name = "set_clipboard",
sig = (text: JString),
},
fn set_handle_color {
name = "set_handle_color",
sig = (color: jint),
},
fn set_imm_data {
name = "set_imm_data",
sig = (
text: JString,
cursor_position: jint,
anchor_position: jint,
preedit_start: jint,
preedit_end: jint,
cur_x: jint,
cur_y: jint,
anchor_x: jint,
anchor_y: jint,
cursor_height: jint,
input_type: jint,
show_cursor_handles: jboolean
),
},
fn show_action_menu {
name = "show_action_menu",
sig = (),
},
fn show_keyboard {
name = "show_keyboard",
sig = (),
},
},
native_methods_export = false,
native_methods {
pub static fn move_cursor_handle {
sig = (id: jint, pos_x: jint, pos_y: jint) -> (),
fn = callback_move_cursor_handle,
},
pub static fn on_back_invoked {
sig = () -> (),
fn = callback_on_back_invoked,
},
pub static fn popup_menu_action {
sig = (id: jint) -> (),
fn = callback_popup_menu_action,
},
pub static fn set_insets {
sig = (
window_top: jint,
window_left: jint,
window_bottom: jint,
window_right: jint,
safe_area_top: jint,
safe_area_left: jint,
safe_area_bottom: jint,
safe_area_right: jint,
keyboard_top: jint,
keyboard_left: jint,
keyboard_bottom: jint,
keyboard_right: jint
) -> (),
fn = callback_set_insets,
},
pub static fn set_night_mode {
sig = (night_mode: jint) -> (),
fn = callback_set_night_mode,
},
pub static fn set_font_scale {
sig = (font_scale: jfloat) -> (),
fn = callback_set_font_scale,
},
pub static fn update_text {
sig = (
text: JString,
cursor_position: jint,
anchor_position: jint,
preedit_start: jint,
preedit_offset: jint
) -> (),
fn = callback_update_text,
},
},
}
bind_java_type! {
AndroidActivity => "android.app.Activity",
type_map = {
AndroidContext => "android.content.Context",
},
is_instance_of = {
AndroidContext,
}
}
bind_java_type! {
AndroidContext => "android.content.Context",
type_map = {
JFile => "java.io.File",
},
methods {
fn get_files_dir() -> JFile,
fn get_cache_dir() -> JFile,
fn get_code_cache_dir() -> JFile, // requires API level >= 21
fn get_class_loader() -> JClassLoader,
fn get_package_name() -> JString,
}
}
bind_java_type! {
AndroidBuildVersion => "android.os.Build$VERSION",
fields {
#[allow(non_snake_case)]
static SDK_INT {
sig = jint,
get = SDK_INT,
},
},
}
bind_java_type! {
AndroidRect => "android.graphics.Rect",
fields {
bottom: jint,
left: jint,
right: jint,
top: jint,
},
}
bind_java_type! {
AndroidInputType => "android.text.InputType",
fields {
#[allow(non_snake_case)]
static TYPE_CLASS_NUMBER {
sig = jint,
get = TYPE_CLASS_NUMBER,
},
#[allow(non_snake_case)]
static TYPE_CLASS_TEXT {
sig = jint,
get = TYPE_CLASS_TEXT,
},
#[allow(non_snake_case)]
static TYPE_TEXT_VARIATION_PASSWORD {
sig = jint,
get = TYPE_TEXT_VARIATION_PASSWORD,
},
#[allow(non_snake_case)]
static TYPE_NUMBER_FLAG_DECIMAL {
sig = jint,
get = TYPE_NUMBER_FLAG_DECIMAL,
},
#[allow(non_snake_case)]
static TYPE_TEXT_FLAG_CAP_SENTENCES {
sig = jint,
get = TYPE_TEXT_FLAG_CAP_SENTENCES,
},
#[allow(non_snake_case)]
static TYPE_TEXT_FLAG_CAP_WORDS {
sig = jint,
get = TYPE_TEXT_FLAG_CAP_WORDS,
},
#[allow(non_snake_case)]
static TYPE_TEXT_FLAG_CAP_CHARACTERS {
sig = jint,
get = TYPE_TEXT_FLAG_CAP_CHARACTERS,
},
#[allow(non_snake_case)]
static TYPE_TEXT_FLAG_AUTO_CORRECT {
sig = jint,
get = TYPE_TEXT_FLAG_AUTO_CORRECT,
},
#[allow(non_snake_case)]
static TYPE_TEXT_FLAG_AUTO_COMPLETE {
sig = jint,
get = TYPE_TEXT_FLAG_AUTO_COMPLETE,
},
}
}
bind_java_type! {
AndroidViewConfiguration => "android.view.ViewConfiguration",
methods {
static fn get_long_press_timeout() -> jint,
}
}
bind_java_type! {
JFile => "java.io.File",
methods {
fn get_absolute_path() -> JString,
}
}
bind_java_type! {
InMemoryDexClassLoader => "dalvik.system.InMemoryDexClassLoader",
constructors {
fn new(dex_buffer: JByteBuffer, parent: JClassLoader),
},
is_instance_of = {
JClassLoader,
}
}
bind_java_type! {
DexFileClassLoader => "dalvik.system.DexClassLoader",
constructors {
fn new(dex_path: JString, optimized_directory: JString, library_search_path: JString, parent: JClassLoader),
},
is_instance_of = {
JClassLoader,
}
}
// See `AttachmentExceptionPolicy::PreReThrowPostCatch` in `jni` crate.
#[track_caller]
pub fn print_jni_error(_app: &AndroidApp, e: jni::errors::Error) -> ! {
panic!("JNI error: {e:#?}")
}
#[allow(dead_code)]
pub struct JavaHelper(jni::refs::Global<SlintAndroidJavaHelper<'static>>, AndroidApp);
fn get_helper_class_loader(
env: &mut Env,
native_activity: &AndroidActivity<'_>,
) -> Result<&'static JClassLoader<'static>, jni::errors::Error> {
static DEX_CLASS_LOADER: OnceLock<jni::refs::Global<JClassLoader<'static>>> = OnceLock::new();
fn build_dex_class_loader<'local>(
env: &mut Env<'local>,
native_activity: &AndroidActivity<'_>,
) -> Result<JClassLoader<'local>, jni::errors::Error> {
let native_activity = env.new_local_ref(native_activity)?;
let app_context = AndroidContext::cast_local(env, native_activity)?;
let context_class_loader = app_context.get_class_loader(env)?;
if AndroidBuildVersion::SDK_INT(env)? >= 26 {
// Safety: DEX_DATA is 'static and the `InMemoryDexClassLoader`` will not mutate it
let dex_buffer =
unsafe { env.new_direct_byte_buffer(DEX_DATA.as_ptr() as *mut _, DEX_DATA.len()) }?;
let dex_loader = InMemoryDexClassLoader::new(env, &dex_buffer, &context_class_loader)?;
JClassLoader::cast_local(env, dex_loader)
} else {
// The dex data must be written in a file; this determines the output
// directory path inside the application code cache directory.
let code_cache_path = app_context
.get_code_cache_dir(env)?
.get_absolute_path(env)
.map(|p| std::path::PathBuf::from(p.to_string()))?;
let dex_name = env!("CARGO_CRATE_NAME").to_string() + ".dex";
let dex_file_path = code_cache_path.join(dex_name);
std::fs::write(&dex_file_path, DEX_DATA).unwrap(); // Note: this panics on failure
let dex_file_path = JString::new(env, dex_file_path.to_string_lossy())?;
// creates the oats directory
let oats_dir_path = code_cache_path.join("oats");
let _ = std::fs::create_dir(&oats_dir_path);
let oats_dir_path = JString::new(env, oats_dir_path.to_string_lossy())?;
// loads the dex file
let dex_loader = DexFileClassLoader::new(
env,
&dex_file_path,
&oats_dir_path,
JString::null(),
&context_class_loader,
)?;
JClassLoader::cast_local(env, dex_loader)
}
}
if DEX_CLASS_LOADER.get().is_none() {
let loader = build_dex_class_loader(env, native_activity)?;
let loader = env.new_global_ref(loader)?;
let _ = DEX_CLASS_LOADER.set(loader);
}
Ok(DEX_CLASS_LOADER.get().unwrap())
}
fn load_java_helper(
app: &AndroidApp,
) -> Result<jni::refs::Global<SlintAndroidJavaHelper<'static>>, jni::errors::Error> {
let jvm = JavaVM::singleton().unwrap_or_else(|_| unsafe {
// Safety: as documented in android-activity to obtain a jni::JavaVM
JavaVM::from_raw(app.vm_as_ptr() as *mut _) // this initializes the `JavaVM::singleton()`
});
jvm.attach_current_thread(|env| {
let native_activity_ptr = app.activity_as_ptr().cast();
let native_activity =
unsafe { env.as_cast_raw::<jni::refs::Global<AndroidActivity>>(&native_activity_ptr)? };
let loader = LoaderContext::Loader(get_helper_class_loader(env, native_activity.as_ref())?);
let _ = SlintAndroidJavaHelperAPI::get(env, &loader)?;
let helper_instance = SlintAndroidJavaHelper::new(env, native_activity)?;
env.new_global_ref(&helper_instance)
})
}
impl JavaHelper {
pub fn new(app: &AndroidApp) -> Result<Self, jni::errors::Error> {
Ok(Self(load_java_helper(app)?, app.clone()))
}
fn with_jni_env<R>(
&self,
f: impl FnOnce(&mut Env, &SlintAndroidJavaHelper<'static>) -> Result<R, jni::errors::Error>,
) -> Result<R, jni::errors::Error> {
JavaVM::singleton()?.attach_current_thread(|env| {
let helper = self.0.as_ref();
f(env, helper)
})
}
/// Unfortunately, the way that the android-activity crate uses to show or hide the virtual keyboard doesn't
/// work with native-activity. So do it manually with JNI
pub fn show_or_hide_soft_input(&self, show: bool) -> Result<(), jni::errors::Error> {
self.with_jni_env(
|env, helper| {
if show { helper.show_keyboard(env) } else { helper.hide_keyboard(env) }
},
)
}
pub fn set_imm_data(
&self,
data: &i_slint_core::window::InputMethodProperties,
scale_factor: f32,
show_cursor_handles: bool,
) -> Result<(), jni::errors::Error> {
self.with_jni_env(|env, helper| {
let mut text = data.text.to_string();
let mut cursor_position = data.cursor_position;
let mut anchor_position = data.anchor_position.unwrap_or(data.cursor_position);
if !data.preedit_text.is_empty() {
text.insert_str(data.preedit_offset, data.preedit_text.as_str());
if cursor_position >= data.preedit_offset {
cursor_position += data.preedit_text.len()
}
if anchor_position >= data.preedit_offset {
anchor_position += data.preedit_text.len()
}
}
let to_utf16 = |x| byte_offset_to_utf16_offset(&text, x as usize);
let text = JString::new(env, text.as_str())?;
let input_type = match data.input_type {
InputType::Text | InputType::Search => {
let hints = &data.input_method_hints;
let capitalization_flag = match hints.capitalization {
CapitalizationMode::None => 0 as jint,
CapitalizationMode::Sentences => {
AndroidInputType::TYPE_TEXT_FLAG_CAP_SENTENCES(env)?
}
CapitalizationMode::Words => {
AndroidInputType::TYPE_TEXT_FLAG_CAP_WORDS(env)?
}
CapitalizationMode::Characters => {
AndroidInputType::TYPE_TEXT_FLAG_CAP_CHARACTERS(env)?
}
_ => 0 as jint,
};
let auto_correct_flag = if hints.auto_correct {
AndroidInputType::TYPE_TEXT_FLAG_AUTO_CORRECT(env)?
} else {
0 as jint
};
let auto_complete_flag = if hints.auto_complete {
AndroidInputType::TYPE_TEXT_FLAG_AUTO_COMPLETE(env)?
} else {
0 as jint
};
AndroidInputType::TYPE_CLASS_TEXT(env)?
| capitalization_flag
| auto_correct_flag
| auto_complete_flag
}
InputType::Password => {
AndroidInputType::TYPE_TEXT_VARIATION_PASSWORD(env)?
| AndroidInputType::TYPE_CLASS_TEXT(env)?
}
InputType::Number => AndroidInputType::TYPE_CLASS_NUMBER(env)?,
InputType::Decimal => {
AndroidInputType::TYPE_CLASS_NUMBER(env)?
| AndroidInputType::TYPE_NUMBER_FLAG_DECIMAL(env)?
}
_ => 0 as jint,
};
let cur_origin = data.cursor_rect_origin.to_physical(scale_factor); // i32
let anchor_origin = data.anchor_point.to_physical(scale_factor);
let cur_size = data.cursor_rect_size.to_physical(scale_factor);
// A caret at the last column or on the last line sits exactly on the clip rect's max
// edge (e.g. every right-aligned field), where the exclusive `Rect::contains` reports
// it invisible and the handle gets sent off-screen. Inflate the rect by one pixel so
// the max edge counts as visible.
let clip_rect = data.clip_rect.map(|r| r.inflate(1., 1.));
let cur_visible = clip_rect.map_or(true, |r| {
r.contains(i_slint_core::lengths::logical_point_from_api(data.cursor_rect_origin))
});
let anchor_visible = clip_rect.map_or(true, |r| {
// anchor_point is `origin + cursor_size` for handle placement; check the anchor
// cursor's origin instead.
let anchor_origin =
i_slint_core::lengths::logical_point_from_api(data.anchor_point)
- i_slint_core::lengths::logical_size_from_api(data.cursor_rect_size)
.to_vector();
r.contains(anchor_origin)
});
// Add 2*cur_size.width to the y position to be a bit under the cursor
let cursor_height = cur_size.height as i32 + 2 * cur_size.width as i32;
let cur_x = if cur_visible { cur_origin.x + cur_size.width as i32 / 2 } else { -1 };
let cur_y = cur_origin.y + cursor_height;
let anchor_x = if anchor_visible { anchor_origin.x } else { -1 };
let anchor_y = anchor_origin.y + 2 * cur_size.width as i32;
helper.set_imm_data(
env,
&text,
to_utf16(cursor_position) as i32,
to_utf16(anchor_position) as i32,
to_utf16(data.preedit_offset) as i32,
to_utf16(data.preedit_offset + data.preedit_text.len()) as i32,
cur_x,
cur_y,
anchor_x,
anchor_y,
cursor_height,
input_type,
show_cursor_handles,
)?;
Ok(())
})
}
pub fn color_scheme(&self) -> Result<i32, jni::errors::Error> {
self.with_jni_env(|env, helper| helper.color_scheme(env))
}
pub fn font_scale(&self) -> Result<f32, jni::errors::Error> {
self.with_jni_env(|env, helper| helper.font_scale(env))
}
pub fn accent_color(&self) -> Result<Color, jni::errors::Error> {
self.with_jni_env(|env, helper| {
Ok(Color::from_argb_encoded(helper.accent_color(env)? as u32))
})
}
pub fn get_safe_area(&self) -> Result<PhysicalEdges, jni::errors::Error> {
self.with_jni_env(|env, helper| {
let rect = helper.get_safe_area(env)?;
let left = rect.left(env)?;
let top = rect.top(env)?;
let right = rect.right(env)?;
let bottom = rect.bottom(env)?;
Ok(PhysicalEdges::new(top, bottom, left, right))
})
}
pub fn set_handle_color(&self, color: Color) -> Result<(), jni::errors::Error> {
self.with_jni_env(|env, helper| {
helper.set_handle_color(env, color.as_argb_encoded() as i32)
})
}
pub fn long_press_timeout(&self) -> Result<Duration, jni::errors::Error> {
self.with_jni_env(|env, _helper| {
let long_press_timeout = AndroidViewConfiguration::get_long_press_timeout(env)?;
Ok(Duration::from_millis(long_press_timeout as _))
})
}
pub fn show_action_menu(&self) -> Result<(), jni::errors::Error> {
self.with_jni_env(|env, helper| helper.show_action_menu(env))
}
pub fn set_clipboard(&self, text: &str) -> Result<(), jni::errors::Error> {
self.with_jni_env(|env, helper| {
let text = JString::new(env, text)?;
helper.set_clipboard(env, &text)
})
}
pub fn get_clipboard(&self) -> Result<String, jni::errors::Error> {
self.with_jni_env(|env, helper| Ok(helper.get_clipboard(env)?.to_string()))
}
/// Ask the Activity to finish. Used from `callback_on_back_invoked` when
/// Slint's key dispatch reports the Back key as unhandled so we preserve
/// the legacy Back-closes-the-activity behavior even under the
/// OnBackInvokedCallback flow.
pub fn finish_activity(&self) -> Result<(), jni::errors::Error> {
self.with_jni_env(|env, helper| helper.finish_activity(env))
}
}
fn callback_update_text<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
text: JString<'local>,
cursor_position: jint,
anchor_position: jint,
preedit_start: jint,
preedit_end: jint,
) -> Result<(), jni::errors::Error> {
let java_str = text.to_string();
let decoded: std::borrow::Cow<str> = (&java_str).into();
let text = SharedString::from(decoded.as_ref());
let cursor_position = utf16_offset_to_byte_offset_clamped(&text, cursor_position as usize);
let anchor_position = utf16_offset_to_byte_offset_clamped(&text, anchor_position as usize);
let preedit_start = utf16_offset_to_byte_offset_clamped(&text, preedit_start as usize);
let preedit_end = utf16_offset_to_byte_offset_clamped(&text, preedit_end as usize);
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(adaptor) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
adaptor.show_cursor_handles.set(false);
let event = if preedit_start != preedit_end {
let adjust = |pos| {
if pos <= preedit_start {
pos
} else if pos >= preedit_end {
preedit_start + (pos - preedit_end)
} else {
preedit_start
}
} as i32;
let mut key_event = KeyEvent::default();
key_event.text =
i_slint_core::format!("{}{}", &text[..preedit_start], &text[preedit_end..]);
InternalKeyEvent {
event_type: KeyEventType::UpdateComposition,
preedit_text: text[preedit_start..preedit_end].into(),
preedit_selection: Some(0..(preedit_end - preedit_start) as i32),
replacement_range: Some(i32::MIN..i32::MAX),
cursor_position: Some(adjust(cursor_position)),
anchor_position: Some(adjust(anchor_position)),
key_event,
..Default::default()
}
} else {
let mut key_event = KeyEvent::default();
key_event.text = text;
InternalKeyEvent {
event_type: KeyEventType::CommitComposition,
replacement_range: Some(i32::MIN..i32::MAX),
cursor_position: Some(cursor_position as _),
anchor_position: Some(anchor_position as _),
key_event,
..Default::default()
}
};
adaptor.window.dispatch_event(i_slint_core::platform::WindowEvent::internal(event));
}
})
.unwrap();
Ok(())
}
fn callback_set_night_mode<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
night_mode: jint,
) -> Result<(), jni::errors::Error> {
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(w) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
let scheme = match night_mode {
0x10 => ColorScheme::Light, // UI_MODE_NIGHT_NO(0x10)
0x20 => ColorScheme::Dark, // UI_MODE_NIGHT_YES(0x20)
0x0 => ColorScheme::Unknown, // UI_MODE_NIGHT_UNDEFINED
_ => ColorScheme::Unknown,
};
let ctx = i_slint_core::window::WindowInner::from_pub(&w.window).context();
ctx.set_color_scheme(scheme);
if let Ok(accent) = w.java_helper.accent_color() {
ctx.set_accent_color(accent);
}
}
})
.unwrap();
Ok(())
}
fn callback_set_font_scale<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
font_scale: jfloat,
) -> Result<(), jni::errors::Error> {
// Skip rather than clobber: an OEM/ROM that hands us 0.0 or NaN during a
// transient configuration change must not zero out the value `bind_context`
// already set.
let Some(size) = font_scale_to_logical_length(font_scale) else { return Ok(()) };
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(w) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
let ctx = i_slint_core::window::WindowInner::from_pub(&w.window).context();
ctx.set_platform_default_font_size(Some(size));
}
})
.unwrap();
Ok(())
}
fn callback_move_cursor_handle<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
id: jint,
pos_x: jint,
pos_y: jint,
) -> Result<(), jni::errors::Error> {
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(adaptor) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
if let Some(focus_item) = i_slint_core::window::WindowInner::from_pub(&adaptor.window)
.focus_item
.borrow()
.upgrade()
{
if let Some(text_input) = focus_item.downcast::<i_slint_core::items::TextInput>() {
let scale_factor = adaptor.window.scale_factor();
let adaptor = adaptor.clone() as Rc<dyn WindowAdapter>;
let size = text_input
.as_pin_ref()
.font_request(&focus_item)
.pixel_size
.unwrap_or_default()
.get();
let pos =
euclid::point2(
pos_x as f32 / scale_factor,
pos_y as f32 / scale_factor - size / 2.,
) - focus_item.map_to_window(focus_item.geometry().origin).to_vector();
let (text_pos, affinity) = text_input.as_pin_ref().byte_offset_for_position(
pos,
&adaptor,
&focus_item,
);
let (cur_pos, cur_affinity) = if id == 0 {
text_input.anchor_position_byte_offset.set(text_pos as i32);
(text_pos as i32, affinity)
} else {
let current_cursor = text_input.as_pin_ref().cursor_position_byte_offset();
let current_anchor = text_input.as_pin_ref().anchor_position_byte_offset();
if (id == 1 && current_anchor < current_cursor)
|| (id == 2 && current_anchor > current_cursor)
{
if current_cursor == text_pos as i32 {
return;
}
text_input.anchor_position_byte_offset.set(text_pos as i32);
(current_cursor, text_input.as_pin_ref().cursor_position_affinity())
} else {
if current_anchor == text_pos as i32 {
return;
}
(text_pos as i32, affinity)
}
};
text_input.as_pin_ref().set_cursor_position_with_affinity(
cur_pos,
cur_affinity,
true,
i_slint_core::items::TextChangeNotify::TriggerCallbacks,
&adaptor,
&focus_item,
);
}
}
}
})
.unwrap();
Ok(())
}
fn callback_popup_menu_action<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
id: jint,
) -> Result<(), jni::errors::Error> {
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(adaptor) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
if let Some(focus_item) = i_slint_core::window::WindowInner::from_pub(&adaptor.window)
.focus_item
.borrow()
.upgrade()
{
if let Some(text_input) = focus_item.downcast::<i_slint_core::items::TextInput>() {
let text_input = text_input.as_pin_ref();
let adaptor = adaptor.clone() as Rc<dyn WindowAdapter>;
match id {
0 => text_input.cut(&adaptor, &focus_item),
1 => text_input.copy(&adaptor, &focus_item),
2 => text_input.paste(&adaptor, &focus_item),
3 => text_input.select_all(&adaptor, &focus_item),
_ => (),
}
}
}
}
})
.unwrap();
Ok(())
}
fn callback_on_back_invoked<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
) -> Result<(), jni::errors::Error> {
// Forward Back as a Key.Back KeyPressed + KeyReleased pair; fall back to
// Activity.finish() if unhandled.
let _ = i_slint_core::api::invoke_from_event_loop(move || {
if let Some(adaptor) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
let text: SharedString = Key::Back.into();
let pressed = adaptor
.window
.dispatch_event_with_result(WindowEvent::KeyPressed { text: text.clone() });
let released =
adaptor.window.dispatch_event_with_result(WindowEvent::KeyReleased { text });
let handled = matches!(pressed, Ok(WindowEventDispatchResult::Accepted))
|| matches!(released, Ok(WindowEventDispatchResult::Accepted));
if !handled {
if let Err(e) = adaptor.java_helper.finish_activity() {
i_slint_core::debug_log!("finish_activity failed: {e:#?}");
}
}
}
});
Ok(())
}
fn callback_set_insets<'local>(
_env: &mut Env<'local>,
_class: JClass<'local>,
window_top: jint,
window_left: jint,
window_bottom: jint,
window_right: jint,
safe_area_top: jint,
safe_area_left: jint,
safe_area_bottom: jint,
safe_area_right: jint,
keyboard_top: jint,
keyboard_left: jint,
keyboard_bottom: jint,
keyboard_right: jint,
) -> Result<(), jni::errors::Error> {
i_slint_core::api::invoke_from_event_loop(move || {
if let Some(w) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) {
w.update_window_insets(
PhysicalPosition::new(window_left as _, window_top as _),
PhysicalSize::new(
(window_right - window_left) as _,
(window_bottom - window_top) as _,
),
PhysicalEdges::new(
safe_area_top as _,
safe_area_bottom as _,
safe_area_left as _,
safe_area_right as _,
),
PhysicalEdges::new(
keyboard_top as _,
keyboard_bottom as _,
keyboard_left as _,
keyboard_right as _,
),
);
}
})
.unwrap();
Ok(())
}

View File

@ -0,0 +1,277 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore androidwindowadapter javahelper
#![doc = include_str!("README.md")]
#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
#![cfg_attr(not(target_os = "android"), allow(rustdoc::broken_intra_doc_links))]
#![cfg(target_os = "android")]
#![cfg_attr(slint_nightly_test, feature(non_exhaustive_omitted_patterns_lint))]
#![cfg_attr(slint_nightly_test, warn(non_exhaustive_omitted_patterns))]
mod androidwindowadapter;
mod javahelper;
mod vsync;
pub mod stg;
#[cfg(all(not(feature = "aa-06"), feature = "aa-05"))]
pub use android_activity_05 as android_activity;
#[cfg(feature = "aa-06")]
pub use android_activity_06 as android_activity;
#[cfg(all(not(feature = "aa-06"), feature = "aa-05"))]
use ndk_08 as ndk;
#[cfg(feature = "aa-06")]
use ndk_09 as ndk;
pub use android_activity::AndroidApp;
use android_activity::PollEvent;
use androidwindowadapter::AndroidWindowAdapter;
use core::ops::ControlFlow;
use core::time::Duration;
use i_slint_core::api::{EventLoopError, PlatformError};
use i_slint_core::platform::{Clipboard, WindowAdapter};
use i_slint_renderer_skia::SkiaRendererExt;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
thread_local! {
static CURRENT_WINDOW: RefCell<Weak<AndroidWindowAdapter>> = RefCell::new(Default::default());
}
pub struct AndroidPlatform {
app: AndroidApp,
window: Rc<AndroidWindowAdapter>,
event_listener: Option<Box<dyn Fn(&PollEvent<'_>)>>,
context: core::cell::OnceCell<i_slint_core::SlintContextWeak>,
}
impl AndroidPlatform {
/// Instantiate a new Android backend given the [`android_activity::AndroidApp`]
///
/// Pass the returned value to [`slint::platform::set_platform()`](`i_slint_core::platform::set_platform()`)
///
/// # Example
/// ```
/// #[cfg(target_os = "android")]
/// #[unsafe(no_mangle)]
/// fn android_main(app: i_slint_backend_android_activity::AndroidApp) {
/// slint::platform::set_platform(Box::new(
/// i_slint_backend_android_activity::AndroidPlatform::new(app),
/// ))
/// .unwrap();
/// // ... your slint application ...
/// }
/// ```
pub fn new(app: AndroidApp) -> Self {
let window = AndroidWindowAdapter::new(app.clone());
CURRENT_WINDOW.set(Rc::downgrade(&window));
Self { app, window, event_listener: None, context: Default::default() }
}
/// Instantiate a new Android backend given the [`android_activity::AndroidApp`]
/// and a function to process the events.
///
/// This is the same as [`AndroidPlatform::new()`], but it allow you to get notified
/// of events.
///
/// Pass the returned value to [`slint::platform::set_platform()`](`i_slint_core::platform::set_platform()`)
///
/// # Example
/// ```
/// #[cfg(target_os = "android")]
/// #[unsafe(no_mangle)]
/// fn android_main(app: i_slint_backend_android_activity::AndroidApp) {
/// slint::platform::set_platform(Box::new(
/// i_slint_backend_android_activity::AndroidPlatform::new_with_event_listener(
/// app,
/// |event| { eprintln!("got event {event:?}") }
/// ),
/// ))
/// .unwrap();
/// // ... your slint application ...
/// }
/// ```
pub fn new_with_event_listener(
app: AndroidApp,
listener: impl Fn(&PollEvent<'_>) + 'static,
) -> Self {
let mut this = Self::new(app);
this.event_listener = Some(Box::new(listener));
this
}
}
impl i_slint_core::platform::Platform for AndroidPlatform {
fn create_window_adapter(&self) -> Result<Rc<dyn WindowAdapter>, PlatformError> {
Ok(self.window.clone())
}
fn run_event_loop(&self) -> Result<(), PlatformError> {
let ctx = self
.context
.get()
.and_then(|ctx| ctx.upgrade())
.expect("the event loop runs inside the context that owns this platform");
let vsync = vsync::VsyncDriver::new(self.app.create_waker());
loop {
let mut timeout = ctx.duration_until_next_timer_update();
// While animating, the vsync thread wakes this loop at each display refresh
// so rendering tracks the refresh rate instead of a fixed poll timeout.
let animating = self.window.window.has_active_animations();
vsync.set_animating(animating);
if animating && !vsync.is_driving() {
// The vsync thread is not driving frames (still starting, or unavailable);
// fall back to a periodic wakeup so animations still advance.
let frame_duration = Duration::from_millis(10);
timeout = Some(timeout.map_or(frame_duration, |x| x.min(frame_duration)));
}
// `request_redraw()` only raises the flag, so a request issued outside the
// poll would otherwise wait here for an unrelated wakeup.
if self.window.pending_redraw.get() {
timeout = Some(Duration::ZERO);
}
// STG (jank-hunt instrumentation): reset per-iteration marks.
{
let pr = stg::S_RENDER_START.load(std::sync::atomic::Ordering::Relaxed);
let pe = stg::S_RENDER_END.load(std::sync::atomic::Ordering::Relaxed);
if pr != 0 && pe != 0 {
stg::S_LAST_RENDER_US
.store(pe - pr, std::sync::atomic::Ordering::Relaxed);
}
}
stg::S_START.store(stg::now_us(), std::sync::atomic::Ordering::Relaxed);
stg::S_FIRST_EV.store(0, std::sync::atomic::Ordering::Relaxed);
stg::S_TIMER_US.store(0, std::sync::atomic::Ordering::Relaxed);
stg::S_EVENT_US.store(0, std::sync::atomic::Ordering::Relaxed);
stg::S_N_EVENTS.store(0, std::sync::atomic::Ordering::Relaxed);
let mut r = Ok(ControlFlow::Continue(()));
self.app.poll_events(timeout, |e| {
if stg::S_FIRST_EV.load(std::sync::atomic::Ordering::Relaxed) == 0 {
stg::S_FIRST_EV
.store(stg::now_us(), std::sync::atomic::Ordering::Relaxed);
}
let t1 = stg::now_us();
ctx.update_timers_and_animations();
let t2 = stg::now_us();
r = self.window.process_event(&e);
let t3 = stg::now_us();
stg::S_TIMER_US.fetch_add(t2 - t1, std::sync::atomic::Ordering::Relaxed);
stg::S_EVENT_US.fetch_add(t3 - t2, std::sync::atomic::Ordering::Relaxed);
stg::S_N_EVENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if let Some(event_listener) = &self.event_listener {
event_listener(&e)
}
});
stg::S_POLL_END.store(stg::now_us(), std::sync::atomic::Ordering::Relaxed);
if r?.is_break() {
break;
}
if self.window.pending_redraw.take() {
stg::S_RENDER_START.store(stg::now_us(), std::sync::atomic::Ordering::Relaxed);
self.window.do_render()?;
stg::S_RENDER_END.store(stg::now_us(), std::sync::atomic::Ordering::Relaxed);
} else {
stg::S_RENDER_END.store(0, std::sync::atomic::Ordering::Relaxed);
}
}
Ok(())
}
fn new_event_loop_proxy(&self) -> Option<Box<dyn i_slint_core::platform::EventLoopProxy>> {
Some(Box::new(AndroidEventLoopProxy {
event_queue: self.window.event_queue.clone(),
waker: self.app.create_waker(),
}))
}
fn set_clipboard_text(&self, text: &str, clipboard: Clipboard) {
if clipboard == Clipboard::DefaultClipboard {
self.window
.java_helper
.set_clipboard(text)
.unwrap_or_else(|e| javahelper::print_jni_error(&self.app, e));
}
}
fn clipboard_text(&self, clipboard: Clipboard) -> Option<String> {
if clipboard == Clipboard::DefaultClipboard {
Some(
self.window
.java_helper
.get_clipboard()
.unwrap_or_else(|e| javahelper::print_jni_error(&self.app, e)),
)
} else {
None
}
}
fn bind_context(&self, ctx: i_slint_core::SlintContextWeak, _: i_slint_core::InternalToken) {
let _ = self.context.set(ctx.clone());
let ctx = ctx.upgrade().expect("bind_context called while the SlintContext is still alive");
let color_scheme = match self
.window
.java_helper
.color_scheme()
.unwrap_or_else(|e| javahelper::print_jni_error(&self.app, e))
{
0x10 => i_slint_core::items::ColorScheme::Light, // UI_MODE_NIGHT_NO
0x20 => i_slint_core::items::ColorScheme::Dark, // UI_MODE_NIGHT_YES
_ => i_slint_core::items::ColorScheme::Unknown,
};
ctx.set_color_scheme(color_scheme);
if let Ok(accent) = self.window.java_helper.accent_color() {
ctx.set_accent_color(accent);
}
if let Ok(scale) = self.window.java_helper.font_scale()
&& let Some(size) = javahelper::font_scale_to_logical_length(scale)
{
ctx.set_platform_default_font_size(Some(size));
}
}
fn long_press_interval(&self, _: i_slint_core::InternalToken) -> Duration {
self.window.java_helper.long_press_timeout().unwrap_or(Duration::from_millis(500))
}
}
enum Event {
Quit,
Other(Box<dyn FnOnce() + Send + 'static>),
}
type EventQueue = Arc<Mutex<Vec<Event>>>;
struct AndroidEventLoopProxy {
event_queue: EventQueue,
waker: android_activity::AndroidAppWaker,
}
impl i_slint_core::platform::EventLoopProxy for AndroidEventLoopProxy {
fn quit_event_loop(&self) -> Result<(), EventLoopError> {
self.event_queue.lock().unwrap().push(Event::Quit);
self.waker.wake();
Ok(())
}
fn invoke_from_event_loop(
&self,
event: Box<dyn FnOnce() + Send>,
) -> Result<(), EventLoopError> {
self.event_queue.lock().unwrap().push(Event::Other(event));
self.waker.wake();
Ok(())
}
}
pub fn set_requested_graphics_api(
requested_graphics_api: Option<i_slint_core::graphics::RequestedGraphicsAPI>,
) -> Result<(), PlatformError> {
let Some(adapter) = CURRENT_WINDOW.with_borrow(|x| x.upgrade()) else {
return Err(format!("On Android a graphics API for Slint can only be requested after calling slint::android::init()").into());
};
adapter.set_requested_graphics_api(requested_graphics_api);
Ok(())
}

View File

@ -0,0 +1,48 @@
//! STG (stage-timestamp) instrumentation for the jank hunt, 2026-10-28.
//!
//! The app's FR hook (rendering notifier) measures render cost and frame
//! gaps; this measures what happens AROUND rendering inside the event
//! loop: Choreographer wake latency, timer callbacks (the app's 8 ms
//! drain tick runs in `update_timers_and_animations`), and event
//! processing. Timestamps are plain atomics — the UI thread only does
//! atomic loads/stores here; the APP formats the log line from its own
//! tick (never log from the UI thread: logd backpressure).
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
static T0: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
pub fn now_us() -> u64 {
T0.get_or_init(Instant::now).elapsed().as_micros() as u64
}
// Per-iteration stage marks (us since process start); reset at loop top.
pub static S_START: AtomicU64 = AtomicU64::new(0);
pub static S_FIRST_EV: AtomicU64 = AtomicU64::new(0);
pub static S_POLL_END: AtomicU64 = AtomicU64::new(0);
pub static S_RENDER_START: AtomicU64 = AtomicU64::new(0);
pub static S_RENDER_END: AtomicU64 = AtomicU64::new(0);
// Accumulated per-iteration costs.
pub static S_TIMER_US: AtomicU64 = AtomicU64::new(0);
pub static S_EVENT_US: AtomicU64 = AtomicU64::new(0);
pub static S_N_EVENTS: AtomicU64 = AtomicU64::new(0);
// Full do_render duration of the PREVIOUS iteration (the AfterRendering
// hook fires mid-render, so the current iteration's render can't be read
// yet): covers renderer.draw PLUS the wgpu surface tail (flush_and_submit
// gr_context.submit + queue.present — the Mali driver calls).
pub static S_LAST_RENDER_US: AtomicU64 = AtomicU64::new(0);
/// One iteration of the event loop: start, first-event, poll-end,
/// render-start, render-end, timer-us, event-us, n-events.
pub fn snapshot() -> (u64, u64, u64, u64, u64, u64, u64, u64) {
(
S_START.load(Ordering::Relaxed),
S_FIRST_EV.load(Ordering::Relaxed),
S_POLL_END.load(Ordering::Relaxed),
S_RENDER_START.load(Ordering::Relaxed),
S_RENDER_END.load(Ordering::Relaxed),
S_TIMER_US.load(Ordering::Relaxed),
S_EVENT_US.load(Ordering::Relaxed),
S_N_EVENTS.load(Ordering::Relaxed),
)
}

View File

@ -0,0 +1,169 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore ALOOPER Condvar wakeups
//! Drives animation frames from the display's vsync using the Android Choreographer.
//!
//! The Choreographer delivers its callback through the `ALooper` it is fetched on, and
//! `ALooper_pollOnce` reports that as `ALOOPER_POLL_CALLBACK`, which the android-activity
//! `poll_events` wrapper logs as a spurious error. To keep the Choreographer off the main
//! looper, a dedicated helper thread owns its own looper, waits for each vsync, and wakes
//! the main event loop through its `AndroidAppWaker`. The main loop then advances the
//! animations and renders. Pacing therefore follows the actual refresh rate instead of a
//! fixed poll timeout.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use crate::android_activity::AndroidAppWaker;
use crate::ndk::looper::{ForeignLooper, ThreadLooper};
/// The Choreographer is not wrapped by the `ndk` crate. Available since API 24; Slint's
/// Android minimum is API 26, so the symbols are always present.
mod ffi {
use core::ffi::{c_long, c_void};
#[repr(C)]
pub struct AChoreographer {
_unused: [u8; 0],
}
pub type FrameCallback = unsafe extern "C" fn(frame_time_nanos: c_long, data: *mut c_void);
#[link(name = "android")]
unsafe extern "C" {
pub fn AChoreographer_getInstance() -> *mut AChoreographer;
pub fn AChoreographer_postFrameCallback(
choreographer: *mut AChoreographer,
callback: FrameCallback,
data: *mut c_void,
);
}
}
struct Shared {
state: Mutex<State>,
cond: Condvar,
/// Set once the helper thread has a working Choreographer and can wake the main
/// loop at every vsync. Until then (and if the thread never starts) the main loop
/// keeps its own periodic wakeup so animations still advance.
driving: AtomicBool,
/// The helper thread's looper, published so the main thread can wake it on shutdown.
looper: Mutex<Option<ForeignLooper>>,
/// Wakes the main event loop when a vsync arrives.
main_waker: AndroidAppWaker,
}
#[derive(Default)]
struct State {
animating: bool,
quit: bool,
}
/// Wakes the main event loop at each display vsync while animations are running.
pub struct VsyncDriver {
shared: Arc<Shared>,
handle: Option<JoinHandle<()>>,
}
impl VsyncDriver {
pub fn new(main_waker: AndroidAppWaker) -> Self {
let shared = Arc::new(Shared {
state: Mutex::new(State::default()),
cond: Condvar::new(),
driving: AtomicBool::new(false),
looper: Mutex::new(None),
main_waker,
});
let handle = std::thread::Builder::new()
.name("slint vsync".into())
.spawn({
let shared = shared.clone();
move || vsync_thread(shared)
})
.ok();
Self { shared, handle }
}
/// Whether the helper thread is driving frames from vsync. When it is not, the
/// caller must keep waking itself so that animations still advance.
pub fn is_driving(&self) -> bool {
self.shared.driving.load(Ordering::Acquire)
}
/// Publishes whether the main loop currently has active animations. Turning it on
/// starts the per-vsync wakeups; turning it off parks the helper after the next frame.
pub fn set_animating(&self, animating: bool) {
let mut state = self.shared.state.lock().unwrap();
if state.animating != animating {
state.animating = animating;
drop(state);
self.shared.cond.notify_one();
}
}
}
impl Drop for VsyncDriver {
fn drop(&mut self) {
self.shared.state.lock().unwrap().quit = true;
self.shared.cond.notify_one();
// Interrupt a poll that may otherwise block until the next vsync, or forever
// while the app is in the background.
if let Some(looper) = self.shared.looper.lock().unwrap().as_ref() {
looper.wake();
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
fn vsync_thread(shared: Arc<Shared>) {
let looper = ThreadLooper::prepare();
*shared.looper.lock().unwrap() = Some(looper.as_foreign().clone());
// SAFETY: `AChoreographer_getInstance` needs a looper on the calling thread, which
// `ThreadLooper::prepare` just established.
let choreographer = unsafe { ffi::AChoreographer_getInstance() };
if choreographer.is_null() {
return;
}
shared.driving.store(true, Ordering::Release);
loop {
{
let mut state = shared.state.lock().unwrap();
while !state.animating && !state.quit {
state = shared.cond.wait(state).unwrap();
}
if state.quit {
break;
}
}
// Request one frame and block until the Choreographer delivers it, or the main
// thread wakes the looper to shut us down. The callback does nothing; the vsync
// signal is simply that the poll returned.
// SAFETY: `choreographer` belongs to this thread and stays valid.
unsafe {
ffi::AChoreographer_postFrameCallback(
choreographer,
noop_frame_callback,
std::ptr::null_mut(),
);
}
let _ = looper.poll_once();
// Wake the main loop to advance the animations and render this frame. A wake
// that was really a shutdown request is harmless: the next iteration breaks at
// the parked wait above.
shared.main_waker.wake();
}
}
extern "C" fn noop_frame_callback(
_frame_time_nanos: core::ffi::c_long,
_data: *mut core::ffi::c_void,
) {
}