Skip to content

Add native Apple Graphite views to SkiaSharp.Views - #4745

Closed
mattleibow wants to merge 6 commits into
mainfrom
mattleibow-apple-native-graphite-views
Closed

mattleibow wants to merge 6 commits into
mainfrom
mattleibow-apple-native-graphite-views

Conversation

@mattleibow

@mattleibow mattleibow commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds SKGraphiteMetalView to the existing SkiaSharp.Views package as an Apple-native alternative to SKMetalView, plus native Basic sample tabs for iOS, Mac Catalyst, macOS, and tvOS.

The view uses Graphite APIs already available on main: it wraps the current Metal drawable, creates a Graphite surface, inserts recordings, submits, and presents through one Metal queue. SKPaintGraphiteSurfaceEventArgs.CreateRecorder(...) and InsertRecording(...) expose Graphite's multi-recorder model without new native interop.

The sample demonstrates that model rather than benchmarking it. Four worker threads exclusively own independent Recorders and offscreen surfaces. They prepare content update N+1 while the view/context thread composes and presents the last complete update N. Producer Recordings are inserted before the presentation Recording.

flowchart LR
    W1[Worker Recorder 1] --> R1[Recording 1]
    W2[Worker Recorder 2] --> R2[Recording 2]
    W3[Worker Recorder 3] --> R3[Recording 3]
    W4[Worker Recorder 4] --> R4[Recording 4]
    R1 --> C[View / Context thread]
    R2 --> C
    R3 --> C
    R4 --> C
    C --> P[Compose latest images]
    P --> S[Snap, insert, submit]
    S --> M[One ordered Metal queue]
Loading

This parallelizes CPU command preparation, analogous to Metal parallel command encoding; it does not claim multiple Metal queues or unordered GPU execution. The view owns drawable presentation while applications choose how to partition independent visual roots.

Recovery follows Apple and Skia guidance:

  • Apple documents MTLDevice and MTLCommandQueue as long-lived, thread-safe objects. A failed command buffer is terminal to that buffer, not automatically to its queue/device. Nil drawables are skipped. See MTLCommandQueue, MTLCommandBuffer status, completion handlers, and MTKView currentDrawable.
  • Skia documents InvalidRecording and PromiseInstantiationFailed as making no command-buffer changes. AddCommandsFailed and AsyncShaderCompilesFailed leave Graphite state unrecoverable/unknown; submission failure is conservatively treated the same. OutOfOrderRecording remains visible so callers can repair known ordering mistakes.
  • Any abandoned frame discards its presentation Recorder so commands targeting an old CAMetalDrawable cannot leak into a later frame. If external Recordings were already inserted, the Context is also recreated because pending work cannot be rolled back.
  • Fatal Graphite failures pause and notify before Context recreation. The app disposes worker-owned Recorders, then Retry unpauses the view. Ordinary recovery preserves Apple's long-lived Metal device/queue; device changes, removal, or access revocation rebuild the full backend and use preferredDevice on macOS when available.
  • iOS, Mac Catalyst, and tvOS pause on application deactivation, release drawables on backgrounding, and resume only if previously running. Expected background notPermitted errors are not surfaced as renderer failures.
  • Presentation command-buffer completion is checked on Apple's driver callback and marshalled to the main thread. Skia's private Graphite command buffer cannot yet expose asynchronous errors without additional native interop, so this PR does not claim to observe those errors.

This PR remains independent of #4729 and mono/skia#345. It adds no Android or MAUI implementation, native Skia change, C API, generated binding, or deferred-canvas API.

Related issues

Related to #4734 and informed by #4885. API documentation is tracked by mono/SkiaSharp-API-docs#214.

Required skia PR

None. This PR uses Graphite APIs already present on main.

Areas affected

  • Managed API (binding/)
  • Native / C API (externals/skia/src/c, include/c)
  • Generated P/Invoke bindings
  • Native dependency or Skia update (libpng, HarfBuzz, FreeType, zlib, milestone bump, …)
  • Views & integrations (MAUI, Uno, WPF, WinUI, Blazor, …)
  • Rendering output / visual behavior
  • Performance
  • Tests
  • Build, packaging, or CI
  • Documentation or samples

Changes

Public API

Added to SkiaSharp.Views.iOS for iOS/Mac Catalyst, SkiaSharp.Views.Mac for macOS, and SkiaSharp.Views.tvOS for tvOS:

public class SKGraphiteMetalView : MTKView, IMTKViewDelegate, IComponent
public SKGraphiteMetalView();
public SKGraphiteMetalView(CGRect frame);
public SKGraphiteMetalView(CGRect frame, IMTLDevice device);
public SKGraphiteMetalView(IntPtr handle);
public SKSize CanvasSize { get; }
public SKGraphiteContext? GraphiteContext { get; }
public event EventHandler<SKPaintGraphiteSurfaceEventArgs>? PaintSurface;
public event EventHandler<SKGraphiteRenderFailedEventArgs>? RenderFailed;

