Root-cause and fix the Mali scroll jank; strip jank-hunt instrumentation

The 19-26 ms mid-scroll stalls (Mali-only, fixed content offsets) were
the Skia renderer's final synchronous GrDirectContext::flush() blocking
the UI thread on Mali driver back-pressure — proven by per-stage
timestamps in the vendored renderer (stall frames: flush 19-24 ms,
walk 1-3 ms, 1 binding re-eval, image imports 0.1 ms each).

- vendor/i-slint-renderer-skia (pinned 1.18.1, [patch.crates-io]):
  remove that one flush. Redundant on the wgpu backend: the surface
  already calls flush_and_submit before queue.present, same Vulkan
  queue, in-order. Phone: 0 stalls across 4 runs (max 3.6-7.4 ms vs
  the 8.3 ms budget), display verified clean.
- docs/BUGS/slint-skia-final-flush-jank.md: full evidence, prior art
  (slint-ui/slint#12030 closest), open question for a future
  upstream filing (not filed yet).
- Profiling also retired the O(n)-walk theory: Slint 1.18 prunes the
  item walk to ~133-152 items; the windowed Flickable built on that
  theory was already reverted (ListView is smooth with the fix).
- Strip all jank-hunt instrumentation: FR/SCR/TICK/APLYD/STG logging,
  stg markers, .gallery_* file knobs, jsamp thread sampler,
  DbgScroll programmatic scroll, nblog perf-file mirroring.
  Also fixes the 'launches into unstoppable fast scroll' bug: a
  leftover .gallery_cmd was re-read on every launch (file never
  deleted) and overrode user swipes — the hook is gone.
- Keep: nblog (logd backpressure is real), zero-dimension decode
  guards, keep-alive (default-off).
- HANDOFF: replace stale windowed-Flickable section with the actual
  root cause/fix; 15 unit tests pass.

Verified on phone (aarch64, 8580 photos) and emulator (x86_64).
This commit is contained in:
Greg Pomerantz 2026-10-28 18:23:50 -04:00
parent 835659131e
commit 93b27d724b
34 changed files with 10934 additions and 472 deletions

3
Cargo.lock generated
View File

@ -1546,6 +1546,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"image", "image",
"kamadak-exif", "kamadak-exif",
"libc",
"log", "log",
"rusqlite", "rusqlite",
"sha1", "sha1",
@ -2123,8 +2124,6 @@ dependencies = [
[[package]] [[package]]
name = "i-slint-renderer-skia" name = "i-slint-renderer-skia"
version = "1.18.1" version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc9c1cf02385f1d26fc1f423544e52390a8e5c2d89420a8042aa94b4fe109d1f"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"cfg-if", "cfg-if",

View File

@ -7,6 +7,7 @@ edition = "2021"
crate-type = ["cdylib", "lib"] crate-type = ["cdylib", "lib"]
[dependencies] [dependencies]
libc = "0.2"
slint = { version = "1.18.1", features = [ slint = { version = "1.18.1", features = [
"backend-android-activity-06", "backend-android-activity-06",
# Exposes `slint::wgpu_30` + `Image: TryFrom<wgpu::Texture>` + # Exposes `slint::wgpu_30` + `Image: TryFrom<wgpu::Texture>` +
@ -68,3 +69,10 @@ max_sdk_version = 32
# arbitrary directories outside the media collection. # arbitrary directories outside the media collection.
[[package.metadata.android.uses_permission]] [[package.metadata.android.uses_permission]]
name = "android.permission.MANAGE_EXTERNAL_STORAGE" name = "android.permission.MANAGE_EXTERNAL_STORAGE"
[patch.crates-io]
# Vendored Slint Skia renderer: removes a redundant per-frame synchronous
# flush that caused 19-24 ms scroll stalls on Mali (see
# docs/BUGS/slint-skia-final-flush-jank.md). Pinned to the 1.18.1 source;
# re-apply the one hunk when bumping Slint.
i-slint-renderer-skia = { path = "vendor/i-slint-renderer-skia" }

View File

@ -375,24 +375,16 @@ phone (Pixel 9 Pro, 120 Hz). Emulator repro via programmatic scroll hook.
(Mali + SystemUI both at 120 Hz), Slint EGL/swap path, or an (Mali + SystemUI both at 120 Hz), Slint EGL/swap path, or an
event-loop/vsync interaction. Needs the phone. event-loop/vsync interaction. Needs the phone.
### Tools / hooks in the tree (all tagged "REMOVE after the hunt") ### Tools / hooks
- `src/lib.rs`: `DbgScroll` + `.gallery_cmd` file (also `stop`); The hunt's file hooks (`.gallery_cmd`, `.gallery_*` knobs, SCRDBG/TICK/APLY
knobs `.gallery_max` (item cap) and `.gallery_grey` (1×1 grey images); logs, jsamp sampler) were REMOVED in the 2026-10-28 cleanup — see §8.9.
`SCRDBG`/`JANKTEST`/`TICK`/`APLY` logs at `info`. `nblog` (non-blocking logger) and the debug-level coverage logs stayed.
- `jsample.c` (in /tmp, NDK-cross with
`~/android-sdk/ndk/27.0.12077973/.../x86_64-linux-android26 -static`):
per-thread `/proc stat` + state + wchan sampler at 1 ms; usage
`jsample <interval_ms> <pid> <tid...>`.
### Next (phone, morning) ### Outcome
1. **Decisive A/B on the phone**: `touch /sdcard/Download/.gallery_grey`, The decisive A/B was not needed: stage timestamps inside the vendored
restart app, user scrolls 30 s, capture logcat. Then remove the file, renderer isolated the stall to the Skia renderer's final synchronous
restart, repeat. Grey smooth + textured janky → texture/GPU path is the flush (Mali driver back-pressure). Fix + evidence: §8.9 and
culprit (then: smaller decode target, upload strategy, possibly Slint `docs/BUGS/slint-skia-final-flush-jank.md`.
image pipeline). Grey also janky → base render/present path (then: Slint
window/EGL config, refresh-rate interaction, vsync driver).
2. Run `jsample` over one of the user's real scrolls and wchan-correlate
the 28–39 ms windows (is android_main R, S/futex, or S/do_epoll_wait?).
3. Compare against Fossify (installed on the phone, user says smooth): 3. Compare against Fossify (installed on the phone, user says smooth):
`dumpsys SurfaceFlinger --latency` on both apps' layers during identical `dumpsys SurfaceFlinger --latency` on both apps' layers during identical
scrolls. scrolls.
@ -664,8 +656,71 @@ in-app thread sampler (`src/jsamp.rs`, `/proc/self/task`, knob
reboot (system_server/surfaceflinger 5-day uptime), but the user reboot (system_server/surfaceflinger 5-day uptime), but the user
experience was "crashing my phone". **Root lesson: do not run experience was "crashing my phone". **Root lesson: do not run
concurrent submitters on Slint's Mali queue.** Keep-alive is now concurrent submitters on Slint's Mali queue.** Keep-alive is now
INACTIVE BY DEFAULT (debug knob `.gallery_keep`), the jsamp sampler is INACTIVE BY DEFAULT (debug knob `.gallery_keep`). The jsamp sampler
off (knob `.gallery_jsamp`), and both are REMOVE-after-hunt. was REMOVED in the 2026-10-28 cleanup (see §8.9).
- Status: mid-gesture 20–28 ms warm-up frames can still occur without - Status (post jank-fix, §8.9): with the Skia final-flush removed, the
keep-alive (~1 per 10 s of scrolling); cold-start-after-idle frame is mid-scroll stalls are GONE (0 stalls, max 3.9–7.4 ms across 4 runs,
40 ms. User finger-verification of the keep-alive-free build pending. phone). Residual after the fix: scroll-START ramp frames (16–27 ms
in the first ~400 ms after >2 s idle, CPU-clock ramp on the 820 MHz
little cores) — revisit only if the user still notices them.
### 8.9 Scroll jank — root cause & fix (2026-10-28, CLOSED)
The mid-scroll 19–26 ms stalls (2–4 per run, at fixed content offsets,
Mali-only — emulator/SwiftShader never reproduced) are **fixed**.
**Root cause (proven by stage-timestamp profiling of the vendored
renderer):** the Slint Skia renderer's final synchronous
`GrDirectContext::flush()` at the end of every frame
(`render_components_to_canvas`) blocked the UI thread 19.2–20.4 ms
whenever the Mali driver queue was momentarily busy (texture uploads
landing, first-draw pipeline state). Steady-state cost of that call:
0.3–0.8 ms. SwiftShader's flush returns instantly → emulator never
reproduced it, and every CPU-side hypothesis failed.
Full evidence, per-stage tables, prior art and the upstream-filing
question: **`docs/BUGS/slint-skia-final-flush-jank.md`**.
**Fix (kept, per user decision):** `vendor/i-slint-renderer-skia`
(pinned 1.18.1, `[patch.crates-io]`) with that one flush removed.
It is redundant on the wgpu backend: `wgpu_30_surface::render` calls
`flush_and_submit` (Skia `submit()`) before `queue.present`, same
Vulkan queue, in-order. `vendor/` contains ONLY this crate; the rest
of the patch set is a single commented-out hunk with an explanation.
Re-apply that hunk when bumping Slint. Upstream NOT filed yet (we
cannot be 100% sure the flush isn't doing a job for non-wgpu
backends) — the bug doc is written so it can be filed later.
**What the profiling also settled:**
- Slint 1.18 DOES prune the item walk (~133–152 visited items, not
O(rows)). The earlier O(n)-walk diagnosis (and the windowed
Flickable that was built on it) was WRONG; the windowed Flickable
was reverted per user directive (use Slint's ListView — it is
smooth once the flush is gone).
- Stall frames had 0–3 new Skia images (0.1 ms each), 1 binding
re-evaluation, 0 ms partial-renderer: none of the usual suspects.
**Verification (phone, Mali G715, 8,580 photos):**
- slow scroll 5 s ×3: 0 stalls, max 3.6 / 5.8 / 3.9 ms
- fast fling 8× velocity: 0 stalls, max 7.4 ms, p50 1.0 ms
- display screenshot-verified clean
- budget at 120 Hz is 8.3 ms → 65–99 % headroom
**Cleanup done (2026-10-28):** all jank-hunt instrumentation stripped
(FR/SCR/TICK/APLYD/STG logging, `stg.rs`, `.gallery_*` knobs, jsamp
thread sampler, perf-file mirroring in nblog, DbgScroll). KEPT:
nblog non-blocking logger (logd backpressure is real), zero-dimension
decode guards (thumb.rs + gputex.rs), keep-alive (still default-off,
`.gallery_keep`), debug-level coverage logs.
**BUG FIXED while cleaning:** the app launched into an unstoppable
fast scroll on the user's phone — a leftover `.gallery_cmd`
(`scroll -12 4000`) from the last A/B run: DbgScroll never deleted
the file, and a fresh process sees `cmd_mtime == None` → re-reads it
on every launch; while active it also overrode the user's swipes.
Fix: the debug-scroll hook (and all file knobs) are gone; the
leftover file was deleted from the device.
**Next: M4 viewer** (tap cell → full decode + overlay, pinch/pan,
double-tap zoom, back gesture, EXIF orientation). Work on the
emulator first (user directive).

View File

@ -0,0 +1,114 @@
# Slint 1.18 Skia renderer: redundant per-frame final `flush()` causes scroll jank on Mali
Status: **worked around locally** (vendored one-line deletion, see below).
Upstream issue: **NOT filed as of 2026-10-28.** Not found in upstream issues at
research time (see "Prior art" below). Re-visit filing if the workaround must be
maintained across Slint upgrades.
## Symptom
Pixel 9 Pro (Tensor G4, **Mali G715**, 120 Hz), 8,580-item `ListView` grid of
GPU-resident wgpu textures: 2–4 deterministic scroll stalls of 19–26 ms at fixed
content offsets during scrolling. Same Slint code on an x86_64 emulator
(SwiftShader Vulkan): **zero stalls**.
## Root cause (proven by stage-timestamp profiling)
The Skia renderer's `render_components_to_canvas` ends with a **CPU-synchronous**
```rust
if let Some(ctx) = gr_context.as_mut() {
ctx.flush(None); // GrDirectContext::flush
}
```
(stage `FL2` in the profiling below). Steady-state cost: 0.3–0.8 ms. When the
Mali driver's queue is momentarily busy — new texture uploads landing
(`queue.write_texture` copies), first-draw pipeline state, swapchain pressure —
that call **blocks the UI thread 19.2–20.4 ms**, producing the visible stall.
SwiftShader's `flush()` returns instantly, which is why the emulator never
reproduced the bug and every CPU-side hypothesis (item walk, binding
re-evaluation, image import, geometry, worker writes) failed.
### Per-stage frame data (Mali G715, programmatic scroll)
Stages: ACQ = `get_current_texture`, MKS = swapchain surface create,
DC = `draw_contents`, EV = render callback, RCI = item walk + draws,
PD = partial-renderer dirty region, FL1 = pre-`BeforeRendering` flush
(active only while our rendering notifier was set), **FL2 = the final
flush**, SUB = `flush_and_submit` (Skia `submit()`), PRE = `queue.present`.
```
steady frames (y < -2000): SR=4-8ms DC=2-3ms RCI=1-2ms FL2=0.3-0.8ms ev=1 IMG=0-3
stall frames:
y=-574.5 : SR=23.9 DC=22.1 RCI=1.0 FL2=20.4 IMG=0
y=-3543 : SR=23.4 DC=21.2 RCI=1.0 FL2=19.8 IMG=0
y=-4347 : SR=24.3 DC=21.9 RCI=2.0 FL2=19.2 IMG=3 (400x301, 301x400, 400x301)
```
Also ruled out by the same data (all small on stall frames):
item walk (RCI 1–2 ms; Slint 1.18 prunes the walk to ~133–152 visited items,
**not** O(rows) — an earlier O(n) walk diagnosis was wrong), binding
re-evaluations (1/frame), new Skia image creation (0.0–0.1 ms each),
partial renderer (0 ms), swapchain acquire (0.2 ms), submit (0.3 ms), present
(0.6 ms).
A second, smaller stall class (22 ms between stage markers, once per run) was
wgpu driver back-pressure on a `vkQueueSubmit` (the "Slint frame init" clear
pass or the texture-transition submit); it disappeared with the fix and never
reappeared in verification runs.
## Why the flush is redundant (for the wgpu backend)
Frame order in `i-slint-renderer-skia/wgpu_30_surface.rs::render`:
1. clear pass (wgpu encoder) + submit
2. `callback(...)` → Skia draws the frame (commands pending in Skia)
3. `flush_and_submit(gr_context)` → **`gr_context.submit(None)`** — submits all
of Skia's pending commands to the same Vulkan queue
4. `queue.present(frame)` → `vkQueuePresentKHR` on the same device/queue
Vulkan guarantees in-order execution on a single queue, so the present cannot
run ahead of Skia's work. The final `GrDirectContext::flush()` therefore adds
no ordering guarantees — only a CPU-side wait that costs 19–24 ms on Mali.
(FL1, the pre-`BeforeRendering` flush, exists to make the window-background
clear visible to `BeforeRendering` callbacks; it is only active while a
rendering notifier is registered and was left in place.)
## Local workaround
`vendor/i-slint-renderer-skia` (pinned 1.18.1, `[patch.crates-io]` in
`Cargo.toml`) with that final flush removed (see the "jank fix" comment in
`lib.rs::render_components_to_canvas`). The patch set is exactly this
one hunk; the rest of `vendor/i-slint-renderer-skia` is byte-identical
to the 1.18.1 registry source.
Verification on the Pixel 9 Pro (post-fix):
| test | before | after |
|---|---|---|
| slow scroll 5 s (×3 runs) | 2–4 stalls, 20–26 ms | 0 stalls, max 3.6 / 5.8 / 3.9 ms |
| fast fling 8× velocity | stalls | 0 stalls, max 7.4 ms, p50 1.0 ms |
| display | — | clean (screenshot-verified, no artifacts) |
Frame budget at 120 Hz is 8.3 ms.
## Open question before filing upstream
We cannot rule out that the final flush exists to bound GPU-side resource
lifetime or to serialize against the (non-wgpu) backends that share
`render_components_to_canvas` (OpenGL/EGL, where the Skia context and the
swapchain may be on different queues). If filing, propose making the flush
backend-gated or replacing it with an async submit, and cite the data above.
## Prior art (adjacent, not identical)
- slint-ui/slint#12030 (open): rendering notifier + FemtoVG causes per-frame
flush → pipeline cache cleared → pipeline recreation every frame. Same
*class* of problem (per-frame synchronous flush interacting with GPU
pipeline state), different backend and mechanism.
- slint-ui/slint#11119 (open): request for a debugging tool to diagnose
performance issues (this bug was found with ad-hoc stage timestamps in the
vendored crates).
- slint-ui/slint#3867 (open): `accessibility` feature perf impact on big
listviews — checked and ruled out for this app (accessibility off).

View File

@ -50,6 +50,13 @@ pub fn upload_rgba(rgba: &[u8], width: u32, height: u32) -> Option<wgpu::Texture
Extent3d, Origin3d, TexelCopyBufferLayout, TexelCopyTextureInfo, TextureAspect, Extent3d, Origin3d, TexelCopyBufferLayout, TexelCopyTextureInfo, TextureAspect,
TextureDescriptor, TextureDimension, TextureUsages, TextureDescriptor, TextureDimension, TextureUsages,
}; };
// Defensive: a 0-dimension create_texture is a wgpu validation error
// that PANICS the calling (worker) thread. Callers already guard, but
// never let a bad decode take down a worker.
if width == 0 || height == 0 {
log::warn!("gputex: refusing zero-dimension upload ({width}x{height})");
return None;
}
let (device, queue) = GPU.get()?; let (device, queue) = GPU.get()?;
let texture = device.create_texture(&TextureDescriptor { let texture = device.create_texture(&TextureDescriptor {
label: Some("gallery-thumb"), label: Some("gallery-thumb"),

View File

@ -1,154 +0,0 @@
//! In-app thread sampler (jank hunt; REMOVE after).
//!
//! The phone is non-rooted, so an external sampler (shell uid) cannot read
//! the app's /proc. This samples `/proc/self/task` from inside the app at
//! 1 ms: per target thread, the scheduler state, wchan (what it waits in),
//! and CPU-time delta — enough to decide, for any FR spike, whether the
//! UI thread was ON-CPU doing work or WAITING (futex/GPU fence), and what
//! the decode workers and the Mali driver threads (`mali-compiler` =
//! shader compilation, `mali-event-hand`) were doing meanwhile.
//!
//! Enabled by `/sdcard/Download/.gallery_jsamp`; output goes to
//! `/sdcard/Download/.gallery_jsamp.log` in the process's monotonic clock
//! (same `now_ms` as SCR/TICK/FR, so windows line up exactly).
#![cfg(target_os = "android")]
use std::io::Write as _;
use std::time::Duration;
const KNOB: &str = "/sdcard/Download/.gallery_jsamp";
const OUT: &str = "/sdcard/Download/.gallery_jsamp.log";
pub fn start() {
if !std::path::Path::new(KNOB).exists() {
return;
}
std::thread::Builder::new()
.name("jsamp".into())
.spawn(move || {
// nice 0: at +10 the sampler starved exactly during the CPU
// contention we try to observe (no samples in the spike
// window).
crate::prio::set_self_nice(0);
// ONE-SHOT permission probes. CRITICAL: SELinux-denied reads
// must never be retried in a tight loop — each denial is an
// audit event, and ~100/s of them flooded the audit subsystem
// and ANR'd the whole app.
let can_task = std::fs::read_dir("/proc/self/task").is_ok();
let can_cpufreq = std::fs::read_to_string(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
)
.is_ok();
let _ = (can_task, can_cpufreq);
// append (not truncate): SELinux denies create+truncate on the
// fresh path; analysis takes the last lines.
let mut out = match std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(OUT)
{
Ok(f) => std::io::BufWriter::new(f),
Err(e) => {
log::error!("jsamp: open {OUT}: {e}");
return;
}
};
// tid -> (comm, last_cpu_us); comm cached (read once per tid)
let mut last: std::collections::HashMap<u32, (String, u64)> =
std::collections::HashMap::new();
let mut skipped: std::collections::HashSet<u32> = std::collections::HashSet::new();
let mut tick = 0u32;
loop {
tick += 1;
if tick % 250 == 0 {
last.clear(); // tids may change (mali pairs get recreated)
skipped.clear();
}
let ts = crate::now_ms();
let dir = std::fs::read_dir("/proc/self/task");
if can_task {
if let Ok(dir) = dir {
for ent in dir.flatten() {
let tid: u32 = match ent.file_name().to_string_lossy().parse() {
Ok(t) => t,
Err(_) => continue,
};
let known_interesting = last.get(&tid).map(|(c, _)| {
c == "android_main"
|| c.starts_with("thumb-")
|| c.starts_with("mali-")
|| c == "slint vsync"
|| c == "gpu-keep"
}).unwrap_or(false);
if !known_interesting && !last.contains_key(&tid) && !skipped.contains(&tid) {
let comm = match std::fs::read_to_string(format!("/proc/self/task/{tid}/comm")) {
Ok(c) => c.trim().to_string(),
Err(_) => continue,
};
let interesting = comm == "android_main"
|| comm.starts_with("thumb-")
|| comm.starts_with("mali-")
|| comm == "slint vsync"
|| comm == "gpu-keep";
if !interesting {
skipped.insert(tid); // cache the negative too
continue;
}
last.entry(tid).or_insert_with(|| (comm, 0));
}
let (comm, prev) = match last.get(&tid) {
Some(v) => (v.0.clone(), v.1),
None => continue,
};
// stat: pid (comm) state ppid ... utime(14) stime(15)
let stat = match std::fs::read_to_string(format!("/proc/self/task/{tid}/stat")) {
Ok(s) => s,
Err(_) => continue,
};
let close = match stat.rfind(')') {
Some(i) => i,
None => continue,
};
let fields: Vec<&str> = stat[close + 2..].split_whitespace().collect();
let state = fields.first().copied().unwrap_or("?");
// utime/stime are USER_HZ ticks (1/100 s) -> us
let cpu_us = fields
.get(11) // utime (0-based after comm: state=0 ppid=1 ... utime=11)
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0)
* 10_000
+ fields
.get(12)
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0)
* 10_000;
let wchan = std::fs::read_to_string(format!("/proc/self/task/{tid}/wchan"))
.map(|w| w.trim().to_string())
.unwrap_or_default();
let delta = cpu_us.saturating_sub(prev);
let _ =
writeln!(out, "JS {ts:11.2} {tid} {comm} {state} {wchan} dcpu={delta}");
last.insert(tid, (comm, cpu_us));
}
}
}
// Per-core frequency: is the CPU in a low-clock state during
// a spike? (Readability probed once at start — never retry a
// denied path; the cgroup/PSI probes were removed after they
// ANR'd the app via audit flooding.)
if can_cpufreq {
let freq0 = std::fs::read_to_string(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
)
.ok()
.map(|s| s.trim().to_string())
.unwrap_or_default();
let _ = writeln!(out, "JSCP {ts:11.2} freq0={freq0}");
}
let _ = out.flush();
std::thread::sleep(Duration::from_millis(5));
}
})
.ok();
log::info!("jsamp: sampling started");
}

View File

@ -76,8 +76,6 @@
slint::include_modules!(); slint::include_modules!();
pub mod db; pub mod db;
#[cfg(target_os = "android")]
pub mod jsamp;
pub mod gputex; pub mod gputex;
pub mod images; pub mod images;
pub mod scan; pub mod scan;
@ -166,7 +164,7 @@ use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use slint::{ use slint::{
ComponentHandle, Image, Model, ModelRc, Rgb8Pixel, Rgba8Pixel, SharedPixelBuffer, SharedString, ComponentHandle, Image, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString,
Timer, Timer,
TimerMode, VecModel, TimerMode, VecModel,
}; };
@ -176,6 +174,11 @@ use crate::thumb::{Engine, Job, JobResult, GRID_TARGET, MAX_WORKER_QUEUE};
/// Must match main.slint (GridRow layout + ListView spacing + padding). /// Must match main.slint (GridRow layout + ListView spacing + padding).
const GRID_COLS: usize = 3; const GRID_COLS: usize = 3;
// Mirrors the VerticalBox padding in main.slint. The list's width already
// excludes it (list-width <=> listview.width), so geometry math must NOT
// subtract it again — kept as the documented single source of truth for the
// .slint side.
#[allow(dead_code)]
const GRID_PADDING: f32 = 12.0; const GRID_PADDING: f32 = 12.0;
const GRID_GAP: f32 = 4.0; const GRID_GAP: f32 = 4.0;
const ROW_SPACING: f32 = 4.0; const ROW_SPACING: f32 = 4.0;
@ -196,20 +199,6 @@ const INITIAL_VIEWPORT_CELLS: usize = 60;
/// Hard cap on cells holding pixels in the model: 225 × ~0.73 MB ≈ 165 MB /// Hard cap on cells holding pixels in the model: 225 × ~0.73 MB ≈ 165 MB
/// (≈1–2 % of a modern phone's RAM; bounded by RETENTION_ROWS in practice). /// (≈1–2 % of a modern phone's RAM; bounded by RETENTION_ROWS in practice).
const MAX_PAINTED: usize = 225; const MAX_PAINTED: usize = 225;
/// Jank-hunt test knob (REMOVE after): live cap on painted cells, default
/// MAX_PAINTED; overridable via /sdcard/Download/.gallery_max_painted.
static MAX_PAINTED_LIVE: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(MAX_PAINTED);
/// Jank-hunt test knob (REMOVE after): 1x1 grey cell images (no texture work).
static JANK_GREY_IMAGES: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
/// Jank-hunt test knob (REMOVE after): disable background processing —
/// no new jobs are submitted (FILL/PRUNE skipped); the decode workers drain
/// and idle. Already-in-flight work still lands; evictions keep memory
/// bounded. New cells stay grey. Isolate: does scroll jank come from the
/// thumbnail pipeline at all?
static JANK_FREEZE: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
/// Per-tick (per-frame) model work budgets. The tick runs at display rate /// Per-tick (per-frame) model work budgets. The tick runs at display rate
/// (~120 Hz): work MUST fit one frame, so updates are SPREAD across frames /// (~120 Hz): work MUST fit one frame, so updates are SPREAD across frames
/// instead of batched (the old 16-row/100 ms batch was visible as a content /// instead of batched (the old 16-row/100 ms batch was visible as a content
@ -218,14 +207,6 @@ static JANK_FREEZE: std::sync::atomic::AtomicBool =
/// pixels actually change) — cheap enough for 4+4 per tick. /// pixels actually change) — cheap enough for 4+4 per tick.
const MAX_PAINT_CELLS_PER_TICK: usize = 2; const MAX_PAINT_CELLS_PER_TICK: usize = 2;
const MAX_EVICT_CELLS_PER_TICK: usize = 4; const MAX_EVICT_CELLS_PER_TICK: usize = 4;
// Jank-hunt test knobs (REMOVE after): .gallery_paint / .gallery_evict /
// .gallery_tick_ms override the per-frame budgets at app start.
static JANK_PAINT: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(MAX_PAINT_CELLS_PER_TICK);
static JANK_EVICT: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(MAX_EVICT_CELLS_PER_TICK);
pub static JANK_TICK_MS: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(DRAIN_INTERVAL_MS);
/// Reconcile tick period. 8 ms ≈ one 120 Hz frame; Slint's event loop is /// Reconcile tick period. 8 ms ≈ one 120 Hz frame; Slint's event loop is
/// VSync-paced on Android, so the actual cadence quantizes to the display /// VSync-paced on Android, so the actual cadence quantizes to the display
/// refresh (8 ms on 120 Hz, ~16 ms on 60 Hz). Per-tick work is tiny and /// refresh (8 ms on 120 Hz, ~16 ms on 60 Hz). Per-tick work is tiny and
@ -258,23 +239,6 @@ struct AppState {
painted_total: AtomicU64, painted_total: AtomicU64,
/// Rate-limits the stall alarm. UI thread only. /// Rate-limits the stall alarm. UI thread only.
last_stall_log: Mutex<Instant>, last_stall_log: Mutex<Instant>,
/// Jank-hunt test hook: file-triggered programmatic scroll (see tick).
dbg: Mutex<DbgScroll>,
}
/// Test hook (jank hunt): `/sdcard/Download/.gallery_cmd` with
/// `scroll <px_per_ms> <duration_ms>` or `stop` drives the list at a
/// perfectly smooth constant velocity — an input source with ZERO transport
/// jitter (adb `input` injects through virtio at ~60 Hz in bursts, which
/// masquerades as app jank). Removes the OS input pipeline from the
/// equation: if a programmatic scroll is janky, the app/render is at fault.
struct DbgScroll {
active_until: Option<Instant>,
vel: f32,
cmd_mtime: Option<std::time::SystemTime>,
last_check: Instant,
last_y: f32,
last_t: Instant,
} }
/// Create the pool + cache dir once per process. /// Create the pool + cache dir once per process.
@ -295,42 +259,6 @@ fn state() -> &'static AppState {
GRID_TARGET, GRID_TARGET,
engine.cache_dir().display() engine.cache_dir().display()
); );
// Jank-hunt test knobs (REMOVE after).
#[cfg(target_os = "android")]
{
if let Ok(s) = std::fs::read_to_string("/sdcard/Download/.gallery_max_painted") {
if let Ok(m) = s.trim().parse::<usize>() {
MAX_PAINTED_LIVE.store(m, Ordering::Relaxed);
log::info!("JANKTEST max_painted -> {m}");
}
}
if std::path::Path::new("/sdcard/Download/.gallery_grey").exists() {
JANK_GREY_IMAGES.store(true, Ordering::Relaxed);
log::info!("JANKTEST grey images ON");
}
if std::path::Path::new("/sdcard/Download/.gallery_freeze").exists() {
JANK_FREEZE.store(true, Ordering::Relaxed);
log::info!("JANKTEST freeze ON — no background processing");
}
if let Ok(s) = std::fs::read_to_string("/sdcard/Download/.gallery_paint") {
if let Ok(m) = s.trim().parse::<usize>() {
JANK_PAINT.store(m, Ordering::Relaxed);
log::info!("JANKTEST paint = {m}");
}
}
if let Ok(s) = std::fs::read_to_string("/sdcard/Download/.gallery_evict") {
if let Ok(m) = s.trim().parse::<usize>() {
JANK_EVICT.store(m, Ordering::Relaxed);
log::info!("JANKTEST evict = {m}");
}
}
if let Ok(s) = std::fs::read_to_string("/sdcard/Download/.gallery_tick_ms") {
if let Ok(m) = s.trim().parse::<u64>() {
JANK_TICK_MS.store(m.max(4), Ordering::Relaxed);
log::info!("JANKTEST tick_ms = {m}");
}
}
}
AppState { AppState {
engine, engine,
entries: Mutex::new(Vec::new()), entries: Mutex::new(Vec::new()),
@ -340,14 +268,6 @@ fn state() -> &'static AppState {
failed: Mutex::new(HashSet::new()), failed: Mutex::new(HashSet::new()),
painted_total: AtomicU64::new(0), painted_total: AtomicU64::new(0),
last_stall_log: Mutex::new(Instant::now()), last_stall_log: Mutex::new(Instant::now()),
dbg: Mutex::new(DbgScroll {
active_until: None,
vel: 0.0,
cmd_mtime: None,
last_check: Instant::now(),
last_y: 0.0,
last_t: Instant::now(),
}),
} }
}) })
} }
@ -404,23 +324,6 @@ fn set_list(weak: &slint::Weak<Main>, entries: Vec<Entry>, status: String) {
app.inflight.lock().unwrap().clear(); app.inflight.lock().unwrap().clear();
app.painted.lock().unwrap().clear(); app.painted.lock().unwrap().clear();
app.failed.lock().unwrap().clear(); app.failed.lock().unwrap().clear();
// Jank-hunt test knob (REMOVE after): cap the item count to isolate
// scene-size cost from textured-cell cost.
#[cfg(target_os = "android")]
let entries = {
let e = entries;
match std::fs::read_to_string("/sdcard/Download/.gallery_max").ok().and_then(
|s| s.trim().parse::<usize>().ok(),
) {
Some(m) if m < e.len() => {
log::info!("JANKTEST capping items {} -> {}", e.len(), m);
let mut e = e;
e.truncate(m);
e
}
_ => e,
}
};
*app.entries.lock().unwrap() = entries.clone(); *app.entries.lock().unwrap() = entries.clone();
let n = entries.len(); let n = entries.len();
*app.viewport.lock().unwrap() = 0..INITIAL_VIEWPORT_CELLS.min(n); *app.viewport.lock().unwrap() = 0..INITIAL_VIEWPORT_CELLS.min(n);
@ -462,7 +365,7 @@ fn apply_cell_updates(
) -> usize { ) -> usize {
let mut painted_now = 0usize; let mut painted_now = 0usize;
for r in paints { for r in paints {
if painted_now >= JANK_PAINT.load(Ordering::Relaxed) { if painted_now >= MAX_PAINT_CELLS_PER_TICK {
break; // the rest is re-covered by the fill step break; // the rest is re-covered by the fill step
} }
if !r.ok || r.id >= entries.len() || entries[r.id].path != r.path { if !r.ok || r.id >= entries.len() || entries[r.id].path != r.path {
@ -481,13 +384,7 @@ fn apply_cell_updates(
let Some(cells) = cells_of(&item) else { let Some(cells) = cells_of(&item) else {
continue; continue;
}; };
// Jank-hunt test knob (REMOVE after): 1x1 grey images — same item let image = if let Some(tex) = r.gpu.clone() { // cheap: Arc interior
// count, zero real texture work. Isolates base window-render cost.
let image = if JANK_GREY_IMAGES.load(Ordering::Relaxed) {
let mut g = SharedPixelBuffer::<Rgb8Pixel>::new(1, 1);
g.make_mut_bytes().fill(32);
Image::from_rgb8(g)
} else if let Some(tex) = r.gpu.clone() { // cheap: Arc interior
// GPU-resident texture: the worker created it on Slint's own // GPU-resident texture: the worker created it on Slint's own
// wgpu device and submitted the upload (async). Zero pixel // wgpu device and submitted the upload (async). Zero pixel
// work in this frame — first present costs ~0 (was ~11 ms // work in this frame — first present costs ~0 (was ~11 ms
@ -561,7 +458,13 @@ fn viewport_for(y: f32, height: f32, width: f32, n: usize) -> Option<Range<usize
if width <= 0.0 || n == 0 { if width <= 0.0 || n == 0 {
return None; return None;
} }
let cell = (width - 2.0 * GRID_PADDING - 2.0 * GRID_GAP) / GRID_COLS as f32; // MUST match main.slint's GridRow exactly: `cw: (self.width - 8px)/3`,
// `height: cw + 4px`. `width` is the ListView's own width (the 12px
// GRID_PADDING is on the surrounding VerticalBox, already excluded) —
// do NOT subtract it again (off-by-8px/row made the paint targeting
// lag the visible rows by ~2 rows: new images' first draw landed on
// visible frames = the 20-27 ms Mali first-present hitch).
let cell = (width - 2.0 * GRID_GAP) / GRID_COLS as f32;
let row_h = cell + ROW_SPACING; let row_h = cell + ROW_SPACING;
let first = (y.abs() / row_h) as usize; let first = (y.abs() / row_h) as usize;
let visible = (height / row_h) as usize + 1; let visible = (height / row_h) as usize + 1;
@ -571,75 +474,27 @@ fn viewport_for(y: f32, height: f32, width: f32, n: usize) -> Option<Range<usize
..((first + visible + MARGIN_ROWS) * GRID_COLS).min(n)) ..((first + visible + MARGIN_ROWS) * GRID_COLS).min(n))
} }
// ---- Jank-hunt instrumentation (2026-10-27; REMOVE after the hunt) ---- /// Render notifier: one-time capture of Slint's wgpu device so the decode
// Every PROCESSED scroll callback logs SCR: the offset stream. Uneven dy = /// workers can upload thumbnail textures off the UI thread (gputex). Runs
// uneven motion quantum; time gaps = the event loop was starved (blocked UI /// on the UI thread during rendering; the work is a one-shot store.
// thread or GPU). Every reconcile tick logs TICK: UI-thread frame cadence fn install_render_notifier(window: &Main) {
// plus the tick's total cost. A slow in-place apply logs APLY (texture
// upload cost. All logging goes through the non-blocking logger (nblog)
// so logd backpressure can never stall a UI frame.
static LAST_SCR_Y: std::sync::atomic::AtomicI64 =
std::sync::atomic::AtomicI64::new(i64::MIN);
static LAST_TICK_T: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// Per-frame ground truth via Window::set_rendering_notifier: FR lines carry
// the app-side render cost (Before->After, us) and the gap between rendered
// frames (ms). Same monotonic clock as SCR, so input->render latency and
// edge-crossing correlation are computable in one file.
static FR_BEFORE_US: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static FR_LAST_US: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn now_us() -> u64 {
NOW_T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
}
/// Install the per-frame logger (jank hunt; REMOVE after). Runs on the UI
/// thread during rendering: only atomics + a non-blocking log push.
fn install_frame_logger(window: &Main) {
use std::sync::atomic::Ordering;
let _ = window.window().set_rendering_notifier(|state, api| { let _ = window.window().set_rendering_notifier(|state, api| {
let now = now_us(); if let slint::RenderingState::RenderingSetup = state {
match state { gputex::init(api);
// One-time: capture Slint's wgpu device so the decode workers log::info!(
// can upload thumbnail textures off the UI thread (gputex). "gputex: wgpu device {}",
slint::RenderingState::RenderingSetup => { if gputex::ready() { "captured" } else { "NOT captured" }
gputex::init(api); );
log::info!("gputex: wgpu device {}", if gputex::ready() { "captured" } else { "NOT captured" });
}
slint::RenderingState::BeforeRendering => {
FR_BEFORE_US.store(now, Ordering::Relaxed);
}
slint::RenderingState::AfterRendering => {
let before = FR_BEFORE_US.load(Ordering::Relaxed);
let last = FR_LAST_US.swap(now, 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);
}
_ => {}
} }
}); });
} }
/// Monotonic ms since process start (wall clock could jump on NTP and be
/// mistaken for jank).
static NOW_T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
#[inline]
pub(crate) fn now_ms() -> f64 {
let t0 = NOW_T0.get_or_init(std::time::Instant::now);
t0.elapsed().as_secs_f64() * 1000.0
}
#[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:
//! logd-pipe backpressure during log bursts was blocking the UI thread //! logd-pipe backpressure during log bursts was observed to block the
//! for 10–40 ms, polluting (and causing) exactly the scroll frames we //! UI thread for 10–40 ms. Records are formatted at the call site and
//! try to measure. Records are formatted at the call site and pushed //! pushed into a bounded channel; a drain thread does the real
//! 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::io::Write as _;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
@ -661,32 +516,7 @@ mod nblog {
std::thread::Builder::new() std::thread::Builder::new()
.name("log-drain".into()) .name("log-drain".into())
.spawn(move || { .spawn(move || {
// Jank hunt (REMOVE after): mirror the cadence lines to a
// file — the logcat ring buffer rotates every few
// seconds under SCR/TICK volume and loses the data.
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);
let mut perf_lines = 0usize;
for (prio, msg) in rx { for (prio, msg) in rx {
if let Some(w) = perf.as_mut() {
if msg.starts_with("SCR ")
|| msg.starts_with("TICK")
|| msg.starts_with("APLY")
|| msg.starts_with("FR ")
{
let _ = writeln!(w, "{}", msg);
perf_lines += 1;
if perf_lines >= 32 {
let _ = w.flush();
perf_lines = 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> =
@ -742,11 +572,6 @@ fn on_scroll(app: &AppState, y: f32, height: f32, width: f32) {
if let Some(vp) = viewport_for(y, height, width, n) { if let Some(vp) = viewport_for(y, height, width, n) {
*app.viewport.lock().unwrap() = vp; *app.viewport.lock().unwrap() = vp;
} }
// SCR (jank hunt): the processed offset stream.
let y100 = (y * 100.0) as i64;
let prev = LAST_SCR_Y.swap(y100, Ordering::Relaxed);
let dy = if prev == i64::MIN { 0.0 } else { (y100 - prev) as f64 / 100.0 };
log::info!("SCR {:11.2} y={:8.1} dy={:7.1}", now_ms(), y, dy);
} }
/// The reconcile tick, at display rate (~120 Hz; VSync-quantized on /// The reconcile tick, at display rate (~120 Hz; VSync-quantized on
@ -776,7 +601,7 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
let timer = Timer::default(); let timer = Timer::default();
timer.start( timer.start(
TimerMode::Repeated, TimerMode::Repeated,
std::time::Duration::from_millis(JANK_TICK_MS.load(Ordering::Relaxed)), std::time::Duration::from_millis(DRAIN_INTERVAL_MS),
move || { move || {
let Some(app) = STATE.get() else { return }; let Some(app) = STATE.get() else { return };
let Some(w) = weak.upgrade() else { return }; let Some(w) = weak.upgrade() else { return };
@ -789,64 +614,6 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
if entries.is_empty() { if entries.is_empty() {
return; return;
} }
// Jank hunt (REMOVE after): tick cadence + cost.
let tick_t0 = Instant::now();
// DEBUG-SCROLL TEST HOOK (REMOVE after the hunt): see DbgScroll.
{
let now = Instant::now();
let mut dbg = app.dbg.lock().unwrap();
if dbg.last_check.elapsed() > std::time::Duration::from_millis(150) {
dbg.last_check = now;
let path = "/sdcard/Download/.gallery_cmd";
if let Ok(md) = std::fs::metadata(path) {
let mt = md.modified().ok();
if mt != dbg.cmd_mtime {
dbg.cmd_mtime = mt;
if let Ok(s) = std::fs::read_to_string(path) {
let t = s.trim();
if t.starts_with("scroll") {
let p: Vec<&str> = t.split_whitespace().collect();
if p.len() == 3 {
if let (Ok(v), Ok(d)) =
(p[1].parse::<f32>(), p[2].parse::<u64>())
{
dbg.vel = v;
dbg.active_until =
Some(now + std::time::Duration::from_millis(d));
dbg.last_t = now;
log::info!("DBGCMD scroll v={v} d={d}");
}
}
} else if t == "stop" {
dbg.active_until = None;
log::info!("DBGCMD stop");
}
}
}
}
}
if let Some(end) = dbg.active_until {
if now < end {
let dt = ((now.duration_since(dbg.last_t).as_millis()) as f32)
.clamp(1.0, 25.0);
dbg.last_t = now;
// Clamp to the list's real range: y in [-(n*row_h-h), 0].
let width = w.get_list_width() as f32;
let height = w.get_list_height() as f32;
let cell = (width - 2.0 * GRID_PADDING - 2.0 * GRID_GAP)
/ GRID_COLS as f32;
let row_h = cell + ROW_SPACING;
let y_min = (-(entries.len() as f32 * row_h) + height).min(0.0);
let y = (w.get_list_y() as f32 + dbg.vel * dt).clamp(y_min, 0.0);
let dy = y - dbg.last_y;
dbg.last_y = y;
w.set_list_y(y);
log::info!("SCRDBG {:?} y={:.1} dy={:.1}", now, y, dy);
} else {
dbg.active_until = None;
}
}
}
// 0. POLL: the list's ACTUAL scroll position (momentum-aware). // 0. POLL: the list's ACTUAL scroll position (momentum-aware).
// The scroll callback (on_scroll) is a fast-path hint for // The scroll callback (on_scroll) is a fast-path hint for
// drags; this is the ground truth. // drags; this is the ground truth.
@ -948,7 +715,7 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
// evictions also fit the frame budget. // evictions also fit the frame budget.
let to_clear: Vec<usize> = { let to_clear: Vec<usize> = {
let painted = app.painted.lock().unwrap(); let painted = app.painted.lock().unwrap();
let cap = MAX_PAINTED_LIVE.load(Ordering::Relaxed); let cap = MAX_PAINTED;
let overflow = painted.len().saturating_sub(cap); let overflow = painted.len().saturating_sub(cap);
// Burst eviction: steady state (painted << cap) does NO // Burst eviction: steady state (painted << cap) does NO
// eviction work at all — every tick's only model change is // eviction work at all — every tick's only model change is
@ -967,7 +734,7 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
.collect(); .collect();
far.sort_by_key(|id| center.abs_diff(*id)); // nearest first far.sort_by_key(|id| center.abs_diff(*id)); // nearest first
far.reverse(); // farthest first far.reverse(); // farthest first
let budget = JANK_EVICT.load(Ordering::Relaxed).max(4); let budget = MAX_EVICT_CELLS_PER_TICK;
let n = far.len().min(budget.max(overflow.min(2 * budget))); let n = far.len().min(budget.max(overflow.min(2 * budget)));
far.into_iter().take(n).collect() far.into_iter().take(n).collect()
} }
@ -975,12 +742,7 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
// 3. APPLY: in-place nested cell updates (≤4 paints + ≤4 // 3. APPLY: in-place nested cell updates (≤4 paints + ≤4
// evictions; each = one cell property change). // evictions; each = one cell property change).
let apply_t0 = Instant::now(); // jank hunt (REMOVE after)
let painted_now = apply_cell_updates(app, m, &entries, &paints, &to_clear); let painted_now = apply_cell_updates(app, m, &entries, &paints, &to_clear);
let apply_us = apply_t0.elapsed().as_micros(); // jank hunt
if apply_us > 1500 { // jank hunt (REMOVE after)
log::info!("APLY {:11.2} {}us p={} c={}", now_ms(), apply_us, painted_now, to_clear.len());
}
// 4. FILL: every viewport cell without pixels and without an // 4. FILL: every viewport cell without pixels and without an
// in-flight job gets submitted now, center-first so the eye is // in-flight job gets submitted now, center-first so the eye is
@ -993,10 +755,6 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
// comes back, the disk cache serves those cells in ~10 ms, never a // comes back, the disk cache serves those cells in ~10 ms, never a
// re-decode. In-flight jobs are untouched; their out-of-viewport // re-decode. In-flight jobs are untouched; their out-of-viewport
// results are dropped at consumption. // results are dropped at consumption.
// Jank-hunt (REMOVE after): both are skipped under FREEZE — the
// decode workers then drain and idle, isolating the scroll path
// from all thumbnail-pipeline activity.
if !JANK_FREEZE.load(Ordering::Relaxed) {
{ {
let painted = app.painted.lock().unwrap(); let painted = app.painted.lock().unwrap();
let failed = app.failed.lock().unwrap(); let failed = app.failed.lock().unwrap();
@ -1053,13 +811,11 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
log::debug!("gallery: pruned {} stale queued jobs", dropped.len()); log::debug!("gallery: pruned {} stale queued jobs", dropped.len());
} }
} }
} // !JANK_FREEZE
// 5. Invariant (debug builds): the viewport is fully covered. // 5. Invariant (debug builds): the viewport is fully covered.
// A violation means a visible cell is forgotten — the exact // A violation means a visible cell is forgotten — the exact
// bug class this design exists to make impossible. // bug class this design exists to make impossible.
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
if !JANK_FREEZE.load(Ordering::Relaxed) {
{ {
let painted = app.painted.lock().unwrap(); let painted = app.painted.lock().unwrap();
let inflight = app.inflight.lock().unwrap(); let inflight = app.inflight.lock().unwrap();
@ -1072,7 +828,6 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
debug_assert!(covered, "viewport cell {id} is uncovered"); debug_assert!(covered, "viewport cell {id} is uncovered");
} }
} }
}
// 6. Diagnostics: stall alarm (rate-limited) + acceptance log. // 6. Diagnostics: stall alarm (rate-limited) + acceptance log.
{ {
@ -1105,19 +860,6 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
); );
} }
} }
// Jank hunt (REMOVE after): stall-only tick log. Log when the
// gap since the previous tick exceeds one 60 Hz frame (a dropped
// 120 Hz frame) or the tick itself was slow — full-cadence
// logging rotates the logcat ring buffer in seconds on the
// phone (its ~1.7 ms/tick baseline tripped the old 500 us
// threshold every tick).
let tick_us = tick_t0.elapsed().as_micros();
let t_now = now_ms();
let last = f64::from_bits(LAST_TICK_T.swap(t_now.to_bits(), Ordering::Relaxed));
let gap = t_now - last;
if tick_us > 3000 || gap > 16.0 {
log::info!("TICK {:11.2} gap={:.1} d={}us p={}", t_now, gap, tick_us, painted_now);
}
}, },
); );
std::mem::forget(timer); std::mem::forget(timer);
@ -1127,7 +869,7 @@ fn start_drain_timer(weak: &slint::Weak<Main>) {
/// (streaming into the list on cold start). M3: the tick fills the viewport /// (streaming into the list on cold start). M3: the tick fills the viewport
/// as it moves — top cells right after (re)paint, visible cells on scroll. /// as it moves — top cells right after (re)paint, visible cells on scroll.
pub fn start_scan(window: &Main) { pub fn start_scan(window: &Main) {
install_frame_logger(window); install_render_notifier(window);
let model = ModelRc::new(VecModel::<Item>::default()); let model = ModelRc::new(VecModel::<Item>::default());
window.set_items(model); window.set_items(model);
let weak = window.as_weak(); let weak = window.as_weak();
@ -1254,9 +996,6 @@ fn android_main(app: slint::android::AndroidApp) {
// (Start/Resume/Pause/Stop/SaveState/ConfigChanged/...) while Slint owns // (Start/Resume/Pause/Stop/SaveState/ConfigChanged/...) while Slint owns
// the event loop. This is Slint's one first-class Android lifecycle hook: // the event loop. This is Slint's one first-class Android lifecycle hook:
// M5 re-checks storage permission on Resume (user returned from Settings). // M5 re-checks storage permission on Resume (user returned from Settings).
// Jank hunt (REMOVE after): in-app thread sampler, gated by knob.
jsamp::start();
// GPU pipeline keep-alive (gputex): started on Start/Resume, stopped // GPU pipeline keep-alive (gputex): started on Start/Resume, stopped
// on Pause/Stop (battery). INACTIVE BY DEFAULT — on Mali it froze the // on Pause/Stop (battery). INACTIVE BY DEFAULT — on Mali it froze the
// display pipeline (see gputex::Keepalive docs). Debug knob: // display pipeline (see gputex::Keepalive docs). Debug knob:

View File

@ -484,7 +484,15 @@ fn worker_loop(
// Upload to the GPU on Slint's own device/queue (async, no UI // Upload to the GPU on Slint's own device/queue (async, no UI
// involvement). On success the CPU bytes are NOT sent over the // involvement). On success the CPU bytes are NOT sent over the
// channel — the texture is already resident. See gputex. // channel — the texture is already resident. See gputex.
let gpu = crate::gputex::upload_rgba(&rgba, width, height); // Zero-dimension decode results (undecodable files) must NOT create
// a texture: wgpu validation panics the worker thread on a 0-width
// create_texture (measured 2026-10-28: 'Dimension X is zero' killed
// thumb-3 mid-scroll).
let gpu = if ok && width > 0 && height > 0 {
crate::gputex::upload_rgba(&rgba, width, height)
} else {
None
};
let rgb = match &gpu { let rgb = match &gpu {
Some(_) => Vec::new(), Some(_) => Vec::new(),
None => rgba, None => rgba,

View File

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

View File

@ -0,0 +1,6 @@
{
"git": {
"sha1": "372cf0ee5577c3dfec309a45e7b778ba4e81b734"
},
"path_in_vcs": "internal/renderers/skia"
}

3538
vendor/i-slint-renderer-skia/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

320
vendor/i-slint-renderer-skia/Cargo.toml vendored Normal file
View File

@ -0,0 +1,320 @@
# 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-renderer-skia"
version = "1.18.1"
authors = ["Slint Developers <info@slint.dev>"]
build = "build.rs"
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Skia based renderer 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]
rustdoc-args = ["--generate-link-to-definition"]
[features]
default = [
"softbuffer",
"wgpu-30",
]
kms = ["softbuffer/kms"]
opengl = []
unstable-wgpu-29 = [
"i-slint-core/unstable-wgpu-29",
"wgpu-29",
]
unstable-wgpu-30 = [
"i-slint-core/unstable-wgpu-30",
"wgpu-30",
]
vulkan = [
"skia-safe/vulkan",
"wgpu-30",
"wgpu-30/vulkan",
"wgpu-30/vulkan-portability",
"wgpu-29?/vulkan",
"wgpu-29?/vulkan-portability",
]
wayland = [
"glutin/wayland",
"softbuffer/wayland",
"softbuffer/wayland-dlopen",
]
wgpu-29 = [
"i-slint-core/wgpu-29",
"dep:wgpu-29",
"dep:spin_on",
"dep:windows-core",
"dep:wgpu-hal-29",
]
wgpu-30 = [
"i-slint-core/wgpu-30",
"dep:wgpu-30",
"dep:spin_on",
"dep:windows-core",
"dep:wgpu-hal-30",
]
x11 = [
"glutin/x11",
"glutin/glx",
"softbuffer/x11",
"softbuffer/x11-dlopen",
]
[lib]
name = "i_slint_renderer_skia"
path = "lib.rs"
[dependencies.cfg-if]
version = "1"
[dependencies.clru]
version = "0.6.0"
[dependencies.const-field-offset]
version = "0.2.1"
[dependencies.glow]
version = "0.18"
[dependencies.i-slint-common]
version = "=1.18.1"
features = ["default"]
default-features = false
[dependencies.i-slint-core]
version = "=1.18.1"
features = [
"default",
"box-shadow-cache",
"shared-parley",
"image-decoders",
"svg",
]
default-features = false
[dependencies.i-slint-core-macros]
version = "=1.18.1"
features = ["default"]
default-features = false
[dependencies.lyon_path]
version = "1.0"
default-features = false
[dependencies.pin-weak]
version = "1"
[dependencies.raw-window-handle]
version = "0.6"
features = ["std"]
[dependencies.scoped-tls-hkt]
version = "0.1"
[dependencies.skia-safe]
version = "0.153.3"
features = ["gl"]
[dependencies.spin_on]
version = "0.1"
optional = true
[dependencies.unicode-segmentation]
version = "1.12.0"
[dependencies.vtable]
version = "0.5"
[dependencies.wgpu-29]
version = "29.0.4"
optional = true
default-features = false
package = "wgpu"
[dependencies.wgpu-30]
version = "30"
optional = true
default-features = false
package = "wgpu"
[build-dependencies.cfg_aliases]
version = "0.2.2"
[target.aarch64-apple-ios-sim.dependencies.objc2]
version = "0.6.0"
features = ["disable-encoding-assertions"]
[target.'cfg(any(not(target_vendor = "apple"), target_os = "macos"))'.dependencies.glutin]
version = "0.32.0"
features = [
"egl",
"wgl",
]
default-features = false
[target.'cfg(not(any(target_vendor = "apple", target_family = "windows")))'.dependencies.skia-safe]
version = "0.153.3"
features = [
"gl",
"vulkan",
]
[target.'cfg(not(any(target_vendor = "apple", target_family = "windows")))'.dependencies.wgpu-29]
version = "29.0.4"
features = ["vulkan"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(not(any(target_vendor = "apple", target_family = "windows")))'.dependencies.wgpu-30]
version = "30"
features = ["vulkan"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(not(target_os = "android"))'.dependencies.bytemuck]
version = "1.13.1"
[target.'cfg(not(target_os = "android"))'.dependencies.softbuffer]
version = "0.4.4"
optional = true
default-features = false
[target.'cfg(target_family = "windows")'.dependencies.skia-safe]
version = "0.153.3"
features = ["d3d"]
[target.'cfg(target_family = "windows")'.dependencies.wgpu-29]
version = "29.0.4"
features = ["dx12"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(target_family = "windows")'.dependencies.wgpu-30]
version = "30"
features = ["dx12"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(target_family = "windows")'.dependencies.windows]
version = "0.62"
features = [
"Win32",
"Win32_Graphics",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Direct3D",
"Win32_Foundation",
"Win32_Graphics_Dxgi_Common",
]
[target.'cfg(target_family = "windows")'.dependencies.windows-core]
version = "0.62.0"
optional = true
[target.'cfg(target_vendor = "apple")'.dependencies.objc2]
version = "0.6.0"
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-app-kit]
version = "0.3.2"
features = [
"std",
"NSResponder",
"NSView",
]
default-features = false
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation]
version = "0.3.2"
features = ["CFCGTypes"]
default-features = false
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation]
version = "0.3.2"
features = [
"std",
"NSGeometry",
]
default-features = false
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-metal]
version = "0.3.2"
features = [
"std",
"MTLCommandQueue",
"MTLCommandBuffer",
"MTLDevice",
"MTLResource",
"MTLTexture",
"MTLTypes",
]
default-features = false
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-quartz-core]
version = "0.3.2"
features = [
"std",
"objc2-metal",
"CALayer",
"CAMetalLayer",
"objc2-core-foundation",
]
default-features = false
[target.'cfg(target_vendor = "apple")'.dependencies.read-fonts]
version = "0.41"
[target.'cfg(target_vendor = "apple")'.dependencies.skia-safe]
version = "0.153.3"
features = ["metal"]
[target.'cfg(target_vendor = "apple")'.dependencies.wgpu-29]
version = "29.0.4"
features = ["metal"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(target_vendor = "apple")'.dependencies.wgpu-30]
version = "30"
features = ["metal"]
optional = true
default-features = false
package = "wgpu"
[target.'cfg(target_vendor = "apple")'.dependencies.wgpu-hal-29]
version = "29.0.4"
optional = true
default-features = false
package = "wgpu-hal"
[target.'cfg(target_vendor = "apple")'.dependencies.wgpu-hal-30]
version = "30"
optional = true
default-features = false
package = "wgpu-hal"
[target.'cfg(target_vendor = "apple")'.dependencies.write-fonts]
version = "0.50"

View File

@ -0,0 +1,117 @@
# 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 CFCG
[package]
name = "i-slint-renderer-skia"
description = "Skia based renderer for Slint"
authors.workspace = true
edition = "2024"
homepage.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
build = "build.rs"
[lib]
path = "lib.rs"
# Note, these features need to be kept in sync (along with their defaults) in
# the C++ crate's CMakeLists.txt
[features]
wayland = ["glutin/wayland", "softbuffer/wayland", "softbuffer/wayland-dlopen"]
x11 = ["glutin/x11", "glutin/glx", "softbuffer/x11", "softbuffer/x11-dlopen"]
opengl = []
# `vulkan-portability` is how wgpu compiles its Vulkan backend on Apple platforms (MoltenVK).
# It feeds an apple-target-gated dependency of wgpu-core, so it's inert elsewhere.
vulkan = [
"skia-safe/vulkan",
"wgpu-30",
"wgpu-30/vulkan",
"wgpu-30/vulkan-portability",
"wgpu-29?/vulkan",
"wgpu-29?/vulkan-portability",
]
kms = ["softbuffer/kms"]
# wgpu-{29,30} enables the wgpu surface module for internal use (e.g. linuxkms DRM rendering), as well as
# the explicit graphics APIs: Direct3D 12 on Windows, Metal on Apple, Vulkan on apple and other unix
wgpu-29 = ["i-slint-core/wgpu-29", "dep:wgpu-29", "dep:spin_on", "dep:windows-core", "dep:wgpu-hal-29"]
unstable-wgpu-29 = ["i-slint-core/unstable-wgpu-29", "wgpu-29"]
wgpu-30 = ["i-slint-core/wgpu-30", "dep:wgpu-30", "dep:spin_on", "dep:windows-core", "dep:wgpu-hal-30"]
unstable-wgpu-30 = ["i-slint-core/unstable-wgpu-30", "wgpu-30"]
default = ["softbuffer", "wgpu-30"]
[dependencies]
i-slint-core = { workspace = true, features = ["default", "box-shadow-cache", "shared-parley", "image-decoders", "svg"] }
i-slint-core-macros = { workspace = true, features = ["default"] }
i-slint-common = { workspace = true, features = ["default"] }
const-field-offset = { version = "0.2.1", path = "../../../helper_crates/const-field-offset" }
vtable = { workspace = true }
cfg-if = "1"
lyon_path = { workspace = true }
pin-weak = "1"
scoped-tls-hkt = "0.1"
raw-window-handle = { version = "0.6", features = ["std"] }
clru = { workspace = true }
skia-safe = { version = "0.153.3", features = ["gl"] }
glow = { workspace = true }
unicode-segmentation = { workspace = true }
wgpu-29 = { workspace = true, optional = true }
wgpu-30 = { workspace = true, optional = true }
spin_on = { version = "0.1", optional = true }
[target.'cfg(any(not(target_vendor = "apple"), target_os = "macos"))'.dependencies]
glutin = { workspace = true, default-features = false, features = ["egl", "wgl"] }
[target.'cfg(not(target_os = "android"))'.dependencies]
# software renderer fallback
softbuffer = { workspace = true, default-features = false, optional = true }
bytemuck = { workspace = true }
[target.'cfg(target_family = "windows")'.dependencies]
windows = { workspace = true, features = ["Win32", "Win32_Graphics", "Win32_Graphics_Dxgi", "Win32_Graphics_Direct3D12", "Win32_Graphics_Direct3D", "Win32_Foundation", "Win32_Graphics_Dxgi_Common"] }
windows-core = { workspace = true, optional = true }
skia-safe = { version = "0.153.3", features = ["d3d"] }
wgpu-29 = { workspace = true, optional = true, features = ["dx12"] }
wgpu-30 = { workspace = true, optional = true, features = ["dx12"] }
[target.'cfg(target_vendor = "apple")'.dependencies]
objc2 = { version = "0.6.0" }
objc2-metal = { version = "0.3.2", default-features = false, features = ["std", "MTLCommandQueue", "MTLCommandBuffer", "MTLDevice", "MTLResource", "MTLTexture", "MTLTypes"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSGeometry"] }
objc2-quartz-core = { version = "0.3.2", default-features = false, features = ["std", "objc2-metal", "CALayer", "CAMetalLayer", "objc2-core-foundation"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSResponder", "NSView"] }
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["CFCGTypes"] }
skia-safe = { version = "0.153.3", features = ["metal"] }
wgpu-29 = { workspace = true, optional = true, features = ["metal"] }
wgpu-30 = { workspace = true, optional = true, features = ["metal"] }
# Version floor for `metal::Queue::as_raw` (used in wgpu_29_surface/metal.rs),
# which was added in wgpu-hal 29.0.4. Enabled by the `wgpu-29` feature; only
# declared here (Apple) because that is the only target using the API.
wgpu-hal-29 = { workspace = true, optional = true }
wgpu-hal-30 = { workspace = true, optional = true }
read-fonts = { workspace = true }
# Pinned to 0.50 to align with read-fonts from parley and avoid duplicated dependencies
write-fonts = { version = "0.50" }
[target.'cfg(not(any(target_vendor = "apple", target_family = "windows")))'.dependencies]
skia-safe = { version = "0.153.3", features = ["gl", "vulkan"] }
wgpu-29 = { workspace = true, optional = true, features = ["vulkan"] }
wgpu-30 = { workspace = true, optional = true, features = ["vulkan"] }
[target.aarch64-apple-ios-sim.dependencies]
# Disabling encoding assertions until https://github.com/madsmtm/objc2/issues/795 is fixed.
objc2 = { version = "0.6.0", features = ["disable-encoding-assertions"] }
[build-dependencies]
cfg_aliases = { workspace = true }
[package.metadata.docs.rs]
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,7 @@
**NOTE**: This library is an **internal** crate of the [Slint project](https://slint.dev).
This crate should **not be used directly** by applications using Slint.
You should use the `slint` crate instead.
**WARNING**: This crate does not follow the semver convention for versioning and can
only be used with `version = "=x.y.z"` in Cargo.toml.

23
vendor/i-slint-renderer-skia/build.rs vendored Normal file
View File

@ -0,0 +1,23 @@
// 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
use cfg_aliases::cfg_aliases;
fn main() {
// Setup cfg aliases
cfg_aliases! {
skia_backend_opengl: { any(feature = "opengl", not(any(target_vendor = "apple", target_family = "windows", target_arch = "wasm32"))) },
skia_backend_wgpu: { any(feature = "wgpu-29", feature = "wgpu-30") },
skia_backend_software: { not(target_os = "android") },
skia_backend_softbuffer: { all(skia_backend_software, feature = "softbuffer") },
// Targets where wgpu and Skia both have their Vulkan backend compiled in.
// This only happens if wgpu has been enabled, and, on windows an mac only, the "vulkan"
// feature is enabled. On linux and other non-macos unixes, skia_wgpu_vulkan is true by
// default, and enabling "vulkan" feature would only serve to have it prioritized over
// opengl at runtime.
skia_wgpu_vulkan: { all(skia_backend_wgpu, any(all(target_family = "unix", not(target_vendor = "apple")), all(any(target_vendor = "apple", target_family = "windows"), feature = "vulkan"))) },
skia_windowed: { any(skia_backend_wgpu, skia_backend_opengl, skia_backend_softbuffer) },
}
println!("cargo:rustc-check-cfg=cfg(slint_nightly_test)");
}

View File

@ -0,0 +1,156 @@
// 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
use i_slint_core::graphics::{
Image, ImageCacheKey, ImageInner, IntSize, OpaqueImage, OpaqueImageVTable, SharedImageBuffer,
cache as core_cache,
};
use i_slint_core::items::ImageFit;
use i_slint_core::lengths::{LogicalSize, ScaleFactor};
struct SkiaCachedImage {
image: skia_safe::Image,
cache_key: ImageCacheKey,
}
i_slint_core::OpaqueImageVTable_static! {
static SKIA_CACHED_IMAGE_VT for SkiaCachedImage
}
impl OpaqueImage for SkiaCachedImage {
fn size(&self) -> IntSize {
IntSize::new(self.image.width() as u32, self.image.height() as u32)
}
fn cache_key(&self) -> ImageCacheKey {
self.cache_key.clone()
}
}
pub(crate) fn as_skia_image(
image: Image,
target_size_fn: &dyn Fn() -> LogicalSize,
image_fit: ImageFit,
scale_factor: ScaleFactor,
canvas: &skia_safe::Canvas,
surface: Option<&dyn crate::Surface>,
) -> Option<skia_safe::Image> {
let image_inner: &ImageInner = (&image).into();
match image_inner {
ImageInner::None => None,
ImageInner::EmbeddedImage { buffer, cache_key } => {
let result = image_buffer_to_skia_image(buffer);
if let Some(img) = result.as_ref() {
core_cache::replace_cached_image(
cache_key.clone(),
ImageInner::BackendStorage(vtable::VRc::into_dyn(vtable::VRc::new(
SkiaCachedImage { image: img.clone(), cache_key: cache_key.clone() },
))),
)
}
result
}
ImageInner::Svg(svg) => {
// Query target_width/height here again to ensure that changes will invalidate the item rendering cache.
let target_size = i_slint_core::graphics::scalable_render_size(
svg.size(),
image_fit,
target_size_fn() * scale_factor,
scale_factor,
Default::default(),
)?;
let pixels = match svg.render(Some(target_size)).ok()? {
SharedImageBuffer::RGB8(_) => unreachable!(),
SharedImageBuffer::RGBA8(_) => unreachable!(),
SharedImageBuffer::RGBA8Premultiplied(pixels) => pixels,
};
let image_info = crate::image_info(
skia_safe::ISize::new(pixels.width() as i32, pixels.height() as i32),
skia_safe::ColorType::RGBA8888,
skia_safe::AlphaType::Premul,
);
skia_safe::images::raster_from_data(
&image_info,
skia_safe::Data::new_copy(pixels.as_bytes()),
pixels.width() as usize * 4,
)
}
ImageInner::StaticTextures(_) => todo!(),
ImageInner::BackendStorage(x) => {
vtable::VRc::borrow(x).downcast::<SkiaCachedImage>().map(|x| x.image.clone())
}
ImageInner::BorrowedOpenGLTexture(texture) => {
surface.and_then(|surface| surface.import_opengl_texture(canvas, texture))
}
ImageInner::NineSlice(n) => as_skia_image(
n.image(),
target_size_fn,
ImageFit::Preserve,
scale_factor,
canvas,
surface,
),
#[cfg(any(feature = "unstable-wgpu-29", feature = "unstable-wgpu-30"))]
ImageInner::WGPUTexture(any_wgpu_texture) => {
surface.and_then(|surface| surface.import_wgpu_texture(canvas, any_wgpu_texture))
}
#[allow(unreachable_patterns)]
_ => None,
}
}
fn image_buffer_to_skia_image(buffer: &SharedImageBuffer) -> Option<skia_safe::Image> {
// Report fully opaque images as such to Skia. This allows Skia to skip
// reading destination pixels back when blending, which is particularly
// important for the software renderer when it renders directly into
// write-combined (uncached) frame buffer memory, where CPU reads are an
// order of magnitude slower than writes. The scan happens once per image;
// the resulting skia_safe::Image is cached.
fn opaque_or(rgba_bytes: &[u8], alpha_type: skia_safe::AlphaType) -> skia_safe::AlphaType {
if rgba_bytes.as_chunks::<4>().0.iter().all(|px| px[3] == 255) {
skia_safe::AlphaType::Opaque
} else {
alpha_type
}
}
let (data, bpl, size, color_type, alpha_type) = match buffer {
SharedImageBuffer::RGB8(pixels) => {
// RGB888 with one byte per component is not supported by Skia right now. Convert once to RGBA8 :-(
let rgba = pixels
.as_bytes()
.chunks(3)
.flat_map(|rgb| IntoIterator::into_iter([rgb[0], rgb[1], rgb[2], 255]))
.collect::<Vec<u8>>();
(
skia_safe::Data::new_copy(&rgba),
pixels.width() as usize * 4,
pixels.size(),
skia_safe::ColorType::RGBA8888,
skia_safe::AlphaType::Opaque,
)
}
SharedImageBuffer::RGBA8(pixels) => (
skia_safe::Data::new_copy(pixels.as_bytes()),
pixels.width() as usize * 4,
pixels.size(),
skia_safe::ColorType::RGBA8888,
opaque_or(pixels.as_bytes(), skia_safe::AlphaType::Unpremul),
),
SharedImageBuffer::RGBA8Premultiplied(pixels) => (
skia_safe::Data::new_copy(pixels.as_bytes()),
pixels.width() as usize * 4,
pixels.size(),
skia_safe::ColorType::RGBA8888,
opaque_or(pixels.as_bytes(), skia_safe::AlphaType::Premul),
),
};
let image_info = crate::image_info(
skia_safe::ISize::new(size.width as i32, size.height as i32),
color_type,
alpha_type,
);
skia_safe::images::raster_from_data(&image_info, data, bpl)
}

View File

@ -0,0 +1,108 @@
// 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
use clru::CLruCache;
use i_slint_common::sharedfontique::HashedBlob;
use i_slint_core::textlayout::sharedparley::{fontique, parley};
use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;
const FONT_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(64).unwrap();
pub struct FontCache {
font_mgr: skia_safe::FontMgr,
// Use HashedBlob in key to keep strong reference to font data blob,
// preventing eviction from fontique's shared cache (see commit 30a03cf).
// The u64 is a hash of variation settings (0 for base typefaces).
fonts: CLruCache<(HashedBlob, u32, u64), Option<skia_safe::Typeface>>,
}
impl Default for FontCache {
fn default() -> Self {
Self { font_mgr: skia_safe::FontMgr::new(), fonts: CLruCache::new(FONT_CACHE_CAPACITY) }
}
}
impl FontCache {
pub fn font_with_variations(
&mut self,
font: &parley::FontData,
synthesis: &fontique::Synthesis,
) -> Option<skia_safe::Typeface> {
let variation_settings = synthesis.variation_settings();
let mut variations_hash = 0u64;
if !variation_settings.is_empty() {
let mut hasher = DefaultHasher::new();
for &(tag, value) in variation_settings {
tag.to_be_bytes().hash(&mut hasher);
value.to_bits().hash(&mut hasher);
}
variations_hash = hasher.finish();
}
let key = (font.data.clone().into(), font.index, variations_hash);
if let Some(cached) = self.fonts.get(&key) {
return cached.clone();
}
let mut typeface = self.load_typeface_internal(font);
if !variation_settings.is_empty() {
typeface = typeface.and_then(|base| {
let coords: Vec<skia_safe::font_arguments::variation_position::Coordinate> =
variation_settings
.iter()
.map(|&(tag, value)| {
skia_safe::font_arguments::variation_position::Coordinate {
axis: skia_safe::FourByteTag::new(u32::from_be_bytes(
tag.to_be_bytes(),
)),
value,
}
})
.collect();
let position =
skia_safe::font_arguments::VariationPosition { coordinates: &coords };
let args = skia_safe::FontArguments::new().set_variation_design_position(position);
base.clone_with_arguments(&args).or(Some(base))
});
}
self.fonts.put(key, typeface.clone());
typeface
}
fn load_typeface_internal(&self, font: &parley::FontData) -> Option<skia_safe::Typeface> {
let typeface = self.font_mgr.new_from_data(
skia_safe::Data::new_copy(font.data.as_ref()),
if font.index > 0 { Some(font.index as _) } else { None },
);
// Due to https://issues.skia.org/issues/310510989, fonts from true type collections
// with an index > 0 fail to load on macOS. As a workaround, we manually extract the font from the
// collection and load it as a single font.
#[cfg(target_vendor = "apple")]
if font.index > 0
&& typeface.is_none()
&& let Some(typeface) = read_fonts::CollectionRef::new(font.data.as_ref())
.ok()
.and_then(|ttc| ttc.get(font.index).ok())
.map(|ttf| write_fonts::FontBuilder::new().copy_missing_tables(ttf).build())
.and_then(|new_ttf| {
self.font_mgr.new_from_data(skia_safe::Data::new_copy(&new_ttf), None)
})
{
return Some(typeface);
}
typeface
}
}
thread_local! {
pub static FONT_CACHE: RefCell<FontCache> = RefCell::new(Default::default())
}

File diff suppressed because it is too large Load Diff

1149
vendor/i-slint-renderer-skia/lib.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,531 @@
// 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 fboid
use std::num::NonZeroU32;
use std::{cell::RefCell, sync::Arc};
use glutin::{
config::GetGlConfig,
context::{ContextApi, ContextAttributesBuilder},
display::GetGlDisplay,
prelude::*,
surface::{SurfaceAttributesBuilder, WindowSurface},
};
use i_slint_core::api::{GraphicsAPI, PhysicalSize as PhysicalWindowSize, Window};
use i_slint_core::graphics::{BorrowedOpenGLTexture, RequestedGraphicsAPI, RequestedOpenGLVersion};
use i_slint_core::partial_renderer::DirtyRegion;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::DrawOutcome;
use crate::SkiaSharedContext;
/// Wraps a [`glutin::context::PossiblyCurrentContext`] and makes it not-current on drop,
/// so that no stale thread-local state remains after the context is destroyed.
struct GlutinContext(Option<glutin::context::PossiblyCurrentContext>);
impl GlutinContext {
fn new(context: glutin::context::PossiblyCurrentContext) -> Self {
Self(Some(context))
}
}
impl std::ops::Deref for GlutinContext {
type Target = glutin::context::PossiblyCurrentContext;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
impl Drop for GlutinContext {
fn drop(&mut self) {
if let Some(context) = self.0.take()
&& let Err(e) = context.make_not_current()
{
i_slint_core::debug_log!(
"Skia OpenGL Renderer: Failed to make context not current: {e}"
);
}
}
}
/// This surface type renders into the given window with OpenGL, using glutin and glow libraries.
pub struct OpenGLSurface {
fb_info: skia_safe::gpu::gl::FramebufferInfo,
surface: RefCell<skia_safe::Surface>,
gr_context: RefCell<skia_safe::gpu::DirectContext>,
glutin_context: GlutinContext,
glutin_surface: glutin::surface::Surface<glutin::surface::WindowSurface>,
}
impl super::Surface for OpenGLSurface {
fn new(
_shared_context: &SkiaSharedContext,
window_handle: Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
display_handle: Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
size: PhysicalWindowSize,
requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, PlatformError> {
Self::new_with_config(
window_handle,
display_handle,
size,
requested_graphics_api.as_ref().map(TryInto::try_into).transpose()?,
glutin::config::ConfigTemplateBuilder::new(),
None,
)
}
fn name(&self) -> &'static str {
"opengl"
}
fn with_graphics_api(&self, callback: &mut dyn FnMut(GraphicsAPI<'_>)) {
let api = GraphicsAPI::NativeOpenGL {
get_proc_address: &|name| {
self.glutin_context.display().get_proc_address(name) as *const _
},
};
callback(api)
}
fn with_active_surface(&self, callback: &mut dyn FnMut()) -> Result<(), PlatformError> {
self.ensure_context_current()?;
callback();
Ok(())
}
fn render(
&self,
_window: &Window,
size: PhysicalWindowSize,
callback: &dyn Fn(
&skia_safe::Canvas,
Option<&mut skia_safe::gpu::DirectContext>,
u8,
) -> Option<DirtyRegion>,
pre_present_callback: &RefCell<Option<Box<dyn FnMut()>>>,
) -> Result<DrawOutcome, PlatformError> {
self.ensure_context_current()?;
let current_context = &self.glutin_context;
let gr_context = &mut self.gr_context.borrow_mut();
let mut surface = self.surface.borrow_mut();
let width = size.width.try_into().ok();
let height = size.height.try_into().ok();
if let Some((width, height)) = width.zip(height)
&& (width != surface.width() || height != surface.height())
{
*surface = Self::create_internal_surface(
self.fb_info,
current_context,
gr_context,
width,
height,
)?;
}
let skia_canvas = surface.canvas();
skia_canvas.save();
callback(
skia_canvas,
Some(gr_context),
u8::try_from(self.glutin_surface.buffer_age()).unwrap_or_default(),
);
skia_canvas.restore();
if let Some(pre_present_callback) = pre_present_callback.borrow_mut().as_mut() {
pre_present_callback();
}
self.glutin_surface.swap_buffers(current_context).map(|_| DrawOutcome::Success).map_err(
|glutin_error| {
format!("Skia OpenGL Renderer: Error swapping buffers: {glutin_error}").into()
},
)
}
fn resize_event(&self, size: PhysicalWindowSize) -> Result<(), PlatformError> {
self.ensure_context_current()?;
if let Some((width, height)) = size.width.try_into().ok().zip(size.height.try_into().ok()) {
self.glutin_surface.resize(&self.glutin_context, width, height);
}
Ok(())
}
fn bits_per_pixel(&self) -> Result<u8, PlatformError> {
let config = self.glutin_context.config();
let rgb_bits = match config.color_buffer_type() {
Some(glutin::config::ColorBufferType::Rgb { r_size, g_size, b_size }) => {
r_size + g_size + b_size
}
other => {
return Err(format!(
"Skia OpenGL Renderer: unsupported color buffer {other:?} encountered"
)
.into());
}
};
Ok(rgb_bits + config.alpha_size())
}
fn import_opengl_texture(
&self,
canvas: &skia_safe::Canvas,
BorrowedOpenGLTexture { texture_id, size, origin, .. }: &BorrowedOpenGLTexture,
) -> Option<skia_safe::Image> {
unsafe {
let mut texture_info = skia_safe::gpu::gl::TextureInfo::from_target_and_id(
glow::TEXTURE_2D,
texture_id.get(),
);
texture_info.format = glow::RGBA8;
let backend_texture = skia_safe::gpu::backend_textures::make_gl(
(size.width as _, size.height as _),
skia_safe::gpu::Mipmapped::No,
texture_info,
"Borrowed GL texture",
);
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
match origin {
i_slint_core::graphics::BorrowedOpenGLTextureOrigin::TopLeft => {
skia_safe::gpu::SurfaceOrigin::TopLeft
}
i_slint_core::graphics::BorrowedOpenGLTextureOrigin::BottomLeft => {
skia_safe::gpu::SurfaceOrigin::BottomLeft
}
_ => unimplemented!(
"internal error: missing implementation for BorrowedOpenGLTextureOrigin"
),
},
skia_safe::ColorType::RGBA8888,
skia_safe::AlphaType::Unpremul,
crate::sampled_texture_color_space(crate::TextureEncoding::Unorm),
)
}
}
}
impl OpenGLSurface {
pub fn new_with_config(
window_handle: Arc<dyn raw_window_handle::HasWindowHandle>,
display_handle: Arc<dyn raw_window_handle::HasDisplayHandle>,
size: PhysicalWindowSize,
requested_opengl_version: Option<RequestedOpenGLVersion>,
config_builder: glutin::config::ConfigTemplateBuilder,
config_filter: Option<&dyn Fn(&glutin::config::Config) -> bool>,
) -> Result<Self, PlatformError> {
let width: std::num::NonZeroU32 = size.width.try_into().map_err(|_| {
format!("Attempting to create window surface with an invalid width: {}", size.width)
})?;
let height: std::num::NonZeroU32 = size.height.try_into().map_err(|_| {
format!("Attempting to create window surface with an invalid height: {}", size.height)
})?;
let window_handle = window_handle
.window_handle()
.map_err(|e| format!("error obtaining window handle for skia opengl renderer: {e}"))?;
let display_handle = display_handle
.display_handle()
.map_err(|e| format!("error obtaining display handle for skia opengl renderer: {e}"))?;
let (current_glutin_context, glutin_surface) = Self::init_glutin(
window_handle,
display_handle,
width,
height,
requested_opengl_version,
config_builder,
config_filter,
)?;
glutin_surface.resize(&current_glutin_context, width, height);
let fb_info = {
use glow::HasContext;
let gl = unsafe {
glow::Context::from_loader_function_cstr(|name| {
current_glutin_context.display().get_proc_address(name) as *const _
})
};
let fboid = unsafe { gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING) };
skia_safe::gpu::gl::FramebufferInfo {
fboid: fboid.try_into().map_err(|_| {
"Skia Renderer: Internal error, framebuffer binding returned signed id"
.to_string()
})?,
format: skia_safe::gpu::gl::Format::RGBA8.into(),
..Default::default()
}
};
let gl_interface = skia_safe::gpu::gl::Interface::new_load_with_cstr(|name| {
current_glutin_context.display().get_proc_address(name) as *const _
})
.ok_or_else(|| {
"Skia Renderer: Internal Error: Could not create OpenGL Interface".to_string()
})?;
let mut gr_context =
skia_safe::gpu::direct_contexts::make_gl(gl_interface, None).ok_or_else(|| {
"Skia Renderer: Internal Error: Could not create Skia Direct Context from GL interface".to_string()
})?;
let width: i32 = size.width.try_into().map_err(|e| {
format!("Attempting to create window surface with width that doesn't fit into non-zero i32: {e}")
})?;
let height: i32 = size.height.try_into().map_err(|e| {
format!(
"Attempting to create window surface with height that doesn't fit into non-zero i32: {e}"
)
})?;
let surface = Self::create_internal_surface(
fb_info,
&current_glutin_context,
&mut gr_context,
width,
height,
)?
.into();
Ok(Self {
fb_info,
surface,
gr_context: RefCell::new(gr_context),
glutin_context: GlutinContext::new(current_glutin_context),
glutin_surface,
})
}
fn init_glutin(
_window_handle: raw_window_handle::WindowHandle<'_>,
_display_handle: raw_window_handle::DisplayHandle<'_>,
width: NonZeroU32,
height: NonZeroU32,
requested_opengl_version: Option<RequestedOpenGLVersion>,
config_template_builder: glutin::config::ConfigTemplateBuilder,
config_filter: Option<&dyn Fn(&glutin::config::Config) -> bool>,
) -> Result<
(
glutin::context::PossiblyCurrentContext,
glutin::surface::Surface<glutin::surface::WindowSurface>,
),
PlatformError,
> {
cfg_if::cfg_if! {
if #[cfg(target_os = "macos")] {
let display_api_preference = glutin::display::DisplayApiPreference::Cgl;
} else if #[cfg(not(target_family = "windows"))] {
let display_api_preference = glutin::display::DisplayApiPreference::Egl;
} else {
let display_api_preference = glutin::display::DisplayApiPreference::EglThenWgl(Some(_window_handle.as_raw()));
}
}
let gl_display = unsafe {
glutin::display::Display::new(_display_handle.as_raw(), display_api_preference)
.map_err(|glutin_error| {
format!(
"Error creating glutin display for native display {:?}: {}",
_display_handle.as_raw(),
glutin_error
)
})?
};
// On macOS, there's only one GL config and that's initialized based on the values in the config template
// builder. So if that one has transparency enabled, it'll show up in the config, and will be set on the
// context later. So we must enable it here, there's no way of enabling it later.
// On EGL/GLX/WGL there are system provided configs that may or may not support transparency. Here in case
// the system doesn't support transparency, we want to fall back to a config that doesn't - better than not
// rendering anything at all. So we don't want to limit the configurations we get to see early on.
// Commented out due to https://github.com/rust-windowing/glutin/issues/1640
#[cfg(target_os = "macos")]
let config_template_builder = config_template_builder.with_transparency(true);
// Upstream advises to use this only on Windows.
#[cfg(target_family = "windows")]
let config_template_builder =
config_template_builder.compatible_with_native_window(_window_handle.as_raw());
let config_template = config_template_builder.build();
let config = unsafe {
gl_display
.find_configs(config_template)
.map_err(|e| format!("Could not find valid OpenGL display configurations: {e}"))?
.filter(|config| config_filter.as_ref().is_none_or(|filter_fn| filter_fn(config)))
.reduce(|accum, config| {
let transparency_check = config.supports_transparency().unwrap_or(false)
& !accum.supports_transparency().unwrap_or(false);
if transparency_check || config.num_samples() < accum.num_samples() {
config
} else {
accum
}
})
.ok_or("Unable to find suitable GL config")?
};
let requested_opengl_version =
requested_opengl_version.unwrap_or(RequestedOpenGLVersion::OpenGLES(Some((3, 0))));
let preferred_context_attributes = match requested_opengl_version {
RequestedOpenGLVersion::OpenGL(version) => {
let version =
version.map(|(major, minor)| glutin::context::Version { major, minor });
ContextAttributesBuilder::new()
.with_context_api(ContextApi::OpenGl(version))
.build(Some(_window_handle.as_raw()))
}
RequestedOpenGLVersion::OpenGLES(version) => {
let version =
version.map(|(major, minor)| glutin::context::Version { major, minor });
ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(version))
.build(Some(_window_handle.as_raw()))
}
};
let gles2_fallback_context_attributes = ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(Some(glutin::context::Version {
major: 2,
minor: 0,
})))
.build(Some(_window_handle.as_raw()));
let fallback_context_attributes =
ContextAttributesBuilder::new().build(Some(_window_handle.as_raw()));
let not_current_gl_context = unsafe {
gl_display
.create_context(&config, &preferred_context_attributes)
.or_else(|_| gl_display.create_context(&config, &gles2_fallback_context_attributes))
.or_else(|_| gl_display.create_context(&config, &fallback_context_attributes))
.map_err(|e| format!("Error creating OpenGL context: {e}"))
}?;
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
_window_handle.as_raw(),
width,
height,
);
let surface = unsafe {
config
.display()
.create_window_surface(&config, &attrs)
.map_err(|e| format!("Error creating OpenGL window surface: {e}"))?
};
let context = not_current_gl_context.make_current(&surface)
.map_err(|glutin_error: glutin::error::Error| -> PlatformError {
format!("Skia Renderer: Failed to make newly created OpenGL context current: {glutin_error}")
.into()
})?;
// Align the GL layer to the top-left, so that resizing only invalidates the bottom/right
// part of the window.
#[cfg(target_os = "macos")]
if let raw_window_handle::RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle {
ns_view,
..
}) = _window_handle.as_raw()
{
let ns_view: &objc2_app_kit::NSView = unsafe { ns_view.cast().as_ref() };
ns_view.setLayerContentsPlacement(objc2_app_kit::NSViewLayerContentsPlacement::TopLeft);
}
// Sanity check, as all this might succeed on Windows without working GL drivers, but this will fail:
if context
.display()
.get_proc_address(&std::ffi::CString::new("glCreateShader").unwrap())
.is_null()
{
return Err(
"Failed to initialize OpenGL driver: Could not locate glCreateShader symbol"
.to_string()
.into(),
);
}
// Try to default to vsync and ignore if the driver doesn't support it.
surface
.set_swap_interval(
&context,
glutin::surface::SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
)
.ok();
Ok((context, surface))
}
fn create_internal_surface(
fb_info: skia_safe::gpu::gl::FramebufferInfo,
gl_context: &glutin::context::PossiblyCurrentContext,
gr_context: &mut skia_safe::gpu::DirectContext,
width: i32,
height: i32,
) -> Result<skia_safe::Surface, PlatformError> {
let config = gl_context.config();
let backend_render_target = skia_safe::gpu::backend_render_targets::make_gl(
(width, height),
Some(config.num_samples() as _),
config.stencil_size() as _,
fb_info,
);
match skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::BottomLeft,
skia_safe::ColorType::RGBA8888,
crate::attachment_color_space(crate::TextureEncoding::Unorm),
None,
) {
Some(surface) => Ok(surface),
None => {
Err("Skia OpenGL Renderer: Failed to allocate internal backend rendering target"
.into())
}
}
}
fn ensure_context_current(&self) -> Result<(), PlatformError> {
if !self.glutin_context.is_current() {
self.glutin_context.make_current(&self.glutin_surface).map_err(
|glutin_error| -> PlatformError {
format!("Skia Renderer: Error making context current: {glutin_error}").into()
},
)?;
}
Ok(())
}
}
impl Drop for OpenGLSurface {
fn drop(&mut self) {
// Make sure that the context is current before Skia calls glDelete***
// In the event that this fails for some reason (lost GL context), convey that to Skia so that it doesn't try to call
// glDelete***
if self.ensure_context_current().is_err() {
i_slint_core::debug_log!(
"Skia OpenGL Renderer warning: Failed to make context current for destruction - considering context abandoned."
);
self.gr_context.borrow_mut().abandon();
}
}
}

View File

@ -0,0 +1,258 @@
// 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
use i_slint_core::api::{PhysicalSize as PhysicalWindowSize, Window};
use i_slint_core::graphics::RequestedGraphicsAPI;
use i_slint_core::partial_renderer::DirtyRegion;
use i_slint_core::renderer::DrawOutcome;
use std::cell::RefCell;
use std::num::NonZeroU32;
use std::rc::Rc;
use std::sync::Arc;
use crate::SkiaSharedContext;
pub trait RenderBuffer {
fn with_buffer(
&self,
window: &Window,
size: PhysicalWindowSize,
render_callback: &mut dyn FnMut(
NonZeroU32,
NonZeroU32,
skia_safe::ColorType,
u8,
&mut [u8],
) -> Result<
Option<DirtyRegion>,
i_slint_core::platform::PlatformError,
>,
) -> Result<(), i_slint_core::platform::PlatformError>;
}
#[cfg(feature = "softbuffer")]
struct SoftbufferRenderBuffer {
_context: softbuffer::Context<Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>>,
surface: RefCell<
softbuffer::Surface<
Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
>,
>,
}
#[cfg(feature = "softbuffer")]
impl RenderBuffer for SoftbufferRenderBuffer {
fn with_buffer(
&self,
window: &Window,
size: PhysicalWindowSize,
render_callback: &mut dyn FnMut(
NonZeroU32,
NonZeroU32,
skia_safe::ColorType,
u8,
&mut [u8],
) -> Result<
Option<DirtyRegion>,
i_slint_core::platform::PlatformError,
>,
) -> Result<(), i_slint_core::platform::PlatformError> {
let Some((width, height)) = size.width.try_into().ok().zip(size.height.try_into().ok())
else {
// Nothing to render
return Ok(());
};
let mut surface = self.surface.borrow_mut();
surface
.resize(width, height)
.map_err(|e| format!("Error resizing softbuffer surface: {e}"))?;
let mut target_buffer = surface
.buffer_mut()
.map_err(|e| format!("Error retrieving softbuffer rendering buffer: {e}"))?;
let dirty_region = render_callback(
width,
height,
skia_safe::ColorType::BGRA8888,
target_buffer.age(),
bytemuck::cast_slice_mut(target_buffer.as_mut()),
)?;
if let Some(dirty_region) = dirty_region {
let scale_factor = i_slint_core::lengths::ScaleFactor::new(window.scale_factor());
let damage_rects = dirty_region
.iter()
.map(|logical| {
let physical_rect = (logical.to_rect() * scale_factor).round_out();
softbuffer::Rect {
x: physical_rect.min_x().ceil() as _,
y: physical_rect.min_y().ceil() as _,
width: ((physical_rect.width() as i32).max(1) as u32).try_into().unwrap(),
height: ((physical_rect.height() as i32).max(1) as u32).try_into().unwrap(),
}
})
.collect::<Vec<_>>();
target_buffer.present_with_damage(&damage_rects)
} else {
target_buffer.present()
}
.map_err(|e| format!("Error presenting softbuffer buffer after skia rendering: {e}"))?;
Ok(())
}
}
/// This surface renders into the given window using Skia's software rasterize.
pub struct SoftwareSurface {
render_buffer: Box<dyn RenderBuffer>,
}
impl super::Surface for SoftwareSurface {
#[cfg(feature = "softbuffer")]
fn new(
_shared_context: &SkiaSharedContext,
window_handle: Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
display_handle: Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
_size: PhysicalWindowSize,
_requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, i_slint_core::platform::PlatformError> {
let _context = softbuffer::Context::new(display_handle)
.map_err(|e| format!("Error creating softbuffer context: {e}"))?;
let surface =
softbuffer::Surface::new(&_context, window_handle).map_err(|softbuffer_error| {
format!("Error creating softbuffer surface: {softbuffer_error}")
})?;
let surface_access =
Box::new(SoftbufferRenderBuffer { _context, surface: RefCell::new(surface) });
Ok(Self { render_buffer: surface_access })
}
#[cfg(not(feature = "softbuffer"))]
fn new(
_shared_context: &SkiaSharedContext,
_window_handle: Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
_display_handle: Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
_size: PhysicalWindowSize,
_requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, i_slint_core::platform::PlatformError> {
struct DummyBuffer;
impl RenderBuffer for DummyBuffer {
fn with_buffer(
&self,
_window: &Window,
_size: PhysicalWindowSize,
_render_callback: &mut dyn FnMut(
std::num::NonZeroU32,
std::num::NonZeroU32,
skia_safe::ColorType,
u8,
&mut [u8],
) -> Result<
Option<DirtyRegion>,
i_slint_core::platform::PlatformError,
>,
) -> Result<(), i_slint_core::platform::PlatformError> {
Err("Slint's Skia renderer compiled without the 'softbuffer' feature cannot render into a window".into())
}
}
Ok(DummyBuffer.into())
}
fn name(&self) -> &'static str {
"software"
}
fn resize_event(
&self,
_size: PhysicalWindowSize,
) -> Result<(), i_slint_core::platform::PlatformError> {
Ok(())
}
fn render(
&self,
window: &Window,
size: PhysicalWindowSize,
callback: &dyn Fn(
&skia_safe::Canvas,
Option<&mut skia_safe::gpu::DirectContext>,
u8,
) -> Option<DirtyRegion>,
pre_present_callback: &RefCell<Option<Box<dyn FnMut()>>>,
) -> Result<DrawOutcome, i_slint_core::platform::PlatformError> {
self.render_buffer.with_buffer(
window,
size,
&mut |width, height, pixel_format, age, pixels| {
let image_info = crate::image_info(
(width.get() as i32, height.get() as i32),
pixel_format,
skia_safe::AlphaType::Opaque,
);
// A scanout buffer may carry padding at the end of each row:
// DRM dumb buffers have their pitch aligned by the driver, so a
// 1366 px wide XRGB8888 row occupies 5504 bytes, not 5464.
// Take the row length from the buffer, as the display does.
let row_bytes = pixels.len() / height.get() as usize;
let row_bytes = (row_bytes >= image_info.min_row_bytes()).then_some(row_bytes);
let mut surface_borrow =
skia_safe::surfaces::wrap_pixels(&image_info, pixels, row_bytes, None)
.ok_or_else(|| {
"Error wrapping target buffer for rendering into with Skia".to_string()
})?;
let dirty_region = callback(surface_borrow.canvas(), None, age);
if let Some(pre_present_callback) = pre_present_callback.borrow_mut().as_mut() {
pre_present_callback();
}
Ok(dirty_region)
},
)?;
Ok(DrawOutcome::Success)
}
fn bits_per_pixel(&self) -> Result<u8, i_slint_core::platform::PlatformError> {
Ok(24)
}
fn use_partial_rendering(&self) -> bool {
true
}
}
impl<T: RenderBuffer + 'static> From<T> for SoftwareSurface {
fn from(render_buffer: T) -> Self {
Self { render_buffer: Box::new(render_buffer) }
}
}
impl<T: RenderBuffer + 'static> RenderBuffer for Rc<T> {
fn with_buffer(
&self,
window: &Window,
size: PhysicalWindowSize,
render_callback: &mut dyn FnMut(
NonZeroU32,
NonZeroU32,
skia_safe::ColorType,
u8,
&mut [u8],
) -> Result<
Option<DirtyRegion>,
i_slint_core::platform::PlatformError,
>,
) -> Result<(), i_slint_core::platform::PlatformError> {
self.as_ref().with_buffer(window, size, render_callback)
}
}

View File

@ -0,0 +1,30 @@
// 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 dispatchable
//! Raw values of the Vulkan handles wgpu-hal hands out.
//!
//! wgpu-hal exposes its Vulkan objects as `ash::vk` handle types without re-exporting `ash`,
//! and Skia's `vk` API takes the raw values.
//! Every `ash::vk` handle is a `#[repr(transparent)]` wrapper mirroring the C type:
//! a pointer for dispatchable handles (`VkInstance`, `VkQueue`, ...)
//! and a `u64` for non-dispatchable ones (`VkImage`, ...).
//! Reading the wrapper is what `ash::vk::Handle::as_raw` does, minus the dependency.
/// Returns the raw value of a dispatchable handle.
///
/// # Safety
/// `handle` must be one of `ash::vk`'s dispatchable handle types.
pub unsafe fn dispatchable<H: Copy>(handle: H) -> u64 {
const { assert!(size_of::<H>() == size_of::<*mut u8>()) };
unsafe { core::mem::transmute_copy::<H, *mut u8>(&handle) as u64 }
}
/// Returns the raw value of a non-dispatchable handle.
///
/// # Safety
/// `handle` must be one of `ash::vk`'s non-dispatchable handle types.
pub unsafe fn non_dispatchable<H: Copy>(handle: H) -> u64 {
const { assert!(size_of::<H>() == size_of::<u64>()) };
unsafe { core::mem::transmute_copy::<H, u64>(&handle) }
}

View File

@ -0,0 +1,661 @@
// 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
#[cfg(feature = "unstable-wgpu-29")]
use i_slint_core::api::GraphicsAPI;
use i_slint_core::api::{PhysicalSize as PhysicalWindowSize, Window};
use i_slint_core::graphics::RequestedGraphicsAPI;
use i_slint_core::partial_renderer::DirtyRegion;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::DrawOutcome;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use wgpu_29 as wgpu;
use crate::SkiaSharedContext;
#[cfg(target_family = "windows")]
mod dx12;
#[cfg(target_vendor = "apple")]
mod metal;
#[cfg(skia_wgpu_vulkan)]
mod vulkan;
/// See [`crate::attachment_color_space`].
pub(crate) fn attachment_color_space(texture: &wgpu::Texture) -> skia_safe::ColorSpace {
crate::attachment_color_space(crate::TextureEncoding::from_format_is_srgb(
texture.format().is_srgb(),
))
}
/// See [`crate::sampled_texture_color_space`].
#[cfg_attr(not(feature = "unstable-wgpu-29"), allow(dead_code))]
pub(crate) fn sampled_texture_color_space(texture: &wgpu::Texture) -> skia_safe::ColorSpace {
crate::sampled_texture_color_space(crate::TextureEncoding::from_format_is_srgb(
texture.format().is_srgb(),
))
}
/// Skia rendering surface backed by WGPU. Supports both on-screen rendering (with a
/// window surface) and offscreen rendering into caller-provided textures.
pub struct WGPUSurface {
pub(crate) gr_context: RefCell<skia_safe::gpu::DirectContext>,
wgpu: Rc<SharedWgpuState>,
surface_config: RefCell<Option<wgpu::SurfaceConfiguration>>,
surface: Option<wgpu::Surface<'static>>,
textures_to_transition_for_sampling: RefCell<Vec<wgpu::Texture>>,
pub(crate) backend: Backend,
alpha_modes: Vec<wgpu::CompositeAlphaMode>,
}
impl WGPUSurface {
pub fn new_with_surface(
surface_target: impl Into<i_slint_core::graphics::wgpu_29::SurfaceTarget>,
size: PhysicalWindowSize,
requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, PlatformError> {
let (instance, adapter, device, queue, surface) =
i_slint_core::graphics::wgpu_29::init_instance_adapter_device_queue_surface(
surface_target,
requested_graphics_api,
i_slint_core::graphics::wgpu_29::default_backends_to_avoid(),
)?;
Self::init_with_parts(
Rc::new(SharedWgpuState { instance, adapter, device, queue }),
surface,
size,
)
}
fn init_with_parts(
wgpu: Rc<SharedWgpuState>,
surface: wgpu::Surface<'static>,
size: PhysicalWindowSize,
) -> Result<Self, PlatformError> {
let SharedWgpuState { adapter, device, queue, .. } = &*wgpu;
#[cfg(target_vendor = "apple")]
metal::set_layer_contents_gravity(&surface);
// On iOS a window has no size until UIKit attaches it to a scene,
// and wgpu rejects a zero-sized configure.
// Start at 1x1; `resize_event` applies the real size.
let mut surface_config = surface
.get_default_config(adapter, size.width.max(1), size.height.max(1))
.ok_or_else(|| PlatformError::from("WGPU surface is not compatible with adapter"))?;
let swapchain_capabilities = surface.get_capabilities(adapter);
let swapchain_format = swapchain_capabilities
.formats
.iter()
.find(|f| {
matches!(f, wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm)
})
.copied()
.unwrap_or_else(|| swapchain_capabilities.formats[0]);
surface_config.format = swapchain_format;
// Prefer FIFO modes over the Mailbox that `get_default_config` picks on some backends
// (it takes the first advertised mode, and DX12 lists Mailbox first), for frame pacing
// and better energy efficiency. `AutoVsync` falls back to FifoRelaxed and then Fifo, so
// it is supported everywhere.
surface_config.present_mode = wgpu::PresentMode::AutoVsync;
let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
surface.configure(device, &surface_config);
if let Some(e) = spin_on::spin_on(error_scope.pop()) {
return Err(PlatformError::from(format!("Error configuring WGPU surface: {e}")));
}
let backend = Backend::new(adapter, device)?;
let gr_context = backend
.make_context(adapter, device, queue)
.ok_or_else(|| PlatformError::from("Failed to create Skia context from WGPU"))?;
Ok(Self {
gr_context: gr_context.into(),
wgpu,
surface_config: Some(surface_config).into(),
surface: Some(surface),
textures_to_transition_for_sampling: RefCell::new(Vec::new()),
backend,
alpha_modes: swapchain_capabilities.alpha_modes,
})
}
pub(crate) fn new_offscreen(
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
backend: Backend,
gr_context: skia_safe::gpu::DirectContext,
) -> Self {
Self {
gr_context: RefCell::new(gr_context),
wgpu: Rc::new(SharedWgpuState { instance, adapter, device, queue }),
surface_config: None.into(),
surface: None,
textures_to_transition_for_sampling: RefCell::new(Vec::new()),
backend,
alpha_modes: vec![],
}
}
/// Transitions any imported wgpu textures to sampling state and flushes
/// the Skia graphics context. Must be called after rendering to ensure
/// Skia's GPU work is submitted.
pub(crate) fn flush_and_submit(&self, gr_context: &mut skia_safe::gpu::DirectContext) {
let textures_to_transition = self.textures_to_transition_for_sampling.take();
if !textures_to_transition.is_empty() {
let mut encoder =
self.wgpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Skia texture transition encoder"),
});
encoder.transition_resources(
std::iter::empty(),
textures_to_transition.iter().map(|texture| wgpu::TextureTransition {
texture,
selector: None,
state: wgpu::TextureUses::RESOURCE,
}),
);
self.wgpu.queue.submit(Some(encoder.finish()));
}
gr_context.submit(None);
}
}
/// The wgpu stack a surface renders with.
///
/// [`SkiaSharedContext`] caches the one the first window created, so that later windows it can
/// serve reuse it instead of creating their own.
/// That cache holds a weak reference and every surface a strong one, so the resources go away
/// with the last surface using them.
/// Were they to outlive the surfaces, they'd be destroyed whenever the last renderer happens to
/// be dropped, and tearing a wgpu device down from a thread-local destructor aborts the process
/// on macOS, where the Metal backend needs an autorelease pool that is gone by then.
/// A window that is still shown owns its surface, so that case remains.
pub(crate) struct SharedWgpuState {
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
}
/// Whether `device` offers everything `settings` asks of it.
///
/// The instance and adapter parts of the settings are covered by
/// [`adapter_matches_graphics_api_request`].
#[cfg(feature = "unstable-wgpu-29")]
fn device_satisfies_settings(
device: &wgpu::Device,
settings: &i_slint_core::graphics::wgpu_29::api::WGPUSettings,
) -> bool {
device.features().contains(settings.device_required_features)
&& settings.device_required_limits.check_limits(&device.limits())
}
fn adapter_matches_graphics_api_request(
adapter: &wgpu::Adapter,
requested_graphics_api: Option<&RequestedGraphicsAPI>,
) -> bool {
let backend = adapter.get_info().backend;
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
match requested_graphics_api {
None => true,
Some(RequestedGraphicsAPI::Metal) => backend == wgpu::Backend::Metal,
Some(RequestedGraphicsAPI::Vulkan) => backend == wgpu::Backend::Vulkan,
Some(RequestedGraphicsAPI::Direct3D) => backend == wgpu::Backend::Dx12,
#[cfg(feature = "unstable-wgpu-29")]
Some(RequestedGraphicsAPI::WGPU29(
i_slint_core::graphics::wgpu_29::api::WGPUConfiguration::Automatic(settings),
)) => {
let backend_bit = match backend {
wgpu::Backend::Vulkan => wgpu::Backends::VULKAN,
wgpu::Backend::Metal => wgpu::Backends::METAL,
wgpu::Backend::Dx12 => wgpu::Backends::DX12,
wgpu::Backend::Gl => wgpu::Backends::GL,
wgpu::Backend::BrowserWebGpu => wgpu::Backends::BROWSER_WEBGPU,
_ => return false,
};
settings.backends.contains(backend_bit)
}
Some(_) => false,
}
}
impl crate::Surface for WGPUSurface {
fn new(
shared_context: &SkiaSharedContext,
window_handle: Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
display_handle: Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
size: PhysicalWindowSize,
requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, PlatformError> {
let make_target = || -> Box<dyn wgpu::DisplayAndWindowHandle + 'static> {
Box::new(WindowAndDisplayHandle(window_handle.clone(), display_handle.clone()))
};
#[cfg(feature = "unstable-wgpu-29")]
let manual_configuration = matches!(
&requested_graphics_api,
Some(RequestedGraphicsAPI::WGPU29(
i_slint_core::graphics::wgpu_29::api::WGPUConfiguration::Manual { .. }
))
);
#[cfg(not(feature = "unstable-wgpu-29"))]
let manual_configuration = false;
#[cfg(feature = "unstable-wgpu-29")]
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
let requested_settings = match &requested_graphics_api {
Some(RequestedGraphicsAPI::WGPU29(
i_slint_core::graphics::wgpu_29::api::WGPUConfiguration::Automatic(settings),
)) => Some(settings.clone()),
_ => None,
};
// try to reuse old / shared graphics primitives from previous windows with matching
// settings
if !manual_configuration {
let shared_state = shared_context.0.wgpu_29_state.borrow().upgrade();
if let Some(shared) = shared_state {
#[cfg(feature = "unstable-wgpu-29")]
let settings_compatible = requested_settings
.as_ref()
.is_none_or(|settings| device_satisfies_settings(&shared.device, settings));
#[cfg(not(feature = "unstable-wgpu-29"))]
let settings_compatible = true;
if settings_compatible
&& adapter_matches_graphics_api_request(
&shared.adapter,
requested_graphics_api.as_ref(),
)
&& let Ok(surface) = shared.instance.create_surface(make_target())
&& shared.adapter.is_surface_supported(&surface)
{
match Self::init_with_parts(shared, surface, size) {
Ok(surface) => return Ok(surface),
Err(err) => {
// The shared device may be lost. Drop it and start over.
i_slint_core::debug_log!(
"Failed to reuse the shared WGPU device: {err} . Re-initializing"
);
shared_context.0.wgpu_29_state.take();
}
}
}
}
}
let (instance, adapter, device, queue, surface) =
i_slint_core::graphics::wgpu_29::init_instance_adapter_device_queue_surface(
make_target(),
requested_graphics_api,
i_slint_core::graphics::wgpu_29::default_backends_to_avoid(),
)?;
let wgpu = Rc::new(SharedWgpuState { instance, adapter, device, queue });
let new_surface = Self::init_with_parts(wgpu.clone(), surface, size)?;
if !manual_configuration {
*shared_context.0.wgpu_29_state.borrow_mut() = Rc::downgrade(&wgpu);
}
Ok(new_surface)
}
fn name(&self) -> &'static str {
if self.surface.is_some() { "wgpu" } else { "wgpu-texture" }
}
fn resize_event(&self, size: PhysicalWindowSize) -> Result<(), PlatformError> {
let mut surface_config_opt = self.surface_config.borrow_mut();
let (Some(surface_config), Some(surface)) = (surface_config_opt.as_mut(), &self.surface)
else {
return Ok(());
};
// Skip reconfigure if size hasn't changed — DRM/KMS surfaces don't
// support being reconfigured.
if surface_config.width == size.width && surface_config.height == size.height {
return Ok(());
}
{
let gr_context = &mut self.gr_context.borrow_mut();
// This is brute force, but for the lack of access to the fences this seems to work: Avoid any pending work so that
// IDXGISwapChain::ResizeBuffers doesn't complain that the surface is still in use.
gr_context.flush_submit_and_sync_cpu();
}
surface_config.width = size.width;
surface_config.height = size.height;
surface.configure(&self.wgpu.device, surface_config);
Ok(())
}
fn render(
&self,
_window: &Window,
_size: PhysicalWindowSize,
callback: &dyn Fn(
&skia_safe::Canvas,
Option<&mut skia_safe::gpu::DirectContext>,
u8,
) -> Option<DirtyRegion>,
pre_present_callback: &RefCell<Option<Box<dyn FnMut()>>>,
) -> Result<DrawOutcome, PlatformError> {
let (Some(surface), Some(surface_config)) = (&self.surface, &*self.surface_config.borrow())
else {
return Err("WGPUSurface::render() called on offscreen surface".into());
};
let gr_context = &mut self.gr_context.borrow_mut();
let frame = match surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => t,
wgpu::CurrentSurfaceTexture::Occluded => return Ok(DrawOutcome::Occluded),
wgpu::CurrentSurfaceTexture::Timeout => return Ok(DrawOutcome::Timeout),
wgpu::CurrentSurfaceTexture::Validation => {
return Err("WGPU surface validation error in get_current_texture".into());
}
stale @ (wgpu::CurrentSurfaceTexture::Outdated
| wgpu::CurrentSurfaceTexture::Suboptimal(_)
| wgpu::CurrentSurfaceTexture::Lost) => {
// `Suboptimal` carries a live `SurfaceTexture`; matched with `_` it is not bound,
// so the value returned by `get_current_texture()` keeps it alive across the
// `surface.configure()` below — which wgpu forbids ("`SurfaceOutput` must be
// dropped before a new `Surface` is made"), panicking on the first frame on
// Wayland. Drop it first. (`Outdated`/`Lost` carry nothing → no-op.)
drop(stale);
surface.configure(&self.wgpu.device, surface_config);
match surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => t,
_ => return Ok(DrawOutcome::Occluded),
}
}
};
let skia_surface = self.backend.make_swapchain_surface(gr_context, &frame.texture);
let mut skia_surface = skia_surface
.ok_or_else(|| PlatformError::from("Failed to create Skia surface from WGPU"))?;
callback(skia_surface.canvas(), Some(gr_context), 0);
self.backend.release_swapchain_surface(gr_context, &mut skia_surface);
self.flush_and_submit(gr_context);
// Skia drew via the raw queue behind wgpu's back; referencing the frame texture in a submission makes the present semaphore wait for that work.
let mut encoder =
self.wgpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Skia present ordering encoder"),
});
encoder.transition_resources(
std::iter::empty(),
std::iter::once(wgpu::TextureTransition {
texture: &frame.texture,
selector: None,
state: wgpu::TextureUses::PRESENT,
}),
);
self.wgpu.queue.submit(Some(encoder.finish()));
if let Some(pre_present_callback) = pre_present_callback.borrow_mut().as_mut() {
pre_present_callback();
}
frame.present();
Ok(DrawOutcome::Success)
}
fn bits_per_pixel(&self) -> Result<u8, PlatformError> {
if let Some(surface_config) = &*self.surface_config.borrow() {
Ok(match surface_config.format {
wgpu_29::TextureFormat::Rgba8Unorm
| wgpu_29::TextureFormat::Rgba8UnormSrgb
| wgpu_29::TextureFormat::Bgra8Unorm
| wgpu_29::TextureFormat::Bgra8UnormSrgb => 32,
fmt => return Err(format!("Unsupported surface format {:#?}", fmt).into()),
})
} else {
// All supported render-target formats (Rgba8Unorm, Bgra8Unorm, and sRGB variants) are 32bpp.
Ok(32)
}
}
#[cfg(feature = "unstable-wgpu-29")]
fn with_graphics_api(&self, callback: &mut dyn FnMut(GraphicsAPI<'_>)) {
let api = i_slint_core::graphics::create_graphics_api_wgpu_29(
self.wgpu.instance.clone(),
self.wgpu.device.clone(),
self.wgpu.queue.clone(),
);
callback(api)
}
#[cfg(any(feature = "unstable-wgpu-29", feature = "unstable-wgpu-30"))]
fn import_wgpu_texture(
&self,
canvas: &skia_safe::Canvas,
any_wgpu_texture: &i_slint_core::graphics::WGPUTexture,
) -> Option<skia_safe::Image> {
let texture: wgpu_29::Texture = match any_wgpu_texture {
#[cfg(feature = "unstable-wgpu-29")]
i_slint_core::graphics::WGPUTexture::WGPU29Texture(texture) => texture.clone(),
#[cfg(feature = "unstable-wgpu-30")]
i_slint_core::graphics::WGPUTexture::WGPU30Texture(..) => return None,
};
// Skia won't submit commands right away, so remember the texture and transition before
// submitting.
self.textures_to_transition_for_sampling.borrow_mut().push(texture.clone());
self.backend.import_texture(canvas, texture)
}
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
// `Opaque` discards the scene's alpha; pick a translucent mode if offered.
// Metal (CAMetalLayer) only offers `PostMultiplied`, so it must be a fallback.
use wgpu::CompositeAlphaMode::{Opaque, PostMultiplied, PreMultiplied};
let wanted: &[wgpu::CompositeAlphaMode] =
if transparent { &[PreMultiplied, PostMultiplied] } else { &[Opaque] };
let Some(mode) = wanted.iter().copied().find(|m| self.alpha_modes.contains(m)) else {
return Ok(());
};
let mut surface_config_opt = self.surface_config.borrow_mut();
let (Some(surface_config), Some(surface)) = (surface_config_opt.as_mut(), &self.surface)
else {
return Ok(());
};
if surface_config.alpha_mode != mode {
surface_config.alpha_mode = mode;
surface.configure(&self.wgpu.device, surface_config);
}
Ok(())
}
fn as_any(&self) -> &dyn core::any::Any {
self
}
}
struct WindowAndDisplayHandle(
Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
);
impl raw_window_handle::HasWindowHandle for WindowAndDisplayHandle {
fn window_handle(
&self,
) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
self.0.window_handle()
}
}
impl raw_window_handle::HasDisplayHandle for WindowAndDisplayHandle {
fn display_handle(
&self,
) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
self.1.display_handle()
}
}
pub(crate) enum Backend {
#[cfg(target_vendor = "apple")]
Metal,
#[cfg(target_family = "windows")]
Dx12,
#[cfg(skia_wgpu_vulkan)]
Vulkan {
/// The family Skia has to hand the swapchain image back to, see
/// [`Backend::release_swapchain_surface`].
queue_family_index: u32,
},
}
impl Backend {
pub(crate) fn new(
adapter: &wgpu::Adapter,
_device: &wgpu::Device,
) -> Result<Self, PlatformError> {
match adapter.get_info().backend {
wgpu_29::Backend::Noop => {
Err(PlatformError::from("Cannot use WGPU Noop backend with Skia"))
}
#[cfg(skia_wgpu_vulkan)]
wgpu_29::Backend::Vulkan => Ok(Self::Vulkan {
// SAFETY: `_device` is a Vulkan device, as the adapter's backend just said.
queue_family_index: unsafe { vulkan::queue_family_index(_device) }.ok_or_else(
|| {
PlatformError::from(
"Cannot query the queue family of the WGPU Vulkan device",
)
},
)?,
}),
#[cfg(target_vendor = "apple")]
wgpu_29::Backend::Metal => Ok(Self::Metal),
#[cfg(target_family = "windows")]
wgpu_29::Backend::Dx12 => Ok(Self::Dx12),
other => Err(PlatformError::from(format!(
"Unsupported WGPU backend for use with Skia: {}",
other
))),
}
}
pub(crate) fn make_context(
&self,
_adapter: &wgpu::Adapter,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => metal::make_metal_context(device, queue),
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_context(&_adapter, &device, &queue) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe { vulkan::make_vulkan_context(device, queue) },
}
}
pub(crate) fn make_surface(
&self,
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::make_metal_surface(gr_context, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_surface(gr_context, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe {
vulkan::make_vulkan_surface(
gr_context,
texture,
skia_safe::gpu::vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
)
},
}
}
/// Like [`Self::make_surface`], but for the swapchain image handed out by
/// [`wgpu::Surface::get_current_texture`].
///
/// Nothing on this path writes the image before Skia does, so a freshly created swapchain
/// hands out images that are still in `UNDEFINED`, and naming the `PRESENT` layout wgpu
/// leaves them in from the second frame on would make Skia's barrier claim a layout the
/// image isn't in yet. `UNDEFINED` is accurate for the first use and legal for every later
/// one, at the price of discarding the previous contents, which this path never reads:
/// `render()` passes a buffer age of 0, so the scene is repainted in full every frame.
/// Pair every call with [`Self::release_swapchain_surface`].
pub(crate) fn make_swapchain_surface(
&self,
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::make_metal_surface(gr_context, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_surface(gr_context, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe {
vulkan::make_vulkan_surface(
gr_context,
texture,
skia_safe::gpu::vk::ImageLayout::UNDEFINED,
)
},
}
}
/// Hands a surface made by [`Self::make_swapchain_surface`] back in the state
/// [`wgpu::SurfaceTexture::present`] expects to find it in.
pub(crate) fn release_swapchain_surface(
&self,
_gr_context: &mut skia_safe::gpu::DirectContext,
_skia_surface: &mut skia_safe::Surface,
) {
match self {
// Metal and D3D12 have no image layout for Skia to hand back.
#[cfg(target_vendor = "apple")]
Self::Metal => {}
#[cfg(target_family = "windows")]
Self::Dx12 => {}
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { queue_family_index } => vulkan::release_vulkan_swapchain_surface(
_gr_context,
_skia_surface,
*queue_family_index,
),
}
}
#[cfg_attr(not(feature = "unstable-wgpu-29"), allow(dead_code))]
pub(crate) fn import_texture(
&self,
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::import_metal_texture(canvas, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::import_dx12_texture(canvas, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe { vulkan::import_vulkan_texture(canvas, texture) },
}
}
}

View File

@ -0,0 +1,176 @@
// 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
use windows::Win32::Graphics::Direct3D12::{D3D12_RESOURCE_STATE_PRESENT, ID3D12Resource};
use windows::Win32::Graphics::Dxgi::Common::DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
};
use wgpu_29 as wgpu;
/// # Safety
/// `resource` must be a valid D3D12 resource for the lifetime of the returned Surface.
unsafe fn wrap_dx12_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
resource: ID3D12Resource,
dxgi_format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
color_type: skia_safe::ColorType,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
let texture_info = skia_safe::gpu::d3d::TextureResourceInfo {
resource,
alloc: None,
resource_state: D3D12_RESOURCE_STATE_PRESENT,
format: dxgi_format,
sample_count: 1,
level_count: 1,
sample_quality_pattern: DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN,
protected: skia_safe::gpu::Protected::No,
};
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_d3d((width, height), &texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
/// # Safety
/// The caller must ensure `texture` was created by a DX12-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
pub unsafe fn make_dx12_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the D3D12 resource is
// ref-counted (COM) and cloned into Skia's internal BackendRenderTarget via wrap_dx12_texture.
unsafe {
let dx12_texture = texture.as_hal::<wgpu::wgc::api::Dx12>()?;
let resource = windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_texture.raw_resource().clone(),
));
let size = texture.size();
let (dxgi_format, color_type) = match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => {
(DXGI_FORMAT_R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888)
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, skia_safe::ColorType::SRGBA8888)
}
wgpu::TextureFormat::Bgra8Unorm => {
(DXGI_FORMAT_B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888)
}
_ => return None,
};
wrap_dx12_texture(
size.width as i32,
size.height as i32,
gr_context,
resource,
dxgi_format,
color_type,
super::attachment_color_space(texture),
)
}
}
#[cfg_attr(not(feature = "unstable-wgpu-29"), allow(dead_code))]
#[allow(non_snake_case)]
pub unsafe fn import_dx12_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let dx12_texture = texture.as_hal::<wgpu::wgc::api::Dx12>();
let resource: ID3D12Resource = windows_core::Interface::from_raw(
windows_core::Interface::into_raw(dx12_texture.unwrap().raw_resource().clone()),
);
let dxgi_texture_format = resource.GetDesc().Format;
let color_type = match dxgi_texture_format {
DXGI_FORMAT_R8G8B8A8_UNORM => skia_safe::ColorType::RGBA8888,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => skia_safe::ColorType::SRGBA8888,
DXGI_FORMAT_B8G8R8A8_UNORM => skia_safe::ColorType::BGRA8888,
_ => return None,
};
let texture_info = skia_safe::gpu::d3d::TextureResourceInfo {
resource,
alloc: None,
resource_state: D3D12_RESOURCE_STATE_PRESENT,
format: dxgi_texture_format,
sample_count: 1,
level_count: 1,
sample_quality_pattern: DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN,
protected: skia_safe::gpu::Protected::No,
};
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_d3d(
(size.width as i32, size.height as i32),
&texture_info,
"slint_imported_wgpu_texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub unsafe fn make_dx12_context(
adapter: &wgpu::Adapter,
_device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
let backend = unsafe {
let maybe_dx12_queue = queue.as_hal::<wgpu::wgc::api::Dx12>();
let dx12_adapter = adapter.as_hal::<wgpu::wgc::api::Dx12>().unwrap();
maybe_dx12_queue.map(|dx12_queue| {
let dx12_queue_raw = dx12_queue.as_raw();
let mut dx12_device_old: Option<windows::Win32::Graphics::Direct3D12::ID3D12Device> =
None;
dx12_queue_raw.GetDevice(&mut dx12_device_old as _).unwrap();
let dx12_device_old = dx12_device_old.unwrap();
let dx12_device = windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_device_old,
));
let idxgiadapter_3: windows::Win32::Graphics::Dxgi::IDXGIAdapter3 =
dx12_adapter.as_raw().clone().into();
skia_safe::gpu::d3d::BackendContext {
adapter: windows_core::Interface::from_raw(windows_core::Interface::into_raw(
idxgiadapter_3,
)),
device: dx12_device,
queue: windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_queue_raw.clone(),
)),
memory_allocator: None,
protected_context: skia_safe::gpu::Protected::No,
}
})
};
unsafe { skia_safe::gpu::direct_contexts::make_d3d(&backend.unwrap(), None) }
}

