From 9ac3ac6de0dcecf9a6cea35e4dbb41f934ebc6a3 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Fri, 13 Nov 2026 19:21:13 +0800 Subject: [PATCH 1/3] Extend SwiftUI compatibility and render Windows controls at native DPI Add generic layout, styling, state, input and presentation APIs. Keep stable node identities across Grid relayout, reuse unchanged subtrees and scroll pixels, and publish Windows drawing through nativeapi view updates. --- .github/workflows/ci.yml | 12 +- Package.swift | 79 +- README.md | 85 +- Sources/CSwiftUIWindows/Drawing.cpp | 1845 +++++++++++++++++ Sources/CSwiftUIWindows/FrameTrace.h | 119 ++ .../CSwiftUIWindows/include/SwiftUIWindows.h | 92 + Sources/SwiftUIPort/AppRunner.swift | 72 +- Sources/SwiftUIPort/NativeViewBackend.swift | 24 +- Sources/SwiftUIPort/VectorImage.swift | 199 ++ .../SwiftUIPort/WindowsDrawingBackend.swift | 745 +++++++ Sources/SwiftUIRuntime/Backend.swift | 50 +- Sources/SwiftUIRuntime/Binding.swift | 11 + Sources/SwiftUIRuntime/ButtonStyle.swift | 34 + Sources/SwiftUIRuntime/Color.swift | 16 +- Sources/SwiftUIRuntime/ContainerViews.swift | 350 ++++ Sources/SwiftUIRuntime/Diff.swift | 24 +- Sources/SwiftUIRuntime/Element.swift | 249 ++- Sources/SwiftUIRuntime/Environment.swift | 56 +- Sources/SwiftUIRuntime/EvaluationGraph.swift | 142 ++ .../SwiftUIRuntime/ExtendedModifiers.swift | 187 ++ Sources/SwiftUIRuntime/Geometry.swift | 42 +- Sources/SwiftUIRuntime/GeometrySnapshot.swift | 31 + Sources/SwiftUIRuntime/Graphics.swift | 315 +++ Sources/SwiftUIRuntime/Input.swift | 219 ++ Sources/SwiftUIRuntime/Layout.swift | 819 ++++++-- Sources/SwiftUIRuntime/Lifecycle.swift | 113 + Sources/SwiftUIRuntime/Modifiers.swift | 134 +- Sources/SwiftUIRuntime/Observation.swift | 98 + Sources/SwiftUIRuntime/Preference.swift | 176 ++ Sources/SwiftUIRuntime/Presentation.swift | 149 ++ Sources/SwiftUIRuntime/Primitives.swift | 101 +- Sources/SwiftUIRuntime/Renderer.swift | 455 +++- Sources/SwiftUIRuntime/Scene.swift | 65 +- Sources/SwiftUIRuntime/State.swift | 151 +- Sources/SwiftUIRuntime/Styles.swift | 210 ++ Sources/SwiftUIRuntime/View.swift | 64 +- Sources/SwiftUIRuntime/ViewBuilder.swift | 34 +- .../DrawingProbe.cpp | 300 +++ .../ScrollProbe.cpp | 117 ++ .../include/DrawingProbe.h | 21 + .../FullRuntimeTests.swift | 89 + .../IncrementalRenderingTests.swift | 552 +++++ .../SwiftUIRuntimeTests/StyledViewTests.swift | 187 ++ Tests/SwiftUIRuntimeTests/TestSupport.swift | 17 +- .../WindowsDrawingTests.swift | 45 + docs/ARCHITECTURE.md | 373 ++-- docs/COMPAT.md | 197 +- docs/DIVERGENCES.md | 250 +-- 48 files changed, 8598 insertions(+), 1117 deletions(-) create mode 100644 Sources/CSwiftUIWindows/Drawing.cpp create mode 100644 Sources/CSwiftUIWindows/FrameTrace.h create mode 100644 Sources/CSwiftUIWindows/include/SwiftUIWindows.h create mode 100644 Sources/SwiftUIPort/VectorImage.swift create mode 100644 Sources/SwiftUIPort/WindowsDrawingBackend.swift create mode 100644 Sources/SwiftUIRuntime/ButtonStyle.swift create mode 100644 Sources/SwiftUIRuntime/ContainerViews.swift create mode 100644 Sources/SwiftUIRuntime/EvaluationGraph.swift create mode 100644 Sources/SwiftUIRuntime/ExtendedModifiers.swift create mode 100644 Sources/SwiftUIRuntime/GeometrySnapshot.swift create mode 100644 Sources/SwiftUIRuntime/Graphics.swift create mode 100644 Sources/SwiftUIRuntime/Input.swift create mode 100644 Sources/SwiftUIRuntime/Lifecycle.swift create mode 100644 Sources/SwiftUIRuntime/Observation.swift create mode 100644 Sources/SwiftUIRuntime/Preference.swift create mode 100644 Sources/SwiftUIRuntime/Presentation.swift create mode 100644 Sources/SwiftUIRuntime/Styles.swift create mode 100644 Tests/CSwiftUIWindowsTestSupport/DrawingProbe.cpp create mode 100644 Tests/CSwiftUIWindowsTestSupport/ScrollProbe.cpp create mode 100644 Tests/CSwiftUIWindowsTestSupport/include/DrawingProbe.h create mode 100644 Tests/SwiftUIRuntimeTests/FullRuntimeTests.swift create mode 100644 Tests/SwiftUIRuntimeTests/IncrementalRenderingTests.swift create mode 100644 Tests/SwiftUIRuntimeTests/StyledViewTests.swift create mode 100644 Tests/WindowsDrawingTests/WindowsDrawingTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68903ac..1123eff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,11 +8,11 @@ on: permissions: contents: read -# The nativeapi Swift binding carries Linux/Windows support on main -# (libnativeapi/nativeapi#33). +# Pin the workspace revision that exposes view update batching and scheduling. +# See libnativeapi/nativeapi#34. env: NATIVEAPI_REPOSITORY: libnativeapi/nativeapi - NATIVEAPI_REF: main + NATIVEAPI_REF: c6f38de82db51582bd01cdd7024df105cb86c439 jobs: runtime-macos: @@ -126,10 +126,10 @@ jobs: run: swift --version - name: Build - run: swift build + run: swift build --build-system native - name: Test - run: swift test + run: swift test --build-system native - name: Smoke test - run: swift run Counter --smoke + run: swift run --build-system native Counter --smoke diff --git a/Package.swift b/Package.swift index 12302fa..fec5dec 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,6 @@ // swift-tools-version:5.9 + +import Foundation import PackageDescription // SwiftUIPort — a declarative SwiftUI-shaped API over nativeapi's native views. @@ -20,37 +22,63 @@ import PackageDescription // a path dependency: this project is not published to a package registry. #if os(macOS) -let packageDependencies: [Package.Dependency] = [] + let packageDependencies: [Package.Dependency] = [] #else -let packageDependencies: [Package.Dependency] = [ - .package(name: "NativeAPI", path: "../nativeapi/bindings/swift") -] + let packageDependencies: [Package.Dependency] = [ + .package( + name: "NativeAPI", + path: ProcessInfo.processInfo.environment["NATIVEAPI_SWIFT_PATH"] + ?? "../nativeapi/bindings/swift") + ] #endif var targets: [Target] = [ - .target(name: "SwiftUIRuntime") + .target( + name: "SwiftUIRuntime", + linkerSettings: [ + // Deep declarative view trees exceed Windows' 1 MiB default in debug builds. + .unsafeFlags(["-Xlinker", "/STACK:16777216"], .when(platforms: [.windows])) + ]) ] +#if os(Windows) + targets.append( + .target( + name: "CSwiftUIWindows", dependencies: [.product(name: "CNativeAPI", package: "NativeAPI")], + publicHeadersPath: "include", + linkerSettings: [.linkedLibrary("gdiplus"), .linkedLibrary("comctl32")])) + let drawingDependencies: [Target.Dependency] = ["CSwiftUIWindows"] + targets.append( + .target( + name: "CSwiftUIWindowsTestSupport", dependencies: ["CSwiftUIWindows"], + path: "Tests/CSwiftUIWindowsTestSupport", publicHeadersPath: "include")) + targets.append( + .testTarget( + name: "WindowsDrawingTests", dependencies: ["CSwiftUIWindowsTestSupport", "SwiftUIPort"])) +#else + let drawingDependencies: [Target.Dependency] = [] +#endif + #if !os(macOS) -targets += [ - .target( - name: "SwiftUIPort", - dependencies: [ - "SwiftUIRuntime", - .product(name: "NativeAPI", package: "NativeAPI"), - ] - ), - .target( - name: "SwiftUI", - dependencies: ["SwiftUIRuntime", "SwiftUIPort"] - ), -] + targets += [ + .target( + name: "SwiftUIPort", + dependencies: [ + "SwiftUIRuntime", + .product(name: "NativeAPI", package: "NativeAPI"), + ] + drawingDependencies + ), + .target( + name: "SwiftUI", + dependencies: ["SwiftUIRuntime", "SwiftUIPort"] + ), + ] #endif #if os(macOS) -let counterDependencies: [Target.Dependency] = [] + let counterDependencies: [Target.Dependency] = [] #else -let counterDependencies: [Target.Dependency] = ["SwiftUI"] + let counterDependencies: [Target.Dependency] = ["SwiftUI"] #endif targets.append( @@ -60,27 +88,24 @@ targets.append( path: "Examples/Counter" ) ) - targets.append( .testTarget( name: "SwiftUIRuntimeTests", dependencies: ["SwiftUIRuntime"] ) ) - var products: [Product] = [ .library(name: "SwiftUIRuntime", targets: ["SwiftUIRuntime"]) ] #if !os(macOS) -products += [ - .library(name: "SwiftUIPort", targets: ["SwiftUIPort"]), - .library(name: "SwiftUI", targets: ["SwiftUI"]), -] + products += [ + .library(name: "SwiftUIPort", targets: ["SwiftUIPort"]), + .library(name: "SwiftUI", targets: ["SwiftUI"]), + ] #endif products.append(.executable(name: "Counter", targets: ["Counter"])) - let package = Package( name: "SwiftUIPort", platforms: [.macOS(.v11)], diff --git a/README.md b/README.md index b346e8f..b21b717 100644 --- a/README.md +++ b/README.md @@ -47,30 +47,22 @@ against Apple's SwiftUI. ## What this is -The engine keeps SwiftUI's authoring model — a `View` protocol with `body`, -`@ViewBuilder`, `@State`/`@Binding`, stacks, modifiers and `WindowGroup` — and -turns it into native control creation, insertion, removal, property updates and -reordering. There is no custom drawing layer and no widget reimplementation: -`Text` is a native label, `Button` is a native button, and stacks are native -containers. - -The important consequence is stated up front: **the visual result is not -identical to Apple SwiftUI.** nativeapi provides native desktop controls and a -row/column layout engine; it has no drawing API, no animation system, no -variable fonts and no rich text. See [docs/DIVERGENCES.md](docs/DIVERGENCES.md) -before judging a screenshot against SwiftUI. - -## What this is not - -- Not a reimplementation of SwiftUI's renderer, layout system or animation. -- Not a source-level port: no Apple SwiftUI code is used or copied. -- Not a macOS port. macOS already has SwiftUI; the port itself targets Windows - and Linux. The Counter example still builds on macOS, against Apple's SwiftUI, - as the same-source reference. -- Not an embedded web view or a Flutter-like render engine. Real platform - controls are used. -- Not a complete SwiftUI. The v0.1 symbol set is in - [docs/COMPAT.md](docs/COMPAT.md); everything else is explicitly missing. +The engine keeps SwiftUI's authoring model: value views, builders, state, +bindings, scoped environment, modifiers and WindowGroup. Windows adds generic +text/shape/layer drawing on a nativeapi window, including custom ButtonStyle +labels. Buttons retain native handles, activation, focus and accessible names. +Linux retains the native label/button/stack backend. + +This is a **partial compatibility layer**. It contains no host application's +components, themes or tokens. It is not Apple's source or renderer, and does +not promise pixel equality. Custom drawing currently requires Windows; +the Windows backend supplies scrolling, vector images, native text editing, +popovers, gestures and basic animation. It remains smaller than Apple SwiftUI. +Read [docs/COMPAT.md](docs/COMPAT.md) and +[docs/DIVERGENCES.md](docs/DIVERGENCES.md) before adopting an API. + +The port targets Windows and Linux. macOS applications and the Counter +reference example use Apple's SwiftUI; runtime tests also build on macOS. ## Requirements @@ -80,7 +72,8 @@ before judging a screenshot against SwiftUI. The package itself remains in language mode 5. - A [nativeapi](https://github.com/libnativeapi/nativeapi) checkout with the Swift binding's platform support. The package consumes it as a **sibling path - dependency** at `../nativeapi/bindings/swift`: + dependency** at `../nativeapi/bindings/swift`, or the path in + `NATIVEAPI_SWIFT_PATH`: ```text Projects/ @@ -88,11 +81,11 @@ before judging a screenshot against SwiftUI. └── swiftui-port/ ``` - The Swift binding's Linux/Windows support landed in - [libnativeapi/nativeapi#33](https://github.com/libnativeapi/nativeapi/pull/33), - so a current `main` checkout is enough. macOS builds `SwiftUIRuntime` for its - tests and the Counter example against Apple's SwiftUI; it does not need - nativeapi. + The Windows backend requires the view batching and update scheduling APIs + in [libnativeapi/nativeapi#34](https://github.com/libnativeapi/nativeapi/pull/34). + Use the nativeapi revision pinned in `.github/workflows/ci.yml` or a revision + that includes those APIs. macOS builds `SwiftUIRuntime` for its tests and the + Counter example against Apple's SwiftUI without a nativeapi dependency. - Linux: `pkg-config`, `libgtk-3-dev`, `libx11-dev`, `libxi-dev` (the binding gets its flags from pkg-config; no `unsafeFlags`). - Windows: the official Swift toolchain with the Visual Studio build tools the @@ -119,6 +112,21 @@ swift test swift run Counter ``` +For the verified Windows source-build path (Swift 6.4.2, MSVC and Windows SDK), +prepare nativeapi's source symlink and use the SwiftPM native builder: + +```powershell +$env:NATIVEAPI_SWIFT_PATH = 'C:/src/nativeapi/bindings/swift' +& "$env:NATIVEAPI_SWIFT_PATH/scripts/prepare-windows.ps1" +swift build --build-system native +swift test --build-system native +swift run --build-system native Counter --smoke +``` + +Enable Windows Developer Mode if Git checked the core symlink out as a text +file. Initialize nativeapi's `core` submodule first. Swift 6.4 warns that the +native builder is deprecated; the commands above record the tested builder. + On Windows and Linux, `swift run Counter --smoke` opens the window and asks the port's runner to quit a few seconds later; CI uses it to prove the window, event loop and renderer start. The window can also be closed normally. macOS runs the @@ -128,7 +136,8 @@ example under Apple's SwiftUI, where the flag has no special meaning. ``` Sources/SwiftUIRuntime/ view protocol, element tree, layout, diff, state -Sources/SwiftUIPort/ NativeViewBackend + App/WindowGroup runner +Sources/SwiftUIPort/ WindowsDrawingBackend, NativeViewBackend, app runner +Sources/CSwiftUIWindows/ generic GDI+ display list and native button bridge Sources/SwiftUI/ facade: `import SwiftUI` Examples/Counter/ the README program Tests/SwiftUIRuntimeTests FakeBackend assertions for layout, diff and state @@ -142,14 +151,12 @@ SwiftUI, and on Windows/Linux it compiles against the port's facade. ## Design in one paragraph -A render pass evaluates `body` into an `Element` tree, resolves inherited -foreground/disabled values, assigns diff keys (explicit `.id` or structural -position), and runs a reference layout. The diff compares that tree with the -mounted one and emits only the commands needed: `create`, `insert`, `remove`, -`move`, `setProps`, `setFrame`. `NativeViewBackend` applies those commands to -nativeapi views; `FakeBackend` records them so the engine is testable on macOS. -Details and the nativeapi mapping table are in -[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). +A render pass evaluates bodies under scoped environment/state, resolves +inherited properties, lays out the tree and diffs sibling identity. Backends +receive incremental commands and the complete tree after diffing. Windows +publishes a retained display list and updates native buttons using those +frames; Linux applies nativeapi layout properties. FakeBackend records commands +for platform-independent tests. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). ## Compatibility diff --git a/Sources/CSwiftUIWindows/Drawing.cpp b/Sources/CSwiftUIWindows/Drawing.cpp new file mode 100644 index 0000000..75c7476 --- /dev/null +++ b/Sources/CSwiftUIWindows/Drawing.cpp @@ -0,0 +1,1845 @@ +#include "SwiftUIWindows.h" +#include +#include + +#include +#include +#include +using std::max; +using std::min; +#include +#include +#include +#include +#include +#include +#include +#include "FrameTrace.h" + +namespace { +using namespace Gdiplus; +constexpr UINT_PTR subclass_id = 0x53554950; +constexpr UINT deferred_input = WM_APP + 581; +struct Command { + int kind = 0; // shape, text, clip, restore + RectF rect; + float radius = 0, stroke_width = 0, size = 14, weight = 400, line_spacing = 0; + uint32_t fill = 0, stroke = 0; + std::wstring text, family; + std::vector path; + std::vector colors; + PointF start, end; + size_t clip_end = 0; + bool operator==(const Command &c) const { + return kind == c.kind && rect.Equals(c.rect) && radius == c.radius && + stroke_width == c.stroke_width && size == c.size && + weight == c.weight && line_spacing == c.line_spacing && + fill == c.fill && stroke == c.stroke && text == c.text && + family == c.family && path == c.path && colors == c.colors && + start.X == c.start.X && start.Y == c.start.Y && end.X == c.end.X && + end.Y == c.end.Y; + } +}; +struct ButtonHook { + int64_t id; + bool custom_draw; + bool hovered = false; + std::wstring help; + RECT clip{}; + int clip_width = -1, clip_height = -1, clip_radius = -1; + bool tab_visible = true; +}; +struct EditHook { + int64_t id; + HFONT font = nullptr; + HBRUSH brush = nullptr; + COLORREF foreground = 0, background = RGB(255, 255, 255); + bool updating = false; + std::wstring fontKey; +}; +struct Framebuffer { + UINT width, height; + HDC dc = CreateCompatibleDC(nullptr); + HBITMAP dib = nullptr; + HGDIOBJ previous = nullptr; + std::unique_ptr bitmap; + Framebuffer(UINT w, UINT h) : width(w), height(h) { + void *pixels = nullptr; + BITMAPINFO info{}; + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biWidth = LONG(w); + info.bmiHeader.biHeight = -LONG(h); + info.bmiHeader.biPlanes = 1; + info.bmiHeader.biBitCount = 32; + info.bmiHeader.biCompression = BI_RGB; + dib = CreateDIBSection(dc, &info, DIB_RGB_COLORS, &pixels, nullptr, 0); + previous = SelectObject(dc, dib); + bitmap = std::make_unique(w, h, INT(w * 4), PixelFormat32bppPARGB, + static_cast(pixels)); + } + ~Framebuffer() { + bitmap.reset(); + SelectObject(dc, previous); + DeleteObject(dib); + DeleteDC(dc); + } +}; +struct TextFont { + FontFamily family; + Font font; + TextFont(const Command &c) + : family(c.family.c_str()), + font(family.GetLastStatus() == Ok ? &family + : FontFamily::GenericSansSerif(), + c.size, c.weight >= 600 ? FontStyleBold : FontStyleRegular, + UnitPixel) {} +}; +struct ControlContext { + HWND parent; + double origin_x, origin_y; + int x, y; +}; +struct ControlGroup { + HWND viewport, window; +}; +struct ScrollDrawing { + int64_t id, revision; + RectF viewport; + double x, y; + size_t begin, end = 0; +}; +struct ScrollCopy { + RECT destination{}; + int dx = 0, dy = 0; + RECT repaint{}; +}; +struct Surface { + HWND host; + sui_event_callback callback; + void *context; + std::vector commands; + std::vector pending; + std::unique_ptr buffer; + bool buffer_dirty = true; + RECT damage{}; + UINT buffer_dpi = 0; + std::vector control_contexts; + std::unordered_map control_groups; + std::unordered_set live_groups; + std::vector control_order, focus_order; + bool controls_updated = false; + std::unordered_map buttons; + HWND tooltip = nullptr; + sui_input_callback input = nullptr; + std::unordered_map edits; + std::unordered_map> fonts; + std::unordered_map native_views; + std::unordered_map native_parents; + bool updating_views = false; + bool native_state_changed = true; + std::vector scrolls, pending_scrolls; + // The immutable frame actually present in the DIB while later publications + // are waiting for WM_PAINT. Never copy pixels relative to an unpainted frame. + std::vector painted_commands; + std::vector painted_scrolls; + std::vector scroll_stack; + ScrollCopy scroll_copy; + int64_t reused_pixels = 0; + sui_paint_stats paint_stats{}; + sui_paint_stats total_paint_stats{}; + double publish_times[6]{}; + bool host_clipped_children = false; + FrameTrace trace; +}; +double ClockMilliseconds() { + static const double frequency = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return double(f.QuadPart) / 1000.; + }(); + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + return now.QuadPart / frequency; +} +void InitializeGraphics() { + static ULONG_PTR token = [] { + ULONG_PTR result = 0; + GdiplusStartupInput input; + GdiplusStartup(&result, &input, nullptr); + return result; + }(); + (void)token; +} +std::wstring Wide(const char *text) { + if (!text || !*text) + return {}; + int count = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0); + std::wstring result(count, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, text, -1, result.data(), count); + result.pop_back(); + return result; +} +void RoundedPath(GraphicsPath &path, RectF r, float radius) { + float d = max(0.f, min(radius * 2, min(r.Width, r.Height))); + if (d < 0.01f) { + path.AddRectangle(r); + return; + } + path.AddArc(r.X, r.Y, d, d, 180, 90); + path.AddArc(r.GetRight() - d, r.Y, d, d, 270, 90); + path.AddArc(r.GetRight() - d, r.GetBottom() - d, d, d, 0, 90); + path.AddArc(r.X, r.GetBottom() - d, d, d, 90, 90); + path.CloseFigure(); +} +void DrawTextCommand(Surface *s, Graphics &g, const Command &c) { + const auto key = c.family + L"\n" + std::to_wstring(c.size) + L":" + + (c.weight >= 600 ? L"bold" : L"regular"); + auto found = s->fonts.find(key); + if (found == s->fonts.end()) { + if (s->fonts.size() >= 256) + s->fonts.clear(); + found = s->fonts.emplace(key, std::make_unique(c)).first; + } + auto &font = found->second->font; + StringFormat format(StringFormat::GenericTypographic()); + format.SetFormatFlags(StringFormatFlagsNoWrap | + StringFormatFlagsMeasureTrailingSpaces); + SolidBrush brush(Color(c.fill)); + // Explicit newlines and line spacing, without inventing a wrapping policy. + const float line_height = font.GetHeight(&g); + size_t start = 0; + int lines = 1 + int(std::count(c.text.begin(), c.text.end(), L'\n')); + float y = c.rect.Y + (c.rect.Height - + (line_height * lines + c.line_spacing * (lines - 1))) / + 2; + while (start <= c.text.size()) { + auto end = c.text.find(L'\n', start); + auto line = + c.text.substr(start, end == std::wstring::npos ? end : end - start); + g.DrawString(line.c_str(), int(line.size()), &font, PointF(c.rect.X, y), + &format, &brush); + if (end == std::wstring::npos) + break; + start = end + 1; + y += line_height + c.line_spacing; + } +} +void VectorPath(GraphicsPath &path, const std::vector &commands) { + PointF current; + for (size_t i = 0; i < commands.size();) { + const int op = int(commands[i++]); + if (op == 3) { + path.CloseFigure(); + continue; + } + if (i + (op == 2 ? 6 : 2) > commands.size()) + break; + PointF p{float(commands[i]), float(commands[i + 1])}; + i += 2; + if (op == 0) { + path.StartFigure(); + current = p; + } else if (op == 1) { + path.AddLine(current, p); + current = p; + } else if (op == 2) { + PointF c2{float(commands[i]), float(commands[i + 1])}, + end{float(commands[i + 2]), float(commands[i + 3])}; + i += 4; + path.AddBezier(current, p, c2, end); + current = end; + } + } +} +// A Bezier curve is contained by the convex hull of its control points. These +// conservative bounds avoid allocating GDI+ paths merely to reject invisible +// ink. +RectF PathBounds(const std::vector &commands) { + double left = 0, top = 0, right = 0, bottom = 0; + bool first = true; + for (size_t i = 0; i < commands.size();) { + const int op = int(commands[i++]); + const size_t count = op == 3 ? 0 : op == 2 ? 6 : 2; + if (i + count > commands.size()) + break; + for (size_t end = i + count; i < end; i += 2) { + const auto x = commands[i], y = commands[i + 1]; + if (first) { + left = right = x; + top = bottom = y; + first = false; + } else { + left = min(left, x); + top = min(top, y); + right = max(right, x); + bottom = max(bottom, y); + } + } + } + return RectF(float(left), float(top), float(right - left), + float(bottom - top)); +} +void RenderFrame(Surface *s) { + RECT client; + GetClientRect(s->host, &client); + const auto dpi = GetDpiForWindow(s->host); + const auto width = UINT(max(1L, client.right)); + const auto height = UINT(max(1L, client.bottom)); + const bool same_size = + s->buffer && s->buffer->width == width && s->buffer->height == height; + if (same_size && s->buffer_dpi == dpi && !s->buffer_dirty) + return; + FrameTrace::Span raster_trace(s->trace, 6, 0, s->host); + const double started = ClockMilliseconds(); + if (!same_size) + s->buffer = std::make_unique(width, height); + const bool full = !same_size || s->buffer_dpi != dpi; + s->buffer_dpi = dpi; + s->buffer_dirty = false; + RECT copied{}; + RECT repaint = s->scroll_copy.repaint; + if (!full) { + const auto © = s->scroll_copy; + if (!IsRectEmpty(©.destination)) { + const auto &r = copy.destination; + GdiFlush(); + if (BitBlt(s->buffer->dc, r.left, r.top, r.right - r.left, + r.bottom - r.top, s->buffer->dc, r.left - copy.dx, + r.top - copy.dy, SRCCOPY)) { + GdiFlush(); + copied = r; + s->reused_pixels = int64_t(r.right - r.left) * (r.bottom - r.top); + } + } + } + s->scroll_copy = {}; + // Complete GDI access before opening GDI+ over the same DIB storage. + Graphics g(s->buffer->bitmap.get()); + if (!full) { + Region dirty(Rect(s->damage.left, s->damage.top, + s->damage.right - s->damage.left, + s->damage.bottom - s->damage.top)); + if (!IsRectEmpty(&copied)) + dirty.Exclude(Rect(copied.left, copied.top, copied.right - copied.left, + copied.bottom - copied.top)); + if (!IsRectEmpty(&repaint)) + dirty.Union(Rect(repaint.left, repaint.top, repaint.right - repaint.left, + repaint.bottom - repaint.top)); + g.SetClip(&dirty); + } + SolidBrush clear(Color(255, 255, 255, 255)); + g.FillRectangle(&clear, 0, 0, INT(width), INT(height)); + s->damage = {}; + g.SetSmoothingMode(SmoothingModeAntiAlias); + g.SetPixelOffsetMode(PixelOffsetModeHalf); + g.SetTextRenderingHint(TextRenderingHintClearTypeGridFit); + float scale = dpi / 96.f; + g.ScaleTransform(scale, scale); + std::vector clips; + for (size_t i = 0; i < s->commands.size(); ++i) { + const auto &c = s->commands[i]; + if ((c.kind == 2 || c.kind == 5) && c.clip_end > i) { + auto bounds = c.rect; + bounds.Inflate(1, 1); + if (!g.IsVisible(bounds)) { + i = c.clip_end; + continue; + } + } + if (c.kind == 3) { + if (!clips.empty()) { + g.Restore(clips.back()); + clips.pop_back(); + } + } else if (c.kind == 4 || c.kind == 5) { + auto bounds = c.rect; + bounds.Inflate(1 + c.stroke_width / 2, 1 + c.stroke_width / 2); + if (c.kind == 4 && !g.IsVisible(bounds)) + continue; + GraphicsPath path; + VectorPath(path, c.path); + if (c.kind == 5) { + clips.push_back(g.Save()); + g.SetClip(&path, CombineModeIntersect); + } else { + if (c.fill >> 24) { + SolidBrush brush(Color(c.fill)); + g.FillPath(&brush, &path); + } + if (c.stroke_width > 0 && c.stroke >> 24) { + Pen pen(Color(c.stroke), c.stroke_width); + g.DrawPath(&pen, &path); + } + } + } else if (c.kind == 6) { + clips.push_back(g.Save()); + g.TranslateTransform(c.rect.X, c.rect.Y); + g.RotateTransform(c.radius); + g.ScaleTransform(c.size, c.weight); + g.TranslateTransform(-c.rect.X, -c.rect.Y); + } else if (c.kind == 7 && c.colors.size() >= 2) { + if (!g.IsVisible(c.rect)) + continue; + LinearGradientBrush brush(c.start, c.end, Color(c.colors.front()), + Color(c.colors.back())); + std::vector colors; + std::vector stops; + for (size_t i = 0; i < c.colors.size(); ++i) { + colors.emplace_back(c.colors[i]); + stops.push_back(REAL(i) / REAL(c.colors.size() - 1)); + } + brush.SetInterpolationColors(colors.data(), stops.data(), + int(colors.size())); + g.FillRectangle(&brush, c.rect); + } else if (c.kind == 9) { + clips.push_back(g.Save()); + g.TranslateTransform(c.rect.X, c.rect.Y); + } else if (c.kind == 8) { + if (!g.IsVisible(c.rect)) + continue; + Image bitmap(c.text.c_str()); + g.DrawImage(&bitmap, c.rect); + } else if (c.kind == 2) { + clips.push_back(g.Save()); + GraphicsPath path; + RoundedPath(path, c.rect, c.radius); + g.SetClip(&path, CombineModeIntersect); + } else if (c.rect.Width > 0 && c.rect.Height > 0 && g.IsVisible(c.rect)) { + if (c.kind == 1) { + DrawTextCommand(s, g, c); + continue; + } + GraphicsPath fill; + RoundedPath(fill, c.rect, c.radius); + if (c.fill >> 24) { + SolidBrush brush(Color(c.fill)); + g.FillPath(&brush, &fill); + } + if (c.stroke_width > 0 && c.stroke >> 24) { + auto r = c.rect; + r.Inflate(-c.stroke_width / 2, -c.stroke_width / 2); + if (r.Width > 0 && r.Height > 0) { + GraphicsPath edge; + RoundedPath(edge, r, max(0.f, c.radius - c.stroke_width / 2)); + Pen pen(Color(c.stroke), c.stroke_width); + g.DrawPath(&pen, &edge); + } + } + } + } + const double elapsed = ClockMilliseconds() - started; + s->paint_stats.raster_ms += elapsed; + s->total_paint_stats.raster_ms += elapsed; + raster_trace.tag = uint64_t(s->reused_pixels); + s->painted_commands.clear(); + s->painted_scrolls.clear(); +} +void Draw(Surface *s, HWND target, HDC dc) { + RenderFrame(s); + FrameTrace::Span blit_trace(s->trace, 7, target == s->host, target); + const double started = ClockMilliseconds(); + ++s->paint_stats.paints; + ++s->total_paint_stats.paints; + RECT client; + GetClientRect(target, &client); + POINT offset = {0, 0}; + MapWindowPoints(target, s->host, &offset, 1); + // The framebuffer is already opaque and in physical pixels. BitBlt avoids + // re-locking/converting the full GDI+ image for every child HWND's paint. + RECT clip; + if (GetClipBox(dc, &clip) == NULLREGION) + return; + const int saved = SaveDC(dc); + if (target == s->host) { + // Styled controls are input/accessibility HWNDs over this shared canvas. + // Preserve native EDIT and unstyled BUTTON pixels; layered edits compose + // themselves over the canvas and must retain its background underneath. + auto exclude = [&](HWND hwnd) { + if (!IsWindowVisible(hwnd) || + (GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & WS_EX_LAYERED)) + return; + RECT r; + GetWindowRect(hwnd, &r); + MapWindowPoints(nullptr, s->host, reinterpret_cast(&r), 2); + ExcludeClipRect(dc, r.left, r.top, r.right, r.bottom); + }; + for (const auto &entry : s->edits) + exclude(entry.first); + for (const auto &entry : s->buttons) + if (!entry.second.custom_draw) + exclude(entry.first); + } + IntersectRect(&client, &client, &clip); + RECT source{-offset.x, -offset.y, LONG(s->buffer->width) - offset.x, + LONG(s->buffer->height) - offset.y}; + IntersectRect(&client, &client, &source); + if (!IsRectEmpty(&client)) + BitBlt(dc, client.left, client.top, client.right - client.left, + client.bottom - client.top, s->buffer->dc, client.left + offset.x, + client.top + offset.y, SRCCOPY); + RestoreDC(dc, saved); + const double elapsed = ClockMilliseconds() - started; + s->paint_stats.blit_ms += elapsed; + s->total_paint_stats.blit_ms += elapsed; +} +LRESULT Paint(Surface *s, HWND hwnd, UINT msg, WPARAM wp) { + if (msg == WM_ERASEBKGND) + return 1; + if (msg == WM_PRINTCLIENT) { + Draw(s, hwnd, reinterpret_cast(wp)); + return 0; + } + PAINTSTRUCT ps; + FrameTrace::Span traced(s->trace, 4, hwnd == s->host ? 1 : 0, hwnd); + HDC dc = BeginPaint(hwnd, &ps); + Draw(s, hwnd, dc); + if (hwnd == s->host) { + RECT clip{}, client{}; + GetClientRect(hwnd, &client); + // An OS-wide expose/theme repaint can invalidate every input HWND after + // publication. A full canvas paint already covered these styled buttons; + // acknowledge that damage instead of copying the same pixels per control. + // Partial/complex paints and overlaps with native widgets remain separate. + if (GetClipBox(dc, &clip) == SIMPLEREGION && EqualRect(&clip, &client)) { + std::vector native; + auto bounds = [&](HWND child) { + RECT r{}; + GetWindowRect(child, &r); + MapWindowPoints(nullptr, s->host, reinterpret_cast(&r), 2); + return r; + }; + for (const auto &entry : s->edits) + if (IsWindowVisible(entry.first)) native.push_back(bounds(entry.first)); + for (const auto &entry : s->buttons) + if (!entry.second.custom_draw && IsWindowVisible(entry.first)) + native.push_back(bounds(entry.first)); + for (const auto &entry : s->buttons) { + if (!entry.second.custom_draw) continue; + const auto r = bounds(entry.first); + RECT covered{}; + if (!IntersectRect(&covered, &r, &clip) || !EqualRect(&covered, &r)) continue; + bool overlap = false; + for (const auto &area : native) { + RECT intersection{}; + overlap |= IntersectRect(&intersection, &r, &area) != FALSE; + } + if (!overlap) ValidateRect(entry.first, nullptr); + } + } + } + EndPaint(hwnd, &ps); + if (hwnd == s->host) { + FrameTrace::Span marker_trace(s->trace, 8, 0, hwnd); + s->trace.Marker(hwnd); + } + return 0; +} +int Modifiers() { + return ((GetKeyState(VK_SHIFT) & 0x8000) ? 1 : 0) | + ((GetKeyState(VK_CONTROL) & 0x8000) ? 2 : 0) | + ((GetKeyState(VK_MENU) & 0x8000) ? 4 : 0) | + (((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & 0x8000) ? 8 : 0); +} +int Input(Surface *s, HWND hwnd, int64_t id, UINT msg, WPARAM wp, LPARAM lp) { + if (!s->input) + return 0; + int event = 0, value = 0; + POINT point = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)}; + switch (msg) { + case WM_MOUSEMOVE: + event = 1; + break; + case WM_LBUTTONDOWN: + event = 2; + break; + case WM_LBUTTONUP: + event = 3; + break; + case WM_LBUTTONDBLCLK: + event = 4; + break; + case WM_MOUSEHWHEEL: + case WM_MOUSEWHEEL: + event = 5; + value = GET_WHEEL_DELTA_WPARAM(wp); + ScreenToClient(hwnd, &point); + break; + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + event = 6; + value = int(wp); + point = {0, 0}; + break; + case WM_RBUTTONDOWN: + event = 9; + break; + case WM_MOUSELEAVE: + event = 10; + break; + } + if (!event) + return 0; + if (event != 6) + MapWindowPoints(hwnd, s->host, &point, 1); + double scale = GetDpiForWindow(s->host) / 96.; + return s->input(s->context, id, event, point.x / scale, point.y / scale, + msg == WM_MOUSEHWHEEL ? -value : value, + Modifiers() | (msg == WM_MOUSEHWHEEL ? 1 : 0)); +} +LRESULT CALLBACK EditProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, + DWORD_PTR data) { + auto *s = reinterpret_cast(data); + auto found = s->edits.find(hwnd); + if (found == s->edits.end()) + return DefSubclassProc(hwnd, msg, wp, lp); + auto id = found->second.id; + if (msg == WM_KEYDOWN && wp == VK_TAB) { + sui_surface_focus_next(s, hwnd, (Modifiers() & 1) != 0); + return 0; + } + if (msg == WM_SETFOCUS || msg == WM_KILLFOCUS) + s->callback(s->context, id, msg == WM_SETFOCUS ? 5 : 6); + if ((msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_MOUSEWHEEL) && + Input(s, hwnd, id, msg, wp, lp)) + return 0; + return DefSubclassProc(hwnd, msg, wp, lp); +} +LRESULT CALLBACK HostProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, + DWORD_PTR data) { + auto *s = reinterpret_cast(data); + FrameTrace::Span traced(s->trace, + msg == WM_MOUSEMOVE || msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL ? 1 : + msg == deferred_input ? 2 : msg == WM_TIMER ? 5 : 0, int(msg), hwnd); + if (msg == WM_NCDESTROY && hwnd == s->host) s->trace.Finish(); + // NativeAPI observes notifications on its content HWND. Scroll grouping is + // an implementation detail and must not interrupt BUTTON/EDIT notifications. + if (hwnd != s->host && msg == WM_COMMAND) + return SendMessageW(s->host, msg, wp, lp); + if (msg == WM_DPICHANGED || msg == WM_DPICHANGED_AFTERPARENT) { + // NativeAPI first applies the suggested bounds. Logical dimensions may + // stay identical, but retained control frames still need the new DPI. + const auto result = DefSubclassProc(hwnd, msg, wp, lp); + if (hwnd == s->host && s->input) + s->input(s->context, 0, 12, 0, 0, 0, 0); + return result; + } + if (msg == deferred_input) { + if (s->input) + s->input(s->context, static_cast(wp), wp ? 7 : 11, 0, 0, 0, 0); + return 0; + } + if (msg == WM_PAINT || msg == WM_PRINTCLIENT || msg == WM_ERASEBKGND) + return Paint(s, hwnd, msg, wp); + if (msg == WM_TIMER && + wp == subclass_id) { // NativeAPI owns GetMessage; Swift's main queue must + // also be serviced. + using Pump = void (*)(void *); + static auto pump = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"dispatch.dll"), + "_dispatch_main_queue_callback_4CF")); + if (pump) + pump(nullptr); + if (s->input) + s->input(s->context, 0, 8, 0, 0, 0, 0); + return 0; + } + if (msg == WM_DRAWITEM && lp) { + auto *item = reinterpret_cast(lp); + auto found = s->buttons.find(item->hwndItem); + if (found != s->buttons.end() && found->second.custom_draw) { + Draw(s, item->hwndItem, item->hDC); + return TRUE; + } + } + if (msg == WM_COMMAND && HIWORD(wp) == EN_CHANGE) { + auto found = s->edits.find(reinterpret_cast(lp)); + if (found != s->edits.end() && !found->second.updating) + PostMessageW(s->host, deferred_input, + static_cast(found->second.id), 0); + } + + if (msg == WM_CTLCOLOREDIT || msg == WM_CTLCOLORSTATIC) { + auto found = s->edits.find(reinterpret_cast(lp)); + if (found != s->edits.end()) { + SetTextColor(reinterpret_cast(wp), found->second.foreground); + SetBkColor(reinterpret_cast(wp), found->second.background); + return reinterpret_cast(found->second.brush); + } + } + if (msg == WM_LBUTTONDOWN) { + SetCapture(hwnd); + SetFocus(hwnd); + } + if (msg == WM_LBUTTONUP && GetCapture() == hwnd) + ReleaseCapture(); + if (msg == WM_MOUSEMOVE) { + TRACKMOUSEEVENT track = {sizeof(track), TME_LEAVE, hwnd, 0}; + TrackMouseEvent(&track); + } + if (Input(s, hwnd, 0, msg, wp, lp)) + return 0; + if (msg == WM_KEYDOWN && wp == VK_TAB) { + sui_surface_focus_next(s, nullptr, (GetKeyState(VK_SHIFT) & 0x8000) != 0); + return 0; + } + return DefSubclassProc(hwnd, msg, wp, lp); +} +LRESULT CALLBACK ButtonProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, + DWORD_PTR data) { + auto *s = reinterpret_cast(data); + FrameTrace::Span traced(s->trace, + msg == WM_MOUSEMOVE || msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL ? 1 : 0, + int(msg), hwnd); + auto found = s->buttons.find(hwnd); + if (found == s->buttons.end()) + return DefSubclassProc(hwnd, msg, wp, lp); + // Scrolling only moves the clipping parent with redraw suppressed. Native + // button state changes can still schedule their own paint, which the next + // canvas publication must absorb. Do not scan every HWND on every scroll. + switch (msg) { + case WM_MOUSEMOVE: + case WM_MOUSELEAVE: + case BM_SETSTATE: + case WM_SETFOCUS: + case WM_KILLFOCUS: + case WM_SETTEXT: + case WM_SETFONT: + case WM_ENABLE: + case WM_STYLECHANGED: + case WM_WINDOWPOSCHANGED: + s->native_state_changed = true; + break; + } + const int64_t id = found->second.id; + if ((msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL || msg == WM_RBUTTONDOWN || + msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && + Input(s, hwnd, id, msg, wp, lp)) + return 0; + if (found->second.custom_draw && + (msg == WM_PAINT || msg == WM_PRINTCLIENT || msg == WM_ERASEBKGND)) + return Paint(s, hwnd, msg, wp); + if (msg == WM_KEYDOWN && wp == VK_TAB) { + sui_surface_focus_next(s, hwnd, (GetKeyState(VK_SHIFT) & 0x8000) != 0); + return 0; + } + if (msg == WM_KEYDOWN && wp == VK_RETURN && !(lp & (1L << 30))) { + sui_button_activate(hwnd); + return 0; + } + int event = 0; + if (msg == WM_MOUSEMOVE && !found->second.hovered) { + found->second.hovered = true; + TRACKMOUSEEVENT track = {sizeof(track), TME_LEAVE, hwnd, 0}; + TrackMouseEvent(&track); + event = 1; + } else if (msg == WM_MOUSELEAVE && found->second.hovered) { + found->second.hovered = false; + event = 2; + } else if (msg == BM_SETSTATE) + event = wp ? 3 : 4; + else if (msg == WM_SETFOCUS) + event = 5; + else if (msg == WM_KILLFOCUS) + event = 6; + // Capture, keyboard activation, focus and BN_CLICKED remain the BUTTON's. + if (event) + s->callback(s->context, id, event); + return DefSubclassProc(hwnd, msg, wp, lp); +} +Command Box(int kind, double x, double y, double w, double h, double radius) { + Command c; + c.kind = kind; + c.rect = RectF(float(x), float(y), float(w), float(h)); + c.radius = float(std::isfinite(radius) ? radius : min(w, h) / 2); + return c; +} +void OrderControl(Surface *s, HWND hwnd) { + if (!s->controls_updated) + sui_controls_begin(s); + s->control_order.push_back(hwnd); + if (s->buttons.count(hwnd) || s->edits.count(hwnd)) + s->focus_order.push_back(hwnd); +} +ControlContext CurrentControls(Surface *s) { + return s->control_contexts.empty() ? ControlContext{s->host, 0, 0, 0, 0} + : s->control_contexts.back(); +} +int ControlPixel(double value, double scale) { + return int(std::floor(value * scale + 0.5 + 1e-8)); +} +ControlContext ChildControls(Surface *s, HWND parent, double x, double y, + double scale) { + const auto ancestor = CurrentControls(s); + return {parent, x, y, ancestor.x + ControlPixel(x - ancestor.origin_x, scale), + ancestor.y + ControlPixel(y - ancestor.origin_y, scale)}; +} +native_view_t NativeView(Surface *s, HWND hwnd) { + auto found = s->native_views.find(hwnd); + if (found != s->native_views.end()) + return found->second; + auto view = native_view_create_with_native_view(hwnd); + // An existing native control already has explicit geometry. Preserve it + // when enrolling the borrowed view in NativeAPI's absolute layout tree. + native_view_set_frame(view, native_view_get_frame(view)); + s->native_views.emplace(hwnd, view); + return view; +} +void ReleaseControl(Surface *s, HWND hwnd) { + auto found = s->native_views.find(hwnd); + if (found == s->native_views.end()) + return; + auto parent = s->native_parents.find(hwnd); + if (parent != s->native_parents.end()) { + auto host = s->native_views.find(parent->second); + if (host != s->native_views.end()) + native_view_remove_subview(host->second, found->second); + s->native_parents.erase(parent); + } + native_view_free(found->second); + s->native_views.erase(found); +} +void DestroyControlGroup(Surface *s, const ControlGroup &group) { + RemoveWindowSubclass(group.window, HostProc, subclass_id); + RemoveWindowSubclass(group.viewport, HostProc, subclass_id); + ReleaseControl(s, group.window); + ReleaseControl(s, group.viewport); + DestroyWindow(group.window); + DestroyWindow(group.viewport); +} +void ParentControl(Surface *s, HWND hwnd) { + const auto context = CurrentControls(s); + if (s->native_parents[hwnd] != context.parent || + GetParent(hwnd) != context.parent) { + native_view_add_subview(NativeView(s, context.parent), NativeView(s, hwnd)); + s->native_parents[hwnd] = context.parent; + } +} +void ApplyRegion(HWND hwnd, HRGN region) { + HRGN old = CreateRectRgn(0, 0, 0, 0); + const bool equal = GetWindowRgn(hwnd, old) != ERROR && EqualRgn(old, region); + DeleteObject(old); + // Changing even an identical region sends WM_WINDOWPOSCHANGED, and redraws + // the control synchronously. Hover must not move/repaint the other controls. + if (equal || !SetWindowRgn(hwnd, region, FALSE)) + DeleteObject(region); +} +RectF InkBounds(const Command &c) { + auto bounds = c.rect; + if (c.kind == 4) + bounds.Inflate(c.stroke_width / 2, c.stroke_width / 2); + return bounds; +} +bool SavesGraphics(int kind) { + return kind == 2 || kind == 5 || kind == 6 || kind == 9; +} +bool Contains(RectF outer, RectF inner) { + return outer.X <= inner.X && outer.Y <= inner.Y && + outer.GetRight() >= inner.GetRight() && + outer.GetBottom() >= inner.GetBottom(); +} +bool Near(double a, double b) { return std::abs(a - b) < 0.0001; } +bool Translates(const Command &a, const Command &b, double dx, double dy, + bool allow_color_change = false) { + if (a.kind != b.kind || !Near(a.rect.X + dx, b.rect.X) || + !Near(a.rect.Y + dy, b.rect.Y) || !Near(a.rect.Width, b.rect.Width) || + !Near(a.rect.Height, b.rect.Height) || a.radius != b.radius || + a.stroke_width != b.stroke_width || a.size != b.size || + a.weight != b.weight || a.line_spacing != b.line_spacing || + (!allow_color_change && (a.fill != b.fill || a.stroke != b.stroke)) || + a.text != b.text || a.family != b.family || a.colors != b.colors || + a.path.size() != b.path.size()) + return false; + if (a.kind == 7 && + (!Near(a.start.X + dx, b.start.X) || !Near(a.start.Y + dy, b.start.Y) || + !Near(a.end.X + dx, b.end.X) || !Near(a.end.Y + dy, b.end.Y))) + return false; + for (size_t i = 0; i < a.path.size();) { + if (a.path[i] != b.path[i]) + return false; + const int op = int(a.path[i++]); + const size_t count = op == 3 ? 0 : op == 2 ? 6 : 2; + if (i + count > a.path.size()) + return false; + for (const size_t end = i + count; i < end; i += 2) + if (!Near(a.path[i] + dx, b.path[i]) || + !Near(a.path[i + 1] + dy, b.path[i + 1])) + return false; + } + return true; +} +struct InkIterator { + const std::vector &commands; + size_t position, end; + double dx, dy; + RectF area; + std::vector clips; + bool valid = true; + const Command *next() { + while (position < end) { + const auto &c = commands[position++]; + if (c.kind == 6 || c.kind == 9) { + valid = false; + return nullptr; + } + if (c.kind == 2 || c.kind == 5) { + clips.push_back(&c); + continue; + } + if (c.kind == 3) { + if (clips.empty()) { + valid = false; + return nullptr; + } + clips.pop_back(); + continue; + } + if ((c.kind == 0 || c.kind == 4) && !(c.fill >> 24) && !(c.stroke >> 24)) + continue; + auto ink = InkBounds(c); + ink.Inflate(2, 2); + for (const auto *clip : clips) + ink.Intersect(clip->rect); + ink.Offset(float(dx), float(dy)); + if (ink.IntersectsWith(area)) { + // External bitmap files can change without changing their command. + if (c.kind == 8) { + valid = false; + return nullptr; + } + return &c; + } + } + return nullptr; + } +}; +bool ScrollInkTranslates(Surface *s, const std::vector &commands, + const ScrollDrawing &a, const ScrollDrawing &b, + RECT destination, int dx, int dy, double scale, + RECT &repaint) { + RectF area(float(destination.left / scale), float(destination.top / scale), + float((destination.right - destination.left) / scale), + float((destination.bottom - destination.top) / scale)); + InkIterator before{commands, a.begin, a.end, dx / scale, dy / scale, area}; + InkIterator after{s->pending, b.begin, b.end, 0, 0, area}; + for (;;) { + const auto *old = before.next(), *next = after.next(); + if (!before.valid || !after.valid) + return false; + if (!old || !next) + return old == next; + if (!Translates(*old, *next, dx / scale, dy / scale, true) || + before.clips.size() != after.clips.size()) + return false; + if (old->fill != next->fill || old->stroke != next->stroke) { + auto ink = InkBounds(*next); + ink.Inflate(2, 2); + RECT changed{LONG(std::floor(ink.X * scale)), + LONG(std::floor(ink.Y * scale)), + LONG(std::ceil(ink.GetRight() * scale)), + LONG(std::ceil(ink.GetBottom() * scale))}; + IntersectRect(&changed, &changed, &destination); + UnionRect(&repaint, &repaint, &changed); + } + for (size_t i = 0; i < before.clips.size(); ++i) + if (!Translates(*before.clips[i], *after.clips[i], dx / scale, + dy / scale)) + return false; + } +} +// Pixel translation is only safe over a uniform opaque backdrop, with no +// stationary overlay intersecting the viewport. Anything uncertain repaints. +bool ScrollBackdrop(Surface *s, const ScrollDrawing &scroll, RectF copy_area) { + RECT client; + GetClientRect(s->host, &client); + const float scale = GetDpiForWindow(s->host) / 96.f; + struct Scope { + RectF clip; + bool complex = false; + }; + std::vector scopes{ + {RectF(0, 0, client.right / scale, client.bottom / scale)}}; + bool flat = true; // The framebuffer's initial clear is solid white. + for (size_t i = 0; i < s->pending.size(); ++i) { + if (i == scroll.begin) { + if (scopes.back().complex || !Contains(scopes.back().clip, copy_area)) { + return false; + } + i = scroll.end - 1; + continue; + } + const auto &c = s->pending[i]; + if (c.kind == 6 || c.kind == 9) + return false; + if (c.kind == 2 || c.kind == 5) { + auto scope = scopes.back(); + scope.clip.Intersect(c.rect); + scope.complex |= c.kind == 5 || c.radius != 0; + scopes.push_back(scope); + continue; + } + if (c.kind == 3) { + if (scopes.size() > 1) + scopes.pop_back(); + continue; + } + if (c.kind == 0 && !(c.fill >> 24) && !(c.stroke >> 24)) + continue; + auto ink = InkBounds(c); + ink.Inflate(2, 2); + ink.Intersect(scopes.back().clip); + if (!ink.IntersectsWith(copy_area)) + continue; + if (i >= scroll.end) { + return false; + } + flat = !scopes.back().complex && c.kind == 0 && c.radius == 0 && + (c.fill >> 24) == 255 && c.stroke_width == 0 && + Contains(c.rect, copy_area) && + Contains(scopes.back().clip, copy_area); + } + return flat; +} +ScrollCopy PrepareScrollCopy(Surface *s) { + RECT client; + GetClientRect(s->host, &client); + const auto dpi = GetDpiForWindow(s->host); + if (!s->buffer || s->buffer_dpi != dpi || + s->buffer->width != UINT(client.right) || + s->buffer->height != UINT(client.bottom)) + return {}; + const double scale = dpi / 96.; + const auto &commands = s->buffer_dirty ? s->painted_commands : s->commands; + const auto &scrolls = s->buffer_dirty ? s->painted_scrolls : s->scrolls; + for (const auto &b : s->pending_scrolls) { + for (const auto &a : scrolls) { + if (a.id != b.id || !a.viewport.Equals(b.viewport) || + a.begin != b.begin || a.end <= a.begin || b.end <= b.begin || + commands.size() - a.end != s->pending.size() - b.end) + continue; + const double x = (b.x - a.x) * scale, y = (b.y - a.y) * scale; + const int dx = int(std::round(x)), dy = int(std::round(y)); + if ((!dx && !dy) || std::abs(x - dx) > 0.001 || std::abs(y - dy) > 0.001) + continue; + // Repaint stationary borders/overhang on every edge and reserve both + // potential scroll-indicator strips. Only the interior can be copied. + RECT area{LONG(std::ceil((b.viewport.X + 4) * scale)), + LONG(std::ceil((b.viewport.Y + 4) * scale)), + LONG(std::floor((b.viewport.GetRight() - 8) * scale)), + LONG(std::floor((b.viewport.GetBottom() - 8) * scale))}; + IntersectRect(&area, &area, &client); + const RectF copy_area(float(area.left / scale), float(area.top / scale), + float((area.right - area.left) / scale), + float((area.bottom - area.top) / scale)); + const bool outside = + std::equal(commands.begin(), commands.begin() + a.begin, + s->pending.begin()) && + std::equal(commands.begin() + a.end, commands.end(), + s->pending.begin() + b.end); + const bool backdrop = ScrollBackdrop(s, b, copy_area); + if (!outside || !backdrop) + continue; + RECT shifted = area, destination; + OffsetRect(&shifted, dx, dy); + if (!IntersectRect(&destination, &area, &shifted)) + continue; + RECT repaint{}; + const bool ink = ScrollInkTranslates(s, commands, a, b, destination, dx, + dy, scale, repaint); + if (!ink) + continue; + // A broad theme/content change is cheaper to redraw. Small hover color + // changes repaint their ink over the translated, last-painted pixels. + if (int64_t(repaint.right - repaint.left) * + (repaint.bottom - repaint.top) > + int64_t(destination.right - destination.left) * + (destination.bottom - destination.top) / 2) + continue; + return {destination, dx, dy, repaint}; + } + } + return {}; +} +// When culling changes the command count, retain the common enclosing clip. +// A scroll viewport stays fixed even though its visible descendants change. +RECT ChangedScope(Surface *s, RECT client) { + const auto &a = s->commands, &b = s->pending; + size_t prefix = 0, suffix = 0; + while (prefix < min(a.size(), b.size()) && a[prefix] == b[prefix]) + ++prefix; + while (suffix < min(a.size(), b.size()) - prefix && + a[a.size() - suffix - 1] == b[b.size() - suffix - 1]) + ++suffix; + struct Scope { + RECT clip; + bool transformed; + }; + std::vector scopes{{client, false}}; + const double scale = GetDpiForWindow(s->host) / 96.; + for (size_t i = 0; i < prefix; ++i) { + const auto &c = a[i]; + if (SavesGraphics(c.kind)) { + auto next = scopes.back(); + if ((c.kind == 2 || c.kind == 5) && !next.transformed) { + const auto r = InkBounds(c); + RECT clip{LONG(std::floor(r.X * scale)), LONG(std::floor(r.Y * scale)), + LONG(std::ceil(r.GetRight() * scale)), + LONG(std::ceil(r.GetBottom() * scale))}; + IntersectRect(&next.clip, &next.clip, &clip); + } + next.transformed |= c.kind == 6 || c.kind == 9; + scopes.push_back(next); + } else if (c.kind == 3 && scopes.size() > 1) { + scopes.pop_back(); + } + } + size_t enclosing = scopes.size() - 1; + for (const auto *commands : {&a, &b}) { + size_t depth = scopes.size() - 1; + for (size_t i = prefix; i < commands->size() - suffix; ++i) { + const auto kind = (*commands)[i].kind; + if (SavesGraphics(kind)) + ++depth; + else if (kind == 3 && depth > 0) + --depth; + enclosing = min(enclosing, depth); + } + } + return scopes[enclosing].clip; +} +RECT Damage(Surface *s) { + RECT client; + GetClientRect(s->host, &client); + if (!s->buffer) + return client; + if (s->commands.size() != s->pending.size()) + return ChangedScope(s, client); + RECT damage{}; + const double scale = GetDpiForWindow(s->host) / 96.; + std::vector transforms; + int transformed = 0; + for (size_t i = 0; i < s->commands.size(); ++i) { + const auto &a = s->commands[i], &b = s->pending[i]; + if (!(a == b)) { + if (a.kind != b.kind || transformed || a.kind == 2 || a.kind == 3 || + a.kind == 5 || a.kind == 6 || a.kind == 9) + return ChangedScope(s, client); + if (!(a.kind == 0 && !(a.fill >> 24) && !(a.stroke >> 24) && + !(b.fill >> 24) && !(b.stroke >> 24))) { + for (const auto *c : {&a, &b}) { + auto r = InkBounds(*c); + // Include antialiasing and text overhang at the edge of a node. + r.Inflate(2 + c->stroke_width, 2 + c->stroke_width); + RECT pixels{LONG(std::floor(r.X * scale)), + LONG(std::floor(r.Y * scale)), + LONG(std::ceil(r.GetRight() * scale)), + LONG(std::ceil(r.GetBottom() * scale))}; + UnionRect(&damage, &damage, &pixels); + } + } + } + if (b.kind == 2 || b.kind == 5 || b.kind == 6 || b.kind == 9) { + bool transform = b.kind == 6 || b.kind == 9; + transforms.push_back(transform); + transformed += transform; + } else if (b.kind == 3 && !transforms.empty()) { + transformed -= transforms.back(); + transforms.pop_back(); + } + } + IntersectRect(&damage, &damage, &client); + return damage; +} +} // namespace +extern "C" { +void sui_prepare_application(void) { + // Must precede Application initialization, which can create hidden HWNDs. + // An embedding host with an existing manifest/context remains in charge. + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); +} +void *sui_surface_create(void *host, sui_event_callback callback, void *context, + uint64_t native_view) { + InitializeGraphics(); + auto *s = new Surface{static_cast(host), callback, context}; + if (!SetWindowSubclass(s->host, HostProc, subclass_id, + reinterpret_cast(s))) { + delete s; + return nullptr; + } + if (native_view) + s->native_views.emplace(s->host, native_handle_retain(native_view)); + const auto style = GetWindowLongPtrW(s->host, GWL_STYLE); + s->host_clipped_children = (style & WS_CLIPCHILDREN) != 0; + SetWindowLongPtrW(s->host, GWL_STYLE, style & ~WS_CLIPCHILDREN); + s->tooltip = CreateWindowExW( + WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, s->host, + nullptr, GetModuleHandleW(nullptr), nullptr); + SetTimer(s->host, subclass_id, 16, nullptr); + return s; +} +void sui_surface_destroy(void *handle) { + auto *s = static_cast(handle); + KillTimer(s->host, subclass_id); + while (!s->edits.empty()) + sui_edit_destroy(s, s->edits.begin()->first); + for (const auto &entry : s->buttons) + RemoveWindowSubclass(entry.first, ButtonProc, subclass_id); + for (const auto &entry : s->buttons) + ReleaseControl(s, entry.first); + for (const auto &entry : s->control_groups) { + DestroyControlGroup(s, entry.second); + } + ReleaseControl(s, s->host); + if (s->updating_views) + native_view_end_updates(false); + RemoveWindowSubclass(s->host, HostProc, subclass_id); + if (s->host_clipped_children) + SetWindowLongPtrW(s->host, GWL_STYLE, + GetWindowLongPtrW(s->host, GWL_STYLE) | WS_CLIPCHILDREN); + if (s->tooltip) + DestroyWindow(s->tooltip); + delete s; +} +int sui_control_focused(void *control) { + return GetFocus() == static_cast(control); +} +void sui_surface_trace_duration(void *handle, int stage, double milliseconds) { + auto *s = static_cast(handle); + if (s->trace.Enabled()) + s->trace.Add(9, stage, FrameTrace::Now(), s->host, + uint64_t((std::max)(0.0, milliseconds) * 1000000)); +} +void sui_surface_trace_update(void *handle, int begin) { + auto *s = static_cast(handle); + if (!s->trace.Enabled()) return; + if (begin) s->trace.update_start = FrameTrace::Now(); + else s->trace.Add(2, 2, s->trace.update_start, s->host); +} +void sui_surface_schedule(void *handle) { + PostMessageW(static_cast(handle)->host, deferred_input, 0, 0); +} +void sui_surface_flush(void *handle) { + auto *s = static_cast(handle); + MSG msg; + while (PeekMessageW(&msg, s->host, deferred_input, deferred_input, PM_REMOVE)) + DispatchMessageW(&msg); +} +void sui_surface_input(void *handle, sui_input_callback callback) { + static_cast(handle)->input = callback; +} +void *sui_edit_create(void *handle, int64_t id, int multiline, int secure) { + auto *s = static_cast(handle); + DWORD style = WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_CLIPSIBLINGS | + (multiline ? (ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN) + : ES_AUTOHSCROLL) | + (secure ? ES_PASSWORD : 0); + HWND edit = CreateWindowExW(0, L"EDIT", L"", style, 0, 0, 1, 1, s->host, + nullptr, GetModuleHandleW(nullptr), nullptr); + if (!edit) + return nullptr; + s->edits.emplace(edit, EditHook{id}); + SetWindowSubclass(edit, EditProc, subclass_id, + reinterpret_cast(s)); + SendMessageW(edit, EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, 0); + return edit; +} +int sui_edit_text(void *edit, char *output, int capacity) { + HWND hwnd = static_cast(edit); + std::wstring text(GetWindowTextLengthW(hwnd) + 1, L'\0'); + GetWindowTextW(hwnd, text.data(), int(text.size())); + int size = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), -1, nullptr, 0, + nullptr, nullptr); + if (output && capacity >= size) + WideCharToMultiByte(CP_UTF8, 0, text.c_str(), -1, output, capacity, nullptr, + nullptr); + return size; +} +void sui_edit_update(void *handle, void *control, const char *text, + const char *placeholder, double x, double y, double w, + double h, const char *family, double size, double weight, + uint32_t foreground, uint32_t background, int enabled, + int focus) { + auto *s = static_cast(handle); + HWND hwnd = static_cast(control); + auto &hook = s->edits.at(hwnd); + hook.updating = true; + auto value = Wide(text); + std::wstring current(GetWindowTextLengthW(hwnd) + 1, L'\0'); + GetWindowTextW(hwnd, current.data(), int(current.size())); + current.resize(wcslen(current.c_str())); + if (value != current) { + DWORD start = 0, end = 0; + SendMessageW(hwnd, EM_GETSEL, reinterpret_cast(&start), + reinterpret_cast(&end)); + SetWindowTextW(hwnd, value.c_str()); + SendMessageW(hwnd, EM_SETSEL, min(start, DWORD(value.size())), + min(end, DWORD(value.size()))); + } + auto cue = Wide(placeholder); + SendMessageW(hwnd, EM_SETCUEBANNER, TRUE, + reinterpret_cast(cue.c_str())); + double scale = GetDpiForWindow(s->host) / 96.; + auto fontKey = Wide(family) + std::to_wstring(size * scale) + L":" + + std::to_wstring(weight); + if (hook.fontKey != fontKey) { + auto font = CreateFontW( + -int(std::round(size * scale)), 0, 0, 0, int(weight), FALSE, FALSE, + FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, + CLEARTYPE_QUALITY, DEFAULT_PITCH, Wide(family).c_str()); + SendMessageW(hwnd, WM_SETFONT, reinterpret_cast(font), TRUE); + if (hook.font) + DeleteObject(hook.font); + hook.font = font; + hook.fontKey = fontKey; + } + auto rgb = [](uint32_t color) { + return RGB((color >> 16) & 255, (color >> 8) & 255, color & 255); + }; + const bool colors_changed = + hook.foreground != rgb(foreground) || hook.background != rgb(background); + hook.foreground = rgb(foreground); + if (!hook.brush || hook.background != rgb(background)) { + if (hook.brush) + DeleteObject(hook.brush); + hook.background = rgb(background); + hook.brush = CreateSolidBrush(hook.background); + } + sui_control_frame(s, hwnd, x, y, w, h); + OrderControl(s, hwnd); + if (IsWindowEnabled(hwnd) != (enabled != 0)) + EnableWindow(hwnd, enabled); + if (focus && enabled && GetFocus() != hwnd) + SetFocus(hwnd); + if (colors_changed) + InvalidateRect(hwnd, nullptr, FALSE); + hook.updating = false; +} +void sui_edit_destroy(void *handle, void *edit) { + auto *s = static_cast(handle); + HWND hwnd = static_cast(edit); + auto found = s->edits.find(hwnd); + if (found == s->edits.end()) + return; + auto hook = found->second; + s->edits.erase(found); + RemoveWindowSubclass(hwnd, EditProc, subclass_id); + ReleaseControl(s, hwnd); + DestroyWindow(hwnd); + if (hook.font) + DeleteObject(hook.font); + if (hook.brush) + DeleteObject(hook.brush); +} +void sui_control_clip(void *control, double x, double y, double w, double h) { + HWND hwnd = static_cast(control); + double scale = GetDpiForWindow(hwnd) / 96.; + const bool visible = w > 0 && h > 0; + if (bool(IsWindowVisible(hwnd)) != visible) + ShowWindow(hwnd, visible ? SW_SHOWNA : SW_HIDE); + ApplyRegion(hwnd, CreateRectRgn(int(std::floor(x * scale)), + int(std::floor(y * scale)), + int(std::ceil((x + w) * scale)), + int(std::ceil((y + h) * scale)))); +} +void sui_control_opacity(void *control, double opacity) { + auto hwnd = static_cast(control); + auto style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE); + if (opacity < 1) { + if (!(style & WS_EX_LAYERED)) + SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | WS_EX_LAYERED); + SetLayeredWindowAttributes(hwnd, 0, BYTE(max(0., min(1., opacity)) * 255), + LWA_ALPHA); + } else if (style & WS_EX_LAYERED) + SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style & ~WS_EX_LAYERED); +} +void sui_control_focus(void *control) { SetFocus(static_cast(control)); } +void sui_edit_replace_text(void *edit, const char *text) { + SetWindowTextW(static_cast(edit), Wide(text).c_str()); +} +void sui_surface_pointer(void *handle, int event, double x, double y, + int value) { + auto *s = static_cast(handle); + double scale = GetDpiForWindow(s->host) / 96.; + POINT point = {LONG(std::round(x * scale)), LONG(std::round(y * scale))}; + UINT msg = event == 2 ? WM_LBUTTONDOWN + : event == 3 ? WM_LBUTTONUP + : event == 5 ? WM_MOUSEWHEEL + : event == 9 ? WM_RBUTTONDOWN + : WM_MOUSEMOVE; + WPARAM wp = (event == 1 || event == 2) ? MK_LBUTTON : 0; + if (event == 5) { + ClientToScreen(s->host, &point); + wp = MAKEWPARAM(0, value); + } + SendMessageW(s->host, msg, wp, MAKELPARAM(point.x, point.y)); +} +void sui_surface_begin(void *handle) { + auto *s = static_cast(handle); + if (s->trace.Enabled()) s->trace.publication_start = FrameTrace::Now(); + if (!s->updating_views) { + native_view_begin_updates(); + s->updating_views = true; + } + s->pending.clear(); + s->pending_scrolls.clear(); + s->scroll_stack.clear(); + s->control_contexts.clear(); + s->live_groups.clear(); + s->control_order.clear(); + s->controls_updated = false; +} +void sui_surface_shape(void *h, double x, double y, double w, double height, + double radius, uint32_t fill, uint32_t stroke, + double width) { + auto c = Box(0, x, y, w, height, radius); + c.fill = fill; + c.stroke = stroke; + c.stroke_width = float(width); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_text(void *h, double x, double y, double w, double height, + const char *text, const char *family, double size, + double weight, double line_spacing, uint32_t color) { + auto c = Box(1, x, y, w, height, 0); + c.text = Wide(text); + c.family = Wide(family); + c.size = float(size); + c.weight = float(weight); + c.fill = color; + c.line_spacing = float(line_spacing); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_path(void *h, const double *commands, int count, uint32_t fill, + uint32_t stroke, double width, int clip) { + Command c; + c.kind = clip ? 5 : 4; + c.path.assign(commands, commands + count); + c.rect = PathBounds(c.path); + c.fill = fill; + c.stroke = stroke; + c.stroke_width = float(width); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_translation(void *h, double x, double y) { + Command c; + c.kind = 9; + c.rect = RectF(float(x), float(y), 0, 0); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_transform(void *h, double cx, double cy, double rotation, + double sx, double sy) { + Command c; + c.kind = 6; + c.rect = RectF(float(cx), float(cy), 0, 0); + c.radius = float(rotation); + c.size = float(sx); + c.weight = float(sy); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_gradient(void *h, double x, double y, double width, + double height, double sx, double sy, double ex, + double ey, const uint32_t *colors, int count) { + auto c = Box(7, x, y, width, height, 0); + c.start = PointF(float(x + sx * width), float(y + sy * height)); + c.end = PointF(float(x + ex * width), float(y + ey * height)); + c.colors.assign(colors, colors + count); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_image(void *h, const char *file, double x, double y, + double width, double height) { + auto c = Box(8, x, y, width, height, 0); + c.text = Wide(file); + static_cast(h)->pending.push_back(std::move(c)); +} +void sui_surface_clip(void *h, double x, double y, double w, double height, + double radius) { + static_cast(h)->pending.push_back(Box(2, x, y, w, height, radius)); +} +void sui_surface_restore(void *h) { + Command c; + c.kind = 3; + static_cast(h)->pending.push_back(c); +} +void sui_surface_end(void *h) { + auto *s = static_cast(h); + double started = ClockMilliseconds(); + auto checkpoint = [&](int stage) { + auto now = ClockMilliseconds(); + s->publish_times[stage] = now - started; + started = now; + }; + s->scroll_copy = PrepareScrollCopy(s); + checkpoint(0); + s->reused_pixels = 0; + s->paint_stats = {}; + // Animation-only publications have no control traversal. Keep their hosts. + if (s->controls_updated) { + for (auto it = s->control_groups.begin(); it != s->control_groups.end();) { + if (s->live_groups.count(it->first)) { + ++it; + continue; + } + DestroyControlGroup(s, it->second); + it = s->control_groups.erase(it); + } + // Later painted siblings are in front. Tab order is retained separately. + std::unordered_map previous; + for (auto it = s->control_order.rbegin(); it != s->control_order.rend(); + ++it) { + auto hwnd = *it; + auto &above = previous[GetParent(hwnd)]; + if (GetWindow(hwnd, GW_HWNDPREV) != above) + SetWindowPos(hwnd, above ? above : HWND_TOP, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW); + above = hwnd; + } + } + checkpoint(1); + std::vector scopes; + for (size_t i = 0; i < s->pending.size(); ++i) { + auto &command = s->pending[i]; + if (SavesGraphics(command.kind)) + scopes.push_back(i); + else if (command.kind == 3 && !scopes.empty()) { + s->pending[scopes.back()].clip_end = i; + scopes.pop_back(); + } + } + checkpoint(2); + if (s->updating_views) { + native_view_end_updates(false); + s->updating_views = false; + } + checkpoint(3); + RECT damage = Damage(s); + if (s->trace.Enabled() && !IsRectEmpty(&damage)) ++s->trace.frame; + checkpoint(4); + UnionRect(&s->damage, &s->damage, &damage); + if (!s->buffer_dirty) { + s->painted_commands = std::move(s->commands); + s->painted_scrolls = std::move(s->scrolls); + } + s->commands.swap(s->pending); + s->scrolls.swap(s->pending_scrolls); + if (!IsRectEmpty(&s->damage)) { + s->buffer_dirty = true; + std::vector native_damage; + auto native_area = [&](HWND hwnd) { + if (!IsWindowVisible(hwnd) || + (GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & WS_EX_LAYERED)) + return; + RECT r; + GetWindowRect(hwnd, &r); + MapWindowPoints(nullptr, s->host, reinterpret_cast(&r), 2); + if (IntersectRect(&r, &r, &s->damage)) + native_damage.push_back(r); + }; + for (const auto &entry : s->edits) + native_area(entry.first); + for (const auto &entry : s->buttons) + if (!entry.second.custom_draw) + native_area(entry.first); + // One canvas copy paints all styled controls. Independent native widgets + // still receive their own damage; do not blit the same pixels per HWND. + RECT exposed; + if (GetUpdateRect(s->host, &exposed, FALSE)) + UnionRect(&s->damage, &s->damage, &exposed); + if (s->native_state_changed) { + RedrawWindow(s->host, nullptr, nullptr, + RDW_VALIDATE | RDW_NOERASE | RDW_NOFRAME | RDW_ALLCHILDREN); + s->native_state_changed = false; + } + for (const auto &entry : s->buttons) { + if (entry.second.custom_draw) { + // A styled popup over an opaque native editor still needs its own + // paint: the canvas deliberately excludes that editor's rectangle. + if (!native_damage.empty()) { + RECT r, overlap; + GetWindowRect(entry.first, &r); + MapWindowPoints(nullptr, s->host, reinterpret_cast(&r), 2); + for (const auto &native : native_damage) { + if (IntersectRect(&overlap, &r, &native)) { + InvalidateRect(entry.first, nullptr, FALSE); + break; + } + } + } + } else + InvalidateRect(entry.first, nullptr, FALSE); + } + for (const auto &entry : s->edits) { + RECT r; + GetWindowRect(entry.first, &r); + MapWindowPoints(nullptr, s->host, reinterpret_cast(&r), 2); + if (IntersectRect(&r, &r, &s->damage)) + InvalidateRect(entry.first, nullptr, FALSE); + } + RedrawWindow(s->host, &s->damage, nullptr, RDW_INVALIDATE | RDW_NOCHILDREN); + } + checkpoint(5); + s->trace.Add(3, !IsRectEmpty(&damage), s->trace.publication_start, s->host); +} +double sui_surface_publish_time(void *handle, int stage) { + return stage >= 0 && stage < 6 + ? static_cast(handle)->publish_times[stage] + : 0; +} +void sui_surface_scroll_begin(void *handle, int64_t id, int64_t revision, + double x, double y, double width, double height, + double content_x, double content_y) { + auto *s = static_cast(handle); + s->scroll_stack.push_back(s->pending_scrolls.size()); + s->pending_scrolls.push_back( + {id, revision, RectF(float(x), float(y), float(width), float(height)), + content_x, content_y, s->pending.size()}); +} +void sui_surface_scroll_end(void *handle) { + auto *s = static_cast(handle); + if (s->scroll_stack.empty()) + return; + s->pending_scrolls[s->scroll_stack.back()].end = s->pending.size(); + s->scroll_stack.pop_back(); +} +int64_t sui_surface_reused_pixels(void *handle) { + return static_cast(handle)->reused_pixels; +} +sui_paint_stats sui_surface_paint_stats(void *handle) { + return static_cast(handle)->paint_stats; +} +sui_paint_stats sui_surface_total_paint_stats(void *handle) { + return static_cast(handle)->total_paint_stats; +} +void sui_control_tab_visible(void *handle, void *control, int visible) { + auto *s = static_cast(handle); + auto found = s->buttons.find(static_cast(control)); + if (found != s->buttons.end()) + found->second.tab_visible = visible != 0; +} +void sui_control_frame(void *handle, void *control, double x, double y, + double width, double height) { + auto *s = static_cast(handle); + HWND hwnd = static_cast(control); + ParentControl(s, hwnd); + const auto context = CurrentControls(s); + const double scale = GetDpiForWindow(s->host) / 96.; + const auto view = NativeView(s, hwnd); + // Read through NativeAPI so a frame queued earlier in this transaction is + // visible here, even while the physical HWND still has its previous frame. + const auto current = native_view_get_frame(view); + RECT before{ControlPixel(current.x, scale), ControlPixel(current.y, scale), + ControlPixel(current.x, scale) + ControlPixel(current.width, scale), + ControlPixel(current.y, scale) + ControlPixel(current.height, scale)}; + // Subtract logical origins before snapping. Rounding world coordinates + // independently makes stable child frames jump at negative half pixels. + const double local_x = x - context.origin_x, local_y = y - context.origin_y; + const int px = ControlPixel(local_x, scale); + const int py = ControlPixel(local_y, scale); + const int pw = max(0, ControlPixel(width, scale)); + const int ph = max(0, ControlPixel(height, scale)); + RECT after{px, py, px + pw, py + ph}; + if (EqualRect(&before, &after)) + return; + // NativeAPI owns the control hierarchy, coalesced layout and deferred moves. + native_view_set_frame(view, {local_x, local_y, width, height}); + RECT client, damage; + GetClientRect(s->host, &client); + UnionRect(&damage, &before, &after); + OffsetRect(&damage, context.x, context.y); + IntersectRect(&damage, &damage, &client); + UnionRect(&s->damage, &s->damage, &damage); +} +void sui_controls_begin(void *handle) { + auto *s = static_cast(handle); + s->controls_updated = true; + s->focus_order.clear(); +} +void sui_controls_push(void *handle, int64_t id, double x, double y, + double width, double height, double clip_x, + double clip_y, double clip_width, double clip_height) { + auto *s = static_cast(handle); + s->live_groups.insert(id); + auto found = s->control_groups.find(id); + if (found == s->control_groups.end()) { + auto create = [&](HWND parent) { + auto hwnd = CreateWindowExW( + WS_EX_CONTROLPARENT, L"STATIC", L"", + WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_NOTIFY, 0, 0, 1, 1, + parent, nullptr, GetModuleHandleW(nullptr), nullptr); + if (hwnd) + SetWindowSubclass(hwnd, HostProc, subclass_id, + reinterpret_cast(s)); + return hwnd; + }; + auto viewport = create(CurrentControls(s).parent); + auto content = viewport ? create(viewport) : nullptr; + if (!content) { + if (viewport) + DestroyWindow(viewport); + s->control_contexts.push_back(CurrentControls(s)); + return; + } + found = + s->control_groups.emplace(id, ControlGroup{viewport, content}).first; + } + auto &group = found->second; + const double scale = GetDpiForWindow(s->host) / 96.; + sui_control_frame(s, group.viewport, clip_x, clip_y, clip_width, clip_height); + OrderControl(s, group.viewport); + s->control_contexts.push_back( + ChildControls(s, group.viewport, clip_x, clip_y, scale)); + // A fixed viewport clips a translated content HWND without changing HRGNs + // on every tick (which makes Windows recalculate every child's visibility). + auto damage = s->damage; + sui_control_frame(s, group.window, x, y, width, height); + if (!EqualRect(&damage, &s->damage)) { + RECT viewport{int(std::floor(clip_x * scale)), + int(std::floor(clip_y * scale)), + int(std::ceil((clip_x + clip_width) * scale)), + int(std::ceil((clip_y + clip_height) * scale))}; + UnionRect(&s->damage, &damage, &viewport); + } + const auto content = ChildControls(s, group.window, x, y, scale); + s->control_contexts.pop_back(); + s->control_contexts.push_back(content); +} +void sui_controls_pop(void *handle) { + auto *s = static_cast(handle); + if (!s->control_contexts.empty()) + s->control_contexts.pop_back(); +} +void sui_surface_button(void *h, void *button, int64_t id, int custom_draw, + uint64_t native_view) { + auto *s = static_cast(h); + HWND hwnd = static_cast(button); + s->native_state_changed = true; + if (native_view) + s->native_views.emplace(hwnd, native_handle_retain(native_view)); + ParentControl(s, hwnd); + SetWindowLongPtrW(hwnd, GWL_STYLE, + GetWindowLongPtrW(hwnd, GWL_STYLE) | WS_CLIPSIBLINGS); + s->buttons.emplace(hwnd, ButtonHook{id, custom_draw != 0}); + if (custom_draw) + SetWindowLongPtrW(hwnd, GWL_STYLE, + (GetWindowLongPtrW(hwnd, GWL_STYLE) & ~BS_TYPEMASK) | + BS_OWNERDRAW); + SetWindowSubclass(hwnd, ButtonProc, subclass_id, + reinterpret_cast(s)); + TOOLINFOW tool = {sizeof(tool)}; + tool.uFlags = TTF_IDISHWND | TTF_SUBCLASS; + tool.hwnd = s->host; + tool.uId = reinterpret_cast(hwnd); + tool.lpszText = const_cast(L""); + if (s->tooltip) + SendMessageW(s->tooltip, TTM_ADDTOOLW, 0, reinterpret_cast(&tool)); +} +void sui_surface_remove_button(void *h, void *button) { + auto *s = static_cast(h); + HWND hwnd = static_cast(button); + RemoveWindowSubclass(hwnd, ButtonProc, subclass_id); + TOOLINFOW tool = {sizeof(tool)}; + tool.hwnd = s->host; + tool.uId = reinterpret_cast(hwnd); + if (s->tooltip) + SendMessageW(s->tooltip, TTM_DELTOOLW, 0, reinterpret_cast(&tool)); + s->buttons.erase(hwnd); + ReleaseControl(s, hwnd); +} +void sui_button_update(void *h, void *button, double radius, const char *help, + double x, double y, double w, double height) { + auto *s = static_cast(h); + HWND hwnd = static_cast(button); + ParentControl(s, hwnd); + // Preserve declaration order without churning every HWND on a state update. + OrderControl(s, hwnd); + auto found = s->buttons.find(hwnd); + if (found == s->buttons.end()) + return; + auto &hook = found->second; + RECT rect; + GetClientRect(hwnd, &rect); + const double limit = min(rect.right, rect.bottom) / 2.; + const int r = int( + std::ceil(std::isfinite(radius) + ? max(0., min(radius * GetDpiForWindow(hwnd) / 96., limit)) + : limit)); + const double scale = GetDpiForWindow(hwnd) / 96.; + RECT clipped{int(std::floor(x * scale)), int(std::floor(y * scale)), + int(std::ceil((x + w) * scale)), + int(std::ceil((y + height) * scale))}; + IntersectRect(&clipped, &clipped, &rect); + // A translation does not change a fully visible control's local region. + // Avoid allocating/querying HRGNs for every control on every scroll tick. + if (hook.clip_width != rect.right || hook.clip_height != rect.bottom || + hook.clip_radius != r || !EqualRect(&hook.clip, &clipped)) { + HRGN region = r ? CreateRoundRectRgn(0, 0, rect.right + 1, rect.bottom + 1, + r * 2, r * 2) + : CreateRectRgn(0, 0, rect.right, rect.bottom); + HRGN clip = CreateRectRgnIndirect(&clipped); + CombineRgn(region, region, clip, RGN_AND); + DeleteObject(clip); + ApplyRegion(hwnd, region); + hook.clip = clipped; + hook.clip_width = rect.right; + hook.clip_height = rect.bottom; + hook.clip_radius = r; + } + auto text = Wide(help); + if (text != hook.help) { + hook.help = std::move(text); + TOOLINFOW tool = {sizeof(tool)}; + tool.hwnd = s->host; + tool.uId = reinterpret_cast(hwnd); + tool.lpszText = hook.help.data(); + if (s->tooltip) + SendMessageW(s->tooltip, TTM_UPDATETIPTEXTW, 0, + reinterpret_cast(&tool)); + } +} +void sui_surface_focus_next(void *h, void *current, int backward) { + auto *s = static_cast(h); + const auto count = int(s->focus_order.size()); + if (!count) + return; + auto found = std::find(s->focus_order.begin(), s->focus_order.end(), + static_cast(current)); + int index = found == s->focus_order.end() + ? (backward ? 0 : -1) + : int(found - s->focus_order.begin()); + for (int i = 0; i < count; ++i) { + index = (index + (backward ? count - 1 : 1)) % count; + const auto hwnd = s->focus_order[index]; + const auto button = s->buttons.find(hwnd); + if (button != s->buttons.end() && !button->second.tab_visible) + continue; + if (IsWindowVisible(hwnd) && IsWindowEnabled(hwnd)) { + SetFocus(hwnd); + return; + } + } +} +sui_size sui_measure_text(const char *text, const char *family_name, + double size, double weight) { + InitializeGraphics(); + Bitmap bitmap(1, 1, PixelFormat32bppPARGB); + Graphics g(&bitmap); + g.SetTextRenderingHint(TextRenderingHintAntiAliasGridFit); + auto text_w = Wide(text), family_w = Wide(family_name); + FontFamily family(family_w.c_str()); + Font font( + family.GetLastStatus() == Ok ? &family : FontFamily::GenericSansSerif(), + float(size), weight >= 600 ? FontStyleBold : FontStyleRegular, UnitPixel); + StringFormat format(StringFormat::GenericTypographic()); + format.SetFormatFlags(StringFormatFlagsNoWrap | + StringFormatFlagsMeasureTrailingSpaces); + RectF measured; + g.MeasureString(text_w.empty() ? L" " : text_w.c_str(), -1, &font, + PointF(0, 0), &format, &measured); + return {text_w.empty() ? 0 : std::ceil(measured.Width), + std::ceil(measured.Height)}; +} +void sui_button_activate(void *button) { + HWND hwnd = static_cast(button); + if (IsWindowEnabled(hwnd)) + SendMessageW(hwnd, BM_CLICK, 0, 0); +} +} diff --git a/Sources/CSwiftUIWindows/FrameTrace.h b/Sources/CSwiftUIWindows/FrameTrace.h new file mode 100644 index 0000000..4241e8c --- /dev/null +++ b/Sources/CSwiftUIWindows/FrameTrace.h @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// Opt-in diagnostics for the normal application's message loop. Records are +// buffered until shutdown; tracing never pumps, schedules or synthesizes input. +struct FrameTrace { + struct Record { + int kind, detail; + int64_t start, end; + uint64_t frame, input, tag, window; + uint32_t queued_ms; + }; + std::wstring path; + std::vector records; + uint64_t frame = 0, input = 0; + int64_t publication_start = 0, update_start = 0; + bool overflow = false, finished = false; + HDC marker_dc = nullptr; + HBITMAP marker_bitmap = nullptr; + HGDIOBJ old_bitmap = nullptr; + uint32_t *marker_pixels = nullptr; + + static int64_t Now() { + LARGE_INTEGER time; + QueryPerformanceCounter(&time); + return time.QuadPart; + } + FrameTrace() { + wchar_t value[32768]; + const auto length = GetEnvironmentVariableW(L"SWIFTUI_PORT_TRACE_PATH", value, 32768); + if (length && length < 32768) { + path.assign(value, length); + records.reserve(200000); + } + } + ~FrameTrace() { + Finish(); + if (marker_dc) SelectObject(marker_dc, old_bitmap); + if (marker_bitmap) DeleteObject(marker_bitmap); + if (marker_dc) DeleteDC(marker_dc); + } + bool Enabled() const { return !path.empty() && !finished; } + void Add(int kind, int detail, int64_t start, HWND window = nullptr, + uint64_t tag = 0, uint32_t queued_ms = 0) { + if (!Enabled()) return; + if (records.size() == 200000) { overflow = true; return; } + records.push_back({kind, detail, start, Now(), frame, input, tag, + reinterpret_cast(window), queued_ms}); + } + struct Span { + FrameTrace &trace; + int kind, detail; + HWND window; + int64_t started; + uint64_t tag = 0; + uint32_t queued_ms = 0; + Span(FrameTrace &trace, int kind, int detail, HWND window) + : trace(trace), kind(kind), detail(detail), window(window), + started(kind && trace.Enabled() ? Now() : 0) { + if (started && kind == 1) { + ++trace.input; + tag = static_cast(GetMessageExtraInfo()); + queued_ms = GetTickCount() - static_cast(GetMessageTime()); + } + } + ~Span() { if (started) trace.Add(kind, detail, started, window, tag, queued_ms); } + }; + void Marker(HWND window) { + if (!Enabled() || !frame) return; + HDC dc = GetDC(window); + if (!dc) return; + if (!marker_dc) { + marker_dc = CreateCompatibleDC(dc); + BITMAPINFO info{}; + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biWidth = 144; + info.bmiHeader.biHeight = -8; + info.bmiHeader.biPlanes = 1; + info.bmiHeader.biBitCount = 32; + info.bmiHeader.biCompression = BI_RGB; + marker_bitmap = CreateDIBSection(dc, &info, DIB_RGB_COLORS, + reinterpret_cast(&marker_pixels), nullptr, 0); + if (marker_bitmap) old_bitmap = SelectObject(marker_dc, marker_bitmap); + } + if (marker_pixels) { + const uint64_t code = 0xA55A | ((frame & 0xffff) << 16) | ((~frame & 0xffff) << 32); + for (int y = 0; y < 8; ++y) + for (int x = 0; x < 144; ++x) + marker_pixels[y * 144 + x] = (code & (uint64_t(1) << (x / 3))) ? 0xffffff : 0; + RECT client{}; + GetClientRect(window, &client); + BitBlt(dc, client.right * 30 / 100 + 8, client.bottom * 15 / 100 + 8, + 144, 8, marker_dc, 0, 0, SRCCOPY); + GdiFlush(); + } + ReleaseDC(window, dc); + } + void Finish() { + if (!Enabled()) return; + finished = true; + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + std::ofstream output{std::filesystem::path(path)}; + output << "frequency," << frequency.QuadPart << ",pid," << GetCurrentProcessId() + << ",overflow," << overflow << '\n'; + output << "kind,detail,start_qpc,end_qpc,frame_id,input_id,tag,hwnd,queued_ms\n"; + for (const auto &r : records) + output << r.kind << ',' << r.detail << ',' << r.start << ',' << r.end << ',' + << r.frame << ',' << r.input << ',' << r.tag << ',' << r.window << ',' + << r.queued_ms << '\n'; + output << "complete\n"; + } +}; diff --git a/Sources/CSwiftUIWindows/include/SwiftUIWindows.h b/Sources/CSwiftUIWindows/include/SwiftUIWindows.h new file mode 100644 index 0000000..16a8996 --- /dev/null +++ b/Sources/CSwiftUIWindows/include/SwiftUIWindows.h @@ -0,0 +1,92 @@ +#pragma once +#include +#ifdef __cplusplus +extern "C" { +#endif +typedef void (*sui_event_callback)(void *context, int64_t id, int event); +void sui_prepare_application(void); +typedef struct { + double width, height; +} sui_size; +typedef int (*sui_input_callback)(void *, int64_t, int, double, double, int, + int); +void sui_surface_schedule(void *); +void sui_surface_trace_update(void *, int begin); +void sui_surface_trace_duration(void *surface, int stage, double milliseconds); +int sui_control_focused(void *control); +void sui_surface_flush(void *); +void sui_surface_input(void *, sui_input_callback); +void *sui_edit_create(void *, int64_t, int multiline, int secure); +void sui_edit_update(void *, void *, const char *, const char *, double, double, + double, double, const char *, double, double, uint32_t, + uint32_t, int, int); +int sui_edit_text(void *, char *, int); +void sui_edit_destroy(void *, void *); +void sui_control_clip(void *, double, double, double, double); +void sui_control_opacity(void *control, double opacity); +void sui_control_focus(void *); +void sui_edit_replace_text(void *, const char *); +void sui_surface_pointer(void *, int event, double x, double y, int value); + +void *sui_surface_create(void *host, sui_event_callback callback, void *context, + uint64_t native_view); +void sui_surface_destroy(void *surface); +void sui_surface_begin(void *surface); +void sui_surface_shape(void *surface, double x, double y, double width, + double height, double radius, uint32_t fill, + uint32_t stroke, double stroke_width); +void sui_surface_text(void *surface, double x, double y, double width, + double height, const char *text, const char *family, + double size, double weight, double line_spacing, + uint32_t color); +void sui_surface_path(void *surface, const double *commands, int count, + uint32_t fill, uint32_t stroke, double width, int clip); +void sui_surface_translation(void *surface, double x, double y); +void sui_surface_transform(void *surface, double cx, double cy, double rotation, + double sx, double sy); +void sui_surface_gradient(void *surface, double x, double y, double width, + double height, double sx, double sy, double ex, + double ey, const uint32_t *colors, int count); +void sui_surface_image(void *surface, const char *file, double x, double y, + double width, double height); +void sui_surface_clip(void *surface, double x, double y, double width, + double height, double radius); +void sui_surface_restore(void *surface); +void sui_surface_scroll_begin(void *surface, int64_t id, int64_t revision, + double x, double y, double width, double height, + double content_x, double content_y); +void sui_surface_scroll_end(void *surface); +int64_t sui_surface_reused_pixels(void *surface); +typedef struct { + double raster_ms, blit_ms; + int paints; +} sui_paint_stats; +sui_paint_stats sui_surface_paint_stats(void *surface); +sui_paint_stats sui_surface_total_paint_stats(void *surface); +double sui_surface_publish_time(void *surface, int stage); +void sui_control_tab_visible(void *surface, void *control, int visible); +void sui_surface_end(void *surface); +void sui_control_frame(void *surface, void *control, double x, double y, + double width, double height); +// Group native controls under a scrolling content window. Coordinates remain +// relative to the surface; nested groups and clipping are handled by the +// bridge. +void sui_controls_begin(void *surface); +void sui_controls_push(void *surface, int64_t id, double x, double y, + double width, double height, double clip_x, + double clip_y, double clip_width, double clip_height); +void sui_controls_pop(void *surface); +void sui_surface_button(void *surface, void *button, int64_t id, + int custom_draw, uint64_t native_view); +void sui_surface_remove_button(void *surface, void *button); +void sui_button_update(void *surface, void *button, double radius, + const char *help, double x, double y, double width, + double height); +void sui_surface_focus_next(void *surface, void *current, int backward); +sui_size sui_measure_text(const char *text, const char *family, double size, + double weight); +// Sends BM_CLICK to one owned native control. Does not post global input. +void sui_button_activate(void *button); +#ifdef __cplusplus +} +#endif diff --git a/Sources/SwiftUIPort/AppRunner.swift b/Sources/SwiftUIPort/AppRunner.swift index 01c56e3..bb026bc 100644 --- a/Sources/SwiftUIPort/AppRunner.swift +++ b/Sources/SwiftUIPort/AppRunner.swift @@ -1,13 +1,21 @@ import Foundation + import NativeAPI -import SwiftUIRuntime /// Runs an app: create the native window, mount the scene's root view, and /// enter the platform application loop. /// /// v0.1 supports one `WindowGroup`. The window is sized 480×320 by default and /// closes through the platform's normal window-close path. +import SwiftUIRuntime + +/// `--smoke` opens the window and asks the application to quit a few seconds +/// later, which is what CI uses to prove the window and event loop work. + public func runApp(_ app: A) { + #if os(Windows) + WindowsDrawingBackend.prepareApplication() + #endif let scene = app.body guard let windowScene = scene as? any _WindowScene else { fatalError("SwiftUIPort v0.1 requires WindowGroup as the top-level Scene") @@ -27,24 +35,61 @@ public func runApp(_ app: A) { let title = windowScene._windowTitle window.setTitle(title.isEmpty ? "SwiftUIPort" : title) - let initialWidth = 480.0 - let initialHeight = 320.0 + let initialWidth = windowScene._defaultSize.width + let initialHeight = windowScene._defaultSize.height window.setContentSize(NativeAPI.Size(width: initialWidth, height: initialHeight)) - guard let backend = NativeViewBackend(window: window) else { - fatalError("nativeapi window has no content view") - } + #if os(Windows) + guard let backend = WindowsDrawingBackend(window: window, schedulesUpdates: true) else { + fatalError("Could not attach the Windows drawing backend") + } + let layout = LayoutEngine(textMeasurer: WindowsDrawingBackend.measureText) + #else + guard let backend = NativeViewBackend(window: window) else { + fatalError("nativeapi window has no content view") + } + let layout = LayoutEngine() + #endif let renderer = Renderer( backend: backend, root: windowScene._makeRootView(), - size: SwiftUIRuntime.Size(width: initialWidth, height: initialHeight) + size: SwiftUIRuntime.Size(width: initialWidth, height: initialHeight), + layoutEngine: layout ) backend.onResize = { [weak renderer] size in renderer?.resize(to: size) } + #if os(Windows) + backend.inputHandler = { [weak renderer] id, event, point, value, modifiers, text in + renderer?.input( + id: id, event: event, point: point, value: value, modifiers: modifiers, text: text) ?? false + } + backend.interactionHandler = { [weak renderer] id, interaction in + renderer?.interact(id, interaction) + } + #endif renderer.mount() + if let path = ProcessInfo.processInfo.environment["SWIFTUI_PORT_TREE_PATH"], + let tree = renderer.tree + { + func encode(_ node: Element) -> [String: Any] { + [ + "kind": node.kind.description, "text": node.props.text, "id": node.id.rawValue, + "x": node.frame.minX, "y": node.frame.minY, "width": node.frame.width, + "height": node.frame.height, "children": node.children.map(encode), + ] + } + if let data = try? JSONSerialization.data( + withJSONObject: encode(tree), options: [.prettyPrinted, .sortedKeys]) + { + try? data.write(to: URL(fileURLWithPath: path)) + } + } window.show() + #if os(Windows) + backend.focusInitialControl() + #endif // A tiling compositor may size the window after the first map. Pick up the // actual content area once it exists; later resizes arrive through the @@ -60,22 +105,21 @@ public func runApp(_ app: A) { startSmokeTimer() } - _ = application.runWithWindow(window) + withExtendedLifetime(renderer) { _ = application.runWithWindow(window) } } - -/// `--smoke` opens the window and asks the application to quit a few seconds -/// later, which is what CI uses to prove the window and event loop work. private func startSmokeTimer() { Thread.detachNewThread { Thread.sleep(forTimeInterval: 3) NativeAPI.Application.shared.quit(0) } } - -public extension App { +extension App { /// The `@main` entry point. `SwiftUI` re-exports this extension, so an app /// only needs `import SwiftUI`. - static func main() { + public static func main() { + #if os(Windows) + WindowsDrawingBackend.prepareApplication() + #endif runApp(Self()) } } diff --git a/Sources/SwiftUIPort/NativeViewBackend.swift b/Sources/SwiftUIPort/NativeViewBackend.swift index abbcdbf..e7ac26e 100644 --- a/Sources/SwiftUIPort/NativeViewBackend.swift +++ b/Sources/SwiftUIPort/NativeViewBackend.swift @@ -1,6 +1,6 @@ import Foundation + import NativeAPI -import SwiftUIRuntime /// The real backend: maps engine elements onto nativeapi's native views. /// @@ -9,6 +9,8 @@ import SwiftUIRuntime /// container with padding. The engine's reference frames are used for the root /// only; nested frames are left to nativeapi's own layout pass, which is the /// authoritative one at runtime. +import SwiftUIRuntime + public final class NativeViewBackend: RenderBackend { public var tapHandler: ((NodeID) -> Void)? public var onResize: ((SwiftUIRuntime.Size) -> Void)? @@ -91,9 +93,14 @@ public final class NativeViewBackend: RenderBackend { guard case .buttonClicked = event else { return } self?.tapHandler?(id) } - case .container, .padding, .empty: + case .container, .padding, .frame, .empty: guard let container = NativeAPI.View.create() else { return } view = container + case .layer, .shape, .styledButton, .presentation, .grid, .zStack, .scroll, .geometry, + .customLayout, .textField, .image, .path, .gradient: + preconditionFailure( + "Custom drawing and ButtonStyle require WindowsDrawingBackend; this backend supports native controls only" + ) case .spacer: guard let spacer = NativeAPI.View.create() else { return } spacer.setFlex(1) @@ -149,7 +156,7 @@ public final class NativeViewBackend: RenderBackend { view.setPadding(props.padding.nativeInsets) view.setFlex(props.flex) applyAlignmentToChildren(parent: id) - case .padding: + case .padding, .frame: view.setLayout(.column) view.setSpacing(0) view.setPadding(props.padding.nativeInsets) @@ -158,7 +165,8 @@ public final class NativeViewBackend: RenderBackend { case .spacer: view.setFlex(1) view.setAlignment(.stretch) - case .empty, .fragment: + case .empty, .fragment, .shape, .layer, .styledButton, .presentation, .grid, .zStack, .scroll, + .geometry, .customLayout, .textField, .image, .path, .gradient: break } } @@ -237,9 +245,9 @@ public final class NativeViewBackend: RenderBackend { private func applyAlignment(to childID: NodeID, parent: NodeID?) { guard let parent, - let parentKind = kinds[parent], - let parentProps = propsByID[parent], - let childView = handles[childID] + let parentKind = kinds[parent], + let parentProps = propsByID[parent], + let childView = handles[childID] else { return } let alignment: NativeAPI.ViewAlignment? @@ -285,7 +293,6 @@ public final class NativeViewBackend: RenderBackend { } } } - extension SwiftUIRuntime.Color { var nativeColor: NativeAPI.Color { NativeAPI.Color.fromRgba( @@ -296,7 +303,6 @@ extension SwiftUIRuntime.Color { ) } } - extension SwiftUIRuntime.EdgeInsets { var nativeInsets: NativeAPI.EdgeInsets { NativeAPI.EdgeInsets(top: top, right: trailing, bottom: bottom, left: leading) diff --git a/Sources/SwiftUIPort/VectorImage.swift b/Sources/SwiftUIPort/VectorImage.swift new file mode 100644 index 0000000..7ebe9d9 --- /dev/null +++ b/Sources/SwiftUIPort/VectorImage.swift @@ -0,0 +1,199 @@ +import Foundation + +/// SVG path geometry for bundled template images. Parsing is cached by URL. +/// Supports the SVG path grammar, including elliptical arcs and smooth curves. +import SwiftUIRuntime + +struct VectorImage { + let bounds: CGRect + let paths: [Path] + static var cache: [String: VectorImage] = [:] + + static func load(_ file: String) -> VectorImage? { + if let cached = cache[file] { return cached } + guard let source = try? String(contentsOfFile: file, encoding: .utf8) else { return nil } + func attributes(_ name: String) -> [String] { + let pattern = name + "=[\"']([^\"']*)[\"']" + guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] } + return regex.matches(in: source, range: NSRange(source.startIndex..., in: source)).compactMap + { match in + Range(match.range(at: 1), in: source).map { String(source[$0]) } + } + } + let box = + attributes("viewBox").first?.split(whereSeparator: { $0 == " " || $0 == "," }).compactMap { + Double($0) + } ?? [] + guard box.count == 4, box[2] > 0, box[3] > 0 else { return nil } + let image = VectorImage( + bounds: CGRect(x: box[0], y: box[1], width: box[2], height: box[3]), + paths: attributes("(?:^|\\s)d").map { parse($0) }) + cache[file] = image + return image + } + + private static func parse(_ source: String) -> Path { + let regex = try! NSRegularExpression( + pattern: "[a-zA-Z]|[-+]?(?:[0-9]*[.])?[0-9]+(?:[eE][-+]?[0-9]+)?") + let tokens = regex.matches(in: source, range: NSRange(source.startIndex..., in: source)).map { + String(source[Range($0.range, in: source)!]) + } + var i = 0 + var command = "M" + var previous = "" + var point = CGPoint.zero + var start = CGPoint.zero + var control = CGPoint.zero + var path = Path() + func number() -> Double { + defer { i += 1 } + return Double(tokens[i]) ?? 0 + } + func isCommand(_ token: String) -> Bool { token.count == 1 && token.first!.isLetter } + while i < tokens.count { + if isCommand(tokens[i]) { + command = tokens[i] + i += 1 + } + let upper = command.uppercased() + let relative = command != upper + let count: Int + switch upper { + case "Z": count = 0 + case "H", "V": count = 1 + case "M", "L", "T": count = 2 + case "S", "Q": count = 4 + case "C": count = 6 + case "A": count = 7 + default: return path + } + if count > 0 && (i + count > tokens.count || tokens[i.. CGPoint { + let x = number() + let y = number() + return CGPoint(x: x + base.x, y: y + base.y) + } + switch upper { + case "M": + point = pair() + start = point + path.move(to: point) + command = relative ? "l" : "L" + case "L": + point = pair() + path.addLine(to: point) + case "H": + point.x = number() + base.x + path.addLine(to: point) + case "V": + point.y = number() + base.y + path.addLine(to: point) + case "C": + let c1 = pair() + let c2 = pair() + let end = pair() + path.addCurve(to: end, control1: c1, control2: c2) + control = c2 + point = end + case "S": + let c1 = + (previous == "C" || previous == "S") + ? CGPoint(x: 2 * point.x - control.x, y: 2 * point.y - control.y) : point + let c2 = pair() + let end = pair() + path.addCurve(to: end, control1: c1, control2: c2) + control = c2 + point = end + case "Q", "T": + let c: CGPoint + if upper == "Q" { + c = pair() + } else { + c = + (previous == "Q" || previous == "T") + ? CGPoint(x: 2 * point.x - control.x, y: 2 * point.y - control.y) : point + } + let end = pair() + path.addCurve( + to: end, + control1: CGPoint( + x: point.x + (c.x - point.x) * 2 / 3, y: point.y + (c.y - point.y) * 2 / 3), + control2: CGPoint(x: end.x + (c.x - end.x) * 2 / 3, y: end.y + (c.y - end.y) * 2 / 3)) + control = c + point = end + case "A": + let rx = number() + let ry = number() + let rotation = number() + let large = number() != 0 + let sweep = number() != 0 + let end = pair() + arc( + &path, from: point, to: end, rx: rx, ry: ry, rotation: rotation, large: large, + sweep: sweep) + point = end + case "Z": + path.closeSubpath() + point = start + command = "M" + default: break + } + previous = upper + } + return path + } + private static func arc( + _ path: inout Path, from p: CGPoint, to q: CGPoint, rx rX: Double, ry rY: Double, + rotation: Double, large: Bool, sweep: Bool + ) { + var rx = abs(rX) + var ry = abs(rY) + if rx == 0 || ry == 0 { + path.addLine(to: q) + return + } + if p == q { return } + let phi = rotation * .pi / 180 + let c = cos(phi) + let s = sin(phi) + let dx = (p.x - q.x) / 2 + let dy = (p.y - q.y) / 2 + let x = c * dx + s * dy + let y = -s * dx + c * dy + let lambda = x * x / (rx * rx) + y * y / (ry * ry) + if lambda > 1 { + rx *= sqrt(lambda) + ry *= sqrt(lambda) + } + let numerator = max(0, rx * rx * ry * ry - rx * rx * y * y - ry * ry * x * x) + let denominator = rx * rx * y * y + ry * ry * x * x + let factor = (large == sweep ? -1.0 : 1.0) * sqrt(numerator / max(denominator, 1e-20)) + let cxp = factor * rx * y / ry + let cyp = -factor * ry * x / rx + let cx = c * cxp - s * cyp + (p.x + q.x) / 2 + let cy = s * cxp + c * cyp + (p.y + q.y) / 2 + let a = atan2((y - cyp) / ry, (x - cxp) / rx) + let end = atan2((-y - cyp) / ry, (-x - cxp) / rx) + var delta = end - a + if sweep && delta < 0 { delta += 2 * .pi } + if !sweep && delta > 0 { delta -= 2 * .pi } + let pieces = max(1, Int(ceil(abs(delta) / (.pi / 2)))) + let step = delta / Double(pieces) + func transform(_ x: Double, _ y: Double) -> CGPoint { + CGPoint(x: cx + c * rx * x - s * ry * y, y: cy + s * rx * x + c * ry * y) + } + for i in 0.. Void)? + public var transactionHandler: ((() -> Void) -> Void)? + public var interactionHandler: ((NodeID, Renderer.Interaction) -> Void)? + public var inputHandler: ((NodeID?, Int, CGPoint, Int, EventModifiers, String) -> Bool)? + private let schedulesUpdates: Bool + private let tracesFrames = ProcessInfo.processInfo.environment["SWIFTUI_PORT_TRACE_PATH"] != nil + private var deliveringUpdate = false + private var pendingRender: (() -> Void)? + private var pendingPointer: (() -> Void)? + private var updateListener: ListenerId? + private var pendingEvents: [() -> Void] = [] + private var modalControls: Set? + private var controlLabels: [NodeID: String] = [:] + private var controlHitRadii: [NodeID: Double] = [:] + private var desiredFocus: NodeID? + private var edits: [NodeID: UnsafeMutableRawPointer] = [:] + private var root: Element? + private struct AnimatedValues: Equatable { + let rotation, scaleX, scaleY, opacity, offsetX, offsetY: Double + init(_ p: NodeProps) { + rotation = p.rotation + scaleX = p.scaleX + scaleY = p.scaleY + opacity = p.opacity + offsetX = p.offsetX + offsetY = p.offsetY + } + } + private struct Motion { + let from: AnimatedValues + let frame: Rect + let animation: Animation + let start: TimeInterval + } + private var motions: [NodeID: Motion] = [:] + private var previous: [NodeID: AnimatedValues] = [:] + public var onResize: ((SwiftUIRuntime.Size) -> Void)? + public private(set) var lastTimings: [String: Double] = [:] + public private(set) var publicationCount = 0 + public private(set) var fullPublicationCount = 0 + public private(set) var nativeHoverEventCount = 0 + public private(set) var nativeHoverEnterCount = 0 + public private(set) var totalPointerQueryMilliseconds: Double = 0 + public var totalPaintTimings: [String: Double] { + guard let surface else { return [:] } + let stats = sui_surface_total_paint_stats(surface) + return ["raster": stats.raster_ms, "blit": stats.blit_ms, "count": Double(stats.paints)] + } + public var lastReusedPixels: Int64 { surface.map { sui_surface_reused_pixels($0) } ?? 0 } + public var lastPaintTimings: [String: Double] { + guard let surface else { return [:] } + let stats = sui_surface_paint_stats(surface) + return ["raster": stats.raster_ms, "blit": stats.blit_ms, "count": Double(stats.paints)] + } + private let window: NativeAPI.Window + private let content: NativeAPI.View + private var surface: UnsafeMutableRawPointer? + private var listener: ListenerId? + private var buttons: [NodeID: (view: NativeAPI.Button, listener: ListenerId)] = [:] + + public init?(window: NativeAPI.Window, schedulesUpdates: Bool = false) { + guard let content = window.contentView, let handle = content.nativeObject else { return nil } + self.schedulesUpdates = schedulesUpdates + self.window = window + self.content = content + content.setLayout(.absolute) + surface = sui_surface_create( + handle, + { context, id, event in + guard let context else { return } + let backend = Unmanaged.fromOpaque(context).takeUnretainedValue() + if event == 1 || event == 2 { backend.nativeHoverEventCount += 1 } + if event == 1 { backend.nativeHoverEnterCount += 1 } + if backend.schedulesUpdates && (event == 1 || event == 2) { + backend.queuePointer() + return + } + let interaction: Renderer.Interaction + switch event { + case 1: interaction = .hover(true) + case 2: interaction = .hover(false) + case 3: interaction = .pressed(true) + case 4: interaction = .pressed(false) + case 5: interaction = .focus(true) + default: interaction = .focus(false) + } + backend.enqueue { [weak backend] in + guard let backend else { return } + let node = NodeID(rawValue: Int(id)) + if event == 5 || event == 6 { + // Several Tab/focus changes can arrive before the next render. + // An obsolete gain must not pull focus back to its old HWND. + let focused = + backend.edits[node].map { sui_control_focused($0) != 0 } + ?? backend.buttons[node]?.view.isFocused ?? false + guard focused == (event == 5) else { return } + } + backend.interactionHandler?(node, interaction) + } + }, Unmanaged.passUnretained(self).toOpaque(), content.nativeHandle) + guard let surface else { return nil } + sui_surface_input( + surface, + { context, id, event, x, y, value, modifiers in + guard let context else { return 0 } + let backend = Unmanaged.fromOpaque(context).takeUnretainedValue() + if backend.schedulesUpdates { + if event == 1 || event == 10 { + backend.queuePointer(fallback: CGPoint(x: x, y: y)) + return 1 + } + if event == 5 { + backend.enqueue { [weak backend] in + _ = backend?.inputHandler?( + id == 0 ? nil : NodeID(rawValue: Int(id)), 5, + CGPoint(x: x, y: y), Int(value), EventModifiers(rawValue: Int(modifiers)), "") + } + return 1 + } + if event == 8 { + if !backend.motions.isEmpty { _ = backend.content.requestUpdate() } + return 0 + } + // Preserve press/key/text ordering relative to earlier pointer input. + if [2, 3, 4, 6, 7, 9].contains(Int(event)) { backend.drainInput() } + } + if event == 12 { + if let root = backend.root { backend.didRender(root) } + return 0 + } + if event == 11 { + let jobs = backend.pendingEvents + backend.pendingEvents.removeAll() + if let transaction = backend.transactionHandler { + transaction { jobs.forEach { $0() } } + } else { + jobs.forEach { $0() } + } + return 0 + } + if event == 8 { + backend.tick() + return 0 + } + if event == 10, let point = backend.pointerLocation(fallback: .zero) { + // Leaving a native scrolling container for one of its children is + // not leaving the SwiftUI surface. Reconcile the current hit path. + return backend.inputHandler?(nil, 1, point, 0, [], "") == true ? 1 : 0 + } + var text = "" + if event == 7, let edit = backend.edits[NodeID(rawValue: Int(id))] { + var bytes = [CChar](repeating: 0, count: Int(sui_edit_text(edit, nil, 0))) + _ = sui_edit_text(edit, &bytes, Int32(bytes.count)) + text = String(cString: bytes) + } + return backend.inputHandler?( + id == 0 ? nil : NodeID(rawValue: Int(id)), Int(event), CGPoint(x: x, y: y), Int(value), + EventModifiers(rawValue: Int(modifiers)), text) == true ? 1 : 0 + }) + if schedulesUpdates { + updateListener = content.addListener { [weak self] event in + if case .updating = event { self?.deliverUpdate() } + } + } + listener = window.addListener { [weak self] event in + // Window's resize event includes decorations; the renderer needs client size. + if case .resized = event, let self { + let size = self.window.contentSize + self.onResize?(SwiftUIRuntime.Size(width: size.width, height: size.height)) + } + } + } + deinit { + content.cancelUpdate() + if let updateListener { _ = content.removeListener(updateListener) } + if let listener { _ = window.removeListener(listener) } + for id in Array(buttons.keys) { removeButton(id) } + if let surface { sui_surface_destroy(surface) } + } + + private struct TextMeasurementKey: Hashable { + let text: String, family: String + let size: Double, weight: Double + } + private static var textMeasurements: [TextMeasurementKey: SwiftUIRuntime.Size] = [:] + + public static func measureText(_ text: String, font: Font) -> SwiftUIRuntime.Size { + let key = TextMeasurementKey( + text: text, family: font.family, size: Double(font.size), weight: font.weight.value) + if let cached = textMeasurements[key] { return cached } + let measured = sui_measure_text(text, font.family, Double(font.size), font.weight.value) + let size = SwiftUIRuntime.Size(width: measured.width, height: measured.height) + // Bound cache growth when applications display arbitrary edited text. + if textMeasurements.count >= 10000 { textMeasurements.removeAll(keepingCapacity: true) } + textMeasurements[key] = size + return size + } + + /// Drawing is published atomically from didRender after diffing assigns IDs. + public func perform(_ commands: [RenderCommand]) {} + public func didMeasureRender(_ timings: [String: Double]) { + guard tracesFrames, let surface else { return } + for (stage, name) in ["evaluate", "environment", "layout", "finalize", "diff", + "backend", "scroll.translate"].enumerated() { + if let value = timings[name] { sui_surface_trace_duration(surface, Int32(stage), value) } + } + for (stage, name) in ["prepare", "draw", "controls", "publish"].enumerated() { + if let value = lastTimings[name] { sui_surface_trace_duration(surface, Int32(stage + 10), value) } + } + } + public func didRender(_ root: Element) { + guard let surface else { return } + fullPublicationCount += 1 + let started = Date.timeIntervalSinceReferenceDate + let now = Date.timeIntervalSinceReferenceDate + var current: [NodeID: AnimatedValues] = [:] + var live = Set() + var liveEdits = Set() + var hasModal = false + var hasFocusRequest = false + func animate(_ node: Element, inherited: Animation?) { + if node.kind == .textField { liveEdits.insert(node.id) } + if node.kind == .styledButton || node.kind == .button { live.insert(node.id) } + hasModal = + hasModal || node.props.accessibilityTraits & AccessibilityTraits.isModal.rawValue != 0 + hasFocusRequest = hasFocusRequest || node.props.focusRequested + let values = AnimatedValues(node.props) + current[node.id] = values + let animation = node.props.animation ?? inherited + if let old = previous[node.id], let animation, animation.duration > 0, + old != values + { + motions[node.id] = Motion( + from: old, frame: node.frame, animation: animation, start: now + animation.delay) + } + node.children.forEach { animate($0, inherited: animation) } + } + animate(root, inherited: nil) + previous = current + motions = motions.filter { current[$0.key] != nil } + self.root = root + modalControls = nil + func modal(_ node: Element) { + if node.props.accessibilityTraits & AccessibilityTraits.isModal.rawValue != 0 { + func ids(_ node: Element) -> [NodeID] { [node.id] + node.children.flatMap(ids) } + modalControls = Set(ids(node)) + } + node.children.forEach(modal) + } + if hasModal { modal(root) } + desiredFocus = nil + func focusTarget(_ node: Element) { + if node.props.focusRequested { + func controls(_ node: Element) -> [NodeID] { + if node.kind == .button || node.kind == .styledButton || node.kind == .textField { + return [node.id] + } + return node.children.flatMap(controls) + } + let candidates = controls(node) + desiredFocus = + candidates.first(where: { id in + if let edit = edits[id] { return sui_control_focused(edit) != 0 } + return buttons[id]?.view.isFocused == true + }) ?? candidates.first + } + node.children.forEach(focusTarget) + } + if hasFocusRequest { focusTarget(root) } + for id in Set(buttons.keys).subtracting(live) { removeButton(id) } + for id in Set(edits.keys).subtracting(liveEdits) { + if let edit = edits.removeValue(forKey: id) { sui_edit_destroy(surface, edit) } + } + sui_surface_begin(surface) + lastTimings["prepare"] = (Date.timeIntervalSinceReferenceDate - started) * 1000 + publish(root, on: surface) + } + + public func didScroll(_ root: Element) { + guard motions.isEmpty else { + didRender(root) + return + } + guard let surface else { return } + self.root = root + // Scrolling does not change live controls, animation values, modal state + // or focus requests. Keep those registrations and publish new geometry. + lastTimings["prepare"] = 0 + sui_surface_begin(surface) + publish(root, on: surface, geometryOnly: true) + } + + private func publish(_ root: Element, on surface: UnsafeMutableRawPointer, geometryOnly: Bool = false) { + publicationCount += 1 + var started = Date.timeIntervalSinceReferenceDate + draw(root, clip: root.frame) + lastTimings["draw"] = (Date.timeIntervalSinceReferenceDate - started) * 1000 + started = Date.timeIntervalSinceReferenceDate + sui_controls_begin(surface) + updateButtons(root, clip: root.frame, geometryOnly: geometryOnly) + lastTimings["controls"] = (Date.timeIntervalSinceReferenceDate - started) * 1000 + started = Date.timeIntervalSinceReferenceDate + sui_surface_end(surface) + lastTimings["publish"] = (Date.timeIntervalSinceReferenceDate - started) * 1000 + for (stage, name) in ["reuse", "order", "commands", "geometry", "damage", "invalidate"] + .enumerated() + { + lastTimings["publish.\(name)"] = sui_surface_publish_time(surface, Int32(stage)) + } + } + + /// Native activation for integration tests or accessibility adapters. It is + /// scoped to a retained control, never to the user's keyboard or pointer. + public func activate(_ id: NodeID) { + if let handle = buttons[id]?.view.nativeObject { + sui_button_activate(handle) + if let surface { sui_surface_flush(surface) } + } + } + /// Programmatic editing and pointer events are scoped to this surface's HWND. + public func replaceText(_ id: NodeID, with text: String) { + if let edit = edits[id] { + sui_edit_replace_text(edit, text) + if let surface { sui_surface_flush(surface) } + } + } + public func pointer(event: Int, at point: CGPoint, value: Int = 0) { + if let surface { sui_surface_pointer(surface, Int32(event), point.x, point.y, Int32(value)) } + } + public func pointerLocation(fallback: CGPoint) -> CGPoint? { + let started = Date.timeIntervalSinceReferenceDate + defer { + totalPointerQueryMilliseconds += (Date.timeIntervalSinceReferenceDate - started) * 1000 + } + let point = DisplayManager.shared.getCursorPosition() + guard WindowManager.shared.getWindowAtPoint(point, excludedWindowId: 0)?.id == window.id + else { return nil } + let bounds = window.contentBounds + let local = CGPoint(x: point.x - bounds.x, y: point.y - bounds.y) + guard local.x >= 0, local.y >= 0, local.x < bounds.width, local.y < bounds.height else { + return nil + } + return local + } + public func nativeButton(_ id: NodeID) -> NativeAPI.Button? { buttons[id]?.view } + public func advanceFocus(from id: NodeID?, backward: Bool = false) { + if let surface { + sui_surface_focus_next( + surface, id.flatMap { buttons[$0]?.view.nativeObject }, backward ? 1 : 0) + } + } + func focusInitialControl() { + // The top-level HWND initially owns focus. Put it on the first available + // control so Tab works before the user has clicked anything. + if !buttons.values.contains(where: { $0.view.isFocused }) { advanceFocus(from: nil) } + } + + public func requestRender(_ render: @escaping () -> Void) -> Bool { + guard schedulesUpdates, !deliveringUpdate else { return false } + pendingRender = render + if content.requestUpdate() { return true } + pendingRender = nil + return false + } + private func queuePointer(fallback: CGPoint = .zero) { + pendingPointer = { [weak self] in + guard let self else { return } + let point = self.pointerLocation(fallback: fallback) + _ = self.inputHandler?(nil, point == nil ? 10 : 1, point ?? fallback, 0, [], "") + } + // A move over unchanged content must not consume the next publication + // slot. Resolve that cheap hit path now; state changes still request one + // deferred render. Preserve ordering when wheel/actions are pending. + if pendingEvents.isEmpty && pendingRender == nil && !deliveringUpdate { + drainInput() + } else if !content.requestUpdate() { + drainInput() + } + } + private func drainInput() { + let jobs = pendingEvents + pendingEvents.removeAll(keepingCapacity: true) + let pointer = pendingPointer + pendingPointer = nil + let run = { + jobs.forEach { $0() } + pointer?() + } + if let transaction = transactionHandler { transaction(run) } else { run() } + } + private func deliverUpdate() { + if let surface { sui_surface_trace_update(surface, 1) } + defer { if let surface { sui_surface_trace_update(surface, 0) } } + deliveringUpdate = true + defer { deliveringUpdate = false } + let publications = publicationCount + drainInput() + let render = pendingRender + pendingRender = nil + render?() + if publications == publicationCount { tick() } + if !motions.isEmpty { _ = content.requestUpdate() } + } + private func enqueue(_ action: @escaping () -> Void) { + let schedule = pendingEvents.isEmpty + pendingEvents.append(action) + if schedulesUpdates { + if !content.requestUpdate() { drainInput() } + } else if schedule, let surface { + sui_surface_schedule(surface) + } + } + private func tick() { + // The C bridge services Dispatch without consuming NativeAPI WM_QUIT. + guard !motions.isEmpty, let surface, let root else { return } + let now = Date.timeIntervalSinceReferenceDate + motions = motions.filter { + $0.value.animation.repeats || now < $0.value.start + $0.value.animation.duration + } + guard + motions.values.contains(where: { + let visible = $0.frame.intersection(root.frame) + return visible.width > 0 && visible.height > 0 + }) + else { return } + sui_surface_begin(surface) + draw(root, clip: root.frame) + sui_surface_end(surface) + } + private func updateButtons( + _ node: Element, allowed: Bool = true, clip: Rect, + background: SwiftUIRuntime.Color = .white, nativeClip: Rect? = nil, + geometryOnly: Bool = false + ) { + let allowed = allowed && node.props.hitTesting + let controlAllowed = allowed && (modalControls?.contains(node.id) ?? true) + let clip = node.props.clipped ? clip.intersection(node.frame) : clip + var nativeClip = nativeClip.map { node.props.clipped ? $0.intersection(node.frame) : $0 } + let background = node.props.background.flatMap { $0.opacity > 0.99 ? $0 : nil } ?? background + let wantsFocus = desiredFocus == node.id + let viewport = node.frame.intersection(clip) + let inViewport = + node.props.visible && controlAllowed && viewport.width > 0 && viewport.height > 0 + // Keep child HWND coordinates stable while the ScrollView's content moves. + // The shared framebuffer remains in surface coordinates at native DPI. + let grouped = node.kind == .scroll && node.children.first != nil + if grouped, let surface, let child = node.children.first { + let r = child.frame + let visible = node.props.visible ? clip.intersection(node.frame) : .zero + sui_controls_push( + surface, Int64(node.id.rawValue), r.minX, r.minY, r.width, r.height, + visible.minX, visible.minY, visible.width, visible.height) + // The parent viewport already clips this content. Only additional + // clipping inside it belongs in each control's local hit region. + nativeClip = r + } + defer { if grouped, let surface { sui_controls_pop(surface) } } + if node.kind == .styledButton || node.kind == .button, buttons[node.id] != nil || inViewport { + let retained = buttons[node.id] != nil + if buttons[node.id] == nil { + guard let button = NativeAPI.Button.create(label(node)), let handle = button.nativeObject + else { + fatalError("nativeapi failed to create a button") + } + let styled = node.kind == .styledButton + if let surface { + sui_surface_button( + surface, handle, Int64(node.id.rawValue), styled ? 1 : 0, button.nativeHandle) + } + let id = node.id + let listener = button.addListener { [weak self] event in + if case .buttonClicked = event { + self?.enqueue { [weak self] in self?.tapHandler?(id) } + } + } + buttons[id] = (button, listener) + } + let button = buttons[node.id]!.view + let r = node.frame + if inViewport || nativeClip != nil, let surface, let handle = button.nativeObject { + sui_control_frame(surface, handle, r.minX, r.minY, r.width, r.height) + } + // A scroll-only publication preserves state and labels. Native parent + // clipping handles visibility inside a scroll group; ungrouped controls + // still need visibility refreshed when their viewport changes. + if !geometryOnly || !retained { + let enabled = node.props.enabled && controlAllowed + if button.isEnabled != enabled { button.setEnabled(enabled) } + let title = label(node) + if controlLabels[node.id] != title { + button.setText(title) + controlLabels[node.id] = title + } + func hitRadius(_ element: Element) -> Double { + max(element.props.hitRadius, element.children.map(hitRadius).max() ?? 0) + } + controlHitRadii[node.id] = hitRadius(node) + } + if !geometryOnly || !retained || nativeClip == nil { + let visible = node.props.visible && controlAllowed && (nativeClip != nil || inViewport) + if button.isVisible != visible { button.setVisible(visible) } + } + if let surface, let handle = button.nativeObject { + sui_control_tab_visible(surface, handle, inViewport ? 1 : 0) + let visible = + node.props.visible && controlAllowed ? r.intersection(nativeClip ?? clip) : .zero + sui_button_update( + surface, handle, controlHitRadii[node.id] ?? 0, node.props.help, + visible.minX - r.minX, visible.minY - r.minY, visible.width, visible.height) + } + if wantsFocus && !button.isFocused && node.props.enabled && inViewport { + button.focus() + } + } + if node.kind == .textField, let surface, edits[node.id] != nil || inViewport { + if edits[node.id] == nil { + edits[node.id] = sui_edit_create( + surface, Int64(node.id.rawValue), node.props.multiline ? 1 : 0, + node.props.secure ? 1 : 0) + } + if let edit = edits[node.id] { + let p = node.props + let r = node.frame + let font = p.font ?? .body + sui_edit_update( + surface, edit, p.text, p.placeholder, r.minX, r.minY, r.width, r.height, font.family, + Double(font.size), font.weight.value, (p.foreground ?? .black).argb, background.argb, + p.enabled && controlAllowed ? 1 : 0, wantsFocus ? 1 : 0) + sui_control_opacity(edit, p.opacity) + let visible = inViewport ? r.intersection(nativeClip ?? clip) : .zero + sui_control_clip( + edit, visible.minX - r.minX, visible.minY - r.minY, visible.width, visible.height) + } + } + for child in orderedChildren(node) { + updateButtons( + child, allowed: allowed, clip: clip, background: background, nativeClip: nativeClip, + geometryOnly: geometryOnly) + } + } + private func label(_ node: Element) -> String { + if !node.props.accessibilityLabel.isEmpty { return node.props.accessibilityLabel } + if !node.props.text.isEmpty { return node.props.text } + return node.children.map(label).filter { !$0.isEmpty }.joined(separator: " ") + } + private func removeButton(_ id: NodeID) { + guard let button = buttons.removeValue(forKey: id) else { return } + controlLabels.removeValue(forKey: id) + controlHitRadii.removeValue(forKey: id) + _ = button.view.removeListener(button.listener) + if let surface, let handle = button.view.nativeObject { + sui_surface_remove_button(surface, handle) + } + button.view.dispose() + } + private func draw(_ node: Element, clip: Rect, transformedAncestor: Bool = false) { + guard let surface, node.props.visible else { return } + var p = node.props + let r = node.frame + var translated = false + if let motion = motions[node.id] { + let elapsed = + max(0, Date.timeIntervalSinceReferenceDate - motion.start) / motion.animation.duration + var fraction = + motion.animation.repeats ? elapsed.truncatingRemainder(dividingBy: 1) : min(1, elapsed) + if motion.animation.autoreverses && Int(elapsed) % 2 == 1 { fraction = 1 - fraction } + func mix(_ from: Double, _ to: Double) -> Double { from + (to - from) * fraction } + p.rotation = mix(motion.from.rotation, p.rotation) + p.scaleX = mix(motion.from.scaleX, p.scaleX) + p.scaleY = mix(motion.from.scaleY, p.scaleY) + p.opacity = mix(motion.from.opacity, p.opacity) + let dx = mix(motion.from.offsetX, p.offsetX) - p.offsetX + let dy = mix(motion.from.offsetY, p.offsetY) - p.offsetY + if dx != 0 || dy != 0 { + sui_surface_translation(surface, dx, dy) + translated = true + } + } + let transformed = p.rotation != 0 || p.scaleX != 1 || p.scaleY != 1 + let canCull = !transformedAncestor && !transformed && !translated + let clip = p.clipped && canCull ? clip.intersection(r) : clip + if canCull && p.clipped && (clip.width <= 0 || clip.height <= 0) { return } + if canCull && node.children.isEmpty && p.shadows.isEmpty + && (node.kind == .text || node.kind == .image || node.kind == .shape) + { + let margin = max(2, p.borderWidth) + let ink = Rect( + x: r.minX - margin, y: r.minY - margin, + width: r.width + margin * 2, height: r.height + margin * 2) + let visible = ink.intersection(clip) + if visible.width <= 0 || visible.height <= 0 { return } + } + if transformed { + sui_surface_transform( + surface, r.minX + r.width / 2, r.minY + r.height / 2, p.rotation, p.scaleX, p.scaleY) + } + func vector( + _ path: Path, fill: SwiftUIRuntime.Color = .clear, stroke: SwiftUIRuntime.Color = .clear, + width: Double = 0, clip: Bool = false + ) { + path.commands.withUnsafeBufferPointer { buffer in + sui_surface_path( + surface, buffer.baseAddress, Int32(buffer.count), fill.opacity(p.opacity).argb, + stroke.opacity(p.opacity).argb, width, clip ? 1 : 0) + } + } + let bounds = CGRect(x: r.minX, y: r.minY, width: r.width, height: r.height) + for shadow in p.shadows where shadow.color.opacity > 0 { + // A finite layered approximation, not a blur filter. It never changes + // the view's layout or native hit rectangle. + let steps = max(1, min(16, Int(ceil(shadow.radius)))) + for step in (0.. 0 || p.borderWidth > 0 && p.borderColor.opacity > 0 { + sui_surface_shape( + surface, r.minX, r.minY, r.width, r.height, p.cornerRadius, + (p.background ?? .clear).opacity(p.opacity).argb, p.borderColor.opacity(p.opacity).argb, + p.borderWidth) + } + if node.kind == .gradient, let gradient = p.gradient { + let colors = gradient.colors.map { $0.opacity(p.opacity).argb } + colors.withUnsafeBufferPointer { buffer in + sui_surface_gradient( + surface, r.minX, r.minY, r.width, r.height, gradient.start.x, gradient.start.y, + gradient.end.x, gradient.end.y, buffer.baseAddress, Int32(buffer.count)) + } + } + if node.kind == .image { + if p.imagePath.lowercased().hasSuffix(".svg"), let image = VectorImage.load(p.imagePath) { + let sx = r.width / image.bounds.width + let sy = r.height / image.bounds.height + let scale = min(sx, sy) + for path in image.paths { + vector( + path.transformed( + x: r.minX + (r.width - image.bounds.width * scale) / 2 - image.bounds.minX * scale, + y: r.minY + (r.height - image.bounds.height * scale) / 2 - image.bounds.minY + * scale, sx: scale, sy: scale), fill: p.foreground ?? .black) + } + } else { + sui_surface_image(surface, p.imagePath, r.minX, r.minY, r.width, r.height) + } + } + if node.kind == .text { + let font = p.font ?? .body + let text = p.renderedText ?? p.text + sui_surface_text( + surface, r.minX, r.minY, r.width, r.height, text, font.family, + Double(font.size), font.weight.value, p.lineSpacing, + (p.foreground ?? .black).opacity(p.opacity).argb) + } + let cacheScroll = + node.kind == .scroll && canCull && p.clipped && p.cornerRadius == 0 + && node.clipPathBuilder == nil && motions.isEmpty && node.children.first != nil + if cacheScroll, let child = node.children.first { + // The bridge verifies translated paint commands, clips and backdrop + // before copying pixels; opaque/custom layout does not need guessing. + sui_surface_scroll_begin( + surface, Int64(node.id.rawValue), 0, + clip.minX, clip.minY, clip.width, clip.height, child.frame.minX, child.frame.minY) + } + for child in orderedChildren(node) { + draw( + child, clip: clip, transformedAncestor: transformedAncestor || transformed || translated) + } + if node.kind == .scroll, p.showsScrollIndicators, let child = node.children.first { + let color = (p.foreground ?? .gray).opacity(0.3).argb + if child.frame.height > r.height && r.height > 0 { + let height = max(20, r.height * r.height / child.frame.height) + let y = r.minY + p.scrollOffset.y / (child.frame.height - r.height) * (r.height - height) + sui_surface_shape(surface, r.maxX - 6, y, 4, height, 2, color, 0, 0) + } + if child.frame.width > r.width && r.width > 0 { + let width = max(20, r.width * r.width / child.frame.width) + let x = r.minX + p.scrollOffset.x / (child.frame.width - r.width) * (r.width - width) + sui_surface_shape(surface, x, r.maxY - 6, width, 4, 2, color, 0, 0) + } + } + if cacheScroll { sui_surface_scroll_end(surface) } + if node.clipPathBuilder != nil { sui_surface_restore(surface) } + if p.clipped { sui_surface_restore(surface) } + if transformed { sui_surface_restore(surface) } + if translated { sui_surface_restore(surface) } + } + private func orderedChildren(_ node: Element) -> [Element] { + let children = + node.kind == .layer && node.props.layerBehind + ? Array(node.children.reversed()) : node.children + guard children.count > 1, children.contains(where: { $0.props.zIndex != 0 }) else { + return children + } + return children.enumerated().sorted(by: { + $0.element.props.zIndex == $1.element.props.zIndex + ? $0.offset < $1.offset : $0.element.props.zIndex < $1.element.props.zIndex + }).map { $0.element } + } + } + extension Rect { + fileprivate func intersection(_ other: Rect) -> Rect { + let x = max(minX, other.minX) + let y = max(minY, other.minY) + return Rect( + x: x, y: y, width: max(0, min(maxX, other.maxX) - x), + height: max(0, min(maxY, other.maxY) - y)) + } + } + extension SwiftUIRuntime.Color { + fileprivate var argb: UInt32 { + func byte(_ value: Double) -> UInt32 { UInt32(max(0, min(255, (value * 255).rounded()))) } + return byte(opacity) << 24 | byte(red) << 16 | byte(green) << 8 | byte(blue) + } + } +#endif diff --git a/Sources/SwiftUIRuntime/Backend.swift b/Sources/SwiftUIRuntime/Backend.swift index 14d1d4c..72c902f 100644 --- a/Sources/SwiftUIRuntime/Backend.swift +++ b/Sources/SwiftUIRuntime/Backend.swift @@ -1,9 +1,24 @@ /// One operation the runtime asks a backend to perform. + /// /// A render pass produces a minimal ordered list: removals first, then the /// creates/inserts/moves needed to reach the new child order, then property /// updates, then frame changes. A matched element is never recreated just /// because its properties changed. + +/// The platform seam. +/// +/// `SwiftUIRuntime` never imports nativeapi. A backend receives commands and +/// turns them into real view operations; ``FakeBackend`` records them for +/// tests. + +/// A backend that records commands instead of touching a platform toolkit. +/// +/// This is the only backend needed to test the engine on macOS, where the +/// `SwiftUI` and `SwiftUIPort` modules are not built. + +import Foundation + public enum RenderCommand: Equatable { case create(id: NodeID, kind: ElementKind, props: NodeProps) case insert(id: NodeID, parent: NodeID?, index: Int) @@ -12,24 +27,26 @@ public enum RenderCommand: Equatable { case setProps(id: NodeID, props: NodeProps) case setFrame(id: NodeID, frame: Rect) } - -/// The platform seam. -/// -/// `SwiftUIRuntime` never imports nativeapi. A backend receives commands and -/// turns them into real view operations; ``FakeBackend`` records them for -/// tests. public protocol RenderBackend: AnyObject { + /// Return true when the backend will call this on its next update boundary. + func requestRender(_ render: @escaping () -> Void) -> Bool + /// Optional diagnostics, after a complete runtime update (milliseconds). + func didMeasureRender(_ timings: [String: Double]) func perform(_ commands: [RenderCommand]) + func didRender(_ root: Element) + /// Content and actions are unchanged; only a scroll offset and descendant + /// frames moved. Backends may retain animation/control property state. + func didScroll(_ root: Element) + /// Current pointer in root coordinates, or nil when it is outside/occluded. + /// Headless backends use the supplied input point. + func pointerLocation(fallback: CGPoint) -> CGPoint? /// Called by the backend when a native button is clicked. The renderer wires /// this to the current action for that node. var tapHandler: ((NodeID) -> Void)? { get set } + /// Groups native notifications from one message turn into one render. + var transactionHandler: ((() -> Void) -> Void)? { get set } } - -/// A backend that records commands instead of touching a platform toolkit. -/// -/// This is the only backend needed to test the engine on macOS, where the -/// `SwiftUI` and `SwiftUIPort` modules are not built. public final class FakeBackend: RenderBackend { public private(set) var commands: [RenderCommand] = [] public var tapHandler: ((NodeID) -> Void)? @@ -71,3 +88,14 @@ public final class FakeBackend: RenderBackend { } } } +extension RenderBackend { + public func requestRender(_ render: @escaping () -> Void) -> Bool { false } + public func didMeasureRender(_ timings: [String: Double]) {} + public func didRender(_ root: Element) {} + public func didScroll(_ root: Element) { didRender(root) } + public func pointerLocation(fallback: CGPoint) -> CGPoint? { fallback } + public var transactionHandler: ((() -> Void) -> Void)? { + get { nil } + set {} + } +} diff --git a/Sources/SwiftUIRuntime/Binding.swift b/Sources/SwiftUIRuntime/Binding.swift index b21468e..375185d 100644 --- a/Sources/SwiftUIRuntime/Binding.swift +++ b/Sources/SwiftUIRuntime/Binding.swift @@ -4,6 +4,7 @@ /// passes `$value`. Reads and writes go straight to the owner's storage, so a /// write marks the renderer dirty exactly as a direct `@State` write does. @propertyWrapper +@dynamicMemberLookup public struct Binding { private let getter: () -> Value private let setter: (Value) -> Void @@ -20,6 +21,16 @@ public struct Binding { public var projectedValue: Binding { self } + public subscript(dynamicMember key: WritableKeyPath) -> Binding { + Binding( + get: { wrappedValue[keyPath: key] }, + set: { + var value = wrappedValue + value[keyPath: key] = $0 + wrappedValue = value + }) + } + /// A binding that ignores writes. Reads always return `value`. public static func constant(_ value: Value) -> Binding { Binding(get: { value }, set: { _ in }) diff --git a/Sources/SwiftUIRuntime/ButtonStyle.swift b/Sources/SwiftUIRuntime/ButtonStyle.swift new file mode 100644 index 0000000..390b62f --- /dev/null +++ b/Sources/SwiftUIRuntime/ButtonStyle.swift @@ -0,0 +1,34 @@ +public struct ButtonStyleConfiguration { + public typealias Label = AnyView + public let label: Label + public let isPressed: Bool +} +@MainActor @preconcurrency public protocol ButtonStyle { + associatedtype Body: View + typealias Configuration = ButtonStyleConfiguration + @ViewBuilder func makeBody(configuration: Configuration) -> Body +} +struct StyledButton: View, _PrimitiveView { + typealias Body = Never + let button: Button