ui

source of pkg::alloy::window::nsaccessibility

1// VoiceOver for the macOS window (PLAN.md, F7c), through2// NSAccessibility: the view stands for the tree's root and every other3// node gets an element, an AlloyAccessibilityElement (a subclass of4// NSAccessibilityElement made here) holding the node's id, made as5// VoiceOver reaches it and released once the node is gone. The view's6// and the elements' methods answer from the tree the program sent; a7// node of no role is left out, its children standing in for it. The8// first question about the view asks the program for its tree, and what9// VoiceOver asks of a node is queued for the window to give the program10// once the call returns, as on Windows; changes to the tree post11// NSAccessibility's notifications. A grid's cells go into rows made12// from their own, elements standing for no node. A node sent with a13// map of its text answers lines, ranges, their frames and attributed14// strings from it (text_ranges.alloy), in UTF-16 units.1516import std::ffi;17import std::map;18import std::math;19import std::option;20import std::string;21import std::vector;2223import window;24import unicode;25import text_ranges;26import cocoa;27import pkg::alloy::objc;2829pub type MacAccess = struct {30    pub o: Objc,31    pub post: extern (c_pointer, c_pointer), // NSAccessibilityPostNotification32    // NSAccessibilityPostNotificationWithUserInfo33    pub post_with_info: extern (c_pointer, c_pointer, c_pointer),34    pub language: c_pointer, // NSAccessibilityLanguageTextAttribute35    pub view: c_pointer,36    pub window: c_pointer,37    pub requested: bool, // whether the program was asked for its tree38    pub asked: bool, // whether that question waits for the window39    pub tree: AccessTree,40    pub elements: Map<u64, c_pointer>,41    // what VoiceOver asked, for the window to give the program42    pub actions: Vector<ActionRequest>,43    // the run loop source the window gives them from44    pub source: AppKitWaker,45    // the elements of grids' rows46    pub rows: Vector<RowElement>,47};4849// A grid's row, an element of its own holding the grid's cells of that50// row.51pub type RowElement = struct {52    pub grid: u64,53    pub row: u32,54    pub element: c_pointer,55};5657pub fn MacAccess::create(58    o: &Objc,59    post: c_pointer,60    post_with_info: c_pointer,61    language: c_pointer,62    source: AppKitWaker63) -> MacAccess {64    return MacAccess {65        .o = copy o,66        .post = copy post as extern (c_pointer, c_pointer),67        .post_with_info = copy post_with_info as extern (c_pointer, c_pointer, c_pointer),68        .language = language,69        .view = 0,70        .window = 0,71        .requested = false,72        .asked = false,73        .tree = AccessTree::empty(),74        .elements = Map<u64, c_pointer>::empty(),75        .actions = Vector<ActionRequest>::empty(),76        .source = source,77        .rows = Vector<RowElement>::empty()78    };79}8081// The state a class's block reaches, 0 once the window is gone: the82// second of the cell's pointers.83fn reached(block: c_pointer) -> c_pointer => block_state(block).view<c_pointer>(2)[1];8485// What `f` answers from the window's accessibility, or `absent` once the86// window is gone.87fn with_access<T>(block: c_pointer, absent: T, f: |&| (&var MacAccess) -> T) -> T {88    const at = reached(block);89    if (at == 0) {90        return move absent;91    }92    return f(&var at.as_var<MacAccess>());93}9495const NIL: c_pointer = 0;9697// The view's accessibility methods, added before its class is98// registered, and the elements' class.99pub fn make_access_classes(o: &Objc, view: c_pointer, cell: c_pointer) {100    const b = &bool_code();101    const yes: extern (c_pointer, c_pointer) -> bool = (block, this) => true;102    const view_children: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(103        block,104        NIL,105        (m) -> c_pointer {106            m.reader_came();107            return m.children_of(m.tree.root);108        }109    );110    const view_role: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(111        block,112        NIL,113        (m) => m.o.string(&"AXGroup")114    );115    const view_label: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(116        block,117        NIL,118        (m) -> c_pointer {119            if (m.tree.nodes.try_get(&m.tree.root) is ::Some |&root|) {120                return m.o.string(&root.semantics.label.view());121            }122            return m.o.call(m.window, &"title");123        }124    );125    const focused: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(126        block,127        this,128        (m) -> c_pointer {129            m.reader_came();130            if (m.tree.focus is ::Some |focus| && m.tree.nodes.contains(&focus)) {131                return m.element(focus);132            }133            return this;134        }135    );136    const hit: extern (137        c_pointer,138        c_pointer,139        NSPoint140    ) -> c_pointer = (block, this, at_screen) => with_access(block, this, (m) -> c_pointer {141        const point = view_point(&m.o, m.view, m.window, at_screen);142        return if (m.hit(m.tree.root, point) is ::Some |found|) m.element(found) else this;143    });144    o.method_with(view, &"accessibilityChildren", &"@@:", view_children, cell);145    o.method_with(view, &"isAccessibilityElement", &f"{b}@:".view(), yes, cell);146    o.method_with(view, &"accessibilityRole", &"@@:", view_role, cell);147    o.method_with(view, &"accessibilityLabel", &"@@:", view_label, cell);148    o.method_with(view, &"accessibilityFocusedUIElement", &"@@:", focused, cell);149    o.method_with(view, &"accessibilityHitTest:", &f"@@:{POINT_CODE}".view(), hit, cell);150151    const element = o.subclass(&"AlloyAccessibilityElement", o.class(&"NSAccessibilityElement"));152    if (!element.is_new) {153        return;154    }155    const e = element.class;156    o.add_state(e);157    const role: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(158        block,159        NIL,160        (m) => m.role(this)161    );162    const label: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(163        block,164        NIL,165        (m) => m.label(this)166    );167    const value: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(168        block,169        NIL,170        (m) => m.value(this)171    );172    const minimum: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(173        block,174        NIL,175        (m) => m.limit(this, false)176    );177    const maximum: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(178        block,179        NIL,180        (m) => m.limit(this, true)181    );182    const parent: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(183        block,184        NIL,185        (m) => m.parent(this)186    );187    const children: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(188        block,189        NIL,190        (m) -> c_pointer {191            if (m.row_of(this) is ::Some |r|) {192                return m.row_cells(r[0], r[1] to u32);193            }194            return m.children_of(m.id_of(this));195        }196    );197    const rows: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(198        block,199        NIL,200        (m) -> c_pointer {201            if (m.node(this) is ::Some |&node| && node.semantics.role is ::Grid) {202                return m.children_of(node.id);203            }204            return NIL;205        }206    );207    const row_count: extern (c_pointer, c_pointer) -> i64 = (block, this) => with_access(208        block,209        0 to i64,210        (m) => m.grid_size(this)[0] to i64211    );212    const column_count: extern (c_pointer, c_pointer) -> i64 = (block, this) => with_access(213        block,214        0 to i64,215        (m) => m.grid_size(this)[1] to i64216    );217    const row_range: extern (c_pointer, c_pointer) -> NSRange = (block, this) => with_access(218        block,219        NSRange { .location = 0, .length = 0 },220        (m) => m.index_range(this, false)221    );222    const column_range: extern (c_pointer, c_pointer) -> NSRange = (block, this) => with_access(223        block,224        NSRange { .location = 0, .length = 0 },225        (m) => m.index_range(this, true)226    );227    const window: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(228        block,229        NIL,230        (m) => m.window231    );232    const frame: extern (c_pointer, c_pointer) -> NSRect = (block, this) => with_access(233        block,234        NSRect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 },235        (m) => m.frame(this)236    );237    const is_focused: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(238        block,239        false,240        (m) => m.tree.focus == ::Some(m.id_of(this))241    );242    const is_enabled: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(243        block,244        false,245        (m) -> bool {246            if (m.node(this) is ::Some |&node|) {247                return !node.semantics.disabled;248            }249            return false;250        }251    );252    const press: extern (c_pointer, c_pointer) -> bool = (block, this) => ask(253        block,254        this,255        Action::Click256    );257    const increment: extern (c_pointer, c_pointer) -> bool = (block, this) => ask(258        block,259        this,260        Action::Increment261    );262    const decrement: extern (c_pointer, c_pointer) -> bool = (block, this) => ask(263        block,264        this,265        Action::Decrement266    );267    const set_value: extern (c_pointer, c_pointer, c_pointer) = (block, this, given) {268        const at = reached(block);269        if (at != 0) {270            var text = at.as_var<MacAccess>().text_of_value(given);271            ask(block, this, Action::SetValue(move text));272        }273    };274    const set_focused: extern (c_pointer, c_pointer, bool) = (block, this, focus) {275        if (focus) {276            ask(block, this, Action::Focus);277        }278    };279    const selected: extern (c_pointer, c_pointer) -> NSRange = (block, this) => with_access(280        block,281        NSRange { .location = 0, .length = 0 },282        (m) => m.selected(this)283    );284    const select: extern (c_pointer, c_pointer, NSRange) = (block, this, range) {285        const at = reached(block);286        if (at != 0) {287            const chosen = at.as_var<MacAccess>().selection_of(this, range);288            ask(block, this, Action::SetSelection(chosen));289        }290    };291    const characters: extern (c_pointer, c_pointer) -> u64 = (block, this) => with_access(292        block,293        0 to u64,294        (m) -> u64 {295            if (m.node(this) is ::Some |&node|) {296                const text = if (297                    node.text is ::Some298                ) &node.mapped_text() else &node.semantics.value.view();299                return utf16_offset(&text, text.length());300            }301            return 0;302        }303    );304    const line_number: extern (c_pointer, c_pointer) -> i64 = (block, this) => with_access(305        block,306        -1 to i64,307        (m) -> i64 {308            if (m.text_node(this) is ::Some |&node| && node.semantics.selection is ::Some |s|) {309                return map_of(&node).line_of(s[1] to u32) to i64;310            }311            return -1;312        }313    );314    const line_for_index: extern (c_pointer, c_pointer, i64) -> i64 = (315        block,316        this,317        index318    ) => with_access(block, -1 to i64, (m) -> i64 {319        if (m.text_node(this) is ::Some |&node| && index >= 0) {320            const at = utf8_offset(&node.mapped_text(), index to u64);321            return map_of(&node).line_of(at to u32) to i64;322        }323        return -1;324    });325    const range_for_line: extern (c_pointer, c_pointer, i64) -> NSRange = (326        block,327        this,328        line329    ) => with_access(330        block,331        NSRange { .location = NOT_FOUND, .length = 0 },332        (m) => m.line_range(this, line)333    );334    const string_for_range: extern (c_pointer, c_pointer, NSRange) -> c_pointer = (335        block,336        this,337        range338    ) => with_access(block, NIL, (m) -> c_pointer {339        if (m.text_node(this) is ::Some |&node|) {340            const text = &node.mapped_text();341            const ends = bytes_of(&text, range);342            return m.o.string(&text[ends[0] to u64..ends[1] to u64]);343        }344        return NIL;345    });346    const attributed_for_range: extern (c_pointer, c_pointer, NSRange) -> c_pointer = (347        block,348        this,349        range350    ) => with_access(block, NIL, (m) => m.attributed(this, range));351    const frame_for_range: extern (c_pointer, c_pointer, NSRange) -> NSRect = (352        block,353        this,354        range355    ) => with_access(356        block,357        NSRect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 },358        (m) => m.range_frame(this, range)359    );360    const range_for_position: extern (c_pointer, c_pointer, NSPoint) -> NSRange = (361        block,362        this,363        at_screen364    ) => with_access(block, NSRange { .location = NOT_FOUND, .length = 0 }, (m) -> NSRange {365        if (m.text_node(this) is ::Some |&node|) {366            const point = view_point(&m.o, m.view, m.window, at_screen);367            const map = &map_of(&node);368            const x = point.x - node.bounds.x;369            const y = point.y - node.bounds.y;370            if (map.grapheme_at(x, y) is ::Some |g|) {371                const text = &node.mapped_text();372                const unit = map.unit_at(&text, g, TextUnit::Character);373                return units_of(&text, unit[0], unit[1]);374            }375        }376        return NSRange { .location = NOT_FOUND, .length = 0 };377    });378    const range_for_index: extern (c_pointer, c_pointer, i64) -> NSRange = (379        block,380        this,381        index382    ) => with_access(block, NSRange { .location = NOT_FOUND, .length = 0 }, (m) -> NSRange {383        if (m.text_node(this) is ::Some |&node| && index >= 0) {384            const text = &node.mapped_text();385            const at = utf8_offset(&text, index to u64) to u32;386            const unit = map_of(&node).unit_at(&text, at, TextUnit::Character);387            return units_of(&text, unit[0], unit[1]);388        }389        return NSRange { .location = NOT_FOUND, .length = 0 };390    });391    // one style runs through the whole text392    const style_range: extern (c_pointer, c_pointer, i64) -> NSRange = (393        block,394        this,395        index396    ) => with_access(block, NSRange { .location = NOT_FOUND, .length = 0 }, (m) -> NSRange {397        if (m.text_node(this) is ::Some |&node|) {398            const text = &node.mapped_text();399            return units_of(&text, 0, text.length() to u32);400        }401        return NSRange { .location = NOT_FOUND, .length = 0 };402    });403    const visible_range: extern (c_pointer, c_pointer) -> NSRange = (block, this) => with_access(404        block,405        NSRange { .location = 0, .length = 0 },406        (m) -> NSRange {407            if (m.text_node(this) is ::Some |&node|) {408                const lines = map_of(&node).visible_lines(node.bounds.height);409                return units_of(&node.mapped_text(), lines[0], lines[1]);410            }411            return NSRange { .location = 0, .length = 0 };412        }413    );414    const selected_text: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(415        block,416        NIL,417        (m) -> c_pointer {418            if (m.text_node(this) is ::Some |&node| && node.semantics.selection is ::Some |s|) {419                const text = &node.mapped_text();420                return m.o.string(&text[min(s[0], s[1])..max(s[0], s[1])]);421            }422            return NIL;423        }424    );425    const subrole: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(426        block,427        NIL,428        (m) => m.subrole(this)429    );430    const help: extern (c_pointer, c_pointer) -> c_pointer = (block, this) => with_access(431        block,432        NIL,433        (m) -> c_pointer {434            if (m.node(this) is ::Some |&node| && node.semantics.description.length() > 0) {435                return m.o.string(&node.semantics.description.view());436            }437            return NIL;438        }439    );440    const is_modal: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(441        block,442        false,443        (m) -> bool {444            if (m.node(this) is ::Some |&node|) {445                return node.semantics.modal;446            }447            return false;448        }449    );450    const is_expanded: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(451        block,452        false,453        (m) -> bool {454            if (m.node(this) is ::Some |&node|) {455                return node.semantics.expanded == ::Some(true);456            }457            return false;458        }459    );460    // AXElementBusy: what it shows is still coming461    const is_busy: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(462        block,463        false,464        (m) -> bool {465            if (m.node(this) is ::Some |&node|) {466                return node.semantics.busy;467            }468            return false;469        }470    );471    // AXRequired: a field a form needs filled in472    const is_required: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(473        block,474        false,475        (m) -> bool {476            if (m.node(this) is ::Some |&node|) {477                return node.semantics.required;478            }479            return false;480        }481    );482    const cancel: extern (c_pointer, c_pointer) -> bool = (block, this) => ask(483        block,484        this,485        Action::Dismiss486    );487    const show_menu: extern (c_pointer, c_pointer) -> bool = (block, this) => ask(488        block,489        this,490        Action::Expand491    );492    const is_selected: extern (c_pointer, c_pointer) -> bool = (block, this) => with_access(493        block,494        false,495        (m) -> bool {496            if (m.node(this) is ::Some |&node|) {497                const s = &node.semantics;498                return s.selected == ::Some(true) || s.checked == ::Some(true);499            }500            return false;501        }502    );503    const set_selected: extern (c_pointer, c_pointer, bool) = (block, this, selected) {504        if (selected) {505            ask(block, this, Action::Select);506        }507    };508    const allowed: extern (c_pointer, c_pointer, c_pointer) -> bool = (509        block,510        this,511        selector512    ) => with_access(block, false, (m) => m.allows(this, selector));513    o.method_with(e, &"accessibilityRole", &"@@:", role, cell);514    o.method_with(e, &"accessibilitySubrole", &"@@:", subrole, cell);515    o.method_with(e, &"accessibilityHelp", &"@@:", help, cell);516    o.method_with(e, &"isAccessibilityModal", &f"{b}@:".view(), is_modal, cell);517    o.method_with(e, &"isAccessibilityExpanded", &f"{b}@:".view(), is_expanded, cell);518    o.method_with(e, &"isAccessibilityElementBusy", &f"{b}@:".view(), is_busy, cell);519    o.method_with(e, &"isAccessibilityRequired", &f"{b}@:".view(), is_required, cell);520    o.method_with(e, &"accessibilityPerformCancel", &f"{b}@:".view(), cancel, cell);521    o.method_with(e, &"accessibilityPerformShowMenu", &f"{b}@:".view(), show_menu, cell);522    o.method_with(e, &"isAccessibilitySelected", &f"{b}@:".view(), is_selected, cell);523    o.method_with(e, &"setAccessibilitySelected:", &f"v@:{b}".view(), set_selected, cell);524    o.method_with(e, &"accessibilityLabel", &"@@:", label, cell);525    o.method_with(e, &"accessibilityValue", &"@@:", value, cell);526    o.method_with(e, &"accessibilityMinValue", &"@@:", minimum, cell);527    o.method_with(e, &"accessibilityMaxValue", &"@@:", maximum, cell);528    o.method_with(e, &"accessibilityParent", &"@@:", parent, cell);529    o.method_with(e, &"accessibilityChildren", &"@@:", children, cell);530    o.method_with(e, &"accessibilityRows", &"@@:", rows, cell);531    o.method_with(e, &"accessibilityRowCount", &"q@:", row_count, cell);532    o.method_with(e, &"accessibilityColumnCount", &"q@:", column_count, cell);533    o.method_with(e, &"accessibilityRowIndexRange", &f"{RANGE_CODE}@:".view(), row_range, cell);534    o.method_with(535        e,536        &"accessibilityColumnIndexRange",537        &f"{RANGE_CODE}@:".view(),538        column_range,539        cell540    );541    o.method_with(e, &"accessibilityWindow", &"@@:", window, cell);542    o.method_with(e, &"accessibilityTopLevelUIElement", &"@@:", window, cell);543    o.struct_method_with(e, &"accessibilityFrame", &f"{RECT_CODE}@:".view(), frame, cell);544    o.method_with(e, &"isAccessibilityElement", &f"{b}@:".view(), yes, cell);545    o.method_with(e, &"isAccessibilityFocused", &f"{b}@:".view(), is_focused, cell);546    o.method_with(e, &"isAccessibilityEnabled", &f"{b}@:".view(), is_enabled, cell);547    o.method_with(e, &"accessibilityPerformPress", &f"{b}@:".view(), press, cell);548    o.method_with(e, &"accessibilityPerformIncrement", &f"{b}@:".view(), increment, cell);549    o.method_with(e, &"accessibilityPerformDecrement", &f"{b}@:".view(), decrement, cell);550    o.method_with(e, &"setAccessibilityValue:", &"v@:@", set_value, cell);551    o.method_with(e, &"setAccessibilityFocused:", &f"v@:{b}".view(), set_focused, cell);552    o.method_with(e, &"accessibilitySelectedTextRange", &f"{RANGE_CODE}@:".view(), selected, cell);553    o.method_with(554        e,555        &"setAccessibilitySelectedTextRange:",556        &f"v@:{RANGE_CODE}".view(),557        select,558        cell559    );560    o.method_with(e, &"accessibilityNumberOfCharacters", &"q@:", characters, cell);561    o.method_with(e, &"accessibilityInsertionPointLineNumber", &"q@:", line_number, cell);562    o.method_with(e, &"accessibilityLineForIndex:", &"q@:q", line_for_index, cell);563    o.method_with(564        e,565        &"accessibilityRangeForLine:",566        &f"{RANGE_CODE}@:q".view(),567        range_for_line,568        cell569    );570    o.method_with(571        e,572        &"accessibilityStringForRange:",573        &f"@@:{RANGE_CODE}".view(),574        string_for_range,575        cell576    );577    o.method_with(578        e,579        &"accessibilityAttributedStringForRange:",580        &f"@@:{RANGE_CODE}".view(),581        attributed_for_range,582        cell583    );584    o.struct_method_with(585        e,586        &"accessibilityFrameForRange:",587        &f"{RECT_CODE}@:{RANGE_CODE}".view(),588        frame_for_range,589        cell590    );591    o.method_with(592        e,593        &"accessibilityRangeForPosition:",594        &f"{RANGE_CODE}@:{POINT_CODE}".view(),595        range_for_position,596        cell597    );598    o.method_with(599        e,600        &"accessibilityRangeForIndex:",601        &f"{RANGE_CODE}@:q".view(),602        range_for_index,603        cell604    );605    o.method_with(606        e,607        &"accessibilityStyleRangeForIndex:",608        &f"{RANGE_CODE}@:q".view(),609        style_range,610        cell611    );612    o.method_with(613        e,614        &"accessibilityVisibleCharacterRange",615        &f"{RANGE_CODE}@:".view(),616        visible_range,617        cell618    );619    o.method_with(e, &"accessibilitySelectedText", &"@@:", selected_text, cell);620    o.method_with(e, &"isAccessibilitySelectorAllowed:", &f"{b}@::".view(), allowed, cell);621    o.register_class(e);622}623624// A screen reader asked about the window: the program is asked for its625// tree once.626fn reader_came(self m: &var MacAccess) {627    if (!m.requested) {628        m.requested = true;629        m.asked = true;630        m.source.signal();631    }632}633634// Queues the action on the element's node for the program.635fn ask(block: c_pointer, element: c_pointer, action: Action) -> bool {636    const at = reached(block);637    if (at == 0) {638        return false;639    }640    const m = &var at.as_var<MacAccess>();641    const id = m.id_of(element);642    if (!m.tree.nodes.contains(&id)) {643        return false;644    }645    m.actions.push(ActionRequest { .node = id, .action = move action });646    m.source.signal();647    return true;648}649650fn id_of(self m: &MacAccess, element: c_pointer) -> u64 => m.o.state(element) to u64;651652// The element's node, while the tree has it.653fn node(self m: &MacAccess, element: c_pointer) -> Option<&AccessNode> {654    const id = m.id_of(element);655    return m.tree.nodes.try_get(&id);656}657658// The node's element, made the first time it is asked for; the view for659// the root.660fn element(self m: &var MacAccess, id: u64) -> c_pointer {661    if (id == m.tree.root) {662        return m.view;663    }664    if (m.elements.try_get(&id) is ::Some |&e|) {665        return e;666    }667    const e = m.o.make(m.o.class(&"AlloyAccessibilityElement"));668    m.o.set_state(e, id to c_pointer);669    m.elements.insert(id, e);670    return e;671}672673// The node's children as VoiceOver sees them, those of no role replaced674// by theirs and a grid's cells by their rows, as an NSArray.675fn children_of(self m: &var MacAccess, id: u64) -> c_pointer {676    var ids = Vector<u64>::empty();677    m.shown_children(id, &var ids);678    var grid = false;679    if (m.tree.nodes.try_get(&id) is ::Some |&node|) {680        grid = node.semantics.role is ::Grid;681    }682    var elements = Vector<c_pointer>::empty();683    for (ids.view()) |child| {684        var e = m.element(child);685        if (686            grid687            && m.tree.nodes.try_get(&child) is ::Some |&c|688            && c.semantics.cell is ::Some |at|689        ) {690            e = m.row_element(id, at[0]);691        }692        var known = false;693        for (elements.view()) |seen| {694            known = known || seen == e;695        }696        if (!known) {697            elements.push(e);698        }699    }700    return array(&m.o, &elements.view());701}702703// The element of the grid's row, made the first time it is asked for.704fn row_element(self m: &var MacAccess, grid: u64, row: u32) -> c_pointer {705    for (m.rows.view()) |&r| {706        if (r.grid == grid && r.row == row) {707            return r.element;708        }709    }710    const e = m.o.make(m.o.class(&"AlloyAccessibilityElement"));711    m.o.set_state(e, 0);712    m.rows.push(RowElement { .grid = grid, .row = row, .element = e });713    return e;714}715716// The grid and row of a row's element.717fn row_of(self m: &MacAccess, element: c_pointer) -> Option<[u64 : 2]> {718    for (m.rows.view()) |&r| {719        if (r.element == element) {720            return ::Some([r.grid, r.row to u64]);721        }722    }723    return ::None;724}725726// The grid's cells in the row, as an NSArray.727fn row_cells(self m: &var MacAccess, grid: u64, row: u32) -> c_pointer {728    var elements = Vector<c_pointer>::empty();729    for (m.cells_in(grid, row).view()) |id| {730        elements.push(m.element(id));731    }732    return array(&m.o, &elements.view());733}734735fn cells_in(self m: &MacAccess, grid: u64, row: u32) -> Vector<u64> {736    var out = Vector<u64>::empty();737    if (m.tree.nodes.try_get(&grid) is ::Some |&node|) {738        for (node.children.view()) |child| {739            if (740                m.tree.nodes.try_get(&child) is ::Some |&c|741                && c.semantics.cell is ::Some |at|742                && at[0] == row743            ) {744                out.push(child);745            }746        }747    }748    return move out;749}750751// A grid's rows and columns, from its cells'.752fn grid_size(self m: &MacAccess, element: c_pointer) -> [u32 : 2] {753    var size: [u32 : 2] = [0, 0];754    if (m.node(element) is ::Some |&node| && node.semantics.role is ::Grid) {755        for (node.children.view()) |child| {756            if (m.tree.nodes.try_get(&child) is ::Some |&c| && c.semantics.cell is ::Some |at|) {757                size = [max(size[0], at[0] + 1), max(size[1], at[1] + 1)];758            }759        }760    }761    return size;762}763764// Where a cell or a row is in its grid: its row, or its column.765fn index_range(self m: &MacAccess, element: c_pointer, column: bool) -> NSRange {766    if (m.row_of(element) is ::Some |r| && !column) {767        return NSRange { .location = r[1], .length = 1 };768    }769    if (m.node(element) is ::Some |&node| && node.semantics.cell is ::Some |at|) {770        return NSRange { .location = at[if (column) 1 else 0] to u64, .length = 1 };771    }772    return NSRange { .location = 0, .length = 0 };773}774775fn shown_children(self m: &MacAccess, id: u64, out: &var Vector<u64>) {776    if (m.tree.nodes.try_get(&id) is ::Some |&node|) {777        for (node.children.view()) |child| {778            if (m.tree.nodes.try_get(&child) is ::Some |&c|) {779                if (c.semantics.role is ::Unknown) {780                    m.shown_children(child, &var out);781                } else {782                    out.push(child);783                }784            }785        }786    }787}788789// The element's parent as VoiceOver sees it: the nearest ancestor with a790// role, or the view.791fn parent(self m: &var MacAccess, element: c_pointer) -> c_pointer {792    if (m.row_of(element) is ::Some |r|) {793        return m.element(r[0]);794    }795    if (m.node(element) is ::Some |&node| && node.semantics.cell is ::Some |cell|) {796        if (797            m.tree.try_parent_of(node.id) is ::Some |up|798            && m.tree.nodes.try_get(&up) is ::Some |&grid|799            && grid.semantics.role is ::Grid800        ) {801            return m.row_element(up, cell[0]);802        }803    }804    var at = m.id_of(element);805    while (m.tree.try_parent_of(at) is ::Some |up|) {806        if (up == m.tree.root) {807            return m.view;808        }809        if (m.tree.nodes.try_get(&up) is ::Some |&node| && !(node.semantics.role is ::Unknown)) {810            return m.element(up);811        }812        at = up;813    }814    return m.view;815}816817fn role(self m: &MacAccess, element: c_pointer) -> c_pointer {818    const node = if (m.node(element) is ::Some |&n|) &n else {819        return m.o.string(if (m.row_of(element) is ::Some) &"AXRow" else &"AXUnknown");820    };821    const s = &node.semantics;822    const name: &[u8] = match (s.role) {823        ::Label, ::ListOption &"AXStaticText";824        ::Button if (s.expanded is ::Some) &"AXMenuButton" else &"AXButton";825        ::CheckBox &"AXCheckBox";826        ::Slider &"AXSlider";827        ::TextInput if (s.multiline) &"AXTextArea" else &"AXTextField";828        ::Image &"AXImage";829        ::List &"AXList";830        ::ScrollView &"AXScrollArea";831        ::Menu &"AXMenu";832        ::MenuItem, ::MenuItemCheckbox &"AXMenuItem";833        ::Tooltip &"AXHelpTag";834        ::ComboBox &"AXPopUpButton";835        ::ListBox &"AXList";836        ::RadioGroup &"AXRadioGroup";837        ::RadioButton, ::Tab &"AXRadioButton";838        ::TabList &"AXTabGroup";839        ::Grid &"AXTable";840        ::GridCell &"AXCell";841        ::ProgressBar &"AXProgressIndicator";842        ::Window, ::Group, ::ListItem, ::Dialog, ::Alert, ::Unknown &"AXGroup";843    };844    return m.o.string(&name);845}846847// A dialog's kind, a tab's or a password field's, as NSSecureTextField848// gives (its value the dots shown), none for the rest.849fn subrole(self m: &MacAccess, element: c_pointer) -> c_pointer {850    if (m.node(element) is ::Some |&node|) {851        match (node.semantics.role) {852            ::TextInput {853                if (node.semantics.secret) {854                    return m.o.string(&"AXSecureTextField");855                }856            }857            ::Dialog {858                return m.o.string(&"AXApplicationDialog");859            }860            ::Alert {861                return m.o.string(&"AXApplicationAlertDialog");862            }863            ::Tab {864                return m.o.string(&"AXTabButton");865            }866            else {}867        }868    }869    return NIL;870}871872// What VoiceOver says of the node; a label's text is its value instead.873fn label(self m: &MacAccess, element: c_pointer) -> c_pointer {874    if (m.node(element) is ::Some |&node|) {875        if (!(node.semantics.role is ::Label || node.semantics.role is ::ListOption)) {876            return m.o.string(&node.semantics.label.view());877        }878    }879    return 0;880}881882// A checkbox's or a tab's state and a slider's value as numbers, a883// field's text, a label's.884fn value(self m: &MacAccess, element: c_pointer) -> c_pointer {885    const node = if (m.node(element) is ::Some |&n|) &n else {886        return 0;887    };888    const s = &node.semantics;889    const o = &m.o;890    if (s.checked is ::Some |checked|) {891        return o.call_integer(o.class(&"NSNumber"), &"numberWithInteger:", if (checked) 1 else 0);892    }893    if (s.role is ::Tab && s.selected is ::Some |selected|) {894        return o.call_integer(o.class(&"NSNumber"), &"numberWithInteger:", if (selected) 1 else 0);895    }896    if (s.range is ::Some |r|) {897        return number(&o, r.value);898    }899    if (s.role is ::Label || s.role is ::ListOption) {900        return o.string(&s.label.view());901    }902    if (s.role is ::TextInput || s.value.length() > 0) {903        return o.string(&s.value.view());904    }905    return 0;906}907908fn number(o: &Objc, value: f64) -> c_pointer {909    const make = o.send<extern (c_pointer, c_pointer, f64) -> c_pointer>();910    return make(o.class(&"NSNumber"), o.sel(&"numberWithDouble:"), value);911}912913// A slider's minimum or maximum.914fn limit(self m: &MacAccess, element: c_pointer, maximum: bool) -> c_pointer {915    if (m.node(element) is ::Some |&node|) {916        if (node.semantics.range is ::Some |r|) {917            return number(&m.o, if (maximum) r.maximum else r.minimum);918        }919    }920    return 0;921}922923fn frame(self m: &MacAccess, element: c_pointer) -> NSRect {924    if (m.node(element) is ::Some |&node|) {925        return screen_rect(&m.o, m.view, m.window, &node.bounds);926    }927    if (m.row_of(element) is ::Some |r|) {928        // a row's cells' union929        var bounds = Option<Area>::None;930        for (m.cells_in(r[0], r[1] to u32).view()) |id| {931            if (m.tree.nodes.try_get(&id) is ::Some |&c|) {932                bounds = ::Some(if (bounds is ::Some |u|) joined(u, c.bounds) else c.bounds);933            }934        }935        if (bounds is ::Some |&b|) {936            return screen_rect(&m.o, m.view, m.window, &b);937        }938    }939    return NSRect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 };940}941942// The smallest area holding both.943fn joined(a: Area, b: Area) -> Area {944    return Area {945        .x = min(a.x, b.x),946        .y = min(a.y, b.y),947        .width = max(a.x + a.width, b.x + b.width) - min(a.x, b.x),948        .height = max(a.y + a.height, b.y + b.height) - min(a.y, b.y)949    };950}951952// The value VoiceOver sets, an NSString or an NSNumber, as text.953fn text_of_value(self m: &MacAccess, given: c_pointer) -> String {954    const o = &m.o;955    const is_kind = o.send<extern (c_pointer, c_pointer, c_pointer) -> bool>();956    if (given != 0 && is_kind(given, o.sel(&"isKindOfClass:"), o.class(&"NSNumber"))) {957        return f"{o.number(given, &"doubleValue")}";958    }959    return plain_text(&o, given);960}961962// A field's selection in UTF-16 units, from its anchor and caret in963// bytes.964fn selected(self m: &MacAccess, element: c_pointer) -> NSRange {965    if (m.node(element) is ::Some |&node|) {966        if (node.semantics.selection is ::Some |ends|) {967            const text = &node.semantics.value.view();968            const a = utf16_offset(&text, ends[0]);969            const b = utf16_offset(&text, ends[1]);970            return if (a <= b) NSRange { .location = a, .length = b - a } else NSRange {971                .location = b,972                .length = a - b973            };974        }975    }976    return NSRange { .location = 0, .length = 0 };977}978979// A selection VoiceOver sets, in bytes, the caret at its end.980fn selection_of(self m: &MacAccess, element: c_pointer, range: NSRange) -> [u64 : 2] {981    if (m.node(element) is ::Some |&node|) {982        const text = &node.semantics.value.view();983        return [984            utf8_offset(&text, range.location),985            utf8_offset(&text, range.location + range.length)986        ];987    }988    return [0, 0];989}990991// The element's node when the program sent a map of its text: a field,992// or a text laid out on several lines.993fn text_node(self m: &MacAccess, element: c_pointer) -> Option<&AccessNode> {994    if (m.node(element) is ::Some |&node| && node.text is ::Some) {995        return ::Some(&node);996    }997    return ::None;998}9991000// A range of UTF-16 units as bytes of the text, within it.1001fn bytes_of(text: &[u8], range: NSRange) -> [u32 : 2] {1002    const start = utf8_offset(&text, range.location);1003    const end = utf8_offset(&text, range.location + min(range.length, NOT_FOUND - range.location));1004    return [start to u32, end to u32];1005}10061007// The bytes from start to end as a range of UTF-16 units.1008fn units_of(text: &[u8], start: u32, end: u32) -> NSRange {1009    const a = utf16_offset(&text, start to u64);1010    return NSRange { .location = a, .length = utf16_offset(&text, end to u64) - a };1011}10121013// The line's characters, as drawn.1014fn line_range(self m: &MacAccess, element: c_pointer, line: i64) -> NSRange {1015    if (m.text_node(element) is ::Some |&node| && line >= 0) {1016        const map = &map_of(&node);1017        if ((line to u64) < map.lines.length()) {1018            const l = &map.lines.get(line to u64);1019            return units_of(&node.mapped_text(), l.start, l.end);1020        }1021    }1022    return NSRange { .location = NOT_FOUND, .length = 0 };1023}10241025// The range's boxes' union on the screen.1026fn range_frame(self m: &MacAccess, element: c_pointer, range: NSRange) -> NSRect {1027    if (m.text_node(element) is ::Some |&node|) {1028        const ends = bytes_of(&node.mapped_text(), range);1029        const boxes = map_of(&node).boxes(ends[0], ends[1]);1030        if (boxes.length() > 0) {1031            var u = boxes.get(0);1032            for (boxes.view()) |b| {1033                u = joined(u, b);1034            }1035            u.x += node.bounds.x;1036            u.y += node.bounds.y;1037            return screen_rect(&m.o, m.view, m.window, &u);1038        }1039    }1040    return NSRect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 };1041}10421043// The range's text with how it is drawn: its font's family and size, its1044// color and its language.1045fn attributed(self m: &MacAccess, element: c_pointer, range: NSRange) -> c_pointer {1046    const node = if (m.text_node(element) is ::Some |&n|) &n else {1047        return NIL;1048    };1049    const text = &node.mapped_text();1050    const ends = bytes_of(&text, range);1051    const format = &map_of(&node).format;1052    const o = &m.o;1053    const family = o.string(&format.family.view());1054    const font = dictionary(1055        &o,1056        &[o.string(&"AXFontName"), o.string(&"AXFontFamily"), o.string(&"AXVisibleName"), o.string(1057            &"AXFontSize"1058        )],1059        &[family, family, family, number(&o, format.size to f64)]1060    );1061    const c = &format.color;1062    const srgb = o.send<extern (c_pointer, c_pointer, f64, f64, f64, f64) -> c_pointer>();1063    const color = srgb(1064        o.class(&"NSColor"),1065        o.sel(&"colorWithSRGBRed:green:blue:alpha:"),1066        c[0] to f64 / 255.0,1067        c[1] to f64 / 255.0,1068        c[2] to f64 / 255.0,1069        c[3] to f64 / 255.01070    );1071    const keys: [c_pointer : 3] = [o.string(&"AXFont"), o.string(&"AXForegroundColor"), m.language];1072    const values: [c_pointer : 3] = [1073        font,1074        o.call(color, &"CGColor"),1075        o.string(&format.language.view())1076    ];1077    const count: u64 = if (m.language != 0 && format.language.length() > 0) 3 else 2;1078    const attributes = dictionary(&o, &keys[..count], &values[..count]);1079    const make = o.send<extern (c_pointer, c_pointer, c_pointer, c_pointer) -> c_pointer>();1080    const string = make(1081        o.call(o.class(&"NSAttributedString"), &"alloc"),1082        o.sel(&"initWithString:attributes:"),1083        o.string(&text[ends[0] to u64..ends[1] to u64]),1084        attributes1085    );1086    return o.call(string, &"autorelease");1087}10881089// An autoreleased NSDictionary of the keys' values.1090fn dictionary(o: &Objc, keys: &[c_pointer], values: &[c_pointer]) -> c_pointer {1091    const make = o.send<extern (c_pointer, c_pointer, c_pointer, c_pointer, u64) -> c_pointer>();1092    return make(1093        o.class(&"NSDictionary"),1094        o.sel(&"dictionaryWithObjects:forKeys:count:"),1095        c_pointer::of(&values),1096        c_pointer::of(&keys),1097        keys.length()1098    );1099}11001101// Whether VoiceOver may use the method on the element: actions only on1102// the nodes that take them.1103fn allows(self m: &MacAccess, element: c_pointer, selector: c_pointer) -> bool {1104    const node = if (m.node(element) is ::Some |&n|) &n else {1105        return false;1106    };1107    const s = &node.semantics;1108    const o = &m.o;1109    if (selector == o.sel(&"accessibilityPerformPress")) {1110        return !s.disabled && match (s.role) {1111            ::Button,1112            ::CheckBox,1113            ::MenuItem,1114            ::MenuItemCheckbox,1115            ::ComboBox,1116            ::ListOption,1117            ::RadioButton,1118            ::Tab,1119            ::GridCell true;1120            else false;1121        };1122    }1123    if (selector == o.sel(&"accessibilityPerformShowMenu")) {1124        return !s.disabled && s.expanded is ::Some;1125    }1126    if (selector == o.sel(&"setAccessibilitySelected:")) {1127        return !s.disabled && match (s.role) {1128            ::ListOption, ::RadioButton, ::Tab, ::GridCell true;1129            else false;1130        };1131    }1132    if (selector == o.sel(&"accessibilityPerformCancel")) {1133        return s.role is ::Dialog || s.role is ::Alert || s.role is ::Menu;1134    }1135    if (1136        selector == o.sel(&"accessibilityPerformIncrement") || selector == o.sel(1137            &"accessibilityPerformDecrement"1138        )1139    ) {1140        return !s.disabled && s.range is ::Some;1141    }1142    if (selector == o.sel(&"setAccessibilityValue:")) {1143        return !s.disabled && (s.role is ::TextInput || s.range is ::Some);1144    }1145    if (selector == o.sel(&"setAccessibilityFocused:")) {1146        return !s.disabled && s.focusable;1147    }1148    if (selector == o.sel(&"setAccessibilitySelectedTextRange:")) {1149        return !s.disabled && s.role is ::TextInput;1150    }1151    return true;1152}11531154// The deepest node with a role under the point, in the view's pixels.1155fn hit(self m: &MacAccess, id: u64, at: Point) -> Option<u64> {1156    const node = if (m.tree.nodes.try_get(&id) is ::Some |&n|) &n else {1157        return ::None;1158    };1159    var k = node.children.length();1160    while (k > 0) {1161        k -= 1;1162        const child = node.children.get(k);1163        if (1164            m.tree.nodes.try_get(&child) is ::Some |&c|1165            && c.bounds.contains(at)1166            && m.hit(child, at) is ::Some |found|1167        ) {1168            return ::Some(found);1169        }1170    }1171    return if (id == m.tree.root || node.semantics.role is ::Unknown) ::None else ::Some(id);1172}11731174// Takes the program's update, posting NSAccessibility's notifications1175// for what changed on elements VoiceOver has.1176pub fn update(self m: &var MacAccess, update: TreeUpdate) {1177    var structure = update.removed.length() > 0;1178    var values = Vector<u64>::empty();1179    var titles = Vector<u64>::empty();1180    var selections = Vector<u64>::empty();1181    for (update.nodes.view()) |&node| {1182        if (m.tree.nodes.try_get(&node.id) is ::Some |&old|) {1183            if (old.children != node.children) {1184                structure = true;1185            }1186            const a = &old.semantics;1187            const b = &node.semantics;1188            if (a.value != b.value || a.checked != b.checked || a.range != b.range) {1189                values.push(node.id);1190            }1191            if (a.label != b.label) {1192                titles.push(node.id);1193            }1194            if (a.selection != b.selection) {1195                selections.push(node.id);1196            }1197        } else {1198            structure = true;1199        }1200    }1201    const focus = m.tree.focus;1202    const o = &m.o;1203    for (update.removed.view()) |id| {1204        if (m.elements.remove(&id) is ::Some |e|) {1205            m.post(e, o.string(&"AXUIElementDestroyed"));1206            o.release(e);1207        }1208        // the rows of a grid gone1209        var k: u64 = 0;1210        while (k < m.rows.length()) {1211            if (m.rows.get(k).grid == id) {1212                const e = m.rows.remove(k).element;1213                m.post(e, o.string(&"AXUIElementDestroyed"));1214                o.release(e);1215            } else {1216                k += 1;1217            }1218        }1219    }1220    m.tree.apply(move update);1221    for (values.view()) |id| {1222        if (m.elements.try_get(&id) is ::Some |&e|) {1223            m.post(e, o.string(&"AXValueChanged"));1224        }1225    }1226    for (titles.view()) |id| {1227        if (m.elements.try_get(&id) is ::Some |&e|) {1228            m.post(e, o.string(&"AXTitleChanged"));1229        }1230    }1231    for (selections.view()) |id| {1232        if (m.elements.try_get(&id) is ::Some |&e|) {1233            m.post(e, o.string(&"AXSelectedTextChanged"));1234        }1235    }1236    if (structure) {1237        m.post(m.view, o.string(&"AXLayoutChanged"));1238    }1239    if (m.tree.focus != focus && m.tree.focus is ::Some |now| && now != m.tree.root) {1240        const e = m.element(now);1241        m.post(e, o.string(&"AXFocusedUIElementChanged"));1242    }1243}12441245// Has VoiceOver say the text: an announcement from the view, at high1246// priority when assertive, else medium.1247pub fn announce(self m: &MacAccess, text: &String, assertive: bool) {1248    if (!m.requested) {1249        return;1250    }1251    const o = &m.o;1252    const keys: [c_pointer : 2] = [o.string(&"AXAnnouncementKey"), o.string(&"AXPriorityKey")];1253    const values: [c_pointer : 2] = [1254        o.string(&text.view()),1255        o.call_integer(o.class(&"NSNumber"), &"numberWithInteger:", if (assertive) 90 else 50)1256    ];1257    const info = dictionary(&o, &keys[..], &values[..]);1258    m.post_with_info(m.view, o.string(&"AXAnnouncementRequested"), info);1259}12601261// Releases the elements, as the window closes.1262pub fn close(self m: &var MacAccess) {1263    for (m.elements.entries()) |&entry| {1264        m.post(entry.value, m.o.string(&"AXUIElementDestroyed"));1265        m.o.release(entry.value);1266    }1267    m.elements.clear();1268    for (m.rows.view()) |&r| {1269        m.o.release(r.element);1270    }1271    m.rows.clear();1272}