View File

@ -0,0 +1,146 @@
// 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
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{MTLCommandQueue, MTLTexture};
use skia_safe::gpu::mtl;
use wgpu_29 as wgpu;
/// # Safety
/// `metal_handle` must be a valid Metal texture handle for the lifetime of the returned Surface.
unsafe fn wrap_metal_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
metal_handle: mtl::Handle,
color_type: skia_safe::ColorType,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
unsafe {
let texture_info = mtl::TextureInfo::new(metal_handle);
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_mtl((width, height), &texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
}
/// # Safety
/// The caller must ensure `texture` was created by a Metal-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
pub unsafe fn make_metal_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the Metal handle is copied
// into Skia's internal BackendRenderTarget via wrap_metal_texture.
unsafe {
let metal_texture = texture.as_hal::<wgpu::wgc::api::Metal>()?;
let handle =
metal_texture.raw_handle() as *const ProtocolObject<dyn MTLTexture> as mtl::Handle;
let size = texture.size();
let color_type = match texture.format() {
wgpu::TextureFormat::Bgra8Unorm => skia_safe::ColorType::BGRA8888,
wgpu::TextureFormat::Rgba8Unorm => skia_safe::ColorType::RGBA8888,
wgpu::TextureFormat::Rgba8UnormSrgb => skia_safe::ColorType::SRGBA8888,
_ => return None,
};
wrap_metal_texture(
size.width as i32,
size.height as i32,
gr_context,
handle,
color_type,
super::attachment_color_space(texture),
)
}
}
#[cfg_attr(not(feature = "unstable-wgpu-29"), allow(dead_code))]
pub unsafe fn import_metal_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let metal_texture = texture.as_hal::<wgpu::wgc::api::Metal>();
let texture_info = mtl::TextureInfo::new(metal_texture.unwrap().raw_handle()
as *const ProtocolObject<dyn MTLTexture>
as mtl::Handle);
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_mtl(
(size.width as _, size.height as _),
skia_safe::gpu::Mipmapped::No,
&texture_info,
"Borrowed Metal texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => skia_safe::ColorType::RGBA8888,
wgpu::TextureFormat::Rgba8UnormSrgb => skia_safe::ColorType::SRGBA8888,
_ => return None,
},
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub fn set_layer_contents_gravity(surface: &wgpu::Surface<'_>) {
// SAFETY: The hal surface is only borrowed for the duration of this call, to adjust a
// CAMetalLayer property that wgpu itself neither reads nor writes.
unsafe {
if let Some(hal_surface) = surface.as_hal::<wgpu::wgc::api::Metal>() {
let layer = hal_surface.render_layer().lock();
let gravity = if !layer.contentsAreFlipped() {
objc2_quartz_core::kCAGravityTopLeft
} else {
objc2_quartz_core::kCAGravityBottomLeft
};
layer.setContentsGravity(gravity);
}
}
}
pub fn make_metal_context(
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
let backend = unsafe {
let maybe_metal_device = device.as_hal::<wgpu::wgc::api::Metal>();
let maybe_metal_queue = queue.as_hal::<wgpu::wgc::api::Metal>();
maybe_metal_device.and_then(|metal_device| {
let metal_device_raw = metal_device.raw_device();
maybe_metal_queue.map(|metal_queue| {
// Share wgpu's command queue with Skia, so that Metal's per-queue hazard tracking
// orders wgpu's texture writes before Skia samples them.
let metal_queue_raw: *const ProtocolObject<dyn MTLCommandQueue> =
metal_queue.as_raw();
mtl::BackendContext::new(
Retained::as_ptr(metal_device_raw) as mtl::Handle,
metal_queue_raw as mtl::Handle,
)
})
})?
};
skia_safe::gpu::direct_contexts::make_metal(&backend, None)
}