public class SKPaintGraphiteSurfaceEventArgs : EventArgs
public SKPaintGraphiteSurfaceEventArgs(SKSurface surface, SKGraphiteBackendTexture backendTexture, SKGraphiteContext context, SKImageInfo info);
public SKPaintGraphiteSurfaceEventArgs(SKSurface surface, SKGraphiteBackendTexture backendTexture, SKGraphiteContext context, SKImageInfo info, SKImageInfo rawInfo);
public SKSurface Surface { get; }
public SKGraphiteBackendTexture BackendTexture { get; }
public SKGraphiteContext Context { get; }
public SKColorType ColorType { get; }
public SKImageInfo Info { get; }
public SKImageInfo RawInfo { get; }
public SKGraphiteRecorder? CreateRecorder();
public SKGraphiteRecorder? CreateRecorder(long recorderBudgetBytes);
public SKGraphiteInsertStatus InsertRecording(SKGraphiteRecording recording);

public sealed class SKGraphiteRenderFailedEventArgs : EventArgs
public SKGraphiteRenderFailedEventArgs(Exception exception);
public SKGraphiteRenderFailedEventArgs(Exception exception, bool requiresContextRecreation);
public Exception Exception { get; }
public bool RequiresContextRecreation { get; }

Behavior

  • Worker Recorders are caller-owned and thread-affine; completed Recordings return to the view/Context thread for insertion.
  • Failure notification occurs before recreation so dependent Recorders can be disposed safely.
  • Retry preserves healthy Metal state, replaces invalid Graphite state, and starts with an empty presentation Recorder.
  • Application lifecycle, drawable release, command-buffer completion errors, device changes, and supported OS gates follow Apple platform guidance.
  • The Basic tabs pipeline four independent roots and show only FPS/failure status rather than redundant backend branding.

Testing

  • Rebased onto origin/main f74bd9adb82a77fd4a423db03c1077ea9d3be7e7; validated with .NET SDK 10.0.400.
  • SkiaSharp.Views built for all eight net9/net10 Apple TFMs.
  • Full SkiaSharp.Views pack passed; new APIs are present in all eight Apple assemblies and absent from Android assemblies.
  • api-tools api-info passed for all eight Apple assemblies, including both failure constructors and RequiresContextRecreation.
  • Native Basic builds passed for iossimulator-arm64, maccatalyst-arm64, osx-arm64, and tvossimulator-arm64. ValidateXcodeVersion=false was needed because the pinned workload requests Xcode 26.0 while the host has Xcode 26.6.
  • iOS simulator rendered four independently recorded roots at 60 FPS, survived background/foreground, resumed cleanly, and produced no render failure.
  • samples-generate passed and retained the shared GraphiteSceneRenderer link in all four generated Apple projects.
  • GPT-5.6 Sol and Claude Opus 4.8 independently reviewed the implementation against official Apple Metal/MetalKit guidance and authoritative Skia Graphite source. Their common findings—partial insertion rollback, autorelease-pool lifetime, command-buffer completion handling, application lifecycle, device changes/removal, platform gates, recovery signaling, and teardown ordering—were implemented. Both considered the revised design ready after correcting the access-revoked code to the current .NET binding's Blacklisted value.
  • Final required console suite: singleton 1/1, Vulkan 4 passed/21 policy skips, Direct3D 2 passed/3 policy skips, and core 6,134 passed/23 skipped. Two transient ownership tests passed focused reruns; the remaining failure is the pre-existing ganesh-gl/DiagonalLines macOS golden mismatch (1,832 pixels versus 1,310 allowed), unchanged from the main baseline.
  • The prior foundation revision passed Azure build 1573135 end-to-end, including Samples Windows/macOS/Linux. Fresh CI for the current hardening revision is pending.
  • git diff --check passed. The final diff contains no Android, MAUI, externals/skia, generated binding, standalone package, or Add Graphite presentation interop #4729-only content.
iOS simulator: pipelined Graphite Recorders

The native iOS Basic sample composing four independently recorded Graphite visual roots at 60 FPS

Checklist

  • Tests added or updated (Apple TFM/package/API matrix, four native builds, generated-sample validation, lifecycle/runtime check)
  • Changes above lists all public API and behavioral changes (or "None.")
  • New/changed public API? Updated Document Apple Graphite view APIs SkiaSharp-API-docs#214
  • Native change? Not applicable — no native change, companion mono/skia PR, or binding regeneration is required

@github-actions

Copy link
Copy Markdown
Contributor

📦 Try the packages from this PR

Warning

Do not run these scripts without first reviewing the code in this PR.

Step 1 — Download the packages

bash / macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 4745

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 4745"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-4745/packages --name skiasharp-pr-4745
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-4745

@mattleibow

Copy link
Copy Markdown
Contributor Author

Parallel dependency track: Graphite presentation/multi-recorder interop remains in #4729 and mono/skia#345. This Apple-native PR intentionally has no dependency on either. After both foundations land, Apple MAUI and Android native work will proceed independently.

