Skip to content

Latest commit

 

History

History
231 lines (212 loc) · 14.7 KB

ARCHITECTURE.md

File metadata and controls

231 lines (212 loc) · 14.7 KB

Architecture

Unofficial; not affiliated with Apple.

English | 简体中文

CrossSwift (crossswift, SwiftPM manifest CrossSwiftUI) separates the platform-independent declarative UI engine from platform backends, AppKit and Apple-framework compatibility shims, and the .xcodeproj build toolchain.

Modules and boundaries

  • SwiftUIRuntime + SwiftUIRuntimeMacros: platform-independent view values, result builders, scoped EnvironmentValues, @State / @AppStorage / @SceneStorage / @Binding / @FocusState / @FocusedValue / @FocusedObject, @Observable (@Bindable) and ObservableObject, compiler macros (@Entry and #Preview over Swift's JSON plugin wire protocol without swift-syntax), element tree, layout engine (with Spacer.minLength, .layoutPriority, layout-preserving .hidden(), and viewport virtualization for LazyVStack/LazyHStack/LazyVGrid/LazyHGrid), sibling diff, controls (DisclosureGroup, Gauge, DatePicker, ColorPicker, AsyncImage, Table, ShareLink, .fileImporter/.fileExporter, .redacted, .refreshable, .swipeActions), navigation (NavigationPath + .navigationDestination), presentations, SVG/PDF vector parsing, embedded SFSymbolCatalog, .xcstrings localization (XCStringsCatalog), multi-segment Path.trimmedPath, rich Canvas, true linear/radial/angular gradients, timed LongPressGesture + gesture arbitration, color/transition/layout animations, retained native-control reconciliation (NativeEngine: NativeRenderer and NativeTreeSession), and shared pure-Swift backend primitives (BackendSupport: Color.argb, flattenScenes, Element paint order & accessibility labels, Path.svgPathData, DrawingMotion, BundleResourceLoader). Imports no NativeAPI, AppKit, browser, or Android APIs.
  • CrossSwiftUI: desktop (NativeAPI) integration for Windows and Linux — WinUIBackend (sole Windows backend over NativeRenderer / CSwiftUIWinUI), GTK4Backend (default Linux backend over NativeRenderer / CSwiftUIGTK4, with opt-out CROSS_SWIFTUI_BACKEND=legacy fallback to LinuxDrawingBackend), centralized backend selection (DesktopBackendSelection), NativeViewBackend, the multi-scene App / WindowGroup / Window / Settings / MenuBarExtra (.menu and .window) / Scene.commands runner (runApp), native window dark/light chrome synchronization, and CrossAppKit + CrossUIKit hosting (NSHostingView, NSHostingController, NSViewRepresentable, NSApplicationDelegateAdaptor, _UIHostingView, UIHostingController, UIHostingConfiguration, UIViewRepresentable, UIViewControllerRepresentable, UIApplicationDelegateAdaptor, plus Color/Font/Image/EdgeInsets ↔ NSColor/UIColor, NSFont/UIFont, NSImage/UIImage, UIEdgeInsets/NSDirectionalEdgeInsets conversions and CombineBridge Published/ObservableObjectPublisher bridging).
  • CSwiftUIWinUI + WinUIHost: C ABI loader and C++/WinRT pure-native WinUI 3 XAML Islands host (CrossSwiftUIWinUI.dll), built via scripts/build-winui3.ps1 and dynamically loaded alongside the executable or from build/winui3-host/Release.
  • CSwiftUIGTK4 + GTK4Host: C ABI loader/IPC bridge and C++ pure-native GTK 4 host (libCrossSwiftUIGTK4.so in-process or CrossSwiftUIGTK4Host isolated child process when NativeAPI links libgtk-3), built via scripts/build-gtk4.sh.
  • CrossAppKit + AppKit + CAppKitWindows: cross-platform AppKit views, controls, windows/panels, menus, status items, TextKit 1/2, pasteboard, workspace (/proc and xdg-open on Linux, Shell/Win32 on Windows), colors/appearances, fonts, images, shared cross-kit primitives (CrossPrimitives: weak boxes, thread keys, font metrics cache, PNG/image header parsing, file-dialog extension normalization), and Carbon global hotkeys over NativeAPI (with Win32/DWM/Shell/COM/Credential Manager/Accessibility glue in CAppKitWindows on Windows). CrossAppKit compiles standalone on macOS for unit tests; AppKit is the import AppKit facade on Windows and Linux.
  • CrossUIKit + UIKit: cross-platform UIKit application & scene lifecycle (UIApplication, UIApplicationDelegate.main(), UIWindowScene, UIWindow), top-left coordinate UIView hierarchy with iterative Auto Layout anchor solving and UIStackView, UIControl + UIAction + UIMenu, native-backed controls (UILabel, UIButton, UITextField, UITextView, UIScrollView), UITableView & UICollectionView with diffable data sources, view controller containers (UIViewController, UINavigationController, UITabBarController, UIAlertController), UITraitCollection, dynamic UIColor, UIFont & UIFontMetrics, UIImage + UIGraphicsImageRenderer + UIBezierPath sharing CrossAppKit's offscreen drawing pipeline, UIPasteboard, UIScreen, and UIDevice. CrossUIKit compiles standalone on macOS for unit tests; UIKit is the import UIKit facade on Windows and Linux.
  • CrossFoundation + framework shims: Apple Foundation extensions missing from swift-corelibs-foundation on Windows/Linux, standalone framework targets (CoreGraphics, full Combine publishers/operators/schedulers, CryptoKit, Carbon, UniformTypeIdentifiers, OSLog, os, SQLite3), and 42 system/framework shim modules under Sources/AppleShims/ (41 Swift framework shims plus CDarwinShims, including QuartzCore, real Security Keychain persistence via Win32 Credential Manager / Linux 0600 XDG keystore, and ServiceManagement login items on Windows and Linux XDG).
  • SwiftUIWeb: WebAssembly (os(WASI)) WindowGroup hosting, DOM/SVG/CSS renderer (including live dark-mode sync, openURL, scrollTo DOM sync, CSS filters, conic/radial/linear gradients, and multi-layer SVG/PDF vectors), and web .xcassets / .xcstrings / SF Symbol loader via JavaScriptKit.
  • SwiftUIAndroid + CSwiftUIAndroid: Android thread-safe JavaVM async bridge (AndroidHost), Choreographer animation loop, dark-mode & openURL sync, and Jetpack Compose host (SwiftUIComposeHost, AndroidStyleRenderers) supporting live switching between Material 3 + Navigation Compose and iOS 27 Liquid Glass styling. See ANDROID.md.
  • SwiftUIHarmony: formal HarmonyOS runtime backend (HarmonyBackend) and parameterized ArkTS host (CrossSwiftUIHost.ets) with async render push, 60 Hz animation ticks, dark-mode sync, rawfile/Resources extraction, and HarmonyOS Native / iOS Liquid Glass dual-style rendering.
  • SwiftUI: user-facing import SwiftUI facade on non-Apple targets, re-exporting Foundation and SwiftUIRuntime together with CrossSwiftUI (+ CrossAppKit, CrossUIKit, CrossFoundation, CoreGraphics) on Windows/Linux, SwiftUIWeb on WASI, SwiftUIAndroid on Android, or SwiftUIHarmony under CROSS_SWIFTUI_HARMONY for HarmonyOS.
  • CrossXcodeBuild + CrossXcodeBuildCLI: pure-Swift .xcodeproj / .xcworkspace parser (ScalarTextScanner, OpenStepPlistParser, XCProjParser), canonical CrossSwift module & shim catalog (CrossSwiftCatalog), Apple-framework & SwiftPM dependency adapter, .xcassets / .xcstrings / .icon / .ico compilers, Windows-safe DirectoryWalker & ToolchainDiscovery, and the xcodebuild CLI driver for Windows, Linux, WebAssembly, HarmonyOS (HarmonyBuilder), and Android (AndroidBuilder).

On macOS, swift build / swift test builds SwiftUIRuntime, CrossAppKit, CrossUIKit, CrossXcodeBuild (xcodebuild), their test suites, and Counter compiled against Apple's native SwiftUI (enforced with -warnings-as-errors in CI). Windows, Linux, WebAssembly, HarmonyOS, and Android builds consume CrossSwift's SwiftUI (and AppKit/UIKit on desktop) facades.

Render pass

  1. Begin state collection. Install stored wrappers by structural path, concrete view type, and property position before evaluating each body.
  2. Track @State and @Observable reads while evaluating bodies and modifiers under scoped EnvironmentValues. A local write invalidates its readers and ancestors; unaffected branches retain their element trees, state, and lifecycle entries. ObservableObject and untracked geometry-state writes invalidate conservatively.
  3. Normalize fragments (preserving explicit IDs and tags), retain both slots of view layers, and resolve inherited foreground, color scheme, disabled, visibility, and alpha values.
  4. Compute layout, evaluate geometry children, hoist presentations, prune state, and assign sibling diff keys. The drawing backends supply native text measurers; deterministic metrics serve headless engine tests.
  5. Diff against the mounted tree, retaining NodeIDs for matched elements. Keys are local to sibling lists; an unchanged sibling order uses a linear path without key dictionaries or move-list scans.
  6. Publish the updated tree and callbacks, send backend commands, then call didRender(root). Rendering guards coalesce writes made during a pass; the Windows bridge batches deferred native notifications from a message turn.

Commands are create, insert, remove, move, setProps, and setFrame. Removing a node disposes its subtree. Actions are looked up by retained NodeID, so a native callback never invokes a stale body closure. Reentrant writes are coalesced into at most eight follow-up render passes.

Windows backend (WinUI 3)

WinUIBackend (in CrossSwiftUI, backed by CSwiftUIWinUI and Sources/WinUIHost) is the sole SwiftUI rendering backend on Windows. It hosts a WinUI 3 DesktopWindowXamlSource (XAML Island) inside NativeAPI's window/view HWND and drives a retained tree of pure-native WinUI 3 controls (TextBlock, Button, TextBox, PasswordBox, ToggleSwitch, Slider, ComboBox, ScrollViewer, ItemsRepeater, Border, Grid, StackPanel, Canvas, Path, Image, Flyout/Popup) through NativeRenderer and NativeTreeSession.

  • Scrolling, inertia, animations, and rounded clipping run natively on Windows' DirectComposition thread.
  • LazyVStack, LazyHStack, LazyVGrid, and LazyHGrid bind visible rows through WinUI 3 ItemsRepeater with O(viewport) native control recycling.
  • CrossSwiftUIWinUI.dll (and Microsoft.WindowsAppRuntime.Bootstrap.dll) are discovered automatically next to the executable, in parent build/winui3-host/Release, or via CROSS_SWIFTUI_WINUI_DLL, and CrossXcodeBuild automatically builds and stages them.
  • App.main configures Per-Monitor V2 DPI awareness before window creation; embedders call WinUIBackend.prepareApplication() and WinUIBackend.setApplicationIdentifier(_:). Offscreen NSImage/UIImage PNG rasterization for tray icons and UIGraphicsImageRenderer lives in CAppKitWindows.

Linux backend (GTK 4 default)

GTK4Backend (in CrossSwiftUI, backed by CSwiftUIGTK4 and Sources/GTK4Host) is the default SwiftUI backend on Linux. It drives pure-native GTK 4 widgets (GtkLabel, GtkButton, GtkEntry, GtkTextView, GtkSwitch, GtkScale, GtkDropDown, GtkScrolledWindow, GtkListView with GtkSignalListItemFactory O(viewport) recycling, GtkPopover, CSS styling, and GSK/Cairo vector drawing) through NativeRenderer and NativeTreeSession.

Because NativeAPI currently links libgtk-3 on Linux (for Flutter compatibility) and GTK 4 forbids loading GTK 3 and GTK 4 in the same process, GTK4Loader.c automatically detects whether libgtk-3 is resident: it launches the isolated CrossSwiftUIGTK4Host child process over a low-latency binary socketpair when GTK 3 is loaded, and loads libCrossSwiftUIGTK4.so in-process otherwise. Set CROSS_SWIFTUI_BACKEND=legacy to opt out to the legacy GTK 3/Cairo LinuxDrawingBackend. See DIVERGENCES.md for platform limits.

State, layout and testing

StateRegistry is process-wide, with state retention and lifecycle ownership isolated per Renderer root so multiple windows, MenuBarExtra hosts, and NSHostingView instances maintain independent @State and .onAppear / .onDisappear / .task lifecycles while sharing @Observable and ObservableObject models. Bindings are get/set closures; focus bindings wrap state. Environment values are saved and restored around subtrees. .id and ForEach identifiers scope both diff identity and stored state. The runtime interns paths by parent and child key, keeping state lookups independent of view depth. Reevaluation retains subscriptions to state values the same view still reads. Published and @Observable writes invalidate observing renderers; StateObject initialization is lazy. Writes from one action or native notification batch are published together. ScrollView retains its stored content when only its internal offset changes. Lifecycle callbacks commit after mounting, and native run-loop timers service tasks plus property and layout animations.

Stack measurement sums main-axis sizes and takes the largest cross-axis size. Padding adds insets; frames constrain and alignment-place a child; layers measure the base view only. Flexible frames and spacers consume remaining proposed space. Custom Layout implementations are probed for axis flexibility rather than assumed to expand horizontally. Measurements are cached by proposal and sizing inputs. Wrapped text and its measured size share a cache across measurement and placement. Rebuilt GeometryReader content keeps layout identities when its sizing inputs match. Placement snapshots copy geometry into the new tree without replacing callbacks or visual properties. Unchanged evaluation revisions reuse mounted subtrees when inherited properties also match: moving them translates their frames, and resizing reflows them. Changed text, fonts, constraints, alignment, scroll offsets, and child identities invalidate the relevant caches. Opaque custom layout/guide closures take the conservative path. Obsolete layout cache entries are reclaimed every eight passes; changing the text measurer or fallback metrics clears them immediately.

The test suites cover runtime layout, diffing, NativeRenderer / NativeTreeSession, multi-window state isolation, environment scope, observation, controls/containers, CrossAppKit & CrossUIKit shims, CrossXcodeBuild project parsing/adaptation, machine-enforced architectural invariants (ArchitectureGovernanceTests: catalog/manifest lockstep, import boundaries, bilingual doc parity, Windows-safe directory/environment rules, and swift-corelibs-xctest @MainActor test discipline), CrossSwiftUITests (WinUI 3 & GTK 4 pure-native backends), non-macOS framework shims (CrossShimsTests), and COMPAT.md symbol verification (COMPATTests). Counter --smoke opens a real window and exits after three seconds to exercise the native application loop.