View File

@ -0,0 +1,274 @@
// 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
use crate::vulkan_handle;
use skia_safe::gpu::vk;
use wgpu_29 as wgpu;
// Raw values of the Vulkan handles behind wgpu-hal's objects, for Skia's `vk` API. The
// parameter types pin which `ash::vk` handle each accessor returns; see `vulkan_handle`.
fn vk_instance(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.shared_instance().raw_instance().handle()) }
}
fn vk_physical_device(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.raw_physical_device()) }
}
fn vk_device(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.raw_device().handle()) }
}
fn vk_queue(queue: &wgpu::hal::vulkan::Queue) -> u64 {
unsafe { vulkan_handle::dispatchable(queue.as_raw()) }
}
fn vk_image(texture: &wgpu::hal::vulkan::Texture) -> u64 {
unsafe { vulkan_handle::non_dispatchable(texture.raw_handle()) }
}
fn vk_format_and_color_type(
format: wgpu::TextureFormat,
) -> Option<(skia_safe::gpu::vk::Format, skia_safe::ColorType)> {
match format {
wgpu::TextureFormat::Rgba8Unorm => {
Some((skia_safe::gpu::vk::Format::R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888))
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
Some((skia_safe::gpu::vk::Format::R8G8B8A8_SRGB, skia_safe::ColorType::SRGBA8888))
}
wgpu::TextureFormat::Bgra8Unorm => {
Some((skia_safe::gpu::vk::Format::B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888))
}
_ => None,
}
}
/// # Safety
/// `vk_image_raw` must be a valid Vulkan image handle for the lifetime of the returned Surface.
unsafe fn wrap_vulkan_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
vk_image_raw: u64,
vk_format: skia_safe::gpu::vk::Format,
color_type: skia_safe::ColorType,
layout: skia_safe::gpu::vk::ImageLayout,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
unsafe {
let texture_info = &skia_safe::gpu::vk::ImageInfo::new(
vk_image_raw as _,
skia_safe::gpu::vk::Alloc::default(),
skia_safe::gpu::vk::ImageTiling::OPTIMAL,
layout,
vk_format,
1,
None,
None,
None,
None,
);
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_vk((width, height), texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
}
/// # Safety
/// The caller must ensure `texture` was created by a Vulkan-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
///
/// `layout` is the layout wgpu leaves the image in, which Skia transitions away from before
/// its first draw. Getting it wrong doesn't just trip the validation layers, it makes the
/// barrier Skia emits name the wrong source layout.
pub unsafe fn make_vulkan_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
layout: skia_safe::gpu::vk::ImageLayout,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the Vulkan handle is copied
// into Skia's internal BackendRenderTarget via wrap_vulkan_texture.
unsafe {
let vulkan_texture = texture.as_hal::<wgpu::wgc::api::Vulkan>()?;
let vk_image_raw = vk_image(&vulkan_texture);
let size = texture.size();
let (vk_format, color_type) = vk_format_and_color_type(texture.format())?;
wrap_vulkan_texture(
size.width as i32,
size.height as i32,
gr_context,
vk_image_raw,
vk_format,
color_type,
layout,
super::attachment_color_space(texture),
)
}
}
/// Records the transition back to `PRESENT_SRC_KHR` and flushes it.
///
/// wgpu's tracker still believes the swapchain image is in its `PRESENT` state, because that is
/// where wgpu itself left it before Skia took over. Leaving it in Skia's color-attachment layout
/// would make the barrier `wgpu::Queue::present` emits name a source layout the image isn't in.
pub fn release_vulkan_swapchain_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
skia_surface: &mut skia_safe::Surface,
queue_family_index: u32,
) {
let present_state = skia_safe::gpu::vk::mutable_texture_states::new_vulkan(
skia_safe::gpu::vk::ImageLayout::PRESENT_SRC_KHR,
queue_family_index,
);
gr_context.flush_surface_with_texture_state(
skia_surface,
&skia_safe::gpu::FlushInfo::default(),
Some(&present_state),
);
}
/// Extension names as `String`, for [`vk::BackendContextBuilder::with_extensions`]. Vulkan
/// extension names are ASCII, so the lossy conversion can't lose anything.
fn cstr_names(names: &[&'static std::ffi::CStr]) -> Vec<String> {
names.iter().map(|name| name.to_string_lossy().into_owned()).collect()
}
/// The queue family the wgpu device submits on, which is also the one Skia has to hand the
/// swapchain image back to.
///
/// # Safety
/// `device` must be backed by the Vulkan wgpu backend.
pub unsafe fn queue_family_index(device: &wgpu::Device) -> Option<u32> {
unsafe { Some(device.as_hal::<wgpu::wgc::api::Vulkan>()?.queue_family_index()) }
}
#[cfg_attr(not(feature = "unstable-wgpu-29"), allow(dead_code))]
pub unsafe fn import_vulkan_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let vulkan_texture = texture.as_hal::<wgpu::wgc::api::Vulkan>();
let alloc = skia_safe::gpu::vk::Alloc::default();
let (vk_format, color_type) = match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => {
(skia_safe::gpu::vk::Format::R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888)
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
(skia_safe::gpu::vk::Format::R8G8B8A8_SRGB, skia_safe::ColorType::SRGBA8888)
}
wgpu::TextureFormat::Bgra8Unorm => {
(skia_safe::gpu::vk::Format::B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888)
}
_ => return None,
};
let texture_info = &skia_safe::gpu::vk::ImageInfo::new(
vk_image(&vulkan_texture.unwrap()) as _,
alloc,
skia_safe::gpu::vk::ImageTiling::OPTIMAL,
skia_safe::gpu::vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
vk_format,
1,
None,
None,
None,
None,
);
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_vk(
(size.width as _, size.height as _),
texture_info,
"Borrowed Vulkan texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub unsafe fn make_vulkan_context(
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
unsafe {
let vulkan_device = device.as_hal::<wgpu::wgc::api::Vulkan>()?;
let vulkan_queue = queue.as_hal::<wgpu::wgc::api::Vulkan>()?;
let shared_instance = vulkan_device.shared_instance();
// Skia only asks about the instance and device handed to it below, or about the loader
// itself with a null instance. wgpu-hal has those handles in typed form, so use them
// rather than rebuilding them from the raw values Skia passes back.
let get_proc = |of| {
let result = match of {
skia_safe::gpu::vk::GetProcOf::Instance(instance, name) => {
let instance_handle = if instance.is_null() {
Default::default() // VK_NULL_HANDLE
} else {
let handle = shared_instance.raw_instance().handle();
debug_assert_eq!(instance as u64, vk_instance(&vulkan_device));
handle
};
shared_instance.entry().get_instance_proc_addr(instance_handle, name)
}
skia_safe::gpu::vk::GetProcOf::Device(device, name) => {
let device_handle = vulkan_device.raw_device().handle();
debug_assert_eq!(device as u64, vk_device(&vulkan_device));
shared_instance.raw_instance().get_device_proc_addr(device_handle, name)
}
};
match result {
Some(f) => f as _,
None => {
//println!("resolve of {} failed", of.name().to_str().unwrap());
core::ptr::null()
}
}
};
// Skia gates features on the extensions it's told about, and rejects anything it
// considers unsupported: without `VK_KHR_swapchain` in this list it refuses to wrap an
// image that's in `PRESENT_SRC_KHR` layout, which is how wgpu hands out swapchain
// images. Hand it what wgpu actually enabled, no more.
let instance_extensions = cstr_names(shared_instance.extensions());
let device_extensions = cstr_names(vulkan_device.enabled_device_extensions());
// WGPU 29 is locked to vulkan 1.3 and skia assumes the highest vulkan API version of the
// physical device is chosen, causing it to ask for unsupported features/functions.
let backend = vk::BackendContext::new_builder(
vk_instance(&vulkan_device) as _,
vk_physical_device(&vulkan_device) as _,
vk_device(&vulkan_device) as _,
(vk_queue(&vulkan_queue) as _, vulkan_device.queue_family_index() as _),
&get_proc,
Some(vk::Version::new(1, 3, 0)),
)
.with_extensions(
&instance_extensions.iter().map(String::as_str).collect::<Vec<_>>(),
&device_extensions.iter().map(String::as_str).collect::<Vec<_>>(),
)
.build();
skia_safe::gpu::direct_contexts::make_vulkan(&backend, None)
}
}

