Commit06c00be0Recorded17 Nov 2026Repositorysigil-ui

Draw macOS windows through the sigil-window AppKit host

Message

sigil-ui no longer owns a macOS host. Its AppKit adapter only draws, into windows that sigil-window 0.2.0 provides, and the Objective-C sources, framework flags and ARC build path are gone, so macOS builds cross-compile from Linux without an Apple SDK.

sigil-window is a dependency only for macOS and Windows targets, and the AppKit modules compile only for macOS, so Linux builds keep their own Wayland code and link nothing from sigil-window.

The compatibility changes for macOS consumers are listed in NEWS.md: host records now come from sigil-window, (sigil ui window appkit services) is removed, present-ui! refuses a stale generation, and the host can emit (input-reset). Requires Sigil 0.24.8.

Changed
 NEWS.md                                       |  17 ++++
 README.md                                     |   8 +-
 demo/macos/Info.plist                         |   2 +-
 demo/macos/launcher.c                         |  48 ++++++++++
 demo/macos/launcher.m                         |  28 ------
 demo/package.sgl                              |   4 +-
 docs/macos.md                                 | 195 ++++++++++++---------------------------
 docs/release.md                               |  17 ++++
 docs/window-services.md                       |   7 +-
 native/appkit-host.h                          |  63 -------------
 native/appkit-host.inc                        | 252 --------------------------------------------------
 native/appkit.m                               | 740 --------------------------------------------------------------------------------------------------------------------------------------------------
 native/raster.c                               |   8 +-
 native/window-appkit-services.inc             | 267 -----------------------------------------------------
 package.sgl                                   |  56 +++++------
 scripts/build-macos-demo.sgl                  | 190 ++++++--------------------------------
 scripts/check-platform-selection.sgl          |  15 +++
 sigil.lock                                    |  88 ------------------
 src/sigil/ui/appkit.sgl                       | 216 +++++++++++++++++--------------------------
 src/sigil/ui/appkit/wait.sgl                  |  57 +-----------
 src/sigil/ui/window/appkit/services.sgl       |  13 ---
 test/appkit-host-stub/sigil/window/appkit.sgl |  46 ++++++++++
 test/appkit/embedding.m                       | 295 ----------------------------------------------------------
 test/appkit/resize.m                          | 187 -------------------------------------
 test/appkit/services.m                        | 219 -------------------------------------------
 test/appkit/tracking.m                        | 119 ------------------------
 test/check-appkit-adapter.sgl                 |  42 +++++++++
 test/link-check/.gitignore                    |   1 +
 test/link-check/package.sgl                   |  16 ++++
 test/link-check/src/link/main.sgl             |  10 ++
 test/test-appkit-wait.sgl                     |  67 +++++++-------
 31 files changed, 464 insertions(+), 2829 deletions(-)
