From aac59a5bf640efd0eef172b6ec89fabe69a2edb0 Mon Sep 17 00:00:00 2001 From: Waozi Date: Mon, 26 Oct 2026 23:18:16 -0300 Subject: [PATCH] Move shared leaderboard into Profile with installed game rankings --- README.md | 19 ++ scripts/leaderboard-test.py | 28 +++ src/entity.zi | 10 + src/leaderboard_model.zi | 138 ++++++++++++ src/leaderboard_native.zi | 405 ++++++++++++++++++++++++++++++++++++ src/leaderboard_view.zi | 216 +++++++++++++++++++ src/native_host.zi | 9 +- tests/leaderboard_test.zi | 67 ++++++ ziran.toml | 2 + 9 files changed, 893 insertions(+), 1 deletion(-) create mode 100644 scripts/leaderboard-test.py create mode 100644 src/leaderboard_model.zi create mode 100644 src/leaderboard_native.zi create mode 100644 src/leaderboard_view.zi create mode 100644 tests/leaderboard_test.zi diff --git a/README.md b/README.md index 2e485c8..4803730 100644 --- a/README.md +++ b/README.md @@ -165,3 +165,22 @@ and reusable record keys stay on the device. The node retains earned unlocks and completion marks separately from new route evidence. Migration never credits Dew, and normal claims remain once per account. Missing snapshots and connection failures remain visible failures rather than successful claims. + +## Shared leaderboard + +Leaderboard lives inside Profile. Hosts provide `entity.leaderboard` with a +bounded `ProfileLeaderboard` snapshot from `entity/leaderboard_model`: installed +boards, the selected board, and ranked friend rows. Selection requests carry +the snapshot's owner, a listed board ID and metric. A host rejects stale owners +and boards it no longer has installed. The `leaderboard` command opens the page; +Back returns to Profile. Labels use the host's existing leaderboard translations. + +Native game hosts use `entity/leaderboard_native`. Forward a game's `leaderboard` +score report to `EntityLeaderboardReport` with its verified identity and title, +and supply `leaderboard_installed` to check current installed membership. +Profile keeps scores separately for each account, publishes the installed +games' reported totals through the existing friend-statistics API, and fetches +rankings asynchronously in `EntityLeaderboardPump` (part of `EntityHostPump`). +Uninstalling hides a retained score immediately. Account changes cancel old +requests and clear old friend rows. No game gets another game's records or keys. +`python3 scripts/leaderboard-test.py` tests these boundaries locally. diff --git a/scripts/leaderboard-test.py b/scripts/leaderboard-test.py new file mode 100644 index 0000000..018d016 --- /dev/null +++ b/scripts/leaderboard-test.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Bounded native tests of installed boards and account-isolated scores.""" +import os +from pathlib import Path +import shutil +import subprocess + +root = Path(__file__).resolve().parents[1] +output = root / 'build/leaderboard-test' +output.mkdir(parents=True, exist_ok=True) +shutil.rmtree(output / 'profile', ignore_errors=True) +env = dict(os.environ) +for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS'): + env.pop(key, None) +env['YUE_DESKTOP_RECOVERY'] = '0' +env['ENTITY_LEADERBOARD_TEST_DATA'] = str(output / 'profile') +ziran = str(root / 'scripts/ziran.sh') +subprocess.run([ziran, 'build', '--project', '--target=c', '--entry', 'leaderboard_test:main', + '-o', str(output / 'c'), 'tests/leaderboard_test.zi'], cwd=root, env=env, check=True) +toolchain = Path(subprocess.check_output([ziran, 'pkg', 'path', 'ziran'], cwd=root, text=True).strip()) +command = ['cc', '-std=c11', '-O1', '-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections', + '-I' + str(toolchain / 'include')] +command += ['-iquote' + str(path) for path in (output / 'c').rglob('*') if path.is_dir()] +command += [str(path) for path in (output / 'c').rglob('*.c')] +command += ['-l:libcurl.so.4', '-lm', '-lpthread', '-o', str(output / 'test')] +subprocess.run(command, cwd=root, env=env, check=True) +subprocess.run([str(output / 'test')], cwd=root, env=env, check=True) +print('PASS: installed-only boards, retained scores, account changes, validation and display encoding') diff --git a/src/entity.zi b/src/entity.zi index ea9812b..e12dc1c 100644 --- a/src/entity.zi +++ b/src/entity.zi @@ -2,6 +2,8 @@ // interface; extension replies name only routes supplied by that host. #import "model" #import "achievement_view" +#import "leaderboard_view" +#import "leaderboard_model" #import "management" #import "dew_model" #import "dew_view" @@ -872,6 +874,7 @@ Draw :: () { loaded = true dew_refresh = true } + if ProfileLeaderboardFrame(!state.host_navigation) { return } if AchievementViewFrame(!state.host_navigation) { return } if dew_page { DrawDew(); return } if management_page != 0 { DrawAccount(); return } @@ -942,6 +945,12 @@ Draw :: () { if (state.controls & ENTITY_NODES) != 0 && ListRow(704, Label("entity.nodes", "Nodes"), NodesSummary(), x, *y, width) { OpenManagement(PAGE_NODES) } + if AppSupports(LEADERBOARD_SERVICE) { + if Action(550, Label("leaderboard_title", "Leaderboard"), Rectangle.{x, y, width, 48.0 * scale}) && Save() { + unused ProfileLeaderboardCommand("leaderboard") + } + y += 60.0 * scale + } ExtensionRows(x, *y, width) if notice != "" { Text(session, TextProps.{.key = cast(u64)22, .text = notice, @@ -1004,6 +1013,7 @@ Main :: () -> s64 { AppReply("handled") return 0 } + if mode == APP_COMMAND && ProfileLeaderboardCommand(AppCommand()) { return 0 } if mode == APP_COMMAND && AchievementCommand(AppCommand()) { return 0 } if mode == APP_FRAME { Draw() } if mode == APP_COMMAND && AppCommand() == "reload" { diff --git a/src/leaderboard_model.zi b/src/leaderboard_model.zi new file mode 100644 index 0000000..194981d --- /dev/null +++ b/src/leaderboard_model.zi @@ -0,0 +1,138 @@ +// A bounded, account-scoped view of boards from the host's installed apps. +// The profile receives display data and selections, never account keys. +#import "std/json_scan" +#import "std/c_string" +#import "std/text_buffer" +#import "std/vec" +#import "model" + +LEADERBOARD_SERVICE :: "entity.leaderboard" +LEADERBOARD_BOARDS :: 32 +LEADERBOARD_ROWS :: 64 + +ProfileBoard :: struct { + app: [97]u8 + app_title: [129]u8 + id: [65]u8 + title: [129]u8 + primary: [65]u8 + average: [65]u8 +} + +ProfileRank :: struct { + name: [129]u8 + value: [49]u8 + average: [49]u8 + own: bool +} + +ProfileLeaderboard :: struct { + owner: [97]u8 + boards: [LEADERBOARD_BOARDS]ProfileBoard + board_count: s32 + selected: s32 + metric: s32 + rows: [LEADERBOARD_ROWS]ProfileRank + row_count: s32 + loading: bool + error: bool +} + +ProfileBoardFind :: (page: *ProfileLeaderboard, id: string) -> s32 { + for index: cast(s32)0..page.board_count - 1 { + if TextUntilNul(page.boards[index].id[:]) == id { return index } + } + return -1 +} + +ProfileLeaderboardEncode :: (page: *ProfileLeaderboard) -> string { + out: Vec(u8) + BuilderPrint(*out, "{\"version\":1,\"owner\":") + EntityQuote(*out, TextUntilNul(page.owner[:])) + BuilderPrint(*out, ",\"selected\":%,\"metric\":%,\"loading\":%,\"error\":%,\"boards\":[", + page.selected, page.metric, ifx page.loading then 1 else 0, ifx page.error then 1 else 0) + for index: cast(s32)0..page.board_count - 1 { + board := *page.boards[index] + BuilderPrint(*out, "%{", ifx index > 0 then "," else "") + keys: [6]string = .["app", "app_title", "id", "title", "primary", "average"] + values: [6]string = .[TextUntilNul(board.app[:]), TextUntilNul(board.app_title[:]), + TextUntilNul(board.id[:]), TextUntilNul(board.title[:]), TextUntilNul(board.primary[:]), TextUntilNul(board.average[:])] + for field: cast(s32)0..5 { + BuilderPrint(*out, "%\"%\":", ifx field > 0 then "," else "", keys[field]) + EntityQuote(*out, values[field]) + } + BuilderPrint(*out, "}") + } + BuilderPrint(*out, "],\"rows\":[") + for index: cast(s32)0..page.row_count - 1 { + row := *page.rows[index] + BuilderPrint(*out, "%{\"name\":", ifx index > 0 then "," else "") + EntityQuote(*out, TextUntilNul(row.name[:])) + BuilderPrint(*out, ",\"value\":") + EntityQuote(*out, TextUntilNul(row.value[:])) + BuilderPrint(*out, ",\"average\":") + EntityQuote(*out, TextUntilNul(row.average[:])) + BuilderPrint(*out, ",\"own\":%}", ifx row.own then 1 else 0) + } + BuilderPrint(*out, "]}") + return BuilderFinish(out) +} + +ProfileLeaderboardDecode :: (document: string, output: *ProfileLeaderboard) -> bool { + if document.count < 2 || document.count >= 65536 { return false } + start := Space(document, 0) + if start >= document.count || document[start] != #char "{" { return false } + end := ValueEnd(document, start, 0) + if end < 0 || Space(document, end) != document.count { return false } + next: ProfileLeaderboard + version := ReadNumber(document, FieldAt(document, start, "version")) + if !version.valid || version.value != 1 || + ReadStringText(document, FieldAt(document, start, "owner"), next.owner[:]) < 1 { return false } + keys: [4]string = .["selected", "metric", "loading", "error"] + values: [4]s32 + for index: cast(s32)0..3 { + number := ReadNumber(document, FieldAt(document, start, keys[index])) + if !number.valid || number.value < -1 || number.value > LEADERBOARD_BOARDS || + number.value != cast(float64)cast(s32)number.value { return false } + values[index] = cast(s32)number.value + } + if values[1] < 0 || values[1] > 1 || values[2] < 0 || values[2] > 1 || values[3] < 0 || values[3] > 1 { return false } + next.selected = values[0] + next.metric = values[1] + next.loading = values[2] == 1 + next.error = values[3] == 1 + at := FieldAt(document, start, "boards") + next.board_count = ArrayCount(document, at) + if next.board_count < 0 || next.board_count > LEADERBOARD_BOARDS { return false } + if (next.board_count == 0 && next.selected != -1) || + (next.board_count > 0 && (next.selected < 0 || next.selected >= next.board_count)) { return false } + for index: cast(s32)0..next.board_count - 1 { + board := *next.boards[index] + item := ElementAt(document, at, index) + if ReadStringText(document, FieldAt(document, item, "app"), board.app[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "app_title"), board.app_title[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "id"), board.id[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "title"), board.title[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "primary"), board.primary[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "average"), board.average[:]) < 0 { return false } + for prior: cast(s32)0..index - 1 { + if TextUntilNul(next.boards[prior].id[:]) == TextUntilNul(board.id[:]) { return false } + } + } + at = FieldAt(document, start, "rows") + next.row_count = ArrayCount(document, at) + if next.row_count < 0 || next.row_count > LEADERBOARD_ROWS || + (next.board_count == 0 && next.row_count != 0) { return false } + for index: cast(s32)0..next.row_count - 1 { + row := *next.rows[index] + item := ElementAt(document, at, index) + if ReadStringText(document, FieldAt(document, item, "name"), row.name[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "value"), row.value[:]) < 0 || + ReadStringText(document, FieldAt(document, item, "average"), row.average[:]) < 0 { return false } + own := ReadNumber(document, FieldAt(document, item, "own")) + if !own.valid || (own.value != 0 && own.value != 1) { return false } + row.own = own.value == 1 + } + output.* = next + return true +} diff --git a/src/leaderboard_native.zi b/src/leaderboard_native.zi new file mode 100644 index 0000000..08a085b --- /dev/null +++ b/src/leaderboard_native.zi @@ -0,0 +1,405 @@ +// Game reports are accepted only with a verified host-supplied identity. +// Installed membership stays with the host; retained scores never install apps. +#import "leaderboard_model" +#import "account_store" +#import "recovery" +#import "daochi_client/keys" +#import "native_files" +#import "std/number_text" +#import "std/date_time_linux" +#import "std/net_http" +#import "std/json_scan" +#import "std/c_string" +#import "std/text_buffer" +#import "std/vec" +#import "model" +#import "daochi_client/client" +#import "daochi_client/async_client" +#import "daochi_client/social" +Auth :: #import "daochi_client/auth"; +#import "kryon/http_transfer" + +LeaderboardInstalled :: #type (game: string) -> bool; +leaderboard_installed: LeaderboardInstalled; +leaderboard_transport: AsyncTransport; + +NativeGameScore :: struct { + board: ProfileBoard + value: s64 +} + +native_scores: [LEADERBOARD_BOARDS]NativeGameScore; +native_score_count: s32; +native_leaderboard_owner: [97]u8; +native_leaderboard_page: ProfileLeaderboard; +native_leaderboard_selected: [65]u8; +native_leaderboard_requested: bool; +native_leaderboard_loaded: bool; +native_leaderboard_error: bool; +native_leaderboard_stage: s32; +native_leaderboard_pending: PendingRequest; +native_leaderboard_session: Auth.Session; +native_leaderboard_transfer: HttpTransfer; +native_leaderboard_response: [16384]u8; +native_leaderboard_stats: [16384]u8; +native_leaderboard_friends: [16384]u8; +native_leaderboard_body: string; +native_leaderboard_path: [768]u8; +native_leaderboard_answer: string; +native_leaderboard_rows: [LEADERBOARD_ROWS]ProfileRank; +native_leaderboard_row_count: s32; +native_leaderboard_rows_dirty: bool = true; + +LeaderboardNameValid :: (name: string, maximum: s64) -> bool { + if name.count == 0 || name.count > maximum { return false } + for byte: name { + if !((byte >= #char "a" && byte <= #char "z") || (byte >= #char "A" && byte <= #char "Z") || + (byte >= #char "0" && byte <= #char "9") || byte == #char "." || byte == #char "_" || byte == #char ":" || byte == #char "-") { return false } + } + return true +} + +NativeLeaderboardFile :: (output: []u8) -> string { + directory: [4096]u8 + root := AccountStorePath("leaderboards", directory[:]) + if !NativeDirectory(root) { return "" } + return NativeJoin(output, root, TextUntilNul(native_leaderboard_owner[:])) +} + +NativeLeaderboardSave :: () -> bool { + out: Vec(u8) + BuilderPrint(*out, "{\"scores\":[") + for index: cast(s32)0..native_score_count - 1 { + score := *native_scores[index] + BuilderPrint(*out, "%{\"app\":", ifx index > 0 then "," else "") + EntityQuote(*out, TextUntilNul(score.board.app[:])) + BuilderPrint(*out, ",\"app_title\":") + EntityQuote(*out, TextUntilNul(score.board.app_title[:])) + BuilderPrint(*out, ",\"id\":") + EntityQuote(*out, TextUntilNul(score.board.id[:])) + BuilderPrint(*out, ",\"title\":") + EntityQuote(*out, TextUntilNul(score.board.title[:])) + BuilderPrint(*out, ",\"value\":%}", score.value) + } + BuilderPrint(*out, "]}") + document := BuilderFinish(out) + defer { EntityFree(document) } + path: [4096]u8 + name := NativeLeaderboardFile(path[:]) + return name != "" && NativeWrite(name, document) +} + +NativeLeaderboardOwner :: () { + owner := TextUntilNul(account_recovery.keys.public_id[:]) + if owner == "" { owner = "local" } + if owner == TextUntilNul(native_leaderboard_owner[:]) { return } + CancelRequest(*native_leaderboard_pending) + HttpTransferCancel(*native_leaderboard_transfer) + native_leaderboard_session = .{} + unused CopyCString(owner, native_leaderboard_owner[:]) + native_score_count = 0 + native_scores = .{} + native_leaderboard_page = .{} + native_leaderboard_selected = .{} + native_leaderboard_stage = 0 + native_leaderboard_loaded = false + native_leaderboard_requested = false + native_leaderboard_error = false + native_leaderboard_stats = .{} + native_leaderboard_friends = .{} + native_leaderboard_rows = .{} + native_leaderboard_row_count = 0 + native_leaderboard_rows_dirty = true + path: [4096]u8 + name := NativeLeaderboardFile(path[:]) + if name == "" { return } + buffer: [32768]u8 + if NativeRead(name, buffer[:]) < 1 { return } + document := TextUntilNul(buffer[:]) + at := FieldAt(document, 0, "scores") + count := ArrayCount(document, at) + if count < 0 || count > LEADERBOARD_BOARDS { return } + for index: cast(s32)0..count - 1 { + score: NativeGameScore + item := ElementAt(document, at, index) + value := ReadNumber(document, FieldAt(document, item, "value")) + if ReadStringText(document, FieldAt(document, item, "app"), score.board.app[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "app_title"), score.board.app_title[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "id"), score.board.id[:]) < 1 || + ReadStringText(document, FieldAt(document, item, "title"), score.board.title[:]) < 1 || + !LeaderboardNameValid(TextUntilNul(score.board.id[:]), 31) || + !value.valid || value.value < 0 || value.value > 100000 || value.value != cast(float64)cast(s64)value.value { continue } + score.value = cast(s64)value.value + unused CopyCString("Levels solved", score.board.primary[:]) + native_scores[native_score_count] = score + native_score_count += 1 + } +} + +EntityLeaderboardReport :: (app: string, app_title: string, game: string, title: string, request: string) -> bool { + if !LeaderboardNameValid(app, 96) || !LeaderboardNameValid(game, 31) || + request.count < 8 || request[:7] != "levels " { return false } + value: s64 = 0 + for byte: request[7:] { + if byte < #char "0" || byte > #char "9" || value > 100000 { return false } + value = value * 10 + cast(s64)(byte - #char "0") + } + if value > 100000 { return false } + NativeLeaderboardOwner() + index: s32 = -1 + for item: cast(s32)0..native_score_count - 1 { + if TextUntilNul(native_scores[item].board.id[:]) == game { index = item } + } + if index < 0 { + if native_score_count >= LEADERBOARD_BOARDS { return false } + index = native_score_count + native_score_count += 1 + } + score := *native_scores[index] + if TextUntilNul(score.board.id[:]) == game && score.value == value && + TextUntilNul(score.board.title[:]) == title { return true } + score.value = value + unused CopyCString(app, score.board.app[:]) + unused CopyCString(app_title, score.board.app_title[:]) + unused CopyCString(game, score.board.id[:]) + unused CopyCString(ifx title == "" then game else title, score.board.title[:]) + unused CopyCString("Levels solved", score.board.primary[:]) + native_leaderboard_loaded = false + native_leaderboard_rows_dirty = true + return NativeLeaderboardSave() +} + +NativeLeaderboardStart :: (context: *void, request: HttpRequest, output: []u8) -> bool { + return HttpTransferStart(*native_leaderboard_transfer, request, output, 15000) +} +NativeLeaderboardPoll :: (context: *void, status: *s32) -> s32 { return HttpTransferPoll(*native_leaderboard_transfer, status) } +NativeLeaderboardCancel :: (context: *void) { HttpTransferCancel(*native_leaderboard_transfer) } + +NativeLeaderboardRow :: (document: string, at: s32, value: s64, own: bool) { + page := *native_leaderboard_page + if page.row_count >= LEADERBOARD_ROWS { return } + alias: [49]u8 + id: [97]u8 + unused ReadStringText(document, FieldAt(document, at, "alias"), alias[:]) + unused ReadStringText(document, FieldAt(document, at, "user_id_hash"), id[:]) + if id[0] == cast(u8)0 { unused ReadStringText(document, FieldAt(document, at, "id"), id[:]) } + row := *page.rows[page.row_count] + display: Vec(u8) + if alias[0] != cast(u8)0 { BuilderPrint(*display, "@%", TextUntilNul(alias[:])) } + else { + public_id := TextUntilNul(id[:]) + BuilderPrint(*display, "%", ifx public_id.count > 12 then public_id[:12] else public_id) + } + text := BuilderFinish(display) + unused CopyCString(text, row.name[:]) + EntityFree(text) + digits: [24]u8 + unused CopyCString(FormatInteger(value, digits[:]), row.value[:]) + row.own = own + page.row_count += 1 +} + +NativeLeaderboardRows :: () { + page := *native_leaderboard_page + if page.selected < 0 || TextUntilNul(page.owner[:]) == "local" { return } + if !native_leaderboard_rows_dirty { + page.rows = native_leaderboard_rows + page.row_count = native_leaderboard_row_count + return + } + selected := TextUntilNul(page.boards[page.selected].id[:]) + own: s64 = 0 + for index: cast(s32)0..native_score_count - 1 { + if TextUntilNul(native_scores[index].board.id[:]) == selected { own = native_scores[index].value } + } + stats := TextUntilNul(native_leaderboard_stats[:]) + ids: [LEADERBOARD_ROWS][97]u8 + at := FieldAt(stats, 0, "rows") + count := ArrayCount(stats, at) + for index: cast(s32)0..count - 1 { + if page.row_count >= LEADERBOARD_ROWS - 1 { break } + item := ElementAt(stats, at, index) + id: [97]u8 + unused ReadStringText(stats, FieldAt(stats, item, "user_id_hash"), id[:]) + if id[0] == cast(u8)0 || TextUntilNul(id[:]) == TextUntilNul(page.owner[:]) { continue } + duplicate := false + for prior: cast(s32)0..page.row_count - 1 { + if TextUntilNul(ids[prior][:]) == TextUntilNul(id[:]) { duplicate = true } + } + value := ReadNumber(stats, FieldAt(stats, item, "value")) + if duplicate || !value.valid || value.value < 0 || value.value > 100000 { continue } + ids[page.row_count] = id + NativeLeaderboardRow(stats, item, cast(s64)value.value, false) + } + friends := TextUntilNul(native_leaderboard_friends[:]) + at = FieldAt(friends, 0, "friends") + count = ArrayCount(friends, at) + for index: cast(s32)0..count - 1 { + if page.row_count >= LEADERBOARD_ROWS - 1 { break } + item := ElementAt(friends, at, index) + id: [97]u8 + unused ReadStringText(friends, FieldAt(friends, item, "user_id_hash"), id[:]) + if id[0] == cast(u8)0 { unused ReadStringText(friends, FieldAt(friends, item, "id"), id[:]) } + if id[0] == cast(u8)0 || TextUntilNul(id[:]) == TextUntilNul(page.owner[:]) { continue } + duplicate := false + for prior: cast(s32)0..page.row_count - 1 { + if TextUntilNul(ids[prior][:]) == TextUntilNul(id[:]) { duplicate = true } + } + if duplicate { continue } + ids[page.row_count] = id + NativeLeaderboardRow(friends, item, 0, false) + } + row := *page.rows[page.row_count] + alias := TextUntilNul(account_alias[:]) + display: Vec(u8) + if alias != "" { BuilderPrint(*display, "@%", alias) } + else { + id := TextUntilNul(page.owner[:]) + BuilderPrint(*display, "%", ifx id.count > 12 then id[:12] else id) + } + text := BuilderFinish(display) + unused CopyCString(text, row.name[:]) + EntityFree(text) + digits: [24]u8 + unused CopyCString(FormatInteger(own, digits[:]), row.value[:]) + row.own = true + page.row_count += 1 + for index: cast(s32)1..page.row_count - 1 { + current := page.rows[index] + value := ReadNumber(TextUntilNul(current.value[:]), 0) + position := index + while position > 0 { + prior := *page.rows[position - 1] + other := ReadNumber(TextUntilNul(prior.value[:]), 0) + if other.value >= value.value { break } + page.rows[position] = prior.* + position -= 1 + } + page.rows[position] = current + } + native_leaderboard_rows = page.rows + native_leaderboard_row_count = page.row_count + native_leaderboard_rows_dirty = false +} + +EntityLeaderboardAnswer :: (request: string) -> string { + NativeLeaderboardOwner() + page := *native_leaderboard_page + page.* = .{} + page.owner = native_leaderboard_owner + for index: cast(s32)0..native_score_count - 1 { + score := *native_scores[index] + if leaderboard_installed == null || !leaderboard_installed(TextUntilNul(score.board.id[:])) { continue } + page.boards[page.board_count] = score.board + page.board_count += 1 + } + page.selected = ProfileBoardFind(page, TextUntilNul(native_leaderboard_selected[:])) + if page.selected < 0 && page.board_count > 0 { page.selected = 0 } + owner: [97]u8 + board: [65]u8 + if request == "refresh" { native_leaderboard_loaded = false } + if ReadStringText(request, FieldAt(request, 0, "owner"), owner[:]) > 0 && + TextUntilNul(owner[:]) == TextUntilNul(page.owner[:]) && + ReadStringText(request, FieldAt(request, 0, "board"), board[:]) > 0 { + chosen := ProfileBoardFind(page, TextUntilNul(board[:])) + if chosen >= 0 { page.selected = chosen } + } + if page.selected >= 0 { + chosen := page.boards[page.selected].id + if TextUntilNul(chosen[:]) != TextUntilNul(native_leaderboard_selected[:]) { + CancelRequest(*native_leaderboard_pending) + native_leaderboard_stage = 0 + native_leaderboard_selected = chosen + native_leaderboard_stats = .{} + native_leaderboard_loaded = false + native_leaderboard_rows_dirty = true + } + if !native_leaderboard_loaded && native_leaderboard_stage == 0 && TextUntilNul(page.owner[:]) != "local" { + native_leaderboard_requested = true + } + NativeLeaderboardRows() + } else { + CancelRequest(*native_leaderboard_pending) + native_leaderboard_stage = 0 + native_leaderboard_requested = false + native_leaderboard_selected = .{} + native_leaderboard_stats = .{} + } + page.loading = native_leaderboard_requested || native_leaderboard_stage != 0 + page.error = native_leaderboard_error + EntityFree(native_leaderboard_answer) + native_leaderboard_answer = ProfileLeaderboardEncode(page) + return native_leaderboard_answer +} + +EntityLeaderboardPump :: () { + NativeLeaderboardOwner() + if native_leaderboard_stage != 0 { + if !PollRequest(*native_leaderboard_pending) { return } + valid := native_leaderboard_pending.result == cast(Auth.AuthResult)Auth.AuthResult.AUTH_OK && native_leaderboard_pending.status == 200 + native_leaderboard_error = native_leaderboard_error || !valid + if native_leaderboard_stage == 2 && valid { native_leaderboard_friends = native_leaderboard_response } + if native_leaderboard_stage == 3 { + if valid { native_leaderboard_stats = native_leaderboard_response } + native_leaderboard_rows_dirty = true + native_leaderboard_stage = 0 + native_leaderboard_loaded = true + return + } + native_leaderboard_stage += 1 + } else { + if !native_leaderboard_requested { return } + native_leaderboard_requested = false + native_leaderboard_error = false + native_leaderboard_stage = 1 + } + client: Client + if !AccountStoreClient(null, *client) { + native_leaderboard_stage = 0 + native_leaderboard_loaded = true + native_leaderboard_error = true + return + } + EntityFree(native_leaderboard_body) + native_leaderboard_body = "" + path: string + if native_leaderboard_stage == 1 { + now := LocalNow() + date := now.year * 10000 + now.month * 100 + now.day + out: Vec(u8) + BuilderPrint(*out, "{\"app\":\"inbe\",\"metrics\":[") + count: s32 = 0 + for index: cast(s32)0..native_score_count - 1 { + score := *native_scores[index] + if leaderboard_installed == null || !leaderboard_installed(TextUntilNul(score.board.id[:])) { continue } + BuilderPrint(*out, "%{\"practice\":\"%\",\"metric\":\"levels\",\"value\":%,\"label\":\"%\",\"local_date\":%}", + ifx count > 0 then "," else "", TextUntilNul(score.board.id[:]), score.value, score.value, date) + count += 1 + } + BuilderPrint(*out, "]}") + native_leaderboard_body = BuilderFinish(out) + path = "/api/v1/profile/stats" + } else if native_leaderboard_stage == 2 { + path = "/api/v1/friends" + } else { + if !BuildFriendStatsPath("inbe", TextUntilNul(native_leaderboard_selected[:]), "levels", native_leaderboard_path[:]) { + native_leaderboard_stage = 0 + native_leaderboard_loaded = true + native_leaderboard_error = true + return + } + path = TextUntilNul(native_leaderboard_path[:]) + } + headers: [0]HttpHeader + transport := leaderboard_transport + if transport.start == null { + transport = AsyncTransport.{.start = NativeLeaderboardStart, .poll = NativeLeaderboardPoll, .cancel = NativeLeaderboardCancel} + } + native_leaderboard_response = .{} + if !BeginRequest(*native_leaderboard_pending, client, *native_leaderboard_session, UnixNow(), transport, + ifx native_leaderboard_stage == 1 then "PUT" else "GET", path, native_leaderboard_body, native_leaderboard_response[:], headers[:]) { + native_leaderboard_stage = 0 + native_leaderboard_loaded = true + native_leaderboard_error = true + } +} diff --git a/src/leaderboard_view.zi b/src/leaderboard_view.zi new file mode 100644 index 0000000..6f35e1e --- /dev/null +++ b/src/leaderboard_view.zi @@ -0,0 +1,216 @@ +// Profile owns the leaderboard UI in every host. The host supplies only +// installed boards and ranked display values through entity.leaderboard. +#import "leaderboard_model" +#import "achievement_view" +#import "kryon/app_context" +#import "kryon/dropdown_props" +#import "kryon/dropdown_widget" +#import "std/number_text" +#import "std/c_string" +#import "std/text_buffer" +#import "std/vec" +#import "model" +#import "kryon/session" +#import "kryon/geometry" +#import "kryon/drawing_props" +#import "kryon/button_props" +#import "kryon/button_widget" +#import "kryon/scroll_props" +#import "kryon/scroll_widget" +#import "kryon/box_props" +#import "kryon/box_widget" +#import "kryon/tree" + +profile_leaderboard_open: bool; +profile_leaderboard_ready: bool; +profile_leaderboard_page: ProfileLeaderboard; +profile_leaderboard_scroll: s32; +profile_leaderboard_ticks: s32; +profile_leaderboard_request: [256]u8; + +LeaderboardLabel :: (key: string, fallback: string) -> string { + label := AppLocale(key) + return ifx label == "" || label == key then fallback else label +} + +ProfileLeaderboardCommand :: (command: string) -> bool { + if command == "reload" { + profile_leaderboard_open = false + profile_leaderboard_ready = false + profile_leaderboard_page = .{} + return false + } + if command == "leaderboard" && AppSupports(LEADERBOARD_SERVICE) { + profile_leaderboard_open = true + profile_leaderboard_ready = false + profile_leaderboard_scroll = 0 + profile_leaderboard_request = .{} + unused CopyCString("refresh", profile_leaderboard_request[:]) + return true + } + if command == "back" && profile_leaderboard_open { + profile_leaderboard_open = false + profile_leaderboard_ready = false + AppReply("handled") + return true + } + return false +} + +ProfileLeaderboardSelect :: (index: s32, metric: s32) { + if index < 0 || index >= profile_leaderboard_page.board_count { return } + request: Vec(u8) + BuilderPrint(*request, "{\"owner\":") + EntityQuote(*request, TextUntilNul(profile_leaderboard_page.owner[:])) + BuilderPrint(*request, ",\"board\":") + EntityQuote(*request, TextUntilNul(profile_leaderboard_page.boards[index].id[:])) + BuilderPrint(*request, ",\"metric\":%}", metric) + document := BuilderFinish(request) + unused CopyCString(document, profile_leaderboard_request[:]) + AchievementRelease(document) + profile_leaderboard_ready = false + profile_leaderboard_scroll = 0 +} + +ProfileLeaderboardFrame :: (navigation: bool) -> bool { + if !profile_leaderboard_open { return false } + profile_leaderboard_ticks += 1 + // Query on every frame to discard account changes and uninstalled boards + // immediately. Providers cache/rank results outside their network work. + response := AppService(LEADERBOARD_SERVICE, TextUntilNul(profile_leaderboard_request[:])) + profile_leaderboard_request = .{} + next: ProfileLeaderboard + if ProfileLeaderboardDecode(response, *next) { + if TextUntilNul(next.owner[:]) != TextUntilNul(profile_leaderboard_page.owner[:]) { + profile_leaderboard_scroll = 0 + } + profile_leaderboard_page = next + profile_leaderboard_ready = true + } else { + // Never leave another account's rows on screen after a failed query. + profile_leaderboard_page = .{} + profile_leaderboard_ready = false + } + page := *profile_leaderboard_page + session := AppSession() + scale := AppScale() + if scale <= 0.0 { scale = 1.0 } + area := AppBounds() + width := area.width - 32.0 * scale + if width > 720.0 * scale { width = 720.0 * scale } + if width < 120.0 * scale { return true } + x := area.x + (area.width - width) * 0.5 + y := area.y + 12.0 * scale + font := cast(s32)(14.0 * scale) + if navigation { + if Button(session, ButtonProps.{.id = 55000, .bounds = Rectangle.{x, y, width, 44.0 * scale}, + .label = LeaderboardLabel("entity.back", "Back")}) != 0 { + profile_leaderboard_open = false + } + y += 56.0 * scale + } + AchievementText(session, 55001, LeaderboardLabel("leaderboard_title", "Leaderboard"), + Rectangle.{x, y, width, 36.0 * scale}, cast(s32)(24.0 * scale)) + y += 44.0 * scale + if !profile_leaderboard_ready || page.board_count == 0 { + AchievementText(session, 55002, LeaderboardLabel("profile_no_leaderboard_data", "No leaderboard data yet."), + Rectangle.{x, y, width, 80.0 * scale}, font) + return true + } + current := *page.boards[page.selected] + apps: [LEADERBOARD_BOARDS]DropdownOption + first: [LEADERBOARD_BOARDS]s32 + app_count: s32 = 0 + selected_app: s32 = 0 + for index: cast(s32)0..page.board_count - 1 { + app := TextUntilNul(page.boards[index].app[:]) + seen := false + for prior: cast(s32)0..app_count - 1 { + if TextUntilNul(page.boards[first[prior]].app[:]) == app { seen = true } + } + if seen { continue } + if app == TextUntilNul(current.app[:]) { selected_app = app_count } + first[app_count] = index + apps[app_count].label = TextUntilNul(page.boards[index].app_title[:]) + app_count += 1 + } + if app_count > 1 { + menu := Dropdown(session, DropdownProps.{.id = 55003, .bounds = Rectangle.{x, y, width, 44.0 * scale}, + .selected_index = selected_app, .scale = scale}, apps[:app_count]) + if menu.changed && menu.selected_index >= 0 && menu.selected_index < app_count { + ProfileLeaderboardSelect(first[menu.selected_index], 0) + } + y += 56.0 * scale + } + choices: [LEADERBOARD_BOARDS]s32 + count: s32 = 0 + for index: cast(s32)0..page.board_count - 1 { + if TextUntilNul(page.boards[index].app[:]) == TextUntilNul(current.app[:]) { + choices[count] = index + count += 1 + } + } + columns := cast(s32)((width + 8.0 * scale) / (168.0 * scale)) + if columns < 2 { columns = 2 } + rows := (count + columns - 1) / columns + columns = (count + rows - 1) / rows + choice_width := (width - cast(float32)(columns - 1) * 8.0 * scale) / cast(float32)columns + for index: cast(s32)0..count - 1 { + chosen := choices[index] + if Button(session, ButtonProps.{.id = 55100 + index, + .bounds = Rectangle.{x + cast(float32)(index % columns) * (choice_width + 8.0 * scale), + y + cast(float32)(index / columns) * 48.0 * scale, choice_width, 40.0 * scale}, + .label = TextUntilNul(page.boards[chosen].title[:]), .selected = chosen == page.selected, + .fit_content = true}) != 0 && chosen != page.selected { + ProfileLeaderboardSelect(chosen, 0) + } + } + y += cast(float32)rows * 48.0 * scale + 8.0 * scale + average := current.average[0] != cast(u8)0 + name_width := width * (ifx average then 0.5 else 0.666667) + value_width := (width - name_width) / (ifx average then 2.0 else 1.0) + AchievementText(session, 55200, LeaderboardLabel("profile_friends_title", "Friends"), + Rectangle.{x, y, name_width, 36.0 * scale}, font) + for metric: cast(s32)0..(ifx average then 1 else 0) { + if Button(session, ButtonProps.{.id = 55201 + metric, + .bounds = Rectangle.{x + name_width + cast(float32)metric * value_width, y, value_width, 36.0 * scale}, + .label = TextUntilNul(ifx metric == 0 then current.primary[:] else current.average[:]), + .selected = metric == page.metric, .fit_content = true}) != 0 && metric != page.metric { + ProfileLeaderboardSelect(page.selected, metric) + } + } + y += 44.0 * scale + if page.row_count == 0 { + AchievementText(session, 55204, LeaderboardLabel(ifx page.loading then "profile_updating_status" else "profile_no_leaderboard_data", + ifx page.loading then "Updating…" else "No leaderboard data yet."), + Rectangle.{x, y, width, 64.0 * scale}, font) + return true + } + row_height := cast(s32)(40.0 * scale) + scroll := Scroll(session, ScrollProps.{.key = cast(u64)55300, + .bounds = Rectangle.{x, y, width, area.y + area.height - y - 8.0 * scale}, + .content_height = page.row_count * row_height, .scroll_offset = profile_leaderboard_scroll}) + profile_leaderboard_scroll = scroll.scroll_offset + if !scroll.opened { return true } + for index: cast(s32)0..page.row_count - 1 { + row := *page.rows[index] + row_y := scroll.content.y + cast(float32)(index * row_height) + key := cast(u64)(55400 + index * 4) + if row.own || index % 2 == 1 { + Box(session, BoxProps.{.key = key, .bounds = Rectangle.{x, row_y, width, cast(float32)row_height}, + .fill = ifx row.own then Color.{156, 188, 143, 64} else Color.{156, 156, 156, 24}, .radius = 8.0 * scale}) + } + name: Vec(u8) + BuilderPrint(*name, "%. %", index + 1, TextUntilNul(row.name[:])) + text := BuilderFinish(name) + AchievementText(session, key + 1, text, Rectangle.{x + 8.0 * scale, row_y, name_width - 16.0 * scale, cast(float32)row_height}, font) + AchievementRelease(text) + AchievementText(session, key + 2, TextUntilNul(row.value[:]), Rectangle.{x + name_width + 8.0 * scale, row_y, value_width - 8.0 * scale, cast(float32)row_height}, font) + if average { + AchievementText(session, key + 3, TextUntilNul(row.average[:]), Rectangle.{x + name_width + value_width + 8.0 * scale, row_y, value_width - 8.0 * scale, cast(float32)row_height}, font) + } + } + unused End(session) + AppKeyboard(false) + return true +} diff --git a/src/native_host.zi b/src/native_host.zi index 25900f4..af0be38 100644 --- a/src/native_host.zi +++ b/src/native_host.zi @@ -4,6 +4,8 @@ #import "dew_native" #import "entity_records" #import "entity_dew" +#import "leaderboard_native" +#import "leaderboard_model" #import "model" #import "native_files" #import "native_management" @@ -36,12 +38,16 @@ EntityHostText :: (text: string) -> HostValue { } EntityHostAllows :: (context: *void, name: string) -> bool { return name == "ReadStoreHost" || name == "WriteStoreHost" || name == "ClipboardCopyHost" || - name == "AppLocaleHost" || name == "entity.management" || name == "entity.assets" || name == "entity.dew" + name == "AppLocaleHost" || name == "entity.management" || name == "entity.assets" || name == "entity.dew" || name == LEADERBOARD_SERVICE } EntityHostServices :: (context: *void, module: *u8, function: *u8, arguments: *HostValue, count: s32, result: *HostValue) -> s32 { name := TextFromCString(function) if name == "AppServiceHost" && count == 2 { service := AppArgumentText(arguments[0]) + if service == LEADERBOARD_SERVICE { + result.* = EntityHostText(EntityLeaderboardAnswer(AppArgumentText(arguments[1]))) + return 1 + } if service == "entity.dew" { request := AppArgumentText(arguments[1]) result.* = EntityHostText(ifx request == "" then DewSnapshot() else ifx DewEnqueue(request) then "queued" else "rejected") @@ -178,6 +184,7 @@ EntityHostPump :: () { DewPump() EntityDewPump() EntityRecordsPump() + EntityLeaderboardPump() } EntityHostClose :: () -> bool { diff --git a/tests/leaderboard_test.zi b/tests/leaderboard_test.zi new file mode 100644 index 0000000..82612e9 --- /dev/null +++ b/tests/leaderboard_test.zi @@ -0,0 +1,67 @@ +#import "leaderboard_model" +#import "leaderboard_native" +#import "account_store" +#import "recovery" +#import "daochi_client/keys" +#import "model" +#import "native_files" +#import "std/c_string" +#import "std/text_buffer" +#import "std/file" +#import "std/vec" + +installed: bool = true; +IsInstalled :: (game: string) -> bool { return installed && game == "arcade.shovey" } + +Check :: () -> s32 { + leaderboard_installed = IsInstalled + if !CopyCString(NativeEnvironment("ENTITY_LEADERBOARD_TEST_DATA"), account_root[:]) { return 1 } + // A local score, saved and restored without connecting an account. + if !EntityLeaderboardReport("arcade", "Arcade", "arcade.shovey", "Shovey", "levels 12") { return 2 } + if EntityLeaderboardReport("arcade", "Arcade", "other/game", "Other", "levels 1") || + EntityLeaderboardReport("arcade", "Arcade", "arcade.shovey", "Shovey", "levels -1") || + EntityLeaderboardReport("arcade", "Arcade", "arcade.shovey", "Shovey", "levels 100001") || + EntityLeaderboardReport("arcade", "Arcade", "arcade.shovey", "Shovey", "levels ") { return 3 } + page: ProfileLeaderboard + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.board_count != 1 || + page.selected != 0 || page.row_count != 0 || TextUntilNul(page.boards[0].title[:]) != "Shovey" { return 4 } + // A retained score must disappear as soon as its game is uninstalled. + installed = false + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.board_count != 0 || page.selected != -1 { return 5 } + installed = true + native_leaderboard_owner = .{} + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.board_count != 1 { return 6 } + // An imported account cannot inherit another account's rankings or scores. + unused CopyCString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", account_recovery.keys.public_id[:]) + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.board_count != 0 || page.row_count != 0 { return 7 } + if !EntityLeaderboardReport("arcade", "Arcade", "arcade.shovey", "Shovey", "levels 4") { return 8 } + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer("{\"owner\":\"stale\",\"board\":\"arcade.shovey\"}"), *page) || + page.board_count != 1 || page.row_count != 1 || TextUntilNul(page.rows[0].value[:]) != "4" { return 9 } + unused CopyCString("{\"rows\":[{\"user_id_hash\":\"friend-a\",\"alias\":\"river\",\"value\":12},{\"user_id_hash\":\"friend-a\",\"alias\":\"duplicate\",\"value\":99}]}", native_leaderboard_stats[:]) + unused CopyCString("{\"friends\":[{\"id\":\"friend-a\",\"alias\":\"river\"},{\"id\":\"friend-b\",\"alias\":\"cedar\"}]}", native_leaderboard_friends[:]) + native_leaderboard_rows_dirty = true + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.row_count != 3 || + TextUntilNul(page.rows[0].name[:]) != "@river" || !page.rows[1].own || + TextUntilNul(page.rows[2].value[:]) != "0" { return 15 } + // Properly escaped display data round-trips; malformed snapshots don't. + unused CopyCString("A \"quoted\" name", page.rows[0].name[:]) + encoded := ProfileLeaderboardEncode(*page) + defer { EntityFree(encoded) } + decoded: ProfileLeaderboard + if !ProfileLeaderboardDecode(encoded, *decoded) || TextUntilNul(decoded.rows[0].name[:]) != "A \"quoted\" name" { return 10 } + if ProfileLeaderboardDecode("{}", *decoded) || ProfileLeaderboardDecode("[]", *decoded) || + ProfileLeaderboardDecode("{\"version\":1,\"owner\":\"a\",\"selected\":0,\"metric\":0,\"loading\":0,\"error\":0,\"boards\":[],\"rows\":[]}", *decoded) { return 11 } + page.boards[1] = page.boards[0] + page.board_count = 2 + duplicate := ProfileLeaderboardEncode(*page) + defer { EntityFree(duplicate) } + if ProfileLeaderboardDecode(duplicate, *decoded) { return 12 } + unused CopyCString("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", account_recovery.keys.public_id[:]) + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.row_count != 0 || page.board_count != 0 { return 13 } + account_recovery.keys.public_id = .{} + if !ProfileLeaderboardDecode(EntityLeaderboardAnswer(""), *page) || page.board_count != 1 || page.row_count != 0 { return 14 } + return 0 +} + +#program_export +main :: () -> s32 { return Check() } diff --git a/ziran.toml b/ziran.toml index 6afa5eb..fd07b81 100644 --- a/ziran.toml +++ b/ziran.toml @@ -31,6 +31,8 @@ game_shop = "src/game_shop.zi" game_shop_native = "src/game_shop_native.zi" game_progress_id = "src/game_progress_id.zi" game_completion = "src/game_completion.zi" +leaderboard_model = "src/leaderboard_model.zi" +leaderboard_native = "src/leaderboard_native.zi" pairing = "src/pairing.zi" pairing_client = "src/pairing_client.zi"