View File

@ -0,0 +1,688 @@
// 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
#[cfg(feature = "unstable-wgpu-30")]
use i_slint_core::api::GraphicsAPI;
use i_slint_core::api::{PhysicalSize as PhysicalWindowSize, Window};
use i_slint_core::graphics::RequestedGraphicsAPI;
use i_slint_core::partial_renderer::DirtyRegion;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::DrawOutcome;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use wgpu_30 as wgpu;
use crate::SkiaSharedContext;
#[cfg(target_family = "windows")]
mod dx12;
#[cfg(target_vendor = "apple")]
mod metal;
#[cfg(skia_wgpu_vulkan)]
mod vulkan;
/// See [`crate::attachment_color_space`].
pub(crate) fn attachment_color_space(texture: &wgpu::Texture) -> skia_safe::ColorSpace {
crate::attachment_color_space(crate::TextureEncoding::from_format_is_srgb(
texture.format().is_srgb(),
))
}
/// See [`crate::sampled_texture_color_space`].
#[cfg_attr(not(feature = "unstable-wgpu-30"), allow(dead_code))]
pub(crate) fn sampled_texture_color_space(texture: &wgpu::Texture) -> skia_safe::ColorSpace {
crate::sampled_texture_color_space(crate::TextureEncoding::from_format_is_srgb(
texture.format().is_srgb(),
))
}
/// Skia rendering surface backed by WGPU. Supports both on-screen rendering (with a
/// window surface) and offscreen rendering into caller-provided textures.
pub struct WGPUSurface {
pub(crate) gr_context: RefCell<skia_safe::gpu::DirectContext>,
wgpu: Rc<SharedWgpuState>,
surface_config: RefCell<Option<wgpu::SurfaceConfiguration>>,
surface: Option<wgpu::Surface<'static>>,
textures_to_transition_for_sampling: RefCell<Vec<wgpu::Texture>>,
pub(crate) backend: Backend,
alpha_modes: Vec<wgpu::CompositeAlphaMode>,
}
impl WGPUSurface {
pub fn new_with_surface(
surface_target: impl Into<i_slint_core::graphics::wgpu_30::SurfaceTarget>,
size: PhysicalWindowSize,
requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, PlatformError> {
let (instance, adapter, device, queue, surface) =
i_slint_core::graphics::wgpu_30::init_instance_adapter_device_queue_surface(
surface_target,
requested_graphics_api,
i_slint_core::graphics::wgpu_30::default_backends_to_avoid(),
)?;
Self::init_with_parts(
Rc::new(SharedWgpuState { instance, adapter, device, queue }),
surface,
size,
)
}
fn init_with_parts(
wgpu: Rc<SharedWgpuState>,
surface: wgpu::Surface<'static>,
size: PhysicalWindowSize,
) -> Result<Self, PlatformError> {
let SharedWgpuState { adapter, device, queue, .. } = &*wgpu;
#[cfg(target_vendor = "apple")]
metal::set_layer_contents_gravity(&surface);
// On iOS a window has no size until UIKit attaches it to a scene,
// and wgpu rejects a zero-sized configure.
// Start at 1x1; `resize_event` applies the real size.
let mut surface_config = surface
.get_default_config(adapter, size.width.max(1), size.height.max(1))
.ok_or_else(|| PlatformError::from("WGPU surface is not compatible with adapter"))?;
let swapchain_capabilities = surface.get_capabilities(adapter);
let swapchain_format = swapchain_capabilities
.formats
.iter()
.find(|f| {
matches!(f, wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm)
})
.copied()
.unwrap_or_else(|| swapchain_capabilities.formats[0]);
surface_config.format = swapchain_format;
// Prefer FIFO modes over the Mailbox that `get_default_config` picks on some backends
// (it takes the first advertised mode, and DX12 lists Mailbox first), for frame pacing
// and better energy efficiency. `AutoVsync` falls back to FifoRelaxed and then Fifo, so
// it is supported everywhere.
surface_config.present_mode = wgpu::PresentMode::AutoVsync;
let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
surface.configure(device, &surface_config);
if let Some(e) = spin_on::spin_on(error_scope.pop()) {
return Err(PlatformError::from(format!("Error configuring WGPU surface: {e}")));
}
let backend = Backend::new(adapter, device)?;
let gr_context = backend
.make_context(adapter, device, queue)
.ok_or_else(|| PlatformError::from("Failed to create Skia context from WGPU"))?;
Ok(Self {
gr_context: gr_context.into(),
wgpu,
surface_config: Some(surface_config).into(),
surface: Some(surface),
textures_to_transition_for_sampling: RefCell::new(Vec::new()),
backend,
alpha_modes: swapchain_capabilities.alpha_modes,
})
}
pub(crate) fn new_offscreen(
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
backend: Backend,
gr_context: skia_safe::gpu::DirectContext,
) -> Self {
Self {
gr_context: RefCell::new(gr_context),
wgpu: Rc::new(SharedWgpuState { instance, adapter, device, queue }),
surface_config: None.into(),
surface: None,
textures_to_transition_for_sampling: RefCell::new(Vec::new()),
backend,
alpha_modes: vec![],
}
}
/// Transitions any imported wgpu textures to sampling state and flushes
/// the Skia graphics context. Must be called after rendering to ensure
/// Skia's GPU work is submitted.
pub(crate) fn flush_and_submit(&self, gr_context: &mut skia_safe::gpu::DirectContext) {
let textures_to_transition = self.textures_to_transition_for_sampling.take();
if !textures_to_transition.is_empty() {
let mut encoder =
self.wgpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Skia texture transition encoder"),
});
encoder.transition_resources(
std::iter::empty(),
textures_to_transition.iter().map(|texture| wgpu::TextureTransition {
texture,
selector: None,
state: wgpu::TextureUses::RESOURCE,
}),
);
self.wgpu.queue.submit(Some(encoder.finish()));
}
gr_context.submit(None);
}
}
/// The wgpu stack a surface renders with.
///
/// [`SkiaSharedContext`] caches the one the first window created, so that later windows it can
/// serve reuse it instead of creating their own.
/// That cache holds a weak reference and every surface a strong one, so the resources go away
/// with the last surface using them.
/// Were they to outlive the surfaces, they'd be destroyed whenever the last renderer happens to
/// be dropped, and tearing a wgpu device down from a thread-local destructor aborts the process
/// on macOS, where the Metal backend needs an autorelease pool that is gone by then.
/// A window that is still shown owns its surface, so that case remains.
pub(crate) struct SharedWgpuState {
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
}
/// Whether `device` offers everything `settings` asks of it.
///
/// The instance and adapter parts of the settings are covered by
/// [`adapter_matches_graphics_api_request`].
#[cfg(feature = "unstable-wgpu-30")]
fn device_satisfies_settings(
device: &wgpu::Device,
settings: &i_slint_core::graphics::wgpu_30::api::WGPUSettings,
) -> bool {
device.features().contains(settings.device_required_features)
&& settings.device_required_limits.check_limits(&device.limits())
}
fn adapter_matches_graphics_api_request(
adapter: &wgpu::Adapter,
requested_graphics_api: Option<&RequestedGraphicsAPI>,
) -> bool {
let backend = adapter.get_info().backend;
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
match requested_graphics_api {
None => true,
Some(RequestedGraphicsAPI::Metal) => backend == wgpu::Backend::Metal,
Some(RequestedGraphicsAPI::Vulkan) => backend == wgpu::Backend::Vulkan,
Some(RequestedGraphicsAPI::Direct3D) => backend == wgpu::Backend::Dx12,
#[cfg(feature = "unstable-wgpu-30")]
Some(RequestedGraphicsAPI::WGPU30(
i_slint_core::graphics::wgpu_30::api::WGPUConfiguration::Automatic(settings),
)) => {
let backend_bit = match backend {
wgpu::Backend::Vulkan => wgpu::Backends::VULKAN,
wgpu::Backend::Metal => wgpu::Backends::METAL,
wgpu::Backend::Dx12 => wgpu::Backends::DX12,
wgpu::Backend::Gl => wgpu::Backends::GL,
wgpu::Backend::BrowserWebGpu => wgpu::Backends::BROWSER_WEBGPU,
_ => return false,
};
settings.backends.contains(backend_bit)
}
Some(_) => false,
}
}
impl crate::Surface for WGPUSurface {
fn new(
shared_context: &SkiaSharedContext,
window_handle: Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
display_handle: Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
size: PhysicalWindowSize,
requested_graphics_api: Option<RequestedGraphicsAPI>,
) -> Result<Self, PlatformError> {
let make_target = || -> Box<dyn wgpu::DisplayAndWindowHandle + 'static> {
Box::new(WindowAndDisplayHandle(window_handle.clone(), display_handle.clone()))
};
#[cfg(feature = "unstable-wgpu-30")]
let manual_configuration = matches!(
&requested_graphics_api,
Some(RequestedGraphicsAPI::WGPU30(
i_slint_core::graphics::wgpu_30::api::WGPUConfiguration::Manual { .. }
))
);
#[cfg(not(feature = "unstable-wgpu-30"))]
let manual_configuration = false;
#[cfg(feature = "unstable-wgpu-30")]
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
let requested_settings = match &requested_graphics_api {
Some(RequestedGraphicsAPI::WGPU30(
i_slint_core::graphics::wgpu_30::api::WGPUConfiguration::Automatic(settings),
)) => Some(settings.clone()),
_ => None,
};
// try to reuse old / shared graphics primitives from previous windows with matching
// settings
if !manual_configuration {
let shared_state = shared_context.0.wgpu_30_state.borrow().upgrade();
if let Some(shared) = shared_state {
#[cfg(feature = "unstable-wgpu-30")]
let settings_compatible = requested_settings
.as_ref()
.is_none_or(|settings| device_satisfies_settings(&shared.device, settings));
#[cfg(not(feature = "unstable-wgpu-30"))]
let settings_compatible = true;
if settings_compatible
&& adapter_matches_graphics_api_request(
&shared.adapter,
requested_graphics_api.as_ref(),
)
&& let Ok(surface) = shared.instance.create_surface(make_target())
&& shared.adapter.is_surface_supported(&surface)
{
match Self::init_with_parts(shared, surface, size) {
Ok(surface) => return Ok(surface),
Err(err) => {
// The shared device may be lost. Drop it and start over.
i_slint_core::debug_log!(
"Failed to reuse the shared WGPU device: {err} . Re-initializing"
);
shared_context.0.wgpu_30_state.take();
}
}
}
}
}
let (instance, adapter, device, queue, surface) =
i_slint_core::graphics::wgpu_30::init_instance_adapter_device_queue_surface(
make_target(),
requested_graphics_api,
i_slint_core::graphics::wgpu_30::default_backends_to_avoid(),
)?;
let wgpu = Rc::new(SharedWgpuState { instance, adapter, device, queue });
let new_surface = Self::init_with_parts(wgpu.clone(), surface, size)?;
if !manual_configuration {
*shared_context.0.wgpu_30_state.borrow_mut() = Rc::downgrade(&wgpu);
}
Ok(new_surface)
}
fn name(&self) -> &'static str {
if self.surface.is_some() { "wgpu" } else { "wgpu-texture" }
}
fn resize_event(&self, size: PhysicalWindowSize) -> Result<(), PlatformError> {
let mut surface_config_opt = self.surface_config.borrow_mut();
let (Some(surface_config), Some(surface)) = (surface_config_opt.as_mut(), &self.surface)
else {
return Ok(());
};
// Skip reconfigure if size hasn't changed — DRM/KMS surfaces don't
// support being reconfigured.
if surface_config.width == size.width && surface_config.height == size.height {
return Ok(());
}
{
let gr_context = &mut self.gr_context.borrow_mut();
// This is brute force, but for the lack of access to the fences this seems to work: Avoid any pending work so that
// IDXGISwapChain::ResizeBuffers doesn't complain that the surface is still in use.
gr_context.flush_submit_and_sync_cpu();
}
surface_config.width = size.width;
surface_config.height = size.height;
surface.configure(&self.wgpu.device, surface_config);
Ok(())
}
fn render(
&self,
_window: &Window,
_size: PhysicalWindowSize,
callback: &dyn Fn(
&skia_safe::Canvas,
Option<&mut skia_safe::gpu::DirectContext>,
u8,
) -> Option<DirtyRegion>,
pre_present_callback: &RefCell<Option<Box<dyn FnMut()>>>,
) -> Result<DrawOutcome, PlatformError> {
let (Some(surface), Some(surface_config)) = (&self.surface, &*self.surface_config.borrow())
else {
return Err("WGPUSurface::render() called on offscreen surface".into());
};
let gr_context = &mut self.gr_context.borrow_mut();
let frame = match surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => t,
wgpu::CurrentSurfaceTexture::Occluded => return Ok(DrawOutcome::Occluded),
wgpu::CurrentSurfaceTexture::Timeout => return Ok(DrawOutcome::Timeout),
wgpu::CurrentSurfaceTexture::Validation => {
return Err("WGPU surface validation error in get_current_texture".into());
}
stale @ (wgpu::CurrentSurfaceTexture::Outdated
| wgpu::CurrentSurfaceTexture::Suboptimal(_)
| wgpu::CurrentSurfaceTexture::Lost) => {
// `Suboptimal` carries a live `SurfaceTexture`; matched with `_` it is not bound,
// so the value returned by `get_current_texture()` keeps it alive across the
// `surface.configure()` below — which wgpu forbids ("`SurfaceOutput` must be
// dropped before a new `Surface` is made"), panicking on the first frame on
// Wayland. Drop it first. (`Outdated`/`Lost` carry nothing → no-op.)
drop(stale);
surface.configure(&self.wgpu.device, surface_config);
match surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => t,
_ => return Ok(DrawOutcome::Occluded),
}
}
};
// Skia renders through the raw backend queue, invisible to wgpu's usage
// tracking, so `Queue::present` would treat the frame as never written
// and clear it. Clear it through wgpu instead before Skia draws; the
// in-order queue keeps Skia's later-committed work on top.
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
self.wgpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Slint frame init"),
});
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Slint frame init"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
self.wgpu.queue.submit(Some(encoder.finish()));
let skia_surface = self.backend.make_swapchain_surface(gr_context, &frame.texture);
let mut skia_surface = skia_surface
.ok_or_else(|| PlatformError::from("Failed to create Skia surface from WGPU"))?;
callback(skia_surface.canvas(), Some(gr_context), 0);
self.backend.release_swapchain_surface(gr_context, &mut skia_surface);
self.flush_and_submit(gr_context);
// Skia drew via the raw queue behind wgpu's back, and `Queue::present` skips its own
// transition when the tracker already says PRESENT, so nothing would order the
// presentation after Skia's work: the clear submission above signals its semaphore
// before Skia even starts. Referencing the frame texture in a submission of our own
// makes present wait for it.
let mut encoder =
self.wgpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Skia present ordering encoder"),
});
encoder.transition_resources(
std::iter::empty(),
std::iter::once(wgpu::TextureTransition {
texture: &frame.texture,
selector: None,
state: wgpu::TextureUses::PRESENT,
}),
);
self.wgpu.queue.submit(Some(encoder.finish()));
if let Some(pre_present_callback) = pre_present_callback.borrow_mut().as_mut() {
pre_present_callback();
}
self.wgpu.queue.present(frame);
Ok(DrawOutcome::Success)
}
fn bits_per_pixel(&self) -> Result<u8, PlatformError> {
if let Some(surface_config) = &*self.surface_config.borrow() {
Ok(match surface_config.format {
wgpu_30::TextureFormat::Rgba8Unorm
| wgpu_30::TextureFormat::Rgba8UnormSrgb
| wgpu_30::TextureFormat::Bgra8Unorm
| wgpu_30::TextureFormat::Bgra8UnormSrgb => 32,
fmt => return Err(format!("Unsupported surface format {:#?}", fmt).into()),
})
} else {
// All supported render-target formats (Rgba8Unorm, Bgra8Unorm, and sRGB variants) are 32bpp.
Ok(32)
}
}
#[cfg(feature = "unstable-wgpu-30")]
fn with_graphics_api(&self, callback: &mut dyn FnMut(GraphicsAPI<'_>)) {
let api = i_slint_core::graphics::create_graphics_api_wgpu_30(
self.wgpu.instance.clone(),
self.wgpu.device.clone(),
self.wgpu.queue.clone(),
);
callback(api)
}
#[cfg(any(feature = "unstable-wgpu-29", feature = "unstable-wgpu-30"))]
fn import_wgpu_texture(
&self,
canvas: &skia_safe::Canvas,
any_wgpu_texture: &i_slint_core::graphics::WGPUTexture,
) -> Option<skia_safe::Image> {
let texture: wgpu_30::Texture = match any_wgpu_texture {
#[cfg(feature = "unstable-wgpu-29")]
i_slint_core::graphics::WGPUTexture::WGPU29Texture(..) => return None,
#[cfg(feature = "unstable-wgpu-30")]
i_slint_core::graphics::WGPUTexture::WGPU30Texture(texture) => texture.clone(),
};
// Skia won't submit commands right away, so remember the texture and transition before
// submitting.
self.textures_to_transition_for_sampling.borrow_mut().push(texture.clone());
self.backend.import_texture(canvas, texture)
}
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
// `Opaque` discards the scene's alpha; pick a translucent mode if offered.
// Metal (CAMetalLayer) only offers `PostMultiplied`, so it must be a fallback.
use wgpu::CompositeAlphaMode::{Opaque, PostMultiplied, PreMultiplied};
let wanted: &[wgpu::CompositeAlphaMode] =
if transparent { &[PreMultiplied, PostMultiplied] } else { &[Opaque] };
let Some(mode) = wanted.iter().copied().find(|m| self.alpha_modes.contains(m)) else {
return Ok(());
};
let mut surface_config_opt = self.surface_config.borrow_mut();
let (Some(surface_config), Some(surface)) = (surface_config_opt.as_mut(), &self.surface)
else {
return Ok(());
};
if surface_config.alpha_mode != mode {
surface_config.alpha_mode = mode;
surface.configure(&self.wgpu.device, surface_config);
}
Ok(())
}
fn as_any(&self) -> &dyn core::any::Any {
self
}
}
struct WindowAndDisplayHandle(
Arc<dyn raw_window_handle::HasWindowHandle + Send + Sync>,
Arc<dyn raw_window_handle::HasDisplayHandle + Send + Sync>,
);
impl raw_window_handle::HasWindowHandle for WindowAndDisplayHandle {
fn window_handle(
&self,
) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
self.0.window_handle()
}
}
impl raw_window_handle::HasDisplayHandle for WindowAndDisplayHandle {
fn display_handle(
&self,
) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
self.1.display_handle()
}
}
pub(crate) enum Backend {
#[cfg(target_vendor = "apple")]
Metal,
#[cfg(target_family = "windows")]
Dx12,
#[cfg(skia_wgpu_vulkan)]
Vulkan {
/// The family Skia has to hand the swapchain image back to, see
/// [`Backend::release_swapchain_surface`].
queue_family_index: u32,
},
}
impl Backend {
pub(crate) fn new(
adapter: &wgpu::Adapter,
_device: &wgpu::Device,
) -> Result<Self, PlatformError> {
match adapter.get_info().backend {
wgpu_30::Backend::Noop => {
Err(PlatformError::from("Cannot use WGPU Noop backend with Skia"))
}
#[cfg(skia_wgpu_vulkan)]
wgpu_30::Backend::Vulkan => Ok(Self::Vulkan {
// SAFETY: `_device` is a Vulkan device, as the adapter's backend just said.
queue_family_index: unsafe { vulkan::queue_family_index(_device) }.ok_or_else(
|| {
PlatformError::from(
"Cannot query the queue family of the WGPU Vulkan device",
)
},
)?,
}),
#[cfg(target_vendor = "apple")]
wgpu_30::Backend::Metal => Ok(Self::Metal),
#[cfg(target_family = "windows")]
wgpu_30::Backend::Dx12 => Ok(Self::Dx12),
other => Err(PlatformError::from(format!(
"Unsupported WGPU backend for use with Skia: {}",
other
))),
}
}
pub(crate) fn make_context(
&self,
_adapter: &wgpu::Adapter,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => metal::make_metal_context(device, queue),
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_context(&_adapter, &device, &queue) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe { vulkan::make_vulkan_context(device, queue) },
}
}
pub(crate) fn make_surface(
&self,
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::make_metal_surface(gr_context, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_surface(gr_context, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe {
vulkan::make_vulkan_surface(
gr_context,
texture,
skia_safe::gpu::vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
)
},
}
}
/// Like [`Self::make_surface`], but for the swapchain image handed out by
/// [`wgpu::Surface::get_current_texture`].
///
/// wgpu returns surface textures to their `PRESENT` state at the end of every submission,
/// so that is the layout Skia finds the image in, not the color-attachment one a plain
/// render target is left in. Pair every call with [`Self::release_swapchain_surface`].
pub(crate) fn make_swapchain_surface(
&self,
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::make_metal_surface(gr_context, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::make_dx12_surface(gr_context, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe {
vulkan::make_vulkan_surface(
gr_context,
texture,
skia_safe::gpu::vk::ImageLayout::PRESENT_SRC_KHR,
)
},
}
}
/// Hands a surface made by [`Self::make_swapchain_surface`] back in the state
/// [`wgpu::Queue::present`] expects to find it in.
pub(crate) fn release_swapchain_surface(
&self,
_gr_context: &mut skia_safe::gpu::DirectContext,
_skia_surface: &mut skia_safe::Surface,
) {
match self {
// Metal and D3D12 have no image layout for Skia to hand back.
#[cfg(target_vendor = "apple")]
Self::Metal => {}
#[cfg(target_family = "windows")]
Self::Dx12 => {}
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { queue_family_index } => vulkan::release_vulkan_swapchain_surface(
_gr_context,
_skia_surface,
*queue_family_index,
),
}
}
#[cfg_attr(not(feature = "unstable-wgpu-30"), allow(dead_code))]
pub(crate) fn import_texture(
&self,
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
match self {
#[cfg(target_vendor = "apple")]
Self::Metal => unsafe { metal::import_metal_texture(canvas, texture) },
#[cfg(target_family = "windows")]
Self::Dx12 => unsafe { dx12::import_dx12_texture(canvas, texture) },
#[cfg(skia_wgpu_vulkan)]
Self::Vulkan { .. } => unsafe { vulkan::import_vulkan_texture(canvas, texture) },
}
}
}

View File

@ -0,0 +1,176 @@
// 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
use windows::Win32::Graphics::Direct3D12::{D3D12_RESOURCE_STATE_PRESENT, ID3D12Resource};
use windows::Win32::Graphics::Dxgi::Common::DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
};
use wgpu_30 as wgpu;
/// # Safety
/// `resource` must be a valid D3D12 resource for the lifetime of the returned Surface.
unsafe fn wrap_dx12_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
resource: ID3D12Resource,
dxgi_format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
color_type: skia_safe::ColorType,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
let texture_info = skia_safe::gpu::d3d::TextureResourceInfo {
resource,
alloc: None,
resource_state: D3D12_RESOURCE_STATE_PRESENT,
format: dxgi_format,
sample_count: 1,
level_count: 1,
sample_quality_pattern: DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN,
protected: skia_safe::gpu::Protected::No,
};
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_d3d((width, height), &texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
/// # Safety
/// The caller must ensure `texture` was created by a DX12-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
pub unsafe fn make_dx12_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the D3D12 resource is
// ref-counted (COM) and cloned into Skia's internal BackendRenderTarget via wrap_dx12_texture.
unsafe {
let dx12_texture = texture.as_hal::<wgpu::wgc::api::Dx12>()?;
let resource = windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_texture.raw_resource().clone(),
));
let size = texture.size();
let (dxgi_format, color_type) = match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => {
(DXGI_FORMAT_R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888)
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, skia_safe::ColorType::SRGBA8888)
}
wgpu::TextureFormat::Bgra8Unorm => {
(DXGI_FORMAT_B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888)
}
_ => return None,
};
wrap_dx12_texture(
size.width as i32,
size.height as i32,
gr_context,
resource,
dxgi_format,
color_type,
super::attachment_color_space(texture),
)
}
}
#[cfg_attr(not(feature = "unstable-wgpu-30"), allow(dead_code))]
#[allow(non_snake_case)]
pub unsafe fn import_dx12_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let dx12_texture = texture.as_hal::<wgpu::wgc::api::Dx12>();
let resource: ID3D12Resource = windows_core::Interface::from_raw(
windows_core::Interface::into_raw(dx12_texture.unwrap().raw_resource().clone()),
);
let dxgi_texture_format = resource.GetDesc().Format;
let color_type = match dxgi_texture_format {
DXGI_FORMAT_R8G8B8A8_UNORM => skia_safe::ColorType::RGBA8888,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => skia_safe::ColorType::SRGBA8888,
DXGI_FORMAT_B8G8R8A8_UNORM => skia_safe::ColorType::BGRA8888,
_ => return None,
};
let texture_info = skia_safe::gpu::d3d::TextureResourceInfo {
resource,
alloc: None,
resource_state: D3D12_RESOURCE_STATE_PRESENT,
format: dxgi_texture_format,
sample_count: 1,
level_count: 1,
sample_quality_pattern: DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN,
protected: skia_safe::gpu::Protected::No,
};
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_d3d(
(size.width as i32, size.height as i32),
&texture_info,
"slint_imported_wgpu_texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub unsafe fn make_dx12_context(
adapter: &wgpu::Adapter,
_device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
let backend = unsafe {
let maybe_dx12_queue = queue.as_hal::<wgpu::wgc::api::Dx12>();
let dx12_adapter = adapter.as_hal::<wgpu::wgc::api::Dx12>().unwrap();
maybe_dx12_queue.map(|dx12_queue| {
let dx12_queue_raw = dx12_queue.as_raw();
let mut dx12_device_old: Option<windows::Win32::Graphics::Direct3D12::ID3D12Device> =
None;
dx12_queue_raw.GetDevice(&mut dx12_device_old as _).unwrap();
let dx12_device_old = dx12_device_old.unwrap();
let dx12_device = windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_device_old,
));
let idxgiadapter_3: windows::Win32::Graphics::Dxgi::IDXGIAdapter3 =
dx12_adapter.as_raw().clone().into();
skia_safe::gpu::d3d::BackendContext {
adapter: windows_core::Interface::from_raw(windows_core::Interface::into_raw(
idxgiadapter_3,
)),
device: dx12_device,
queue: windows_core::Interface::from_raw(windows_core::Interface::into_raw(
dx12_queue_raw.clone(),
)),
memory_allocator: None,
protected_context: skia_safe::gpu::Protected::No,
}
})
};
unsafe { skia_safe::gpu::direct_contexts::make_d3d(&backend.unwrap(), None) }
}

