Rewrite the launcher in MoonBit (old code moves to legacy/) #1

Merged
nandi merged 9 commits from moonbit-rewrite into main 2026-11-23 01:57:10 +00:00
20 changed files with 636 additions and 447 deletions
Showing only changes of commit 17f81c60c8 - Show all commits

No files matched your search

+69 -51
View File
@@ -22,18 +22,18 @@ pub(all) struct WidgetInfo {
/// The label of the app the widget comes from (for the picker's search).
app : String
/// Natural height in CSS px.
h : Int
h : Int32
}
///|
/// 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
w : Int32
min_w : Int32
min_h : Int32
max_w : Int32
max_h : Int32
h : Bool
v : Bool
}
@@ -56,9 +56,9 @@ pub(all) enum Sheet {
/// The menu of the empty home.
HomeMenu
/// The menu of a home slot.
Item(Int)
Item(Int32)
/// The menu of a drawer app (row in the app list).
DrawerApp(Int)
DrawerApp(Int32)
WidgetPicker
}
@@ -75,11 +75,11 @@ pub(all) enum Edge {
/// at `left`, `top`.
pub(all) struct ResizeDrag {
edge : Edge
slot : Int
slot : Int32
left : Double
top : Double
mut cols : Int
mut rows : Int
mut cols : Int32
mut rows : Int32
}
///|
@@ -87,7 +87,7 @@ pub(all) struct ResizeDrag {
pub(all) struct Carry {
dx : Double
dy : Double
mut cell : Int
mut cell : Int32
}
///|
@@ -99,10 +99,10 @@ pub(all) struct Model {
mut wloading : Bool
/// The home screen, in order.
mut home : Array[@grid.Slot]
mut next_key : Int
mut next_key : Int32
/// Grid columns, and rows that fill the screen (0 until the page has measured).
mut cols : Int
mut nrows : Int
mut cols : Int32
mut nrows : Int32
/// Where the grid is on the screen (px, viewport) and how wide a column is.
mut grid_left : Double
mut grid_top : Double
@@ -116,9 +116,9 @@ pub(all) struct Model {
/// 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
mut lifted : Int32
/// Widget slot showing resize handles.
mut resizing : Int
mut resizing : Int32
/// The lifted slot was grabbed while showing handles: drop it back into them.
mut regrab : Bool
mut carry : Carry?
@@ -126,13 +126,13 @@ pub(all) struct Model {
/// 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 chosen : Int32
mut limits : Map[Int32, Limits]
mut notice : String
mut notice_gen : Int
mut notice_gen : Int32
// ---- self-update
mut installed : Int
mut declined : Int
mut installed : Int32
mut declined : Int32
mut checking : Bool
mut manual_check : Bool
mut apk_url : String?
@@ -143,7 +143,7 @@ pub(all) struct Model {
/// 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 fresh : Int32
mut gesture : @gesture.State
}
@@ -193,10 +193,10 @@ pub fn Model::new() -> Model {
///|
/// The most slots the home screen holds.
pub let home_cap : Int = 200
pub let home_cap : Int32 = 200
///|
pub let app_cap : Int = 512
pub let app_cap : Int32 = 512
///|
#derive(Eq, Debug)
@@ -207,31 +207,49 @@ pub(all) enum Msg {
/// 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)
Started(
now~ : Int64,
last_check~ : Int64,
declined~ : Int32,
installed~ : Int32,
)
/// 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)
Measured(
vw~ : Int32,
vh~ : Int32,
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?)
LimitsKnown(Int32, String?)
/// A package changed: look at the app list again.
Reload
/// The Home button or intent.
GoHome
Back
WidgetAdded(Int)
WidgetAdded(Int32)
/// A long press on a native widget view lifts its slot.
WidgetMenu(Int)
WidgetMenu(Int32)
/// A press on the native view of the widget showing handles picks it up.
WidgetGrab(Int)
WidgetGrab(Int32)
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)
Touch(
dx~ : Double,
dy~ : Double,
ms~ : Int32,
home_top~ : Bool,
list_end~ : Bool,
)
ReleaseFetched(String?)
VersionFetched(String?)
NoticeDone(Int)
NoticeDone(Int32)
// ---- from handlers
Query(String)
Clear
@@ -239,30 +257,30 @@ pub(all) enum Msg {
WClear
OpenDrawer
CloseDrawer
OpenApp(Int)
OpenApp(Int32)
OpenFirst
OpenHome(Int)
AddHome(Int)
ToggleHome(Int)
AppMenu(Int)
AppInfoOf(Int)
UninstallOf(Int)
OpenHome(Int32)
AddHome(Int32)
ToggleHome(Int32)
AppMenu(Int32)
AppInfoOf(Int32)
UninstallOf(Int32)
Menu
CloseSheet
PickApps
PickWidget
ChooseWidget(Int)
ChooseWidget(Int32)
ChooseFirstWidget
Remove(Int)
Remove(Int32)
/// Swap the slot with the one before it.
MoveEarlier(Int)
InfoOf(Int)
MoveEarlier(Int32)
InfoOf(Int32)
Settings
Wallpaper
Recents
CheckUpdates
Lift(Int)
Grab(Int)
Lift(Int32)
Grab(Int32)
ResizeBegin(Edge)
ResizeDone
/// Does nothing; stands in a chain to stop a tap reaching an element below.
@@ -279,7 +297,7 @@ pub(all) enum Effect {
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int)
RemoveWidget(Int32)
OpenSettings
PickWallpaper
OpenRecents
@@ -288,16 +306,16 @@ pub(all) enum Effect {
LoadApps
LoadWidgets
/// Ask the shell for a widget's limits and answer `LimitsKnown`.
QueryLimits(Int)
QueryLimits(Int32)
SaveHome(String)
SaveLastCheck(Int64)
/// Send the message after this many ms.
Delay(Int, Msg)
Delay(Int32, Msg)
/// After this many ms, feed `Hold(token)` to `input` (the long-press timer).
HoldTimer(Int, Int)
HoldTimer(Int32, Int32)
FetchRelease(String)
FetchVersion(String)
InstallApk(String, Int)
InstallApk(String, Int32)
/// The drawer opened with its search in front: focus it and raise the keyboard.
FocusSearch
HideKeyboard
+7 -13
View File
@@ -24,7 +24,7 @@ pub fn save_json(home : Array[@grid.Slot]) -> String {
///|
/// 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]? {
pub fn load_json(text : String, next_key : Ref[Int32]) -> 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] = []
@@ -52,7 +52,7 @@ pub fn load_json(text : String, next_key : Ref[Int]) -> Array[@grid.Slot]? {
}
///|
fn take_key(next_key : Ref[Int]) -> Int {
fn take_key(next_key : Ref[Int32]) -> Int32 {
let k = next_key.val
next_key.val = k + 1
k
@@ -63,14 +63,11 @@ fn take_key(next_key : Ref[Int]) -> Int {
/// `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] {
pub fn legacy_import(text : String, next_key : Ref[Int32]) -> Array[@grid.Slot] {
guard @jsonx.parse(text) is Some(kv) else { return [] }
fn num(k : String, i : Int, d : Int) -> Int {
fn num(k : String, i : Int32, d : Int32) -> Int32 {
match @jsonx.get(kv, "ultra.home.\{k}.\{i}") {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => d
}
Some(String(s)) => @string.parse_int(s) catch { _ => d }
Some(Number(n, ..)) => n.to_int()
_ => d
}
@@ -105,12 +102,9 @@ pub fn legacy_import(text : String, next_key : Ref[Int]) -> Array[@grid.Slot] {
}
///|
fn num2(kv : Json, key : String) -> Int {
fn num2(kv : Json, key : String) -> Int32 {
match @jsonx.get(kv, key) {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => 0
}
Some(String(s)) => @string.parse_int(s) catch { _ => 0 }
Some(Number(n, ..)) => n.to_int()
_ => 0
}
+111 -31
View File
@@ -32,9 +32,18 @@ struct Sim {
///|
fn Sim::new() -> Sim {
let m = Model::new()
let s = { m, tree: [], table: [], log: [], last_x: 0.0, last_y: 0.0 }
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(
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
}
@@ -71,11 +80,11 @@ fn text_of(n : @vdom.Node[Msg]) -> String {
fn Sim::chain_where(
self : Sim,
pred : (@vdom.Element[Msg]) -> Bool,
from? : Int = 0,
) -> Array[Int]? {
from~ : Int32 = 0,
) -> Array[Int32]? {
let mut counter = 0
let mut found : Array[Int]? = None
let stack : Array[Int] = []
let mut found : Array[Int32]? = None
let stack : Array[Int32] = []
fn walk(n : @vdom.Node[Msg]) -> Unit {
if found is Some(_) {
return
@@ -128,9 +137,9 @@ fn walk_count(n : @vdom.Node[Msg], bump : () -> Unit) -> Unit {
fn Sim::chain(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
) -> Array[Int] {
label~ : String = "",
from~ : Int32 = 0,
) -> Array[Int32] {
match
self.chain_where(from~, fn(e) {
e.classes.contains(class) &&
@@ -147,7 +156,12 @@ fn Sim::feed(self : Sim, inp : @gesture.Input) -> Unit {
}
///|
fn Sim::press(self : Sim, chain : Array[Int], x? : Double = 0.0, y? : Double = 0.0) -> Unit {
fn Sim::press(
self : Sim,
chain : Array[Int32],
x~ : Double = 0.0,
y~ : Double = 0.0,
) -> Unit {
self.feed(Down(x~, y~, chain~))
self.last_x = x
self.last_y = y
@@ -180,15 +194,20 @@ fn Sim::release(self : Sim) -> Unit {
fn Sim::tap(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
label~ : String = "",
from~ : Int32 = 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 {
fn Sim::long_press(
self : Sim,
chain : Array[Int32],
x~ : Double = 0.0,
y~ : Double = 0.0,
) -> Unit {
self.press(chain, x~, y~)
self.hold()
self.release()
@@ -223,7 +242,7 @@ fn Sim::has_effect(self : Sim, e : Effect) -> Bool {
///|
/// Centre of the cell (col, row) in viewport px.
fn cell_center(col : Int, row : Int) -> (Double, Double) {
fn cell_center(col : Int32, row : Int32) -> (Double, Double) {
(
16.0 + col.to_double() * (65.2 + 8.0) + 32.6,
150.0 + row.to_double() * 72.0 + 32.0,
@@ -321,7 +340,12 @@ test "search filters the drawer; Enter opens the first match" {
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" }))
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))
@@ -383,7 +407,13 @@ test "uninstall asks the shell; the slot goes when the app leaves the list" {
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\":\"\"}]}")))
s.send(
AppsLoaded(
Some(
"{\"apps\":[{\"label\":\"Chrome\",\"component\":\"c.chrome/.Main\",\"icon\":\"\"}]}",
),
),
)
assert_eq(s.m.home.length(), 0)
}
@@ -437,8 +467,8 @@ test "an app dropped in an empty cell stays there; the rest stay packed" {
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 }))
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))
@@ -452,7 +482,7 @@ test "dropping a pinned app onto another pinned one moves that one on" {
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.press(s.chain("tile", label~), x=fx, y=fy)
s.hold()
s.move_to(tx, ty)
s.release()
@@ -495,7 +525,11 @@ test "add a widget: picker search, choose, shell adds it" {
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.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))
@@ -504,7 +538,12 @@ test "add a widget: picker search, choose, shell adds it" {
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}")))
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\""))
@@ -530,7 +569,12 @@ test "a widget: hold opens resize handles; drag the handles; Done" {
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}")))
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)
@@ -538,9 +582,15 @@ test "a widget: hold opens resize handles; drag the handles; Done" {
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"))
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()
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)
@@ -548,7 +598,9 @@ test "a widget: hold opens resize handles; drag the handles; Done" {
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()
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)
@@ -574,10 +626,19 @@ test "resizing stays within the widget's limits" {
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}")))
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()
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()
@@ -592,7 +653,12 @@ test "a native widget view lifts, drags and drops its slot" {
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}")))
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)
@@ -675,7 +741,10 @@ test "the old WebView build's home screen is brought over once" {
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(
(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()
@@ -684,7 +753,15 @@ test "the old WebView build's home screen is brought over once" {
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))))
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)
}
@@ -697,7 +774,10 @@ fn slot_app(c : String) -> @grid.Slot {
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()
let r = load_json(
"{\"slots\":[{\"kind\":\"app\"},{\"kind\":\"app\",\"str\":\"a\"}]}",
Ref::new(1),
).unwrap()
assert_eq(r.length(), 1)
}
+53 -29
View File
@@ -11,7 +11,7 @@ pub fn matches_query(label : String, query : String) -> Bool {
}
///|
pub fn Model::app_row(self : Model, component : String) -> Int {
pub fn Model::app_row(self : Model, component : String) -> Int32 {
for i in 0..<self.apps.length() {
if self.apps[i].component == component {
return i
@@ -22,7 +22,7 @@ pub fn Model::app_row(self : Model, component : String) -> Int {
///|
/// The home slot holding the app at `row` in the app list, or -1.
pub fn Model::home_of(self : Model, row : Int) -> Int {
pub fn Model::home_of(self : Model, row : Int32) -> Int32 {
let comp = self.apps[row].component
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == comp {
@@ -33,7 +33,7 @@ pub fn Model::home_of(self : Model, row : Int) -> Int {
}
///|
pub fn Model::slot_of_widget(self : Model, wid : Int) -> Int {
pub fn Model::slot_of_widget(self : Model, wid : Int32) -> Int32 {
for i in 0..<self.home.length() {
if self.home[i].kind == Widget && self.home[i].wid == wid {
return i
@@ -44,7 +44,7 @@ pub fn Model::slot_of_widget(self : Model, wid : Int) -> Int {
///|
/// The first app (row in the list) whose label matches the search.
pub fn Model::first_match(self : Model) -> Int {
pub fn Model::first_match(self : Model) -> Int32 {
for i in 0..<self.apps.length() {
if matches_query(self.apps[i].label, self.query) {
return i
@@ -54,13 +54,16 @@ pub fn Model::first_match(self : Model) -> Int {
}
///|
pub fn Model::widget_matches(self : Model, i : Int) -> Bool {
pub fn Model::widget_matches(self : Model, i : Int32) -> Bool {
matches_query(self.widgets[i].label, self.wquery) ||
matches_query(self.widgets[i].app, self.wquery) && trimmed(self.wquery) != ""
(
matches_query(self.widgets[i].app, self.wquery) &&
trimmed(self.wquery) != ""
)
}
///|
pub fn Model::first_widget_match(self : Model) -> Int {
pub fn Model::first_widget_match(self : Model) -> Int32 {
for i in 0..<self.widgets.length() {
if self.widget_matches(i) {
return i
@@ -71,7 +74,7 @@ pub fn Model::first_widget_match(self : Model) -> Int {
///|
/// Home slots that are not drawn: apps that are not installed.
pub fn Model::hidden(self : Model, i : Int) -> Bool {
pub fn Model::hidden(self : Model, i : Int32) -> Bool {
self.home[i].kind == App && self.app_row(self.home[i].str) < 0
}
@@ -93,14 +96,14 @@ fn Model::push_slot(self : Model, s : @grid.Slot) -> Unit {
}
///|
fn Model::new_key(self : Model) -> Int {
fn Model::new_key(self : Model) -> Int32 {
let k = self.next_key
self.next_key += 1
k
}
///|
fn Model::remove_slot(self : Model, at : Int, fx : Array[Effect]) -> Unit {
fn Model::remove_slot(self : Model, at : Int32, fx : Array[Effect]) -> Unit {
if at < 0 || at >= self.home.length() {
return
}
@@ -121,13 +124,15 @@ fn Model::remove_slot(self : Model, at : Int, fx : Array[Effect]) -> Unit {
}
///|
fn Model::add_app(self : Model, row : Int, fx : Array[Effect]) -> Unit {
fn Model::add_app(self : Model, row : Int32, 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.push_slot(
@grid.Slot::app(self.apps[row].component, key=self.new_key()),
)
self.say("Added to home", fx)
}
}
@@ -191,7 +196,7 @@ fn Model::close_drawer(self : Model, fx : Array[Effect]) -> Unit {
fn Model::slot_box(
self : Model,
packed : @grid.Packed,
i : Int,
i : Int32,
) -> (Double, Double, Double, Double)? {
match packed.cells[i] {
Some(c) => {
@@ -209,7 +214,12 @@ fn inside(b : (Double, Double, Double, Double), x : Double, y : Double) -> Bool
///|
/// 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 {
fn Model::slot_at(
self : Model,
packed : @grid.Packed,
x : Double,
y : Double,
) -> Int32 {
for i in 0..<self.home.length() {
if i == self.lifted {
continue
@@ -244,15 +254,13 @@ fn Model::drag_lifted(
Some(b) => (b.0, b.1)
None => (x0, y0)
}
let c = { dx: x0 - bx, dy: y0 - by, cell: -1 }
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) {
if !widget && self.slot_box(packed, self.lifted) is Some(b) && inside(b, x, y) {
return
}
let half_w = self.col_w / 2.0
@@ -264,7 +272,9 @@ fn Model::drag_lifted(
)
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 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
@@ -331,7 +341,14 @@ fn Model::begin_resize(self : Model, edge : Edge, fx : Array[Effect]) -> Unit {
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() })
self.resize = Some({
edge,
slot: i,
left,
top,
cols: s.cols(self.cols),
rows: s.height(),
})
fx.push(QueryLimits(s.wid))
}
@@ -405,7 +422,7 @@ pub fn update(m : Model, msg : Msg) -> Array[Effect] {
}
///|
fn Model::choose_widget(self : Model, i : Int, fx : Array[Effect]) -> Unit {
fn Model::choose_widget(self : Model, i : Int32, fx : Array[Effect]) -> Unit {
if i >= 0 && i < self.widgets.length() {
if self.home.length() < home_cap {
self.chosen = i
@@ -508,7 +525,9 @@ fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
fx.push(HideKeyboard)
}
WidgetAdded(id) =>
if m.chosen >= 0 && m.chosen < m.widgets.length() && m.home.length() < home_cap {
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(
@@ -566,7 +585,7 @@ fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
ReleaseFetched(text) => {
let release = text.bind(@updater.parse_release)
match release {
Some({ version_url: Some(v), apk_url: Some(a), tag }) => {
Some({ version_url: Some(v), apk_url: Some(a), tag, }) => {
m.apk_url = Some(a)
m.release_tag = tag
fx.push(FetchVersion(v))
@@ -588,7 +607,12 @@ fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
match (latest, m.apk_url) {
(Some(latest), Some(url)) =>
match
@updater.decide(latest, m.installed, m.declined, manual=m.manual_check) {
@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)
@@ -599,10 +623,7 @@ fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
fx.push(InstallApk(url, n))
}
}
_ =>
if m.manual_check {
m.say("Couldn't check for updates", fx)
}
_ => if m.manual_check { m.say("Couldn't check for updates", fx) }
}
}
NoticeDone(gen) => if gen == m.notice_gen { m.notice = "" }
@@ -757,7 +778,10 @@ pub fn input(
inp : @gesture.Input,
) -> Array[Effect] {
let fx : Array[Effect] = []
fn nearest(chain : Array[Int], pick : (@vdom.Handlers[Msg]) -> Msg?) -> Msg? {
fn nearest(
chain : Array[Int32],
pick : (@vdom.Handlers[Msg]) -> Msg?,
) -> Msg? {
for id in chain {
if id >= 0 && id < table.length() {
if pick(table[id]) is Some(msg) {
+123 -122
View File
@@ -3,16 +3,16 @@ using @vdom {type Node, type Handlers, el, text, cls_if}
///|
fn tap(msg : Msg) -> Handlers[Msg] {
{ ..Handlers::none(), tap: Some(msg) }
{ ..Handlers::none(), tap: Some(msg), }
}
///|
fn icon(key : String) -> Node[Msg] {
el(
"img",
classes=["icon"],
attrs=[("alt", ""), ("draggable", "false"), ("data-icon", key)],
)
el("img", classes=["icon"], attrs=[
("alt", ""),
("draggable", "false"),
("data-icon", key),
])
}
///|
@@ -27,14 +27,14 @@ fn handle(edge : String, e : Edge) -> Node[Msg] {
"span",
classes=["resize-handle"],
attrs=[("data-edge", edge), ("aria-hidden", "true")],
handlers={ ..Handlers::none(), down: Some(ResizeBegin(e)), tap: Some(Nop) },
handlers={ ..Handlers::none(), down: Some(ResizeBegin(e)), tap: Some(Nop), },
)
}
///|
fn Model::view_slot(
self : Model,
i : Int,
i : Int32,
packed : @grid.Packed,
) -> Node[Msg]? {
let s = self.home[i]
@@ -49,7 +49,9 @@ fn Model::view_slot(
if live {
attrs.push(("data-wid", s.wid.to_string()))
}
let children = [el("span", classes=["widget-label"], children=[text(s.str)])]
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))
@@ -59,14 +61,26 @@ fn Model::view_slot(
el(
"li",
key=s.key,
classes=["widget-slot", cls_if("lifted", i == self.lifted), cls_if("resizing", i == self.resizing)],
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 },
down: if i == self.resizing {
Some(Grab(i))
} else {
None
},
tap: if i == self.resizing {
Some(Nop)
} else {
None
},
},
children~,
),
@@ -82,8 +96,15 @@ fn Model::view_slot(
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)])],
handlers={
..Handlers::none(),
tap: Some(OpenHome(i)),
press: Some(Lift(i)),
},
children=[
icon(a.icon),
el("span", classes=["name"], children=[text(a.label)]),
],
),
)
}
@@ -92,22 +113,12 @@ fn Model::view_slot(
///|
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")]),
],
),
],
)
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")]),
]),
])
}
///|
@@ -147,11 +158,9 @@ fn Model::view_home(self : Model) -> Node[Msg] {
]
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("p", classes=["hint"], children=[
text("Swipe down for all apps. Long-press to add apps and widgets."),
]),
)
}
el(
@@ -160,7 +169,11 @@ fn Model::view_home(self : Model) -> Node[Msg] {
handlers={
..Handlers::none(),
press: Some(Menu),
tap: if self.resizing >= 0 { Some(ResizeDone) } else { None },
tap: if self.resizing >= 0 {
Some(ResizeDone)
} else {
None
},
},
children~,
)
@@ -182,66 +195,63 @@ fn Model::view_drawer(self : Model) -> Node[Msg] {
handlers=if self.picking {
tap(ToggleHome(i))
} else {
{ ..Handlers::none(), tap: Some(OpenApp(i)), press: Some(AppMenu(i)) }
{
..Handlers::none(),
tap: Some(OpenApp(i)),
press: Some(AppMenu(i)),
}
},
children=[icon(a.icon), el("span", classes=["name"], children=[text(a.label)])],
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" })],
),
],
),
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.")],
),
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")],
),
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…")]))
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.")]))
}
@@ -316,9 +326,13 @@ fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
WidgetPicker => {
items.push(sheet_title("Add a widget"))
if self.wloading {
items.push(el("p", classes=["empty"], children=[text("Loading widgets…")]))
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.")]))
items.push(
el("p", classes=["empty"], children=[text("No widgets installed.")]),
)
} else {
items.push(
el(
@@ -352,17 +366,17 @@ fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
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)],
),
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.")]))
items.push(
el("p", classes=["empty"], children=[text("No widgets match.")]),
)
}
}
}
@@ -372,7 +386,7 @@ fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
"div",
classes=["sheet"],
attrs=[("role", "dialog"), ("aria-modal", "true")],
handlers={ ..Handlers::none(), escape: Some(CloseSheet) },
handlers={ ..Handlers::none(), escape: Some(CloseSheet), },
children=items,
),
]
@@ -380,30 +394,20 @@ fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
///|
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")],
),
],
)
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"),
]),
])
}
///|
@@ -420,12 +424,9 @@ pub fn view(m : Model) -> Array[Node[Msg]] {
}
if m.notice != "" {
out.push(
el(
"div",
classes=["notice"],
attrs=[("role", "status")],
children=[text(m.notice)],
),
el("div", classes=["notice"], attrs=[("role", "status")], children=[
text(m.notice),
]),
)
}
out
@@ -465,7 +466,7 @@ pub(all) enum Key {
pub fn key(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
chain : Array[Int32],
k : Key,
) -> Array[Effect] {
for id in chain {
@@ -488,7 +489,7 @@ pub fn key(
pub fn typed(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
chain : Array[Int32],
value : String,
) -> Array[Effect] {
for id in chain {
+19 -11
View File
@@ -14,7 +14,7 @@
///|
/// How long a stationary hold takes to become a long press.
pub let hold_ms : Int = 500
pub let hold_ms : Int32 = 500
///|
/// How far (px) the pointer may travel before it stops being a tap or a hold.
@@ -23,23 +23,23 @@ pub let slop : Double = 10.0
///|
#derive(Eq, Debug)
pub(all) enum Input {
Down(x~ : Double, y~ : Double, chain~ : Array[Int])
Down(x~ : Double, y~ : Double, chain~ : Array[Int32])
Move(x~ : Double, y~ : Double)
Up(x~ : Double, y~ : Double)
Cancel
/// The timer started by `Schedule(_, token)` fired.
Hold(Int)
Hold(Int32)
}
///|
#derive(Eq, Debug)
pub(all) enum Out {
/// Start a timer of this many ms, then send `Hold(token)`.
Schedule(Int, Int)
Schedule(Int32, Int32)
/// The pointer went down on this chain (the app may act at once, e.g. grab a widget).
Began(chain~ : Array[Int], x~ : Double, y~ : Double)
Tap(chain~ : Array[Int])
Press(chain~ : Array[Int])
Began(chain~ : Array[Int32], x~ : Double, y~ : Double)
Tap(chain~ : Array[Int32])
Press(chain~ : Array[Int32])
/// The pointer is at x, y; it went down at x0, y0.
Drag(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
/// The pointer is up. `moved`: it travelled past the slop; `held`: a press fired.
@@ -53,13 +53,21 @@ pub(all) struct State {
mut y0 : Double
mut moved : Bool
mut held : Bool
mut chain : Array[Int]
mut token : Int
mut chain : Array[Int32]
mut token : Int32
}
///|
pub fn State::new() -> State {
{ down: false, x0: 0.0, y0: 0.0, moved: false, held: false, chain: [], token: 0 }
{
down: false,
x0: 0.0,
y0: 0.0,
moved: false,
held: false,
chain: [],
token: 0,
}
}
///|
@@ -130,7 +138,7 @@ pub(all) enum Swipe {
///|
/// A touch that travelled dx, dy px in dt ms is a swipe when it was quick, long enough
/// and more vertical than horizontal.
pub fn classify_swipe(dx : Double, dy : Double, dt : Int) -> Swipe? {
pub fn classify_swipe(dx : Double, dy : Double, dt : Int32) -> Swipe? {
if dt >= 700 || dy.abs() < 60.0 || dx.abs() > dy.abs() {
None
} else if dy > 0.0 {
+8 -5
View File
@@ -1,11 +1,14 @@
///|
test "a tap: down then up without moving" {
let g = State::new()
assert_eq(
g.step(Down(x=10.0, y=10.0, chain=[3, 1])),
[Began(chain=[3, 1], x=10.0, y=10.0), Schedule(500, 1)],
)
assert_eq(g.step(Up(x=11.0, y=10.0)), [Tap(chain=[3, 1]), Release(moved=false, held=false)])
assert_eq(g.step(Down(x=10.0, y=10.0, chain=[3, 1])), [
Began(chain=[3, 1], x=10.0, y=10.0),
Schedule(500, 1),
])
assert_eq(g.step(Up(x=11.0, y=10.0)), [
Tap(chain=[3, 1]),
Release(moved=false, held=false),
])
}
///|
+1
View File
@@ -0,0 +1 @@
+63 -62
View File
@@ -10,15 +10,15 @@
///|
/// Row height in px.
pub let cell_px : Int = 64
pub let cell_px : Int32 = 64
///|
/// Gap between rows in px.
pub let row_gap : Int = 8
pub let row_gap : Int32 = 8
///|
/// Gap between columns in px.
pub let col_gap : Int = 8
pub let col_gap : Int32 = 8
///|
#derive(Eq, Debug)
@@ -34,36 +34,36 @@ pub(all) struct Slot {
/// An app's component name, or a widget's label.
str : String
/// A widget's host id (0 for apps).
wid : Int
wid : Int32
/// A widget's width in columns (0: the whole row).
mut w : Int
mut w : Int32
/// A widget's height in rows.
mut rows : Int
mut x : Int
mut y : Int
mut rows : Int32
mut x : Int32
mut y : Int32
/// A stable identity for the view's keyed diff (not persisted).
key : Int
key : Int32
}
///|
pub fn Slot::app(str : String, key~ : Int = 0) -> Slot {
{ kind: App, str, wid: 0, w: 0, rows: 1, x: -1, y: -1, key }
pub fn Slot::app(str : String, key~ : Int32 = 0) -> Slot {
{ kind: App, str, wid: 0, w: 0, rows: 1, x: -1, y: -1, key, }
}
///|
pub fn Slot::widget(
str : String,
wid : Int,
w~ : Int = 0,
rows~ : Int = 1,
key~ : Int = 0,
wid : Int32,
w~ : Int32 = 0,
rows~ : Int32 = 1,
key~ : Int32 = 0,
) -> Slot {
{ kind: Widget, str, wid, w, rows, x: -1, y: -1, key }
{ kind: Widget, str, wid, w, rows, x: -1, y: -1, key, }
}
///|
/// Rows of app tiles nearest to a widget height in px, at least one.
pub fn widget_rows(px : Int) -> Int {
pub fn widget_rows(px : Int32) -> Int32 {
let k = (px + row_gap + (cell_px + row_gap) / 2) / (cell_px + row_gap)
if k < 1 {
1
@@ -73,7 +73,7 @@ pub fn widget_rows(px : Int) -> Int {
}
///|
pub fn Slot::cols(self : Slot, cols : Int) -> Int {
pub fn Slot::cols(self : Slot, cols : Int32) -> Int32 {
match self.kind {
App => 1
Widget => if self.w <= 0 || self.w > cols { cols } else { self.w }
@@ -81,7 +81,7 @@ pub fn Slot::cols(self : Slot, cols : Int) -> Int {
}
///|
pub fn Slot::height(self : Slot) -> Int {
pub fn Slot::height(self : Slot) -> Int32 {
match self.kind {
App => 1
Widget => if self.rows < 1 { 1 } else { self.rows }
@@ -89,7 +89,7 @@ pub fn Slot::height(self : Slot) -> Int {
}
///|
pub fn Slot::pinned(self : Slot, cols : Int) -> Bool {
pub fn Slot::pinned(self : Slot, cols : Int32) -> Bool {
self.x >= 0 && self.y >= 0 && self.x + self.cols(cols) <= cols
}
@@ -97,10 +97,10 @@ pub fn Slot::pinned(self : Slot, cols : Int) -> Bool {
/// Where a slot goes, in cells.
#derive(Eq, Debug)
pub(all) struct Cell {
col : Int
row : Int
w : Int
h : Int
col : Int32
row : Int32
w : Int32
h : Int32
}
///|
@@ -108,7 +108,7 @@ pub(all) struct Packed {
/// One per slot, `None` for a hidden one.
cells : Array[Cell?]
/// Rows used, at least the rows that fill the screen.
rows : Int
rows : Int32
}
///|
@@ -118,16 +118,16 @@ pub(all) struct Packed {
/// leaves slot i out (an app that is not installed).
pub fn pack(
slots : Array[Slot],
cols : Int,
nrows : Int,
hidden~ : (Int) -> Bool = fn(_) { false },
cols : Int32,
nrows : Int32,
hidden~ : (Int32) -> Bool = fn(_) { false },
) -> Packed {
let occ : Array[Array[Bool]] = []
fn taken(c : Int, r : Int) -> Bool {
fn taken(c : Int32, r : Int32) -> Bool {
r < occ.length() && occ[r][c]
}
fn fits(c : Int, r : Int, w : Int, h : Int) -> Bool {
fn fits(c : Int32, r : Int32, w : Int32, h : Int32) -> Bool {
if c < 0 || c + w > cols {
return false
}
@@ -141,7 +141,7 @@ pub fn pack(
true
}
fn mark(c : Int, r : Int, w : Int, h : Int) -> Unit {
fn mark(c : Int32, r : Int32, w : Int32, h : Int32) -> Unit {
for y in r..<(r + h) {
while occ.length() <= y {
occ.push(Array::make(cols, false))
@@ -162,7 +162,7 @@ pub fn pack(
}
let w = s.cols(cols)
let h = s.height()
cells[i] = Some({ col: s.x, row: s.y, w, h })
cells[i] = Some({ col: s.x, row: s.y, w, h, })
mark(s.x, s.y, w, h)
rows = @cmp.maximum(rows, s.y + h)
}
@@ -178,7 +178,7 @@ pub fn pack(
let mut c = 0
while c + w <= cols {
if fits(c, r, w, h) {
cells[i] = Some({ col: c, row: r, w, h })
cells[i] = Some({ col: c, row: r, w, h, })
mark(c, r, w, h)
rows = @cmp.maximum(rows, r + h)
break
@@ -188,7 +188,7 @@ pub fn pack(
r += 1
}
}
{ cells, rows }
{ cells, rows, }
}
///|
@@ -206,19 +206,15 @@ pub fn box(cell : Cell, col_w : Double) -> (Double, Double, Double, Double) {
///|
/// The cell nearest to a point (px in the grid, from its top left): (col, row).
pub fn cell_at(x : Double, y : Double, col_w : Double) -> (Int, Int) {
let c = ((x / (col_w + col_gap.to_double()) + 0.5).floor()).to_int()
let r = ((y / (cell_px + row_gap).to_double() + 0.5).floor()).to_int()
pub fn cell_at(x : Double, y : Double, col_w : Double) -> (Int32, Int32) {
let c = (x / (col_w + col_gap.to_double()) + 0.5).floor().to_int()
let r = (y / (cell_px + row_gap).to_double() + 0.5).floor().to_int()
(@cmp.maximum(0, c), @cmp.maximum(0, r))
}
///|
/// The cell whose box contains a point, or `None` outside every cell (in the gaps).
pub fn cell_under(
x : Double,
y : Double,
col_w : Double,
) -> (Int, Int)? {
pub fn cell_under(x : Double, y : Double, col_w : Double) -> (Int32, Int32)? {
if x < 0.0 || y < 0.0 {
return None
}
@@ -226,7 +222,8 @@ pub fn cell_under(
let ph = (cell_px + row_gap).to_double()
let c = (x / pw).floor().to_int()
let r = (y / ph).floor().to_int()
if x - c.to_double() * pw > col_w || y - r.to_double() * ph > cell_px.to_double() {
if x - c.to_double() * pw > col_w ||
y - r.to_double() * ph > cell_px.to_double() {
None
} else {
Some((c, r))
@@ -238,11 +235,11 @@ pub fn cell_under(
/// 0: no limit on rows).
pub fn pin(
slots : Array[Slot],
i : Int,
col : Int,
row : Int,
cols : Int,
nrows : Int,
i : Int32,
col : Int32,
row : Int32,
cols : Int32,
nrows : Int32,
) -> Unit {
let s = slots[i]
let mut x = col
@@ -259,7 +256,7 @@ pub fn pin(
///|
/// Unpin the slots under pinned slot `i`, so they flow into free cells.
pub fn clear_cells(slots : Array[Slot], i : Int, cols : Int) -> Unit {
pub fn clear_cells(slots : Array[Slot], i : Int32, cols : Int32) -> Unit {
let a = slots[i]
for j in 0..<slots.length() {
let b = slots[j]
@@ -278,14 +275,14 @@ pub fn clear_cells(slots : Array[Slot], i : Int, cols : Int) -> Unit {
///|
/// Take slot `a` out and put it back at `b`, shifting the slots between.
pub fn move_slot(slots : Array[Slot], a : Int, b : Int) -> Unit {
pub fn move_slot(slots : Array[Slot], a : Int32, b : Int32) -> Unit {
let s = slots.remove(a)
slots.insert(b, s)
}
///|
/// The size in px of `k` cells of `size` px, `gap` apart.
pub fn span(k : Int, size : Double, gap : Double) -> Double {
pub fn span(k : Int32, size : Double, gap : Double) -> Double {
k.to_double() * size + (k - 1).to_double() * gap
}
@@ -295,13 +292,13 @@ pub fn span(k : Int, size : Double, gap : Double) -> Double {
/// `lo`..`hi` cells.
pub fn fit(
want : Double,
lo : Int,
hi : Int,
lo : Int32,
hi : Int32,
size : Double,
gap : Double,
min : Int,
max : Int,
) -> Int {
min : Int32,
max : Int32,
) -> Int32 {
let mut k = ((want + gap) / (size + gap) + 0.5).floor().to_int()
while k < hi && span(k, size, gap) < (min - 8).to_double() {
k += 1
@@ -314,13 +311,15 @@ pub fn fit(
///|
/// Columns a new widget of natural width `px` starts at (0: the whole row).
pub fn widget_cols(px : Int, col_w : Double, cols : Int) -> Int {
pub fn widget_cols(px : Int32, col_w : Double, cols : Int32) -> Int32 {
if px <= 0 {
return 0
}
let k = @cmp.maximum(
1,
((px + col_gap - 8).to_double() / (col_w + col_gap.to_double())).ceil().to_int(),
((px + col_gap - 8).to_double() / (col_w + col_gap.to_double()))
.ceil()
.to_int(),
)
if k >= cols {
0
@@ -331,7 +330,7 @@ pub fn widget_cols(px : Int, col_w : Double, cols : Int) -> Int {
///|
/// How many grid columns the screen has for a viewport width in CSS px.
pub fn columns_for(width : Int) -> Int {
pub fn columns_for(width : Int32) -> Int32 {
if width >= 480 {
6
} else {
@@ -341,13 +340,15 @@ pub fn columns_for(width : Int) -> Int {
///|
/// The width of one column, given the width of the grid.
pub fn column_width(grid_width : Double, cols : Int) -> Double {
pub fn column_width(grid_width : Double, cols : Int32) -> Double {
(grid_width - (cols - 1).to_double() * col_gap.to_double()) / cols.to_double()
}
///|
/// How many rows of the grid fit in `height` px.
pub fn rows_fit(height : Double) -> Int {
let r = ((height + row_gap.to_double()) / (cell_px + row_gap).to_double()).floor().to_int()
pub fn rows_fit(height : Double) -> Int32 {
let r = ((height + row_gap.to_double()) / (cell_px + row_gap).to_double())
.floor()
.to_int()
@cmp.maximum(1, r)
}
+39 -44
View File
@@ -1,5 +1,5 @@
///|
fn app(x? : Int = -1, y? : Int = -1) -> Slot {
fn app(x~ : Int32 = -1, y~ : Int32 = -1) -> Slot {
let s = Slot::app("a")
s.x = x
s.y = y
@@ -7,7 +7,7 @@ fn app(x? : Int = -1, y? : Int = -1) -> Slot {
}
///|
fn widget(w : Int, rows : Int, x? : Int = -1, y? : Int = -1) -> Slot {
fn widget(w : Int32, rows : Int32, x~ : Int32 = -1, y~ : Int32 = -1) -> Slot {
let s = Slot::widget("W", 1, w~, rows~)
s.x = x
s.y = y
@@ -17,9 +17,9 @@ fn widget(w : Int, rows : Int, x? : Int = -1, y? : Int = -1) -> Slot {
///|
fn cells(
home : Array[Slot],
cols? : Int = 5,
nrows? : Int = 0,
) -> Array[(Int, Int, Int, Int)?] {
cols~ : Int32 = 5,
nrows~ : Int32 = 0,
) -> Array[(Int32, Int32, Int32, Int32)?] {
pack(home, cols, nrows).cells.map(fn(c) {
match c {
Some(c) => Some((c.col, c.row, c.w, c.h))
@@ -30,59 +30,54 @@ fn cells(
///|
test "apps fill rows left to right" {
assert_eq(
cells([app(), app(), app(), app(), app(), app()]),
[
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((0, 1, 1, 1)),
],
)
assert_eq(cells([app(), app(), app(), app(), app(), app()]), [
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((0, 1, 1, 1)),
])
}
///|
test "a whole-row widget takes its rows; apps go below" {
assert_eq(cells([widget(0, 2), app()]), [Some((0, 0, 5, 2)), Some((0, 2, 1, 1))])
assert_eq(cells([widget(0, 2), app()]), [
Some((0, 0, 5, 2)),
Some((0, 2, 1, 1)),
])
}
///|
test "dense: apps fill the cells beside a narrow widget" {
assert_eq(
cells([widget(3, 2), app(), app(), app(), app(), app()]),
[
Some((0, 0, 3, 2)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((3, 1, 1, 1)),
Some((4, 1, 1, 1)),
Some((0, 2, 1, 1)),
],
)
assert_eq(cells([widget(3, 2), app(), app(), app(), app(), app()]), [
Some((0, 0, 3, 2)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((3, 1, 1, 1)),
Some((4, 1, 1, 1)),
Some((0, 2, 1, 1)),
])
}
///|
test "a widget too wide for the rest of a row starts the next; apps backfill" {
assert_eq(
cells([app(), app(), app(), widget(3, 1), app()]),
[
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((0, 1, 3, 1)),
Some((3, 0, 1, 1)),
],
)
assert_eq(cells([app(), app(), app(), widget(3, 1), app()]), [
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((0, 1, 3, 1)),
Some((3, 0, 1, 1)),
])
}
///|
test "pinned slots keep their cell; the rest flow around them" {
assert_eq(
cells([app(), app(x=2, y=3), app()]),
[Some((0, 0, 1, 1)), Some((2, 3, 1, 1)), Some((1, 0, 1, 1))],
)
assert_eq(cells([app(), app(x=2, y=3), app()]), [
Some((0, 0, 1, 1)),
Some((2, 3, 1, 1)),
Some((1, 0, 1, 1)),
])
}
///|
@@ -100,7 +95,7 @@ test "a pin that no longer fits the columns flows instead" {
test "hidden slots take no cell" {
let p = pack([app(), app()], 5, 0, hidden=fn(i) { i == 0 })
assert_eq(p.cells[0], None)
assert_eq(p.cells[1], Some({ col: 0, row: 0, w: 1, h: 1 }))
assert_eq(p.cells[1], Some({ col: 0, row: 0, w: 1, h: 1, }))
}
///|
@@ -144,7 +139,7 @@ test "a new widget's columns from its natural width" {
///|
test "boxes and cells in px" {
let b = box({ col: 1, row: 2, w: 2, h: 1 }, 70.0)
let b = box({ col: 1, row: 2, w: 2, h: 1, }, 70.0)
assert_eq(b, (78.0, 144.0, 148.0, 64.0))
assert_eq(cell_at(80.0, 150.0, 70.0), (1, 2))
assert_eq(cell_under(80.0, 150.0, 70.0), Some((1, 2)))
+4 -4
View File
@@ -10,7 +10,7 @@ pub fn get(j : Json, key : String) -> Json? {
}
///|
pub fn str(j : Json, key : String, default? : String = "") -> String {
pub fn str(j : Json, key : String, default~ : String = "") -> String {
match get(j, key) {
Some(String(s)) => s
_ => default
@@ -18,7 +18,7 @@ pub fn str(j : Json, key : String, default? : String = "") -> String {
}
///|
pub fn int(j : Json, key : String, default? : Int = 0) -> Int {
pub fn int(j : Json, key : String, default~ : Int32 = 0) -> Int32 {
match get(j, key) {
Some(Number(n, ..)) => n.to_int()
Some(True) => 1
@@ -27,7 +27,7 @@ pub fn int(j : Json, key : String, default? : Int = 0) -> Int {
}
///|
pub fn bool(j : Json, key : String, default? : Bool = false) -> Bool {
pub fn bool(j : Json, key : String, default~ : Bool = false) -> Bool {
match get(j, key) {
Some(True) => true
Some(False) => false
@@ -46,7 +46,7 @@ pub fn arr(j : Json, key : String) -> Array[Json] {
///|
pub fn parse(text : String) -> Json? {
try Some(@json.parse(text)) catch {
Some(@json.parse(text)) catch {
_ => None
}
}
+10 -11
View File
@@ -7,8 +7,7 @@
/// versionCode. The latest-release API names the download URLs of both assets.
///|
pub let release_api : String =
"https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest"
pub let release_api : String = "https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest"
///|
pub let apk_asset : String = "ultra-launcher.apk"
@@ -45,12 +44,12 @@ pub fn parse_release(text : String) -> Release? {
}
}
}
Some({ tag: @jsonx.str(json, "tag_name"), version_url, apk_url })
Some({ tag: @jsonx.str(json, "tag_name"), version_url, apk_url, })
}
///|
/// The versionCode in a `version.json`.
pub fn parse_version(text : String) -> Int? {
pub fn parse_version(text : String) -> Int32? {
guard @jsonx.parse(text) is Some(json) else { return None }
match @jsonx.get(json, "versionCode") {
Some(Number(n, ..)) => Some(n.to_int())
@@ -60,7 +59,7 @@ pub fn parse_version(text : String) -> Int? {
///|
/// The versionCode a release tag `build-<N>` stands for.
pub fn tag_version(tag : String) -> Int? {
pub fn tag_version(tag : String) -> Int32? {
guard tag.has_prefix("build-") else { return None }
let rest = tag.clamped_view(start=6)
if rest.length() == 0 {
@@ -79,20 +78,20 @@ pub fn tag_version(tag : String) -> Int? {
///|
#derive(Eq, Debug)
pub(all) enum Decision {
UpToDate(Int)
UpToDate(Int32)
/// A newer build exists and should be installed.
Install(Int)
Install(Int32)
/// The user already cancelled this build's install; not offered again unless they ask.
Declined(Int)
Declined(Int32)
}
///|
/// `latest` is the newest published versionCode, `installed` the running one, `declined`
/// the last build whose install the user cancelled (-1: none).
pub fn decide(
latest : Int,
installed : Int,
declined : Int,
latest : Int32,
installed : Int32,
declined : Int32,
manual~ : Bool,
) -> Decision {
if latest <= installed {
+7 -2
View File
@@ -21,7 +21,10 @@ test "bad or partial release json" {
///|
test "version.json" {
assert_eq(parse_version("{\"versionCode\": 29000123, \"commit\": \"abc\"}"), Some(29000123))
assert_eq(
parse_version("{\"versionCode\": 29000123, \"commit\": \"abc\"}"),
Some(29000123),
)
assert_eq(parse_version("{}"), None)
assert_eq(parse_version("x"), None)
}
@@ -32,7 +35,9 @@ test "tags compare as build numbers" {
assert_eq(tag_version("build-"), None)
assert_eq(tag_version("v1.2.3"), None)
assert_eq(tag_version("build-12x"), None)
assert_true(tag_version("build-10").unwrap() < tag_version("build-9000").unwrap())
assert_true(
tag_version("build-10").unwrap() < tag_version("build-9000").unwrap(),
)
}
///|
+1
View File
@@ -0,0 +1 @@
+23 -12
View File
@@ -25,7 +25,14 @@ pub(all) struct Handlers[M] {
///|
pub fn[M] Handlers::none() -> Handlers[M] {
{ down: None, tap: None, press: None, enter: None, escape: None, input: None }
{
down: None,
tap: None,
press: None,
enter: None,
escape: None,
input: None,
}
}
///|
@@ -48,7 +55,7 @@ pub(all) enum Node[M] {
pub(all) struct Element[M] {
tag : String
/// Identity among siblings for the keyed diff (0: none).
key : Int
key : Int32
classes : Array[String]
attrs : Array[(String, String)]
/// DOM properties (not attributes), e.g. an input's `value`.
@@ -62,15 +69,15 @@ pub(all) struct Element[M] {
/// An element builder: `el("div", classes=["a"], children=[...])`.
pub fn[M] el(
tag : String,
key? : Int = 0,
classes? : Array[String] = [],
attrs? : Array[(String, String)] = [],
props? : Array[(String, String)] = [],
style? : String = "",
handlers? : Handlers[M] = Handlers::none(),
children? : Array[Node[M]] = [],
key~ : Int32 = 0,
classes~ : Array[String] = [],
attrs~ : Array[(String, String)] = [],
props~ : Array[(String, String)] = [],
style~ : String = "",
handlers~ : Handlers[M] = Handlers::none(),
children~ : Array[Node[M]] = [],
) -> Node[M] {
El({ tag, key, classes, attrs, props, style, handlers, children })
El({ tag, key, classes, attrs, props, style, handlers, children, })
}
///|
@@ -81,7 +88,11 @@ pub fn[M] text(s : String) -> Node[M] {
///|
/// `cls("a", on=false)` is the empty class, so callers can build lists with `filter`.
pub fn cls_if(name : String, on : Bool) -> String {
if on { name } else { "" }
if on {
name
} else {
""
}
}
///|
@@ -126,7 +137,7 @@ fn[M] handler_names(h : Handlers[M]) -> String {
///|
/// Render a node as HTML text, one element per line (children indented), for tests.
/// Handlers show as an `on="tap press"` attribute.
pub fn[M] to_html(node : Node[M], indent? : Int = 0) -> String {
pub fn[M] to_html(node : Node[M], indent~ : Int32 = 0) -> String {
let pad = " ".repeat(indent)
match node {
Text(s) => pad + escape_html(s)
+2 -2
View File
@@ -1,9 +1,9 @@
///|
test "to_html" {
let n : Node[Int] = el(
let n : Node[Int32] = el(
"div",
classes=["a", cls_if("b", false), cls_if("c", true)],
handlers={ ..Handlers::none(), tap: Some(1) },
handlers={ ..Handlers::none(), tap: Some(1), },
children=[el("span", children=[text("x < y")]), text("tail")],
)
inspect(
+29 -18
View File
@@ -43,7 +43,12 @@ extern "js" fn dom_class(d : Dom, v : String) -> Unit =
///|
/// Put `d` into `parent` right before `before` (or last when `before` is not a node),
/// unless it is already there.
extern "js" fn dom_place(parent : Dom, d : Dom, before : Dom, has_before : Bool) -> Unit =
extern "js" fn dom_place(
parent : Dom,
d : Dom,
before : Dom,
has_before : Bool,
) -> Unit =
#|(p, d, b, has) => { const next = has ? b : null; if (d.parentNode !== p || d.nextSibling !== next) p.insertBefore(d, next); }
///|
@@ -102,7 +107,7 @@ extern "js" fn ev_touch_y(e : Ev) -> Double =
#|(e) => (e.changedTouches && e.changedTouches[0] ? e.changedTouches[0].clientY : 0)
///|
extern "js" fn ev_touches(e : Ev) -> Int =
extern "js" fn ev_touches(e : Ev) -> Int32 =
#|(e) => (e.touches ? e.touches.length : 0)
///|
@@ -111,7 +116,7 @@ extern "js" fn ev_chain(e : Ev) -> String =
#|(e) => { const out = []; for (let n = e.target; n && n.getAttribute; n = n.parentNode) { const v = n.getAttribute("data-n"); if (v !== null) out.push(v); } return out.join(","); }
///|
extern "js" fn set_timeout(ms : Int, f : () -> Unit) -> Unit =
extern "js" fn set_timeout(ms : Int32, f : () -> Unit) -> Unit =
#|(ms, f) => { setTimeout(f, ms) }
///|
@@ -154,7 +159,7 @@ extern "js" fn measure() -> Bool =
///|
/// Measurement i: viewport width, height, grid left, top, width, the home's bottom padding.
extern "js" fn measured(i : Int) -> Double =
extern "js" fn measured(i : Int32) -> Double =
#|(i) => window.__m[i]
///|
@@ -211,20 +216,20 @@ extern "js" fn toast(s : String) -> Unit =
///|
/// Snapshot the page's icon images; returns how many.
extern "js" fn icons_scan() -> Int =
extern "js" fn icons_scan() -> Int32 =
#|() => { window.__imgs = [...document.querySelectorAll("img.icon[data-icon]")]; return window.__imgs.length; }
///|
extern "js" fn icon_key(i : Int) -> String =
extern "js" fn icon_key(i : Int32) -> String =
#|(i) => window.__imgs[i].dataset.icon
///|
/// Whether image i already shows the icon for its key.
extern "js" fn icon_done(i : Int) -> Bool =
extern "js" fn icon_done(i : Int32) -> Bool =
#|(i) => window.__imgs[i].__icon === window.__imgs[i].dataset.icon
///|
extern "js" fn icon_set(i : Int, src : String) -> Unit =
extern "js" fn icon_set(i : Int32, src : String) -> Unit =
#|(i, src) => { const img = window.__imgs[i]; img.__icon = img.dataset.icon; if (src) { img.src = src; img.classList.remove("missing"); } else img.classList.add("missing"); }
///|
@@ -255,7 +260,7 @@ extern "js" fn h_add_widget(p : String) -> Unit =
#|(p) => window.Android.addWidget(p)
///|
extern "js" fn h_remove_widget(id : Int) -> Unit =
extern "js" fn h_remove_widget(id : Int32) -> Unit =
#|(id) => window.Android.removeWidget(id)
///|
@@ -263,7 +268,7 @@ extern "js" fn h_place_widgets(json : String) -> Unit =
#|(j) => window.Android.placeWidgets(j)
///|
extern "js" fn h_cover_widgets(y : Int) -> Unit =
extern "js" fn h_cover_widgets(y : Int32) -> Unit =
#|(y) => window.Android.coverWidgets(y)
///|
@@ -271,7 +276,7 @@ extern "js" fn h_exclude_gestures(json : String) -> Unit =
#|(j) => window.Android.excludeGestures && window.Android.excludeGestures(j)
///|
extern "js" fn h_widget_limits(id : Int) -> String =
extern "js" fn h_widget_limits(id : Int32) -> String =
#|(id) => window.Android.widgetLimits(id)
///|
@@ -307,19 +312,19 @@ extern "js" fn h_open_recents() -> Unit =
#|() => window.Android.openRecents()
///|
extern "js" fn h_http_get(url : String, tag : Int) -> Unit =
extern "js" fn h_http_get(url : String, tag : Int32) -> Unit =
#|(url, tag) => window.Android.httpGet(url, tag)
///|
extern "js" fn h_install_apk(url : String, version : Int) -> Unit =
extern "js" fn h_install_apk(url : String, version : Int32) -> Unit =
#|(url, v) => window.Android.installApk(url, v)
///|
extern "js" fn h_declined_version() -> Int =
extern "js" fn h_declined_version() -> Int32 =
#|() => window.Android.declinedVersion()
///|
extern "js" fn h_installed_version() -> Int =
extern "js" fn h_installed_version() -> Int32 =
#|() => window.Android.installedVersion()
// ---- what the shell calls on the page -----------------------------------------------
@@ -333,7 +338,7 @@ extern "js" fn expose0(name : String, f : () -> Unit) -> Unit =
#|(n, f) => { window.launcher[n] = f }
///|
extern "js" fn expose1(name : String, f : (Int) -> Unit) -> Unit =
extern "js" fn expose1(name : String, f : (Int32) -> Unit) -> Unit =
#|(n, f) => { window.launcher[n] = f }
///|
@@ -346,7 +351,10 @@ extern "js" fn expose_dd(name : String, f : (Double, Double) -> Unit) -> Unit =
///|
/// `f(tag, ok, text)`: a finished `httpGet`.
extern "js" fn expose_result(name : String, f : (Int, Bool, String) -> Unit) -> Unit =
extern "js" fn expose_result(
name : String,
f : (Int32, Bool, String) -> Unit,
) -> Unit =
#|(n, f) => { window.launcher[n] = f }
///|
@@ -356,7 +364,10 @@ extern "js" fn expose_json(name : String, f : (String) -> Unit) -> Unit =
///|
/// Run `f` for each `key\nsrc` pair of a JSON object (flattened, so no arrays cross).
extern "js" fn json_entries(json : String, f : (String, String) -> Unit) -> Unit =
extern "js" fn json_entries(
json : String,
f : (String, String) -> Unit,
) -> Unit =
#|(j, f) => { const o = JSON.parse(j); for (const k in o) f(k, o[k] ?? "") }
///|
+57 -22
View File
@@ -19,17 +19,17 @@ priv struct PageState {
mut focus_pending : Bool
mut placed : String
mut excluded : String
mut cover_y : Int
mut cover_y : Int32
mut cover_last : Double
mut cover_loop : Bool
mut measured : String
mut touch : (Double, Double, Double)?
mut demo_widget : Int
mut http_tag : Int
http : Map[Int, (Bool, String) -> Unit]
mut demo_widget : Int32
mut http_tag : Int32
http : Map[Int32, (Bool, String) -> Unit]
icon_src : Map[String, String]
icon_asked : Map[String, Bool]
icon_tries : Map[String, Int]
icon_tries : Map[String, Int32]
}
///|
@@ -100,8 +100,18 @@ fn exec(e : @app.Effect) -> Unit {
let android = is_android()
match e {
Launch(c) => if android { h_launch(c) } else { toast("Open " + c) }
AppInfo(c) => if android { h_app_info(c) } else { toast("App info for " + c) }
Uninstall(c) => if android { h_uninstall(c) } else { toast("Uninstall " + c) }
AppInfo(c) =>
if android {
h_app_info(c)
} else {
toast("App info for " + c)
}
Uninstall(c) =>
if android {
h_uninstall(c)
} else {
toast("Uninstall " + c)
}
AddWidget(p) =>
if android {
h_add_widget(p)
@@ -111,9 +121,24 @@ fn exec(e : @app.Effect) -> Unit {
set_timeout(0, fn() { dispatch(WidgetAdded(id)) })
}
RemoveWidget(id) => if android { h_remove_widget(id) }
OpenSettings => if android { h_open_settings() } else { toast("Open system settings") }
PickWallpaper => if android { h_pick_wallpaper() } else { toast("Pick a wallpaper") }
OpenRecents => if android { h_open_recents() } else { toast("Show open windows") }
OpenSettings =>
if android {
h_open_settings()
} else {
toast("Open system settings")
}
PickWallpaper =>
if android {
h_pick_wallpaper()
} else {
toast("Pick a wallpaper")
}
OpenRecents =>
if android {
h_open_recents()
} else {
toast("Show open windows")
}
Haptic => h_haptic()
LoadApps =>
fetch_text("apps.json", fn(ok, text) {
@@ -149,7 +174,11 @@ fn exec(e : @app.Effect) -> Unit {
dispatch(VersionFetched(if ok { Some(text) } else { None }))
})
InstallApk(url, n) =>
if android { h_install_apk(url, n) } else { toast("Install update \{n}") }
if android {
h_install_apk(url, n)
} else {
toast("Install update \{n}")
}
FocusSearch => state.val.focus_pending = true
HideKeyboard => {
blur_active()
@@ -309,17 +338,13 @@ fn got_icons(json : String) -> Unit {
// ---- input -------------------------------------------------------------------------
///|
fn parse_chain(s : String) -> Array[Int] {
fn parse_chain(s : String) -> Array[Int32] {
if s == "" {
return []
}
let out : Array[Int] = []
let out : Array[Int32] = []
for part in s.split(",") {
out.push(
try @string.parse_int(part) catch {
_ => -1
},
)
out.push(@string.parse_int(part) catch { _ => -1 })
}
out
}
@@ -342,10 +367,16 @@ fn wire_events() -> Unit {
listen("document", "pointerup", true, fn(e) { feed(Up(x=ev_x(e), y=ev_y(e))) })
listen("document", "pointercancel", true, fn(_) { feed(Cancel) })
// keep the page from scrolling under a lifted slot or a handle being dragged
listen("document", "touchmove", false, fn(e) { if is_dragging() { ev_prevent(e) } })
listen("document", "touchmove", false, fn(e) {
if is_dragging() {
ev_prevent(e)
}
})
listen("document", "contextmenu", false, fn(e) { ev_prevent(e) })
listen("document", "input", true, fn(e) {
run(@app.typed(model, state.val.table, parse_chain(ev_chain(e)), ev_value(e)))
run(
@app.typed(model, state.val.table, parse_chain(ev_chain(e)), ev_value(e)),
)
})
listen("document", "keydown", true, fn(e) {
if ev_composing(e) {
@@ -428,7 +459,7 @@ fn num(key : String) -> Int64 {
if s == "" {
0L
} else {
try @string.parse_int64(s) catch {
@string.parse_int64(s) catch {
_ => 0L
}
}
@@ -441,7 +472,11 @@ fn main {
}
expose_api()
wire_events()
let saved = if storage_has("launcher.home") { Some(storage_get("launcher.home")) } else { None }
let saved = if storage_has("launcher.home") {
Some(storage_get("launcher.home"))
} else {
None
}
let legacy = if saved is None { Some(storage_legacy()) } else { None }
dispatch(Restore(saved~, legacy~))
if is_android() {
+1 -3
View File
@@ -6,8 +6,6 @@ import {
"moonbitlang/core/string",
}
options(
is_main: true,
)
pkgtype(kind: "executable")
supported_targets = "js"
+9 -5
View File
@@ -9,9 +9,9 @@ priv struct RNode {
dom : Dom
is_text : Bool
tag : String
key : Int
key : Int32
mut text : String
mut n : Int
mut n : Int32
mut classes : String
mut attrs : Map[String, String]
mut props : Map[String, String]
@@ -54,7 +54,11 @@ fn new_rnode(n : @vdom.Node[@app.Msg]) -> RNode {
}
///|
fn update_rnode(r : RNode, n : @vdom.Node[@app.Msg], counter : Ref[Int]) -> Unit {
fn update_rnode(
r : RNode,
n : @vdom.Node[@app.Msg],
counter : Ref[Int32],
) -> Unit {
match n {
Text(s) =>
if s != r.text {
@@ -127,10 +131,10 @@ fn patch_children(
parent : Dom,
old : Array[RNode],
new : Array[@vdom.Node[@app.Msg]],
counter : Ref[Int],
counter : Ref[Int32],
) -> Array[RNode] {
let used : Array[Bool] = Array::make(old.length(), false)
let by_key : Map[Int, Int] = {}
let by_key : Map[Int32, Int32] = {}
for i in 0..<old.length() {
if old[i].key != 0 {
by_key[old[i].key] = i