Add the pure MoonBit core: grid, gestures, updater, vdom, app

grid: packing, pinning, resize steps (port of Layout.js and app.py's grid logic).
gesture: pointer state machine (tap, long press, drag, release, swipe).
updater: release/version parsing and the update decision.
vdom: pure virtual DOM with an HTML-text renderer for tests.
app: Elm-style Model/Msg/update/view with effects as data, persistence (JSON
layout, import of the old WebView build's localStorage), drawer/search, menus,
drag and resize. 60 headless tests drive it through pointer input.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
SpriteandClaude Sonnet 5.5 committed 2026-11-23 00:55:16 +00:00
1 parent 66e8e90da1
commit 28e0284d9b
28 files changed
+4278

No files matched your search

+307
View File
@@ -0,0 +1,307 @@
///|
/// The launcher as an Elm-style program, pure: `Model`, `Msg`, `update` (returns the
/// `Effect`s for the platform to run) and `view` (returns a `vdom` tree). It ports
/// legacy/web/app.py, the LPython app, and the gesture handling that lived in its
/// index.html. Nothing here touches a platform: the web/ package runs the effects and
/// renders the tree, and the tests below drive the whole thing headlessly.
///|
pub(all) struct AppInfo {
label : String
component : String
icon : String
/// A system app: it has no Uninstall.
system : Bool
}
///|
pub(all) struct WidgetInfo {
label : String
provider : String
icon : String
/// The label of the app the widget comes from (for the picker's search).
app : String
/// Natural height in CSS px.
h : Int
}
///|
/// How a widget may be resized, in CSS px (the shell's `widgetLimits`): its natural
/// width, min/max size (0: no max), and whether it resizes horizontally / vertically.
pub(all) struct Limits {
w : Int
min_w : Int
min_h : Int
max_w : Int
max_h : Int
h : Bool
v : Bool
}
///|
pub let default_limits : Limits = {
w: 0,
min_w: 120,
min_h: 80,
max_w: 0,
max_h: 0,
h: true,
v: true,
}
///|
#derive(Eq, Debug)
pub(all) enum Sheet {
NoSheet
/// The menu of the empty home.
HomeMenu
/// The menu of a home slot.
Item(Int)
/// The menu of a drawer app (row in the app list).
DrawerApp(Int)
WidgetPicker
}
///|
#derive(Eq, Debug)
pub(all) enum Edge {
Right
Bottom
Corner
}
///|
/// A resize in progress: a handle was pressed on the widget whose box (px, viewport) was
/// at `left`, `top`.
pub(all) struct ResizeDrag {
edge : Edge
slot : Int
left : Double
top : Double
mut cols : Int
mut rows : Int
}
///|
/// Where the lifted slot was held, and the cell it was last sent to.
pub(all) struct Carry {
dx : Double
dy : Double
mut cell : Int
}
///|
pub(all) struct Model {
mut apps : Array[AppInfo]
mut loading : Bool
mut load_error : String
mut widgets : Array[WidgetInfo]
mut wloading : Bool
/// The home screen, in order.
mut home : Array[@grid.Slot]
mut next_key : Int
/// Grid columns, and rows that fill the screen (0 until the page has measured).
mut cols : Int
mut nrows : Int
/// Where the grid is on the screen (px, viewport) and how wide a column is.
mut grid_left : Double
mut grid_top : Double
mut col_w : Double
mut query : String
mut wquery : String
mut drawer : Bool
/// The drawer is in "add apps" mode: taps toggle home slots.
mut picking : Bool
mut sheet : Sheet
/// The package being uninstalled: its home slot goes when it leaves the app list.
mut gone : String
/// Home slot picked up by a long press, being dragged.
mut lifted : Int
/// Widget slot showing resize handles.
mut resizing : Int
/// The lifted slot was grabbed while showing handles: drop it back into them.
mut regrab : Bool
mut carry : Carry?
mut resize : ResizeDrag?
/// Native widget views report their drags through `NativeDrag`; where it began.
mut native_from : (Double, Double)?
/// Widget row being added.
mut chosen : Int
mut limits : Map[Int, Limits]
mut notice : String
mut notice_gen : Int
// ---- self-update
mut installed : Int
mut declined : Int
mut checking : Bool
mut manual_check : Bool
mut apk_url : String?
mut release_tag : String
/// The layout JSON last handed to `SaveHome`.
mut saved : String
/// A pointer drag (lift or resize) happened since the pointer went down: the swipe
/// check that follows the touch ignores it.
mut dragged : Bool
/// A widget just added whose limits will set its starting width.
mut fresh : Int
mut gesture : @gesture.State
}
///|
pub fn Model::new() -> Model {
{
apps: [],
loading: true,
load_error: "",
widgets: [],
wloading: false,
home: [],
next_key: 1,
cols: 5,
nrows: 0,
grid_left: 0.0,
grid_top: 0.0,
col_w: 0.0,
query: "",
wquery: "",
drawer: false,
picking: false,
sheet: NoSheet,
gone: "",
lifted: -1,
resizing: -1,
regrab: false,
carry: None,
resize: None,
native_from: None,
chosen: -1,
limits: {},
notice: "",
notice_gen: 0,
installed: 0,
declined: -1,
checking: false,
manual_check: false,
apk_url: None,
release_tag: "",
saved: "",
dragged: false,
fresh: -1,
gesture: @gesture.State::new(),
}
}
///|
/// The most slots the home screen holds.
pub let home_cap : Int = 200
///|
pub let app_cap : Int = 512
///|
#derive(Eq, Debug)
/// What a view node can send. Raw pointer input goes through `Input` and the gesture
/// recogniser first; everything else is a Msg a handler or the shell sends directly.
pub(all) enum Msg {
// ---- from the platform
/// Boot: the saved layout (this app's JSON, and the old WebView build's
/// `ultra.home.*` localStorage as a JSON object), the clock, and the self-update state.
Restore(saved~ : String?, legacy~ : String?)
Started(now~ : Int64, last_check~ : Int64, declined~ : Int, installed~ : Int)
/// The page measured itself: viewport size, and where the home grid is.
Measured(vw~ : Int, vh~ : Int, grid_left~ : Double, grid_top~ : Double, grid_w~ : Double, bottom_pad~ : Double)
AppsLoaded(String?)
WidgetsLoaded(String?)
/// The shell's answer to `QueryLimits`.
LimitsKnown(Int, String?)
/// A package changed: look at the app list again.
Reload
/// The Home button or intent.
GoHome
Back
WidgetAdded(Int)
/// A long press on a native widget view lifts its slot.
WidgetMenu(Int)
/// A press on the native view of the widget showing handles picks it up.
WidgetGrab(Int)
NativeDrag(Double, Double)
NativeDrop(Bool)
/// The swipe the page saw: dx, dy, ms, whether the home is scrolled to the top, and
/// whether the drawer's list is at its end.
Touch(dx~ : Double, dy~ : Double, ms~ : Int, home_top~ : Bool, list_end~ : Bool)
ReleaseFetched(String?)
VersionFetched(String?)
UpdateDeclined(Int)
NoticeDone(Int)
// ---- from handlers
Query(String)
Clear
WQuery(String)
WClear
OpenDrawer
CloseDrawer
OpenApp(Int)
OpenFirst
OpenHome(Int)
AddHome(Int)
ToggleHome(Int)
AppMenu(Int)
AppInfoOf(Int)
UninstallOf(Int)
Menu
CloseSheet
PickApps
PickWidget
ChooseWidget(Int)
ChooseFirstWidget
Remove(Int)
/// Swap the slot with the one before it.
MoveEarlier(Int)
InfoOf(Int)
Settings
Wallpaper
Recents
CheckUpdates
Lift(Int)
Grab(Int)
ResizeBegin(Edge)
ResizeDone
/// Does nothing; stands in a chain to stop a tap reaching an element below.
Nop
/// The recogniser saw a drag / the pointer lift (see `input`).
Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
Released(moved~ : Bool, held~ : Bool)
}
///|
#derive(Eq, Debug)
pub(all) enum Effect {
Launch(String)
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int)
OpenSettings
PickWallpaper
OpenRecents
Haptic
/// Fetch apps.json / widgets.json and answer `AppsLoaded` / `WidgetsLoaded`.
LoadApps
LoadWidgets
/// Ask the shell for a widget's limits and answer `LimitsKnown`.
QueryLimits(Int)
SaveHome(String)
SaveLastCheck(Int64)
SaveDeclined(Int)
/// Send the message after this many ms.
Delay(Int, Msg)
/// After this many ms, feed `Hold(token)` to `input` (the long-press timer).
HoldTimer(Int, Int)
FetchRelease(String)
FetchVersion(String)
InstallApk(String, Int)
/// The drawer opened with its search in front: focus it and raise the keyboard.
FocusSearch
HideKeyboard
ScrollTop
}
+10
View File
@@ -0,0 +1,10 @@
import {
"experiments/launcher/grid",
"experiments/launcher/gesture",
"experiments/launcher/updater",
"experiments/launcher/vdom",
"experiments/launcher/jsonx",
"moonbitlang/core/json",
"moonbitlang/core/cmp",
"moonbitlang/core/string",
}
+175
View File
@@ -0,0 +1,175 @@
///|
/// The saved home layout as JSON:
/// `{"v":1,"slots":[{"kind":"app","str":COMPONENT,"x":-1,"y":-1},
/// {"kind":"widget","str":LABEL,"wid":ID,"w":COLS,"rows":ROWS,"x":-1,"y":-1}]}`.
pub fn save_json(home : Array[@grid.Slot]) -> String {
let slots : Array[Json] = home.map(fn(s) {
match s.kind {
App => { "kind": "app", "str": s.str, "x": s.x, "y": s.y }
Widget =>
{
"kind": "widget",
"str": s.str,
"wid": s.wid,
"w": s.w,
"rows": s.rows,
"x": s.x,
"y": s.y,
}
}
})
Json::object({ "v": 1, "slots": Json::array(slots) }).stringify()
}
///|
/// Read a saved layout; `None` if the text is not one. Slots without a name are
/// dropped, and no more than `home_cap` are kept.
pub fn load_json(text : String, next_key : Ref[Int]) -> Array[@grid.Slot]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "slots") is Some(Array(_)) else { return None }
let out : Array[@grid.Slot] = []
for s in @jsonx.arr(j, "slots") {
let str = @jsonx.str(s, "str")
if str == "" || out.length() >= home_cap {
continue
}
let slot = if @jsonx.str(s, "kind") == "widget" {
@grid.Slot::widget(
str,
@jsonx.int(s, "wid"),
w=@cmp.maximum(0, @jsonx.int(s, "w")),
rows=@cmp.maximum(1, @jsonx.int(s, "rows", default=1)),
key=take_key(next_key),
)
} else {
@grid.Slot::app(str, key=take_key(next_key))
}
slot.x = @jsonx.int(s, "x", default=-1)
slot.y = @jsonx.int(s, "y", default=-1)
out.push(slot)
}
Some(out)
}
///|
fn take_key(next_key : Ref[Int]) -> Int {
let k = next_key.val
next_key.val = k + 1
k
}
///|
/// The WebView build kept its home in localStorage as `ultra.home.n` and, for slot i,
/// `ultra.home.{kind,str,wid,h,w,cx,cy}.i` (all strings; kind 1 is a widget, `h` its
/// height in px, `cx`/`cy` the pinned cell). `text` is those keys as a JSON object. Widget
/// heights in px become whole rows.
pub fn legacy_import(text : String, next_key : Ref[Int]) -> Array[@grid.Slot] {
guard @jsonx.parse(text) is Some(kv) else { return [] }
fn num(k : String, i : Int, d : Int) -> Int {
match @jsonx.get(kv, "ultra.home.\{k}.\{i}") {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => d
}
Some(Number(n, ..)) => n.to_int()
_ => d
}
}
let n = num2(kv, "ultra.home.n")
let out : Array[@grid.Slot] = []
for i in 0..<n {
let str = match @jsonx.get(kv, "ultra.home.str.\{i}") {
Some(String(s)) => s
_ => ""
}
if str == "" || out.length() >= home_cap {
continue
}
let slot = if num("kind", i, 0) == 1 {
@grid.Slot::widget(
str,
num("wid", i, 0),
w=@cmp.maximum(0, num("w", i, 0)),
rows=@grid.widget_rows(num("h", i, 120)),
key=take_key(next_key),
)
} else {
@grid.Slot::app(str, key=take_key(next_key))
}
slot.x = num("cx", i, -1)
slot.y = num("cy", i, -1)
out.push(slot)
}
out
}
///|
fn num2(kv : Json, key : String) -> Int {
match @jsonx.get(kv, key) {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => 0
}
Some(Number(n, ..)) => n.to_int()
_ => 0
}
}
///|
/// The apps.json the shell (or the demo) serves: `{"apps": [{"label", "component",
/// "icon", "system"}]}`, capped at `app_cap`.
pub fn parse_apps(text : String) -> Array[AppInfo]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "apps") is Some(Array(_)) else { return None }
let out : Array[AppInfo] = []
for a in @jsonx.arr(j, "apps") {
if out.length() >= app_cap {
break
}
out.push({
label: @jsonx.str(a, "label"),
component: @jsonx.str(a, "component"),
icon: @jsonx.str(a, "icon"),
system: @jsonx.bool(a, "system"),
})
}
Some(out)
}
///|
/// widgets.json: `{"widgets": [{"label", "app", "provider", "icon", "h"}]}`.
pub fn parse_widgets(text : String) -> Array[WidgetInfo]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "widgets") is Some(Array(_)) else { return None }
let out : Array[WidgetInfo] = []
for w in @jsonx.arr(j, "widgets") {
if out.length() >= 256 {
break
}
out.push({
label: @jsonx.str(w, "label"),
provider: @jsonx.str(w, "provider"),
icon: @jsonx.str(w, "icon"),
app: @jsonx.str(w, "app"),
h: @jsonx.int(w, "h"),
})
}
Some(out)
}
///|
/// The shell's `widgetLimits` JSON (`{"w","minW","minH","maxW","maxH","h","v"}`);
/// missing fields take the defaults.
pub fn parse_limits(text : String) -> Limits {
guard @jsonx.parse(text) is Some(j) else { return default_limits }
{
w: @jsonx.int(j, "w"),
min_w: @jsonx.int(j, "minW"),
min_h: @jsonx.int(j, "minH"),
max_w: @jsonx.int(j, "maxW"),
max_h: @jsonx.int(j, "maxH"),
h: @jsonx.bool(j, "h", default=true),
v: @jsonx.bool(j, "v", default=true),
}
}
+243
View File
@@ -0,0 +1,243 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/app"
import {
"experiments/launcher/gesture",
"experiments/launcher/grid",
"experiments/launcher/vdom",
"moonbitlang/core/debug",
"moonbitlang/core/ref",
}
// Values
pub let app_cap : Int32
pub let default_limits : Limits
pub fn handler_table(Array[@vdom.Node[Msg]]) -> Array[@vdom.Handlers[Msg]]
pub let home_cap : Int32
pub fn input(Model, Array[@vdom.Handlers[Msg]], @gesture.Input) -> Array[Effect]
pub fn key(Model, Array[@vdom.Handlers[Msg]], Array[Int32], Key) -> Array[Effect]
pub fn legacy_import(String, @ref.Ref[Int32]) -> Array[@grid.Slot]
pub fn load_json(String, @ref.Ref[Int32]) -> Array[@grid.Slot]?
pub fn matches_query(String, String) -> Bool
pub fn parse_apps(String) -> Array[AppInfo]?
pub fn parse_limits(String) -> Limits
pub fn parse_widgets(String) -> Array[WidgetInfo]?
pub fn save_json(Array[@grid.Slot]) -> String
pub fn typed(Model, Array[@vdom.Handlers[Msg]], Array[Int32], String) -> Array[Effect]
pub fn update(Model, Msg) -> Array[Effect]
pub fn view(Model) -> Array[@vdom.Node[Msg]]
// Errors
// Types and methods
pub(all) struct AppInfo {
label : String
component : String
icon : String
system : Bool
}
pub(all) struct Carry {
dx : Double
dy : Double
mut cell : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Edge {
Right
Bottom
Corner
}
pub(all) enum Effect {
Launch(String)
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int32)
OpenSettings
PickWallpaper
OpenRecents
Haptic
LoadApps
LoadWidgets
QueryLimits(Int32)
SaveHome(String)
SaveLastCheck(Int64)
SaveDeclined(Int32)
Delay(Int32, Msg)
HoldTimer(Int32, Int32)
FetchRelease(String)
FetchVersion(String)
InstallApk(String, Int32)
FocusSearch
HideKeyboard
ScrollTop
}
pub(all) enum Key {
Enter
Escape
}
pub(all) struct Limits {
w : Int32
min_w : Int32
min_h : Int32
max_w : Int32
max_h : Int32
h : Bool
v : Bool
}
pub(all) struct Model {
mut apps : Array[AppInfo]
mut loading : Bool
mut load_error : String
mut widgets : Array[WidgetInfo]
mut wloading : Bool
mut home : Array[@grid.Slot]
mut next_key : Int32
mut cols : Int32
mut nrows : Int32
mut grid_left : Double
mut grid_top : Double
mut col_w : Double
mut query : String
mut wquery : String
mut drawer : Bool
mut picking : Bool
mut sheet : Sheet
mut gone : String
mut lifted : Int32
mut resizing : Int32
mut regrab : Bool
mut carry : Carry?
mut resize : ResizeDrag?
mut native_from : (Double, Double)?
mut chosen : Int32
mut limits : Map[Int32, Limits]
mut notice : String
mut notice_gen : Int32
mut installed : Int32
mut declined : Int32
mut checking : Bool
mut manual_check : Bool
mut apk_url : String?
mut release_tag : String
mut saved : String
mut dragged : Bool
mut fresh : Int32
mut gesture : @gesture.State
}
pub fn Model::app_row(Self, String) -> Int32
pub fn Model::first_match(Self) -> Int32
pub fn Model::first_widget_match(Self) -> Int32
pub fn Model::hidden(Self, Int32) -> Bool
pub fn Model::home_of(Self, Int32) -> Int32
pub fn Model::new() -> Self
pub fn Model::packed(Self) -> @grid.Packed
pub fn Model::slot_of_widget(Self, Int32) -> Int32
pub fn Model::widget_matches(Self, Int32) -> Bool
pub(all) enum Msg {
Restore(saved~ : String?, legacy~ : String?)
Started(now~ : Int64, last_check~ : Int64, declined~ : Int32, installed~ : Int32)
Measured(vw~ : Int32, vh~ : Int32, grid_left~ : Double, grid_top~ : Double, grid_w~ : Double, bottom_pad~ : Double)
AppsLoaded(String?)
WidgetsLoaded(String?)
LimitsKnown(Int32, String?)
Reload
GoHome
Back
WidgetAdded(Int32)
WidgetMenu(Int32)
WidgetGrab(Int32)
NativeDrag(Double, Double)
NativeDrop(Bool)
Touch(dx~ : Double, dy~ : Double, ms~ : Int32, home_top~ : Bool, list_end~ : Bool)
ReleaseFetched(String?)
VersionFetched(String?)
UpdateDeclined(Int32)
NoticeDone(Int32)
Query(String)
Clear
WQuery(String)
WClear
OpenDrawer
CloseDrawer
OpenApp(Int32)
OpenFirst
OpenHome(Int32)
AddHome(Int32)
ToggleHome(Int32)
AppMenu(Int32)
AppInfoOf(Int32)
UninstallOf(Int32)
Menu
CloseSheet
PickApps
PickWidget
ChooseWidget(Int32)
ChooseFirstWidget
Remove(Int32)
MoveEarlier(Int32)
InfoOf(Int32)
Settings
Wallpaper
Recents
CheckUpdates
Lift(Int32)
Grab(Int32)
ResizeBegin(Edge)
ResizeDone
Nop
Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
Released(moved~ : Bool, held~ : Bool)
}
pub(all) struct ResizeDrag {
edge : Edge
slot : Int32
left : Double
top : Double
mut cols : Int32
mut rows : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Sheet {
NoSheet
HomeMenu
Item(Int32)
DrawerApp(Int32)
WidgetPicker
}
pub(all) struct WidgetInfo {
label : String
provider : String
icon : String
app : String
h : Int32
}
// Type aliases
// Traits
+826
View File
@@ -0,0 +1,826 @@
///|
/// A headless harness: a model, its rendered tree, and pointer input aimed at elements
/// found by class and text, as the page would aim it.
///|
let apps_json : String =
#|{"apps":[
#|{"label":"Calculator","component":"c.calc/.Main","icon":"i1"},
#|{"label":"Calendar","component":"c.cal/.Main","icon":"i2"},
#|{"label":"Chrome","component":"c.chrome/.Main","icon":"i3"},
#|{"label":"Gmail","component":"c.gmail/.Main","icon":"i4"},
#|{"label":"Phone","component":"c.phone/.Main","icon":"i5","system":true},
#|{"label":"Weather","component":"c.weather/.Main","icon":"i6"}]}
///|
let widgets_json : String =
#|{"widgets":[
#|{"label":"Clock","app":"Clock","provider":"c.clock/.W","icon":"w1","h":140},
#|{"label":"Weather","app":"Google","provider":"c.google/.W","icon":"w2","h":120},
#|{"label":"Calendar","app":"Calendar","provider":"c.cal/.W","icon":"w3","h":200}]}
///|
struct Sim {
m : Model
mut tree : Array[@vdom.Node[Msg]]
mut table : Array[@vdom.Handlers[Msg]]
log : Array[Effect]
mut last_x : Double
mut last_y : Double
}
///|
fn Sim::new() -> Sim {
let m = Model::new()
let s = { m, tree: [], table: [], log: [], last_x: 0.0, last_y: 0.0 }
s.run(update(m, Restore(saved=None, legacy=None)))
s.send(Measured(vw=390, vh=800, grid_left=16.0, grid_top=150.0, grid_w=358.0, bottom_pad=24.0))
s.send(AppsLoaded(Some(apps_json)))
s
}
///|
fn Sim::refresh(self : Sim) -> Unit {
self.tree = view(self.m)
self.table = handler_table(self.tree)
}
///|
fn Sim::run(self : Sim, fx : Array[Effect]) -> Unit {
for e in fx {
self.log.push(e)
}
self.refresh()
}
///|
fn Sim::send(self : Sim, msg : Msg) -> Unit {
self.run(update(self.m, msg))
}
///|
fn text_of(n : @vdom.Node[Msg]) -> String {
match n {
Text(s) => s
El(e) => e.children.map(text_of).join("")
}
}
///|
/// The chain (handler numbers, innermost first) of the first element matching `pred`.
fn Sim::chain_where(
self : Sim,
pred : (@vdom.Element[Msg]) -> Bool,
from? : Int = 0,
) -> Array[Int]? {
let mut counter = 0
let mut found : Array[Int]? = None
let stack : Array[Int] = []
fn walk(n : @vdom.Node[Msg]) -> Unit {
if found is Some(_) {
return
}
if n is El(e) {
let has = !e.handlers.is_empty()
if has {
stack.push(counter)
counter += 1
}
if pred(e) {
found = Some(stack.rev())
return
}
for c in e.children {
walk(c)
}
if has {
ignore(stack.pop())
}
}
}
let mut top = 0
for n in self.tree {
if top < from {
walk_count(n, fn() { counter += 1 })
} else {
walk(n)
}
top += 1
}
found
}
///|
/// Count the handler-bearing elements below a node without matching (to keep numbering).
fn walk_count(n : @vdom.Node[Msg], bump : () -> Unit) -> Unit {
if n is El(e) {
if !e.handlers.is_empty() {
bump()
}
for c in e.children {
walk_count(c, bump)
}
}
}
///|
fn Sim::chain(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
) -> Array[Int] {
match
self.chain_where(from~, fn(e) {
e.classes.contains(class) &&
(label == "" || text_of(El(e)).contains(label))
}) {
Some(c) => c
None => abort("no .\{class} \{label} in the tree")
}
}
///|
fn Sim::feed(self : Sim, inp : @gesture.Input) -> Unit {
self.run(input(self.m, self.table, inp))
}
///|
fn Sim::press(self : Sim, chain : Array[Int], x? : Double = 0.0, y? : Double = 0.0) -> Unit {
self.feed(Down(x~, y~, chain~))
self.last_x = x
self.last_y = y
}
///|
fn Sim::hold(self : Sim) -> Unit {
let mut token = -1
for e in self.log {
if e is HoldTimer(_, t) {
token = t
}
}
self.feed(Hold(token))
}
///|
fn Sim::move_to(self : Sim, x : Double, y : Double) -> Unit {
self.feed(Move(x~, y~))
self.last_x = x
self.last_y = y
}
///|
fn Sim::release(self : Sim) -> Unit {
self.feed(Up(x=self.last_x, y=self.last_y))
}
///|
fn Sim::tap(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
) -> Unit {
self.press(self.chain(class, label~, from~))
self.release()
}
///|
fn Sim::long_press(self : Sim, chain : Array[Int], x? : Double = 0.0, y? : Double = 0.0) -> Unit {
self.press(chain, x~, y~)
self.hold()
self.release()
}
///|
fn Sim::home_names(self : Sim) -> Array[String] {
self.m.home.map(fn(s) {
if s.kind == Widget {
"[" + s.str + "]"
} else {
self.m.apps[self.m.app_row(s.str)].label
}
})
}
///|
/// The sheet (dialog) as HTML.
fn Sim::sheet_html(self : Sim) -> String {
for n in self.tree {
if n is El(e) && e.classes.contains("sheet") {
return @vdom.to_html(n)
}
}
""
}
///|
fn Sim::has_effect(self : Sim, e : Effect) -> Bool {
self.log.contains(e)
}
///|
/// Centre of the cell (col, row) in viewport px.
fn cell_center(col : Int, row : Int) -> (Double, Double) {
(
16.0 + col.to_double() * (65.2 + 8.0) + 32.6,
150.0 + row.to_double() * 72.0 + 32.0,
)
}
///|
/// Add apps to the home screen through the long-press menu and the drawer's pick mode.
fn Sim::add_apps(self : Sim, labels : Array[String]) -> Unit {
self.long_press(self.chain("home"))
self.tap("sheet-item", label="Add apps")
for l in labels {
self.tap("tile", label=l, from=1) // the drawer's, not the home screen's under it
}
self.tap("btn", label="Done")
}
///|
test "boot: blank home with a hint, apps load" {
let s = Sim::new()
assert_true(s.has_effect(LoadApps))
assert_eq(s.m.apps.length(), 6)
assert_eq(s.m.home.length(), 0)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("Swipe down for all apps"))
}
///|
test "long press on the blank home opens the menu; Check for updates closes it" {
let s = Sim::new()
s.long_press(s.chain("home"))
assert_eq(s.m.sheet, HomeMenu)
assert_true(s.has_effect(Haptic))
s.tap("sheet-item", label="Check for updates")
assert_eq(s.m.sheet, NoSheet)
assert_true(s.has_effect(FetchRelease(@updater.release_api)))
assert_eq(s.m.notice, "Checking for updates…")
}
///|
test "add apps through the drawer's pick mode" {
let s = Sim::new()
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Add apps")
assert_true(s.m.drawer && s.m.picking)
assert_true(!s.has_effect(FocusSearch)) // picking is for scrolling: no keyboard
s.tap("tile", label="Chrome", from=1)
s.tap("tile", label="Gmail", from=1)
s.tap("tile", label="Phone", from=1)
s.tap("tile", label="Gmail", from=1) // toggled off again
s.tap("btn", label="Done")
assert_true(!s.m.drawer)
assert_eq(s.home_names(), ["Chrome", "Phone"])
}
///|
test "swipe down opens the drawer, swipe up closes it" {
let s = Sim::new()
s.send(Touch(dx=3.0, dy=120.0, ms=200, home_top=true, list_end=false))
assert_true(s.m.drawer)
assert_true(s.has_effect(FocusSearch))
s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=false))
assert_true(s.m.drawer) // the list isn't at its end yet
s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=true))
assert_true(!s.m.drawer)
assert_true(s.has_effect(HideKeyboard))
s.send(Touch(dx=3.0, dy=40.0, ms=200, home_top=true, list_end=false))
assert_true(!s.m.drawer) // too short
}
///|
test "the home search pill opens the drawer" {
let s = Sim::new()
s.tap("search-pill")
assert_true(s.m.drawer && !s.m.picking)
assert_true(s.has_effect(FocusSearch))
}
///|
test "search filters the drawer; Enter opens the first match" {
let s = Sim::new()
s.send(OpenDrawer)
let names = fn() {
let out : Array[String] = []
for n in s.tree {
ignore(n)
}
for a in s.m.apps {
if matches_query(a.label, s.m.query) {
out.push(a.label)
}
}
out
}
assert_eq(names().length(), 6)
let input_chain = s.chain("input")
s.run(typed(s.m, s.table, input_chain, "ca"))
assert_eq(names(), ["Calculator", "Calendar", "Camera".to_string()].filter(fn(x) { x != "Camera" }))
s.run(typed(s.m, s.table, input_chain, " CAL"))
assert_eq(names(), ["Calculator", "Calendar"])
s.run(key(s.m, s.table, input_chain, Enter))
assert_true(s.has_effect(Launch("c.calc/.Main")))
assert_true(!s.m.drawer)
assert_eq(s.m.query, "")
}
///|
test "Enter with no search text or no match opens nothing" {
let s = Sim::new()
s.send(OpenDrawer)
let c = s.chain("input")
s.run(key(s.m, s.table, c, Enter))
assert_true(s.m.drawer)
s.run(typed(s.m, s.table, c, "zzz"))
s.run(key(s.m, s.table, c, Enter))
assert_true(s.m.drawer)
assert_true(@vdom.to_html(s.tree[1]).contains("No apps match."))
s.run(key(s.m, s.table, c, Escape))
assert_eq(s.m.query, "")
}
///|
test "tapping an app in the drawer launches it" {
let s = Sim::new()
s.send(OpenDrawer)
s.tap("tile", label="Gmail", from=1)
assert_true(s.has_effect(Launch("c.gmail/.Main")))
assert_true(!s.m.drawer)
}
///|
test "long press on a drawer app: menu; system apps have no uninstall" {
let s = Sim::new()
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_eq(s.m.sheet, DrawerApp(3))
let html = s.sheet_html()
assert_true(html.contains("Add to home"))
assert_true(html.contains("App info"))
assert_true(html.contains("Uninstall"))
s.tap("sheet-item", label="Add to home")
assert_eq(s.home_names(), ["Gmail"])
s.long_press(s.chain("tile", label="Phone", from=1))
assert_true(!s.sheet_html().contains("Uninstall"))
s.tap("sheet-overlay")
assert_eq(s.m.sheet, NoSheet)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_true(s.sheet_html().contains("Remove from home"))
}
///|
test "uninstall asks the shell; the slot goes when the app leaves the list" {
let s = Sim::new()
s.add_apps(["Gmail"])
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
s.tap("sheet-item", label="Uninstall")
assert_true(s.has_effect(Uninstall("c.gmail/.Main")))
assert_eq(s.home_names(), ["Gmail"])
s.send(AppsLoaded(Some("{\"apps\":[{\"label\":\"Chrome\",\"component\":\"c.chrome/.Main\",\"icon\":\"\"}]}")))
assert_eq(s.m.home.length(), 0)
}
///|
test "home slots: tap launches, long press without moving opens the menu" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
s.tap("tile", label="Gmail")
assert_true(s.has_effect(Launch("c.gmail/.Main")))
s.long_press(s.chain("tile", label="Gmail"))
assert_eq(s.m.sheet, Item(1))
s.tap("sheet-item", label="Move earlier")
assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"])
s.long_press(s.chain("tile", label="Gmail"))
s.tap("sheet-item", label="Move later")
assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"])
s.long_press(s.chain("tile", label="Chrome"))
assert_true(!s.sheet_html().contains("Move earlier"))
s.tap("sheet-item", label="Remove from home")
assert_eq(s.home_names(), ["Gmail", "Phone"])
}
///|
test "dragging a home app over another reorders; a drag does not open the menu" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
let (ax, ay) = cell_center(1, 0)
let (bx, by) = cell_center(0, 0)
s.press(s.chain("tile", label="Gmail"), x=ax, y=ay)
s.hold()
assert_eq(s.m.lifted, 1)
s.move_to(bx + 5.0, by)
s.move_to(bx, by)
s.release()
assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"])
assert_eq(s.m.sheet, NoSheet)
assert_eq(s.m.lifted, -1)
}
///|
test "an app dropped in an empty cell stays there; the rest stay packed" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
let (px, py) = cell_center(2, 0)
let (tx, ty) = cell_center(3, 2)
s.press(s.chain("tile", label="Phone"), x=px, y=py)
s.hold()
s.move_to(tx - 30.0, ty)
s.move_to(tx, ty)
s.release()
assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"])
assert_eq((s.m.home[2].x, s.m.home[2].y), (3, 2))
let cells = s.m.packed().cells
assert_eq(cells[0], Some({ col: 0, row: 0, w: 1, h: 1 }))
assert_eq(cells[2], Some({ col: 3, row: 2, w: 1, h: 1 }))
// and it survives a save and a load
let back = load_json(save_json(s.m.home), Ref::new(1)).unwrap()
assert_eq((back[2].x, back[2].y), (3, 2))
}
///|
test "dropping a pinned app onto another pinned one moves that one on" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail"])
for (label, col, row) in [("Chrome", 3, 1), ("Gmail", 3, 3)] {
let from = cell_center(0, 0) // Gmail flows up into the first cell once Chrome is pinned
let (fx, fy) = from
let (tx, ty) = cell_center(col, row)
s.press(s.chain("tile", label=label), x=fx, y=fy)
s.hold()
s.move_to(tx, ty)
s.release()
}
assert_eq((s.m.home[0].x, s.m.home[0].y), (3, 1))
assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 3))
// drag Gmail on top of Chrome's cell: Chrome is unpinned
let (gx, gy) = cell_center(3, 3)
let (cx, cy) = cell_center(3, 2) // a free cell next to it
s.press(s.chain("tile", label="Gmail"), x=gx, y=gy)
s.hold()
s.move_to(cx, cy)
s.release()
assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 2))
}
///|
test "add a widget: picker search, choose, shell adds it" {
let s = Sim::new()
s.add_apps(["Chrome"])
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Add widget")
assert_true(s.has_effect(LoadWidgets))
assert_true(s.sheet_html().contains("Loading widgets"))
s.send(WidgetsLoaded(Some(widgets_json)))
let names = fn() {
let out : Array[String] = []
for i in 0..<s.m.widgets.length() {
if s.m.widget_matches(i) {
out.push(s.m.widgets[i].label)
}
}
out
}
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
assert_eq(names(), ["Calendar"])
s.run(typed(s.m, s.table, c, "goo"))
assert_eq(names(), ["Weather"]) // by the app it comes from
s.run(typed(s.m, s.table, c, "zzz"))
assert_true(s.sheet_html().contains("No widgets match."))
s.run(typed(s.m, s.table, c, ""))
s.press(s.chain_where(fn(e) { e.tag == "li" && text_of(El(e)).contains("Clock") }).unwrap())
s.release()
assert_true(s.has_effect(AddWidget("c.clock/.W")))
s.send(WidgetAdded(100))
assert_eq(s.home_names(), ["Chrome", "[Clock]"])
assert_eq(s.m.home[1].wid, 100)
assert_eq(s.m.home[1].rows, 2) // 140px: two rows
assert_true(s.has_effect(QueryLimits(100)))
// its natural width sets the starting columns: 110px wide = 2 columns
s.send(LimitsKnown(100, Some("{\"w\":110,\"minW\":110,\"minH\":80,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[1].w, 2)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("data-wid=\"100\""))
assert_true(html.contains("widget-slot"))
}
///|
test "widget picker Enter chooses the first match" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
s.run(key(s.m, s.table, c, Enter))
assert_true(s.has_effect(AddWidget("c.cal/.W")))
assert_eq(s.m.sheet, NoSheet)
}
///|
test "a widget: hold opens resize handles; drag the handles; Done" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(LimitsKnown(100, Some("{\"w\":0,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[0].w, 0)
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
assert_eq(s.m.resizing, 0) // no item menu for a widget: handles
assert_eq(s.m.sheet, NoSheet)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("resize-handle"))
assert_true(@vdom.to_html(s.tree[1]).contains("Drag to move, or drag the handles to resize"))
// drag the bottom handle down to the fourth row
let hc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "b")) }).unwrap()
s.press(hc, x=100.0, y=150.0 + 2.0 * 72.0 + 70.0)
assert_true(s.has_effect(QueryLimits(100)))
s.move_to(100.0, 150.0 + 3.0 * 72.0 + 40.0)
s.release()
assert_eq(s.m.home[0].rows, 4)
assert_eq(s.m.resizing, 0) // handles stay
// the right handle to three columns (the widget starts the full row)
let rc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "r")) }).unwrap()
s.press(rc, x=370.0, y=170.0)
let (c3x, _) = cell_center(2, 0)
s.move_to(c3x + 36.0, 170.0)
s.release()
assert_eq(s.m.home[0].w, 3)
// pressing the widget's body picks it up at once; letting go keeps the handles
let wc = s.chain("widget-slot")
s.press(wc, x=wx, y=wy)
assert_eq(s.m.lifted, 0)
s.release()
assert_eq(s.m.resizing, 0)
assert_eq(s.m.lifted, -1)
// Done (a tap on the bar's button) ends it
s.tap("btn", label="Done")
assert_eq(s.m.resizing, -1)
assert_eq(s.m.home[0].w, 3)
}
///|
test "resizing stays within the widget's limits" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(LimitsKnown(100, Some("{\"w\":0,\"minW\":200,\"maxW\":220,\"minH\":64,\"h\":true,\"v\":false}")))
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
let rc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "rb")) }).unwrap()
s.press(rc, x=370.0, y=250.0)
s.move_to(60.0, 600.0) // far left and down
s.release()
assert_eq(s.m.home[0].w, 3) // 3 columns = 204px, the nearest to 200 within the limit
assert_eq(s.m.home[0].rows, 2) // vertical resizing is off
}
///|
test "a native widget view lifts, drags and drops its slot" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(2))
s.send(WidgetAdded(7))
s.send(LimitsKnown(7, Some("{\"w\":130,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[0].w, 2)
s.send(WidgetMenu(7))
assert_eq(s.m.lifted, 0)
let (x, y) = cell_center(1, 0)
s.send(NativeDrag(x, y))
let (tx, ty) = cell_center(2, 3)
s.send(NativeDrag(tx, ty))
s.send(NativeDrop(true))
assert_eq(s.m.lifted, -1)
assert_eq(s.m.sheet, NoSheet)
assert_eq((s.m.home[0].x, s.m.home[0].y), (1, 3)) // it moved by the finger's travel
// lifting and letting go without moving shows the handles
s.send(WidgetMenu(7))
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
// a press on the native view while handles show picks it up
s.send(WidgetGrab(7))
assert_eq(s.m.lifted, 0)
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
}
///|
test "widgets and apps drawn under a sheet or the drawer are not live" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(5))
assert_true(@vdom.to_html(s.tree[0]).contains("data-wid=\"5\""))
s.send(OpenDrawer)
assert_true(!@vdom.to_html(s.tree[0]).contains("data-wid"))
}
///|
test "back and home close things from the top down" {
let s = Sim::new()
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_eq(s.m.sheet, DrawerApp(3))
s.send(Back)
assert_eq(s.m.sheet, NoSheet)
assert_true(s.m.drawer)
s.send(Back)
assert_true(!s.m.drawer)
s.send(OpenDrawer)
s.send(GoHome)
assert_true(!s.m.drawer)
assert_true(s.has_effect(ScrollTop))
}
///|
test "the layout is saved on every change and restored" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail"])
let mut saved = ""
for e in s.log {
if e is SaveHome(j) {
saved = j
}
}
assert_eq(saved, save_json(s.m.home))
let s2 = Sim::new()
s2.run(update(s2.m, Restore(saved=Some(saved), legacy=None)))
assert_eq(s2.home_names(), ["Chrome", "Gmail"])
// restoring what is already saved doesn't save it again
let n = s2.log.filter(fn(e) { e is SaveHome(_) }).length() - 1 // Sim::new saved the empty one
assert_eq(n, 0)
}
///|
test "the old WebView build's home screen is brought over once" {
let legacy =
#|{"ultra.home.n":"3",
#|"ultra.home.kind.0":"0","ultra.home.str.0":"c.chrome/.Main","ultra.home.cx.0":"-1","ultra.home.cy.0":"-1",
#|"ultra.home.kind.1":"1","ultra.home.str.1":"Clock","ultra.home.wid.1":"12","ultra.home.h.1":"136",
#|"ultra.home.w.1":"3","ultra.home.cx.1":"1","ultra.home.cy.1":"2",
#|"ultra.home.kind.2":"0"}
let next = Ref::new(1)
let slots = legacy_import(legacy, next)
assert_eq(slots.length(), 2)
assert_eq((slots[0].kind, slots[0].str), (App, "c.chrome/.Main"))
assert_eq((slots[1].wid, slots[1].w, slots[1].rows, slots[1].x, slots[1].y), (12, 3, 2, 1, 2))
assert_eq(legacy_import("{}", Ref::new(1)).length(), 0)
assert_eq(legacy_import("garbage", Ref::new(1)).length(), 0)
let s = Sim::new()
s.run(update(s.m, Restore(saved=None, legacy=Some(legacy))))
assert_eq(s.m.home.length(), 2)
assert_true(s.log.contains(SaveHome(save_json(s.m.home)))) // saved in the new format
// a saved layout wins over the old one
let s2 = Sim::new()
s2.run(update(s2.m, Restore(saved=Some(save_json([slot_app("c.gmail/.Main")])), legacy=Some(legacy))))
assert_eq(s2.m.home.length(), 1)
}
///|
fn slot_app(c : String) -> @grid.Slot {
@grid.Slot::app(c)
}
///|
test "load_json rejects what is not a layout and drops nameless slots" {
assert_true(load_json("nope", Ref::new(1)) is None)
assert_true(load_json("{}", Ref::new(1)) is None)
let r = load_json("{\"slots\":[{\"kind\":\"app\"},{\"kind\":\"app\",\"str\":\"a\"}]}", Ref::new(1)).unwrap()
assert_eq(r.length(), 1)
}
///|
test "self-update: automatic check, newer build, install" {
let s = Sim::new()
s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10))
assert_true(s.has_effect(SaveLastCheck(100000000L)))
assert_true(s.has_effect(FetchRelease(@updater.release_api)))
s.send(
ReleaseFetched(
Some(
"{\"tag_name\":\"build-12\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}",
),
),
)
assert_true(s.has_effect(FetchVersion("u/v")))
s.send(VersionFetched(Some("{\"versionCode\":12}")))
assert_true(s.has_effect(InstallApk("u/a", 12)))
assert_eq(s.m.notice, "Downloading launcher update (build 12)…")
assert_true(!s.m.checking)
}
///|
test "self-update: up to date is silent unless asked; declined builds are not offered" {
let rel =
#|{"tag_name":"build-10","assets":[{"name":"version.json","browser_download_url":"u/v"},{"name":"ultra-launcher.apk","browser_download_url":"u/a"}]}
let s = Sim::new()
s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10))
s.send(ReleaseFetched(Some(rel)))
s.send(VersionFetched(Some("{\"versionCode\":10}")))
assert_eq(s.m.notice, "")
assert_true(s.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0)
// manual says so
s.send(CheckUpdates)
s.send(ReleaseFetched(Some(rel)))
s.send(VersionFetched(Some("{\"versionCode\":10}")))
assert_eq(s.m.notice, "ultra Home is up to date (build 10)")
// a declined build: silent for automatic checks, offered again when asked
let s2 = Sim::new()
s2.send(Started(now=100000000L, last_check=0L, declined=11, installed=10))
s2.send(ReleaseFetched(Some(rel)))
s2.send(VersionFetched(Some("{\"versionCode\":11}")))
assert_true(s2.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0)
s2.send(CheckUpdates)
s2.send(ReleaseFetched(Some(rel)))
s2.send(VersionFetched(Some("{\"versionCode\":11}")))
assert_true(s2.has_effect(InstallApk("u/a", 11)))
s2.send(UpdateDeclined(11))
assert_true(s2.has_effect(SaveDeclined(11)))
}
///|
test "self-update: recent check is skipped; failures and the tag fallback" {
let s = Sim::new()
s.send(Started(now=1000L, last_check=900L, declined=-1, installed=10))
assert_true(!s.has_effect(FetchRelease(@updater.release_api)))
s.send(CheckUpdates)
s.send(CheckUpdates) // already checking
assert_eq(s.m.notice, "Already checking for updates")
s.send(ReleaseFetched(None))
assert_eq(s.m.notice, "Couldn't check for updates")
assert_true(!s.m.checking)
// version.json unreadable: the release tag says the build number
s.send(CheckUpdates)
s.send(
ReleaseFetched(
Some(
"{\"tag_name\":\"build-20\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}",
),
),
)
s.send(VersionFetched(None))
assert_true(s.has_effect(InstallApk("u/a", 20)))
}
///|
test "menu items reach the shell" {
let s = Sim::new()
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Wallpaper")
assert_true(s.has_effect(PickWallpaper))
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Settings")
assert_true(s.has_effect(OpenSettings))
s.tap("panel-btn")
assert_true(s.has_effect(OpenRecents))
}
///|
test "app info for a home slot" {
let s = Sim::new()
s.add_apps(["Chrome"])
s.long_press(s.chain("tile", label="Chrome"))
s.tap("sheet-item", label="App info")
assert_true(s.has_effect(AppInfo("c.chrome/.Main")))
}
///|
test "view snapshot: home with an app" {
let s = Sim::new()
s.add_apps(["Chrome"])
inspect(
@vdom.to_html(s.tree[0]),
content=(
#|<div class="home" on="press">
#| <section class="panel" aria-label="Shortcuts">
#| <button class="panel-btn" on="tap">
#| <span class="windows-glyph" aria-hidden="true"></span>
#| <span>Windows</span>
#| </button>
#| </section>
#| <button class="search-pill" aria-label="Search apps" on="tap">
#| <span class="magnifier" aria-hidden="true"></span>
#| <span>Search apps</span>
#| </button>
#| <ul class="slots" style="grid-template-columns:repeat(5,minmax(0,1fr));grid-template-rows:repeat(8,64px)">
#| <li class="tile" data-slot="0" style="grid-column:1 / span 1;grid-row:1 / span 1" on="tap press">
#| <img class="icon" alt="" draggable="false" data-icon="i3"></img>
#| <span class="name">Chrome</span>
#| </li>
#| </ul>
#|</div>
),
)
}
+795
View File
@@ -0,0 +1,795 @@
///|
fn trimmed(s : String) -> String {
s.trim().to_string()
}
///|
/// The lower-cased, trimmed search text matches the label.
pub fn matches_query(label : String, query : String) -> Bool {
let q = trimmed(query).to_lower()
q == "" || label.to_lower().contains(q)
}
///|
pub fn Model::app_row(self : Model, component : String) -> Int {
for i in 0..<self.apps.length() {
if self.apps[i].component == component {
return i
}
}
-1
}
///|
/// The home slot holding the app at `row` in the app list, or -1.
pub fn Model::home_of(self : Model, row : Int) -> Int {
let comp = self.apps[row].component
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == comp {
return i
}
}
-1
}
///|
pub fn Model::slot_of_widget(self : Model, wid : Int) -> Int {
for i in 0..<self.home.length() {
if self.home[i].kind == Widget && self.home[i].wid == wid {
return i
}
}
-1
}
///|
/// The first app (row in the list) whose label matches the search.
pub fn Model::first_match(self : Model) -> Int {
for i in 0..<self.apps.length() {
if matches_query(self.apps[i].label, self.query) {
return i
}
}
-1
}
///|
pub fn Model::widget_matches(self : Model, i : Int) -> Bool {
matches_query(self.widgets[i].label, self.wquery) ||
matches_query(self.widgets[i].app, self.wquery) && trimmed(self.wquery) != ""
}
///|
pub fn Model::first_widget_match(self : Model) -> Int {
for i in 0..<self.widgets.length() {
if self.widget_matches(i) {
return i
}
}
-1
}
///|
/// Home slots that are not drawn: apps that are not installed.
pub fn Model::hidden(self : Model, i : Int) -> Bool {
self.home[i].kind == App && self.app_row(self.home[i].str) < 0
}
///|
pub fn Model::packed(self : Model) -> @grid.Packed {
@grid.pack(self.home, self.cols, self.nrows, hidden=fn(i) { self.hidden(i) })
}
///|
fn Model::say(self : Model, text : String, fx : Array[Effect]) -> Unit {
self.notice = text
self.notice_gen += 1
fx.push(Delay(1800, NoticeDone(self.notice_gen)))
}
///|
fn Model::push_slot(self : Model, s : @grid.Slot) -> Unit {
self.home.push(s)
}
///|
fn Model::new_key(self : Model) -> Int {
let k = self.next_key
self.next_key += 1
k
}
///|
fn Model::remove_slot(self : Model, at : Int, fx : Array[Effect]) -> Unit {
if at < 0 || at >= self.home.length() {
return
}
if self.home[at].kind == Widget {
fx.push(RemoveWidget(self.home[at].wid))
}
ignore(self.home.remove(at))
if self.lifted == at {
self.lifted = -1
} else if self.lifted > at {
self.lifted -= 1
}
if self.resizing == at {
self.resizing = -1
} else if self.resizing > at {
self.resizing -= 1
}
}
///|
fn Model::add_app(self : Model, row : Int, fx : Array[Effect]) -> Unit {
if self.home_of(row) >= 0 {
self.say("Already on the home screen", fx)
} else if self.home.length() >= home_cap {
self.say("The home screen is full", fx)
} else {
self.push_slot(@grid.Slot::app(self.apps[row].component, key=self.new_key()))
self.say("Added to home", fx)
}
}
///|
/// Once an app uninstalled from the drawer is out of the list, take it off home.
fn Model::drop_gone(self : Model, fx : Array[Effect]) -> Unit {
if self.gone == "" {
return
}
if self.app_row(self.gone) >= 0 {
return
}
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == self.gone {
self.remove_slot(i, fx)
break
}
}
self.gone = ""
}
///|
fn Model::close_all(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer {
fx.push(HideKeyboard)
}
self.query = ""
self.drawer = false
self.picking = false
self.sheet = NoSheet
self.lifted = -1
self.resizing = -1
self.regrab = false
self.carry = None
self.resize = None
}
///|
fn Model::open_drawer(self : Model, fx : Array[Effect]) -> Unit {
if self.sheet == NoSheet && !self.drawer {
self.drawer = true
fx.push(FocusSearch)
}
}
///|
fn Model::close_drawer(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer && self.sheet == NoSheet {
self.drawer = false
self.picking = false
self.query = ""
fx.push(HideKeyboard)
}
}
// ---- dragging -----------------------------------------------------------------
///|
/// The box (px, viewport) of slot `i`, from the packing.
fn Model::slot_box(
self : Model,
packed : @grid.Packed,
i : Int,
) -> (Double, Double, Double, Double)? {
match packed.cells[i] {
Some(c) => {
let (x, y, w, h) = @grid.box(c, self.col_w)
Some((x + self.grid_left, y + self.grid_top, w, h))
}
None => None
}
}
///|
fn inside(b : (Double, Double, Double, Double), x : Double, y : Double) -> Bool {
x >= b.0 && x <= b.0 + b.2 && y >= b.1 && y <= b.1 + b.3
}
///|
/// The slot (not the lifted one) under a point, or -1.
fn Model::slot_at(self : Model, packed : @grid.Packed, x : Double, y : Double) -> Int {
for i in 0..<self.home.length() {
if i == self.lifted {
continue
}
if self.slot_box(packed, i) is Some(b) && inside(b, x, y) {
return i
}
}
-1
}
///|
/// The pointer is at x, y with a slot lifted (it went down at x0, y0). An app over
/// another slot takes its place in the order; over an empty cell it is left in that cell.
/// A widget goes to the cell under it wherever that is (apps flow around it).
fn Model::drag_lifted(
self : Model,
x : Double,
y : Double,
x0 : Double,
y0 : Double,
) -> Unit {
if self.lifted < 0 || self.lifted >= self.home.length() || self.col_w <= 0.0 {
return
}
let packed = self.packed()
let lifted = self.home[self.lifted]
let carry = match self.carry {
Some(c) => c
None => {
let (bx, by) = match self.slot_box(packed, self.lifted) {
Some(b) => (b.0, b.1)
None => (x0, y0)
}
let c = { dx: x0 - bx, dy: y0 - by, cell: -1 }
self.carry = Some(c)
c
}
}
let widget = lifted.kind == Widget
if !widget &&
self.slot_box(packed, self.lifted) is Some(b) &&
inside(b, x, y) {
return
}
let half_w = self.col_w / 2.0
let half_h = @grid.cell_px.to_double() / 2.0
let (fc, fr) = @grid.cell_at(
x - self.grid_left - half_w,
y - self.grid_top - half_h,
self.col_w,
)
let mut to = self.slot_at(packed, x, y)
if to < 0 {
let cx = self.grid_left + fc.to_double() * (self.col_w + @grid.col_gap.to_double()) + half_w
let cy = self.grid_top +
fr.to_double() * (@grid.cell_px + @grid.row_gap).to_double() +
half_h
to = self.slot_at(packed, cx, cy)
}
if to >= 0 && !widget {
carry.cell = -1
lifted.x = -1 // back into the flow, at that place in the order
lifted.y = -1
@grid.move_slot(self.home, self.lifted, to)
self.lifted = to
return
}
let grid_bottom = self.grid_top +
(packed.rows * (@grid.cell_px + @grid.row_gap)).to_double()
if y > grid_bottom {
return // below the grid
}
let (col, row) = @grid.cell_at(
x - self.grid_left - carry.dx,
y - self.grid_top - carry.dy,
self.col_w,
)
let cell = row * 64 + @cmp.minimum(col, 63)
if cell != carry.cell {
carry.cell = cell
@grid.pin(self.home, self.lifted, col, row, self.cols, self.nrows)
}
}
///|
/// The pointer is up. Letting go without moving opens the item's menu (a widget gets
/// resize handles instead); letting go of a dragged one just drops it, and whatever it
/// then covers moves on to free cells.
fn Model::drop_lifted(self : Model, moved : Bool) -> Unit {
self.carry = None
if self.lifted < 0 || self.lifted >= self.home.length() {
self.lifted = -1
self.regrab = false
return
}
let s = self.home[self.lifted]
if s.x >= 0 {
@grid.clear_cells(self.home, self.lifted, self.cols)
}
if !moved || self.regrab {
match s.kind {
Widget => self.resizing = self.lifted
App => self.sheet = Item(self.lifted)
}
}
self.lifted = -1
self.regrab = false
}
///|
fn Model::begin_resize(self : Model, edge : Edge, fx : Array[Effect]) -> Unit {
let i = self.resizing
if i < 0 || i >= self.home.length() {
return
}
let s = self.home[i]
let (left, top) = match self.slot_box(self.packed(), i) {
Some(b) => (b.0, b.1)
None => (self.grid_left, self.grid_top)
}
self.resize = Some({ edge, slot: i, left, top, cols: s.cols(self.cols), rows: s.height() })
fx.push(QueryLimits(s.wid))
}
///|
/// Dragging a handle snaps the widget to whole columns and rows, within its limits.
fn Model::drag_resize(
self : Model,
r : ResizeDrag,
x : Double,
y : Double,
fx : Array[Effect],
) -> Unit {
if r.slot >= self.home.length() || self.col_w <= 0.0 {
return
}
let s = self.home[r.slot]
let lim = self.limits.get(s.wid).unwrap_or(default_limits)
let n = self.cols
let mut cols = r.cols
let mut rows = r.rows
if r.edge != Bottom && lim.h {
cols = @grid.fit(
x - r.left,
1,
n,
self.col_w,
@grid.col_gap.to_double(),
lim.min_w,
lim.max_w,
)
}
if r.edge != Right && lim.v {
rows = @grid.fit(
y - r.top,
1,
20,
@grid.cell_px.to_double(),
@grid.row_gap.to_double(),
lim.min_h,
lim.max_h,
)
}
if cols == r.cols && rows == r.rows {
return
}
r.cols = cols
r.rows = rows
fx.push(Haptic)
s.w = if cols >= n { 0 } else { cols }
s.rows = rows
if s.x >= 0 {
@grid.pin(self.home, r.slot, s.x, s.y, self.cols, self.nrows)
@grid.clear_cells(self.home, r.slot, self.cols)
}
}
// ---- update -------------------------------------------------------------------
///|
/// Apply a message to the model; returns the effects for the platform to run. The
/// saved layout is kept in step automatically (a `SaveHome` whenever it changed).
pub fn update(m : Model, msg : Msg) -> Array[Effect] {
let fx : Array[Effect] = []
step(m, msg, fx)
let json = save_json(m.home)
if json != m.saved {
m.saved = json
fx.push(SaveHome(json))
}
fx
}
///|
fn Model::choose_widget(self : Model, i : Int, fx : Array[Effect]) -> Unit {
if i >= 0 && i < self.widgets.length() {
if self.home.length() < home_cap {
self.chosen = i
fx.push(AddWidget(self.widgets[i].provider))
} else {
self.say("The home screen is full", fx)
}
self.sheet = NoSheet
}
}
///|
fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
match msg {
Restore(saved~, legacy~) => {
let next = Ref::new(m.next_key)
let mut slots = None
if saved is Some(text) {
slots = load_json(text, next)
if slots is Some(_) {
m.saved = text
}
}
if slots is None && legacy is Some(text) {
slots = Some(legacy_import(text, next))
}
if slots is Some(s) {
m.home = s
}
m.next_key = next.val
fx.push(LoadApps)
}
Started(now~, last_check~, declined~, installed~) => {
m.installed = installed
m.declined = declined
if @updater.should_check(now, last_check, manual=false) && !m.checking {
m.checking = true
m.manual_check = false
fx.push(SaveLastCheck(now))
fx.push(FetchRelease(@updater.release_api))
}
}
Measured(vw~, vh~, grid_left~, grid_top~, grid_w~, bottom_pad~) => {
m.cols = @grid.columns_for(vw)
m.grid_left = grid_left
m.grid_top = grid_top
m.col_w = @grid.column_width(grid_w, m.cols)
m.nrows = @grid.rows_fit(vh.to_double() - bottom_pad - grid_top)
}
AppsLoaded(text) => {
m.loading = false
match text.bind(parse_apps) {
Some(apps) => {
m.apps = apps
m.load_error = ""
m.drop_gone(fx)
}
None => m.load_error = "no response"
}
if m.sheet is DrawerApp(_) {
m.sheet = NoSheet // rows may have moved
}
}
WidgetsLoaded(text) => {
m.wloading = false
m.widgets = text.bind(parse_widgets).unwrap_or([])
}
LimitsKnown(wid, text) => {
let lim = match text {
Some(t) => parse_limits(t)
None => default_limits
}
m.limits[wid] = lim
if m.fresh == wid {
m.fresh = -1
let i = m.slot_of_widget(wid)
if i >= 0 && m.col_w > 0.0 {
m.home[i].w = @grid.widget_cols(lim.w, m.col_w, m.cols)
}
}
}
Reload => fx.push(LoadApps)
GoHome => {
m.close_all(fx)
fx.push(ScrollTop)
}
Back =>
if m.lifted >= 0 {
m.lifted = -1
m.regrab = false
m.carry = None
} else if m.resizing >= 0 {
m.resizing = -1
} else if m.sheet != NoSheet {
m.sheet = NoSheet
} else if m.drawer {
m.drawer = false
m.picking = false
m.query = ""
fx.push(HideKeyboard)
}
WidgetAdded(id) =>
if m.chosen >= 0 && m.chosen < m.widgets.length() && m.home.length() < home_cap {
let w = m.widgets[m.chosen]
m.push_slot(
@grid.Slot::widget(
w.label,
id,
rows=@grid.widget_rows(w.h),
key=m.new_key(),
),
)
m.chosen = -1
m.fresh = id
fx.push(QueryLimits(id))
}
WidgetMenu(wid) => {
let i = m.slot_of_widget(wid)
if i >= 0 && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = false
m.lifted = i
m.native_from = None
}
}
WidgetGrab(wid) => {
let i = m.slot_of_widget(wid)
if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = true
m.lifted = i
m.native_from = None
}
}
NativeDrag(x, y) => {
m.dragged = true
let (x0, y0) = match m.native_from {
Some(p) => p
None => {
m.native_from = Some((x, y))
(x, y)
}
}
m.drag_lifted(x, y, x0, y0)
}
NativeDrop(moved) => {
m.native_from = None
m.drop_lifted(moved)
}
Touch(dx~, dy~, ms~, home_top~, list_end~) =>
if !m.dragged && m.lifted < 0 && m.sheet == NoSheet {
match @gesture.classify_swipe(dx, dy, ms) {
Some(Down) => if !m.drawer && home_top { m.open_drawer(fx) }
Some(Up) => if m.drawer && list_end { m.close_drawer(fx) }
None => ()
}
}
ReleaseFetched(text) => {
let release = text.bind(@updater.parse_release)
match release {
Some({ version_url: Some(v), apk_url: Some(a), tag }) => {
m.apk_url = Some(a)
m.release_tag = tag
fx.push(FetchVersion(v))
}
_ => {
m.checking = false
if m.manual_check {
m.say("Couldn't check for updates", fx)
}
}
}
}
VersionFetched(text) => {
m.checking = false
let latest = match text.bind(@updater.parse_version) {
Some(v) => Some(v)
None => @updater.tag_version(m.release_tag)
}
match (latest, m.apk_url) {
(Some(latest), Some(url)) =>
match
@updater.decide(latest, m.installed, m.declined, manual=m.manual_check) {
UpToDate(n) =>
if m.manual_check {
m.say("ultra Home is up to date (build \{n})", fx)
}
Declined(_) => ()
Install(n) => {
m.say("Downloading launcher update (build \{n})…", fx)
fx.push(InstallApk(url, n))
}
}
_ =>
if m.manual_check {
m.say("Couldn't check for updates", fx)
}
}
}
UpdateDeclined(n) => {
m.declined = n
fx.push(SaveDeclined(n))
}
NoticeDone(gen) => if gen == m.notice_gen { m.notice = "" }
Query(q) => m.query = q
Clear => m.query = ""
WQuery(q) => m.wquery = q
WClear => m.wquery = ""
OpenDrawer => m.open_drawer(fx)
CloseDrawer => m.close_drawer(fx)
OpenApp(row) =>
if row >= 0 && row < m.apps.length() {
fx.push(Launch(m.apps[row].component))
m.close_all(fx)
}
OpenFirst => {
let i = m.first_match()
if i >= 0 && trimmed(m.query) != "" {
fx.push(Launch(m.apps[i].component))
m.close_all(fx)
}
}
OpenHome(i) =>
if i >= 0 && i < m.home.length() {
m.resizing = -1
fx.push(Launch(m.home[i].str))
}
AddHome(row) => {
m.add_app(row, fx)
m.sheet = NoSheet
}
ToggleHome(row) => {
let i = m.home_of(row)
if i >= 0 {
m.remove_slot(i, fx)
} else if m.home.length() < home_cap {
m.push_slot(@grid.Slot::app(m.apps[row].component, key=m.new_key()))
}
}
AppMenu(row) =>
if m.drawer && m.sheet == NoSheet {
fx.push(Haptic)
m.sheet = DrawerApp(row)
}
AppInfoOf(row) => {
fx.push(AppInfo(m.apps[row].component))
m.sheet = NoSheet
}
UninstallOf(row) => {
m.gone = m.apps[row].component
fx.push(Uninstall(m.gone))
m.sheet = NoSheet
}
Menu => {
m.resizing = -1
fx.push(Haptic)
m.sheet = HomeMenu
}
CloseSheet => m.sheet = NoSheet
PickApps => {
m.sheet = NoSheet
m.drawer = true
m.picking = true
}
PickWidget => {
m.sheet = WidgetPicker
m.wquery = ""
m.wloading = true
fx.push(LoadWidgets)
}
ChooseWidget(i) => m.choose_widget(i, fx)
ChooseFirstWidget => m.choose_widget(m.first_widget_match(), fx)
Remove(i) => {
m.resizing = -1
m.remove_slot(i, fx)
m.sheet = NoSheet
}
MoveEarlier(k) => {
if k > 0 && k < m.home.length() {
let a = m.home[k]
m.home[k] = m.home[k - 1]
m.home[k - 1] = a
}
m.sheet = NoSheet
}
InfoOf(i) => {
if i >= 0 && i < m.home.length() {
fx.push(AppInfo(m.home[i].str))
}
m.sheet = NoSheet
}
Settings => {
fx.push(OpenSettings)
m.sheet = NoSheet
}
Wallpaper => {
fx.push(PickWallpaper)
m.sheet = NoSheet
}
Recents => fx.push(OpenRecents)
CheckUpdates => {
m.sheet = NoSheet
if m.checking {
m.say("Already checking for updates", fx)
} else {
m.checking = true
m.manual_check = true
m.say("Checking for updates…", fx)
fx.push(FetchRelease(@updater.release_api))
}
}
Lift(i) =>
if !m.drawer && m.sheet == NoSheet && i != m.lifted && i < m.home.length() {
fx.push(Haptic)
m.resizing = -1
m.regrab = false
m.lifted = i
}
Grab(i) =>
if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = true
m.lifted = i
}
ResizeBegin(edge) => m.begin_resize(edge, fx)
ResizeDone => m.resizing = -1
Nop => ()
Dragged(x~, y~, x0~, y0~) => {
m.dragged = true
match m.resize {
Some(r) => m.drag_resize(r, x, y, fx)
None => m.drag_lifted(x, y, x0, y0)
}
}
Released(moved~, held~) => {
ignore(held)
m.resize = None
m.drop_lifted(moved)
}
}
}
// ---- pointer input --------------------------------------------------------------
///|
/// Feed raw pointer input through the gesture recogniser and on to the handlers.
/// `table` holds the handlers of the nodes of the tree last rendered (`vdom` numbers the
/// elements that have any, in document order); an input's `chain` lists those numbers
/// from the innermost element up. Returns the effects to run.
pub fn input(
m : Model,
table : Array[@vdom.Handlers[Msg]],
inp : @gesture.Input,
) -> Array[Effect] {
let fx : Array[Effect] = []
fn nearest(chain : Array[Int], pick : (@vdom.Handlers[Msg]) -> Msg?) -> Msg? {
for id in chain {
if id >= 0 && id < table.length() {
if pick(table[id]) is Some(msg) {
return Some(msg)
}
}
}
None
}
if inp is Down(..) {
m.dragged = false
}
for out in m.gesture.step(inp) {
let msg : Msg? = match out {
Schedule(ms, token) => {
fx.push(HoldTimer(ms, token))
None
}
Began(chain~, ..) => nearest(chain, fn(h) { h.down })
Tap(chain~) => nearest(chain, fn(h) { h.tap })
Press(chain~) => nearest(chain, fn(h) { h.press })
Drag(x~, y~, x0~, y0~) => Some(Dragged(x~, y~, x0~, y0~))
Release(moved~, held~) => Some(Released(moved~, held~))
}
if msg is Some(msg) {
fx.append(update(m, msg))
}
}
fx
}
+502
View File
@@ -0,0 +1,502 @@
///|
using @vdom {type Node, type Handlers, el, text, cls_if}
///|
fn tap(msg : Msg) -> Handlers[Msg] {
{ ..Handlers::none(), tap: Some(msg) }
}
///|
fn icon(key : String) -> Node[Msg] {
el(
"img",
classes=["icon"],
attrs=[("alt", ""), ("draggable", "false"), ("data-icon", key)],
)
}
///|
/// The `grid-column` / `grid-row` of a cell: explicit, so the packing is the model's.
fn cell_style(c : @grid.Cell) -> String {
"grid-column:\{c.col + 1} / span \{c.w};grid-row:\{c.row + 1} / span \{c.h}"
}
///|
fn handle(edge : String, e : Edge) -> Node[Msg] {
el(
"span",
classes=["resize-handle"],
attrs=[("data-edge", edge), ("aria-hidden", "true")],
handlers={ ..Handlers::none(), down: Some(ResizeBegin(e)), tap: Some(Nop) },
)
}
///|
fn Model::view_slot(
self : Model,
i : Int,
packed : @grid.Packed,
) -> Node[Msg]? {
let s = self.home[i]
guard packed.cells[i] is Some(cell) else { return None }
let style = cell_style(cell)
match s.kind {
Widget => {
let live = !self.drawer &&
self.sheet == NoSheet &&
(self.resizing < 0 || i == self.resizing)
let attrs = [("data-slot", i.to_string())]
if live {
attrs.push(("data-wid", s.wid.to_string()))
}
let children = [el("span", classes=["widget-label"], children=[text(s.str)])]
if i == self.resizing {
children.push(handle("r", Right))
children.push(handle("b", Bottom))
children.push(handle("rb", Corner))
}
Some(
el(
"li",
key=s.key,
classes=["widget-slot", cls_if("lifted", i == self.lifted), cls_if("resizing", i == self.resizing)],
attrs~,
style~,
handlers={
..Handlers::none(),
press: Some(Lift(i)),
down: if i == self.resizing { Some(Grab(i)) } else { None },
tap: if i == self.resizing { Some(Nop) } else { None },
},
children~,
),
)
}
App => {
let row = self.app_row(s.str)
let a = self.apps[row]
Some(
el(
"li",
key=s.key,
classes=["tile", cls_if("lifted", i == self.lifted)],
attrs=[("data-slot", i.to_string())],
style~,
handlers={ ..Handlers::none(), tap: Some(OpenHome(i)), press: Some(Lift(i)) },
children=[icon(a.icon), el("span", classes=["name"], children=[text(a.label)])],
),
)
}
}
}
///|
fn view_panel() -> Node[Msg] {
el(
"section",
classes=["panel"],
attrs=[("aria-label", "Shortcuts")],
children=[
el(
"button",
classes=["panel-btn"],
handlers=tap(Recents),
children=[
el("span", classes=["windows-glyph"], attrs=[("aria-hidden", "true")]),
el("span", children=[text("Windows")]),
],
),
],
)
}
///|
/// The pill under the panel: a tap opens the drawer, where the search takes the keyboard.
fn view_search_pill() -> Node[Msg] {
el(
"button",
classes=["search-pill"],
attrs=[("aria-label", "Search apps")],
handlers=tap(OpenDrawer),
children=[
el("span", classes=["magnifier"], attrs=[("aria-hidden", "true")]),
el("span", children=[text("Search apps")]),
],
)
}
///|
fn Model::view_home(self : Model) -> Node[Msg] {
let packed = self.packed()
let slots : Array[Node[Msg]] = []
for i in 0..<self.home.length() {
if self.view_slot(i, packed) is Some(n) {
slots.push(n)
}
}
let rows = if self.home.length() > 0 { packed.rows } else { 0 }
let children = [
view_panel(),
view_search_pill(),
el(
"ul",
classes=["slots", cls_if("dragging", self.lifted >= 0)],
style="grid-template-columns:repeat(\{self.cols},minmax(0,1fr));grid-template-rows:repeat(\{rows},\{@grid.cell_px}px)",
children=slots,
),
]
if self.home.length() == 0 {
children.push(
el(
"p",
classes=["hint"],
children=[text("Swipe down for all apps. Long-press to add apps and widgets.")],
),
)
}
el(
"div",
classes=["home"],
handlers={
..Handlers::none(),
press: Some(Menu),
tap: if self.resizing >= 0 { Some(ResizeDone) } else { None },
},
children~,
)
}
///|
fn Model::view_drawer(self : Model) -> Node[Msg] {
let tiles : Array[Node[Msg]] = []
for i in 0..<self.apps.length() {
let a = self.apps[i]
if !matches_query(a.label, self.query) {
continue
}
tiles.push(
el(
"li",
key=i + 1,
classes=["tile", cls_if("on", self.picking && self.home_of(i) >= 0)],
handlers=if self.picking {
tap(ToggleHome(i))
} else {
{ ..Handlers::none(), tap: Some(OpenApp(i)), press: Some(AppMenu(i)) }
},
children=[icon(a.icon), el("span", classes=["name"], children=[text(a.label)])],
),
)
}
let children : Array[Node[Msg]] = [
el(
"div",
classes=["drawer-head"],
children=[
el(
"input",
classes=["input"],
attrs=[
("type", "search"),
("placeholder", "Search apps"),
("enterkeyhint", "go"),
("aria-label", "Search apps"),
("autocomplete", "off"),
],
props=[("value", self.query)],
handlers={
..Handlers::none(),
input: Some(fn(v) { Query(v) }),
enter: Some(OpenFirst),
escape: Some(Clear),
},
),
el(
"button",
classes=["btn", "ghost", "sm"],
handlers=tap(CloseDrawer),
children=[text(if self.picking { "Done" } else { "Close" })],
),
],
),
]
if self.picking {
children.push(
el(
"p",
classes=["drawer-note"],
children=[text("Tap apps to add them to the home screen or take them off.")],
),
)
}
if self.load_error != "" {
children.push(
el(
"div",
classes=["alert", "destructive"],
attrs=[("role", "alert")],
children=[text("Could not list apps")],
),
)
}
children.push(el("ul", classes=["apps"], children=tiles))
if self.loading {
children.push(el("p", classes=["empty"], children=[text("Loading apps…")]))
} else if tiles.length() == 0 {
children.push(el("p", classes=["empty"], children=[text("No apps match.")]))
}
el("div", classes=["drawer", cls_if("picking", self.picking)], children~)
}
///|
fn sheet_btn(label : String, msg : Msg) -> Node[Msg] {
el("button", classes=["sheet-item"], handlers=tap(msg), children=[text(label)])
}
///|
fn sheet_title(label : String) -> Node[Msg] {
el("h2", classes=["sheet-title"], children=[text(label)])
}
///|
fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
let items : Array[Node[Msg]] = []
match self.sheet {
NoSheet => ()
HomeMenu => {
items.push(sheet_title("Home screen"))
items.push(sheet_btn("Add apps", PickApps))
items.push(sheet_btn("Add widget", PickWidget))
items.push(sheet_btn("Wallpaper", Wallpaper))
items.push(sheet_btn("Settings", Settings))
items.push(sheet_btn("Check for updates", CheckUpdates))
}
Item(i) =>
if i >= 0 && i < self.home.length() {
let s = self.home[i]
let row = self.app_row(s.str)
items.push(
sheet_title(
if s.kind == Widget {
s.str
} else if row >= 0 {
self.apps[row].label
} else {
s.str
},
),
)
if i > 0 {
items.push(sheet_btn("Move earlier", MoveEarlier(i)))
}
if i < self.home.length() - 1 {
items.push(sheet_btn("Move later", MoveEarlier(i + 1)))
}
if s.kind == App {
items.push(sheet_btn("App info", InfoOf(i)))
items.push(sheet_btn("Remove from home", Remove(i)))
} else {
items.push(sheet_btn("Remove widget", Remove(i)))
}
}
DrawerApp(row) =>
if row >= 0 && row < self.apps.length() {
items.push(sheet_title(self.apps[row].label))
let h = self.home_of(row)
if h >= 0 {
items.push(sheet_btn("Remove from home", Remove(h)))
} else {
items.push(sheet_btn("Add to home", AddHome(row)))
}
items.push(sheet_btn("App info", AppInfoOf(row)))
if !self.apps[row].system {
items.push(sheet_btn("Uninstall", UninstallOf(row)))
}
}
WidgetPicker => {
items.push(sheet_title("Add a widget"))
if self.wloading {
items.push(el("p", classes=["empty"], children=[text("Loading widgets…")]))
} else if self.widgets.length() == 0 {
items.push(el("p", classes=["empty"], children=[text("No widgets installed.")]))
} else {
items.push(
el(
"input",
classes=["input", "widget-search"],
attrs=[
("type", "search"),
("placeholder", "Search widgets"),
("enterkeyhint", "go"),
("aria-label", "Search widgets"),
("autocomplete", "off"),
],
props=[("value", self.wquery)],
handlers={
..Handlers::none(),
input: Some(fn(v) { WQuery(v) }),
enter: Some(ChooseFirstWidget),
escape: Some(WClear),
},
),
)
}
let rows : Array[Node[Msg]] = []
for i in 0..<self.widgets.length() {
if !self.widget_matches(i) {
continue
}
let w = self.widgets[i]
let name : Array[Node[Msg]] = [text(w.label)]
if w.app != "" && w.app != w.label {
name.push(el("small", children=[text(w.app)]))
}
rows.push(
el(
"li",
key=i + 1,
handlers=tap(ChooseWidget(i)),
children=[icon(w.icon), el("span", classes=["widget-name"], children=name)],
),
)
}
items.push(el("ul", classes=["widget-list"], children=rows))
if !self.wloading && self.widgets.length() > 0 && rows.length() == 0 {
items.push(el("p", classes=["empty"], children=[text("No widgets match.")]))
}
}
}
[
el("div", classes=["sheet-overlay"], handlers=tap(CloseSheet)),
el(
"div",
classes=["sheet"],
attrs=[("role", "dialog"), ("aria-modal", "true")],
handlers={ ..Handlers::none(), escape: Some(CloseSheet) },
children=items,
),
]
}
///|
fn Model::view_resize_bar(self : Model) -> Node[Msg] {
el(
"div",
classes=["resize-bar"],
attrs=[("role", "toolbar")],
children=[
el(
"span",
classes=["resize-hint"],
children=[text("Drag to move, or drag the handles to resize")],
),
el(
"button",
classes=["btn", "ghost", "sm"],
handlers=tap(Remove(self.resizing)),
children=[text("Remove")],
),
el(
"button",
classes=["btn", "primary", "sm"],
handlers=tap(ResizeDone),
children=[text("Done")],
),
],
)
}
///|
/// The whole screen as a tree.
pub fn view(m : Model) -> Array[Node[Msg]] {
let out : Array[Node[Msg]] = [m.view_home()]
if m.drawer {
out.push(m.view_drawer())
}
if m.sheet != NoSheet {
out.append(m.view_sheet())
} else if m.resizing >= 0 && !m.drawer {
out.push(m.view_resize_bar())
}
if m.notice != "" {
out.push(
el(
"div",
classes=["notice"],
attrs=[("role", "status")],
children=[text(m.notice)],
),
)
}
out
}
///|
/// The handlers of a tree's elements, numbered in document order (pre-order): the
/// platform layer marks each such element with its number and reports pointer input as
/// chains of them (see `input`).
pub fn handler_table(nodes : Array[Node[Msg]]) -> Array[Handlers[Msg]] {
let out : Array[Handlers[Msg]] = []
fn walk(n : Node[Msg]) -> Unit {
if n is El(e) {
if !e.handlers.is_empty() {
out.push(e.handlers)
}
for c in e.children {
walk(c)
}
}
}
for n in nodes {
walk(n)
}
out
}
///|
pub(all) enum Key {
Enter
Escape
}
///|
/// A key pressed in an input; `chain` as for `input`.
pub fn key(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
k : Key,
) -> Array[Effect] {
for id in chain {
if id >= 0 && id < table.length() {
let h = table[id]
let msg = match k {
Enter => h.enter
Escape => h.escape
}
if msg is Some(msg) {
return update(m, msg)
}
}
}
[]
}
///|
/// An input's text changed.
pub fn typed(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
value : String,
) -> Array[Effect] {
for id in chain {
if id >= 0 && id < table.length() {
if table[id].input is Some(f) {
return update(m, f(value))
}
}
}
[]
}