From 144dcfdf378567cdddcd8a2b371f6b50377652cc Mon Sep 17 00:00:00 2001 From: Waozi Date: Thu, 22 Oct 2026 21:30:15 -0300 Subject: [PATCH] Share inline Dew balance and the account host across games and web --- README.md | 7 ++ scripts/build-web.py | 65 ++++++++++++++++++ src/account_store.zi | 52 +++++++++++++-- src/browser_host.zi | 124 ++++++++++++++++++++++++++++++++++ src/dew_model.zi | 34 ++++++++++ src/dew_view.zi | 140 +++++++++++++++++++++++++++++++++++++++ src/entity.zi | 103 ++++++++++++++++++++++++++-- src/native_host.zi | 5 +- tests/management_test.zi | 7 ++ ziran.lock | 6 +- ziran.toml | 2 + 11 files changed, 531 insertions(+), 14 deletions(-) create mode 100644 scripts/build-web.py create mode 100644 src/browser_host.zi create mode 100644 src/dew_view.zi diff --git a/README.md b/README.md index 4ecd139..3395851 100644 --- a/README.md +++ b/README.md @@ -100,3 +100,10 @@ explicit retry; it never becomes a new debit. Switching or logging out cancels the old account's in-flight requests. The `entity/dew_model` export shares strict integer balance, allowance and funding-address validation with Inner Breeze. No currency transfer or game-specific shop is added. + +The Profile shows Inbe's shared `DewBalance` card inline. Game hosts hide the +Name and Intention fields and identify players by their alias or public ID. +The browser host uses Kryon's existing `BundleApp` lifecycle, IndexedDB-backed +files and the same native Entity account provider; game bundles receive only +a navigation service and never see account keys. `scripts/build-web.py` links +this provider for browser applications with the locked cryptography packages. diff --git a/scripts/build-web.py b/scripts/build-web.py new file mode 100644 index 0000000..ad02e81 --- /dev/null +++ b/scripts/build-web.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Link a browser app with the same Entity account provider as native hosts.""" +import argparse +import os +from pathlib import Path +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bundle', type=Path, required=True) + parser.add_argument('--profile', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--entry', default='runtime:main') + parser.add_argument('--source', default='src/web/runtime.zi') + args = parser.parse_args() + project = Path.cwd() + ziran = os.environ.get('ZIRAN', 'ziran') + locked = [] if (project / 'ziran.local.toml').exists() else ['--locked'] + + def package(name): + return Path(subprocess.check_output([ziran, 'pkg', 'path', name, *locked], text=True).strip()) + + toolchain = package('ziran') + kryon = package('kryon') + work = project / 'build/profile-web' + generated = work / 'generated' + output = args.output.resolve() + output.parent.mkdir(parents=True, exist_ok=True) + emcc = os.environ.get('EMCC') or str(Path.home() / 'emsdk/upstream/emscripten/emcc') + if not Path(emcc).exists(): + emcc = 'emcc' + emar = str(Path(emcc).with_name('emar')) if '/' in emcc else 'emar' + emcmake = str(Path(emcc).with_name('emcmake')) if '/' in emcc else 'emcmake' + env = {**os.environ, 'EM_CACHE': str(work / 'emscripten-cache')} + subprocess.run([ziran, 'build', '--project', *locked, '--target=c', '--define', 'PLATFORM_WEB', + '--define', 'BUNDLE_NATIVE_RENDERER', '--entry', args.entry, + '-o', str(generated), args.source], check=True, env=env) + runtime = work / 'runtime/libziran.a' + subprocess.run(['make', '-C', str(toolchain), 'BOOTSTRAP=1', 'BUILD_DIR=' + str(runtime.parent), + 'CC=' + emcc, 'AR=' + emar, 'OBJCOPY=true', 'CFLAGS=-O2', str(runtime)], check=True, env=env) + oqs = work / 'oqs' + subprocess.run([emcmake, 'cmake', '-S', str(package('liboqs')), '-B', str(oqs), + '-DCMAKE_BUILD_TYPE=MinSizeRel', '-DBUILD_SHARED_LIBS=OFF', '-DOQS_BUILD_ONLY_LIB=ON', + '-DOQS_USE_OPENSSL=OFF', '-DOQS_DIST_BUILD=OFF', '-DOQS_OPT_TARGET=generic', + '-DOQS_MINIMAL_BUILD=SIG_ml_dsa_44'], check=True, env=env) + subprocess.run(['cmake', '--build', str(oqs), '--target', 'oqs', '-j2'], check=True, env=env) + subprocess.run([emcc, '-O2', '-ffunction-sections', '-fdata-sections', + '-I' + str(toolchain / 'include'), '-iquote', str(generated), + *[item for path in generated.rglob('*') if path.is_dir() for item in ('-iquote', str(path))], + *map(str, generated.rglob('*.c')), str(runtime), + str(package('monocypher') / 'src/monocypher.c'), str(oqs / 'lib/liboqs.a'), + '--js-library', str(toolchain / 'web/ziran_web.js'), '-lidbfs.js', + '--embed-file', str(kryon / 'assets/fonts/LiberationSans-Regular.ttf') + '@/kryon-font.ttf', + '--embed-file', str(args.bundle.resolve()) + '@/app.zib', + '--embed-file', str(args.profile.resolve()) + '@/entity.zib', + '-sASYNCIFY', '-sALLOW_MEMORY_GROWTH=1', '-sFORCE_FILESYSTEM=1', + '-sSTACK_SIZE=16777216', '-sASYNCIFY_STACK_SIZE=1048576', '-sENVIRONMENT=web', + '-sEXPORTED_RUNTIME_METHODS=FS', + '-sEXPORTED_FUNCTIONS=_main', + '--shell-file', str(kryon / 'mk/zib-shell.html'), '-o', str(output)], check=True, env=env) + + +if __name__ == '__main__': + main() diff --git a/src/account_store.zi b/src/account_store.zi index 73f6068..dcd1b52 100644 --- a/src/account_store.zi +++ b/src/account_store.zi @@ -16,6 +16,11 @@ Auth :: #import "daochi_client/auth"; #import "std/vec" #import "std/byte_text_linux" #import "std/file" +#if #defined(PLATFORM_WEB) { + #import "kryon/file_picker" + #import "kryon/page_files" + #import "std/web" +} #if !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { Dialog :: #import "file_dialog_linux"; } @@ -28,12 +33,16 @@ account_pairing_delivered: bool; account_standalone_ready: bool; account_root: [4096]u8; account_client_id: [64]u8; +account_application_id: [64]u8; AccountStorePath :: (name: string, output: []u8) -> string { return NativeJoin(output, TextUntilNul(account_root[:]), name) } AccountStoreChooseFile :: (context: *void, save: bool, output: []u8) -> s32 { - #if #defined(ANDROID_BUILD) || #defined(PLATFORM_WEB) { + #if #defined(PLATFORM_WEB) { + return PickFile(FilePickerProps.{.title = ifx save then "Back up account key" else "Import account key", + .filter = "Account keys | *.key *.json", .suggested_name = "entity-account.key", .save = save}, output) + } else #if #defined(ANDROID_BUILD) { return -1 } else { patterns: [2]string = .["*.key", "*.json"] @@ -45,6 +54,29 @@ AccountStoreChooseFile :: (context: *void, save: bool, output: []u8) -> s32 { return ifx selected.accepted then 1 else 0 } } +AccountStoreDeliverFile :: (context: *void, path: string) -> bool { + #if #defined(PLATFORM_WEB) { + scope := WebScope() + defer WebEnd(scope) + data := WebCall1(PageFileSystem(), WebName("readFile"), WebText(path)) + parts := WebNewArray() + unused WebCall1(parts, WebName("push"), data) + blob := WebNew1(WebGetObject(WebGlobal, WebName("Blob")), WebObject(parts)) + urls := WebGetObject(WebGlobal, WebName("URL")) + url := WebCall1(urls, WebName("createObjectURL"), WebObject(blob)) + document := WebGetObject(WebGlobal, WebName("document")) + anchor := WebAsObject(WebCall1(document, WebName("createElement"), WebText("a"))) + WebSet(anchor, WebName("href"), url) + WebSet(anchor, WebName("download"), WebText("entity-account.key")) + unused WebCall0(anchor, WebName("click")) + unused WebCall1(urls, WebName("revokeObjectURL"), url) + unused RemoveFile(path) + return !WebFailed() + } else { + return true + } +} + AccountStoreSaveKey :: (recovery: *Recovery) -> bool { text: [ACCOUNT_EXPORT_ENCRYPTED_TEXT_SIZE]u8 defer { SecureWipe(*text[0], text.count) } @@ -91,7 +123,7 @@ AccountStoreSnapshot :: (context: *void, output: *Management) { output.alias = account_alias output.capabilities = ACCOUNT_CREATE | ACCOUNT_IMPORT | ACCOUNT_SWITCH | ACCOUNT_LINK if account_standalone_ready { output.capabilities |= ACCOUNT_BACKUP | ACCOUNT_ALIAS | ACCOUNT_LOGOUT | ACCOUNT_CLEAR_REMOTE } - #if #defined(ANDROID_BUILD) || #defined(PLATFORM_WEB) { + #if #defined(ANDROID_BUILD) { output.capabilities &= ~(ACCOUNT_IMPORT | ACCOUNT_BACKUP) } output.node_count = account_profile.node_count @@ -151,7 +183,7 @@ AccountStoreDigest :: (body: string, output: []u8) -> bool { AccountStoreClient :: (context: *void, output: *Client) -> bool { if !account_standalone_ready { return false } output.server_url = TextUntilNul(account_profile.nodes[account_profile.preferred][:]) - output.app_id = TextUntilNul(account_client_id[:]) + output.app_id = TextUntilNul(account_application_id[:]) output.identity = Auth.Identity.{.account_id = TextUntilNul(account_recovery.keys.public_id[:]), .public_key = TextUntilNul(account_recovery.keys.public_key_hex[:]), .client_id = TextUntilNul(account_client_id[:]), .signing_context = cast(*void)*account_recovery.keys} @@ -194,7 +226,17 @@ AccountStoreStart :: () -> bool { // provider; they never open another credential store. AccountStoreStartAt :: (root: string, client_id: string) -> bool { if root == "" || client_id == "" || !CopyCString(root, account_root[:]) || - !CopyCString(client_id, account_client_id[:]) || !NativeDirectory(root) { return false } + !CopyCString(client_id, account_application_id[:]) || !NativeDirectory(root) { return false } + // The node requires an installation ID of at least eight characters. + // Product names such as arcade/entity are app IDs, not device IDs. + client_path: [4096]u8 + account_client_id = .{} + if NativeRead(AccountStorePath("client.id", client_path[:]), account_client_id[:]) != 32 { + random: [16]u8 + if SecureRandom(*random[0], random.count) == 0 { return false } + BytesToHex(*random[0], random.count, *account_client_id[0], account_client_id.count) + if !NativeWrite(AccountStorePath("client.id", client_path[:]), TextUntilNul(account_client_id[:])) { return false } + } account_profile = EntityDefault() path: [4096]u8 text: [ACCOUNT_EXPORT_ENCRYPTED_TEXT_SIZE]u8 @@ -211,7 +253,7 @@ AccountStoreStartAt :: (root: string, client_id: string) -> bool { unused CopyCString(TextUntilNul(account_recovery.keys.public_id[:]), account_profile.owner_id[:]) unused SharedProfileLoad(TextUntilNul(account_recovery.keys.public_id[:]), *account_profile) account_provider = ManagementProvider.{.snapshot = AccountStoreSnapshot, .load = AccountStoreLoad, - .apply = AccountStoreApply, .action = AccountStoreAction, .client = AccountStoreClient, .choose_file = AccountStoreChooseFile} + .apply = AccountStoreApply, .action = AccountStoreAction, .client = AccountStoreClient, .choose_file = AccountStoreChooseFile, .deliver_file = AccountStoreDeliverFile} AccountStoreReadAlias() pairing_load = AccountStoreLoad pairing_server = AccountStoreServer diff --git a/src/browser_host.zi b/src/browser_host.zi new file mode 100644 index 0000000..10375c6 --- /dev/null +++ b/src/browser_host.zi @@ -0,0 +1,124 @@ +// Browser applications reuse Kryon's standalone bundle host and Entity's +// existing account provider. Only this host can access account keys. +using Canvas :: #import "kryon/Canvas"; +#import "kryon/bundle_app" +#import "kryon/bundle_storage_web" +#import "kryon/bundle_assets" +#import "kryon/app_files" +#import "kryon/app_context_host" +#import "kryon/app_protocol" +#import "kryon/hosted_values" +#import "kryon/page_core" +#import "kryon/session" +#import "kryon/geometry" +#import "kryon/tree" +#import "kryon/TestDriver" +#import "kryon/Frame" +#import "kryon/tree_input" +#import "kryon/ScrollDevice" +#import "kryon/key_input" +#import "kryon/text_input_props" +#import "kryon/text_props" +#import "kryon/text_widget" +#import "kryon/button_props" +#import "kryon/button_widget" +#import "kryon/widget_palette" +#import "std/bundle_host" +#import "std/byte_text_linux" +#import "std/file" +#import "std/web" +#import "std/c_string" +#import "native_host" +#import "model" + +browser_game: BundleApp; +browser_profile: bool; +browser_ready: bool; + +BrowserAllows :: (context: *void, name: string) -> bool { + return name == "entity.profile" || BundleAppAllows(context, name) +} +BrowserServices :: (context: *void, module: *u8, function: *u8, + arguments: *HostValue, count: s32, result: *HostValue) -> s32 { + if TextFromCString(function) == "AppServiceHost" && count == 2 && + AppArgumentText(arguments[0]) == "entity.profile" { + if AppArgumentText(arguments[1]) == "open" { + EntityHostReload() + browser_profile = true + } + result.* = EntityHostText("available") + return 1 + } + return BundleAppServices(context, module, function, arguments, count, result) +} + +BrowserMain :: (palette: WidgetPalette) -> s32 { + if !OpenCanvas() { return 1 } + defer CloseCanvas() + if !BundleStorageOpen() { return 1 } + while !BundleStorageReady() && !BundleStorageFailed() { WebSleep(10) } + if !BundleStorageReady() { return 1 } + game_bytes, game_found := ReadEntireFile("/app.zib") + profile_bytes, profile_found := ReadEntireFile("/entity.zib") + defer { AppFileFree(game_bytes); AppFileFree(profile_bytes) } + if !game_found || !profile_found || !BundleAppOpen(*browser_game, game_bytes, "/kryon-apps") { return 1 } + defer BundleAppClose(*browser_game) + browser_game.extracted_assets = true + if !BundleWriteAssets(browser_game.app.app.bundle, *browser_game.local.files) { return 1 } + browser_game.app.allows = BrowserAllows + browser_game.app.services = BrowserServices + if !EntityHostOpen(profile_bytes, "/kryon-apps/profile", "arcade", true) { return 1 } + defer { unused EntityHostClose(); unused BundleStorageSync(false) } + session := SessionOpen() + if !SessionValid(session) { return 1 } + defer { unused SessionClose(session) } + unused WidgetPaletteUse(session, palette) + saved := PageNow() + browser_ready = true + WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("profileReady"), WebBool(true)) + while PollCanvas() { + scope := WebScope() + WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("profileVisible"), WebBool(browser_profile)) + BeginCanvasFrame() + viewport := CanvasViewport() + pointer := PollPointer() + key := CanvasPressedKey() + modifiers := CanvasModifiers() + active := ifx browser_profile then session else browser_game.app.session + point := CanvasTypedCodepoint() + while point != 0 { unused TypedCodepointSend(active, point); point = CanvasTypedCodepoint() } + typed: [1024]u8 + text := TypedTextTake(active, typed[:]) + EntityHostPump() + if browser_profile { + TreePointerUpdate(session, pointer) + TreeSecondaryPointerUpdate(session, PollSecondaryPointer()) + PointerWheelSend(session, pointer.x, pointer.y, CanvasWheelMove()) + KeyboardModifiersSend(session, modifiers) + if key != 0 { unused KeyboardSend(session, key) } + BeginScrollFrame(session, Vector2.{pointer.x, pointer.y}, pointer.pressed, + pointer.down, pointer.released, CanvasWheelMove(), PageNow() / 1000.0) + if BeginFrame(session, cast(u64)1, viewport) != FrameStatus.FrameOk { return 1 } + bounds := Rectangle.{viewport.x, viewport.y + 56.0, viewport.width, viewport.height - 56.0} + if !EntityHostFrame(session, bounds, key, modifiers, TextFieldInputFor(key, modifiers, text), true) { return 1 } + Text(session, TextProps.{.key = cast(u64)49002, .text = "Profile", .font = 20, + .bounds = Rectangle.{100.0, 12.0, viewport.width - 200.0, 36.0}}) + if Button(session, ButtonProps.{.key = cast(u64)49001, .id = 49001, .label = "Back", + .bounds = Rectangle.{8.0, 6.0, 76.0, 44.0}}) != 0 || key == 256 { + if !EntityHostBack() && EntityHostSave() { browser_profile = false } + } + if EndFrame(session) != FrameStatus.FrameOk { return 1 } + } else if !BundleAppFrame(*browser_game, viewport, pointer, PollSecondaryPointer(), + key, modifiers, CanvasWheelMove(), text, PageNow() / 1000.0) { return 1 } + TestDriverFrame(active) + CanvasCursor(active) + unused EndCanvasFrame() + if PageNow() - saved >= 1000.0 { + unused BundleAppSave(*browser_game) + unused BundleStorageSync(false) + saved = PageNow() + } + WebEnd(scope) + } + return 0 +} diff --git a/src/dew_model.zi b/src/dew_model.zi index 7746a0c..696cd36 100644 --- a/src/dew_model.zi +++ b/src/dew_model.zi @@ -3,6 +3,7 @@ #import "std/json_scan" #import "std/c_string" #import "std/text_buffer" +#import "std/number_text" DewUnits :: 1000000 DewNode :: "https://api.waozi.xyz" // The node's paid storage sizes, in the order the app offers them. @@ -28,6 +29,39 @@ DewAccount :: struct { plans: [DewPlanCount]DewStoragePlan } +// Six decimal places match Inbe's signed ledger; trailing zeros vanish. +// The caller owns the buffer, so portable profiles allocate nothing per frame. +DewFormat :: (units: s64, divisor: s64, output: []u8, suffix: string = "") -> bool { + if units < 0 || divisor <= 0 || output.count < 2 { return false } + digits: [32]u8 + whole := FormatInteger(units / divisor, digits[:]) + if !CopyCString(whole, output) { return false } + at := whole.count + remainder := units % divisor + if remainder != 0 { + if at + 1 >= output.count { return false } + output[at] = cast(u8)46 + at += 1 + factor := divisor / 10 + while factor > 0 { + if at + 1 >= output.count { return false } + output[at] = cast(u8)(48 + remainder / factor) + at += 1 + remainder %= factor + if remainder == 0 { break } + factor /= 10 + } + } + if suffix != "" { + if at + suffix.count + 1 >= output.count { return false } + output[at] = cast(u8)32 + at += 1 + for byte: suffix { output[at] = byte; at += 1 } + } + output[at] = cast(u8)0 + return true +} + DewInteger :: (json: string, at: s32, value: *s64) -> bool { if at < 0 || at >= cast(s32)json.count { return false diff --git a/src/dew_view.zi b/src/dew_view.zi new file mode 100644 index 0000000..1b67ac9 --- /dev/null +++ b/src/dew_view.zi @@ -0,0 +1,140 @@ +// Inbe's Dew balance card, shared by the profile app and native hosts. +// The provider supplies verified account state and translated summaries; +// this view owns the same layout, storage bar and actions everywhere. +#import "kryon/session" +#import "kryon/geometry" +#import "kryon/drawing_props" +#import "kryon/text_props" +#import "kryon/text_widget" +#import "kryon/text_measure" +#import "kryon/box_props" +#import "kryon/box_widget" +#import "kryon/button_props" +#import "kryon/button_widget" +#import "kryon/control_props" + +DewBalanceTopUp :: 1 +DewBalancePlans :: 2 + +DewBalanceProps :: struct { + key: u64 + bounds: Rectangle + scale: float32 + font: s32 + small_font: s32 + title: string + balance: string + worth: string + plan: string + usage: string + notice: string + top_up: string + plans: string + ready: bool + known: bool + busy: bool + enabled: bool + usage_percent: s32 + has_usage: bool + fill: Color + track: Color + accent: Color + warning: Color + danger: Color +} + +DewBalanceResult :: struct { height: float32; action: s32 } + +DewLineHeight :: (session: Session, text: string, width: float32, font: s32) -> float32 { + if text == "" { return 0.0 } + return cast(float32)TextHeight(session, TextProps.{.text = text, .font = font, + .bounds = Rectangle.{0.0, 0.0, width, 0.0}, .wrap = TextWrap.TextWrapAuto}) +} + +DewBalanceLine :: (session: Session, key: u64, text: string, x: float32, + y: *float32, width: float32, font: s32, scale: float32, draw: bool) { + if text == "" { return } + height := DewLineHeight(session, text, width, font) + if draw { + Text(session, TextProps.{.key = key, .text = text, .font = font, + .bounds = Rectangle.{x, y.*, width, height}, + .wrap = TextWrap.TextWrapAuto}) + } + y.* += height + 8.0 * scale +} + +DewBalance :: (session: Session, props: DewBalanceProps, draw: bool = true) -> DewBalanceResult { + scale := ifx props.scale > 0.0 then props.scale else 1.0 + key := ifx props.key != 0 then props.key else cast(u64)46000 + font := cast(s32)(cast(float32)(ifx props.font > 0 then props.font else 16) * scale) + small := cast(s32)(cast(float32)(ifx props.small_font > 0 then props.small_font else 14) * scale) + x := props.bounds.x + 14.0 * scale + y := props.bounds.y + 14.0 * scale + width := props.bounds.width - 28.0 * scale + result: DewBalanceResult + if width <= 0.0 { return result } + if draw { + measured := DewBalance(session, props, false) + Box(session, BoxProps.{.key = key, .bounds = Rectangle.{props.bounds.x, props.bounds.y, + props.bounds.width, measured.height - 8.0 * scale}, .fill = props.fill, .radius = 12.0 * scale}) + } + DewBalanceLine(session, key + 1, props.title, x, *y, width, font, scale, draw) + value_font := cast(s32)(24.0 * scale) + if props.ready && props.known { + button_width := cast(float32)TextWidth(session, TextProps.{.text = props.top_up, .font = font}) + 32.0 * scale + if button_width > width * 0.5 { button_width = width * 0.5 } + text_width := width - button_width - 12.0 * scale + value_height := DewLineHeight(session, props.balance, text_width, value_font) + worth_height := DewLineHeight(session, props.worth, text_width, small) + if worth_height > 0.0 { worth_height += 2.0 * scale } + row_height := 44.0 * scale + if value_height + worth_height > row_height { row_height = value_height + worth_height } + text_y := y + (row_height - value_height - worth_height) * 0.5 + DewBalanceLine(session, key + 2, props.balance, x, *text_y, text_width, value_font, scale, draw) + if props.worth != "" { + worth_y := y + (row_height - value_height - worth_height) * 0.5 + value_height + 2.0 * scale + DewBalanceLine(session, key + 3, props.worth, x, *worth_y, text_width, small, scale, draw) + } + if draw && Button(session, ButtonProps.{.key = key + 4, .id = cast(s32)(key + 4), + .label = props.top_up, .bounds = Rectangle.{x + width - button_width, + y + (row_height - 44.0 * scale) * 0.5, button_width, 44.0 * scale}, + .disabled = props.busy, .tone = ButtonTone.ButtonToneAccent, + .emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 { + result.action = DewBalanceTopUp + } + y += row_height + 8.0 * scale + DewBalanceLine(session, key + 5, props.plan, x, *y, width, font, scale, draw) + if props.has_usage { + percent := props.usage_percent + if percent < 0 { percent = 0 } + if percent > 100 { percent = 100 } + if draw { + bar_height := 8.0 * scale + Box(session, BoxProps.{.key = key + 6, + .bounds = Rectangle.{x, y, width, bar_height}, .fill = props.track, .radius = bar_height * 0.5}) + if percent > 0 { + fill := width * cast(float32)percent / 100.0 + if fill < bar_height { fill = bar_height } + color := ifx percent >= 100 then props.danger else ifx percent >= 90 then props.warning else props.accent + Box(session, BoxProps.{.key = key + 7, + .bounds = Rectangle.{x, y, fill, bar_height}, .fill = color, .radius = bar_height * 0.5}) + } + } + y += 16.0 * scale + DewBalanceLine(session, key + 8, props.usage, x, *y, width, small, scale, draw) + } + if props.enabled && props.plans != "" { + if draw && Button(session, ButtonProps.{.key = key + 9, .id = cast(s32)(key + 9), + .label = props.plans, .bounds = Rectangle.{x, y, width, 44.0 * scale}, + .tone = ButtonTone.ButtonToneAccent, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 { + result.action = DewBalancePlans + } + y += 52.0 * scale + } + } else { + DewBalanceLine(session, key + 2, props.balance, x, *y, width, value_font, scale, draw) + } + DewBalanceLine(session, key + 10, props.notice, x, *y, width, small, scale, draw) + result.height = y - props.bounds.y + 20.0 * scale + return result +} diff --git a/src/entity.zi b/src/entity.zi index df88996..8fad6de 100644 --- a/src/entity.zi +++ b/src/entity.zi @@ -4,6 +4,7 @@ #import "achievement_view" #import "management" #import "dew_model" +#import "dew_view" #import "std/json_scan" #import "std/number_text" #import "node_url" @@ -198,7 +199,7 @@ OpenManagement :: (page: s32) { AccountSummary :: (x: float32, y: *float32, width: float32) { if management.account { title := TextUntilNul(management.alias[:]) - if title == "" { title = TextUntilNul(state.name[:]) } + if title == "" { title = TextUntilNul(management.public_id[:]) } if title == "" { title = Label("entity.account", "Account") } if Action(702, title, Rectangle.{x, y.*, width, 44.0 * scale}) { OpenManagement(1) @@ -639,6 +640,7 @@ ExtensionRows :: (left: float32, top: *float32, width: float32) { entry := state.extensions[index] route := TextUntilNul(entry.id[:]) if management.available && route == "account" { continue } + if route == "dew" && AppSupports("entity.dew") { continue } detailed := entry.summary[0] != cast(u8)0 row_height := (ifx detailed then 76.0 else 60.0) * scale row := Rectangle.{left, top.*, width, row_height} @@ -679,6 +681,7 @@ Draw :: () { count := ReadStore("entity.json", bytes[:]) if count > 0 { unused EntityDecode(TextUntilNul(bytes[:]), *state) } loaded = true + dew_refresh = true } if AchievementViewFrame(!state.host_navigation) { return } if dew_page { DrawDew(); return } @@ -691,6 +694,8 @@ Draw :: () { if panel_width > 560.0 * scale { panel_width = 560.0 * scale } if panel_width < 208.0 * scale { return } width := panel_width - 48.0 * scale + inline_dew := AppSupports("entity.dew") + if inline_dew { ProfileDewRead() } columns := cast(s32)((width + 12.0 * scale) / (56.0 * scale)) if columns > 7 { columns = 7 } if columns < 3 { columns = 3 } @@ -698,6 +703,8 @@ Draw :: () { for index: 0..27 { if (state.pictures & (1 << cast(s32)index)) != 0 { picture_count += 1 } } picker_height := cast(float32)((picture_count + columns - 1) / columns) * 56.0 * scale + 16.0 * scale height := (ifx !state.host_navigation then 352.0 else 308.0) * scale + if (state.controls & ENTITY_IDENTITY) == 0 { height -= 100.0 * scale } + if inline_dew { height += ProfileDewBalance(0.0, 0.0, width, false).height } if (state.controls & ENTITY_NODES) != 0 && !management.available { height += cast(float32)(112 + state.node_count * 56) * scale } if management.available { height += (ifx management.account then 64.0 else 144.0) * scale } if !management.available { @@ -711,6 +718,7 @@ Draw :: () { for index: 0..state.extension_count - 1 { entry := state.extensions[index] if management.available && TextUntilNul(entry.id[:]) == "account" { continue } + if TextUntilNul(entry.id[:]) == "dew" && inline_dew { continue } height += (ifx entry.summary[0] != cast(u8)0 then 84.0 else 68.0) * scale } if notice != "" { height += 48.0 * scale } @@ -761,9 +769,12 @@ Draw :: () { y += picker_height } if management.available { AccountSummary(x, *y, width) } - TextLine(20, Label("entity.name", "Name"), x, y, width, 14) - if EditField(0, state.name[:], Label("entity.name", "Name"), Rectangle.{x, y + 28.0 * scale, width, 44.0 * scale}, 40) { Save() } - y += 100.0 * scale + if inline_dew { y += ProfileDewBalance(x, y, width, true).height } + if (state.controls & ENTITY_IDENTITY) != 0 { + TextLine(20, Label("entity.name", "Name"), x, y, width, 14) + if EditField(0, state.name[:], Label("entity.name", "Name"), Rectangle.{x, y + 28.0 * scale, width, 44.0 * scale}, 40) { Save() } + y += 100.0 * scale + } if (state.controls & ENTITY_INTENTION) != 0 { TextLine(21, Label("entity.intention", "Intention"), x, y, width, 14) if EditField(1, state.intention[:], Label("entity.intention", "Intention"), Rectangle.{x, y + 28.0 * scale, width, 44.0 * scale}, 90) { Save() } @@ -862,6 +873,90 @@ dew_refresh: bool; dew_confirmation: s32 = -1; dew_view_tick: s32; dew_view_json: [20000]u8; +dew_profile_account: DewAccount; +dew_profile_available: bool; +dew_profile_busy: bool; +dew_profile_error: bool; +dew_profile_host_actions: bool; +dew_profile_worth: [256]u8; +dew_profile_plan: [256]u8; +dew_profile_usage: [256]u8; + +ProfileDewRead :: () { + dew_view_tick += 1 + if dew_view_tick % 15 != 1 && !dew_refresh { return } + unused CopyCString(AppService("entity.dew", ""), dew_view_json[:]) + json := TextUntilNul(dew_view_json[:]) + owner: [65]u8 + unused ReadStringText(json, FieldAt(json, 0, "owner"), owner[:]) + same_owner := TextUntilNul(owner[:]) == TextUntilNul(management.public_id[:]) && TextUntilNul(owner[:]).count == 64 + dew_profile_available = same_owner && MatchLiteral(json, FieldAt(json, 0, "available"), "true") + dew_profile_busy = MatchLiteral(json, FieldAt(json, 0, "busy"), "true") + dew_profile_error = MatchLiteral(json, FieldAt(json, 0, "error"), "true") + dew_profile_host_actions = MatchLiteral(json, FieldAt(json, 0, "host_actions"), "true") + dew_profile_account = .{} + dew_profile_worth = .{} + dew_profile_plan = .{} + dew_profile_usage = .{} + at := FieldAt(json, 0, "account") + end := ValueEnd(json, at, 0) + if same_owner && at >= 0 && end > at { + unused DewParseAccount(json[at:end], TextUntilNul(owner[:]), *dew_profile_account) + unused ReadStringText(json, FieldAt(json, 0, "worth"), dew_profile_worth[:]) + unused ReadStringText(json, FieldAt(json, 0, "plan_summary"), dew_profile_plan[:]) + unused ReadStringText(json, FieldAt(json, 0, "usage_summary"), dew_profile_usage[:]) + } + if dew_refresh && dew_profile_available && !dew_profile_busy { + sequence := cast(s32)ReadNumber(json, FieldAt(json, 0, "sequence")).value + DewCommand("refresh", sequence) + dew_refresh = false + } +} + +ProfileDewBalance :: (x: float32, y: float32, width: float32, draw: bool) -> DewBalanceResult { + account := dew_profile_account + amount: [64]u8 + unused CopyCString("—", amount[:]) + if account.known && dew_profile_available { unused DewFormat(account.balance, DewUnits, amount[:], "Dew") } + plan := TextUntilNul(dew_profile_plan[:]) + usage := TextUntilNul(dew_profile_usage[:]) + own_plan: [256]u8 + own_usage: [256]u8 + if account.known && plan == "" { + unused CopyCString(ifx account.plan_size > 0 then Label("profile_dew_paid_plan", "Paid storage") else Label("profile_dew_plan_free", "Free"), own_plan[:]) + plan = TextUntilNul(own_plan[:]) + } + if account.known && usage == "" && account.limit_bytes > 0 { + used: [64]u8 + limit: [64]u8 + unused DewFormat(account.used_bytes / 1048576, 1, used[:], "MB") + unused DewFormat(account.limit_bytes / 1048576, 1, limit[:], "MB") + at: s64 = 0 + for byte: TextUntilNul(used[:]) { own_usage[at] = byte; at += 1 } + for byte: " / " { own_usage[at] = byte; at += 1 } + for byte: TextUntilNul(limit[:]) { own_usage[at] = byte; at += 1 } + usage = TextUntilNul(own_usage[:]) + } + notice := "" + if !dew_profile_available { notice = Label("profile_dew_connect", "Connect your account to the Waozi node to view Dew.") } + else if dew_profile_error { notice = Label("profile_dew_error", "Could not refresh Dew. Any balance shown is the last confirmed balance.") } + else if !account.known { notice = Label("profile_dew_loading", "Checking Dew…") } + result := DewBalance(session, DewBalanceProps.{.bounds = Rectangle.{x, y, width, 0.0}, .scale = scale, + .title = Label("profile_dew_title", "Dew balance"), .balance = TextUntilNul(amount[:]), + .worth = TextUntilNul(dew_profile_worth[:]), .plan = plan, .usage = usage, .notice = notice, + .top_up = Label("profile_dew_topup", "Top up"), .plans = Label("profile_dew_plans", "Storage plans"), + .ready = dew_profile_available, .known = account.known, .busy = dew_profile_busy, .enabled = account.enabled, + .has_usage = account.limit_bytes > 0, + .usage_percent = ifx account.limit_bytes > 0 then cast(s32)(account.used_bytes * 100 / account.limit_bytes) else 0, + .fill = ThemeOr("canvas", 0x142724ff, 0xeef4f2ff), .track = ThemeOr("border", 0x34514aff, 0xdde7e3ff), + .accent = ThemeOr("accent", 0x49a68eff, 0x298a71ff), + .warning = Color.{163, 98, 0, 255}, .danger = Color.{179, 38, 30, 255}}, draw) + if result.action != 0 { + if dew_profile_host_actions { AppReply(ifx result.action == DewBalanceTopUp then "dew-topup" else "dew-plans") } + else { dew_page = true; dew_refresh = true; management_scroll = 0 } + } + return result +} DewCommand :: (operation: string, sequence: s32, size: string = "", period: string = "") { request: Vec(u8) diff --git a/src/native_host.zi b/src/native_host.zi index 6a02225..8a2a7e5 100644 --- a/src/native_host.zi +++ b/src/native_host.zi @@ -23,6 +23,7 @@ portable: AppContext; profile_document: string; asset_folder: [4096]u8; entity_host_navigation: bool; +entity_host_game: bool; entity_paste: [16384]u8; EntityHostText :: (text: string) -> HostValue { @@ -62,10 +63,9 @@ EntityHostServices :: (context: *void, module: *u8, function: *u8, arguments: *H EntityFree(profile_document) state := account_profile state.host_navigation = entity_host_navigation - state.controls |= ENTITY_INTENTION + if entity_host_game { state.controls = ENTITY_NODES } state.extensions = .{} state.extension_count = 0 - if DewReady() { unused EntityAddExtension(*state, "dew", "Dew") } profile_document = EntityEncode(state) output := arguments[1] if output.kind != cast(s32)HostValueKind.HostSlice || output.elements == null || output.length <= cast(usize)profile_document.count { return 0 } @@ -94,6 +94,7 @@ EntityHostAssetAllowed :: (path: string) -> bool { EntityHostOpen :: (bytes: string, root: string, client_id: string, host_navigation: bool = false) -> bool { entity_host_navigation = host_navigation + entity_host_game = client_id == "arcade" if !AccountStoreStartAt(root, client_id) || !CopyCString(root, asset_folder[:]) { return false } portable = AppContext.{.expected_id = "entity", .allows = EntityHostAllows, .services = EntityHostServices, .widgets = WidgetHostCall} diff --git a/tests/management_test.zi b/tests/management_test.zi index 58708b8..2e17888 100644 --- a/tests/management_test.zi +++ b/tests/management_test.zi @@ -136,6 +136,9 @@ Check :: () -> s32 { address := NativeJoin(path[:], NativeRoot(root[:]), "atomic.txt") if !NativeWrite(address, "old") || !NativeWrite(address, "new") || NativeRead(address, document[:]) != 3 || TextUntilNul(document[:]) != "new" { return 29 } if !AccountStoreStart() { return 31 } + installation := account_client_id + if TextUntilNul(installation[:]).count != 32 { return 47 } + if !AccountStoreStart() || TextUntilNul(account_client_id[:]) != TextUntilNul(installation[:]) { return 48 } unused CopyCString("Before switch", account_profile.name[:]) if AccountStoreApply(null, *fixture, 0) != 2 || account_standalone_ready { return 32 } if AccountStoreApply(null, *fixture, 1) != 1 || TextUntilNul(account_profile.name[:]) != "Fixture profile" { return 33 } @@ -147,6 +150,10 @@ Check :: () -> s32 { unused CopyCString("logout", action.operation[:]) if AccountStoreAction(null, *action) != 1 || account_standalone_ready || account_profile.name[0] == cast(u8)0 { return 35 } if !AccountStoreStart() || account_standalone_ready || account_profile.name[0] == cast(u8)0 { return 36 } + value: [64]u8 + if !DewFormat(12345678, DewUnits, value[:], "Dew") || TextUntilNul(value[:]) != "12.345678 Dew" { return 49 } + if !DewFormat(12000000, DewUnits, value[:]) || TextUntilNul(value[:]) != "12" { return 50 } + if DewFormat(-1, DewUnits, value[:]) { return 51 } // Dew accepts node-priced integer balances only for the current account. account_recovery = fixture account_standalone_ready = true diff --git a/ziran.lock b/ziran.lock index 24b00fe..c79ab98 100644 --- a/ziran.lock +++ b/ziran.lock @@ -36,9 +36,9 @@ "url": "https://github.com/ziranlang/oqs.git" }, { - "commit": "6b9fed32f5368917deb4b5161fc8b4e9b32588ed", + "commit": "f4b41d137f9afaa593438af129d4665fe0e943c2", "dependencies": {"raylib": "p5a77c9c35110e925"}, - "id": "p88faf314c87eb03a", + "id": "p7c3ea7cca40fb156", "name": "kryon", "ref": "master", "url": "https://github.com/kryonlabs/kryon.git" @@ -62,7 +62,7 @@ } ], "root": { - "dependencies": {"daochi_client": "pb64e76ded5e7220b", "kryon": "p88faf314c87eb03a", "monocypher": "p4266498010aa1745", "qrcode": "p0dfa70137405b096"}, + "dependencies": {"daochi_client": "pb64e76ded5e7220b", "kryon": "p7c3ea7cca40fb156", "monocypher": "p4266498010aa1745", "qrcode": "p0dfa70137405b096"}, "name": "Entity" }, "toolchain": { diff --git a/ziran.toml b/ziran.toml index 5265f44..c7512bf 100644 --- a/ziran.toml +++ b/ziran.toml @@ -15,12 +15,14 @@ module_aliases = { FileDialogLinux = "file_dialog_linux" } [exports] model = "src/model.zi" dew_model = "src/dew_model.zi" +dew_view = "src/dew_view.zi" node_url = "src/node_url.zi" management = "src/management.zi" recovery = "src/recovery.zi" native_files = "src/native_files.zi" native_management = "src/native_management.zi" native_host = "src/native_host.zi" +browser_host = "src/browser_host.zi" pairing = "src/pairing.zi" pairing_client = "src/pairing_client.zi"