Draw macOS windows through the sigil-window AppKit host
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.
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(-)NEWS.mdmodified
# sigil-ui 0.2.6An SDK-free AppKit drawing adapter release. Requires Sigil 0.24.8.- Darwin and Windows use sigil-window 0.2.0; Linux retains its existing Wayland host without linking a second copy of the Wayland symbols.- Native host tokens and geometry/key records now use sigil-window's SW ABI. Rebuild native adapters; the retired SUI records are incompatible.- Remove `(sigil ui window appkit services)`; native services belong to sigil-window. The legacy AppKit wait module forwards to the host.- UI presentation refuses a stale generation or a different window.- AppKit open-window defaults its title to "Sigil" and accepts visible?.- AppKit emits `(input-reset)` when input ownership must be reset.- macOS code and development drivers use plain C and runtime-loaded APIs; full demo cross-build qualification still requires the font backend port.- Follow [the registry-lock and release gates](docs/release.md) before publishing.# sigil-ui 0.2.5A Windows raster adapter release.README.mdmodified
## InstallRequires Sigil 0.24.6. Add the registry dependency to your package'sRequires Sigil 0.24.8. Add the registry dependency to your package's`dependencies` list, then run `sigil deps install`:```scheme(from-pkg name: "sigil/sigil-ui" version: "^0.2")```This release is 0.2.4; see [NEWS](NEWS.md) for changes.This release is 0.2.6; see [NEWS](NEWS.md) for changes.## Minimal example`(sigil ui window)` provides the common window and input interface on Linux andmacOS, including [title, clipboard, and acknowledged fullscreen services](docs/window-services.md).See [macOS support](docs/macos.md) for the AppKit backend, developmentbundle build, scheduler integration and current gaps.See [macOS support](docs/macos.md) for the drawing adapter, sigil-window'sprebuilt Mac qualification packet, scheduler integration and remaining gates.## Popup chooserdemo/macos/Info.plistmodified
<key>CFBundleVersion</key><string>1</string> <key>NSHighResolutionCapable</key><true/> <key>NSPrincipalClass</key><string>NSApplication</string> <key>LSMinimumSystemVersion</key><string>13.0</string> <key>LSMinimumSystemVersion</key><string>15.0</string></dict></plist>demo/macos/launcher.cadded
/* SDK-free Launch Services entry. Keep the demo's receipts and resources * beside its development bundle before replacing this process. */#include <limits.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>extern int _NSGetExecutablePath(char *, uint32_t *);static int parent(char *path){ char *slash = strrchr(path, '/'); if (!slash || slash == path) return 0; *slash = 0; return 1;}int main(int argc, char **argv){ (void)argc; char unresolved[PATH_MAX], contents[PATH_MAX], root[PATH_MAX], file[PATH_MAX]; uint32_t capacity = sizeof(unresolved); if (_NSGetExecutablePath(unresolved, &capacity) || !realpath(unresolved, contents) || !parent(contents) || !parent(contents)) return 1; if (snprintf(root, sizeof(root), "%s", contents) >= (int)sizeof(root) || !parent(root) || !parent(root)) return 1;#define PATH(base, suffix) \ (snprintf(file, sizeof(file), "%s/%s", base, suffix) < (int)sizeof(file)) if (!PATH(contents, "Resources") || chdir(file)) return 1; if (!PATH(root, "state") || setenv("CFFIXED_USER_HOME", file, 1)) return 1; if (!PATH(root, "tmp/") || setenv("TMPDIR", file, 1)) return 1; if (!PATH(root, "app.log") || !freopen(file, "a", stdout) || dup2(fileno(stdout), STDERR_FILENO) < 0) return 1; if (!PATH(root, "app.exit")) return 1; unlink(file); if (setenv("SIGIL_UI_DEMO_EXIT_FILE", file, 1) || !PATH(root, "app.pid")) return 1; FILE *receipt = fopen(file, "w"); if (!receipt) return 1; int written = fprintf(receipt, "%ld\n", (long)getpid()); int closed = fclose(receipt); if (written < 0 || closed) return 1; if (!PATH(contents, "Resources/sigil-ui-demo")) return 1; argv[0] = file; execv(file, argv); perror("exec demo"); return 1;}demo/macos/launcher.mdeleted
#import <Foundation/Foundation.h>#include <stdio.h>#include <unistd.h>/* Give Launch Services the bundle identity before replacing this PID with the * compiled demo. Keep test logs, framework state and temporary files nearby. */int main(int argc, char **argv) { (void)argc; @autoreleasepool { NSString *resources=NSBundle.mainBundle.resourcePath; NSString *root=[NSBundle.mainBundle.bundlePath stringByDeletingLastPathComponent]; if (chdir(resources.fileSystemRepresentation)) return 1; setenv("CFFIXED_USER_HOME",[root stringByAppendingPathComponent:@"state"].fileSystemRepresentation,1); setenv("TMPDIR",[root stringByAppendingPathComponent:@"tmp/"].fileSystemRepresentation,1); if (!freopen([root stringByAppendingPathComponent:@"app.log"].fileSystemRepresentation,"a",stdout)) return 1; if (dup2(fileno(stdout),STDERR_FILENO)<0) return 1; NSString *exitPath=[root stringByAppendingPathComponent:@"app.exit"]; unlink(exitPath.fileSystemRepresentation); setenv("SIGIL_UI_DEMO_EXIT_FILE",exitPath.fileSystemRepresentation,1); FILE *receipt=fopen([root stringByAppendingPathComponent:@"app.pid"].fileSystemRepresentation,"w"); if (!receipt) return 1; fprintf(receipt,"%d\n",getpid()); fclose(receipt); NSString *executable=[resources stringByAppendingPathComponent:@"sigil-ui-demo"]; argv[0]=(char *)executable.fileSystemRepresentation; execv(executable.fileSystemRepresentation,argv); perror("exec demo"); return 1; }}demo/package.sglmodified
name: 'dev output-dir: "build/dev" debug?: #t optimize: 1)) optimize: 1) (config name: 'darwin-arm64 toolchain: 'zig target: "aarch64-macos.15.0-none" features: '(cross darwin) output-dir: "build/darwin-arm64")) dependencies: (list (from-pkg name: "sigil/sigil-stdlib" version: "^0.24.0")docs/macos.mdmodified
# macOS windows`(sigil ui window)` selects AppKit on macOS and Wayland on Linux. It exports`open-window`, geometry/focus/close accessors, `window-dispatch`,`window-make-ui`, `window-present!`, `window-present-ui!` and `window-close!`.Sizes and input coordinates are logical pixels; canvases and present damageuse device pixels. Events have the forms documented in `(sigil ui wayland)`.Existing Wayland APIs and behavior remain available on Linux.On macOS, `open-window` accepts `min-width` and `min-height` (logical pixels,default 240 and 160, each overridable down to zero). The native frame trackerhonors those minima. Empty native content still uses a 1×1 logical backingplaceholder and recovers on the next nonempty resize. Retained UI repaintingclips text at the viewport, including partial glyphs; direct `render-items!`keeps its strict text bounds check.The package compiles its Objective-C C ABI only for Darwin and links the systemAppKit and QuartzCore frameworks. Wayland and Linux device code stay Linux-only.Offscreen rendering and PNG output work on either platform; opening fbdev orDRM on macOS raises an explicit unsupported-device error.## Build the demoRequires macOS 13 or later, Command Line Tools and Sigil 0.24.5. From outsidethe checkout, pass the absolute path of the installed Sigil executable:# macOS drawing adaptersigil-ui 0.2.6 draws into sigil-window 0.2.0's SDK-free AppKit host.`(sigil ui window)` selects the AppKit adapter on Darwin. Existing`appkit-*` names in `(sigil ui appkit)` remain available: open/close,geometry, dispatch, clipboard, fullscreen, canvas/UI/overlay presentationand the event loop. The host owns all windows, input, child views,clipboard state and scheduling; this package owns rasterization and UI state.Sizes and input coordinates are logical pixels. Canvas extents and explicitdamage rectangles are device pixels. UI damage is scaled once before hostpresentation. Empty damage does not submit a frame. Presentation snapshotsthe host generation, and a UI associated with an older generation or adifferent window is refused. Recreate the UI after resize/scale changes.The native host copies the pixel and optional A8 alpha planes.`appkit-run!` delegates to the host loop. During nested AppKit tracking,its paint callback repaints already realized display items at currentgeometry. It does not rerun components, update application state or dispatchbrowser work. The application step runs in the outer event loop. All nativehost calls stay on the process main thread.Native embedding adapters include sigil-window's `native/appkit-host.h` anduse `sigil_window_appkit_*` symbols. Host tokens are numeric identities, notNSWindow/NSView pointers. The old sigil-ui SUI geometry/key records are notbinary-compatible with the new SW records; rebuild FFI layouts and callbackconversions together. Host ABI and callback ownership are documented bysigil-window in `docs/appkit-abi.md`.The UI package contains no Objective-C source or framework link flags.Its Darwin native sources are raster.c, png.c and surface-unavailable.c;AppKit native sources come from sigil-window. Named darwin-arm64 anddarwin-amd64 configurations use Zig 0.16.0 and macOS 15.0. A complete demoalso depends on its font backend: the currently released CoreText backendstill needs a separate SDK-free migration. Do not mistake host/UI objectbuilds for proof that the full demo or an application core cross-builds.For cross-build dependency resolution with Sigil 0.24.8, supply targetfeatures before the manifest is loaded, as well as selecting the namedconfiguration. The manifest uses these features to select sigil-window:```textsigil /path/to/checkout/scripts/build-macos-demo.sgl /path/to/sigil buildsigil /path/to/checkout/scripts/build-macos-demo.sgl /path/to/sigil bundleopen "/path/to/checkout/build/macos/Sigil UI Demo.app"SIGIL_FEATURES=cross,darwin sigil deps installSIGIL_FEATURES=cross,darwin sigil build -c darwin-arm64SIGIL_FEATURES=cross,windows sigil build -c windows-amd64```The driver uses the ordinary package build and a dependency redirect to thecheckout for the demo. Build caches and dependency state stay below`build/macos/`. The bundle contains the compiled demo and bitmap fonts; itslauncher records the PID and input-event log beside the bundle. The demo writes`app.exit` for controlled exits (0 for normal close, 1 for a caught error); thelauncher removes an old receipt first. A missing receipt is not proof of anormal exit. Type sampletext when testing. Close the window, press Escape, or use Command-Q to exit.This is a development bundle without distribution signing or notarization.Passing `--timing` to the demo enables pointer event-to-copy and event-to-drawstatistics, sampled periodically and printed when the window closes. Drawing follows input processingwithout an intervening timer; the system cursor can still lead the softwarecrosshair by a display frame.## Presentation and event loopThe host keeps a native XRGB8888 buffer, copying only submitted damage from theSigil canvas. A layer-backed NSView draws that buffer using a temporary CGImageand `CGContextDrawImage`, with interpolation disabled. This avoids asynchronousCore Animation ownership of a GC-managed bytevector and keeps exposure repaintindependent of the application's next render. AppKit coalesces invalidationand schedules drawing. Frame events report view drawing, not a hardwarepresentation timestamp. No periodic frame timer runs while idle.The window's integer backing scale determines canvas dimensions and `ui-scale`.Recreate the UI after a resize event, including a scale change between screens.Damage rectangles become logical view invalidations. Frame-edge drags aretracked through ordinary mouse events so each size returns to the application'sdispatch loop. When AppKit takes over a native tracking path, `window-run!`uses its scoped common-mode application step to keep layout/rendering moving.A stale canvas stays anchored at the upper left at its original logical size.AppKit controls final display timing; other synchronous native tracking loops,such as menus, can postpone application updates until they return.All window operations run on the main thread. Native input/delegate callbacksqueue data. `window-run!` installs a scoped application step on a common-moderun-loop source so queued events and rendering continue during AppKit's nativetracking loops. The step receives event batches and must update state/rendersynchronously: it must not suspend, block, capture a continuation or escape.Queue asynchronous work outside that callback. Its procedure stays GC-rooted;registration is removed on close or when the driver exits. Ordinary dispatchremains available, but a dispatch-only outer loop cannot update while AppKitholds the stack in a nested tracker.Use the matching features during Windows dependency installation too.Linux builds use the default host features and exclude sigil-window.Outside an async scheduler, dispatch blocks inAppKit until an event or the requested timeout. Within a scheduler, dispatchfirst yields through the normal I/O distributor, then watches current socketand raw descriptor waits through one-shot CFFileDescriptor run-loop sources.The earliest timer/I/O deadline bounds the wait; runnable tasks prevent blocking.The next dispatch distributes readiness using the existing scheduler. Keep theGUI task calling dispatch; blocking it elsewhere cannot service AppKit. Onlypredicate-based external waiters retain the scheduler's 100 ms fallback becausethey have no wake descriptor. The adapter follows the scheduler waiter recordlayout in Sigil 0.24 and has regression tests for that boundary.The former Objective-C host fixtures have moved to sigil-window's C nativehost and Sigil conformance fixtures. Use its sealed `qualify.sgl` packet onan arm64 Mac to validate the Linux-built host executables. This replacesthe retired services-check/embedding-check/tracking-check/resize-checkpaths in build-macos-demo.sgl. Active menus, native fullscreen animation,outline text and browser integration need separate behavior qualification.## Input and gapsThe drawing adapter's host-boundary checks run on Linux without a display:Keys report press/repeat/release, keysym-style names, text, the common modifierlist and evdev position codes (zero for unmapped positions). Pointer coordinatesstart at the upper left. Scroll deltas use the Wayland sign convention; precisetrackpad scrolling has zero wheel steps. Window focus and close requests use thesame event forms as Wayland. A minimal app menu supplies Quit.Text currently uses NSEvent characters. Composition, dead-key handling and IMEneed NSTextInputClient integration. Accessibility, clipboard, drag and drop,fullscreen/output selection, richer menus, Metal rendering and native fractionalscaling remain follow-ups. There is no WKWebView or browser integration.## Native child views and overlays`(window-host-token window)` returns an opaque process-local AppKit host ID,or `#f` on platforms without this capability. Keep the window alive while usingits token. The trusted C adapter API is [appkit-host.h](../native/appkit-host.h).Application code receives no NSWindow/NSView pointers. The adapter passes itsunparented NSView to `sigil_ui_appkit_child_adopt`; the host retains it untilremoval or close, independently of the adapter's ownership. Tokens are neverreused, and stale tokens fail. All calls and callbacks require the main thread.Child allocations use logical top-left coordinates, with clipping at the childand content boundaries. Greater sibling order draws above lower order, beneaththe canvas. Geometry notifications include actual content size and integerbacking scale: the adapter supplies its layout policy by placing the childagain. An empty allocation hides the child and restores UI focus. Notificationsrun before detach or window destruction while the child is still parented.A close notification replaces the detach notification. Callbacks may removechildren reentrantly; a repeated removal fails. Drop adapter contexts only aftertheir detach/close notification has returned.`(window-present-overlay! window canvas alpha-mask)` presents the XRGB canvasabove native children using a `(sigil ui mask)` A8 mask of the same device size.Zero alpha exposes the native child and passes pointer hit tests through; anynonzero alpha captures input for the UI, including partially transparent chrome.The host copies both planes and premultiplies its native image, leaving thecanvas unchanged. Overlay presentation currently copies the whole image becausealpha may change independently of RGB damage. Ordinary `window-present!` restoresopaque canvas presentation. These overlay calls are currently macOS-only.Scoped key filters run newest first before key equivalents or child responderdispatch. They receive copied key data and the target child ID (zero for UI).Returning true consumes the press; otherwise it passes. The chosen target anddecision persist through repeats and release, without rerunning filters. Passedchild events continue through AppKit exactly once; UI events keep the ordinarySigil input forms. Filter removal, focus loss, detach or a reentrant focus changecancels pending ownership and suppresses stale releases. Explicit focus APIsselect a child or the canvas; detaching a focused child restores the canvasresponder. Focus and deactivation notifications let the adapter update its state.```textsigil -L test/appkit-host-stub test/check-appkit-adapter.sgl```Native notifications and filters must return synchronously: do not block,suspend, navigate, run JavaScript or enter Sigil from them. Queue such work forthe ordinary event loop. No WebKit types or navigation policy are part of thisAPI. `embedding-check` in the development driver tests it with a plain nativechild; `resize-check` and `tracking-check` cover the existing window controls.The controlled host verifies buffer/alpha forwarding, damage validation,window ownership and generation refusal. It does not stand in for nativeAppKit behavior. The legacy `(sigil ui appkit wait)` module forwards tosigil-window's scheduler implementation.docs/release.mdadded
# Release dependency gatesFor 0.2.6, release sigil-window 0.2.0 before finalizing the UI release:1. Publish the independently accepted sigil-window release.2. Install UI registry dependencies for the release targets and confirm the lock pins sigil-window 0.2.0 with its published integrity on Darwin/Windows. Linux must not acquire that dependency through sigil-ui.3. Commit the resolved registry lock; a local redirect is not release evidence.4. Run the full sigil-ui test suite on Linux against the real registry lock.5. Rerun the 22 AppKit drawing-boundary checks against that lock, with the controlled host first on the source path.6. Complete Windows cross-build and the real Mac host/drawing behavior gates, then publish sigil-ui.The Mac font/drawing gate requires the accepted SDK-free CoreText backend.Source/object builds alone do not qualify native drawing or browser behavior.docs/window-services.mdmodified
The portable dispatcher adds the service status without changing legacy events.Qualification uses an isolated Wayland protocol server and an owned headlesscompositor. AppKit controls use hidden windows, controlled native transitionnotifications, and a private named pasteboard. They do not activate a window,change Spaces, or access the user's clipboard.compositor. AppKit host qualification belongs to sigil-window's Linux-builtnative/Sigil/WKWebView packet; its hidden-window controls use controlledtransitions and a private named pasteboard. Real UI drawing with outlinefonts requires the SDK-free sigil-font backend and its separate Mac gate.native/appkit-host.hdeleted
/* Trusted native-adapter API. No AppKit pointers cross the Sigil window API. * Every function and callback runs synchronously on the main thread. Callbacks * must not suspend, block, navigate or enter a script engine. Tokens are scoped * to this process and never reused; stale tokens fail without touching AppKit. */#ifndef SIGIL_UI_APPKIT_HOST_H#define SIGIL_UI_APPKIT_HOST_H#include <stdbool.h>#include <stdint.h>#ifdef __cplusplusextern "C" {#endiftypedef uint64_t SUIHostToken;typedef uint64_t SUIChildToken;typedef uint64_t SUIHookToken;typedef struct { double x, y, width, height; /* Logical top-left child allocation. */ double content_width, content_height; int scale; bool visible, focused;} SUIGeometry;typedef enum { SUI_HOST_GEOMETRY, SUI_HOST_FOCUS, SUI_HOST_DEACTIVATED, SUI_CHILD_WILL_DETACH, SUI_HOST_WILL_CLOSE} SUIHostEvent;typedef void (*SUIHostNotify)(void *context, SUIHostToken host, SUIChildToken child, SUIHostEvent event, const SUIGeometry *geometry);typedef struct { int action; /* 0 release, 1 press, 2 repeat. */ uint16_t hardware_code; uint32_t modifiers; /* shift=1 control=2 alt=4 super=8 caps=16 num=32 */ SUIChildToken target; /* Zero means the sigil-ui canvas. */ const char *name, *text; /* Copied data, valid only during this callback. */} SUIKey;typedef bool (*SUIKeyFilter)(void *context, SUIHostToken host, const SUIKey *key);bool sigil_ui_appkit_host_valid(SUIHostToken host);bool sigil_ui_appkit_host_geometry(SUIHostToken host, SUIGeometry *geometry);/* native_view is an unparented NSView*, bridged by the trusted adapter. The * host retains it until detach; the adapter keeps its own ownership. Higher * order values draw above lower values, below the canvas overlay. */SUIChildToken sigil_ui_appkit_child_adopt(SUIHostToken host, void *native_view, double x, double y, double width, double height, int order, SUIHostNotify notify, void *context);bool sigil_ui_appkit_child_place(SUIHostToken host, SUIChildToken child, double x, double y, double width, double height, int order);bool sigil_ui_appkit_child_remove(SUIHostToken host, SUIChildToken child);bool sigil_ui_appkit_focus_child(SUIHostToken host, SUIChildToken child);bool sigil_ui_appkit_focus_ui(SUIHostToken host);/* Filters run newest first on a press; consume/pass and target stick through * its repeats/release. A passed child event follows native dispatch once. * Removing a filter or changing focus cancels its pending key ownership. */SUIHookToken sigil_ui_appkit_key_filter_add(SUIHostToken host, SUIKeyFilter filter, void *context);bool sigil_ui_appkit_key_filter_remove(SUIHostToken host, SUIHookToken hook);#ifdef __cplusplus}#endif#endifnative/appkit-host.incdeleted
/* Included by appkit.m: registry and trusted adapter implementation. */@interface SUIContainerView : NSView@end@implementation SUIContainerView- (BOOL)isFlipped { return YES; }@end@interface SUIChild : NSObject@property SUIChildToken token;@property(strong) NSView *view;@property(strong) SUIContainerView *container;@property int order;@property BOOL detaching;@property SUIHostNotify notify;@property void *context;@end@implementation SUIChild@end@interface SUIHook : NSObject@property SUIHookToken token;@property SUIKeyFilter filter;@property void *context;@end@implementation SUIHook@end@interface SUIKeyOwner : NSObject@property SUIChildToken target;@property BOOL consumed;@end@implementation SUIKeyOwner@endstatic NSMapTable<NSNumber *, SUIHost *> *hostRegistry;static uint64_t tokenSerial;static uint64_t freshToken(void) { return tokenSerial<(UINT64_C(1)<<48) ? ++tokenSerial : 0; }static SUIHost *findHost(SUIHostToken token) { if (!NSThread.isMainThread || !token) return nil; SUIHost *host=[hostRegistry objectForKey:@(token)]; return host.closed ? nil : host;}static SUIHostToken hostToken(SUIHost *host) { if (!NSThread.isMainThread || host.closed || host.closing) return 0; if (!host.token) { if (!hostRegistry) hostRegistry=[NSMapTable strongToWeakObjectsMapTable]; host.token=freshToken(); if (host.token) [hostRegistry setObject:host forKey:@(host.token)]; host.children=[NSMutableDictionary new]; host.hooks=[NSMutableArray new]; host.keyOwners=[NSMutableDictionary new]; host.canceledKeys=[NSMutableSet new]; } return host.token;}static SUIChild *focusedChild(SUIHost *host) { NSResponder *responder=host.window.firstResponder; if (![responder isKindOfClass:NSView.class]) return nil; for (SUIChild *child in host.children.allValues) { if (!child.detaching && !child.container.hidden && (responder==child.view || [(NSView *)responder isDescendantOf:child.view])) return child; } return nil;}static SUIGeometry childGeometry(SUIHost *host, SUIChild *child) { NSRect frame=child ? child.container.frame : host.view.bounds; return (SUIGeometry){frame.origin.x,frame.origin.y,frame.size.width,frame.size.height, host.view.bounds.size.width,host.view.bounds.size.height,host.scale, child ? !child.container.hidden : !NSIsEmptyRect(host.view.bounds), host.focused && (child ? focusedChild(host)==child : focusedChild(host)==nil)};}static void notifyChild(SUIHost *host, SUIChild *child, SUIHostEvent event) { if (child.notify) { SUIGeometry geometry=childGeometry(host,child); child.notify(child.context,host.token,child.token,event,&geometry); }}static void cancelKeys(SUIHost *host) { host.keyEpoch++; [host.canceledKeys addObjectsFromArray:host.keyOwners.allKeys]; [host.keyOwners removeAllObjects];}static void hostFocusChanged(SUIHost *host, BOOL deactivated) { SUIChildToken target=focusedChild(host).token; if (target==host.notifiedFocus && host.focused==host.notifiedActive && !deactivated) return; host.notifiedFocus=target; host.notifiedActive=host.focused; cancelKeys(host); for (SUIChild *child in host.children.allValues) { if (!child.detaching) notifyChild(host,child,deactivated ? SUI_HOST_DEACTIVATED : SUI_HOST_FOCUS); }}static void hostGeometryChanged(SUIHost *host) { for (SUIChild *child in host.children.allValues) { if (!child.detaching) notifyChild(host,child,SUI_HOST_GEOMETRY); }}static void ensureContent(SUIHost *host) { if (host.content) return; NSRect bounds=host.view.bounds; host.content=[[SUIContainerView alloc] initWithFrame:bounds]; host.content.wantsLayer=YES; host.content.layer.masksToBounds=YES; SUIView *canvas=host.view; BOOL uiFocused=host.window.firstResponder==canvas; [canvas removeFromSuperview]; host.window.contentView=host.content; canvas.frame=host.content.bounds; canvas.autoresizingMask=NSViewWidthSizable | NSViewHeightSizable; [host.content addSubview:canvas]; if (uiFocused) [host.window makeFirstResponder:canvas];}static BOOL validAllocation(double x, double y, double width, double height) { return isfinite(x) && isfinite(y) && isfinite(width) && isfinite(height) && fabs(x)<=16384 && fabs(y)<=16384 && width>=0 && height>=0 && width<=16384 && height<=16384;}static void orderChildren(SUIHost *host) { NSArray<SUIChild *> *children=[host.children.allValues sortedArrayUsingComparator: ^NSComparisonResult(SUIChild *a, SUIChild *b) { if (a.order!=b.order) return a.order<b.order ? NSOrderedAscending : NSOrderedDescending; return a.token<b.token ? NSOrderedAscending : NSOrderedDescending; }]; for (SUIChild *child in children) { [host.content addSubview:child.container positioned:NSWindowBelow relativeTo:host.view]; }}bool sigil_ui_appkit_host_valid(SUIHostToken token) { return findHost(token)!=nil; }bool sigil_ui_appkit_host_geometry(SUIHostToken token, SUIGeometry *geometry) { SUIHost *host=findHost(token); if (!host || !geometry) return false; *geometry=childGeometry(host,nil); return true;}bool sigil_ui_appkit_child_place(SUIHostToken token, SUIChildToken id, double x, double y, double width, double height, int order) { SUIHost *host=findHost(token); SUIChild *child=host.children[@(id)]; if (!host || host.closing || !child || child.detaching || !validAllocation(x,y,width,height)) return false; NSRect frame=NSMakeRect(x,y,width,height); BOOL changed=!NSEqualRects(frame,child.container.frame) || order!=child.order; child.order=order; child.container.frame=frame; child.view.frame=NSMakeRect(0,0,width,height); child.container.hidden=width==0 || height==0; if (child.container.hidden && host.notifiedFocus==id) sigil_ui_appkit_focus_ui(token); orderChildren(host); if (changed) notifyChild(host,child,SUI_HOST_GEOMETRY); return true;}SUIChildToken sigil_ui_appkit_child_adopt(SUIHostToken token, void *nativeView, double x, double y, double width, double height, int order, SUIHostNotify notify, void *context) { SUIHost *host=findHost(token); if (!host || host.closing || !nativeView || !validAllocation(x,y,width,height)) return 0; NSView *view=(__bridge NSView *)nativeView; if (![view isKindOfClass:NSView.class] || view.superview || view.window) return 0; SUIChild *child=[SUIChild new]; child.token=freshToken(); if (!child.token) return 0; ensureContent(host); child.view=view; child.notify=notify; child.context=context; child.container=[[SUIContainerView alloc] initWithFrame:NSZeroRect]; child.container.wantsLayer=YES; child.container.layer.masksToBounds=YES; [child.container addSubview:view]; host.children[@(child.token)]=child; [host.content addSubview:child.container positioned:NSWindowBelow relativeTo:host.view]; sigil_ui_appkit_child_place(token,child.token,x,y,width,height,order); /* A notification may synchronously remove the new child or close the host. */ return host.children[@(child.token)]==child && !host.closed ? child.token : 0;}static BOOL removeChild(SUIHost *host, SUIChild *child, SUIHostEvent event) { if (!child || child.detaching) return false; child.detaching=YES; cancelKeys(host); if (host.notifiedFocus==child.token) { [host.window makeFirstResponder:host.view]; hostFocusChanged(host,NO); } notifyChild(host,child,event); [child.view removeFromSuperview]; [child.container removeFromSuperview]; [host.children removeObjectForKey:@(child.token)]; child.notify=NULL; child.context=NULL; return true;}bool sigil_ui_appkit_child_remove(SUIHostToken token, SUIChildToken child) { SUIHost *host=findHost(token); return host && removeChild(host,host.children[@(child)],SUI_CHILD_WILL_DETACH);}bool sigil_ui_appkit_focus_ui(SUIHostToken token) { SUIHost *host=findHost(token); if (!host || host.closing) return false; BOOL result=[host.window makeFirstResponder:host.view]; hostFocusChanged(host,NO); return result;}bool sigil_ui_appkit_focus_child(SUIHostToken token, SUIChildToken id) { SUIHost *host=findHost(token); SUIChild *child=host.children[@(id)]; if (!host || host.closing || !child || child.detaching || child.container.hidden) return false; BOOL result=[host.window makeFirstResponder:child.view]; hostFocusChanged(host,NO); return result;}SUIHookToken sigil_ui_appkit_key_filter_add(SUIHostToken token, SUIKeyFilter filter, void *context) { SUIHost *host=findHost(token); if (!host || host.closing || !filter) return 0; SUIHook *hook=[SUIHook new]; hook.token=freshToken(); if (!hook.token) return 0; hook.filter=filter; hook.context=context; [host.hooks addObject:hook]; return hook.token;}bool sigil_ui_appkit_key_filter_remove(SUIHostToken token, SUIHookToken id) { SUIHost *host=findHost(token); if (!host) return false; for (SUIHook *hook in host.hooks.copy) { if (hook.token==id) { cancelKeys(host); [host.hooks removeObject:hook]; return true; } } return false;}static void hostWillClose(SUIHost *host) { cancelKeys(host); [host.hooks removeAllObjects]; for (SUIChild *child in host.children.allValues) removeChild(host,child,SUI_HOST_WILL_CLOSE); [hostRegistry removeObjectForKey:@(host.token)]; host.content=nil;}static BOOL routeKey(SUIHost *host, NSEvent *event) { if (!host.token) { [(SUIApplication *)NSApp sendUIKey:event host:host]; return NO; } hostFocusChanged(host,NO); int action=event.type==NSEventTypeKeyUp ? 0 : 1; if (event.type==NSEventTypeKeyDown && event.isARepeat) action=2; if (event.type==NSEventTypeFlagsChanged) { /* The UI decoder already handles each modifier's release correctly. * Determine the hook action from its hardware-specific flag as well. */ NSEventModifierFlags flag=0; switch (event.keyCode) { case 54: case 55: flag=NSEventModifierFlagCommand; break; case 56: case 60: flag=NSEventModifierFlagShift; break; case 58: case 61: flag=NSEventModifierFlagOption; break; case 59: case 62: flag=NSEventModifierFlagControl; break; case 57: flag=NSEventModifierFlagCapsLock; break; default: /* System shortcuts can synchronize flags with an unmapped * key code. It is neither a key release nor a text event. */ if (focusedChild(host)) return YES; [(SUIApplication *)NSApp sendUIKey:event host:host]; return NO; } action=(event.modifierFlags & flag) ? 1 : 0; } NSNumber *code=@(event.keyCode); if (action==1) [host.canceledKeys removeObject:code]; else if ([host.canceledKeys containsObject:code]) return NO; SUIKeyOwner *owner=host.keyOwners[code]; if (!owner) { owner=[SUIKeyOwner new]; owner.target=focusedChild(host).token; __attribute__((objc_precise_lifetime)) NSString *name=[keyName(event) copy]; __attribute__((objc_precise_lifetime)) NSString *text= event.type==NSEventTypeKeyDown ? [event.characters copy] : @""; SUIKey key={action,event.keyCode,mods(event.modifierFlags),owner.target, name.UTF8String ?: "",text.UTF8String ?: ""}; uint64_t epoch=host.keyEpoch; for (SUIHook *hook in (action==1 ? host.hooks.reverseObjectEnumerator.allObjects : @[])) { if (![host.hooks containsObject:hook]) continue; if (hook.filter(hook.context,host.token,&key)) { owner.consumed=YES; break; } if (host.closed || host.closing) return NO; } if (host.closed || host.closing) return NO; if (epoch!=host.keyEpoch || focusedChild(host).token!=owner.target || [host.canceledKeys containsObject:code]) { [host.canceledKeys addObject:code]; return NO; } if (action!=0) host.keyOwners[code]=owner; } if (action==0) [host.keyOwners removeObjectForKey:code]; if (owner.consumed) return NO; if (owner.target) return YES; [(SUIApplication *)NSApp sendUIKey:event host:host]; return NO;}native/appkit.mdeleted
/* AppKit host for the retained software canvas. Call only on the main thread. * Delegates queue data. A scoped tracking-mode source can run a synchronous * application render step; that step must never suspend or escape. */#import <AppKit/AppKit.h>#import <QuartzCore/QuartzCore.h>#include <sigil/sigil.h>#include <math.h>#include <string.h>#include "appkit-host.h"#include "window-services.h"@class SUIChild, SUIHook, SUIKeyOwner;@interface SUIEvent : NSObject@property int type;@property int64_t a, b, c, d, e, f;@property(copy) NSString *name;@property(copy) NSString *text;@end@implementation SUIEvent@end@class SUIHost;@interface SUIView : NSView@property(weak) SUIHost *host;@property(strong) NSMutableData *pixels;@property(strong) NSMutableData *alpha;@property int pixelWidth, pixelHeight;@property(strong) NSTrackingArea *tracking;@end@interface SUIHost : NSObject <NSWindowDelegate>{@public SuiFullscreenRequest fullscreenRequest;}@property(strong) NSWindow *window;@property(strong) SUIView *view;@property(strong) NSMutableArray<SUIEvent *> *events;@property(strong) SUIEvent *current;@property int width, height, scale;@property BOOL focused, closed, overflow;@property NSEventModifierFlags modifiers;@property int resizeEdges;@property NSRect resizeFrame;@property NSPoint resizeOrigin;@property BOOL timing;@property double pointerTime, presentedPointerTime, copyTotal, copyMax, drawTotal, drawMax;@property unsigned long copyCount, drawCount;@property SigilVM *trackingVM;@property Value trackingHandler;@property CFRunLoopSourceRef trackingSource;@property BOOL inTrackingStep;@property SUIHostToken token;@property BOOL closing;@property(strong) NSView *content;@property(strong) NSMutableDictionary<NSNumber *, SUIChild *> *children;@property(strong) NSMutableArray<SUIHook *> *hooks;@property(strong) NSMutableDictionary<NSNumber *, SUIKeyOwner *> *keyOwners;@property(strong) NSMutableSet<NSNumber *> *canceledKeys;@property SUIChildToken notifiedFocus;@property BOOL notifiedActive;@property uint64_t keyEpoch;@property BOOL inKeyCallback;@property BOOL fullscreenAcknowledged;@property int fullscreenTransition;@property uint64_t fullscreenGeneration;@property uint64_t fullscreenTransitionGeneration;@property CFRunLoopTimerRef fullscreenTimer;#ifdef SUI_WINDOW_SERVICES_TEST@property(strong) NSPasteboard *servicePasteboard;#endif- (void)geometry;- (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;- (void)key:(NSEvent *)event;@endstatic NSHashTable<SUIHost *> *hosts;static Value hostTag;static __weak SUIHost *resizingHost;static void hostGeometryChanged(SUIHost *host);static void hostFocusChanged(SUIHost *host, BOOL deactivated);static void hostWillClose(SUIHost *host);static BOOL routeKey(SUIHost *host, NSEvent *event);static SUIHostToken hostToken(SUIHost *host);static void windowServiceConfigured(SUIHost *host, BOOL actual);static void windowServiceFailed(SUIHost *host);static void stopWindowServices(SUIHost *host);static void stopTrackingStep(SUIHost *host) { if (host.trackingSource) { CFRunLoopSourceInvalidate(host.trackingSource); CFRelease(host.trackingSource); host.trackingSource=NULL; } host.trackingHandler=SIGIL_FALSE; host.trackingVM=NULL;}static void trackingStepReady(void *info) { SUIHost *host=(__bridge SUIHost *)info; CFStringRef mode=CFRunLoopCopyCurrentMode(CFRunLoopGetMain()); BOOL tracking=mode && CFEqual(mode,(__bridge CFStringRef)NSEventTrackingRunLoopMode); if (mode) CFRelease(mode); if (!tracking || host.closed || host.inTrackingStep || !host.events.count || host.trackingHandler==SIGIL_FALSE || !host.trackingVM) return; host.inTrackingStep=YES; SigilVM *vm=host.trackingVM; Value result=sigil_applyN(vm,host.trackingHandler,0,NULL); host.inTrackingStep=NO; if (result==SIGIL_FALSE || sigil_error_message(vm)) host.trackingHandler=SIGIL_FALSE; if (!host.closed) { [host.view displayIfNeeded]; [CATransaction flush]; }}static void traceHost(SigilVM *vm, void *data) { SUIHost *host=(__bridge SUIHost *)data; sigil__gc_mark_foreign_value(vm,host.trackingHandler);}static void timingReport(SUIHost *host) { fprintf(stderr,"TIMING pointer copy count=%lu mean=%.2f max=%.2f ms; draw count=%lu mean=%.2f max=%.2f ms\n", host.copyCount,host.copyCount ? host.copyTotal/host.copyCount : 0,host.copyMax, host.drawCount,host.drawCount ? host.drawTotal/host.drawCount : 0,host.drawMax);}enum { ResizeLeft=1, ResizeRight=2, ResizeBottom=4, ResizeTop=8 };static const double resizeOutsideBand=16;/* AppKit's standard frame tracker nests inside sendEvent: until mouse-up. * Own just the frame-edge drag so the outer Sigil loop can consume each size * event and render a new canvas between drags, without reentering the VM. */static BOOL beginResize(SUIHost *host, NSPoint point) { NSRect frame=host.window.frame; if (!NSPointInRect(point,NSInsetRect(frame,-resizeOutsideBand,-resizeOutsideBand)) || (host.window.styleMask & NSWindowStyleMaskFullScreen)) return NO; int edges=0; if (point.x>=NSMinX(frame)-resizeOutsideBand && point.x<=NSMinX(frame)+5) edges|=ResizeLeft; else if (point.x>=NSMaxX(frame)-5 && point.x<=NSMaxX(frame)+resizeOutsideBand) edges|=ResizeRight; if (point.y>=NSMinY(frame)-resizeOutsideBand && point.y<=NSMinY(frame)+5) edges|=ResizeBottom; else if (point.y>=NSMaxY(frame)-5 && point.y<=NSMaxY(frame)+resizeOutsideBand) edges|=ResizeTop; if (!edges) return NO; host.resizeEdges=edges; host.resizeFrame=frame; host.resizeOrigin=point; resizingHost=host; return YES;}static void updateResize(SUIHost *host, NSPoint point) { NSRect frame=host.resizeFrame; double dx=point.x-host.resizeOrigin.x, dy=point.y-host.resizeOrigin.y; NSRect minimum=[host.window frameRectForContentRect:NSMakeRect(0,0, MAX(0,host.window.contentMinSize.width),MAX(0,host.window.contentMinSize.height))]; if (host.resizeEdges & ResizeLeft) { frame.size.width=MAX(minimum.size.width,frame.size.width-dx); frame.origin.x=NSMaxX(host.resizeFrame)-frame.size.width; } else if (host.resizeEdges & ResizeRight) frame.size.width=MAX(minimum.size.width,frame.size.width+dx); if (host.resizeEdges & ResizeBottom) { frame.size.height=MAX(minimum.size.height,frame.size.height-dy); frame.origin.y=NSMaxY(host.resizeFrame)-frame.size.height; } else if (host.resizeEdges & ResizeTop) frame.size.height=MAX(minimum.size.height,frame.size.height+dy); [host.window setFrame:frame display:YES animate:NO]; [host geometry];}static int mods(NSEventModifierFlags f) { return ((f & NSEventModifierFlagShift) ? 1 : 0) | ((f & NSEventModifierFlagControl) ? 2 : 0) | ((f & NSEventModifierFlagOption) ? 4 : 0) | ((f & NSEventModifierFlagCommand) ? 8 : 0) | ((f & NSEventModifierFlagCapsLock) ? 16 : 0);}/* Apple hardware positions to Linux evdev positions, independent of layout. * Unmapped keys use zero rather than exposing platform-specific codes. */static int evdev(unsigned code) { static const unsigned short table[128] = { [0]=30,[1]=31,[2]=32,[3]=33,[4]=35,[5]=34,[6]=44,[7]=45,[8]=46,[9]=47, [11]=48,[12]=16,[13]=17,[14]=18,[15]=19,[16]=21,[17]=20,[18]=2,[19]=3, [20]=4,[21]=5,[22]=7,[23]=6,[24]=13,[25]=10,[26]=8,[27]=12,[28]=9,[29]=11, [30]=27,[31]=24,[32]=22,[33]=26,[34]=23,[35]=25,[36]=28,[37]=38,[38]=36, [39]=40,[40]=37,[41]=39,[42]=43,[43]=51,[44]=53,[45]=49,[46]=50,[47]=52, [48]=15,[49]=57,[50]=41,[51]=14,[53]=1,[54]=126,[55]=125,[56]=42, [57]=58,[58]=56,[59]=29,[60]=54,[61]=100,[62]=97,[65]=83,[67]=55, [69]=78,[71]=69,[75]=98,[76]=96,[78]=74,[81]=117,[82]=82,[83]=79, [84]=80,[85]=81,[86]=75,[87]=76,[88]=77,[89]=71,[91]=72,[92]=73, [96]=63,[97]=64,[98]=65,[99]=61,[100]=66,[101]=67,[103]=87,[109]=68, [111]=88,[114]=110,[115]=102,[116]=104,[117]=111,[118]=62,[119]=107, [120]=60,[121]=109,[122]=59,[123]=105,[124]=106,[125]=108,[126]=103 }; return code < 128 ? table[code] : 0;}static NSString *keyName(NSEvent *event) { switch (event.keyCode) { case 36: case 76: return @"Return"; case 48: return (event.modifierFlags & NSEventModifierFlagShift) ? @"ISO_Left_Tab" : @"Tab"; case 49: return @"space"; case 51: return @"BackSpace"; case 53: return @"Escape"; case 54: return @"Super_R"; case 55: return @"Super_L"; case 56: return @"Shift_L"; case 60: return @"Shift_R"; case 57: return @"Caps_Lock"; case 58: return @"Alt_L"; case 61: return @"Alt_R"; case 59: return @"Control_L"; case 62: return @"Control_R"; case 115: return @"Home"; case 119: return @"End"; case 116: return @"Page_Up"; case 121: return @"Page_Down"; case 117: return @"Delete"; case 114: return @"Insert"; case 123: return @"Left"; case 124: return @"Right"; case 125: return @"Down"; case 126: return @"Up"; } NSString *s = event.charactersIgnoringModifiers ?: @""; if (s.length == 1) { unichar c = [s characterAtIndex:0]; if (c >= NSF1FunctionKey && c <= NSF35FunctionKey) return [NSString stringWithFormat:@"F%d", c - NSF1FunctionKey + 1]; static NSString *punct = @"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; static NSArray *names; if (!names) names = @[@"exclam",@"quotedbl",@"numbersign",@"dollar",@"percent", @"ampersand",@"apostrophe",@"parenleft",@"parenright",@"asterisk",@"plus", @"comma",@"minus",@"period",@"slash",@"colon",@"semicolon",@"less",@"equal", @"greater",@"question",@"at",@"bracketleft",@"backslash",@"bracketright", @"asciicircum",@"underscore",@"grave",@"braceleft",@"bar",@"braceright",@"asciitilde"]; NSRange r = [punct rangeOfString:s]; if (r.location != NSNotFound) return names[r.location]; if (c < 128) return s; return [NSString stringWithFormat:@"U%04X", c]; } return @"";}@implementation SUIHost- (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 { SUIEvent *last=self.events.lastObject; if ((type==8 || type==1) && last.type==type && last.a==a && last.b==b && last.c==c) return; if (self.events.count >= 4096) { self.overflow = YES; return; } SUIEvent *event = [SUIEvent new]; event.type=type; event.a=a; event.b=b; event.c=c; event.d=d; event.e=e; event.f=f; [self.events addObject:event]; if (type!=3 && self.trackingSource && !self.inTrackingStep) { CFRunLoopSourceSignal(self.trackingSource); CFRunLoopWakeUp(CFRunLoopGetMain()); }}- (void)geometry { /* Keep allocation dimensions positive even when native content is empty. * A later nonempty size emits another resize and replaces this backing. */ int width = MAX(1, (int)floor(self.view.bounds.size.width)); int height = MAX(1, (int)floor(self.view.bounds.size.height)); int scale = MAX(1, (int)lround(self.window.backingScaleFactor)); if (width != self.width || height != self.height || scale != self.scale) { self.width=width; self.height=height; self.scale=scale; [self emit:1 a:width b:height c:scale d:0 e:0 f:0]; hostGeometryChanged(self); }}- (void)windowDidResize:(NSNotification *)n { (void)n; [self geometry]; }- (void)windowDidChangeBackingProperties:(NSNotification *)n { (void)n; [self geometry]; }- (void)windowWillEnterFullScreen:(NSNotification *)n { (void)n; self.fullscreenTransition=1; }- (void)windowWillExitFullScreen:(NSNotification *)n { (void)n; self.fullscreenTransition=-1; }- (void)windowDidEnterFullScreen:(NSNotification *)n { (void)n; windowServiceConfigured(self,YES); }- (void)windowDidExitFullScreen:(NSNotification *)n { (void)n; windowServiceConfigured(self,NO); }- (void)windowDidFailToEnterFullScreen:(NSWindow *)window { (void)window; windowServiceFailed(self); }- (void)windowDidFailToExitFullScreen:(NSWindow *)window { (void)window; windowServiceFailed(self); }- (void)windowDidBecomeKey:(NSNotification *)n { (void)n; self.focused=YES; [self emit:5 a:1 b:0 c:0 d:0 e:0 f:0]; hostFocusChanged(self,NO);}- (void)windowDidResignKey:(NSNotification *)n { (void)n; self.focused=NO; self.modifiers=0; [self emit:5 a:0 b:0 c:0 d:0 e:0 f:0]; hostFocusChanged(self,YES);}- (BOOL)windowShouldClose:(NSWindow *)sender { (void)sender; [self emit:2 a:0 b:0 c:0 d:0 e:0 f:0]; return NO;}- (void)key:(NSEvent *)event { int action = event.type == NSEventTypeKeyUp ? 0 : 1; if (event.type == NSEventTypeKeyDown && event.isARepeat) action=2; if (event.type == NSEventTypeFlagsChanged) { NSEventModifierFlags mask = 0; switch (event.keyCode) { case 54: case 55: mask=NSEventModifierFlagCommand; break; case 56: case 60: mask=NSEventModifierFlagShift; break; case 57: mask=NSEventModifierFlagCapsLock; break; case 58: case 61: mask=NSEventModifierFlagOption; break; case 59: case 62: mask=NSEventModifierFlagControl; break; default: return; } action = (event.modifierFlags & mask) ? 1 : 0; } [self emit:4 a:action b:0 c:mods(event.modifierFlags) d:evdev(event.keyCode) e:0 f:0]; if (self.overflow) return; SUIEvent *key = self.events.lastObject; key.name = keyName(event); NSString *text = event.type == NSEventTypeKeyDown ? (event.characters ?: @"") : @""; BOOL printable = text.length && [text characterAtIndex:0] >= 32 && !([text characterAtIndex:0] >= 0xf700 && [text characterAtIndex:0] <= 0xf8ff); key.text = action && event.type != NSEventTypeFlagsChanged && printable && !(event.modifierFlags & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) ? text : @""; self.modifiers = event.modifierFlags;}@end@interface SUIApplication : NSApplication- (NSPoint)resizePointForEvent:(NSEvent *)event;- (void)sendUIKey:(NSEvent *)event host:(SUIHost *)host;- (void)forwardNativeEvent:(NSEvent *)event;@end@implementation SUIApplication- (NSPoint)resizePointForEvent:(NSEvent *)event { /* Use the event's recorded position, not the current global cursor. The * cursor may already have left the resize band when mouse-down is read. */ CGEventRef native=event.CGEvent; if (native) { CGPoint point=CGEventGetLocation(native); return NSMakePoint(point.x,NSMaxY(NSScreen.screens.firstObject.frame)-point.y); } return event.window ? [event.window convertPointToScreen:event.locationInWindow] : event.locationInWindow;}- (void)sendEvent:(NSEvent *)event { SUIHost *drag=resizingHost; if (drag && (event.type==NSEventTypeLeftMouseDragged || event.type==NSEventTypeLeftMouseUp)) { updateResize(drag,[self resizePointForEvent:event]); if (event.type==NSEventTypeLeftMouseUp) { drag.resizeEdges=0; resizingHost=nil; } return; } for (SUIHost *host in hosts.allObjects) { if (event.type==NSEventTypeLeftMouseDown && (event.window==host.window || (!event.window && host.window.keyWindow)) && beginResize(host,[self resizePointForEvent:event])) return; if (event.window == host.window && (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp || event.type == NSEventTypeFlagsChanged)) { host.inKeyCallback=YES; @try { if (routeKey(host,event)) { [self forwardNativeEvent:event]; hostFocusChanged(host,NO); } } @finally { host.inKeyCallback=NO; } return; } } [super sendEvent:event]; for (SUIHost *host in hosts.allObjects) { if (event.window==host.window) hostFocusChanged(host,NO); }}- (void)forwardNativeEvent:(NSEvent *)event { [super sendEvent:event]; }/* UI-owned events preserve the existing minimal menu and event forms. */- (void)sendUIKey:(NSEvent *)event host:(SUIHost *)host { if (event.type == NSEventTypeKeyDown && (event.modifierFlags & NSEventModifierFlagCommand) && [event.charactersIgnoringModifiers.lowercaseString isEqualToString:@"q"]) { for (SUIHost *h in hosts.allObjects) [h emit:2 a:0 b:0 c:0 d:0 e:0 f:0]; } else [host key:event];}- (void)terminate:(id)sender { (void)sender; for (SUIHost *host in hosts.allObjects) [host emit:2 a:0 b:0 c:0 d:0 e:0 f:0];}@end@implementation SUIView- (void)setFrameSize:(NSSize)size { [super setFrameSize:size]; [self.host geometry];}- (BOOL)isFlipped { return YES; }- (BOOL)acceptsFirstResponder { return YES; }- (BOOL)isOpaque { return self.alpha==nil; }- (NSView *)hitTest:(NSPoint)point { NSPoint local=[self convertPoint:point fromView:self.superview]; if (self.hidden || !NSPointInRect(local,self.bounds)) return nil; if (self.alpha) { int x=floor(local.x*self.host.scale), y=floor(local.y*self.host.scale); if (x<0 || y<0 || x>=self.pixelWidth || y>=self.pixelHeight || ((const uint8_t *)self.alpha.bytes)[y*self.pixelWidth+x]==0) return nil; } return self;}- (void)updateTrackingAreas { if (self.tracking) [self removeTrackingArea:self.tracking]; self.tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect owner:self userInfo:nil]; [self addTrackingArea:self.tracking]; [super updateTrackingAreas];}- (NSPoint)point:(NSEvent *)event { return [self convertPoint:event.locationInWindow fromView:nil]; }- (void)mouseEntered:(NSEvent *)event { 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];}- (void)mouseExited:(NSEvent *)event { (void)event; [self.host emit:7 a:0 b:0 c:0 d:0 e:0 f:0]; }- (void)mouseMoved:(NSEvent *)event { if (self.host.timing) self.host.pointerTime=event.timestamp; 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];}- (void)mouseDragged:(NSEvent *)e { [self mouseMoved:e]; }- (void)rightMouseDragged:(NSEvent *)e { [self mouseMoved:e]; }- (void)otherMouseDragged:(NSEvent *)e { [self mouseMoved:e]; }- (void)button:(NSEvent *)event down:(BOOL)down { if (down) { [self.window makeFirstResponder:self]; hostFocusChanged(self.host,NO); } NSPoint p=[self point:event]; [self.host emit:9 a:272+event.buttonNumber b:down c:floor(p.x) d:floor(p.y) e:0 f:0];}- (void)mouseDown:(NSEvent *)e { [self button:e down:YES]; }- (void)mouseUp:(NSEvent *)e { [self button:e down:NO]; }- (void)rightMouseDown:(NSEvent *)e { [self button:e down:YES]; }- (void)rightMouseUp:(NSEvent *)e { [self button:e down:NO]; }- (void)otherMouseDown:(NSEvent *)e { [self button:e down:YES]; }- (void)otherMouseUp:(NSEvent *)e { [self button:e down:NO]; }- (void)scrollWheel:(NSEvent *)event { NSPoint p=[self point:event]; [self.host emit:10 a:llround(-event.scrollingDeltaX*256) b:llround(-event.scrollingDeltaY*256) c:event.hasPreciseScrollingDeltas ? 0 : llround(-event.scrollingDeltaX) d:event.hasPreciseScrollingDeltas ? 0 : llround(-event.scrollingDeltaY) e:floor(p.x) f:floor(p.y)];}- (void)drawRect:(NSRect)dirty { (void)dirty; if (self.alpha) CGContextClearRect(NSGraphicsContext.currentContext.CGContext,self.bounds); else { [[NSColor blackColor] setFill]; NSRectFill(self.bounds); } if (!self.pixels) return; CGColorSpaceRef color = CGColorSpaceCreateDeviceRGB(); CGDataProviderRef data = CGDataProviderCreateWithCFData((__bridge CFDataRef)self.pixels); CGImageRef image = CGImageCreate(self.pixelWidth, self.pixelHeight, 8, 32, self.pixelWidth*4, color, kCGBitmapByteOrder32Little | (self.alpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst), data, NULL, false, kCGRenderingIntentDefault); CGContextRef ctx = NSGraphicsContext.currentContext.CGContext; CGContextSaveGState(ctx); CGContextSetInterpolationQuality(ctx, kCGInterpolationNone); CGContextTranslateCTM(ctx, 0, self.bounds.size.height); CGContextScaleCTM(ctx, 1, -1); /* Never stretch a stale canvas while the next size is being rendered. */ CGFloat scale=self.host.scale; CGContextDrawImage(ctx,CGRectMake(0,self.bounds.size.height-self.pixelHeight/scale, self.pixelWidth/scale,self.pixelHeight/scale),image); CGContextRestoreGState(ctx); CGImageRelease(image); CGDataProviderRelease(data); CGColorSpaceRelease(color); SUIHost *host=self.host; if (host.presentedPointerTime>0) { double ms=(NSProcessInfo.processInfo.systemUptime-host.presentedPointerTime)*1000; host.drawCount++; host.drawTotal+=ms; host.drawMax=MAX(host.drawMax,ms); host.presentedPointerTime=0; if (host.drawCount==16 || host.drawCount%64==0) timingReport(host); } [self.host emit:3 a:(int64_t)(NSProcessInfo.processInfo.systemUptime*1000) b:0 c:0 d:0 e:0 f:0];}@endstatic SUIHost *asHost(SigilVM *vm, Value value) { if (![NSThread isMainThread]) { sigil__vm_error(vm, SIGIL_ERR_IO, "AppKit window operations require the main thread"); return nil; } if (!sigil_is_foreign(value) || sigil_foreign_type(value) != hostTag) { sigil__vm_error(vm, SIGIL_ERR_TYPE, "expected an AppKit window"); return nil; } return (__bridge SUIHost *)sigil_foreign_data(value);}#include "window-appkit-services.inc"static void closeHost(SUIHost *host) { if (host.closed || host.closing) return; host.closing=YES; stopWindowServices(host); hostWillClose(host); if (host.timing) timingReport(host); stopTrackingStep(host); host.closed=YES; host.focused=NO; if (resizingHost==host) resizingHost=nil; host.window.delegate=nil; host.view.host=nil; [host.window close]; host.window=nil; host.view=nil; [hosts removeObject:host];}static void finalizeHost(void *data) { SUIHost *host = (__bridge_transfer SUIHost *)data; if (NSThread.isMainThread) closeHost(host); else dispatch_async(dispatch_get_main_queue(), ^{ closeHost(host); });}static Value nativeOpen(SigilVM *vm, int argc, Value *args) { (void)argc; if (!NSThread.isMainThread || !sigil_is_string(args[0]) || !sigil_is_fixnum(args[1]) || !sigil_is_fixnum(args[2]) || !sigil_is_fixnum(args[3]) || !sigil_is_fixnum(args[4]) || sigil_as_fixnum(args[1]) < 1 || sigil_as_fixnum(args[1]) > 16384 || sigil_as_fixnum(args[2]) < 1 || sigil_as_fixnum(args[2]) > 16384 || sigil_as_fixnum(args[3]) < 0 || sigil_as_fixnum(args[3]) > 16384 || sigil_as_fixnum(args[4]) < 0 || sigil_as_fixnum(args[4]) > 16384) { sigil__vm_error(vm, SIGIL_ERR_TYPE, "open-window: main thread, title, dimensions 1..16384 and minima 0..16384 required"); return SIGIL_UNDEFINED; } @autoreleasepool { if (!hosts) { hosts=[NSHashTable weakObjectsHashTable]; [SUIApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; NSMenu *menu=[NSMenu new]; NSMenuItem *app=[NSMenuItem new]; [menu addItem:app]; app.submenu=[NSMenu new]; [app.submenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; NSApp.mainMenu=menu; [NSApp finishLaunching]; } SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new]; host.timing=getenv("SIGIL_UI_TIMING")!=NULL; host.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0, sigil_as_fixnum(args[1]),sigil_as_fixnum(args[2])) styleMask: 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
void sigil__register_sigil_ui_surface(SigilVM *vm);void sigil__register_sigil_ui_png(SigilVM *vm);#ifdef __APPLE__void sigil__register_sigil_ui_appkit(SigilVM *vm);#elif !defined(_WIN32)#if !defined(__APPLE__) && !defined(_WIN32)void sigil__register_sigil_ui_wayland(SigilVM *vm);#endif } sigil__register_sigil_ui_surface(vm); sigil__register_sigil_ui_png(vm);#ifdef __APPLE__ sigil__register_sigil_ui_appkit(vm);#elif !defined(_WIN32)#if !defined(__APPLE__) && !defined(_WIN32) sigil__register_sigil_ui_wayland(vm);#endif}native/window-appkit-services.incdeleted
/* Host-only window services. No canvas, renderer, layout, or presentation API. */static int64_t windowServiceNow(void){ return (int64_t)(NSProcessInfo.processInfo.systemUptime*1000);}static BOOL windowServiceLive(SUIHost *host){ return host && !host.closed && !host.closing && host.window;}static SUIHost *windowServiceHandle(SigilVM *vm, Value value){ if (!sigil_is_foreign(value) || sigil_foreign_type(value)!=hostTag) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window service: expected an AppKit window"); return nil; } if (!NSThread.isMainThread) return nil; return (__bridge SUIHost *)sigil_foreign_data(value);}static void windowServiceWake(SUIHost *host){ [host emit:12 a:host.fullscreenAcknowledged b:host->fullscreenRequest.status c:0 d:0 e:0 f:0]; [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:NO];}static void windowServiceStopTimer(SUIHost *host){ if (!host.fullscreenTimer) return; CFRunLoopTimerInvalidate(host.fullscreenTimer); CFRelease(host.fullscreenTimer); host.fullscreenTimer=NULL;}static void windowServiceTick(SUIHost *host){ if (windowServiceLive(host) && sui_fullscreen_expire(&host->fullscreenRequest,windowServiceNow())) { host.fullscreenTransition=0; windowServiceStopTimer(host); windowServiceWake(host); }}static void windowServiceArmTimer(SUIHost *host){ windowServiceStopTimer(host); if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return; __weak SUIHost *weakHost=host; int64_t remaining=sui_fullscreen_wait(&host->fullscreenRequest,windowServiceNow(),-1); host.fullscreenTimer=CFRunLoopTimerCreateWithHandler(NULL, CFAbsoluteTimeGetCurrent()+remaining/1000.0,0,0,0,^(CFRunLoopTimerRef timer) { (void)timer; SUIHost *liveHost=weakHost; if (!liveHost) return; windowServiceTick(liveHost); /* Preserve the monotonic deadline if the timer fires early. */ if (windowServiceLive(liveHost) && liveHost->fullscreenRequest.status==SUI_FULLSCREEN_PENDING) windowServiceArmTimer(liveHost); }); if (!host.fullscreenTimer) { sui_fullscreen_refuse(&host->fullscreenRequest); windowServiceWake(host); return; } CFRunLoopAddCommonMode(CFRunLoopGetMain(),(__bridge CFStringRef)NSEventTrackingRunLoopMode); CFRunLoopAddTimer(CFRunLoopGetMain(),host.fullscreenTimer,kCFRunLoopCommonModes);}static void windowServiceQueueFullscreen(SUIHost *host);static void windowServiceConfigured(SUIHost *host, BOOL actual){ if (!windowServiceLive(host)) return; BOOL changed=host.fullscreenAcknowledged!=actual; host.fullscreenAcknowledged=actual; host.fullscreenTransition=0; int statusChanged=sui_fullscreen_configured(&host->fullscreenRequest,actual); if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) windowServiceStopTimer(host); if (changed || statusChanged) windowServiceWake(host); if (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING) windowServiceQueueFullscreen(host);}static void windowServiceFailed(SUIHost *host){ if (!windowServiceLive(host)) return; host.fullscreenTransition=0; if (host.fullscreenTransitionGeneration!=host.fullscreenGeneration) { if (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING) windowServiceQueueFullscreen(host); return; } if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return; windowServiceStopTimer(host); if (sui_fullscreen_refuse(&host->fullscreenRequest)) windowServiceWake(host);}static void windowServiceQueueFullscreen(SUIHost *host){ uint64_t generation=host.fullscreenGeneration; __weak SUIHost *weakHost=host; CFRunLoopPerformBlock(CFRunLoopGetMain(),kCFRunLoopDefaultMode,^{ SUIHost *liveHost=weakHost; if (!windowServiceLive(liveHost) || liveHost.fullscreenGeneration!=generation || liveHost->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return; windowServiceTick(liveHost); if (liveHost->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING || liveHost.fullscreenTransition) return; if (liveHost.fullscreenAcknowledged==liveHost->fullscreenRequest.requested) { windowServiceConfigured(liveHost,liveHost.fullscreenAcknowledged); return; } liveHost.fullscreenTransition=liveHost->fullscreenRequest.requested ? 1 : -1; liveHost.fullscreenTransitionGeneration=generation; @try { [liveHost.window toggleFullScreen:nil]; } @catch (NSException *failure) { (void)failure; windowServiceFailed(liveHost); } }); CFRunLoopWakeUp(CFRunLoopGetMain());}static void stopWindowServices(SUIHost *host){ windowServiceStopTimer(host); host.fullscreenGeneration++; sui_fullscreen_refuse(&host->fullscreenRequest);}static NSString *windowServiceString(SigilVM *vm, Value value, const char *who){ if (!sigil_is_string(value)) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"%s: expected a string",who); return nil; } return [[NSString alloc] initWithBytes:sigil_string_bytes(value) length:((SigilString *)sigil_as_ptr(value))->byte_length encoding:NSUTF8StringEncoding];}static Value nativeWindowTitle(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); if (!sigil_is_string(args[1])) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: expected a string"); return SIGIL_UNDEFINED; } size_t size=((SigilString *)sigil_as_ptr(args[1]))->byte_length; if (size>4095 || memchr(sigil_string_bytes(args[1]),0,size)) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: invalid title"); return SIGIL_UNDEFINED; } if (!windowServiceLive(host)) return SIGIL_FALSE; NSString *title=windowServiceString(vm,args[1],"window-set-title!"); if (!title) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-title!: invalid UTF-8"); return SIGIL_UNDEFINED; } @try { host.window.title=title; return sigil_bool([host.window.title isEqualToString:title]); } @catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }}static BOOL windowServiceClipboardAllowed(SUIHost *host){ if (!windowServiceLive(host) || host.inTrackingStep || host.inKeyCallback) return NO; CFStringRef mode=CFRunLoopCopyCurrentMode(CFRunLoopGetMain()); BOOL tracking=mode && CFEqual(mode,(__bridge CFStringRef)NSEventTrackingRunLoopMode); if (mode) CFRelease(mode); return !tracking;}static NSPasteboard *windowServicePasteboard(SUIHost *host){#ifdef SUI_WINDOW_SERVICES_TEST /* The native fixture must supply a private named pasteboard. */ return host.servicePasteboard;#else (void)host; return NSPasteboard.generalPasteboard;#endif}static Value nativeWindowClipboardRead(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); if (!windowServiceClipboardAllowed(host)) return SIGIL_FALSE; @try { NSString *text=[windowServicePasteboard(host) stringForType:NSPasteboardTypeString]; if (!text || [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding]>4u*1024*1024) return SIGIL_FALSE; NSData *bytes=[text dataUsingEncoding:NSUTF8StringEncoding]; if (!bytes || bytes.length>4u*1024*1024) return SIGIL_FALSE; return sigil_make_string(vm,bytes.length ? bytes.bytes : "",bytes.length); } @catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }}static Value nativeWindowClipboardSet(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); if (!sigil_is_string(args[1])) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-clipboard-set!: expected a string"); return SIGIL_UNDEFINED; } if (!windowServiceClipboardAllowed(host) || ((SigilString *)sigil_as_ptr(args[1]))->byte_length>4u*1024*1024) return SIGIL_FALSE; NSString *text=windowServiceString(vm,args[1],"window-clipboard-set!"); if (!text) return SIGIL_FALSE; @try { NSPasteboard *pasteboard=windowServicePasteboard(host); if (!pasteboard) return SIGIL_FALSE; NSPasteboardItem *item=[NSPasteboardItem new]; if (![item setString:text forType:NSPasteboardTypeString]) return SIGIL_FALSE; [pasteboard clearContents]; return sigil_bool([pasteboard writeObjects:@[item]]); } @catch (NSException *failure) { (void)failure; return SIGIL_FALSE; }}static Value nativeWindowFullscreenState(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); return sigil_bool(windowServiceLive(host) && host.fullscreenAcknowledged);}static Value nativeWindowFullscreenStatus(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); if (!windowServiceLive(host)) return sigil_fixnum(SUI_FULLSCREEN_REFUSED); windowServiceTick(host); return sigil_fixnum(host->fullscreenRequest.status);}static Value nativeWindowFullscreen(SigilVM *vm, int argc, Value *args){ (void)argc; SUIHost *host=windowServiceHandle(vm,args[0]); if (!sigil_is_bool(args[1])) { sigil__vm_error(vm,SIGIL_ERR_TYPE,"window-set-fullscreen!: expected a boolean"); return SIGIL_UNDEFINED; } if (!host) return SIGIL_FALSE; host.fullscreenGeneration++; sui_fullscreen_request(&host->fullscreenRequest,sigil_as_bool(args[1]),windowServiceNow()); if (!windowServiceLive(host) || !(host.window.styleMask & NSWindowStyleMaskResizable)) { sui_fullscreen_refuse(&host->fullscreenRequest); if (windowServiceLive(host)) windowServiceWake(host); return SIGIL_FALSE; } windowServiceWake(host); windowServiceArmTimer(host); if (host->fullscreenRequest.status!=SUI_FULLSCREEN_PENDING) return SIGIL_FALSE; windowServiceQueueFullscreen(host); return SIGIL_TRUE;}static void registerWindowAppkitServices(SigilVM *vm){ if (!sigil_begin_module(vm,"(sigil ui window appkit services)")) return;#define SERVICE(name,fn,n) sigil_module_register_native(vm,name,fn,SIGIL_ARITY_EXACT(n),name); sigil_module_export(vm,name) SERVICE("%window-title!",nativeWindowTitle,2); SERVICE("%window-clipboard-read",nativeWindowClipboardRead,1); SERVICE("%window-clipboard-set!",nativeWindowClipboardSet,2); SERVICE("%window-fullscreen?",nativeWindowFullscreenState,1); SERVICE("%window-fullscreen!",nativeWindowFullscreen,2); SERVICE("%window-fullscreen-status",nativeWindowFullscreenStatus,1);#undef SERVICE sigil_end_module(vm);}package.sglmodified
(define ui-flags '("-std=c99" "-Wall" "-Wextra" "-Wno-unused-parameter" "-D_GNU_SOURCE"))(define (compile-ui ctx) (let ((compiled ((compile-c-sources sources: (append ui-common-sources (case (target-os ctx) ((darwin) '("native/surface-unavailable.c")) ((windows) '("native/surface-unavailable.c")) ((linux) '("native/surface.c" "native/wayland.c")) (else (error "sigil-ui supports Linux, macOS and Windows targets")))) include-dirs: '("native/wayland" "native/wayland/include") flags: (with-sigil-c-flags ui-flags)) ctx))) (if (eq? (target-os ctx) 'darwin) ((compile-c-sources sources: '("native/appkit.m") flags: (with-sigil-c-flags (append ui-flags '("-fobjc-arc")))) compiled) compiled))) ((compile-c-sources sources: (append ui-common-sources (case (target-os ctx) ((darwin windows) '("native/surface-unavailable.c")) ((linux) '("native/surface.c" "native/wayland.c")) (else (error "sigil-ui supports Linux, macOS and Windows targets")))) include-dirs: '("native/wayland" "native/wayland/include") flags: (with-sigil-c-flags ui-flags)) ctx))(define (compile-ui-modules ctx) ((compile-sigil-modules sources: "src/**/*.sgl" exclude: (if (eq? (target-os ctx) 'windows) '() (list (path-join (context-package-dir ctx) "src/sigil/ui/win32.sgl"))) exclude: (map (lambda (file) (path-join (context-package-dir ctx) file)) (append (if (eq? (target-os ctx) 'windows) '() '("src/sigil/ui/win32.sgl")) (if (eq? (target-os ctx) 'darwin) '() '("src/sigil/ui/appkit.sgl" "src/sigil/ui/appkit/wait.sgl")))) output-dir: (config-output-subdir "lib")) ctx))(package name: "sigil-ui" version: "0.2.5" sigil: "0.24.6" version: "0.2.6" sigil: "0.24.8" description: "Retained-mode UI framework with a software renderer" url: "https://git.usesigil.org/sigil/sigil-ui" license: "BSD-3-Clause" authors: (list "David Wilson <david@daviwil.com>") configs: (list (config name: 'darwin-arm64 toolchain: 'zig target: "aarch64-macos.15.0-none" features: '(cross darwin) output-dir: "build/darwin-arm64") (config name: 'darwin-amd64 toolchain: 'zig target: "x86_64-macos.15.0-none" features: '(cross darwin) output-dir: "build/darwin-amd64") (config name: 'windows-amd64 toolchain: 'zig target: "x86_64-windows-gnu" features: '(cross windows) output-dir: "build/windows-amd64") (config name: 'dev output-dir: "build/dev" dependencies: (append (cond-expand (windows (list (from-pkg name: "sigil/sigil-window" version: "^0.1.0"))) ((or windows darwin) (list (from-pkg name: "sigil/sigil-window" version: "^0.2.0"))) (else '())) (list (from-pkg name: "sigil/sigil-font" version: "^0.1.0") (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-font" version: "^0.1.0") (from-pkg name: "sigil/sigil-lib" version: "^0.24.6") (from-pkg name: "sigil/sigil-stdlib" version: "^0.24.6"))) ;; The test runner declares its package/build/store helpers transitively. dev-dependencies: (list (from-pkg name: "sigil/sigil-test-runner" version: "^0.24.6")) ;; Pixel loops and device access are native. Linux uses runtime-loaded ;; Wayland libraries and checked-in protocol code; Darwin uses AppKit. ;; Wayland libraries and checked-in protocol code. AppKit host ownership ;; and native child services are supplied by sigil-window. libraries: (list (library name: 'sigil-ui c-sources: ui-common-sources c-include-dirs: '("native" "native/wayland" "native/wayland/include") native-init: "sigil__init_sigil_ui_native" link-flags: (lambda (ctx) (if (eq? (target-os ctx) 'darwin) '("-framework" "AppKit" "-framework" "QuartzCore") '())))) link-flags: '())) tasks: (list (taskscripts/build-macos-demo.sglmodified
#!/usr/bin/env sigil;;; Build with an installed Sigil executable passed as argument one.;;; All build/dependency/cache state stays beneath this checkout.;;; Cross-build the development demo on Linux; never uses an Apple SDK.(import (sigil shell prelude))(requires (tools clang cp))(requires (tools cp))(define root (realpath (path (script-dir) "..")))(define runtime (realpath (arg 1)))(define action (arg 2 default: "build"))(define build (path root "build" "macos"))(each directory '("tmp" "state" "cache" "data" "sigil" "store") (ensure-directory (path build directory)))(setenv! "TMPDIR" (str (path build "tmp") "/"))(setenv! "CFFIXED_USER_HOME" (path build "state"))(define zig (realpath (arg 3 default: (path (getenv "HOME") ".sigil/toolchain/zig/zig"))))(unless (equal? (out ,zig version) "0.16.0") (error "Expected Zig 0.16.0"))(define build (path root "build/macos"))(each name '("tmp" "state" "cache" "store") (ensure-directory (path build name)))(setenv! "TMPDIR" (path build "tmp"))(setenv! "XDG_CACHE_HOME" (path build "cache"))(setenv! "XDG_DATA_HOME" (path build "data"))(setenv! "SIGIL_HOME" (path build "sigil"))(setenv! "SIGIL_STORE" (path build "store"))(setenv! "SIGIL_TOOLCHAIN_CACHE_DIR" (path build "cache" "toolchains"))(setenv! "SIGIL_JOBS" "2")(setenv! "PATH" (str (dirname runtime) ":" (getenv "PATH")))(define (sigil-includes) (let ((headers (glob (path build "sigil" "deps" "*sigil-lib*" "include/sigil/sigil.h")))) (when (null? headers) (error "Build the package before native checks")) (dirname (dirname (car headers)))))(define (run-step name argv directory) (println "Starting ~a" name) (flush-output-port (current-output-port)) (let* ((log (path build (str name ".log"))) (result ($? ,@argv cwd: ,directory out: ,log err: 'merge timeout: 600))) (write-text (path build (str name ".result")) (format-outcome result)) (unless (ok? result) (let* ((text (read-text log)) (size (string-length text))) (println "~a" (substring text (max 0 (- size 6000)) size))) (error "Build step failed; see log" name log))))(cond ((string=? action "services-check") (let ((binary (path build "services-check"))) ($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter ,(str "-I" (sigil-includes)) ,(path root "test/appkit/services.m") ,(path root "demo/build/dev/native/libsigil.a") ,(path root "demo/build/dev/native/allocator-stock.o") -framework AppKit -framework QuartzCore -o ,binary timeout: 60) (run-step "services-check" (list binary) root) (run-step "services-state" (list runtime (path root "scripts/test-window-services.sgl")) build))) ((string=? action "embedding-check") (let ((includes (sigil-includes))) (define (compile-embedding source binary) ($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter ,(str "-I" includes) ,source ,(path root "demo/build/dev/native/libsigil.a") ,(path root "demo/build/dev/native/allocator-stock.o") -framework AppKit -framework QuartzCore -o ,binary timeout: 60)) (define (reject-embedding name file old replacement expected) (let* ((directory (path build name)) (source (read-text (path root "native" file))) (binary (path directory "check"))) (unless (= (string-count source old) 1) (error "Embedding mutation anchor changed" name)) (ensure-directory (path directory "native")) (ensure-directory (path directory "test/appkit")) (each native-file '("appkit.m" "appkit-host.h" "appkit-host.inc" "window-services.h" "window-appkit-services.inc") (write-text (path directory "native" native-file) (read-text (path root "native" native-file)))) (write-text (path directory "native" file) (string-replace source old replacement)) (write-text (path directory "test/appkit/embedding.m") (read-text (path root "test/appkit/embedding.m"))) (compile-embedding (path directory "test/appkit/embedding.m") binary) (let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15))) (unless (and (not (ok? result)) (contains? (stdout-of result) expected)) (error "Embedding mutant was not rejected" name (format-outcome result))) (println "PASS: rejected ~a" name)))) (compile-embedding (path root "test/appkit/embedding.m") (path build "embedding-check")) (run-step "embedding-check" (list (path build "embedding-check")) root) (reject-embedding "opaque-hit-test" "appkit.m" "((const uint8_t *)self.alpha.bytes)[y*self.pixelWidth+x]==0" "NO" "hitContent(host,NSMakePoint(10,10))==view") (reject-embedding "duplicate-native-forward" "appkit.m" "[self forwardNativeEvent:event];" "[self forwardNativeEvent:event]; [self forwardNativeEvent:event];" "fixture.presses==2 && view.downs==2 && view.ups==1") (reject-embedding "leaked-canceled-release" "appkit-host.inc" "[host.canceledKeys addObject:code];" "/* Missing in-flight cancellation. */" "host.events.count==0"))) ((string=? action "tracking-check") (let ((includes (sigil-includes))) (define (compile-tracking source binary) ($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter ,(str "-I" includes) ,source ,(path root "demo/build/dev/native/libsigil.a") ,(path root "demo/build/dev/native/allocator-stock.o") -framework AppKit -framework QuartzCore -o ,binary timeout: 60)) (compile-tracking (path root "test/appkit/tracking.m") (path build "tracking-check")) (run-step "tracking-check" (list (path build "tracking-check")) root) (let* ((directory (path build "default-mode-tracking")) (source (read-text (path root "native/appkit.m"))) (anchor "CFRunLoopAddSource(CFRunLoopGetMain(),host.trackingSource,kCFRunLoopCommonModes);") (binary (path directory "check"))) (unless (= (string-count source anchor) 1) (error "Tracking mutation anchor changed")) (ensure-directory (path directory "native")) (ensure-directory (path directory "test/appkit")) (each file '("appkit-host.h" "appkit-host.inc" "window-services.h" "window-appkit-services.inc") (write-text (path directory "native" file) (read-text (path root "native" file)))) (write-text (path directory "native/appkit.m") (string-replace source anchor "CFRunLoopAddSource(CFRunLoopGetMain(),host.trackingSource,kCFRunLoopDefaultMode);")) (write-text (path directory "test/appkit/tracking.m") (read-text (path root "test/appkit/tracking.m"))) (compile-tracking (path directory "test/appkit/tracking.m") binary) (let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15))) (unless (and (not (ok? result)) (contains? (stdout-of result) "FAIL: real tracking mode ticks=4 processed=0 presents=0 draws=0")) (error "Default-mode-only tracking control was not rejected" (format-outcome result))) (println "PASS: rejected default-mode-only tracking source"))))) ((string=? action "tests") (run-step "tests" (list runtime "test" "test/test-raster.sgl" "test/test-tree.sgl" "test/test-appkit-wait.sgl" "test/test-viewport.sgl" "test/test-chooser.sgl") root)) ((string=? action "resize-check") (let ((includes (sigil-includes)) (native (path root "demo/build/dev/native"))) (define (compile-fixture source binary) ($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter ,(str "-I" includes) ,source ,(path native "libsigil.a") ,(path native "allocator-stock.o") -framework AppKit -framework QuartzCore -o ,binary timeout: 60)) (define (reject-mutant name old replacement expected) (let* ((directory (path build name)) (source (read-text (path root "native/appkit.m"))) (binary (path directory "check"))) (unless (= (string-count source old) 1) (error "Mutation anchor changed" name)) (ensure-directory (path directory "native")) (ensure-directory (path directory "test/appkit")) (each file '("appkit-host.h" "appkit-host.inc" "window-services.h" "window-appkit-services.inc") (write-text (path directory "native" file) (read-text (path root "native" file)))) (write-text (path directory "native/appkit.m") (string-replace source old replacement)) (write-text (path directory "test/appkit/resize.m") (read-text (path root "test/appkit/resize.m"))) (compile-fixture (path directory "test/appkit/resize.m") binary) (let ((result ($? ,binary out: ,(path directory "log") err: 'merge timeout: 15))) (unless (and (not (ok? result)) (contains? (stdout-of result) expected)) (error "Expected resize control did not reject mutant" name (format-outcome result))) (println "PASS: rejected ~a" name)))) (compile-fixture (path root "test/appkit/resize.m") (path build "resize-check")) (run-step "resize-check" (list (path build "resize-check")) root) (reject-mutant "old-resize-band" "static const double resizeOutsideBand=16;" "static const double resizeOutsideBand=5;" "FAIL: outside-edge drag cannot present intermediate frames") (reject-mutant "missing-resize-present" " SUIView *view=host.view;" " return SIGIL_TRUE;\n SUIView *view=host.view;" "FAIL: resized frame not drawn before mouse-up"))) ((string=? action "native-check") ($ clang -fobjc-arc -std=c99 -Wall -Wextra -Werror -Wno-unused-parameter -fsyntax-only ,(str "-I" (sigil-includes)) ,(path root "native" "appkit.m") timeout: 60)) ((string=? action "build") (run-step "package-deps" (list runtime "deps" "install") root) (run-step "package-build" (list runtime "build") root) (write-text (path root "demo" "dev-redirects.sgl") "(redirects packages: (list (for-package name: \"sigil/sigil-ui\" use: (from-path dir: \"..\"))))\n") (setenv! "SIGIL_REDIRECTS" (path root "demo" "dev-redirects.sgl")) (run-step "demo-deps" (list runtime "deps" "install") (path root "demo")) (run-step "demo-build" (list runtime "build") (path root "demo"))) ((string=? action "bundle") (let* ((contents (path build "Sigil UI Demo.app" "Contents")) (resources (path contents "Resources"))) (ensure-directory (path contents "MacOS")) (ensure-directory resources) ($ clang -fobjc-arc -Wall -Wextra -Werror -framework Foundation ,(path root "demo/macos/launcher.m") -o ,(path contents "MacOS/sigil-ui-launcher") timeout: 60) ($ cp ,(path root "demo/macos/Info.plist") ,(path contents "Info.plist")) ($ cp ,(path root "demo/build/dev/bin/sigil-ui-demo") ,(path resources "sigil-ui-demo.next")) (rename-file (path resources "sigil-ui-demo.next") (path resources "sigil-ui-demo")) ($ cp -R ,(path root "demo/assets") ,resources))) (else (error "Unknown build action" action))) ((equal? action "build") (define redirects (path build "redirects.sgl")) (write-text redirects (format "(redirects packages: (list (for-package name: ~s use: (from-path dir: ~s))))\n" "sigil/sigil-ui" root)) ($ ,runtime deps install --redirects ,redirects cwd: ,(path root "demo")) ($ ,runtime build -c darwin-arm64 --redirects ,redirects cwd: ,(path root "demo"))) ((equal? action "bundle") (define binary (path root "demo/build/darwin-arm64/bin/sigil-ui-demo")) (unless (file? binary) (error "Cross-build the demo before bundling" binary)) (define contents (path build "Sigil UI Demo.app/Contents")) (ensure-directory (path contents "MacOS")) (ensure-directory (path contents "Resources")) ($ ,zig cc -target aarch64-macos.15.0-none -std=c11 -D_DARWIN_C_SOURCE -Wall -Wextra -Werror -O1 ,(path root "demo/macos/launcher.c") -o ,(path contents "MacOS/sigil-ui-launcher")) ($ cp ,(path root "demo/macos/Info.plist") ,(path contents "Info.plist")) ($ cp ,binary ,(path contents "Resources/sigil-ui-demo")) ($ cp -R ,(path root "demo/assets") ,(path contents "Resources"))) (else (error "Expected build or bundle; host checks belong to sigil-window" action)))(println "PASS: ~a" action)scripts/check-platform-selection.sgladded
#!/usr/bin/env sigil;;; Inspect the actual manifest under the compiling CLI's target features.(import (sigil shell prelude) (sigil package) (sigil build))(define root (realpath (path (script-dir) "..")))(define expected (arg 1))(define pkg (load-package (path root "package.sgl")))(define window? (let loop ((dependencies (package-dependencies pkg))) (and (pair? dependencies) (or (and (from-pkg? (car dependencies)) (equal? (from-pkg-name (car dependencies)) "sigil/sigil-window")) (loop (cdr dependencies))))))(unless (eq? window? (not (equal? expected "linux"))) (error "Manifest selected the wrong host dependency" expected window?))(println "PASS: manifest target ~a selects sigil-window=~a" expected window?)sigil.lockdeleted
;; Auto-generated by sigil deps install. Do not edit.(lock (package name: "sigil/sigil-font" source: pkg integrity: "sha256:a835f3549c71cfa74bf81686597b952471d2ff631b40b04376eedfff2438a104" version: "0.1.1" 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"))) (package name: "sigil/sigil-lib" source: pkg integrity: "sha256:af2baf1b8a1ddb310028bb1bbc8d259aaa05a4734111c635ff43367418d9d71a" version: "0.24.6" dependencies: ()) (package name: "sigil/sigil-stdlib" source: pkg integrity: "sha256:092727ba77898c1be23d1be541bf98c401db53c23f00f857a3fcf596ac174f99" version: "0.24.6" dependencies: ()) (package name: "sigil/sigil-shell" source: pkg integrity: "sha256:7f056c1599670bf7787197491859b7eebc20e009e290a7472acbea2ee05ef090" version: "0.24.8" dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8") (from-pkg name: "sigil/sigil-json" version: "^0.16.0"))) (package name: "sigil/sigil-test" source: pkg integrity: "sha256:29ef6ce2849f6fe9b5862dd70dc327f8d4cd0c6266173348be4a45b2d5888b76" version: "0.24.8" dependencies: ()) (package name: "sigil/sigil-test-runner" source: pkg integrity: "sha256:d3c5ed29ae1b09c7a2504a3c3cc86da1d454d48ae9a4fdf9eda4e5a14d984337" version: "0.24.8" 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"))) (package name: "sigil/sigil-ffi" source: pkg integrity: "sha256:b4cb94a02de29983912211db42e8414767fa82d2ba70f70a50c41f428af2b18e" version: "0.16.6" dependencies: ()) (package name: "sigil/sigil-freetype" source: pkg integrity: "sha256:ca82f1260607ce7f275f0d2bb0b379e685263e993e166fcdc0f988db6dd5846e" version: "0.9.1" 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"))) (package name: "sigil/sigil-fontconfig" source: pkg integrity: "sha256:38580792ec6dc221a1c23079ad0836a86c44d6d043d9e3694039a3ceaf0c5598" version: "0.9.1" 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"))) (package name: "sigil/sigil-json" source: pkg integrity: "sha256:5e04c7409a0009bfd0d2be31b2ecb5c61b1536aca92b03fb17044213deb52692" version: "0.16.2" dependencies: ()) (package name: "sigil/sigil-package" source: pkg integrity: "sha256:a130682282c0f76592f221da30a6a141b6c95c8e893e910fa6cd8d56aca6ab1d" version: "0.24.8" dependencies: ()) (package name: "sigil/sigil-build" source: pkg integrity: "sha256:e31d26f7f87ca7894bb250bfe0cebf0af8aaa4f63b73b9c0363a17b7a16268f3" version: "0.24.8" 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"))) (package name: "sigil/sigil-crypto" source: pkg integrity: "sha256:fc2620e9ce36aa121173628a059a3a4fd1be57f4d18286628590f8e3c549ef56" version: "0.19.2" dependencies: ((from-pkg name: "sigil/sigil-lib" version: ">=0.24"))) (package name: "sigil/sigil-store" source: pkg integrity: "sha256:28d54b079bbde8c6551a6e3fa3cece41cb66dc4c4112aeaf222872a4ae389e86" version: "0.24.8" 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"))) (package name: "sigil/sigil-deps" source: pkg integrity: "sha256:f195c87dd085eff6702ed1613024272bd992644b6962ba33dd05da5d453a9c98" version: "0.24.8" 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"))) (package name: "sigil/sigil-sqlite" source: pkg integrity: "sha256:ae319b42069c3e00408f03923b0eacbef58369b2e6e76dfb24b0b833d39ff618" version: "0.16.4" dependencies: ()) (package name: "sigil/sigil-git" source: pkg integrity: "sha256:0b3251700a28e3d8ed823e0d15ee23d90e933fb940e224d1e3cde8f973d3f639" version: "0.24.8" dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.8"))))src/sigil/ui/appkit.sglmodified
;;; AppKit implementation of the platform window contract. Input is queued;;;; a scoped tracking source can drive a synchronous state/render step.;;; AppKit drawing adapter. Native ownership lives in sigil-window.(define-library (sigil ui appkit) (import (sigil struct) (sigil ui raster) (sigil ui tree) (sigil ui mask) (sigil ui appkit wait) (sigil ui window appkit services)) (import (rename (sigil window appkit) (open-window open-appkit-window) (window? appkit-window?) (window-role appkit-window-role) (window-width appkit-window-width) (window-height appkit-window-height) (window-scale appkit-window-scale) (window-device-width host-device-width) (window-device-height host-device-height) (window-focused? appkit-window-focused?) (window-closed? appkit-window-closed?) (window-dispatch appkit-dispatch) (window-close! appkit-close!) (window-run! host-run!) (window-host-token appkit-host-token) (window-set-title! appkit-set-title!) (window-clipboard-read appkit-clipboard-read) (window-clipboard-set! appkit-clipboard-set!) (window-fullscreen? appkit-fullscreen?) (window-set-fullscreen! appkit-set-fullscreen!) (window-fullscreen-status appkit-fullscreen-status)) (sigil ui raster) (sigil ui tree) (sigil ui mask) (sigil ui display) (sigil ui theme)) (export open-appkit-window appkit-window? appkit-window-role appkit-window-width appkit-window-height appkit-window-scale appkit-window-device-width appkit-window-device-height appkit-set-title! appkit-clipboard-read appkit-clipboard-set! appkit-fullscreen? appkit-set-fullscreen! appkit-fullscreen-status) (begin (define-native (%mac-open title width height min-width min-height) (: any? any? any? any? any? -> any?)) (define-native (%mac-dispatch handle timeout reads writes) (: any? any? any? any? -> any?)) (define-native (%mac-next! handle event) (: any? any? -> any?)) (define-native (%mac-text handle) (: any? -> any?)) (define-native (%mac-name handle) (: any? -> any?)) (define-native (%mac-info! handle info) (: any? any? -> any?)) (define-native (%mac-present! handle pixels width rects) (: any? any? any? any? -> any?)) (define-native (%mac-present-overlay! handle pixels width rects alpha) (: any? any? any? any? any? -> any?)) (define-native (%mac-host-token handle) (: any? -> any?)) (define-native (%mac-close! handle) (: any? -> any?)) (define-native (%mac-tracking-handler! handle step) (: any? any? -> any?)) (define-struct appkit-window (handle) (event) (info)) (define (open-appkit-window (keys: (role 'toplevel) (title "sigil-ui") (app-id "sigil-ui") (width 640) (height 480) (min-width 240) (min-height 160) (output #f) (display #f))) (unless (and (eq? role 'toplevel) (not output) (not display)) (error "AppKit supports toplevel windows without output/display selection")) (appkit-window handle: (%mac-open title width height min-width min-height) event: (make-vector 8 0) info: (make-vector 5 0))) (define (info s index) (%mac-info! (appkit-window-handle s) (appkit-window-info s)) (vector-ref (appkit-window-info s) index)) (define (appkit-window-role s) 'toplevel) (define (appkit-host-token s) (%mac-host-token (appkit-window-handle s))) (define (appkit-present-overlay! s canvas alpha) (unless (and (= (mask-width alpha) (canvas-width canvas)) (define current-presentation (make-parameter #f)) ;; Keep legacy canvas extents; exact host metrics live in (sigil window). (define (appkit-window-device-width window) (window-raster-width window)) (define (appkit-window-device-height window) (window-raster-height window)) (define (validate-damage canvas rectangles) (for-each (lambda (rectangle) (unless (and (list? rectangle) (= (length rectangle) 4) (let loop ((values rectangle)) (or (null? values) (and (exact-integer? (car values)) (>= (car values) 0) (loop (cdr values))))) (<= (+ (car rectangle) (list-ref rectangle 2)) (canvas-width canvas)) (<= (+ (cadr rectangle) (list-ref rectangle 3)) (canvas-height canvas))) (error "appkit-present!: invalid device damage rectangle" rectangle))) rectangles)) (define (present-canvas window canvas rectangles generation) (validate-damage canvas rectangles) (if (null? rectangles) #t (window-present-pixels! window (canvas-pixels canvas) (canvas-width canvas) (canvas-height canvas) generation))) (define (appkit-present! window canvas . rectangles) (present-canvas window canvas (if (pair? rectangles) (car rectangles) (list (list 0 0 (canvas-width canvas) (canvas-height canvas)))) (window-generation window))) (define (appkit-present-ui! window ui damage) (let ((context (ui-presentation-context ui)) (presentation (current-presentation))) (unless context (set! context (vector window (window-generation window))) (set-ui-presentation-context! ui context)) (and (eq? window (vector-ref context 0)) (= (window-generation window) (vector-ref context 1)) (let ((accepted (present-canvas window (ui-canvas ui) (map (lambda (rectangle) (map (lambda (value) (* value (ui-scale ui))) rectangle)) damage) (vector-ref context 1)))) (when (and accepted presentation (eq? window (vector-ref presentation 0))) (vector-set! presentation 1 ui)) accepted)))) (define (appkit-make-ui window theme background) (let ((ui (make-ui theme (make-canvas (window-raster-width window) (window-raster-height window)) (appkit-window-scale window) background))) (set-ui-presentation-context! ui (vector window (window-generation window))) ui)) (define (appkit-present-overlay! window canvas alpha) (unless (and (mask? alpha) (= (mask-width alpha) (canvas-width canvas)) (= (mask-height alpha) (canvas-height canvas))) (error "appkit-present-overlay!: mask must match canvas device size")) (%mac-present-overlay! (appkit-window-handle s) (canvas-pixels canvas) (canvas-width canvas) (list (list 0 0 (canvas-width canvas) (canvas-height canvas))) (mask-alpha alpha))) (define (appkit-window-width s) (info s 0)) (define (appkit-window-height s) (info s 1)) (define (appkit-window-scale s) (info s 2)) (define (appkit-window-device-width s) (* (info s 0) (info s 2))) (define (appkit-window-device-height s) (* (info s 1) (info s 2))) (define (appkit-window-focused? s) (= 1 (info s 3))) (define (appkit-window-closed? s) (= 1 (info s 4))) (define (appkit-set-title! s title) (%window-title! (appkit-window-handle s) title)) (define (appkit-clipboard-read s) (%window-clipboard-read (appkit-window-handle s))) (define (appkit-clipboard-set! s text) (%window-clipboard-set! (appkit-window-handle s) text)) (define (appkit-fullscreen? s) (%window-fullscreen? (appkit-window-handle s))) (define (appkit-set-fullscreen! s enabled?) (%window-fullscreen! (appkit-window-handle s) enabled?)) (define (appkit-fullscreen-status s) (fullscreen-status-symbol (%window-fullscreen-status (appkit-window-handle s)))) (define (modifiers bits) (let loop ((names '(shift control alt super caps-lock num-lock)) (bit 1) (result '())) (if (null? names) (reverse result) (loop (cdr names) (* bit 2) (if (odd? (quotient bits bit)) (cons (car names) result) result))))) (define (decode s type v) (let ((h (appkit-window-handle s)) (a (vector-ref v 1)) (b (vector-ref v 2)) (c (vector-ref v 3)) (d (vector-ref v 4)) (e (vector-ref v 5)) (f (vector-ref v 6))) (case type ((1) (list 'resize a b c)) ((2) (list 'close)) ((3) (list 'frame a)) ((4) (list 'key (case a ((0) 'release) ((1) 'press) (else 'repeat)) (%mac-name h) (%mac-text h) (modifiers c) d)) ((5) (list 'keyboard-focus (= a 1))) ((6) (list 'pointer-enter a b)) ((7) (list 'pointer-leave)) ((8) (list 'pointer-motion a b)) ((9) (list 'pointer-button (if (= b 1) 'press 'release) (case a ((272) 'left) ((273) 'right) ((274) 'middle) ((275) 'side) ((276) 'extra) (else a)) c d)) ((10) (list 'scroll (/ a 256.0) (/ b 256.0) c d e f)) ((12) (list 'fullscreen (= a 1) (fullscreen-status-symbol b))) (else (error "unknown AppKit event" type))))) (define (appkit-dispatch s timeout-ms) (let* ((wait (appkit-wait-plan timeout-ms)) (h (appkit-window-handle s)) (v (appkit-window-event s))) (%mac-dispatch h (car wait) (cadr wait) (caddr wait)) (let loop ((result '())) (let ((type (%mac-next! h v))) (if (= type 0) (reverse result) (loop (cons (decode s type v) result))))))) (define (appkit-present! s canvas . rectangles) (%mac-present! (appkit-window-handle s) (canvas-pixels canvas) (canvas-width canvas) (if (pair? rectangles) (car rectangles) (list (list 0 0 (canvas-width canvas) (canvas-height canvas)))))) (define (appkit-present-ui! s ui damage) (appkit-present! s (ui-canvas ui) (map (lambda (r) (map (lambda (n) (* n (ui-scale ui))) r)) damage))) (define (appkit-make-ui s theme background) (make-ui theme (make-canvas (appkit-window-device-width s) (appkit-window-device-height s)) (appkit-window-scale s) background)) (define (appkit-close! s) (%mac-close! (appkit-window-handle s))) ;;; step is synchronous: update state and render; never suspend, block, ;;; capture a continuation or escape from a native tracking callback. (define (appkit-run! s step) (let ((failure #f)) (define (tracking-step) (guard (e (#t (set! failure e) #f)) (step (let ((h (appkit-window-handle s)) (v (appkit-window-event s))) (let loop ((events '())) (let ((type (%mac-next! h v))) (if (= type 0) (reverse events) (loop (cons (decode s type v) events))))))) #t)) (define (stop!) (%mac-tracking-handler! (appkit-window-handle s) #f)) ;; The explicit guard also removes registration when an async prompt ;; unwinds an exception before dynamic-wind's after thunk can run. (guard (e (#t (stop!) (raise e))) (dynamic-wind (lambda () (%mac-tracking-handler! (appkit-window-handle s) tracking-step)) (lambda () (step '()) (let loop () (when failure (raise failure)) (unless (appkit-window-closed? s) (let ((events (appkit-dispatch s #f))) (when failure (raise failure)) (step events)) (loop)))) stop!)))))) (error "appkit-present-overlay!: alpha must match canvas extent")) (window-present-overlay-pixels! window (canvas-pixels canvas) (canvas-width canvas) (canvas-height canvas) (window-generation window) (mask-alpha alpha))) (define (appkit-run! window step) (let ((presentation (vector window #f))) (define (paint) (let ((ui (vector-ref presentation 1))) (when ui (let* ((scale (appkit-window-scale window)) (width (appkit-window-width window)) (height (appkit-window-height window)) (generation (window-generation window)) (canvas (make-canvas (* width scale) (* height scale)))) ;; Paint realized items without event/state steps or components. (repaint-rects! canvas (ui-items ui) scale (theme-color (ui-theme ui) (ui-background ui)) (list (list 0 0 width height))) (window-present-pixels! window (canvas-pixels canvas) (canvas-width canvas) (canvas-height canvas) generation))))) (parameterize ((current-presentation presentation)) (host-run! window step paint))))))src/sigil/ui/appkit/wait.sglmodified
;;; Bridge the cooperative scheduler's current waits into an AppKit wait.;;; The GUI task stays runnable: CF callbacks never enter the VM. After each;;; native wake, the next dispatch yields through the normal I/O distributor.;;; Compatibility path; platform scheduling belongs to sigil-window.(define-library (sigil ui appkit wait) (import (sigil async) (sigil async scheduler) (sigil system) (sigil socket) (sigil signals) (sigil time) (sigil math)) (export appkit-wait-plan) (begin (define (appkit-wait-plan timeout-ms) (let ((sched (current-scheduler))) (if (not sched) (list (if timeout-ms timeout-ms -1) '() '()) (begin ;; A zero-deadline wait runs the existing scheduler distributor ;; before this task next blocks in AppKit, including ready I/O. (await-readable-fds '() timeout-ms: 0) (let ((deadline (and timeout-ms (>= timeout-ms 0) (+ (current-second) (/ timeout-ms 1000.0)))) (reads '()) (writes '())) (define (bound! time) (when (and time (or (not deadline) (< time deadline))) (set! deadline time))) (define (waiters! waiters socket?) (for-each (lambda (w) (let* ((direction (vector-ref w 1)) (items (if (eq? direction 'read-any) (vector-ref w 0) (list (vector-ref w 0))))) (when (> (vector-length w) 3) (bound! (vector-ref w 3))) (for-each (lambda (item) (let ((fd (if socket? (socket-fd item) item))) (when fd (if (eq? direction 'write) (set! writes (cons fd writes)) (set! reads (cons fd reads)))))) items))) waiters)) (let ((queue (%async-scheduler-run-queue sched)) (timers (%async-scheduler-timer-waiters sched)) (signal-fd (%signal-wake-fd))) (unless (and (null? (car queue)) (null? (cdr queue))) (bound! (current-second))) (when (pair? timers) (bound! (vector-ref (car timers) 0))) ;; Predicate-only external waiters have no notification fd. ;; Match the runtime's documented 100 ms fallback only here. (unless (null? (%async-scheduler-external-waiters sched)) (bound! (+ (current-second) 0.1))) (when signal-fd (set! reads (cons signal-fd reads)))) (waiters! (%async-scheduler-io-waiters sched) #t) (waiters! (%async-scheduler-fd-waiters sched) #f) (list (if deadline (min 2147483647 (max 0 (exact (ceiling (* 1000 (- deadline (current-second))))))) -1) reads writes)))))))) (import (sigil window appkit wait)) (export appkit-wait-plan))src/sigil/ui/window/appkit/services.sgldeleted
;;; Opaque native handles; this module moves with the host into sigil-window.(define-library (sigil ui window appkit services) (import (sigil ui window services)) (export %window-title! %window-clipboard-read %window-clipboard-set! %window-fullscreen? %window-fullscreen! %window-fullscreen-status fullscreen-status-symbol) (begin (define-native (%window-title! handle title) (: any? any? -> any?)) (define-native (%window-clipboard-read handle) (: any? -> any?)) (define-native (%window-clipboard-set! handle text) (: any? any? -> any?)) (define-native (%window-fullscreen? handle) (: any? -> any?)) (define-native (%window-fullscreen! handle enabled?) (: any? any? -> any?)) (define-native (%window-fullscreen-status handle) (: any? -> any?))))test/appkit-host-stub/sigil/window/appkit.sgladded
;;; Controlled host boundary for drawing adapter tests on any platform.(define-library (sigil window appkit) (export open-window window? window-role window-width window-height window-scale window-device-width window-device-height window-raster-width window-raster-height window-generation window-focused? window-closed? window-dispatch window-close! window-run! window-host-token window-set-title! window-clipboard-read window-clipboard-set! window-fullscreen? window-set-fullscreen! window-fullscreen-status window-present-pixels! window-present-overlay-pixels! test-generation! test-calls test-last) (begin (define calls 0) (define last #f) (define (test-calls) calls) (define (test-last) last) (define (open-window . arguments) (vector 1)) (define (window? window) (vector? window)) (define (window-role window) 'toplevel) (define (window-width window) 10) (define (window-height window) 8) (define (window-scale window) 2) (define (window-device-width window) 20) (define (window-device-height window) 16) (define (window-raster-width window) 20) (define (window-raster-height window) 16) (define (window-generation window) (vector-ref window 0)) (define (test-generation! window generation) (vector-set! window 0 generation)) (define (window-focused? window) #t) (define (window-closed? window) #f) (define (window-dispatch window timeout) '()) (define (window-close! window) #t) (define (window-run! window step paint) (step '()) (paint)) (define (window-host-token window) 42) (define (window-set-title! window title) #t) (define (window-clipboard-read window) "") (define (window-clipboard-set! window text) #t) (define (window-fullscreen? window) #f) (define (window-set-fullscreen! window enabled?) #t) (define (window-fullscreen-status window) 'idle) (define (record! window pixels width height generation alpha) (set! calls (+ calls 1)) (set! last (list pixels width height generation alpha)) (= generation (window-generation window))) (define (window-present-pixels! window pixels width height generation) (record! window pixels width height generation #f)) (define (window-present-overlay-pixels! window pixels width height generation alpha) (record! window pixels width height generation alpha))))test/appkit/embedding.mdeleted
/* Owned hidden native child; no WebKit, global input or external windows. */#include "../../native/appkit.m"#include <assert.h>/* NSApplication suppresses keys for a hidden, inactive app. Replace only its * final native forwarding sink with direct NSWindow dispatch. This qualifies * the host's routing and real responder delivery without console activation; * it does not claim end-to-end active NSApplication/menu delivery. */@interface FixtureApplication : SUIApplication@property int forwarded;@end@implementation FixtureApplication- (void)forwardNativeEvent:(NSEvent *)event { self.forwarded++; [event.window sendEvent:event];}@end@interface FixtureWindow : NSWindow@property CGFloat testScale;@end@implementation FixtureWindow- (CGFloat)backingScaleFactor { return self.testScale ?: [super backingScaleFactor]; }@end@interface FixtureChild : NSView@property int downs, ups, equivalents, clicks;@end@implementation FixtureChild- (BOOL)acceptsFirstResponder { return YES; }- (void)keyDown:(NSEvent *)event { (void)event; self.downs++; }- (void)keyUp:(NSEvent *)event { (void)event; self.ups++; }- (BOOL)performKeyEquivalent:(NSEvent *)event { (void)event; self.equivalents++; return NO; }- (void)mouseDown:(NSEvent *)event { (void)event; self.clicks++; }- (void)drawRect:(NSRect)rect { [[NSColor blueColor] setFill]; NSRectFill(rect); }@endtypedef struct { SUIHost * __unsafe_unretained host; FixtureChild * __unsafe_unretained view; int geometry, focus, deactivated, detached, closed, presses; BOOL consume, redirect, removeOnGeometry;} Fixture;static void notified(void *data, SUIHostToken host, SUIChildToken child, SUIHostEvent event, const SUIGeometry *geometry) { Fixture *fixture=data; assert(NSThread.isMainThread && sigil_ui_appkit_host_valid(host)); assert(geometry->scale>=1); if (event==SUI_HOST_GEOMETRY) { fixture->geometry++; if (fixture->removeOnGeometry) { fixture->removeOnGeometry=NO; assert(sigil_ui_appkit_child_remove(host,child)); } } if (event==SUI_HOST_FOCUS) fixture->focus++; if (event==SUI_HOST_DEACTIVATED) fixture->deactivated++; if (event==SUI_CHILD_WILL_DETACH || event==SUI_HOST_WILL_CLOSE) { assert(fixture->view.superview && fixture->host.window); assert(!sigil_ui_appkit_child_remove(host,child)); /* Reentrant removal. */ if (event==SUI_HOST_WILL_CLOSE) fixture->closed++; else fixture->detached++; }}static bool filter(void *data, SUIHostToken host, const SUIKey *key) { Fixture *fixture=data; fixture->presses++; assert(key->action==1 && key->name && key->text); assert(key->target && fixture->view.downs==0); /* Before native dispatch. */ if (fixture->redirect) sigil_ui_appkit_focus_ui(host); return fixture->consume;}static bool countFilter(void *data, SUIHostToken host, const SUIKey *key) { (void)host; (void)key; (*(int *)data)++; return false;}static NSEvent *key(SUIHost *host, NSEventType type, BOOL repeat, unsigned code, NSString *text) { return [NSEvent keyEventWithType:type location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:host.window.windowNumber context:nil characters:text charactersIgnoringModifiers:text isARepeat:repeat keyCode:code];}static void sendKey(SUIHost *host, NSEventType type, BOOL repeat, unsigned code, NSString *text) { [NSApp sendEvent:key(host,type,repeat,code,text)];}static NSBitmapImageRep *bitmap(int width, int height) { return [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*4 bitsPerPixel:32];}static NSView *hitContent(SUIHost *host, NSPoint logical) { /* hitTest: takes coordinates in the receiver's superview. The content * root is flipped, while AppKit's decorated parent is not. */ return [host.content hitTest:[host.content convertPoint:logical toView:host.content.superview]];}static void checkComposition(SUIHost *host, int width, int height) { NSBitmapImageRep *overlay=bitmap(width,height), *composite=bitmap(width,height); [NSGraphicsContext saveGraphicsState]; NSGraphicsContext.currentContext=[NSGraphicsContext graphicsContextWithBitmapImageRep:overlay]; CGContextScaleCTM(NSGraphicsContext.currentContext.CGContext,host.scale,host.scale); [host.view drawRect:host.view.bounds]; NSGraphicsContext.currentContext=[NSGraphicsContext graphicsContextWithBitmapImageRep:composite]; [[NSColor blueColor] setFill]; NSRectFill(NSMakeRect(0,0,width,height)); CGContextRef context=NSGraphicsContext.currentContext.CGContext; CGContextSetBlendMode(context,kCGBlendModeNormal); CGContextDrawImage(context,CGRectMake(0,0,width,height),overlay.CGImage); [NSGraphicsContext restoreGraphicsState]; NSColor *clear=[composite colorAtX:10*host.scale y:10*host.scale]; NSColor *opaque=[composite colorAtX:90*host.scale y:10*host.scale]; NSColor *partial=[composite colorAtX:50*host.scale y:10*host.scale]; assert(clear.blueComponent>0.95 && clear.redComponent<0.05); assert(opaque.redComponent>0.95 && opaque.blueComponent<0.05); assert(partial.redComponent>0.45 && partial.redComponent<0.55 && partial.blueComponent>0.45 && partial.blueComponent<0.55);}int main(void) { @autoreleasepool { [FixtureApplication sharedApplication]; [NSApp finishLaunching]; hosts=[NSHashTable weakObjectsHashTable]; SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new]; host.window=[[FixtureWindow alloc] initWithContentRect:NSMakeRect(100,100,120,100) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; host.window.releasedWhenClosed=NO; host.view=[[SUIView alloc] initWithFrame:host.window.contentView.bounds]; host.view.host=host; host.view.wantsLayer=YES; host.window.contentView=host.view; host.window.delegate=host; [hosts addObject:host]; [host geometry]; host.focused=YES; assert([host.window makeFirstResponder:host.view]); SUIHostToken token=hostToken(host); FixtureChild *view=[[FixtureChild alloc] initWithFrame:NSZeroRect]; Fixture fixture={.host=host,.view=view}; SUIChildToken child=sigil_ui_appkit_child_adopt(token,(__bridge void *)view, 0,0,120,100,0,notified,&fixture); assert(child && view.superview && fixture.geometry==1); assert(host.window.firstResponder==host.view); assert(!sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,NULL,NULL)); assert(sigil_ui_appkit_focus_child(token,child) && host.window.firstResponder==view); assert(fixture.focus==1); int olderCalls=0; SUIHookToken older=sigil_ui_appkit_key_filter_add(token,countFilter,&olderCalls); SUIHookToken hook=sigil_ui_appkit_key_filter_add(token,filter,&fixture); assert(hook && older); fixture.consume=YES; sendKey(host,NSEventTypeKeyDown,NO,11,@"b"); fixture.consume=NO; /* Disposition must remain consumed until release. */ sendKey(host,NSEventTypeKeyDown,YES,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b"); assert(fixture.presses==1 && view.downs==0 && view.ups==0 && view.equivalents==0); assert(olderCalls==0); sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); sendKey(host,NSEventTypeKeyDown,YES,0,@"a"); sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(fixture.presses==2 && view.downs==2 && view.ups==1); assert(((FixtureApplication *)NSApp).forwarded==3); assert(olderCalls==1 && sigil_ui_appkit_key_filter_remove(token,older)); view.downs=0; fixture.consume=YES; sendKey(host,NSEventTypeKeyDown,NO,11,@"b"); assert(sigil_ui_appkit_key_filter_remove(token,hook)); sendKey(host,NSEventTypeKeyDown,YES,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b"); assert(view.downs==0 && view.ups==1 && ((FixtureApplication *)NSApp).forwarded==3); sendKey(host,NSEventTypeKeyDown,NO,11,@"b"); sendKey(host,NSEventTypeKeyUp,NO,11,@"b"); assert(view.downs==1 && view.ups==2); assert(!sigil_ui_appkit_key_filter_remove(token,hook)); puts("PASS: pre-dispatch consume/pass and exactly-once repeat/release routing"); /* Screenshot/system shortcuts can emit FlagsChanged with key code 0. * Never ask that event for characters or release an owned A key. */ CGEventRef flags=CGEventCreateKeyboardEvent(NULL,0,false); assert(flags); CGEventSetType(flags,kCGEventFlagsChanged); NSEvent *unknownFlags=[NSEvent eventWithCGEvent:flags]; CFRelease(flags); assert(unknownFlags.type==NSEventTypeFlagsChanged && unknownFlags.keyCode==0); assert(sigil_ui_appkit_focus_ui(token)); [host.events removeAllObjects]; @try { assert(!routeKey(host,unknownFlags)); } @catch (NSException *failure) { fprintf(stderr,"REPRO unknown FlagsChanged: %s\n",failure.reason.UTF8String); return 42; } sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); SUIKeyOwner *uiOwner=host.keyOwners[@0]; assert(uiOwner); assert(!routeKey(host,unknownFlags)); assert(host.keyOwners[@0]==uiOwner && host.events.count==1); sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(host.events.count==2 && !host.keyOwners[@0]); assert(sigil_ui_appkit_focus_child(token,child)); sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); SUIKeyOwner *nativeOwner=host.keyOwners[@0]; assert(nativeOwner); assert(routeKey(host,unknownFlags)); assert(host.keyOwners[@0]==nativeOwner); sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(!host.keyOwners[@0]); [host.events removeAllObjects]; puts("PASS: unknown modifier synchronization preserves UI/native key ownership"); view.downs=view.ups=0; fixture.redirect=YES; fixture.consume=NO; hook=sigil_ui_appkit_key_filter_add(token,filter,&fixture); sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); assert(view.downs==0 && host.window.firstResponder==host.view); [host.events removeAllObjects]; sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(host.events.count==0); assert(sigil_ui_appkit_key_filter_remove(token,hook)); [host.events removeAllObjects]; sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(host.events.count==2 && host.events[0].type==4 && host.events[1].type==4); assert(sigil_ui_appkit_focus_child(token,child)); sendKey(host,NSEventTypeKeyDown,NO,0,@"a"); [host windowDidResignKey:[NSNotification notificationWithName:NSWindowDidResignKeyNotification object:host.window]]; sendKey(host,NSEventTypeKeyUp,NO,0,@"a"); assert(view.ups==0 && fixture.deactivated==1); [host windowDidBecomeKey:[NSNotification notificationWithName:NSWindowDidBecomeKeyNotification object:host.window]]; assert(fixture.focus>=3); puts("PASS: reentrant focus change cancels ownership and deactivation suppresses stale release"); SigilVM *vm=sigil_vm_create(); sigil__register_sigil_ui_appkit(vm); Value handle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)host, finalizeHost,traceHost,sizeof(void *)); Value capability=nativeHostToken(vm,1,&handle); assert(sigil_is_fixnum(capability) && (uint64_t)sigil_as_fixnum(capability)==token); int width=host.width*host.scale, height=host.height*host.scale; Value pixels=sigil_make_bytevector(vm,width*height*4), alpha=sigil_make_bytevector(vm,width*height); uint8_t *rgb=sigil_bytevector_data(pixels), *mask=sigil_bytevector_data(alpha); for (int y=0;y<height;y++) for (int x=0;x<width;x++) { int i=y*width+x; rgb[i*4]=0; rgb[i*4+1]=0; rgb[i*4+2]=255; rgb[i*4+3]=0; mask[i]=x<width/3 ? 0 : x<width*2/3 ? 128 : 255; } Value present[]={handle,pixels,sigil_fixnum(width),SIGIL_EMPTY,alpha}; assert(nativePresentOverlay(vm,5,present)==SIGIL_TRUE); assert(hitContent(host,NSMakePoint(10,10))==view); assert(hitContent(host,NSMakePoint(90,10))==host.view); assert(hitContent(host,NSMakePoint(50,10))==host.view); assert(host.content.subviews.lastObject==host.view); checkComposition(host,width,height); assert(((uint8_t *)host.view.pixels.bytes)[2]==0); int opaque=(10*host.scale*width+90*host.scale)*4; assert(((uint8_t *)host.view.pixels.bytes)[opaque+2]==255 && ((uint8_t *)host.view.pixels.bytes)[opaque+3]==255); assert(rgb[(10*host.scale*width+50*host.scale)*4+2]==255); /* Canvas unchanged. */ assert(nativePresent(vm,4,present)==SIGIL_TRUE && host.view.alpha==nil); assert(hitContent(host,NSMakePoint(10,10))==host.view); assert(nativePresentOverlay(vm,5,present)==SIGIL_TRUE); FixtureChild *sibling=[[FixtureChild alloc] initWithFrame:NSZeroRect]; SUIChildToken other=sigil_ui_appkit_child_adopt(token,(__bridge void *)sibling,0,0,120,100,1,NULL,NULL); assert(other && hitContent(host,NSMakePoint(10,10))==sibling); assert(sigil_ui_appkit_child_place(token,other,0,0,120,100,-1)); assert(hitContent(host,NSMakePoint(10,10))==view); assert(sigil_ui_appkit_child_remove(token,other)); NSEvent *click=[NSEvent mouseEventWithType:NSEventTypeLeftMouseDown location:NSMakePoint(10,90) modifierFlags:0 timestamp:0 windowNumber:host.window.windowNumber context:nil eventNumber:1 clickCount:1 pressure:1]; [hitContent(host,NSMakePoint(10,10)) mouseDown:click]; assert(view.clicks==1); assert(sigil_ui_appkit_child_place(token,child,10,20,60,40,0)); assert(NSEqualRects(view.superview.frame,NSMakeRect(10,20,60,40))); assert(!sigil_ui_appkit_child_place(token,child,10,20,-1,40,0)); assert(NSEqualRects(view.superview.frame,NSMakeRect(10,20,60,40))); assert(sigil_ui_appkit_child_place(token,child,-10,20,60,40,0)); assert(hitContent(host,NSMakePoint(-1,30))==nil); assert(hitContent(host,NSMakePoint(1,30))==view); int previous=fixture.geometry; [host.window setContentSize:NSMakeSize(140,110)]; assert(fixture.geometry>previous && host.width==140 && host.height==110); previous=fixture.geometry; ((FixtureWindow *)host.window).testScale=3; [host windowDidChangeBackingProperties:[NSNotification notificationWithName:NSWindowDidChangeBackingPropertiesNotification object:host.window]]; SUIGeometry geometry; assert(sigil_ui_appkit_host_geometry(token,&geometry) && geometry.scale==3 && fixture.geometry>previous); ((FixtureWindow *)host.window).testScale=0; [host geometry]; assert(sigil_ui_appkit_child_place(token,child,0,0,0,0,0)); assert(view.superview.hidden && host.window.firstResponder==host.view); assert(!sigil_ui_appkit_focus_child(token,child)); assert(sigil_ui_appkit_child_place(token,child,0,0,120,100,0)); assert(sigil_ui_appkit_focus_child(token,child)); assert(sigil_ui_appkit_child_remove(token,child)); assert(fixture.detached==1 && !view.superview && host.window.firstResponder==host.view); assert(!sigil_ui_appkit_child_remove(token,child)); puts("PASS: alpha composition/hit testing, sibling order, resize/scale and empty/detached focus"); fixture.removeOnGeometry=YES; assert(!sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,notified,&fixture)); assert(!view.superview && fixture.detached==2); child=sigil_ui_appkit_child_adopt(token,(__bridge void *)view,0,0,120,100,0,notified,&fixture); assert(child && sigil_ui_appkit_focus_child(token,child)); assert(sigil_ui_appkit_host_valid(token)); dispatch_semaphore_t checked=dispatch_semaphore_create(0); __block BOOL rejected=NO; dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT,0),^{ rejected=!sigil_ui_appkit_host_valid(token) && !sigil_ui_appkit_focus_ui(token); dispatch_semaphore_signal(checked); }); assert(dispatch_semaphore_wait(checked,dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC))==0 && rejected); closeHost(host); assert(fixture.closed==1 && !view.superview && !sigil_ui_appkit_host_valid(token)); assert(nativeHostToken(vm,1,&handle)==SIGIL_FALSE); assert(!sigil_ui_appkit_focus_child(token,child)); assert(!sigil_ui_appkit_host_valid(token+1000)); sigil_vm_destroy(vm); assert(fixture.closed==1); puts("PASS: before-close notification, owned view removal and stale token rejection"); return 0; }}test/appkit/resize.mdeleted
/* Native fixture driven by scripts/build-macos-demo.sgl. No global input, * visible window, or callback into Sigil is needed for the frame tracker. */#include "../../native/appkit.m"#include <assert.h>#include <fcntl.h>#include <unistd.h>static NSPoint simulatedPoint;static unsigned dispatchedMouse;@interface SUITestApplication : SUIApplication@end@implementation SUITestApplication- (NSPoint)resizePointForEvent:(NSEvent *)event { (void)event; return simulatedPoint; }- (void)sendEvent:(NSEvent *)event { if (event.type==NSEventTypeLeftMouseDown || event.type==NSEventTypeLeftMouseDragged) dispatchedMouse++; [super sendEvent:event];}@endstatic void postMouse(SUIHost *host, NSEventType type, NSPoint point) { simulatedPoint=point; NSEvent *event=[NSEvent mouseEventWithType:type location:[host.window convertPointFromScreen:point] modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:host.window.windowNumber context:nil eventNumber:1 clickCount:1 pressure:1]; [NSApp postEvent:event atStart:NO];}static BOOL drawOffscreen(SUIHost *host) { int width=host.width*host.scale, height=host.height*host.scale; NSBitmapImageRep *bitmap=[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*4 bitsPerPixel:32]; NSGraphicsContext *context=[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]; [NSGraphicsContext saveGraphicsState]; NSGraphicsContext.currentContext=context; CGContextScaleCTM(context.CGContext,host.scale,host.scale); [host.view drawRect:host.view.bounds]; [NSGraphicsContext restoreGraphicsState]; if ([bitmap colorAtX:width-2 y:height-2].redComponent<=0.1) { fprintf(stderr,"FAIL: resized frame not drawn before mouse-up\n"); return NO; } return YES;}static void signalPipe(CFRunLoopTimerRef timer, void *info) { (void)timer; int fd=*(int *)info; assert(write(fd,"x",1)==1);}static void watchdog(CFRunLoopTimerRef timer, void *info) { (void)timer; *(BOOL *)info=YES; [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES];}int main(void) { @autoreleasepool { [SUITestApplication sharedApplication]; [NSApp finishLaunching]; hosts=[NSHashTable weakObjectsHashTable]; SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new]; host.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,320,180) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; host.window.releasedWhenClosed=NO; host.window.contentMinSize=NSMakeSize(64,64); host.view=[[SUIView alloc] initWithFrame:host.window.contentView.bounds]; host.view.host=host; host.window.contentView=host.view; host.window.delegate=host; [hosts addObject:host]; [host geometry]; [host.events removeAllObjects]; NSEvent *command=[NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint modifierFlags:NSEventModifierFlagCommand timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:host.window.windowNumber context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:55]; BOOL rejectsRepeat=NO, rejectsText=NO; @try { (void)command.isARepeat; } @catch (NSException *e) { (void)e; rejectsRepeat=YES; } @try { (void)command.characters; } @catch (NSException *e) { (void)e; rejectsText=YES; } assert(rejectsRepeat && rejectsText); /* The old handler's failure control. */ [host key:command]; assert(host.events.lastObject.type==4 && host.events.lastObject.a==1); assert([host.events.lastObject.name isEqualToString:@"Super_L"]); assert([host.events.lastObject.text isEqualToString:@""]); NSEvent *release=[NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:host.window.windowNumber context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:55]; [host key:release]; assert(host.events.lastObject.a==0); [host windowDidResignKey:[NSNotification notificationWithName:NSWindowDidResignKeyNotification object:host.window]]; [host windowDidBecomeKey:[NSNotification notificationWithName:NSWindowDidBecomeKeyNotification object:host.window]]; assert(host.focused && host.events.lastObject.type==5); [host.events removeAllObjects]; puts("PASS: modifier-event property failure control, safe press/release and focus cycling"); NSRect start=host.window.frame; NSPoint origin=NSMakePoint(NSMaxX(start)-1,NSMinY(start)+1); assert(beginResize(host,origin)); assert(host.resizeEdges==(ResizeRight|ResizeBottom)); for (int i=1;i<=4;i++) { updateResize(host,NSMakePoint(origin.x+i*20,origin.y-i*15)); assert(host.width==320+i*20 && host.height==180+i*15); assert(fabs(NSMaxY(host.window.frame)-NSMaxY(start))<0.1); assert(host.events.lastObject.type==1); /* Each intermediate size is observable before the mouse-up. */ assert(host.events.count==(NSUInteger)i); } host.resizeEdges=0; resizingHost=nil; assert(!beginResize(host,NSMakePoint(NSMidX(host.window.frame),NSMidY(host.window.frame)))); NSRect grown=host.window.frame; NSPoint leftTop=NSMakePoint(NSMinX(grown)+1,NSMaxY(grown)-1); assert(beginResize(host,leftTop)); updateResize(host,NSMakePoint(leftTop.x+1000,leftTop.y-1000)); assert(host.width==64 && host.height==64); assert(fabs(NSMaxX(host.window.frame)-NSMaxX(grown))<0.1); assert(fabs(NSMinY(host.window.frame)-NSMinY(grown))<0.1); /* Exercise the real CF descriptor -> AppKit wake path. The Sigil * wait-plan tests cover the scheduler side of this same boundary. */ SigilVM *vm=sigil_vm_create(); assert(vm); hostTag=sigil_intern_symbol(vm,"ui-appkit-window",16); Value root=sigil_intern_symbol(vm,"fixture-window",14); Value handle=sigil_make_foreign(vm,hostTag,(__bridge_retained void *)host,finalizeHost,sizeof(void *)); assert(sigil_define_binding(vm,root,handle)); /* Drive the real application dispatcher and native wait. A global * mouse-position read would miss these recorded outside-edge events. * Every intermediate event must cause a fresh canvas and draw before * mouse-up, including the newly exposed bottom/right area. */ host.resizeEdges=0; resizingHost=nil; [host.window setContentSize:NSMakeSize(320,180)]; [host geometry]; NSRect frame=host.window.frame; NSPoint outside=NSMakePoint(NSMaxX(frame)+8,NSMinY(frame)-8); if (!beginResize(host,outside)) { fprintf(stderr,"FAIL: outside-edge drag cannot present intermediate frames\n"); return 1; } host.resizeEdges=0; resizingHost=nil; [host.events removeAllObjects]; Value pump[]={handle,sigil_fixnum(50),SIGIL_EMPTY,SIGIL_EMPTY}; postMouse(host,NSEventTypeLeftMouseDown,outside); nativeDispatch(vm,4,pump); if (resizingHost!=host) fprintf(stderr,"Dispatcher diagnostic: mouse=%u window=%ld key=%d events=%lu\n", dispatchedMouse,(long)host.window.windowNumber,host.window.keyWindow,(unsigned long)host.events.count); assert(resizingHost==host); int presented=0, drawn=0; for (int i=1;i<=4;i++) { [host.events removeAllObjects]; postMouse(host,NSEventTypeLeftMouseDragged,NSMakePoint(outside.x+i*20,outside.y-i*15)); nativeDispatch(vm,4,pump); BOOL resized=NO; for (SUIEvent *event in host.events) if (event.type==1) resized=YES; if (resized) { int width=host.width*host.scale, height=host.height*host.scale; Value pixels=sigil_make_bytevector(vm,(size_t)width*height*4); memset(sigil_bytevector_data(pixels),0x80,(size_t)width*height*4); Value present[]={sigil_lookup_binding(vm,root),pixels,sigil_fixnum(width),SIGIL_EMPTY}; assert(nativePresent(vm,4,present)==SIGIL_TRUE); presented++; if (!drawOffscreen(host)) return 1; drawn++; } assert(presented==i && drawn==i && resizingHost==host); assert(host.width==320+i*20 && host.height==180+i*15); } postMouse(host,NSEventTypeLeftMouseUp,NSMakePoint(outside.x+80,outside.y-60)); nativeDispatch(vm,4,pump); assert(resizingHost==nil); printf("PASS: %d intermediate presents and %d draws before mouse-up\n",presented,drawn); int pipes[2]; assert(pipe(pipes)==0); assert(fcntl(pipes[0],F_SETFL,O_NONBLOCK)==0); Value reads=sigil_cons(vm,sigil_fixnum(pipes[0]),SIGIL_EMPTY); Value args[]={handle,sigil_fixnum(-1),reads,SIGIL_EMPTY}; CFRunLoopTimerContext writer={0,&pipes[1],NULL,NULL,NULL}; BOOL expired=NO; CFRunLoopTimerContext guard={0,&expired,NULL,NULL,NULL}; CFAbsoluteTime startTime=CFAbsoluteTimeGetCurrent(); CFRunLoopTimerRef signal=CFRunLoopTimerCreate(NULL,startTime+0.05,0,0,0,signalPipe,&writer); CFRunLoopTimerRef limit=CFRunLoopTimerCreate(NULL,startTime+0.5,0,0,0,watchdog,&guard); CFRunLoopAddTimer(CFRunLoopGetMain(),signal,kCFRunLoopCommonModes); CFRunLoopAddTimer(CFRunLoopGetMain(),limit,kCFRunLoopCommonModes); [host.events removeAllObjects]; char byte; while (read(pipes[0],&byte,1)<0 && !expired) nativeDispatch(vm,4,args); assert(!expired); double elapsed=CFAbsoluteTimeGetCurrent()-startTime; assert(elapsed>=0.04 && elapsed<0.5); CFRunLoopTimerInvalidate(signal); CFRunLoopTimerInvalidate(limit); CFRelease(signal); CFRelease(limit); close(pipes[0]); close(pipes[1]); printf("PASS: native descriptor wake in %.1f ms without periodic polling\n",elapsed*1000); closeHost(host); assert(host.closed && resizingHost==nil); sigil_vm_destroy(vm); puts("PASS: intermediate resize events, opposite-edge anchoring, minimum size, cleanup"); } return 0;}test/appkit/services.mdeleted
/* Hidden host-service controls. Never activate a window or use the general pasteboard. */#define SUI_WINDOW_SERVICES_TEST 1#include "../../native/appkit.m"#include <assert.h>#include <pthread.h>@interface ServiceWindow : NSWindow@property int requests;@property int behavior; /* 0 acknowledge, 1 refuse, 2 leave pending */@end@implementation ServiceWindow- (void)toggleFullScreen:(id)sender { (void)sender; self.requests++; SUIHost *host=(SUIHost *)self.delegate; if (self.behavior==1) { [host windowDidFailToEnterFullScreen:self]; return; } if (self.behavior==2) return; if (host->fullscreenRequest.requested) [host windowDidEnterFullScreen:[NSNotification notificationWithName:NSWindowDidEnterFullScreenNotification object:self]]; else [host windowDidExitFullScreen:[NSNotification notificationWithName:NSWindowDidExitFullScreenNotification object:self]];}@endstatic Value callText(SigilVM *vm, SUIHost *host, Value handle, const char *text, Value (*fn)(SigilVM *,int,Value *)){ (void)host; Value args[]={handle,sigil_make_string(vm,text,strlen(text))}; return fn(vm,2,args);}static Value request(SigilVM *vm, Value handle, BOOL enabled){ Value args[]={handle,sigil_bool(enabled)}; return nativeWindowFullscreen(vm,2,args);}static void pump(SigilVM *vm, Value handle){ SUIHost *host=windowServiceHandle(vm,handle); /* Model the Sigil caller draining its queue, retaining history separately * for assertions. Only the real native dispatcher runs the AppKit loop. */ NSMutableArray<SUIEvent *> *history=host.events; host.events=[NSMutableArray new]; Value args[]={handle,sigil_fixnum(100),SIGIL_EMPTY,SIGIL_EMPTY}; nativeDispatch(vm,4,args); [history addObjectsFromArray:host.events]; host.events=history;}static void waitStatus(SigilVM *vm, SUIHost *host, Value handle, int target, double seconds){ double deadline=NSProcessInfo.processInfo.systemUptime+seconds; do { pump(vm,handle); if (host->fullscreenRequest.status==target) return; } while (NSProcessInfo.processInfo.systemUptime<deadline); fprintf(stderr,"FAIL: native fullscreen status %d expected %d\n",host->fullscreenRequest.status,target); abort();}static void assertText(Value value, const char *expected){ assert(sigil_is_string(value)); size_t size=((SigilString *)sigil_as_ptr(value))->byte_length; assert(size==strlen(expected) && !memcmp(sigil_string_bytes(value),expected,size));}typedef struct { SigilVM *vm; Value handle, text; BOOL refused; } ServiceThread;static void *serviceThread(void *data){ @autoreleasepool { ServiceThread *fixture=data; assert(!NSThread.isMainThread); Value text[]={fixture->handle,fixture->text}, fullscreen[]={fixture->handle,SIGIL_TRUE}; fixture->refused=nativeWindowClipboardRead(fixture->vm,1,&fixture->handle)==SIGIL_FALSE && nativeWindowClipboardSet(fixture->vm,2,text)==SIGIL_FALSE && nativeWindowTitle(fixture->vm,2,text)==SIGIL_FALSE && nativeWindowFullscreenState(fixture->vm,1,&fixture->handle)==SIGIL_FALSE && nativeWindowFullscreen(fixture->vm,2,fullscreen)==SIGIL_FALSE && sigil_as_fixnum(nativeWindowFullscreenStatus(fixture->vm,1,&fixture->handle))==SUI_FULLSCREEN_REFUSED; } return NULL;}int main(void){ @autoreleasepool { [SUIApplication sharedApplication]; [NSApp finishLaunching]; hosts=[NSHashTable weakObjectsHashTable]; SigilVM *vm=sigil_vm_create(); assert(vm); sigil__register_sigil_ui_appkit(vm); SUIHost *host=[SUIHost new]; host.events=[NSMutableArray new]; host.trackingHandler=SIGIL_FALSE; ServiceWindow *window=[[ServiceWindow alloc] initWithContentRect:NSMakeRect(0,0,320,240) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; host.window=window; window.releasedWhenClosed=NO; window.delegate=host; host.servicePasteboard=[NSPasteboard pasteboardWithUniqueName]; assert(host.servicePasteboard); Value handle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)host, finalizeHost,traceHost,sizeof(void *)); assert(sigil_define_binding(vm,sigil_intern_symbol(vm,"services-window",15),handle)); assert(!window.visible); assert(callText(vm,host,handle,"Title — λ",nativeWindowTitle)==SIGIL_TRUE); assert(callText(vm,host,handle,"Title — λ",nativeWindowTitle)==SIGIL_TRUE); assert([window.title isEqualToString:@"Title — λ"]); assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE); assert(callText(vm,host,handle,"",nativeWindowClipboardSet)==SIGIL_TRUE); assertText(nativeWindowClipboardRead(vm,1,&handle),""); assert(callText(vm,host,handle,"Text — λ",nativeWindowClipboardSet)==SIGIL_TRUE); assertText(nativeWindowClipboardRead(vm,1,&handle),"Text — λ"); [host.servicePasteboard clearContents]; assert([host.servicePasteboard setData:[NSData dataWithBytes:"x" length:1] forType:@"application/octet-stream"]); assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE); assert(callText(vm,host,handle,"Sentinel",nativeWindowClipboardSet)==SIGIL_TRUE); NSInteger change=host.servicePasteboard.changeCount; host.inTrackingStep=YES; assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE); assert(callText(vm,host,handle,"Forbidden",nativeWindowClipboardSet)==SIGIL_FALSE); host.inTrackingStep=NO; host.inKeyCallback=YES; assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE); assert(callText(vm,host,handle,"Forbidden",nativeWindowClipboardSet)==SIGIL_FALSE); host.inKeyCallback=NO; assert(host.servicePasteboard.changeCount==change); assertText(nativeWindowClipboardRead(vm,1,&handle),"Sentinel"); puts("PASS: synchronous UTF-8 title, private clipboard empty/text/non-text, callback refusal"); assert(sigil_as_fixnum(nativeWindowFullscreenStatus(vm,1,&handle))==SUI_FULLSCREEN_IDLE); assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE); assert(request(vm,handle,YES)==SIGIL_TRUE); assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE); assert(host.events.firstObject.a==0 && host.events.firstObject.b==SUI_FULLSCREEN_PENDING); waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_TRUE && window.requests==1); assert(host.events.firstObject.b==SUI_FULLSCREEN_PENDING); assert(host.events.lastObject.a==1 && host.events.lastObject.b==SUI_FULLSCREEN_GRANTED); assert(!host.fullscreenTimer); [host.events removeAllObjects]; assert(request(vm,handle,NO)==SIGIL_TRUE); assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_TRUE); waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(nativeWindowFullscreenState(vm,1,&handle)==SIGIL_FALSE && window.requests==2); assert(request(vm,handle,NO)==SIGIL_TRUE); waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(window.requests==2); puts("PASS: acknowledged enter/exit, event-time status, no-op grant and timer removal"); assert(request(vm,handle,YES)==SIGIL_TRUE); assert(request(vm,handle,NO)==SIGIL_TRUE); waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(window.requests==2 && !host.fullscreenAcknowledged); window.behavior=2; assert(request(vm,handle,YES)==SIGIL_TRUE); pump(vm,handle); assert(host.fullscreenTransition==1); assert(request(vm,handle,NO)==SIGIL_TRUE); [host windowDidEnterFullScreen:[NSNotification notificationWithName:NSWindowDidEnterFullScreenNotification object:window]]; assert(host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING && host.fullscreenAcknowledged); window.behavior=0; waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(!host.fullscreenAcknowledged); puts("PASS: queued and in-flight supersession retains the latest requested state"); window.behavior=1; assert(request(vm,handle,YES)==SIGIL_TRUE); waitStatus(vm,host,handle,SUI_FULLSCREEN_REFUSED,1); assert(!host.fullscreenAcknowledged && !host.fullscreenTimer); window.behavior=2; [host.events removeAllObjects]; double started=NSProcessInfo.processInfo.systemUptime; assert(request(vm,handle,YES)==SIGIL_TRUE); pump(vm,handle); __block BOOL watchdogFired=NO; CFRunLoopTimerRef watchdog=CFRunLoopTimerCreateWithHandler(NULL,CFAbsoluteTimeGetCurrent()+6,0,0,0, ^(CFRunLoopTimerRef timer) { (void)timer; watchdogFired=YES; [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES]; }); assert(watchdog); CFRunLoopAddTimer(CFRunLoopGetMain(),watchdog,kCFRunLoopCommonModes); while (host->fullscreenRequest.status==SUI_FULLSCREEN_PENDING && !watchdogFired) { NSMutableArray<SUIEvent *> *history=host.events; host.events=[NSMutableArray new]; Value wait[]={handle,sigil_fixnum(-1),SIGIL_EMPTY,SIGIL_EMPTY}; nativeDispatch(vm,4,wait); [history addObjectsFromArray:host.events]; host.events=history; } CFRunLoopTimerInvalidate(watchdog); CFRelease(watchdog); assert(!watchdogFired && host->fullscreenRequest.status==SUI_FULLSCREEN_REFUSED); assert(NSProcessInfo.processInfo.systemUptime-started>=4.8); assert(host.events.lastObject.b==SUI_FULLSCREEN_REFUSED && !host.fullscreenTimer); window.behavior=0; assert(request(vm,handle,YES)==SIGIL_TRUE); waitStatus(vm,host,handle,SUI_FULLSCREEN_GRANTED,1); assert(host.fullscreenAcknowledged); puts("PASS: native failure and silent transition refusal wake dispatch at the bounded deadline"); ServiceThread threadFixture={vm,handle,sigil_make_string(vm,"Owned",5),NO}; pthread_t thread; assert(!pthread_create(&thread,NULL,serviceThread,&threadFixture)); assert(!pthread_join(thread,NULL)); assert(threadFixture.refused); window.styleMask=NSWindowStyleMaskTitled; assert(request(vm,handle,YES)==SIGIL_FALSE); window.styleMask|=NSWindowStyleMaskResizable; assert(request(vm,handle,YES)==SIGIL_TRUE); closeHost(host); assert(!host.fullscreenTimer); assert(nativeWindowClipboardRead(vm,1,&handle)==SIGIL_FALSE); assert(callText(vm,host,handle,"Closed",nativeWindowClipboardSet)==SIGIL_FALSE); assert(callText(vm,host,handle,"Closed",nativeWindowTitle)==SIGIL_FALSE); assert(request(vm,handle,YES)==SIGIL_FALSE); assert(sigil_as_fixnum(nativeWindowFullscreenStatus(vm,1,&handle))==SUI_FULLSCREEN_REFUSED); CFRunLoopRunInMode(kCFRunLoopDefaultMode,0.02,false); assert(host.closed && !host.window); [host.servicePasteboard releaseGlobally]; host.servicePasteboard=nil; sigil_vm_destroy(vm); puts("PASS: wrong thread, unsupported host, pending-close cancellation and stale services"); return 0; }}test/appkit/tracking.mdeleted
/* Real tracking-mode fixture. The current outer-loop-only implementation * must fail this before a common-mode application step is installed. */#include "../../native/appkit.m"#include <assert.h>static SUIHost *fixtureHost;static Value fixtureHandle;static int ticks, processed, presented, drawn;static BOOL tinyPhase, sawOne, sawZero, recovered;static Value trackingStep(SigilVM *vm, int argc, Value *args) { (void)argc; (void)args; BOOL resize=NO; for (SUIEvent *event in fixtureHost.events) { if (event.type!=3) processed++; if (event.type==1) resize=YES; } [fixtureHost.events removeAllObjects]; if (resize) { int width=fixtureHost.width*fixtureHost.scale, height=fixtureHost.height*fixtureHost.scale; Value pixels=sigil_make_bytevector(vm,(size_t)width*height*4); memset(sigil_bytevector_data(pixels),0x90,(size_t)width*height*4); Value present[]={fixtureHandle,pixels,sigil_fixnum(width),SIGIL_EMPTY}; assert(nativePresent(vm,4,present)==SIGIL_TRUE); presented++; NSBitmapImageRep *bitmap=[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width*4 bitsPerPixel:32]; NSGraphicsContext *context=[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]; [NSGraphicsContext saveGraphicsState]; NSGraphicsContext.currentContext=context; CGContextScaleCTM(context.CGContext,fixtureHost.scale,fixtureHost.scale); [fixtureHost.view drawRect:fixtureHost.view.bounds]; [NSGraphicsContext restoreGraphicsState]; if ([bitmap colorAtX:width-1 y:height-1].redComponent>0.1) { drawn++; if (tinyPhase && fixtureHost.width==180 && fixtureHost.height==120) recovered=YES; } } return SIGIL_TRUE;}static void resizeInTracking(CFRunLoopTimerRef timer, void *info) { (void)info; ticks++; if (tinyPhase) { NSSize size=ticks==1 ? NSMakeSize(1,1) : ticks==2 ? NSZeroSize : NSMakeSize(180,120); /* Drive the real content-view resize callback, including sizes that * AppKit's decorated window frame may clamp before they reach it. */ [fixtureHost.window setContentSize:size]; [fixtureHost.view setFrameSize:size]; if (ticks==1) sawOne=NSEqualSizes(fixtureHost.view.bounds.size,NSMakeSize(1,1)) && fixtureHost.width==1 && fixtureHost.height==1; if (ticks==2) sawZero=NSEqualSizes(fixtureHost.view.bounds.size,NSZeroSize) && fixtureHost.width==1 && fixtureHost.height==1; if (ticks==3) CFRunLoopTimerInvalidate(timer); return; } [fixtureHost.window setContentSize:NSMakeSize(120+ticks*12,100+ticks*8)]; [fixtureHost geometry]; if (ticks==4) CFRunLoopTimerInvalidate(timer);}int main(void) { @autoreleasepool { [SUIApplication sharedApplication]; [NSApp finishLaunching]; hosts=[NSHashTable weakObjectsHashTable]; fixtureHost=[SUIHost new]; fixtureHost.events=[NSMutableArray new]; fixtureHost.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,120,100) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; fixtureHost.window.releasedWhenClosed=NO; fixtureHost.view=[[SUIView alloc] initWithFrame:fixtureHost.window.contentView.bounds]; fixtureHost.view.host=fixtureHost; fixtureHost.window.contentView=fixtureHost.view; fixtureHost.window.delegate=fixtureHost; [hosts addObject:fixtureHost]; [fixtureHost geometry]; [fixtureHost.events removeAllObjects]; SigilVM *vm=sigil_vm_create(); assert(vm); sigil__register_sigil_ui_appkit(vm); Value root=sigil_intern_symbol(vm,"tracking-window",15); fixtureHandle=sigil_make_foreign_traced(vm,hostTag,(__bridge_retained void *)fixtureHost,finalizeHost,traceHost,sizeof(void *)); assert(sigil_define_binding(vm,root,fixtureHandle)); int stepIndex=sigil_register_native(vm,"fixture-tracking-step",trackingStep,SIGIL_ARITY_EXACT(0),"fixture"); Value step=sigil_make_native_proc(vm,stepIndex); int install=-1; for (int i=0;i<sigil_native_count(vm);i++) { if (strstr(sigil_get_native(vm,i)->name,"%mac-tracking-handler!")) install=i; } if (install>=0) { Value args[]={fixtureHandle,step}; sigil_get_native(vm,install)->func(vm,2,args); } step=SIGIL_FALSE; /* Only the foreign host tracer now owns this Value. */ int collect=sigil_lookup_native(vm,"%gc-collect!"); assert(collect>=0); sigil_get_native(vm,collect)->func(vm,0,NULL); fixtureHandle=sigil_lookup_binding(vm,root); CFStringRef mode=(__bridge CFStringRef)NSEventTrackingRunLoopMode; CFRunLoopTimerRef timer=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+0.015, 0.03,0,0,resizeInTracking,NULL); CFRunLoopAddTimer(CFRunLoopGetMain(),timer,mode); CFRunLoopRunInMode(mode,0.20,false); CFRunLoopTimerInvalidate(timer); CFRelease(timer); BOOL pass=ticks==4 && processed>=4 && presented==4 && drawn==4; printf("%s: real tracking mode ticks=%d processed=%d presents=%d draws=%d before tracking ends\n", pass ? "PASS" : "FAIL",ticks,processed,presented,drawn); if (pass) { tinyPhase=YES; ticks=processed=presented=drawn=0; fixtureHost.window.contentMinSize=NSZeroSize; timer=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+0.015, 0.03,0,0,resizeInTracking,NULL); CFRunLoopAddTimer(CFRunLoopGetMain(),timer,mode); CFRunLoopRunInMode(mode,0.20,false); CFRunLoopTimerInvalidate(timer); CFRelease(timer); pass=sawOne && sawZero && recovered && !fixtureHost.closed && presented>=2 && drawn>=2; printf("%s: real tracking 1x1=%d 0x0=%d normal-redraw=%d presents=%d draws=%d\n", pass ? "PASS" : "FAIL",sawOne,sawZero,recovered,presented,drawn); } closeHost(fixtureHost); assert(fixtureHost.trackingSource==NULL && fixtureHost.trackingHandler==SIGIL_FALSE); sigil_vm_destroy(vm); return pass ? 0 : 1; }}test/check-appkit-adapter.sgladded
;;; Run with the controlled host directory first on the module search path.(import (sigil ui appkit) (sigil ui raster) (sigil ui mask) (sigil ui tree) (sigil ui theme) (prefix (sigil window appkit) host:))(define checks 0)(define (check condition label) (set! checks (+ checks 1)) (unless condition (error "AppKit drawing adapter failed" label)) (println "PASS: ~a" label))(define (raises? thunk) (guard (failure (#t #t)) (thunk) #f))(define window (open-appkit-window))(define other (open-appkit-window))(define canvas (make-canvas 20 16))(check (= 20 (appkit-window-device-width window)) "legacy canvas extent follows host raster width")(check (appkit-present! window canvas) "canvas forwards to host")(check (eq? (car (host:test-last)) (canvas-pixels canvas)) "original canvas bytes forwarded")(check (equal? (cdr (host:test-last)) '(20 16 1 #f)) "dimensions and current generation forwarded")(define before (host:test-calls))(check (appkit-present! window canvas '()) "empty damage succeeds")(check (= before (host:test-calls)) "empty damage does not present")(each rectangle '((-1 0 1 1) (0 0 21 1) (0 0 1 17) (0 0 1.5 1) (0 0 1)) (check (raises? (lambda () (appkit-present! window canvas (list rectangle)))) "malformed device damage rejected"))(check (= before (host:test-calls)) "invalid damage never reaches host")(define ui (appkit-make-ui window (make-theme '() '() '()) 0))(check (and (= (ui-width ui) 10) (= (ui-height ui) 8) (= (ui-scale ui) 2)) "UI allocates at host raster scale")(check (appkit-present-ui! window ui '((0 0 10 8))) "logical UI damage converts to device damage")(check (not (appkit-present-ui! other ui '((0 0 10 8)))) "UI refuses another window")(host:test-generation! window 2)(define stale-before (host:test-calls))(check (not (appkit-present-ui! window ui '((0 0 10 8)))) "stale UI generation refused")(check (= stale-before (host:test-calls)) "stale UI does not reach host")(check (appkit-present! window canvas) "direct presentation snapshots the new generation")(check (= 2 (list-ref (host:test-last) 3)) "updated generation forwarded")(define alpha (make-mask 20 16 (make-bytevector 320 128)))(check (appkit-present-overlay! window canvas alpha) "overlay forwards to host")(check (eq? (list-ref (host:test-last) 4) (mask-alpha alpha)) "overlay alpha plane forwarded")(check (raises? (lambda () (appkit-present-overlay! window canvas (make-mask 1 1 (bytevector 0))))) "mismatched overlay dimensions rejected")(println "RESULT PASS checks=~a" checks)test/link-check/.gitignoreadded
/sigil.locktest/link-check/package.sgladded
;;; A real executable link catches duplicate native libraries and symbols.(package name: "sigil-ui-link-check" version: "0.0.0" sigil: "0.24.8" entry: '(link main) dependencies: (list (from-path dir: "../.." package: "sigil-ui") (from-pkg name: "sigil/sigil-lib" version: "0.24.8") (from-pkg name: "sigil/sigil-stdlib" version: "0.24.8")) configs: (list (config name: 'dev toolchain: 'zig target: "x86_64-linux-musl" static?: #t output-dir: "build/dev")) tasks: (list (task name: 'build steps: (list (compile-sigil-modules sources: "src/**/*.sgl")))))test/link-check/src/link/main.sgladded
(define-library (link main) (import (sigil ui raster) (sigil io)) (export main) (begin (define (main) (let ((canvas (make-canvas 12 10))) (canvas-fill! canvas 2 3 4 5 #x123456) (unless (= (canvas-pixel canvas 3 4) #x123456) (error "Linked native raster did not draw the expected pixel")) (println "PASS: linked sigil-ui native executable rasterized 0x123456")))))test/test-appkit-wait.sglmodified
;;; The scheduler-to-run-loop wait plan needs no display and runs on Linux too.(import (sigil test) (sigil async) (sigil time) (sigil socket) (sigil system) (sigil ui appkit wait))(test-group "AppKit wait plan" (test "a synchronous idle wait has no periodic deadline" (assert-equal '(-1 () ()) (appkit-wait-plan #f)) (assert-equal '(25 () ()) (appkit-wait-plan 25))) (test "a scheduler timer bounds an otherwise indefinite wait" (with-async (go (sleep 0.2)) (let ((plan (appkit-wait-plan #f))) (assert-true (> (car plan) 0)) (assert-true (<= (car plan) 200))))) (test "runnable work prevents a native blocking wait" (let ((running #t)) (with-async (go (let loop () (when running (yield) (loop)))) (let ((delay (car (appkit-wait-plan #f)))) (set! running #f) (assert-equal 0 delay))))) (test "a socket wait contributes its descriptor and deadline" (let* ((pair (socket-pair)) (reader (car pair)) (writer (cadr pair))) (with-async (go (await-readable-any (list reader) timeout-ms: 150)) (let ((plan (appkit-wait-plan #f))) (assert-true (and (member (socket-fd reader) (cadr plan)) #t)) (assert-true (> (car plan) 0)) (assert-true (<= (car plan) 150)))) (socket-close reader) (socket-close writer))));;; AppKit compatibility modules are compiled only for Darwin.(import (sigil test) (sigil async) (sigil time) (sigil socket) (sigil system))(cond-expand (darwin (import (sigil ui appkit wait)) (test-group "AppKit wait plan" (test "a synchronous idle wait has no periodic deadline" (assert-equal '(-1 () ()) (appkit-wait-plan #f)) (assert-equal '(25 () ()) (appkit-wait-plan 25))) (test "a scheduler timer bounds an otherwise indefinite wait" (with-async (go (sleep 0.2)) (assert-equal 0 (car (appkit-wait-plan #f))) (let ((plan (appkit-wait-plan #f))) (assert-true (> (car plan) 0)) (assert-true (<= (car plan) 200))))) (test "runnable work prevents a native blocking wait" (let ((running #t)) (with-async (go (let loop () (when running (yield) (loop)))) (let ((delay (car (appkit-wait-plan #f)))) (set! running #f) (assert-equal 0 delay))))) (test "a socket wait contributes its descriptor and deadline" (let* ((pair (socket-pair)) (reader (car pair)) (writer (cadr pair))) (with-async (go (await-readable-any (list reader) timeout-ms: 150)) (assert-equal 0 (car (appkit-wait-plan #f))) (let ((plan (appkit-wait-plan #f))) (assert-true (and (member (socket-fd reader) (cadr plan)) #t)) (assert-true (> (car plan) 0)) (assert-true (<= (car plan) 150)))) (socket-close reader) (socket-close writer))))) (else (test-skip "AppKit wait facade requires Darwin")))