@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been deployed and is available at:

🔗 View Staging Site
🔗 View Staging Docs
🔗 View Staging Gallery (Blazor)
🔗 View Staging Gallery (Uno Platform)
🔗 View Staging SkiaFiddle

This preview will be updated automatically when you push new commits to this PR.


This comment is automatically updated by the documentation staging workflow.

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #4745

No ⭐ source-build (pr) benchmark results were produced for this run, so there is nothing to compare yet. The source-build legs are best-effort and may be skipped (native unchanged) or may have failed — see the run for details.

📈 View the benchmark run & perf-dashboard artifact →

@github-actions

github-actions Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

📦 Artifact size report

Packages from this PR (build 1573395) vs the latest nightly baseline 4.152.0-nightly.47 (observed 2026-08-28).

Total .nupkg size: 569.6 MB → 569.3 MB (−377.7 KB, -0.1%)

Packages

⚠️ marks growth over 500.0 KB or 2%. Changes under 50.0 KB are treated as noise.

Package baseline this PR Δ Δ%
SkiaSharp.NativeAssets.WinUI 109.1 MB 108.5 MB 🟢 −577.1 KB -0.5%
SkiaSharp.NativeAssets.WebAssembly 69.7 MB 69.7 MB 🔴 +84.9 KB +0.1%

+39 package(s) unchanged (< 50.0 KB).

Per-file changes

SkiaSharp.NativeAssets.WinUI

File Size
runtimes/win-arm64/native/libGLESv2.pdb 64.5 MB → 64.4 MB (🟢 −96.0 KB)
runtimes/win-x64/native/libGLESv2.pdb 66.6 MB → 66.6 MB (🟢 −80.0 KB)
runtimes/win-x86/native/libGLESv2.pdb 67.3 MB → 67.2 MB (🟢 −80.0 KB)

Informational only — this never blocks the PR. Native binaries are labelled by os/arch.

@mattleibow
mattleibow force-pushed the mattleibow-apple-native-graphite-views branch from 7afc5b3 to 512f530 Compare August 28, 2026 20:24
@mattleibow mattleibow changed the title Add native Apple Graphite views and samples Add native Apple Graphite views to SkiaSharp.Views Aug 28, 2026
Copilot AI added 3 commits August 29, 2026 01:07
Introduce the Apple-only SkiaSharp.Views.Graphite package with Metal-backed iOS, Mac Catalyst, macOS, and tvOS controls and native Basic sample pages. Keep the layer independent from the pending Graphite presentation interop, Android, MAUI, and mono/skia changes.

Co-authored-by: Copilot App <[email protected]>
Ship the Apple Graphite control in the existing platform view assemblies instead of creating a separate package. Make initialization transactional, contain unhandled render failures inside MetalKit callbacks, and use the bound Metal capability API.

Co-authored-by: Copilot App <[email protected]>
Make the Apple Graphite sample pipeline independent visual roots through worker-owned Recorders while the view presents the last completed update. Add event-args helpers that create correctly cached Recorders and insert recordings through the view's context bookkeeping.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 705e7540-cc61-4a7d-b4ae-2c93138c031b
@mattleibow
mattleibow force-pushed the mattleibow-apple-native-graphite-views branch from 512f530 to 791aa94 Compare August 29, 2026 00:04
Copilot AI added 3 commits August 29, 2026 02:14
Let the event args call the Context directly and report unrecoverable insertion state back to the view after painting, avoiding a per-frame delegate while preserving safe disposal behavior.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 705e7540-cc61-4a7d-b4ae-2c93138c031b
Preserve Apple's long-lived Metal queue while rebuilding Graphite state after fatal insertion or submission failures. Discard an abandoned presentation Recorder before retrying, notify before recreation, and let the samples dispose worker state before an explicit retry.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 705e7540-cc61-4a7d-b4ae-2c93138c031b
Follow Apple Metal guidance for drawable release, application suspension, command-buffer error reporting, and long-lived device/queue ownership. Follow Skia recovery semantics for partial recording insertion, abandoned presentation work, and Graphite Context recreation.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 705e7540-cc61-4a7d-b4ae-2c93138c031b
@mattleibow

Copy link
Copy Markdown
Contributor Author

Superseded for iOS/Mac Catalyst by #5329, which adds engine-named native SKGraphiteView/SKGaneshView containers plus MAUI controls, typed contexts, tracked producer recordings, lifecycle/readback coverage, and Android presentation. Its prerequisite interop remains separately reviewable in #4729 and mono/skia#345.

The replacement is intentionally draft pending Windows/producing-build acceptance and the independently reproduced main GL golden blocker. Its iOS/Mac Catalyst device suites pass with real pixels and zero skips.

This closure does not discard the unported macOS/tvOS native implementation in this PR. The source and branch mattleibow-apple-native-graphite-views are preserved here as prior art for a separate follow-up; no branch is deleted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants