57 Commits
Author SHA1 Message Date
waozi 48bfea6ee5 Add Simple Calendar and include Task Manager package 2026-11-21 13:41:03 -03:00
waozi 6b3ce6ce58 Update Werkzeug account and clipboard feedback 2026-11-20 01:57:32 -03:00
waozi 63006ba891 Give Werkzeug Gallery matching app artwork 2026-11-17 22:07:52 -03:00
waozi f38dcef65f Use Mesh client package and node naming throughout Werk 2026-11-17 16:52:16 -03:00
waozi 4d765e6348 Draw in Harmony's theme while embedded
Embedded in a host such as Harmony's Sessions window, Werkzeug reads the
host's palette at most every quarter second through Kryon's
ParentThemeLinux and builds its whole palette from it: surfaces, text
levels, borders, accent and controls, so every colour matches the host and
follows a theme change. Started on its own, it keeps the profile's
appearance. The expansion mirrors Kryon's SystemPaletteColors until Apps,
Entity, Workbook, Css and Auth move to that Kryon together.
2026-11-17 11:49:00 -03:00
waoziandClaude Opus 5.5 0f77bd6207 Copy Auth codes from the whole card and add transparent tool artwork
Auth (pinned in the first commit of this series) copies the current code as
plain digits when any part of a card is tapped; Edit stays separately
clickable and never touches the clipboard. auth-gui-test taps six points
of a card, then checks Edit, Cancel and the code shown afterwards.

The five colorful tool icons are lossless WebPs with transparent
backgrounds.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:42 -03:00
waoziandClaude Opus 5.5 0e718b1fff Add Gallery, a local photo browser for desktop and Android
Gallery is a separate portable tool: it browses local folders and albums,
opens a photo, moves between pictures and zooms. Werkzeug keeps the
folder grant in its private data and serves only Gallery; navigation
never leaves the granted root, and image bytes and pixels are bounded.
On Android it reads through the Storage Access Framework, read-only.
Nothing is synced.

Gallery has its own Linux launcher and icon, is bundled in the APK and on
the web build, and is covered by gallery-test (native fixtures),
gallery-gui-test (private Xvfb) and gallery-android-test (private
emulator).

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:42 -03:00
waoziandClaude Opus 5.5 8096256580 Read the account picture back while Profile is closed
Werkzeug started the background picture reader only while Profile was
open or a local picture was waiting to be sent. Sync-enabled accounts
now start it automatically. A received picture replaces the local one
only when no local choice is still waiting for the node, and the shared
native profile is updated with it, so Entity does not load an older
picture over it.

entity-account-test drives the normal background pump against a private
HTTP fixture (challenge, signed login, picture) with Profile closed.
gui-test extracts and decodes all 17 bundled Entity picture resources.
docs/development.md describes both diagnostics and what they do not
establish.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:41 -03:00
waoziandClaude Opus 5.5 aa6cc16955 Run Android input and document tests on a private emulator
scripts/private-emulator.py owns a disposable headless API 31 emulator.
android_startup.py launches Werkzeug and waits for visible Home; it waits
out only the System UI "isn't responding" dialog, so an app ANR still
fails. Its regression tests run in make test. The input, profile and
Workbook document-picker tests use it, find controls by text or content
description, and allow a cold system picker more time.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:41 -03:00
waoziandClaude Opus 5.5 d047174079 Run Android on Kryon's NativeActivity host without raylib
Kryon's android_run owns NativeActivity lifecycle, touch, IME, density
and software presentation; Werkzeug draws each frame through
ProjectFrame and wraps android_main to save its apps on exit. Werkzeug's
own android_jni.zi is replaced by kryon/android_jni.

The NDK build links kryon_android_codecs (WebP and AVIF) instead of
raylib and compiles Kryon's APK fopen reader. APK files are read through
that reader, and an Android image cache keeps decoded pixels within a
fixed budget for the Pixmap renderer. Java text is converted through
explicit UTF-8, so NUL and supplementary characters survive. While an
EditText is editing, hardware keys go to it instead of the native queue.

RAYLIB_DIR is gone from the Makefile, the Gradle environment and the
release workflow.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:41 -03:00
waoziandClaude Opus 5.5 1b283cb00b Build Werkzeug on Kryon 0.4 and Ziran 0.6
Pin Kryon 3f724419 (after 0.4.0) with the Ziran it pins, e0367fa9
(after v0.6.0, with the Wasm record-copy fix the browser build needs),
and Apps 0d726f2a, Entity 9414cb89, Auth e5a72371 and Workbook 020c9322.
Every package now pins that same Kryon and Ziran, so the lock holds one
Kryon copy.

Kryon 0.4 removed the Widgets and Desktop modules. Werkzeug's screens,
tools and tests import Kryon's public widget modules (kryon/box,
kryon/text, kryon/button, kryon/text_field, ...) and call their qualified
Draw and Props names. The desktop and browser loops take keys with
DesktopInputTake and CanvasInputTake; screenshots come from kryon/Cairo.

Bundles build in project mode with package-qualified entries instead of
hand-written module paths, and Apps' build-ui.py builds the shared
controller. Its reviewed digest is now 3292387c. scripts/ziran.sh runs
the compiler in the caller's directory, so app-logic-test builds Auth's
tests in Auth's own project, and package lookups no longer inherit make's
flags. Private-display fixtures get their own HOME and XDG folders, and
the OCR checks read antialiased labels before thresholding.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:41 -03:00
waozi 04a02ce1b1 Use Auth cards with next-code previews and countdown bars 2026-11-16 01:44:19 -03:00
waozi 6ab96ea56c Update Werk artwork, packaging and package dependencies 2026-11-07 21:42:16 -03:00
waozi 8e445a64d8 Preserve Workbook Android failure diagnostics 2026-11-07 21:03:16 -03:00
waozi 3343ad6261 Remove obsolete KSS source dependency wildcard 2026-11-07 19:11:51 -03:00
waozi c961ebb430 Pin Entity and Kryon with passphrase backups and the Continue as crash fix 2026-11-02 10:38:16 -03:00
waozi 685c419dd4 Resolve locked WebP sources for Android builds 2026-11-02 05:10:27 -03:00
waozi 73caeb9a35 Unify Entity profile dependencies and correct password masking 2026-11-02 04:55:13 -03:00
waozi cf2a2efc58 Permit D8 account handoff API outlines in APK validation 2026-11-02 00:05:06 -03:00
waozi 8c3070cb17 Update shared profile and validate current account controls 2026-11-01 23:40:29 -03:00
waozi f830878a78 Connect Werkzeug to shared Android account consent 2026-11-01 22:08:36 -03:00
waozi 52dcef68e7 Skip the sign-out backup warning once the key is backed up 2026-11-01 20:47:06 -03:00
waozi 250bbd2a35 Open newer account backups and build with ML-KEM for device links 2026-11-01 20:03:27 -03:00
waozi 6a32976e9f Offer and keep Entity's abstract profile pictures
Werkzeug unpacked only Entity's Kryon pictures, so the Abstract tab of
Entity's picture picker had nothing to draw, and the profile bridge dropped
the picture kind, so an abstract choice reverted. Werkzeug now unpacks all
of Entity's pictures, keeps the kind, publishes it in Entity's numbers and
shows an abstract picture on the home screen.

Entity is pinned at its node picture reader; the lock follows Kryon master,
which changes the Apps controller bundle, so its digest is re-pinned from
the locked build.
2026-10-30 00:57:32 -03:00
waozi a2a7b97f7c Pin the Apps controller built with Kryon edffc8bf
The Entity lock bump moved Kryon, which changes the shared Apps controller
bundle; this is its digest from the locked build.
2026-10-29 23:16:09 -03:00
waozi 98d732c367 Send the chosen profile picture to the node through Entity
Werkzeug kept its profile picture on this device only, so friends saw a
default picture. A picture chosen in Profile now goes to the account's
node through Entity's shared publisher, retrying while offline, and is
sent once per choice. Profiles saved earlier with a picture other than
the first count it as chosen.
2026-10-29 23:05:13 -03:00
waozi 0199559631 Check that the Android APKs hold no Google library
Kryon's google-free action fails the release build when a Gradle file
names a Google library outside a Google Play edition or an APK holds one.
2026-10-29 16:10:51 -03:00
waozi 2a38d480a4 Wait for Workbook UI updates in platform tests 2026-10-28 14:56:37 -03:00
waozi 53cb190de7 Cover Workbook transfers on the Google Android emulator 2026-10-28 14:32:39 -03:00
waozi b2ddcb69a8 Keep bundle runtime caches matched to their toolchain 2026-10-28 13:15:42 -03:00
waozi a69631e327 Release Werkzeug 0.4.7 with Workbook on every platform 2026-10-28 12:56:43 -03:00
waozi dd550dd58b Verify the shared profile document without confusing favicon requests 2026-10-28 04:19:25 -03:00
waozi 36fd01fe5d Open the shared browser profile after the active tool has saved 2026-10-28 04:07:42 -03:00
waozi 0cb5600c14 Load the shared browser profile from the Ziran host 2026-10-28 03:54:01 -03:00
waozi ead336b215 Format the shared browser profile readiness condition 2026-10-28 03:48:57 -03:00
waozi 6cea9233ef Use the shared Waozi browser profile and Entity manager 2026-10-28 03:48:29 -03:00
waozi fbd7c4038a Select the Add action below the node input in Android tests 2026-10-27 03:52:56 -03:00
waozi 7bfa8fef2b Follow the shared Profile Nodes flow in the Android test 2026-10-27 03:08:45 -03:00
waozi bee76ab379 Read small dark-theme labels in the Android input test 2026-10-27 02:51:21 -03:00
waozi d8284a83e0 Pin the Apps controller built with Kryon 0931212f
Werkzeug 0.4.6 moved Kryon with Entity ca637d0, which changes the shared
Apps controller bundle; this is its digest from the locked build.
2026-10-27 02:19:43 -03:00
waozi f2dad4b37f Release Werkzeug 0.4.6
Entity ca637d0 saves account aliases typed with capitals, an @ or spaces
and says when an alias is taken.
2026-10-27 02:03:08 -03:00
waozi 40f2cdf731 Retry Android SDK downloads across build workflows 2026-10-26 20:06:30 -03:00
waozi b193cbfa9f Fix Android native app startup with private runtime directories 2026-10-26 19:46:29 -03:00
waozi 4e139b3ffb Identify Android controller integrity failures 2026-10-26 19:25:17 -03:00
waozi a5e69bb227 Report Android Apps controller startup failures 2026-10-26 18:04:35 -03:00
waozi b0003dc032 Capture private emulator asset diagnostics on test failure 2026-10-26 17:47:14 -03:00
waozi e26d26f5db Fix workflows for the root web app and retry Android SDK setup 2026-10-26 17:29:40 -03:00
waozi a45fd1d3ed Open the card embed page beside the root app in the browser test 2026-10-26 02:47:32 -03:00
waozi 2e5d765962 Check the site's root app files in the Pages build 2026-10-26 02:38:57 -03:00
waozi 4d499720d8 Make werk.waozi.xyz the web app itself
The site serves Werkzeug at its root instead of a separate landing page;
/app/ forwards there and download links keep their addresses. Browser
storage is per origin, so saved vaults stay.
2026-10-26 02:32:31 -03:00
waozi ae502a322d Build Auth from its package and hash with the crypto package: manifest, lock, Makefile, Pass, the host, tests, Android sources and docs 2026-10-24 23:43:18 -03:00
waozi 1a4e0e0891 Auth comes from its own Ziran package (waozixyz/auth) and SHA-256 and PBKDF2 from the crypto package, replacing apps/auth and shared/; Pass keeps reading at most 508 salt bytes, as existing vault keys need 2026-10-24 23:43:05 -03:00
waozi 3b8c4eaf64 Use Kryon shared app and render stages on Android
Compose Werkzeug frames through the shared Android pipeline and drain it before closing app state. Preserve the native linker callbacks during source generation. Pin the verified Kryon and Ziran revisions and the regenerated Apps controller validated by its native behavior fixture.
2026-10-24 06:40:35 -03:00
waozi 60a68d258a Add the Werkzeug 0.4.4 build to the F-Droid recipe
Matches fdroiddata merge request 53909. New release tags are added by
F-Droid's update checker, which copies this build for each tag.
2026-10-24 02:17:58 -03:00
waozi 0a2ab3bb45 Show only the tools as large tiles in mini mode
The ?mini embed and desktop --mini now open on the tool tiles alone, with no
Profile, search or title bar. Opening a tool keeps its bar with Back, which
returns to the tiles. Mini mode is read with Kryon's shared mini_embed.
2026-10-24 02:04:09 -03:00
waozi b9a6c6d350 Remove the Plan 9 build of the pass command 2026-10-23 22:10:21 -03:00
waozi b53050764b Keep F-Droid dependency handling upstream 2026-10-23 20:54:23 -03:00
171 changed files with 7979 additions and 4357 deletions

No files matched your search

+36 -20
View File
@@ -52,11 +52,19 @@ jobs:
env:
WERK_WEB_BROWSER: google-chrome
run: make web-smoke
- name: Upload browser failure diagnostics
if: failure()
uses: actions/upload-artifact@v4
with:
name: werk-browser-diagnostics-ci
path: build/web-test/*.png
if-no-files-found: ignore
- name: Verify generated site
run: |
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/index.wasm
test -s build/site/index.wasm
test -s build/site/sw.js
test -s build/site/assets.json
- name: Check fastlane metadata
run: |
set -eu
@@ -110,7 +118,8 @@ jobs:
path: |
build/werk
build/apps
build/pfp.png
build/pfp.webp
build/tools
if-no-files-found: error
build-android:
@@ -142,15 +151,12 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'shared/*.zi', 'apps/*/*.zi', 'droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'ziran.lock') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'apps/*/*.zi', 'droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Build debug APK
run: |
set -euo pipefail
@@ -158,10 +164,22 @@ jobs:
make android-debug
android-input-test:
name: Android NativeActivity input
name: ${{ matrix.name }}
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
strategy:
fail-fast: false
matrix:
include:
- name: Android NativeActivity input
api: 30
image: default
test: android-profile-test
- name: Workbook Android documents
api: 35
image: google_apis
test: workbook-android-test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
@@ -170,15 +188,12 @@ jobs:
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh 'platforms;android-${{ matrix.api }}'
- name: Install screenshot OCR
run: |
sudo apt-get update
sudo apt-get install -y tesseract-ocr
sudo apt-get install -y tesseract-ocr python3-pil
# Without /dev/kvm access the emulator runs unaccelerated and is too
# slow to answer input before Android reports it not responding.
- name: Enable KVM for the emulator
@@ -189,16 +204,17 @@ jobs:
- name: Run Android input tests
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 30
api-level: ${{ matrix.api }}
arch: x86_64
target: default
target: ${{ matrix.image }}
emulator-boot-timeout: 900
emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -no-metrics
script: make android-emulator android-input-test
script: make android-emulator ${{ matrix.test }}
- uses: actions/upload-artifact@v4
if: failure()
with:
name: android-input-test-reports
name: android-input-test-reports-${{ matrix.api }}
path: |
build/android-input/
build/workbook-android-test/
if-no-files-found: ignore
+1 -3
View File
@@ -21,9 +21,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
sdkmanager="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$sdkmanager" --licenses >/dev/null || true
"$sdkmanager" 'platforms;android-36' 'build-tools;34.0.0' 'ndk;28.2.13676358' 'cmake;3.22.1'
bash scripts/install_android_sdk.sh
- name: Prepare preserved release key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
+12 -11
View File
@@ -73,7 +73,7 @@ jobs:
run: |
name="werk-linux-${{ matrix.arch }}"
mkdir -p "build/release/$name"
cp -R build/werk build/apps build/pfp.png LICENSE README.md assets/app/icon.png "build/release/$name/"
cp -R build/werk build/apps build/pfp.webp build/tools LICENSE README.md assets/app/icon.png "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
make package-deb
- name: Package AppImage
@@ -124,15 +124,12 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'shared/*.zi', 'apps/*/*.zi', 'ziran.lock') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'apps/*/*.zi', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Prepare Android signing key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
@@ -152,7 +149,6 @@ jobs:
chmod +x droid/gradlew
export KRYON_DIR="$(./scripts/ziran.sh pkg path Kryon --locked)"
export ZIRAN_ROOT="$(./scripts/ziran.sh pkg path ziran --locked)"
export RAYLIB_DIR="$(./scripts/ziran.sh pkg path raylib --locked)/src"
export LIBOQS_DIR="$(./scripts/ziran.sh pkg path liboqs --locked)"
export MONOCYPHER_DIR="$(./scripts/ziran.sh pkg path monocypher --locked)"
./droid/gradlew -p droid assembleRelease \
@@ -176,6 +172,12 @@ jobs:
test -s "build/release/werk-$VERSION.apk"
test -s "build/release/werk-$VERSION-arm64-v8a.apk"
test -s "build/release/werk-$VERSION-armeabi-v7a.apk"
# Only a Google Play edition may hold a Google library, in its build
# files as in its APK.
- name: Keep Google libraries out of the APKs and their build files
uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
with:
packages: build/release/werk-android*.apk
- uses: actions/upload-artifact@v4
with:
name: android
@@ -202,11 +204,10 @@ jobs:
cd build/site
zip -qr ../werk-web.zip .
# The whole app folder: its page loads content-hashed script and
# The site root is the app: its page loads content-hashed script and
# Wasm names, and the service worker caches the files in assets.json.
mkdir -p ../werk-html5
cp -R app/. ../werk-html5/
cp -R icons/. ../werk-html5/icons/
cp -R . ../werk-html5/
sed -i \
-e 's#href="/manifest.webmanifest"#href="manifest.webmanifest"#g' \
-e 's#href="/icons/#href="icons/#g' \
+2 -2
View File
@@ -46,8 +46,8 @@ jobs:
set -euo pipefail
make site
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/index.wasm
test -s build/site/index.wasm
test -s build/site/sw.js
- name: Install screenshot OCR
run: |
sudo apt-get update
+3
View File
@@ -5,3 +5,6 @@
__pycache__/
*.pyc
.wrangler/
/backup/
/work/
/apps/*/build/
+7 -6
View File
@@ -5,12 +5,13 @@ first.
## Tools are separate apps
- Each tool lives in `apps/<tool>/` and builds into its own bundle,
`build/apps/<tool>.zx`. A tool reaches the host only through
`shared/werk_app.zi`; the host (`src/apps.zi`) checks every call a
bundle asks for and keeps each tool's files, assets and secret separate.
- Tools never import another tool's modules. Code two tools need goes in
`shared/`, as SHA-256 and PBKDF2 do.
- Each tool builds into its own bundle, `build/apps/<tool>.zx`: Pass,
Calculator and Clock from `apps/<tool>/`, Auth and Workbook from their own
Ziran packages. The host (`src/apps.zi`) checks every call a bundle asks
for and keeps each tool's files, assets and secret separate.
- Tools never import another tool's modules. Code two tools need comes from
a Ziran package, as SHA-256 and PBKDF2 come from `crypto`; no git
submodules.
- Keep the host interface small and generic (files, clock, clipboard,
key derivation, device secret, input). A new host call needs a new host
build before any bundle can use it.
+37
View File
@@ -1,5 +1,42 @@
# Changelog
## [Unreleased]
- Add Simple Calendar with Month, Week and Agenda views, recurring events, search and private local storage.
- Include Task Manager from its separate `kryonlabs/taskmgr` package with live process monitoring, filtering, sorting, task termination, command launch and performance graphs.
- Show a brief confirmation when Auth copies a code to the clipboard.
- Show your account username in the top-right profile button.
- Give Gallery matching artwork on Werkzeug Home and an icon in the Linux window switcher.
- Use Mesh account sync and client imports while keeping existing account keys and Werkzeug data compatible.
- Embedded in Harmony's Sessions window, Werkzeug draws every colour from Harmony's theme and follows its changes; started on its own it keeps its own appearance.
- Tap the whole Auth card to copy the current code as plain digits, while keeping Edit and the next-code preview.
- Browse local photo folders and albums with Gallery on desktop and Android.
- Remove the backgrounds from the five colorful tool icons.
- Read the account picture back from the node without replacing a local choice still waiting to sync.
- Auth shows grouped codes and the next code on clean cards, with a purple countdown line that turns orange halfway through.
- Password fields in Profile start empty and show one mask character for each character you type.
- Continue with an account already signed in to another Waozi app on Android, after approving the transfer there.
- Signing out skips the backup warning once this account's key is backed up.
- Open the newer account backups other waozi apps save.
- Send the profile picture you choose to your node, so friends see it in every app.
- Offer Entity's abstract profile pictures, like every other app, and keep the one you choose.
- Continue as no longer crashes the other app when it was closed.
- A fresh look: colorful artwork for each tool on Home, rounded tiles and softly tinted buttons that follow your accent color.
## [0.4.7] - 2026-10-28
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
## [0.4.6] - 2026-10-27
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
## [0.4.5] - 2026-10-26
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
## [0.4.4] - 2026-10-23
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
+126 -61
View File
@@ -2,24 +2,33 @@
ZIRAN ?= ./scripts/ziran.sh
# Gradle invokes make again for portable bundles. Inherited environment
# variables otherwise export these shell-derived paths while resolving them.
unexport ZIRAN_ROOT KRYON_DIR RAYLIB_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR ENTITY_DIR APPS_DIR
unexport ZIRAN_ROOT KRYON_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR TASKMGR_DIR ENTITY_DIR APPS_DIR AUTH_DIR CRYPTO_DIR
# Local overrides refer to the real root repositories. Published builds
# require the exact versions recorded in the committed lock.
LOCK_FLAGS := $(if $(wildcard ziran.local.toml),,--locked)
ZIRAN_ROOT = $(shell $(ZIRAN) pkg path ziran $(LOCK_FLAGS))
KRYON_DIR = $(shell $(ZIRAN) pkg path kryon $(LOCK_FLAGS))
RAYLIB_DIR = $(shell $(ZIRAN) pkg path raylib $(LOCK_FLAGS))/src
MINGCUTE_DIR = $(shell $(ZIRAN) pkg path mingcute $(LOCK_FLAGS))
# Package resolution may build its compiler. Do not pass this make's target
# overrides or jobserver descriptors to that independent package build.
PACKAGE_ZIRAN = env -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(ZIRAN)
ZIRAN_ROOT = $(shell $(PACKAGE_ZIRAN) pkg path ziran $(LOCK_FLAGS))
KRYON_DIR = $(shell $(PACKAGE_ZIRAN) pkg path kryon $(LOCK_FLAGS))
MINGCUTE_DIR = $(shell $(PACKAGE_ZIRAN) pkg path mingcute $(LOCK_FLAGS))
# Account sync: ML-DSA-44 account keys from liboqs, and Ed25519, X25519,
# BLAKE2b and XChaCha20-Poly1305 from Monocypher.
LIBOQS_DIR = $(shell $(ZIRAN) pkg path liboqs $(LOCK_FLAGS))
MONOCYPHER_DIR = $(shell $(ZIRAN) pkg path monocypher $(LOCK_FLAGS))
QRCODE_DIR = $(shell $(ZIRAN) pkg path qrcode $(LOCK_FLAGS))
WORKBOOK_DIR = $(shell $(ZIRAN) pkg path workbook $(LOCK_FLAGS))
ENTITY_DIR = $(shell $(ZIRAN) pkg path entity $(LOCK_FLAGS))
APPS_DIR = $(shell $(ZIRAN) pkg path apps $(LOCK_FLAGS))
LIBOQS_DIR = $(shell $(PACKAGE_ZIRAN) pkg path liboqs $(LOCK_FLAGS))
MONOCYPHER_DIR = $(shell $(PACKAGE_ZIRAN) pkg path monocypher $(LOCK_FLAGS))
QRCODE_DIR = $(shell $(PACKAGE_ZIRAN) pkg path qrcode $(LOCK_FLAGS))
WORKBOOK_DIR = $(shell $(PACKAGE_ZIRAN) pkg path workbook $(LOCK_FLAGS))
TASKMGR_DIR = $(shell $(PACKAGE_ZIRAN) pkg path taskmgr $(LOCK_FLAGS))
ENTITY_DIR = $(shell $(PACKAGE_ZIRAN) pkg path entity $(LOCK_FLAGS))
APPS_DIR = $(shell $(PACKAGE_ZIRAN) pkg path apps $(LOCK_FLAGS))
# Auth is its own package; SHA-256 and PBKDF2 come from the crypto package.
AUTH_DIR = $(shell $(PACKAGE_ZIRAN) pkg path auth $(LOCK_FLAGS))
CRYPTO_DIR = $(shell $(PACKAGE_ZIRAN) pkg path crypto $(LOCK_FLAGS))
# Qualified entries retain each package's import aliases while using the
# consumer's locked compiler, UI library and runtime.
PACKAGE_ID = $(shell python3 -c 'import json; print(json.load(open("ziran.lock"))["root"]["dependencies"]["$(1)"])')
LIBOQS_FLAGS := -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
-DOQS_USE_OPENSSL=OFF -DOQS_DIST_BUILD=OFF -DOQS_OPT_TARGET=generic '-DOQS_MINIMAL_BUILD=SIG_ml_dsa_44;KEM_ml_kem_768'
MONOCYPHER_SOURCES = $(MONOCYPHER_DIR)/src/monocypher.c $(MONOCYPHER_DIR)/src/optional/monocypher-ed25519.c
CC ?= cc
BIN_DIR ?= $(HOME)/bin
@@ -28,15 +37,15 @@ DESKTOP_DIR ?= $(shell xdg-user-dir DESKTOP 2>/dev/null)
# The tool bundles and Werkzeug's other files.
LIB_DIR ?= $(HOME)/.local/lib/werk
WEB_CC ?= $(if $(wildcard $(HOME)/emsdk/upstream/emscripten/emcc),$(HOME)/emsdk/upstream/emscripten/emcc,emcc)
SOURCES := $(wildcard src/*.zi shared/*.zi apps/*/*.zi)
LIBRARY_SOURCES = $(wildcard $(KRYON_DIR)/src/ui/*.zi $(KRYON_DIR)/src/ui/*/module.zi $(KRYON_DIR)/src/kss/*.zi $(KRYON_DIR)/src/backend/*.zi $(KRYON_DIR)/src/backend/*/module.zi $(ZIRAN_ROOT)/std/*.zi)
SOURCES := $(wildcard src/*.zi apps/*/*.zi)
LIBRARY_SOURCES = $(wildcard $(KRYON_DIR)/src/ui/*.zi $(KRYON_DIR)/src/ui/*/module.zi $(KRYON_DIR)/src/backend/*.zi $(KRYON_DIR)/src/backend/*/module.zi $(ZIRAN_ROOT)/std/*.zi)
ZIRAN_RUNTIME_SOURCES = $(wildcard $(ZIRAN_ROOT)/cmd/zir/*.[ch] $(ZIRAN_ROOT)/include/*.h)
ENTITY_SOURCES = $(wildcard $(ENTITY_DIR)/src/*.zi $(ENTITY_DIR)/assets/entity/*)
CFLAGS := -std=c99 -O2 -Wno-unused-variable -I$(ZIRAN_ROOT)/include
PROJECT := --project $(LOCK_FLAGS)
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
.PHONY: all apps portable-apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test entity-account-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage plan9-c
.PHONY: all apps portable-apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test entity-account-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage
all: cli gui
native: all
@@ -50,46 +59,62 @@ build/pass: build/generated/cli/.complete
cli: build/pass
cp build/pass pass
# Each app is its own bundle; Werkzeug runs them in one window. Workbook runs
# only in the Linux desktop app, so the web and Android apps leave it out.
APPS := pass auth calculator clock
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zx) build/apps/entity.zx build/apps/apps.zx
APP_BUNDLES := $(PORTABLE_BUNDLES) build/apps/workbook.zx
SHARED_SOURCES := $(wildcard shared/*.zi)
# Each app is its own bundle, shared by the desktop, web and Android hosts.
APPS := pass calculator clock calendar gallery
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zx) build/apps/auth.zx build/apps/entity.zx build/apps/apps.zx build/apps/workbook.zx build/apps/taskmgr.zx
APP_BUNDLES := $(PORTABLE_BUNDLES)
CRYPTO_SOURCES = $(wildcard $(CRYPTO_DIR)/src/*.zi)
APPS_UI_SOURCES = $(wildcard $(APPS_DIR)/src/*.zi $(APPS_DIR)/ui/*.zi $(APPS_DIR)/ui/locales/*.json)
APP_MODULE_PATHS = --module-path shared --module-path kryon=$(KRYON_DIR)/src/backend --module-path kryon=$(KRYON_DIR)/src/ui --module-path $(KRYON_DIR)/src/ui --module-path $(MINGCUTE_DIR)/src --module-path $(ZIRAN_ROOT)/std
apps: $(APP_BUNDLES)
portable-apps: $(PORTABLE_BUNDLES)
# Compile the shared screen with the host's compiler and UI library. The
# reviewed payload must match both the build pin and the native host pin.
build/apps/apps.zx: $(APPS_UI_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock apps-controller.sha256 Makefile scripts/ziran.sh
mkdir -p $(@D)
python3 '$(APPS_DIR)/scripts/generate-ui-locales.py' --check
$(ZIRAN) bundle --root $(APPS_DIR)/ui --module-path $(APPS_DIR)/src $(APP_MODULE_PATHS) \
--define KRYON_HOSTED_UI --entry apps:Main -o $@ $(APPS_DIR)/ui/apps.zi
sha256sum $@ | cut -d ' ' -f 1 > $(@D)/apps.sha256
python3 '$(APPS_DIR)/scripts/build-ui.py' --project $(CURDIR) --output $(abspath $(@D)) \
--compiler $(if $(findstring /,$(ZIRAN)),$(abspath $(ZIRAN)),$(ZIRAN))
test "$$(cat $(@D)/apps.sha256)" = "$$(cat apps-controller.sha256)"
.SECONDEXPANSION:
build/apps/%.zx: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
build/apps/%.zx: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle --root . --module-path apps/$* $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
$(ZIRAN) bundle $(PROJECT) --root . --define KRYON_HOSTED_UI --define WERK_APP \
$(if $(wildcard apps/$*/assets),--asset-dir assets=apps/$*/assets) --entry $*:Main -o $@ apps/$*/$*.zi
build/apps/auth.zx: $(wildcard $(AUTH_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(AUTH_DIR)/src --define KRYON_HOSTED_UI --define WERK_APP \
--entry $(call PACKAGE_ID,auth)_auth:Main -o $@ $(AUTH_DIR)/src/auth.zi
build/apps/workbook.zx: $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle --root $(WORKBOOK_DIR) --module-path $(WORKBOOK_DIR)/src $(APP_MODULE_PATHS) \
--module-path kryon=$(KRYON_DIR)/src/backend --define KRYON_HOSTED_UI --entry app:Main -o $@ $(WORKBOOK_DIR)/src/app.zi
$(ZIRAN) bundle $(PROJECT) --root $(WORKBOOK_DIR)/src \
--define KRYON_HOSTED_UI --entry $(call PACKAGE_ID,workbook)_app:Main -o $@ $(WORKBOOK_DIR)/src/app.zi
build/apps/entity.zx: $(ENTITY_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
build/apps/taskmgr.zx: $(wildcard $(TASKMGR_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle --root $(ENTITY_DIR) --module-path $(ENTITY_DIR)/src $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI \
--module-path qrcode=$(QRCODE_DIR)/src --asset-dir assets=$(ENTITY_DIR)/assets --entry entity:Main -o $@ $(ENTITY_DIR)/src/entity.zi
$(ZIRAN) bundle $(PROJECT) --root $(TASKMGR_DIR)/src \
--define KRYON_HOSTED_UI --entry $(call PACKAGE_ID,taskmgr)_hosted:Main -o $@ $(TASKMGR_DIR)/src/hosted.zi
# These portable apps use their public package exports. Their UI sources may
# advance independently; all bundles are emitted by this host's compiler.
build/apps/gallery.zx: $(wildcard apps/gallery/*.zi) apps/gallery/ziran.toml apps/gallery/ziran.lock ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root . --define KRYON_HOSTED_UI --entry gallery:Main -o $@ apps/gallery/gallery.zi
build/apps/entity.zx: $(ENTITY_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(ENTITY_DIR)/src --define KRYON_HOSTED_UI \
--asset-dir assets=$(ENTITY_DIR)/assets --entry $(call PACKAGE_ID,entity)_entity:Main -o $@ $(ENTITY_DIR)/src/entity.zi
# The portable bundle runtime the host links, built from the locked Ziran.
build/ziran/libziran.a: ziran.lock $(ZIRAN_RUNTIME_SOURCES)
.PHONY: runtime-cache-force
runtime-cache-force:
build/ziran/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/ziran)"
build/ziran/libziran.a: ziran.lock $(ZIRAN_RUNTIME_SOURCES) build/ziran/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
build/generated/desktop/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ENTITY_SOURCES) ziran.toml ziran.lock
build/generated/desktop/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(wildcard $(TASKMGR_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ENTITY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_DESKTOP --target=c --entry desktop:main -o $(@D) src/desktop.zi
@@ -102,9 +127,14 @@ build/werk: build/generated/desktop/.complete build/ziran/libziran.a build/liboq
build/generated/desktop/*.c $(MONOCYPHER_SOURCES) build/ziran/libziran.a build/liboqs/lib/liboqs.a \
$(shell pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo gtk+-3.0) -lX11 -l:libcurl.so.4 -lm -lpthread -o $@.new
mv -f $@.new $@
build/pfp.png: $(KRYON_DIR)/icons/pfp.png
build/pfp.webp: $(KRYON_DIR)/icons/pfp.webp
cp $< $@
gui: build/werk build/pfp.png apps
# Launcher artwork for the bundled tools, beside the host like pfp.webp.
TOOL_ICONS := $(wildcard assets/tools/*.webp)
build/tools/%.webp: assets/tools/%.webp
mkdir -p $(@D)
cp $< $@
gui: build/werk build/pfp.webp $(TOOL_ICONS:assets/%=build/%) apps
run: gui
./build/werk
@@ -123,37 +153,55 @@ lesspass-compat-test: cli
python3 scripts/lesspass_compat_test.py --cli ./pass
entity-account-test: build/liboqs/lib/liboqs.a
ZIRAN_BIN=$(ZIRAN) python3 scripts/entity_account_test.py
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test
.PHONY: android-sdk-install-test
android-sdk-install-test:
python3 scripts/install_android_sdk_test.py
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test android-sdk-install-test android-apk-check-test android-startup-test runtime-cache-test gallery-test
.PHONY: android-startup-test
android-startup-test:
python3 scripts/android_startup_test.py
.PHONY: android-apk-check-test
android-apk-check-test:
python3 scripts/android_apk_check_test.py
.PHONY: runtime-cache-test
runtime-cache-test:
python3 scripts/runtime_cache_test.py
gui-smoke: gui
sh scripts/gui_smoke.sh
gui-test: gui
python3 scripts/private-display.py python3 scripts/apps_gui_test.py
python3 scripts/private-display.py python3 scripts/calendar_taskmgr_gui_test.py
sh scripts/werk_gui_test.sh
python3 scripts/private-display.py python3 scripts/workbook_gui_test.py
python3 scripts/private-display.py python3 scripts/launcher_gui_test.py
WERK_TEST_ZIRAN="$(ZIRAN)" python3 scripts/private-display.py python3 scripts/launcher_gui_test.py
sh scripts/migration_test.sh
python3 -I scripts/auth_command_test.py
python3 scripts/private-display.py python3 scripts/auth_gui_test.py
# The bundle runtime for the browser, built from the locked Ziran.
WEB_AR ?= $(dir $(WEB_CC))emar
build/web-runtime/libziran.a: ziran.lock
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BOOTSTRAP=1 BUILD_DIR=$(abspath build/web-runtime) \
build/web-runtime/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/web-runtime)"
build/web-runtime/libziran.a: Makefile ziran.lock build/web-runtime/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BOOTSTRAP=0 BUILD_DIR=$(abspath build/web-runtime) \
GEN_ZI2C=$(ZIRAN_ROOT)/build/bin/zi2c BOOTSTRAP_BIN=$(ZIRAN_ROOT)/build/bootstrap/bin/zi2c \
CC=$(WEB_CC) AR=$(WEB_AR) OBJCOPY=true CFLAGS=-O2 $(abspath $@)
build/generated/browser/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
build/generated/browser/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(wildcard $(TASKMGR_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target=c -o $(@D) src/browser.zi
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target-os web --target-cpu wasm32 --target=c -o $(@D) src/browser.zi
touch $@
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(PORTABLE_BUNDLES) build/pfp.png assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(PORTABLE_BUNDLES) build/pfp.webp $(TOOL_ICONS) assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
mkdir -p $(@D)
$(WEB_CC) -O2 -Wno-parentheses-equality -I$(ZIRAN_ROOT)/include -iquote build/generated/browser build/generated/browser/*.c \
build/web-runtime/libziran.a \
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sEXPORTED_RUNTIME_METHODS=FS,IDBFS -lidbfs.js \
-sASYNCIFY -sALLOW_MEMORY_GROWTH=1 -sSTACK_SIZE=16777216 -sASYNCIFY_STACK_SIZE=1048576 -sENVIRONMENT=web \
--embed-file assets/fonts/NotoSans-Regular.ttf@/kryon-font.ttf \
$(foreach bundle,$(PORTABLE_BUNDLES),--embed-file $(bundle)@/apps/$(notdir $(bundle))) --embed-file build/pfp.png@/pfp.png --embed-file assets/app/icon.png@/icon.png -o $@
build/web-app/index.html: build/web-app/index.js web/site/app/index.html
cp web/site/app/index.html $@
$(foreach bundle,$(PORTABLE_BUNDLES),--embed-file $(bundle)@/apps/$(notdir $(bundle))) --embed-file build/pfp.webp@/pfp.webp --embed-file assets/tools@/tools --embed-file assets/app/icon.png@/icon.png -o $@
build/web-app/index.html: build/web-app/index.js web/site/index.html
cp web/site/index.html $@
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
@@ -171,39 +219,43 @@ web-smoke: site
# CMake emits JNI and foreign ABI types separately for each Android ABI.
android-debug: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-universal-debug.apk build/werk-android-debug.apk
python3 scripts/android_apk_check.py build/werk-android-debug.apk
cp droid/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/werk-android-arm64-v8a-debug.apk
cp droid/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/werk-android-armeabi-v7a-debug.apk
android-emulator: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-debug.apk build/werk-android-emulator.apk
python3 scripts/android_apk_check.py build/werk-android-emulator.apk
android-release: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
.PHONY: android-bundle
android-bundle: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
cp droid/app/build/outputs/bundle/release/app-release.aab build/werk-$(shell cat VERSION).aab
.PHONY: android-fdroid
# F-Droid owns signing and updates. Keep the same package/version as the
# reference release; the suffix belongs to the unsigned output filename.
# F-Droid compares this source build with the signed upstream release.
android-fdroid:
$(MAKE) android-release GRADLE_ARGS="$(GRADLE_ARGS) -PfDroidBuild=true"
cp droid/app/build/outputs/apk/release/app-universal-release-unsigned.apk build/werk-$(shell cat VERSION)-fdroid-unsigned.apk
python3 scripts/android_apk_check.py build/werk-$(shell cat VERSION)-fdroid-unsigned.apk
mkdir -p build/fdroid
cp droid/app/build/outputs/apk/release/app-universal-release-unsigned.apk build/fdroid/werk.apk
python3 scripts/android_apk_check.py build/fdroid/werk.apk
android-smoke:
bash scripts/android_smoke.sh
android-input-test:
$(MAKE) android-profile-test
$(MAKE) workbook-android-test
$(MAKE) gallery-android-test
.PHONY: android-profile-test workbook-android-test gallery-android-test
android-profile-test:
python3 scripts/android_input_test.py
# The pass command for Plan 9; transfer the checkout with build/plan9 and run mk.
plan9-c:
mkdir -p build/plan9
$(ZIRAN) build $(PROJECT) --define PLAN9_BUILD --target=plan9-c --entry cli:main -o build/plan9/cli apps/pass/cli.zi
workbook-android-test:
python3 scripts/workbook_android_test.py
gallery-android-test:
python3 scripts/android_gallery_test.py
check-package-urls:
bash scripts/check_package_urls.sh
@@ -219,7 +271,9 @@ install-gui: gui
install -m 0755 build/werk "$(BIN_DIR)/werk.new"
mv -f "$(BIN_DIR)/werk.new" "$(BIN_DIR)/werk"
install -m 0600 $(APP_BUNDLES) "$(LIB_DIR)/apps/"
install -m 0644 build/pfp.png "$(LIB_DIR)/pfp.png"
install -m 0644 build/pfp.webp "$(LIB_DIR)/pfp.webp"
install -d -m 0755 "$(LIB_DIR)/tools"
install -m 0644 $(TOOL_ICONS) "$(LIB_DIR)/tools/"
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" --bin-dir "$(BIN_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)")
install -m 0644 packaging/linux/werk-bundle.xml "$(DATA_DIR)/mime/packages/werk-bundle.xml"
@if command -v update-mime-database >/dev/null; then update-mime-database "$(DATA_DIR)/mime"; fi
@@ -234,3 +288,14 @@ package-deb: gui
./scripts/package-deb.sh
package-appimage: gui
./scripts/package-appimage.sh
.PHONY: gallery-test gallery-gui-test
gallery-test:
rm -rf build/gallery-test-generated
mkdir -p build/gallery-test-generated
$(ZIRAN) build $(PROJECT) --root . --target=c --entry gallery_test:Check -o build/gallery-test-generated tests/gallery_test.zi
printf '%s\n' '#include "tests/gallery_test.h"' 'int main(void) { return Check(); }' > build/gallery-test-generated/main.c
$(CC) -std=c11 -O2 -I$(ZIRAN_ROOT)/include -Ibuild/gallery-test-generated $$(find build/gallery-test-generated -name '*.c' -print) -o build/gallery-test
python3 scripts/gallery_gui_test.py --behavioral-only
gallery-gui-test: gui gallery-test
python3 scripts/private-display.py dbus-run-session -- python3 scripts/gallery_gui_test.py
+4 -3
View File
@@ -7,17 +7,18 @@
Small, private tools for everyday life. Generate passwords, manage sign-in
codes, calculate and keep time in one free, open-source app.
[Try it online](https://werk.waozi.xyz/app/)
[Try it online](https://werk.waozi.xyz/)
· [Download the latest release](https://github.com/waozixyz/werk/releases/latest)
· [What's new](CHANGELOG.md)
## Your everyday tools
- **Pass:** generate the same password from your site, login, master password and settings. Save profiles without keeping a password database.
- **Auth:** keep two-factor sign-in codes together. Import existing accounts, rename them and copy a code when you need it.
- **Auth:** keep two-factor sign-in codes together. Tap anywhere on a card to copy its current code, or use Edit to change the account.
- **Calculator:** everyday arithmetic and scientific functions, with a keypad or keyboard.
- **Clock:** see the local time and use a stopwatch that keeps running while the app is closed.
- **Workbook on Linux:** edit spreadsheets with sheet tabs, familiar menus and portable workbook files.
- **Workbook:** edit spreadsheets on Linux, Android and the web, with formulas, sheet tabs and portable workbook files.
- **Gallery:** browse local photo folders and albums on Linux and Android. Open a photo, move between pictures and zoom; your photos stay local.
<p align="center">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-pass.png" alt="Pass password generation" width="30%">
+1 -1
View File
@@ -1 +1 @@
0.4.4
0.4.7
+1 -1
View File
@@ -1 +1 @@
952db2717c6d8500aa9a4c29b78c3028a19821e11bf511f39471bf04cf02c6cd
7a9599b7e728333c237b2bf23cdf9fb985f4a3c82f9cc0ba4dd16434ac876c12
-632
View File
@@ -1,632 +0,0 @@
// Auth: two-factor sign-in codes. Each account is a synced record holding
// its otpauth link, so it follows the owner's Werkzeug account to their
// other devices; secrets are never shown again after adding.
#import "session"
#import "geometry"
#import "text_props"
#import "text_widget"
#import "text_input_props"
#import "text_field_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "box_props"
#import "box_widget"
#import "scroll_props"
#import "scroll_widget"
#import "tree"
#import "text_buffer"
#import "number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "totp"
#import "exports"
Icon :: #import "mingcute_regular_shield";
Edit :: #import "mingcute_regular_edit_2";
ACCOUNT_LIMIT :: 128
LIST_LIMIT :: 65536
// Copied codes clear from the clipboard after this many seconds.
CODE_CLEAR_SECONDS :: 30
VIEW_LIST :: 0
VIEW_ADD :: 1
VIEW_EDIT :: 2
FIELD_LINKS :: 1
FIELD_ISSUER :: 2
FIELD_NAME :: 3
FIELD_SECRET :: 4
FIELD_SITES :: 5
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
CachedCode :: struct {
step: s64
code: [12]u8
}
accounts: [ACCOUNT_LIMIT]Account;
codes: [ACCOUNT_LIMIT]CachedCode;
// Each account's record id, and whether its record is written.
record_ids: [ACCOUNT_LIMIT][33]u8;
recorded: [ACCOUNT_LIMIT]bool;
records_version: s32 = -1;
ids: [8192]u8;
account_count: s32;
loaded: bool;
view: s32;
focused: s32;
fields: [6]FieldState;
// A whole export fits: Aegis's JSON is about 250 bytes per account.
links: [65536]u8;
issuer: [64]u8;
name: [128]u8;
secret: [256]u8;
sites: [256]u8;
status: [128]u8;
// The account being edited, and whether its Remove was tapped once; a
// second tap removes it.
editing: s32 = -1;
remove_pending: bool;
list_scroll: s32;
store: [LIST_LIMIT]u8;
session: Session;
SetStatus :: (text: string) {
unused CopyLimited(text, status[:])
}
Clear :: (bytes: []u8) {
index: s64 = 0
while index < bytes.count {
bytes[index] = cast(u8)0
index += 1
}
}
// An account's record id comes from its link, so the same account added on
// two devices is one record. An edited account keeps its id.
SetRecordId :: (index: s32, link: string) {
unused RecordIdFor(link, record_ids[index][:])
}
// Writes the records of accounts added since the last save.
SaveAccounts :: () -> bool {
saved := true
index: s32 = 0
while index < account_count {
if !recorded[index] {
line: [1024]u8
{
link := LinkText(*accounts[index], line[:])
if link != "" {
if record_ids[index][0] == cast(u8)0 {
SetRecordId(index, link)
}
recorded[index] = RecordWrite(TextUntilNul(record_ids[index][:]), link)
}
}
Clear(line[:])
saved = saved && recorded[index]
}
index += 1
}
return saved
}
LoadAccounts :: () {
records_version = RecordsVersion()
// Accounts saved before records existed move into records once.
count := ReadStore("accounts.txt", store[:])
if count > 0 {
account_count = 0
unused AddExport(TextView(store[0:count]), false)
if SaveAccounts() {
unused WriteStore("accounts.txt", "")
}
}
Clear(store[:])
while account_count > 0 {
account_count -= 1
accounts[account_count] = Account.{}
record_ids[account_count][0] = cast(u8)0
}
listed := RecordList(ids[:])
start: s32 = 0
at: s32 = 0
while listed > 0 && at <= listed && account_count < ACCOUNT_LIMIT {
if at == listed || ids[at] == cast(u8)10 {
if at > start {
id := TextView(ids[start:at])
length := RecordRead(id, store[:])
account: Account
if length > 0 && ParseLink(TextView(store[0:length]), *account) {
accounts[account_count] = account
codes[account_count] = CachedCode.{.step = -1}
unused CopyLimited(id, record_ids[account_count][:])
recorded[account_count] = true
account_count += 1
}
account = Account.{}
Clear(store[0:ifx length > 0 then length else 0])
}
start = at + 1
}
at += 1
}
}
// The same secret gives the same codes, whatever the account is called.
SameAccount :: (left: *Account, right: *Account) -> bool {
return TextUntilNul(left.secret[:]) == TextUntilNul(right.secret[:])
}
// Adds the accounts of an export: otpauth links separated by spaces or line
// breaks, Google Authenticator's export links or Aegis's JSON. Returns how
// many were new.
AddExport :: (text: string, report: bool) -> s32 {
result := ReadExport(text)
added: s32 = 0
refused := result.skipped
found: s32 = 0
while found < result.count {
account := *export_accounts[found]
known := false
index: s32 = 0
while index < account_count {
if SameAccount(*accounts[index], account) {
known = true
}
index += 1
}
if !known && account_count >= ACCOUNT_LIMIT {
refused += 1
} else if !known {
accounts[account_count] = account.*
codes[account_count] = CachedCode.{.step = -1}
record_ids[account_count][0] = cast(u8)0
recorded[account_count] = false
account_count += 1
added += 1
}
found += 1
}
ClearExport()
if report {
number: [24]u8
message: [128]u8
used := AppendText(message[:], 0, "Added ")
used = AppendText(message[:], used, FormatInteger(cast(s64)added, number[:]))
used = AppendText(message[:], used, ifx added == 1 then " account" else " accounts")
if refused > 0 {
used = AppendText(message[:], used, ", skipped ")
used = AppendText(message[:], used, FormatInteger(cast(s64)refused, number[:]))
}
if result.encrypted {
used = AppendText(message[:], 0, "This export is encrypted; export it without a password")
}
SetStatus(TextView(message[0:used]))
}
return added
}
AddManual :: () -> bool {
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
if name[0] == cast(u8)0 && issuer[0] == cast(u8)0 {
SetStatus("Enter a name for the account")
return false
}
if !SetSecret(*account, TextUntilNul(secret[:])) {
SetStatus("The secret key is not valid Base32")
account = Account.{}
return false
}
account.issuer = issuer
account.name = name
if account_count >= ACCOUNT_LIMIT {
SetStatus("Auth holds at most 128 accounts")
account = Account.{}
return false
}
accounts[account_count] = account
codes[account_count] = CachedCode.{.step = -1}
record_ids[account_count][0] = cast(u8)0
recorded[account_count] = false
account_count += 1
account = Account.{}
return true
}
// Saves the edited name and websites. The account keeps its record id, so
// the change replaces it on every device.
SaveEdit :: () -> bool {
account := *accounts[editing]
if name[0] == cast(u8)0 && issuer[0] == cast(u8)0 {
SetStatus("Enter a name for the account")
return false
}
websites: [256]u8
if !NormalizeSites(TextUntilNul(sites[:]), websites[:]) {
SetStatus("Enter websites such as github.com, separated by spaces")
return false
}
account.issuer = issuer
account.name = name
account.sites = websites
recorded[editing] = false
if !SaveAccounts() {
SetStatus("Could not save the account")
return false
}
return true
}
RemoveAccount :: (index: s32) -> bool {
if recorded[index] && !RecordRemove(TextUntilNul(record_ids[index][:])) {
return false
}
position := index
while position + 1 < account_count {
accounts[position] = accounts[position + 1]
codes[position] = codes[position + 1]
record_ids[position] = record_ids[position + 1]
recorded[position] = recorded[position + 1]
position += 1
}
account_count -= 1
accounts[account_count] = Account.{}
codes[account_count] = CachedCode.{}
record_ids[account_count][0] = cast(u8)0
recorded[account_count] = false
return true
}
Unix :: () -> s64 {
return cast(s64)AppNow()
}
// The current code, computed once per time step.
Code :: (index: s32) -> string {
account := *accounts[index]
step := Unix() / cast(s64)account.period
if codes[index].step != step {
codes[index].step = step
unused CodeNow(account.kind, account.key[:], account.key_count, account.digits, account.period,
Unix(), codes[index].code[:])
}
return TextUntilNul(codes[index].code[:])
}
Label :: (key: u64, text: string, bounds: Rectangle, font: s32) {
Text(session, TextProps.{.key = key, .bounds = bounds, .text = text, .font = font,
.wrap = TextWrap.TextWrapEllipsis})
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props := ButtonProps.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) != 0
}
ApplyEdit :: (buffer: []u8, edit: TextFieldEdit) {
if !edit.changed {
return
}
length: s64 = 0
while length < buffer.count && buffer[length] != cast(u8)0 {
length += 1
}
if edit.start < 0 || edit.end < edit.start || cast(s64)edit.end > length {
return
}
used := length - cast(s64)(edit.end - edit.start) + edit.replacement.count
if used >= buffer.count {
return
}
tail := length - cast(s64)edit.end
if edit.replacement.count > cast(s64)(edit.end - edit.start) {
// Move the tail right, from its end.
index := tail - 1
while index >= 0 {
buffer[cast(s64)edit.start + edit.replacement.count + index] = buffer[cast(s64)edit.end + index]
index -= 1
}
} else {
index: s64 = 0
while index < tail {
buffer[cast(s64)edit.start + edit.replacement.count + index] = buffer[cast(s64)edit.end + index]
index += 1
}
}
index: s64 = 0
while index < edit.replacement.count {
buffer[cast(s64)edit.start + index] = edit.replacement[index]
index += 1
}
index = used
while index < buffer.count {
buffer[index] = cast(u8)0
index += 1
}
}
Field :: (id: s32, label: string, placeholder: string, buffer: []u8, bounds: Rectangle, secure: bool) {
state := *fields[id]
edit: TextFieldEdit
{
props := TextFieldProps.{.key = cast(u64)(500 + id), .focus_id = 500 + id, .bounds = bounds,
.label = label, .placeholder = placeholder, .value = TextUntilNul(buffer),
.cursor = state.cursor, .anchor = state.anchor, .scroll_x = state.scroll_x,
.focused = focused == id, .max_bytes = cast(s32)buffer.count - 1,
.max_codepoints = cast(s32)buffer.count - 1, .secure = secure}
// A secret shows as dots once typed; an empty field shows its hint.
if secure && buffer[0] != cast(u8)0 {
props.display_value = "••••••••"
}
if focused == id {
props.input = AppFieldInput()
}
result := TextField(session, props)
state.cursor = result.cursor
state.anchor = result.anchor
state.scroll_x = result.scroll_x
if result.focused {
focused = id
} else if focused == id {
focused = 0
}
edit = result.edit
}
ApplyEdit(buffer, edit)
}
// Opens an account's name, websites and Remove.
OpenEdit :: (index: s32) {
account := *accounts[index]
issuer = account.issuer
name = account.name
sites = account.sites
fields[FIELD_ISSUER] = FieldState.{}
fields[FIELD_NAME] = FieldState.{}
fields[FIELD_SITES] = FieldState.{}
editing = index
remove_pending = false
focused = 0
view = VIEW_EDIT
SetStatus("")
}
CloseEdit :: () {
Clear(issuer[:])
Clear(name[:])
Clear(sites[:])
editing = -1
remove_pending = false
focused = 0
view = VIEW_LIST
}
// One account: its name, current code (tap to copy), the seconds left and
// Edit.
DrawRow :: (index: s32, x: float32, y: float32, inner: float32, row: float32) {
account := *accounts[index]
Box(session, BoxProps.{.key = cast(u64)(1000 + index), .bounds = Rectangle.{x, y, inner, row - 8.0},
.radius = 10.0})
title := TextUntilNul(account.issuer[:])
subtitle := TextUntilNul(account.name[:])
if title == "" {
title = subtitle
subtitle = ""
}
text_width := inner - 210.0
Label(cast(u64)(2000 + index), title, Rectangle.{x + 12.0, y + 12.0, text_width, 22.0}, 16)
Label(cast(u64)(3000 + index), subtitle, Rectangle.{x + 12.0, y + 38.0, text_width, 18.0}, 12)
code := Code(index)
if Action(4000 + index, code, Rectangle.{x + inner - 196.0, y + 12.0, 140.0, 44.0}, false) {
if ClipboardCopy(code, CODE_CLEAR_SECONDS) {
SetStatus("Code copied; it clears in 30 seconds")
} else {
SetStatus("The clipboard is unavailable")
}
}
remaining := cast(s64)account.period - Unix() % cast(s64)account.period
number: [24]u8
// The seconds left, centred beside the code.
Label(cast(u64)(5000 + index), FormatInteger(remaining, number[:]),
Rectangle.{x + inner - 52.0, y + 27.0, 16.0, 18.0}, 12)
edit := ButtonProps.{.key = cast(u64)(6000 + index), .id = 6000 + index, .label = "Edit",
.bounds = Rectangle.{x + inner - 40.0, y + 16.0, 36.0, 36.0},
.icon_shape = Edit.Shape, .icon_only = true,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, edit) != 0 {
OpenEdit(index)
}
}
ListView :: (area: Rectangle, left: float32, width: float32) {
if Action(10, "Add account", Rectangle.{left, area.y + 12.0, width, 40.0}, true) {
view = VIEW_ADD
focused = 0
SetStatus("")
return
}
top := area.y + 64.0
height := area.height - 100.0
if account_count == 0 {
Label(cast(u64)11, "No accounts yet. Add one with its otpauth link or secret key.",
Rectangle.{left, top, width, 24.0}, 14)
}
row: float32 = 76.0
scroll := Scroll(session, ScrollProps.{.key = cast(u64)12, .bounds = Rectangle.{left, top, width, height},
.content_height = cast(s32)(cast(float32)account_count * row), .scroll_offset = list_scroll,
.scale = 1.0})
list_scroll = scroll.scroll_offset
if scroll.opened {
x := scroll.content.x
inner := scroll.content.width - 10.0
index: s32 = 0
while index < account_count && view == VIEW_LIST {
DrawRow(index, x, scroll.content.y + cast(float32)index * row, inner, row)
index += 1
}
End(session)
}
}
AddView :: (area: Rectangle, left: float32, width: float32) {
y := area.y + 12.0
Label(cast(u64)20, "Paste otpauth links or an authenticator export", Rectangle.{left, y, width, 20.0}, 14)
Field(FIELD_LINKS, "Links or export", "otpauth://totp/…", links[:], Rectangle.{left, y + 24.0, width, 40.0}, true)
y += 76.0
// The desktop can also read an export file or a picture of its QR code.
files := FileImportAvailable()
button := ifx files then (width - 8.0) / 2.0 else width
if Action(21, "Import", Rectangle.{left, y, button, 40.0}, true) {
ImportLinks()
}
if files && Action(25, "Import file", Rectangle.{left + button + 8.0, y, button, 40.0}, false) {
count := FileImport(links[:])
if count > 0 {
ImportLinks()
} else if count < 0 {
Clear(links[:])
SetStatus("That file is not an authenticator export or its QR code")
}
}
y += 64.0
Label(cast(u64)22, "Or enter the secret key", Rectangle.{left, y, width, 20.0}, 14)
y += 24.0
Field(FIELD_ISSUER, "Service", "Service, such as GitHub", issuer[:], Rectangle.{left, y, width, 40.0}, false)
y += 48.0
Field(FIELD_NAME, "Account", "Account name or email", name[:], Rectangle.{left, y, width, 40.0}, false)
y += 48.0
Field(FIELD_SECRET, "Secret key", "Secret key", secret[:], Rectangle.{left, y, width, 40.0}, true)
y += 56.0
half := (width - 8.0) / 2.0
if Action(23, "Add", Rectangle.{left, y, half, 40.0}, true) {
if AddManual() {
if SaveAccounts() {
SetStatus("Account added")
} else {
SetStatus("Could not save the accounts")
}
Clear(issuer[:])
Clear(name[:])
Clear(secret[:])
view = VIEW_LIST
}
}
if Action(24, "Cancel", Rectangle.{left + half + 8.0, y, half, 40.0}, false) {
Clear(links[:])
Clear(secret[:])
view = VIEW_LIST
SetStatus("")
}
}
// Adds the accounts in the links field, then forgets the field.
ImportLinks :: () {
added := AddExport(TextUntilNul(links[:]), true)
if added > 0 && !SaveAccounts() {
SetStatus("Could not save the accounts")
}
Clear(links[:])
fields[FIELD_LINKS] = FieldState.{}
if added > 0 {
view = VIEW_LIST
}
}
EditView :: (area: Rectangle, left: float32, width: float32) {
y := area.y + 12.0
Field(FIELD_ISSUER, "Service", "Service, such as GitHub", issuer[:], Rectangle.{left, y, width, 40.0}, false)
y += 48.0
Field(FIELD_NAME, "Account", "Account name or email", name[:], Rectangle.{left, y, width, 40.0}, false)
y += 56.0
Label(cast(u64)40, "Websites where it signs in, such as github.com", Rectangle.{left, y, width, 20.0}, 14)
y += 24.0
Field(FIELD_SITES, "Websites", "github.com", sites[:], Rectangle.{left, y, width, 40.0}, false)
y += 56.0
half := (width - 8.0) / 2.0
if Action(41, "Save", Rectangle.{left, y, half, 40.0}, true) {
if SaveEdit() {
CloseEdit()
SetStatus("Account saved")
}
return
}
if Action(42, "Cancel", Rectangle.{left + half + 8.0, y, half, 40.0}, false) {
CloseEdit()
SetStatus("")
return
}
y += 64.0
remove := ButtonProps.{.key = cast(u64)43, .id = 43, .bounds = Rectangle.{left, y, width, 40.0},
.label = ifx remove_pending then "Tap again to remove" else "Remove account",
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if remove_pending {
remove.tone = ButtonTone.ButtonToneDanger
remove.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
if Button(session, remove) == 0 {
return
}
if !remove_pending {
remove_pending = true
SetStatus("Tap the red button again to remove this account")
return
}
removed := RemoveAccount(editing)
CloseEdit()
SetStatus(ifx removed then "Account removed" else "Could not remove the account")
}
Draw :: () {
session = AppSession()
area := AppBounds()
width := area.width - 32.0
if width > 520.0 {
width = 520.0
}
left := area.x + (area.width - width) * 0.5
if view == VIEW_ADD {
AddView(area, left, width)
} else if view == VIEW_EDIT && editing >= 0 && editing < account_count {
EditView(area, left, width)
} else {
ListView(area, left, width)
}
Label(cast(u64)30, TextUntilNul(status[:]), Rectangle.{left, area.y + area.height - 28.0, width, 20.0}, 12)
AppKeyboard(focused != 0)
}
#program_export "AuthMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("auth")
AppDescribe("Auth", Icon.Shape)
return APP_PROTOCOL
}
if AppMode() != APP_FRAME {
return 0
}
// Records from another device replace the list, and close an edit.
if !loaded || RecordsVersion() != records_version {
LoadAccounts()
loaded = true
if view == VIEW_EDIT {
CloseEdit()
}
}
Draw()
return 0
}
-388
View File
@@ -1,388 +0,0 @@
// Authenticator exports: otpauth links, one or many as Ente Auth and other
// apps export them, Google Authenticator's otpauth-migration links and
// Aegis's unencrypted JSON. Encrypted exports are recognized and refused.
#import "text_buffer"
#import "json_scan"
#import "totp"
EXPORT_LIMIT :: 128
MIGRATION_LIMIT :: 16384
ExportResult :: struct {
// Accounts read into export_accounts.
count: s32
// Entries that are not time-based codes or could not be read.
skipped: s32
// The export is encrypted; only unencrypted exports can be read.
encrypted: bool
}
export_accounts: [EXPORT_LIMIT]Account;
export_result: ExportResult;
migration_text: [MIGRATION_LIMIT]u8;
migration_bytes: [MIGRATION_LIMIT]u8;
aegis_positions: [EXPORT_LIMIT * 2]s32;
Wipe :: (bytes: []u8) {
index: s64 = 0
while index < bytes.count {
bytes[index] = cast(u8)0
index += 1
}
}
Keep :: (account: *Account) {
if export_result.count >= EXPORT_LIMIT || (account.issuer[0] == cast(u8)0 && account.name[0] == cast(u8)0) {
export_result.skipped += 1
return
}
export_accounts[export_result.count] = account.*
export_result.count += 1
}
// Forgets the accounts read, secrets included.
ClearExport :: () {
index: s32 = 0
while index < EXPORT_LIMIT {
export_accounts[index] = Account.{}
index += 1
}
export_result = ExportResult.{}
}
// "Issuer:alice" names carry the issuer; the account keeps only "alice".
SplitLabel :: (account: *Account) {
issuer: [64]u8
rest: [128]u8
{
name := TextUntilNul(account.name[:])
colon: s64 = 0
while colon < name.count && name[colon] != cast(u8)58 {
colon += 1
}
if colon >= name.count || !CopyLimited(name[0:colon], issuer[:]) {
return
}
start := colon + 1
while start < name.count && name[start] == cast(u8)32 {
start += 1
}
unused CopyLimited(name[start:name.count], rest[:])
}
if account.issuer[0] == cast(u8)0 {
account.issuer = issuer
} else if TextUntilNul(issuer[:]) != TextUntilNul(account.issuer[:]) {
return
}
account.name = rest
}
Base64Value :: (byte: u8) -> s32 {
if byte >= cast(u8)65 && byte <= cast(u8)90 {
return cast(s32)(byte - cast(u8)65)
}
if byte >= cast(u8)97 && byte <= cast(u8)122 {
return cast(s32)(byte - cast(u8)97) + 26
}
if byte >= cast(u8)48 && byte <= cast(u8)57 {
return cast(s32)(byte - cast(u8)48) + 52
}
// A "+" that a link turned into a space, and the URL-safe alphabet.
if byte == cast(u8)43 || byte == cast(u8)32 || byte == cast(u8)45 {
return 62
}
if byte == cast(u8)47 || byte == cast(u8)95 {
return 63
}
return -1
}
// Decodes Base64 up to its padding. Returns the byte count, or -1.
Base64Decode :: (text: string, output: []u8) -> s32 {
buffer: u32 = 0
bits: s32 = 0
count: s32 = 0
index: s64 = 0
while index < text.count && text[index] != cast(u8)61 {
value := Base64Value(text[index])
index += 1
if value < 0 {
return -1
}
buffer = (buffer << cast(u32)6) | cast(u32)value
bits += 6
if bits >= 8 {
bits -= 8
if count >= cast(s32)output.count {
return -1
}
output[count] = cast(u8)(buffer >> cast(u32)bits)
count += 1
}
}
return count
}
// A protocol buffer varint; at becomes -1 when the data ends inside it.
Varint :: (data: []u8, end: s32, at: *s32) -> u64 {
value: u64 = 0
shift: u64 = 0
while at.* >= 0 && at.* < end && shift < cast(u64)64 {
byte := data[at.*]
at.* += 1
value = value | (cast(u64)(byte & cast(u8)127) << shift)
if byte < cast(u8)128 {
return value
}
shift += cast(u64)7
}
at.* = -1
return 0
}
// Moves past one field's value; false when the data is malformed.
SkipField :: (data: []u8, end: s32, at: *s32, wire: u64) -> bool {
if wire == cast(u64)0 {
unused Varint(data, end, at)
} else if wire == cast(u64)1 {
at.* += 8
} else if wire == cast(u64)5 {
at.* += 4
} else if wire == cast(u64)2 {
length := Varint(data, end, at)
if at.* < 0 || length > cast(u64)(end - at.*) {
return false
}
at.* += cast(s32)length
} else {
return false
}
return at.* >= 0 && at.* <= end
}
// One account of a migration payload (Google's OtpParameters): the secret's
// bytes, name, issuer, algorithm, digits and type.
ReadParameters :: (data: []u8, start: s32, end: s32) {
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
secret_at: s32 = -1
secret_count: s32 = 0
readable := true
at := start
while readable && at < end {
key := Varint(data, end, *at)
if at < 0 {
readable = false
break
}
field := key >> cast(u64)3
wire := key & cast(u64)7
if wire == cast(u64)2 {
length := Varint(data, end, *at)
if at < 0 || length > cast(u64)(end - at) {
readable = false
break
}
value := TextView(data[at:at + cast(s32)length])
if field == cast(u64)1 {
secret_at = at
secret_count = cast(s32)length
} else if field == cast(u64)2 {
readable = CopyLimited(value, account.name[:])
} else if field == cast(u64)3 {
readable = CopyLimited(value, account.issuer[:])
}
at += cast(s32)length
} else if wire == cast(u64)0 {
value := Varint(data, end, *at)
if at < 0 {
readable = false
break
}
if field == cast(u64)4 {
// 0 unspecified and 1 SHA-1, 2 SHA-256, 3 SHA-512; 4 is MD5.
if value == cast(u64)2 {
account.kind = HASH_SHA256
} else if value == cast(u64)3 {
account.kind = HASH_SHA512
} else if value > cast(u64)1 {
readable = false
}
} else if field == cast(u64)5 {
// 0 unspecified and 1 six digits, 2 eight.
if value == cast(u64)2 {
account.digits = 8
} else if value > cast(u64)1 {
readable = false
}
} else if field == cast(u64)6 {
// 1 is a counter-based (HOTP) account, 2 time-based.
readable = value != cast(u64)1
}
} else {
readable = SkipField(data, end, *at, wire)
}
}
secret: [256]u8
readable = readable && secret_at >= 0 && secret_count <= KEY_LIMIT &&
Base32Encode(data[secret_at:secret_at + secret_count], secret_count, secret[:]) > 0 &&
SetSecret(*account, TextUntilNul(secret[:]))
if readable {
SplitLabel(*account)
Keep(*account)
} else {
export_result.skipped += 1
}
Wipe(secret[:])
account = Account.{}
}
// otpauth-migration://offline?data=…: Base64 of a MigrationPayload whose
// first field repeats once per account.
ReadMigration :: (link: string) {
prefix := "otpauth-migration://offline?"
if !StartsWithIgnoringCase(link, prefix) {
export_result.skipped += 1
return
}
query := link[prefix.count:link.count]
data := ""
position: s64 = 0
while position < query.count {
end := position
while end < query.count && query[end] != cast(u8)38 {
end += 1
}
if StartsWithIgnoringCase(query[position:end], "data=") {
data = query[position + 5:end]
}
position = end + 1
}
count: s32 = -1
if data != "" && Unescape(data, migration_text[:]) {
count = Base64Decode(TextUntilNul(migration_text[:]), migration_bytes[:])
}
if count <= 0 {
export_result.skipped += 1
}
at: s32 = 0
while count > 0 && at >= 0 && at < count {
key := Varint(migration_bytes[:], count, *at)
if at < 0 {
break
}
if key == cast(u64)10 {
length := Varint(migration_bytes[:], count, *at)
if at < 0 || length > cast(u64)(count - at) {
export_result.skipped += 1
break
}
ReadParameters(migration_bytes[:], at, at + cast(s32)length)
at += cast(s32)length
} else if !SkipField(migration_bytes[:], count, *at, key & cast(u64)7) {
break
}
}
Wipe(migration_text[:])
Wipe(migration_bytes[:])
}
ReadText :: (text: string, at: s32, output: []u8) -> string {
if at < 0 || ReadStringText(text, at, output) < 0 {
output[0] = cast(u8)0
}
return TextUntilNul(output)
}
// Aegis's export: {"db":{"entries":[{"type":"totp","name":…,"issuer":…,
// "info":{"secret":…,"algo":…,"digits":…,"period":…}}]}}. An encrypted
// Aegis export keeps db as a string; Ente Auth's has encryptedData.
ReadAegis :: (text: string) {
db := FieldAt(text, 0, "db")
if (db >= 0 && text[db] == cast(u8)34) || FieldAt(text, 0, "encryptedData") >= 0 {
export_result.encrypted = true
return
}
entries := FieldAt(text, db, "entries")
total := ArrayPositions(text, entries, aegis_positions[:])
if total > EXPORT_LIMIT * 2 {
total = EXPORT_LIMIT * 2
}
index: s32 = 0
while index < total {
entry := aegis_positions[index]
index += 1
info := FieldAt(text, entry, "info")
kind: [16]u8
if ReadText(text, FieldAt(text, entry, "type"), kind[:]) != "totp" || info < 0 {
export_result.skipped += 1
continue
}
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
secret: [256]u8
readable := SetSecret(*account, ReadText(text, FieldAt(text, info, "secret"), secret[:]))
algorithm: [16]u8
if ReadText(text, FieldAt(text, info, "algo"), algorithm[:]) != "" {
account.kind = ParseAlgorithm(TextUntilNul(algorithm[:]))
readable = readable && account.kind != 0
}
digits := ReadNumber(text, FieldAt(text, info, "digits"))
if digits.valid {
account.digits = cast(s32)digits.value
readable = readable && account.digits >= 6 && account.digits <= 8
}
period := ReadNumber(text, FieldAt(text, info, "period"))
if period.valid {
account.period = cast(s32)period.value
readable = readable && account.period >= 1 && account.period <= 300
}
issuer: [64]u8
name: [128]u8
readable = readable && CopyLimited(ReadText(text, FieldAt(text, entry, "issuer"), issuer[:]), account.issuer[:]) &&
CopyLimited(ReadText(text, FieldAt(text, entry, "name"), name[:]), account.name[:])
if readable {
Keep(*account)
} else {
export_result.skipped += 1
}
Wipe(secret[:])
account = Account.{}
}
}
// Reads every account in an export into export_accounts.
ReadExport :: (text: string) -> ExportResult {
ClearExport()
start: s64 = 0
while start < text.count && text[start] <= cast(u8)32 {
start += 1
}
if start < text.count && text[start] == cast(u8)123 {
ReadAegis(text[start:text.count])
return export_result
}
while start < text.count {
while start < text.count && text[start] <= cast(u8)32 {
start += 1
}
end := start
while end < text.count && text[end] > cast(u8)32 {
end += 1
}
if end > start {
word := text[start:end]
if StartsWithIgnoringCase(word, "otpauth-migration://") {
ReadMigration(word)
} else {
account: Account
if ParseLink(word, *account) {
Keep(*account)
} else {
export_result.skipped += 1
}
account = Account.{}
}
}
start = end
}
return export_result
}
-95
View File
@@ -1,95 +0,0 @@
// Reading authenticator exports, with the RFC 6238 test keys only.
#import "text_buffer"
#import "totp"
#import "exports"
// Example Co:[email protected] (SHA-1, 6 digits), Second:bob (SHA-256,
// 8 digits) and a counter-based account, as Google Authenticator exports them.
MIGRATION :: "otpauth-migration://offline?data=CjoKFDEyMzQ1Njc4OTAxMjM0NTY3ODkwEhxFeGFtcGxlIENvOmFsaWNlQGV4YW1wbGUuY29tIAEoATACCjUKIDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyEgNib2IaBlNlY29uZCACKAIwAgorChQxMjM0NTY3ODkwMTIzNDU2Nzg5MBIHY291bnRlchoESG90cCABKAEwARABGAEgACi5YA%3D%3D"
AEGIS :: #string END
{"version":1,"header":{"slots":null,"params":null},"db":{"version":2,"entries":[
{"type":"totp","uuid":"1","name":"carol","issuer":"Third","icon":null,
"info":{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","algo":"SHA512","digits":7,"period":60}},
{"type":"hotp","uuid":"2","name":"dave","issuer":"Counter",
"info":{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","algo":"SHA1","digits":6,"counter":1}}]}}
END;
AEGIS_ENCRYPTED :: "{\"version\":1,\"header\":{\"slots\":[{\"type\":1}],\"params\":{}},\"db\":\"c2VhbGVk\"}"
// Ente Auth's plain text export: one link per line, with its own fields.
ENTE :: #string END
otpauth://totp/First:one?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=First&algorithm=sha1&digits=6&period=30&codeDisplay=%7B%22pinned%22%3Afalse%2C%22tags%22%3A%5B%5D%7D
otpauth://totp/Second:two?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Second&algorithm=sha1&digits=6&period=30
not-a-link
END;
Code :: (index: s32, unix: s64, output: []u8) -> string {
account := *export_accounts[index]
return CodeNow(account.kind, account.key[:], account.key_count, account.digits, account.period, unix, output)
}
#program_export
Run :: () -> s32 {
code: [12]u8
result := ReadExport(MIGRATION)
if result.count != 2 || result.skipped != 1 || result.encrypted {
return 10
}
if TextUntilNul(export_accounts[0].issuer[:]) != "Example Co" ||
TextUntilNul(export_accounts[0].name[:]) != "[email protected]" || export_accounts[0].digits != 6 ||
Code(0, 59, code[:]) != "287082" {
return 11
}
if TextUntilNul(export_accounts[1].issuer[:]) != "Second" || TextUntilNul(export_accounts[1].name[:]) != "bob" ||
export_accounts[1].kind != HASH_SHA256 || Code(1, 59, code[:]) != "46119246" {
return 12
}
result = ReadExport(AEGIS)
if result.count != 1 || result.skipped != 1 || TextUntilNul(export_accounts[0].issuer[:]) != "Third" ||
export_accounts[0].kind != HASH_SHA512 || export_accounts[0].digits != 7 || export_accounts[0].period != 60 {
return 20
}
result = ReadExport(AEGIS_ENCRYPTED)
if result.count != 0 || !result.encrypted {
return 21
}
result = ReadExport(ENTE)
if result.count != 2 || result.skipped != 1 || TextUntilNul(export_accounts[1].name[:]) != "two" {
return 30
}
ClearExport()
if export_accounts[0].secret[0] != cast(u8)0 || export_accounts[0].key_count != 0 {
return 31
}
// Websites: hosts or addresses, kept in the account's link.
sites: [256]u8
if !NormalizeSites("https://GitHub.com/login, account.proton.me", sites[:]) ||
TextUntilNul(sites[:]) != "github.com account.proton.me" || NormalizeSites("github", sites[:]) ||
NormalizeSites("[email protected]", sites[:]) || NormalizeSites("github..com", sites[:]) {
return 40
}
account: Account
again: Account
saved: [1024]u8
if !ParseLink("otpauth://totp/Example:alice?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&sites=example.com%20login.example.org", *account) ||
TextUntilNul(account.sites[:]) != "example.com login.example.org" ||
!ParseLink(LinkText(*account, saved[:]), *again) || TextUntilNul(again.sites[:]) != "example.com login.example.org" {
return 41
}
encoded: [64]u8
key := "12345678901234567890"
bytes: [20]u8
for index: 0..19 {
bytes[index] = key[index]
}
if Base32Encode(bytes[:], 20, encoded[:]) != 32 || TextUntilNul(encoded[:]) != "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" ||
Base32Encode(bytes[:], 1, encoded[:]) != 2 || TextUntilNul(encoded[:]) != "GE" {
return 42
}
id: [33]u8
if RecordIdFor(TextView(saved[0:0]), id[:]) != "e3b0c44298fc1c149afbf4c8996fb924" {
return 43
}
return 0
}
-812
View File
@@ -1,812 +0,0 @@
// Time-based one-time passwords (RFC 6238) with HMAC-SHA-1, SHA-256 or
// SHA-512, and the otpauth:// links authenticator apps export.
#import "text_buffer"
#import "sha256"
HASH_SHA1 :: 1
HASH_SHA256 :: 2
HASH_SHA512 :: 3
// Longest key, message and decoded secret this module handles.
KEY_LIMIT :: 128
HASH_INPUT_LIMIT :: 256
Digest :: struct {
bytes: [64]u8
count: s32
}
// The 80 SHA-512 round constants, each as its high and low 32 bits.
sha512_round_halves: [160]u32 = .[
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f,
0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242,
0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235,
0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275,
0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f,
0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc,
0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6,
0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218,
0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99,
0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc,
0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915,
0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba,
0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc,
0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
RotateLeft32 :: (value: u32, amount: u32) -> u32 {
return (value << amount) | (value >> (cast(u32)32 - amount))
}
RotateRight64 :: (value: u64, amount: u64) -> u64 {
return (value >> amount) | (value << (cast(u64)64 - amount))
}
// Pads a message the SHA way into blocks: 0x80, zeros, then the bit length
// in the last eight bytes. Returns the padded length.
Pad :: (input: []u8, count: s32, block: s32, output: []u8) -> s32 {
index: s32 = 0
while index < count {
output[index] = input[index]
index += 1
}
output[count] = cast(u8)0x80
length_bytes: s32 = ifx block == 128 then 16 else 8
total := ((count + 1 + length_bytes + block - 1) / block) * block
index = count + 1
while index < total {
output[index] = cast(u8)0
index += 1
}
bits := cast(u64)count * cast(u64)8
for shift: 0..7 {
output[total - 1 - cast(s32)shift] = cast(u8)(bits >> (cast(u64)shift * cast(u64)8))
}
return total
}
Sha1 :: (input: []u8, count: s32) -> Digest {
padded: [HASH_INPUT_LIMIT + 128]u8
total := Pad(input, count, 64, padded[:])
state: [5]u32 = .[0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]
offset: s32 = 0
while offset < total {
words: [80]u32
for index: 0..15 {
at := offset + cast(s32)index * 4
words[index] = (cast(u32)padded[at] << cast(u32)24) | (cast(u32)padded[at + 1] << cast(u32)16) |
(cast(u32)padded[at + 2] << cast(u32)8) | cast(u32)padded[at + 3]
}
for index: 16..79 {
mixed: u32 = words[index - 3] ^ words[index - 8]
mixed = mixed ^ words[index - 14]
mixed = mixed ^ words[index - 16]
words[index] = RotateLeft32(mixed, cast(u32)1)
}
a := state[0]
b := state[1]
c := state[2]
d := state[3]
e := state[4]
for index: 0..79 {
mix: u32
constant: u32
if index < 20 {
mix = (b & c) | (~b & d)
constant = 0x5a827999
} else if index < 40 {
mix = b ^ c ^ d
constant = 0x6ed9eba1
} else if index < 60 {
mix = (b & c) | (b & d) | (c & d)
constant = 0x8f1bbcdc
} else {
mix = b ^ c ^ d
constant = 0xca62c1d6
}
next := RotateLeft32(a, cast(u32)5) + mix + e + constant + words[index]
e = d
d = c
c = RotateLeft32(b, cast(u32)30)
b = a
a = next
}
state[0] += a
state[1] += b
state[2] += c
state[3] += d
state[4] += e
offset += 64
}
digest: Digest
digest.count = 20
for index: 0..4 {
for part: 0..3 {
digest.bytes[index * 4 + part] = cast(u8)(state[index] >> (cast(u32)(3 - part) * cast(u32)8))
}
}
return digest
}
Sha512 :: (input: []u8, count: s32) -> Digest {
padded: [HASH_INPUT_LIMIT + 256]u8
total := Pad(input, count, 128, padded[:])
initial: [16]u32 = .[0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b,
0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b,
0x5be0cd19, 0x137e2179]
state: [8]u64
for index: 0..7 {
state[index] = (cast(u64)initial[index * 2] << cast(u64)32) | cast(u64)initial[index * 2 + 1]
}
offset: s32 = 0
while offset < total {
words: [80]u64
for index: 0..15 {
value: u64 = 0
for part: 0..7 {
value = (value << cast(u64)8) | cast(u64)padded[offset + cast(s32)index * 8 + cast(s32)part]
}
words[index] = value
}
for index: 16..79 {
low: u64 = RotateRight64(words[index - 15], cast(u64)1)
low = low ^ RotateRight64(words[index - 15], cast(u64)8)
low = low ^ (words[index - 15] >> cast(u64)7)
high: u64 = RotateRight64(words[index - 2], cast(u64)19)
high = high ^ RotateRight64(words[index - 2], cast(u64)61)
high = high ^ (words[index - 2] >> cast(u64)6)
words[index] = words[index - 16] + low + words[index - 7] + high
}
a := state[0]
b := state[1]
c := state[2]
d := state[3]
e := state[4]
f := state[5]
g := state[6]
h := state[7]
for index: 0..79 {
major: u64 = RotateRight64(e, cast(u64)14)
major = major ^ RotateRight64(e, cast(u64)18)
major = major ^ RotateRight64(e, cast(u64)41)
choose := (e & f) ^ (~e & g)
constant := (cast(u64)sha512_round_halves[index * 2] << cast(u64)32) | cast(u64)sha512_round_halves[index * 2 + 1]
first := h + major + choose + constant + words[index]
minor: u64 = RotateRight64(a, cast(u64)28)
minor = minor ^ RotateRight64(a, cast(u64)34)
minor = minor ^ RotateRight64(a, cast(u64)39)
mixture := (a & b) ^ (a & c) ^ (b & c)
h = g
g = f
f = e
e = d + first
d = c
c = b
b = a
a = first + minor + mixture
}
state[0] += a
state[1] += b
state[2] += c
state[3] += d
state[4] += e
state[5] += f
state[6] += g
state[7] += h
offset += 128
}
digest: Digest
digest.count = 64
for index: 0..7 {
for part: 0..7 {
digest.bytes[index * 8 + part] = cast(u8)(state[index] >> (cast(u64)(7 - part) * cast(u64)8))
}
}
return digest
}
Hash :: (kind: s32, input: []u8, count: s32) -> Digest {
if kind == HASH_SHA256 {
hashed := Sha256(TextView(input[0:count]))
digest: Digest
digest.count = 32
for index: 0..31 {
digest.bytes[index] = hashed[index]
}
return digest
}
if kind == HASH_SHA512 {
return Sha512(input, count)
}
return Sha1(input, count)
}
// HMAC (RFC 2104). Keys up to KEY_LIMIT bytes and messages up to 64 bytes.
Hmac :: (kind: s32, key: []u8, key_count: s32, message: []u8, message_count: s32) -> Digest {
block: s32 = ifx kind == HASH_SHA512 then 128 else 64
block_key: [128]u8
if key_count > block {
hashed := Hash(kind, key, key_count)
for index: 0..63 {
block_key[index] = hashed.bytes[index]
}
} else {
index: s32 = 0
while index < key_count {
block_key[index] = key[index]
index += 1
}
}
inner_input: [HASH_INPUT_LIMIT]u8
index: s32 = 0
while index < block {
inner_input[index] = block_key[index] ^ cast(u8)0x36
index += 1
}
index = 0
while index < message_count {
inner_input[block + index] = message[index]
index += 1
}
inner := Hash(kind, inner_input[:], block + message_count)
outer_input: [HASH_INPUT_LIMIT]u8
index = 0
while index < block {
outer_input[index] = block_key[index] ^ cast(u8)0x5c
index += 1
}
index = 0
while index < inner.count {
outer_input[block + index] = inner.bytes[index]
index += 1
}
result := Hash(kind, outer_input[:], block + inner.count)
for wipe: 0..127 {
block_key[wipe] = cast(u8)0
}
for wipe: 0..HASH_INPUT_LIMIT - 1 {
inner_input[wipe] = cast(u8)0
outer_input[wipe] = cast(u8)0
}
return result
}
// The code for a counter (HOTP, RFC 4226), zero-padded to digits.
CodeAt :: (kind: s32, key: []u8, key_count: s32, digits: s32, counter: u64, output: []u8) -> string {
message: [8]u8
for index: 0..7 {
message[index] = cast(u8)(counter >> (cast(u64)(7 - index) * cast(u64)8))
}
mac := Hmac(kind, key, key_count, message[:], 8)
offset := cast(s32)(mac.bytes[mac.count - 1] & cast(u8)0x0f)
binary := ((cast(u32)mac.bytes[offset] & cast(u32)0x7f) << cast(u32)24) |
(cast(u32)mac.bytes[offset + 1] << cast(u32)16) |
(cast(u32)mac.bytes[offset + 2] << cast(u32)8) | cast(u32)mac.bytes[offset + 3]
modulus: u32 = 1
for step: 1..digits {
modulus *= cast(u32)10
}
value := binary % modulus
position := digits - 1
while position >= 0 {
output[position] = cast(u8)(48 + cast(s32)(value % cast(u32)10))
value /= cast(u32)10
position -= 1
}
output[digits] = cast(u8)0
return TextView(output[0:digits])
}
// The code for a Unix time (TOTP, RFC 6238).
CodeNow :: (kind: s32, key: []u8, key_count: s32, digits: s32, period: s32, unix: s64, output: []u8) -> string {
step := unix / cast(s64)period
if step < 0 {
step = 0
}
return CodeAt(kind, key, key_count, digits, cast(u64)step, output)
}
// Decodes Base32 (RFC 4648) ignoring case, spaces, hyphens and padding.
// Returns the byte count, or -1 for any other character or a key too long.
Base32Decode :: (text: string, output: []u8) -> s32 {
buffer: u32 = 0
bits: s32 = 0
count: s32 = 0
index: s64 = 0
while index < text.count {
byte := text[index]
index += 1
if byte == cast(u8)32 || byte == cast(u8)45 || byte == cast(u8)61 {
continue
}
value: s32 = -1
if byte >= cast(u8)65 && byte <= cast(u8)90 {
value = cast(s32)(byte - cast(u8)65)
} else if byte >= cast(u8)97 && byte <= cast(u8)122 {
value = cast(s32)(byte - cast(u8)97)
} else if byte >= cast(u8)50 && byte <= cast(u8)55 {
value = cast(s32)(byte - cast(u8)50) + 26
}
if value < 0 {
return -1
}
buffer = (buffer << cast(u32)5) | cast(u32)value
bits += 5
if bits >= 8 {
bits -= 8
if count >= cast(s32)output.count {
return -1
}
output[count] = cast(u8)(buffer >> cast(u32)bits)
count += 1
}
}
return count
}
// Encodes bytes as Base32 without padding. Returns the length, or -1 when
// it does not fit in output.
Base32Encode :: (bytes: []u8, count: s32, output: []u8) -> s32 {
alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
buffer: u32 = 0
bits: s32 = 0
used: s32 = 0
index: s32 = 0
while index < count {
buffer = (buffer << cast(u32)8) | cast(u32)bytes[index]
bits += 8
index += 1
while bits >= 5 {
bits -= 5
if used >= cast(s32)output.count - 1 {
return -1
}
output[used] = alphabet[cast(s64)((buffer >> cast(u32)bits) & cast(u32)31)]
used += 1
}
}
if bits > 0 {
if used >= cast(s32)output.count - 1 {
return -1
}
output[used] = alphabet[cast(s64)((buffer << cast(u32)(5 - bits)) & cast(u32)31)]
used += 1
}
output[used] = cast(u8)0
return used
}
Account :: struct {
issuer: [64]u8
name: [128]u8
// The websites where this account signs in, such as github.com,
// separated by spaces.
sites: [256]u8
// The secret as Base32, kept to save it again.
secret: [256]u8
key: [KEY_LIMIT]u8
key_count: s32
kind: s32
digits: s32
period: s32
}
Lower :: (byte: u8) -> u8 {
if byte >= cast(u8)65 && byte <= cast(u8)90 {
return byte + cast(u8)32
}
return byte
}
StartsWithIgnoringCase :: (text: string, prefix: string) -> bool {
if text.count < prefix.count {
return false
}
index: s64 = 0
while index < prefix.count {
if Lower(text[index]) != Lower(prefix[index]) {
return false
}
index += 1
}
return true
}
HexValue :: (byte: u8) -> s32 {
if byte >= cast(u8)48 && byte <= cast(u8)57 {
return cast(s32)(byte - cast(u8)48)
}
lower := Lower(byte)
if lower >= cast(u8)97 && lower <= cast(u8)102 {
return cast(s32)(lower - cast(u8)97) + 10
}
return -1
}
// Percent-decodes into output ("+" is a space in a query). False when it
// does not fit.
Unescape :: (text: string, output: []u8) -> bool {
used: s64 = 0
index: s64 = 0
while index < text.count {
byte := text[index]
if byte == cast(u8)37 && index + 2 < text.count && HexValue(text[index + 1]) >= 0 && HexValue(text[index + 2]) >= 0 {
byte = cast(u8)(HexValue(text[index + 1]) * 16 + HexValue(text[index + 2]))
index += 2
} else if byte == cast(u8)43 {
byte = cast(u8)32
}
if used >= output.count - 1 || byte < cast(u8)32 {
return false
}
output[used] = byte
used += 1
index += 1
}
output[used] = cast(u8)0
return true
}
ParseNumber :: (text: string) -> s32 {
if text.count == 0 || text.count > 6 {
return -1
}
value: s32 = 0
index: s64 = 0
while index < text.count {
if text[index] < cast(u8)48 || text[index] > cast(u8)57 {
return -1
}
value = value * 10 + cast(s32)(text[index] - cast(u8)48)
index += 1
}
return value
}
ParseAlgorithm :: (text: string) -> s32 {
upper: [8]u8
if text.count > 7 {
return 0
}
index: s64 = 0
while index < text.count {
byte := text[index]
upper[index] = ifx byte >= cast(u8)97 && byte <= cast(u8)122 then byte - cast(u8)32 else byte
index += 1
}
name := TextView(upper[0:text.count])
if name == "SHA1" {
return HASH_SHA1
}
if name == "SHA256" {
return HASH_SHA256
}
if name == "SHA512" {
return HASH_SHA512
}
return 0
}
// Checks a Base32 secret and fills the account's key from it.
SetSecret :: (account: *Account, secret: string) -> bool {
clean: [256]u8
used: s64 = 0
index: s64 = 0
while index < secret.count {
byte := secret[index]
index += 1
if byte == cast(u8)32 || byte == cast(u8)45 || byte == cast(u8)61 {
continue
}
if used >= 255 {
return false
}
clean[used] = ifx byte >= cast(u8)97 && byte <= cast(u8)122 then byte - cast(u8)32 else byte
used += 1
}
count := Base32Decode(TextView(clean[0:used]), account.key[:])
// Shorter keys than 80 bits are refused as RFC 4226 asks; most services
// use 160.
if count < 10 {
return false
}
account.key_count = count
index = 0
while index < used {
account.secret[index] = clean[index]
index += 1
}
account.secret[used] = cast(u8)0
return true
}
CopyLimited :: (text: string, output: []u8) -> bool {
if text.count >= output.count {
return false
}
index: s64 = 0
while index < text.count {
if text[index] < cast(u8)32 {
return false
}
output[index] = text[index]
index += 1
}
output[text.count] = cast(u8)0
return true
}
// A host name such as github.com or account.proton.me.
ValidHost :: (host: string) -> bool {
if host.count < 3 || host.count > 253 || host[0] == cast(u8)46 || host[0] == cast(u8)45 ||
host[host.count - 1] == cast(u8)46 {
return false
}
dot := false
index: s64 = 0
while index < host.count {
byte := Lower(host[index])
letter := byte >= cast(u8)97 && byte <= cast(u8)122
digit := byte >= cast(u8)48 && byte <= cast(u8)57
if byte == cast(u8)46 {
if host[index - 1] == cast(u8)46 {
return false
}
dot = true
} else if !letter && !digit && byte != cast(u8)45 {
return false
}
index += 1
}
return dot
}
// Reads websites separated by spaces or commas, each a host or an address
// such as https://github.com/login, into lowercase hosts separated by
// single spaces. False when one is not a website.
NormalizeSites :: (text: string, output: []u8) -> bool {
used: s64 = 0
output[0] = cast(u8)0
start: s64 = 0
while start < text.count {
while start < text.count && (text[start] <= cast(u8)32 || text[start] == cast(u8)44) {
start += 1
}
end := start
while end < text.count && text[end] > cast(u8)32 && text[end] != cast(u8)44 {
end += 1
}
if end > start {
site := text[start:end]
if StartsWithIgnoringCase(site, "https://") {
site = site[8:site.count]
} else if StartsWithIgnoringCase(site, "http://") {
site = site[7:site.count]
}
host_end: s64 = 0
while host_end < site.count && site[host_end] != cast(u8)47 && site[host_end] != cast(u8)63 &&
site[host_end] != cast(u8)35 {
host_end += 1
}
host := site[0:host_end]
if !ValidHost(host) || used + host.count + 1 >= output.count {
output[0] = cast(u8)0
return false
}
if used > 0 {
output[used] = cast(u8)32
used += 1
}
index: s64 = 0
while index < host.count {
output[used] = Lower(host[index])
used += 1
index += 1
}
output[used] = cast(u8)0
}
start = end
}
return true
}
// Reads an otpauth://totp/ link. HOTP and other kinds are refused.
ParseLink :: (link: string, account: *Account) -> bool {
account.* = Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
prefix := "otpauth://totp/"
if !StartsWithIgnoringCase(link, prefix) {
return false
}
rest := link[prefix.count:link.count]
query_at: s64 = 0
while query_at < rest.count && rest[query_at] != cast(u8)63 {
query_at += 1
}
label: [256]u8
if !Unescape(rest[0:query_at], label[:]) {
return false
}
label_text := TextUntilNul(label[:])
colon: s64 = 0
while colon < label_text.count && label_text[colon] != cast(u8)58 {
colon += 1
}
if colon < label_text.count {
start := colon + 1
while start < label_text.count && label_text[start] == cast(u8)32 {
start += 1
}
if !CopyLimited(label_text[0:colon], account.issuer[:]) ||
!CopyLimited(label_text[start:label_text.count], account.name[:]) {
return false
}
} else if !CopyLimited(label_text, account.name[:]) {
return false
}
has_secret := false
position := query_at + 1
while position < rest.count {
end := position
while end < rest.count && rest[end] != cast(u8)38 {
end += 1
}
pair := rest[position:end]
equals: s64 = 0
while equals < pair.count && pair[equals] != cast(u8)61 {
equals += 1
}
key := pair[0:equals]
// Other apps add their own fields, such as Ente Auth's codeDisplay.
known := key == "secret" || key == "issuer" || key == "algorithm" || key == "digits" ||
key == "period" || key == "sites"
if equals < pair.count && known {
value: [256]u8
if !Unescape(pair[equals + 1:pair.count], value[:]) {
return false
}
text := TextUntilNul(value[:])
if key == "secret" {
if !SetSecret(account, text) {
return false
}
has_secret = true
} else if key == "issuer" {
if !CopyLimited(text, account.issuer[:]) {
return false
}
} else if key == "algorithm" {
account.kind = ParseAlgorithm(text)
if account.kind == 0 {
return false
}
} else if key == "digits" {
account.digits = ParseNumber(text)
if account.digits < 6 || account.digits > 8 {
return false
}
} else if key == "period" {
account.period = ParseNumber(text)
if account.period < 1 || account.period > 300 {
return false
}
} else if key == "sites" {
// An unreadable list only loses the websites, not the account.
unused NormalizeSites(text, account.sites[:])
}
}
position = end + 1
}
return has_secret && (account.issuer[0] != cast(u8)0 || account.name[0] != cast(u8)0)
}
Unreserved :: (byte: u8) -> bool {
return byte >= cast(u8)65 && byte <= cast(u8)90 || byte >= cast(u8)97 && byte <= cast(u8)122 ||
byte >= cast(u8)48 && byte <= cast(u8)57 || byte == cast(u8)45 || byte == cast(u8)46 ||
byte == cast(u8)95 || byte == cast(u8)126
}
AppendText :: (output: []u8, used: s64, text: string) -> s64 {
index: s64 = 0
while index < text.count {
if used < 0 || used >= output.count - 1 {
return -1
}
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
AppendEscaped :: (output: []u8, used: s64, text: string) -> s64 {
hex := "0123456789ABCDEF"
index: s64 = 0
while index < text.count && used >= 0 {
byte := text[index]
if Unreserved(byte) {
used = AppendText(output, used, text[index:index + 1])
} else if used + 3 < output.count {
output[used] = cast(u8)37
output[used + 1] = hex[cast(s64)(byte >> cast(u8)4)]
output[used + 2] = hex[cast(s64)(byte & cast(u8)15)]
used += 3
output[used] = cast(u8)0
} else {
return -1
}
index += 1
}
return used
}
// The account as an otpauth link, the format Auth saves and imports.
LinkText :: (account: *Account, output: []u8) -> string {
used := AppendText(output, 0, "otpauth://totp/")
issuer := TextUntilNul(account.issuer[:])
if issuer != "" {
used = AppendEscaped(output, used, issuer)
used = AppendText(output, used, ":")
}
used = AppendEscaped(output, used, TextUntilNul(account.name[:]))
used = AppendText(output, used, "?secret=")
used = AppendText(output, used, TextUntilNul(account.secret[:]))
if issuer != "" {
used = AppendText(output, used, "&issuer=")
used = AppendEscaped(output, used, issuer)
}
algorithms: [4]string = .["", "SHA1", "SHA256", "SHA512"]
used = AppendText(output, used, "&algorithm=")
used = AppendText(output, used, algorithms[account.kind])
digits: [2]u8
digits[0] = cast(u8)(48 + account.digits)
used = AppendText(output, used, "&digits=")
used = AppendText(output, used, TextView(digits[0:1]))
period: [8]u8
value := account.period
length: s32 = 0
while value > 0 || length == 0 {
period[7 - length] = cast(u8)(48 + value % 10)
value /= 10
length += 1
}
used = AppendText(output, used, "&period=")
used = AppendText(output, used, TextView(period[8 - length:8]))
sites := TextUntilNul(account.sites[:])
if sites != "" {
used = AppendText(output, used, "&sites=")
used = AppendEscaped(output, used, sites)
}
if used < 0 {
return ""
}
return TextView(output[0:used])
}
// An account's record id: the first 16 bytes of its link's SHA-256 as hex,
// so the same account added on two devices is one record.
RecordIdFor :: (link: string, output: []u8) -> string {
hex := "0123456789abcdef"
digest := Sha256(link)
for at: 0..15 {
output[at * 2] = hex[cast(s64)(digest[at] >> cast(u8)4)]
output[at * 2 + 1] = hex[cast(s64)(digest[at] & cast(u8)15)]
}
output[32] = cast(u8)0
for at: 0..31 {
digest[at] = cast(u8)0
}
return TextView(output[0:32])
}
-64
View File
@@ -1,64 +0,0 @@
// RFC 6238 and RFC 4648 test vectors, with the RFCs' public fixture keys.
#import "text_buffer"
#import "totp"
KeyFrom :: (text: string, output: []u8) -> s32 {
index: s64 = 0
while index < text.count {
output[index] = text[index]
index += 1
}
return cast(s32)text.count
}
Expect :: (kind: s32, key: string, unix: s64, expected: string) -> bool {
bytes: [KEY_LIMIT]u8
count := KeyFrom(key, bytes[:])
code: [12]u8
return CodeNow(kind, bytes[:], count, 8, 30, unix, code[:]) == expected
}
#program_export
Run :: () -> s32 {
sha1 := "12345678901234567890"
sha256 := "12345678901234567890123456789012"
sha512 := "1234567890123456789012345678901234567890123456789012345678901234"
times: [6]s64 = .[59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000]
sha1_codes: [6]string = .["94287082", "07081804", "14050471", "89005924", "69279037", "65353130"]
sha256_codes: [6]string = .["46119246", "68084774", "67062674", "91819424", "90698825", "77737706"]
sha512_codes: [6]string = .["90693936", "25091201", "99943326", "93441116", "38618901", "47863826"]
for index: 0..5 {
if !Expect(HASH_SHA1, sha1, times[index], sha1_codes[index]) {
return 10 + cast(s32)index
}
if !Expect(HASH_SHA256, sha256, times[index], sha256_codes[index]) {
return 20 + cast(s32)index
}
if !Expect(HASH_SHA512, sha512, times[index], sha512_codes[index]) {
return 30 + cast(s32)index
}
}
decoded: [KEY_LIMIT]u8
count := Base32Decode("gezd gnbv-gy3t qojq GEZDGNBVGY3TQOJQ====", decoded[:])
if count != 20 || TextView(decoded[0:20]) != sha1 || Base32Decode("GEZ1", decoded[:]) != -1 {
return 40
}
account: Account
link := "otpauth://totp/Example%20Co:alice%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Example%20Co&algorithm=SHA256&digits=8&period=60"
if !ParseLink(link, *account) || TextUntilNul(account.issuer[:]) != "Example Co" ||
TextUntilNul(account.name[:]) != "[email protected]" || account.kind != HASH_SHA256 ||
account.digits != 8 || account.period != 60 || account.key_count != 20 {
return 41
}
saved: [1024]u8
again: Account
if !ParseLink(LinkText(*account, saved[:]), *again) || TextUntilNul(again.secret[:]) != TextUntilNul(account.secret[:]) ||
TextUntilNul(again.issuer[:]) != "Example Co" || again.digits != 8 || again.period != 60 {
return 42
}
if ParseLink("otpauth://hotp/Example:alice?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&counter=1", *again) ||
ParseLink("otpauth://totp/Example:alice?secret=SHORT", *again) {
return 43
}
return 0
}
+22 -25
View File
@@ -1,25 +1,22 @@
Box :: #import "kryon/box";
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Calculator: a keypad and keyboard calculator. Basic covers ordinary
// arithmetic with brackets; Scientific adds trigonometry in degrees or
// radians, hyperbolic functions, powers, roots, logarithms, factorials and
// constants. It keeps the expression in memory; the mode and angle unit are
// saved.
#import "session"
#import "geometry"
#import "text_props"
#import "text_align"
#import "text_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "box_props"
#import "box_widget"
#import "text_buffer"
#import "number_text"
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/text_align"
#import "kryon/control_props"
#import "std/text_buffer"
#import "std/number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "arithmetic"
Icon :: #import "mingcute_regular_counter";
DeleteBack :: #import "mingcute_regular_delete_back";
Icon :: #import "mingcute/mingcute_regular_counter";
DeleteBack :: #import "mingcute/mingcute_regular_delete_back";
using ButtonTone;
using ButtonEmphasis;
@@ -339,17 +336,17 @@ Press :: (key: Key) {
}
Tab :: (session: Session, id: s32, label: string, bounds: Rectangle, active: bool) -> bool {
props := ButtonProps.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
props := Button.Props.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if active {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) != 0
return Button.Draw(session, props) != 0
}
DrawKey :: (session: Session, index: s32, key: Key, bounds: Rectangle) {
props := ButtonProps.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
props := Button.Props.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
.label = key.label,
.tone = cast(ButtonTone)(ifx key.accent then ButtonToneAccent else ButtonToneNeutral),
.emphasis = cast(ButtonEmphasis)(ifx key.accent then ButtonEmphasisFilled else ButtonEmphasisSoft)}
@@ -358,7 +355,7 @@ DrawKey :: (session: Session, index: s32, key: Key, bounds: Rectangle) {
props.icon_shape = DeleteBack.Shape
props.label = ""
}
if Button(session, props) != 0 {
if Button.Draw(session, props) != 0 {
Press(key)
}
}
@@ -385,7 +382,7 @@ Draw :: () {
top += 36.0 + gap
display_height: float32 = ifx scientific then 104.0 else 112.0
display := Rectangle.{left, top, width, display_height}
Box(session, BoxProps.{.key = cast(u64)3, .bounds = display, .radius = 12.0})
Box.Draw(session, Box.Props.{.key = cast(u64)3, .bounds = display, .radius = 12.0})
shown := ExpressionText()
if shown == "" {
shown = "0"
@@ -397,18 +394,18 @@ Draw :: () {
if shown.count > 28 {
font = 18
}
Text(session, TextProps.{.key = cast(u64)4,
Text.Draw(session, Text.Props.{.key = cast(u64)4,
.bounds = Rectangle.{left + 16.0, top + 14.0, width - 32.0, 48.0},
.text = shown, .font = font, .align = TextAlign.TextAlignEnd, .wrap = TextWrap.TextWrapEllipsis})
Text(session, TextProps.{.key = cast(u64)5,
.text = shown, .size = font, .align = TextAlign.TextAlignEnd, .wrap = Text.Wrap.TextWrapEllipsis})
Text.Draw(session, Text.Props.{.key = cast(u64)5,
.bounds = Rectangle.{left + 16.0, top + display_height - 36.0, width - 32.0, 24.0},
.text = TextUntilNul(result_text[:]), .font = 16, .align = TextAlign.TextAlignEnd})
.text = TextUntilNul(result_text[:]), .size = 16, .align = TextAlign.TextAlignEnd})
if scientific {
// The angle unit, switched by tapping it.
unit := ButtonProps.{.key = cast(u64)6, .id = 6, .bounds = Rectangle.{left + 10.0, top + display_height - 38.0, 64.0, 28.0},
unit := Button.Props.{.key = cast(u64)6, .id = 6, .bounds = Rectangle.{left + 10.0, top + display_height - 38.0, 64.0, 28.0},
.label = ifx degrees then "DEG" else "RAD", .size = ControlSize.ControlSizeSmall,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, unit) != 0 {
if Button.Draw(session, unit) != 0 {
degrees = !degrees
SaveSettings()
}
+812
View File
@@ -0,0 +1,812 @@
// Simple Calendar: Month, Week, and Agenda views with local event creation,
// editing, deletion, recurrence, search and private persistence.
Box :: #import "kryon/box";
Button :: #import "kryon/button";
Checkbox :: #import "kryon/checkbox";
Scroll :: #import "kryon/scroll";
Text :: #import "kryon/text";
TextField :: #import "kryon/text_field";
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "kryon/control_props"
#import "kryon/drawing_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/text_align"
#import "kryon/tree"
#import "std/number_text"
#import "std/text_buffer"
#import "calendar_model"
Icon :: #import "mingcute/mingcute_regular_calendar";
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
STORE_BUFFER_CAP :: 65536;
session: Session;
store: CalendarStore;
loaded: bool;
dirty: bool;
view_mode: s32 = VIEW_MONTH;
display_year: s64 = 2026;
display_month: s32 = 1;
selected_year: s64 = 2026;
selected_month: s32 = 1;
selected_day: s32 = 1;
local_offset: s32;
local_offset_at: float64 = -61.0;
day_scroll_y: s32;
week_scroll_y: s32;
agenda_scroll_y: s32;
editor_scroll_y: s32;
// Search in Agenda view.
search_buf: [96]u8;
search_state: FieldState;
// Event editor state.
editing: bool;
edit_index: s32 = -1; // -1 when creating a new event
edit_title: [EVENT_TITLE_CAP]u8;
edit_date: [16]u8;
edit_start: [16]u8;
edit_end: [16]u8;
edit_location: [EVENT_LOCATION_CAP]u8;
edit_notes: [EVENT_NOTES_CAP]u8;
edit_all_day: bool;
edit_recurrence: s32;
edit_color: s32;
edit_error: [96]u8;
edit_fields: [6]FieldState;
focused_field: s32; // 0 none, 1..6 editor fields, 10 search
store_io_buf: [STORE_BUFFER_CAP]u8;
TodayCivil :: () -> CivilDate {
now := AppNow()
if now - local_offset_at > 60.0 {
local_offset = AppLocalOffset()
local_offset_at = now
}
secs := cast(s64)now
if cast(float64)secs > now { secs -= 1 }
local := secs + cast(s64)local_offset
days := local / 86400
if local < 0 && local % 86400 != 0 { days -= 1 }
return CivilFromDays(days)
}
JumpToday :: () {
today := TodayCivil()
display_year = today.year
display_month = today.month
selected_year = today.year
selected_month = today.month
selected_day = today.day
day_scroll_y = 0
}
LoadCalendar :: () {
StoreInit(*store)
count := ReadStore("calendar.json", store_io_buf[:])
if count > 0 {
unused DeserializeStore(TextView(store_io_buf[:count]), *store)
}
view_mode = store.default_view
JumpToday()
loaded = true
dirty = false
}
SaveCalendar :: () {
store.default_view = view_mode
used := SerializeStore(*store, store_io_buf[:])
if used > 0 {
unused WriteStore("calendar.json", TextView(store_io_buf[:used]))
dirty = false
}
}
SwatchColor :: (index: s32) -> Color {
if index == 1 { return Color.{46, 158, 102, 255} } // Green
if index == 2 { return Color.{219, 143, 36, 255} } // Amber
if index == 3 { return Color.{209, 71, 77, 255} } // Red
if index == 4 { return Color.{138, 92, 199, 255} } // Purple
if index == 5 { return Color.{36, 153, 168, 255} } // Teal
return Color.{56, 128, 219, 255} // Blue
}
SwatchName :: (index: s32) -> string {
names: [COLOR_COUNT]string = .["Blue", "Green", "Amber", "Red", "Purple", "Teal"]
if index < 0 || index >= COLOR_COUNT { return names[0] }
return names[index]
}
OpenNewEvent :: (year: s64, month: s32, day: s32) {
editing = true
edit_index = -1
edit_title[0] = cast(u8)0
edit_location[0] = cast(u8)0
edit_notes[0] = cast(u8)0
edit_error[0] = cast(u8)0
unused FormatDateISO(year, month, day, edit_date[:])
CopyField(edit_start[:], "09:00")
CopyField(edit_end[:], "10:00")
edit_all_day = false
edit_recurrence = REPEAT_NONE
edit_color = 0
for i: 0..5 { edit_fields[i] = FieldState.{} }
editor_scroll_y = 0
focused_field = 1
}
OpenEditEvent :: (index: s32) {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return }
ev := *store.events[index]
editing = true
edit_index = index
CopyField(edit_title[:], TextUntilNul(ev.title[:]))
CopyField(edit_location[:], TextUntilNul(ev.location[:]))
CopyField(edit_notes[:], TextUntilNul(ev.notes[:]))
unused FormatDateISO(ev.year, ev.month, ev.day, edit_date[:])
unused FormatTimeHHMM(ev.start_minute, edit_start[:])
unused FormatTimeHHMM(ev.end_minute, edit_end[:])
edit_all_day = ev.all_day
edit_recurrence = ev.recurrence
edit_color = ev.color
edit_error[0] = cast(u8)0
for i: 0..5 { edit_fields[i] = FieldState.{} }
editor_scroll_y = 0
focused_field = 1
}
CommitEditor :: () {
title := TextUntilNul(edit_title[:])
if title.count == 0 {
CopyField(edit_error[:], "Please enter an event title.")
return
}
parsed := ParseDateISO(TextUntilNul(edit_date[:]))
if !parsed.ok {
CopyField(edit_error[:], "Date must be YYYY-MM-DD.")
return
}
start_min: s32 = 540
end_min: s32 = 600
if !edit_all_day {
st := ParseTimeHHMM(TextUntilNul(edit_start[:]))
et := ParseTimeHHMM(TextUntilNul(edit_end[:]))
if !st.ok || !et.ok {
CopyField(edit_error[:], "Times must be HH:MM (24-hour).")
return
}
if et.minute < st.minute {
CopyField(edit_error[:], "End time must be after start time.")
return
}
start_min = st.minute
end_min = et.minute
}
ev: CalendarEvent
ev.year = parsed.year
ev.month = parsed.month
ev.day = parsed.day
ev.all_day = edit_all_day
ev.start_minute = start_min
ev.end_minute = end_min
ev.recurrence = edit_recurrence
ev.color = edit_color
CopyField(ev.title[:], title)
CopyField(ev.location[:], TextUntilNul(edit_location[:]))
CopyField(ev.notes[:], TextUntilNul(edit_notes[:]))
if edit_index >= 0 {
unused UpdateEvent(*store, edit_index, ev)
} else {
if AddEvent(*store, ev) < 0 {
CopyField(edit_error[:], "Calendar event limit reached.")
return
}
}
selected_year = parsed.year
selected_month = parsed.month
selected_day = parsed.day
display_year = parsed.year
display_month = parsed.month
editing = false
focused_field = 0
dirty = true
SaveCalendar()
}
ApplyEdit :: (buffer: []u8, edit: TextField.Edit) -> bool {
if !edit.changed { return false }
length := cast(s32)TextUntilNul(buffer).count
if edit.start < 0 || edit.end < edit.start || edit.end > length { return false }
used := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
if used >= cast(s32)buffer.count || used >= 512 { return false }
next: [512]u8
pos: s32 = 0
for i: 0..edit.start - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)edit.replacement.count - 1 { next[pos] = edit.replacement[i]; pos += 1 }
for i: edit.end..length - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)buffer.count - 1 {
buffer[i] = ifx i < used then next[i] else cast(u8)0
}
return true
}
DrawField :: (id: s32, label: string, buffer: []u8, state: *FieldState, bounds: Rectangle) -> bool {
snapshot: [512]u8
CopyField(snapshot[:], TextUntilNul(buffer))
props: TextField.Props
props.key = cast(u64)(900 + id)
props.focus_id = 900 + id
props.bounds = bounds
props.label = label
props.value = TextUntilNul(snapshot[:])
props.cursor = state.cursor
props.anchor = state.anchor
props.scroll_x = state.scroll_x
props.focused = focused_field == id
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
if props.focused { props.input = AppFieldInput() }
result := TextField.Draw(session, props)
state.cursor = result.cursor
state.anchor = result.anchor
state.scroll_x = result.scroll_x
changed := ApplyEdit(buffer, result.edit)
if result.focused { focused_field = id }
if result.escaped && focused_field == id { focused_field = 0 }
return changed
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.size = ControlSize.ControlSizeSmall
props.tone = ifx accent then ButtonTone.ButtonToneAccent else ButtonTone.ButtonToneNeutral
props.emphasis = ifx accent then ButtonEmphasis.ButtonEmphasisFilled else ButtonEmphasis.ButtonEmphasisSoft
return Button.Draw(session, props) != 0
}
DangerAction :: (id: s32, label: string, bounds: Rectangle) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.size = ControlSize.ControlSizeSmall
props.tone = ButtonTone.ButtonToneDanger
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
return Button.Draw(session, props) != 0
}
DrawText :: (key: u64, value: string, bounds: Rectangle, size: s32, align: TextAlign) {
Text.Draw(session, Text.Props.{.key = key, .bounds = bounds, .text = value, .size = size,
.align = align, .wrap = Text.Wrap.TextWrapEllipsis})
}
FormatEventTimeRange :: (ev: *CalendarEvent, out: []u8) -> string {
if ev.all_day { return "All day" }
s_buf: [12]u8
e_buf: [12]u8
used := AppendText(out, 0, FormatTimeHHMM(ev.start_minute, s_buf[:]))
used = AppendText(out, used, " - ")
used = AppendText(out, used, FormatTimeHHMM(ev.end_minute, e_buf[:]))
return TextView(out[:used])
}
DrawEventRow :: (row_id: s32, ev_index: s32, bounds: Rectangle, show_date: bool, y: s64, m: s32, d: s32) -> bool {
ev := *store.events[ev_index]
dark := AppDark()
card_bg := ifx dark then Color.{38, 41, 48, 255} else Color.{242, 245, 250, 255}
border := ifx dark then Color.{66, 71, 87, 255} else Color.{214, 219, 232, 255}
base_key := cast(u64)(5000 + row_id * 10)
Box.Draw(session, Box.Props.{.key = base_key, .bounds = bounds, .fill = card_bg, .border = border, .radius = 8.0})
// Color accent bar on the left.
Box.Draw(session, Box.Props.{.key = base_key + 1,
.bounds = Rectangle.{bounds.x + 2.0, bounds.y + 6.0, 5.0, bounds.height - 12.0},
.fill = SwatchColor(ev.color), .radius = 2.5})
time_buf: [32]u8
meta_buf: [160]u8
used: s32 = 0
if show_date {
iso: [16]u8
used = AppendText(meta_buf[:], used, FormatDateISO(y, m, d, iso[:]))
used = AppendText(meta_buf[:], used, " ")
}
used = AppendText(meta_buf[:], used, FormatEventTimeRange(ev, time_buf[:]))
if ev.recurrence != REPEAT_NONE {
used = AppendText(meta_buf[:], used, " [")
used = AppendText(meta_buf[:], used, RecurrenceLabel(ev.recurrence))
used = AppendText(meta_buf[:], used, "]")
}
loc := TextUntilNul(ev.location[:])
if loc.count > 0 {
used = AppendText(meta_buf[:], used, " @ ")
used = AppendText(meta_buf[:], used, loc)
}
text_w := bounds.width - 78.0
DrawText(base_key + 2, TextUntilNul(ev.title[:]),
Rectangle.{bounds.x + 14.0, bounds.y + 6.0, text_w, 20.0}, 14, TextAlign.TextAlignStart)
DrawText(base_key + 3, TextView(meta_buf[:used]),
Rectangle.{bounds.x + 14.0, bounds.y + 27.0, text_w, 18.0}, 12, TextAlign.TextAlignStart)
return Action(6000 + row_id, "Edit",
Rectangle.{bounds.x + bounds.width - 58.0, bounds.y + 10.0, 50.0, 30.0}, false)
}
DrawMonthView :: (area: Rectangle) {
today := TodayCivil()
// Month navigation header.
nav_y := area.y
if Action(100, "<", Rectangle.{area.x, nav_y, 34.0, 32.0}, false) {
step := StepMonth(display_year, display_month, -1)
display_year = step.year
display_month = step.month
}
if Action(101, ">", Rectangle.{area.x + 38.0, nav_y, 34.0, 32.0}, false) {
step := StepMonth(display_year, display_month, 1)
display_year = step.year
display_month = step.month
}
title_buf: [48]u8
tu := AppendText(title_buf[:], 0, MonthName(display_month))
tu = AppendText(title_buf[:], tu, " ")
tu = AppendNumber(title_buf[:], tu, display_year)
DrawText(102, TextView(title_buf[:tu]),
Rectangle.{area.x + 78.0, nav_y + 5.0, area.width - 216.0, 24.0}, 16, TextAlign.TextAlignCenter)
if Action(103, "Today", Rectangle.{area.x + area.width - 134.0, nav_y, 58.0, 32.0}, false) {
JumpToday()
}
if Action(104, ifx store.week_starts_monday then "Mon" else "Sun",
Rectangle.{area.x + area.width - 72.0, nav_y, 36.0, 32.0}, false) {
store.week_starts_monday = !store.week_starts_monday
dirty = true
SaveCalendar()
}
if Action(105, "+", Rectangle.{area.x + area.width - 32.0, nav_y, 32.0, 32.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
// Weekday headers.
wd_y := nav_y + 38.0
col_w := area.width / 7.0
for col: 0..6 {
wd_idx := ifx store.week_starts_monday then (cast(s32)col + 1) % 7 else cast(s32)col
DrawText(cast(u64)(110 + col), WeekdayShortName(wd_idx),
Rectangle.{area.x + cast(float32)col * col_w, wd_y, col_w, 18.0}, 12, TextAlign.TextAlignCenter)
}
// 6x7 Month grid.
grid: [42]GridCell
BuildMonthGrid(display_year, display_month, store.week_starts_monday, grid[:])
grid_y := wd_y + 22.0
cell_h: float32 = 38.0
if area.height < 480.0 { cell_h = 32.0 }
dark := AppDark()
today_border := Color.{56, 140, 235, 255}
dot_color := Color.{61, 173, 115, 255}
muted_fill := ifx dark then Color.{28, 31, 36, 255} else Color.{245, 247, 250, 255}
for idx: 0..41 {
row := idx / 7
col := idx % 7
cell := grid[idx]
cx := area.x + cast(float32)col * col_w + 1.5
cy := grid_y + cast(float32)row * cell_h + 1.5
cw := col_w - 3.0
ch := cell_h - 3.0
is_sel := cell.year == selected_year && cell.month == selected_month && cell.day == selected_day
is_today := cell.year == today.year && cell.month == today.month && cell.day == today.day
ev_count := DateEventCount(*store, cell.year, cell.month, cell.day)
if !cell.in_month && !is_sel {
Box.Draw(session, Box.Props.{.key = cast(u64)(200 + idx), .bounds = Rectangle.{cx, cy, cw, ch},
.fill = muted_fill, .radius = 6.0})
}
label_buf: [16]u8
lu := AppendNumber(label_buf[:], 0, cast(s64)cell.day)
if ev_count > 0 {
lu = AppendText(label_buf[:], lu, "*")
}
props: Button.Props
props.key = cast(u64)(300 + idx)
props.id = 300 + cast(s32)idx
props.bounds = Rectangle.{cx, cy, cw, ch}
props.label = TextView(label_buf[:lu])
props.size = ControlSize.ControlSizeSmall
props.tone = ifx is_sel then ButtonTone.ButtonToneAccent else ButtonTone.ButtonToneNeutral
props.emphasis = ifx is_sel then ButtonEmphasis.ButtonEmphasisFilled else (ifx cell.in_month then ButtonEmphasis.ButtonEmphasisSoft else ButtonEmphasis.ButtonEmphasisGhost)
if Button.Draw(session, props) != 0 {
selected_year = cell.year
selected_month = cell.month
selected_day = cell.day
display_year = cell.year
display_month = cell.month
day_scroll_y = 0
}
if is_today && !is_sel {
Box.Draw(session, Box.Props.{.key = cast(u64)(400 + idx), .bounds = Rectangle.{cx, cy, cw, ch},
.border = today_border, .radius = 6.0})
}
if ev_count > 0 {
Box.Draw(session, Box.Props.{.key = cast(u64)(450 + idx),
.bounds = Rectangle.{cx + cw * 0.5 - 3.0, cy + ch - 5.0, 6.0, 3.0},
.fill = ifx is_sel then Color.{255, 255, 255, 230} else dot_color, .radius = 1.5})
}
}
// Selected day agenda panel below grid.
panel_y := grid_y + cell_h * 6.0 + 10.0
date_buf: [64]u8
DrawText(500, FormatDateLong(selected_year, selected_month, selected_day, date_buf[:]),
Rectangle.{area.x, panel_y + 4.0, area.width - 102.0, 22.0}, 15, TextAlign.TextAlignStart)
if Action(501, "+ Event", Rectangle.{area.x + area.width - 94.0, panel_y, 94.0, 30.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
list_y := panel_y + 36.0
list_h := area.y + area.height - list_y
if list_h < 56.0 { list_h = 56.0 }
day_events: [64]s32
found := EventsOnDate(*store, selected_year, selected_month, selected_day, day_events[:])
if found == 0 {
DrawText(502, "No events scheduled for this day.",
Rectangle.{area.x + 4.0, list_y + 10.0, area.width - 8.0, 22.0}, 13, TextAlign.TextAlignStart)
return
}
row_h: float32 = 54.0
content_h := cast(s32)(cast(float32)found * row_h) + 8
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
scroll := Scroll.Draw(session, Scroll.Props.{.key = 505, .bounds = list_bounds,
.scroll_offset = day_scroll_y, .content_height = content_h, .scale = 1.0})
day_scroll_y = scroll.scroll_offset
if scroll.opened {
for i: 0..found - 1 {
y := scroll.content.y + cast(float32)i * row_h
if DrawEventRow(cast(s32)i, day_events[i],
Rectangle.{scroll.content.x, y, scroll.content.width - 10.0, row_h - 4.0},
false, selected_year, selected_month, selected_day) {
OpenEditEvent(day_events[i])
}
}
End(session)
}
}
DrawWeekView :: (area: Rectangle) {
sel_days := DaysFromCivil(selected_year, selected_month, selected_day)
start_days := WeekStartDays(sel_days, store.week_starts_monday)
start_c := CivilFromDays(start_days)
end_c := CivilFromDays(start_days + 6)
today := TodayCivil()
// Week navigation header.
nav_y := area.y
if Action(150, "<", Rectangle.{area.x, nav_y, 34.0, 32.0}, false) {
c := CivilFromDays(sel_days - 7)
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
if Action(151, ">", Rectangle.{area.x + 38.0, nav_y, 34.0, 32.0}, false) {
c := CivilFromDays(sel_days + 7)
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
range_buf: [64]u8
ru := AppendNumber(range_buf[:], 0, cast(s64)start_c.day)
ru = AppendText(range_buf[:], ru, " ")
ru = AppendText(range_buf[:], ru, MonthShortName(start_c.month))
ru = AppendText(range_buf[:], ru, " - ")
ru = AppendNumber(range_buf[:], ru, cast(s64)end_c.day)
ru = AppendText(range_buf[:], ru, " ")
ru = AppendText(range_buf[:], ru, MonthShortName(end_c.month))
ru = AppendText(range_buf[:], ru, " ")
ru = AppendNumber(range_buf[:], ru, end_c.year)
DrawText(152, TextView(range_buf[:ru]),
Rectangle.{area.x + 76.0, nav_y + 5.0, area.width - 176.0, 24.0}, 15, TextAlign.TextAlignCenter)
if Action(153, "Today", Rectangle.{area.x + area.width - 96.0, nav_y, 58.0, 32.0}, false) { JumpToday() }
if Action(154, "+", Rectangle.{area.x + area.width - 34.0, nav_y, 34.0, 32.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
// Scrollable 7-day breakdown.
list_y := nav_y + 40.0
list_h := area.y + area.height - list_y
if list_h < 60.0 { list_h = 60.0 }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
// Measure total content height.
day_counts: [7]s32
total_h: float32 = 8.0
for d: 0..6 {
c := CivilFromDays(start_days + cast(s64)d)
day_counts[d] = DateEventCount(*store, c.year, c.month, c.day)
total_h += 34.0 + (ifx day_counts[d] > 0 then cast(float32)day_counts[d] * 54.0 else 26.0) + 6.0
}
content_h := cast(s32)total_h
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
scroll := Scroll.Draw(session, Scroll.Props.{.key = 160, .bounds = list_bounds,
.scroll_offset = week_scroll_y, .content_height = content_h, .scale = 1.0})
week_scroll_y = scroll.scroll_offset
if scroll.opened {
cur_y := scroll.content.y
cw := scroll.content.width - 10.0
row_counter: s32 = 100
day_events: [32]s32
for d: 0..6 {
c := CivilFromDays(start_days + cast(s64)d)
is_today := c.year == today.year && c.month == today.month && c.day == today.day
is_sel := c.year == selected_year && c.month == selected_month && c.day == selected_day
hdr_buf: [64]u8
hu := AppendText(hdr_buf[:], 0, WeekdayShortName(c.weekday))
hu = AppendText(hdr_buf[:], hu, ", ")
hu = AppendNumber(hdr_buf[:], hu, cast(s64)c.day)
hu = AppendText(hdr_buf[:], hu, " ")
hu = AppendText(hdr_buf[:], hu, MonthShortName(c.month))
if is_today { hu = AppendText(hdr_buf[:], hu, " (Today)") }
if Action(700 + cast(s32)d, TextView(hdr_buf[:hu]),
Rectangle.{scroll.content.x, cur_y, cw - 66.0, 28.0}, is_sel) {
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
if Action(710 + cast(s32)d, "+ Add",
Rectangle.{scroll.content.x + cw - 60.0, cur_y, 60.0, 28.0}, false) {
OpenNewEvent(c.year, c.month, c.day)
}
cur_y += 34.0
found := EventsOnDate(*store, c.year, c.month, c.day, day_events[:])
if found == 0 {
DrawText(cast(u64)(720 + d), "No events",
Rectangle.{scroll.content.x + 10.0, cur_y, cw - 20.0, 20.0}, 12, TextAlign.TextAlignStart)
cur_y += 26.0
} else {
for k: 0..found - 1 {
if DrawEventRow(row_counter, day_events[k],
Rectangle.{scroll.content.x, cur_y, cw, 50.0},
false, c.year, c.month, c.day) {
OpenEditEvent(day_events[k])
}
row_counter += 1
cur_y += 54.0
}
}
cur_y += 6.0
}
End(session)
}
}
DrawAgendaView :: (area: Rectangle) {
top_y := area.y
if DrawField(10, "Search events...", search_buf[:], *search_state,
Rectangle.{area.x, top_y, area.width - 76.0, 36.0}) {
agenda_scroll_y = 0
}
if Action(170, "+ New", Rectangle.{area.x + area.width - 70.0, top_y, 70.0, 36.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
today := TodayCivil()
items: [128]AgendaItem
query := TextUntilNul(search_buf[:])
count := CollectAgenda(*store, DaysFromCivil(today.year, today.month, today.day), 60, query, items[:])
list_y := top_y + 44.0
list_h := area.y + area.height - list_y
if list_h < 60.0 { list_h = 60.0 }
if count == 0 {
DrawText(171, ifx query.count > 0 then "No matching events found." else "No upcoming events in the next 60 days.",
Rectangle.{area.x + 4.0, list_y + 10.0, area.width - 8.0, 24.0}, 14, TextAlign.TextAlignStart)
return
}
row_h: float32 = 54.0
content_h := cast(s32)(cast(float32)count * row_h) + 8
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
scroll := Scroll.Draw(session, Scroll.Props.{.key = 175, .bounds = list_bounds,
.scroll_offset = agenda_scroll_y, .content_height = content_h, .scale = 1.0})
agenda_scroll_y = scroll.scroll_offset
if scroll.opened {
for i: 0..count - 1 {
y := scroll.content.y + cast(float32)i * row_h
it := items[i]
if DrawEventRow(400 + cast(s32)i, it.event_index,
Rectangle.{scroll.content.x, y, scroll.content.width - 10.0, row_h - 4.0},
true, it.year, it.month, it.day) {
OpenEditEvent(it.event_index)
}
}
End(session)
}
}
StepEditorDate :: (delta: s64) {
p := ParseDateISO(TextUntilNul(edit_date[:]))
if !p.ok { return }
c := CivilFromDays(DaysFromCivil(p.year, p.month, p.day) + delta)
unused FormatDateISO(c.year, c.month, c.day, edit_date[:])
}
DrawEditor :: (area: Rectangle) {
DrawText(800, ifx edit_index >= 0 then "Edit Event" else "New Event",
Rectangle.{area.x, area.y, area.width, 26.0}, 18, TextAlign.TextAlignStart)
body_y := area.y + 32.0
body_h := area.height - 84.0
if body_h < 120.0 { body_h = 120.0 }
list_bounds := Rectangle.{area.x, body_y, area.width, body_h}
content_h: s32 = 430
if content_h < cast(s32)body_h { content_h = cast(s32)body_h }
scroll := Scroll.Draw(session, Scroll.Props.{.key = 805, .bounds = list_bounds,
.scroll_offset = editor_scroll_y, .content_height = content_h, .scale = 1.0})
editor_scroll_y = scroll.scroll_offset
if scroll.opened {
y := scroll.content.y
x := scroll.content.x
w := scroll.content.width - 10.0
unused DrawField(1, "Title", edit_title[:], *edit_fields[0], Rectangle.{x, y, w, 38.0})
y += 46.0
// Date field with -1d / +1d quick step buttons.
unused DrawField(2, "Date (YYYY-MM-DD)", edit_date[:], *edit_fields[1], Rectangle.{x, y, w - 92.0, 38.0})
if Action(810, "-1d", Rectangle.{x + w - 88.0, y, 42.0, 38.0}, false) { StepEditorDate(-1) }
if Action(811, "+1d", Rectangle.{x + w - 42.0, y, 42.0, 38.0}, false) { StepEditorDate(1) }
y += 46.0
// All-day checkbox.
cb_props := Checkbox.Props.{.key = 812, .id = 812, .label = "All-day event",
.bounds = Rectangle.{x, y, w, 30.0}, .checked = edit_all_day}
edit_all_day = Checkbox.Draw(session, cb_props).checked
y += 36.0
if !edit_all_day {
half := (w - 8.0) * 0.5
unused DrawField(3, "Start (HH:MM)", edit_start[:], *edit_fields[2], Rectangle.{x, y, half, 38.0})
unused DrawField(4, "End (HH:MM)", edit_end[:], *edit_fields[3], Rectangle.{x + half + 8.0, y, half, 38.0})
y += 46.0
}
// Recurrence selector.
DrawText(813, "Repeat", Rectangle.{x, y, w, 18.0}, 13, TextAlign.TextAlignStart)
y += 22.0
rep_w := (w - 16.0) / 5.0
for r: 0..4 {
if Action(820 + cast(s32)r, RecurrenceLabel(cast(s32)r),
Rectangle.{x + cast(float32)r * (rep_w + 4.0), y, rep_w, 30.0},
edit_recurrence == cast(s32)r) {
edit_recurrence = cast(s32)r
}
}
y += 38.0
// Color swatches.
DrawText(814, "Color", Rectangle.{x, y, w, 18.0}, 13, TextAlign.TextAlignStart)
y += 22.0
sw_w := (w - 20.0) / cast(float32)COLOR_COUNT
for c: 0..COLOR_COUNT - 1 {
sx := x + cast(float32)c * (sw_w + 4.0)
if Action(830 + cast(s32)c, SwatchName(cast(s32)c),
Rectangle.{sx, y, sw_w, 28.0}, edit_color == cast(s32)c) {
edit_color = cast(s32)c
}
Box.Draw(session, Box.Props.{.key = cast(u64)(840 + c),
.bounds = Rectangle.{sx + 4.0, y + 29.0, sw_w - 8.0, 4.0},
.fill = SwatchColor(cast(s32)c), .radius = 2.0})
}
y += 42.0
unused DrawField(5, "Location (optional)", edit_location[:], *edit_fields[4], Rectangle.{x, y, w, 38.0})
y += 46.0
unused DrawField(6, "Notes (optional)", edit_notes[:], *edit_fields[5], Rectangle.{x, y, w, 38.0})
y += 46.0
err := TextUntilNul(edit_error[:])
if err.count > 0 {
DrawText(850, err, Rectangle.{x, y, w, 22.0}, 13, TextAlign.TextAlignStart)
}
End(session)
}
// Bottom buttons: Save, Cancel, Delete.
btn_y := area.y + area.height - 42.0
if Action(860, "Save", Rectangle.{area.x, btn_y, 96.0, 38.0}, true) {
CommitEditor()
}
if Action(861, "Cancel", Rectangle.{area.x + 104.0, btn_y, 96.0, 38.0}, false) {
editing = false
focused_field = 0
}
if edit_index >= 0 {
if DangerAction(862, "Delete", Rectangle.{area.x + area.width - 96.0, btn_y, 96.0, 38.0}) {
unused DeleteEvent(*store, edit_index)
editing = false
focused_field = 0
dirty = true
SaveCalendar()
}
}
}
Draw :: () {
session = AppSession()
bounds := AppBounds()
pad: float32 = 12.0
area := Rectangle.{bounds.x + pad, bounds.y + 8.0, bounds.width - pad * 2.0, bounds.height - 16.0}
if editing {
DrawEditor(area)
AppKeyboard(focused_field != 0)
return
}
// Top view switcher: Month | Week | Agenda.
tab_w := (area.width - 12.0) / 3.0
if Action(10, "Month", Rectangle.{area.x, area.y, tab_w, 34.0}, view_mode == VIEW_MONTH) {
view_mode = VIEW_MONTH
focused_field = 0
dirty = true
}
if Action(11, "Week", Rectangle.{area.x + tab_w + 6.0, area.y, tab_w, 34.0}, view_mode == VIEW_WEEK) {
view_mode = VIEW_WEEK
focused_field = 0
dirty = true
}
if Action(12, "Agenda", Rectangle.{area.x + (tab_w + 6.0) * 2.0, area.y, tab_w, 34.0}, view_mode == VIEW_AGENDA) {
view_mode = VIEW_AGENDA
dirty = true
}
body := Rectangle.{area.x, area.y + 42.0, area.width, area.height - 42.0}
if view_mode == VIEW_MONTH {
DrawMonthView(body)
} else if view_mode == VIEW_WEEK {
DrawWeekView(body)
} else {
DrawAgendaView(body)
}
AppKeyboard(focused_field != 0)
}
#program_export "CalendarMain"
Main :: () -> s32 {
mode := AppMode()
if mode == APP_IDENTIFY {
AppIdentity("calendar")
AppDescribe("Calendar", Icon.Shape)
return APP_PROTOCOL
}
if mode == APP_SAVE {
if loaded && dirty { SaveCalendar() }
return 0
}
if mode != APP_FRAME {
return 0
}
if !loaded {
LoadCalendar()
}
Draw()
return 0
}
+630
View File
@@ -0,0 +1,630 @@
// Simple Calendar model: proleptic Gregorian date math, month/week grids,
// recurring events, search, agenda queries and JSON persistence.
#import "std/json_scan"
#import "std/number_text"
#import "std/text_buffer"
#import "std/vec"
MAX_EVENTS :: 256;
EVENT_TITLE_CAP :: 128;
EVENT_LOCATION_CAP :: 128;
EVENT_NOTES_CAP :: 256;
REPEAT_NONE :: 0;
REPEAT_DAILY :: 1;
REPEAT_WEEKLY :: 2;
REPEAT_MONTHLY :: 3;
REPEAT_YEARLY :: 4;
VIEW_MONTH :: 0;
VIEW_WEEK :: 1;
VIEW_AGENDA :: 2;
COLOR_COUNT :: 6;
CivilDate :: struct {
year: s64
month: s32
day: s32
weekday: s32 // 0 = Sunday .. 6 = Saturday
}
CalendarEvent :: struct {
id: s32
active: bool
year: s64
month: s32
day: s32
all_day: bool
start_minute: s32 // 0..1439
end_minute: s32 // 0..1440
recurrence: s32
color: s32
title: [EVENT_TITLE_CAP]u8
location: [EVENT_LOCATION_CAP]u8
notes: [EVENT_NOTES_CAP]u8
}
GridCell :: struct {
year: s64
month: s32
day: s32
in_month: bool
days: s64
}
CalendarStore :: struct {
events: [MAX_EVENTS]CalendarEvent
next_id: s32
week_starts_monday: bool
default_view: s32
}
AgendaItem :: struct {
event_index: s32
days: s64
year: s64
month: s32
day: s32
}
MonthYear :: struct {
year: s64
month: s32
}
ParsedDate :: struct {
year: s64
month: s32
day: s32
ok: bool
}
ParsedTime :: struct {
minute: s32
ok: bool
}
IsLeapYear :: (year: s64) -> bool {
if year % 400 == 0 { return true }
if year % 100 == 0 { return false }
return year % 4 == 0
}
DaysInMonth :: (year: s64, month: s32) -> s32 {
if month == 2 { return ifx IsLeapYear(year) then 29 else 28 }
if month == 4 || month == 6 || month == 9 || month == 11 { return 30 }
return 31
}
// Howard Hinnant's civil/days algorithms (proleptic Gregorian, 1970-01-01 = 0).
DaysFromCivil :: (year: s64, month: s32, day: s32) -> s64 {
y := year - (ifx month <= 2 then 1 else 0)
era := ifx y >= 0 then y / 400 else (y - 399) / 400
yoe := y - era * 400
m := cast(s64)month
doy := (153 * (ifx m > 2 then m - 3 else m + 9) + 2) / 5 + cast(s64)day - 1
doe := yoe * 365 + yoe / 4 - yoe / 100 + doy
return era * 146097 + doe - 719468
}
CivilFromDays :: (days: s64) -> CivilDate {
shifted := days + 719468
era := ifx shifted >= 0 then shifted / 146097 else (shifted - 146096) / 146097
doe := shifted - era * 146097
yoe := (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
doy := doe - (365 * yoe + yoe / 4 - yoe / 100)
mp := (5 * doy + 2) / 153
result: CivilDate
result.day = cast(s32)(doy - (153 * mp + 2) / 5 + 1)
result.month = cast(s32)(ifx mp < 10 then mp + 3 else mp - 9)
result.year = yoe + era * 400 + (ifx result.month <= 2 then 1 else 0)
wd := (days + 4) % 7
if wd < 0 { wd += 7 }
result.weekday = cast(s32)wd
return result
}
WeekdayOf :: (year: s64, month: s32, day: s32) -> s32 {
return CivilFromDays(DaysFromCivil(year, month, day)).weekday
}
ValidDate :: (year: s64, month: s32, day: s32) -> bool {
if year < 1 || year > 9999 { return false }
if month < 1 || month > 12 { return false }
if day < 1 || day > DaysInMonth(year, month) { return false }
return true
}
StepMonth :: (year: s64, month: s32, delta: s32) -> MonthYear {
total := year * 12 + cast(s64)(month - 1) + cast(s64)delta
ny := total / 12
nm := total % 12
if nm < 0 {
nm += 12
ny -= 1
}
return MonthYear.{.year = ny, .month = cast(s32)(nm + 1)}
}
MonthName :: (month: s32) -> string {
names: [12]string = .["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
if month < 1 || month > 12 { return names[0] }
return names[month - 1]
}
MonthShortName :: (month: s32) -> string {
names: [12]string = .["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
if month < 1 || month > 12 { return names[0] }
return names[month - 1]
}
WeekdayName :: (weekday: s32) -> string {
names: [7]string = .["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
if weekday < 0 || weekday > 6 { return names[0] }
return names[weekday]
}
WeekdayShortName :: (weekday: s32) -> string {
names: [7]string = .["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
if weekday < 0 || weekday > 6 { return names[0] }
return names[weekday]
}
RecurrenceLabel :: (recurrence: s32) -> string {
if recurrence == REPEAT_DAILY { return "Daily" }
if recurrence == REPEAT_WEEKLY { return "Weekly" }
if recurrence == REPEAT_MONTHLY { return "Monthly" }
if recurrence == REPEAT_YEARLY { return "Yearly" }
return "Once"
}
BuildMonthGrid :: (year: s64, month: s32, week_starts_monday: bool, out: []GridCell) {
first_days := DaysFromCivil(year, month, 1)
first_wd := CivilFromDays(first_days).weekday
offset: s32 = ifx week_starts_monday then (first_wd + 6) % 7 else first_wd
start_days := first_days - cast(s64)offset
for index: 0..41 {
if index >= out.count { break }
d := start_days + cast(s64)index
c := CivilFromDays(d)
out[index] = GridCell.{.year = c.year, .month = c.month, .day = c.day,
.in_month = c.year == year && c.month == month, .days = d}
}
}
WeekStartDays :: (days: s64, week_starts_monday: bool) -> s64 {
wd := CivilFromDays(days).weekday
offset: s32 = ifx week_starts_monday then (wd + 6) % 7 else wd
return days - cast(s64)offset
}
StoreInit :: (store: *CalendarStore) {
store.* = CalendarStore.{}
store.next_id = 1
store.week_starts_monday = false
store.default_view = VIEW_MONTH
}
CopyField :: (dst: []u8, src: string) {
limit := src.count
if limit >= dst.count { limit = dst.count - 1 }
for i: 0..limit - 1 { dst[i] = src[i] }
dst[limit] = cast(u8)0
}
AppendText :: (out: []u8, used: s32, text: string) -> s32 {
pos := used
for i: 0..text.count - 1 {
if pos >= cast(s32)out.count - 1 { break }
out[pos] = text[i]
pos += 1
}
out[pos] = cast(u8)0
return pos
}
AppendTwoDigits :: (out: []u8, used: s32, value: s64) -> s32 {
v := ifx value < 0 then 0 else value
digits: [2]u8
digits[0] = cast(u8)(48 + cast(s32)((v / 10) % 10))
digits[1] = cast(u8)(48 + cast(s32)(v % 10))
return AppendText(out, used, TextView(digits[:]))
}
AppendFourDigits :: (out: []u8, used: s32, value: s64) -> s32 {
v := ifx value < 0 then 0 else value
digits: [4]u8
digits[0] = cast(u8)(48 + cast(s32)((v / 1000) % 10))
digits[1] = cast(u8)(48 + cast(s32)((v / 100) % 10))
digits[2] = cast(u8)(48 + cast(s32)((v / 10) % 10))
digits[3] = cast(u8)(48 + cast(s32)(v % 10))
return AppendText(out, used, TextView(digits[:]))
}
AppendNumber :: (out: []u8, used: s32, value: s64) -> s32 {
buf: [32]u8
return AppendText(out, used, FormatInteger(value, buf[:]))
}
FormatDateISO :: (year: s64, month: s32, day: s32, out: []u8) -> string {
used := AppendFourDigits(out, 0, year)
used = AppendText(out, used, "-")
used = AppendTwoDigits(out, used, cast(s64)month)
used = AppendText(out, used, "-")
used = AppendTwoDigits(out, used, cast(s64)day)
return TextView(out[:used])
}
ParseDateISO :: (text: string) -> ParsedDate {
bad := ParsedDate.{}
if text.count != 10 { return bad }
if text[4] != cast(u8)45 || text[7] != cast(u8)45 { return bad }
for i: 0..9 {
if i == 4 || i == 7 { continue }
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
}
year := cast(s64)(text[0] - 48) * 1000 + cast(s64)(text[1] - 48) * 100 +
cast(s64)(text[2] - 48) * 10 + cast(s64)(text[3] - 48)
month := cast(s32)(text[5] - 48) * 10 + cast(s32)(text[6] - 48)
day := cast(s32)(text[8] - 48) * 10 + cast(s32)(text[9] - 48)
if !ValidDate(year, month, day) { return bad }
return ParsedDate.{.year = year, .month = month, .day = day, .ok = true}
}
FormatTimeHHMM :: (minute_of_day: s32, out: []u8) -> string {
m := minute_of_day
if m < 0 { m = 0 }
if m > 1439 { m = 1439 }
used := AppendTwoDigits(out, 0, cast(s64)(m / 60))
used = AppendText(out, used, ":")
used = AppendTwoDigits(out, used, cast(s64)(m % 60))
return TextView(out[:used])
}
ParseTimeHHMM :: (text: string) -> ParsedTime {
bad := ParsedTime.{}
if text.count < 4 || text.count > 5 { return bad }
colon: s64 = -1
for i: 0..text.count - 1 {
if text[i] == cast(u8)58 { colon = i; break }
}
if colon < 1 || colon > 2 || text.count - colon - 1 != 2 { return bad }
hour: s32 = 0
for i: 0..colon - 1 {
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
hour = hour * 10 + cast(s32)(text[i] - 48)
}
minute: s32 = 0
for i: colon + 1..text.count - 1 {
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
minute = minute * 10 + cast(s32)(text[i] - 48)
}
if hour < 0 || hour > 23 || minute < 0 || minute > 59 { return bad }
return ParsedTime.{.minute = hour * 60 + minute, .ok = true}
}
FormatDateLong :: (year: s64, month: s32, day: s32, out: []u8) -> string {
wd := WeekdayOf(year, month, day)
used := AppendText(out, 0, WeekdayName(wd))
used = AppendText(out, used, ", ")
used = AppendNumber(out, used, cast(s64)day)
used = AppendText(out, used, " ")
used = AppendText(out, used, MonthName(month))
used = AppendText(out, used, " ")
used = AppendNumber(out, used, year)
return TextView(out[:used])
}
EventOccursOn :: (event: *CalendarEvent, year: s64, month: s32, day: s32) -> bool {
if !event.active { return false }
target_days := DaysFromCivil(year, month, day)
start_days := DaysFromCivil(event.year, event.month, event.day)
if target_days < start_days { return false }
if event.recurrence == REPEAT_NONE {
return target_days == start_days
}
if event.recurrence == REPEAT_DAILY {
return true
}
if event.recurrence == REPEAT_WEEKLY {
return (target_days - start_days) % 7 == 0
}
if event.recurrence == REPEAT_MONTHLY {
max_day := DaysInMonth(year, month)
expected_day := ifx event.day > max_day then max_day else event.day
return day == expected_day
}
if event.recurrence == REPEAT_YEARLY {
if month != event.month { return false }
max_day := DaysInMonth(year, month)
expected_day := ifx event.day > max_day then max_day else event.day
return day == expected_day
}
return false
}
EventBefore :: (a: *CalendarEvent, b: *CalendarEvent) -> bool {
if a.all_day != b.all_day { return a.all_day }
if !a.all_day && a.start_minute != b.start_minute { return a.start_minute < b.start_minute }
return a.id < b.id
}
EventsOnDate :: (store: *CalendarStore, year: s64, month: s32, day: s32, out: []s32) -> s32 {
count: s32 = 0
for i: 0..MAX_EVENTS - 1 {
if EventOccursOn(*store.events[i], year, month, day) {
if count >= cast(s32)out.count { break }
out[count] = cast(s32)i
count += 1
}
}
// Insertion sort by all_day first, then start_minute, then id.
for i: 1..count - 1 {
key := out[i]
j := i - 1
while j >= 0 && EventBefore(*store.events[key], *store.events[out[j]]) {
out[j + 1] = out[j]
j -= 1
}
out[j + 1] = key
}
return count
}
DateEventCount :: (store: *CalendarStore, year: s64, month: s32, day: s32) -> s32 {
count: s32 = 0
for i: 0..MAX_EVENTS - 1 {
if EventOccursOn(*store.events[i], year, month, day) { count += 1 }
}
return count
}
AddEvent :: (store: *CalendarStore, item: CalendarEvent) -> s32 {
for i: 0..MAX_EVENTS - 1 {
if !store.events[i].active {
ev := item
ev.active = true
if ev.id <= 0 {
ev.id = store.next_id
store.next_id += 1
} else if ev.id >= store.next_id {
store.next_id = ev.id + 1
}
if ev.color < 0 || ev.color >= COLOR_COUNT { ev.color = 0 }
if ev.recurrence < REPEAT_NONE || ev.recurrence > REPEAT_YEARLY { ev.recurrence = REPEAT_NONE }
store.events[i] = ev
return cast(s32)i
}
}
return -1
}
UpdateEvent :: (store: *CalendarStore, index: s32, item: CalendarEvent) -> bool {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return false }
ev := item
ev.id = store.events[index].id
ev.active = true
if ev.color < 0 || ev.color >= COLOR_COUNT { ev.color = 0 }
if ev.recurrence < REPEAT_NONE || ev.recurrence > REPEAT_YEARLY { ev.recurrence = REPEAT_NONE }
store.events[index] = ev
return true
}
DeleteEvent :: (store: *CalendarStore, index: s32) -> bool {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return false }
store.events[index] = CalendarEvent.{}
return true
}
FindEventById :: (store: *CalendarStore, id: s32) -> s32 {
for i: 0..MAX_EVENTS - 1 {
if store.events[i].active && store.events[i].id == id { return cast(s32)i }
}
return -1
}
AsciiLower :: (b: u8) -> u8 {
if b >= cast(u8)65 && b <= cast(u8)90 { return b + cast(u8)32 }
return b
}
ContainsFold :: (haystack: string, needle: string) -> bool {
if needle.count == 0 { return true }
if needle.count > haystack.count { return false }
limit := haystack.count - needle.count
for start: 0..limit {
ok := true
for k: 0..needle.count - 1 {
if AsciiLower(haystack[start + k]) != AsciiLower(needle[k]) {
ok = false
break
}
}
if ok { return true }
}
return false
}
EventMatchesQuery :: (event: *CalendarEvent, query: string) -> bool {
if query.count == 0 { return true }
if ContainsFold(TextUntilNul(event.title[:]), query) { return true }
if ContainsFold(TextUntilNul(event.location[:]), query) { return true }
if ContainsFold(TextUntilNul(event.notes[:]), query) { return true }
return false
}
CollectAgenda :: (store: *CalendarStore, from_days: s64, horizon_days: s32, query: string, out: []AgendaItem) -> s32 {
count: s32 = 0
if query.count > 0 {
// When searching, list all matching events sorted by their start date.
for i: 0..MAX_EVENTS - 1 {
if !store.events[i].active { continue }
if !EventMatchesQuery(*store.events[i], query) { continue }
if count >= cast(s32)out.count { break }
ev := *store.events[i]
out[count] = AgendaItem.{.event_index = cast(s32)i,
.days = DaysFromCivil(ev.year, ev.month, ev.day),
.year = ev.year, .month = ev.month, .day = ev.day}
count += 1
}
for i: 1..count - 1 {
key := out[i]
j := i - 1
while j >= 0 && (key.days < out[j].days ||
(key.days == out[j].days && EventBefore(*store.events[key.event_index], *store.events[out[j].event_index]))) {
out[j + 1] = out[j]
j -= 1
}
out[j + 1] = key
}
return count
}
day_indices: [64]s32
for offset: 0..horizon_days - 1 {
if count >= cast(s32)out.count { break }
d := from_days + cast(s64)offset
c := CivilFromDays(d)
found := EventsOnDate(store, c.year, c.month, c.day, day_indices[:])
for k: 0..found - 1 {
if count >= cast(s32)out.count { break }
out[count] = AgendaItem.{.event_index = day_indices[k], .days = d,
.year = c.year, .month = c.month, .day = c.day}
count += 1
}
}
return count
}
WriteQuoted :: (bytes: *Vec(u8), text: string) {
BuilderPrint(bytes, "\"")
hex := "0123456789abcdef"
for byte: text {
if byte == cast(u8)34 || byte == cast(u8)92 {
BuilderPrint(bytes, "\\")
unused VecPush(bytes.*, byte)
} else if byte == cast(u8)10 {
BuilderPrint(bytes, "\\n")
} else if byte == cast(u8)13 {
BuilderPrint(bytes, "\\r")
} else if byte == cast(u8)9 {
BuilderPrint(bytes, "\\t")
} else if byte < cast(u8)32 {
BuilderPrint(bytes, "\\u00")
unused VecPush(bytes.*, hex[cast(s32)byte / 16])
unused VecPush(bytes.*, hex[cast(s32)byte % 16])
} else {
unused VecPush(bytes.*, byte)
}
}
BuilderPrint(bytes, "\"")
}
SerializeStore :: (store: *CalendarStore, out: []u8) -> s32 {
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"v\":1,\"next_id\":%,\"week_starts_monday\":%,\"default_view\":%,\"events\":[",
store.next_id, ifx store.week_starts_monday then "true" else "false", store.default_view)
first := true
for i: 0..MAX_EVENTS - 1 {
ev := *store.events[i]
if !ev.active { continue }
if !first { BuilderPrint(*bytes, ",") }
first = false
BuilderPrint(*bytes, "{\"id\":%,\"y\":%,\"m\":%,\"d\":%,\"all_day\":%,\"start\":%,\"end\":%,\"repeat\":%,\"color\":%,\"title\":",
ev.id, ev.year, ev.month, ev.day,
ifx ev.all_day then "true" else "false",
ev.start_minute, ev.end_minute, ev.recurrence, ev.color)
WriteQuoted(*bytes, TextUntilNul(ev.title[:]))
BuilderPrint(*bytes, ",\"location\":")
WriteQuoted(*bytes, TextUntilNul(ev.location[:]))
BuilderPrint(*bytes, ",\"notes\":")
WriteQuoted(*bytes, TextUntilNul(ev.notes[:]))
BuilderPrint(*bytes, "}")
}
BuilderPrint(*bytes, "]}\n")
count := cast(s32)bytes.count
if count >= cast(s32)out.count {
VecFree(bytes)
return -1
}
{
slice := VecSlice(bytes, 0, bytes.count)
for i: 0..count - 1 { out[i] = slice[i] }
}
out[count] = cast(u8)0
VecFree(bytes)
return count
}
ReadJsonInt :: (text: string, obj: s32, field: string, fallback: s64) -> s64 {
at := FieldAt(text, obj, field)
if at < 0 { return fallback }
num := ReadNumber(text, at)
return ifx num.valid then cast(s64)num.value else fallback
}
ReadJsonBool :: (text: string, obj: s32, field: string, fallback: bool) -> bool {
at := FieldAt(text, obj, field)
if at < 0 { return fallback }
if MatchLiteral(text, at, "true") { return true }
if MatchLiteral(text, at, "false") { return false }
return fallback
}
ReadJsonString :: (text: string, obj: s32, field: string, out: []u8) {
out[0] = cast(u8)0
at := FieldAt(text, obj, field)
if at < 0 { return }
used := ReadStringText(text, at, out)
if used < 0 {
out[0] = cast(u8)0
} else if used < cast(s32)out.count {
out[used] = cast(u8)0
} else {
out[out.count - 1] = cast(u8)0
}
}
DeserializeStore :: (text: string, store: *CalendarStore) -> bool {
StoreInit(store)
if text.count == 0 { return false }
root := Space(text, 0)
if root >= cast(s32)text.count || text[root] != cast(u8)123 { return false }
store.next_id = cast(s32)ReadJsonInt(text, root, "next_id", 1)
if store.next_id < 1 { store.next_id = 1 }
store.week_starts_monday = ReadJsonBool(text, root, "week_starts_monday", false)
store.default_view = cast(s32)ReadJsonInt(text, root, "default_view", VIEW_MONTH)
if store.default_view < VIEW_MONTH || store.default_view > VIEW_AGENDA {
store.default_view = VIEW_MONTH
}
arr := FieldAt(text, root, "events")
if arr < 0 { return true }
count := ArrayCount(text, arr)
at := Space(text, arr + 1)
for i: 0..count - 1 {
if at >= cast(s32)text.count { break }
if text[at] == cast(u8)123 {
ev: CalendarEvent
ev.id = cast(s32)ReadJsonInt(text, at, "id", 0)
ev.year = ReadJsonInt(text, at, "y", 2026)
ev.month = cast(s32)ReadJsonInt(text, at, "m", 1)
ev.day = cast(s32)ReadJsonInt(text, at, "d", 1)
ev.all_day = ReadJsonBool(text, at, "all_day", false)
ev.start_minute = cast(s32)ReadJsonInt(text, at, "start", 540)
ev.end_minute = cast(s32)ReadJsonInt(text, at, "end", 600)
ev.recurrence = cast(s32)ReadJsonInt(text, at, "repeat", REPEAT_NONE)
ev.color = cast(s32)ReadJsonInt(text, at, "color", 0)
ReadJsonString(text, at, "title", ev.title[:])
ReadJsonString(text, at, "location", ev.location[:])
ReadJsonString(text, at, "notes", ev.notes[:])
if ValidDate(ev.year, ev.month, ev.day) && ev.title[0] != cast(u8)0 {
unused AddEvent(store, ev)
}
}
at = Space(text, ValueEnd(text, at, 0))
if at < cast(s32)text.count && text[at] == cast(u8)44 { at = Space(text, at + 1) }
}
return true
}
+114
View File
@@ -0,0 +1,114 @@
// Unit tests for Simple Calendar date math, grid generation, recurrence,
// search, agenda ordering and JSON persistence.
#import "std/text_buffer"
#import "calendar_model"
#program_export
Run :: () -> s32 {
// Leap years and month lengths.
if !IsLeapYear(2024) || !IsLeapYear(2000) { return 1 }
if IsLeapYear(1900) || IsLeapYear(2026) { return 2 }
if DaysInMonth(2024, 2) != 29 || DaysInMonth(2026, 2) != 28 { return 3 }
if DaysInMonth(2026, 11) != 30 || DaysInMonth(2026, 12) != 31 { return 4 }
// Civil <-> Days roundtrip and weekdays (1970-01-01 = Thursday = 4; 2026-11-21 = Saturday = 6).
if DaysFromCivil(1970, 1, 1) != 0 { return 5 }
epoch := CivilFromDays(0)
if epoch.year != 1970 || epoch.month != 1 || epoch.day != 1 || epoch.weekday != 4 { return 6 }
d2026 := DaysFromCivil(2026, 11, 21)
c2026 := CivilFromDays(d2026)
if c2026.year != 2026 || c2026.month != 11 || c2026.day != 21 || c2026.weekday != 6 { return 7 }
// StepMonth across year boundaries.
s1 := StepMonth(2026, 1, -1)
if s1.year != 2025 || s1.month != 12 { return 8 }
s2 := StepMonth(2026, 12, 1)
if s2.year != 2027 || s2.month != 1 { return 9 }
// Month grid (November 2026 starts on Sunday = 0).
grid_sun: [42]GridCell
BuildMonthGrid(2026, 11, false, grid_sun[:])
if grid_sun[0].year != 2026 || grid_sun[0].month != 11 || grid_sun[0].day != 1 || !grid_sun[0].in_month { return 10 }
if grid_sun[29].day != 30 || !grid_sun[29].in_month { return 11 }
if grid_sun[30].month != 12 || grid_sun[30].day != 1 || grid_sun[30].in_month { return 12 }
grid_mon: [42]GridCell
BuildMonthGrid(2026, 11, true, grid_mon[:])
if grid_mon[0].month != 10 || grid_mon[0].day != 26 || grid_mon[0].in_month { return 13 }
if grid_mon[6].month != 11 || grid_mon[6].day != 1 || !grid_mon[6].in_month { return 14 }
// Date and time parsing/formatting.
pd := ParseDateISO("2026-11-21")
if !pd.ok || pd.year != 2026 || pd.month != 11 || pd.day != 21 { return 15 }
bad_date := ParseDateISO("2026-02-29")
if bad_date.ok { return 16 }
pt := ParseTimeHHMM("09:45")
if !pt.ok || pt.minute != 585 { return 17 }
bad_time := ParseTimeHHMM("25:00")
if bad_time.ok { return 18 }
// Store CRUD, recurrence, sorting, search.
store: CalendarStore
StoreInit(*store)
store.week_starts_monday = true
e1: CalendarEvent
e1.year = 2026; e1.month = 11; e1.day = 21
e1.all_day = false; e1.start_minute = 600; e1.end_minute = 660
e1.recurrence = REPEAT_WEEKLY; e1.color = 1
CopyField(e1.title[:], "Team Sync")
CopyField(e1.location[:], "Room \"A\"")
CopyField(e1.notes[:], "Line1\nLine2")
idx1 := AddEvent(*store, e1)
if idx1 < 0 { return 19 }
e2: CalendarEvent
e2.year = 2026; e2.month = 11; e2.day = 21
e2.all_day = true; e2.recurrence = REPEAT_NONE; e2.color = 2
CopyField(e2.title[:], "Release Day")
idx2 := AddEvent(*store, e2)
if idx2 < 0 { return 20 }
e3: CalendarEvent
e3.year = 2026; e3.month = 1; e3.day = 31
e3.all_day = false; e3.start_minute = 480; e3.end_minute = 510
e3.recurrence = REPEAT_MONTHLY; e3.color = 3
CopyField(e3.title[:], "Month End")
if AddEvent(*store, e3) < 0 { return 21 }
// Sorting on 2026-11-21: all-day event first, then timed event.
hits: [16]s32
found := EventsOnDate(*store, 2026, 11, 21, hits[:])
if found != 2 || hits[0] != idx2 || hits[1] != idx1 { return 22 }
// Weekly recurrence on 2026-11-28, and not before start date (2026-11-14).
if DateEventCount(*store, 2026, 11, 28) != 1 { return 23 }
if DateEventCount(*store, 2026, 11, 14) != 0 { return 24 }
// Monthly clamping on Feb 28 2026 for a Jan 31 monthly event.
if DateEventCount(*store, 2026, 2, 28) != 1 { return 25 }
// JSON persistence round-trip.
json_buf: [8192]u8
used := SerializeStore(*store, json_buf[:])
if used <= 0 { return 26 }
reloaded: CalendarStore
if !DeserializeStore(TextView(json_buf[:used]), *reloaded) { return 27 }
if !reloaded.week_starts_monday { return 28 }
if DateEventCount(*reloaded, 2026, 11, 21) != 2 { return 29 }
r_idx := FindEventById(*reloaded, store.events[idx1].id)
if r_idx < 0 { return 30 }
if TextUntilNul(reloaded.events[r_idx].title[:]) != "Team Sync" { return 31 }
if TextUntilNul(reloaded.events[r_idx].location[:]) != "Room \"A\"" { return 32 }
// Search via CollectAgenda.
agenda: [16]AgendaItem
qcount := CollectAgenda(*reloaded, d2026, 30, "sync", agenda[:])
if qcount != 1 || agenda[0].event_index != r_idx { return 33 }
// Delete event.
if !DeleteEvent(*reloaded, r_idx) { return 34 }
if DateEventCount(*reloaded, 2026, 11, 21) != 1 { return 35 }
return 0
}
+13 -15
View File
@@ -1,18 +1,16 @@
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Clock: the local time and date, and a stopwatch that keeps running while
// the app is closed.
#import "session"
#import "geometry"
#import "text_props"
#import "text_align"
#import "text_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "text_buffer"
#import "number_text"
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/text_align"
#import "kryon/control_props"
#import "std/text_buffer"
#import "std/number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
Icon :: #import "mingcute_regular_time";
Icon :: #import "mingcute/mingcute_regular_time";
VIEW_CLOCK :: 0
VIEW_STOPWATCH :: 1
@@ -205,18 +203,18 @@ SaveStopwatch :: () {
}
Big :: (key: u64, text: string, area: Rectangle, y: float32, font: s32) {
Text(session, TextProps.{.key = key, .bounds = Rectangle.{area.x + 16.0, y, area.width - 32.0, cast(float32)(font + 16)},
.text = text, .font = font, .align = TextAlign.TextAlignCenter})
Text.Draw(session, Text.Props.{.key = key, .bounds = Rectangle.{area.x + 16.0, y, area.width - 32.0, cast(float32)(font + 16)},
.text = text, .size = font, .align = TextAlign.TextAlignCenter})
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props := ButtonProps.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
props := Button.Props.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) != 0
return Button.Draw(session, props) != 0
}
Draw :: () {
+196
View File
@@ -0,0 +1,196 @@
// Gallery is a separate portable tool. Only Werk knows platform file grants.
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/tree"
Text :: #import "kryon/text";
Button :: #import "kryon/button";
#import "kryon/control_props"
#import "std/number_text"
#import "std/c_string"
#import "std/text_buffer"
#import "kryon/app_context"
#import "kryon/app_protocol"
Model :: #import "gallery_model";
Icon :: #import "mingcute/mingcute_regular_photo_album";
Image :: #import "kryon/image";
Showing :: #import "kryon/image_showing";
Scroll :: #import "kryon/scroll";
listing: Model.Listing;
viewer: Model.Viewer = Model.Viewer.{.selected = -1, .zoom = 1};
loaded: bool;
status: [32]u8;
location: [1024]u8;
can_up: bool;
grid_offset: s32;
zoom_x: s32;
zoom_y: s32;
session: Session;
// The host's navigation is in the same retained tree as the active tool.
// Keep Gallery controls separate from its Home/avatar keys.
KEY_BASE :: 2000000
Call :: (request: string) -> string { return AppService("gallery.local.v1", request) }
Indexed :: (verb: string, index: s32) -> string {
number: [24]u8; buffer: [64]u8
text := FormatInteger(cast(s64)index, number[:])
for at: 0..verb.count - 1 { buffer[at] = verb[at] }
for at: 0..text.count - 1 { buffer[verb.count + at] = text[at] }
buffer[verb.count + text.count] = cast(u8)0
return Call(TextUntilNul(buffer[:]))
}
Reload :: () {
listing.count = Model.Index(Call("count"))
if listing.count < 0 { listing.count = 0 }
if listing.count > Model.LIMIT { listing.count = Model.LIMIT }
for index: 0..listing.count - 1 {
unused CopyCString(Indexed("name:", cast(s32)index), listing.entries[index].name[:])
listing.entries[index].folder = Indexed("kind:", cast(s32)index) == "folder"
listing.entries[index].path[0] = cast(u8)0
}
unused CopyCString(Call("location"), location[:]); can_up = Call("can-up") == "yes"
unused CopyCString(Call("status"), status[:])
viewer = Model.Viewer.{.selected = -1, .zoom = 1}; grid_offset = 0; zoom_x = 0; zoom_y = 0
}
Action :: (id: s32, label: string, bounds: Rectangle, disabled: bool) -> bool {
return Button.Draw(session, Button.Props.{.key = cast(u64)(KEY_BASE + id), .id = KEY_BASE + id, .bounds = bounds,
.label = label, .disabled = disabled, .tone = ButtonTone.ButtonToneNeutral,
.emphasis = ButtonEmphasis.ButtonEmphasisSoft, .fit_content = true}) != 0
}
Label :: (key: u64, text: string, bounds: Rectangle) {
Text.Draw(session, Text.Props.{.key = cast(u64)KEY_BASE + key, .bounds = bounds, .text = text, .size = 16})
}
Picture :: (index: s32, bounds: Rectangle, preview: bool = false) -> bool {
entry := *listing.entries[index]
unused CopyCString(Indexed(ifx preview then "thumb:" else "asset:", index), entry.path[:])
props := Image.Props.{.key = cast(u64)(KEY_BASE + 5000 + index), .bounds = bounds,
.asset_path = TextUntilNul(entry.path[:]), .alt_text = TextUntilNul(entry.name[:]),
.fit = Image.ImageFit.ImageFitContain, .smooth = true}
if props.asset_path == "" {
Label(cast(u64)(7000 + index), "Image unavailable", bounds)
return false
}
state := Showing.ImageShowingOf(session, props)
if state == Image.ImageShowing.ImageShowingUnavailable {
Label(cast(u64)(7000 + index), "Image unavailable", bounds)
return false
}
if state == Image.ImageShowing.ImageShowingNone { Label(cast(u64)(7000 + index), "Loading image...", bounds) }
Image.Draw(session, props)
return true
}
DrawViewer :: (area: Rectangle) {
width := (area.width - 32.0) / 3.0
if Action(30, "Albums", Rectangle.{area.x, area.y, width, 42.0}, false) { viewer.selected = -1; return }
previous := viewer; Model.Move(*previous, *listing, -1)
next := viewer; Model.Move(*next, *listing, 1)
if Action(31, "Previous", Rectangle.{area.x + width + 8.0, area.y, width, 42.0}, previous.selected == viewer.selected) { viewer = previous; zoom_x = 0; zoom_y = 0 }
if Action(32, "Next", Rectangle.{area.x + (width + 8.0) * 2.0, area.y, width, 42.0}, next.selected == viewer.selected) { viewer = next; zoom_x = 0; zoom_y = 0 }
if AppKey() == 263 { Model.Move(*viewer, *listing, -1); zoom_x = 0; zoom_y = 0 }
if AppKey() == 262 { Model.Move(*viewer, *listing, 1); zoom_x = 0; zoom_y = 0 }
if AppKey() == 256 { viewer.selected = -1; return }
Label(40, TextUntilNul(listing.entries[viewer.selected].name[:]), Rectangle.{area.x, area.y + 50.0, area.width, 28.0})
viewport := Rectangle.{area.x, area.y + 84.0, area.width - 8.0, area.height - 194.0}
if viewport.height < 40.0 { viewport.height = 40.0 }
scale := cast(float32)viewer.zoom
horizontal := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 50, .bounds = viewport, .horizontal = true,
.content_width = cast(s32)(viewport.width * scale), .scroll_offset = zoom_x, .manual_scroll = true})
zoom_x = horizontal.scroll_offset
vertical := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 51, .bounds = viewport,
.content_height = cast(s32)(viewport.height * scale), .scroll_offset = zoom_y, .manual_scroll = true})
zoom_y = vertical.scroll_offset
available := Picture(viewer.selected, Rectangle.{horizontal.content.x, vertical.content.y, viewport.width * scale, viewport.height * scale})
if vertical.opened { unused End(session) }
if horizontal.opened { unused End(session) }
if !available {
problem: [256]u8
unused CopyCString(Indexed("asset-error:", viewer.selected), problem[:])
if problem[0] == cast(u8)0 { unused CopyCString(Model.ImageError(Model.IMAGE_FORMAT_ERROR), problem[:]) }
Label(54, TextUntilNul(problem[:]), Rectangle.{viewport.x + 8.0, viewport.y + 36.0, viewport.width - 16.0, 80.0})
if Action(55, "Retry image", Rectangle.{viewport.x + 8.0, viewport.y + 122.0, 140.0, 40.0}, false) { unused Indexed("retry:", viewer.selected) }
}
pan_width := (area.width - 24.0) / 4.0
pan_y := area.y + area.height - 94.0
step_x := cast(s32)(viewport.width / 4.0)
step_y := cast(s32)(viewport.height / 4.0)
max_x := cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1))
max_y := cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1))
if Action(60, "Pan left", Rectangle.{area.x, pan_y, pan_width, 38.0}, !available || zoom_x <= 0) { zoom_x -= step_x }
if Action(61, "Pan right", Rectangle.{area.x + pan_width + 8.0, pan_y, pan_width, 38.0}, !available || zoom_x >= max_x) { zoom_x += step_x }
if Action(62, "Pan up", Rectangle.{area.x + (pan_width + 8.0) * 2.0, pan_y, pan_width, 38.0}, !available || zoom_y <= 0) { zoom_y -= step_y }
if Action(63, "Pan down", Rectangle.{area.x + (pan_width + 8.0) * 3.0, pan_y, pan_width, 38.0}, !available || zoom_y >= max_y) { zoom_y += step_y }
if zoom_x < 0 { zoom_x = 0 }; if zoom_x > max_x { zoom_x = max_x }
if zoom_y < 0 { zoom_y = 0 }; if zoom_y > max_y { zoom_y = max_y }
y := area.y + area.height - 48.0
if Action(33, "Zoom out", Rectangle.{area.x, y, width, 42.0}, !available || viewer.zoom == 1) { Model.Zoom(*viewer, -1); zoom_x = cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1) * 0.5); zoom_y = cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1) * 0.5) }
if Action(34, "Fit", Rectangle.{area.x + width + 8.0, y, width, 42.0}, false) { viewer.zoom = 1; zoom_x = 0; zoom_y = 0 }
if Action(35, "Zoom in", Rectangle.{area.x + (width + 8.0) * 2.0, y, width, 42.0}, !available || viewer.zoom == 4) { Model.Zoom(*viewer, 1); zoom_x = cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1) * 0.5); zoom_y = cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1) * 0.5) }
}
DrawGrid :: (area: Rectangle) {
pending := TextUntilNul(status[:]) == "pending"
if Action(10, "Choose folder", Rectangle.{area.x, area.y, 148.0, 44.0}, pending) {
unused CopyCString(Call("choose"), status[:]); pending = TextUntilNul(status[:]) == "pending"
}
if Action(11, "Refresh", Rectangle.{area.x + 156.0, area.y, 92.0, 44.0}, pending) { unused Call("refresh"); Reload() }
if can_up && Action(12, "Up", Rectangle.{area.x + 256.0, area.y, 54.0, 44.0}, pending) { unused Call("up"); Reload() }
Label(13, TextUntilNul(location[:]), Rectangle.{area.x, area.y + 52.0, area.width, 26.0})
current := TextUntilNul(status[:])
message := "Name order - folders first"
if current == "pending" { message = "Choose a local folder in the system window" }
else if current == "empty" { message = "Choose a folder to browse photos on this device" }
else if current == "cancelled" { message = "Selection cancelled - your folder is unchanged" }
else if current == "error" { message = "Cannot read this folder. Choose it again or refresh." }
else if current == "save-error" { message = "Could not save this selection. Your previous folder is unchanged. Try again." }
else if current == "chooser-missing" { message = "Folder chooser unavailable. Install Zenity, then choose the folder again." }
else if current == "unavailable" { message = "Local folders are available in the Android and desktop apps" }
else if current == "limited" { message = "Showing first 512 items by name. Open a smaller folder." }
else if listing.count == 0 { message = "No supported photos or albums in this folder" }
Label(14, message, Rectangle.{area.x, area.y + 82.0, area.width, 46.0})
columns := cast(s32)(area.width / 150.0)
if columns < 2 { columns = 2 }
tile := (area.width - cast(float32)(columns - 1) * 8.0) / cast(float32)columns
height := tile + 38.0
rows := (listing.count + columns - 1) / columns
viewport := Rectangle.{area.x, area.y + 134.0, area.width, area.height - 134.0}
grid := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 20, .bounds = viewport,
.content_height = cast(s32)(cast(float32)rows * (height + 8.0)), .scroll_offset = grid_offset})
grid_offset = grid.scroll_offset
for index: 0..listing.count - 1 {
x := grid.content.x + cast(float32)(index % columns) * (tile + 8.0)
y := grid.content.y + cast(float32)(index / columns) * (height + 8.0)
if y + height >= viewport.y && y < viewport.y + viewport.height {
entry := *listing.entries[index]
if !entry.folder { unused Picture(cast(s32)index, Rectangle.{x + 4.0, y + 4.0, tile - 8.0, tile - 8.0}, true) }
else { Label(cast(u64)(4000 + index), "Folder", Rectangle.{x + 8.0, y + 12.0, tile - 16.0, tile - 12.0}) }
Label(cast(u64)(6000 + index), TextUntilNul(entry.name[:]), Rectangle.{x + 8.0, y + tile, tile - 16.0, 34.0})
if Button.Draw(session, Button.Props.{.key = cast(u64)(KEY_BASE + 100 + index), .id = cast(s32)(KEY_BASE + 100 + index),
.bounds = Rectangle.{x, y, tile, height}, .label = TextUntilNul(entry.name[:]),
.invisible = true, .disabled = pending}) != 0 {
if entry.folder { unused Indexed("enter:", cast(s32)index); loaded = false; break }
else { viewer = Model.Viewer.{.selected = cast(s32)index, .zoom = 1}; zoom_x = 0; zoom_y = 0 }
}
}
}
if grid.opened { unused End(session) }
}
#program_export "GalleryMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("gallery"); AppDescribe("Gallery", Icon.Shape); return APP_PROTOCOL
}
if AppMode() == APP_BACK && viewer.selected >= 0 { viewer.selected = -1; return 1 }
if AppMode() != APP_FRAME { return 0 }
session = AppSession()
if !loaded { Reload(); loaded = true }
if TextUntilNul(status[:]) == "pending" {
value := Call("poll")
if value != "pending" { Reload() }
}
area := AppBounds()
area.x += 12.0; area.y += 12.0; area.width -= 24.0; area.height -= 24.0
if viewer.selected >= 0 { DrawViewer(area) } else { DrawGrid(area) }
return 0
}
+152
View File
@@ -0,0 +1,152 @@
// Portable gallery state. No account, network, deletion or arbitrary-path API.
#import "std/text_buffer"
#import "std/byte_text_linux"
#import "std/c_string"
LIMIT :: 512
PATH_CAPACITY :: 1024
IMAGE_BYTE_LIMIT :: 67108864
IMAGE_PIXEL_LIMIT :: 32000000
IMAGE_READ_ERROR :: 1
IMAGE_FORMAT_ERROR :: 2
IMAGE_LIMIT_ERROR :: 3
ImageError :: (reason: s32) -> string {
if reason == IMAGE_READ_ERROR { return "Cannot read image. Retry or refresh the folder." }
if reason == IMAGE_FORMAT_ERROR { return "Cannot decode image. Retry or choose another photo." }
if reason == IMAGE_LIMIT_ERROR { return "Image exceeds the viewing limit: 64 MiB or 32 megapixels." }
return ""
}
Dimensions :: struct { width: s64; height: s64 }
Big16 :: (bytes: []u8, at: s32) -> s64 { return cast(s64)bytes[at] * 256 + cast(s64)bytes[at + 1] }
Little :: (bytes: []u8, at: s32, count: s32) -> s64 {
value: s64; multiplier: s64 = 1
for index: 0..count - 1 { value += cast(s64)bytes[at + index] * multiplier; multiplier *= 256 }
return value
}
Big32 :: (bytes: []u8, at: s32) -> s64 { return Big16(bytes, at) * 65536 + Big16(bytes, at + 2) }
PixelError :: (size: Dimensions) -> s32 {
if size.width <= 0 || size.height <= 0 { return IMAGE_FORMAT_ERROR }
if size.height > IMAGE_PIXEL_LIMIT || size.width > IMAGE_PIXEL_LIMIT / size.height { return IMAGE_LIMIT_ERROR }
return 0
}
// Header-only bounds checks run before a native decoder allocates pixels.
// JPEG's variable-length segments are walked by the host with bounded I/O.
HeaderDimensions :: (bytes: []u8) -> Dimensions {
if bytes.count < 30 { return .{} }
if bytes[0] == 137 && bytes[1] == 80 && bytes[2] == 78 && bytes[3] == 71 && bytes[12] == 73 && bytes[13] == 72 && bytes[14] == 68 && bytes[15] == 82 {
return Dimensions.{Big32(bytes, 16), Big32(bytes, 20)}
}
if bytes[0] == 71 && bytes[1] == 73 && bytes[2] == 70 { return Dimensions.{Little(bytes, 6, 2), Little(bytes, 8, 2)} }
if bytes[0] == 66 && bytes[1] == 77 {
height := Little(bytes, 22, 4)
if height >= 2147483648 { height = 4294967296 - height }
return Dimensions.{Little(bytes, 18, 4), height}
}
if bytes[0] == 82 && bytes[1] == 73 && bytes[2] == 70 && bytes[3] == 70 && bytes[8] == 87 && bytes[9] == 69 && bytes[10] == 66 && bytes[11] == 80 {
if bytes[15] == 88 { return Dimensions.{Little(bytes, 24, 3) + 1, Little(bytes, 27, 3) + 1} }
if bytes[15] == 76 && bytes[20] == 47 {
bits := Little(bytes, 21, 4)
return Dimensions.{(bits & 16383) + 1, ((bits >> 14) & 16383) + 1}
}
if bytes[15] == 32 && bytes[23] == 157 && bytes[24] == 1 && bytes[25] == 42 { return Dimensions.{Little(bytes, 26, 2) & 16383, Little(bytes, 28, 2) & 16383} }
}
return .{}
}
Entry :: struct {
name: [256]u8
path: [PATH_CAPACITY]u8
folder: bool
}
Listing :: struct {
entries: [LIMIT]Entry
count: s32
truncated: bool
}
Viewer :: struct {
selected: s32
zoom: s32
pan_x: s32
pan_y: s32
}
ImageName :: (name: string) -> bool {
dot: s64 = -1
for index: 0..name.count - 1 { if name[index] == #char "." { dot = index } }
if dot < 0 || name.count - dot > 6 { return false }
extension: [8]u8
for index: dot..name.count - 1 {
byte := name[index]
if byte >= #char "A" && byte <= #char "Z" { byte += cast(u8)32 }
extension[index - dot] = byte
}
suffix := TextUntilNul(extension[:])
return suffix == ".jpg" || suffix == ".jpeg" || suffix == ".png" || suffix == ".webp" || suffix == ".bmp" || suffix == ".gif"
}
// Bytewise UTF-8 order is stable across platforms, locales and launches.
Before :: (left: Entry, right: Entry) -> bool {
if left.folder != right.folder { return left.folder }
a := TextUntilNul(left.name[:]); b := TextUntilNul(right.name[:])
count := ifx a.count < b.count then a.count else b.count
for index: 0..count - 1 { if a[index] != b[index] { return a[index] < b[index] } }
if a.count != b.count { return a.count < b.count }
a = TextUntilNul(left.path[:]); b = TextUntilNul(right.path[:])
count = ifx a.count < b.count then a.count else b.count
for index: 0..count - 1 { if a[index] != b[index] { return a[index] < b[index] } }
return a.count < b.count
}
Add :: (listing: *Listing, name: string, path: string, folder: bool) -> bool {
if name == "" || name == "." || name == ".." || name.count >= 256 || path == "" || path.count >= PATH_CAPACITY { return false }
entry: Entry
unused CopyCString(name, entry.name[:]); unused CopyCString(path, entry.path[:]); entry.folder = folder
// Retain the first LIMIT entries in sorted order even when the provider's
// enumeration order varies. Never silently present an arbitrary subset.
at := listing.count
if at == LIMIT {
listing.truncated = true
if !Before(entry, listing.entries[LIMIT - 1]) { return false }
at -= 1
} else { listing.count += 1 }
while at > 0 && Before(entry, listing.entries[at - 1]) {
listing.entries[at] = listing.entries[at - 1]; at -= 1
}
listing.entries[at] = entry
return true
}
Index :: (text: string) -> s32 {
if text == "" { return -1 }
result: s32 = 0
for index: 0..text.count - 1 {
if text[index] < #char "0" || text[index] > #char "9" || result > 10000 { return -1 }
result = result * 10 + cast(s32)(text[index] - #char "0")
}
return result
}
Move :: (viewer: *Viewer, listing: *Listing, direction: s32) {
at := viewer.selected + direction
while at >= 0 && at < listing.count {
if !listing.entries[at].folder {
viewer.selected = at; viewer.zoom = 1; viewer.pan_x = 0; viewer.pan_y = 0; return
}
at += direction
}
}
Zoom :: (viewer: *Viewer, delta: s32) {
viewer.zoom += delta
if viewer.zoom < 1 { viewer.zoom = 1 }
if viewer.zoom > 4 { viewer.zoom = 4 }
viewer.pan_x = 0; viewer.pan_y = 0
}
Within :: (root: string, path: string) -> bool {
if root == "" || path == "" { return false }
if root == path { return true }
if root == "/" { return path[0] == #char "/" }
return path.count > root.count && path[:root.count] == root && path[root.count] == #char "/"
}
+166
View File
@@ -0,0 +1,166 @@
{
"format": 1,
"packages": [
{
"commit": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"dependencies": {},
"id": "p0dd67588478f9a3e",
"name": "libsamplerate",
"ref": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"source": true,
"url": "https://github.com/libsndfile/libsamplerate.git"
},
{
"commit": "829a65d769d935c4852f8159e964312c0957260a",
"dependencies": {},
"id": "p16cd0434af3dff7b",
"name": "sdl3",
"ref": "829a65d769d935c4852f8159e964312c0957260a",
"source": true,
"url": "https://github.com/libsdl-org/SDL.git"
},
{
"commit": "f26a552247e2cd367fd33def6860d903cac6ab8a",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p274c2dd6d03a7c0c",
"name": "avif",
"ref": "f26a552247e2cd367fd33def6860d903cac6ab8a",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "p2af20e0c835b1c63",
"name": "webp",
"ref": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "1844042d1ca751e62e61df7617dba19c98588339",
"dependencies": {},
"id": "p3b3c785a0e17e605",
"name": "libwebp",
"ref": "1844042d1ca751e62e61df7617dba19c98588339",
"source": true,
"url": "https://github.com/webmproject/libwebp.git"
},
{
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
"dependencies": {},
"id": "p57c0272208aae8db",
"name": "libavif",
"ref": "1aadfad932c98c069a1204261b1856f81f3bc199",
"source": true,
"url": "https://github.com/AOMediaCodec/libavif.git"
},
{
"commit": "bd278217e2bac754d868b3d6502eac4257658d4b",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa"},
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
"id": "p5d7d12505a42f7b3",
"name": "av1",
"ref": "bd278217e2bac754d868b3d6502eac4257658d4b",
"url": "https://github.com/ziranlang/av1.git"
},
{
"commit": "360553150917f352e49e1beb78917370792ccaef",
"dependencies": {},
"id": "p69c0e968ae5735d9",
"name": "image-codec",
"ref": "360553150917f352e49e1beb78917370792ccaef",
"url": "https://github.com/ziranlang/image-codec.git"
},
{
"commit": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"dependencies": {},
"id": "p74ab3cb6eb3b86fa",
"name": "libaom",
"ref": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"source": true,
"url": "https://aomedia.googlesource.com/aom"
},
{
"commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"dependencies": {},
"id": "pb24767b9eb34d961",
"name": "dav1d",
"ref": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"source": true,
"url": "https://github.com/videolan/dav1d.git"
},
{
"commit": "ce5837f80e8ce6cb8d2d9f77915095d764da3485",
"dependencies": {"dr_libs": "pb7c2dd1c09da0c1c", "libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e", "stb": "pe4a63e2d6e0424e7"},
"dependency_refs": {"dr_libs": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c", "libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7", "stb": "9600522de53973336fa033a289858a4354cbb04c"},
"id": "pb46a53117b2530ce",
"name": "audio",
"ref": "ce5837f80e8ce6cb8d2d9f77915095d764da3485",
"url": "https://github.com/ziranlang/audio.git"
},
{
"commit": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c",
"dependencies": {},
"id": "pb7c2dd1c09da0c1c",
"name": "dr_libs",
"ref": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c",
"source": true,
"url": "https://github.com/mackron/dr_libs.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"dependencies": {},
"id": "pcc7aa76725f2fb2f",
"name": "raylib",
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"source": true,
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "9cc6872f75447c3a24c16764f9829d0f58751cb0",
"dependencies": {},
"id": "pe1027b9d16704793",
"name": "mingcute",
"ref": "master",
"url": "https://github.com/kryonlabs/mingcute.git"
},
{
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"dependencies": {},
"id": "pe1fe9bbe80bf1d6d",
"name": "libopus",
"ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"source": true,
"url": "https://github.com/xiph/opus.git"
},
{
"commit": "9600522de53973336fa033a289858a4354cbb04c",
"dependencies": {},
"id": "pe4a63e2d6e0424e7",
"name": "stb",
"ref": "9600522de53973336fa033a289858a4354cbb04c",
"source": true,
"url": "https://github.com/nothings/stb.git"
},
{
"commit": "3f72441949d4e16094834fa9220e5d7fa77a0ac0",
"dependencies": {"audio": "pb46a53117b2530ce", "avif": "p274c2dd6d03a7c0c", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "raylib": "pcc7aa76725f2fb2f", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
"dependency_refs": {"audio": "ce5837f80e8ce6cb8d2d9f77915095d764da3485", "avif": "f26a552247e2cd367fd33def6860d903cac6ab8a", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "raylib": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
"id": "peb1e86e2b07f33bb",
"name": "kryon",
"ref": "3f72441949d4e16094834fa9220e5d7fa77a0ac0",
"url": "https://github.com/kryonlabs/kryon.git"
}
],
"root": {
"dependencies": {"kryon": "peb1e86e2b07f33bb", "mingcute": "pe1027b9d16704793"},
"dependency_refs": {"kryon": "3f72441949d4e16094834fa9220e5d7fa77a0ac0", "mingcute": "master"},
"name": "werk-gallery"
},
"toolchain": {
"commit": "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda",
"ref": "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda",
"url": "https://github.com/ziranlang/ziran.git"
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "werk-gallery"
entry = "gallery.zi"
module_roots = ["."]
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "3f72441949d4e16094834fa9220e5d7fa77a0ac0"
[dependencies.mingcute]
git = "https://github.com/kryonlabs/mingcute.git"
ref = "master"
+28 -69
View File
@@ -4,20 +4,12 @@
#import "version"
#import "c_string"
#import "text_buffer"
#if !#defined(PLAN9_BUILD) {
#import "cli_profiles"
#import "cli_native"
}
#import "cli_profiles"
#import "cli_native"
libc :: #system_library "libc";
Write :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
Read :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "read";
#if #defined(PLAN9_BUILD) {
GetEnvRaw :: (name: *s8) -> *s8 #foreign libc "getenv";
GetEnv :: (name: *u8) -> *u8 { return cast(*u8)GetEnvRaw(cast(*s8)name) }
} else {
GetEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
}
GetEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
Usage :: #string END
Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
@@ -70,23 +62,6 @@ Error :: (message: string) -> s32 {
return 2
}
ReadMaster :: (buffer: []u8) -> bool {
used: s32 = 0
while used < cast(s32)buffer.count - 1 {
byte: u8
if Read(0, *byte, cast(usize)1) != cast(isize)1 { return used > 0 }
if byte == cast(u8)10 {
if used > 0 && buffer[used - 1] == cast(u8)13 { used -= 1 }
buffer[used] = cast(u8)0
return true
}
if byte == cast(u8)0 { return false }
buffer[used] = byte
used += 1
}
return false
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
options: PassOptions
@@ -153,35 +128,27 @@ main :: (argc: s32, argv: **u8) -> s32 {
}
if version { Print(1, "pass "); Print(1, Version); Print(1, "\n"); return 0 }
site: string; login: string; clear_ms: s64
#if !#defined(PLAN9_BUILD) {
// Keep the decoded profile alive until generation has finished.
profile: LegacyProfile
}
// Keep the decoded profile alive until generation has finished.
profile: LegacyProfile
if profile_name != "" {
if count != 1 { return Error("expected SITE with --profile") }
} else if count < 2 { Print(2, Usage); return 2 }
#if !#defined(PLAN9_BUILD) {
candidate := profile_name
if candidate == "" && count == 2 { candidate = positional[0] }
profile = LoadLegacyProfile(candidate, profile_name != "", *options, explicit)
if !profile.valid { return Error("invalid CLI profiles configuration or unknown profile") }
if profile.found {
site = ifx profile_name != "" then positional[0] else positional[1]
login = TextUntilNul(profile.login[:])
if (explicit & cast(u32)64) == cast(u32)0 { options.exclude = TextUntilNul(profile.exclude[:]) }
} else { site = positional[0]; login = positional[1] }
if !copy { copy = profile.copy }
clear_ms = profile.clear_ms
if clear_after != "" {
clear_ms = DurationMilliseconds(clear_after)
if clear_ms < 0 { return Error("invalid --clear-after duration") }
}
if vault_path == "" && !prompt && count != 3 { vault_path = TextUntilNul(profile.vault[:]) }
} else {
if profile_name != "" || vault_path != "" || clear_after != "" { return Error("profiles and vaults require the Linux CLI") }
if copy && !no_copy { return Error("--copy is not available on Plan 9") }
site = positional[0]; login = positional[1]
candidate := profile_name
if candidate == "" && count == 2 { candidate = positional[0] }
profile = LoadLegacyProfile(candidate, profile_name != "", *options, explicit)
if !profile.valid { return Error("invalid CLI profiles configuration or unknown profile") }
if profile.found {
site = ifx profile_name != "" then positional[0] else positional[1]
login = TextUntilNul(profile.login[:])
if (explicit & cast(u32)64) == cast(u32)0 { options.exclude = TextUntilNul(profile.exclude[:]) }
} else { site = positional[0]; login = positional[1] }
if !copy { copy = profile.copy }
clear_ms = profile.clear_ms
if clear_after != "" {
clear_ms = DurationMilliseconds(clear_after)
if clear_ms < 0 { return Error("invalid --clear-after duration") }
}
if vault_path == "" && !prompt && count != 3 { vault_path = TextUntilNul(profile.vault[:]) }
if vault_path != "" && (prompt || count == 3) { return Error("--vault cannot be combined with --prompt or MASTER_PASSWORD") }
if prompt && count == 3 { return Error("MASTER_PASSWORD cannot be supplied together with --prompt") }
master: [1024]u8
@@ -190,11 +157,9 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !CopyText(positional[2], master[:]) { return Error("master password is too long") }
} else {
unlocked: bool
#if !#defined(PLAN9_BUILD) {
if vault_path != "" {
if !DecryptVault(vault_path, master[:]) { return Error("cannot unlock vault: wrong passphrase, unreadable or corrupted vault") }
unlocked = true
}
if vault_path != "" {
if !DecryptVault(vault_path, master[:]) { return Error("cannot unlock vault: wrong passphrase, unreadable or corrupted vault") }
unlocked = true
}
if !unlocked {
name: [32]u8
@@ -203,11 +168,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !prompt && environment != null {
if !CopyText(TextFromCString(environment), master[:]) { return Error("master password is too long") }
} else {
#if !#defined(PLAN9_BUILD) {
if !ReadSecret(master[:], "Master password: ") { return Error("missing master password") }
} else {
if !ReadMaster(master[:]) { return Error("missing master password") }
}
if !ReadSecret(master[:], "Master password: ") { return Error("missing master password") }
}
}
}
@@ -217,13 +178,11 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !generated.valid {
Print(2, "pass: "); Print(2, generated.error); Print(2, "\n"); return 1
}
#if !#defined(PLAN9_BUILD) {
if copy && !no_copy {
if !CopyPassword(TextView(generated.password[0:generated.length]), clear_ms) {
return Error("clipboard unavailable; install xclip or use --no-copy")
}
Print(2, "Password copied to the clipboard.\n"); return 0
if copy && !no_copy {
if !CopyPassword(TextView(generated.password[0:generated.length]), clear_ms) {
return Error("clipboard unavailable; install xclip or use --no-copy")
}
Print(2, "Password copied to the clipboard.\n"); return 0
}
Print(1, TextView(generated.password[0:generated.length])); Print(1, "\n")
return 0
+33 -41
View File
@@ -1,33 +1,25 @@
Spinbox :: #import "kryon/spinbox";
Checkbox :: #import "kryon/checkbox";
TextField :: #import "kryon/text_field";
Scroll :: #import "kryon/scroll";
Image :: #import "kryon/image";
Box :: #import "kryon/box";
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Pass: a stateless password generator. The same site, login, master
// password and settings always give the same password, with no database.
#import "session"
#import "geometry"
#import "text_props"
#import "text_widget"
#import "text_input_props"
#import "text_field_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "checkbox_props"
#import "checkbox_widget"
#import "spinbox_props"
#import "spinbox_widget"
#import "box_props"
#import "box_widget"
#import "image_props"
#import "image_widget"
#import "scroll_props"
#import "scroll_widget"
#import "tree"
#import "text_buffer"
#import "utf8"
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/control_props"
#import "kryon/tree"
#import "std/text_buffer"
#import "std/utf8"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "pass_core"
#import "pass_state"
#import "pass_text"
Icon :: #import "mingcute_regular_keyhole";
Icon :: #import "mingcute/mingcute_regular_keyhole";
FieldState :: struct {
cursor: s32
@@ -49,15 +41,15 @@ emoji: [32]u8;
session: Session;
Label :: (value: string, x: float32, y: float32, width: float32, font: s32) {
props: TextProps
props: Text.Props
props.bounds = Rectangle.{x, y, width, cast(float32)(font + 8)}
props.text = value
props.font = font
Text(session, props)
props.size = font
Text.Draw(session, props)
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool, disabled: bool) -> bool {
props: ButtonProps
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
@@ -69,10 +61,10 @@ Action :: (id: s32, label: string, bounds: Rectangle, accent: bool, disabled: bo
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) == 1
return Button.Draw(session, props) == 1
}
ApplyEdit :: (buffer: []u8, edit: TextFieldEdit) -> bool {
ApplyEdit :: (buffer: []u8, edit: TextField.Edit) -> bool {
if !edit.changed {
return false
}
@@ -121,7 +113,7 @@ Field :: (index: s32, label: string, buffer: []u8, bounds: Rectangle, secure: bo
mask: [1024]u8
// The views of the copies end with this block, before they are wiped.
{
props: TextFieldProps
props: TextField.Props
position: s32 = 0
while position < cast(s32)buffer.count && position < 1023 {
snapshot[position] = buffer[position]
@@ -157,7 +149,7 @@ Field :: (index: s32, label: string, buffer: []u8, bounds: Rectangle, secure: bo
if props.focused {
props.input = AppFieldInput()
}
result := TextField(session, props)
result := TextField.Draw(session, props)
fields[index].cursor = result.cursor
fields[index].anchor = result.anchor
fields[index].scroll_x = result.scroll_x
@@ -189,18 +181,18 @@ Codepoints :: (text: string) -> s32 {
}
Check :: (id: s32, label: string, value: bool, bounds: Rectangle) -> bool {
props: CheckboxProps
props: Checkbox.Props
props.key = cast(u64)id
props.id = id
props.label = label
props.bounds = bounds
props.checked = value
return Checkbox(session, props).checked
return Checkbox.Draw(session, props).checked
}
Integer :: (id: s32, label: string, value: s32, low: s32, high: s32, x: float32, y: float32, width: float32) -> s32 {
Label(label, x, y + 8.0, width - 160.0, 16)
props: SpinboxProps
props: Spinbox.Props
props.key = cast(u64)id
props.id = id
props.label = label
@@ -209,7 +201,7 @@ Integer :: (id: s32, label: string, value: s32, low: s32, high: s32, x: float32,
props.min = low
props.max = high
props.step = 1
return Spinbox(session, props).value
return Spinbox.Draw(session, props).value
}
CurrentOptions :: () -> PassOptions {
@@ -250,13 +242,13 @@ Fingerprint :: (x: float32, y: float32) {
while glyph < 63 && cast(u32)master_emoji_codepoints[glyph] != decoded.value {
glyph += 1
}
props: ImageProps
props: Image.Props
props.asset_path = atlas
props.alt_text = TextView(emoji[position:decoded.after])
props.bounds = Rectangle.{x + cast(float32)index * 28.0, y, 24.0, 24.0}
props.source = Rectangle.{cast(float32)(glyph % 8) * 64.0, cast(float32)(glyph / 8) * 64.0, 64.0, 64.0}
props.tint = ifx AppDark() then cast(u32)0xe8e8e8ff else cast(u32)0x202c29ff
Image(session, props)
Image.Draw(session, props)
position = decoded.after
}
}
@@ -315,11 +307,11 @@ GenerateForm :: (x: float32, y: float32, width: float32) {
y += 60.0
Label("Generated password", x, y, width, 14)
y += 28.0
props: BoxProps
props: Box.Props
props.key = cast(u64)42
props.bounds = Rectangle.{x, y, width, 54.0}
props.radius = 8.0
Box(session, props)
Box.Draw(session, props)
Label(ifx Generated() == "" then "Password will appear here" else Generated(), x + 10.0, y + 16.0, width - 20.0, 16)
y += 68.0
if Action(41, "Copy", Rectangle.{x, y, width, 40.0}, false, false) {
@@ -438,13 +430,13 @@ Draw :: () {
if view == 2 {
content_height = 760
}
props: ScrollProps
props: Scroll.Props
props.key = cast(u64)(10 + view)
props.bounds = Rectangle.{left, area.y + 12.0, width, height}
props.content_height = content_height
props.scroll_offset = scroll_offsets[view]
props.scale = 1.0
scroll := Scroll(session, props)
scroll := Scroll.Draw(session, props)
scroll_offsets[view] = scroll.scroll_offset
if scroll.opened {
if view == 0 {
+7 -3
View File
@@ -1,4 +1,4 @@
#import "sha256"
#import "crypto/sha256"
#if #defined(WERK_APP) {
#import "kryon/app_context"
}
@@ -57,10 +57,14 @@ DeriveKey :: (password: string, salt: string) -> [32]u8 {
derive_failed = !AppPbkdf2Sha256(password, salt, 100000, output[:])
return output
} else {
return Pbkdf2Sha256(password, salt, 100000)
return Pbkdf2Sha256(password, ifx salt.count > PASS_SALT_LIMIT then salt[0:PASS_SALT_LIMIT] else salt, 100000)
}
}
// Werkzeug's key derivation has always read at most this many salt bytes,
// and existing vault keys depend on it; the host derives the same way.
PASS_SALT_LIMIT :: 508
PassClassEmptyError :: (class_index: s32) -> string {
if class_index == 0 {
@@ -319,7 +323,7 @@ MasterEmoji :: (master: string, output: []u8) -> s32 {
if output.count <= 0 { return 0 }
output[0] = cast(u8)0
digest := Sha256(master)
digest := Sha256Of(master)
used: s32 = 0
for index: 0..3 {
codepoint: u32 = cast(u32)master_emoji_codepoints[
+4 -4
View File
@@ -1,5 +1,5 @@
#import "pass_core"
#import "sha256"
#import "crypto/sha256"
#program_export
DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
@@ -11,8 +11,8 @@ DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
#program_export
Answer :: () -> s32 {
empty := Sha256("")
abc := Sha256("abc")
empty := Sha256Of("")
abc := Sha256Of("abc")
derived := DeriveKey("password", "salt")
if empty[0] != cast(u8)0xe3 || empty[31] != cast(u8)0x55 { return 1 }
if abc[0] != cast(u8)0xba || abc[31] != cast(u8)0xad { return 2 }
@@ -117,7 +117,7 @@ Answer :: () -> s32 {
#program_export
PortableAnswer :: () -> s32 {
digest := HmacSha256("password", "salt")
digest := HmacSha256Of("password", "salt")
if digest[0] != cast(u8)0xfc || digest[31] != cast(u8)0xd0 {
return 1
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 753 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 637 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 675 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 819 KiB

+50 -17
View File
@@ -26,7 +26,7 @@ key-file import, backups, device linking and logout. Switching accounts asks
whether to keep and merge local Auth records or replace them. A private rollback
journal preserves the previous key and records if a switch is interrupted.
The account can use a [Daochi](https://github.com/kryonlabs/daochi) node,
The account can use a [Mesh](https://github.com/ziranlang/mesh) node,
`api.waozi.xyz` by default. Tools work locally without an account. Saved nodes
and the preferred node live in Profile → Nodes; choosing a node preserves the
account and its paused state. The sync switch pauses automatic synchronization
@@ -42,11 +42,15 @@ Werkzeug vault context is included.
Desktop Self and participating native apps share public profile preferences only
for the same verified account ID. Account keys and Auth records stay in the
host's private store. Android retains its existing native Account screen and
legacy device-link flow; browser account sync is unavailable.
legacy device-link flow. In the browser, Profile opens the shared manager at
https://entity.waozi.xyz. Public name, picture and appearance follow the active
waozi.xyz profile. Werkzeug's browser tool data stays local; account sync for
those tool records is unavailable.
The embedded web app (`/app/?mini`) opens on Home with every tool, and also
provides Profile. Use `?mini&app=pass`, `auth`, `calculator` or `clock` to
open a particular tool first. Browser sync is currently unavailable.
The embedded web app (`/app/?mini`) shows only the tools, as large tiles,
with no Profile; `werk --mini` does the same on the desktop. Use
`?mini&app=pass`, `auth`, `calculator` or `clock` to open a particular tool
first; Back returns to the tiles. Browser sync is currently unavailable.
- Each record is sealed on the device with XChaCha20-Poly1305 under a random
vault key that is never sent to the node unencrypted. The seal covers the
@@ -62,7 +66,7 @@ open a particular tool first. Browser sync is currently unavailable.
that has not seen a newer one. A lost device keeps the keys it had: stop
syncing there if you can, and replace two-factor secrets you care about.
`scripts/sync_e2e_test.sh` runs two devices against a local Daochi node.
`scripts/sync_e2e_test.sh` runs two devices against a local Mesh node.
## The `werk sync` and `werk auth` commands
@@ -93,18 +97,22 @@ opens the window on one tool, as Harmony's Auth entry does.
## Tools are separate apps
Each tool lives in `apps/<tool>/` and is built into its own portable bundle,
`build/apps/<tool>.zx`. All four are preinstalled. A tool reaches the host
only through the calls in `shared/werk_app.zi` (its private files,
clipboard, clock, key derivation and device-protected secret), and the host
checks every call a bundle asks for before it runs. Tools never import each
other.
Each tool is built into its own portable bundle, `build/apps/<tool>.zx`:
Pass, Calculator and Clock from `apps/<tool>/`, Auth from its own Ziran
package ([waozixyz/auth](https://github.com/waozixyz/auth)), and Workbook from
[kryonlabs/workbook](https://github.com/kryonlabs/workbook). All five are
preinstalled. A tool reaches the host only through Kryon's app context (its
private files, clipboard, clock, key derivation and device-protected
secret), and the host checks every call a bundle asks for before it runs.
Tools never import each other; what two need, such as SHA-256 and PBKDF2,
comes from a Ziran package (`crypto`).
## Build and test
Dependencies and the compiler are pinned in `ziran.lock`. Desktop builds need
SDL2, Cairo, FreeType, Fontconfig, Pango, GTK 3 and X11 development packages.
Workbook uses the installed Gnumeric library; file choosers need Zenity. Browser
Workbook uses its built-in spreadsheet engine on Android and the web; Linux
also uses the installed Gnumeric library for imported documents. Linux file choosers need Zenity. Browser
builds need Emscripten; Android builds need JDK 21 and the SDK/NDK versions in
`droid/app/build.gradle`. Desktop tests use Xvfb, xdotool, xclip and
ImageMagick on private displays.
@@ -123,7 +131,13 @@ make android-fdroid # unsigned F-Droid candidate, same Android ID and version
make android-emulator # the x86_64 APK for a private emulator
```
Linux installs include separate Pass, Auth, Calculator, Clock and Workbook
Android input tests require an explicitly owned private emulator through
`WERK_ANDROID_EMULATOR`. `python3 scripts/private-emulator.py make android-input-test`
owns a headless API 31 Google APIs emulator, including Workbook's system document picker.
CI also retains API 30 input, profile and in-place update coverage through
`make android-profile-test`.
Linux installs include separate Pass, Auth, Calculator, Clock, Workbook and Gallery
launchers, each with its own icon. They open the selected tool directly and
share Werkzeug's existing private data. `make install-gui` also adds shortcuts
to the desktop folder configured by `xdg-user-dir`; set `DESKTOP_DIR=` to skip
@@ -131,7 +145,7 @@ those shortcuts. Debian packages include the same application-menu entries.
F-Droid metadata is maintained in `packaging/fdroid`. The `android-fdroid`
target disables developer signing even when a release keystore is configured
and writes `build/werk-VERSION-fdroid-unsigned.apk`. It adds no version or
and writes `build/fdroid/werk.apk` for comparison with the signed release. It adds no version or
package suffix, preserving existing installations and reference-APK checks.
The unsigned candidate is for builders, not installation. Werkzeug currently
has no built-in updater: F-Droid or your chosen installer handles updates.
@@ -190,10 +204,9 @@ print the generated password instead. Run `pass --help` for all flags.
```text
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
apps/auth/ Auth: TOTP, otpauth links, exports, accounts and screens
auth (package) Auth: TOTP, otpauth links, exports, accounts and screens (waozixyz/auth)
apps/calculator/ Calculator
apps/clock/ Clock and stopwatch
shared/ the app interface, protocol and SHA-256/PBKDF2
src/werk.zi home screen, profile screen and the bar above a tool
src/apps.zi loads, checks and runs the app bundles
src/platform.zi files, clock, clipboard and secrets per platform
@@ -201,6 +214,26 @@ src/desktop.zi, src/android_main.zi, src/browser.zi platform main loops
src/command.zi werk sync and werk auth without a window
```
## Profile-picture diagnostics
`make entity-account-test` uses a private local HTTP fixture to fetch a
picture through the normal background pump while Profile is closed. It checks
the challenge and signed login, saves the returned picture locally and in the
shared profile, and preserves another app's name. Its sanitized result is
`build/entity-account-test/picture-sync-diagnostics.json`; it contains no account
identifiers, keys, signatures or tokens.
`make gui-test` also extracts and decodes all 17 Entity picture resources in a
private display. Its resource names, dimensions and permissions are recorded
in `build/apps-gui-test/entity-resource-diagnostics.json`. This distinguishes
bundled-resource failures from sync failures without reading a real account.
Werkzeug previously skipped starting the background picture reader when
Profile was closed and no local picture was pending. Sync-enabled accounts
now start it automatically. These tests cover that reproduced failure. The
reported shared-resource failure across other apps has not been reproduced;
the tests do not establish its server-side or cross-app cause.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
+15 -5
View File
@@ -43,8 +43,8 @@ android {
applicationId 'xyz.waozi.pass'
minSdk 21
targetSdk 36
versionCode 18
versionName "0.4.4"
versionCode 21
versionName "0.4.7"
// Default to the two realistic phone targets; override with
// -Pabi=x86_64 etc. for emulator builds.
def abis = project.findProperty('abi') ?: 'armeabi-v7a,arm64-v8a'
@@ -103,15 +103,25 @@ tasks.named('preBuild').configure { dependsOn prepareFonts }
// The tool apps are portable bundles, built once for every ABI.
def makeApps = tasks.register('makeApps', Exec) {
workingDir '../..'
workingDir rootProject.file('..')
if (System.getenv('WERK_ZIRAN_COMMAND')) {
environment 'ZIRAN', System.getenv('WERK_ZIRAN_COMMAND')
}
commandLine 'make', 'portable-apps'
}
def kryonSource = providers.environmentVariable('KRYON_DIR').orElse(providers.exec {
workingDir rootProject.file('..')
commandLine (System.getenv('WERK_ZIRAN_COMMAND') ?: rootProject.file('../scripts/ziran.sh').absolutePath), 'pkg', 'path', 'kryon'
}.standardOutput.asText.map { it.trim() })
// Entity owns the account policy; Kryon supplies the shared Android consent UI.
apply from: new File(kryonSource.get(), 'templates/android-account-handoff.gradle')
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
def prepareImages = tasks.register('prepareImages', Sync) {
dependsOn makeApps
from('../../assets/app/icon.png')
from("${System.getenv('KRYON_DIR')}/icons/pfp.png")
from('../../build/apps') { include '*.zx'; exclude 'workbook.zx'; into 'apps' }
from(kryonSource.map { "${it}/icons/pfp.webp" })
from('../../assets/tools') { include '*.webp'; into 'tools' }
from('../../build/apps') { include '*.zx'; into 'apps' }
into layout.buildDirectory.dir('generated/appAssets')
}
tasks.named('preBuild').configure { dependsOn prepareImages }
+1 -1
View File
@@ -6,7 +6,7 @@
<uses-permission android:name="android.permission.INTERNET" />
<application
android:hasCode="false"
android:hasCode="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:allowBackup="false">
+55 -29
View File
@@ -1,30 +1,20 @@
cmake_minimum_required(VERSION 3.22)
project(Werkzeug C)
project(Werkzeug C ASM)
get_filename_component(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../.." ABSOLUTE)
set(KRYON_DIR "$ENV{KRYON_DIR}" CACHE PATH "Locked Kryon source" FORCE)
set(ZIRAN_ROOT "$ENV{ZIRAN_ROOT}" CACHE PATH "Locked Ziran toolchain" FORCE)
set(RAYLIB_DIR "$ENV{RAYLIB_DIR}" CACHE PATH "Locked raylib source" FORCE)
set(LIBOQS_DIR "$ENV{LIBOQS_DIR}" CACHE PATH "Locked liboqs source" FORCE)
set(MONOCYPHER_DIR "$ENV{MONOCYPHER_DIR}" CACHE PATH "Locked Monocypher source" FORCE)
foreach(root KRYON_DIR ZIRAN_ROOT RAYLIB_DIR LIBOQS_DIR MONOCYPHER_DIR)
if(NOT ${root})
message(FATAL_ERROR "Set ${root}; use make android-debug or make android-release")
endif()
endforeach()
set(ZIRAN "${REPO_ROOT}/scripts/ziran.sh")
if(DEFINED ENV{WERK_ZIRAN_COMMAND} AND NOT "$ENV{WERK_ZIRAN_COMMAND}" STREQUAL "")
get_filename_component(ZIRAN "$ENV{WERK_ZIRAN_COMMAND}" ABSOLUTE BASE_DIR "${REPO_ROOT}")
endif()
set(GENERATED "${CMAKE_BINARY_DIR}/ziran")
set(DEFINES --define ANDROID_BUILD)
set(DEFINES --define ANDROID_BUILD --target-os android)
if(ANDROID_ABI STREQUAL "arm64-v8a")
list(APPEND DEFINES --define __aarch64__)
list(APPEND DEFINES --define __aarch64__ --target-cpu arm64)
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
list(APPEND DEFINES --define __arm__)
list(APPEND DEFINES --define __arm__ --target-cpu none)
elseif(ANDROID_ABI STREQUAL "x86_64")
list(APPEND DEFINES --define __x86_64__)
list(APPEND DEFINES --define __x86_64__ --target-cpu x64)
elseif(ANDROID_ABI STREQUAL "x86")
list(APPEND DEFINES --define __i386__)
list(APPEND DEFINES --define __i386__ --target-cpu none)
else()
message(FATAL_ERROR "Unsupported Android ABI: ${ANDROID_ABI}")
endif()
@@ -32,12 +22,37 @@ set(LOCK_FLAGS --locked)
if(EXISTS "${REPO_ROOT}/ziran.local.toml")
set(LOCK_FLAGS)
endif()
# Plain Gradle builds resolve the same packages as Make. F-Droid needs no
# source patches or machine-specific environment variables in its recipe.
function(werk_package variable package suffix)
if(NOT "$ENV{${variable}}" STREQUAL "")
set(path "$ENV{${variable}}")
else()
execute_process(COMMAND "${ZIRAN}" pkg path "${package}" ${LOCK_FLAGS}
WORKING_DIRECTORY "${REPO_ROOT}" OUTPUT_VARIABLE path
OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
string(APPEND path "${suffix}")
endif()
set(${variable} "${path}" CACHE PATH "Locked ${package} source" FORCE)
endfunction()
werk_package(KRYON_DIR kryon "")
werk_package(ZIRAN_ROOT ziran "")
werk_package(WEBP_DIR libwebp "")
werk_package(AVIF_DIR libavif "")
werk_package(AOM_DIR libaom "")
werk_package(LIBOQS_DIR liboqs "")
werk_package(MONOCYPHER_DIR monocypher "")
werk_package(WORKBOOK_DIR workbook "")
werk_package(TASKMGR_DIR taskmgr "")
file(GLOB_RECURSE SOURCE_INPUTS CONFIGURE_DEPENDS
"${REPO_ROOT}/src/*.zi" "${REPO_ROOT}/shared/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock")
"${REPO_ROOT}/src/*.zi" "${REPO_ROOT}/apps/gallery/*.zi" "${WORKBOOK_DIR}/src/*.zi" "${TASKMGR_DIR}/src/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock" "${REPO_ROOT}/scripts/runtime_cache.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SOURCE_INPUTS})
file(REMOVE_RECURSE "${GENERATED}")
execute_process(COMMAND "${ZIRAN}" build --project ${LOCK_FLAGS} ${DEFINES}
--target=c --entry android_main:main -o "${GENERATED}" src/android_main.zi
# NativeActivity and JNI callbacks are native linker roots.
--target=c --no-main -o "${GENERATED}" src/android_main.zi
"${KRYON_DIR}/src/backend/android_fopen.zi"
WORKING_DIRECTORY "${REPO_ROOT}" COMMAND_ERROR_IS_FATAL ANY)
file(GLOB GENERATED_SOURCES CONFIGURE_DEPENDS "${GENERATED}/*.c")
# Kryon's Android glue compiles its thread configurator with the same zi2c.
@@ -47,19 +62,25 @@ foreach(candidate "${ZIRAN_ROOT}/build/bin/zi2c" "${REPO_ROOT}/build/ziran-boots
endif()
endforeach()
include("${KRYON_DIR}/cmake/KryonAndroid.cmake")
kryon_android_raylib("${RAYLIB_DIR}")
kryon_android_codecs("${WEBP_DIR}" "${AVIF_DIR}" "${AOM_DIR}")
# The portable runtime that runs the app bundles, built from the locked Ziran
# for this ABI.
set(BUNDLE_RUNTIME_DIR "${CMAKE_BINARY_DIR}/bundle-runtime")
execute_process(COMMAND make -C "${ZIRAN_ROOT}" BOOTSTRAP=1 "BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
# Use the host's installed GNU Make, including an SDK-provided executable.
# All code generators run on the host; only runtime objects target the ABI.
find_program(WERK_MAKE_COMMAND NAMES make gmake REQUIRED)
execute_process(COMMAND "${WERK_MAKE_COMMAND}" -j4 -C "${ZIRAN_ROOT}"
"BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
"CC=${CMAKE_C_COMPILER} --target=${CMAKE_C_COMPILER_TARGET} --sysroot=${CMAKE_SYSROOT}"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}" "CFLAGS=-O2 -fPIC"
"FRAMEFLAGS=-Wframe-larger-than=16384" "${BUNDLE_RUNTIME_DIR}/libziran.a"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}"
"GEN_ZI2C=${ZIRAN_ROOT}/build/bin/zi2c"
"CFLAGS=-O2 -fPIC" "FRAMEFLAGS=-Wframe-larger-than=16384"
"${BUNDLE_RUNTIME_DIR}/libziran.a"
COMMAND_ERROR_IS_FATAL ANY)
# Account sync: liboqs for ML-DSA-44 account keys, Monocypher for the rest.
set(OQS_BUILD_ONLY_LIB ON CACHE BOOL "" FORCE)
set(OQS_USE_OPENSSL OFF CACHE BOOL "" FORCE)
set(OQS_MINIMAL_BUILD "SIG_ml_dsa_44" CACHE STRING "" FORCE)
set(OQS_MINIMAL_BUILD "SIG_ml_dsa_44;KEM_ml_kem_768" CACHE STRING "" FORCE)
set(OQS_DIST_BUILD OFF CACHE BOOL "" FORCE)
set(OQS_OPT_TARGET generic CACHE STRING "" FORCE)
foreach(oqs_x86_feature
@@ -68,17 +89,22 @@ foreach(oqs_x86_feature
set(OQS_USE_${oqs_x86_feature}_INSTRUCTIONS OFF CACHE BOOL "" FORCE)
endforeach()
add_subdirectory("${LIBOQS_DIR}" "${CMAKE_BINARY_DIR}/liboqs")
# JNI_OnLoad is discovered by Android's loader, outside the native entry graph.
set_source_files_properties("${GENERATED}/android_glue.c"
PROPERTIES COMPILE_OPTIONS "-fvisibility=default")
add_library(main SHARED ${GENERATED_SOURCES}
"${MONOCYPHER_DIR}/src/monocypher.c" "${MONOCYPHER_DIR}/src/optional/monocypher-ed25519.c")
target_include_directories(main PRIVATE "${GENERATED}" "${ZIRAN_ROOT}/include"
target_compile_options(main PRIVATE "-iquote${GENERATED}")
target_include_directories(main PRIVATE "${ZIRAN_ROOT}/include"
"${MONOCYPHER_DIR}/src" "${MONOCYPHER_DIR}/src/optional")
target_link_libraries(main oqs)
target_link_libraries(main PRIVATE oqs z kryon_android_codecs)
kryon_android_app(main)
target_link_libraries(main "${BUNDLE_RUNTIME_DIR}/libziran.a")
target_link_options(main PRIVATE -Wl,--wrap=pthread_attr_init)
# Save hosted documents after the canonical NativeActivity loop returns.
target_link_options(main PRIVATE -Wl,--wrap=android_main)
target_link_libraries(main PRIVATE "${BUNDLE_RUNTIME_DIR}/libziran.a")
# Linker build IDs include debug-path differences even after stripping. The
# installed code is identical; omit this note for reproducible signed APKs.
# https://f-droid.org/docs/Reproducible_Builds/#ndk-build-id
target_link_options(main PRIVATE -Wl,--build-id=none)
# Werkzeug has no handwritten native sources; every app translation unit above is
# generated from .zi for this ABI. raylib and the NDK own native_app_glue.
# generated from .zi for this ABI. Kryon and the NDK own native_app_glue.
@@ -0,0 +1 @@
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
@@ -0,0 +1 @@
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
@@ -0,0 +1,2 @@
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
@@ -4,10 +4,11 @@ Werkzeug holds small private tools in one app. Everything is computed on your de
• Auth shows two-factor sign-in codes (TOTP with SHA-1, SHA-256 or SHA-512). Add accounts by secret key or from otpauth links, Google Authenticator export links, unencrypted Aegis exports or Ente Auth's plain-text export. Rename an account or note the websites where it signs in. Copied codes are cleared from the clipboard after 30 seconds. Optional sync keeps them on all your devices, encrypted on the device so the server never sees them.
• Calculator handles everyday arithmetic with brackets, powers and percent, and has a Scientific mode with trigonometry, logarithms, roots, factorials, π and e.
• Clock shows the local time and date and has a stopwatch.
• Workbook edits spreadsheets with formulas, multiple sheets and automatic saving. Import or export a Gnumeric workbook through Android's file chooser, and use the same document on the desktop or web.
A profile with your name and picture sets the appearance every tool shares.
Every tool works without a Daochi account. In Profile → Sync you can choose your own node before connecting an account, or pause sync without forgetting your keys and local records. Sync stays off after restarting until you turn it on again.
Every tool works without a Mesh account. In Profile → Sync you can choose your own node before connecting an account, or pause sync without forgetting your keys and local records. Sync stays off after restarting until you turn it on again.
Pass is an independent implementation of the LessPass algorithm. Compatibility does not imply endorsement by or affiliation with the LessPass project.
-20
View File
@@ -1,20 +0,0 @@
</$objtype/mkfile
# Generate with `make plan9-c` on the host, then build natively with `mk`.
CLI_FILES=`{ls build/plan9/cli/*.c}
CLI_HEADERS=`{ls build/plan9/cli/*.h}
CLI_OBJECTS=${CLI_FILES:%.c=%.$O}
CFLAGS=-FTVw
all:V: pass
pass: $CLI_OBJECTS
$LD -o $target $prereq
$CLI_OBJECTS: $CLI_HEADERS
%.$O: %.c
$CC $CFLAGS -o $target $stem.c
install:V: pass
cp pass /$objtype/bin/pass
+2 -14
View File
@@ -1,17 +1,5 @@
# Update Pass to Werkzeug
This updates the existing `xyz.waozi.pass` F-Droid entry. The owner chose an in-place update: retain the original Android package and author signing certificate, show the app as Werkzeug, and preserve existing Pass data.
Update the existing `xyz.waozi.pass` app to Werkzeug. The package ID and signing certificate are preserved for in-place updates.
The separate-package new-app proposal !53912 is superseded by this update. Do not mark this merge request ready without owner approval.
Werkzeug continues the same upstream project with Pass, Auth, Calculator and Clock. Its source is https://github.com/waozixyz/werk and its listing and screenshots are maintained in Fastlane.
## Candidate and remaining work
- Version 0.4.4 (version code 18) is being prepared with the original `xyz.waozi.pass` package. Its release, exact source pin and reference APK still need verification before the recipe is updated.
- Preserve the existing published Pass build entry and author signing certificate.
- The prior comparison differed only in each native library's build-ID note. The fix disables that note as documented by F-Droid. Both ARM32 and ARM64 libraries rebuilt in different native build directories now match the local candidate APK byte for byte; comparison against the published signed APK in F-Droid remains pending.
- Rerun the update check against the published compatible release tag.
- Resolve the missing explicit licenses in Apps, Entity, Daochi Client and Crypto, and the source-library template exceptions before review.
This remains a Draft update, not an approved or published F-Droid release.
Listing text and screenshots are maintained upstream in Fastlane.
+18 -11
View File
@@ -12,7 +12,7 @@ AutoName: Werkzeug
RepoType: git
Repo: https://github.com/waozixyz/werk.git
Binaries: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
Binaries: https://github.com/waozixyz/pass/releases/download/v%v/pass-%v.apk
Builds:
- versionName: 0.2.9
@@ -25,20 +25,27 @@ Builds:
- apt-get install -y gcc libc-dev
gradle:
- yes
binary: https://github.com/waozixyz/pass/releases/download/v%v/pass-%v.apk
scandelete:
- vendor/kryon/vendor
ndk: 28.2.13676358
- versionName: 0.4.4
versionCode: 18
commit: b53050764b8402a96e2e6b9b8c90d6567a3bea77
subdir: droid/app
sudo:
- apt-get update
- apt-get install -y build-essential cmake libssl-dev
gradle:
- yes
binary: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
ndk: 28.2.13676358
gradleprops:
- fDroidBuild=true
AllowedAPKSigningKeys: 1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee19589c2d
MaintainerNotes: Updates the existing Pass entry as Werkzeug using xyz.waozi.pass
and its existing author signing certificate. The 0.4.4 / 18 candidate is being prepared;
add its build entry only after the compatible source commit and reference APK are
verified. Keep the merge request Draft pending owner approval and successful source/reproducibility
builds.
AutoUpdateMode: None
AutoUpdateMode: Version
UpdateCheckMode: Tags
CurrentVersion: 0.2.9
CurrentVersionCode: 10
CurrentVersion: 0.4.4
CurrentVersionCode: 18
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/waozixyz/apps.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/crypto.git
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/daochi-client.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/waozixyz/entity.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/kryonlabs/kryon.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/kryonlabs/kss.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/kryonlabs/mingcute.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/LoupVaillant/Monocypher.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/oqs.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/qrcode.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/waozixyz/entity.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/waozixyz/workbook.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/ziran.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/open-quantum-safe/liboqs.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/raysan5/raylib.git
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+1 -1
View File
@@ -11,5 +11,5 @@
<launchable type="desktop-id">xyz.waozi.werk.desktop</launchable>
<url type="homepage">https://github.com/waozixyz/werk</url>
<provides><binary>werk</binary></provides>
<releases><release version="0.4.4" date="2026-10-23"/><release version="0.4.3" date="2026-10-23"/><release version="0.4.2" date="2026-10-23"/><release version="0.4.1" date="2026-10-23"/><release version="0.4.0" date="2026-10-15"/><release version="0.3.1" date="2026-10-13"/><release version="0.3.0" date="2026-10-13"/><release version="0.2.10" date="2026-10-05"/><release version="0.2.9" date="2026-09-05"/><release version="0.2.8" date="2026-08-26"/><release version="0.2.7" date="2026-08-24"/><release version="0.2.6" date="2026-08-24"/><release version="0.2.5" date="2026-08-24"/><release version="0.2.4" date="2026-08-22"/><release version="0.2.3" date="2026-08-21"/><release version="0.2.2" date="2026-08-20"/><release version="0.2.1" date="2026-08-19"/><release version="0.2.0" date="2026-08-18"/><release version="0.1.3" date="2026-08-17"/><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
<releases><release version="0.4.7" date="2026-10-28"/><release version="0.4.6" date="2026-10-27"/><release version="0.4.5" date="2026-10-26"/><release version="0.4.4" date="2026-10-23"/><release version="0.4.3" date="2026-10-23"/><release version="0.4.2" date="2026-10-23"/><release version="0.4.1" date="2026-10-23"/><release version="0.4.0" date="2026-10-15"/><release version="0.3.1" date="2026-10-13"/><release version="0.3.0" date="2026-10-13"/><release version="0.2.10" date="2026-10-05"/><release version="0.2.9" date="2026-09-05"/><release version="0.2.8" date="2026-08-26"/><release version="0.2.7" date="2026-08-24"/><release version="0.2.6" date="2026-08-24"/><release version="0.2.5" date="2026-08-24"/><release version="0.2.4" date="2026-08-22"/><release version="0.2.3" date="2026-08-21"/><release version="0.2.2" date="2026-08-20"/><release version="0.2.1" date="2026-08-19"/><release version="0.2.0" date="2026-08-18"/><release version="0.1.3" date="2026-08-17"/><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
</component>
@@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Name=Calendar
Comment=Schedule events with Werkzeug
Exec=werk --app calendar
TryExec=werk
Icon=werk-calendar
Terminal=false
Categories=Office;Calendar;
Keywords=Werkzeug;Calendar;Events;Schedule;
StartupNotify=true
StartupWMClass=werk-calendar
@@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Name=Gallery
Comment=Browse local photo albums with Werkzeug
Exec=werk --app gallery
TryExec=werk
Icon=werk-gallery
Terminal=false
Categories=Graphics;Photography;
Keywords=Werkzeug;Photos;Albums;Local;
StartupNotify=true
StartupWMClass=werk-gallery
@@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Name=Task Manager
Comment=Monitor processes and performance with Werkzeug
Exec=werk --app taskmgr
TryExec=werk
Icon=werk-taskmgr
Terminal=false
Categories=System;Monitor;
Keywords=Werkzeug;Task Manager;Processes;CPU;Memory;
StartupNotify=true
StartupWMClass=werk-taskmgr
+1 -1
View File
@@ -23,7 +23,7 @@ Before closed/open testing or production, complete the store text, images,
privacy policy, account-deletion requirements, target audience, ads declaration,
content rating and Data safety answers. Accept Play terms only with owner
authorization. Tools work locally without an account; optional account/sync
connects to the chosen Daochi node. Do not declare that the app never connects
connects to the chosen Mesh node. Do not declare that the app never connects
or that the node receives no identifiers. Biometric unlock stays on the device.
If Play App Signing is enabled, preserve the existing signing identity for
+1 -1
View File
@@ -37,7 +37,7 @@ if not args.unsigned:
expected = "1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee19589c2d"
assert fingerprints and {x.replace(":", "").lower() for x in fingerprints} == {expected}, "Bundle signer differs from the existing release key"
with zipfile.ZipFile(bundle) as archive:
expected_bundles = {f"base/assets/apps/{app}.zx" for app in ("pass", "auth", "calculator", "clock", "entity", "apps")}
expected_bundles = {f"base/assets/apps/{app}.zx" for app in ("pass", "auth", "calculator", "clock", "workbook", "entity", "apps")}
actual_bundles = {name for name in archive.namelist() if name.startswith("base/assets/apps/") and not name.endswith("/")}
assert actual_bundles == expected_bundles, f"Stale or missing app bundles: {actual_bundles ^ expected_bundles}"
for name in expected_bundles:
+51 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Reject packaged legacy app classes; Android generates resource constants."""
"""Reject app-owned bytecode; permit shared Kryon account consent and resource constants."""
import re
import struct
import sys
@@ -35,27 +35,73 @@ def elf_section_names(data):
yield strings[name:strings.index(0, name)].decode("ascii")
def elf_exports(data):
wide = data[4] == 2
table = struct.unpack_from("<Q" if wide else "<I", data, 40 if wide else 32)[0]
size, count = struct.unpack_from("<HH", data, 58 if wide else 46)
sections = []
for index in range(count):
entry = table + index * size
kind = struct.unpack_from("<I", data, entry + 4)[0]
offset, length = struct.unpack_from("<QQ" if wide else "<II", data, entry + (24 if wide else 16))
link = struct.unpack_from("<I", data, entry + (40 if wide else 24))[0]
stride = struct.unpack_from("<Q" if wide else "<I", data, entry + (56 if wide else 36))[0]
sections.append((kind, offset, length, link, stride))
for kind, offset, length, link, stride in sections:
if kind != 11: # SHT_DYNSYM: symbols visible to Android's loader.
continue
_, strings_offset, strings_length, _, _ = sections[link]
strings = data[strings_offset:strings_offset + strings_length]
for entry in range(offset, offset + length, stride):
name = struct.unpack_from("<I", data, entry)[0]
info, other, defined = struct.unpack_from("<BBH", data, entry + (4 if wide else 12))
if info >> 4 in (1, 2) and other & 3 == 0 and defined != 0:
yield strings[name:strings.index(0, name)].decode("ascii")
HANDOFF = {
"Lorg/kryonlabs/platform/" + name
for name in ("AccountHandoff", "AccountHandoffConsentActivity",
"AccountHandoffNameProvider", "AccountHandoffRequestActivity")
}
def allowed_class(item: str) -> bool:
return bool(re.fullmatch(r"Lxyz/waozi/pass/R(?:\$[^;]+)?;", item)) or any(
item == base + ";" or bool(re.fullmatch(
re.escape(base) + r"\$\$ExternalSynthetic(?:Lambda|ApiModelOutline)[0-9]+;", item))
for base in HANDOFF)
def check_apk(path):
with ZipFile(path) as archive:
names = archive.namelist()
# Account policy stays in Ziran. Kryon's consent flow is the only
# platform Java allowed alongside Android's resource constants.
packaged_classes = set()
for name in names:
if name.endswith(".dex"):
classes = list(dex_classes(archive.read(name)))
assert all(re.fullmatch(r"Lxyz/waozi/pass/R(?:\$[^;]+)?;", item) for item in classes), f"{path}: packaged application bytecode: {classes}"
packaged_classes.update(classes)
unexpected = [item for item in classes if not allowed_class(item)]
assert not unexpected, f"{path}: packaged application bytecode: {unexpected}"
assert {base + ";" for base in HANDOFF} <= packaged_classes, f"{path}: missing shared account consent classes"
for font in ["ui.ttf", "emoji.ttf"]:
assert "assets/fonts/" + font in names, f"{path}: missing {font}"
bundles = {f"assets/apps/{app}.zx" for app in ["apps", "entity", "pass", "auth", "calculator", "clock"]}
bundles = {f"assets/apps/{app}.zx" for app in ["apps", "entity", "pass", "auth", "calculator", "clock", "workbook", "gallery"]}
packaged = {name for name in names if name.startswith("assets/apps/") and not name.endswith("/")}
assert packaged == bundles, f"{path}: stale or missing app bundles: {packaged ^ bundles}"
for name in bundles:
assert archive.read(name)[:4] == b"ZX\0\0", f"{path}: {name} has an obsolete bundle format"
assert "assets/pfp.png" in names, f"{path}: missing profile pictures"
assert "assets/pfp.webp" in names, f"{path}: missing profile pictures"
assert "assets/tools/pass.webp" in names, f"{path}: missing tool artwork"
native = [name for name in names if name.endswith("/libmain.so")]
assert native, f"{path}: no NativeActivity payload"
for name in native:
assert "JNI_OnLoad" in set(elf_exports(archive.read(name))), f"{path}: {name} hides account JNI registration"
assert ".note.gnu.build-id" not in set(elf_section_names(archive.read(name))), \
f"{path}: {name} contains a build-path-dependent build ID"
print(f"{path}: native Ziran app; only generated resource classes")
print(f"{path}: native Ziran app with shared Kryon account consent")
if __name__ == "__main__":
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Exercise the APK bytecode allowlist without building an APK."""
import unittest
from android_apk_check import allowed_class
class AllowedClassTest(unittest.TestCase):
def test_approved_classes_and_compiler_helpers(self):
for name in ("AccountHandoff", "AccountHandoffConsentActivity",
"AccountHandoffNameProvider", "AccountHandoffRequestActivity"):
base = "Lorg/kryonlabs/platform/" + name
for suffix in (";", "$$ExternalSyntheticLambda0;",
"$$ExternalSyntheticApiModelOutline0;",
"$$ExternalSyntheticApiModelOutline12;"):
with self.subTest(descriptor=base + suffix):
self.assertTrue(allowed_class(base + suffix))
for descriptor in ("Lxyz/waozi/pass/R;", "Lxyz/waozi/pass/R$string;"):
self.assertTrue(allowed_class(descriptor))
def test_rejects_other_and_lookalike_classes(self):
for descriptor in (
"Lxyz/waozi/pass/MainActivity;",
"Lxyz/waozi/pass/AccountHandoff$$ExternalSyntheticApiModelOutline0;",
"Lorg/kryonlabs/platform/Other$$ExternalSyntheticApiModelOutline0;",
"Lorg/kryonlabs/platform/AccountHandoffExtra$$ExternalSyntheticApiModelOutline0;",
"Lorg/kryonlabs/platform/AccountHandoff$$ExternalSyntheticApiModelOutline;",
"Lorg/kryonlabs/platform/AccountHandoff$$ExternalSyntheticApiModelOutline0Extra;",
"Lorg/kryonlabs/platform/AccountHandoff$$ExternalSyntheticLambda0Extra;",
"Lxyz/waozi/pass/Rogue;",
):
with self.subTest(descriptor=descriptor):
self.assertFalse(allowed_class(descriptor))
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -31,5 +31,5 @@ for path, expected_abis in [(fdroid, {"armeabi-v7a", "arm64-v8a"}),
assert abis == expected_abis, f"{path}: wrong ABIs {abis}"
assert archive.read("assets/icon.png") == (root / "assets/app/icon.png").read_bytes(), "Stale app logo"
signature = subprocess.run(["apksigner", "verify", str(path)], capture_output=True)
assert (signature.returncode != 0) == (path == fdroid), "F-Droid must be unsigned; debug must be signed"
assert (signature.returncode != 0) == (path == fdroid), "The source-comparison APK omits signing; debug APKs must be signed"
print("Android distribution: matching package/version, Werkzeug label/logo, correct ABIs, builder signing and no installer permissions")
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
"""Exercise the real local folder grant and viewer on a private emulator."""
import os
from pathlib import Path
import re
import struct
import subprocess
import time
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
from android_labels import label_position
from android_startup import launch_home
from android_apk_check import check_apk
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "build/android-gallery-test"
OUT.mkdir(parents=True, exist_ok=True)
SERIAL = os.environ.get("WERK_ANDROID_EMULATOR", "")
assert SERIAL.startswith("emulator-"), "Select an explicitly owned private emulator"
PACKAGE = "xyz.waozi.pass"
FOLDER = "/sdcard/Pictures/WerkGalleryFixture"
def adb(*args, check=True, input=None):
return subprocess.run(["adb", "-s", SERIAL, *args], check=check,
capture_output=True, input=input, timeout=90)
def shell(*args, check=True):
return adb("shell", *args, check=check).stdout.decode()
def frame(name="current"):
path = OUT / (name + ".png")
path.write_bytes(adb("exec-out", "screencap", "-p").stdout)
return path
def tap(x, y):
shell("input", "tap", str(x), str(y))
time.sleep(.4)
def label(word, timeout=25):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
path = frame()
position = label_position(path, word)
if position:
return position
time.sleep(.3)
raise AssertionError("Missing Gallery label: " + word)
def expect_text(expected):
wanted = "".join(character.casefold() for character in expected if character.isalnum())
deadline = time.monotonic() + 25
while time.monotonic() < deadline:
text = subprocess.check_output(["tesseract", str(frame()), "stdout", "--psm", "11"],
stderr=subprocess.DEVNULL, text=True)
actual = "".join(character.casefold() for character in text if character.isalnum())
if wanted in actual:
return
time.sleep(.3)
raise AssertionError("Missing visible Gallery text: " + expected)
def click(word):
tap(*label(word))
def system_nodes():
path = "/data/local/tmp/werk-gallery-ui.xml"
shell("uiautomator", "dump", "--compressed", path)
text = shell("cat", path)
(OUT / "picker.xml").write_text(text)
return list(ET.fromstring(text).iter("node"))
def system_click(*labels, required=True):
for node in system_nodes():
if node.get("text", "").casefold() in [s.casefold() for s in labels] or node.get("content-desc", "").casefold() in [s.casefold() for s in labels]:
bounds = list(map(int, re.findall(r"\d+", node.get("bounds", ""))))
if len(bounds) == 4 and node.get("enabled") != "false":
tap((bounds[0] + bounds[2]) // 2, (bounds[1] + bounds[3]) // 2)
return True
if required:
raise AssertionError("Missing system picker control: " + repr(labels))
return False
def picker_ready():
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
if any(node.get("text", "").casefold() == "use this folder"
for node in system_nodes()):
return
except (subprocess.SubprocessError, ET.ParseError):
pass
time.sleep(.3)
raise AssertionError("System folder picker did not become ready")
def cancel_picker():
picker_ready()
# Back first navigates a remembered folder's parents. Stop as soon as
# DocumentsUI returns to our activity; never send Back into Gallery.
for _ in range(12):
shell("input", "keyevent", "4")
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
activities = shell("dumpsys", "activity", "activities")
resumed = [line for line in activities.splitlines() if "mResumedActivity" in line]
if any(PACKAGE + "/android.app.NativeActivity" in line for line in resumed):
return
time.sleep(.2)
raise AssertionError("System folder picker did not cancel back to Gallery")
def choose(folder):
click("Choose")
picker_ready()
# DocumentsUI may restore the last selected folder. Select the local
# device root explicitly rather than relying on a provider's history.
if system_click("Show roots", "Open navigation drawer", required=False):
if not system_click("Internal storage", "Pixel 2", "Android SDK built for x86_64", required=False):
nodes = system_nodes()
candidates = [node for node in nodes if node.get("resource-id", "").endswith("/title") and
("sdk_" in node.get("text", "").lower() or "emulator" in node.get("text", "").lower())]
assert candidates, "Local device root missing from system picker"
bounds = list(map(int, re.findall(r"\d+", candidates[0].get("bounds", ""))))
tap((bounds[0] + bounds[2]) // 2, (bounds[1] + bounds[3]) // 2)
else:
# Some DocumentsUI tree pickers expose only breadcrumbs. The first
# breadcrumb must identify this local device, then returns to its root.
crumbs = [node for node in system_nodes()
if node.get("resource-id", "").endswith("/breadcrumb_text")]
assert crumbs, "Local folder picker has neither roots nor breadcrumbs"
name = crumbs[0].get("text", "").casefold()
assert "sdk_" in name or "emulator" in name or name in ("internal storage", "pixel 2"), name
bounds = list(map(int, re.findall(r"\d+", crumbs[0].get("bounds", ""))))
tap((bounds[0] + bounds[2]) // 2, (bounds[1] + bounds[3]) // 2)
system_click("Pictures")
system_click(folder)
system_click("Use this folder")
system_click("Allow")
time.sleep(1)
def pixels(name, color):
with Image.open(frame(name)) as image:
data = image.convert("RGB").getdata()
if color == "red":
return sum(r > 190 and g < 70 and b < 70 for r, g, b in data)
if color == "blue":
return sum(b > 190 and r < 70 and g < 70 for r, g, b in data)
if color == "green":
return sum(g > 90 and r < 70 and b < 70 for r, g, b in data)
return sum(r > 190 and g > 190 and b < 70 for r, g, b in data)
apk = Path(os.environ.get("WERK_ANDROID_APK", ROOT / "build/werk-android-emulator.apk"))
check_apk(apk)
adb("install", "-r", str(apk))
fixtures = OUT / "photos"
(fixtures / "Album").mkdir(parents=True, exist_ok=True)
for name, color in (("a.png", "red"), ("z.JPG", "blue"), ("Album/b.png", "green")):
image = Image.new("RGB", (640, 480), color)
ImageDraw.Draw(image).rectangle((220, 100, 420, 380), fill="yellow")
image.save(fixtures / name)
(fixtures / "broken.png").write_bytes((fixtures / "a.png").read_bytes()[:33] + b"corrupt image fixture")
image_cases = fixtures / "ImageCases"
image_cases.mkdir(exist_ok=True)
Image.new("RGB", (3072, 2048), "red").save(image_cases / "00-large.png", compress_level=0)
assert (image_cases / "00-large.png").stat().st_size > 16 * 1024 * 1024
with (image_cases / "01-byte-limit.png").open("wb") as stream:
stream.write((fixtures / "a.png").read_bytes()[:33])
stream.truncate(64 * 1024 * 1024 + 1)
header = bytearray((fixtures / "a.png").read_bytes()[:33])
header[16:24] = struct.pack(">II", 40000, 40000)
(image_cases / "02-pixel-limit.png").write_bytes(header)
rotated = Image.new("RGB", (640, 480), "blue")
ImageDraw.Draw(rotated).rectangle((0, 0, 639, 239), fill="red")
metadata = Image.Exif()
metadata[274] = 6 # EXIF: rotate clockwise, making red the right half.
rotated.save(image_cases / "03-rotated.jpg", quality=95, exif=metadata)
shell("mkdir", "-p", FOLDER, "/sdcard/Pictures/WerkGalleryEmpty")
adb("push", str(fixtures) + "/.", FOLDER + "/")
# Only fixture state in this private test package is replaced.
shell("am", "force-stop", PACKAGE)
shell("run-as", PACKAGE, "rm", "-rf", "files/gallery")
launch_home(adb, OUT, PACKAGE, "gallery-launch")
click("Gallery")
label("Choose")
click("Choose")
cancel_picker()
label("cancelled")
choose("WerkGalleryFixture")
label("WerkGalleryFixture")
label("Album")
assert pixels("red-thumbnail", "red") > 500, "Local PNG thumbnail was not rendered"
assert pixels("blue-thumbnail", "blue") > 500, "Local JPEG thumbnail was not rendered"
click("a.png")
assert pixels("red-viewer", "red") > 5000, "Selected local image was not rendered"
yellow = pixels("fit-marker", "yellow")
click("in")
zoomed = pixels("zoom-marker", "yellow")
assert zoomed > yellow * 1.3, "Zoom did not enlarge the rendered image"
click("Pan left")
assert pixels("pan-marker", "yellow") < zoomed * .9, "Pan did not move the enlarged image"
click("Fit")
assert abs(pixels("fit-restored", "yellow") - yellow) < yellow * .05, "Fit did not restore the image viewport"
click("Next") # broken fixture: navigation must continue past unreadable data.
label("broken.png")
label("decode")
adb("push", str(fixtures / "a.png"), FOLDER + "/broken.png")
click("Retry image")
assert pixels("retry-image", "red") > 5000, "Retry did not reopen the repaired image"
click("Next")
assert pixels("blue-viewer", "blue") > 5000
click("Previous")
label("broken.png")
click("Albums")
click("Album")
expect_text("WerkGalleryFixture / Album")
click("b.png")
assert pixels("album-viewer", "green") > 5000
click("Albums")
click("Up")
click("ImageCases")
expect_text("WerkGalleryFixture / ImageCases")
click("00-large.png")
assert pixels("large-image", "red") > 5000, "An ordinary photo larger than 16 MiB did not render"
click("Next")
label("exceeds")
click("Next")
label("exceeds")
click("Next")
label("03-rotated.jpg")
with Image.open(frame("exif-rotation")) as image:
red_x = red_count = blue_x = blue_count = 0
for index, (r, g, b) in enumerate(image.convert("RGB").getdata()):
if r > 190 and g < 70 and b < 70:
red_x += index % image.width
red_count += 1
if b > 190 and r < 70 and g < 70:
blue_x += index % image.width
blue_count += 1
assert red_count > 5000 and blue_count > 5000
assert red_x / red_count > blue_x / blue_count + 100, "JPEG EXIF orientation was not applied"
click("Albums")
click("Up")
location = shell("run-as", PACKAGE, "cat", "files/gallery/location.txt").strip()
assert location.startswith("content://com.android.externalstorage.documents/tree/"), location
assert shell("run-as", PACKAGE, "stat", "-c", "%a", "files/gallery", "files/gallery/location.txt").split() == ["700", "600"]
shell("am", "force-stop", PACKAGE)
launch_home(adb, OUT, PACKAGE, "gallery-restart")
click("Gallery")
label("Album")
click("a.png")
assert pixels("persisted-grant", "red") > 5000, "Persisted folder grant did not survive restart"
click("Albums")
choose("WerkGalleryEmpty")
label("supported")
choose("WerkGalleryFixture")
shell("mv", FOLDER, FOLDER + "-removed")
click("Refresh")
label("Cannot")
frame("revoked-folder")
assert shell("pidof", PACKAGE).strip(), "Gallery failure killed its host"
print("Android Gallery: real local picker, cancel, album breadcrumbs, rendered images, zoom/pan/Fit, decoder failure/retry, large photo and size limits, private persisted grant, restart, empty and revoked folders passed", flush=True)
+73 -36
View File
@@ -1,13 +1,14 @@
#!/usr/bin/env python3
"""Drive only a private emulator; never choose a connected phone implicitly."""
from pathlib import Path
import csv
import io
import os
import re
import subprocess
import time
from PIL import Image
from android_apk_check import check_apk
from android_labels import label_position
from android_startup import launch_home
root = Path(__file__).resolve().parents[1]
output = root / "build/android-input"
@@ -31,23 +32,41 @@ def shell(*arguments, check=True):
def shot(name):
(output / f"{name}.png").write_bytes(adb("exec-out", "screencap", "-p").stdout)
def find_label(word, timeout=15):
def find_label(word, timeout=15, minimum_y=0):
deadline = time.monotonic() + timeout
while True:
shot("label")
data = subprocess.check_output(["tesseract", str(output / "label.png"), "stdout", "--psm", "11", "-c", "tessedit_create_tsv=1"],
stderr=subprocess.DEVNULL, text=True)
for item in csv.DictReader(io.StringIO(data), delimiter="\t"):
if item["text"].strip().lower() == word.lower():
return (int(item["left"]) + int(item["width"]) // 2,
int(item["top"]) + int(item["height"]) // 2)
screenshot = output / "label.png"
if minimum_y:
with Image.open(screenshot) as frame:
screenshot = output / "label-bottom.png"
frame.crop((0, minimum_y, frame.width, frame.height)).save(screenshot)
position = label_position(screenshot, word)
if position is None:
position = label_position(screenshot, word, psm=6)
if position is not None:
return position[0], position[1] + minimum_y
if time.monotonic() >= deadline:
alive()
raise AssertionError(f"Could not find {word!r} in the private emulator")
time.sleep(0.3)
def tap_label(word):
tap(*find_label(word))
def open_profiles():
# Android's clipboard preview can consume the first navigation tap.
# Require the destination form before letting the caller edit its name.
for attempt in range(2):
# Wait for the bottom bar to return to its full-height position
# after the keyboard closes before tapping the tab.
tap(*find_label("Profiles", minimum_y=bottom - int(100 * zoom)))
try:
return find_label("Profile name")
except AssertionError:
if attempt:
raise
def scroll_to_label(word, direction="down"):
hide_keyboard()
for attempt in range(7):
@@ -122,12 +141,13 @@ def system_bars(height):
"""The app's first and last rows in pixels: Werkzeug keeps its content
between the status bar and the navigation bar."""
dump = shell("dumpsys", "window")
(output / "window-insets.txt").write_text(dump)
# Android 12 and older name inset sources ITYPE_STATUS_BAR and so on.
status = re.search(r"type=(?:statusBars|ITYPE_STATUS_BAR) frame=\[0,0\]\[\d+,(\d+)\]", dump)
status = re.search(r"type=(?:statusBars|ITYPE_STATUS_BAR).*?frame=\[0,0\]\[\d+,(\d+)\]", dump)
# A display cutout taller than the status bar pushes the app down further.
cutout = re.search(r"type=(?:displayCutout|ITYPE_[A-Z_]*CUTOUT[A-Z_]*) frame=\[0,0\]\[\d+,(\d+)\]", dump)
navigation = re.search(r"type=(?:navigationBars|ITYPE_NAVIGATION_BAR) frame=\[0,(\d+)\]\[\d+,(\d+)\]", dump)
top = max(int(status.group(1)) if status else 0, int(cutout.group(1)) if cutout else 0)
cutout = re.search(r"type=(?:displayCutout|ITYPE_[A-Z_]*CUTOUT[A-Z_]*).*?frame=\[0,0\]\[\d+,(\d+)\]", dump)
navigation = re.search(r"type=(?:navigationBars|ITYPE_NAVIGATION_BAR).*?frame=\[0,(\d+)\]\[\d+,(\d+)\]", dump)
top = max(int(status.group(1)) if status else round(24 * zoom), int(cutout.group(1)) if cutout else 0)
bottom = int(navigation.group(1)) if navigation and int(navigation.group(2)) == height else height
return top, bottom
@@ -140,8 +160,9 @@ try:
shell("run-as", package, "mkdir", "-p", "files/profile")
adb("shell", f"run-as {package} sh -c 'umask 077; cat > files/profile/settings.txt'",
input=b"name=Fixture Person\ntheme_mode=1\n")
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(2); alive(); dismiss_other_apps_not_responding(); shot("launch")
launch_home(adb, output, package, "launch")
alive(); dismiss_other_apps_not_responding(); shot("launch")
find_label("Profile")
size = shell("wm", "size").strip().split()[-1]
width, height = map(int, size.split("x"))
# Werkzeug scales by the screen density, as Android's dp do.
@@ -150,31 +171,32 @@ try:
top, bottom = system_bars(height)
# The shared Apps screen can change layout; select the visible tool.
tap_label("Pass"); time.sleep(0.5); alive(); shot("pass")
runtime_modes = shell("run-as", package, "stat", "-c", "%a", "files/cache", "files/cache/ziran-native").split()
assert runtime_modes == ["700", "700"], f"Native runtime cache is not private: {runtime_modes}"
find_label("Site")
bar = 56
fill_field("Site", "example.com")
assert "mInputShown=true" in shell("dumpsys", "input_method"), "Soft keyboard did not open"
fill_field("Login", "alice")
fill_field("Master", "test master")
shot("keyboard")
hide_keyboard(); alive()
tap(width // 2, bottom - int(35 * zoom))
fill_field("Profile", "Android test")
shell("input", "keyevent", "4"); time.sleep(0.3)
tap(int(100 * zoom), top + int((105 + bar) * zoom))
open_profiles()
fill_field("Profile name", "Android test")
hide_keyboard()
tap_label("Save Current Profile")
expected = "Android test\texample.com\talice\t16\t1\t1\t1\t1\t1\t\n"
saved = shell("run-as", package, "cat", "files/apps/pass/profiles.tsv")
assert saved == expected, f"Profile input/persistence mismatch: {saved!r}"
assert "test master" not in saved
print("Android: keyboard input and first saved profile verified", flush=True)
# Generate from the saved profile and copy it.
tap(int(100 * zoom), top + int((210 + bar) * zoom))
tap_label("Generate")
# A slow emulator may still be deriving the password.
time.sleep(2); dismiss_other_apps_not_responding()
tap(int(100 * zoom), bottom - int(119 * zoom)) # Copy, at the bottom of the scrolled form
tap(*scroll_to_label("Copy"))
shot("generated")
tap(width // 2, bottom - int(35 * zoom))
tap(int(90 * zoom), top + int((55 + bar) * zoom))
_, profile_y = open_profiles()
tap(int(90 * zoom), profile_y + int(40 * zoom))
shell("input", "keyevent", "123") # Move to the end.
shell("input", "keyevent", *["67" for _ in "Android test"])
time.sleep(0.5)
@@ -184,20 +206,20 @@ try:
# once per clip, so it is not automated here.
type_text("dEeEDu7/b27L#r\\<\\&")
time.sleep(0.5)
shell("input", "keyevent", "4"); time.sleep(0.3)
tap(int(100 * zoom), top + int((105 + bar) * zoom))
hide_keyboard()
tap_label("Save Current Profile")
password = "dEeEDu7/b27L#r<&" # Independent LessPass reference.
expected += password + "\texample.com\talice\t16\t1\t1\t1\t1\t1\t\n"
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected, "Android second profile mismatch"
shell("am", "force-stop", package)
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(1); alive(); dismiss_other_apps_not_responding()
launch_home(adb, output, package, "restart")
alive(); dismiss_other_apps_not_responding()
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected
assert shell("run-as", package, "stat", "-c", "%a", "files/apps/pass/profiles.tsv").strip() == "600"
shot("persisted")
print("Android: second profile, restart and private permissions verified", flush=True)
# The shared Profile retains existing names and edits appearance.
tap_label("Fixture"); time.sleep(0.8); alive()
tap_label("Profile"); time.sleep(0.8); alive()
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
assert "name=Fixture Person\n" in settings, "Profile lost the retained name"
tap(*scroll_to_label("Dark")); time.sleep(0.5)
@@ -206,14 +228,25 @@ try:
shot("profile-appearance")
print("Android: retained profile name and appearance verified", flush=True)
tap(*scroll_to_label("Light"))
# Android exposes Nodes directly in Profile.
# The shared Profile manages nodes on its own page.
hide_keyboard()
tap(*scroll_to_label("Node", direction="up"))
tap(*scroll_to_label("Nodes", direction="up"))
tap_label("Add")
node_input = find_label("address")
tap(*node_input)
type_text("https://sync.example.invalid:8443/")
hide_keyboard()
# The accent button's white label is not reliable in screenshot OCR.
_, appearance = scroll_to_label("Appearance")
tap(width - int(81 * zoom), appearance - int(56 * zoom)); time.sleep(0.8)
# The Add action sits below the visible address field. Its white text
# and the page heading are unreliable OCR targets on small displays.
tap(width // 2, node_input[1] + int(64 * zoom))
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
assert "https://sync.example.invalid:8443" in settings, "Custom node was not added"
# The new node is the last row above Add node; its detail page puts
# Make default below the connection status. Check the saved result.
_, add_node_y = scroll_to_label("Add")
tap(width // 2, add_node_y - int(64 * zoom))
_, status_y = find_label("connected")
tap(width // 2, status_y + int(64 * zoom))
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
assert "node=https://sync.example.invalid:8443\n" in settings, "Custom node was not saved"
assert adb("shell", "run-as", package, "test", "-f", "files/account/keys.txt", check=False).returncode != 0
@@ -222,12 +255,16 @@ try:
# profile. No owner phone is selected by this harness.
shell("am", "force-stop", package)
adb("install", "-r", str(apk))
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(1); alive(); dismiss_other_apps_not_responding()
launch_home(adb, output, package, "updated")
alive(); dismiss_other_apps_not_responding()
assert shell("run-as", package, "cat", "files/profile/settings.txt") == settings
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected
shot("updated")
print("Werkzeug Android: input, profiles, custom node and in-place package update preserved private data")
except BaseException:
shot("failure")
# These tags report asset loading and native startup without recording the
# test's typed credentials. The emulator and its profile are disposable.
logs = adb("logcat", "-d", "-s", "kryon:I", "Werkzeug:I", "AndroidRuntime:E", "libc:F", check=False)
(output / "startup-logcat.txt").write_bytes(logs.stdout)
raise
+44
View File
@@ -0,0 +1,44 @@
"""Locate visible labels in screenshots from the private Android emulator."""
import csv
import io
import subprocess
from PIL import Image
def label_position(path, word, psm=11):
def normalized(value):
return "".join(character for character in value.casefold() if character.isalnum())
for scale in (1, 3):
screenshot = path
if scale == 3:
# Tesseract misses white labels on small, dark theme buttons.
# Separate those glyphs from the background before enlarging.
with Image.open(path) as source:
contrast = source.convert("L").point(lambda value: 0 if value > 160 else 255)
contrast = contrast.resize((source.width * scale, source.height * scale),
Image.Resampling.BICUBIC)
screenshot = path.with_name(path.stem + "-contrast.png")
contrast.save(screenshot)
data = subprocess.check_output(
["tesseract", str(screenshot), "stdout", "--psm", str(psm), "-c", "tessedit_create_tsv=1"],
stderr=subprocess.DEVNULL, text=True)
rows = [item for item in csv.DictReader(io.StringIO(data), delimiter="\t")
if item["text"].strip()]
count = len(word.split())
for index in range(len(rows) - count + 1):
group = rows[index:index + count]
if normalized(" ".join(item["text"] for item in group)) != normalized(word):
continue
# Sparse-text OCR may split a button's words into separate blocks.
# Require one visual line and left-to-right order instead.
top = max(int(item["top"]) for item in group)
bottom = min(int(item["top"]) + int(item["height"]) for item in group)
if bottom <= top or any(int(left["left"]) >= int(right["left"])
for left, right in zip(group, group[1:])):
continue
return ((int(group[0]["left"]) + int(group[-1]["left"]) +
int(group[-1]["width"])) // 2 // scale,
(top + bottom) // 2 // scale)
return None
+60
View File
@@ -0,0 +1,60 @@
"""Wait for visible Home on an explicitly selected private Android emulator."""
import re
import shutil
import time
import xml.etree.ElementTree as ET
from android_labels import label_position
def wait_for_system_ui(adb, frame, output):
# Preserve evidence and wait only for the observed system dialog. An app
# ANR must remain a test failure.
if not label_position(frame, "Wait"):
return False
path = "/data/local/tmp/werk-startup-window.xml"
adb("shell", "rm", "-f", path)
dumped = adb("shell", "uiautomator", "dump", "--compressed", path, check=False)
if dumped.returncode:
return False
tree = adb("shell", "cat", path, check=False)
if tree.returncode:
return False
data = tree.stdout.decode()
if "System UI isn" not in data or "responding" not in data:
return False
try:
nodes = ET.fromstring(data).iter("node")
except ET.ParseError:
return False
for node in nodes:
if node.get("text") == "Wait":
bounds = list(map(int, re.findall(r"\d+", node.get("bounds", ""))))
if len(bounds) == 4:
shutil.copyfile(frame, output / "system-ui-dialog.png")
(output / "system-ui-window.xml").write_text(data)
print("Waiting for the private guest's System UI", flush=True)
adb("shell", "input", "tap", str((bounds[0] + bounds[2]) // 2),
str((bounds[1] + bounds[3]) // 2))
return True
return False
def launch_home(adb, output, package, name, timeout=180):
launch = adb("shell", "am", "start", "-W", "-n",
package + "/android.app.NativeActivity").stdout.decode()
(output / (name + ".txt")).write_text(launch)
# Android's launch metric can time out before a cold software guest draws
# its first frame. Require visible Home before interacting with its list.
deadline = time.monotonic() + timeout
system_waits = 0
while time.monotonic() < deadline:
frame = output / (name + "-home.png")
frame.write_bytes(adb("exec-out", "screencap", "-p").stdout)
if any(label_position(frame, word) for word in ("Werkzeug", "Pass", "Auth", "Calculator")):
print("Android Home visible after " + name, flush=True)
return
if system_waits == 0 and wait_for_system_ui(adb, frame, output):
system_waits = 1
time.sleep(.5)
raise AssertionError("Android Home did not become visible after " + name + ": " + launch)
+114
View File
@@ -0,0 +1,114 @@
"""Regression tests for private Android startup readiness."""
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import Mock, patch
import android_startup
class StartupTest(unittest.TestCase):
def setUp(self):
root = Path(__file__).resolve().parents[1] / "build/android-startup-test"
root.mkdir(parents=True, exist_ok=True)
self.directory = tempfile.TemporaryDirectory(dir=root)
self.addCleanup(self.directory.cleanup)
self.output = Path(self.directory.name)
self.frame = self.output / "frame.png"
self.frame.write_bytes(b"mock screenshot")
self.now = 0
self.clock = patch.object(android_startup.time, "monotonic", lambda: self.now)
self.clock.start()
self.addCleanup(self.clock.stop)
self.sleep = patch.object(android_startup.time, "sleep", self.advance)
self.sleep.start()
self.addCleanup(self.sleep.stop)
def advance(self, seconds):
self.now += seconds
def result(self, code=0, data=b""):
return subprocess.CompletedProcess([], code, data, b"")
def launch(self, adb, timeout=5):
android_startup.launch_home(adb, self.output, "xyz.waozi.pass", "launch", timeout)
def test_delayed_home_after_android_launch_metric_timeout(self):
adb = Mock(return_value=self.result(data=b"Status: timeout\n"))
with patch.object(android_startup, "label_position",
side_effect=lambda frame, word: (10, 20) if self.now >= 3 and word == "Pass" else None):
self.launch(adb)
self.assertEqual(self.now, 3)
self.assertIn("-W", adb.call_args_list[0].args)
self.assertEqual((self.output / "launch.txt").read_text(), "Status: timeout\n")
def test_missing_home_fails_within_deadline(self):
adb = Mock(return_value=self.result())
with patch.object(android_startup, "label_position", return_value=None):
with self.assertRaisesRegex(AssertionError, "did not become visible"):
self.launch(adb, timeout=2)
self.assertEqual(self.now, 2)
def test_default_deadline_allows_cold_home_after_105_seconds(self):
adb = Mock(return_value=self.result())
with patch.object(android_startup, "label_position",
side_effect=lambda frame, word: (10, 20) if self.now >= 105 and word == "Pass" else None):
android_startup.launch_home(adb, self.output, "xyz.waozi.pass", "launch")
self.assertEqual(self.now, 105)
def test_default_deadline_still_rejects_absent_home(self):
adb = Mock(return_value=self.result())
with patch.object(android_startup, "label_position", return_value=None):
with self.assertRaisesRegex(AssertionError, "did not become visible"):
android_startup.launch_home(adb, self.output, "xyz.waozi.pass", "launch")
self.assertEqual(self.now, 180)
def test_launch_command_failure_remains_failure(self):
adb = Mock(side_effect=subprocess.CalledProcessError(1, ["adb"]))
with self.assertRaises(subprocess.CalledProcessError):
self.launch(adb)
adb.assert_called_once()
def test_wait_only_for_exact_system_ui_dialog(self):
for title, expected in (("System UI isn&apos;t responding", True),
("Werkzeug isn&apos;t responding", False),
("Calculator isn&apos;t responding", False)):
with self.subTest(title=title):
tree = ('<hierarchy><node text="' + title +
'"/><node text="Wait" bounds="[0,20][100,60]"/></hierarchy>')
adb = Mock(return_value=self.result(data=tree.encode()))
with patch.object(android_startup, "label_position", return_value=(50, 40)):
self.assertEqual(android_startup.wait_for_system_ui(adb, self.frame, self.output), expected)
taps = [call for call in adb.call_args_list if call.args[:3] == ("shell", "input", "tap")]
self.assertEqual(len(taps), int(expected))
if expected:
self.assertEqual(taps[0].args[-2:], ("50", "40"))
self.assertEqual((self.output / "system-ui-dialog.png").read_bytes(), self.frame.read_bytes())
def test_failed_fresh_dump_never_reads_stale_tree(self):
adb = Mock(side_effect=[self.result(), self.result(1)])
with patch.object(android_startup, "label_position", return_value=(50, 40)):
self.assertFalse(android_startup.wait_for_system_ui(adb, self.frame, self.output))
self.assertEqual(adb.call_count, 2)
self.assertEqual(adb.call_args_list[0].args[:3], ("shell", "rm", "-f"))
def test_failed_read_or_malformed_tree_never_taps(self):
for result in (self.result(1, b"System UI isn't responding"),
self.result(data=b"System UI isn't responding but not XML")):
adb = Mock(side_effect=[self.result(), self.result(), result])
with patch.object(android_startup, "label_position", return_value=(50, 40)):
self.assertFalse(android_startup.wait_for_system_ui(adb, self.frame, self.output))
self.assertEqual(adb.call_count, 3)
def test_persistent_overlay_allows_one_wait_then_fails(self):
adb = Mock(return_value=self.result())
with patch.object(android_startup, "label_position", return_value=None), \
patch.object(android_startup, "wait_for_system_ui", return_value=True) as wait:
with self.assertRaisesRegex(AssertionError, "did not become visible"):
self.launch(adb, timeout=2)
wait.assert_called_once()
if __name__ == "__main__":
unittest.main()
+18 -16
View File
@@ -5,26 +5,28 @@ set -eu
ziran=${1:?pass the ziran command}
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
case "$ziran" in
/*) ;;
*/*) ziran="$root/$ziran" ;;
esac
ziran_root=$("$ziran" pkg path ziran)
kryon=$("$ziran" pkg path kryon)
mingcute=$("$ziran" pkg path mingcute)
# Test Auth in its canonical package graph, as the portable app builds.
auth=$("$ziran" pkg path auth)
mkdir -p build/app-logic-test
"$ziran" bundle --root . --module-path apps/auth --module-path shared --module-path "$ziran_root/std" \
--entry totp_test:Run -o build/app-logic-test/totp.zx apps/auth/totp_test.zi
test "$("$ziran" run build/app-logic-test/totp.zx)" = 0
"$ziran" bundle --root . --module-path apps/auth --module-path shared --module-path "$ziran_root/std" \
--entry exports_test:Run -o build/app-logic-test/exports.zx apps/auth/exports_test.zi
test "$("$ziran" run build/app-logic-test/exports.zx)" = 0
"$ziran" bundle --root . --module-path apps/calculator --module-path "$ziran_root/std" \
--entry arithmetic_test:Run -o build/app-logic-test/arithmetic.zx apps/calculator/arithmetic_test.zi
for name in totp exports; do
(cd "$auth" && "$ziran" bundle --project --locked --entry "${name}_test:Run" \
-o "$root/build/app-logic-test/$name.zx" "tests/${name}_test.zi")
test "$("$ziran" run "build/app-logic-test/$name.zx")" = 0
done
"$ziran" bundle --project --root . --entry arithmetic_test:Run \
-o build/app-logic-test/arithmetic.zx apps/calculator/arithmetic_test.zi
test "$("$ziran" run build/app-logic-test/arithmetic.zx)" = 0
set -- --root tests --module-path apps/calculator \
--module-path "kryon=$kryon/src/backend" --module-path "kryon=$kryon/src/ui" \
--module-path "$kryon/src/ui" --module-path "$mingcute/src" --module-path "$ziran_root/std" \
--entry calculator_input_test:main
"$ziran" bundle --project --root . --entry calendar_test:Run \
-o build/app-logic-test/calendar.zx apps/calendar/calendar_test.zi
test "$("$ziran" run build/app-logic-test/calendar.zx)" = 0
set -- --project --root . --module-path tests --entry calculator_input_test:main
"$ziran" bundle "$@" --define KRYON_HOSTED_UI \
--bind app_context:AppKeyHost=calculator_input_test:AppKeyHost \
--bind app_context:AppFieldInputHost=calculator_input_test:AppFieldInputHost \
--bind-host calculator_input_test \
-o build/app-logic-test/input.zx tests/calculator_input_test.zi
test "$("$ziran" run build/app-logic-test/input.zx)" = 42
"$ziran" build "$@" --target=c -o build/app-logic-test/input-c tests/calculator_input_test.zi
+40 -10
View File
@@ -45,12 +45,18 @@ def capture(name):
labels = source.convert("L").point(lambda value: 0 if value < 140 else 255)
labels.resize((source.width * 3, source.height * 3)).save(work / "labels.png")
source.resize((source.width * 3, source.height * 3)).save(work / "full-text.png")
return command("tesseract", str(work / "labels.png"), "stdout", "--psm", "11")
# Keep both views: thresholding can erase thin strokes at narrow sizes.
return "\n".join(command("tesseract", str(work / target), "stdout", "--psm", "11")
for target in ("labels.png", "full-text.png"))
def click(x, y):
command("xdotool", "mousemove", "--window", window, str(x), str(y))
command("xdotool", "click", "--window", window, "1")
# XTEST updates the private display's physical button state. XSendEvent
# (--window) cannot represent a held press to the native SDL sampler.
command("xdotool", "mousedown", "1")
time.sleep(.12) # Keep the press visible to the native frame sampler.
command("xdotool", "mouseup", "1")
time.sleep(.2)
@@ -71,12 +77,12 @@ def click_word(word):
def key(value):
command("xdotool", "key", "--window", window, value)
command("xdotool", "key", "--clearmodifiers", value)
time.sleep(.2)
def type_text(value):
command("xdotool", "type", "--window", window, "--delay", "30", value)
command("xdotool", "type", "--clearmodifiers", "--delay", "30", value)
time.sleep(.3)
@@ -110,17 +116,39 @@ try:
deadline = time.monotonic() + 20
while True:
home = capture("home")
if all(name in home for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")):
if all(name in home for name in ("Pass", "Auth", "Calculator", "Clock", "Calendar", "Workbook", "Gallery", "Task")):
break
assert app.poll() is None, "Werkzeug exited while loading Apps"
assert time.monotonic() < deadline, "Shared Apps controller did not render: " + home
assert not re.search(r"\d[\d.]*\s*(?:kB|MB)\b", home, re.I), home
for name in ("Auth", "Calculator", "Clock", "Workbook", "Pass"):
pictures = work / "cache/werk/apps/entity/assets/entity"
expected_pictures = {"abstract-amber.webp", "abstract-jade.webp", "abstract-violet.webp",
"flowers.webp", "pfp.webp", "wurm-base.webp", "wurm-reward-skins.webp",
"wurm-skins.webp", "wurm-special-skins.webp"}
expected_pictures.update(f"shovey-{index}.png" for index in range(8))
assert {path.name for path in pictures.glob("*")} == expected_pictures, "Entity's bundled picture resources were not extracted"
picture_diagnostics = []
for path in sorted(pictures.iterdir()):
assert path.stat().st_mode & 0o777 == 0o600, path.name
with Image.open(path) as image:
image.load()
picture_diagnostics.append({'resource': path.name, 'size': image.size,
'private': True})
(work / 'entity-resource-diagnostics.json').write_text(json.dumps({
'fixture_only': True, 'bundle': 'entity',
'extraction_path': 'assets/entity', 'decoded': picture_diagnostics,
}, indent=2) + '\n')
for name in ("Auth", "Calculator", "Clock", "Calendar", "Workbook", "Gallery", "Pass"):
click_word(name)
expect_title(name)
assert "stopped" not in capture(name.lower()).lower(), name + " failed to run"
click(28, 28)
expect_title("Werkzeug")
click_word("Task")
expect_title("Task Manager")
assert "stopped" not in capture("taskmgr").lower(), "Task Manager failed to run"
click(28, 28)
expect_title("Werkzeug")
for width, height in ((360, 640), (720, 520)):
command("xdotool", "windowsize", "--sync", window, str(width), str(height))
text = capture(f"home-{width}")
@@ -153,10 +181,12 @@ try:
click(120, name[1] + 34)
key("ctrl+a")
type_text("Timepiece")
# The icon choices are: own icon, then Pass, Auth, Calculator, Clock, Workbook.
# The icon choices are: own icon, then Pass, Auth, Calculator, Clock, Calendar, Workbook, Gallery, Task Manager.
click(name[0] - 16 + 120, name[1] + 116)
# White text on the filled Save button is not reliably recognized by OCR.
click(310, name[1] + 182)
# White text on the filled Save button is not reliably recognized by OCR;
# Save sits directly to the right of Cancel on the same row.
cancel = word_position("Cancel")
click(310, cancel[1])
saved = json.loads(preferences.read_text())
clock = next(item for item in saved["apps"] if item["id"] == "clock")
assert clock["title"] == "Timepiece" and clock["icon"] == "auth", clock
@@ -184,7 +214,7 @@ try:
saved = json.loads(preferences.read_text())
clock = next(item for item in saved["apps"] if item["id"] == "clock")
assert not clock["favorite"] and clock["title"] == "Timepiece" and clock["icon"] == "auth"
print("Shared Apps: list/grid, search, menus, pins, name/icon edits, restart persistence, five tools and resized layouts verified locally")
print("Shared Apps: list/grid, search, menus, pins, name/icon edits, restart persistence, eight tools, Entity picture resources and resized layouts verified locally")
finally:
if app.poll() is None:
app.terminate()
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/env python3
"""Auth cards in Werkzeug's native host, using only private Xvfb and RFC keys."""
from pathlib import Path
import base64
import hashlib
import hmac
import os
import re
import shutil
import statistics
import struct
import subprocess
import time
from PIL import Image, ImageOps
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
root = Path(__file__).resolve().parents[1]
output = root / "build/auth-gui-test"
shutil.rmtree(output, ignore_errors=True)
data = output / "data"
(data / "profile").mkdir(parents=True)
settings = data / "profile/settings.txt"
settings.write_text("theme_mode=2\n")
environment = dict(os.environ, WERK_DATA=str(data), WERK_ASSETS=str(root / "build"),
ENTITY_DATA=str(output / "entity"), XDG_CACHE_HOME=str(output / "cache"),
XDG_CONFIG_HOME=str(output / "config"), XDG_DATA_HOME=str(output / "xdg"))
key = b"12345678901234567890"
second_key = b"12345678901234567890123456789012"
links = "\n".join(
f"otpauth://totp/{issuer}:alice?issuer={issuer}&secret={base64.b32encode(secret).decode()}"
f"&digits={digits}&period={period}"
for issuer, secret, digits, period in
(("Fixture", key, 6, 10), ("Second", second_key, 8, 60)))
subprocess.run([str(root / "build/werk"), "auth", "import"], input=links,
env=environment, capture_output=True, text=True, check=True, timeout=30)
app = None
def command(*args):
return subprocess.check_output(args, env=environment, text=True, timeout=20)
def expected(secret, at, digits, period):
mac = hmac.new(secret, struct.pack(">Q", int(at) // period), hashlib.sha1).digest()
offset = mac[-1] & 15
value = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7fffffff
return f"{value % 10 ** digits:0{digits}d}"
def capture(name):
target = output / f"{name}.png"
command("import", "-window", window, str(target))
return target
def read_code(image, bounds, name, expected_codes=None):
target = output / f"{name}.png"
with Image.open(image) as frame:
region = frame.crop(bounds).convert("L")
if region.getpixel((0, 0)) < 128:
region = ImageOps.invert(region)
region = ImageOps.autocontrast(region)
# Small preview glyphs differ between installed fonts, and Tesseract reads
# a large current-code 5 as 0 or 9 at some scales. Require an exact
# independently computed RFC code from real OCR, with no digit substitution.
first = None
variants = ((scale, threshold) for scale in (6, 3, 4) for threshold in (None, 150, 110, 190))
for scale, threshold in variants:
variant = region.resize((region.width * scale, region.height * scale), Image.Resampling.LANCZOS)
if threshold is not None:
variant = variant.point(lambda value: 255 if value > threshold else 0)
variant.save(target)
text = command("tesseract", str(target), "stdout", "--psm", "7",
"-c", "preserve_interword_spaces=1",
"-c", "tessedit_char_whitelist=0123456789 ").strip()
if first is None:
first = text
if expected_codes is None or re.sub(r"\s", "", text) in expected_codes:
break
else:
raise AssertionError(f"{name}: OCR {first!r}, expected one of {sorted(expected_codes)}")
digits = re.sub(r"\s", "", text)
if " " not in text:
# OCR sometimes joins a real grouping space. Character positions
# must still show the extra gaps separating each group of three digits.
boxes = command("tesseract", str(target), "stdout", "--psm", "7",
"-c", "tessedit_char_whitelist=0123456789", "makebox")
centers = [(int(parts[1]) + int(parts[3])) / 2
for line in boxes.splitlines()
if len(parts := line.split()) == 6 and parts[0].isdigit()]
assert len(centers) == len(digits) and len(digits) in (6, 8), boxes
steps = [right - left for left, right in zip(centers, centers[1:])]
separators = set(range(2, len(steps), 3))
ordinary = [step for index, step in enumerate(steps) if index not in separators]
assert all(steps[index] > statistics.median(ordinary) + 6 for index in separators), f"No visible grouping gap in {name}: {steps}"
return digits
def stop():
if app is not None and app.poll() is None:
app.terminate()
app.wait(timeout=10)
try:
for dark in (True, False):
settings.write_text(f"theme_mode={2 if dark else 1}\n")
app = subprocess.Popen([str(root / "build/werk"), "--app", "auth"], env=environment)
deadline = time.monotonic() + 30
window = None
while time.monotonic() < deadline:
assert app.poll() is None, "Werkzeug exited"
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
env=environment, capture_output=True, text=True)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
break
time.sleep(0.1)
assert window is not None, "Auth did not show a private window"
command("xdotool", "windowsize", window, "420", "760")
command("xdotool", "windowfocus", "--sync", window)
time.sleep(1)
before = time.time()
image = capture("auth-dark" if dark else "auth-light")
after = time.time()
with Image.open(image) as frame:
body = frame.convert("RGB").getpixel((200, 240))
assert body == ((28, 28, 28) if dark else (242, 240, 245)), body
for row, secret, digits, period in ((0, key, 6, 10), (1, second_key, 8, 60)):
y = row * 136
for label, bounds, offset in (
("current", (32, 184 + y, 236, 230 + y), 0),
("next", (234, 207 + y, 380, 234 + y), period)):
wanted = {expected(secret, at + offset, digits, period) for at in (before, after)}
actual = read_code(image, bounds, f"{label}-{row}-{dark}", wanted)
assert actual in wanted, (row, label, actual)
# Background, title, account, current code, preview and bottom padding.
for x, y in ((20, 124), (70, 146), (70, 169), (100, 210), (340, 220), (390, 244)):
subprocess.run(["xclip", "-selection", "clipboard", "-i"],
input="fixture-before-card", text=True, env=environment,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=True, timeout=20)
before = time.time()
command("xdotool", "mousemove", "--window", window, str(x), str(y))
command("xdotool", "click", "1")
time.sleep(0.15)
copied = command("xclip", "-selection", "clipboard", "-o")
assert re.fullmatch(r"[0-9]{6}", copied), (x, y, copied)
assert copied in {expected(key, at, 6, 10) for at in (before, time.time())}, (x, y, copied)
toast = output / f"copy-toast-text-{dark}.png"
with Image.open(capture(f"copy-toast-{dark}")) as frame:
center = frame.width // 2
region = frame.crop((center - 105, frame.height - 66, center + 105, frame.height - 4)).convert("L")
if dark:
region = ImageOps.invert(region)
region = ImageOps.autocontrast(region)
region.resize((region.width * 4, region.height * 4), Image.Resampling.LANCZOS).save(toast)
text = command("tesseract", str(toast), "stdout", "--psm", "11")
assert "Copied to clipboard" in text, text
# Edit remains independently clickable and never overwrites the clipboard.
before_edit = copied
command("xdotool", "mousemove", "--window", window, "370", "146")
command("xdotool", "click", "1")
time.sleep(0.2)
assert command("xclip", "-selection", "clipboard", "-o") == before_edit
edit_image = capture("edit-dark" if dark else "edit-light")
text = command("tesseract", str(edit_image), "stdout", "--psm", "11")
assert "Remove account" in text, text
# Sparse-page OCR skips small labels inside filled buttons. Read the
# actual action in isolation, with enough contrast in either theme.
cancel_image = output / f"cancel-{dark}.png"
with Image.open(edit_image) as frame:
action = frame.crop((214, 252, 404, 292)).convert("L")
if dark:
action = ImageOps.invert(action)
action.resize((action.width * 6, action.height * 6)).save(cancel_image)
assert command("tesseract", str(cancel_image), "stdout", "--psm", "7").strip() == "Cancel"
command("xdotool", "mousemove", "--window", window, "309", "272")
command("xdotool", "click", "1")
time.sleep(0.2)
returned = capture(f"after-cancel-{dark}")
assert re.fullmatch(r"[0-9]{6}", read_code(returned, (32, 184, 236, 230), f"returned-{dark}"))
if dark:
# The short fixture period exercises both colours and a new cycle.
seen = set()
deadline = time.monotonic() + 13
while len(seen) < 2 and time.monotonic() < deadline:
image = capture("progress")
with Image.open(image) as frame:
pixels = frame.convert("RGB")
for phase, color in (("purple", (159, 53, 232)), ("orange", (238, 145, 48))):
length = sum(pixels.getpixel((x, 121)) == color for x in range(16, 394))
if length > 10:
assert 187 <= length <= 378 if phase == "purple" else length <= 191
seen.add(phase)
time.sleep(0.2)
assert seen == {"purple", "orange"}, seen
stop()
print("Auth native GUI: grouped current/next codes, raw copy and toast, both bar colours, dark/light cards")
finally:
stop()
+2 -3
View File
@@ -11,15 +11,14 @@ def render(size, background=None):
return image
outputs = {'assets/app/icon.png':512, 'fastlane/metadata/android/en-US/images/icon.png':512,
'web/site/icons/favicon-32.png':32, 'web/site/icons/apple-touch-icon.png':180,
'web/site/icons/icon-192.png':192, 'web/site/icons/icon-512.png':512,
'web/site/app/icons/icon-192.png':192, 'web/site/app/icons/icon-512.png':512}
'web/site/icons/icon-192.png':192, 'web/site/icons/icon-512.png':512}
for density, size in [('mdpi',48),('hdpi',72),('xhdpi',96),('xxhdpi',144),('xxxhdpi',192)]:
outputs[f'droid/app/src/main/res/mipmap-{density}/ic_launcher.png'] = size
for path, size in outputs.items():
render(size, '#ffffff' if 'launcher' in path or '/icons/' in path else None).save(ROOT / path)
font_path = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
name = 'Werkzeug'
for path, size in [('assets/app/readme-banner.png',(1536,512)), ('assets/app/readme-square-630x500.png',(630,500)), ('showcase/banner.png',(1536,1024)), ('web/site/images/social.png',(1536,1024))]:
for path, size in [('assets/app/readme-banner.png',(1536,512)), ('assets/app/readme-square-630x500.png',(630,500)), ('showcase/banner.png',(1536,1024))]:
w,h=size; image=Image.new('RGB',size,'#f7f3ff'); d=ImageDraw.Draw(image)
icon_size=int(min(w*.24,h*.55))
while True: # shrink the mark until the name fits with a margin
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Verify Calendar and Task Manager end-to-end inside Werkzeug on private Xvfb."""
import csv
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
from PIL import Image
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
root = Path(__file__).resolve().parents[1]
work = root / "build/calendar-taskmgr-gui-test"
binary = root / "build/werk"
assets = root / "build"
shutil.rmtree(work, ignore_errors=True)
work.mkdir(parents=True)
env = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
WERK_ASSETS=str(assets), ENTITY_DATA=str(work / "entity"),
XDG_CONFIG_HOME=str(work / "config"), XDG_DATA_HOME=str(work / "share"),
XDG_CACHE_HOME=str(work / "cache"))
for name in ("HOME", "WERK_DATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"):
Path(env[name]).mkdir(parents=True)
profile = Path(env["WERK_DATA"]) / "profile"
profile.mkdir()
(profile / "settings.txt").write_text("theme_mode=1\n")
def cmd(*args):
return subprocess.check_output(args, env=env, text=True, timeout=20)
def capture(window, name):
time.sleep(0.35)
picture = work / f"{name}.png"
cmd("import", "-window", window, str(picture))
with Image.open(picture) as src:
labels = src.convert("L").point(lambda v: 0 if v < 140 else 255)
labels.resize((src.width * 3, src.height * 3)).save(work / "labels.png")
src.resize((src.width * 3, src.height * 3)).save(work / "full.png")
return "\n".join(cmd("tesseract", str(work / t), "stdout", "--psm", "11")
for t in ("labels.png", "full.png"))
def click(window, x, y):
cmd("xdotool", "mousemove", "--window", window, str(x), str(y))
cmd("xdotool", "mousedown", "1")
time.sleep(0.12)
cmd("xdotool", "mouseup", "1")
time.sleep(0.25)
def word_pos(window, word):
capture(window, "probe")
for target in ("labels.png", "full.png"):
tsv = cmd("tesseract", str(work / target), "stdout", "--psm", "11",
"-c", "tessedit_create_tsv=1")
for row in csv.DictReader(io.StringIO(tsv), delimiter="\t"):
if row["text"].strip() == word:
return ((int(row["left"]) + int(row["width"]) // 2) // 3,
(int(row["top"]) + int(row["height"]) // 2) // 3)
raise AssertionError(f"Missing visible control: {word!r}")
def launch(app_id, expected_title):
proc = subprocess.Popen([str(binary), "--app", app_id], env=env)
deadline = time.monotonic() + 25
window = None
while time.monotonic() < deadline:
assert proc.poll() is None, f"{app_id} exited during startup"
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(proc.pid)],
env=env, capture_output=True, text=True, timeout=5)
if found.returncode == 0 and found.stdout.strip():
window = found.stdout.splitlines()[0]
if cmd("xdotool", "getwindowname", window).strip() == expected_title:
break
time.sleep(0.15)
assert window, f"{app_id} did not show its window"
cmd("xdotool", "windowfocus", "--sync", window)
return proc, window
# 1. Verify Simple Calendar: Month, event creation, persistence, Week & Agenda.
proc, win = launch("calendar", "Calendar")
try:
text = capture(win, "calendar-month")
assert all(w in text for w in ("Week", "Agenda", "Today")), text
assert "stopped" not in text.lower(), text
# Open New Event editor via the top-right "+" button (x=392, y=122).
click(win, 392, 122)
editor = capture(win, "calendar-editor")
assert "New Event" in editor and "Repeat" in editor, editor
# Type event title and save (Title field is auto-focused).
cmd("xdotool", "type", "--clearmodifiers", "--delay", "25", "Launch Review")
time.sleep(0.25)
# Save button is at bottom-left of the 420x760 window (x=60, y=730).
click(win, 60, 730)
after_save = capture(win, "calendar-saved")
assert "Launch" in after_save or "Review" in after_save, after_save
# Check private persistence on disk.
cal_file = Path(env["WERK_DATA"]) / "apps/calendar/calendar.json"
assert cal_file.exists(), "calendar.json was not written"
assert cal_file.stat().st_mode & 0o777 == 0o600
data = json.loads(cal_file.read_text())
assert any(ev["title"] == "Launch Review" for ev in data["events"]), data
# Switch to Week and Agenda views.
wx, wy = word_pos(win, "Week")
click(win, wx, wy)
week_text = capture(win, "calendar-week")
assert "Launch" in week_text or "Review" in week_text, week_text
ax, ay = word_pos(win, "Agenda")
click(win, ax, ay)
agenda_text = capture(win, "calendar-agenda")
assert "Launch" in agenda_text or "Review" in agenda_text, agenda_text
finally:
proc.terminate()
proc.wait(timeout=10)
# 2. Verify Task Manager: Processes table, live /proc metrics, Performance graphs.
proc, win = launch("taskmgr", "Task Manager")
try:
text = capture(win, "taskmgr-processes")
assert "Performance" in text and "Mem" in text, text
assert "stopped" not in text.lower(), text
px, py = word_pos(win, "Performance")
click(win, px, py)
perf = capture(win, "taskmgr-performance")
assert "CPU" in perf and "Memory" in perf and "System" in perf, perf
assert "stopped" not in perf.lower(), perf
finally:
proc.terminate()
proc.wait(timeout=10)
print("Calendar and Task Manager GUI end-to-end tests passed locally")
+82 -5
View File
@@ -1,10 +1,15 @@
#!/usr/bin/env python3
"""Test native Entity account transitions with private fixture data only."""
import os
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import shutil
import shlex
import subprocess
import time
import threading
from urllib.parse import parse_qs, urlparse
ROOT = Path(__file__).resolve().parents[1]
ZIRAN = os.environ.get('ZIRAN_BIN', str(ROOT / 'scripts/ziran.sh'))
@@ -20,21 +25,93 @@ output = ROOT / 'build/entity-account-test'
output.mkdir(parents=True, exist_ok=True)
generated = output / 'generated'
shutil.rmtree(generated, ignore_errors=True)
subprocess.run([ZIRAN, 'build', '--project', '--root', str(ROOT), '--define', 'PLATFORM_DESKTOP', '--target=c',
subprocess.run([ZIRAN, 'build', '--project', '--root', str(ROOT), '--define', 'PLATFORM_DESKTOP',
'--bind-host', 'entity_account_test', '--target=c',
'--entry', 'entity_account_test:Check', '-o', str(generated),
'tests/entity_account_test.zi'], cwd=ROOT, env=ENV, check=True)
(generated / 'main.c').write_text('#include "tests/entity_account_test.h"\n#include <stdio.h>\n#include <string.h>\n'
'int main(void) { int result = Check(); if (result) fprintf(stderr, "Entity account fixture %d failed\\n", result); return result != 0; }\n')
executable = output / 'test'
desktop_libraries = shlex.split(subprocess.check_output(
['pkg-config', '--libs', 'gtk+-3.0', 'x11'], text=True, env=ENV))
subprocess.run([os.environ.get('CC', 'cc'), '-std=c11', '-O2', '-ffunction-sections', '-fdata-sections',
'-Wl,--gc-sections', f'-I{std_root / "include"}', f'-I{generated}', f'-I{monocypher / "src"}',
*map(str, generated.rglob('*.c')), str(monocypher / 'src/monocypher.c'),
str(monocypher / 'src/optional/monocypher-ed25519.c'),
str(ROOT / 'build/liboqs/lib/liboqs.a'), '-l:libcurl.so.4', '-lpthread', '-lm', '-o', str(executable)], check=True, env=ENV)
str(ROOT / 'build/liboqs/lib/liboqs.a'), *desktop_libraries,
'-l:libcurl.so.4', '-lpthread', '-lm', '-o', str(executable)], check=True, env=ENV)
data = output / 'data'
shutil.rmtree(data, ignore_errors=True)
ENV.update(WERK_DATA=str(data), XDG_CACHE_HOME=str(output / 'cache'))
subprocess.run([str(executable)], check=True, env=ENV)
ENV.update(WERK_DATA=str(data), ENTITY_DATA=str(data / 'entity'), XDG_CACHE_HOME=str(output / 'cache'))
requests = []
fixture_errors = []
class PictureNode(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, payload):
body = json.dumps(payload).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
path = urlparse(self.path)
# The real management pump also checks backup availability. Keep
# that independent request in the fixture instead of bypassing it.
if path.path == '/api/v1/account/backup':
requests.append('backup-status')
self.reply({'stored': False})
return
if path.path == '/api/v1/account-backup/methods':
requests.append('sign-in-methods')
self.reply({})
return
owner = parse_qs(path.query).get('user_id', [''])[0]
if path.path != '/api/v1/sync/challenge' or len(owner) != 64:
fixture_errors.append('Unexpected challenge route or identity length')
self.send_error(400)
return
requests.append('challenge')
self.reply({'nonce': '0' * 64})
def do_POST(self):
assert self.path == '/api/v1/sync/login'
assert self.headers.get('X-Daochi-User') and self.headers.get('X-Daochi-Signature')
body = self.rfile.read(int(self.headers['Content-Length']))
assert isinstance(json.loads(body), dict)
requests.append('login')
self.reply({'auth_token': 'private-fixture-token', 'expires_in_seconds': 3600,
'server_time': int(time.time()), 'profile_icon': 128,
'account_alias': 'fixture_user'})
with ThreadingHTTPServer(('127.0.0.1', 0), PictureNode) as node:
thread = threading.Thread(target=node.serve_forever, daemon=True)
thread.start()
try:
subprocess.run([str(executable)], check=True, env=dict(
ENV, WERK_TEST_PICTURE_SERVER=f'http://127.0.0.1:{node.server_port}'))
finally:
node.shutdown()
thread.join(timeout=5)
assert 'login' in requests and requests.index('challenge') < requests.index('login'), \
'Background picture read did not complete the real HTTP login'
assert requests.count('challenge') >= requests.count('login')
assert not fixture_errors, fixture_errors
(output / 'picture-sync-diagnostics.json').write_text(json.dumps({
'fixture_only': True,
'profile_opened': False,
'pump': 'WerkManagementPump',
'http_routes': requests,
'received_icon': 128,
'local_and_shared_persistence': 'passed',
'other_app_profile_fields': 'preserved',
}, indent=2) + '\n')
# A concurrent CLI reader must wait for an active GUI switch instead of
# treating its rollback journal as an interrupted transaction.
ready = data / 'account/switch/held'
@@ -59,4 +136,4 @@ finally:
ready.unlink(missing_ok=True)
for path in data.rglob('*'):
assert path.stat().st_mode & 0o077 == 0, f'Non-private fixture path: {path.name}'
print('Entity: vault retention, merge/replace, tombstones, pause choice, failed writes, interrupted-switch recovery, concurrent reader locking and logout passed.')
print('Entity: account transitions, vault retention, failed-write recovery, concurrent locking, picture readback and shared-profile preservation passed.')
+377
View File
@@ -0,0 +1,377 @@
#!/usr/bin/env python3
"""Gallery behavioral fixtures and real chooser/UI integration on private Xvfb.
Run via build-queue -- python3 scripts/private-display.py dbus-run-session -- python3
scripts/gallery_gui_test.py. --behavioral-only needs just the native host test;
WERK_GALLERY_TEST_EXECUTABLE selects that test (default build/gallery-test).
"""
import argparse
import contextlib
import csv
import io
import os
from pathlib import Path
import shutil
import signal
import struct
import subprocess
import time
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
os.umask(0o077)
parser = argparse.ArgumentParser()
parser.add_argument("--behavioral-only", action="store_true")
args = parser.parse_args()
work = ROOT / "build/gallery-test-fixtures"
if work.exists():
shutil.rmtree(work)
work.mkdir(parents=True)
photos = work / "photos"
photos.mkdir()
(photos / "Album").mkdir()
empty = work / "empty"
empty.mkdir()
outside = work / "photos-other"
outside.mkdir()
# Generated fixtures only. No personal photo or desktop access.
for name, color in (("a.png", "red"), ("z.JPG", "blue"), ("Album/b.png", "green"), ("été.png", "cyan")):
image = Image.new("RGB", (640, 480), color)
draw = ImageDraw.Draw(image)
draw.rectangle((220, 100, 420, 380), fill="yellow")
image.save(photos / name)
Image.new("RGB", (40, 40), "magenta").save(outside / "outside.png")
# Valid dimensions with a corrupt payload exercises the real host decoder.
(photos / "broken.png").write_bytes((photos / "a.png").read_bytes()[:33] + b"corrupt image fixture")
(photos / "notes.txt").write_text("not a photo")
(photos / ".hidden.png").write_bytes((photos / "a.png").read_bytes())
(photos / "escaped.png").symlink_to(outside / "outside.png")
(photos / "EscapedAlbum").symlink_to(outside, target_is_directory=True)
large = work / "large"
large.mkdir()
for index in reversed(range(520)):
(large / f"{index:04}.png").write_bytes((photos / "a.png").read_bytes())
images = work / "image-cases"
images.mkdir()
# An ordinary six-megapixel PNG exceeds the former16MiB cutoff without
# requiring a large decoder allocation. All assets stay binary on disk.
Image.new("RGB", (3072, 2048), "red").save(images / "00-large.png", compress_level=0)
assert (images / "00-large.png").stat().st_size > 16 * 1024 * 1024
with (images / "01-size-limit.png").open("wb") as stream:
stream.write((photos / "a.png").read_bytes()[:33])
stream.truncate(64 * 1024 * 1024 + 1)
header = bytearray((photos / "a.png").read_bytes()[:33])
header[16:24] = struct.pack(">II", 40000, 40000)
(images / "02-pixel-limit.png").write_bytes(header)
(images / "03-invalid.png").write_bytes(b"not an image")
for index, suffix in enumerate(("bmp", "webp", "gif", "jpg"), 4):
Image.new("RGB", (80, 60), "blue").save(images / f"{index:02}-photo.{suffix}")
retry = work / "retry"
retry.mkdir()
(retry / "retry.png").write_bytes((photos / "a.png").read_bytes())
blocked = work / "blocked"
blocked.write_text("a regular file cannot contain location.txt")
missing_programs = work / "no-programs"
missing_programs.mkdir()
env = dict(os.environ)
for name, sub in (("HOME", "home"), ("WERK_DATA", "data"), ("ENTITY_DATA", "entity"),
("XDG_CONFIG_HOME", "config"), ("XDG_DATA_HOME", "share"), ("XDG_CACHE_HOME", "cache")):
env[name] = str(work / sub)
Path(env[name]).mkdir(parents=True, exist_ok=True)
env["WERK_ASSETS"] = os.environ.get("WERK_TEST_ASSETS", str(ROOT / "build"))
env["WERK_GALLERY_TEST_DATA"] = str(work / "host-data")
env["WERK_GALLERY_TEST_OUTSIDE"] = str(outside / "outside.png")
env["WERK_GALLERY_TEST_CANDIDATE"] = str(outside)
env["WERK_GALLERY_TEST_BLOCKED"] = str(blocked)
private = Path(env["WERK_GALLERY_TEST_DATA"]) / "gallery"
private.mkdir(parents=True, mode=0o700)
exe = Path(os.environ.get("WERK_GALLERY_TEST_EXECUTABLE", ROOT / "build/gallery-test"))
assert exe.is_file(), f"Build fixture host test first: {exe}"
for mode, location in (("normal", photos), ("persist", photos), ("images", images), ("retry", retry), ("chooser-missing", photos), ("empty", empty), ("large", large), ("revoked", work / "missing"), ("first-save-failure", None)):
if location is None:
(private / "location.txt").unlink(missing_ok=True)
else:
(private / "location.txt").write_text(str(location))
(private / "location.txt").chmod(0o600)
native_env = {key: value for key, value in env.items() if key not in
("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER")}
native_env["WERK_GALLERY_TEST_MODE"] = mode
if mode == "chooser-missing":
native_env["PATH"] = str(missing_programs)
result = subprocess.run([str(exe)], env=native_env, timeout=30)
assert result.returncode == 0, f"Gallery native fixture {mode}: exit {result.returncode}"
if mode in ("normal", "persist"):
assert (private / "location.txt").read_text() == str(outside if mode == "persist" else photos)
assert (private / "location.txt").stat().st_mode & 0o777 == 0o600
if mode == "persist":
# A fresh OS process must read the actual grant just saved by the
# native service. Do not preseed or rewrite location.txt here.
reopened = subprocess.run([str(exe)], env=dict(native_env, WERK_GALLERY_TEST_MODE="persist-reopen"), timeout=30)
assert reopened.returncode == 0, "Saved grant did not survive a fresh process"
print("Gallery native fixtures passed: sorting/albums, real grant save/reload, failed-save rollback, retry after read failure, >16MiB image, byte/pixel bounds, format headers, empty/missing roots, symlink isolation and viewer state", flush=True)
if args.behavioral_only:
raise SystemExit(0)
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use scripts/private-display.py"
# First launch has no grant: exercise empty, real chooser cancellation and
# successful folder grant, viewer controls and process restart persistence.
binary = Path(os.environ.get("WERK_TEST_BINARY", ROOT / "build/werk"))
app = None
window = None
def command(*values):
return subprocess.check_output(values, env=env, text=True, timeout=20).strip()
def wait_until(action, description, seconds=30):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
assert app.poll() is None, "Gallery host exited"
value = action()
if value:
return value
time.sleep(.15)
capture("failure")
raise AssertionError(description)
def capture(name):
path = work / f"{name}.png"
command("import", "-window", window, str(path))
return path
def words(region="all", psm=11):
path = capture("current")
with Image.open(path) as image:
top = max(0, image.height - 128) if region == "footer" else 0
bottom = min(152, image.height) if region == "header" else image.height
image = image.crop((0, top, image.width, bottom))
image.convert("RGB").resize((image.width * 3, image.height * 3)).save(work / "text.png")
text = command("tesseract", str(work / "text.png"), "stdout", "--psm", str(psm), "-c", "tessedit_create_tsv=1")
rows = [row for row in csv.DictReader(io.StringIO(text), delimiter="\t")
if (row.get("text") or "").strip() and (row.get("left") or "").isdigit()]
for row in rows:
row["top"] = str(int(row["top"]) + top * 3)
return rows
def has_text(expected):
return any(expected.lower() in " ".join(row["text"] for row in words(region, psm)).lower()
for region, psm in (("all", 11), ("header", 6), ("footer", 6)))
def click_text(expected):
def find():
parts = expected.split()
# Bright fixture photos can dominate sparse OCR. Read the viewer's
# control strip separately while keeping exact labels and coordinates.
for region, psm in (("all", 11), ("header", 6), ("footer", 6)):
rows = words(region, psm)
for index, row in enumerate(rows):
if [item["text"].strip().lower() for item in rows[index:index + len(parts)]] == [p.lower() for p in parts]:
return (int(row["left"]) + int(row["width"]) // 2) // 3, (int(row["top"]) + int(row["height"]) // 2) // 3
return None
x, y = wait_until(find, "Missing Gallery control: " + expected)
command("xdotool", "windowfocus", "--sync", window)
command("xdotool", "mousemove", "--window", window, str(x), str(y))
command("xdotool", "click", "1")
time.sleep(.3)
print(f"Gallery clicked {expected!r} at {x},{y}", flush=True)
def launch():
global app, window
with (work / "runtime.log").open("ab") as log:
app = subprocess.Popen([str(binary)], env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
def find():
result = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)], env=env, text=True, capture_output=True)
return result.stdout.splitlines()[0] if result.returncode == 0 else None
window = wait_until(find, "Werkzeug did not open its test window")
command("xdotool", "windowfocus", "--sync", window)
click_text("Gallery")
def chooser():
def find():
result = subprocess.run(["xdotool", "search", "--onlyvisible", "--name", "^Choose a local photo folder$"], env=env, text=True, capture_output=True)
if result.returncode:
return None
for candidate in result.stdout.splitlines():
# GTK may delegate Zenity's chooser to the portal on our private
# session bus. Its window then belongs to the portal process.
# The exact title is confined to this test's private Xvfb; also
# require the host's actual chooser process to remain alive.
children = subprocess.run(["ps", "-o", "comm=", "--ppid", str(app.pid)],
env=env, text=True, capture_output=True)
if "zenity" in children.stdout.split():
return candidate
return None
try:
return wait_until(find, "Native folder chooser did not appear")
except AssertionError:
# Only this test's Xvfb windows are visible through env[DISPLAY].
windows = subprocess.run(["xdotool", "search", "--onlyvisible", "--name", "."],
env=env, text=True, capture_output=True)
for candidate in windows.stdout.splitlines()[:20]:
title = command("xdotool", "getwindowname", candidate)
pid = subprocess.run(["xdotool", "getwindowpid", candidate], env=env, text=True, capture_output=True)
print(f"Private chooser diagnostic: {candidate} pid={pid.stdout.strip()} title={title!r}", flush=True)
children = subprocess.run(["ps", "-o", "pid,ppid,comm,wchan:32", "--ppid", str(app.pid)],
env=env, text=True, capture_output=True)
print(children.stdout, flush=True)
raise
def colors(path):
with Image.open(path) as image:
return sum(1 for r, g, b in image.convert("RGB").getdata() if r > 190 and g < 70 and b < 70), sum(1 for r, g, b in image.convert("RGB").getdata() if b > 190 and r < 70 and g < 70)
def marker_area(path):
with Image.open(path) as image:
return sum(1 for r, g, b in image.convert("RGB").getdata() if r > 190 and g > 190 and b < 70)
def marker_center(path):
with Image.open(path) as image:
total_x = total_y = count = 0
for index, (r, g, b) in enumerate(image.convert("RGB").getdata()):
if r > 190 and g > 190 and b < 70:
total_x += index % image.width
total_y += index // image.width
count += 1
assert count, "Fixture marker is not visible"
return total_x / count, total_y / count
def assert_photo_fits(path):
with Image.open(path) as image:
left, top, right, bottom = image.width, image.height, 0, 0
for index, (r, g, b) in enumerate(image.convert("RGB").getdata()):
if r > 190 and g < 70 and b < 70:
x, y = index % image.width, index // image.width
left, top, right, bottom = min(left, x), min(top, y), max(right, x), max(bottom, y)
assert right > left and bottom > top, "Photo is absent"
assert left >= 8 and right < image.width - 8 and top > 80 and bottom < image.height - 90, "Fit escaped the viewer viewport"
def choose_location(location):
click_text("Choose folder")
dialog = chooser()
def dialog_key(key):
command("xdotool", "windowfocus", "--sync", dialog)
command("xdotool", "key", "--clearmodifiers", key)
# Leave GTK's Recent search view before entering a directory.
dialog_key("alt+Home")
time.sleep(.5)
dialog_key("ctrl+l")
command("xdotool", "type", "--clearmodifiers", str(location) + "/")
time.sleep(.5)
dialog_key("Return")
def closed():
visible = subprocess.run(["xdotool", "search", "--onlyvisible", "--name",
"^Choose a local photo folder$"], env=env, text=True,
capture_output=True)
return dialog not in visible.stdout.splitlines()
try:
wait_until(closed, "Native folder chooser did not accept the fixture folder")
except AssertionError:
focus = command("xdotool", "getwindowfocus")
print(f"Chooser focus: {focus} {command('xdotool', 'getwindowname', focus)!r}", flush=True)
command("import", "-window", dialog, str(work / "chooser-selection.png"))
raise
try:
launch()
assert has_text("Choose a folder"), "Missing initial empty state"
click_text("Choose folder")
dialog = chooser()
command("xdotool", "windowfocus", "--sync", dialog)
command("xdotool", "key", "Escape")
wait_until(lambda: has_text("cancelled"), "Chooser cancellation was not shown")
choose_location(photos)
wait_until(lambda: has_text("a.png") and has_text("z.JPG"), "Fixture photos did not populate")
grid = capture("grid")
red, blue = colors(grid)
assert red > 2000 and blue > 2000, "Real fixture thumbnails were not rendered"
saved = Path(env["WERK_DATA"]) / "gallery/location.txt"
blocked_save = saved.with_name("location.txt.new")
blocked_save.mkdir()
choose_location(empty)
wait_until(lambda: has_text("Could not save") and has_text("a.png"), "Failed save did not preserve the previous album")
assert saved.read_text() == str(photos), "Failed selection replaced the saved grant"
blocked_save.rmdir()
choose_location(empty)
wait_until(lambda: has_text("No supported photos"), "Folder selection did not recover after save failure")
choose_location(photos)
wait_until(lambda: has_text("a.png") and has_text("z.JPG"), "Original fixture folder did not reopen")
click_text("Album")
wait_until(lambda: has_text("b.png"), "Album did not open")
click_text("Up")
click_text("a.png")
wait_until(lambda: has_text("Zoom in"), "Viewer did not open")
# The centered yellow fixture marker grows when zoomed; the surrounding
# red region can shrink because zoom correctly clips the photo's edges.
before = marker_area(capture("fit"))
click_text("Zoom in")
after = marker_area(capture("zoom"))
assert after > before * 1.1, "Zoom did not change rendered photo scale"
center = marker_center(capture("before-pan"))
click_text("Pan right")
moved = marker_center(capture("pan-right"))
assert moved[0] < center[0] - 10, "Horizontal pan did not move the image"
click_text("Pan down")
lowered = marker_center(capture("pan-down"))
assert lowered[1] < moved[1] - 10, "Vertical pan did not move the image"
click_text("Fit")
fitted = marker_area(capture("fit-restored"))
assert abs(fitted - before) < before * .12, "Fit did not restore rendered scale"
click_text("Next")
wait_until(lambda: has_text("Cannot decode image") and has_text("Retry image"), "Corrupt image lacks a recoverable decoder error")
click_text("Retry image")
wait_until(lambda: has_text("Cannot decode image"), "Corrupt-image retry lost its error state")
capture("unavailable-image")
removed = (photos / "z.JPG").read_bytes()
(photos / "z.JPG").unlink()
click_text("Next")
wait_until(lambda: has_text("Cannot read image") and has_text("Retry image"), "Unreadable image lacks a recoverable read error")
(photos / "z.JPG").write_bytes(removed)
click_text("Retry image")
wait_until(lambda: colors(capture("next"))[1] > 5000, "Next photo did not render")
click_text("Previous")
click_text("Previous")
wait_until(lambda: colors(capture("previous"))[0] > 5000, "Previous photo did not render")
app.terminate()
app.wait(timeout=10)
launch()
wait_until(lambda: has_text("a.png"), "Selected location did not survive restart")
command("xdotool", "windowsize", "--sync", window, "360", "640")
wait_until(lambda: has_text("Choose folder"), "Narrow Gallery controls did not render")
click_text("a.png")
wait_until(lambda: colors(capture("narrow-viewer"))[0] > 3000 and has_text("Fit") and has_text("Next"), "Narrow viewer or controls did not render")
narrow_before = marker_area(capture("narrow-fit"))
click_text("Zoom in")
assert marker_area(capture("narrow-zoom")) > narrow_before * 1.1, "Narrow zoom did not scale image"
click_text("Fit")
assert abs(marker_area(capture("narrow-restored")) - narrow_before) < narrow_before * .12, "Narrow Fit did not restore scale"
assert_photo_fits(capture("narrow-fitted-bounds"))
command("xdotool", "windowsize", "--sync", window, "520", "700")
wait_until(lambda: colors(capture("resized-viewer"))[0] > 3000 and has_text("Fit"), "Resized viewer lost image or controls")
assert_photo_fits(capture("resized-fitted-bounds"))
click_text("Albums")
saved = Path(env["WERK_DATA"]) / "gallery/location.txt"
assert saved.read_text() == str(photos)
assert saved.stat().st_mode & 0o777 == 0o600
assert saved.parent.stat().st_mode & 0o777 == 0o700
command("xdotool", "windowsize", "--sync", window, "960", "720")
choose_location(images)
wait_until(lambda: has_text("00-large.png"), "Large-image fixture did not populate")
click_text("00-large.png")
wait_until(lambda: colors(capture("large-photo"))[0] > 5000, "Ordinary photo over16MiB did not render")
# Next/Previous buttons were exercised above. Also cover the viewer's
# keyboard navigation while advancing through large-image error cases.
command("xdotool", "key", "--window", window, "Right")
wait_until(lambda: has_text("Image exceeds") and has_text("Retry image"), "Byte limit lacks an explicit image error")
command("xdotool", "key", "--window", window, "Right")
wait_until(lambda: has_text("Image exceeds") and has_text("Retry image"), "Pixel limit lacks an explicit image error")
print("Gallery private-Xvfb GUI passed: actual chooser/cancel, thumbnails/albums, decoder/read errors and retry, large image and limits, next/previous, rendered fit/zoom/pan, persisted root, narrow viewer", flush=True)
finally:
if app:
# The host and its native chooser have their own test-only process
# group. Also clean up a chooser left open by a failing assertion.
with contextlib.suppress(ProcessLookupError):
os.killpg(app.pid, signal.SIGTERM)
try:
app.wait(timeout=10)
except subprocess.TimeoutExpired:
with contextlib.suppress(ProcessLookupError):
os.killpg(app.pid, signal.SIGKILL)
app.wait(timeout=10)
+24 -7
View File
@@ -1,6 +1,7 @@
#!/bin/sh
# Renders Werkzeug's home screen in light and dark on private Xvfb displays,
# with disposable profiles, never the user's saved data.
# Renders Werkzeug's home screen in light and dark, and its --mini tool tiles,
# on private Xvfb displays with disposable profiles, never the user's saved
# data.
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
@@ -22,22 +23,38 @@ for mode in light dark; do
KRYON_CAPTURE_PATH="$work/werk-$mode.png" "$root/build/werk"
test -s "$work/werk-$mode.png"
done
python3 scripts/private-display.py \
env -u WERK_ASSETS HOME="$work/home" WERK_DATA="$work/light/data" XDG_CACHE_HOME="$work/light/cache" \
KRYON_CAPTURE_PATH="$work/werk-mini.png" "$root/build/werk" --mini
test -s "$work/werk-mini.png"
python3 - "$work" <<'PY'
from pathlib import Path
from PIL import Image
import sys
work = Path(sys.argv[1])
# Isolate the dark labels from the muted tile fills before text recognition.
with Image.open(work / "werk-light.png") as source:
labels = source.convert("L").point(lambda value: 0 if value < 130 else 255)
labels.resize((source.width * 3, source.height * 3)).save(work / "labels.png")
for name in ("light", "mini"):
with Image.open(work / f"werk-{name}.png") as source:
labels = source.convert("L").point(lambda value: 0 if value < 130 else 255)
labels.resize((source.width * 3, source.height * 3)).save(work / f"labels-{name}.png")
PY
rendered=$(tesseract "$work/labels.png" stdout --psm 11 2>/dev/null)
rendered=$(tesseract "$work/labels-light.png" stdout --psm 11 2>/dev/null)
for app in Pass Auth Calculator Clock; do
printf '%s\n' "$rendered" | grep -q "$app" || { echo "Missing preinstalled app: $app" >&2; exit 1; }
done
# Mini mode is the tool tiles alone, without Profile, search or title.
rendered=$(tesseract "$work/labels-mini.png" stdout --psm 11 2>/dev/null)
for app in Pass Auth Calculator Clock; do
printf '%s\n' "$rendered" | grep -q "$app" || { echo "Missing mini tile: $app" >&2; exit 1; }
done
for hidden in Profile Find Werkzeug; do
if printf '%s\n' "$rendered" | grep -qi "$hidden"; then
echo "Werkzeug --mini shows $hidden" >&2
exit 1
fi
done
if cmp -s "$work/werk-light.png" "$work/werk-dark.png"; then
echo 'Werkzeug light and dark themes rendered the same frame' >&2
exit 1
fi
echo 'Werkzeug desktop: light and dark home screens rendered on private Xvfb displays'
echo 'Werkzeug desktop: light and dark home screens and --mini tool tiles rendered on private Xvfb displays'
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
manager=${ANDROID_SDK_MANAGER:-"${ANDROID_HOME:?ANDROID_HOME is required}/cmdline-tools/latest/bin/sdkmanager"}
delay=${ANDROID_SDK_RETRY_DELAY:-10}
accept_licenses() {
# yes can receive SIGPIPE after sdkmanager exits successfully.
yes | "$manager" --licenses >/dev/null || test "${PIPESTATUS[1]}" -eq 0
}
retry() {
local attempt
for attempt in 1 2 3; do
if "$@"; then
return 0
fi
if [ "$attempt" -lt 3 ]; then
echo "Android SDK installer failed; retrying ($attempt/3)" >&2
sleep "$delay"
fi
done
echo "::error::Android SDK installation failed after three attempts" >&2
return 1
}
retry accept_licenses
retry "$manager" 'platforms;android-36' 'build-tools;34.0.0' \
'ndk;28.2.13676358' 'cmake;3.22.1' "$@"
+62
View File
@@ -0,0 +1,62 @@
"""Exercise installer retry and failure propagation without network or an SDK."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class AndroidSdkInstallerTest(unittest.TestCase):
def install(self, failures):
temporary = tempfile.TemporaryDirectory(prefix="werk-sdk-installer-")
self.addCleanup(temporary.cleanup)
directory = Path(temporary.name)
manager = directory / "sdkmanager"
manager.write_text("""#!/usr/bin/env python3
import json, os, sys
from pathlib import Path
root = Path(__file__).parent
if sys.argv[1:] == ['--licenses']:
raise SystemExit(0)
log = root / 'calls.json'
calls = json.loads(log.read_text()) if log.exists() else []
calls.append(sys.argv[1:])
log.write_text(json.dumps(calls))
raise SystemExit(1 if len(calls) <= int(os.environ['SDK_TEST_FAILURES']) else 0)
""")
manager.chmod(0o700)
environment = os.environ | {"ANDROID_SDK_MANAGER": str(manager),
"ANDROID_SDK_RETRY_DELAY": "0",
"SDK_TEST_FAILURES": str(failures)}
result = subprocess.run(["bash", str(ROOT / "scripts/install_android_sdk.sh"),
"platforms;android-30"], env=environment,
capture_output=True, text=True, timeout=10)
calls = json.loads((directory / "calls.json").read_text())
return result, calls
def test_success_does_not_repeat_installation(self):
result, calls = self.install(0)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0], ["platforms;android-36", "build-tools;34.0.0",
"ndk;28.2.13676358", "cmake;3.22.1", "platforms;android-30"])
def test_transient_download_failure_recovers(self):
result, calls = self.install(2)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(calls), 3)
self.assertEqual(calls[0], calls[1])
self.assertEqual(calls[1], calls[2])
def test_permanent_failure_stops_the_job(self):
result, calls = self.install(3)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(len(calls), 3)
self.assertIn("failed after three attempts", result.stderr)
if __name__ == "__main__":
unittest.main()
+9 -4
View File
@@ -16,8 +16,13 @@ stage = work / "install with spaces"
share = stage / "share"
desktop = stage / "Desktop"
library = stage / "lib/werk"
subprocess.run(["make", "install-gui", f"BIN_DIR={stage / 'bin'}", f"DATA_DIR={share}",
f"LIB_DIR={library}", f"DESKTOP_DIR={desktop}"], cwd=root, check=True)
prebuilt = ["-o", "gui"] if os.environ.get("WERK_TEST_PREBUILT") == "1" else []
build_environment = dict(os.environ, XDG_CACHE_HOME=os.environ["WERK_TEST_BUILD_CACHE"])
for key in ("MAKEFLAGS", "MFLAGS", "MAKEOVERRIDES"):
build_environment.pop(key, None)
subprocess.run(["make", *prebuilt, "install-gui", f"ZIRAN={os.environ['WERK_TEST_ZIRAN']}",
f"BIN_DIR={stage / 'bin'}", f"DATA_DIR={share}", f"LIB_DIR={library}",
f"DESKTOP_DIR={desktop}"], cwd=root, env=build_environment, check=True)
environment = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
WERK_ASSETS=str(library), ENTITY_DATA=str(work / "entity"),
XDG_DATA_HOME=str(share), XDG_CONFIG_HOME=str(work / "config"),
@@ -34,7 +39,7 @@ def command(*args):
for tool, name in (("", "Werkzeug"), ("pass", "Pass"), ("auth", "Auth"),
("calculator", "Calculator"), ("clock", "Clock"), ("workbook", "Workbook")):
("calculator", "Calculator"), ("clock", "Clock"), ("workbook", "Workbook"), ("gallery", "Gallery")):
identity = "xyz.waozi.werk" + ("." + tool if tool else "")
entry = share / "applications" / (identity + ".desktop")
assert entry.read_bytes() == (desktop / entry.name).read_bytes()
@@ -88,4 +93,4 @@ subprocess.run(["python3", str(root / "scripts/install-launchers.py"), "--data-d
"--desktop-dir", str(desktop), "--uninstall"], check=True)
assert not list((share / "applications").glob("xyz.waozi.werk*.desktop"))
assert not list(desktop.glob("xyz.waozi.werk*.desktop"))
print("All six installed launchers, distinct icons and shortcut removal verified locally")
print("All seven installed launchers, distinct icons and shortcut removal verified locally")
+3 -1
View File
@@ -15,7 +15,9 @@ mkdir -p "$appdir/usr/bin" "$appdir/usr/lib/werk/apps" "$appdir/usr/share/applic
"$appdir/usr/share/mime/packages" "$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
cp "$artifacts/werk" "$appdir/usr/bin/werk"
cp "$artifacts"/apps/*.zx "$appdir/usr/lib/werk/apps/"
cp "$artifacts/pfp.png" "$appdir/usr/lib/werk/pfp.png"
cp "$artifacts/pfp.webp" "$appdir/usr/lib/werk/pfp.webp"
mkdir -p "$appdir/usr/lib/werk/tools"
cp "$artifacts"/tools/*.webp "$appdir/usr/lib/werk/tools/"
python3 "$root/scripts/install-launchers.py" --data-dir "$appdir/usr/share"
cp "$root/packaging/linux/werk-bundle.xml" "$appdir/usr/share/mime/packages/werk-bundle.xml"
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$appdir/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
+3 -1
View File
@@ -14,7 +14,9 @@ mkdir -p "$stage/DEBIAN" "$stage/usr/bin" "$stage/usr/lib/werk/apps" "$stage/usr
"$stage/usr/share/mime/packages" "$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/werk" "$out"
cp "$artifacts/werk" "$stage/usr/bin/werk"
cp "$artifacts"/apps/*.zx "$stage/usr/lib/werk/apps/"
cp "$artifacts/pfp.png" "$stage/usr/lib/werk/pfp.png"
cp "$artifacts/pfp.webp" "$stage/usr/lib/werk/pfp.webp"
mkdir -p "$stage/usr/lib/werk/tools"
cp "$artifacts"/tools/*.webp "$stage/usr/lib/werk/tools/"
python3 "$root/scripts/install-launchers.py" --data-dir "$stage/usr/share"
cp "$root/packaging/linux/werk-bundle.xml" "$stage/usr/share/mime/packages/werk-bundle.xml"
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$stage/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
+4 -10
View File
@@ -6,18 +6,12 @@ ziran=${1:?pass the ziran command}
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
ziran_root=$("$ziran" pkg path ziran)
kryon=$("$ziran" pkg path kryon)
args="--root tests --module-path apps/pass --module-path shared --module-path kryon=$kryon/src/backend --module-path kryon=$kryon/src/ui --module-path $kryon/src/ui --module-path $ziran_root/std"
set -- --project --root . --module-path tests
mkdir -p build/pass-state-test
"$ziran" build $args --target=c -o build/pass-state-test/c tests/pass_state_test.zi
"$ziran" build "$@" --target=c -o build/pass-state-test/c tests/pass_state_test.zi
${CC:-cc} -std=c99 -O2 -ffunction-sections -fdata-sections -Wl,--gc-sections -I"$ziran_root/include" -Ibuild/pass-state-test/c build/pass-state-test/c/*.c -o build/pass-state-test/native
env -u DISPLAY -u WAYLAND_DISPLAY build/pass-state-test/native
binds=""
for name in ReadStoreHost WriteStoreHost ClipboardCopyHost SecureAvailableHost SecureSavedHost \
SecureRequestHost SecureForgetHost SecurePollHost; do
binds="$binds --bind app_context:$name=pass_state_host:$name"
done
"$ziran" bundle $args --entry pass_state_test:PassStateAnswer $binds \
-o build/pass-state-test/portable.zx tests/pass_state_test.zi tests/pass_state_host.zi
"$ziran" bundle "$@" --entry pass_state_test:PassStateAnswer --bind-host pass_state_host \
-o build/pass-state-test/portable.zx tests/pass_state_test.zi
test "$("$ziran" run build/pass-state-test/portable.zx)" = 42
echo 'Pass state: native and portable tests pass'
+17 -2
View File
@@ -6,11 +6,27 @@ import select
import shutil
import subprocess
import sys
import tempfile
evidence = Path(__file__).resolve().parents[1] / "build/desktop-task"
evidence.mkdir(parents=True, exist_ok=True)
private_root = Path(tempfile.mkdtemp(prefix="session-", dir=evidence))
environment = dict(os.environ)
# A fixture's nested build uses the selected toolchain's existing package
# cache; only the applications and desktop services use the private cache.
environment["WERK_TEST_BUILD_CACHE"] = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
# D-Bus activated pickers and portals inherit this environment, before each
# fixture sets up its own application data. Keep their settings private too.
for key, folder in (("HOME", "home"), ("XDG_RUNTIME_DIR", "runtime"),
("XDG_CONFIG_HOME", "config"), ("XDG_DATA_HOME", "share"),
("XDG_CACHE_HOME", "cache")):
path = private_root / folder
path.mkdir(mode=0o700)
environment[key] = str(path)
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"):
environment.pop(key, None)
environment["YUE_DESKTOP_RECOVERY"] = "0"
environment["HARMONY_DESKTOP_RECOVERY"] = "0"
environment["WERK_TEST_PRIVATE_DISPLAY"] = "1"
environment["SDL_RENDER_DRIVER"] = "software"
read_fd, write_fd = os.pipe()
@@ -27,8 +43,6 @@ try:
assert process.stat().st_uid == os.getuid(), "Private server has another owner"
command = process.joinpath("cmdline").read_bytes().replace(b"\0", b" ").decode()
assert f"-displayfd {write_fd} " in command, "Unexpected display allocation source"
evidence = Path(__file__).resolve().parents[1] / "build/desktop-task"
evidence.mkdir(parents=True, exist_ok=True)
with (evidence / "private-displays.log").open("a") as receipt:
receipt.write(f"pid={server.pid} executable={executable} display=:{display} command={command}\n")
environment["DISPLAY"] = ":" + display
@@ -40,3 +54,4 @@ finally:
if server.poll() is None:
server.terminate()
server.wait(timeout=10)
shutil.rmtree(private_root)
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Run Android tests in this repository's disposable, headless emulator."""
import os
from pathlib import Path
import socket
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
WORK = ROOT / "build/android-emulator"
WORK.mkdir(parents=True, exist_ok=True)
SDK = Path(os.environ.get("ANDROID_SDK_ROOT", Path.home() / "Android/Sdk"))
environment = dict(os.environ)
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"):
environment.pop(key, None)
environment.update(HARMONY_DESKTOP_RECOVERY="0", YUE_DESKTOP_RECOVERY="0",
ANDROID_AVD_HOME=str(WORK / "avd"), ANDROID_USER_HOME=str(WORK / "user"),
ANDROID_SDK_ROOT=str(SDK), WERK_ANDROID_EMULATOR="emulator-5580")
for key in ("ANDROID_AVD_HOME", "ANDROID_USER_HOME"):
Path(environment[key]).mkdir(parents=True, exist_ok=True)
avd = WORK / "avd/werk.avd"
if not avd.exists():
manager = SDK / "cmdline-tools/latest/bin/avdmanager"
subprocess.run([str(manager), "create", "avd", "--name", "werk", "--package",
"system-images;android-31;google_apis;x86_64", "--device", "pixel_2",
"--path", str(avd)], input=b"no\n", env=environment, check=True)
for port in (5580, 5581):
with socket.socket() as probe:
# A previous owned emulator can leave a TIME_WAIT socket briefly.
# This still refuses a port held by a live listening process.
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
probe.bind(("127.0.0.1", port))
adb = str(SDK / "platform-tools/adb")
environment["PATH"] = str(SDK / "platform-tools") + os.pathsep + environment["PATH"]
def guest(*args, timeout=20):
return subprocess.run([adb, "-s", environment["WERK_ANDROID_EMULATOR"], *args],
env=environment, capture_output=True, timeout=timeout)
with (WORK / "emulator.log").open("wb") as log:
process = subprocess.Popen([str(SDK / "emulator/emulator"), "-avd", "werk", "-port", "5580",
"-no-window", "-no-audio", "-no-boot-anim", "-no-snapshot",
"-gpu", "swiftshader_indirect", "-memory", "2048", "-cores", "2",
"-camera-back", "none", "-camera-front", "none", "-accel", "on"],
env=environment, stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 300
while time.monotonic() < deadline:
assert process.poll() is None, "Private emulator exited; see build/android-emulator/emulator.log"
if guest("shell", "getprop", "sys.boot_completed").stdout.strip() == b"1":
break
time.sleep(2)
else:
raise AssertionError("Private emulator did not boot within 300 seconds")
guest("shell", "wm", "size", "720x1280")
guest("shell", "wm", "density", "240")
# These local UI fixtures need no mobile network. Avoid the AVD's
# delayed SIM setup activity stealing foreground during a test.
radio = guest("shell", "cmd", "connectivity", "airplane-mode", "enable")
assert radio.returncode == 0, "Could not isolate the private emulator's mobile radio: " + radio.stderr.decode()
guest("shell", "input", "keyevent", "82")
print("Owned headless emulator ready: emulator-5580", flush=True)
assert sys.argv[1:], "Supply the Android test command"
result = subprocess.run(sys.argv[1:], cwd=ROOT, env=environment)
raise SystemExit(result.returncode)
finally:
try:
crash = guest("logcat", "-b", "crash", "-d", "-t", "120", timeout=5)
(WORK / "crash-logcat.txt").write_bytes(crash.stdout)
except (OSError, subprocess.TimeoutExpired):
pass
# Only the emulator process created above is ours to stop.
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=20)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
"""Registers the werkzeug app on a Daochi node with a signed manifest, so the
"""Registers the werkzeug app on a Mesh node with a signed manifest, so the
node accepts Werkzeug's sealed Auth records. The publisher key signs the
manifest and is created on first use; the node's registry key approves it.
Usage: register_daochi_app.py NODE_URL PUBLISHER_PEM REGISTRY_PEM
Usage: register_mesh_app.py NODE_URL PUBLISHER_PEM REGISTRY_PEM
[--dry-run] [--new-registry] [--registry-public]
"""
import json, os, sys, urllib.request, urllib.error
@@ -32,7 +32,7 @@ def raw_public(key):
publisher = load_or_create(publisher_path, True)
registry = load_or_create(registry_path, '--new-registry' in sys.argv)
collection = 'private.werkzeug.v1.auth'
# Daochi signs json.Marshal of its normalized AppManifest: struct field order,
# Mesh signs json.Marshal of its normalized AppManifest: struct field order,
# omitempty fields left out, each collection carrying the app id.
manifest = {
'manifest_version': 1,
+3
View File
@@ -14,7 +14,10 @@ icons = {
"auth": ("regular/system/shield.svg", "#146B58"),
"calculator": ("regular/education/counter.svg", "#245F9B"),
"clock": ("regular/system/time.svg", "#9A4F19"),
"calendar": ("regular/business/calendar.svg", "#B5434E"),
"gallery": ("regular/files/photo_album.svg", "#8251A0"),
"workbook": ("extra/table_row_add.svg", "#356B30"),
"taskmgr": ("regular/development/performance.svg", "#2B6B7A"),
}
for app, (relative, color) in icons.items():
source = ET.parse(mingcute / "svg" / relative).getroot()
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Keep generated runtime objects tied to one toolchain checkout."""
from pathlib import Path
import shutil
import subprocess
import sys
def prepare(source, output):
root = Path(__file__).resolve().parents[1]
source = Path(source).resolve()
output = Path(output).resolve()
if (not output.is_relative_to(root) or output.name not in {"ziran", "web-runtime", "bundle-runtime"}
or not any(output.is_relative_to(root / parent) for parent in ("build", "droid/app/.cxx", "droid/app/build"))):
raise ValueError("Runtime cache must be an owned build intermediate")
revision = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
identity = str(source) + "\n" + revision + "\n"
marker = output / ".toolchain"
if marker.is_file() and marker.read_text() == identity:
return
if output.exists():
shutil.rmtree(output)
output.mkdir(parents=True)
marker.write_text(identity)
if __name__ == "__main__":
prepare(*sys.argv[1:])
+33
View File
@@ -0,0 +1,33 @@
"""A changed compiler checkout must never reuse the old parser's objects."""
from pathlib import Path
import shutil
from runtime_cache import prepare
root = Path(__file__).resolve().parents[1]
fixture = root / "build/runtime-cache-test"
shutil.rmtree(fixture, ignore_errors=True)
fixture.mkdir(parents=True)
outside = fixture / "keep-output"
outside.write_text("owner output")
cache = fixture / "ziran"
try:
prepare(root, cache)
marker = cache / ".toolchain"
original_time = marker.stat().st_mtime_ns
object_file = cache / "parser.o"
object_file.write_text("compiled parser")
prepare(root, cache)
assert object_file.exists() and marker.stat().st_mtime_ns == original_time
marker.write_text("another toolchain checkout\n")
prepare(root, cache)
assert not object_file.exists(), "An incompatible parser object survived"
assert outside.read_text() == "owner output"
try:
prepare(root, root / "build")
except ValueError:
pass
else:
raise AssertionError("The whole build directory must never be cleared")
print("Runtime cache: reuse, toolchain invalidation and output preservation passed")
finally:
shutil.rmtree(fixture)
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more