1// The window on macOS, through AppKit (PLAN.md, F7): the2// frameworks open while running and every call is an Objective-C message3// (objc.alloy). AppKit's own loop runs (`[NSApp run]`, F7 question 2A)4// and calls the program back through classes made here: AlloyView, the5// window's content, takes the mouse, the keyboard, input methods (as an6// NSTextInputClient), the Edit menu's commands, drops and the cursor, and7// answers VoiceOver (nsaccessibility.alloy); AlloyWindowDelegate the8// window's closing, resizing, scale and focus; AlloyApplicationDelegate9// the application's quitting. Each method is a block reaching this10// module's state through a cell in C's heap, so the classes, made once a11// process, serve every window run after. Redraws are paced by a12// CVDisplayLink, whose thread signals a run loop source on the main13// thread, as a Waker does; frames from the CPU go into the view's layer14// as a CGImage. The clipboard is the general NSPasteboard and file15// dialogs are NSOpenPanel and NSSavePanel, run modal. macOS 11 or later.1617import std::ffi;18import std::fs;19import std::option;20import std::string;21import std::vector;22import std::io;23import std::time;2425import window;26import unicode;27import pkg::alloy::objc;28import loading;29import cocoa;30import nsaccessibility;3132// CoreFoundation's, CoreGraphics', CoreVideo's and Carbon's C functions.33type Frameworks = struct {34 main_run_loop: extern () -> c_pointer,35 create_source: extern (c_pointer, c_ssize, c_pointer) -> c_pointer,36 add_source: extern (c_pointer, c_pointer, c_pointer),37 signal_source: c_pointer, // CFRunLoopSourceSignal38 wake_up: c_pointer, // CFRunLoopWakeUp39 invalidate_source: extern (c_pointer),40 common_modes: c_pointer, // kCFRunLoopCommonModes41 create_timer: extern (42 c_pointer,43 f64,44 f64,45 u64,46 c_ssize,47 extern (c_pointer, c_pointer),48 c_pointer49 ) -> c_pointer,50 add_timer: extern (c_pointer, c_pointer, c_pointer),51 set_fire_date: extern (c_pointer, f64),52 invalidate_timer: extern (c_pointer),53 absolute_time: extern () -> f64,54 release: extern (c_pointer),55 create_data: extern (c_pointer, c_pointer, c_ssize) -> c_pointer,56 color_space_named: extern (c_pointer) -> c_pointer,57 srgb: c_pointer, // kCGColorSpaceSRGB58 provider_from_data: extern (c_pointer) -> c_pointer,59 release_provider: extern (c_pointer),60 release_color_space: extern (c_pointer),61 create_image: extern (62 c_size,63 c_size,64 c_size,65 c_size,66 c_size,67 c_pointer,68 u32,69 c_pointer,70 c_pointer,71 bool,72 i3273 ) -> c_pointer,74 release_image: extern (c_pointer),75 create_link: extern (c_pointer) -> i32,76 set_link_callback: extern (77 c_pointer,78 extern (c_pointer, c_pointer, c_pointer, u64, c_pointer, c_pointer) -> i32,79 c_pointer80 ) -> i32,81 start_link: extern (c_pointer) -> i32,82 stop_link: extern (c_pointer) -> i32,83 release_link: extern (c_pointer),84 // secure event input, keeping the keys from other programs85 enable_secure_input: extern () -> i32,86 disable_secure_input: extern () -> i32,87};8889// The system's framework of the name.90fn framework(name: &[u8]) -> Option<Library> {91 return Library::open(&f"/System/Library/Frameworks/{name}.framework/{name}".view());92}9394fn Frameworks::load() -> Option<Frameworks> {95 const foundation = if (framework(&"CoreFoundation") is ::Some |l|) l else {96 return ::None;97 };98 const graphics = if (framework(&"CoreGraphics") is ::Some |l|) l else {99 return ::None;100 };101 const video = if (framework(&"CoreVideo") is ::Some |l|) l else {102 return ::None;103 };104 const carbon = if (framework(&"Carbon") is ::Some |l|) l else {105 return ::None;106 };107 return ::Some(Frameworks {108 .main_run_loop = function(&foundation, &"CFRunLoopGetMain"),109 .create_source = function(&foundation, &"CFRunLoopSourceCreate"),110 .add_source = function(&foundation, &"CFRunLoopAddSource"),111 .signal_source = address_of(&foundation, &"CFRunLoopSourceSignal"),112 .wake_up = address_of(&foundation, &"CFRunLoopWakeUp"),113 .invalidate_source = function(&foundation, &"CFRunLoopSourceInvalidate"),114 .common_modes = pointer_at(&foundation, &"kCFRunLoopCommonModes"),115 .create_timer = function(&foundation, &"CFRunLoopTimerCreate"),116 .add_timer = function(&foundation, &"CFRunLoopAddTimer"),117 .set_fire_date = function(&foundation, &"CFRunLoopTimerSetNextFireDate"),118 .invalidate_timer = function(&foundation, &"CFRunLoopTimerInvalidate"),119 .absolute_time = function(&foundation, &"CFAbsoluteTimeGetCurrent"),120 .release = function(&foundation, &"CFRelease"),121 .create_data = function(&foundation, &"CFDataCreate"),122 .color_space_named = function(&graphics, &"CGColorSpaceCreateWithName"),123 .srgb = pointer_at(&graphics, &"kCGColorSpaceSRGB"),124 .provider_from_data = function(&graphics, &"CGDataProviderCreateWithCFData"),125 .release_provider = function(&graphics, &"CGDataProviderRelease"),126 .release_color_space = function(&graphics, &"CGColorSpaceRelease"),127 .create_image = function(&graphics, &"CGImageCreate"),128 .release_image = function(&graphics, &"CGImageRelease"),129 .create_link = function(&video, &"CVDisplayLinkCreateWithActiveCGDisplays"),130 .set_link_callback = function(&video, &"CVDisplayLinkSetOutputCallback"),131 .start_link = function(&video, &"CVDisplayLinkStart"),132 .stop_link = function(&video, &"CVDisplayLinkStop"),133 .release_link = function(&video, &"CVDisplayLinkRelease"),134 .enable_secure_input = function(&carbon, &"EnableSecureEventInput"),135 .disable_secure_input = function(&carbon, &"DisableSecureEventInput")136 });137}138139pub type AppKit = struct {140 o: Objc,141 f: Frameworks,142 window: Window,143 handler: |&| (&var Window, &Event),144 cell: c_pointer, // where the classes' methods find this145 app: c_pointer = 0, // NSApp146 ns_window: c_pointer = 0,147 view: c_pointer = 0,148 window_delegate: c_pointer = 0,149 app_delegate: c_pointer = 0,150 run_loop: c_pointer = 0,151 wake_source: c_pointer = 0,152 frame_source: c_pointer = 0,153 // the program's deadline (`wake_at`): a timer repeating once in154 // centuries, its next firing moved to each deadline155 timer: c_pointer = 0,156 link: c_pointer = 0, // the CVDisplayLink157 ticker: c_pointer = 0, // what its callback signals, in C's heap158 linked: bool = false, // whether the display link runs159 frame_wanted: bool = false,160 painting: bool = false,161 sized: bool = false, // whether the handler has had a Resized162 inside: bool = false, // whether the pointer is over the view163 position: Point = Point { .x = 0.0, .y = 0.0 },164 closed: bool = false,165 string_type: c_pointer, // NSPasteboardTypeString166 // NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification167 display_options: c_pointer,168 file_url_type: c_pointer, // NSPasteboardTypeFileURL169 // the input method's composition, while there is one170 composing: bool = false,171 marked: String = String::empty(),172 secure: bool = false, // whether secure event input is on173 drag_accepted: bool = false,174 showing_dialog: bool = false,175 dialogs: Vector<DialogRequest> = Vector<DialogRequest>::empty(), // waiting for the one showing176 // VoiceOver once installed (window.alloy's Start): the source177 // signalled when it asked something, and what answers it178 access_source: c_pointer = 0,179 access: Option<MacAccess> = ::None,180 parts: Parts = Parts {},181};182183// What the loop calls of what a program installed, set as each starts,184// so that a program installing nothing links none of it: the handler's185// requests for VoiceOver and its elements let go as the window goes, and186// the dialogs asked for.187type Parts = struct {188 access: Option<(&var AppKit, &var Requests)> = ::None,189 access_ended: Option<(&var AppKit)> = ::None,190 dialogs: Option<(&var AppKit, &var Requests)> = ::None,191};192193pub fn run_appkit(config: &WindowConfig, handler: |&| (&var Window, &Event)) -> i32 {194 const o = if (Objc::load() is ::Some |r|) r else {195 print_error(&"pkg::alloy::window: the Objective-C runtime cannot be loaded\n");196 return 1;197 };198 const f = if (Frameworks::load() is ::Some |loaded|) loaded else {199 print_error(&"pkg::alloy::window: AppKit's frameworks cannot be loaded\n");200 return 1;201 };202 const appkit = if (framework(&"AppKit") is ::Some |l|) l else {203 print_error(&"pkg::alloy::window: AppKit cannot be loaded\n");204 return 1;205 };206 const pool = o.pool_push();207 var a = AppKit {208 .o = o,209 .f = f,210 .window = Window::opening(&config, 1.0),211 .handler = move handler,212 .cell = make_classes(&o),213 .string_type = pointer_at(&appkit, &"NSPasteboardTypeString"),214 .display_options = pointer_at(215 &appkit,216 &"NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification"217 ),218 .file_url_type = pointer_at(&appkit, &"NSPasteboardTypeFileURL")219 };220 // the cell: the window's state, then its accessibility's once221 // installed222 const slots = &var a.cell.view_var<c_pointer>(2);223 slots[0] = c_pointer::from(&var a);224 slots[1] = 0;225 a.open(&config);226 o.pool_pop(pool);227 // AppKit's loop, until the window closes and `stop:` ends it228 o.call(a.app, &"run");229 slots[0] = 0;230 slots[1] = 0;231 a.finish();232 return 0;233}234235// The classes, made the first time a window opens in the process; the236// cell their methods read this module's state from.237fn make_classes(o: &Objc) -> c_pointer {238 const view = o.subclass(&"AlloyView", o.class(&"NSView"));239 if (!view.is_new) {240 return block_state(o.method_block(view.class, &"isFlipped"));241 }242 const cell = lasting(16);243 const b = &bool_code();244 // the view: drawn top down, the mouse, the keyboard, the cursor245 const yes: extern (c_pointer, c_pointer) -> bool = (block, this) => true;246 o.method_with(view.class, &"isFlipped", &f"{b}@:".view(), yes, cell);247 o.method_with(view.class, &"acceptsFirstResponder", &f"{b}@:".view(), yes, cell);248 const yes_for: extern (c_pointer, c_pointer, c_pointer) -> bool = (block, this, event) => true;249 o.method_with(view.class, &"acceptsFirstMouse:", &f"{b}@:@".view(), yes_for, cell);250 const down: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {251 reach(block, (a) => a.button(event, true));252 };253 const up: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {254 reach(block, (a) => a.button(event, false));255 };256 const moved: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {257 reach(block, (a) => a.pointer_moved(event));258 };259 const exited: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {260 reach(block, (a) => a.pointer_left());261 };262 const scrolled: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {263 reach(block, (a) => a.scroll(event));264 };265 const key_down: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {266 reach(block, (a) => a.key(event, true));267 };268 const key_up: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {269 reach(block, (a) => a.key(event, false));270 };271 const flags: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {272 reach(block, (a) => a.flags_changed(event));273 };274 const cursor: extern (c_pointer, c_pointer, c_pointer) = (block, this, event) {275 reach(block, (a) => a.show_cursor());276 };277 const buttons: [&[u8] : 3] = [&"mouseDown:", &"rightMouseDown:", &"otherMouseDown:"];278 for (buttons) |&name| {279 o.method_with(view.class, &name, &"v@:@", down, cell);280 }281 const releases: [&[u8] : 3] = [&"mouseUp:", &"rightMouseUp:", &"otherMouseUp:"];282 for (releases) |&name| {283 o.method_with(view.class, &name, &"v@:@", up, cell);284 }285 const moves: [&[u8] : 5] = [286 &"mouseMoved:", &"mouseDragged:", &"rightMouseDragged:", &"otherMouseDragged:", &"mouseEntered:"287 ];288 for (moves) |&name| {289 o.method_with(view.class, &name, &"v@:@", moved, cell);290 }291 o.method_with(view.class, &"mouseExited:", &"v@:@", exited, cell);292 o.method_with(view.class, &"scrollWheel:", &"v@:@", scrolled, cell);293 o.method_with(view.class, &"keyDown:", &"v@:@", key_down, cell);294 o.method_with(view.class, &"keyUp:", &"v@:@", key_up, cell);295 o.method_with(view.class, &"flagsChanged:", &"v@:@", flags, cell);296 o.method_with(view.class, &"cursorUpdate:", &"v@:@", cursor, cell);297298 // the Edit menu's commands, as the keys they stand for299 const cut: extern (c_pointer, c_pointer, c_pointer) = (block, this, sender) {300 reach(block, (a) => a.command('x'));301 };302 const copied: extern (c_pointer, c_pointer, c_pointer) = (block, this, sender) {303 reach(block, (a) => a.command('c'));304 };305 const paste: extern (c_pointer, c_pointer, c_pointer) = (block, this, sender) {306 reach(block, (a) => a.command('v'));307 };308 const select_all: extern (c_pointer, c_pointer, c_pointer) = (block, this, sender) {309 reach(block, (a) => a.command('a'));310 };311 o.method_with(view.class, &"cut:", &"v@:@", cut, cell);312 o.method_with(view.class, &"copy:", &"v@:@", copied, cell);313 o.method_with(view.class, &"paste:", &"v@:@", paste, cell);314 o.method_with(view.class, &"selectAll:", &"v@:@", select_all, cell);315316 // NSTextInputClient: what an input method composes and commits, and317 // where the text input is for its candidates318 const insert: extern (319 c_pointer,320 c_pointer,321 c_pointer,322 NSRange323 ) = (block, this, text, replaced) {324 reach(block, (a) => a.insert_text(text));325 };326 const mark: extern (c_pointer, c_pointer, c_pointer, NSRange, NSRange) = (327 block,328 this,329 text,330 selected,331 replaced332 ) {333 reach(block, (a) => a.mark_text(text, selected));334 };335 const unmark: extern (c_pointer, c_pointer) = (block, this) {336 reach(block, (a) => a.unmark_text());337 };338 const has_marked: extern (c_pointer, c_pointer) -> bool = (block, this) -> bool {339 const at = held(block);340 return at != 0 && at.as_var<AppKit>().composing;341 };342 const marked_range: extern (c_pointer, c_pointer) -> NSRange = (block, this) -> NSRange {343 const at = held(block);344 if (at == 0 || !at.as_var<AppKit>().composing) {345 return NSRange { .location = NOT_FOUND, .length = 0 };346 }347 const marked = &at.as_var<AppKit>().marked.view();348 return NSRange { .location = 0, .length = utf16_offset(&marked, marked.length()) };349 };350 const selected_range: extern (c_pointer, c_pointer) -> NSRange = (block, this) -> NSRange {351 return NSRange { .location = NOT_FOUND, .length = 0 };352 };353 const attributes: extern (c_pointer, c_pointer) -> c_pointer = (block, this) -> c_pointer {354 const at = held(block);355 if (at == 0) {356 return 0;357 }358 const a = &at.as_var<AppKit>();359 return a.o.call(a.o.class(&"NSArray"), &"array");360 };361 const substring: extern (c_pointer, c_pointer, NSRange, c_pointer) -> c_pointer = (362 block,363 this,364 range,365 actual366 ) => 0;367 const index_at: extern (c_pointer, c_pointer, NSPoint) -> u64 = (block, this, at) => NOT_FOUND;368 const caret: extern (c_pointer, c_pointer, NSRange, c_pointer) -> NSRect = (369 block,370 this,371 range,372 actual373 ) -> NSRect {374 const at = held(block);375 if (at == 0) {376 return NSRect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 };377 }378 return at.as_var<AppKit>().caret_rect();379 };380 const command: extern (c_pointer, c_pointer, c_pointer) = (block, this, selector) {};381 o.method_with(382 view.class,383 &"insertText:replacementRange:",384 &f"v@:@{RANGE_CODE}".view(),385 insert,386 cell387 );388 o.method_with(389 view.class,390 &"setMarkedText:selectedRange:replacementRange:",391 &f"v@:@{RANGE_CODE}{RANGE_CODE}".view(),392 mark,393 cell394 );395 o.method_with(view.class, &"unmarkText", &"v@:", unmark, cell);396 o.method_with(view.class, &"hasMarkedText", &f"{b}@:".view(), has_marked, cell);397 o.method_with(view.class, &"markedRange", &f"{RANGE_CODE}@:".view(), marked_range, cell);398 o.method_with(view.class, &"selectedRange", &f"{RANGE_CODE}@:".view(), selected_range, cell);399 o.method_with(view.class, &"validAttributesForMarkedText", &"@@:", attributes, cell);400 o.method_with(401 view.class,402 &"attributedSubstringForProposedRange:actualRange:",403 &f"@@:{RANGE_CODE}^{RANGE_CODE}".view(),404 substring,405 cell406 );407 o.method_with(408 view.class,409 &"characterIndexForPoint:",410 &f"Q@:{POINT_CODE}".view(),411 index_at,412 cell413 );414 o.struct_method_with(415 view.class,416 &"firstRectForCharacterRange:actualRange:",417 &f"{RECT_CODE}@:{RANGE_CODE}^{RANGE_CODE}".view(),418 caret,419 cell420 );421 o.method_with(view.class, &"doCommandBySelector:", &"v@::", command, cell);422 o.adopt(view.class, &"NSTextInputClient");423 o.register_class(view.class);424425 // the window's delegate426 const delegate = o.subclass(&"AlloyWindowDelegate", o.class(&"NSObject"));427 const should_close: extern (428 c_pointer,429 c_pointer,430 c_pointer431 ) -> bool = (block, this, sender) -> bool {432 reach(block, (a) => a.deliver(&Event::CloseRequested));433 return false;434 };435 const resized: extern (c_pointer, c_pointer, c_pointer) = (block, this, note) {436 reach(block, (a) => a.measure());437 };438 const focused: extern (c_pointer, c_pointer, c_pointer) = (block, this, note) {439 reach(block, (a) => a.deliver(&Event::Focused(true)));440 };441 const unfocused: extern (c_pointer, c_pointer, c_pointer) = (block, this, note) {442 reach(block, (a) => a.deliver(&Event::Focused(false)));443 };444 o.method_with(delegate.class, &"windowShouldClose:", &f"{b}@:@".view(), should_close, cell);445 o.method_with(delegate.class, &"windowDidResize:", &"v@:@", resized, cell);446 o.method_with(delegate.class, &"windowDidChangeBackingProperties:", &"v@:@", resized, cell);447 o.method_with(delegate.class, &"windowDidBecomeKey:", &"v@:@", focused, cell);448 o.method_with(delegate.class, &"windowDidResignKey:", &"v@:@", unfocused, cell);449 const display_changed: extern (c_pointer, c_pointer, c_pointer) = (block, this, note) {450 reach(block, (a) => a.motion_changed());451 };452 o.method_with(453 delegate.class,454 &"accessibilityDisplayOptionsChanged:",455 &"v@:@",456 display_changed,457 cell458 );459 o.adopt(delegate.class, &"NSWindowDelegate");460 o.register_class(delegate.class);461462 // the application's delegate: quitting (Cmd+Q, the Dock, logging463 // out) asks the program, which closes its window or not464 const application = o.subclass(&"AlloyApplicationDelegate", o.class(&"NSObject"));465 const should_terminate: extern (466 c_pointer,467 c_pointer,468 c_pointer469 ) -> u64 = (block, this, sender) -> u64 {470 reach(block, (a) => a.deliver(&Event::CloseRequested));471 return 0; // NSTerminateCancel472 };473 const launched: extern (c_pointer, c_pointer, c_pointer) = (block, this, note) {474 reach(block, (a) => a.launched());475 };476 o.method_with(477 application.class,478 &"applicationShouldTerminate:",479 &"Q@:@",480 should_terminate,481 cell482 );483 o.method_with(application.class, &"applicationDidFinishLaunching:", &"v@:@", launched, cell);484 o.adopt(application.class, &"NSApplicationDelegate");485 o.register_class(application.class);486 return cell;487}488489// Calls `f` with the state the block's cell holds, while a window runs.490fn reach(block: c_pointer, f: |&| (&var AppKit)) {491 const at = held(block);492 if (at != 0) {493 f(&var at.as_var<AppKit>());494 }495}496497// The state the block's cell holds, 0 when no window runs.498fn held(block: c_pointer) -> c_pointer => block_state(block).view<c_pointer>(1)[0];499500// NSDraggingDestination on the view, once files are installed: files501// and text dragged from other programs.502fn add_drag_methods(o: &Objc, view: c_pointer, cell: c_pointer) {503 const b = &bool_code();504 const entered: extern (c_pointer, c_pointer, c_pointer) -> u64 = (block, this, info) -> u64 {505 const at = held(block);506 return if (at == 0) 0 else at.as_var<AppKit>().drag_entered(info);507 };508 const updated: extern (c_pointer, c_pointer, c_pointer) -> u64 = (block, this, info) -> u64 {509 const at = held(block);510 return if (at == 0) 0 else at.as_var<AppKit>().drag_moved(info);511 };512 const left: extern (c_pointer, c_pointer, c_pointer) = (block, this, info) {513 reach(block, (a) => a.deliver(&Event::DragLeft));514 };515 const prepare: extern (c_pointer, c_pointer, c_pointer) -> bool = (block, this, info) => true;516 const perform: extern (c_pointer, c_pointer, c_pointer) -> bool = (block, this, info) -> bool {517 const at = held(block);518 return at != 0 && at.as_var<AppKit>().dropped(info);519 };520 o.method_with(view, &"draggingEntered:", &"Q@:@", entered, cell);521 o.method_with(view, &"draggingUpdated:", &"Q@:@", updated, cell);522 o.method_with(view, &"draggingExited:", &"v@:@", left, cell);523 o.method_with(view, &"prepareForDragOperation:", &f"{b}@:@".view(), prepare, cell);524 o.method_with(view, &"performDragOperation:", &f"{b}@:@".view(), perform, cell);525}526527fn open(self a: &var AppKit, config: &WindowConfig) {528 const o = &a.o;529 a.app = o.call(o.class(&"NSApplication"), &"sharedApplication");530 // NSApplicationActivationPolicyRegular: a Dock icon and a menu bar531 o.call_integer(a.app, &"setActivationPolicy:", 0);532 a.app_delegate = o.make(o.class(&"AlloyApplicationDelegate"));533 o.call_with(a.app, &"setDelegate:", a.app_delegate);534 a.make_menu();535536 // titled, closable, miniaturizable, and resizable when asked537 const style: u64 = if (config.resizable) 1 | 2 | 4 | 8 else 1 | 2 | 4;538 const content = NSRect {539 .x = 0.0,540 .y = 0.0,541 .width = config.size.width to f64,542 .height = config.size.height to f64543 };544 const init_window = o.send<extern (545 c_pointer,546 c_pointer,547 NSRect,548 u64,549 u64,550 bool551 ) -> c_pointer>();552 // NSBackingStoreBuffered553 a.ns_window = init_window(554 o.call(o.class(&"NSWindow"), &"alloc"),555 o.sel(&"initWithContentRect:styleMask:backing:defer:"),556 content,557 style,558 2,559 false560 );561 o.call_bool(a.ns_window, &"setReleasedWhenClosed:", false);562 o.call_bool(a.ns_window, &"setAcceptsMouseMovedEvents:", true);563 o.call_with(a.ns_window, &"setTitle:", o.string(&config.title));564 a.window_delegate = o.make(o.class(&"AlloyWindowDelegate"));565 o.call_with(a.ns_window, &"setDelegate:", a.window_delegate);566 // "Reduce motion", and its changes through the workspace's own567 // notification center568 const workspace = o.call(o.class(&"NSWorkspace"), &"sharedWorkspace");569 a.window.reduced_motion = o.boolean(workspace, &"accessibilityDisplayShouldReduceMotion");570 const observe = o.send<extern (571 c_pointer,572 c_pointer,573 c_pointer,574 c_pointer,575 c_pointer,576 c_pointer577 )>();578 observe(579 o.call(workspace, &"notificationCenter"),580 o.sel(&"addObserver:selector:name:object:"),581 a.window_delegate,582 o.sel(&"accessibilityDisplayOptionsChanged:"),583 a.display_options,584 0585 );586587 const init_view = o.send<extern (c_pointer, c_pointer, NSRect) -> c_pointer>();588 a.view = init_view(o.call(o.class(&"AlloyView"), &"alloc"), o.sel(&"initWithFrame:"), content);589 o.call_bool(a.view, &"setWantsLayer:", true);590 // the pointer's moves, entering and leaving, and the cursor, over the591 // view wherever it is (NSTrackingMouseEnteredAndExited, MouseMoved,592 // CursorUpdate, ActiveAlways, InVisibleRect)593 const init_area = o.send<extern (594 c_pointer,595 c_pointer,596 NSRect,597 u64,598 c_pointer,599 c_pointer600 ) -> c_pointer>();601 const area = init_area(602 o.call(o.class(&"NSTrackingArea"), &"alloc"),603 o.sel(&"initWithRect:options:owner:userInfo:"),604 content,605 0x01 | 0x02 | 0x04 | 0x80 | 0x200,606 a.view,607 0608 );609 o.call_with(a.view, &"addTrackingArea:", area);610 o.release(area);611 o.call_with(a.ns_window, &"setContentView:", a.view);612 o.call_with(a.ns_window, &"makeFirstResponder:", a.view);613614 a.make_sources();615 a.window.target = Target::AppKit(AppKitTarget { .window = a.ns_window, .view = a.view });616617 const scale = o.number(a.ns_window, &"backingScaleFactor") to f32;618 if (scale != 1.0) {619 a.deliver(&Event::Scaled(scale));620 }621 a.measure();622 o.call(a.ns_window, &"center");623 o.call_with(a.ns_window, &"makeKeyAndOrderFront:", 0);624}625626// Gives the program "Reduce motion" when it changed.627fn motion_changed(self a: &var AppKit) {628 const workspace = a.o.call(a.o.class(&"NSWorkspace"), &"sharedWorkspace");629 const reduced = a.o.boolean(workspace, &"accessibilityDisplayShouldReduceMotion");630 if (reduced != a.window.reduced_motion) {631 a.deliver(&Event::ReducedMotion(reduced));632 }633}634635// Brings the application forward once AppKit has started it.636fn launched(self a: &var AppKit) {637 a.o.call_bool(a.app, &"activateIgnoringOtherApps:", true);638}639640// The menu bar: the application menu (Hide, Hide Others, Show All,641// Quit) and the Edit menu (Cut, Copy, Paste, Select All), whose commands642// the view takes as the keys they stand for.643fn make_menu(self a: &var AppKit) {644 const o = &a.o;645 const bar = o.make(o.class(&"NSMenu"));646 const holder = o.make(o.class(&"NSMenuItem"));647 o.call_with(bar, &"addItem:", holder);648 const menu = o.make(o.class(&"NSMenu"));649 const name = &a.window.title.view();650 a.menu_item(menu, &f"Hide {name}".view(), &"hide:", &"h", 1 << 20);651 a.menu_item(menu, &"Hide Others", &"hideOtherApplications:", &"h", (1 << 20) | (1 << 19));652 a.menu_item(menu, &"Show All", &"unhideAllApplications:", &"", 0);653 o.call_with(menu, &"addItem:", o.call(o.class(&"NSMenuItem"), &"separatorItem"));654 a.menu_item(menu, &f"Quit {name}".view(), &"terminate:", &"q", 1 << 20);655 o.call_with(holder, &"setSubmenu:", menu);656 const edit_holder = o.make(o.class(&"NSMenuItem"));657 o.call_with(bar, &"addItem:", edit_holder);658 const edit = o.call_with(659 o.call(o.class(&"NSMenu"), &"alloc"),660 &"initWithTitle:",661 o.string(&"Edit")662 );663 a.menu_item(edit, &"Cut", &"cut:", &"x", 1 << 20);664 a.menu_item(edit, &"Copy", &"copy:", &"c", 1 << 20);665 a.menu_item(edit, &"Paste", &"paste:", &"v", 1 << 20);666 a.menu_item(edit, &"Select All", &"selectAll:", &"a", 1 << 20);667 o.call_with(edit_holder, &"setSubmenu:", edit);668 o.call_with(a.app, &"setMainMenu:", bar);669 o.release(edit);670 o.release(edit_holder);671 o.release(menu);672 o.release(holder);673 o.release(bar);674}675676fn menu_item(677 self a: &AppKit,678 menu: c_pointer,679 title: &[u8],680 action: &[u8],681 key: &[u8],682 modifiers: u64683) {684 const o = &a.o;685 const init_item = o.send<extern (686 c_pointer,687 c_pointer,688 c_pointer,689 c_pointer,690 c_pointer691 ) -> c_pointer>();692 const item = init_item(693 o.call(o.class(&"NSMenuItem"), &"alloc"),694 o.sel(&"initWithTitle:action:keyEquivalent:"),695 o.string(&title),696 o.sel(&action),697 o.string(&key)698 );699 o.call_integer(item, &"setKeyEquivalentModifierMask:", modifiers);700 o.call_with(menu, &"addItem:", item);701 o.release(item);702}703704/* --- Waking and pacing --- */705706// A run loop source on the main thread, whose `perform` runs there once707// another thread signals it (CFRunLoopSourceContext, version 0).708fn source(self a: &AppKit, perform: extern (c_pointer)) -> c_pointer {709 var context: [c_pointer : 10] = [0 : 10];710 context[1] = a.cell;711 context[9] = perform as c_pointer;712 const source = a.f.create_source(0, 0, c_pointer::of(&context[..]));713 a.f.add_source(a.run_loop, source, a.f.common_modes);714 return source;715}716717fn make_sources(self a: &var AppKit) {718 a.run_loop = a.f.main_run_loop();719 const woken: extern (c_pointer) = (cell) {720 reach_cell(cell, (a) => a.deliver(&Event::Woken));721 };722 const ticked: extern (c_pointer) = (cell) {723 reach_cell(cell, (a) => a.tick());724 };725 a.wake_source = a.source(woken);726 a.frame_source = a.source(ticked);727 const fired: extern (c_pointer, c_pointer) = (timer, cell) {728 reach_cell(cell, (a) => a.timer_fired());729 };730 // CFRunLoopTimerContext: version, info, retain, release, description731 var context: [c_pointer : 5] = [0 : 5];732 context[1] = a.cell;733 a.timer = a.f.create_timer(734 0,735 a.f.absolute_time() + NEVER,736 NEVER,737 0,738 0,739 fired,740 c_pointer::of(&context[..])741 );742 a.f.add_timer(a.run_loop, a.timer, a.f.common_modes);743 a.window.waker = Waker::AppKit(a.waker_of(a.wake_source));744 // the display link's thread signals the frame source each refresh745 var link: c_pointer = 0;746 if (a.f.create_link(c_pointer::from(&var link)) != 0 || link == 0) {747 return;748 }749 a.link = link;750 a.ticker = lasting(AppKitWaker.size());751 a.ticker.view_var<AppKitWaker>(1)[0] = a.waker_of(a.frame_source);752 const refreshed: extern (c_pointer, c_pointer, c_pointer, u64, c_pointer, c_pointer) -> i32 = (753 link,754 now,755 output,756 flags,757 flags_out,758 ticker759 ) -> i32 {760 ticker.view<AppKitWaker>(1)[0].signal();761 return 0;762 };763 a.f.set_link_callback(link, refreshed, a.ticker);764}765766// Calls `f` with the state the cell holds, from a run loop source,767// which no autorelease pool wraps as AppKit's events are.768fn reach_cell(cell: c_pointer, f: |&| (&var AppKit)) {769 const at = cell.view<c_pointer>(1)[0];770 if (at != 0) {771 const a = &var at.as_var<AppKit>();772 const pool = a.o.pool_push();773 f(&var a);774 a.o.pool_pop(pool);775 }776}777778// What signals the source on the main run loop, from any thread.779fn waker_of(self a: &AppKit, source: c_pointer) -> AppKitWaker => AppKitWaker {780 .signal = a.f.signal_source,781 .wake_up = a.f.wake_up,782 .source = source,783 .run_loop = a.run_loop784};785786// Seconds far enough ahead to stand for never.787const NEVER: f64 = 10000000000.0;788789// Moves the timer's next firing to the program's deadline, or to never.790fn arm_timer(self a: &AppKit) {791 var after = NEVER;792 if (a.window.until_wake() is ::Some |left|) {793 after = left.seconds();794 }795 a.f.set_fire_date(a.timer, a.f.absolute_time() + after);796}797798fn timer_fired(self a: &var AppKit) {799 if (a.window.take_due()) {800 a.deliver(&Event::Timer);801 } else {802 a.arm_timer();803 }804}805806// A refresh of the display: the frame asked for, or the link stopped807// when none is.808fn tick(self a: &var AppKit) {809 if (!a.frame_wanted) {810 if (a.linked) {811 a.f.stop_link(a.link);812 a.linked = false;813 }814 return;815 }816 a.frame_wanted = false;817 a.paint();818}819820/* --- Events --- */821822// Gives the event to the handler, then does what it asked.823fn deliver(self a: &var AppKit, event: &Event) {824 if (a.closed) {825 return;826 }827 a.window.apply(&event);828 a.handler(&var a.window, &event);829 const o = &a.o;830 var asked = a.window.take_requests();831 for (asked.starting.view()) |&start| {832 if (start is ::AppKit |f|) {833 f(&var a);834 }835 }836 if (asked.title) {837 o.call_with(a.ns_window, &"setTitle:", o.string(&a.window.title.view()));838 }839 if (asked.cursor && a.inside) {840 a.show_cursor();841 }842 if (asked.text_input) {843 a.text_input_moved();844 }845 a.update_secure_input();846 if (asked.wake && a.timer != 0) {847 a.arm_timer();848 }849 if (a.window.presented && !a.painting) {850 a.window.presented = false;851 a.show_frame();852 }853 if (a.window.redraw_requested && !a.painting) {854 a.window.redraw_requested = false;855 a.want_frame();856 }857 if (asked.clipboard is ::Some |&text|) {858 a.write_clipboard(&text.view());859 }860 if (a.parts.access is ::Some |give|) {861 give(&var a, &var asked);862 }863 if (a.parts.dialogs is ::Some |show|) {864 show(&var a, &var asked);865 }866 if (asked.clipboard_wanted && !a.closed) {867 a.deliver(&Event::Clipboard(a.read_clipboard()));868 }869 if (asked.close && !a.closed) {870 a.close();871 }872}873874// Asks the display link for the next refresh.875fn want_frame(self a: &var AppKit) {876 a.frame_wanted = true;877 if (a.link == 0) {878 // no display link: the frame comes at once879 a.waker_of(a.frame_source).signal();880 return;881 }882 if (!a.linked) {883 a.f.start_link(a.link);884 a.linked = true;885 }886}887888// A Redraw, its frame shown.889fn paint(self a: &var AppKit) {890 a.painting = true;891 a.deliver(&Event::Redraw(a.window.now()));892 a.painting = false;893 if (a.window.presented) {894 a.window.presented = false;895 a.show_frame();896 }897 a.window.surface_presented = false;898 if (a.window.redraw_requested) {899 a.window.redraw_requested = false;900 a.want_frame();901 }902}903904// The view's size in pixels, given as Resized and drawn at once (AppKit905// resizes live in a loop of its own), and the scale when it changed.906fn measure(self a: &var AppKit) {907 if (a.view == 0) {908 return;909 }910 const o = &a.o;911 const scale = o.number(a.ns_window, &"backingScaleFactor") to f32;912 if (scale != a.window.scale) {913 a.deliver(&Event::Scaled(scale));914 }915 const bounds = o.send_struct<extern (c_pointer, c_pointer) -> NSRect>()(916 a.view,917 o.sel(&"bounds")918 );919 const size = Size {920 .width = (bounds.width * scale to f64 + 0.5) to u32,921 .height = (bounds.height * scale to f64 + 0.5) to u32922 };923 if (size.width == 0 || size.height == 0) {924 return;925 }926 if (size != a.window.size || !a.sized) {927 a.sized = true;928 a.deliver(&Event::Resized(size));929 a.frame_wanted = false;930 a.paint();931 }932}933934// Shows the last frame presented as the view's layer's contents: a935// CGImage of a copy of its pixels, 32 bits each, blue first in memory936// with the top byte unused (kCGImageAlphaNoneSkipFirst,937// kCGBitmapByteOrder32Little), as Wayland's and GDI's frames are.938fn show_frame(self a: &AppKit) {939 const frame = a.window.frame_size;940 if (frame.width == 0 || frame.height == 0) {941 return;942 }943 const f = &a.f;944 const bytes = (frame.width to u64) * (frame.height to u64) * 4;945 const data = f.create_data(0, c_pointer::of(&a.window.frame), bytes as i64 to c_ssize);946 const provider = f.provider_from_data(data);947 const space = f.color_space_named(f.srgb);948 const image = f.create_image(949 frame.width to c_size,950 frame.height to c_size,951 8,952 32,953 (frame.width to u64 * 4) to c_size,954 space,955 6 | 0x2000,956 provider,957 0,958 false,959 0960 );961 const layer = a.o.call(a.view, &"layer");962 a.o.call_with(layer, &"setContents:", image);963 f.release_image(image);964 f.release_color_space(space);965 f.release_provider(provider);966 f.release(data);967}968969// Where the event happened in the view, in pixels from its top left.970fn location(self a: &AppKit, event: c_pointer) -> Point {971 const o = &a.o;972 const in_window = o.send<extern (c_pointer, c_pointer) -> NSPoint>()(973 event,974 o.sel(&"locationInWindow")975 );976 const convert = o.send<extern (c_pointer, c_pointer, NSPoint, c_pointer) -> NSPoint>();977 const at = convert(a.view, o.sel(&"convertPoint:fromView:"), in_window, 0);978 const scale = a.window.scale to f64;979 return Point { .x = (at.x * scale) to f32, .y = (at.y * scale) to f32 };980}981982fn pointer_moved(self a: &var AppKit, event: c_pointer) {983 if (!a.inside) {984 a.inside = true;985 a.show_cursor();986 }987 a.position = a.location(event);988 a.deliver(&Event::PointerMoved(a.position));989}990991fn pointer_left(self a: &var AppKit) {992 a.inside = false;993 a.deliver(&Event::PointerLeft);994}995996fn button(self a: &var AppKit, event: c_pointer, pressed: bool) {997 const number = a.o.integer(event, &"buttonNumber");998 const button = match (number) {999 0 PointerButton::Left;1000 1 PointerButton::Right;1001 2 PointerButton::Middle;1002 3 PointerButton::Back;1003 4 PointerButton::Forward;1004 else PointerButton::Other(number to u32);1005 };1006 a.position = a.location(event);1007 const e = Event::Button(ButtonEvent {1008 .button = button,1009 .pressed = pressed,1010 .position = a.position,1011 .modifiers = a.modifiers(event)1012 });1013 a.deliver(&e);1014}10151016// A wheel's notches as lines, a touchpad's movement in pixels; macOS1017// gives them positive up and left, as the content moves.1018fn scroll(self a: &var AppKit, event: c_pointer) {1019 const o = &a.o;1020 const precise = o.boolean(event, &"hasPreciseScrollingDeltas");1021 const x = o.number(event, &"scrollingDeltaX");1022 const y = o.number(event, &"scrollingDeltaY");1023 const unit = if (precise) a.window.scale to f64 else 1.0;1024 const e = Event::Scroll(ScrollEvent {1025 .delta = Point { .x = (-x * unit) to f32, .y = (-y * unit) to f32 },1026 .precise = precise,1027 .modifiers = a.modifiers(event)1028 });1029 a.deliver(&e);1030}10311032// NSEventModifierFlagShift, Control, Option, Command1033fn modifiers(self a: &AppKit, event: c_pointer) -> Modifiers {1034 const flags = a.o.integer(event, &"modifierFlags");1035 return Modifiers {1036 .shift = (flags & (1 << 17)) != 0,1037 .control = (flags & (1 << 18)) != 0,1038 .alt = (flags & (1 << 19)) != 0,1039 .super = (flags & (1 << 20)) != 01040 };1041}10421043fn key(self a: &var AppKit, event: c_pointer, pressed: bool) {1044 const o = &a.o;1045 const code = o.send<extern (c_pointer, c_pointer) -> u16>()(event, o.sel(&"keyCode"));1046 const modifiers = a.modifiers(event);1047 var key = key_of(code);1048 if (key is ::Unknown) {1049 // the character the key writes without modifiers, lower case1050 const plain = o.text_of(o.call(event, &"charactersIgnoringModifiers"));1051 const c = first_character(&plain.view());1052 if (c >= 32 && c != 127 && !(c >= 0xF700 && c <= 0xF8FF)) {1053 key = Key::Character(if (c >= 'A' && c <= 'Z') c + 32 else c);1054 }1055 }1056 // a key pressed while an input method composes is the input1057 // method's1058 if (pressed && a.composing && !modifiers.super && a.composes()) {1059 a.interpret(event);1060 return;1061 }1062 const e = Event::Key(KeyEvent {1063 .key = key,1064 .pressed = pressed,1065 .repeat = pressed && o.boolean(event, &"isARepeat"),1066 .modifiers = modifiers1067 });1068 a.deliver(&e);1069 if (!pressed || modifiers.super || modifiers.control || a.closed) {1070 return;1071 }1072 // text typed: through the input method while the program takes text1073 // (insertText:, setMarkedText:), else the key's characters, as a1074 // password's are, nothing composed1075 if (a.composes()) {1076 a.interpret(event);1077 return;1078 }1079 var text = printable(&o.text_of(o.call(event, &"characters")).view());1080 if (text.length() > 0) {1081 a.deliver(&Event::Text(move text));1082 }1083}10841085// Gives the key to the input method, which calls the view back.1086fn interpret(self a: &AppKit, event: c_pointer) {1087 const events: [c_pointer : 1] = [event];1088 a.o.call_with(a.view, &"interpretKeyEvents:", array(&a.o, &events[..]));1089}10901091// The text's characters but control characters and the function keys'1092// private ones.1093fn printable(bytes: &[u8]) -> String {1094 var text = String::empty();1095 var at: u64 = 0;1096 while (at < bytes.length()) {1097 const length = utf8_length(bytes[at]);1098 const end = if (at + length > bytes.length()) bytes.length() else at + length;1099 const c = first_character(&bytes[at..end]);1100 if (c >= 32 && c != 127 && !(c >= 0xF700 && c <= 0xF8FF)) {1101 text.append(&bytes[at..end]);1102 }1103 at = end;1104 }1105 return move text;1106}11071108// An Edit menu command, as its key with Command pressed and released.1109fn command(self a: &var AppKit, c: u32) {1110 const modifiers = Modifiers { .shift = false, .control = false, .alt = false, .super = true };1111 a.deliver(&Event::Key(KeyEvent {1112 .key = Key::Character(c),1113 .pressed = true,1114 .repeat = false,1115 .modifiers = modifiers1116 }));1117 a.deliver(&Event::Key(KeyEvent {1118 .key = Key::Character(c),1119 .pressed = false,1120 .repeat = false,1121 .modifiers = modifiers1122 }));1123}11241125/* --- Input methods --- */11261127// Text the input method commits, ending its composition.1128fn insert_text(self a: &var AppKit, text: c_pointer) {1129 var typed = printable(&plain_text(&a.o, text).view());1130 a.end_composition();1131 if (typed.length() > 0) {1132 a.deliver(&Event::Text(move typed));1133 }1134}11351136// The composition in progress, its caret at the end of the input1137// method's selection in it.1138fn mark_text(self a: &var AppKit, text: c_pointer, selected: NSRange) {1139 var marked = plain_text(&a.o, text);1140 if (marked.length() == 0 && !a.composing) {1141 return;1142 }1143 a.composing = marked.length() > 0;1144 a.marked = copy marked;1145 const cursor = utf8_offset(&marked.view(), selected.location + selected.length);1146 a.deliver(&Event::Preedit(Preedit { .text = move marked, .cursor = cursor }));1147}11481149// The input method gives up its composition, which is typed as it is.1150fn unmark_text(self a: &var AppKit) {1151 if (!a.composing) {1152 return;1153 }1154 var typed = move a.marked;1155 a.marked = String::empty();1156 a.end_composition();1157 if (typed.length() > 0) {1158 a.deliver(&Event::Text(move typed));1159 }1160}11611162fn end_composition(self a: &var AppKit) {1163 if (a.composing) {1164 a.composing = false;1165 a.marked = String::empty();1166 a.deliver(&Event::Preedit(Preedit { .text = String::empty(), .cursor = 0 }));1167 }1168}11691170// The program took or stopped taking text, or its text input moved: a1171// composition is dropped when it stops, and the input method looks again1172// for where the candidates go.1173fn text_input_moved(self a: &var AppKit) {1174 const context = a.o.call(a.view, &"inputContext");1175 if (!a.composes()) {1176 if (a.composing) {1177 if (context != 0) {1178 a.o.call(context, &"discardMarkedText");1179 }1180 a.end_composition();1181 }1182 return;1183 }1184 if (context != 0) {1185 a.o.call(context, &"invalidateCharacterCoordinates");1186 }1187}11881189// Whether keys go through the input method: while the program takes1190// text, but for a password.1191fn composes(self a: &AppKit) -> bool => a.window.text_input is ::Some && !a.window.secret_input;11921193// Secure event input while a password's field takes text in the focused1194// window, as NSSecureTextField has it: no other program reads the keys1195// meanwhile.1196fn update_secure_input(self a: &var AppKit) {1197 const wanted = a.window.secret_input1198 && a.window.text_input is ::Some1199 && a.window.focused1200 && !a.closed;1201 if (wanted != a.secure) {1202 if (wanted) {1203 a.f.enable_secure_input();1204 } else {1205 a.f.disable_secure_input();1206 }1207 a.secure = wanted;1208 }1209}12101211// The text input's area on the screen, where the candidates go.1212fn caret_rect(self a: &AppKit) -> NSRect {1213 const area = if (a.window.text_input is ::Some |area|) area else Area {1214 .x = 0.0,1215 .y = 0.0,1216 .width = 0.0,1217 .height = 0.01218 };1219 return screen_rect(&a.o, a.view, a.ns_window, &area);1220}12211222// A modifier key pressed or released: whether its flag is now set.1223fn flags_changed(self a: &var AppKit, event: c_pointer) {1224 const o = &a.o;1225 const code = o.send<extern (c_pointer, c_pointer) -> u16>()(event, o.sel(&"keyCode"));1226 const flags = o.integer(event, &"modifierFlags");1227 // Shift, Control, Option, Command, Caps Lock: their flag1228 const flag: u64 = match (code) {1229 56, 60 1 << 17;1230 59, 62 1 << 18;1231 58, 61 1 << 19;1232 55, 54 1 << 20;1233 57 1 << 16;1234 else 0;1235 };1236 if (flag == 0) {1237 return;1238 }1239 const e = Event::Key(KeyEvent {1240 .key = key_of(code),1241 .pressed = (flags & flag) != 0,1242 .repeat = false,1243 .modifiers = a.modifiers(event)1244 });1245 a.deliver(&e);1246}12471248// The keys of macOS's virtual key codes (Events.h's kVK_ constants) that1249// write no character.1250fn key_of(code: u16) -> Key {1251 return match (code) {1252 36, 76 Key::Enter;1253 53 Key::Escape;1254 51 Key::Backspace;1255 48 Key::Tab;1256 117 Key::Delete;1257 114 Key::Insert;1258 123 Key::Left;1259 124 Key::Right;1260 126 Key::Up;1261 125 Key::Down;1262 115 Key::Home;1263 119 Key::End;1264 116 Key::PageUp;1265 121 Key::PageDown;1266 56, 60 Key::Shift;1267 59, 62 Key::Control;1268 58, 61 Key::Alt;1269 55, 54 Key::Super;1270 57 Key::CapsLock;1271 110 Key::Menu; // kVK_ContextualMenu1272 49 Key::Character(' ');1273 122 Key::Function(1);1274 120 Key::Function(2);1275 99 Key::Function(3);1276 118 Key::Function(4);1277 96 Key::Function(5);1278 97 Key::Function(6);1279 98 Key::Function(7);1280 100 Key::Function(8);1281 101 Key::Function(9);1282 109 Key::Function(10);1283 103 Key::Function(11);1284 111 Key::Function(12);1285 105 Key::Function(13);1286 107 Key::Function(14);1287 113 Key::Function(15);1288 106 Key::Function(16);1289 else Key::Unknown(code to u32);1290 };1291}12921293// The text's first character as a code point, 0 for none.1294fn first_character(text: &[u8]) -> u32 {1295 if (text.length() == 0 || utf8_length(text[0]) > text.length()) {1296 return 0;1297 }1298 return code_at(&text, 0);1299}13001301// Shows the window's cursor: NSCursor's arrow, pointing hand or I-beam.1302fn show_cursor(self a: &AppKit) {1303 const o = &a.o;1304 const name: &[u8] = match (a.window.cursor) {1305 ::Arrow &"arrowCursor";1306 ::Hand &"pointingHandCursor";1307 ::Text &"IBeamCursor";1308 };1309 o.call(o.call(o.class(&"NSCursor"), &name), &"set");1310}13111312/* --- The clipboard, dialogs and drops --- */13131314fn pasteboard(self a: &AppKit) -> c_pointer {1315 return a.o.call(a.o.class(&"NSPasteboard"), &"generalPasteboard");1316}13171318fn write_clipboard(self a: &AppKit, text: &[u8]) {1319 const o = &a.o;1320 const board = a.pasteboard();1321 o.integer(board, &"clearContents");1322 o.send<extern (c_pointer, c_pointer, c_pointer, c_pointer) -> bool>()(1323 board,1324 o.sel(&"setString:forType:"),1325 o.string(&text),1326 a.string_type1327 );1328}13291330// The clipboard's text; empty when it holds none.1331fn read_clipboard(self a: &AppKit) -> String {1332 return a.o.text_of(a.o.call_with(a.pasteboard(), &"stringForType:", a.string_type));1333}13341335// Shows the panel modal and gives the files chosen, none when cancelled.1336fn show_dialog(self a: &AppKit, asked: &DialogRequest) -> Vector<ChosenFile> {1337 const o = &a.o;1338 var files = Vector<ChosenFile>::empty();1339 const panel = if (asked.save) o.call(o.class(&"NSSavePanel"), &"savePanel") else o.call(1340 o.class(&"NSOpenPanel"),1341 &"openPanel"1342 );1343 if (panel == 0) {1344 return move files;1345 }1346 const d = &asked.dialog;1347 if (d.title.length() > 0) {1348 o.call_with(panel, &"setTitle:", o.string(&d.title.view()));1349 o.call_with(panel, &"setMessage:", o.string(&d.title.view()));1350 }1351 // the filters' extensions, unless one takes any file1352 var extensions = Vector<c_pointer>::empty();1353 var any = false;1354 for (d.filters.view()) |&filter| {1355 for (filter.patterns.view()) |&pattern| {1356 const p = &pattern.view();1357 if (p.length() > 2 && p[..2] == "*." && p[2..] != "*") {1358 extensions.push(o.string(&p[2..]));1359 } else {1360 any = true;1361 }1362 }1363 }1364 if (extensions.length() > 0 && !any) {1365 o.call_with(panel, &"setAllowedFileTypes:", array(&o, &extensions.view()));1366 }1367 if (asked.save) {1368 if (d.name.length() > 0) {1369 o.call_with(panel, &"setNameFieldStringValue:", o.string(&d.name.view()));1370 }1371 } else {1372 o.call_bool(panel, &"setCanChooseFiles:", true);1373 o.call_bool(panel, &"setCanChooseDirectories:", false);1374 o.call_bool(panel, &"setAllowsMultipleSelection:", d.multiple);1375 }1376 // NSModalResponseOK1377 if (o.integer(panel, &"runModal") != 1) {1378 return move files;1379 }1380 if (asked.save) {1381 const url = o.call(panel, &"URL");1382 if (url != 0) {1383 files.push(ChosenFile::at(PathStyle::Unix, &o.text_of(o.call(url, &"path")).view()));1384 }1385 } else {1386 const urls = o.call(panel, &"URLs");1387 for ([..o.integer(urls, &"count")]) |k| {1388 const url = object_at(&o, urls, k);1389 files.push(ChosenFile::at(PathStyle::Unix, &o.text_of(o.call(url, &"path")).view()));1390 }1391 }1392 return move files;1393}13941395// Whether the pasteboard holds the type.1396fn holds(self a: &AppKit, board: c_pointer, kind: c_pointer) -> bool {1397 const kinds: [c_pointer : 1] = [kind];1398 return a.o.call_with(board, &"availableTypeFromArray:", array(&a.o, &kinds[..])) != 0;1399}14001401// Where the drag is in the view, in pixels.1402fn drag_position(self a: &AppKit, info: c_pointer) -> Point {1403 const o = &a.o;1404 const at = o.send<extern (c_pointer, c_pointer) -> NSPoint>()(info, o.sel(&"draggingLocation"));1405 return window_point(&o, a.view, a.ns_window, at);1406}14071408// Something dragged came over the view: copied when it holds files or1409// text (NSDragOperationCopy).1410fn drag_entered(self a: &var AppKit, info: c_pointer) -> u64 {1411 const board = a.o.call(info, &"draggingPasteboard");1412 const files = a.holds(board, a.file_url_type);1413 const text = a.holds(board, a.string_type);1414 a.drag_accepted = files || text;1415 a.deliver(&Event::DragEntered(Dragged {1416 .position = a.drag_position(info),1417 .files = files,1418 .text = text1419 }));1420 return if (a.drag_accepted) 1 else 0;1421}14221423fn drag_moved(self a: &var AppKit, info: c_pointer) -> u64 {1424 a.deliver(&Event::DragMoved(a.drag_position(info)));1425 return if (a.drag_accepted) 1 else 0;1426}14271428// What was dropped: its files if it has some, else its text.1429fn dropped(self a: &var AppKit, info: c_pointer) -> bool {1430 const o = &a.o;1431 const board = o.call(info, &"draggingPasteboard");1432 var drop = Drop {1433 .position = a.drag_position(info),1434 .files = Vector<ChosenFile>::empty(),1435 .text = ::None1436 };1437 const classes: [c_pointer : 1] = [o.class(&"NSURL")];1438 const read = o.send<extern (c_pointer, c_pointer, c_pointer, c_pointer) -> c_pointer>();1439 const urls = read(1440 board,1441 o.sel(&"readObjectsForClasses:options:"),1442 array(&o, &classes[..]),1443 01444 );1445 if (urls != 0) {1446 for ([..o.integer(urls, &"count")]) |k| {1447 const url = object_at(&o, urls, k);1448 // Finder's are file reference URLs, as paths through filePathURL1449 const file = if (o.boolean(url, &"isFileURL")) o.call(url, &"filePathURL") else 0;1450 if (file != 0) {1451 drop.files.push(ChosenFile::at(1452 PathStyle::Unix,1453 &o.text_of(o.call(file, &"path")).view()1454 ));1455 }1456 }1457 }1458 if (drop.files.length() == 0 && a.holds(board, a.string_type)) {1459 drop.text = ::Some(o.text_of(o.call_with(board, &"stringForType:", a.string_type)));1460 }1461 const taken = drop.files.length() > 0 || drop.text is ::Some;1462 a.deliver(&Event::Dropped(move drop));1463 return taken;1464}14651466/* --- What a program installs --- */14671468// Answers VoiceOver: the view's accessibility methods and the elements'1469// class, made now, and a source its calls signal once they return.1470pub fn start_voiceover(a: &var AppKit) {1471 const appkit = if (framework(&"AppKit") is ::Some |l|) l else {1472 return;1473 };1474 a.access = ::Some(MacAccess::create(1475 &a.o,1476 address_of(&appkit, &"NSAccessibilityPostNotification"),1477 address_of(&appkit, &"NSAccessibilityPostNotificationWithUserInfo"),1478 pointer_at(&appkit, &"NSAccessibilityLanguageTextAttribute"),1479 AppKitWaker { .signal = 0, .wake_up = 0, .source = 0, .run_loop = 0 }1480 ));1481 const acted: extern (c_pointer) = (cell) {1482 reach_cell(cell, (a) => a.acted());1483 };1484 a.access_source = a.source(acted);1485 const source = a.waker_of(a.access_source);1486 if (a.access is ::Some |&var m|) {1487 m.view = a.view;1488 m.window = a.ns_window;1489 m.source = source;1490 a.cell.view_var<c_pointer>(2)[1] = c_pointer::from(&var m);1491 }1492 make_access_classes(&a.o, a.o.class(&"AlloyView"), a.cell);1493 a.parts.access = ::Some(give_voiceover);1494 a.parts.access_ended = ::Some(end_voiceover);1495}14961497// What VoiceOver asked, once its call returned: the program's tree, then1498// actions on its nodes.1499fn acted(self a: &var AppKit) {1500 var asked = false;1501 var actions = Vector<ActionRequest>::empty();1502 if (a.access is ::Some |&var m|) {1503 asked = m.asked;1504 m.asked = false;1505 // each action asked for signals this again1506 actions = move m.actions;1507 m.actions = Vector<ActionRequest>::empty();1508 }1509 if (asked) {1510 a.deliver(&Event::AccessRequested);1511 }1512 for (actions.items()) |&var action| {1513 a.deliver(&Event::Action(move action));1514 }1515}15161517// Gives VoiceOver the view's direction, which it reads the view's1518// elements by (a text's language goes with its attributes, F14b), the1519// tree's updates and what to say.1520fn give_voiceover(a: &var AppKit, asked: &var Requests) {1521 if (asked.language) {1522 a.o.call_integer(1523 a.view,1524 &"setUserInterfaceLayoutDirection:",1525 if (a.window.right_to_left) 1 else 01526 );1527 }1528 if (a.access is ::Some |&var m|) {1529 for (asked.access.items()) |&var update| {1530 m.update(move update);1531 }1532 for (asked.announcements.view()) |&said| {1533 m.announce(&said.text, said.assertive);1534 }1535 }1536}15371538fn end_voiceover(a: &var AppKit) {1539 a.f.invalidate_source(a.access_source);1540 a.cell.view_var<c_pointer>(2)[1] = 0;1541 if (a.access is ::Some |&var m|) {1542 m.close();1543 }1544}15451546// Takes files and text dragged over the view and shows NSOpenPanel and1547// NSSavePanel.1548pub fn start_files_appkit(a: &var AppKit) {1549 add_drag_methods(&a.o, a.o.class(&"AlloyView"), a.cell);1550 const dragged: [c_pointer : 2] = [a.file_url_type, a.string_type];1551 a.o.call_with(a.view, &"registerForDraggedTypes:", array(&a.o, &dragged[..]));1552 a.parts.dialogs = ::Some(show_panels);1553}15541555// A panel's own loop goes on delivering events meanwhile, which may ask1556// for more dialogs: those wait for it.1557fn show_panels(a: &var AppKit, asked: &var Requests) {1558 for (asked.dialogs.items()) |&var dialog| {1559 a.dialogs.push(move dialog);1560 }1561 if (!a.showing_dialog) {1562 a.showing_dialog = true;1563 var k: u64 = 0;1564 while (k < a.dialogs.length() && !a.closed) {1565 const dialog = copy a.dialogs.get(k);1566 k += 1;1567 var files = a.show_dialog(&dialog);1568 a.deliver(&Event::FilesChosen(Chosen { .request = dialog.id, .files = move files }));1569 }1570 a.dialogs.clear();1571 a.showing_dialog = false;1572 }1573}15741575/* --- Closing --- */15761577// Closes the window and ends AppKit's loop: `stop:` takes effect after1578// the next event, so one is posted.1579fn close(self a: &var AppKit) {1580 a.closed = true;1581 const o = &a.o;1582 if (a.linked) {1583 a.f.stop_link(a.link);1584 a.linked = false;1585 }1586 o.call(a.ns_window, &"close");1587 o.call_with(a.app, &"stop:", 0);1588 const make_event = o.send<extern (1589 c_pointer,1590 c_pointer,1591 u64,1592 NSPoint,1593 u64,1594 f64,1595 i64,1596 c_pointer,1597 i16,1598 i64,1599 i641600 ) -> c_pointer>();1601 // NSEventTypeApplicationDefined1602 const event = make_event(1603 o.class(&"NSEvent"),1604 o.sel(1605 &"otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:"1606 ),1607 15,1608 NSPoint { .x = 0.0, .y = 0.0 },1609 0,1610 0.0,1611 0,1612 0,1613 0,1614 0,1615 01616 );1617 o.send<extern (c_pointer, c_pointer, c_pointer, bool)>()(1618 a.app,1619 o.sel(&"postEvent:atStart:"),1620 event,1621 true1622 );1623}16241625// What the window held, released once AppKit's loop has returned. The1626// sources stay allocated, invalidated, for Wakers other tasks may still1627// hold; the display link's callback is stopped first.1628fn finish(self a: &var AppKit) {1629 const o = &a.o;1630 if (a.secure) {1631 a.f.disable_secure_input();1632 a.secure = false;1633 }1634 if (a.link != 0) {1635 a.f.stop_link(a.link);1636 a.f.release_link(a.link);1637 }1638 a.f.invalidate_source(a.wake_source);1639 a.f.invalidate_source(a.frame_source);1640 if (a.timer != 0) {1641 a.f.invalidate_timer(a.timer);1642 a.f.release(a.timer);1643 }1644 if (a.parts.access_ended is ::Some |ended|) {1645 ended(&var a);1646 }1647 o.call_with(a.ns_window, &"setDelegate:", 0);1648 o.call_with(a.app, &"setDelegate:", 0);1649 o.release(a.view);1650 o.release(a.ns_window);1651 o.release(a.window_delegate);1652 o.release(a.app_delegate);1653}