ui_app

source of pkg::alloy::ui_controls::menus

1// Menus (decisions/F11.md, F11a): a list of actions in a layer,2// opened below a button, beside an item as its submenu, or where the3// pointer was as a context menu. Each item is an element of its own, a4// MenuRow, which the keyboard's focus and the pointer highlight alike;5// the list moves the focus among them.67import std::string;8import std::vector;9import std::option;10import std::math;11import std::time;12import pkg::alloy::window;13import pkg::alloy::draw;14import pkg::alloy::text as text;1516import pkg::alloy::ui;17import pkg::alloy::ui::store;18import pkg::alloy::ui::tree;19import pkg::alloy::ui::layout;20import pkg::alloy::ui::painting;21import pkg::alloy::ui::events;22import pkg::alloy::ui::widgets;23import pkg::alloy::ui::fields;24import pkg::alloy::ui::scrolling;25import pkg::alloy::ui::running;26import pkg::alloy::ui::timers;27import pkg::alloy::ui::layers;28import pkg::alloy::ui::motion;29import pkg::alloy::ui::transitions;30import pkg::alloy::ui::languages;31import pkg::alloy::ui::extensions;32import pkg::alloy::ui::views;33import ui_controls;3435// How long the pointer rests on an item before its submenu opens.36const SUBMENU_DELAY: u64 = 250;3738const ROW_PADDING: Padding = Padding { .start = 12.0, .top = 6.0, .end = 12.0, .bottom = 6.0 };39const LIST_PADDING: f32 = 4.0;40const SHORTCUT_GAP: f32 = 32.0;41const SEPARATOR: f32 = 9.0; // the room a line above an item takes42const CHECK: f32 = 14.0; // a checked item's mark, before its label43const CHECK_GAP: f32 = 8.0;4445// The items of a menu, their focus moved by the keys.46pub type MenuList : Widget = struct {47    pub children: &[Element],48    pub rows: Vector<Element>,49    pub layer: Layer,50    pub sub: bool, // a submenu, which Left closes51};5253// An item of a menu.54pub type MenuRow : Widget = struct {55    pub item: MenuItem,56    pub checks: bool = false, // some item of its menu is checked or not: the labels leave room57    pub open: Option<Layer> = ::None, // its submenu, while open58    pub laid: Option<*text::Layout> = ::None,59    pub hint: Option<*text::Layout> = ::None, // the shortcut, or a submenu's arrow60};6162// What the Ui calls of the menus once the first opens: the pointer coming63// onto an item, and Tab in a menu.64pub type Menus : Extension = struct {};6566pub fn hovered(self m: &var Menus, ui: &var Ui, index: u32) {67    if (ui.row(index) is ::Some) {68        ui.menu_hovered(index);69    }70}7172// Tab in a menu closes every menu and goes on from what opened it.73pub fn key(self m: &var Menus, ui: &var Ui, key: &KeyEvent) -> bool {74    if (75        key.pressed76        && plain_tab(&key)77        && ui.focused is ::Some |f|78        && ui.layer_of(f) is ::Some |k|79        && ui.layers.get(k).overlay.role is ::Menu80    ) {81        ui.close_menus();82        ui.move_focus(!key.modifiers.shift);83        return true;84    }85    return false;86}8788pub fn open_menu(self ui: &var Ui, place: Place, items: Vector<MenuItem>, sub: bool) -> Layer {89    if (ui.extension<Menus>() is ::None) {90        ui.install(new Menus {});91    }92    const keyboard = ui.focus_ring;93    const layer = ui.open_layer(94        Overlay { .place = place, .role = LayerRole::Menu },95        |move items, sub| (ui: &var Ui, layer: Layer) -> Element {96            var rows = Vector<Element>::empty();97            var checks = false;98            for (items.view()) |&item| {99                checks = checks || item.checked is ::Some;100            }101            for (items.view()) |&item| {102                rows.push(ui.add(MenuRow { .item = copy item, .checks = checks }));103            }104            return ui.add(MenuList {105                .children = &rows.view(),106                .rows = copy rows,107                .layer = layer,108                .sub = sub109            });110        }111    );112    // from the keyboard, the first item takes the focus at once113    if (keyboard && ui.layer_index(layer) is ::Some |k|) {114        const panel = ui.layers.get(k).panel;115        if (ui.menu_list(panel) is ::Some |list|) {116            ui.focus_row(list, Step::First);117        }118    }119    ui.press_opened(layer);120    return layer;121}122123// The menu list a menu's panel holds.124fn menu_list(self ui: &Ui, panel: u32) -> Option<u32> {125    if (ui.node(panel).children.try_get(0) is ::Some |&list|) {126        return ::Some(list);127    }128    return ::None;129}130131// Closes every menu open, submenus with them.132pub fn close_menus(self ui: &var Ui) {133    var k = ui.layers.length();134    while (k > 0) {135        k -= 1;136        if (k < ui.layers.length() && ui.layers.get(k).overlay.role is ::Menu) {137            ui.close_at(k);138        }139    }140}141142// Closes the menus opened above the layer at the index but the item's143// own submenu: those of another item than the one the focus came to.144fn close_menus_above(self ui: &var Ui, k: u64, item: u32) {145    var top = ui.layers.length();146    while (top > k + 1) {147        top -= 1;148        if (top >= ui.layers.length()) {149            continue;150        }151        const overlay = &ui.layers.get(top).overlay;152        var own = false;153        if (overlay.place is ::After |e| && e.index == item) {154            own = true;155        }156        if (overlay.role is ::Menu && !own) {157            ui.close_at(top);158        }159    }160}161162// The pointer came onto an item: it takes the focus, and its submenu163// opens after a moment's rest.164pub fn menu_hovered(self ui: &var Ui, index: u32) {165    if (!ui.takes_focus(index)) {166        return;167    }168    ui.focus_node(::Some(index), false);169    const row = ui.element(index);170    if (ui.row(index) is ::Some |&r| && r.item.submenu.length() > 0 && r.open is ::None) {171        ui.after(Duration::from_milliseconds(SUBMENU_DELAY), |row| (ui: &var Ui) {172            if (ui.has_focus(row)) {173                ui.open_submenu(row, false);174            }175        });176    }177}178179pub fn row(self ui: &Ui, index: u32) -> Option<&MenuRow> {180    if (ui.node(index).widget is ::Some |&widget| && widget is MenuRow |&r|) {181        return ::Some(&r);182    }183    return ::None;184}185186fn row_var(self ui: &var Ui, index: u32) -> Option<&var MenuRow> {187    if (ui.node_var(index).widget is ::Some |&var widget| && widget is MenuRow |&var r|) {188        return ::Some(&var r);189    }190    return ::None;191}192193// Opens the item's submenu beside it, belonging to its menu; from the194// keyboard its first item takes the focus.195fn open_submenu(self ui: &var Ui, row: Element, keyboard: bool) {196    var items = Vector<MenuItem>::empty();197    if (ui.row(row.index) is ::Some |&r|) {198        if (r.open is ::Some || r.item.submenu.length() == 0 || !r.item.enabled) {199            return;200        }201        items = copy r.item.submenu;202    }203    const saved = ui.handling;204    const ring = ui.focus_ring;205    ui.handling = ::Some(row.index);206    ui.focus_ring = keyboard;207    const layer = ui.open_menu(Place::After(row), move items, true);208    ui.handling = saved;209    if (!keyboard) {210        // the pointer opened it: the focus stays on the item211        ui.focus_node(::Some(row.index), false);212    }213    ui.focus_ring = if (keyboard) true else ring;214    if (ui.layer_index(layer) is ::Some |k|) {215        ui.layers.get_var(k).overlay.on_close = |row| (ui: &var Ui) {216            if (ui.exists(row) && ui.row_var(row.index) is ::Some |&var r|) {217                r.open = ::None;218                ui.apply(row.index, Change::Paint);219            }220        };221    }222    if (ui.row_var(row.index) is ::Some |&var r|) {223        r.open = ::Some(layer);224    }225    ui.apply(row.index, Change::Paint);226}227228// Chooses the item: its submenu opens, or every menu closes and its229// function runs, as a handler of no element.230fn choose(self ui: &var Ui, index: u32, keyboard: bool) {231    const r = if (ui.row(index) is ::Some |&r|) &r else {232        return;233    };234    if (!r.item.enabled) {235        return;236    }237    if (r.item.submenu.length() > 0) {238        ui.open_submenu(ui.element(index), keyboard);239        return;240    }241    const chosen = copy r.item.on_select;242    ui.close_menus();243    const saved = ui.handling;244    ui.handling = ::None;245    chosen(&var ui);246    ui.handling = saved;247}248249// Where the focus goes among a list's items.250type Step = enum {251    First,252    Last,253    Next,254    Previous,255    Letter: u32,256};257258// Moves the focus to the item the step names, among those enabled.259fn focus_row(self ui: &var Ui, list: u32, step: Step) {260    var rows = Vector<Element>::empty();261    if (ui.node(list).widget is ::Some |&widget| && widget is MenuList |&l|) {262        rows = copy l.rows;263    }264    const count = rows.length();265    if (count == 0) {266        return;267    }268    var at = Option<u64>::None;269    for (rows.view(), [..count]) |&row, k| {270        if (ui.has_focus(row)) {271            at = ::Some(k);272        }273    }274    const enabled = |&ui, &rows| (k: u64) -> bool => ui.takes_focus(rows.get(k).index);275    var found = Option<u64>::None;276    match (step) {277        ::First, ::Last {278            for ([..count]) |n| {279                const k = if (step is ::First) n else count - 1 - n;280                if (found is ::None && enabled(k)) {281                    found = ::Some(k);282                }283            }284        }285        ::Next, ::Previous, ::Letter {286            const start = if (at is ::Some |k|) k else if (step is ::Previous) 0 else count - 1;287            for ([1..count + 1]) |n| {288                const k = if (step is ::Previous) (start + count * 2 - n) % count else (start + n)289                    % count;290                if (found is ::None && enabled(k)) {291                    if (step is ::Letter |c|) {292                        if (293                            ui.row(rows.get(k).index) is ::Some |&r|294                            && starts_with(&r.item.label, c)295                        ) {296                            found = ::Some(k);297                        }298                    } else {299                        found = ::Some(k);300                    }301                }302            }303        }304    }305    if (found is ::Some |k|) {306        ui.focus_node(::Some(rows.get(k).index), true);307    }308}309310// Whether the label starts with the character, ASCII letters in either311// case.312fn starts_with(label: &String, c: u32) -> bool {313    const text = &label.view();314    if (text.length() == 0) {315        return false;316    }317    return fold(text[0] to u32) == fold(c);318}319320fn fold(c: u32) -> u32 => if (c >= 'A' to u32 && c <= 'Z' to u32) c + 32 else c;321322/* --- The list --- */323324pub fn layout(self l: &var MenuList, arrange: &var Arrange, limits: Limits) -> Extent {325    const inner = Limits {326        .max_width = max(limits.max_width - 2.0 * LIST_PADDING, 0.0),327        .max_height = UNBOUNDED328    };329    var width: f32 = 160.0;330    for ([..arrange.count()]) |k| {331        width = max(width, arrange.lay_out(k, inner).width);332    }333    width = min(width, inner.max_width);334    var y = LIST_PADDING;335    for ([..arrange.count()]) |k| {336        const size = arrange.lay_out(k, Limits { .min_width = width, .max_width = width });337        arrange.place(k, Point { .x = LIST_PADDING, .y = y });338        y += size.height;339    }340    return limits.constrain(Extent {341        .width = width + 2.0 * LIST_PADDING,342        .height = y + LIST_PADDING343    });344}345346exp fn paint(self l: &MenuList, look: &Look, paint: &var Paint) {}347348pub fn children(self l: &MenuList) -> &[Element] => &l.children;349350exp fn renew(self l: &var MenuList, next: MenuList) -> Change => Change::Nothing;351352// Taken by a press on the list's edge or when opened by the pointer, so353// the keys reach it before an item has the focus.354pub fn focusable(self l: &MenuList) -> bool => true;355356pub fn event(self l: &var MenuList, ui: &var Ui, input: &Input) -> bool {357    const k = if (input is ::Key |&k|) k else {358        return false;359    };360    const list = if (ui.handling is ::Some |h|) h else {361        return false;362    };363    const step: Option<Step> = match (k.key) {364        ::Down ::Some(Step::Next);365        ::Up ::Some(Step::Previous);366        ::Home, ::PageUp ::Some(Step::First);367        ::End, ::PageDown ::Some(Step::Last);368        ::Character |c| if (c != ' ' to u32 && !k.modifiers.control && !k.modifiers.alt) ::Some(369            Step::Letter(c)370        ) else ::None;371        else ::None;372    };373    if (step is ::Some |s|) {374        if (k.pressed) {375            ui.focus_row(list, s);376        }377        return true;378    }379    // Left closes a submenu, Right right to left, where it opened leftward380    const back = if (ui.handling_rtl()) k.key is ::Right else k.key is ::Left;381    if (back && l.sub) {382        if (k.pressed) {383            ui.close(l.layer);384        }385        return true;386    }387    return false;388}389390/* --- An item --- */391392pub fn layout(self r: &var MenuRow, arrange: &var Arrange, limits: Limits) -> Extent {393    const size = arrange.theme().text_size;394    var style = arrange.text_style(size);395    const fonts = &var arrange.fonts();396    const laid = text::Layout::fitted(&fonts, &r.item.label.view(), &style, UNBOUNDED);397    var width = ROW_PADDING.start + r.lead() + laid.width + ROW_PADDING.end;398    var height = ROW_PADDING.top + laid.height + ROW_PADDING.bottom;399    r.hint = ::None;400    // a submenu's arrow points where it opens, to the end: mirrored right401    // to left402    const hinted: &[u8] = if (r.item.submenu.length() > 0) &"›" else &r.item.shortcut.view();403    if (hinted.length() > 0) {404        style.size = size * 0.9;405        const hint = text::Layout::fitted(&fonts, &hinted, &style, UNBOUNDED);406        width += SHORTCUT_GAP + hint.width;407        r.hint = ::Some(new hint);408    }409    if (r.item.separated) {410        height += SEPARATOR;411    }412    r.laid = ::Some(new laid);413    return limits.constrain(Extent { .width = width, .height = height });414}415416// The room before the label: a check mark's in a menu with some.417fn lead(self r: &MenuRow) -> f32 => if (r.checks) CHECK + CHECK_GAP else 0.0;418419exp fn paint(self r: &MenuRow, look: &Look, paint: &var Paint) {420    const theme = &look.theme;421    const top = if (r.item.separated) SEPARATOR else 0.0;422    if (r.item.separated) {423        paint.rect(424            Rect::at(425                ROW_PADDING.start / 2.0,426                SEPARATOR / 2.0 - 0.5,427                look.size.width - ROW_PADDING.start,428                1.0429            ),430            Fill::Color(theme.border)431        );432    }433    const area = Rect::at(0.0, top, look.size.width, look.size.height - top);434    const lit = r.item.enabled && (look.focused || look.hovered || r.open is ::Some);435    if (lit) {436        var fill = theme.primary;437        fill.a = if (look.pressed) 0.24 else 0.14;438        paint.rounded_rect(area, Radii::all(theme.radius - 2.0), Fill::Color(fill));439    }440    var ink = theme.text;441    if (!r.item.enabled) {442        ink.a = 0.45;443    }444    if (r.item.checked == ::Some(true) && look.marks.check is ::Some |mark|) {445        paint.mask(446            Rect::at(447                look.from_start(ROW_PADDING.start, CHECK),448                top + (area.height - CHECK) / 2.0,449                CHECK,450                CHECK451            ),452            mark,453            ink454        );455    }456    if (r.laid is ::Some |&laid|) {457        paint.text(458            &laid,459            Point {460                .x = look.from_start(ROW_PADDING.start + r.lead(), laid.width),461                .y = top + (area.height - laid.height) / 2.0462            },463            ink464        );465    }466    if (r.hint is ::Some |&hint|) {467        var muted = theme.muted;468        if (!r.item.enabled) {469            muted.a = 0.45;470        }471        paint.text(472            &hint,473            Point {474                .x = look.from_start(look.size.width - ROW_PADDING.end - hint.width, hint.width),475                .y = top + (area.height - hint.height) / 2.0476            },477            muted478        );479    }480}481482pub fn event(self r: &var MenuRow, ui: &var Ui, input: &Input) -> bool {483    const index = if (ui.handling is ::Some |h|) h else {484        return false;485    };486    match (input) {487        ::Click {488            ui.choose(index, false);489            return true;490        }491        ::Key |&k| {492            // Right opens a submenu, Left right to left493            const opens = if (ui.handling_rtl()) k.key is ::Left else k.key is ::Right;494            const activates = match (k.key) {495                ::Enter true;496                ::Character |c| c == ' ' to u32;497                else opens && r.item.submenu.length() > 0;498            };499            if (!activates) {500                return false;501            }502            if (k.pressed) {503                ui.choose(index, true);504            }505            return true;506        }507        ::Focus |focused| {508            // a submenu of another item of the same menu closes509            if (focused && ui.layer_of(index) is ::Some |k|) {510                ui.close_menus_above(k, index);511            }512            ui.refresh(Change::Paint);513            return false;514        }515        ::Action |&a| {516            match (a) {517                ::Expand {518                    ui.open_submenu(ui.element(index), true);519                }520                ::Collapse {521                    if (r.open is ::Some |layer|) {522                        ui.close(layer);523                    }524                }525                else {}526            }527            return true;528        }529        ::Press, ::Release {530            return true;531        }532        else {533            return false;534        }535    }536}537538exp fn renew(self r: &var MenuRow, next: MenuRow) -> Change => Change::Nothing;539540pub fn interactive(self r: &MenuRow) -> bool => true;541542pub fn focusable(self r: &MenuRow) -> bool => r.item.enabled;543544pub fn semantics(self r: &MenuRow) -> Semantics => Semantics {545    .role = if (r.item.checked is ::Some) Role::MenuItemCheckbox else Role::MenuItem,546    .checked = r.item.checked,547    .label = copy r.item.label,548    .description = copy r.item.shortcut,549    .disabled = !r.item.enabled,550    .focusable = r.item.enabled,551    .expanded = if (r.item.submenu.length() > 0) ::Some(r.open is ::Some) else ::None552};553554/* --- A button opening a menu --- */555556pub fn layout(self b: &var MenuButton, arrange: &var Arrange, limits: Limits) -> Extent {557    return button_layout(&var arrange, &b.label, &b.padding, limits, &var b.laid);558}559560exp fn paint(self b: &MenuButton, look: &Look, paint: &var Paint) {561    // held down while its menu is open562    paint_button(&b.laid, b.variant, b.enabled, b.open is ::Some, &look, &var paint);563}564565pub fn event(self b: &var MenuButton, ui: &var Ui, input: &Input) -> bool {566    if (!b.enabled) {567        return claims(&input);568    }569    match (input) {570        ::Press {571            // the pointer goes on to the menu, whose item a release572            // after a drag chooses573            b.open_menu_of(&var ui);574            ui.uncapture();575        }576        ::Click {577            // a screen reader's press, the pointer's having opened it578            ui.focus_ring = true;579            b.open_menu_of(&var ui);580        }581        ::Key |&k| {582            if (!activates(&k) && !(k.key is ::Down)) {583                return false;584            }585            if (k.pressed && b.open is ::None) {586                ui.focus_ring = true;587                b.open_menu_of(&var ui);588            }589        }590        ::Action |&a| {591            match (a) {592                ::Expand {593                    b.open_menu_of(&var ui);594                }595                ::Collapse {596                    if (b.open is ::Some |layer|) {597                        ui.close(layer);598                    }599                }600                else {}601            }602        }603        else {}604    }605    return claims(&input);606}607608// Opens the button's menu below it, unless open.609fn open_menu_of(self b: &var MenuButton, ui: &var Ui) {610    if (b.open is ::Some) {611        return;612    }613    const button = ui.source();614    const layer = ui.open_menu(Place::Below(button), copy b.items, false);615    if (ui.layer_index(layer) is ::Some |k|) {616        ui.layers.get_var(k).overlay.on_close = |button| (ui: &var Ui) {617            if (618                ui.exists(button)619                && ui.node_var(button.index).widget is ::Some |&var widget|620                && widget is MenuButton |&var b|621            ) {622                b.open = ::None;623                ui.apply(button.index, Change::Paint);624            }625        };626        b.open = ::Some(layer);627        ui.refresh(Change::Paint);628    }629}630631exp fn renew(self b: &var MenuButton, next: MenuButton) -> Change {632    const relayout = b.label != next.label || b.padding != next.padding || b.sizing != next.sizing;633    b.label = move next.label;634    b.accessible = move next.accessible;635    b.items = move next.items;636    b.variant = next.variant;637    b.enabled = next.enabled;638    b.padding = next.padding;639    b.sizing = next.sizing;640    if (relayout) {641        b.laid = ::None;642        return Change::Layout;643    }644    return Change::Paint;645}646647pub fn sizing(self b: &MenuButton) -> Sizing => b.sizing;648pub fn interactive(self b: &MenuButton) -> bool => true;649pub fn focusable(self b: &MenuButton) -> bool => b.enabled;650pub fn cursor(self b: &MenuButton) -> Cursor => if (b.enabled) Cursor::Hand else Cursor::Arrow;651652pub fn semantics(self b: &MenuButton) -> Semantics => Semantics {653    .role = Role::Button,654    .label = said(&b.accessible, &b.label),655    .disabled = !b.enabled,656    .focusable = b.enabled,657    .expanded = ::Some(b.open is ::Some)658};