View File

@ -0,0 +1,146 @@
// 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
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{MTLCommandQueue, MTLTexture};
use skia_safe::gpu::mtl;
use wgpu_30 as wgpu;
/// # Safety
/// `metal_handle` must be a valid Metal texture handle for the lifetime of the returned Surface.
unsafe fn wrap_metal_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
metal_handle: mtl::Handle,
color_type: skia_safe::ColorType,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
unsafe {
let texture_info = mtl::TextureInfo::new(metal_handle);
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_mtl((width, height), &texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
}
/// # Safety
/// The caller must ensure `texture` was created by a Metal-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
pub unsafe fn make_metal_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the Metal handle is copied
// into Skia's internal BackendRenderTarget via wrap_metal_texture.
unsafe {
let metal_texture = texture.as_hal::<wgpu::wgc::api::Metal>()?;
let handle =
metal_texture.raw_handle() as *const ProtocolObject<dyn MTLTexture> as mtl::Handle;
let size = texture.size();
let color_type = match texture.format() {
wgpu::TextureFormat::Bgra8Unorm => skia_safe::ColorType::BGRA8888,
wgpu::TextureFormat::Rgba8Unorm => skia_safe::ColorType::RGBA8888,
wgpu::TextureFormat::Rgba8UnormSrgb => skia_safe::ColorType::SRGBA8888,
_ => return None,
};
wrap_metal_texture(
size.width as i32,
size.height as i32,
gr_context,
handle,
color_type,
super::attachment_color_space(texture),
)
}
}
#[cfg_attr(not(feature = "unstable-wgpu-30"), allow(dead_code))]
pub unsafe fn import_metal_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let metal_texture = texture.as_hal::<wgpu::wgc::api::Metal>();
let texture_info = mtl::TextureInfo::new(metal_texture.unwrap().raw_handle()
as *const ProtocolObject<dyn MTLTexture>
as mtl::Handle);
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_mtl(
(size.width as _, size.height as _),
skia_safe::gpu::Mipmapped::No,
&texture_info,
"Borrowed Metal texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => skia_safe::ColorType::RGBA8888,
wgpu::TextureFormat::Rgba8UnormSrgb => skia_safe::ColorType::SRGBA8888,
_ => return None,
},
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub fn set_layer_contents_gravity(surface: &wgpu::Surface<'_>) {
// SAFETY: The hal surface is only borrowed for the duration of this call, to adjust a
// CAMetalLayer property that wgpu itself neither reads nor writes.
unsafe {
if let Some(hal_surface) = surface.as_hal::<wgpu::wgc::api::Metal>() {
let layer = hal_surface.render_layer().lock();
let gravity = if !layer.contentsAreFlipped() {
objc2_quartz_core::kCAGravityTopLeft
} else {
objc2_quartz_core::kCAGravityBottomLeft
};
layer.setContentsGravity(gravity);
}
}
}
pub fn make_metal_context(
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
let backend = unsafe {
let maybe_metal_device = device.as_hal::<wgpu::wgc::api::Metal>();
let maybe_metal_queue = queue.as_hal::<wgpu::wgc::api::Metal>();
maybe_metal_device.and_then(|metal_device| {
let metal_device_raw = metal_device.raw_device();
maybe_metal_queue.map(|metal_queue| {
// Share wgpu's command queue with Skia, so that Metal's per-queue hazard tracking
// orders wgpu's texture writes before Skia samples them.
let metal_queue_raw: *const ProtocolObject<dyn MTLCommandQueue> =
metal_queue.as_raw();
mtl::BackendContext::new(
Retained::as_ptr(metal_device_raw) as mtl::Handle,
metal_queue_raw as mtl::Handle,
)
})
})?
};
skia_safe::gpu::direct_contexts::make_metal(&backend, None)
}