Diff
NEWS.mdmodified
@@ -1,3 +1,20 @@
+1
# sigil-ui 0.2.6
+2
+3
An SDK-free AppKit drawing adapter release. Requires Sigil 0.24.8.
+4
+5
- Darwin and Windows use sigil-window 0.2.0; Linux retains its existing
+6
Wayland host without linking a second copy of the Wayland symbols.
+7
- Native host tokens and geometry/key records now use sigil-window's SW
+8
ABI. Rebuild native adapters; the retired SUI records are incompatible.
+9
- Remove `(sigil ui window appkit services)`; native services belong to
+10
sigil-window. The legacy AppKit wait module forwards to the host.
+11
- UI presentation refuses a stale generation or a different window.
+12
- AppKit open-window defaults its title to "Sigil" and accepts visible?.
+13
- AppKit emits `(input-reset)` when input ownership must be reset.
+14
- macOS code and development drivers use plain C and runtime-loaded APIs;
+15
full demo cross-build qualification still requires the font backend port.
+16
- Follow [the registry-lock and release gates](docs/release.md) before publishing.
+17
18
# sigil-ui 0.2.5
19
20
A Windows raster adapter release.
README.mdmodified
@@ -21,14 +21,14 @@ integer scaling and named theme colors, fonts and images.
21
22
## Install
23
−24
Requires Sigil 0.24.6. Add the registry dependency to your package's
+24
Requires Sigil 0.24.8. Add the registry dependency to your package's
25
`dependencies` list, then run `sigil deps install`:
26
27
```scheme
28
(from-pkg name: "sigil/sigil-ui" version: "^0.2")
29
```
30
−31
This release is 0.2.4; see [NEWS](NEWS.md) for changes.
+31
This release is 0.2.6; see [NEWS](NEWS.md) for changes.
32
33
## Minimal example
34
@@ -85,8 +85,8 @@ The application owns the event loop; see [the demo](demo/src/demo/main.sgl).
85
86
`(sigil ui window)` provides the common window and input interface on Linux and
87
macOS, including [title, clipboard, and acknowledged fullscreen services](docs/window-services.md).
−88
See [macOS support](docs/macos.md) for the AppKit backend, development
−89
bundle build, scheduler integration and current gaps.
+88
See [macOS support](docs/macos.md) for the drawing adapter, sigil-window's
+89
prebuilt Mac qualification packet, scheduler integration and remaining gates.
90
91
## Popup chooser
92
demo/macos/Info.plistmodified
@@ -8,5 +8,5 @@
8
<key>CFBundleVersion</key><string>1</string>
9
<key>NSHighResolutionCapable</key><true/>
10
<key>NSPrincipalClass</key><string>NSApplication</string>
−11
<key>LSMinimumSystemVersion</key><string>13.0</string>
+11
<key>LSMinimumSystemVersion</key><string>15.0</string>
12
</dict></plist>
demo/macos/launcher.cadded
@@ -0,0 +1,48 @@
+1
/* SDK-free Launch Services entry. Keep the demo's receipts and resources
+2
* beside its development bundle before replacing this process. */
+3
#include <limits.h>
+4
#include <stdint.h>
+5
#include <stdio.h>
+6
#include <stdlib.h>
+7
#include <string.h>
+8
#include <unistd.h>
+9
extern int _NSGetExecutablePath(char *, uint32_t *);
+10
+11
static int parent(char *path)
+12
{
+13
char *slash = strrchr(path, '/');
+14
if (!slash || slash == path) return 0;
+15
*slash = 0;
+16
return 1;
+17
}
+18
+19
int main(int argc, char **argv)
+20
{
+21
(void)argc;
+22
char unresolved[PATH_MAX], contents[PATH_MAX], root[PATH_MAX], file[PATH_MAX];
+23
uint32_t capacity = sizeof(unresolved);
+24
if (_NSGetExecutablePath(unresolved, &capacity) || !realpath(unresolved, contents) ||
+25
!parent(contents) || !parent(contents)) return 1;
+26
if (snprintf(root, sizeof(root), "%s", contents) >= (int)sizeof(root) ||
+27
!parent(root) || !parent(root)) return 1;
+28
#define PATH(base, suffix) \
+29
(snprintf(file, sizeof(file), "%s/%s", base, suffix) < (int)sizeof(file))
+30
if (!PATH(contents, "Resources") || chdir(file)) return 1;
+31
if (!PATH(root, "state") || setenv("CFFIXED_USER_HOME", file, 1)) return 1;
+32
if (!PATH(root, "tmp/") || setenv("TMPDIR", file, 1)) return 1;
+33
if (!PATH(root, "app.log") || !freopen(file, "a", stdout) ||
+34
dup2(fileno(stdout), STDERR_FILENO) < 0) return 1;
+35
if (!PATH(root, "app.exit")) return 1;
+36
unlink(file);
+37
if (setenv("SIGIL_UI_DEMO_EXIT_FILE", file, 1) || !PATH(root, "app.pid")) return 1;
+38
FILE *receipt = fopen(file, "w");
+39
if (!receipt) return 1;
+40
int written = fprintf(receipt, "%ld\n", (long)getpid());
+41
int closed = fclose(receipt);
+42
if (written < 0 || closed) return 1;
+43
if (!PATH(contents, "Resources/sigil-ui-demo")) return 1;
+44
argv[0] = file;
+45
execv(file, argv);
+46
perror("exec demo");
+47
return 1;
+48
}
demo/macos/launcher.mdeleted
@@ -1,28 +0,0 @@
−1
#import <Foundation/Foundation.h>
−2
#include <stdio.h>
−3
#include <unistd.h>
−4
−5
/* Give Launch Services the bundle identity before replacing this PID with the
−6
* compiled demo. Keep test logs, framework state and temporary files nearby. */
−7
int main(int argc, char **argv) {
−8
(void)argc;
−9
@autoreleasepool {
−10
NSString *resources=NSBundle.mainBundle.resourcePath;
−11
NSString *root=[NSBundle.mainBundle.bundlePath stringByDeletingLastPathComponent];
−12
if (chdir(resources.fileSystemRepresentation)) return 1;
−13
setenv("CFFIXED_USER_HOME",[root stringByAppendingPathComponent:@"state"].fileSystemRepresentation,1);
−14
setenv("TMPDIR",[root stringByAppendingPathComponent:@"tmp/"].fileSystemRepresentation,1);
−15
if (!freopen([root stringByAppendingPathComponent:@"app.log"].fileSystemRepresentation,"a",stdout)) return 1;
−16
if (dup2(fileno(stdout),STDERR_FILENO)<0) return 1;
−17
NSString *exitPath=[root stringByAppendingPathComponent:@"app.exit"];
−18
unlink(exitPath.fileSystemRepresentation);
−19
setenv("SIGIL_UI_DEMO_EXIT_FILE",exitPath.fileSystemRepresentation,1);
−20
FILE *receipt=fopen([root stringByAppendingPathComponent:@"app.pid"].fileSystemRepresentation,"w");
−21
if (!receipt) return 1;
−22
fprintf(receipt,"%d\n",getpid()); fclose(receipt);
−23
NSString *executable=[resources stringByAppendingPathComponent:@"sigil-ui-demo"];
−24
argv[0]=(char *)executable.fileSystemRepresentation;
−25
execv(executable.fileSystemRepresentation,argv);
−26
perror("exec demo"); return 1;
−27
}
−28
}
demo/package.sglmodified
@@ -19,7 +19,9 @@
19
name: 'dev
20
output-dir: "build/dev"
21
debug?: #t
−22
optimize: 1))
+22
optimize: 1)
+23
(config name: 'darwin-arm64 toolchain: 'zig target: "aarch64-macos.15.0-none"
+24
features: '(cross darwin) output-dir: "build/darwin-arm64"))
25
26
dependencies: (list
27
(from-pkg name: "sigil/sigil-stdlib" version: "^0.24.0")
docs/macos.mdmodified
@@ -1,144 +1,67 @@
−1
# macOS windows
−2
−3
`(sigil ui window)` selects AppKit on macOS and Wayland on Linux. It exports
−4
`open-window`, geometry/focus/close accessors, `window-dispatch`,
−5
`window-make-ui`, `window-present!`, `window-present-ui!` and `window-close!`.
−6
Sizes and input coordinates are logical pixels; canvases and present damage
−7
use device pixels. Events have the forms documented in `(sigil ui wayland)`.
−8
Existing Wayland APIs and behavior remain available on Linux.
−9
−10
On macOS, `open-window` accepts `min-width` and `min-height` (logical pixels,
−11
default 240 and 160, each overridable down to zero). The native frame tracker
−12
honors those minima. Empty native content still uses a 1×1 logical backing
−13
placeholder and recovers on the next nonempty resize. Retained UI repainting
−14
clips text at the viewport, including partial glyphs; direct `render-items!`
−15
keeps its strict text bounds check.
−16
−17
The package compiles its Objective-C C ABI only for Darwin and links the system
−18
AppKit and QuartzCore frameworks. Wayland and Linux device code stay Linux-only.
−19
Offscreen rendering and PNG output work on either platform; opening fbdev or
−20
DRM on macOS raises an explicit unsupported-device error.
−21
−22
## Build the demo
−23
−24
Requires macOS 13 or later, Command Line Tools and Sigil 0.24.5. From outside
−25
the checkout, pass the absolute path of the installed Sigil executable:
+1
# macOS drawing adapter
+2
+3
sigil-ui 0.2.6 draws into sigil-window 0.2.0's SDK-free AppKit host.
+4
`(sigil ui window)` selects the AppKit adapter on Darwin. Existing
+5
`appkit-*` names in `(sigil ui appkit)` remain available: open/close,
+6
geometry, dispatch, clipboard, fullscreen, canvas/UI/overlay presentation
+7
and the event loop. The host owns all windows, input, child views,
+8
clipboard state and scheduling; this package owns rasterization and UI state.
+9
+10
Sizes and input coordinates are logical pixels. Canvas extents and explicit
+11
damage rectangles are device pixels. UI damage is scaled once before host
+12
presentation. Empty damage does not submit a frame. Presentation snapshots
+13
the host generation, and a UI associated with an older generation or a
+14
different window is refused. Recreate the UI after resize/scale changes.
+15
The native host copies the pixel and optional A8 alpha planes.
+16
+17
`appkit-run!` delegates to the host loop. During nested AppKit tracking,
+18
its paint callback repaints already realized display items at current
+19
geometry. It does not rerun components, update application state or dispatch
+20
browser work. The application step runs in the outer event loop. All native
+21
host calls stay on the process main thread.
+22
+23
Native embedding adapters include sigil-window's `native/appkit-host.h` and
+24
use `sigil_window_appkit_*` symbols. Host tokens are numeric identities, not
+25
NSWindow/NSView pointers. The old sigil-ui SUI geometry/key records are not
+26
binary-compatible with the new SW records; rebuild FFI layouts and callback
+27
conversions together. Host ABI and callback ownership are documented by
+28
sigil-window in `docs/appkit-abi.md`.
+29
+30
The UI package contains no Objective-C source or framework link flags.
+31
Its Darwin native sources are raster.c, png.c and surface-unavailable.c;
+32
AppKit native sources come from sigil-window. Named darwin-arm64 and
+33
darwin-amd64 configurations use Zig 0.16.0 and macOS 15.0. A complete demo
+34
also depends on its font backend: the currently released CoreText backend
+35
still needs a separate SDK-free migration. Do not mistake host/UI object
+36
builds for proof that the full demo or an application core cross-builds.
+37
+38
For cross-build dependency resolution with Sigil 0.24.8, supply target
+39
features before the manifest is loaded, as well as selecting the named
+40
configuration. The manifest uses these features to select sigil-window:
41
42
```text
−28
sigil /path/to/checkout/scripts/build-macos-demo.sgl /path/to/sigil build
−29
sigil /path/to/checkout/scripts/build-macos-demo.sgl /path/to/sigil bundle
−30
open "/path/to/checkout/build/macos/Sigil UI Demo.app"
+43
SIGIL_FEATURES=cross,darwin sigil deps install
+44
SIGIL_FEATURES=cross,darwin sigil build -c darwin-arm64
+45
SIGIL_FEATURES=cross,windows sigil build -c windows-amd64
46
```
47
−33
The driver uses the ordinary package build and a dependency redirect to the
−34
checkout for the demo. Build caches and dependency state stay below
−35
`build/macos/`. The bundle contains the compiled demo and bitmap fonts; its
−36
launcher records the PID and input-event log beside the bundle. The demo writes
−37
`app.exit` for controlled exits (0 for normal close, 1 for a caught error); the
−38
launcher removes an old receipt first. A missing receipt is not proof of a
−39
normal exit. Type sample
−40
text when testing. Close the window, press Escape, or use Command-Q to exit.
−41
This is a development bundle without distribution signing or notarization.
−42
Passing `--timing` to the demo enables pointer event-to-copy and event-to-draw
−43
statistics, sampled periodically and printed when the window closes. Drawing follows input processing
−44
without an intervening timer; the system cursor can still lead the software
−45
crosshair by a display frame.
−46
−47
## Presentation and event loop
−48
−49
The host keeps a native XRGB8888 buffer, copying only submitted damage from the
−50
Sigil canvas. A layer-backed NSView draws that buffer using a temporary CGImage
−51
and `CGContextDrawImage`, with interpolation disabled. This avoids asynchronous
−52
Core Animation ownership of a GC-managed bytevector and keeps exposure repaint
−53
independent of the application's next render. AppKit coalesces invalidation
−54
and schedules drawing. Frame events report view drawing, not a hardware
−55
presentation timestamp. No periodic frame timer runs while idle.
−56
−57
The window's integer backing scale determines canvas dimensions and `ui-scale`.
−58
Recreate the UI after a resize event, including a scale change between screens.
−59
Damage rectangles become logical view invalidations. Frame-edge drags are
−60
tracked through ordinary mouse events so each size returns to the application's
−61
dispatch loop. When AppKit takes over a native tracking path, `window-run!`
−62
uses its scoped common-mode application step to keep layout/rendering moving.
−63
A stale canvas stays anchored at the upper left at its original logical size.
−64
AppKit controls final display timing; other synchronous native tracking loops,
−65
such as menus, can postpone application updates until they return.
−66
−67
All window operations run on the main thread. Native input/delegate callbacks
−68
queue data. `window-run!` installs a scoped application step on a common-mode
−69
run-loop source so queued events and rendering continue during AppKit's native
−70
tracking loops. The step receives event batches and must update state/render
−71
synchronously: it must not suspend, block, capture a continuation or escape.
−72
Queue asynchronous work outside that callback. Its procedure stays GC-rooted;
−73
registration is removed on close or when the driver exits. Ordinary dispatch
−74
remains available, but a dispatch-only outer loop cannot update while AppKit
−75
holds the stack in a nested tracker.
+48
Use the matching features during Windows dependency installation too.
+49
Linux builds use the default host features and exclude sigil-window.
50
−77
Outside an async scheduler, dispatch blocks in
−78
AppKit until an event or the requested timeout. Within a scheduler, dispatch
−79
first yields through the normal I/O distributor, then watches current socket
−80
and raw descriptor waits through one-shot CFFileDescriptor run-loop sources.
−81
The earliest timer/I/O deadline bounds the wait; runnable tasks prevent blocking.
−82
The next dispatch distributes readiness using the existing scheduler. Keep the
−83
GUI task calling dispatch; blocking it elsewhere cannot service AppKit. Only
−84
predicate-based external waiters retain the scheduler's 100 ms fallback because
−85
they have no wake descriptor. The adapter follows the scheduler waiter record
−86
layout in Sigil 0.24 and has regression tests for that boundary.
+51
The former Objective-C host fixtures have moved to sigil-window's C native
+52
host and Sigil conformance fixtures. Use its sealed `qualify.sgl` packet on
+53
an arm64 Mac to validate the Linux-built host executables. This replaces
+54
the retired services-check/embedding-check/tracking-check/resize-check
+55
paths in build-macos-demo.sgl. Active menus, native fullscreen animation,
+56
outline text and browser integration need separate behavior qualification.
57
−88
## Input and gaps
+58
The drawing adapter's host-boundary checks run on Linux without a display:
59
−90
Keys report press/repeat/release, keysym-style names, text, the common modifier
−91
list and evdev position codes (zero for unmapped positions). Pointer coordinates
−92
start at the upper left. Scroll deltas use the Wayland sign convention; precise
−93
trackpad scrolling has zero wheel steps. Window focus and close requests use the
−94
same event forms as Wayland. A minimal app menu supplies Quit.
−95
−96
Text currently uses NSEvent characters. Composition, dead-key handling and IME
−97
need NSTextInputClient integration. Accessibility, clipboard, drag and drop,
−98
fullscreen/output selection, richer menus, Metal rendering and native fractional
−99
scaling remain follow-ups. There is no WKWebView or browser integration.
−100
−101
## Native child views and overlays
−102
−103
`(window-host-token window)` returns an opaque process-local AppKit host ID,
−104
or `#f` on platforms without this capability. Keep the window alive while using
−105
its token. The trusted C adapter API is [appkit-host.h](../native/appkit-host.h).
−106
Application code receives no NSWindow/NSView pointers. The adapter passes its
−107
unparented NSView to `sigil_ui_appkit_child_adopt`; the host retains it until
−108
removal or close, independently of the adapter's ownership. Tokens are never
−109
reused, and stale tokens fail. All calls and callbacks require the main thread.
−110
−111
Child allocations use logical top-left coordinates, with clipping at the child
−112
and content boundaries. Greater sibling order draws above lower order, beneath
−113
the canvas. Geometry notifications include actual content size and integer
−114
backing scale: the adapter supplies its layout policy by placing the child
−115
again. An empty allocation hides the child and restores UI focus. Notifications
−116
run before detach or window destruction while the child is still parented.
−117
A close notification replaces the detach notification. Callbacks may remove
−118
children reentrantly; a repeated removal fails. Drop adapter contexts only after
−119
their detach/close notification has returned.
−120
−121
`(window-present-overlay! window canvas alpha-mask)` presents the XRGB canvas
−122
above native children using a `(sigil ui mask)` A8 mask of the same device size.
−123
Zero alpha exposes the native child and passes pointer hit tests through; any
−124
nonzero alpha captures input for the UI, including partially transparent chrome.
−125
The host copies both planes and premultiplies its native image, leaving the
−126
canvas unchanged. Overlay presentation currently copies the whole image because
−127
alpha may change independently of RGB damage. Ordinary `window-present!` restores
−128
opaque canvas presentation. These overlay calls are currently macOS-only.
−129
−130
Scoped key filters run newest first before key equivalents or child responder
−131
dispatch. They receive copied key data and the target child ID (zero for UI).
−132
Returning true consumes the press; otherwise it passes. The chosen target and
−133
decision persist through repeats and release, without rerunning filters. Passed
−134
child events continue through AppKit exactly once; UI events keep the ordinary
−135
Sigil input forms. Filter removal, focus loss, detach or a reentrant focus change
−136
cancels pending ownership and suppresses stale releases. Explicit focus APIs
−137
select a child or the canvas; detaching a focused child restores the canvas
−138
responder. Focus and deactivation notifications let the adapter update its state.
+60
```text
+61
sigil -L test/appkit-host-stub test/check-appkit-adapter.sgl
+62
```
63
−140
Native notifications and filters must return synchronously: do not block,
−141
suspend, navigate, run JavaScript or enter Sigil from them. Queue such work for
−142
the ordinary event loop. No WebKit types or navigation policy are part of this
−143
API. `embedding-check` in the development driver tests it with a plain native
−144
child; `resize-check` and `tracking-check` cover the existing window controls.
+64
The controlled host verifies buffer/alpha forwarding, damage validation,
+65
window ownership and generation refusal. It does not stand in for native
+66
AppKit behavior. The legacy `(sigil ui appkit wait)` module forwards to
+67
sigil-window's scheduler implementation.
docs/release.mdadded
@@ -0,0 +1,17 @@
+1
# Release dependency gates
+2
+3
For 0.2.6, release sigil-window 0.2.0 before finalizing the UI release:
+4
+5
1. Publish the independently accepted sigil-window release.
+6
2. Install UI registry dependencies for the release targets and confirm the
+7
lock pins sigil-window 0.2.0 with its published integrity on Darwin/Windows.
+8
Linux must not acquire that dependency through sigil-ui.
+9
3. Commit the resolved registry lock; a local redirect is not release evidence.
+10
4. Run the full sigil-ui test suite on Linux against the real registry lock.
+11
5. Rerun the 22 AppKit drawing-boundary checks against that lock, with the
+12
controlled host first on the source path.
+13
6. Complete Windows cross-build and the real Mac host/drawing behavior gates,
+14
then publish sigil-ui.
+15
+16
The Mac font/drawing gate requires the accepted SDK-free CoreText backend.
+17
Source/object builds alone do not qualify native drawing or browser behavior.
docs/window-services.mdmodified
@@ -42,6 +42,7 @@ The existing `(sigil ui wayland)` calls retain their behavior, including
42
The portable dispatcher adds the service status without changing legacy events.
43
44
Qualification uses an isolated Wayland protocol server and an owned headless
−45
compositor. AppKit controls use hidden windows, controlled native transition
−46
notifications, and a private named pasteboard. They do not activate a window,
−47
change Spaces, or access the user's clipboard.
+45
compositor. AppKit host qualification belongs to sigil-window's Linux-built
+46
native/Sigil/WKWebView packet; its hidden-window controls use controlled
+47
transitions and a private named pasteboard. Real UI drawing with outline
+48
fonts requires the SDK-free sigil-font backend and its separate Mac gate.
native/appkit-host.hdeleted
@@ -1,63 +0,0 @@
−1
/* Trusted native-adapter API. No AppKit pointers cross the Sigil window API.
−2
* Every function and callback runs synchronously on the main thread. Callbacks
−3
* must not suspend, block, navigate or enter a script engine. Tokens are scoped
−4
* to this process and never reused; stale tokens fail without touching AppKit.
−5
*/
−6
#ifndef SIGIL_UI_APPKIT_HOST_H
−7
#define SIGIL_UI_APPKIT_HOST_H
−8
#include <stdbool.h>
−9
#include <stdint.h>
−10
#ifdef __cplusplus
−11
extern "C" {
−12
#endif
−13
−14
typedef uint64_t SUIHostToken;
−15
typedef uint64_t SUIChildToken;
−16
typedef uint64_t SUIHookToken;
−17
−18
typedef struct {
−19
double x, y, width, height; /* Logical top-left child allocation. */
−20
double content_width, content_height;
−21
int scale;
−22
bool visible, focused;
−23
} SUIGeometry;
−24
−25
typedef enum {
−26
SUI_HOST_GEOMETRY, SUI_HOST_FOCUS, SUI_HOST_DEACTIVATED,
−27
SUI_CHILD_WILL_DETACH, SUI_HOST_WILL_CLOSE
−28
} SUIHostEvent;
−29
typedef void (*SUIHostNotify)(void *context, SUIHostToken host,
−30
SUIChildToken child, SUIHostEvent event, const SUIGeometry *geometry);
−31
−32
typedef struct {
−33
int action; /* 0 release, 1 press, 2 repeat. */
−34
uint16_t hardware_code;
−35
uint32_t modifiers; /* shift=1 control=2 alt=4 super=8 caps=16 num=32 */
−36
SUIChildToken target; /* Zero means the sigil-ui canvas. */
−37
const char *name, *text; /* Copied data, valid only during this callback. */
−38
} SUIKey;
−39
typedef bool (*SUIKeyFilter)(void *context, SUIHostToken host, const SUIKey *key);
−40
−41
bool sigil_ui_appkit_host_valid(SUIHostToken host);
−42
bool sigil_ui_appkit_host_geometry(SUIHostToken host, SUIGeometry *geometry);
−43
/* native_view is an unparented NSView*, bridged by the trusted adapter. The
−44
* host retains it until detach; the adapter keeps its own ownership. Higher
−45
* order values draw above lower values, below the canvas overlay. */
−46
SUIChildToken sigil_ui_appkit_child_adopt(SUIHostToken host, void *native_view,
−47
double x, double y, double width, double height, int order,
−48
SUIHostNotify notify, void *context);
−49
bool sigil_ui_appkit_child_place(SUIHostToken host, SUIChildToken child,
−50
double x, double y, double width, double height, int order);
−51
bool sigil_ui_appkit_child_remove(SUIHostToken host, SUIChildToken child);
−52
bool sigil_ui_appkit_focus_child(SUIHostToken host, SUIChildToken child);
−53
bool sigil_ui_appkit_focus_ui(SUIHostToken host);
−54
/* Filters run newest first on a press; consume/pass and target stick through
−55
* its repeats/release. A passed child event follows native dispatch once.
−56
* Removing a filter or changing focus cancels its pending key ownership. */
−57
SUIHookToken sigil_ui_appkit_key_filter_add(SUIHostToken host,
−58
SUIKeyFilter filter, void *context);
−59
bool sigil_ui_appkit_key_filter_remove(SUIHostToken host, SUIHookToken hook);
−60
#ifdef __cplusplus
−61
}
−62
#endif
−63
#endif
native/appkit-host.incdeleted
@@ -1,252 +0,0 @@
−1
/* Included by appkit.m: registry and trusted adapter implementation. */
−2
@interface SUIContainerView : NSView
−3
@end
−4
@implementation SUIContainerView
−5
- (BOOL)isFlipped { return YES; }
−6
@end
−7
−8
@interface SUIChild : NSObject
−9
@property SUIChildToken token;
−10
@property(strong) NSView *view;
−11
@property(strong) SUIContainerView *container;
−12
@property int order;
−13
@property BOOL detaching;
−14
@property SUIHostNotify notify;
−15
@property void *context;
−16
@end
−17
@implementation SUIChild
−18
@end
−19
@interface SUIHook : NSObject
−20
@property SUIHookToken token;
−21
@property SUIKeyFilter filter;
−22
@property void *context;
−23
@end
−24
@implementation SUIHook
−25
@end
−26
@interface SUIKeyOwner : NSObject
−27
@property SUIChildToken target;
−28
@property BOOL consumed;
−29
@end
−30
@implementation SUIKeyOwner
−31
@end
−32
−33
static NSMapTable<NSNumber *, SUIHost *> *hostRegistry;
−34
static uint64_t tokenSerial;
−35
static uint64_t freshToken(void) { return tokenSerial<(UINT64_C(1)<<48) ? ++tokenSerial : 0; }
−36
static SUIHost *findHost(SUIHostToken token) {
−37
if (!NSThread.isMainThread || !token) return nil;
−38
SUIHost *host=[hostRegistry objectForKey:@(token)];
−39
return host.closed ? nil : host;
−40
}
−41
static SUIHostToken hostToken(SUIHost *host) {
−42
if (!NSThread.isMainThread || host.closed || host.closing) return 0;
−43
if (!host.token) {
−44
if (!hostRegistry) hostRegistry=[NSMapTable strongToWeakObjectsMapTable];
−45
host.token=freshToken();
−46
if (host.token) [hostRegistry setObject:host forKey:@(host.token)];
−47
host.children=[NSMutableDictionary new]; host.hooks=[NSMutableArray new];
−48
host.keyOwners=[NSMutableDictionary new]; host.canceledKeys=[NSMutableSet new];
−49
}
−50
return host.token;
−51
}
−52
static SUIChild *focusedChild(SUIHost *host) {
−53
NSResponder *responder=host.window.firstResponder;
−54
if (![responder isKindOfClass:NSView.class]) return nil;
−55
for (SUIChild *child in host.children.allValues) {
−56
if (!child.detaching && !child.container.hidden &&
−57
(responder==child.view || [(NSView *)responder isDescendantOf:child.view])) return child;
−58
}
−59
return nil;
−60
}
−61
static SUIGeometry childGeometry(SUIHost *host, SUIChild *child) {
−62
NSRect frame=child ? child.container.frame : host.view.bounds;
−63
return (SUIGeometry){frame.origin.x,frame.origin.y,frame.size.width,frame.size.height,
−64
host.view.bounds.size.width,host.view.bounds.size.height,host.scale,
−65
child ? !child.container.hidden : !NSIsEmptyRect(host.view.bounds),
−66
host.focused && (child ? focusedChild(host)==child : focusedChild(host)==nil)};
−67
}
−68
static void notifyChild(SUIHost *host, SUIChild *child, SUIHostEvent event) {
−69
if (child.notify) {
−70
SUIGeometry geometry=childGeometry(host,child);
−71
child.notify(child.context,host.token,child.token,event,&geometry);
−72
}
−73
}
−74
static void cancelKeys(SUIHost *host) {
−75
host.keyEpoch++;
−76
[host.canceledKeys addObjectsFromArray:host.keyOwners.allKeys];
−77
[host.keyOwners removeAllObjects];
−78
}
−79
static void hostFocusChanged(SUIHost *host, BOOL deactivated) {
−80
SUIChildToken target=focusedChild(host).token;
−81
if (target==host.notifiedFocus && host.focused==host.notifiedActive && !deactivated) return;
−82
host.notifiedFocus=target; host.notifiedActive=host.focused; cancelKeys(host);
−83
for (SUIChild *child in host.children.allValues) {
−84
if (!child.detaching) notifyChild(host,child,deactivated ? SUI_HOST_DEACTIVATED : SUI_HOST_FOCUS);
−85
}
−86
}
−87
static void hostGeometryChanged(SUIHost *host) {
−88
for (SUIChild *child in host.children.allValues) {
−89
if (!child.detaching) notifyChild(host,child,SUI_HOST_GEOMETRY);
−90
}
−91
}
−92
static void ensureContent(SUIHost *host) {
−93
if (host.content) return;
−94
NSRect bounds=host.view.bounds;
−95
host.content=[[SUIContainerView alloc] initWithFrame:bounds];
−96
host.content.wantsLayer=YES; host.content.layer.masksToBounds=YES;
−97
SUIView *canvas=host.view;
−98
BOOL uiFocused=host.window.firstResponder==canvas;
−99
[canvas removeFromSuperview];
−100
host.window.contentView=host.content;
−101
canvas.frame=host.content.bounds;
−102
canvas.autoresizingMask=NSViewWidthSizable | NSViewHeightSizable;
−103
[host.content addSubview:canvas];
−104
if (uiFocused) [host.window makeFirstResponder:canvas];
−105
}
−106
static BOOL validAllocation(double x, double y, double width, double height) {
−107
return isfinite(x) && isfinite(y) && isfinite(width) && isfinite(height) &&
−108
fabs(x)<=16384 && fabs(y)<=16384 && width>=0 && height>=0 && width<=16384 && height<=16384;
−109
}
−110
static void orderChildren(SUIHost *host) {
−111
NSArray<SUIChild *> *children=[host.children.allValues sortedArrayUsingComparator:
−112
^NSComparisonResult(SUIChild *a, SUIChild *b) {
−113
if (a.order!=b.order) return a.order<b.order ? NSOrderedAscending : NSOrderedDescending;
−114
return a.token<b.token ? NSOrderedAscending : NSOrderedDescending;
−115
}];
−116
for (SUIChild *child in children) {
−117
[host.content addSubview:child.container positioned:NSWindowBelow relativeTo:host.view];
−118
}
−119
}
−120
bool sigil_ui_appkit_host_valid(SUIHostToken token) { return findHost(token)!=nil; }
−121
bool sigil_ui_appkit_host_geometry(SUIHostToken token, SUIGeometry *geometry) {
−122
SUIHost *host=findHost(token); if (!host || !geometry) return false;
−123
*geometry=childGeometry(host,nil); return true;
−124
}
−125
bool sigil_ui_appkit_child_place(SUIHostToken token, SUIChildToken id,
−126
double x, double y, double width, double height, int order) {
−127
SUIHost *host=findHost(token); SUIChild *child=host.children[@(id)];
−128
if (!host || host.closing || !child || child.detaching || !validAllocation(x,y,width,height)) return false;
−129
NSRect frame=NSMakeRect(x,y,width,height);
−130
BOOL changed=!NSEqualRects(frame,child.container.frame) || order!=child.order;
−131
child.order=order; child.container.frame=frame;
−132
child.view.frame=NSMakeRect(0,0,width,height);
−133
child.container.hidden=width==0 || height==0;
−134
if (child.container.hidden && host.notifiedFocus==id) sigil_ui_appkit_focus_ui(token);
−135
orderChildren(host);
−136
if (changed) notifyChild(host,child,SUI_HOST_GEOMETRY);
−137
return true;
−138
}
−139
SUIChildToken sigil_ui_appkit_child_adopt(SUIHostToken token, void *nativeView,
−140
double x, double y, double width, double height, int order,
−141
SUIHostNotify notify, void *context) {
−142
SUIHost *host=findHost(token);
−143
if (!host || host.closing || !nativeView || !validAllocation(x,y,width,height)) return 0;
−144
NSView *view=(__bridge NSView *)nativeView;
−145
if (![view isKindOfClass:NSView.class] || view.superview || view.window) return 0;
−146
SUIChild *child=[SUIChild new]; child.token=freshToken(); if (!child.token) return 0;
−147
ensureContent(host);
−148
child.view=view; child.notify=notify; child.context=context;
−149
child.container=[[SUIContainerView alloc] initWithFrame:NSZeroRect];
−150
child.container.wantsLayer=YES; child.container.layer.masksToBounds=YES;
−151
[child.container addSubview:view]; host.children[@(child.token)]=child;
−152
[host.content addSubview:child.container positioned:NSWindowBelow relativeTo:host.view];
−153
sigil_ui_appkit_child_place(token,child.token,x,y,width,height,order);
−154
/* A notification may synchronously remove the new child or close the host. */
−155
return host.children[@(child.token)]==child && !host.closed ? child.token : 0;
−156
}
−157
static BOOL removeChild(SUIHost *host, SUIChild *child, SUIHostEvent event) {
−158
if (!child || child.detaching) return false;
−159
child.detaching=YES; cancelKeys(host);
−160
if (host.notifiedFocus==child.token) {
−161
[host.window makeFirstResponder:host.view]; hostFocusChanged(host,NO);
−162
}
−163
notifyChild(host,child,event);
−164
[child.view removeFromSuperview]; [child.container removeFromSuperview];
−165
[host.children removeObjectForKey:@(child.token)];
−166
child.notify=NULL; child.context=NULL;
−167
return true;
−168
}
−169
bool sigil_ui_appkit_child_remove(SUIHostToken token, SUIChildToken child) {
−170
SUIHost *host=findHost(token); return host && removeChild(host,host.children[@(child)],SUI_CHILD_WILL_DETACH);
−171
}
−172
bool sigil_ui_appkit_focus_ui(SUIHostToken token) {
−173
SUIHost *host=findHost(token); if (!host || host.closing) return false;
−174
BOOL result=[host.window makeFirstResponder:host.view]; hostFocusChanged(host,NO); return result;
−175
}
−176
bool sigil_ui_appkit_focus_child(SUIHostToken token, SUIChildToken id) {
−177
SUIHost *host=findHost(token); SUIChild *child=host.children[@(id)];
−178
if (!host || host.closing || !child || child.detaching || child.container.hidden) return false;
−179
BOOL result=[host.window makeFirstResponder:child.view]; hostFocusChanged(host,NO); return result;
−180
}
−181
SUIHookToken sigil_ui_appkit_key_filter_add(SUIHostToken token, SUIKeyFilter filter, void *context) {
−182
SUIHost *host=findHost(token); if (!host || host.closing || !filter) return 0;
−183
SUIHook *hook=[SUIHook new]; hook.token=freshToken(); if (!hook.token) return 0;
−184
hook.filter=filter; hook.context=context; [host.hooks addObject:hook]; return hook.token;
−185
}
−186
bool sigil_ui_appkit_key_filter_remove(SUIHostToken token, SUIHookToken id) {
−187
SUIHost *host=findHost(token); if (!host) return false;
−188
for (SUIHook *hook in host.hooks.copy) {
−189
if (hook.token==id) { cancelKeys(host); [host.hooks removeObject:hook]; return true; }
−190
}
−191
return false;
−192
}
−193
static void hostWillClose(SUIHost *host) {
−194
cancelKeys(host); [host.hooks removeAllObjects];
−195
for (SUIChild *child in host.children.allValues) removeChild(host,child,SUI_HOST_WILL_CLOSE);
−196
[hostRegistry removeObjectForKey:@(host.token)]; host.content=nil;
−197
}
−198
−199
static BOOL routeKey(SUIHost *host, NSEvent *event) {
−200
if (!host.token) { [(SUIApplication *)NSApp sendUIKey:event host:host]; return NO; }
−201
hostFocusChanged(host,NO);
−202
int action=event.type==NSEventTypeKeyUp ? 0 : 1;
−203
if (event.type==NSEventTypeKeyDown && event.isARepeat) action=2;
−204
if (event.type==NSEventTypeFlagsChanged) {
−205
/* The UI decoder already handles each modifier's release correctly.
−206
* Determine the hook action from its hardware-specific flag as well. */
−207
NSEventModifierFlags flag=0;
−208
switch (event.keyCode) {
−209
case 54: case 55: flag=NSEventModifierFlagCommand; break;
−210
case 56: case 60: flag=NSEventModifierFlagShift; break;
−211
case 58: case 61: flag=NSEventModifierFlagOption; break;
−212
case 59: case 62: flag=NSEventModifierFlagControl; break;
−213
case 57: flag=NSEventModifierFlagCapsLock; break;
−214
default:
−215
/* System shortcuts can synchronize flags with an unmapped
−216
* key code. It is neither a key release nor a text event. */
−217
if (focusedChild(host)) return YES;
−218
[(SUIApplication *)NSApp sendUIKey:event host:host];
−219
return NO;
−220
}
−221
action=(event.modifierFlags & flag) ? 1 : 0;
−222
}
−223
NSNumber *code=@(event.keyCode);
−224
if (action==1) [host.canceledKeys removeObject:code];
−225
else if ([host.canceledKeys containsObject:code]) return NO;
−226
SUIKeyOwner *owner=host.keyOwners[code];
−227
if (!owner) {
−228
owner=[SUIKeyOwner new]; owner.target=focusedChild(host).token;
−229
__attribute__((objc_precise_lifetime)) NSString *name=[keyName(event) copy];
−230
__attribute__((objc_precise_lifetime)) NSString *text=
−231
event.type==NSEventTypeKeyDown ? [event.characters copy] : @"";
−232
SUIKey key={action,event.keyCode,mods(event.modifierFlags),owner.target,
−233
name.UTF8String ?: "",text.UTF8String ?: ""};
−234
uint64_t epoch=host.keyEpoch;
−235
for (SUIHook *hook in (action==1 ? host.hooks.reverseObjectEnumerator.allObjects : @[])) {
−236
if (![host.hooks containsObject:hook]) continue;
−237
if (hook.filter(hook.context,host.token,&key)) { owner.consumed=YES; break; }
−238
if (host.closed || host.closing) return NO;
−239
}
−240
if (host.closed || host.closing) return NO;
−241
if (epoch!=host.keyEpoch || focusedChild(host).token!=owner.target ||
−242
[host.canceledKeys containsObject:code]) {
−243
[host.canceledKeys addObject:code];
−244
return NO;
−245
}
−246
if (action!=0) host.keyOwners[code]=owner;
−247
}
−248
if (action==0) [host.keyOwners removeObjectForKey:code];
−249
if (owner.consumed) return NO;
−250
if (owner.target) return YES;
−251
[(SUIApplication *)NSApp sendUIKey:event host:host]; return NO;
−252
}
native/appkit.mdeleted
@@ -1,740 +0,0 @@
−1
/* AppKit host for the retained software canvas. Call only on the main thread.
−2
* Delegates queue data. A scoped tracking-mode source can run a synchronous
−3
* application render step; that step must never suspend or escape. */
−4
#import <AppKit/AppKit.h>
−5
#import <QuartzCore/QuartzCore.h>
−6
#include <sigil/sigil.h>
−7
#include <math.h>
−8
#include <string.h>
−9
#include "appkit-host.h"
−10
#include "window-services.h"
−11
−12
@class SUIChild, SUIHook, SUIKeyOwner;
−13
−14
@interface SUIEvent : NSObject
−15
@property int type;
−16
@property int64_t a, b, c, d, e, f;
−17
@property(copy) NSString *name;
−18
@property(copy) NSString *text;
−19
@end
−20
@implementation SUIEvent
−21
@end
−22
−23
@class SUIHost;
−24
@interface SUIView : NSView
−25
@property(weak) SUIHost *host;
−26
@property(strong) NSMutableData *pixels;
−27
@property(strong) NSMutableData *alpha;
−28
@property int pixelWidth, pixelHeight;
−29
@property(strong) NSTrackingArea *tracking;
−30
@end
−31
−32
@interface SUIHost : NSObject <NSWindowDelegate>
−33
{
−34
@public
−35
SuiFullscreenRequest fullscreenRequest;
−36
}
−37
@property(strong) NSWindow *window;
−38
@property(strong) SUIView *view;
−39
@property(strong) NSMutableArray<SUIEvent *> *events;
−40
@property(strong) SUIEvent *current;
−41
@property int width, height, scale;
−42
@property BOOL focused, closed, overflow;
−43
@property NSEventModifierFlags modifiers;
−44
@property int resizeEdges;
−45
@property NSRect resizeFrame;
−46
@property NSPoint resizeOrigin;
−47
@property BOOL timing;
−48
@property double pointerTime, presentedPointerTime, copyTotal, copyMax, drawTotal, drawMax;
−49
@property unsigned long copyCount, drawCount;
−50
@property SigilVM *trackingVM;
−51
@property Value trackingHandler;
−52
@property CFRunLoopSourceRef trackingSource;
−53
@property BOOL inTrackingStep;
−54
@property SUIHostToken token;
−55
@property BOOL closing;
−56
@property(strong) NSView *content;
−57
@property(strong) NSMutableDictionary<NSNumber *, SUIChild *> *children;
−58
@property(strong) NSMutableArray<SUIHook *> *hooks;
−59
@property(strong) NSMutableDictionary<NSNumber *, SUIKeyOwner *> *keyOwners;
−60
@property(strong) NSMutableSet<NSNumber *> *canceledKeys;
−61
@property SUIChildToken notifiedFocus;
−62
@property BOOL notifiedActive;
−63
@property uint64_t keyEpoch;
−64
@property BOOL inKeyCallback;
−65
@property BOOL fullscreenAcknowledged;
−66
@property int fullscreenTransition;
−67
@property uint64_t fullscreenGeneration;
−68
@property uint64_t fullscreenTransitionGeneration;
−69
@property CFRunLoopTimerRef fullscreenTimer;
−70
#ifdef SUI_WINDOW_SERVICES_TEST
−71
@property(strong) NSPasteboard *servicePasteboard;
−72
#endif
−73
- (void)geometry;
−74
- (void)emit:(int)type a:(int64_t)a b:(int64_t)b c:(int64_t)c d:(int64_t)d e:(int64_t)e f:(int64_t)f;
−75
- (void)key:(NSEvent *)event;
−76
@end
−77
−78
static NSHashTable<SUIHost *> *hosts;
−79
static Value hostTag;
−80
static __weak SUIHost *resizingHost;
−81
static void hostGeometryChanged(SUIHost *host);
−82
static void hostFocusChanged(SUIHost *host, BOOL deactivated);
−83
static void hostWillClose(SUIHost *host);
−84
static BOOL routeKey(SUIHost *host, NSEvent *event);
−85
static SUIHostToken hostToken(SUIHost *host);
−86
static void windowServiceConfigured(SUIHost *host, BOOL actual);
−87
static void windowServiceFailed(SUIHost *host);
−88
static void stopWindowServices(SUIHost *host);
−89
−90
static void stopTrackingStep(SUIHost *host) {
−91
if (host.trackingSource) {
−92
CFRunLoopSourceInvalidate(host.trackingSource);
−93
CFRelease(host.trackingSource); host.trackingSource=NULL;
−94
}
−95
host.trackingHandler=SIGIL_FALSE; host.trackingVM=NULL;
−96
}
−97
static void trackingStepReady(void *info) {
−98
SUIHost *host=(__bridge SUIHost *)info;
−99
CFStringRef mode=CFRunLoopCopyCurrentMode(CFRunLoopGetMain());
−100
BOOL tracking=mode && CFEqual(mode,(__bridge CFStringRef)NSEventTrackingRunLoopMode);
−101
if (mode) CFRelease(mode);
−102
if (!tracking || host.closed || host.inTrackingStep || !host.events.count ||
−103
host.trackingHandler==SIGIL_FALSE || !host.trackingVM) return;
−104
host.inTrackingStep=YES;
−105
SigilVM *vm=host.trackingVM;
−106
Value result=sigil_applyN(vm,host.trackingHandler,0,NULL);
−107
host.inTrackingStep=NO;
−108
if (result==SIGIL_FALSE || sigil_error_message(vm)) host.trackingHandler=SIGIL_FALSE;
−109
if (!host.closed) {
−110
[host.view displayIfNeeded];
−111
[CATransaction flush];
−112
}
−113
}
−114
static void traceHost(SigilVM *vm, void *data) {
−115
SUIHost *host=(__bridge SUIHost *)data;
−116
sigil__gc_mark_foreign_value(vm,host.trackingHandler);
−117
}
−118
−119
static void timingReport(SUIHost *host) {
−120
fprintf(stderr,"TIMING pointer copy count=%lu mean=%.2f max=%.2f ms; draw count=%lu mean=%.2f max=%.2f ms\n",
−121
host.copyCount,host.copyCount ? host.copyTotal/host.copyCount : 0,host.copyMax,
−122
host.drawCount,host.drawCount ? host.drawTotal/host.drawCount : 0,host.drawMax);
−123
}
−124
−125
enum { ResizeLeft=1, ResizeRight=2, ResizeBottom=4, ResizeTop=8 };
−126
static const double resizeOutsideBand=16;
−127
−128
/* AppKit's standard frame tracker nests inside sendEvent: until mouse-up.
−129
* Own just the frame-edge drag so the outer Sigil loop can consume each size
−130
* event and render a new canvas between drags, without reentering the VM. */
−131
static BOOL beginResize(SUIHost *host, NSPoint point) {
−132
NSRect frame=host.window.frame;
−133
if (!NSPointInRect(point,NSInsetRect(frame,-resizeOutsideBand,-resizeOutsideBand)) ||
−134
(host.window.styleMask & NSWindowStyleMaskFullScreen)) return NO;
−135
int edges=0;
−136
if (point.x>=NSMinX(frame)-resizeOutsideBand && point.x<=NSMinX(frame)+5) edges|=ResizeLeft;
−137
else if (point.x>=NSMaxX(frame)-5 && point.x<=NSMaxX(frame)+resizeOutsideBand) edges|=ResizeRight;
−138
if (point.y>=NSMinY(frame)-resizeOutsideBand && point.y<=NSMinY(frame)+5) edges|=ResizeBottom;
−139
else if (point.y>=NSMaxY(frame)-5 && point.y<=NSMaxY(frame)+resizeOutsideBand) edges|=ResizeTop;
−140
if (!edges) return NO;
−141
host.resizeEdges=edges; host.resizeFrame=frame; host.resizeOrigin=point;
−142
resizingHost=host;
−143
return YES;
−144
}
−145
static void updateResize(SUIHost *host, NSPoint point) {
−146
NSRect frame=host.resizeFrame;
−147
double dx=point.x-host.resizeOrigin.x, dy=point.y-host.resizeOrigin.y;
−148
NSRect minimum=[host.window frameRectForContentRect:NSMakeRect(0,0,
−149
MAX(0,host.window.contentMinSize.width),MAX(0,host.window.contentMinSize.height))];
−150
if (host.resizeEdges & ResizeLeft) {
−151
frame.size.width=MAX(minimum.size.width,frame.size.width-dx);
−152
frame.origin.x=NSMaxX(host.resizeFrame)-frame.size.width;
−153
} else if (host.resizeEdges & ResizeRight) frame.size.width=MAX(minimum.size.width,frame.size.width+dx);
−154
if (host.resizeEdges & ResizeBottom) {
−155
frame.size.height=MAX(minimum.size.height,frame.size.height-dy);
−156
frame.origin.y=NSMaxY(host.resizeFrame)-frame.size.height;
−157
} else if (host.resizeEdges & ResizeTop) frame.size.height=MAX(minimum.size.height,frame.size.height+dy);
−158
[host.window setFrame:frame display:YES animate:NO];
−159
[host geometry];
−160
}
−161
−162
static int mods(NSEventModifierFlags f) {
−163
return ((f & NSEventModifierFlagShift) ? 1 : 0) |
−164
((f & NSEventModifierFlagControl) ? 2 : 0) |
−165
((f & NSEventModifierFlagOption) ? 4 : 0) |
−166
((f & NSEventModifierFlagCommand) ? 8 : 0) |
−167
((f & NSEventModifierFlagCapsLock) ? 16 : 0);
−168
}
−169
−170
/* Apple hardware positions to Linux evdev positions, independent of layout.
−171
* Unmapped keys use zero rather than exposing platform-specific codes. */
−172
static int evdev(unsigned code) {
−173
static const unsigned short table[128] = {
−174
[0]=30,[1]=31,[2]=32,[3]=33,[4]=35,[5]=34,[6]=44,[7]=45,[8]=46,[9]=47,
−175
[11]=48,[12]=16,[13]=17,[14]=18,[15]=19,[16]=21,[17]=20,[18]=2,[19]=3,
−176
[20]=4,[21]=5,[22]=7,[23]=6,[24]=13,[25]=10,[26]=8,[27]=12,[28]=9,[29]=11,
−177
[30]=27,[31]=24,[32]=22,[33]=26,[34]=23,[35]=25,[36]=28,[37]=38,[38]=36,
−178
[39]=40,[40]=37,[41]=39,[42]=43,[43]=51,[44]=53,[45]=49,[46]=50,[47]=52,
−179
[48]=15,[49]=57,[50]=41,[51]=14,[53]=1,[54]=126,[55]=125,[56]=42,
−180
[57]=58,[58]=56,[59]=29,[60]=54,[61]=100,[62]=97,[65]=83,[67]=55,
−181
[69]=78,[71]=69,[75]=98,[76]=96,[78]=74,[81]=117,[82]=82,[83]=79,
−182
[84]=80,[85]=81,[86]=75,[87]=76,[88]=77,[89]=71,[91]=72,[92]=73,
−183
[96]=63,[97]=64,[98]=65,[99]=61,[100]=66,[101]=67,[103]=87,[109]=68,
−184
[111]=88,[114]=110,[115]=102,[116]=104,[117]=111,[118]=62,[119]=107,
−185
[120]=60,[121]=109,[122]=59,[123]=105,[124]=106,[125]=108,[126]=103
−186
};
−187
return code < 128 ? table[code] : 0;
−188
}
−189
−190
static NSString *keyName(NSEvent *event) {
−191
switch (event.keyCode) {
−192
case 36: case 76: return @"Return";
−193
case 48: return (event.modifierFlags & NSEventModifierFlagShift) ? @"ISO_Left_Tab" : @"Tab";
−194
case 49: return @"space";
−195
case 51: return @"BackSpace";
−196
case 53: return @"Escape";
−197
case 54: return @"Super_R"; case 55: return @"Super_L";
−198
case 56: return @"Shift_L"; case 60: return @"Shift_R";
−199
case 57: return @"Caps_Lock";
−200
case 58: return @"Alt_L"; case 61: return @"Alt_R";
−201
case 59: return @"Control_L"; case 62: return @"Control_R";
−202
case 115: return @"Home"; case 119: return @"End";
−203
case 116: return @"Page_Up"; case 121: return @"Page_Down";
−204
case 117: return @"Delete"; case 114: return @"Insert";
−205
case 123: return @"Left"; case 124: return @"Right";
−206
case 125: return @"Down"; case 126: return @"Up";
−207
}
−208
NSString *s = event.charactersIgnoringModifiers ?: @"";
−209
if (s.length == 1) {
−210
unichar c = [s characterAtIndex:0];
−211
if (c >= NSF1FunctionKey && c <= NSF35FunctionKey)
−212
return [NSString stringWithFormat:@"F%d", c - NSF1FunctionKey + 1];
−213
static NSString *punct = @"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
−214
static NSArray *names;
−215
if (!names) names = @[@"exclam",@"quotedbl",@"numbersign",@"dollar",@"percent",
−216
@"ampersand",@"apostrophe",@"parenleft",@"parenright",@"asterisk",@"plus",
−217
@"comma",@"minus",@"period",@"slash",@"colon",@"semicolon",@"less",@"equal",
−218
@"greater",@"question",@"at",@"bracketleft",@"backslash",@"bracketright",
−219
@"asciicircum",@"underscore",@"grave",@"braceleft",@"bar",@"braceright",@"asciitilde"];
−220
NSRange r = [punct rangeOfString:s];
−221
if (r.location != NSNotFound) return names[r.location];
−222
if (c < 128) return s;
−223
return [NSString stringWithFormat:@"U%04X", c];
−224
}
−225
return @"";
−226
}
−227
−228
@implementation SUIHost
−229
- (void)emit:(int)type a:(int64_t)a b:(int64_t)b c:(int64_t)c d:(int64_t)d e:(int64_t)e f:(int64_t)f {
−230
SUIEvent *last=self.events.lastObject;
−231
if ((type==8 || type==1) && last.type==type && last.a==a && last.b==b && last.c==c) return;
−232
if (self.events.count >= 4096) { self.overflow = YES; return; }
−233
SUIEvent *event = [SUIEvent new];
−234
event.type=type; event.a=a; event.b=b; event.c=c; event.d=d; event.e=e; event.f=f;
−235
[self.events addObject:event];
−236
if (type!=3 && self.trackingSource && !self.inTrackingStep) {
−237
CFRunLoopSourceSignal(self.trackingSource);
−238
CFRunLoopWakeUp(CFRunLoopGetMain());
−239
}
−240
}
−241
- (void)geometry {
−242
/* Keep allocation dimensions positive even when native content is empty.
−243
* A later nonempty size emits another resize and replaces this backing. */
−244
int width = MAX(1, (int)floor(self.view.bounds.size.width));
−245
int height = MAX(1, (int)floor(self.view.bounds.size.height));
−246
int scale = MAX(1, (int)lround(self.window.backingScaleFactor));
−247
if (width != self.width || height != self.height || scale != self.scale) {
−248
self.width=width; self.height=height; self.scale=scale;
−249
[self emit:1 a:width b:height c:scale d:0 e:0 f:0];
−250
hostGeometryChanged(self);
−251
}
−252
}
−253
- (void)windowDidResize:(NSNotification *)n { (void)n; [self geometry]; }
−254
- (void)windowDidChangeBackingProperties:(NSNotification *)n { (void)n; [self geometry]; }
−255
- (void)windowWillEnterFullScreen:(NSNotification *)n { (void)n; self.fullscreenTransition=1; }
−256
- (void)windowWillExitFullScreen:(NSNotification *)n { (void)n; self.fullscreenTransition=-1; }
−257
- (void)windowDidEnterFullScreen:(NSNotification *)n { (void)n; windowServiceConfigured(self,YES); }
−258
- (void)windowDidExitFullScreen:(NSNotification *)n { (void)n; windowServiceConfigured(self,NO); }
−259
- (void)windowDidFailToEnterFullScreen:(NSWindow *)window { (void)window; windowServiceFailed(self); }
−260
- (void)windowDidFailToExitFullScreen:(NSWindow *)window { (void)window; windowServiceFailed(self); }
−261
- (void)windowDidBecomeKey:(NSNotification *)n {
−262
(void)n; self.focused=YES; [self emit:5 a:1 b:0 c:0 d:0 e:0 f:0];
−263
hostFocusChanged(self,NO);
−264
}
−265
- (void)windowDidResignKey:(NSNotification *)n {
−266
(void)n; self.focused=NO; self.modifiers=0; [self emit:5 a:0 b:0 c:0 d:0 e:0 f:0];
−267
hostFocusChanged(self,YES);
−268
}
−269
- (BOOL)windowShouldClose:(NSWindow *)sender {
−270
(void)sender; [self emit:2 a:0 b:0 c:0 d:0 e:0 f:0]; return NO;
−271
}
−272
- (void)key:(NSEvent *)event {
−273
int action = event.type == NSEventTypeKeyUp ? 0 : 1;
−274
if (event.type == NSEventTypeKeyDown && event.isARepeat) action=2;
−275
if (event.type == NSEventTypeFlagsChanged) {
−276
NSEventModifierFlags mask = 0;
−277
switch (event.keyCode) {
−278
case 54: case 55: mask=NSEventModifierFlagCommand; break;
−279
case 56: case 60: mask=NSEventModifierFlagShift; break;
−280
case 57: mask=NSEventModifierFlagCapsLock; break;
−281
case 58: case 61: mask=NSEventModifierFlagOption; break;
−282
case 59: case 62: mask=NSEventModifierFlagControl; break;
−283
default: return;
−284
}
−285
action = (event.modifierFlags & mask) ? 1 : 0;
−286
}
−287
[self emit:4 a:action b:0 c:mods(event.modifierFlags) d:evdev(event.keyCode) e:0 f:0];
−288
if (self.overflow) return;
−289
SUIEvent *key = self.events.lastObject;
−290
key.name = keyName(event);
−291
NSString *text = event.type == NSEventTypeKeyDown ? (event.characters ?: @"") : @"";
−292
BOOL printable = text.length && [text characterAtIndex:0] >= 32 &&
−293
!([text characterAtIndex:0] >= 0xf700 && [text characterAtIndex:0] <= 0xf8ff);
−294
key.text = action && event.type != NSEventTypeFlagsChanged && printable &&
−295
!(event.modifierFlags & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) ? text : @"";
−296
self.modifiers = event.modifierFlags;
−297
}
−298
@end
−299
−300
@interface SUIApplication : NSApplication
−301
- (NSPoint)resizePointForEvent:(NSEvent *)event;
−302
- (void)sendUIKey:(NSEvent *)event host:(SUIHost *)host;
−303
- (void)forwardNativeEvent:(NSEvent *)event;
−304
@end
−305
@implementation SUIApplication
−306
- (NSPoint)resizePointForEvent:(NSEvent *)event {
−307
/* Use the event's recorded position, not the current global cursor. The
−308
* cursor may already have left the resize band when mouse-down is read. */
−309
CGEventRef native=event.CGEvent;
−310
if (native) {
−311
CGPoint point=CGEventGetLocation(native);
−312
return NSMakePoint(point.x,NSMaxY(NSScreen.screens.firstObject.frame)-point.y);
−313
}
−314
return event.window ? [event.window convertPointToScreen:event.locationInWindow] : event.locationInWindow;
−315
}
−316
- (void)sendEvent:(NSEvent *)event {
−317
SUIHost *drag=resizingHost;
−318
if (drag && (event.type==NSEventTypeLeftMouseDragged || event.type==NSEventTypeLeftMouseUp)) {
−319
updateResize(drag,[self resizePointForEvent:event]);
−320
if (event.type==NSEventTypeLeftMouseUp) { drag.resizeEdges=0; resizingHost=nil; }
−321
return;
−322
}
−323
for (SUIHost *host in hosts.allObjects) {
−324
if (event.type==NSEventTypeLeftMouseDown &&
−325
(event.window==host.window || (!event.window && host.window.keyWindow)) &&
−326
beginResize(host,[self resizePointForEvent:event])) return;
−327
if (event.window == host.window && (event.type == NSEventTypeKeyDown ||
−328
event.type == NSEventTypeKeyUp || event.type == NSEventTypeFlagsChanged)) {
−329
host.inKeyCallback=YES;
−330
@try {
−331
if (routeKey(host,event)) { [self forwardNativeEvent:event]; hostFocusChanged(host,NO); }
−332
} @finally { host.inKeyCallback=NO; }
−333
return;
−334
}
−335
}
−336
[super sendEvent:event];
−337
for (SUIHost *host in hosts.allObjects) {
−338
if (event.window==host.window) hostFocusChanged(host,NO);
−339
}
−340
}
−341
- (void)forwardNativeEvent:(NSEvent *)event { [super sendEvent:event]; }
−342
/* UI-owned events preserve the existing minimal menu and event forms. */
−343
- (void)sendUIKey:(NSEvent *)event host:(SUIHost *)host {
−344
if (event.type == NSEventTypeKeyDown && (event.modifierFlags & NSEventModifierFlagCommand) &&
−345
[event.charactersIgnoringModifiers.lowercaseString isEqualToString:@"q"]) {
−346
for (SUIHost *h in hosts.allObjects) [h emit:2 a:0 b:0 c:0 d:0 e:0 f:0];
−347
} else [host key:event];
−348
}
−349
- (void)terminate:(id)sender {
−350
(void)sender;
−351
for (SUIHost *host in hosts.allObjects) [host emit:2 a:0 b:0 c:0 d:0 e:0 f:0];
−352
}
−353
@end
−354
−355
@implementation SUIView
−356
- (void)setFrameSize:(NSSize)size {
−357
[super setFrameSize:size];
−358
[self.host geometry];
−359
}
−360
- (BOOL)isFlipped { return YES; }
−361
- (BOOL)acceptsFirstResponder { return YES; }
−362
- (BOOL)isOpaque { return self.alpha==nil; }
−363
- (NSView *)hitTest:(NSPoint)point {
−364
NSPoint local=[self convertPoint:point fromView:self.superview];
−365
if (self.hidden || !NSPointInRect(local,self.bounds)) return nil;
−366
if (self.alpha) {
−367
int x=floor(local.x*self.host.scale), y=floor(local.y*self.host.scale);
−368
if (x<0 || y<0 || x>=self.pixelWidth || y>=self.pixelHeight ||
−369
((const uint8_t *)self.alpha.bytes)[y*self.pixelWidth+x]==0) return nil;
−370
}
−371
return self;
−372
}
−373
- (void)updateTrackingAreas {
−374
if (self.tracking) [self removeTrackingArea:self.tracking];
−375
self.tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:
−376
NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow |
−377
NSTrackingInVisibleRect owner:self userInfo:nil];
−378
[self addTrackingArea:self.tracking];
−379
[super updateTrackingAreas];
−380
}
−381
- (NSPoint)point:(NSEvent *)event { return [self convertPoint:event.locationInWindow fromView:nil]; }
−382
- (void)mouseEntered:(NSEvent *)event {
−383
NSPoint p=[self point:event]; [self.host emit:6 a:floor(p.x) b:floor(p.y) c:0 d:0 e:0 f:0];
−384
}
−385
- (void)mouseExited:(NSEvent *)event { (void)event; [self.host emit:7 a:0 b:0 c:0 d:0 e:0 f:0]; }
−386
- (void)mouseMoved:(NSEvent *)event {
−387
if (self.host.timing) self.host.pointerTime=event.timestamp;
−388
NSPoint p=[self point:event]; [self.host emit:8 a:floor(p.x) b:floor(p.y) c:0 d:0 e:0 f:0];
−389
}
−390
- (void)mouseDragged:(NSEvent *)e { [self mouseMoved:e]; }
−391
- (void)rightMouseDragged:(NSEvent *)e { [self mouseMoved:e]; }
−392
- (void)otherMouseDragged:(NSEvent *)e { [self mouseMoved:e]; }
−393
- (void)button:(NSEvent *)event down:(BOOL)down {
−394
if (down) { [self.window makeFirstResponder:self]; hostFocusChanged(self.host,NO); }
−395
NSPoint p=[self point:event];
−396
[self.host emit:9 a:272+event.buttonNumber b:down c:floor(p.x) d:floor(p.y) e:0 f:0];
−397
}
−398
- (void)mouseDown:(NSEvent *)e { [self button:e down:YES]; }
−399
- (void)mouseUp:(NSEvent *)e { [self button:e down:NO]; }
−400
- (void)rightMouseDown:(NSEvent *)e { [self button:e down:YES]; }
−401
- (void)rightMouseUp:(NSEvent *)e { [self button:e down:NO]; }
−402
- (void)otherMouseDown:(NSEvent *)e { [self button:e down:YES]; }
−403
- (void)otherMouseUp:(NSEvent *)e { [self button:e down:NO]; }
−404
- (void)scrollWheel:(NSEvent *)event {
−405
NSPoint p=[self point:event];
−406
[self.host emit:10 a:llround(-event.scrollingDeltaX*256) b:llround(-event.scrollingDeltaY*256)
−407
c:event.hasPreciseScrollingDeltas ? 0 : llround(-event.scrollingDeltaX)
−408
d:event.hasPreciseScrollingDeltas ? 0 : llround(-event.scrollingDeltaY)
−409
e:floor(p.x) f:floor(p.y)];
−410
}
−411
- (void)drawRect:(NSRect)dirty {
−412
(void)dirty;
−413
if (self.alpha) CGContextClearRect(NSGraphicsContext.currentContext.CGContext,self.bounds);
−414
else { [[NSColor blackColor] setFill]; NSRectFill(self.bounds); }
−415
if (!self.pixels) return;
−416
CGColorSpaceRef color = CGColorSpaceCreateDeviceRGB();
−417
CGDataProviderRef data = CGDataProviderCreateWithCFData((__bridge CFDataRef)self.pixels);
−418
CGImageRef image = CGImageCreate(self.pixelWidth, self.pixelHeight, 8, 32,
−419
self.pixelWidth*4, color, kCGBitmapByteOrder32Little |
−420
(self.alpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst),
−421
data, NULL, false, kCGRenderingIntentDefault);
−422
CGContextRef ctx = NSGraphicsContext.currentContext.CGContext;
−423
CGContextSaveGState(ctx);
−424
CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
−425
CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
−426
CGContextScaleCTM(ctx, 1, -1);
−427
/* Never stretch a stale canvas while the next size is being rendered. */
−428
CGFloat scale=self.host.scale;
−429
CGContextDrawImage(ctx,CGRectMake(0,self.bounds.size.height-self.pixelHeight/scale,
−430
self.pixelWidth/scale,self.pixelHeight/scale),image);
−431
CGContextRestoreGState(ctx);
−432
CGImageRelease(image); CGDataProviderRelease(data); CGColorSpaceRelease(color);
−433
SUIHost *host=self.host;
−434
if (host.presentedPointerTime>0) {
−435
double ms=(NSProcessInfo.processInfo.systemUptime-host.presentedPointerTime)*1000;
−436
host.drawCount++; host.drawTotal+=ms; host.drawMax=MAX(host.drawMax,ms);
−437
host.presentedPointerTime=0;
−438
if (host.drawCount==16 || host.drawCount%64==0) timingReport(host);
−439
}
−440
[self.host emit:3 a:(int64_t)(NSProcessInfo.processInfo.systemUptime*1000) b:0 c:0 d:0 e:0 f:0];
−441
}
−442
@end
−443
−444
static SUIHost *asHost(SigilVM *vm, Value value) {
−445
if (![NSThread isMainThread]) {
−446
sigil__vm_error(vm, SIGIL_ERR_IO, "AppKit window operations require the main thread"); return nil;
−447
}
−448
if (!sigil_is_foreign(value) || sigil_foreign_type(value) != hostTag) {
−449
sigil__vm_error(vm, SIGIL_ERR_TYPE, "expected an AppKit window"); return nil;
−450
}
−451
return (__bridge SUIHost *)sigil_foreign_data(value);
−452
}
−453
#include "window-appkit-services.inc"
−454
−455
static void closeHost(SUIHost *host) {
−456
if (host.closed || host.closing) return;
−457
host.closing=YES;
−458
stopWindowServices(host);
−459
hostWillClose(host);
−460
if (host.timing) timingReport(host);
−461
stopTrackingStep(host);
−462
host.closed=YES; host.focused=NO;
−463
if (resizingHost==host) resizingHost=nil;
−464
host.window.delegate=nil; host.view.host=nil;
−465
[host.window close]; host.window=nil; host.view=nil;
−466
[hosts removeObject:host];
−467
}
−468
static void finalizeHost(void *data) {
−469
SUIHost *host = (__bridge_transfer SUIHost *)data;
−470
if (NSThread.isMainThread) closeHost(host);
−471
else dispatch_async(dispatch_get_main_queue(), ^{ closeHost(host); });
−472
}
−473
static Value nativeOpen(SigilVM *vm, int argc, Value *args) {
−474
(void)argc;
−475
if (!NSThread.isMainThread || !sigil_is_string(args[0]) ||
−476
!sigil_is_fixnum(args[1]) || !sigil_is_fixnum(args[2]) ||
−477
!sigil_is_fixnum(args[3]) || !sigil_is_fixnum(args[4]) ||
−478
sigil_as_fixnum(args[1]) < 1 || sigil_as_fixnum(args[1]) > 16384 ||
−479
sigil_as_fixnum(args[2]) < 1 || sigil_as_fixnum(args[2]) > 16384 ||
−480
sigil_as_fixnum(args[3]) < 0 || sigil_as_fixnum(args[3]) > 16384 ||
−481
sigil_as_fixnum(args[4]) < 0 || sigil_as_fixnum(args[4]) > 16384) {
−482
sigil__vm_error(vm, SIGIL_ERR_TYPE, "open-window: main thread, title, dimensions 1..16384 and minima 0..16384 required");
−483
return SIGIL_UNDEFINED;
−484
}
−485
@autoreleasepool {
−486
if (!hosts) {
−487
hosts=[NSHashTable weakObjectsHashTable];
−488
[SUIApplication sharedApplication];
−489
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
−490
NSMenu *menu=[NSMenu new]; NSMenuItem *app=[NSMenuItem new];
−491
[menu addItem:app]; app.submenu=[NSMenu new];
−492
[app.submenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"];
−493
NSApp.mainMenu=menu; [NSApp finishLaunching];
−494
}
−495
SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new];
−496
host.timing=getenv("SIGIL_UI_TIMING")!=NULL;
−497
host.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,
−498
sigil_as_fixnum(args[1]),sigil_as_fixnum(args[2])) styleMask:
−499
NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable |

Showing the first 500 of 741 diff lines for this file. This diff is INCOMPLETE; read the file or clone the repository for the rest.

native/raster.cmodified
@@ -282,9 +282,7 @@ static Value native_count_other(SigilVM *vm, int argc, Value *args)
282
283
void sigil__register_sigil_ui_surface(SigilVM *vm);
284
void sigil__register_sigil_ui_png(SigilVM *vm);
−285
#ifdef __APPLE__
−286
void sigil__register_sigil_ui_appkit(SigilVM *vm);
−287
#elif !defined(_WIN32)
+285
#if !defined(__APPLE__) && !defined(_WIN32)
286
void sigil__register_sigil_ui_wayland(SigilVM *vm);
287
#endif
288
@@ -310,9 +308,7 @@ void sigil__init_sigil_ui_native(SigilVM *vm)
308
}
309
sigil__register_sigil_ui_surface(vm);
310
sigil__register_sigil_ui_png(vm);
−313
#ifdef __APPLE__
−314
sigil__register_sigil_ui_appkit(vm);
−315
#elif !defined(_WIN32)
+311
#if !defined(__APPLE__) && !defined(_WIN32)
312
sigil__register_sigil_ui_wayland(vm);
313
#endif
314
}
native/window-appkit-services.incdeleted
@@ -1,267 +0,0 @@
−1
/* Host-only window services. No canvas, renderer, layout, or presentation API. */
−2
static int64_t windowServiceNow(void)
−3
{
−4
return (int64_t)(NSProcessInfo.processInfo.systemUptime*1000);
−5
}
−6
−7
static BOOL windowServiceLive(SUIHost *host)
−8
{
−9
return host && !host.closed && !host.closing && host.window;
−10
}
−11
−12
static SUIHost *windowServiceHandle(SigilVM *vm, Value value)
−13
{
−14
if (!sigil_is_foreign(value) || sigil_foreign_type(value)!=hostTag) {
−15
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window service: expected an AppKit window");
−16
return nil;
−17
}
−18
if (!NSThread.isMainThread) return nil;
−19
return (__bridge SUIHost *)sigil_foreign_data(value);
−20
}
−21
−22
static void windowServiceWake(SUIHost *host)
−23
{
−24
[host emit:12 a:host.fullscreenAcknowledged b:host->fullscreenRequest.status c:0 d:0 e:0 f:0];
−25
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint
−26
modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:NO];
−27
}
−28
−29
static void windowServiceStopTimer(SUIHost *host)
−30
{
−31
if (!host.fullscreenTimer) return;
−32
CFRunLoopTimerInvalidate(host.fullscreenTimer);
−33
CFRelease(host.fullscreenTimer);
−34
host.fullscreenTimer=NULL;
−35
}
−36
−37
static void windowServiceTick(SUIHost *host)
−38
{
−39
if (windowServiceLive(host) && sui_fullscreen_expire(&host->fullscreenRequest,windowServiceNow())) {
−40
host.fullscreenTransition=0;
−41
windowServiceStopTimer(host);
−42
windowServiceWake(host);
−43
}
−44
}
−45
−46
static void windowServiceArmTimer(SUIHost *host)
−47
{
−48
windowServiceStopTimer(host);
−49
if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return;
−50
__weak SUIHost *weakHost=host;
−51
int64_t remaining=sui_fullscreen_wait(&host->fullscreenRequest,windowServiceNow(),-1);
−52
host.fullscreenTimer=CFRunLoopTimerCreateWithHandler(NULL,
−53
CFAbsoluteTimeGetCurrent()+remaining/1000.0,0,0,0,^(CFRunLoopTimerRef timer) {
−54
(void)timer;
−55
SUIHost *liveHost=weakHost;
−56
if (!liveHost) return;
−57
windowServiceTick(liveHost);
−58
/* Preserve the monotonic deadline if the timer fires early. */
−59
if (windowServiceLive(liveHost) && liveHost->fullscreenRequest.status==SUI_FULLSCREEN_PENDING)
−60
windowServiceArmTimer(liveHost);
−61
});
−62
if (!host.fullscreenTimer) {
−63
sui_fullscreen_refuse(&host->fullscreenRequest);
−64
windowServiceWake(host);
−65
return;
−66
}
−67
CFRunLoopAddCommonMode(CFRunLoopGetMain(),(__bridge CFStringRef)NSEventTrackingRunLoopMode);
−68
CFRunLoopAddTimer(CFRunLoopGetMain(),host.fullscreenTimer,kCFRunLoopCommonModes);
−69
}
−70
−71
static void windowServiceQueueFullscreen(SUIHost *host);
−72
−73
static void windowServiceConfigured(SUIHost *host, BOOL actual)
−74
{
−75
if (!windowServiceLive(host)) return;
−76
BOOL changed=host.fullscreenAcknowledged!=actual;
−77
host.fullscreenAcknowledged=actual;
−78
host.fullscreenTransition=0;
−79
int statusChanged=sui_fullscreen_configured(&host->fullscreenRequest,actual);
−80
if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) windowServiceStopTimer(host);
−81
if (changed || statusChanged) windowServiceWake(host);
−82
if (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING) windowServiceQueueFullscreen(host);
−83
}
−84
−85
static void windowServiceFailed(SUIHost *host)
−86
{
−87
if (!windowServiceLive(host)) return;
−88
host.fullscreenTransition=0;
−89
if (host.fullscreenTransitionGeneration!=host.fullscreenGeneration) {
−90
if (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING) windowServiceQueueFullscreen(host);
−91
return;
−92
}
−93
if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return;
−94
windowServiceStopTimer(host);
−95
if (sui_fullscreen_refuse(&host->fullscreenRequest)) windowServiceWake(host);
−96
}
−97
−98
static void windowServiceQueueFullscreen(SUIHost *host)
−99
{
−100
uint64_t generation=host.fullscreenGeneration;
−101
__weak SUIHost *weakHost=host;
−102
CFRunLoopPerformBlock(CFRunLoopGetMain(),kCFRunLoopDefaultMode,^{
−103
SUIHost *liveHost=weakHost;
−104
if (!windowServiceLive(liveHost) || liveHost.fullscreenGeneration!=generation ||
−105
liveHost->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return;
−106
windowServiceTick(liveHost);
−107
if (liveHost->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING || liveHost.fullscreenTransition) return;
−108
if (liveHost.fullscreenAcknowledged==liveHost->fullscreenRequest.requested) {
−109
windowServiceConfigured(liveHost,liveHost.fullscreenAcknowledged);
−110
return;
−111
}
−112
liveHost.fullscreenTransition=liveHost->fullscreenRequest.requested ? 1 : -1;
−113
liveHost.fullscreenTransitionGeneration=generation;
−114
@try { [liveHost.window toggleFullScreen:nil]; }
−115
@catch (NSException *failure) { (void)failure; windowServiceFailed(liveHost); }
−116
});
−117
CFRunLoopWakeUp(CFRunLoopGetMain());
−118
}
−119
−120
static void stopWindowServices(SUIHost *host)
−121
{
−122
windowServiceStopTimer(host);
−123
host.fullscreenGeneration++;
−124
sui_fullscreen_refuse(&host->fullscreenRequest);
−125
}
−126
−127
static NSString *windowServiceString(SigilVM *vm, Value value, const char *who)
−128
{
−129
if (!sigil_is_string(value)) {
−130
sigil__vm_error(vm,SIGIL_ERR_TYPE,"%s: expected a string",who);
−131
return nil;
−132
}
−133
return [[NSString alloc] initWithBytes:sigil_string_bytes(value)
−134
length:((SigilString *)sigil_as_ptr(value))->byte_length encoding:NSUTF8StringEncoding];
−135
}
−136
−137
static Value nativeWindowTitle(SigilVM *vm, int argc, Value *args)
−138
{
−139
(void)argc;
−140
SUIHost *host=windowServiceHandle(vm,args[0]);
−141
if (!sigil_is_string(args[1])) {
−142
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: expected a string");
−143
return SIGIL_UNDEFINED;
−144
}
−145
size_t size=((SigilString *)sigil_as_ptr(args[1]))->byte_length;
−146
if (size>4095 || memchr(sigil_string_bytes(args[1]),0,size)) {
−147
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: invalid title");
−148
return SIGIL_UNDEFINED;
−149
}
−150
if (!windowServiceLive(host)) return SIGIL_FALSE;
−151
NSString *title=windowServiceString(vm,args[1],"window-set-title!");
−152
if (!title) {
−153
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: invalid UTF-8");
−154
return SIGIL_UNDEFINED;
−155
}
−156
@try { host.window.title=title; return sigil_bool([host.window.title isEqualToString:title]); }
−157
@catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }
−158
}
−159
−160
static BOOL windowServiceClipboardAllowed(SUIHost *host)
−161
{
−162
if (!windowServiceLive(host) || host.inTrackingStep || host.inKeyCallback) return NO;
−163
CFStringRef mode=CFRunLoopCopyCurrentMode(CFRunLoopGetMain());
−164
BOOL tracking=mode && CFEqual(mode,(__bridge CFStringRef)NSEventTrackingRunLoopMode);
−165
if (mode) CFRelease(mode);
−166
return !tracking;
−167
}
−168
−169
static NSPasteboard *windowServicePasteboard(SUIHost *host)
−170
{
−171
#ifdef SUI_WINDOW_SERVICES_TEST
−172
/* The native fixture must supply a private named pasteboard. */
−173
return host.servicePasteboard;
−174
#else
−175
(void)host;
−176
return NSPasteboard.generalPasteboard;
−177
#endif
−178
}
−179
−180
static Value nativeWindowClipboardRead(SigilVM *vm, int argc, Value *args)
−181
{
−182
(void)argc;
−183
SUIHost *host=windowServiceHandle(vm,args[0]);
−184
if (!windowServiceClipboardAllowed(host)) return SIGIL_FALSE;
−185
@try {
−186
NSString *text=[windowServicePasteboard(host) stringForType:NSPasteboardTypeString];
−187
if (!text || [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding]>4u*1024*1024) return SIGIL_FALSE;
−188
NSData *bytes=[text dataUsingEncoding:NSUTF8StringEncoding];
−189
if (!bytes || bytes.length>4u*1024*1024) return SIGIL_FALSE;
−190
return sigil_make_string(vm,bytes.length ? bytes.bytes : "",bytes.length);
−191
} @catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }
−192
}
−193
−194
static Value nativeWindowClipboardSet(SigilVM *vm, int argc, Value *args)
−195
{
−196
(void)argc;
−197
SUIHost *host=windowServiceHandle(vm,args[0]);
−198
if (!sigil_is_string(args[1])) {
−199
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-clipboard-set!: expected a string");
−200
return SIGIL_UNDEFINED;
−201
}
−202
if (!windowServiceClipboardAllowed(host) ||
−203
((SigilString *)sigil_as_ptr(args[1]))->byte_length>4u*1024*1024) return SIGIL_FALSE;
−204
NSString *text=windowServiceString(vm,args[1],"window-clipboard-set!");
−205
if (!text) return SIGIL_FALSE;
−206
@try {
−207
NSPasteboard *pasteboard=windowServicePasteboard(host);
−208
if (!pasteboard) return SIGIL_FALSE;
−209
NSPasteboardItem *item=[NSPasteboardItem new];
−210
if (![item setString:text forType:NSPasteboardTypeString]) return SIGIL_FALSE;
−211
[pasteboard clearContents];
−212
return sigil_bool([pasteboard writeObjects:@[item]]);
−213
} @catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }
−214
}
−215
−216
static Value nativeWindowFullscreenState(SigilVM *vm, int argc, Value *args)
−217
{
−218
(void)argc;
−219
SUIHost *host=windowServiceHandle(vm,args[0]);
−220
return sigil_bool(windowServiceLive(host) && host.fullscreenAcknowledged);
−221
}
−222
−223
static Value nativeWindowFullscreenStatus(SigilVM *vm, int argc, Value *args)
−224
{
−225
(void)argc;
−226
SUIHost *host=windowServiceHandle(vm,args[0]);
−227
if (!windowServiceLive(host)) return sigil_fixnum(SUI_FULLSCREEN_REFUSED);
−228
windowServiceTick(host);
−229
return sigil_fixnum(host->fullscreenRequest.status);
−230
}
−231
−232
static Value nativeWindowFullscreen(SigilVM *vm, int argc, Value *args)
−233
{
−234
(void)argc;
−235
SUIHost *host=windowServiceHandle(vm,args[0]);
−236
if (!sigil_is_bool(args[1])) {
−237
sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-fullscreen!: expected a boolean");
−238
return SIGIL_UNDEFINED;
−239
}
−240
if (!host) return SIGIL_FALSE;
−241
host.fullscreenGeneration++;
−242
sui_fullscreen_request(&host->fullscreenRequest,sigil_as_bool(args[1]),windowServiceNow());
−243
if (!windowServiceLive(host) || !(host.window.styleMask & NSWindowStyleMaskResizable)) {
−244
sui_fullscreen_refuse(&host->fullscreenRequest);
−245
if (windowServiceLive(host)) windowServiceWake(host);
−246
return SIGIL_FALSE;
−247
}
−248
windowServiceWake(host);
−249
windowServiceArmTimer(host);
−250
if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return SIGIL_FALSE;
−251
windowServiceQueueFullscreen(host);
−252
return SIGIL_TRUE;
−253
}
−254
−255
static void registerWindowAppkitServices(SigilVM *vm)
−256
{
−257
if (!sigil_begin_module(vm,"(sigil ui window appkit services)")) return;
−258
#define SERVICE(name,fn,n) sigil_module_register_native(vm,name,fn,SIGIL_ARITY_EXACT(n),name); sigil_module_export(vm,name)
−259
SERVICE("%window-title!",nativeWindowTitle,2);
−260
SERVICE("%window-clipboard-read",nativeWindowClipboardRead,1);
−261
SERVICE("%window-clipboard-set!",nativeWindowClipboardSet,2);
−262
SERVICE("%window-fullscreen?",nativeWindowFullscreenState,1);
−263
SERVICE("%window-fullscreen!",nativeWindowFullscreen,2);
−264
SERVICE("%window-fullscreen-status",nativeWindowFullscreenStatus,1);
−265
#undef SERVICE
−266
sigil_end_module(vm);
−267
}
package.sglmodified
@@ -8,38 +8,41 @@
8
(define ui-flags '("-std=c99" "-Wall" "-Wextra" "-Wno-unused-parameter" "-D_GNU_SOURCE"))
9
10
(define (compile-ui ctx)
−11
(let ((compiled
−12
((compile-c-sources
−13
sources: (append ui-common-sources
−14
(case (target-os ctx)
−15
((darwin) '("native/surface-unavailable.c"))
−16
((windows) '("native/surface-unavailable.c"))
−17
((linux) '("native/surface.c" "native/wayland.c"))
−18
(else (error "sigil-ui supports Linux, macOS and Windows targets"))))
−19
include-dirs: '("native/wayland" "native/wayland/include")
−20
flags: (with-sigil-c-flags ui-flags)) ctx)))
−21
(if (eq? (target-os ctx) 'darwin)
−22
((compile-c-sources sources: '("native/appkit.m")
−23
flags: (with-sigil-c-flags (append ui-flags '("-fobjc-arc")))) compiled)
−24
compiled)))
+11
((compile-c-sources
+12
sources: (append ui-common-sources
+13
(case (target-os ctx)
+14
((darwin windows) '("native/surface-unavailable.c"))
+15
((linux) '("native/surface.c" "native/wayland.c"))
+16
(else (error "sigil-ui supports Linux, macOS and Windows targets"))))
+17
include-dirs: '("native/wayland" "native/wayland/include")
+18
flags: (with-sigil-c-flags ui-flags)) ctx))
19
20
(define (compile-ui-modules ctx)
21
((compile-sigil-modules
22
sources: "src/**/*.sgl"
−29
exclude: (if (eq? (target-os ctx) 'windows) '()
−30
(list (path-join (context-package-dir ctx) "src/sigil/ui/win32.sgl")))
+23
exclude: (map (lambda (file) (path-join (context-package-dir ctx) file))
+24
(append
+25
(if (eq? (target-os ctx) 'windows) '() '("src/sigil/ui/win32.sgl"))
+26
(if (eq? (target-os ctx) 'darwin) '()
+27
'("src/sigil/ui/appkit.sgl" "src/sigil/ui/appkit/wait.sgl"))))
28
output-dir: (config-output-subdir "lib")) ctx))
29
30
(package
31
name: "sigil-ui"
−35
version: "0.2.5"
−36
sigil: "0.24.6"
+32
version: "0.2.6"
+33
sigil: "0.24.8"
34
description: "Retained-mode UI framework with a software renderer"
35
url: "https://git.usesigil.org/sigil/sigil-ui"
36
license: "BSD-3-Clause"
37
authors: (list "David Wilson <david@daviwil.com>")
38
39
configs: (list
+40
(config name: 'darwin-arm64 toolchain: 'zig target: "aarch64-macos.15.0-none"
+41
features: '(cross darwin) output-dir: "build/darwin-arm64")
+42
(config name: 'darwin-amd64 toolchain: 'zig target: "x86_64-macos.15.0-none"
+43
features: '(cross darwin) output-dir: "build/darwin-amd64")
+44
(config name: 'windows-amd64 toolchain: 'zig target: "x86_64-windows-gnu"
+45
features: '(cross windows) output-dir: "build/windows-amd64")
46
(config
47
name: 'dev
48
output-dir: "build/dev"
@@ -53,12 +56,13 @@
56
57
dependencies: (append
58
(cond-expand
−56
(windows (list (from-pkg name: "sigil/sigil-window" version: "^0.1.0")))
+59
((or windows darwin)
+60
(list (from-pkg name: "sigil/sigil-window" version: "^0.2.0")))
61
(else '()))
62
(list
−59
(from-pkg name: "sigil/sigil-font" version: "^0.1.0")
−60
(from-pkg name: "sigil/sigil-lib" version: "^0.24.6")
−61
(from-pkg name: "sigil/sigil-stdlib" version: "^0.24.6")))
+63
(from-pkg name: "sigil/sigil-font" version: "^0.1.0")
+64
(from-pkg name: "sigil/sigil-lib" version: "^0.24.6")
+65
(from-pkg name: "sigil/sigil-stdlib" version: "^0.24.6")))
66
67
;; The test runner declares its package/build/store helpers transitively.
68
dev-dependencies: (list
@@ -67,17 +71,15 @@
71
(from-pkg name: "sigil/sigil-test-runner" version: "^0.24.6"))
72
73
;; Pixel loops and device access are native. Linux uses runtime-loaded
−70
;; Wayland libraries and checked-in protocol code; Darwin uses AppKit.
+74
;; Wayland libraries and checked-in protocol code. AppKit host ownership
+75
;; and native child services are supplied by sigil-window.
76
libraries: (list
77
(library
78
name: 'sigil-ui
79
c-sources: ui-common-sources
80
c-include-dirs: '("native" "native/wayland" "native/wayland/include")
81
native-init: "sigil__init_sigil_ui_native"
−77
link-flags: (lambda (ctx)
−78
(if (eq? (target-os ctx) 'darwin)
−79
'("-framework" "AppKit" "-framework" "QuartzCore")
−80
'()))))
+82
link-flags: '()))
83
84
tasks: (list
85
(task
scripts/build-macos-demo.sglmodified
@@ -1,171 +1,37 @@
1
#!/usr/bin/env sigil
−2
;;; Build with an installed Sigil executable passed as argument one.
−3
;;; All build/dependency/cache state stays beneath this checkout.
+2
;;; Cross-build the development demo on Linux; never uses an Apple SDK.
3
(import (sigil shell prelude))
−5
(requires (tools clang cp))
+4
(requires (tools cp))
5
(define root (realpath (path (script-dir) "..")))
6
(define runtime (realpath (arg 1)))
7
(define action (arg 2 default: "build"))
−9
(define build (path root "build" "macos"))
−10
(each directory '("tmp" "state" "cache" "data" "sigil" "store")
−11
(ensure-directory (path build directory)))
−12
(setenv! "TMPDIR" (str (path build "tmp") "/"))
−13
(setenv! "CFFIXED_USER_HOME" (path build "state"))
+8
(define zig (realpath (arg 3 default: (path (getenv "HOME") ".sigil/toolchain/zig/zig"))))
+9
(unless (equal? (out ,zig version) "0.16.0") (error "Expected Zig 0.16.0"))
+10
(define build (path root "build/macos"))
+11
(each name '("tmp" "state" "cache" "store")
+12
(ensure-directory (path build name)))
+13
(setenv! "TMPDIR" (path build "tmp"))
14
(setenv! "XDG_CACHE_HOME" (path build "cache"))
−15
(setenv! "XDG_DATA_HOME" (path build "data"))
−16
(setenv! "SIGIL_HOME" (path build "sigil"))
15
(setenv! "SIGIL_STORE" (path build "store"))
−18
(setenv! "SIGIL_TOOLCHAIN_CACHE_DIR" (path build "cache" "toolchains"))
−19
(setenv! "SIGIL_JOBS" "2")
−20
(setenv! "PATH" (str (dirname runtime) ":" (getenv "PATH")))
−21
(define (sigil-includes)
−22
(let ((headers (glob (path build "sigil" "deps" "*sigil-lib*" "include/sigil/sigil.h"))))
−23
(when (null? headers) (error "Build the package before native checks"))
−24
(dirname (dirname (car headers)))))
−25
(define (run-step name argv directory)
−26
(println "Starting ~a" name)
−27
(flush-output-port (current-output-port))
−28
(let* ((log (path build (str name ".log")))
−29
(result ($? ,@argv cwd: ,directory out: ,log err: 'merge timeout: 600)))
−30
(write-text (path build (str name ".result")) (format-outcome result))
−31
(unless (ok? result)
−32
(let* ((text (read-text log)) (size (string-length text)))
−33
(println "~a" (substring text (max 0 (- size 6000)) size)))
−34
(error "Build step failed; see log" name log))))
16
(cond
−36
((string=? action "services-check")
−37
(let ((binary (path build "services-check")))
−38
($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter
−39
,(str "-I" (sigil-includes)) ,(path root "test/appkit/services.m")
−40
,(path root "demo/build/dev/native/libsigil.a")
−41
,(path root "demo/build/dev/native/allocator-stock.o")
−42
-framework AppKit -framework QuartzCore -o ,binary timeout: 60)
−43
(run-step "services-check" (list binary) root)
−44
(run-step "services-state" (list runtime (path root "scripts/test-window-services.sgl")) build)))
−45
((string=? action "embedding-check")
−46
(let ((includes (sigil-includes)))
−47
(define (compile-embedding source binary)
−48
($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter
−49
,(str "-I" includes) ,source
−50
,(path root "demo/build/dev/native/libsigil.a")
−51
,(path root "demo/build/dev/native/allocator-stock.o")
−52
-framework AppKit -framework QuartzCore -o ,binary timeout: 60))
−53
(define (reject-embedding name file old replacement expected)
−54
(let* ((directory (path build name))
−55
(source (read-text (path root "native" file)))
−56
(binary (path directory "check")))
−57
(unless (= (string-count source old) 1) (error "Embedding mutation anchor changed" name))
−58
(ensure-directory (path directory "native"))
−59
(ensure-directory (path directory "test/appkit"))
−60
(each native-file '("appkit.m" "appkit-host.h" "appkit-host.inc"
−61
"window-services.h" "window-appkit-services.inc")
−62
(write-text (path directory "native" native-file) (read-text (path root "native" native-file))))
−63
(write-text (path directory "native" file) (string-replace source old replacement))
−64
(write-text (path directory "test/appkit/embedding.m") (read-text (path root "test/appkit/embedding.m")))
−65
(compile-embedding (path directory "test/appkit/embedding.m") binary)
−66
(let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15)))
−67
(unless (and (not (ok? result)) (contains? (stdout-of result) expected))
−68
(error "Embedding mutant was not rejected" name (format-outcome result)))
−69
(println "PASS: rejected ~a" name))))
−70
(compile-embedding (path root "test/appkit/embedding.m") (path build "embedding-check"))
−71
(run-step "embedding-check" (list (path build "embedding-check")) root)
−72
(reject-embedding "opaque-hit-test" "appkit.m"
−73
"((const uint8_t *)self.alpha.bytes)[y*self.pixelWidth+x]==0" "NO"
−74
"hitContent(host,NSMakePoint(10,10))==view")
−75
(reject-embedding "duplicate-native-forward" "appkit.m"
−76
"[self forwardNativeEvent:event];" "[self forwardNativeEvent:event]; [self forwardNativeEvent:event];"
−77
"fixture.presses==2 && view.downs==2 && view.ups==1")
−78
(reject-embedding "leaked-canceled-release" "appkit-host.inc"
−79
"[host.canceledKeys addObject:code];" "/* Missing in-flight cancellation. */"
−80
"host.events.count==0")))
−81
((string=? action "tracking-check")
−82
(let ((includes (sigil-includes)))
−83
(define (compile-tracking source binary)
−84
($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter
−85
,(str "-I" includes) ,source
−86
,(path root "demo/build/dev/native/libsigil.a")
−87
,(path root "demo/build/dev/native/allocator-stock.o")
−88
-framework AppKit -framework QuartzCore -o ,binary timeout: 60))
−89
(compile-tracking (path root "test/appkit/tracking.m") (path build "tracking-check"))
−90
(run-step "tracking-check" (list (path build "tracking-check")) root)
−91
(let* ((directory (path build "default-mode-tracking"))
−92
(source (read-text (path root "native/appkit.m")))
−93
(anchor "CFRunLoopAddSource(CFRunLoopGetMain(),host.trackingSource,kCFRunLoopCommonModes);")
−94
(binary (path directory "check")))
−95
(unless (= (string-count source anchor) 1) (error "Tracking mutation anchor changed"))
−96
(ensure-directory (path directory "native"))
−97
(ensure-directory (path directory "test/appkit"))
−98
(each file '("appkit-host.h" "appkit-host.inc" "window-services.h" "window-appkit-services.inc")
−99
(write-text (path directory "native" file) (read-text (path root "native" file))))
−100
(write-text (path directory "native/appkit.m")
−101
(string-replace source anchor
−102
"CFRunLoopAddSource(CFRunLoopGetMain(),host.trackingSource,kCFRunLoopDefaultMode);"))
−103
(write-text (path directory "test/appkit/tracking.m") (read-text (path root "test/appkit/tracking.m")))
−104
(compile-tracking (path directory "test/appkit/tracking.m") binary)
−105
(let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15)))
−106
(unless (and (not (ok? result))
−107
(contains? (stdout-of result) "FAIL: real tracking mode ticks=4 processed=0 presents=0 draws=0"))
−108
(error "Default-mode-only tracking control was not rejected" (format-outcome result)))
−109
(println "PASS: rejected default-mode-only tracking source")))))
−110
((string=? action "tests")
−111
(run-step "tests" (list runtime "test" "test/test-raster.sgl" "test/test-tree.sgl"
−112
"test/test-appkit-wait.sgl" "test/test-viewport.sgl"
−113
"test/test-chooser.sgl") root))
−114
((string=? action "resize-check")
−115
(let ((includes (sigil-includes))
−116
(native (path root "demo/build/dev/native")))
−117
(define (compile-fixture source binary)
−118
($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter
−119
,(str "-I" includes) ,source
−120
,(path native "libsigil.a") ,(path native "allocator-stock.o")
−121
-framework AppKit -framework QuartzCore -o ,binary timeout: 60))
−122
(define (reject-mutant name old replacement expected)
−123
(let* ((directory (path build name))
−124
(source (read-text (path root "native/appkit.m")))
−125
(binary (path directory "check")))
−126
(unless (= (string-count source old) 1) (error "Mutation anchor changed" name))
−127
(ensure-directory (path directory "native"))
−128
(ensure-directory (path directory "test/appkit"))
−129
(each file '("appkit-host.h" "appkit-host.inc" "window-services.h" "window-appkit-services.inc")
−130
(write-text (path directory "native" file) (read-text (path root "native" file))))
−131
(write-text (path directory "native/appkit.m") (string-replace source old replacement))
−132
(write-text (path directory "test/appkit/resize.m") (read-text (path root "test/appkit/resize.m")))
−133
(compile-fixture (path directory "test/appkit/resize.m") binary)
−134
(let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15)))
−135
(unless (and (not (ok? result)) (contains? (stdout-of result) expected))
−136
(error "Expected resize control did not reject mutant" name (format-outcome result)))
−137
(println "PASS: rejected ~a" name))))
−138
(compile-fixture (path root "test/appkit/resize.m") (path build "resize-check"))
−139
(run-step "resize-check" (list (path build "resize-check")) root)
−140
(reject-mutant "old-resize-band" "static const double resizeOutsideBand=16;"
−141
"static const double resizeOutsideBand=5;"
−142
"FAIL: outside-edge drag cannot present intermediate frames")
−143
(reject-mutant "missing-resize-present" " SUIView *view=host.view;"
−144
" return SIGIL_TRUE;\n SUIView *view=host.view;"
−145
"FAIL: resized frame not drawn before mouse-up")))
−146
((string=? action "native-check")
−147
($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter
−148
-fsyntax-only ,(str "-I" (sigil-includes))
−149
,(path root "native" "appkit.m") timeout: 60))
−150
((string=? action "build")
−151
(run-step "package-deps" (list runtime "deps" "install") root)
−152
(run-step "package-build" (list runtime "build") root)
−153
(write-text (path root "demo" "dev-redirects.sgl")
−154
"(redirects packages: (list (for-package name: \"sigil/sigil-ui\" use: (from-path dir: \"..\"))))\n")
−155
(setenv! "SIGIL_REDIRECTS" (path root "demo" "dev-redirects.sgl"))
−156
(run-step "demo-deps" (list runtime "deps" "install") (path root "demo"))
−157
(run-step "demo-build" (list runtime "build") (path root "demo")))
−158
((string=? action "bundle")
−159
(let* ((contents (path build "Sigil UI Demo.app" "Contents"))
−160
(resources (path contents "Resources")))
−161
(ensure-directory (path contents "MacOS"))
−162
(ensure-directory resources)
−163
($ clang -fobjc-arc -Wall -Wextra -Werror -framework Foundation
−164
,(path root "demo/macos/launcher.m") -o ,(path contents "MacOS/sigil-ui-launcher")
−165
timeout: 60)
−166
($ cp ,(path root "demo/macos/Info.plist") ,(path contents "Info.plist"))
−167
($ cp ,(path root "demo/build/dev/bin/sigil-ui-demo") ,(path resources "sigil-ui-demo.next"))
−168
(rename-file (path resources "sigil-ui-demo.next") (path resources "sigil-ui-demo"))
−169
($ cp -R ,(path root "demo/assets") ,resources)))
−170
(else (error "Unknown build action" action)))
+17
((equal? action "build")
+18
(define redirects (path build "redirects.sgl"))
+19
(write-text redirects
+20
(format "(redirects packages: (list (for-package name: ~s use: (from-path dir: ~s))))\n"
+21
"sigil/sigil-ui" root))
+22
($ ,runtime deps install --redirects ,redirects cwd: ,(path root "demo"))
+23
($ ,runtime build -c darwin-arm64 --redirects ,redirects cwd: ,(path root "demo")))
+24
((equal? action "bundle")
+25
(define binary (path root "demo/build/darwin-arm64/bin/sigil-ui-demo"))
+26
(unless (file? binary) (error "Cross-build the demo before bundling" binary))
+27
(define contents (path build "Sigil UI Demo.app/Contents"))
+28
(ensure-directory (path contents "MacOS"))
+29
(ensure-directory (path contents "Resources"))
+30
($ ,zig cc -target aarch64-macos.15.0-none -std=c11 -D_DARWIN_C_SOURCE
+31
-Wall -Wextra -Werror -O1 ,(path root "demo/macos/launcher.c")
+32
-o ,(path contents "MacOS/sigil-ui-launcher"))
+33
($ cp ,(path root "demo/macos/Info.plist") ,(path contents "Info.plist"))
+34
($ cp ,binary ,(path contents "Resources/sigil-ui-demo"))
+35
($ cp -R ,(path root "demo/assets") ,(path contents "Resources")))
+36
(else (error "Expected build or bundle; host checks belong to sigil-window" action)))
37
(println "PASS: ~a" action)
scripts/check-platform-selection.sgladded
@@ -0,0 +1,15 @@
+1
#!/usr/bin/env sigil
+2
;;; Inspect the actual manifest under the compiling CLI's target features.
+3
(import (sigil shell prelude) (sigil package) (sigil build))
+4
(define root (realpath (path (script-dir) "..")))
+5
(define expected (arg 1))
+6
(define pkg (load-package (path root "package.sgl")))
+7
(define window?
+8
(let loop ((dependencies (package-dependencies pkg)))
+9
(and (pair? dependencies)
+10
(or (and (from-pkg? (car dependencies))
+11
(equal? (from-pkg-name (car dependencies)) "sigil/sigil-window"))
+12
(loop (cdr dependencies))))))
+13
(unless (eq? window? (not (equal? expected "linux")))
+14
(error "Manifest selected the wrong host dependency" expected window?))
+15
(println "PASS: manifest target ~a selects sigil-window=~a" expected window?)
sigil.lockdeleted
@@ -1,88 +0,0 @@
−1
;; Auto-generated by sigil deps install. Do not edit.
−2
(lock
−3
(package name: "sigil/sigil-font"
−4
source: pkg
−5
integrity: "sha256:a835f3549c71cfa74bf81686597b952471d2ff631b40b04376eedfff2438a104"
−6
version: "0.1.1"
−7
dependencies: ((from-pkg name: "sigil/sigil-lib" version: "^0.24.6") (from-pkg name: "sigil/sigil-stdlib" version: "^0.24.6") (from-pkg name: "sigil/sigil-ffi" version: "^0.16.6") (from-pkg name: "sigil/sigil-freetype" version: "^0.9.0") (from-pkg name: "sigil/sigil-fontconfig" version: "^0.9.0")))
−8
(package name: "sigil/sigil-lib"
−9
source: pkg
−10
integrity: "sha256:af2baf1b8a1ddb310028bb1bbc8d259aaa05a4734111c635ff43367418d9d71a"
−11
version: "0.24.6"
−12
dependencies: ())
−13
(package name: "sigil/sigil-stdlib"
−14
source: pkg
−15
integrity: "sha256:092727ba77898c1be23d1be541bf98c401db53c23f00f857a3fcf596ac174f99"
−16
version: "0.24.6"
−17
dependencies: ())
−18
(package name: "sigil/sigil-shell"
−19
source: pkg
−20
integrity: "sha256:7f056c1599670bf7787197491859b7eebc20e009e290a7472acbea2ee05ef090"
−21
version: "0.24.8"
−22
dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8") (from-pkg name: "sigil/sigil-json" version: "^0.16.0")))
−23
(package name: "sigil/sigil-test"
−24
source: pkg
−25
integrity: "sha256:29ef6ce2849f6fe9b5862dd70dc327f8d4cd0c6266173348be4a45b2d5888b76"
−26
version: "0.24.8"
−27
dependencies: ())
−28
(package name: "sigil/sigil-test-runner"
−29
source: pkg
−30
integrity: "sha256:d3c5ed29ae1b09c7a2504a3c3cc86da1d454d48ae9a4fdf9eda4e5a14d984337"
−31
version: "0.24.8"
−32
dependencies: ((from-pkg name: "sigil/sigil-test" version: "=0.24.8") (from-pkg name: "sigil/sigil-package" version: "=0.24.8") (from-pkg name: "sigil/sigil-build" version: "=0.24.8") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8") (from-pkg name: "sigil/sigil-json" version: "^0.16.0")))
−33
(package name: "sigil/sigil-ffi"
−34
source: pkg
−35
integrity: "sha256:b4cb94a02de29983912211db42e8414767fa82d2ba70f70a50c41f428af2b18e"
−36
version: "0.16.6"
−37
dependencies: ())
−38
(package name: "sigil/sigil-freetype"
−39
source: pkg
−40
integrity: "sha256:ca82f1260607ce7f275f0d2bb0b379e685263e993e166fcdc0f988db6dd5846e"
−41
version: "0.9.1"
−42
dependencies: ((from-pkg name: "sigil/sigil-lib" version: "^0.24.5") (from-pkg name: "sigil/sigil-stdlib" version: "^0.24.5") (from-pkg name: "sigil/sigil-ffi" version: "^0.16.4")))
−43
(package name: "sigil/sigil-fontconfig"
−44
source: pkg
−45
integrity: "sha256:38580792ec6dc221a1c23079ad0836a86c44d6d043d9e3694039a3ceaf0c5598"
−46
version: "0.9.1"
−47
dependencies: ((from-pkg name: "sigil/sigil-lib" version: "^0.24.5") (from-pkg name: "sigil/sigil-stdlib" version: "^0.24.5") (from-pkg name: "sigil/sigil-ffi" version: "^0.16.4")))
−48
(package name: "sigil/sigil-json"
−49
source: pkg
−50
integrity: "sha256:5e04c7409a0009bfd0d2be31b2ecb5c61b1536aca92b03fb17044213deb52692"
−51
version: "0.16.2"
−52
dependencies: ())
−53
(package name: "sigil/sigil-package"
−54
source: pkg
−55
integrity: "sha256:a130682282c0f76592f221da30a6a141b6c95c8e893e910fa6cd8d56aca6ab1d"
−56
version: "0.24.8"
−57
dependencies: ())
−58
(package name: "sigil/sigil-build"
−59
source: pkg
−60
integrity: "sha256:e31d26f7f87ca7894bb250bfe0cebf0af8aaa4f63b73b9c0363a17b7a16268f3"
−61
version: "0.24.8"
−62
dependencies: ((from-pkg name: "sigil/sigil-shell" version: "=0.24.8") (from-pkg name: "sigil/sigil-json" version: "^0.16.0") (from-pkg name: "sigil/sigil-crypto" version: "^0.19.1") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8") (from-pkg name: "sigil/sigil-store" version: "=0.24.8") (from-pkg name: "sigil/sigil-package" version: "=0.24.8") (from-pkg name: "sigil/sigil-deps" version: "=0.24.8")))
−63
(package name: "sigil/sigil-crypto"
−64
source: pkg
−65
integrity: "sha256:fc2620e9ce36aa121173628a059a3a4fd1be57f4d18286628590f8e3c549ef56"
−66
version: "0.19.2"
−67
dependencies: ((from-pkg name: "sigil/sigil-lib" version: ">=0.24")))
−68
(package name: "sigil/sigil-store"
−69
source: pkg
−70
integrity: "sha256:28d54b079bbde8c6551a6e3fa3cece41cb66dc4c4112aeaf222872a4ae389e86"
−71
version: "0.24.8"
−72
dependencies: ((from-pkg name: "sigil/sigil-shell" version: "=0.24.8") (from-pkg name: "sigil/sigil-crypto" version: "^0.19.1") (from-pkg name: "sigil/sigil-sqlite" version: "^0.16.0")))
−73
(package name: "sigil/sigil-deps"
−74
source: pkg
−75
integrity: "sha256:f195c87dd085eff6702ed1613024272bd992644b6962ba33dd05da5d453a9c98"
−76
version: "0.24.8"
−77
dependencies: ((from-pkg name: "sigil/sigil-git" version: "=0.24.8") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8") (from-pkg name: "sigil/sigil-package" version: "=0.24.8")))
−78
(package name: "sigil/sigil-sqlite"
−79
source: pkg
−80
integrity: "sha256:ae319b42069c3e00408f03923b0eacbef58369b2e6e76dfb24b0b833d39ff618"
−81
version: "0.16.4"
−82
dependencies: ())
−83
(package name: "sigil/sigil-git"
−84
source: pkg
−85
integrity: "sha256:0b3251700a28e3d8ed823e0d15ee23d90e933fb940e224d1e3cde8f973d3f639"
−86
version: "0.24.8"
−87
dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8")))
−88
)
src/sigil/ui/appkit.sglmodified
@@ -1,8 +1,17 @@
−1
;;; AppKit implementation of the platform window contract. Input is queued;
−2
;;; a scoped tracking source can drive a synchronous state/render step.
+1
;;; AppKit drawing adapter. Native ownership lives in sigil-window.
2
(define-library (sigil ui appkit)
−4
(import (sigil struct) (sigil ui raster) (sigil ui tree) (sigil ui mask)
−5
(sigil ui appkit wait) (sigil ui window appkit services))
+3
(import
+4
(rename (sigil window appkit)
+5
(open-window open-appkit-window) (window? appkit-window?) (window-role appkit-window-role)
+6
(window-width appkit-window-width) (window-height appkit-window-height) (window-scale appkit-window-scale)
+7
(window-device-width host-device-width) (window-device-height host-device-height)
+8
(window-focused? appkit-window-focused?) (window-closed? appkit-window-closed?)
+9
(window-dispatch appkit-dispatch) (window-close! appkit-close!) (window-run! host-run!)
+10
(window-host-token appkit-host-token) (window-set-title! appkit-set-title!)
+11
(window-clipboard-read appkit-clipboard-read) (window-clipboard-set! appkit-clipboard-set!)
+12
(window-fullscreen? appkit-fullscreen?) (window-set-fullscreen! appkit-set-fullscreen!)
+13
(window-fullscreen-status appkit-fullscreen-status))
+14
(sigil ui raster) (sigil ui tree) (sigil ui mask) (sigil ui display) (sigil ui theme))
15
(export open-appkit-window appkit-window? appkit-window-role
16
appkit-window-width appkit-window-height appkit-window-scale
17
appkit-window-device-width appkit-window-device-height
@@ -12,133 +21,74 @@
21
appkit-set-title! appkit-clipboard-read appkit-clipboard-set!
22
appkit-fullscreen? appkit-set-fullscreen! appkit-fullscreen-status)
23
(begin
−15
(define-native (%mac-open title width height min-width min-height) (: any? any? any? any? any? -> any?))
−16
(define-native (%mac-dispatch handle timeout reads writes) (: any? any? any? any? -> any?))
−17
(define-native (%mac-next! handle event) (: any? any? -> any?))
−18
(define-native (%mac-text handle) (: any? -> any?))
−19
(define-native (%mac-name handle) (: any? -> any?))
−20
(define-native (%mac-info! handle info) (: any? any? -> any?))
−21
(define-native (%mac-present! handle pixels width rects) (: any? any? any? any? -> any?))
−22
(define-native (%mac-present-overlay! handle pixels width rects alpha) (: any? any? any? any? any? -> any?))
−23
(define-native (%mac-host-token handle) (: any? -> any?))
−24
(define-native (%mac-close! handle) (: any? -> any?))
−25
(define-native (%mac-tracking-handler! handle step) (: any? any? -> any?))
−26
−27
(define-struct appkit-window (handle) (event) (info))
−28
−29
(define (open-appkit-window (keys: (role 'toplevel) (title "sigil-ui")
−30
(app-id "sigil-ui") (width 640) (height 480)
−31
(min-width 240) (min-height 160)
−32
(output #f) (display #f)))
−33
(unless (and (eq? role 'toplevel) (not output) (not display))
−34
(error "AppKit supports toplevel windows without output/display selection"))
−35
(appkit-window handle: (%mac-open title width height min-width min-height)
−36
event: (make-vector 8 0) info: (make-vector 5 0)))
−37
−38
(define (info s index)
−39
(%mac-info! (appkit-window-handle s) (appkit-window-info s))
−40
(vector-ref (appkit-window-info s) index))
−41
(define (appkit-window-role s) 'toplevel)
−42
(define (appkit-host-token s) (%mac-host-token (appkit-window-handle s)))
−43
(define (appkit-present-overlay! s canvas alpha)
−44
(unless (and (= (mask-width alpha) (canvas-width canvas))
+24
(define current-presentation (make-parameter #f))
+25
;; Keep legacy canvas extents; exact host metrics live in (sigil window).
+26
(define (appkit-window-device-width window) (window-raster-width window))
+27
(define (appkit-window-device-height window) (window-raster-height window))
+28
(define (validate-damage canvas rectangles)
+29
(for-each
+30
(lambda (rectangle)
+31
(unless (and (list? rectangle) (= (length rectangle) 4)
+32
(let loop ((values rectangle))
+33
(or (null? values)
+34
(and (exact-integer? (car values)) (>= (car values) 0)
+35
(loop (cdr values)))))
+36
(<= (+ (car rectangle) (list-ref rectangle 2)) (canvas-width canvas))
+37
(<= (+ (cadr rectangle) (list-ref rectangle 3)) (canvas-height canvas)))
+38
(error "appkit-present!: invalid device damage rectangle" rectangle)))
+39
rectangles))
+40
(define (present-canvas window canvas rectangles generation)
+41
(validate-damage canvas rectangles)
+42
(if (null? rectangles)
+43
#t
+44
(window-present-pixels! window (canvas-pixels canvas)
+45
(canvas-width canvas) (canvas-height canvas) generation)))
+46
(define (appkit-present! window canvas . rectangles)
+47
(present-canvas window canvas
+48
(if (pair? rectangles) (car rectangles)
+49
(list (list 0 0 (canvas-width canvas) (canvas-height canvas))))
+50
(window-generation window)))
+51
(define (appkit-present-ui! window ui damage)
+52
(let ((context (ui-presentation-context ui)) (presentation (current-presentation)))
+53
(unless context
+54
(set! context (vector window (window-generation window)))
+55
(set-ui-presentation-context! ui context))
+56
(and (eq? window (vector-ref context 0))
+57
(= (window-generation window) (vector-ref context 1))
+58
(let ((accepted
+59
(present-canvas window (ui-canvas ui)
+60
(map (lambda (rectangle)
+61
(map (lambda (value) (* value (ui-scale ui))) rectangle)) damage)
+62
(vector-ref context 1))))
+63
(when (and accepted presentation (eq? window (vector-ref presentation 0)))
+64
(vector-set! presentation 1 ui))
+65
accepted))))
+66
(define (appkit-make-ui window theme background)
+67
(let ((ui (make-ui theme
+68
(make-canvas (window-raster-width window) (window-raster-height window))
+69
(appkit-window-scale window) background)))
+70
(set-ui-presentation-context! ui (vector window (window-generation window)))
+71
ui))
+72
(define (appkit-present-overlay! window canvas alpha)
+73
(unless (and (mask? alpha) (= (mask-width alpha) (canvas-width canvas))
74
(= (mask-height alpha) (canvas-height canvas)))
−46
(error "appkit-present-overlay!: mask must match canvas device size"))
−47
(%mac-present-overlay! (appkit-window-handle s) (canvas-pixels canvas) (canvas-width canvas)
−48
(list (list 0 0 (canvas-width canvas) (canvas-height canvas)))
−49
(mask-alpha alpha)))
−50
(define (appkit-window-width s) (info s 0))
−51
(define (appkit-window-height s) (info s 1))
−52
(define (appkit-window-scale s) (info s 2))
−53
(define (appkit-window-device-width s) (* (info s 0) (info s 2)))
−54
(define (appkit-window-device-height s) (* (info s 1) (info s 2)))
−55
(define (appkit-window-focused? s) (= 1 (info s 3)))
−56
(define (appkit-window-closed? s) (= 1 (info s 4)))
−57
−58
(define (appkit-set-title! s title) (%window-title! (appkit-window-handle s) title))
−59
(define (appkit-clipboard-read s) (%window-clipboard-read (appkit-window-handle s)))
−60
(define (appkit-clipboard-set! s text) (%window-clipboard-set! (appkit-window-handle s) text))
−61
(define (appkit-fullscreen? s) (%window-fullscreen? (appkit-window-handle s)))
−62
(define (appkit-set-fullscreen! s enabled?) (%window-fullscreen! (appkit-window-handle s) enabled?))
−63
(define (appkit-fullscreen-status s)
−64
(fullscreen-status-symbol (%window-fullscreen-status (appkit-window-handle s))))
−65
−66
(define (modifiers bits)
−67
(let loop ((names '(shift control alt super caps-lock num-lock)) (bit 1) (result '()))
−68
(if (null? names)
−69
(reverse result)
−70
(loop (cdr names) (* bit 2)
−71
(if (odd? (quotient bits bit)) (cons (car names) result) result)))))
−72
−73
(define (decode s type v)
−74
(let ((h (appkit-window-handle s))
−75
(a (vector-ref v 1)) (b (vector-ref v 2)) (c (vector-ref v 3))
−76
(d (vector-ref v 4)) (e (vector-ref v 5)) (f (vector-ref v 6)))
−77
(case type
−78
((1) (list 'resize a b c))
−79
((2) (list 'close))
−80
((3) (list 'frame a))
−81
((4) (list 'key (case a ((0) 'release) ((1) 'press) (else 'repeat))
−82
(%mac-name h) (%mac-text h) (modifiers c) d))
−83
((5) (list 'keyboard-focus (= a 1)))
−84
((6) (list 'pointer-enter a b))
−85
((7) (list 'pointer-leave))
−86
((8) (list 'pointer-motion a b))
−87
((9) (list 'pointer-button (if (= b 1) 'press 'release)
−88
(case a ((272) 'left) ((273) 'right) ((274) 'middle)
−89
((275) 'side) ((276) 'extra) (else a)) c d))
−90
((10) (list 'scroll (/ a 256.0) (/ b 256.0) c d e f))
−91
((12) (list 'fullscreen (= a 1) (fullscreen-status-symbol b)))
−92
(else (error "unknown AppKit event" type)))))
−93
−94
(define (appkit-dispatch s timeout-ms)
−95
(let* ((wait (appkit-wait-plan timeout-ms))
−96
(h (appkit-window-handle s))
−97
(v (appkit-window-event s)))
−98
(%mac-dispatch h (car wait) (cadr wait) (caddr wait))
−99
(let loop ((result '()))
−100
(let ((type (%mac-next! h v)))
−101
(if (= type 0)
−102
(reverse result)
−103
(loop (cons (decode s type v) result)))))))
−104
−105
(define (appkit-present! s canvas . rectangles)
−106
(%mac-present! (appkit-window-handle s) (canvas-pixels canvas) (canvas-width canvas)
−107
(if (pair? rectangles) (car rectangles)
−108
(list (list 0 0 (canvas-width canvas) (canvas-height canvas))))))
−109
(define (appkit-present-ui! s ui damage)
−110
(appkit-present! s (ui-canvas ui)
−111
(map (lambda (r) (map (lambda (n) (* n (ui-scale ui))) r)) damage)))
−112
(define (appkit-make-ui s theme background)
−113
(make-ui theme (make-canvas (appkit-window-device-width s) (appkit-window-device-height s))
−114
(appkit-window-scale s) background))
−115
(define (appkit-close! s) (%mac-close! (appkit-window-handle s)))
−116
−117
;;; step is synchronous: update state and render; never suspend, block,
−118
;;; capture a continuation or escape from a native tracking callback.
−119
(define (appkit-run! s step)
−120
(let ((failure #f))
−121
(define (tracking-step)
−122
(guard (e (#t (set! failure e) #f))
−123
(step (let ((h (appkit-window-handle s)) (v (appkit-window-event s)))
−124
(let loop ((events '()))
−125
(let ((type (%mac-next! h v)))
−126
(if (= type 0) (reverse events)
−127
(loop (cons (decode s type v) events)))))))
−128
#t))
−129
(define (stop!) (%mac-tracking-handler! (appkit-window-handle s) #f))
−130
;; The explicit guard also removes registration when an async prompt
−131
;; unwinds an exception before dynamic-wind's after thunk can run.
−132
(guard (e (#t (stop!) (raise e)))
−133
(dynamic-wind
−134
(lambda () (%mac-tracking-handler! (appkit-window-handle s) tracking-step))
−135
(lambda ()
−136
(step '())
−137
(let loop ()
−138
(when failure (raise failure))
−139
(unless (appkit-window-closed? s)
−140
(let ((events (appkit-dispatch s #f)))
−141
(when failure (raise failure))
−142
(step events))
−143
(loop))))
−144
stop!))))))
+75
(error "appkit-present-overlay!: alpha must match canvas extent"))
+76
(window-present-overlay-pixels! window (canvas-pixels canvas)
+77
(canvas-width canvas) (canvas-height canvas) (window-generation window) (mask-alpha alpha)))
+78
(define (appkit-run! window step)
+79
(let ((presentation (vector window #f)))
+80
(define (paint)
+81
(let ((ui (vector-ref presentation 1)))
+82
(when ui
+83
(let* ((scale (appkit-window-scale window))
+84
(width (appkit-window-width window))
+85
(height (appkit-window-height window))
+86
(generation (window-generation window))
+87
(canvas (make-canvas (* width scale) (* height scale))))
+88
;; Paint realized items without event/state steps or components.
+89
(repaint-rects! canvas (ui-items ui) scale
+90
(theme-color (ui-theme ui) (ui-background ui)) (list (list 0 0 width height)))
+91
(window-present-pixels! window (canvas-pixels canvas)
+92
(canvas-width canvas) (canvas-height canvas) generation)))))
+93
(parameterize ((current-presentation presentation))
+94
(host-run! window step paint))))))
src/sigil/ui/appkit/wait.sglmodified
@@ -1,55 +1,4 @@
−1
;;; Bridge the cooperative scheduler's current waits into an AppKit wait.
−2
;;; The GUI task stays runnable: CF callbacks never enter the VM. After each
−3
;;; native wake, the next dispatch yields through the normal I/O distributor.
+1
;;; Compatibility path; platform scheduling belongs to sigil-window.
2
(define-library (sigil ui appkit wait)
−5
(import (sigil async) (sigil async scheduler) (sigil system) (sigil socket)
−6
(sigil signals) (sigil time) (sigil math))
−7
(export appkit-wait-plan)
−8
(begin
−9
(define (appkit-wait-plan timeout-ms)
−10
(let ((sched (current-scheduler)))
−11
(if (not sched)
−12
(list (if timeout-ms timeout-ms -1) '() '())
−13
(begin
−14
;; A zero-deadline wait runs the existing scheduler distributor
−15
;; before this task next blocks in AppKit, including ready I/O.
−16
(await-readable-fds '() timeout-ms: 0)
−17
(let ((deadline (and timeout-ms (>= timeout-ms 0)
−18
(+ (current-second) (/ timeout-ms 1000.0))))
−19
(reads '()) (writes '()))
−20
(define (bound! time)
−21
(when (and time (or (not deadline) (< time deadline)))
−22
(set! deadline time)))
−23
(define (waiters! waiters socket?)
−24
(for-each
−25
(lambda (w)
−26
(let* ((direction (vector-ref w 1))
−27
(items (if (eq? direction 'read-any)
−28
(vector-ref w 0) (list (vector-ref w 0)))))
−29
(when (> (vector-length w) 3) (bound! (vector-ref w 3)))
−30
(for-each
−31
(lambda (item)
−32
(let ((fd (if socket? (socket-fd item) item)))
−33
(when fd
−34
(if (eq? direction 'write)
−35
(set! writes (cons fd writes))
−36
(set! reads (cons fd reads))))))
−37
items)))
−38
waiters))
−39
(let ((queue (%async-scheduler-run-queue sched))
−40
(timers (%async-scheduler-timer-waiters sched))
−41
(signal-fd (%signal-wake-fd)))
−42
(unless (and (null? (car queue)) (null? (cdr queue)))
−43
(bound! (current-second)))
−44
(when (pair? timers) (bound! (vector-ref (car timers) 0)))
−45
;; Predicate-only external waiters have no notification fd.
−46
;; Match the runtime's documented 100 ms fallback only here.
−47
(unless (null? (%async-scheduler-external-waiters sched))
−48
(bound! (+ (current-second) 0.1)))
−49
(when signal-fd (set! reads (cons signal-fd reads))))
−50
(waiters! (%async-scheduler-io-waiters sched) #t)
−51
(waiters! (%async-scheduler-fd-waiters sched) #f)
−52
(list (if deadline
−53
(min 2147483647 (max 0 (exact (ceiling (* 1000 (- deadline (current-second)))))))
−54
-1)
−55
reads writes))))))))
+3
(import (sigil window appkit wait))
+4
(export appkit-wait-plan))
src/sigil/ui/window/appkit/services.sgldeleted
@@ -1,13 +0,0 @@
−1
;;; Opaque native handles; this module moves with the host into sigil-window.
−2
(define-library (sigil ui window appkit services)
−3
(import (sigil ui window services))
−4
(export %window-title! %window-clipboard-read %window-clipboard-set!
−5
%window-fullscreen? %window-fullscreen! %window-fullscreen-status
−6
fullscreen-status-symbol)
−7
(begin
−8
(define-native (%window-title! handle title) (: any? any? -> any?))
−9
(define-native (%window-clipboard-read handle) (: any? -> any?))
−10
(define-native (%window-clipboard-set! handle text) (: any? any? -> any?))
−11
(define-native (%window-fullscreen? handle) (: any? -> any?))
−12
(define-native (%window-fullscreen! handle enabled?) (: any? any? -> any?))
−13
(define-native (%window-fullscreen-status handle) (: any? -> any?))))
test/appkit-host-stub/sigil/window/appkit.sgladded
@@ -0,0 +1,46 @@
+1
;;; Controlled host boundary for drawing adapter tests on any platform.
+2
(define-library (sigil window appkit)
+3
(export open-window window? window-role window-width window-height window-scale
+4
window-device-width window-device-height window-raster-width window-raster-height
+5
window-generation window-focused? window-closed? window-dispatch window-close! window-run!
+6
window-host-token window-set-title! window-clipboard-read window-clipboard-set!
+7
window-fullscreen? window-set-fullscreen! window-fullscreen-status
+8
window-present-pixels! window-present-overlay-pixels!
+9
test-generation! test-calls test-last)
+10
(begin
+11
(define calls 0)
+12
(define last #f)
+13
(define (test-calls) calls)
+14
(define (test-last) last)
+15
(define (open-window . arguments) (vector 1))
+16
(define (window? window) (vector? window))
+17
(define (window-role window) 'toplevel)
+18
(define (window-width window) 10)
+19
(define (window-height window) 8)
+20
(define (window-scale window) 2)
+21
(define (window-device-width window) 20)
+22
(define (window-device-height window) 16)
+23
(define (window-raster-width window) 20)
+24
(define (window-raster-height window) 16)
+25
(define (window-generation window) (vector-ref window 0))
+26
(define (test-generation! window generation) (vector-set! window 0 generation))
+27
(define (window-focused? window) #t)
+28
(define (window-closed? window) #f)
+29
(define (window-dispatch window timeout) '())
+30
(define (window-close! window) #t)
+31
(define (window-run! window step paint) (step '()) (paint))
+32
(define (window-host-token window) 42)
+33
(define (window-set-title! window title) #t)
+34
(define (window-clipboard-read window) "")
+35
(define (window-clipboard-set! window text) #t)
+36
(define (window-fullscreen? window) #f)
+37
(define (window-set-fullscreen! window enabled?) #t)
+38
(define (window-fullscreen-status window) 'idle)
+39
(define (record! window pixels width height generation alpha)
+40
(set! calls (+ calls 1))
+41
(set! last (list pixels width height generation alpha))
+42
(= generation (window-generation window)))
+43
(define (window-present-pixels! window pixels width height generation)
+44
(record! window pixels width height generation #f))
+45
(define (window-present-overlay-pixels! window pixels width height generation alpha)
+46
(record! window pixels width height generation alpha))))
test/appkit/embedding.mdeleted
@@ -1,295 +0,0 @@
−1
/* Owned hidden native child; no WebKit, global input or external windows. */
−2
#include "../../native/appkit.m"
−3
#include <assert.h>
−4
−5
/* NSApplication suppresses keys for a hidden, inactive app. Replace only its
−6
* final native forwarding sink with direct NSWindow dispatch. This qualifies
−7
* the host's routing and real responder delivery without console activation;
−8
* it does not claim end-to-end active NSApplication/menu delivery. */
−9
@interface FixtureApplication : SUIApplication
−10
@property int forwarded;
−11
@end
−12
@implementation FixtureApplication
−13
- (void)forwardNativeEvent:(NSEvent *)event {
−14
self.forwarded++;
−15
[event.window sendEvent:event];
−16
}
−17
@end
−18
−19
@interface FixtureWindow : NSWindow
−20
@property CGFloat testScale;
−21
@end
−22
@implementation FixtureWindow
−23
- (CGFloat)backingScaleFactor { return self.testScale ?: [super backingScaleFactor]; }
−24
@end
−25
−26
@interface FixtureChild : NSView
−27
@property int downs, ups, equivalents, clicks;
−28
@end
−29
@implementation FixtureChild
−30
- (BOOL)acceptsFirstResponder { return YES; }
−31
- (void)keyDown:(NSEvent *)event { (void)event; self.downs++; }
−32
- (void)keyUp:(NSEvent *)event { (void)event; self.ups++; }
−33
- (BOOL)performKeyEquivalent:(NSEvent *)event { (void)event; self.equivalents++; return NO; }
−34
- (void)mouseDown:(NSEvent *)event { (void)event; self.clicks++; }
−35
- (void)drawRect:(NSRect)rect { [[NSColor blueColor] setFill]; NSRectFill(rect); }
−36
@end
−37
−38
typedef struct {
−39
SUIHost * __unsafe_unretained host;
−40
FixtureChild * __unsafe_unretained view;
−41
int geometry, focus, deactivated, detached, closed, presses;
−42
BOOL consume, redirect, removeOnGeometry;
−43
} Fixture;
−44
static void notified(void *data, SUIHostToken host, SUIChildToken child,
−45
SUIHostEvent event, const SUIGeometry *geometry) {
−46
Fixture *fixture=data;
−47
assert(NSThread.isMainThread && sigil_ui_appkit_host_valid(host));
−48
assert(geometry->scale>=1);
−49
if (event==SUI_HOST_GEOMETRY) {
−50
fixture->geometry++;
−51
if (fixture->removeOnGeometry) {
−52
fixture->removeOnGeometry=NO;
−53
assert(sigil_ui_appkit_child_remove(host,child));
−54
}
−55
}
−56
if (event==SUI_HOST_FOCUS) fixture->focus++;
−57
if (event==SUI_HOST_DEACTIVATED) fixture->deactivated++;
−58
if (event==SUI_CHILD_WILL_DETACH || event==SUI_HOST_WILL_CLOSE) {
−59
assert(fixture->view.superview && fixture->host.window);
−60
assert(!sigil_ui_appkit_child_remove(host,child)); /* Reentrant removal. */
−61
if (event==SUI_HOST_WILL_CLOSE) fixture->closed++; else fixture->detached++;
−62
}
−63
}
−64
static bool filter(void *data, SUIHostToken host, const SUIKey *key) {
−65
Fixture *fixture=data; fixture->presses++;
−66
assert(key->action==1 && key->name && key->text);
−67
assert(key->target && fixture->view.downs==0); /* Before native dispatch. */
−68
if (fixture->redirect) sigil_ui_appkit_focus_ui(host);
−69
return fixture->consume;
−70
}
−71
static bool countFilter(void *data, SUIHostToken host, const SUIKey *key) {
−72
(void)host; (void)key; (*(int *)data)++; return false;
−73
}
−74
static NSEvent *key(SUIHost *host, NSEventType type, BOOL repeat, unsigned code, NSString *text) {
−75
return [NSEvent keyEventWithType:type location:NSZeroPoint modifierFlags:0 timestamp:0
−76
windowNumber:host.window.windowNumber context:nil characters:text
−77
charactersIgnoringModifiers:text isARepeat:repeat keyCode:code];
−78
}
−79
static void sendKey(SUIHost *host, NSEventType type, BOOL repeat, unsigned code, NSString *text) {
−80
[NSApp sendEvent:key(host,type,repeat,code,text)];
−81
}
−82
static NSBitmapImageRep *bitmap(int width, int height) {
−83
return [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height
−84
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace
−85
bytesPerRow:width*4 bitsPerPixel:32];
−86
}
−87
static NSView *hitContent(SUIHost *host, NSPoint logical) {
−88
/* hitTest: takes coordinates in the receiver's superview. The content
−89
* root is flipped, while AppKit's decorated parent is not. */
−90
return [host.content hitTest:[host.content convertPoint:logical toView:host.content.superview]];
−91
}
−92
static void checkComposition(SUIHost *host, int width, int height) {
−93
NSBitmapImageRep *overlay=bitmap(width,height), *composite=bitmap(width,height);
−94
[NSGraphicsContext saveGraphicsState];
−95
NSGraphicsContext.currentContext=[NSGraphicsContext graphicsContextWithBitmapImageRep:overlay];
−96
CGContextScaleCTM(NSGraphicsContext.currentContext.CGContext,host.scale,host.scale);
−97
[host.view drawRect:host.view.bounds];
−98
NSGraphicsContext.currentContext=[NSGraphicsContext graphicsContextWithBitmapImageRep:composite];
−99
[[NSColor blueColor] setFill]; NSRectFill(NSMakeRect(0,0,width,height));
−100
CGContextRef context=NSGraphicsContext.currentContext.CGContext;
−101
CGContextSetBlendMode(context,kCGBlendModeNormal);
−102
CGContextDrawImage(context,CGRectMake(0,0,width,height),overlay.CGImage);
−103
[NSGraphicsContext restoreGraphicsState];
−104
NSColor *clear=[composite colorAtX:10*host.scale y:10*host.scale];
−105
NSColor *opaque=[composite colorAtX:90*host.scale y:10*host.scale];
−106
NSColor *partial=[composite colorAtX:50*host.scale y:10*host.scale];
−107
assert(clear.blueComponent>0.95 && clear.redComponent<0.05);
−108
assert(opaque.redComponent>0.95 && opaque.blueComponent<0.05);
−109
assert(partial.redComponent>0.45 && partial.redComponent<0.55 &&
−110
partial.blueComponent>0.45 && partial.blueComponent<0.55);
−111
}
−112
int main(void) {
−113
@autoreleasepool {
−114
[FixtureApplication sharedApplication]; [NSApp finishLaunching];
−115
hosts=[NSHashTable weakObjectsHashTable];
−116
SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new];
−117
host.window=[[FixtureWindow alloc] initWithContentRect:NSMakeRect(100,100,120,100)
−118
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable
−119
backing:NSBackingStoreBuffered defer:NO];
−120
host.window.releasedWhenClosed=NO;
−121
host.view=[[SUIView alloc] initWithFrame:host.window.contentView.bounds];
−122
host.view.host=host; host.view.wantsLayer=YES;
−123
host.window.contentView=host.view; host.window.delegate=host;
−124
[hosts addObject:host]; [host geometry]; host.focused=YES;
−125
assert([host.window makeFirstResponder:host.view]);
−126
SUIHostToken token=hostToken(host);
−127
FixtureChild *view=[[FixtureChild alloc] initWithFrame:NSZeroRect];
−128
Fixture fixture={.host=host,.view=view};
−129
SUIChildToken child=sigil_ui_appkit_child_adopt(token,(__bridge void *)view,
−130
0,0,120,100,0,notified,&fixture);
−131
assert(child && view.superview && fixture.geometry==1);
−132
assert(host.window.firstResponder==host.view);
−133
assert(!sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,NULL,NULL));
−134
assert(sigil_ui_appkit_focus_child(token,child) && host.window.firstResponder==view);
−135
assert(fixture.focus==1);
−136
int olderCalls=0;
−137
SUIHookToken older=sigil_ui_appkit_key_filter_add(token,countFilter,&olderCalls);
−138
SUIHookToken hook=sigil_ui_appkit_key_filter_add(token,filter,&fixture); assert(hook && older);
−139
fixture.consume=YES;
−140
sendKey(host,NSEventTypeKeyDown,NO,11,@"b");
−141
fixture.consume=NO; /* Disposition must remain consumed until release. */
−142
sendKey(host,NSEventTypeKeyDown,YES,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b");
−143
assert(fixture.presses==1 && view.downs==0 && view.ups==0 && view.equivalents==0);
−144
assert(olderCalls==0);
−145
sendKey(host,NSEventTypeKeyDown,NO,0,@"a");
−146
sendKey(host,NSEventTypeKeyDown,YES,0,@"a"); sendKey(host,NSEventTypeKeyUp,NO,0,@"a");
−147
assert(fixture.presses==2 && view.downs==2 && view.ups==1);
−148
assert(((FixtureApplication *)NSApp).forwarded==3);
−149
assert(olderCalls==1 && sigil_ui_appkit_key_filter_remove(token,older));
−150
view.downs=0; fixture.consume=YES;
−151
sendKey(host,NSEventTypeKeyDown,NO,11,@"b");
−152
assert(sigil_ui_appkit_key_filter_remove(token,hook));
−153
sendKey(host,NSEventTypeKeyDown,YES,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b");
−154
assert(view.downs==0 && view.ups==1 && ((FixtureApplication *)NSApp).forwarded==3);
−155
sendKey(host,NSEventTypeKeyDown,NO,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b");
−156
assert(view.downs==1 && view.ups==2);
−157
assert(!sigil_ui_appkit_key_filter_remove(token,hook));
−158
puts("PASS: pre-dispatch consume/pass and exactly-once repeat/release routing");
−159
−160
/* Screenshot/system shortcuts can emit FlagsChanged with key code 0.
−161
* Never ask that event for characters or release an owned A key. */
−162
CGEventRef flags=CGEventCreateKeyboardEvent(NULL,0,false);
−163
assert(flags); CGEventSetType(flags,kCGEventFlagsChanged);
−164
NSEvent *unknownFlags=[NSEvent eventWithCGEvent:flags]; CFRelease(flags);
−165
assert(unknownFlags.type==NSEventTypeFlagsChanged && unknownFlags.keyCode==0);
−166
assert(sigil_ui_appkit_focus_ui(token));
−167
[host.events removeAllObjects];
−168
@try { assert(!routeKey(host,unknownFlags)); }
−169
@catch (NSException *failure) {
−170
fprintf(stderr,"REPRO unknown FlagsChanged: %s\n",failure.reason.UTF8String);
−171
return 42;
−172
}
−173
sendKey(host,NSEventTypeKeyDown,NO,0,@"a");
−174
SUIKeyOwner *uiOwner=host.keyOwners[@0]; assert(uiOwner);
−175
assert(!routeKey(host,unknownFlags));
−176
assert(host.keyOwners[@0]==uiOwner && host.events.count==1);
−177
sendKey(host,NSEventTypeKeyUp,NO,0,@"a");
−178
assert(host.events.count==2 && !host.keyOwners[@0]);
−179
assert(sigil_ui_appkit_focus_child(token,child));
−180
sendKey(host,NSEventTypeKeyDown,NO,0,@"a");
−181
SUIKeyOwner *nativeOwner=host.keyOwners[@0]; assert(nativeOwner);
−182
assert(routeKey(host,unknownFlags));
−183
assert(host.keyOwners[@0]==nativeOwner);
−184
sendKey(host,NSEventTypeKeyUp,NO,0,@"a");
−185
assert(!host.keyOwners[@0]);
−186
[host.events removeAllObjects];
−187
puts("PASS: unknown modifier synchronization preserves UI/native key ownership");
−188
−189
view.downs=view.ups=0;
−190
fixture.redirect=YES; fixture.consume=NO;
−191
hook=sigil_ui_appkit_key_filter_add(token,filter,&fixture);
−192
sendKey(host,NSEventTypeKeyDown,NO,0,@"a");
−193
assert(view.downs==0 && host.window.firstResponder==host.view);
−194
[host.events removeAllObjects];
−195
sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(host.events.count==0);
−196
assert(sigil_ui_appkit_key_filter_remove(token,hook));
−197
[host.events removeAllObjects];
−198
sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); sendKey(host,NSEventTypeKeyUp,NO,0,@"a");
−199
assert(host.events.count==2 && host.events[0].type==4 && host.events[1].type==4);
−200
assert(sigil_ui_appkit_focus_child(token,child));
−201
sendKey(host,NSEventTypeKeyDown,NO,0,@"a");
−202
[host windowDidResignKey:[NSNotification notificationWithName:NSWindowDidResignKeyNotification object:host.window]];
−203
sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(view.ups==0 && fixture.deactivated==1);
−204
[host windowDidBecomeKey:[NSNotification notificationWithName:NSWindowDidBecomeKeyNotification object:host.window]];
−205
assert(fixture.focus>=3);
−206
puts("PASS: reentrant focus change cancels ownership and deactivation suppresses stale release");
−207
−208
SigilVM *vm=sigil_vm_create(); sigil__register_sigil_ui_appkit(vm);
−209
Value handle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)host,
−210
finalizeHost,traceHost,sizeof(void *));
−211
Value capability=nativeHostToken(vm,1,&handle);
−212
assert(sigil_is_fixnum(capability) && (uint64_t)sigil_as_fixnum(capability)==token);
−213
int width=host.width*host.scale, height=host.height*host.scale;
−214
Value pixels=sigil_make_bytevector(vm,width*height*4), alpha=sigil_make_bytevector(vm,width*height);
−215
uint8_t *rgb=sigil_bytevector_data(pixels), *mask=sigil_bytevector_data(alpha);
−216
for (int y=0;y<height;y++) for (int x=0;x<width;x++) {
−217
int i=y*width+x; rgb[i*4]=0; rgb[i*4+1]=0; rgb[i*4+2]=255; rgb[i*4+3]=0;
−218
mask[i]=x<width/3 ? 0 : x<width*2/3 ? 128 : 255;
−219
}
−220
Value present[]={handle,pixels,sigil_fixnum(width),SIGIL_EMPTY,alpha};
−221
assert(nativePresentOverlay(vm,5,present)==SIGIL_TRUE);
−222
assert(hitContent(host,NSMakePoint(10,10))==view);
−223
assert(hitContent(host,NSMakePoint(90,10))==host.view);
−224
assert(hitContent(host,NSMakePoint(50,10))==host.view);
−225
assert(host.content.subviews.lastObject==host.view);
−226
checkComposition(host,width,height);
−227
assert(((uint8_t *)host.view.pixels.bytes)[2]==0);
−228
int opaque=(10*host.scale*width+90*host.scale)*4;
−229
assert(((uint8_t *)host.view.pixels.bytes)[opaque+2]==255 &&
−230
((uint8_t *)host.view.pixels.bytes)[opaque+3]==255);
−231
assert(rgb[(10*host.scale*width+50*host.scale)*4+2]==255); /* Canvas unchanged. */
−232
assert(nativePresent(vm,4,present)==SIGIL_TRUE && host.view.alpha==nil);
−233
assert(hitContent(host,NSMakePoint(10,10))==host.view);
−234
assert(nativePresentOverlay(vm,5,present)==SIGIL_TRUE);
−235
FixtureChild *sibling=[[FixtureChild alloc] initWithFrame:NSZeroRect];
−236
SUIChildToken other=sigil_ui_appkit_child_adopt(token,(__bridge void *)sibling,0,0,120,100,1,NULL,NULL);
−237
assert(other && hitContent(host,NSMakePoint(10,10))==sibling);
−238
assert(sigil_ui_appkit_child_place(token,other,0,0,120,100,-1));
−239
assert(hitContent(host,NSMakePoint(10,10))==view);
−240
assert(sigil_ui_appkit_child_remove(token,other));
−241
NSEvent *click=[NSEvent mouseEventWithType:NSEventTypeLeftMouseDown
−242
location:NSMakePoint(10,90) modifierFlags:0 timestamp:0
−243
windowNumber:host.window.windowNumber context:nil eventNumber:1 clickCount:1 pressure:1];
−244
[hitContent(host,NSMakePoint(10,10)) mouseDown:click]; assert(view.clicks==1);
−245
assert(sigil_ui_appkit_child_place(token,child,10,20,60,40,0));
−246
assert(NSEqualRects(view.superview.frame,NSMakeRect(10,20,60,40)));
−247
assert(!sigil_ui_appkit_child_place(token,child,10,20,-1,40,0));
−248
assert(NSEqualRects(view.superview.frame,NSMakeRect(10,20,60,40)));
−249
assert(sigil_ui_appkit_child_place(token,child,-10,20,60,40,0));
−250
assert(hitContent(host,NSMakePoint(-1,30))==nil);
−251
assert(hitContent(host,NSMakePoint(1,30))==view);
−252
int previous=fixture.geometry;
−253
[host.window setContentSize:NSMakeSize(140,110)];
−254
assert(fixture.geometry>previous && host.width==140 && host.height==110);
−255
previous=fixture.geometry;
−256
((FixtureWindow *)host.window).testScale=3;
−257
[host windowDidChangeBackingProperties:[NSNotification
−258
notificationWithName:NSWindowDidChangeBackingPropertiesNotification object:host.window]];
−259
SUIGeometry geometry;
−260
assert(sigil_ui_appkit_host_geometry(token,&geometry) && geometry.scale==3 && fixture.geometry>previous);
−261
((FixtureWindow *)host.window).testScale=0; [host geometry];
−262
assert(sigil_ui_appkit_child_place(token,child,0,0,0,0,0));
−263
assert(view.superview.hidden && host.window.firstResponder==host.view);
−264
assert(!sigil_ui_appkit_focus_child(token,child));
−265
assert(sigil_ui_appkit_child_place(token,child,0,0,120,100,0));
−266
assert(sigil_ui_appkit_focus_child(token,child));
−267
assert(sigil_ui_appkit_child_remove(token,child));
−268
assert(fixture.detached==1 && !view.superview && host.window.firstResponder==host.view);
−269
assert(!sigil_ui_appkit_child_remove(token,child));
−270
puts("PASS: alpha composition/hit testing, sibling order, resize/scale and empty/detached focus");
−271
−272
fixture.removeOnGeometry=YES;
−273
assert(!sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,notified,&fixture));
−274
assert(!view.superview && fixture.detached==2);
−275
child=sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,notified,&fixture);
−276
assert(child && sigil_ui_appkit_focus_child(token,child));
−277
assert(sigil_ui_appkit_host_valid(token));
−278
dispatch_semaphore_t checked=dispatch_semaphore_create(0);
−279
__block BOOL rejected=NO;
−280
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT,0),^{
−281
rejected=!sigil_ui_appkit_host_valid(token) && !sigil_ui_appkit_focus_ui(token);
−282
dispatch_semaphore_signal(checked);
−283
});
−284
assert(dispatch_semaphore_wait(checked,dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC))==0 && rejected);
−285
closeHost(host);
−286
assert(fixture.closed==1 && !view.superview && !sigil_ui_appkit_host_valid(token));
−287
assert(nativeHostToken(vm,1,&handle)==SIGIL_FALSE);
−288
assert(!sigil_ui_appkit_focus_child(token,child));
−289
assert(!sigil_ui_appkit_host_valid(token+1000));
−290
sigil_vm_destroy(vm);
−291
assert(fixture.closed==1);
−292
puts("PASS: before-close notification, owned view removal and stale token rejection");
−293
return 0;
−294
}
−295
}
test/appkit/resize.mdeleted
@@ -1,187 +0,0 @@
−1
/* Native fixture driven by scripts/build-macos-demo.sgl. No global input,
−2
* visible window, or callback into Sigil is needed for the frame tracker. */
−3
#include "../../native/appkit.m"
−4
#include <assert.h>
−5
#include <fcntl.h>
−6
#include <unistd.h>
−7
−8
static NSPoint simulatedPoint;
−9
static unsigned dispatchedMouse;
−10
@interface SUITestApplication : SUIApplication
−11
@end
−12
@implementation SUITestApplication
−13
- (NSPoint)resizePointForEvent:(NSEvent *)event { (void)event; return simulatedPoint; }
−14
- (void)sendEvent:(NSEvent *)event {
−15
if (event.type==NSEventTypeLeftMouseDown || event.type==NSEventTypeLeftMouseDragged) dispatchedMouse++;
−16
[super sendEvent:event];
−17
}
−18
@end
−19
−20
static void postMouse(SUIHost *host, NSEventType type, NSPoint point) {
−21
simulatedPoint=point;
−22
NSEvent *event=[NSEvent mouseEventWithType:type location:[host.window convertPointFromScreen:point]
−23
modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime
−24
windowNumber:host.window.windowNumber context:nil eventNumber:1 clickCount:1 pressure:1];
−25
[NSApp postEvent:event atStart:NO];
−26
}
−27
−28
static BOOL drawOffscreen(SUIHost *host) {
−29
int width=host.width*host.scale, height=host.height*host.scale;
−30
NSBitmapImageRep *bitmap=[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
−31
pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES
−32
isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*4 bitsPerPixel:32];
−33
NSGraphicsContext *context=[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
−34
[NSGraphicsContext saveGraphicsState]; NSGraphicsContext.currentContext=context;
−35
CGContextScaleCTM(context.CGContext,host.scale,host.scale);
−36
[host.view drawRect:host.view.bounds];
−37
[NSGraphicsContext restoreGraphicsState];
−38
if ([bitmap colorAtX:width-2 y:height-2].redComponent<=0.1) {
−39
fprintf(stderr,"FAIL: resized frame not drawn before mouse-up\n");
−40
return NO;
−41
}
−42
return YES;
−43
}
−44
−45
static void signalPipe(CFRunLoopTimerRef timer, void *info) {
−46
(void)timer;
−47
int fd=*(int *)info;
−48
assert(write(fd,"x",1)==1);
−49
}
−50
static void watchdog(CFRunLoopTimerRef timer, void *info) {
−51
(void)timer; *(BOOL *)info=YES;
−52
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint
−53
modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES];
−54
}
−55
−56
int main(void) {
−57
@autoreleasepool {
−58
[SUITestApplication sharedApplication];
−59
[NSApp finishLaunching];
−60
hosts=[NSHashTable weakObjectsHashTable];
−61
SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new];
−62
host.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,320,180)
−63
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable
−64
backing:NSBackingStoreBuffered defer:NO];
−65
host.window.releasedWhenClosed=NO;
−66
host.window.contentMinSize=NSMakeSize(64,64);
−67
host.view=[[SUIView alloc] initWithFrame:host.window.contentView.bounds];
−68
host.view.host=host; host.window.contentView=host.view; host.window.delegate=host;
−69
[hosts addObject:host]; [host geometry]; [host.events removeAllObjects];
−70
NSEvent *command=[NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint
−71
modifierFlags:NSEventModifierFlagCommand timestamp:NSProcessInfo.processInfo.systemUptime
−72
windowNumber:host.window.windowNumber context:nil characters:@""
−73
charactersIgnoringModifiers:@"" isARepeat:NO keyCode:55];
−74
BOOL rejectsRepeat=NO, rejectsText=NO;
−75
@try { (void)command.isARepeat; } @catch (NSException *e) { (void)e; rejectsRepeat=YES; }
−76
@try { (void)command.characters; } @catch (NSException *e) { (void)e; rejectsText=YES; }
−77
assert(rejectsRepeat && rejectsText); /* The old handler's failure control. */
−78
[host key:command];
−79
assert(host.events.lastObject.type==4 && host.events.lastObject.a==1);
−80
assert([host.events.lastObject.name isEqualToString:@"Super_L"]);
−81
assert([host.events.lastObject.text isEqualToString:@""]);
−82
NSEvent *release=[NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint
−83
modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime
−84
windowNumber:host.window.windowNumber context:nil characters:@""
−85
charactersIgnoringModifiers:@"" isARepeat:NO keyCode:55];
−86
[host key:release]; assert(host.events.lastObject.a==0);
−87
[host windowDidResignKey:[NSNotification notificationWithName:NSWindowDidResignKeyNotification object:host.window]];
−88
[host windowDidBecomeKey:[NSNotification notificationWithName:NSWindowDidBecomeKeyNotification object:host.window]];
−89
assert(host.focused && host.events.lastObject.type==5);
−90
[host.events removeAllObjects];
−91
puts("PASS: modifier-event property failure control, safe press/release and focus cycling");
−92
NSRect start=host.window.frame;
−93
NSPoint origin=NSMakePoint(NSMaxX(start)-1,NSMinY(start)+1);
−94
assert(beginResize(host,origin));
−95
assert(host.resizeEdges==(ResizeRight|ResizeBottom));
−96
for (int i=1;i<=4;i++) {
−97
updateResize(host,NSMakePoint(origin.x+i*20,origin.y-i*15));
−98
assert(host.width==320+i*20 && host.height==180+i*15);
−99
assert(fabs(NSMaxY(host.window.frame)-NSMaxY(start))<0.1);
−100
assert(host.events.lastObject.type==1);
−101
/* Each intermediate size is observable before the mouse-up. */
−102
assert(host.events.count==(NSUInteger)i);
−103
}
−104
host.resizeEdges=0; resizingHost=nil;
−105
assert(!beginResize(host,NSMakePoint(NSMidX(host.window.frame),NSMidY(host.window.frame))));
−106
NSRect grown=host.window.frame;
−107
NSPoint leftTop=NSMakePoint(NSMinX(grown)+1,NSMaxY(grown)-1);
−108
assert(beginResize(host,leftTop));
−109
updateResize(host,NSMakePoint(leftTop.x+1000,leftTop.y-1000));
−110
assert(host.width==64 && host.height==64);
−111
assert(fabs(NSMaxX(host.window.frame)-NSMaxX(grown))<0.1);
−112
assert(fabs(NSMinY(host.window.frame)-NSMinY(grown))<0.1);
−113
/* Exercise the real CF descriptor -> AppKit wake path. The Sigil
−114
* wait-plan tests cover the scheduler side of this same boundary. */
−115
SigilVM *vm=sigil_vm_create(); assert(vm);
−116
hostTag=sigil_intern_symbol(vm,"ui-appkit-window",16);
−117
Value root=sigil_intern_symbol(vm,"fixture-window",14);
−118
Value handle=sigil_make_foreign(vm,hostTag,(__bridge_retained void *)host,finalizeHost,sizeof(void *));
−119
assert(sigil_define_binding(vm,root,handle));
−120
/* Drive the real application dispatcher and native wait. A global
−121
* mouse-position read would miss these recorded outside-edge events.
−122
* Every intermediate event must cause a fresh canvas and draw before
−123
* mouse-up, including the newly exposed bottom/right area. */
−124
host.resizeEdges=0; resizingHost=nil;
−125
[host.window setContentSize:NSMakeSize(320,180)]; [host geometry];
−126
NSRect frame=host.window.frame;
−127
NSPoint outside=NSMakePoint(NSMaxX(frame)+8,NSMinY(frame)-8);
−128
if (!beginResize(host,outside)) {
−129
fprintf(stderr,"FAIL: outside-edge drag cannot present intermediate frames\n");
−130
return 1;
−131
}
−132
host.resizeEdges=0; resizingHost=nil; [host.events removeAllObjects];
−133
Value pump[]={handle,sigil_fixnum(50),SIGIL_EMPTY,SIGIL_EMPTY};
−134
postMouse(host,NSEventTypeLeftMouseDown,outside); nativeDispatch(vm,4,pump);
−135
if (resizingHost!=host) fprintf(stderr,"Dispatcher diagnostic: mouse=%u window=%ld key=%d events=%lu\n",
−136
dispatchedMouse,(long)host.window.windowNumber,host.window.keyWindow,(unsigned long)host.events.count);
−137
assert(resizingHost==host);
−138
int presented=0, drawn=0;
−139
for (int i=1;i<=4;i++) {
−140
[host.events removeAllObjects];
−141
postMouse(host,NSEventTypeLeftMouseDragged,NSMakePoint(outside.x+i*20,outside.y-i*15));
−142
nativeDispatch(vm,4,pump);
−143
BOOL resized=NO;
−144
for (SUIEvent *event in host.events) if (event.type==1) resized=YES;
−145
if (resized) {
−146
int width=host.width*host.scale, height=host.height*host.scale;
−147
Value pixels=sigil_make_bytevector(vm,(size_t)width*height*4);
−148
memset(sigil_bytevector_data(pixels),0x80,(size_t)width*height*4);
−149
Value present[]={sigil_lookup_binding(vm,root),pixels,sigil_fixnum(width),SIGIL_EMPTY};
−150
assert(nativePresent(vm,4,present)==SIGIL_TRUE); presented++;
−151
if (!drawOffscreen(host)) return 1;
−152
drawn++;
−153
}
−154
assert(presented==i && drawn==i && resizingHost==host);
−155
assert(host.width==320+i*20 && host.height==180+i*15);
−156
}
−157
postMouse(host,NSEventTypeLeftMouseUp,NSMakePoint(outside.x+80,outside.y-60));
−158
nativeDispatch(vm,4,pump); assert(resizingHost==nil);
−159
printf("PASS: %d intermediate presents and %d draws before mouse-up\n",presented,drawn);
−160
int pipes[2]; assert(pipe(pipes)==0);
−161
assert(fcntl(pipes[0],F_SETFL,O_NONBLOCK)==0);
−162
Value reads=sigil_cons(vm,sigil_fixnum(pipes[0]),SIGIL_EMPTY);
−163
Value args[]={handle,sigil_fixnum(-1),reads,SIGIL_EMPTY};
−164
CFRunLoopTimerContext writer={0,&pipes[1],NULL,NULL,NULL};
−165
BOOL expired=NO;
−166
CFRunLoopTimerContext guard={0,&expired,NULL,NULL,NULL};
−167
CFAbsoluteTime startTime=CFAbsoluteTimeGetCurrent();
−168
CFRunLoopTimerRef signal=CFRunLoopTimerCreate(NULL,startTime+0.05,0,0,0,signalPipe,&writer);
−169
CFRunLoopTimerRef limit=CFRunLoopTimerCreate(NULL,startTime+0.5,0,0,0,watchdog,&guard);
−170
CFRunLoopAddTimer(CFRunLoopGetMain(),signal,kCFRunLoopCommonModes);
−171
CFRunLoopAddTimer(CFRunLoopGetMain(),limit,kCFRunLoopCommonModes);
−172
[host.events removeAllObjects];
−173
char byte;
−174
while (read(pipes[0],&byte,1)<0 && !expired) nativeDispatch(vm,4,args);
−175
assert(!expired);
−176
double elapsed=CFAbsoluteTimeGetCurrent()-startTime;
−177
assert(elapsed>=0.04 && elapsed<0.5);
−178
CFRunLoopTimerInvalidate(signal); CFRunLoopTimerInvalidate(limit);
−179
CFRelease(signal); CFRelease(limit); close(pipes[0]); close(pipes[1]);
−180
printf("PASS: native descriptor wake in %.1f ms without periodic polling\n",elapsed*1000);
−181
closeHost(host);
−182
assert(host.closed && resizingHost==nil);
−183
sigil_vm_destroy(vm);
−184
puts("PASS: intermediate resize events, opposite-edge anchoring, minimum size, cleanup");
−185
}
−186
return 0;
−187
}
test/appkit/services.mdeleted
@@ -1,219 +0,0 @@
−1
/* Hidden host-service controls. Never activate a window or use the general pasteboard. */
−2
#define SUI_WINDOW_SERVICES_TEST 1
−3
#include "../../native/appkit.m"
−4
#include <assert.h>
−5
#include <pthread.h>
−6
−7
@interface ServiceWindow : NSWindow
−8
@property int requests;
−9
@property int behavior; /* 0 acknowledge, 1 refuse, 2 leave pending */
−10
@end
−11
@implementation ServiceWindow
−12
- (void)toggleFullScreen:(id)sender {
−13
(void)sender;
−14
self.requests++;
−15
SUIHost *host=(SUIHost *)self.delegate;
−16
if (self.behavior==1) { [host windowDidFailToEnterFullScreen:self]; return; }
−17
if (self.behavior==2) return;
−18
if (host->fullscreenRequest.requested)
−19
[host windowDidEnterFullScreen:[NSNotification notificationWithName:NSWindowDidEnterFullScreenNotification object:self]];
−20
else [host windowDidExitFullScreen:[NSNotification notificationWithName:NSWindowDidExitFullScreenNotification object:self]];
−21
}
−22
@end
−23
−24
static Value callText(SigilVM *vm, SUIHost *host, Value handle, const char *text,
−25
Value (*fn)(SigilVM *,int,Value *))
−26
{
−27
(void)host;
−28
Value args[]={handle,sigil_make_string(vm,text,strlen(text))};
−29
return fn(vm,2,args);
−30
}
−31
static Value request(SigilVM *vm, Value handle, BOOL enabled)
−32
{
−33
Value args[]={handle,sigil_bool(enabled)};
−34
return nativeWindowFullscreen(vm,2,args);
−35
}
−36
static void pump(SigilVM *vm, Value handle)
−37
{
−38
SUIHost *host=windowServiceHandle(vm,handle);
−39
/* Model the Sigil caller draining its queue, retaining history separately
−40
* for assertions. Only the real native dispatcher runs the AppKit loop. */
−41
NSMutableArray<SUIEvent *> *history=host.events;
−42
host.events=[NSMutableArray new];
−43
Value args[]={handle,sigil_fixnum(100),SIGIL_EMPTY,SIGIL_EMPTY};
−44
nativeDispatch(vm,4,args);
−45
[history addObjectsFromArray:host.events];
−46
host.events=history;
−47
}
−48
static void waitStatus(SigilVM *vm, SUIHost *host, Value handle, int target, double seconds)
−49
{
−50
double deadline=NSProcessInfo.processInfo.systemUptime+seconds;
−51
do {
−52
pump(vm,handle);
−53
if (host->fullscreenRequest.status==target) return;
−54
} while (NSProcessInfo.processInfo.systemUptime<deadline);
−55
fprintf(stderr,"FAIL: native fullscreen status %d expected %d\n",host->fullscreenRequest.status,target);
−56
abort();
−57
}
−58
static void assertText(Value value, const char *expected)
−59
{
−60
assert(sigil_is_string(value));
−61
size_t size=((SigilString *)sigil_as_ptr(value))->byte_length;
−62
assert(size==strlen(expected) && !memcmp(sigil_string_bytes(value),expected,size));
−63
}
−64
−65
typedef struct { SigilVM *vm; Value handle, text; BOOL refused; } ServiceThread;
−66
static void *serviceThread(void *data)
−67
{
−68
@autoreleasepool {
−69
ServiceThread *fixture=data;
−70
assert(!NSThread.isMainThread);
−71
Value text[]={fixture->handle,fixture->text}, fullscreen[]={fixture->handle,SIGIL_TRUE};
−72
fixture->refused=nativeWindowClipboardRead(fixture->vm,1,&fixture->handle)==SIGIL_FALSE &&
−73
nativeWindowClipboardSet(fixture->vm,2,text)==SIGIL_FALSE &&
−74
nativeWindowTitle(fixture->vm,2,text)==SIGIL_FALSE &&
−75
nativeWindowFullscreenState(fixture->vm,1,&fixture->handle)==SIGIL_FALSE &&
−76
nativeWindowFullscreen(fixture->vm,2,fullscreen)==SIGIL_FALSE &&
−77
sigil_as_fixnum(nativeWindowFullscreenStatus(fixture->vm,1,&fixture->handle))==SUI_FULLSCREEN_REFUSED;
−78
}
−79
return NULL;
−80
}
−81
−82
int main(void)
−83
{
−84
@autoreleasepool {
−85
[SUIApplication sharedApplication]; [NSApp finishLaunching];
−86
hosts=[NSHashTable weakObjectsHashTable];
−87
SigilVM *vm=sigil_vm_create(); assert(vm);
−88
sigil__register_sigil_ui_appkit(vm);
−89
SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new]; host.trackingHandler=SIGIL_FALSE;
−90
ServiceWindow *window=[[ServiceWindow alloc] initWithContentRect:NSMakeRect(0,0,320,240)
−91
styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskResizable
−92
backing:NSBackingStoreBuffered defer:NO];
−93
host.window=window; window.releasedWhenClosed=NO; window.delegate=host;
−94
host.servicePasteboard=[NSPasteboard pasteboardWithUniqueName];
−95
assert(host.servicePasteboard);
−96
Value handle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)host,
−97
finalizeHost,traceHost,sizeof(void *));
−98
assert(sigil_define_binding(vm,sigil_intern_symbol(vm,"services-window",15),handle));
−99
assert(!window.visible);
−100
−101
assert(callText(vm,host,handle,"Title — λ",nativeWindowTitle)==SIGIL_TRUE);
−102
assert(callText(vm,host,handle,"Title — λ",nativeWindowTitle)==SIGIL_TRUE);
−103
assert([window.title isEqualToString:@"Title — λ"]);
−104
assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE);
−105
assert(callText(vm,host,handle,"",nativeWindowClipboardSet)==SIGIL_TRUE);
−106
assertText(nativeWindowClipboardRead(vm,1,&handle),"");
−107
assert(callText(vm,host,handle,"Text — λ",nativeWindowClipboardSet)==SIGIL_TRUE);
−108
assertText(nativeWindowClipboardRead(vm,1,&handle),"Text — λ");
−109
[host.servicePasteboard clearContents];
−110
assert([host.servicePasteboard setData:[NSData dataWithBytes:"x" length:1] forType:@"application/octet-stream"]);
−111
assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE);
−112
assert(callText(vm,host,handle,"Sentinel",nativeWindowClipboardSet)==SIGIL_TRUE);
−113
NSInteger change=host.servicePasteboard.changeCount;
−114
host.inTrackingStep=YES;
−115
assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE);
−116
assert(callText(vm,host,handle,"Forbidden",nativeWindowClipboardSet)==SIGIL_FALSE);
−117
host.inTrackingStep=NO; host.inKeyCallback=YES;
−118
assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE);
−119
assert(callText(vm,host,handle,"Forbidden",nativeWindowClipboardSet)==SIGIL_FALSE);
−120
host.inKeyCallback=NO;
−121
assert(host.servicePasteboard.changeCount==change);
−122
assertText(nativeWindowClipboardRead(vm,1,&handle),"Sentinel");
−123
puts("PASS: synchronous UTF-8 title, private clipboard empty/text/non-text, callback refusal");
−124
−125
assert(sigil_as_fixnum(nativeWindowFullscreenStatus(vm,1,&handle))==SUI_FULLSCREEN_IDLE);
−126
assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE);
−127
assert(request(vm,handle,YES)==SIGIL_TRUE);
−128
assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE);
−129
assert(host.events.firstObject.a==0 && host.events.firstObject.b==SUI_FULLSCREEN_PENDING);
−130
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−131
assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_TRUE && window.requests==1);
−132
assert(host.events.firstObject.b==SUI_FULLSCREEN_PENDING);
−133
assert(host.events.lastObject.a==1 && host.events.lastObject.b==SUI_FULLSCREEN_GRANTED);
−134
assert(!host.fullscreenTimer);
−135
[host.events removeAllObjects];
−136
assert(request(vm,handle,NO)==SIGIL_TRUE);
−137
assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_TRUE);
−138
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−139
assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE && window.requests==2);
−140
assert(request(vm,handle,NO)==SIGIL_TRUE);
−141
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−142
assert(window.requests==2);
−143
puts("PASS: acknowledged enter/exit, event-time status, no-op grant and timer removal");
−144
−145
assert(request(vm,handle,YES)==SIGIL_TRUE);
−146
assert(request(vm,handle,NO)==SIGIL_TRUE);
−147
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−148
assert(window.requests==2 && !host.fullscreenAcknowledged);
−149
window.behavior=2;
−150
assert(request(vm,handle,YES)==SIGIL_TRUE);
−151
pump(vm,handle);
−152
assert(host.fullscreenTransition==1);
−153
assert(request(vm,handle,NO)==SIGIL_TRUE);
−154
[host windowDidEnterFullScreen:[NSNotification notificationWithName:NSWindowDidEnterFullScreenNotification object:window]];
−155
assert(host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING && host.fullscreenAcknowledged);
−156
window.behavior=0;
−157
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−158
assert(!host.fullscreenAcknowledged);
−159
puts("PASS: queued and in-flight supersession retains the latest requested state");
−160
−161
window.behavior=1;
−162
assert(request(vm,handle,YES)==SIGIL_TRUE);
−163
waitStatus(vm,host,handle,SUI_FULLSCREEN_REFUSED,1);
−164
assert(!host.fullscreenAcknowledged && !host.fullscreenTimer);
−165
window.behavior=2;
−166
[host.events removeAllObjects];
−167
double started=NSProcessInfo.processInfo.systemUptime;
−168
assert(request(vm,handle,YES)==SIGIL_TRUE);
−169
pump(vm,handle);
−170
__block BOOL watchdogFired=NO;
−171
CFRunLoopTimerRef watchdog=CFRunLoopTimerCreateWithHandler(NULL,CFAbsoluteTimeGetCurrent()+6,0,0,0,
−172
^(CFRunLoopTimerRef timer) {
−173
(void)timer; watchdogFired=YES;
−174
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint
−175
modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES];
−176
});
−177
assert(watchdog);
−178
CFRunLoopAddTimer(CFRunLoopGetMain(),watchdog,kCFRunLoopCommonModes);
−179
while (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING && !watchdogFired) {
−180
NSMutableArray<SUIEvent *> *history=host.events;
−181
host.events=[NSMutableArray new];
−182
Value wait[]={handle,sigil_fixnum(-1),SIGIL_EMPTY,SIGIL_EMPTY};
−183
nativeDispatch(vm,4,wait);
−184
[history addObjectsFromArray:host.events]; host.events=history;
−185
}
−186
CFRunLoopTimerInvalidate(watchdog); CFRelease(watchdog);
−187
assert(!watchdogFired && host->fullscreenRequest.status==SUI_FULLSCREEN_REFUSED);
−188
assert(NSProcessInfo.processInfo.systemUptime-started>=4.8);
−189
assert(host.events.lastObject.b==SUI_FULLSCREEN_REFUSED && !host.fullscreenTimer);
−190
window.behavior=0;
−191
assert(request(vm,handle,YES)==SIGIL_TRUE);
−192
waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1);
−193
assert(host.fullscreenAcknowledged);
−194
puts("PASS: native failure and silent transition refusal wake dispatch at the bounded deadline");
−195
−196
ServiceThread threadFixture={vm,handle,sigil_make_string(vm,"Owned",5),NO};
−197
pthread_t thread;
−198
assert(!pthread_create(&thread,NULL,serviceThread,&threadFixture));
−199
assert(!pthread_join(thread,NULL));
−200
assert(threadFixture.refused);
−201
window.styleMask=NSWindowStyleMaskTitled;
−202
assert(request(vm,handle,YES)==SIGIL_FALSE);
−203
window.styleMask|=NSWindowStyleMaskResizable;
−204
assert(request(vm,handle,YES)==SIGIL_TRUE);
−205
closeHost(host);
−206
assert(!host.fullscreenTimer);
−207
assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE);
−208
assert(callText(vm,host,handle,"Closed",nativeWindowClipboardSet)==SIGIL_FALSE);
−209
assert(callText(vm,host,handle,"Closed",nativeWindowTitle)==SIGIL_FALSE);
−210
assert(request(vm,handle,YES)==SIGIL_FALSE);
−211
assert(sigil_as_fixnum(nativeWindowFullscreenStatus(vm,1,&handle))==SUI_FULLSCREEN_REFUSED);
−212
CFRunLoopRunInMode(kCFRunLoopDefaultMode,0.02,false);
−213
assert(host.closed && !host.window);
−214
[host.servicePasteboard releaseGlobally]; host.servicePasteboard=nil;
−215
sigil_vm_destroy(vm);
−216
puts("PASS: wrong thread, unsupported host, pending-close cancellation and stale services");
−217
return 0;
−218
}
−219
}
test/appkit/tracking.mdeleted
@@ -1,119 +0,0 @@
−1
/* Real tracking-mode fixture. The current outer-loop-only implementation
−2
* must fail this before a common-mode application step is installed. */
−3
#include "../../native/appkit.m"
−4
#include <assert.h>
−5
−6
static SUIHost *fixtureHost;
−7
static Value fixtureHandle;
−8
static int ticks, processed, presented, drawn;
−9
static BOOL tinyPhase, sawOne, sawZero, recovered;
−10
−11
static Value trackingStep(SigilVM *vm, int argc, Value *args) {
−12
(void)argc; (void)args;
−13
BOOL resize=NO;
−14
for (SUIEvent *event in fixtureHost.events) {
−15
if (event.type!=3) processed++;
−16
if (event.type==1) resize=YES;
−17
}
−18
[fixtureHost.events removeAllObjects];
−19
if (resize) {
−20
int width=fixtureHost.width*fixtureHost.scale, height=fixtureHost.height*fixtureHost.scale;
−21
Value pixels=sigil_make_bytevector(vm,(size_t)width*height*4);
−22
memset(sigil_bytevector_data(pixels),0x90,(size_t)width*height*4);
−23
Value present[]={fixtureHandle,pixels,sigil_fixnum(width),SIGIL_EMPTY};
−24
assert(nativePresent(vm,4,present)==SIGIL_TRUE); presented++;
−25
NSBitmapImageRep *bitmap=[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
−26
pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES
−27
isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*4 bitsPerPixel:32];
−28
NSGraphicsContext *context=[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
−29
[NSGraphicsContext saveGraphicsState]; NSGraphicsContext.currentContext=context;
−30
CGContextScaleCTM(context.CGContext,fixtureHost.scale,fixtureHost.scale);
−31
[fixtureHost.view drawRect:fixtureHost.view.bounds];
−32
[NSGraphicsContext restoreGraphicsState];
−33
if ([bitmap colorAtX:width-1 y:height-1].redComponent>0.1) {
−34
drawn++;
−35
if (tinyPhase && fixtureHost.width==180 && fixtureHost.height==120) recovered=YES;
−36
}
−37
}
−38
return SIGIL_TRUE;
−39
}
−40
static void resizeInTracking(CFRunLoopTimerRef timer, void *info) {
−41
(void)info;
−42
ticks++;
−43
if (tinyPhase) {
−44
NSSize size=ticks==1 ? NSMakeSize(1,1) : ticks==2 ? NSZeroSize : NSMakeSize(180,120);
−45
/* Drive the real content-view resize callback, including sizes that
−46
* AppKit's decorated window frame may clamp before they reach it. */
−47
[fixtureHost.window setContentSize:size];
−48
[fixtureHost.view setFrameSize:size];
−49
if (ticks==1) sawOne=NSEqualSizes(fixtureHost.view.bounds.size,NSMakeSize(1,1)) &&
−50
fixtureHost.width==1 && fixtureHost.height==1;
−51
if (ticks==2) sawZero=NSEqualSizes(fixtureHost.view.bounds.size,NSZeroSize) &&
−52
fixtureHost.width==1 && fixtureHost.height==1;
−53
if (ticks==3) CFRunLoopTimerInvalidate(timer);
−54
return;
−55
}
−56
[fixtureHost.window setContentSize:NSMakeSize(120+ticks*12,100+ticks*8)];
−57
[fixtureHost geometry];
−58
if (ticks==4) CFRunLoopTimerInvalidate(timer);
−59
}
−60
−61
int main(void) {
−62
@autoreleasepool {
−63
[SUIApplication sharedApplication]; [NSApp finishLaunching];
−64
hosts=[NSHashTable weakObjectsHashTable];
−65
fixtureHost=[SUIHost new]; fixtureHost.events=[NSMutableArray new];
−66
fixtureHost.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,120,100)
−67
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable
−68
backing:NSBackingStoreBuffered defer:NO];
−69
fixtureHost.window.releasedWhenClosed=NO;
−70
fixtureHost.view=[[SUIView alloc] initWithFrame:fixtureHost.window.contentView.bounds];
−71
fixtureHost.view.host=fixtureHost; fixtureHost.window.contentView=fixtureHost.view;
−72
fixtureHost.window.delegate=fixtureHost;
−73
[hosts addObject:fixtureHost]; [fixtureHost geometry]; [fixtureHost.events removeAllObjects];
−74
SigilVM *vm=sigil_vm_create(); assert(vm);
−75
sigil__register_sigil_ui_appkit(vm);
−76
Value root=sigil_intern_symbol(vm,"tracking-window",15);
−77
fixtureHandle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)fixtureHost,finalizeHost,traceHost,sizeof(void *));
−78
assert(sigil_define_binding(vm,root,fixtureHandle));
−79
int stepIndex=sigil_register_native(vm,"fixture-tracking-step",trackingStep,SIGIL_ARITY_EXACT(0),"fixture");
−80
Value step=sigil_make_native_proc(vm,stepIndex);
−81
int install=-1;
−82
for (int i=0;i<sigil_native_count(vm);i++) {
−83
if (strstr(sigil_get_native(vm,i)->name,"%mac-tracking-handler!")) install=i;
−84
}
−85
if (install>=0) {
−86
Value args[]={fixtureHandle,step};
−87
sigil_get_native(vm,install)->func(vm,2,args);
−88
}
−89
step=SIGIL_FALSE; /* Only the foreign host tracer now owns this Value. */
−90
int collect=sigil_lookup_native(vm,"%gc-collect!"); assert(collect>=0);
−91
sigil_get_native(vm,collect)->func(vm,0,NULL);
−92
fixtureHandle=sigil_lookup_binding(vm,root);
−93
CFStringRef mode=(__bridge CFStringRef)NSEventTrackingRunLoopMode;
−94
CFRunLoopTimerRef timer=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+0.015,
−95
0.03,0,0,resizeInTracking,NULL);
−96
CFRunLoopAddTimer(CFRunLoopGetMain(),timer,mode);
−97
CFRunLoopRunInMode(mode,0.20,false);
−98
CFRunLoopTimerInvalidate(timer); CFRelease(timer);
−99
BOOL pass=ticks==4 && processed>=4 && presented==4 && drawn==4;
−100
printf("%s: real tracking mode ticks=%d processed=%d presents=%d draws=%d before tracking ends\n",
−101
pass ? "PASS" : "FAIL",ticks,processed,presented,drawn);
−102
if (pass) {
−103
tinyPhase=YES; ticks=processed=presented=drawn=0;
−104
fixtureHost.window.contentMinSize=NSZeroSize;
−105
timer=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+0.015,
−106
0.03,0,0,resizeInTracking,NULL);
−107
CFRunLoopAddTimer(CFRunLoopGetMain(),timer,mode);
−108
CFRunLoopRunInMode(mode,0.20,false);
−109
CFRunLoopTimerInvalidate(timer); CFRelease(timer);
−110
pass=sawOne && sawZero && recovered && !fixtureHost.closed && presented>=2 && drawn>=2;
−111
printf("%s: real tracking 1x1=%d 0x0=%d normal-redraw=%d presents=%d draws=%d\n",
−112
pass ? "PASS" : "FAIL",sawOne,sawZero,recovered,presented,drawn);
−113
}
−114
closeHost(fixtureHost);
−115
assert(fixtureHost.trackingSource==NULL && fixtureHost.trackingHandler==SIGIL_FALSE);
−116
sigil_vm_destroy(vm);
−117
return pass ? 0 : 1;
−118
}
−119
}
test/check-appkit-adapter.sgladded
@@ -0,0 +1,42 @@
+1
;;; Run with the controlled host directory first on the module search path.
+2
(import (sigil ui appkit) (sigil ui raster) (sigil ui mask) (sigil ui tree)
+3
(sigil ui theme) (prefix (sigil window appkit) host:))
+4
(define checks 0)
+5
(define (check condition label)
+6
(set! checks (+ checks 1))
+7
(unless condition (error "AppKit drawing adapter failed" label))
+8
(println "PASS: ~a" label))
+9
(define (raises? thunk)
+10
(guard (failure (#t #t)) (thunk) #f))
+11
(define window (open-appkit-window))
+12
(define other (open-appkit-window))
+13
(define canvas (make-canvas 20 16))
+14
(check (= 20 (appkit-window-device-width window)) "legacy canvas extent follows host raster width")
+15
(check (appkit-present! window canvas) "canvas forwards to host")
+16
(check (eq? (car (host:test-last)) (canvas-pixels canvas)) "original canvas bytes forwarded")
+17
(check (equal? (cdr (host:test-last)) '(20 16 1 #f)) "dimensions and current generation forwarded")
+18
(define before (host:test-calls))
+19
(check (appkit-present! window canvas '()) "empty damage succeeds")
+20
(check (= before (host:test-calls)) "empty damage does not present")
+21
(each rectangle '((-1 0 1 1) (0 0 21 1) (0 0 1 17) (0 0 1.5 1) (0 0 1))
+22
(check (raises? (lambda () (appkit-present! window canvas (list rectangle))))
+23
"malformed device damage rejected"))
+24
(check (= before (host:test-calls)) "invalid damage never reaches host")
+25
(define ui (appkit-make-ui window (make-theme '() '() '()) 0))
+26
(check (and (= (ui-width ui) 10) (= (ui-height ui) 8) (= (ui-scale ui) 2))
+27
"UI allocates at host raster scale")
+28
(check (appkit-present-ui! window ui '((0 0 10 8))) "logical UI damage converts to device damage")
+29
(check (not (appkit-present-ui! other ui '((0 0 10 8)))) "UI refuses another window")
+30
(host:test-generation! window 2)
+31
(define stale-before (host:test-calls))
+32
(check (not (appkit-present-ui! window ui '((0 0 10 8)))) "stale UI generation refused")
+33
(check (= stale-before (host:test-calls)) "stale UI does not reach host")
+34
(check (appkit-present! window canvas) "direct presentation snapshots the new generation")
+35
(check (= 2 (list-ref (host:test-last) 3)) "updated generation forwarded")
+36
(define alpha (make-mask 20 16 (make-bytevector 320 128)))
+37
(check (appkit-present-overlay! window canvas alpha) "overlay forwards to host")
+38
(check (eq? (list-ref (host:test-last) 4) (mask-alpha alpha)) "overlay alpha plane forwarded")
+39
(check (raises? (lambda ()
+40
(appkit-present-overlay! window canvas (make-mask 1 1 (bytevector 0)))))
+41
"mismatched overlay dimensions rejected")
+42
(println "RESULT PASS checks=~a" checks)
test/link-check/.gitignoreadded
@@ -0,0 +1 @@
+1
/sigil.lock
test/link-check/package.sgladded
@@ -0,0 +1,16 @@
+1
;;; A real executable link catches duplicate native libraries and symbols.
+2
(package
+3
name: "sigil-ui-link-check"
+4
version: "0.0.0"
+5
sigil: "0.24.8"
+6
entry: '(link main)
+7
dependencies: (list
+8
(from-path dir: "../.." package: "sigil-ui")
+9
(from-pkg name: "sigil/sigil-lib" version: "0.24.8")
+10
(from-pkg name: "sigil/sigil-stdlib" version: "0.24.8"))
+11
configs: (list
+12
(config name: 'dev toolchain: 'zig target: "x86_64-linux-musl"
+13
static?: #t output-dir: "build/dev"))
+14
tasks: (list
+15
(task name: 'build steps: (list
+16
(compile-sigil-modules sources: "src/**/*.sgl")))))
test/link-check/src/link/main.sgladded
@@ -0,0 +1,10 @@
+1
(define-library (link main)
+2
(import (sigil ui raster) (sigil io))
+3
(export main)
+4
(begin
+5
(define (main)
+6
(let ((canvas (make-canvas 12 10)))
+7
(canvas-fill! canvas 2 3 4 5 #x123456)
+8
(unless (= (canvas-pixel canvas 3 4) #x123456)
+9
(error "Linked native raster did not draw the expected pixel"))
+10
(println "PASS: linked sigil-ui native executable rasterized 0x123456")))))
test/test-appkit-wait.sglmodified
@@ -1,31 +1,36 @@
−1
;;; The scheduler-to-run-loop wait plan needs no display and runs on Linux too.
−2
(import (sigil test) (sigil async) (sigil time) (sigil socket) (sigil system)
−3
(sigil ui appkit wait))
−4
−5
(test-group "AppKit wait plan"
−6
(test "a synchronous idle wait has no periodic deadline"
−7
(assert-equal '(-1 () ()) (appkit-wait-plan #f))
−8
(assert-equal '(25 () ()) (appkit-wait-plan 25)))
−9
(test "a scheduler timer bounds an otherwise indefinite wait"
−10
(with-async
−11
(go (sleep 0.2))
−12
(let ((plan (appkit-wait-plan #f)))
−13
(assert-true (> (car plan) 0))
−14
(assert-true (<= (car plan) 200)))))
−15
(test "runnable work prevents a native blocking wait"
−16
(let ((running #t))
−17
(with-async
−18
(go (let loop () (when running (yield) (loop))))
−19
(let ((delay (car (appkit-wait-plan #f))))
−20
(set! running #f)
−21
(assert-equal 0 delay)))))
−22
(test "a socket wait contributes its descriptor and deadline"
−23
(let* ((pair (socket-pair)) (reader (car pair)) (writer (cadr pair)))
−24
(with-async
−25
(go (await-readable-any (list reader) timeout-ms: 150))
−26
(let ((plan (appkit-wait-plan #f)))
−27
(assert-true (and (member (socket-fd reader) (cadr plan)) #t))
−28
(assert-true (> (car plan) 0))
−29
(assert-true (<= (car plan) 150))))
−30
(socket-close reader)
−31
(socket-close writer))))
+1
;;; AppKit compatibility modules are compiled only for Darwin.
+2
(import (sigil test) (sigil async) (sigil time) (sigil socket) (sigil system))
+3
(cond-expand
+4
(darwin
+5
(import (sigil ui appkit wait))
+6
(test-group "AppKit wait plan"
+7
(test "a synchronous idle wait has no periodic deadline"
+8
(assert-equal '(-1 () ()) (appkit-wait-plan #f))
+9
(assert-equal '(25 () ()) (appkit-wait-plan 25)))
+10
(test "a scheduler timer bounds an otherwise indefinite wait"
+11
(with-async
+12
(go (sleep 0.2))
+13
(assert-equal 0 (car (appkit-wait-plan #f)))
+14
(let ((plan (appkit-wait-plan #f)))
+15
(assert-true (> (car plan) 0))
+16
(assert-true (<= (car plan) 200)))))
+17
(test "runnable work prevents a native blocking wait"
+18
(let ((running #t))
+19
(with-async
+20
(go (let loop () (when running (yield) (loop))))
+21
(let ((delay (car (appkit-wait-plan #f))))
+22
(set! running #f)
+23
(assert-equal 0 delay)))))
+24
(test "a socket wait contributes its descriptor and deadline"
+25
(let* ((pair (socket-pair)) (reader (car pair)) (writer (cadr pair)))
+26
(with-async
+27
(go (await-readable-any (list reader) timeout-ms: 150))
+28
(assert-equal 0 (car (appkit-wait-plan #f)))
+29
(let ((plan (appkit-wait-plan #f)))
+30
(assert-true (and (member (socket-fd reader) (cadr plan)) #t))
+31
(assert-true (> (car plan) 0))
+32
(assert-true (<= (car plan) 150))))
+33
(socket-close reader)
+34
(socket-close writer)))))
+35
(else
+36
(test-skip "AppKit wait facade requires Darwin")))