draw

source of pkg::alloy::window::uia

1// UI Automation for the Win32 window (PLAN.md, F6b): the window2// answers WM_GETOBJECT with a provider for the root of the tree the3// program sends, and every node gets a provider as UI Automation asks for4// it. A provider is one COM object with a table of functions for each5// interface it answers, at fixed offsets within it: the simple provider,6// the fragment, the fragment root (the root's only) and the patterns7// (Invoke for buttons, Toggle for checkboxes, RangeValue for sliders,8// Value for fields, combo boxes and buttons with a value, ScrollItem for anything,9// ExpandCollapse for what opens, Selection for list boxes, radio10// groups, tab lists and calendars, SelectionItem for their options,11// radios, tabs and days, Grid and Table for calendars, GridItem for12// their days, Text and Text2 for what has a text map: fields and texts13// of several lines, whose ranges are COM objects of their own, a node14// and two byte offsets, answered from the map by text_ranges.alloy).15// Calls come on the window's thread16// (ProviderOptions_UseComThreading); what a screen reader asks17// goes to the program as Event::Action, and changes to the tree raise18// UI Automation's events while a client listens.1920import std::string;21import std::vector;22import std::option;23import std::map;24import std::ffi;25import std::math;2627import window;28import unicode;29import text_ranges;30import pkg::alloy::com;3132extern UiaReturnRawElementProvider(33    hwnd: c_pointer,34    wparam: u64,35    lparam: i64,36    provider: c_pointer37) -> i64;38extern UiaHostProviderFromHwnd(hwnd: c_pointer, out: c_pointer) -> i32;39extern UiaRaiseAutomationEvent(provider: c_pointer, event: EventId) -> i32;40extern UiaRaiseAutomationPropertyChangedEvent(41    provider: c_pointer,42    property: PropertyId,43    before: Variant,44    after: Variant45) -> i32;46extern UiaRaiseStructureChangedEvent(47    provider: c_pointer,48    change: i32,49    runtime: c_pointer,50    length: i3251) -> i32;52extern UiaClientsAreListening() -> i32;53extern UiaRaiseNotificationEvent(54    provider: c_pointer,55    kind: i32,56    processing: i32,57    text: c_pointer,58    activity: c_pointer59) -> i32;60extern UiaDisconnectProvider(provider: c_pointer) -> i32;61extern LocaleNameToLCID(name: c_pointer, flags: u32) -> u32;62extern ClientToScreen(hwnd: c_pointer, point: c_pointer) -> i32;63extern PostMessageW(hwnd: c_pointer, message: u32, wparam: u64, lparam: i64) -> i32;64extern UiaGetReservedNotSupportedValue(out: c_pointer) -> i32;6566const IID_SIMPLE: [u8 : 16] = guid(&"d6dd68d1-86fd-4332-8666-9abedea2d24c");67const IID_FRAGMENT: [u8 : 16] = guid(&"f7063da8-8359-439c-9297-bbc5299a7d87");68const IID_FRAGMENT_ROOT: [u8 : 16] = guid(&"620ce2a5-ab8f-40a9-86cb-de3c75599b58");69const IID_INVOKE: [u8 : 16] = guid(&"54fcb24b-e18e-47a2-b4d3-eccbe77599a2");70const IID_TOGGLE: [u8 : 16] = guid(&"56d00bd0-c4f4-433c-a836-1a52a57e0892");71const IID_RANGE_VALUE: [u8 : 16] = guid(&"36dc7aef-33e6-4691-afe1-2be7274b3d33");72const IID_VALUE: [u8 : 16] = guid(&"c7935180-6fb3-4201-b174-7df73adbf64a");73const IID_SCROLL_ITEM: [u8 : 16] = guid(&"2360c714-4bf1-4b26-ba65-9b21316127eb");74const IID_EXPAND_COLLAPSE: [u8 : 16] = guid(&"d847d3a5-cab0-4a98-8c32-ecb45c59ad24");75const IID_SELECTION: [u8 : 16] = guid(&"fb8b03af-3bdf-48d4-bd36-1a65793be168");76const IID_SELECTION_ITEM: [u8 : 16] = guid(&"2acad808-b2d4-452d-a407-91ff1ad167b2");77const IID_GRID: [u8 : 16] = guid(&"b17d6187-0907-464b-a168-0ef17a1572b1");78const IID_GRID_ITEM: [u8 : 16] = guid(&"d02541f1-fb81-4d64-ae32-f520f8a6dbd1");79const IID_TABLE: [u8 : 16] = guid(&"9c860395-97b3-490a-b52a-858cc22af166");80const IID_TEXT: [u8 : 16] = guid(&"3589c92c-63f3-4367-99bb-ada653b77cf2");81const IID_TEXT2: [u8 : 16] = guid(&"0dc5e6ed-3e16-4bf1-8f9a-a979878bc195");82const IID_TEXT_RANGE: [u8 : 16] = guid(&"5347ad7b-c355-46f8-aff5-909033582f63");8384const UIA_E_ELEMENTNOTAVAILABLE: i32 = (0x80040201 to u32) as i32;85const UIA_E_INVALIDOPERATION: i32 = (0x80131509 to u32) as i32;86const E_NOTIMPL: i32 = (0x80004001 to u32) as i32;8788// WM_APP + 2, posted after a screen reader's request: the window gives it89// the program once the call returns90pub const ACTED: u32 = 0x8002;9192// UI Automation's ids (UIAutomationClient.h): the patterns and properties93// the providers answer, of the many a client may ask for, the events they94// raise and the control types the roles are95type PatternId = enum : i32 {96    Invoke = 10000,97    Selection = 10001,98    Value = 10002,99    RangeValue = 10003,100    ExpandCollapse = 10005,101    Grid = 10006,102    GridItem = 10007,103    SelectionItem = 10010,104    Table = 10012,105    Text = 10014,106    Toggle = 10015,107    ScrollItem = 10017,108    Text2 = 10024,109};110111type PropertyId = enum : i32 {112    ControlType = 30003,113    Name = 30005,114    HasKeyboardFocus = 30008,115    IsKeyboardFocusable = 30009,116    IsEnabled = 30010,117    AutomationId = 30011,118    HelpText = 30013,119    Culture = 30015,120    FrameworkId = 30024,121    IsPassword = 30019,122    IsRequiredForForm = 30025,123    IsTextPatternAvailable = 30040,124    IsTextPattern2Available = 30119,125    ValueValue = 30045,126    RangeValueValue = 30047,127    AriaProperties = 30102,128    IsDataValidForForm = 30103,129    ExpandCollapseState = 30070,130    SelectionItemIsSelected = 30079,131    ToggleState = 30086,132    PositionInSet = 30152,133    SizeOfSet = 30153,134    FullDescription = 30159,135    IsDialog = 30174,136};137138type EventId = enum : i32 {139    FocusChanged = 20005,140    ElementSelected = 20012,141    TextSelectionChanged = 20014,142    TextChanged = 20015,143};144145type ControlType = enum : i32 {146    Button = 50000,147    Calendar = 50001,148    CheckBox = 50002,149    ComboBox = 50003,150    Edit = 50004,151    Image = 50006,152    ListItem = 50007,153    List = 50008,154    Menu = 50009,155    MenuItem = 50011,156    ProgressBar = 50012,157    RadioButton = 50013,158    Slider = 50015,159    Tab = 50018,160    TabItem = 50019,161    Text = 50020,162    ToolTip = 50022,163    Group = 50026,164    DataItem = 50029,165    Window = 50032,166    Pane = 50033,167};168169// The interfaces a provider answers, each a table of functions, in the170// order their tables are in it and in Tables.171type Face = enum {172    Simple,173    Fragment,174    FragmentRoot,175    Invoke,176    Toggle,177    RangeValue,178    Value,179    ScrollItem,180    ExpandCollapse,181    Selection,182    SelectionItem,183    Grid,184    GridItem,185    Table,186    Text, // ITextProvider2, which starts with ITextProvider's187};188189const FACES: u64 = 15;190191// Where the face's table is in a provider.192fn offset(self face: &Face) -> u64 => (face to u64) * 8;193194// The face's function at the index, in Tables' slots.195fn slot(self face: &Face, index: u64) -> u64 => (face to u64) * TABLE_SIZE + index;196197type Provider = struct {198    tables: [c_pointer : FACES],199    count: u32,200    node: u64,201    uia: c_pointer, // the Uia, 0 once the window is gone202};203204// The window's UI Automation: the tree as the program sent it, each205// node's parent, and the providers alive, by node.206pub type Uia = struct {207    pub hwnd: c_pointer,208    pub requested: bool, // whether the program was asked for its tree209    pub tree: AccessTree,210    pub providers: Map<u64, c_pointer>,211    pub tables: c_pointer, // the function tables, made once, 0 once closed212    pub closed: bool, // the window is gone: no provider is made213    // what a screen reader asked, for the window to give the program214    pub actions: Vector<ActionRequest>,215    pub culture: u32 = 0, // the window's language's LCID, 0 for none216    pub ranges: Vector<c_pointer> = Vector<c_pointer>::empty(), // the text ranges alive217};218219// Takes the window's language, a BCP 47 tag, as its LCID, which every220// node gives as its Culture.221pub fn set_language(self uia: &var Uia, tag: &[u8]) {222    const name = wide(&tag);223    uia.culture = LocaleNameToLCID(c_pointer::of(&name.view()), 0);224}225226pub fn Uia::create(hwnd: c_pointer) -> Uia {227    return Uia {228        .hwnd = hwnd,229        .requested = false,230        .tree = AccessTree::empty(),231        .providers = Map<u64, c_pointer>::empty(),232        .tables = make_tables(),233        .closed = false,234        .actions = Vector<ActionRequest>::empty()235    };236}237238// WM_GETOBJECT for UI Automation's root: the root's provider.239pub fn answer(self uia: &var Uia, wparam: u64, lparam: i64) -> i64 {240    if (uia.closed) {241        return 0;242    }243    const root = uia.provider(if (uia.tree.root != 0) uia.tree.root else ROOT_UNSENT);244    // UI Automation takes a reference of its own245    const answered = UiaReturnRawElementProvider(uia.hwnd, wparam, lparam, root);246    release(root);247    return answered;248}249250// The root's id until the program sends its tree.251const ROOT_UNSENT: u64 = 1 << 63;252253// Takes the program's update, raising UI Automation's events for what254// changed while a client listens.255pub fn update(self uia: &var Uia, update: TreeUpdate) {256    if (uia.closed) {257        return;258    }259    const listening = UiaClientsAreListening() != 0;260    var changed_names = Vector<u64>::empty();261    var structure = update.removed.length() > 0;262    for (update.nodes.view()) |&node| {263        if (uia.tree.nodes.try_get(&node.id) is ::Some |&old|) {264            if (old.children != node.children) {265                structure = true;266            }267            if (listening && uia.providers.contains(&node.id)) {268                uia.raise_changes(&old, &node);269            }270        } else {271            structure = true;272        }273    }274    const focus = uia.tree.focus;275    if (uia.tree.root != update.root && uia.tree.root == 0) {276        // the root the providers had before the tree came277        if (uia.providers.remove(&ROOT_UNSENT) is ::Some |p|) {278            p.as_var<Provider>().node = update.root;279            uia.providers.insert(update.root, p);280        }281    }282    uia.tree.apply(move update);283    if (!listening) {284        return;285    }286    if (structure) {287        const root = uia.provider(uia.tree.root);288        UiaRaiseStructureChangedEvent(root, 1, 0, 0); // ChildrenInvalidated289        release(root);290    }291    if (uia.tree.focus != focus && uia.tree.focus is ::Some |now| && now != uia.tree.root) {292        const p = uia.provider(now);293        UiaRaiseAutomationEvent(p, ::FocusChanged);294        release(p);295    }296}297298fn raise_changes(self uia: &var Uia, old: &AccessNode, node: &AccessNode) {299    const p = uia.provider(node.id);300    const a = &old.semantics;301    const b = &node.semantics;302    if (a.label != b.label) {303        UiaRaiseAutomationPropertyChangedEvent(304            p,305            ::Name,306            Variant::text(&a.label.view()),307            Variant::text(&b.label.view())308        );309    }310    if (311        b.role is ::ListOption || b.role is ::RadioButton || b.role is ::Tab || b.role is ::GridCell312    ) {313        const was = is_selected(&a);314        const now = is_selected(&b);315        if (was != now) {316            UiaRaiseAutomationPropertyChangedEvent(317                p,318                ::SelectionItemIsSelected,319                Variant::boolean(was),320                Variant::boolean(now)321            );322            if (now) {323                UiaRaiseAutomationEvent(p, ::ElementSelected);324            }325        }326    } else if (a.checked != b.checked) {327        UiaRaiseAutomationPropertyChangedEvent(328            p,329            ::ToggleState,330            Variant::integer(toggle_state(&a)),331            Variant::integer(toggle_state(&b))332        );333    }334    if (a.expanded != b.expanded && b.expanded is ::Some |open|) {335        UiaRaiseAutomationPropertyChangedEvent(336            p,337            ::ExpandCollapseState,338            Variant::integer(if (a.expanded == ::Some(true)) 1 else 0),339            Variant::integer(if (open) 1 else 0)340        );341    }342    // what Narrator and NVDA read a field's or a text's changes by343    if (node.text is ::Some) {344        if (a.value != b.value || a.label != b.label) {345            UiaRaiseAutomationEvent(p, ::TextChanged);346        }347        if (a.selection != b.selection) {348            UiaRaiseAutomationEvent(p, ::TextSelectionChanged);349        }350    }351    if (a.value != b.value) {352        if (b.range is ::Some |r|) {353            var before: f64 = 0.0;354            if (a.range is ::Some |q|) {355                before = q.value;356            }357            UiaRaiseAutomationPropertyChangedEvent(358                p,359                ::RangeValueValue,360                Variant::number(before),361                Variant::number(r.value)362            );363        } else {364            UiaRaiseAutomationPropertyChangedEvent(365                p,366                ::ValueValue,367                Variant::text(&a.value.view()),368                Variant::text(&b.value.view())369            );370        }371    }372    release(p);373}374375// Has screen readers say the text: a notification from the root, Other376// (4), important (ImportantAll, 0) when assertive, else MostRecent (3).377pub fn announce(self uia: &var Uia, text: &String, assertive: bool) {378    if (uia.closed || uia.tree.root == 0 || UiaClientsAreListening() == 0) {379        return;380    }381    const p = uia.provider(uia.tree.root);382    const said = bstr(&text.view());383    const activity = bstr(&"alloy");384    UiaRaiseNotificationEvent(p, 4, if (assertive) 0 else 3, said, activity);385    free_bstr(said);386    free_bstr(activity);387    release(p);388}389390// Lets the providers UI Automation still holds go, as the window closes:391// each is freed once released.392pub fn disconnect(self uia: &var Uia) {393    uia.closed = true;394    for (uia.providers.entries()) |&entry| {395        entry.value.as_var<Provider>().uia = 0;396        UiaDisconnectProvider(entry.value);397    }398    uia.providers.clear();399    for (uia.ranges.view()) |r| {400        r.as_var<TextRange>().uia = 0;401    }402    uia.ranges.clear();403    UiaReturnRawElementProvider(uia.hwnd, 0, 0, 0);404}405406// Whether UI Automation still holds a provider.407pub fn held(self uia: &Uia) -> bool => uia.tables != 0 && uia.tables.as_ref<Tables>().live > 0;408409// Frees the tables, or leaves them to the last provider still held.410pub fn finish(self uia: &var Uia) {411    if (uia.tables == 0) {412        return;413    }414    const tables = &var uia.tables.as_var<Tables>();415    tables.closed = true;416    if (tables.live == 0) {417        var freed = move uia.tables.take<Tables>();418    }419    uia.tables = 0;420}421422// The node's provider, its simple interface, with a reference for the423// caller.424fn provider(self uia: &var Uia, node: u64) -> c_pointer {425    if (uia.providers.try_get(&node) is ::Some |&p|) {426        p.as_var<Provider>().count += 1;427        return p;428    }429    var tables: [c_pointer : FACES] = [0 : FACES];430    for ([..FACES]) |k| {431        tables[k] = uia.tables + (k * TABLE_SIZE * 8) to c_pointer;432    }433    var made: *var Provider = new Provider {434        .tables = tables,435        .count = 1,436        .node = node,437        .uia = c_pointer::from(&uia)438    };439    const p = c_pointer::keep(move made);440    uia.providers.insert(node, p);441    uia.tables.as_var<Tables>().live += 1;442    return p;443}444445/* --- The function tables --- */446447// Room for each table's functions, the longest's (Text's 11), and the448// text ranges' table after them.449const TABLE_SIZE: u64 = 11;450const RANGE_SLOTS: u64 = 21;451const SLOTS: u64 = FACES * TABLE_SIZE + RANGE_SLOTS;452453type Tables = struct {454    slots: [c_pointer : SLOTS],455    live: u64, // the providers alive, which point into the slots456    closed: bool, // the window is gone: the last provider freed frees them457};458459type QueryFunction = extern (c_pointer, c_pointer, c_pointer) -> i32;460type CountFunction = extern (c_pointer) -> u32;461type Method = extern (c_pointer) -> i32;462type OutMethod = extern (c_pointer, c_pointer) -> i32;463type IdOutMethod = extern (c_pointer, i32, c_pointer) -> i32;464type PointMethod = extern (c_pointer, f64, f64, c_pointer) -> i32;465type NumberMethod = extern (c_pointer, f64) -> i32;466type CellMethod = extern (c_pointer, i32, i32, c_pointer) -> i32;467type UiaPointMethod = extern (c_pointer, UiaPoint, c_pointer) -> i32;468type IdMethod = extern (c_pointer, i32) -> i32;469type IdIdOutMethod = extern (c_pointer, i32, i32, c_pointer) -> i32;470type EndpointsMethod = extern (c_pointer, i32, c_pointer, i32, c_pointer) -> i32;471type EndpointMethod = extern (c_pointer, i32, c_pointer, i32) -> i32;472type MoveEndpointMethod = extern (c_pointer, i32, i32, i32, c_pointer) -> i32;473type FindAttributeMethod = extern (c_pointer, i32, Variant, i32, c_pointer) -> i32;474type FindTextMethod = extern (c_pointer, c_pointer, i32, i32, c_pointer) -> i32;475476// A point on the screen, as RangeFromPoint takes it.477type UiaPoint = struct {478    x: f64,479    y: f64,480};481482// The tables, one after another, TABLE_SIZE slots each, in Face's483// order: kept until the window is gone and no provider is left.484fn make_tables() -> c_pointer {485    var tables: *var Tables = new Tables {486        .slots = [0 : SLOTS],487        .live = 0,488        .closed = false489    };490    const all = &var tables.slots;491    put_unknown(&var all[..], Face::Simple, simple_query, simple_add, simple_release);492    const options: OutMethod = provider_options;493    const pattern: IdOutMethod = pattern_provider;494    const property: IdOutMethod = property_value;495    const host: OutMethod = host_provider;496    all[Face::Simple.slot(3)] = options as c_pointer;497    all[Face::Simple.slot(4)] = pattern as c_pointer;498    all[Face::Simple.slot(5)] = property as c_pointer;499    all[Face::Simple.slot(6)] = host as c_pointer;500    put_unknown(&var all[..], Face::Fragment, fragment_query, fragment_add, fragment_release);501    const navigate: IdOutMethod = navigate;502    const runtime: OutMethod = runtime_id;503    const bounds: OutMethod = bounding_rectangle;504    const embedded: OutMethod = embedded_roots;505    const focus: Method = set_focus;506    const root: OutMethod = fragment_root;507    all[Face::Fragment.slot(3)] = navigate as c_pointer;508    all[Face::Fragment.slot(4)] = runtime as c_pointer;509    all[Face::Fragment.slot(5)] = bounds as c_pointer;510    all[Face::Fragment.slot(6)] = embedded as c_pointer;511    all[Face::Fragment.slot(7)] = focus as c_pointer;512    all[Face::Fragment.slot(8)] = root as c_pointer;513    put_unknown(&var all[..], Face::FragmentRoot, root_query, root_add, root_release);514    const from_point: PointMethod = provider_from_point;515    const get_focus: OutMethod = focused_provider;516    all[Face::FragmentRoot.slot(3)] = from_point as c_pointer;517    all[Face::FragmentRoot.slot(4)] = get_focus as c_pointer;518    put_unknown(&var all[..], Face::Invoke, invoke_query, invoke_add, invoke_release);519    const invoke: Method = invoke;520    all[Face::Invoke.slot(3)] = invoke as c_pointer;521    put_unknown(&var all[..], Face::Toggle, toggle_query, toggle_add, toggle_release);522    const toggle: Method = toggle;523    const state: OutMethod = get_toggle_state;524    all[Face::Toggle.slot(3)] = toggle as c_pointer;525    all[Face::Toggle.slot(4)] = state as c_pointer;526    put_unknown(&var all[..], Face::RangeValue, range_query, range_add, range_release);527    const set_number: NumberMethod = set_range_value;528    const value: OutMethod = range_value;529    const read_only: OutMethod = range_read_only;530    const maximum: OutMethod = range_maximum;531    const minimum: OutMethod = range_minimum;532    const large: OutMethod = range_large_change;533    const small: OutMethod = range_small_change;534    all[Face::RangeValue.slot(3)] = set_number as c_pointer;535    all[Face::RangeValue.slot(4)] = value as c_pointer;536    all[Face::RangeValue.slot(5)] = read_only as c_pointer;537    all[Face::RangeValue.slot(6)] = maximum as c_pointer;538    all[Face::RangeValue.slot(7)] = minimum as c_pointer;539    all[Face::RangeValue.slot(8)] = large as c_pointer;540    all[Face::RangeValue.slot(9)] = small as c_pointer;541    put_unknown(&var all[..], Face::Value, value_query, value_add, value_release);542    const set_text: OutMethod = set_value;543    const text: OutMethod = get_value;544    const text_read_only: OutMethod = value_read_only;545    all[Face::Value.slot(3)] = set_text as c_pointer;546    all[Face::Value.slot(4)] = text as c_pointer;547    all[Face::Value.slot(5)] = text_read_only as c_pointer;548    put_unknown(&var all[..], Face::ScrollItem, scroll_query, scroll_add, scroll_release);549    const scroll: Method = scroll_into_view;550    all[Face::ScrollItem.slot(3)] = scroll as c_pointer;551    put_unknown(&var all[..], Face::ExpandCollapse, expand_query, expand_add, expand_release);552    const expand: Method = expand;553    const collapse: Method = collapse;554    const expanded: OutMethod = expand_collapse_state;555    all[Face::ExpandCollapse.slot(3)] = expand as c_pointer;556    all[Face::ExpandCollapse.slot(4)] = collapse as c_pointer;557    all[Face::ExpandCollapse.slot(5)] = expanded as c_pointer;558    put_unknown(&var all[..], Face::Selection, selection_query, selection_add, selection_release);559    const chosen: OutMethod = get_selection;560    const multiple: OutMethod = can_select_multiple;561    const required: OutMethod = selection_required;562    all[Face::Selection.slot(3)] = chosen as c_pointer;563    all[Face::Selection.slot(4)] = multiple as c_pointer;564    all[Face::Selection.slot(5)] = required as c_pointer;565    put_unknown(&var all[..], Face::SelectionItem, item_query, item_add, item_release);566    const select: Method = select_item;567    const add_to: Method = select_item_too;568    const remove_from: Method = unselect_item;569    const is_selected: OutMethod = item_selected;570    const container: OutMethod = item_container;571    all[Face::SelectionItem.slot(3)] = select as c_pointer;572    all[Face::SelectionItem.slot(4)] = add_to as c_pointer;573    all[Face::SelectionItem.slot(5)] = remove_from as c_pointer;574    all[Face::SelectionItem.slot(6)] = is_selected as c_pointer;575    all[Face::SelectionItem.slot(7)] = container as c_pointer;576    put_unknown(&var all[..], Face::Grid, grid_query, grid_add, grid_release);577    const item: CellMethod = grid_item;578    const rows: OutMethod = grid_rows;579    const columns: OutMethod = grid_columns;580    all[Face::Grid.slot(3)] = item as c_pointer;581    all[Face::Grid.slot(4)] = rows as c_pointer;582    all[Face::Grid.slot(5)] = columns as c_pointer;583    put_unknown(&var all[..], Face::GridItem, cell_query, cell_add, cell_release);584    const row: OutMethod = cell_row;585    const column: OutMethod = cell_column;586    const span: OutMethod = cell_span;587    const grid: OutMethod = cell_grid;588    all[Face::GridItem.slot(3)] = row as c_pointer;589    all[Face::GridItem.slot(4)] = column as c_pointer;590    all[Face::GridItem.slot(5)] = span as c_pointer;591    all[Face::GridItem.slot(6)] = span as c_pointer;592    all[Face::GridItem.slot(7)] = grid as c_pointer;593    put_unknown(&var all[..], Face::Table, table_query, table_add, table_release);594    const headers: OutMethod = table_headers;595    const major: OutMethod = table_major;596    all[Face::Table.slot(3)] = headers as c_pointer;597    all[Face::Table.slot(4)] = headers as c_pointer;598    all[Face::Table.slot(5)] = major as c_pointer;599    put_unknown(&var all[..], Face::Text, text_query, text_add, text_release);600    const text_selection: OutMethod = text_selection;601    const visible: OutMethod = visible_ranges;602    const from_child: QueryFunction = range_from_child;603    const text_point: UiaPointMethod = range_from_point;604    const document: OutMethod = document_range;605    const supported: OutMethod = supported_selection;606    const annotation: QueryFunction = range_from_annotation;607    const caret: QueryFunction = caret_range;608    all[Face::Text.slot(3)] = text_selection as c_pointer;609    all[Face::Text.slot(4)] = visible as c_pointer;610    all[Face::Text.slot(5)] = from_child as c_pointer;611    all[Face::Text.slot(6)] = text_point as c_pointer;612    all[Face::Text.slot(7)] = document as c_pointer;613    all[Face::Text.slot(8)] = supported as c_pointer;614    all[Face::Text.slot(9)] = annotation as c_pointer;615    all[Face::Text.slot(10)] = caret as c_pointer;616    put_range_table(&var all[FACES * TABLE_SIZE..]);617    return c_pointer::keep(move tables);618}619620// IUnknown's three functions at the start of the face's table.621fn put_unknown(622    all: &var [c_pointer],623    face: Face,624    query: QueryFunction,625    add: CountFunction,626    release: CountFunction627) {628    all[face.slot(0)] = query as c_pointer;629    all[face.slot(1)] = add as c_pointer;630    all[face.slot(2)] = release as c_pointer;631}632633/* --- IUnknown, for each table --- */634635// The provider holding the face's table.636fn holder(this: c_pointer, face: Face) -> &var Provider {637    const at = this - face.offset() to c_pointer;638    return &var at.as_var<Provider>();639}640641fn query(this: c_pointer, face: Face, id: c_pointer, out: c_pointer) -> i32 {642    const p = &var holder(this, face);643    const base = this - face.offset() to c_pointer;644    var found = Option<Face>::None;645    if (is_guid(id, &IID_UNKNOWN) || is_guid(id, &IID_SIMPLE)) {646        found = ::Some(Face::Simple);647    } else if (is_guid(id, &IID_FRAGMENT)) {648        found = ::Some(Face::Fragment);649    } else if (is_guid(id, &IID_FRAGMENT_ROOT) && p.is_root()) {650        found = ::Some(Face::FragmentRoot);651    } else if (is_guid(id, &IID_INVOKE)) {652        found = ::Some(Face::Invoke);653    } else if (is_guid(id, &IID_TOGGLE)) {654        found = ::Some(Face::Toggle);655    } else if (is_guid(id, &IID_RANGE_VALUE)) {656        found = ::Some(Face::RangeValue);657    } else if (is_guid(id, &IID_VALUE)) {658        found = ::Some(Face::Value);659    } else if (is_guid(id, &IID_SCROLL_ITEM)) {660        found = ::Some(Face::ScrollItem);661    } else if (is_guid(id, &IID_EXPAND_COLLAPSE)) {662        found = ::Some(Face::ExpandCollapse);663    } else if (is_guid(id, &IID_SELECTION)) {664        found = ::Some(Face::Selection);665    } else if (is_guid(id, &IID_SELECTION_ITEM)) {666        found = ::Some(Face::SelectionItem);667    } else if (is_guid(id, &IID_GRID)) {668        found = ::Some(Face::Grid);669    } else if (is_guid(id, &IID_GRID_ITEM)) {670        found = ::Some(Face::GridItem);671    } else if (is_guid(id, &IID_TABLE)) {672        found = ::Some(Face::Table);673    } else if ((is_guid(id, &IID_TEXT) || is_guid(id, &IID_TEXT2)) && has_map(&p)) {674        found = ::Some(Face::Text);675    }676    if (found is ::Some |answered|) {677        p.count += 1;678        put(out, base + answered.offset() to c_pointer);679        return S_OK;680    }681    put(out, 0);682    return E_NOINTERFACE;683}684685fn add(this: c_pointer, face: Face) -> u32 {686    const p = &var holder(this, face);687    p.count += 1;688    return p.count;689}690691fn drop_reference(this: c_pointer, face: Face) -> u32 {692    const base = this - face.offset() to c_pointer;693    const p = &var holder(this, face);694    p.count -= 1;695    const left = p.count;696    if (left == 0) {697        if (p.uia != 0) {698            const uia = &var p.uia.as_var<Uia>();699            if (uia.providers.try_get(&p.node) is ::Some |&kept| && kept == base) {700                uia.providers.remove(&p.node);701            }702        }703        var gone = move base.take<Provider>();704        // tables[0] is where the tables start705        const tables = &var gone.tables[0].as_var<Tables>();706        tables.live -= 1;707        if (tables.live == 0 && tables.closed) {708            var freed = move gone.tables[0].take<Tables>();709        }710    }711    return left;712}713714fn simple_query(715    this: c_pointer,716    id: c_pointer,717    out: c_pointer718) -> i32 => query(this, Face::Simple, id, out);719fn simple_add(this: c_pointer) -> u32 => add(this, Face::Simple);720fn simple_release(this: c_pointer) -> u32 => drop_reference(this, Face::Simple);721fn fragment_query(722    this: c_pointer,723    id: c_pointer,724    out: c_pointer725) -> i32 => query(this, Face::Fragment, id, out);726fn fragment_add(this: c_pointer) -> u32 => add(this, Face::Fragment);727fn fragment_release(this: c_pointer) -> u32 => drop_reference(this, Face::Fragment);728fn root_query(729    this: c_pointer,730    id: c_pointer,731    out: c_pointer732) -> i32 => query(this, Face::FragmentRoot, id, out);733fn root_add(this: c_pointer) -> u32 => add(this, Face::FragmentRoot);734fn root_release(this: c_pointer) -> u32 => drop_reference(this, Face::FragmentRoot);735fn invoke_query(736    this: c_pointer,737    id: c_pointer,738    out: c_pointer739) -> i32 => query(this, Face::Invoke, id, out);740fn invoke_add(this: c_pointer) -> u32 => add(this, Face::Invoke);741fn invoke_release(this: c_pointer) -> u32 => drop_reference(this, Face::Invoke);742fn toggle_query(743    this: c_pointer,744    id: c_pointer,745    out: c_pointer746) -> i32 => query(this, Face::Toggle, id, out);747fn toggle_add(this: c_pointer) -> u32 => add(this, Face::Toggle);748fn toggle_release(this: c_pointer) -> u32 => drop_reference(this, Face::Toggle);749fn range_query(750    this: c_pointer,751    id: c_pointer,752    out: c_pointer753) -> i32 => query(this, Face::RangeValue, id, out);754fn range_add(this: c_pointer) -> u32 => add(this, Face::RangeValue);755fn range_release(this: c_pointer) -> u32 => drop_reference(this, Face::RangeValue);756fn value_query(757    this: c_pointer,758    id: c_pointer,759    out: c_pointer760) -> i32 => query(this, Face::Value, id, out);761fn value_add(this: c_pointer) -> u32 => add(this, Face::Value);762fn value_release(this: c_pointer) -> u32 => drop_reference(this, Face::Value);763fn scroll_query(764    this: c_pointer,765    id: c_pointer,766    out: c_pointer767) -> i32 => query(this, Face::ScrollItem, id, out);768fn scroll_add(this: c_pointer) -> u32 => add(this, Face::ScrollItem);769fn scroll_release(this: c_pointer) -> u32 => drop_reference(this, Face::ScrollItem);770fn expand_query(771    this: c_pointer,772    id: c_pointer,773    out: c_pointer774) -> i32 => query(this, Face::ExpandCollapse, id, out);775fn expand_add(this: c_pointer) -> u32 => add(this, Face::ExpandCollapse);776fn expand_release(this: c_pointer) -> u32 => drop_reference(this, Face::ExpandCollapse);777fn selection_query(778    this: c_pointer,779    id: c_pointer,780    out: c_pointer781) -> i32 => query(this, Face::Selection, id, out);782fn selection_add(this: c_pointer) -> u32 => add(this, Face::Selection);783fn selection_release(this: c_pointer) -> u32 => drop_reference(this, Face::Selection);784fn item_query(785    this: c_pointer,786    id: c_pointer,787    out: c_pointer788) -> i32 => query(this, Face::SelectionItem, id, out);789fn item_add(this: c_pointer) -> u32 => add(this, Face::SelectionItem);790fn item_release(this: c_pointer) -> u32 => drop_reference(this, Face::SelectionItem);791fn grid_query(792    this: c_pointer,793    id: c_pointer,794    out: c_pointer795) -> i32 => query(this, Face::Grid, id, out);796fn grid_add(this: c_pointer) -> u32 => add(this, Face::Grid);797fn grid_release(this: c_pointer) -> u32 => drop_reference(this, Face::Grid);798fn cell_query(799    this: c_pointer,800    id: c_pointer,801    out: c_pointer802) -> i32 => query(this, Face::GridItem, id, out);803fn cell_add(this: c_pointer) -> u32 => add(this, Face::GridItem);804fn cell_release(this: c_pointer) -> u32 => drop_reference(this, Face::GridItem);805fn table_query(806    this: c_pointer,807    id: c_pointer,808    out: c_pointer809) -> i32 => query(this, Face::Table, id, out);810fn text_query(811    this: c_pointer,812    id: c_pointer,813    out: c_pointer814) -> i32 => query(this, Face::Text, id, out);815fn text_add(this: c_pointer) -> u32 => add(this, Face::Text);816fn text_release(this: c_pointer) -> u32 => drop_reference(this, Face::Text);817fn table_add(this: c_pointer) -> u32 => add(this, Face::Table);818fn table_release(this: c_pointer) -> u32 => drop_reference(this, Face::Table);819820/* --- What the providers answer --- */821822// Whether the provider's node has a text map, which the Text pattern823// reads.824fn has_map(p: &Provider) -> bool {825    if (node_of(&p) is ::Some |&node|) {826        return node.text is ::Some;827    }828    return false;829}830831fn is_root(self p: &Provider) -> bool {832    if (p.uia == 0) {833        return false;834    }835    const uia = &p.uia.as_ref<Uia>();836    return p.node == uia.tree.root || p.node == ROOT_UNSENT;837}838839// The provider's node as the tree has it; None when the window or the840// node has gone.841fn node_of(p: &Provider) -> Option<&AccessNode> {842    if (p.uia == 0) {843        return ::None;844    }845    const uia = &p.uia.as_ref<Uia>();846    if (uia.tree.nodes.try_get(&p.node) is ::Some |&node|) {847        return ::Some(&node);848    }849    return ::None;850}851852// Asks the program for the action on the provider's node.853fn ask(p: &Provider, action: Action) -> i32 => request(p.uia, p.node, move action);854855// Asks the program for the action on the node, through the Uia at the856// address, none once the window is gone.857fn request(at: c_pointer, node: u64, action: Action) -> i32 {858    if (at == 0) {859        return UIA_E_ELEMENTNOTAVAILABLE;860    }861    const uia = &var at.as_var<Uia>();862    uia.actions.push(ActionRequest { .node = node, .action = move action });863    PostMessageW(uia.hwnd, ACTED, 0, 0);864    return S_OK;865}866867fn provider_options(this: c_pointer, out: c_pointer) -> i32 {868    // ProviderOptions_ServerSideProvider | ProviderOptions_UseComThreading869    out.view_var<u32>(1)[0] = 0x21;870    return S_OK;871}872873fn pattern_provider(this: c_pointer, pattern: i32, out: c_pointer) -> i32 {874    put(out, 0);875    const p = &var holder(this, Face::Simple);876    const node = if (node_of(&p) is ::Some |&n|) &n else {877        return S_OK;878    };879    const id = if (PatternId::from(pattern) is ::Some |known|) known else {880        return S_OK;881    };882    const role = node.semantics.role;883    const found: Option<Face> = match (id) {884        ::Invoke if (885            role is ::Button || role is ::MenuItem || role is ::MenuItemCheckbox886        ) ::Some(Face::Invoke) else ::None;887        ::ExpandCollapse if (888            node.semantics.expanded is ::Some889        ) ::Some(Face::ExpandCollapse) else ::None;890        ::Toggle if (891            role is ::CheckBox892            || role is ::MenuItemCheckbox893        ) ::Some(Face::Toggle) else ::None;894        ::RangeValue if (node.semantics.range is ::Some) ::Some(Face::RangeValue) else ::None;895        ::Value if (has_value(&node.semantics)) ::Some(Face::Value) else ::None;896        ::Selection if (897            role is ::ListBox898            || role is ::RadioGroup899            || role is ::TabList900            || role is ::Grid901        ) ::Some(Face::Selection) else ::None;902        ::SelectionItem if (903            role is ::ListOption || role is ::RadioButton || role is ::Tab || role is ::GridCell904        ) ::Some(Face::SelectionItem) else ::None;905        ::Grid if (role is ::Grid) ::Some(Face::Grid) else ::None;906        ::Table if (role is ::Grid) ::Some(Face::Table) else ::None;907        ::GridItem if (node.semantics.cell is ::Some) ::Some(Face::GridItem) else ::None;908        ::Text, ::Text2 if (node.text is ::Some) ::Some(Face::Text) else ::None;909        ::ScrollItem if (p.is_root()) ::None else ::Some(Face::ScrollItem);910    };911    if (found is ::Some |face|) {912        p.count += 1;913        put(out, this + face.offset() to c_pointer);914    }915    return S_OK;916}917918fn property_value(this: c_pointer, property: i32, out: c_pointer) -> i32 {919    const p = &holder(this, Face::Simple);920    var v = Variant::empty();921    if (922        !p.is_root()923        && node_of(&p) is ::Some |&node|924        && PropertyId::from(property) is ::Some |id|925    ) {926        const s = &node.semantics;927        const uia = &p.uia.as_ref<Uia>();928        match (id) {929            ::Name {930                v = Variant::text(&s.label.view());931            }932            ::ControlType {933                v = Variant::integer(control_type(s.role) to i32);934            }935            ::IsKeyboardFocusable {936                v = Variant::boolean(s.focusable);937            }938            ::HasKeyboardFocus {939                v = Variant::boolean(uia.tree.focus == ::Some(node.id));940            }941            ::IsEnabled {942                v = Variant::boolean(!s.disabled);943            }944            ::AutomationId {945                v = Variant::text(&f"{node.id}".view());946            }947            ::FrameworkId {948                v = Variant::text(&"Alloy");949            }950            ::Culture {951                if (uia.culture != 0) {952                    v = Variant::integer(uia.culture as i32);953                }954            }955            ::HelpText, ::FullDescription {956                if (s.description.length() > 0) {957                    v = Variant::text(&s.description.view());958                }959            }960            ::IsDataValidForForm {961                v = Variant::boolean(!s.invalid);962            }963            ::IsRequiredForForm {964                v = Variant::boolean(s.required);965            }966            ::IsPassword {967                v = Variant::boolean(s.secret);968            }969            ::IsTextPatternAvailable, ::IsTextPattern2Available {970                v = Variant::boolean(node.text is ::Some);971            }972            ::IsDialog {973                v = Variant::boolean(s.role is ::Dialog || s.role is ::Alert);974            }975            ::ExpandCollapseState {976                if (s.expanded is ::Some |open|) {977                    v = Variant::integer(if (open) 1 else 0);978                }979            }980            ::SelectionItemIsSelected {981                v = Variant::boolean(is_selected(&s));982            }983            ::AriaProperties {984                var aria = String::empty();985                if (s.current) {986                    aria.append(if (s.role is ::GridCell) &"current=date" else &"current=true");987                }988                if (s.busy) {989                    aria.append(if (aria.length() > 0) &";busy=true" else &"busy=true");990                }991                if (s.invalid) {992                    aria.append(if (aria.length() > 0) &";invalid=true" else &"invalid=true");993                }994                if (s.required) {995                    aria.append(if (aria.length() > 0) &";required=true" else &"required=true");996                }997                if (aria.length() > 0) {998                    v = Variant::text(&aria.view());999                }1000            }1001            ::PositionInSet, ::SizeOfSet {1002                if (s.position is ::Some |at|) {1003                    v = Variant::integer(at[if (id is ::PositionInSet) 0 else 1] to i32);1004                }1005            }1006        }1007    }1008    out.view_var<Variant>(1)[0] = v;1009    return S_OK;1010}10111012// A field's or a combo box's text, or a button's value: a date picker's1013// date.1014fn has_value(s: &Semantics) -> bool => s.role is ::TextInput || s.role is ::ComboBox1015    || (s.role is ::Button && s.value.length() > 0);10161017fn control_type(role: Role) -> ControlType => match (role) {1018    ::Window ::Window;1019    ::Group ::Group;1020    ::Label ::Text;1021    ::Button ::Button;1022    ::CheckBox ::CheckBox;1023    ::Slider ::Slider;1024    ::TextInput ::Edit;1025    ::Image ::Image;1026    ::List ::List;1027    ::ListItem ::ListItem;1028    ::Menu ::Menu;1029    ::MenuItem, ::MenuItemCheckbox ::MenuItem;1030    ::Tooltip ::ToolTip;1031    ::ComboBox ::ComboBox;1032    ::ListBox ::List;1033    ::ListOption ::ListItem;1034    ::RadioGroup ::Group;1035    ::RadioButton ::RadioButton;1036    ::TabList ::Tab;1037    ::Tab ::TabItem;1038    ::Grid ::Calendar;1039    ::GridCell ::DataItem;1040    ::ProgressBar ::ProgressBar;1041    ::Dialog, ::Alert, ::ScrollView, ::Unknown ::Pane;1042};10431044fn host_provider(this: c_pointer, out: c_pointer) -> i32 {1045    put(out, 0);1046    const p = &holder(this, Face::Simple);1047    if (p.is_root()) {1048        const uia = &p.uia.as_ref<Uia>();1049        return UiaHostProviderFromHwnd(uia.hwnd, out);1050    }1051    return S_OK;1052}10531054type NavigateDirection = enum : i32 {1055    Parent = 0,1056    NextSibling = 1,1057    PreviousSibling = 2,1058    FirstChild = 3,1059    LastChild = 4,1060};10611062fn navigate(this: c_pointer, direction: i32, out: c_pointer) -> i32 {1063    put(out, 0);1064    const p = &holder(this, Face::Fragment);1065    if (p.uia == 0) {1066        return UIA_E_ELEMENTNOTAVAILABLE;1067    }1068    const toward = if (NavigateDirection::from(direction) is ::Some |d|) d else {1069        return S_OK;1070    };1071    const uia = &var p.uia.as_var<Uia>();1072    var target = Option<u64>::None;1073    const parent = uia.tree.try_parent_of(p.node);1074    match (toward) {1075        ::Parent {1076            target = parent;1077        }1078        ::NextSibling, ::PreviousSibling {1079            if (parent is ::Some |up| && uia.tree.nodes.try_get(&up) is ::Some |&holder_node|) {1080                const siblings = &holder_node.children.view();1081                for ([..siblings.length()]) |k| {1082                    if (siblings[k] == p.node) {1083                        if (toward is ::NextSibling && k + 1 < siblings.length()) {1084                            target = ::Some(siblings[k + 1]);1085                        } else if (toward is ::PreviousSibling && k > 0) {1086                            target = ::Some(siblings[k - 1]);1087                        }1088                    }1089                }1090            }1091        }1092        ::FirstChild, ::LastChild {1093            if (node_of(&p) is ::Some |&node| && node.children.length() > 0) {1094                const children = &node.children.view();1095                target = ::Some(1096                    if (toward is ::FirstChild) children[0] else children[children.length() - 1]1097                );1098            }1099        }1100    }1101    if (target is ::Some |id|) {1102        put(out, uia.provider(id) + Face::Fragment.offset() to c_pointer);1103    }1104    return S_OK;1105}11061107fn runtime_id(this: c_pointer, out: c_pointer) -> i32 {1108    put(out, 0);1109    const p = &holder(this, Face::Fragment);1110    if (p.is_root()) {1111        return S_OK;1112    }1113    // UiaAppendRuntimeId, then the node's id in two halves1114    const ids: [i32 : 3] = [3, (p.node & 0xFFFFFFFF) to u32 as i32, (p.node >> 32) to u32 as i32];1115    put(out, integers(&ids[..]));1116    return S_OK;1117}11181119// The client area's top left on the screen.1120fn client_origin(hwnd: c_pointer) -> [f64 : 2] {1121    var point: [i32 : 2] = [0, 0];1122    ClientToScreen(hwnd, c_pointer::of(&point[..]));1123    return [point[0] to f64, point[1] to f64];1124}11251126fn bounding_rectangle(this: c_pointer, out: c_pointer) -> i32 {1127    var rect: [f64 : 4] = [0.0 : 4];1128    const p = &holder(this, Face::Fragment);1129    if (!p.is_root() && node_of(&p) is ::Some |&node|) {1130        const uia = &p.uia.as_ref<Uia>();1131        const origin = client_origin(uia.hwnd);1132        const b = node.bounds;1133        rect = [origin[0] + b.x to f64, origin[1] + b.y to f64, b.width to f64, b.height to f64];1134    }1135    out.view_var<f64>(4)[..] = rect[..];1136    return S_OK;1137}11381139fn embedded_roots(this: c_pointer, out: c_pointer) -> i32 {1140    put(out, 0);1141    return S_OK;1142}11431144fn set_focus(this: c_pointer) -> i32 => ask(&holder(this, Face::Fragment), Action::Focus);11451146fn fragment_root(this: c_pointer, out: c_pointer) -> i32 {1147    put(out, 0);1148    const p = &holder(this, Face::Fragment);1149    if (p.uia == 0) {1150        return UIA_E_ELEMENTNOTAVAILABLE;1151    }1152    const uia = &var p.uia.as_var<Uia>();1153    const root = if (uia.tree.root != 0) uia.tree.root else ROOT_UNSENT;1154    put(out, uia.provider(root) + Face::FragmentRoot.offset() to c_pointer);1155    return S_OK;1156}11571158// The deepest node holding the point on the screen, under the root.1159fn provider_from_point(this: c_pointer, x: f64, y: f64, out: c_pointer) -> i32 {1160    put(out, 0);1161    const p = &holder(this, Face::FragmentRoot);1162    if (p.uia == 0) {1163        return UIA_E_ELEMENTNOTAVAILABLE;1164    }1165    const uia = &var p.uia.as_var<Uia>();1166    const origin = client_origin(uia.hwnd);1167    const at = Point { .x = (x - origin[0]) to f32, .y = (y - origin[1]) to f32 };1168    if (uia.tree.node_at(uia.tree.root, at) is ::Some |found|) {1169        put(out, uia.provider(found) + Face::Fragment.offset() to c_pointer);1170    }1171    return S_OK;1172}11731174fn focused_provider(this: c_pointer, out: c_pointer) -> i32 {1175    put(out, 0);1176    const p = &holder(this, Face::FragmentRoot);1177    if (p.uia == 0) {1178        return UIA_E_ELEMENTNOTAVAILABLE;1179    }1180    const uia = &var p.uia.as_var<Uia>();1181    if (1182        uia.tree.focus is ::Some |focus|1183        && focus != uia.tree.root1184        && uia.tree.nodes.contains(&focus)1185    ) {1186        put(out, uia.provider(focus) + Face::Fragment.offset() to c_pointer);1187    }1188    return S_OK;1189}11901191fn invoke(this: c_pointer) -> i32 => ask(&holder(this, Face::Invoke), Action::Click);11921193fn toggle(this: c_pointer) -> i32 => ask(&holder(this, Face::Toggle), Action::Click);11941195// ToggleState_On or Off.1196fn toggle_state(s: &Semantics) -> i32 => if (s.checked == ::Some(true)) 1 else 0;11971198fn get_toggle_state(this: c_pointer, out: c_pointer) -> i32 {1199    var state: i32 = 0;1200    if (node_of(&holder(this, Face::Toggle)) is ::Some |&node|) {1201        state = toggle_state(&node.semantics);1202    }1203    out.view_var<i32>(1)[0] = state;1204    return S_OK;1205}12061207fn range_of(this: c_pointer) -> Option<AccessRange> {1208    if (node_of(&holder(this, Face::RangeValue)) is ::Some |&node|) {1209        return node.semantics.range;1210    }1211    return ::None;1212}12131214fn set_range_value(this: c_pointer, value: f64) -> i32 {1215    return ask(&holder(this, Face::RangeValue), Action::SetValue(f"{value}"));1216}12171218fn put_number(out: c_pointer, value: f64) -> i32 {1219    out.view_var<f64>(1)[0] = value;1220    return S_OK;1221}12221223fn range_value(this: c_pointer, out: c_pointer) -> i32 {1224    return put_number(out, if (range_of(this) is ::Some |r|) r.value else 0.0);1225}12261227fn range_maximum(this: c_pointer, out: c_pointer) -> i32 {1228    return put_number(out, if (range_of(this) is ::Some |r|) r.maximum else 0.0);1229}12301231fn range_minimum(this: c_pointer, out: c_pointer) -> i32 {1232    return put_number(out, if (range_of(this) is ::Some |r|) r.minimum else 0.0);1233}12341235fn range_small_change(this: c_pointer, out: c_pointer) -> i32 {1236    var step: f64 = 0.0;1237    if (range_of(this) is ::Some |r|) {1238        step = if (r.step > 0.0) r.step else (r.maximum - r.minimum) / 20.0;1239    }1240    return put_number(out, step);1241}12421243fn range_large_change(this: c_pointer, out: c_pointer) -> i32 {1244    var step: f64 = 0.0;1245    if (range_of(this) is ::Some |r|) {1246        step = (r.maximum - r.minimum) / 10.0;1247    }1248    return put_number(out, step);1249}12501251fn read_only(p: &Provider, out: c_pointer) -> i32 {1252    var disabled = true;1253    if (node_of(&p) is ::Some |&node|) {1254        // a combo box's or a button's value is chosen, not typed, a1255        // progress bar's told1256        disabled = node.semantics.disabled1257            || node.semantics.role is ::ComboBox1258            || node.semantics.role is ::Button1259            || node.semantics.role is ::ProgressBar;1260    }1261    out.view_var<i32>(1)[0] = if (disabled) 1 else 0;1262    return S_OK;1263}12641265fn range_read_only(this: c_pointer, out: c_pointer) -> i32 => read_only(1266    &holder(this, Face::RangeValue),1267    out1268);12691270fn value_read_only(this: c_pointer, out: c_pointer) -> i32 => read_only(1271    &holder(this, Face::Value),1272    out1273);12741275fn set_value(this: c_pointer, text: c_pointer) -> i32 {1276    return ask(&holder(this, Face::Value), Action::SetValue(narrow_c(text, false)));1277}12781279fn get_value(this: c_pointer, out: c_pointer) -> i32 {1280    var text = String::empty();1281    if (node_of(&holder(this, Face::Value)) is ::Some |&node|) {1282        text = copy node.semantics.value;1283    }1284    put(out, bstr(&text.view()));1285    return S_OK;1286}12871288fn expand(this: c_pointer) -> i32 => ask(&holder(this, Face::ExpandCollapse), Action::Expand);12891290fn collapse(this: c_pointer) -> i32 => ask(&holder(this, Face::ExpandCollapse), Action::Collapse);12911292// ExpandCollapseState_Collapsed (0) or Expanded (1).1293fn expand_collapse_state(this: c_pointer, out: c_pointer) -> i32 {1294    var state: i32 = 0;1295    if (node_of(&holder(this, Face::ExpandCollapse)) is ::Some |&node|) {1296        if (node.semantics.expanded == ::Some(true)) {1297            state = 1;1298        }1299    }1300    out.view_var<i32>(1)[0] = state;1301    return S_OK;1302}13031304fn scroll_into_view(this: c_pointer) -> i32 => ask(1305    &holder(this, Face::ScrollItem),1306    Action::ScrollIntoView1307);13081309// Whether an option is selected or a radio checked.1310fn is_selected(s: &Semantics) -> bool => s.selected == ::Some(true) || s.checked == ::Some(true);13111312// The options of a list box or the radios of a group selected, as a1313// SAFEARRAY of their providers.1314fn get_selection(this: c_pointer, out: c_pointer) -> i32 {1315    var chosen = Vector<c_pointer>::empty();1316    const p = &holder(this, Face::Selection);1317    if (node_of(&p) is ::Some |&node|) {1318        const uia = &var p.uia.as_var<Uia>();1319        for (node.children.view()) |child| {1320            if (uia.tree.nodes.try_get(&child) is ::Some |&c| && is_selected(&c.semantics)) {1321                chosen.push(uia.provider(child));1322            }1323        }1324    }1325    put(out, unknowns(&chosen.view()));1326    for (chosen.view()) |c| {1327        release(c);1328    }1329    return S_OK;1330}13311332fn put_bool(out: c_pointer, value: bool) -> i32 {1333    out.view_var<i32>(1)[0] = if (value) 1 else 0;1334    return S_OK;1335}13361337fn can_select_multiple(this: c_pointer, out: c_pointer) -> i32 => put_bool(out, false);13381339fn selection_required(this: c_pointer, out: c_pointer) -> i32 => put_bool(out, false);13401341fn select_item(this: c_pointer) -> i32 => ask(&holder(this, Face::SelectionItem), Action::Select);13421343// One option at most is selected: adding one selects it alone.1344fn select_item_too(this: c_pointer) -> i32 => select_item(this);13451346// Unselecting nothing is the only way to leave one selected.1347fn unselect_item(this: c_pointer) -> i32 => S_OK;13481349fn item_selected(this: c_pointer, out: c_pointer) -> i32 {1350    var selected = false;1351    if (node_of(&holder(this, Face::SelectionItem)) is ::Some |&node|) {1352        selected = is_selected(&node.semantics);1353    }1354    return put_bool(out, selected);1355}13561357// The list box or the group holding the option.1358fn item_container(this: c_pointer, out: c_pointer) -> i32 {1359    put(out, 0);1360    const p = &holder(this, Face::SelectionItem);1361    if (p.uia == 0) {1362        return UIA_E_ELEMENTNOTAVAILABLE;1363    }1364    const uia = &var p.uia.as_var<Uia>();1365    if (uia.tree.try_parent_of(p.node) is ::Some |parent|) {1366        put(out, uia.provider(parent));1367    }1368    return S_OK;1369}13701371/* --- Grids: a calendar's days --- */13721373// The grid's rows and columns, from its cells'.1374fn grid_size(uia: &Uia, grid: &AccessNode) -> [u32 : 2] {1375    var size: [u32 : 2] = [0, 0];1376    for (grid.children.view()) |child| {1377        if (uia.tree.nodes.try_get(&child) is ::Some |&c| && c.semantics.cell is ::Some |at|) {1378            size = [max(size[0], at[0] + 1), max(size[1], at[1] + 1)];1379        }1380    }1381    return size;1382}13831384fn grid_item(this: c_pointer, row: i32, column: i32, out: c_pointer) -> i32 {1385    put(out, 0);1386    const p = &holder(this, Face::Grid);1387    const node = if (node_of(&p) is ::Some |&n|) &n else {1388        return UIA_E_ELEMENTNOTAVAILABLE;1389    };1390    const uia = &var p.uia.as_var<Uia>();1391    for (node.children.view()) |child| {1392        if (uia.tree.nodes.try_get(&child) is ::Some |&c| && c.semantics.cell is ::Some |at|) {1393            if (at[0] to i32 == row && at[1] to i32 == column) {1394                put(out, uia.provider(child));1395            }1396        }1397    }1398    return S_OK;1399}14001401fn grid_count(this: c_pointer, out: c_pointer, columns: bool) -> i32 {1402    var count: u32 = 0;1403    const p = &holder(this, Face::Grid);1404    if (node_of(&p) is ::Some |&node|) {1405        count = grid_size(&p.uia.as_ref<Uia>(), &node)[if (columns) 1 else 0];1406    }1407    out.view_var<i32>(1)[0] = count to i32;1408    return S_OK;1409}14101411fn grid_rows(this: c_pointer, out: c_pointer) -> i32 => grid_count(this, out, false);14121413fn grid_columns(this: c_pointer, out: c_pointer) -> i32 => grid_count(this, out, true);14141415fn cell_place(this: c_pointer, out: c_pointer, column: bool) -> i32 {1416    var at: u32 = 0;1417    if (1418        node_of(&holder(this, Face::GridItem)) is ::Some |&node|1419        && node.semantics.cell is ::Some |c|1420    ) {1421        at = c[if (column) 1 else 0];1422    }1423    out.view_var<i32>(1)[0] = at to i32;1424    return S_OK;1425}14261427fn cell_row(this: c_pointer, out: c_pointer) -> i32 => cell_place(this, out, false);14281429fn cell_column(this: c_pointer, out: c_pointer) -> i32 => cell_place(this, out, true);14301431// A cell spans one row and one column.1432fn cell_span(this: c_pointer, out: c_pointer) -> i32 {1433    out.view_var<i32>(1)[0] = 1;1434    return S_OK;1435}14361437// The grid holding the cell.1438fn cell_grid(this: c_pointer, out: c_pointer) -> i32 {1439    put(out, 0);1440    const p = &holder(this, Face::GridItem);1441    if (p.uia == 0) {1442        return UIA_E_ELEMENTNOTAVAILABLE;1443    }1444    const uia = &var p.uia.as_var<Uia>();1445    if (uia.tree.try_parent_of(p.node) is ::Some |parent|) {1446        put(out, uia.provider(parent));1447    }1448    return S_OK;1449}14501451// A calendar's grid has no header cells.1452fn table_headers(this: c_pointer, out: c_pointer) -> i32 {1453    put(out, unknowns(&[]));1454    return S_OK;1455}14561457// RowOrColumnMajor_RowMajor.1458fn table_major(this: c_pointer, out: c_pointer) -> i32 {1459    out.view_var<i32>(1)[0] = 0;1460    return S_OK;1461}14621463/* --- Text: a field's, a text's of several lines --- */14641465// A text range, a COM object of its own: a node's text from `start` to1466// `end`, in bytes, which each call clamps to the text as it is now.1467type TextRange = struct {1468    table: c_pointer, // the ranges' table in Tables1469    count: u32,1470    node: u64,1471    start: u32,1472    end: u32,1473    uia: c_pointer, // the Uia, 0 once the window is gone1474};14751476// A new range of the node's text, with a reference for the caller.1477fn new_range(self uia: &var Uia, node: u64, start: u32, end: u32) -> c_pointer {1478    var made: *var TextRange = new TextRange {1479        .table = uia.tables + (FACES * TABLE_SIZE * 8) to c_pointer,1480        .count = 1,1481        .node = node,1482        .start = start,1483        .end = end,1484        .uia = c_pointer::from(&uia)1485    };1486    const r = c_pointer::keep(move made);1487    uia.ranges.push(r);1488    uia.tables.as_var<Tables>().live += 1;1489    return r;1490}14911492// The provider's node and its map, for the Text pattern's functions.1493fn mapped(this: c_pointer) -> Option<&AccessNode> {1494    if (node_of(&holder(this, Face::Text)) is ::Some |&node| && node.text is ::Some) {1495        return ::Some(&node);1496    }1497    return ::None;1498}14991500// A range of the Text face's node into `out`.1501fn put_range(this: c_pointer, out: c_pointer, start: u32, end: u32) -> i32 {1502    const p = &holder(this, Face::Text);1503    if (p.uia == 0) {1504        put(out, 0);1505        return UIA_E_ELEMENTNOTAVAILABLE;1506    }1507    put(out, p.uia.as_var<Uia>().new_range(p.node, start, end));1508    return S_OK;1509}15101511// A SAFEARRAY of one range into `out`.1512fn put_ranges(this: c_pointer, out: c_pointer, start: u32, end: u32) -> i32 {1513    var r: c_pointer = 0;1514    const result = put_range(this, c_pointer::from(&r), start, end);1515    put(out, unknowns(&[r]));1516    release(r);1517    return result;1518}15191520// A field's selection, the anchor and the caret as one range, or the1521// caret alone; a text has none.1522fn text_selection(this: c_pointer, out: c_pointer) -> i32 {1523    const node = if (mapped(this) is ::Some |&n|) &n else {1524        put(out, unknowns(&[]));1525        return S_OK;1526    };1527    if (node.semantics.selection is ::Some |s|) {1528        const map = &map_of(&node);1529        const a = map.clamped(s[0] to u32);1530        const b = map.clamped(s[1] to u32);1531        return put_ranges(this, out, min(a, b), max(a, b));1532    }1533    put(out, unknowns(&[]));1534    return S_OK;1535}15361537// The lines inside the node's bounds.1538fn visible_ranges(this: c_pointer, out: c_pointer) -> i32 {1539    const node = if (mapped(this) is ::Some |&n|) &n else {1540        put(out, unknowns(&[]));1541        return UIA_E_ELEMENTNOTAVAILABLE;1542    };1543    const shown = map_of(&node).visible_lines(node.bounds.height);1544    return put_ranges(this, out, shown[0], shown[1]);1545}15461547// The node has no children: the whole text.1548fn range_from_child(this: c_pointer, child: c_pointer, out: c_pointer) -> i32 {1549    return document_range(this, out);1550}15511552// The empty range at the boundary nearest the point on the screen.1553fn range_from_point(this: c_pointer, point: UiaPoint, out: c_pointer) -> i32 {1554    const node = if (mapped(this) is ::Some |&n|) &n else {1555        put(out, 0);1556        return UIA_E_ELEMENTNOTAVAILABLE;1557    };1558    const origin = client_origin(holder(this, Face::Text).uia.as_ref<Uia>().hwnd);1559    const at = map_of(&node).offset_at(1560        (point.x - origin[0]) to f32 - node.bounds.x,1561        (point.y - origin[1]) to f32 - node.bounds.y1562    );1563    return put_range(this, out, at, at);1564}15651566fn document_range(this: c_pointer, out: c_pointer) -> i32 {1567    const node = if (mapped(this) is ::Some |&n|) &n else {1568        put(out, 0);1569        return UIA_E_ELEMENTNOTAVAILABLE;1570    };1571    return put_range(this, out, 0, map_of(&node).end());1572}15731574// SupportedTextSelection_Single for a field, None for a text.1575fn supported_selection(this: c_pointer, out: c_pointer) -> i32 {1576    var single = false;1577    if (mapped(this) is ::Some |&node|) {1578        single = node.semantics.role is ::TextInput;1579    }1580    out.view_var<i32>(1)[0] = if (single) 1 else 0;1581    return S_OK;1582}15831584// No text here is annotated.1585fn range_from_annotation(this: c_pointer, annotation: c_pointer, out: c_pointer) -> i32 {1586    put(out, 0);1587    return E_NOTIMPL;1588}15891590// The empty range at the caret, active while the node has the focus.1591fn caret_range(this: c_pointer, active: c_pointer, out: c_pointer) -> i32 {1592    const node = if (mapped(this) is ::Some |&n|) &n else {1593        put(out, 0);1594        return UIA_E_ELEMENTNOTAVAILABLE;1595    };1596    const uia = &holder(this, Face::Text).uia.as_ref<Uia>();1597    if (active != 0) {1598        active.view_var<i32>(1)[0] = if (uia.tree.focus == ::Some(node.id)) 1 else 0;1599    }1600    var caret: u32 = 0;1601    if (node.semantics.selection is ::Some |s|) {1602        caret = map_of(&node).clamped(s[1] to u32);1603    }1604    return put_range(this, out, caret, caret);1605}16061607/* --- Text ranges --- */16081609fn put_range_table(all: &var [c_pointer]) {1610    const query: QueryFunction = text_range_query;1611    const add: CountFunction = text_range_add;1612    const drop: CountFunction = text_range_release;1613    const clone: OutMethod = range_clone;1614    const compare: QueryFunction = range_compare;1615    const endpoints: EndpointsMethod = compare_endpoints;1616    const expand: IdMethod = expand_to_unit;1617    const find_attribute: FindAttributeMethod = find_attribute;1618    const find_text: FindTextMethod = find_text;1619    const attribute: IdOutMethod = attribute_value;1620    const rectangles: OutMethod = bounding_rectangles;1621    const enclosing: OutMethod = enclosing_element;1622    const text: IdOutMethod = range_text;1623    const move_by: IdIdOutMethod = move_range;1624    const move_endpoint: MoveEndpointMethod = move_endpoint_by_unit;1625    const move_to: EndpointMethod = move_endpoint_by_range;1626    const select: Method = select_range;1627    const refuse: Method = refuse_selection;1628    const scroll: IdMethod = scroll_range;1629    const children: OutMethod = range_children;1630    const functions: [c_pointer : RANGE_SLOTS] = [1631        query as c_pointer,1632        add as c_pointer,1633        drop as c_pointer,1634        clone as c_pointer,1635        compare as c_pointer,1636        endpoints as c_pointer,1637        expand as c_pointer,1638        find_attribute as c_pointer,1639        find_text as c_pointer,1640        attribute as c_pointer,1641        rectangles as c_pointer,1642        enclosing as c_pointer,1643        text as c_pointer,1644        move_by as c_pointer,1645        move_endpoint as c_pointer,1646        move_to as c_pointer,1647        select as c_pointer,1648        refuse as c_pointer,1649        refuse as c_pointer,1650        scroll as c_pointer,1651        children as c_pointer1652    ];1653    all[..RANGE_SLOTS] = functions[..];1654}16551656fn text_range_query(this: c_pointer, id: c_pointer, out: c_pointer) -> i32 {1657    if (is_guid(id, &IID_UNKNOWN) || is_guid(id, &IID_TEXT_RANGE)) {1658        this.as_var<TextRange>().count += 1;1659        put(out, this);1660        return S_OK;1661    }1662    put(out, 0);1663    return E_NOINTERFACE;1664}16651666fn text_range_add(this: c_pointer) -> u32 {1667    const r = &var this.as_var<TextRange>();1668    r.count += 1;1669    return r.count;1670}16711672fn text_range_release(this: c_pointer) -> u32 {1673    const r = &var this.as_var<TextRange>();1674    r.count -= 1;1675    const left = r.count;1676    if (left == 0) {1677        if (r.uia != 0) {1678            const ranges = &var r.uia.as_var<Uia>().ranges;1679            for ([..ranges.length()]) |k| {1680                if (ranges.get(k) == this) {1681                    ranges.remove(k);1682                    break;1683                }1684            }1685        }1686        var gone = move this.take<TextRange>();1687        // the ranges' table is the last in Tables1688        const tables = gone.table - (FACES * TABLE_SIZE * 8) to c_pointer;1689        const t = &var tables.as_var<Tables>();1690        t.live -= 1;1691        if (t.live == 0 && t.closed) {1692            var freed = move tables.take<Tables>();1693        }1694    }1695    return left;1696}16971698// The range's node with its map, its ends clamped to its text; None1699// once the node or its map is gone.1700fn read(r: &var TextRange) -> Option<&AccessNode> {1701    if (r.uia == 0) {1702        return ::None;1703    }1704    const uia = &r.uia.as_ref<Uia>();1705    if (uia.tree.nodes.try_get(&r.node) is ::Some |&node| && node.text is ::Some |&map|) {1706        r.start = map.clamped(r.start);1707        r.end = max(r.start, map.clamped(r.end));1708        return ::Some(&node);1709    }1710    return ::None;1711}17121713// The UIA TextUnit's: a format run and a page are the whole text here.1714fn unit_of(unit: i32) -> TextUnit => match (unit) {1715    0 TextUnit::Character;1716    2 TextUnit::Word;1717    3 TextUnit::Line;1718    4 TextUnit::Paragraph;1719    else TextUnit::Document;1720};17211722fn range_clone(this: c_pointer, out: c_pointer) -> i32 {1723    const r = &var this.as_var<TextRange>();1724    if (read(&var r) is ::None) {1725        put(out, 0);1726        return UIA_E_ELEMENTNOTAVAILABLE;1727    }1728    put(out, r.uia.as_var<Uia>().new_range(r.node, r.start, r.end));1729    return S_OK;1730}17311732// The other range as one of these, if it is.1733fn other_range(this: c_pointer, other: c_pointer) -> Option<&var TextRange> {1734    if (other == 0 || other.as_ref<TextRange>().table != this.as_ref<TextRange>().table) {1735        return ::None;1736    }1737    return ::Some(&var other.as_var<TextRange>());1738}17391740fn range_compare(this: c_pointer, other: c_pointer, out: c_pointer) -> i32 {1741    const r = &this.as_ref<TextRange>();1742    var same = false;1743    if (other_range(this, other) is ::Some |&o|) {1744        same = o.node == r.node && o.start == r.start && o.end == r.end;1745    }1746    return put_bool(out, same);1747}17481749// An endpoint's offset: TextPatternRangeEndpoint_Start (0) or End.1750fn endpoint(self r: &TextRange, which: i32) -> u32 => if (which == 0) r.start else r.end;17511752fn set_endpoint(self r: &var TextRange, which: i32, at: u32) {1753    if (which == 0) {1754        r.start = at;1755        r.end = max(r.end, at);1756    } else {1757        r.end = at;1758        r.start = min(r.start, at);1759    }1760}17611762fn compare_endpoints(1763    this: c_pointer,1764    which: i32,1765    other: c_pointer,1766    its: i32,1767    out: c_pointer1768) -> i32 {1769    const r = &this.as_ref<TextRange>();1770    if (other_range(this, other) is ::Some |&o|) {1771        out.view_var<i32>(1)[0] = (r.endpoint(which) to i64 - o.endpoint(its) to i64) to i32;1772        return S_OK;1773    }1774    return UIA_E_INVALIDOPERATION;1775}17761777fn expand_to_unit(this: c_pointer, unit: i32) -> i32 {1778    const r = &var this.as_var<TextRange>();1779    const node = if (read(&var r) is ::Some |&n|) &n else {1780        return UIA_E_ELEMENTNOTAVAILABLE;1781    };1782    const range = map_of(&node).unit_at(&node.mapped_text(), r.start, unit_of(unit));1783    r.start = range[0];1784    r.end = range[1];1785    return S_OK;1786}17871788// Moves the range `count` units on: an empty one stays empty, any other1789// becomes the unit it then starts, never past the last.1790fn move_range(this: c_pointer, unit: i32, count: i32, out: c_pointer) -> i32 {1791    out.view_var<i32>(1)[0] = 0;1792    const r = &var this.as_var<TextRange>();1793    const node = if (read(&var r) is ::Some |&n|) &n else {1794        return UIA_E_ELEMENTNOTAVAILABLE;1795    };1796    const map = &map_of(&node);1797    const text = &node.mapped_text();1798    const u = unit_of(unit);1799    if (r.start == r.end) {1800        const m = map.moved(&text, r.start, u, count);1801        r.start = m.at;1802        r.end = m.at;1803        out.view_var<i32>(1)[0] = m.count;1804        return S_OK;1805    }1806    const from = map.unit_at(&text, r.start, u)[0];1807    var m = map.moved(&text, from, u, count);1808    if (m.at >= map.end() && m.count > 0) {1809        m = map.moved(&text, from, u, m.count - 1);1810    }1811    const range = map.unit_at(&text, m.at, u);1812    r.start = range[0];1813    r.end = range[1];1814    out.view_var<i32>(1)[0] = m.count;1815    return S_OK;1816}18171818fn move_endpoint_by_unit(1819    this: c_pointer,1820    which: i32,1821    unit: i32,1822    count: i32,1823    out: c_pointer1824) -> i32 {1825    out.view_var<i32>(1)[0] = 0;1826    const r = &var this.as_var<TextRange>();1827    const node = if (read(&var r) is ::Some |&n|) &n else {1828        return UIA_E_ELEMENTNOTAVAILABLE;1829    };1830    const m = map_of(&node).moved(&node.mapped_text(), r.endpoint(which), unit_of(unit), count);1831    r.set_endpoint(which, m.at);1832    out.view_var<i32>(1)[0] = m.count;1833    return S_OK;1834}18351836fn move_endpoint_by_range(this: c_pointer, which: i32, other: c_pointer, its: i32) -> i32 {1837    const at = if (other_range(this, other) is ::Some |&o|) o.endpoint(its) else {1838        return UIA_E_INVALIDOPERATION;1839    };1840    this.as_var<TextRange>().set_endpoint(which, at);1841    return S_OK;1842}18431844// The range's text in UTF-16 units, at most `limit` when not negative.1845fn range_text(this: c_pointer, limit: i32, out: c_pointer) -> i32 {1846    const r = &var this.as_var<TextRange>();1847    const node = if (read(&var r) is ::Some |&n|) &n else {1848        put(out, bstr(&""));1849        return UIA_E_ELEMENTNOTAVAILABLE;1850    };1851    const part = &node.mapped_text()[r.start to u64..r.end to u64];1852    const cut = if (limit >= 0) utf8_offset(&part, limit to u64) else part.length();1853    put(out, bstr(&part[..cut]));1854    return S_OK;1855}18561857// The range's boxes on the screen, four doubles each.1858fn bounding_rectangles(this: c_pointer, out: c_pointer) -> i32 {1859    const r = &var this.as_var<TextRange>();1860    const node = if (read(&var r) is ::Some |&n|) &n else {1861        put(out, doubles(&[]));1862        return UIA_E_ELEMENTNOTAVAILABLE;1863    };1864    const origin = client_origin(r.uia.as_ref<Uia>().hwnd);1865    var numbers = Vector<f64>::empty();1866    for (map_of(&node).boxes(r.start, r.end).view()) |&b| {1867        numbers.push(origin[0] + (node.bounds.x + b.x) to f64);1868        numbers.push(origin[1] + (node.bounds.y + b.y) to f64);1869        numbers.push(b.width to f64);1870        numbers.push(b.height to f64);1871    }1872    put(out, doubles(&numbers.view()));1873    return S_OK;1874}18751876fn enclosing_element(this: c_pointer, out: c_pointer) -> i32 {1877    const r = &var this.as_var<TextRange>();1878    if (read(&var r) is ::None) {1879        put(out, 0);1880        return UIA_E_ELEMENTNOTAVAILABLE;1881    }1882    put(out, r.uia.as_var<Uia>().provider(r.node));1883    return S_OK;1884}18851886fn range_children(this: c_pointer, out: c_pointer) -> i32 {1887    put(out, unknowns(&[]));1888    return S_OK;1889}18901891// Selects the range in a field, the caret at its end.1892fn select_range(this: c_pointer) -> i32 {1893    const r = &var this.as_var<TextRange>();1894    const node = if (read(&var r) is ::Some |&n|) &n else {1895        return UIA_E_ELEMENTNOTAVAILABLE;1896    };1897    if (!(node.semantics.role is ::TextInput)) {1898        return UIA_E_INVALIDOPERATION;1899    }1900    return request(r.uia, r.node, Action::SetSelection([r.start to u64, r.end to u64]));1901}19021903// A field has one selection: none is added nor taken away.1904fn refuse_selection(this: c_pointer) -> i32 => UIA_E_INVALIDOPERATION;19051906fn scroll_range(this: c_pointer, top: i32) -> i32 {1907    const r = &var this.as_var<TextRange>();1908    if (read(&var r) is ::None) {1909        return UIA_E_ELEMENTNOTAVAILABLE;1910    }1911    return request(r.uia, r.node, Action::ScrollIntoView);1912}19131914// The text found in the range, exactly or ignoring ASCII case, the last1915// when `backward`; none found puts no range.1916fn find_text(1917    this: c_pointer,1918    wanted: c_pointer,1919    backward: i32,1920    ignore_case: i32,1921    out: c_pointer1922) -> i32 {1923    put(out, 0);1924    const r = &var this.as_var<TextRange>();1925    const node = if (read(&var r) is ::Some |&n|) &n else {1926        return UIA_E_ELEMENTNOTAVAILABLE;1927    };1928    const needle = narrow_c(wanted, false);1929    const n = &needle.view();1930    const hay = &node.mapped_text()[r.start to u64..r.end to u64];1931    if (n.length() == 0 || n.length() > hay.length()) {1932        return S_OK;1933    }1934    var found: Option<u64> = ::None;1935    for ([..hay.length() - n.length() + 1]) |at| {1936        var same = true;1937        for ([..n.length()]) |k| {1938            if (!same_byte(hay[at + k], n[k], ignore_case != 0)) {1939                same = false;1940                break;1941            }1942        }1943        if (same) {1944            found = ::Some(at);1945            if (backward == 0) {1946                break;1947            }1948        }1949    }1950    if (found is ::Some |at|) {1951        const start = r.start + at to u32;1952        put(out, r.uia.as_var<Uia>().new_range(r.node, start, start + n.length() to u32));1953    }1954    return S_OK;1955}19561957fn same_byte(a: u8, b: u8, ignore_case: bool) -> bool {1958    if (a == b) {1959        return true;1960    }1961    const lower = |ignore_case| (c: u8) => if (ignore_case && c >= 'A' && c <= 'Z') c + 32 else c;1962    return lower(a) == lower(b);1963}19641965// The text attributes UI Automation asks of a range.1966type TextAttribute = enum : i32 {1967    Culture = 40004,1968    FontName = 40005,1969    FontSize = 40006,1970    FontWeight = 40007,1971    ForegroundColor = 40008,1972    IsItalic = 40014,1973    IsReadOnly = 40015,1974    StyleId = 40034,1975    IsActive = 40036,1976    SelectionActiveEnd = 40037,1977    CaretPosition = 40038,1978    CaretBidiMode = 40039,1979    FlowDirections = 40028,1980};19811982// The attribute's value over the range: the text's one format, its1983// start's line's direction; UiaGetReservedNotSupportedValue for the rest.1984fn attribute_of(node: &AccessNode, uia: &Uia, start: u32, attribute: i32) -> Variant {1985    const map = &map_of(&node);1986    const f = &map.format;1987    const s = &node.semantics;1988    const line = &map.lines.get(map.line_of(start));1989    const caret: u32 = if (s.selection is ::Some |sel|) map.clamped(sel[1] to u32) else 0;1990    const name = wide(&f.language.view());1991    if (TextAttribute::from(attribute) is ::Some |known|) {1992        return match (known) {1993            ::Culture Variant::integer(LocaleNameToLCID(c_pointer::of(&name.view()), 0) as i32);1994            ::FontName Variant::text(&f.family.view());1995            // points, at 96 pixels an inch1996            ::FontSize Variant::number(f.size to f64 * 0.75);1997            ::FontWeight Variant::integer(f.weight as i32);1998            // a COLORREF: red in the low byte1999            ::ForegroundColor Variant::integer(2000                (f.color[0] to u32 | f.color[1] to u32 << 8 | f.color[2] to u32 << 16) as i322001            );2002            ::IsItalic Variant::boolean(false);2003            ::IsReadOnly Variant::boolean(f.read_only || s.disabled || !(s.role is ::TextInput));2004            // StyleId_Heading1, else StyleId_Normal2005            ::StyleId Variant::integer(if (f.heading) 70001 else 70012);2006            ::IsActive Variant::boolean(uia.tree.focus == ::Some(node.id));2007            // ActiveEnd_Start (1) when the caret is the selection's start2008            ::SelectionActiveEnd Variant::integer(2009                if (s.selection is ::Some |sel| && sel[1] < sel[0]) 1 else 22010            );2011            // CaretPosition_BeginningOfLine (2), EndOfLine (1), Unknown (0)2012            ::CaretPosition Variant::integer(2013                if (caret == line.start) 2 else if (caret == line.end) 1 else 02014            );2015            // CaretBidiMode_RTL (1) on a line read right to left2016            ::CaretBidiMode Variant::integer(2017                if (map.lines.get(map.line_of(caret)).right_to_left) 1 else 02018            );2019            // FlowDirections_RightToLeft (1)2020            ::FlowDirections Variant::integer(if (line.right_to_left) 1 else 0);2021        };2022    }2023    var reserved: c_pointer = 0;2024    UiaGetReservedNotSupportedValue(c_pointer::from(&reserved));2025    return Variant::unknown(reserved);2026}20272028fn attribute_value(this: c_pointer, attribute: i32, out: c_pointer) -> i32 {2029    const r = &var this.as_var<TextRange>();2030    const node = if (read(&var r) is ::Some |&n|) &n else {2031        out.view_var<Variant>(1)[0] = Variant::empty();2032        return UIA_E_ELEMENTNOTAVAILABLE;2033    };2034    out.view_var<Variant>(1)[0] = attribute_of(&node, &r.uia.as_ref<Uia>(), r.start, attribute);2035    return S_OK;2036}20372038// The range itself when its one run has the value, else none.2039fn find_attribute(2040    this: c_pointer,2041    attribute: i32,2042    value: Variant,2043    backward: i32,2044    out: c_pointer2045) -> i32 {2046    put(out, 0);2047    const r = &var this.as_var<TextRange>();2048    const node = if (read(&var r) is ::Some |&n|) &n else {2049        return UIA_E_ELEMENTNOTAVAILABLE;2050    };2051    const has = attribute_of(&node, &r.uia.as_ref<Uia>(), r.start, attribute);2052    var same = has.kind == value.kind && has.value == value.value;2053    if (has.kind is ::Bstr) {2054        same = value.kind is ::Bstr2055            && narrow_c(has.value to c_pointer, false) == narrow_c(value.value to c_pointer, false);2056        free_bstr(has.value to c_pointer);2057    }2058    if (same) {2059        put(out, r.uia.as_var<Uia>().new_range(r.node, r.start, r.end));2060    }2061    return S_OK;2062}