View File

@ -0,0 +1,274 @@
// 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
use crate::vulkan_handle;
use skia_safe::gpu::vk;
use wgpu_30 as wgpu;
// Raw values of the Vulkan handles behind wgpu-hal's objects, for Skia's `vk` API. The
// parameter types pin which `ash::vk` handle each accessor returns; see `vulkan_handle`.
fn vk_instance(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.shared_instance().raw_instance().handle()) }
}
fn vk_physical_device(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.raw_physical_device()) }
}
fn vk_device(device: &wgpu::hal::vulkan::Device) -> u64 {
unsafe { vulkan_handle::dispatchable(device.raw_device().handle()) }
}
fn vk_queue(queue: &wgpu::hal::vulkan::Queue) -> u64 {
unsafe { vulkan_handle::dispatchable(queue.as_raw()) }
}
fn vk_image(texture: &wgpu::hal::vulkan::Texture) -> u64 {
unsafe { vulkan_handle::non_dispatchable(texture.raw_handle()) }
}
fn vk_format_and_color_type(
format: wgpu::TextureFormat,
) -> Option<(skia_safe::gpu::vk::Format, skia_safe::ColorType)> {
match format {
wgpu::TextureFormat::Rgba8Unorm => {
Some((skia_safe::gpu::vk::Format::R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888))
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
Some((skia_safe::gpu::vk::Format::R8G8B8A8_SRGB, skia_safe::ColorType::SRGBA8888))
}
wgpu::TextureFormat::Bgra8Unorm => {
Some((skia_safe::gpu::vk::Format::B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888))
}
_ => None,
}
}
/// # Safety
/// `vk_image_raw` must be a valid Vulkan image handle for the lifetime of the returned Surface.
unsafe fn wrap_vulkan_texture(
width: i32,
height: i32,
gr_context: &mut skia_safe::gpu::DirectContext,
vk_image_raw: u64,
vk_format: skia_safe::gpu::vk::Format,
color_type: skia_safe::ColorType,
layout: skia_safe::gpu::vk::ImageLayout,
color_space: skia_safe::ColorSpace,
) -> Option<skia_safe::Surface> {
unsafe {
let texture_info = &skia_safe::gpu::vk::ImageInfo::new(
vk_image_raw as _,
skia_safe::gpu::vk::Alloc::default(),
skia_safe::gpu::vk::ImageTiling::OPTIMAL,
layout,
vk_format,
1,
None,
None,
None,
None,
);
let backend_render_target =
skia_safe::gpu::backend_render_targets::make_vk((width, height), texture_info);
skia_safe::gpu::surfaces::wrap_backend_render_target(
gr_context,
&backend_render_target,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
color_space,
None,
)
}
}
/// # Safety
/// The caller must ensure `texture` was created by a Vulkan-backed wgpu device and remains
/// valid for the lifetime of the returned `skia_safe::Surface`.
///
/// `layout` is the layout wgpu leaves the image in, which Skia transitions away from before
/// its first draw. Getting it wrong doesn't just trip the validation layers, it makes the
/// barrier Skia emits name the wrong source layout.
pub unsafe fn make_vulkan_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
texture: &wgpu::Texture,
layout: skia_safe::gpu::vk::ImageLayout,
) -> Option<skia_safe::Surface> {
// SAFETY: texture is borrowed for the duration of this call; the Vulkan handle is copied
// into Skia's internal BackendRenderTarget via wrap_vulkan_texture.
unsafe {
let vulkan_texture = texture.as_hal::<wgpu::wgc::api::Vulkan>()?;
let vk_image_raw = vk_image(&vulkan_texture);
let size = texture.size();
let (vk_format, color_type) = vk_format_and_color_type(texture.format())?;
wrap_vulkan_texture(
size.width as i32,
size.height as i32,
gr_context,
vk_image_raw,
vk_format,
color_type,
layout,
super::attachment_color_space(texture),
)
}
}
/// Records the transition back to `PRESENT_SRC_KHR` and flushes it.
///
/// wgpu's tracker still believes the swapchain image is in its `PRESENT` state, because that is
/// where wgpu itself left it before Skia took over. Leaving it in Skia's color-attachment layout
/// would make the barrier `wgpu::Queue::present` emits name a source layout the image isn't in.
pub fn release_vulkan_swapchain_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
skia_surface: &mut skia_safe::Surface,
queue_family_index: u32,
) {
let present_state = skia_safe::gpu::vk::mutable_texture_states::new_vulkan(
skia_safe::gpu::vk::ImageLayout::PRESENT_SRC_KHR,
queue_family_index,
);
gr_context.flush_surface_with_texture_state(
skia_surface,
&skia_safe::gpu::FlushInfo::default(),
Some(&present_state),
);
}
/// Extension names as `String`, for [`vk::BackendContextBuilder::with_extensions`]. Vulkan
/// extension names are ASCII, so the lossy conversion can't lose anything.
fn cstr_names(names: &[&'static std::ffi::CStr]) -> Vec<String> {
names.iter().map(|name| name.to_string_lossy().into_owned()).collect()
}
/// The queue family the wgpu device submits on, which is also the one Skia has to hand the
/// swapchain image back to.
///
/// # Safety
/// `device` must be backed by the Vulkan wgpu backend.
pub unsafe fn queue_family_index(device: &wgpu::Device) -> Option<u32> {
unsafe { Some(device.as_hal::<wgpu::wgc::api::Vulkan>()?.queue_family_index()) }
}
#[cfg_attr(not(feature = "unstable-wgpu-30"), allow(dead_code))]
pub unsafe fn import_vulkan_texture(
canvas: &skia_safe::Canvas,
texture: wgpu::Texture,
) -> Option<skia_safe::Image> {
unsafe {
let color_space = super::sampled_texture_color_space(&texture);
let vulkan_texture = texture.as_hal::<wgpu::wgc::api::Vulkan>();
let alloc = skia_safe::gpu::vk::Alloc::default();
let (vk_format, color_type) = match texture.format() {
wgpu::TextureFormat::Rgba8Unorm => {
(skia_safe::gpu::vk::Format::R8G8B8A8_UNORM, skia_safe::ColorType::RGBA8888)
}
wgpu::TextureFormat::Rgba8UnormSrgb => {
(skia_safe::gpu::vk::Format::R8G8B8A8_SRGB, skia_safe::ColorType::SRGBA8888)
}
wgpu::TextureFormat::Bgra8Unorm => {
(skia_safe::gpu::vk::Format::B8G8R8A8_UNORM, skia_safe::ColorType::BGRA8888)
}
_ => return None,
};
let texture_info = &skia_safe::gpu::vk::ImageInfo::new(
vk_image(&vulkan_texture.unwrap()) as _,
alloc,
skia_safe::gpu::vk::ImageTiling::OPTIMAL,
skia_safe::gpu::vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
vk_format,
1,
None,
None,
None,
None,
);
let size = texture.size();
let backend_texture = skia_safe::gpu::backend_textures::make_vk(
(size.width as _, size.height as _),
texture_info,
"Borrowed Vulkan texture",
);
Some(
skia_safe::image::Image::from_texture(
canvas.recording_context().as_mut().unwrap(),
&backend_texture,
skia_safe::gpu::SurfaceOrigin::TopLeft,
color_type,
skia_safe::AlphaType::Unpremul,
color_space,
)
.unwrap(),
)
}
}
pub unsafe fn make_vulkan_context(
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<skia_safe::gpu::DirectContext> {
unsafe {
let vulkan_device = device.as_hal::<wgpu::wgc::api::Vulkan>()?;
let vulkan_queue = queue.as_hal::<wgpu::wgc::api::Vulkan>()?;
let shared_instance = vulkan_device.shared_instance();
// Skia only asks about the instance and device handed to it below, or about the loader
// itself with a null instance. wgpu-hal has those handles in typed form, so use them
// rather than rebuilding them from the raw values Skia passes back.
let get_proc = |of| {
let result = match of {
skia_safe::gpu::vk::GetProcOf::Instance(instance, name) => {
let instance_handle = if instance.is_null() {
Default::default() // VK_NULL_HANDLE
} else {
let handle = shared_instance.raw_instance().handle();
debug_assert_eq!(instance as u64, vk_instance(&vulkan_device));
handle
};
shared_instance.entry().get_instance_proc_addr(instance_handle, name)
}
skia_safe::gpu::vk::GetProcOf::Device(device, name) => {
let device_handle = vulkan_device.raw_device().handle();
debug_assert_eq!(device as u64, vk_device(&vulkan_device));
shared_instance.raw_instance().get_device_proc_addr(device_handle, name)
}
};
match result {
Some(f) => f as _,
None => {
//println!("resolve of {} failed", of.name().to_str().unwrap());
core::ptr::null()
}
}
};
// Skia gates features on the extensions it's told about, and rejects anything it
// considers unsupported: without `VK_KHR_swapchain` in this list it refuses to wrap an
// image that's in `PRESENT_SRC_KHR` layout, which is how wgpu hands out swapchain
// images. Hand it what wgpu actually enabled, no more.
let instance_extensions = cstr_names(shared_instance.extensions());
let device_extensions = cstr_names(vulkan_device.enabled_device_extensions());
// WGPU 29 is locked to vulkan 1.3 and skia assumes the highest vulkan API version of the
// physical device is chosen, causing it to ask for unsupported features/functions.
let backend = vk::BackendContext::new_builder(
vk_instance(&vulkan_device) as _,
vk_physical_device(&vulkan_device) as _,
vk_device(&vulkan_device) as _,
(vk_queue(&vulkan_queue) as _, vulkan_device.queue_family_index() as _),
&get_proc,
Some(vk::Version::new(1, 3, 0)),
)
.with_extensions(
&instance_extensions.iter().map(String::as_str).collect::<Vec<_>>(),
&device_extensions.iter().map(String::as_str).collect::<Vec<_>>(),
)
.build();
skia_safe::gpu::direct_contexts::make_vulkan(&backend, None)
}
}

View File

@ -0,0 +1,306 @@
// 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 rasterizers
use std::pin::Pin;
use std::rc::Rc;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::RendererSealed;
use i_slint_core::window::WindowAdapter;
use crate::{SkiaRenderer, SkiaSharedContext};
/// Use the Skia renderer with WGPU when implementing a custom Slint platform where you want the
/// scene to be rendered into a WGPU texture. The rendering is done using the
/// [Skia](https://skia.org/) library with platform-native GPU acceleration.
///
/// This is the Skia equivalent of `FemtoVGWGPURenderer`, offering superior font rendering
/// quality through platform-native text rasterizers.
///
/// This type is generic over the wgpu version, one instantiation per enabled
/// `unstable-wgpu-*` feature. Use it through the version-specific aliases,
/// `SkiaWGPU29Renderer` for wgpu 29 and `SkiaWGPU30Renderer` for wgpu 30 —
/// they stay unambiguous when several wgpu versions are enabled at once.
///
/// Rendering notifier callbacks registered via
/// [`Window::set_rendering_notifier()`](i_slint_core::api::Window::set_rendering_notifier)
/// will receive [`GraphicsAPI::WGPU29`](i_slint_core::api::GraphicsAPI::WGPU29) (respectively
/// [`GraphicsAPI::WGPU30`](i_slint_core::api::GraphicsAPI::WGPU30)) with the
/// renderer's instance, device, and queue.
pub struct SkiaWGPURendererGeneric<Surface> {
renderer: SkiaRenderer,
_surface: std::marker::PhantomData<Surface>,
}
/// Renders into wgpu 29 textures. Available with the `unstable-wgpu-29` feature;
/// the matching wgpu API types are re-exported in the `slint::wgpu_29` module.
#[cfg(feature = "wgpu-29")]
pub type SkiaWGPU29Renderer = SkiaWGPURendererGeneric<crate::wgpu_29_surface::WGPUSurface>;
/// Renders into wgpu 30 textures. Available with the `unstable-wgpu-30` feature;
/// the matching wgpu API types are re-exported in the `slint::wgpu_30` module.
#[cfg(feature = "wgpu-30")]
pub type SkiaWGPU30Renderer = SkiaWGPURendererGeneric<crate::wgpu_30_surface::WGPUSurface>;
/// Deprecated alias for the newest enabled wgpu version: wgpu 30 when the
/// `unstable-wgpu-30` feature is enabled, wgpu 29 otherwise.
///
/// Use the versioned names, `SkiaWGPU29Renderer` or `SkiaWGPU30Renderer`, instead;
/// they don't change meaning when another `unstable-wgpu-*` feature gets enabled elsewhere
/// in the dependency graph.
#[deprecated(since = "1.18.0", note = "Use `SkiaWGPU29Renderer` or `SkiaWGPU30Renderer` instead")]
#[cfg(feature = "wgpu-30")]
pub type SkiaWGPURenderer = SkiaWGPU30Renderer;
/// Deprecated alias for the newest enabled wgpu version: wgpu 30 when the
/// `unstable-wgpu-30` feature is enabled, wgpu 29 otherwise.
///
/// Use the versioned names, `SkiaWGPU29Renderer` or `SkiaWGPU30Renderer`, instead;
/// they don't change meaning when another `unstable-wgpu-*` feature gets enabled elsewhere
/// in the dependency graph.
#[deprecated(since = "1.18.0", note = "Use `SkiaWGPU29Renderer` or `SkiaWGPU30Renderer` instead")]
#[cfg(all(feature = "wgpu-29", not(feature = "wgpu-30")))]
pub type SkiaWGPURenderer = SkiaWGPU29Renderer;
impl<Surface: crate::Surface + 'static> SkiaWGPURendererGeneric<Surface> {
fn new_with_surface(surface: Surface) -> Self {
let shared_context = SkiaSharedContext::default();
let renderer = SkiaRenderer::new_with_surface(&shared_context, Box::new(surface));
Self { renderer, _surface: std::marker::PhantomData }
}
// SkiaRenderer owns the surface as a trait object; downcast back to the concrete
// type for the WGPU-specific fields and methods that `render_to_texture` needs.
fn surface(&self) -> std::cell::Ref<'_, Surface> {
std::cell::Ref::map(self.renderer.surface.borrow(), |surface| {
surface.as_ref().unwrap().as_any().downcast_ref::<Surface>().unwrap()
})
}
}
// The version-specific constructors and render entry points below are kept in sync manually,
// like the wgpu_29_surface/wgpu_30_surface modules they build on.
#[cfg(feature = "wgpu-29")]
impl SkiaWGPU29Renderer {
/// Creates a new SkiaWGPU29Renderer.
///
/// The `instance`, `adapter`, `device` and `queue` are the WGPU resources used for rendering.
/// The `adapter` is needed to determine the GPU backend and create the Skia graphics context.
///
/// The wgpu resources are also provided to rendering notifier callbacks via
/// [`GraphicsAPI::WGPU29`](i_slint_core::api::GraphicsAPI::WGPU29).
pub fn new(
instance: wgpu_29::Instance,
adapter: wgpu_29::Adapter,
device: wgpu_29::Device,
queue: wgpu_29::Queue,
) -> Result<Self, PlatformError> {
use crate::wgpu_29_surface::{Backend, WGPUSurface};
let backend = Backend::new(&adapter, &device)?;
let gr_context = backend.make_context(&adapter, &device, &queue).ok_or_else(|| {
PlatformError::from("Failed to create Skia graphics context from WGPU")
})?;
Ok(Self::new_with_surface(WGPUSurface::new_offscreen(
instance, adapter, device, queue, backend, gr_context,
)))
}
/// Render the scene to the given texture.
///
/// The texture must have been created with `RENDER_ATTACHMENT` usage and have a supported
/// format. Supported formats depend on the GPU backend: `Rgba8Unorm` and `Rgba8UnormSrgb`
/// are supported on all backends; `Bgra8Unorm` is additionally supported on Metal and Vulkan.
pub fn render_to_texture(&self, texture: &wgpu_29::Texture) -> Result<(), PlatformError> {
let surface = self.surface();
self.renderer.invoke_rendering_notifier_setup(&*surface)?;
let gr_context = &mut surface.gr_context.borrow_mut();
let mut skia_surface =
surface.backend.make_surface(gr_context, texture).ok_or_else(|| {
PlatformError::from("Failed to wrap WGPU texture as Skia render target")
})?;
let window_adapter = self.renderer.window_adapter()?;
let window = window_adapter.window();
self.renderer.render_to_canvas(
skia_surface.canvas(),
0.,
(0., 0.),
Some(gr_context),
0,
Some(&*surface),
window,
None,
);
surface.flush_and_submit(gr_context);
Ok(())
}
}
#[cfg(feature = "wgpu-30")]
impl SkiaWGPU30Renderer {
/// Creates a new SkiaWGPU30Renderer.
///
/// The `instance`, `adapter`, `device` and `queue` are the WGPU resources used for rendering.
/// The `adapter` is needed to determine the GPU backend and create the Skia graphics context.
///
/// The wgpu resources are also provided to rendering notifier callbacks via
/// [`GraphicsAPI::WGPU30`](i_slint_core::api::GraphicsAPI::WGPU30).
pub fn new(
instance: wgpu_30::Instance,
adapter: wgpu_30::Adapter,
device: wgpu_30::Device,
queue: wgpu_30::Queue,
) -> Result<Self, PlatformError> {
use crate::wgpu_30_surface::{Backend, WGPUSurface};
let backend = Backend::new(&adapter, &device)?;
let gr_context = backend.make_context(&adapter, &device, &queue).ok_or_else(|| {
PlatformError::from("Failed to create Skia graphics context from WGPU")
})?;
Ok(Self::new_with_surface(WGPUSurface::new_offscreen(
instance, adapter, device, queue, backend, gr_context,
)))
}
/// Render the scene to the given texture.
///
/// The texture must have been created with `RENDER_ATTACHMENT` usage and have a supported
/// format. Supported formats depend on the GPU backend: `Rgba8Unorm` and `Rgba8UnormSrgb`
/// are supported on all backends; `Bgra8Unorm` is additionally supported on Metal and Vulkan.
pub fn render_to_texture(&self, texture: &wgpu_30::Texture) -> Result<(), PlatformError> {
let surface = self.surface();
self.renderer.invoke_rendering_notifier_setup(&*surface)?;
let gr_context = &mut surface.gr_context.borrow_mut();
let mut skia_surface =
surface.backend.make_surface(gr_context, texture).ok_or_else(|| {
PlatformError::from("Failed to wrap WGPU texture as Skia render target")
})?;
let window_adapter = self.renderer.window_adapter()?;
let window = window_adapter.window();
self.renderer.render_to_canvas(
skia_surface.canvas(),
0.,
(0., 0.),
Some(gr_context),
0,
Some(&*surface),
window,
None,
);
surface.flush_and_submit(gr_context);
Ok(())
}
}
#[doc(hidden)]
impl<Surface> RendererSealed for SkiaWGPURendererGeneric<Surface> {
fn text_layout_cache(
&self,
) -> Option<&i_slint_core::textlayout::sharedparley::TextLayoutCache> {
RendererSealed::text_layout_cache(&self.renderer)
}
fn set_rendering_notifier(
&self,
callback: Box<dyn i_slint_core::api::RenderingNotifier>,
) -> Result<(), i_slint_core::api::SetRenderingNotifierError> {
self.renderer.set_rendering_notifier(callback)
}
fn free_graphics_resources(
&self,
component: i_slint_core::item_tree::ItemTreeRef,
items: &mut dyn Iterator<Item = Pin<i_slint_core::items::ItemRef<'_>>>,
) -> Result<(), PlatformError> {
self.renderer.free_graphics_resources(component, items)
}
fn set_window_adapter(&self, window_adapter: &Rc<dyn WindowAdapter>) {
self.renderer.set_window_adapter(window_adapter)
}
fn window_adapter(&self) -> Option<Rc<dyn WindowAdapter>> {
RendererSealed::window_adapter(&self.renderer)
}
fn resize(&self, size: i_slint_core::api::PhysicalSize) -> Result<(), PlatformError> {
self.renderer.resize(size)
}
fn take_snapshot(
&self,
) -> Result<
i_slint_core::graphics::SharedPixelBuffer<i_slint_core::graphics::Rgba8Pixel>,
PlatformError,
> {
self.renderer.take_snapshot()
}
fn supports_transformations(&self) -> bool {
self.renderer.supports_transformations()
}
}
// Assert the consumer-visible signatures of every renderer name. Building the crate only
// compiles the definitions; these coercions prove the intended calls resolve, in particular
// that the deprecated `SkiaWGPURenderer::new` stays unambiguous with both wgpu features enabled.
#[cfg(test)]
mod signature_tests {
use super::*;
#[cfg(feature = "wgpu-29")]
const _: fn(
wgpu_29::Instance,
wgpu_29::Adapter,
wgpu_29::Device,
wgpu_29::Queue,
) -> Result<SkiaWGPU29Renderer, PlatformError> = SkiaWGPU29Renderer::new;
#[cfg(feature = "wgpu-29")]
const _: fn(&SkiaWGPU29Renderer, &wgpu_29::Texture) -> Result<(), PlatformError> =
SkiaWGPU29Renderer::render_to_texture;
#[cfg(feature = "wgpu-30")]
const _: fn(
wgpu_30::Instance,
wgpu_30::Adapter,
wgpu_30::Device,
wgpu_30::Queue,
) -> Result<SkiaWGPU30Renderer, PlatformError> = SkiaWGPU30Renderer::new;
#[cfg(feature = "wgpu-30")]
const _: fn(&SkiaWGPU30Renderer, &wgpu_30::Texture) -> Result<(), PlatformError> =
SkiaWGPU30Renderer::render_to_texture;
#[cfg(feature = "wgpu-30")]
#[allow(deprecated)]
const _: fn(
wgpu_30::Instance,
wgpu_30::Adapter,
wgpu_30::Device,
wgpu_30::Queue,
) -> Result<SkiaWGPURenderer, PlatformError> = SkiaWGPURenderer::new;
#[cfg(all(feature = "wgpu-29", not(feature = "wgpu-30")))]
#[allow(deprecated)]
const _: fn(
wgpu_29::Instance,
wgpu_29::Adapter,
wgpu_29::Device,
wgpu_29::Queue,
) -> Result<SkiaWGPURenderer, PlatformError> = SkiaWGPURenderer::new;
}