Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48bfea6ee5 | ||
|
|
6b3ce6ce58 | ||
|
|
63006ba891 | ||
|
|
f38dcef65f | ||
|
|
4d765e6348 | ||
|
|
0f77bd6207 | ||
|
|
0e718b1fff | ||
|
|
8096256580 | ||
|
|
aa6cc16955 | ||
|
|
d047174079 | ||
|
|
1b283cb00b | ||
|
|
04a02ce1b1 | ||
|
|
6ab96ea56c | ||
|
|
8e445a64d8 | ||
|
|
3343ad6261 | ||
|
|
c961ebb430 | ||
|
|
685c419dd4 | ||
|
|
73caeb9a35 | ||
|
|
cf2a2efc58 | ||
|
|
8c3070cb17 | ||
|
|
f830878a78 | ||
|
|
52dcef68e7 | ||
|
|
250bbd2a35 | ||
|
|
6a32976e9f | ||
|
|
a2a7b97f7c | ||
|
|
98d732c367 | ||
|
|
0199559631 | ||
|
|
2a38d480a4 | ||
|
|
53cb190de7 | ||
|
|
b2ddcb69a8 | ||
|
|
a69631e327 | ||
|
|
dd550dd58b | ||
|
|
36fd01fe5d | ||
|
|
0cb5600c14 | ||
|
|
ead336b215 | ||
|
|
6cea9233ef | ||
|
|
fbd7c4038a | ||
|
|
7bfa8fef2b | ||
|
|
bee76ab379 | ||
|
|
d8284a83e0 | ||
|
|
f2dad4b37f | ||
|
|
40f2cdf731 | ||
|
|
b193cbfa9f | ||
|
|
4e139b3ffb | ||
|
|
a5e69bb227 | ||
|
|
b0003dc032 | ||
|
|
e26d26f5db | ||
|
|
a45fd1d3ed | ||
|
|
2e5d765962 | ||
|
|
4d499720d8 | ||
|
|
ae502a322d | ||
|
|
1a4e0e0891 | ||
|
|
3b8c4eaf64 | ||
|
|
60a68d258a | ||
|
|
0a2ab3bb45 | ||
|
|
b9a6c6d350 | ||
|
|
b53050764b | ||
|
|
b8722b6b28 | ||
|
|
26047247f9 | ||
|
|
c801c62542 | ||
|
|
7601d7c58c | ||
|
|
47d77ab0ad | ||
|
|
09ac0a29f1 | ||
|
|
0fd42f7574 | ||
|
|
f5ea95a4ad | ||
|
|
a46090bb61 | ||
|
|
f596eadcd9 | ||
|
|
dd313c6497 | ||
|
|
bd283650e7 | ||
|
|
cdc1a27eaa | ||
|
|
7cbcba75d7 | ||
|
|
1532a077cc | ||
|
|
bf4c5aa90a | ||
|
|
af2cbb8700 | ||
|
|
3df6755173 | ||
|
|
d777510144 | ||
|
|
b66e4adac0 | ||
|
|
d768923212 | ||
|
|
0702855958 | ||
|
|
1b7056e520 | ||
|
|
3559cc6232 | ||
|
|
ac00936501 |
No files matched your search
@@ -9,3 +9,8 @@ libpango1.0-dev
|
||||
xvfb
|
||||
xauth
|
||||
libgtk-3-dev
|
||||
python3-pil
|
||||
tesseract-ocr
|
||||
imagemagick
|
||||
gnumeric
|
||||
zenity
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: Install CLI test dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y openssl xclip xvfb xauth
|
||||
sudo apt-get install -y openssl xclip xvfb xauth tesseract-ocr imagemagick
|
||||
- name: Install Emscripten
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -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,24 +188,33 @@ jobs:
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v3
|
||||
- name: Install Android SDK components
|
||||
timeout-minutes: 15
|
||||
run: bash scripts/install_android_sdk.sh 'platforms;android-${{ matrix.api }}'
|
||||
- name: Install screenshot OCR
|
||||
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"
|
||||
sudo apt-get update
|
||||
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
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
- 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
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Google Play testing bundle
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
bundle:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
- name: Install build tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
|
||||
bash scripts/install_android_sdk.sh
|
||||
- name: Prepare preserved release key
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
test -n "$KEYSTORE_BASE64"
|
||||
umask 077
|
||||
mkdir -p "$HOME/.android"
|
||||
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
|
||||
- name: Build signed testing candidate
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||
run: |
|
||||
test -n "$KEYSTORE_PASSWORD"
|
||||
test -n "$KEY_ALIAS"
|
||||
make android-bundle
|
||||
- name: Validate the candidate
|
||||
run: |
|
||||
curl --fail --show-error --location --retry 3 \
|
||||
https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
|
||||
--output "$RUNNER_TEMP/bundletool.jar"
|
||||
python3 scripts/android-bundle-check.py "build/werk-$(cat VERSION).aab" \
|
||||
--bundletool "$RUNNER_TEMP/bundletool.jar" --version "$(cat VERSION)"
|
||||
- name: Remove temporary release key
|
||||
if: always()
|
||||
run: rm -f "$HOME/.android/pass-release.keystore"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: werkzeug-play-testing
|
||||
path: build/*.aab
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -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' \
|
||||
|
||||
@@ -46,8 +46,12 @@ 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
|
||||
sudo apt-get install -y tesseract-ocr imagemagick
|
||||
- name: Verify browser input, storage, cache upgrades, and offline launch
|
||||
env:
|
||||
WERK_WEB_BROWSER: google-chrome
|
||||
|
||||
@@ -5,3 +5,6 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.wrangler/
|
||||
/backup/
|
||||
/work/
|
||||
/apps/*/build/
|
||||
@@ -5,12 +5,13 @@ first.
|
||||
|
||||
## Tools are separate apps
|
||||
|
||||
- Each tool lives in `apps/<tool>/` and builds into its own bundle,
|
||||
`build/apps/<tool>.zib`. 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.
|
||||
@@ -23,9 +24,10 @@ first.
|
||||
- Never commit, print or log a real master password, Auth secret, otpauth
|
||||
link, export file or current code. Tests use fixture values only, such as
|
||||
the RFC 6238 keys.
|
||||
- Keep Pass's on-disk formats and the Android package `xyz.waozi.pass`:
|
||||
existing installations update in place and keep their saved master
|
||||
password. `src/migrate.zi` moves Pass's old files once; keep it.
|
||||
- Keep Pass's on-disk formats and `src/migrate.zi`. The owner's latest choice
|
||||
on 2026-10-23 is an update of the existing Android/F-Droid app: keep
|
||||
`xyz.waozi.pass` and its signing certificate, with the display name Werkzeug.
|
||||
Preserve existing Pass data and any separate `xyz.waozi.werk` installation.
|
||||
- Every file Werkzeug writes is private (0600 in 0700 folders).
|
||||
|
||||
## Platforms and tests
|
||||
|
||||
@@ -1,5 +1,63 @@
|
||||
# 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.
|
||||
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
|
||||
|
||||
## [0.4.3] - 2026-10-23
|
||||
|
||||
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
|
||||
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
|
||||
|
||||
## [0.4.2] - 2026-10-23
|
||||
|
||||
- Linux packages include the libraries needed for sync and importing QR-code pictures.
|
||||
- Packaging a new AppImage preserves previous downloads.
|
||||
|
||||
## [0.4.1] - 2026-10-23
|
||||
|
||||
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
|
||||
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
|
||||
- Tool windows show their own names and icons in the desktop switcher.
|
||||
|
||||
## [0.4.0] - 2026-10-19
|
||||
|
||||
- A new purple W logo across the app, Android and the website.
|
||||
|
||||
@@ -1,36 +1,51 @@
|
||||
.DEFAULT_GOAL := all
|
||||
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 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))
|
||||
SELF_DIR = $(shell $(ZIRAN) pkg path self $(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
|
||||
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
|
||||
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)
|
||||
SELF_SOURCES = $(wildcard $(SELF_DIR)/src/*.zi $(SELF_DIR)/assets/self/*)
|
||||
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 cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test self-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
|
||||
|
||||
@@ -44,28 +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.
|
||||
APPS := pass auth calculator clock
|
||||
APP_BUNDLES := $(APPS:%=build/apps/%.zib) build/apps/self.zib
|
||||
SHARED_SOURCES := $(wildcard shared/*.zi)
|
||||
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
|
||||
# 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)
|
||||
apps: $(APP_BUNDLES)
|
||||
.SECONDEXPANSION:
|
||||
build/apps/%.zib: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
|
||||
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)
|
||||
$(ZIRAN) bundle --root . --module-path apps/$* $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
|
||||
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/*) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
|
||||
mkdir -p $(@D)
|
||||
$(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/self.zib: $(SELF_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
|
||||
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 --root $(SELF_DIR) --module-path $(SELF_DIR)/src $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI \
|
||||
--module-path qrcode=$(QRCODE_DIR)/src --asset-dir assets=$(SELF_DIR)/assets --entry self:Main -o $@ $(SELF_DIR)/src/self.zi
|
||||
$(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 $(PROJECT) --root $(WORKBOOK_DIR)/src \
|
||||
--define KRYON_HOSTED_UI --entry $(call PACKAGE_ID,workbook)_app:Main -o $@ $(WORKBOOK_DIR)/src/app.zi
|
||||
|
||||
build/apps/taskmgr.zx: $(wildcard $(TASKMGR_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
|
||||
mkdir -p $(@D)
|
||||
$(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)
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
|
||||
.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) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(SELF_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
|
||||
@@ -76,10 +125,16 @@ build/liboqs/lib/liboqs.a: ziran.lock
|
||||
build/werk: build/generated/desktop/.complete build/ziran/libziran.a build/liboqs/lib/liboqs.a Makefile
|
||||
$(CC) $(CFLAGS) -Ibuild/generated/desktop -I$(MONOCYPHER_DIR)/src -I$(MONOCYPHER_DIR)/src/optional \
|
||||
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 $@
|
||||
build/pfp.png: $(KRYON_DIR)/icons/pfp.png
|
||||
$(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.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
|
||||
|
||||
@@ -96,36 +151,57 @@ cli-test: cli
|
||||
sh scripts/cli_test.sh ./pass
|
||||
lesspass-compat-test: cli
|
||||
python3 scripts/lesspass_compat_test.py --cli ./pass
|
||||
self-account-test:
|
||||
ZIRAN_BIN=$(ZIRAN) python3 scripts/self_account_test.py
|
||||
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test self-account-test
|
||||
entity-account-test: build/liboqs/lib/liboqs.a
|
||||
ZIRAN_BIN=$(ZIRAN) python3 scripts/entity_account_test.py
|
||||
.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
|
||||
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 $(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 $(APP_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 \
|
||||
--embed-file build/apps@/apps --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)
|
||||
@@ -142,36 +218,44 @@ web-smoke: site
|
||||
bash scripts/web_smoke.sh
|
||||
|
||||
# CMake emits JNI and foreign ABI types separately for each Android ABI.
|
||||
android-debug: 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)
|
||||
android-debug: portable-apps
|
||||
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: 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)
|
||||
android-emulator: portable-apps
|
||||
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: 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)
|
||||
android-release: portable-apps
|
||||
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)" 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
|
||||
@@ -182,18 +266,36 @@ install-cli: cli
|
||||
mkdir -p $(BIN_DIR)
|
||||
install -m 0755 pass $(BIN_DIR)/pass
|
||||
install-gui: gui
|
||||
mkdir -p $(BIN_DIR) $(LIB_DIR)/apps $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
|
||||
install -m 0755 build/werk $(BIN_DIR)/werk
|
||||
install -m 0644 $(APP_BUNDLES) $(LIB_DIR)/apps/
|
||||
install -m 0644 build/pfp.png $(LIB_DIR)/pfp.png
|
||||
cp packaging/linux/xyz.waozi.werk.desktop $(DATA_DIR)/applications/xyz.waozi.werk.desktop
|
||||
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
|
||||
mkdir -p "$(BIN_DIR)" "$(DATA_DIR)/applications" "$(DATA_DIR)/icons/hicolor/512x512/apps" "$(DATA_DIR)/mime/packages"
|
||||
install -d -m 0700 "$(LIB_DIR)" "$(LIB_DIR)/apps"
|
||||
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.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
|
||||
@if command -v update-desktop-database >/dev/null; then update-desktop-database "$(DATA_DIR)/applications"; fi
|
||||
uninstall-cli:
|
||||
rm -f $(BIN_DIR)/pass
|
||||
uninstall-gui:
|
||||
rm -f $(BIN_DIR)/werk $(DATA_DIR)/applications/xyz.waozi.werk.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
|
||||
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)") --uninstall
|
||||
rm -f $(BIN_DIR)/werk
|
||||
rm -rf $(LIB_DIR)
|
||||
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
|
||||
@@ -1,236 +1,48 @@
|
||||
<p align="center">
|
||||
<a href="https://f-droid.org/packages/xyz.waozi.pass/">
|
||||
<img src="assets/app/badge-f-droid.png" alt="Get it on F-Droid" height="56">
|
||||
</a>
|
||||
<img src="fastlane/metadata/android/en-US/images/featureGraphic.png" alt="Werkzeug" width="100%">
|
||||
</p>
|
||||
|
||||
# Werkzeug
|
||||
|
||||
Small private tools in one app. The home screen opens each one:
|
||||
Small, private tools for everyday life. Generate passwords, manage sign-in
|
||||
codes, calculate and keep time in one free, open-source app.
|
||||
|
||||
- **Pass**: a stateless password generator. The same site, login, master
|
||||
password and settings always give the same password, so there is no
|
||||
password database to keep. It is an independent implementation of the
|
||||
LessPass algorithm; compatibility does not imply endorsement by or
|
||||
affiliation with the LessPass project.
|
||||
- **Auth**: two-factor sign-in codes (TOTP, RFC 6238, with SHA-1, SHA-256 or
|
||||
SHA-512 and 6 to 8 digits). Add accounts by pasting `otpauth://` links, one
|
||||
or many such as Ente Auth's plain-text export, a Google Authenticator
|
||||
export link or an unencrypted Aegis export, or by entering the secret key.
|
||||
On the desktop, Import file reads an export or a picture of its QR code
|
||||
(it uses zenity, and GdkPixbuf and ZBar for pictures).
|
||||
Tap a code to copy it; it is cleared from the clipboard after 30 seconds.
|
||||
Edit renames an account, notes the websites where it signs in, such as
|
||||
`github.com`, or removes it.
|
||||
- **Calculator**: arithmetic with brackets, powers and percent, by keypad or
|
||||
keyboard, and a Scientific mode with trigonometry, logarithms, roots and
|
||||
factorials.
|
||||
- **Clock**: the local time and date, and a stopwatch that keeps running
|
||||
while the app is closed.
|
||||
[Try it online](https://werk.waozi.xyz/)
|
||||
· [Download the latest release](https://github.com/waozixyz/werk/releases/latest)
|
||||
· [What's new](CHANGELOG.md)
|
||||
|
||||
The profile holds your name, a picture and the appearance every tool shares:
|
||||
system, light or dark, an accent color and Material or Classic widgets.
|
||||
## Your everyday tools
|
||||
|
||||
Werkzeug is a harness for practical tools. Each built-in tool uses the shared
|
||||
Kryon app interface, so another compatible harness can run its bundle too.
|
||||
On the desktop, `werk --bundle /path/to/diary.zib` opens Inner Breeze's Diary
|
||||
through that interface, with its own private documents and optional photo
|
||||
picker. It needs no `inbe.zib`. These local Diary documents do not yet join
|
||||
Werkzeug's account sync. External bundles cannot replace a built-in tool or
|
||||
receive Pass's device secret or Auth's records.
|
||||
- **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. 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:** 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.
|
||||
|
||||
## Privacy
|
||||
<p align="center">
|
||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-pass.png" alt="Pass password generation" width="30%">
|
||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/03-auth.png" alt="Auth sign-in codes" width="30%">
|
||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04-calculator.png" alt="Scientific calculator" width="30%">
|
||||
</p>
|
||||
|
||||
Everything is computed on the device. Werkzeug makes no network requests
|
||||
unless you set up sync or explicitly request an account or device-link action.
|
||||
Each tool keeps its own files, readable only by your user:
|
||||
## Make it yours
|
||||
|
||||
| Platform | Data |
|
||||
|---|---|
|
||||
| Linux | `$XDG_DATA_HOME/werk` (or `~/.local/share/werk`) |
|
||||
| Android | the app's private storage |
|
||||
| Browser | IndexedDB on this site |
|
||||
Choose light or dark appearance, an accent color and your profile picture.
|
||||
On Linux, open each tool directly from its own application-menu or Desktop
|
||||
shortcut, with its own icon.
|
||||
|
||||
Auth's accounts are synced records: `otpauth` links in the private
|
||||
`records/auth.txt`, protected by the file permissions of your account or the
|
||||
Android app sandbox.
|
||||
## Your data and choices
|
||||
|
||||
## Sync
|
||||
Password generation and local tools work on your device. Account sync and
|
||||
node connections are optional. Each tool keeps its own private files.
|
||||
|
||||
Profile uses the shared Self bundle. Desktop Account management shows the
|
||||
public ID, alias, sync status and queued changes, and provides account creation,
|
||||
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.
|
||||
Werkzeug was formerly Pass. Android keeps the original `xyz.waozi.pass`
|
||||
package and signing certificate so existing Pass installations can update
|
||||
to Werkzeug while keeping their saved data.
|
||||
|
||||
The account can use a [Daochi](https://github.com/kryonlabs/daochi) 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
|
||||
and stays paused after restarting. Logout keeps local Auth records.
|
||||
[F-Droid update submission (draft)](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/53909)
|
||||
· [Report a problem](https://github.com/waozixyz/werk/issues)
|
||||
· [Build, command-line tools and data details](docs/development.md)
|
||||
|
||||
Desktop key backups retain Werkzeug's Auth vault key as protected recovery
|
||||
context. Use a passphrase to encrypt the backup. Importing a legacy account key
|
||||
for the already-connected identity preserves its existing vault key. The shared
|
||||
QR workflow also preserves that context and asks both devices to compare digits
|
||||
before connecting. Legacy clients cannot read the extended QR payload when
|
||||
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.
|
||||
|
||||
The embedded web app (`/app/?mini`) also provides Home and Profile, so all
|
||||
four tools are reachable. Use `?mini&app=auth`, `calculator` or `clock` to
|
||||
open a particular tool first. 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
|
||||
account, the record and the time of the change, so the server can neither
|
||||
read nor alter a record or a removal.
|
||||
- The account key (ML-DSA-44) signs in and signs each sync together with
|
||||
the device's own Ed25519 key.
|
||||
- Desktop device linking uses the shared Self QR/code exchange with X25519
|
||||
and encrypted key transfer. Confirm the matching number on both devices.
|
||||
Android's existing 12-character connection code remains available in its
|
||||
native account screen.
|
||||
- The server can still withhold changes or serve an older copy to a device
|
||||
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.
|
||||
|
||||
## The `werk sync` and `werk auth` commands
|
||||
|
||||
On Linux, the same data works without a window, for devices without a
|
||||
screen and for scripts:
|
||||
|
||||
```text
|
||||
werk sync status | create | show | join [CODE] | key [FILE] | now
|
||||
werk auth list
|
||||
werk auth code ID
|
||||
werk auth import [FILE]
|
||||
werk auth rename ID SERVICE ACCOUNT
|
||||
werk auth sites ID [WEBSITE ...]
|
||||
werk auth remove ID
|
||||
```
|
||||
|
||||
`werk sync show` prints a code for another device to enter; `werk sync join`
|
||||
reads one from its argument or standard input. `werk sync key` signs in with
|
||||
an account key from FILE or standard input; for a key with a passphrase, give
|
||||
FILE and the passphrase on standard input. `werk auth list` prints the
|
||||
accounts as JSON with their ids and websites, never their secrets.
|
||||
`werk auth code ID` prints the current code and the seconds it stays valid.
|
||||
`werk auth import` reads a file, or standard input: otpauth links, Google
|
||||
Authenticator export links, an unencrypted Aegis export, or a PNG or JPEG of
|
||||
an export's QR code when GdkPixbuf and ZBar (`libzbar0`) are installed.
|
||||
Changes sync right away when the device has an account. `werk --app auth`
|
||||
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>.zib`. 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.
|
||||
|
||||
## 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; 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.
|
||||
|
||||
```sh
|
||||
make gui # build/werk and the app bundles in build/apps
|
||||
make test # Pass/CLI, Auth, Calculator and private account recovery fixtures
|
||||
make gui-smoke # light and dark home screens on a private Xvfb display
|
||||
make gui-test # every tool, clipboard and profile on a private display,
|
||||
# and werk auth without one
|
||||
make site # build/site: browser app and offline worker
|
||||
make web-smoke # private headless Chromium
|
||||
make android-debug # ARM32, ARM64 and universal APKs
|
||||
make android-fdroid # unsigned F-Droid candidate, same Android ID and version
|
||||
make android-emulator # the x86_64 APK for a private emulator
|
||||
```
|
||||
|
||||
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
|
||||
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.
|
||||
Android requires the same signing certificate for an in-place update; the
|
||||
F-Droid recipe retains the developer-signature reproducibility requirement.
|
||||
|
||||
The [F-Droid TODO](packaging/fdroid/TODO.md) records completed checks, the
|
||||
remaining submission/reproducibility steps and the prepared merge-request text.
|
||||
|
||||
For development with the real project repositories, create an ignored
|
||||
`ziran.local.toml`:
|
||||
|
||||
```toml
|
||||
[overrides]
|
||||
kryon = "../../kryonlabs/kryon"
|
||||
ziran = "../../ziranlang/ziran"
|
||||
```
|
||||
|
||||
## The `pass` command
|
||||
|
||||
```text
|
||||
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
pass [OPTIONS] PROFILE SITE
|
||||
```
|
||||
|
||||
`make cli` builds it and `make install-cli` installs it. The default password
|
||||
has 16 characters and includes lowercase letters, uppercase letters, digits
|
||||
and symbols. Length must be between 5 and 35, matching LessPass clients. The
|
||||
default counter is 1.
|
||||
|
||||
Passing a master password as an argument can expose it to process inspection
|
||||
and shell history. Omitting it is safer: `pass` first checks
|
||||
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
|
||||
`--prompt` to bypass the environment and read from standard input:
|
||||
|
||||
```sh
|
||||
pass --prompt example.com alice
|
||||
pass --length 24 --counter 2 example.com alice
|
||||
pass --no-symbols --exclude '0O1Il' example.com alice
|
||||
```
|
||||
|
||||
The Linux CLI also reads saved identities from
|
||||
`$XDG_CONFIG_HOME/pass/profiles.json` (or `~/.config/pass/profiles.json`).
|
||||
`pass w example.com` and `pass --profile w example.com` use the saved login
|
||||
and generation options. Existing OpenSSL-encrypted vaults are unlocked with
|
||||
a hidden `Vault passphrase:` prompt. A configured vault takes precedence over
|
||||
`LESSPASS_MASTER_PASSWORD`; `--prompt` bypasses it. Explicit flags override
|
||||
profile defaults. Profiles and vaults are read without changing them.
|
||||
|
||||
`--copy` or a profile's `copy` setting copies through `xclip` on X11;
|
||||
`--clear-after 90s` releases that clipboard selection after the given time
|
||||
without erasing a later copy from another application. Use `--no-copy` to
|
||||
print the generated password instead. Run `pass --help` for all flags.
|
||||
|
||||
## Source layout
|
||||
|
||||
```text
|
||||
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
|
||||
apps/auth/ Auth: TOTP, otpauth links, exports, accounts and screens
|
||||
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
|
||||
src/desktop.zi, src/android_main.zi, src/browser.zi platform main loops
|
||||
src/command.zi werk sync and werk auth without a window
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
|
||||
[`LICENSE`](LICENSE).
|
||||
BSD 3-Clause. See [LICENSE](LICENSE).
|
||||
@@ -0,0 +1 @@
|
||||
7a9599b7e728333c237b2bf23cdf9fb985f4a3c82f9cc0ba4dd16434ac876c12
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -32,6 +30,8 @@ running: bool;
|
||||
started_at: float64;
|
||||
elapsed: float64;
|
||||
session: Session;
|
||||
local_offset: s32;
|
||||
local_offset_read_at: float64 = -61.0;
|
||||
|
||||
// The civil date of a day count since 1970-01-01 (proleptic Gregorian).
|
||||
CivilFromDays :: (days: s64) -> Civil {
|
||||
@@ -78,11 +78,15 @@ AppendNumber :: (output: []u8, used: s32, value: s64) -> s32 {
|
||||
|
||||
LocalSeconds :: () -> s64 {
|
||||
now := AppNow()
|
||||
if now - local_offset_read_at > 60.0 {
|
||||
local_offset = AppLocalOffset()
|
||||
local_offset_read_at = now
|
||||
}
|
||||
seconds := cast(s64)now
|
||||
if cast(float64)seconds > now {
|
||||
seconds -= 1
|
||||
}
|
||||
return seconds + cast(s64)AppLocalOffset()
|
||||
return seconds + cast(s64)local_offset
|
||||
}
|
||||
|
||||
TimeText :: (output: []u8) -> string {
|
||||
@@ -199,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 :: () {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 "/"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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[
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
After Width: | Height: | Size: 753 KiB |
|
After Width: | Height: | Size: 637 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 675 KiB |
|
After Width: | Height: | Size: 294 KiB |
|
After Width: | Height: | Size: 743 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 819 KiB |
@@ -0,0 +1,240 @@
|
||||
# Werkzeug development and data
|
||||
|
||||
[Back to Werkzeug](../README.md).
|
||||
|
||||
## Privacy
|
||||
|
||||
Everything is computed on the device. Werkzeug makes no network requests
|
||||
unless you set up sync or explicitly request an account or device-link action.
|
||||
Each tool keeps its own files, readable only by your user:
|
||||
|
||||
| Platform | Data |
|
||||
|---|---|
|
||||
| Linux | `$XDG_DATA_HOME/werk` (or `~/.local/share/werk`) |
|
||||
| Android | the app's private storage |
|
||||
| Browser | IndexedDB on this site |
|
||||
|
||||
Auth's accounts are synced records: `otpauth` links in the private
|
||||
`records/auth.txt`, protected by the file permissions of your account or the
|
||||
Android app sandbox.
|
||||
|
||||
## Sync
|
||||
|
||||
Profile uses the shared Self bundle. Desktop Account management shows the
|
||||
public ID, alias, sync status and queued changes, and provides account creation,
|
||||
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 [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
|
||||
and stays paused after restarting. Logout keeps local Auth records.
|
||||
|
||||
Desktop key backups retain Werkzeug's Auth vault key as protected recovery
|
||||
context. Use a passphrase to encrypt the backup. Importing a legacy account key
|
||||
for the already-connected identity preserves its existing vault key. The shared
|
||||
QR workflow also preserves that context and asks both devices to compare digits
|
||||
before connecting. Legacy clients cannot read the extended QR payload when
|
||||
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. 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`) 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
|
||||
account, the record and the time of the change, so the server can neither
|
||||
read nor alter a record or a removal.
|
||||
- The account key (ML-DSA-44) signs in and signs each sync together with
|
||||
the device's own Ed25519 key.
|
||||
- Desktop device linking uses the shared Self QR/code exchange with X25519
|
||||
and encrypted key transfer. Confirm the matching number on both devices.
|
||||
Android's existing 12-character connection code remains available in its
|
||||
native account screen.
|
||||
- The server can still withhold changes or serve an older copy to a device
|
||||
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 Mesh node.
|
||||
|
||||
## The `werk sync` and `werk auth` commands
|
||||
|
||||
On Linux, the same data works without a window, for devices without a
|
||||
screen and for scripts:
|
||||
|
||||
```text
|
||||
werk sync status | create | show | join [CODE] | key [FILE] | now
|
||||
werk auth list
|
||||
werk auth code ID
|
||||
werk auth import [FILE]
|
||||
werk auth rename ID SERVICE ACCOUNT
|
||||
werk auth sites ID [WEBSITE ...]
|
||||
werk auth remove ID
|
||||
```
|
||||
|
||||
`werk sync show` prints a code for another device to enter; `werk sync join`
|
||||
reads one from its argument or standard input. `werk sync key` signs in with
|
||||
an account key from FILE or standard input; for a key with a passphrase, give
|
||||
FILE and the passphrase on standard input. `werk auth list` prints the
|
||||
accounts as JSON with their ids and websites, never their secrets.
|
||||
`werk auth code ID` prints the current code and the seconds it stays valid.
|
||||
`werk auth import` reads a file, or standard input: otpauth links, Google
|
||||
Authenticator export links, an unencrypted Aegis export, or a PNG or JPEG of
|
||||
an export's QR code when GdkPixbuf and ZBar (`libzbar0`) are installed.
|
||||
Changes sync right away when the device has an account. `werk --app auth`
|
||||
opens the window on one tool, as Harmony's Auth entry does.
|
||||
|
||||
## Tools are separate apps
|
||||
|
||||
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 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.
|
||||
|
||||
```sh
|
||||
make gui # build/werk and the app bundles in build/apps
|
||||
make install-gui # Werkzeug and each tool in the app menu and on the desktop
|
||||
make test # Pass/CLI, Auth, Calculator and private account recovery fixtures
|
||||
make gui-smoke # light and dark home screens on a private Xvfb display
|
||||
make gui-test # every tool, clipboard and profile on a private display,
|
||||
# and werk auth without one
|
||||
make site # build/site: browser app and offline worker
|
||||
make web-smoke # private headless Chromium
|
||||
make android-debug # ARM32, ARM64 and universal APKs
|
||||
make android-fdroid # unsigned F-Droid candidate, same Android ID and version
|
||||
make android-emulator # the x86_64 APK for a private emulator
|
||||
```
|
||||
|
||||
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
|
||||
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/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.
|
||||
Android requires the same signing certificate for an in-place update; the
|
||||
F-Droid recipe retains the developer-signature reproducibility requirement.
|
||||
|
||||
The [F-Droid TODO](../packaging/fdroid/TODO.md) records completed checks, the
|
||||
remaining submission/reproducibility steps and the prepared merge-request text.
|
||||
|
||||
For development with the real project repositories, create an ignored
|
||||
`ziran.local.toml`:
|
||||
|
||||
```toml
|
||||
[overrides]
|
||||
kryon = "../../kryonlabs/kryon"
|
||||
ziran = "../../ziranlang/ziran"
|
||||
```
|
||||
|
||||
## The `pass` command
|
||||
|
||||
```text
|
||||
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
pass [OPTIONS] PROFILE SITE
|
||||
```
|
||||
|
||||
`make cli` builds it and `make install-cli` installs it. The default password
|
||||
has 16 characters and includes lowercase letters, uppercase letters, digits
|
||||
and symbols. Length must be between 5 and 35, matching LessPass clients. The
|
||||
default counter is 1.
|
||||
|
||||
Passing a master password as an argument can expose it to process inspection
|
||||
and shell history. Omitting it is safer: `pass` first checks
|
||||
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
|
||||
`--prompt` to bypass the environment and read from standard input:
|
||||
|
||||
```sh
|
||||
pass --prompt example.com alice
|
||||
pass --length 24 --counter 2 example.com alice
|
||||
pass --no-symbols --exclude '0O1Il' example.com alice
|
||||
```
|
||||
|
||||
The Linux CLI also reads saved identities from
|
||||
`$XDG_CONFIG_HOME/pass/profiles.json` (or `~/.config/pass/profiles.json`).
|
||||
`pass w example.com` and `pass --profile w example.com` use the saved login
|
||||
and generation options. Existing OpenSSL-encrypted vaults are unlocked with
|
||||
a hidden `Vault passphrase:` prompt. A configured vault takes precedence over
|
||||
`LESSPASS_MASTER_PASSWORD`; `--prompt` bypasses it. Explicit flags override
|
||||
profile defaults. Profiles and vaults are read without changing them.
|
||||
|
||||
`--copy` or a profile's `copy` setting copies through `xclip` on X11;
|
||||
`--clear-after 90s` releases that clipboard selection after the given time
|
||||
without erasing a later copy from another application. Use `--no-copy` to
|
||||
print the generated password instead. Run `pass --help` for all flags.
|
||||
|
||||
## Source layout
|
||||
|
||||
```text
|
||||
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
|
||||
auth (package) Auth: TOTP, otpauth links, exports, accounts and screens (waozixyz/auth)
|
||||
apps/calculator/ Calculator
|
||||
apps/clock/ Clock and stopwatch
|
||||
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
|
||||
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
|
||||
[`LICENSE`](../LICENSE).
|
||||
@@ -14,9 +14,9 @@ android {
|
||||
}
|
||||
|
||||
def getKeystorePath = { -> project.findProperty('keystore.path') ?: keystoreProps['keystore.path'] ?: System.getenv("HOME") + "/.android/pass-release.keystore" }
|
||||
def getKeystoreAlias = { -> project.findProperty('keystore.alias') ?: keystoreProps['keystore.alias'] ?: "pass-key" }
|
||||
def getKeystoreAlias = { -> project.findProperty('keystore.alias') ?: keystoreProps['keystore.alias'] ?: System.getenv('KEY_ALIAS') ?: "pass-key" }
|
||||
|
||||
def releasePassword = project.findProperty('keystore.password') ?: ""
|
||||
def releasePassword = project.findProperty('keystore.password') ?: System.getenv('KEYSTORE_PASSWORD') ?: ""
|
||||
|
||||
def releaseKeystorePath = getKeystorePath()
|
||||
def releaseKeystore = releaseKeystorePath ? file(releaseKeystorePath) : null
|
||||
@@ -43,8 +43,8 @@ android {
|
||||
applicationId 'xyz.waozi.pass'
|
||||
minSdk 21
|
||||
targetSdk 36
|
||||
versionCode 14
|
||||
versionName "0.4.0"
|
||||
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'
|
||||
@@ -80,6 +80,7 @@ android {
|
||||
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
|
||||
packaging {
|
||||
@@ -102,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 '../..'
|
||||
commandLine 'make', 'apps'
|
||||
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', Copy) {
|
||||
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 '*.zib'; 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 }
|
||||
@@ -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">
|
||||
|
||||
@@ -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,13 +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,3 @@
|
||||
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
|
||||
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
|
||||
- Tool windows show their own names and icons in the desktop switcher.
|
||||
@@ -0,0 +1,2 @@
|
||||
- Linux packages include the libraries needed for sync and importing QR-code pictures.
|
||||
- Packaging a new AppImage preserves previous downloads.
|
||||
@@ -0,0 +1,2 @@
|
||||
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
|
||||
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
|
||||
@@ -0,0 +1,2 @@
|
||||
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
|
||||
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
|
||||
@@ -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.
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 99 KiB |
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
/config/
|
||||
/repo/
|
||||
/tmp/
|
||||
/logs/
|
||||
@@ -1,26 +1,5 @@
|
||||
# Draft: xyz.waozi.pass: rename to Werkzeug and update to 0.3.1
|
||||
# Update Pass to Werkzeug
|
||||
|
||||
Pass became Werkzeug in 0.3.0. The current F-Droid recipe still selects Pass
|
||||
0.2.9 and its old website and APK name. Update the existing package to the
|
||||
public Werkzeug 0.3.1 release, current links and versioned APK name. Preserve
|
||||
`xyz.waozi.pass` and the allowed signing certificate so existing installations
|
||||
can update in place.
|
||||
Update the existing `xyz.waozi.pass` app to Werkzeug. The package ID and signing certificate are preserved for in-place updates.
|
||||
|
||||
The new build uses the exact Ziran toolchain and seven dependency revisions
|
||||
from the release lock, fetched as F-Droid source libraries before the build.
|
||||
Package mappings and native/image paths use those managed sources. The old
|
||||
0.2.9 build retains its original reference APK filename.
|
||||
|
||||
Metadata lint and formatting checks pass, and all source pins match the
|
||||
public release lock. The prebuild commands were executed against the release
|
||||
CMake/Gradle inputs and the generated mappings and paths checked. The public
|
||||
0.3.1 universal APK was verified: package `xyz.waozi.pass`, versionCode 13,
|
||||
label Werkzeug, both ARM ABIs and the existing allowed signing certificate.
|
||||
|
||||
A full F-Droid source rebuild and reproducibility comparison remain pending.
|
||||
Keep this request in draft until those checks pass. Local 0.4.0 development
|
||||
changes are not part of this recipe's release reference.
|
||||
|
||||
- [Original merged submission](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/46404)
|
||||
- [Existing successful reproducible build](https://monitor.f-droid.org/builds/log/xyz.waozi.pass/10)
|
||||
- [Public renamed release](https://github.com/waozixyz/werk/releases/tag/v0.3.1)
|
||||
Listing text and screenshots are maintained upstream in Fastlane.
|
||||
@@ -1,58 +1,17 @@
|
||||
# Werkzeug F-Droid TODO
|
||||
# Werkzeug F-Droid update status
|
||||
|
||||
Updated 2026-10-15. The recipe update is prepared locally. Draft submission
|
||||
is approved, but GitLab authentication is still blocked and no new merge
|
||||
request has been created. Nothing from this work has been released.
|
||||
The owner's latest request is an update of the existing Pass app. Keep `xyz.waozi.pass`, the existing author signing certificate and private app data. The visible name remains Werkzeug. Preserve any separate `xyz.waozi.werk` installation as well.
|
||||
|
||||
## Prepared and verified
|
||||
- [x] Prepare the original Android application ID and matching artifact verifiers.
|
||||
- [x] Prepare 0.4.4 with version code 18 through `update_version.sh`.
|
||||
- [x] Build the compatible ARM and private-emulator candidates with matching ZX dependencies and current app bundles.
|
||||
- [x] Verify both ARM native libraries match byte for byte after independent builds in different directories.
|
||||
- [ ] Publish the compatible candidate through the normal release workflow and pin its exact source revision in the recipe.
|
||||
- [ ] Complete source-build and reproducibility verification against its reference APK.
|
||||
- [ ] Resolve missing explicit dependency licenses and remaining GitLab pipeline results.
|
||||
- [ ] Obtain owner approval before marking the update ready for review.
|
||||
- [ ] Verify catalog publication after maintainers merge and F-Droid publishes it.
|
||||
|
||||
- [x] Confirm the [original Pass submission](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/46404)
|
||||
was merged and its [0.2.9 reproducible build](https://monitor.f-droid.org/builds/log/xyz.waozi.pass/10) succeeded.
|
||||
- [x] Prepare the rename and recipe for the public Werkzeug 0.3.1 release
|
||||
(Android versionCode 13), including pinned toolchain/source dependencies.
|
||||
- [x] Validate metadata formatting, lint, source pins, prebuild commands and
|
||||
the public reference APK's identity, label, ABIs and signing certificate.
|
||||
- [x] Implement and test the selected logo, all-tools mini navigation,
|
||||
optional Daochi/custom-node settings, persistent sync pause and unsigned
|
||||
F-Droid build mode in the local 0.4.0 app (versionCode 14).
|
||||
[Update draft](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/53909) · [Recipe](metadata/xyz.waozi.pass.yml) · [Merge-request text](MERGE_REQUEST.md)
|
||||
|
||||
The local app checks cover source/core/CLI compatibility, desktop and browser
|
||||
UI, encrypted two-device sync, Android builds, and private-emulator input,
|
||||
node settings and update/data preservation. They do **not** establish that
|
||||
F-Droid can reproducibly build the 0.3.1 recipe.
|
||||
|
||||
## Resume the F-Droid submission
|
||||
|
||||
1. [ ] Restore GitLab sign-in. The existing ThinkPad spare-browser viewer
|
||||
is paused for manual sign-in; resume automation after the owner confirms.
|
||||
2. [ ] Refresh upstream metadata and search open merge requests for an
|
||||
existing Werkzeug update before creating another one.
|
||||
3. [ ] Submit the metadata and source-library definitions as a **draft**
|
||||
using [the prepared merge-request text](MERGE_REQUEST.md). Record its URL here.
|
||||
4. [ ] Run the full F-Droid source build and reproducibility comparison
|
||||
against the signed public reference APK. Resolve any CI/build differences.
|
||||
5. [ ] Verify update compatibility: preserve `xyz.waozi.pass`, the existing
|
||||
allowed signing certificate, and the release's versionName/versionCode.
|
||||
Keep `-fdroid` in the output filename only.
|
||||
6. [ ] Once reproducibility and CI pass, request maintainer review. Track
|
||||
the merge and verify Werkzeug's actual catalog availability separately.
|
||||
|
||||
Merge request URL: pending submission.
|
||||
|
||||
## Later 0.4.0 release
|
||||
|
||||
- [ ] Coordinate the separate, uncommitted Clock/alarm work and verify the
|
||||
final release source. Preserve that work during the handoff.
|
||||
- [ ] Obtain owner approval before publishing the 0.4.0 app release.
|
||||
- [ ] After that signed release is public, update the recipe to its full
|
||||
upstream commit and versioned APK, then repeat the reproducibility checks.
|
||||
The current draft must continue to reference public 0.3.1 until then.
|
||||
|
||||
## Handoff files
|
||||
|
||||
- [Build metadata](metadata/xyz.waozi.pass.yml)
|
||||
- [Pinned source-library definitions](srclibs/)
|
||||
- [Draft merge-request text](MERGE_REQUEST.md)
|
||||
- Local unsigned candidate: `make android-fdroid`
|
||||
|
||||
The unsigned candidate is a build artifact, not an installable release.
|
||||
The local recipe is being prepared; its source pin still needs the verified compatible candidate. A Draft or a successful source build does not imply F-Droid catalog publication.
|
||||
@@ -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,51 +25,27 @@ Builds:
|
||||
- apt-get install -y gcc libc-dev
|
||||
gradle:
|
||||
- yes
|
||||
binary: https://github.com/waozixyz/werk/releases/download/v%v/pass-%v.apk
|
||||
scandelete:
|
||||
- vendor/kryon/vendor
|
||||
ndk: 28.2.13676358
|
||||
|
||||
- versionName: 0.3.1
|
||||
versionCode: 13
|
||||
commit: bde94573f4eda34fbc9ff46d7d1af2b60f0ce941
|
||||
- versionName: 0.4.4
|
||||
versionCode: 18
|
||||
commit: b53050764b8402a96e2e6b9b8c90d6567a3bea77
|
||||
subdir: droid/app
|
||||
sudo:
|
||||
- apt-get update
|
||||
- apt-get install -y build-essential libssl-dev
|
||||
- apt-get install -y build-essential cmake libssl-dev
|
||||
gradle:
|
||||
- yes
|
||||
output: build/outputs/apk/release/app-universal-release-unsigned.apk
|
||||
srclibs:
|
||||
- Ziran@201be1072cfb2ad59b4060f8579db36f6848b8cb
|
||||
- Kryon@159563f46c9f6cb4aa011f7372e175042b10fa68
|
||||
- Monocypher@e65d27722a43e9ed88da1987f3ad5675503c8cad
|
||||
- Oqs@5cc7677b290f0448462410f7c7e85f518664b943
|
||||
- Mingcute@933691600cf10e81b1f53d9919dbcb371c1968e1
|
||||
- raylib@fafa2cea97d0cb379d832086ba45a989fa6f9c8e
|
||||
- DaochiClient@d453a26642d7e35265d5d4fe2cc33a6a0725b0ca
|
||||
- liboqs@fd44469daeffe6b28f031f54f9bb66cbae69a572
|
||||
prebuild:
|
||||
- printf '[overrides]\nziran = "$$Ziran$$"\nkryon = "$$Kryon$$"\nmingcute =
|
||||
"$$Mingcute$$"\ndaochi_client = "$$DaochiClient$$"\noqs = "$$Oqs$$"\nliboqs
|
||||
= "$$liboqs$$"\nmonocypher = "$$Monocypher$$"\nraylib = "$$raylib$$"\n' >
|
||||
../../ziran.local.toml
|
||||
- sed -i -e 's|$ENV{KRYON_DIR}|$$Kryon$$|g' -e 's|$ENV{ZIRAN_ROOT}|$$Ziran$$|g'
|
||||
-e 's|$ENV{RAYLIB_DIR}|$$raylib$$/src|g' -e 's|$ENV{LIBOQS_DIR}|$$liboqs$$|g'
|
||||
-e 's|$ENV{MONOCYPHER_DIR}|$$Monocypher$$|g' src/main/cpp/CMakeLists.txt
|
||||
- sed -i 's@from(.*KRYON_DIR.*@from("$$Kryon$$/icons/pfp.png")@' build.gradle
|
||||
build:
|
||||
- make -C $$Ziran$$ all
|
||||
- make -C ../.. apps ZIRAN=$$Ziran$$/build/bin/ziran
|
||||
binary: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
|
||||
ndk: 28.2.13676358
|
||||
gradleprops:
|
||||
- fDroidBuild=true
|
||||
- abi=armeabi-v7a,arm64-v8a
|
||||
- splitApks=true
|
||||
|
||||
AllowedAPKSigningKeys: 1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee19589c2d
|
||||
|
||||
AutoUpdateMode: Version
|
||||
UpdateCheckMode: Tags
|
||||
CurrentVersion: 0.3.1
|
||||
CurrentVersionCode: 13
|
||||
CurrentVersion: 0.4.4
|
||||
CurrentVersionCode: 18
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/daochi-client.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/kryonlabs/kryon.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/kryonlabs/mingcute.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/LoupVaillant/Monocypher.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/oqs.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/ziran.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/open-quantum-safe/liboqs.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/raysan5/raylib.git
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
||||
<mime-type type="application/x-ziran-bundle">
|
||||
<comment>Ziran application bundle</comment>
|
||||
<glob pattern="*.zx"/>
|
||||
</mime-type>
|
||||
</mime-info>
|
||||
@@ -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.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=Auth
|
||||
Comment=Two-factor sign-in codes with Werkzeug
|
||||
Exec=werk --app auth
|
||||
TryExec=werk
|
||||
Icon=werk-auth
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
Keywords=Werkzeug;TOTP;2FA;Authenticator;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-auth
|
||||
@@ -0,0 +1,12 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Calculator
|
||||
Comment=Everyday and scientific calculations with Werkzeug
|
||||
Exec=werk --app calculator
|
||||
TryExec=werk
|
||||
Icon=werk-calculator
|
||||
Terminal=false
|
||||
Categories=Utility;Calculator;
|
||||
Keywords=Werkzeug;Math;Scientific;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-calculator
|
||||
@@ -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=Clock
|
||||
Comment=Local time and stopwatch with Werkzeug
|
||||
Exec=werk --app clock
|
||||
TryExec=werk
|
||||
Icon=werk-clock
|
||||
Terminal=false
|
||||
Categories=Utility;Clock;
|
||||
Keywords=Werkzeug;Time;Stopwatch;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-clock
|
||||
@@ -1,9 +1,12 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Werkzeug
|
||||
Comment=Passwords, two-factor codes, a calculator and a clock
|
||||
Exec=werk
|
||||
Comment=Private everyday tools
|
||||
Exec=werk --bundle %f
|
||||
TryExec=werk
|
||||
Icon=werk
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk
|
||||
MimeType=application/x-ziran-bundle;
|
||||
@@ -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=Pass
|
||||
Comment=Generate repeatable passwords with Werkzeug
|
||||
Exec=werk --app pass
|
||||
TryExec=werk
|
||||
Icon=werk-pass
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
Keywords=Werkzeug;Password;LessPass;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-pass
|
||||
@@ -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
|
||||
@@ -0,0 +1,12 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Workbook
|
||||
Comment=Edit spreadsheets with Werkzeug
|
||||
Exec=werk --app workbook
|
||||
TryExec=werk
|
||||
Icon=werk-workbook
|
||||
Terminal=false
|
||||
Categories=Office;Spreadsheet;
|
||||
Keywords=Werkzeug;Spreadsheet;Formula;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-workbook
|
||||
@@ -0,0 +1,35 @@
|
||||
# Google Play testing
|
||||
|
||||
The public app is **Werkzeug**, package `xyz.waozi.pass`. Preserve the existing
|
||||
release certificate. This package updates the existing Pass app
|
||||
(`xyz.waozi.pass`) in place and keeps its private data. A separate
|
||||
`xyz.waozi.werk` installation remains separate and untouched.
|
||||
|
||||
`make android-bundle` builds a release AAB for both ARM architectures, targeting
|
||||
Android 16/API 36. Supply the existing `keystore.*` Gradle properties to sign it;
|
||||
without them it is an unsigned build artifact. Never upload an unsigned bundle.
|
||||
The manual Play bundle workflow signs with the repository's existing Android
|
||||
release secrets and retains the candidate as an Actions artifact.
|
||||
|
||||
Use `listing.json` and the upstream Fastlane listing to create the app in Play
|
||||
Console. Start with **Internal testing**, which supports up to 100 testers. The
|
||||
owner must choose the tester email list or Google Group. Record the actual app
|
||||
and opt-in URLs after creation. No public production rollout is configured.
|
||||
|
||||
Review the exact bundle and testing release before making it available to
|
||||
testers. Internal testing can begin before the full production listing is
|
||||
complete, and internal-only releases are exempt from the Data safety section.
|
||||
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 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
|
||||
cross-store compatibility rather than silently generating a different app key.
|
||||
An upload key and an app-signing key have different roles.
|
||||
|
||||
References: [create an app](https://support.google.com/googleplay/android-developer/answer/9859152),
|
||||
[testing tracks](https://support.google.com/googleplay/android-developer/answer/9845334),
|
||||
[target API](https://support.google.com/googleplay/android-developer/answer/11926878).
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"packageName": "xyz.waozi.pass",
|
||||
"title": "Werkzeug",
|
||||
"defaultLanguage": "en-US",
|
||||
"applicationType": "app",
|
||||
"category": "TOOLS",
|
||||
"price": "free",
|
||||
"contactEmail": "[email protected]",
|
||||
"website": "https://werk.waozi.xyz",
|
||||
"privacyPolicy": "https://werk.waozi.xyz/privacy.html",
|
||||
"initialTrack": "internal",
|
||||
"storeMetadata": "fastlane/metadata/android",
|
||||
"status": "prepared; Play Console creation, declarations and upload pending"
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate a Werkzeug Play candidate without uploading it."""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
from android_apk_check import elf_section_names
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("bundle", type=Path)
|
||||
parser.add_argument("--bundletool", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--unsigned", action="store_true", help="Validate structure only; this candidate cannot be uploaded")
|
||||
args = parser.parse_args()
|
||||
bundle = args.bundle.resolve(strict=True)
|
||||
tool = args.bundletool.resolve(strict=True)
|
||||
subprocess.run(["java", "-jar", str(tool), "validate", "--bundle=" + str(bundle)],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
xml = subprocess.check_output(["java", "-jar", str(tool), "dump", "manifest", "--bundle=" + str(bundle)], text=True)
|
||||
manifest = ET.fromstring(xml)
|
||||
android = "{http://schemas.android.com/apk/res/android}"
|
||||
assert manifest.get("package") == "xyz.waozi.pass", "Werkzeug updates the existing Pass package"
|
||||
assert manifest.get(android + "versionName") == args.version
|
||||
assert int(manifest.find("uses-sdk").get(android + "targetSdkVersion")) >= 36
|
||||
assert manifest.find("application").get(android + "debuggable", "false") == "false"
|
||||
if not args.unsigned:
|
||||
signed = subprocess.check_output(["jarsigner", "-verify", str(bundle)], text=True,
|
||||
env=dict(os.environ, LC_ALL="C"))
|
||||
assert "jar verified." in signed, "The Play candidate must be signed"
|
||||
certificates = subprocess.check_output(["keytool", "-printcert", "-jarfile", str(bundle)], text=True,
|
||||
env=dict(os.environ, LC_ALL="C"))
|
||||
fingerprints = re.findall(r"SHA256:\s*([A-Fa-f0-9:]+)", certificates)
|
||||
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", "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:
|
||||
assert archive.read(name)[:4] == b"ZX\0\0", f"Obsolete bundle format: {name}"
|
||||
for font in ("ui.ttf", "emoji.ttf"):
|
||||
assert "base/assets/fonts/" + font in archive.namelist()
|
||||
abis = {x.split("/")[2] for x in archive.namelist() if x.startswith("base/lib/") and x.endswith(".so")}
|
||||
assert abis == {"arm64-v8a", "armeabi-v7a"}
|
||||
root = Path(__file__).resolve().parents[1] / "build/play-verify"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=root) as directory:
|
||||
for name in archive.namelist():
|
||||
if not name.startswith("base/lib/arm64-v8a/") or not name.endswith(".so"): continue
|
||||
library = Path(directory) / Path(name).name
|
||||
library.write_bytes(archive.read(name))
|
||||
assert ".note.gnu.build-id" not in set(elf_section_names(library.read_bytes())), "Native library contains a build-path-dependent build ID"
|
||||
headers = subprocess.check_output(["readelf", "-lW", str(library)], text=True)
|
||||
loads = [line.split() for line in headers.splitlines() if line.strip().startswith("LOAD ")]
|
||||
assert loads and all(int(parts[-1], 16) >= 16384 for parts in loads), "Native library needs 16 KB alignment"
|
||||
print("Werkzeug " + args.version + ": " + ("unsigned structure verified; signing pending" if args.unsigned else "signed Play bundle verified"))
|
||||
@@ -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
|
||||
@@ -21,20 +21,87 @@ def dex_classes(data):
|
||||
yield data[offset:data.index(0, offset)].decode("ascii")
|
||||
|
||||
|
||||
def elf_section_names(data):
|
||||
assert data[:4] == b"\x7fELF" and data[5] == 1, "Expected a little-endian ELF library"
|
||||
wide = data[4] == 2
|
||||
assert data[4] in (1, 2), "Unsupported ELF class"
|
||||
table = struct.unpack_from("<Q" if wide else "<I", data, 40 if wide else 32)[0]
|
||||
size, count, strings_index = struct.unpack_from("<HHH", data, 58 if wide else 46)
|
||||
strings_entry = table + strings_index * size
|
||||
offset, length = struct.unpack_from("<QQ" if wide else "<II", data, strings_entry + (24 if wide else 16))
|
||||
strings = data[offset:offset + length]
|
||||
for index in range(count):
|
||||
name = struct.unpack_from("<I", data, table + index * size)[0]
|
||||
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}"
|
||||
for app in ["pass", "auth", "calculator", "clock"]:
|
||||
assert f"assets/apps/{app}.zib" in names, f"{path}: missing the {app} app"
|
||||
assert "assets/pfp.png" in names, f"{path}: missing profile pictures"
|
||||
assert any(name.endswith("/libmain.so") for name in names), f"{path}: no NativeActivity payload"
|
||||
print(f"{path}: native Ziran app; only generated resource classes")
|
||||
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.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 with shared Kryon account consent")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -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()
|
||||
@@ -16,7 +16,7 @@ for path, expected_abis in [(fdroid, {"armeabi-v7a", "arm64-v8a"}),
|
||||
package = re.search(r"package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'", badging)
|
||||
assert package, f"{path}: no package identity"
|
||||
current = package.groups()
|
||||
assert current[0] == "xyz.waozi.pass", "Updating must preserve Pass's Android ID"
|
||||
assert current[0] == "xyz.waozi.pass", "Werkzeug updates the existing Pass package"
|
||||
assert current[2] == (root / "VERSION").read_text().strip(), "Channel added a version suffix"
|
||||
if identity is None:
|
||||
identity = current
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -1,18 +1,21 @@
|
||||
#!/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"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
serial = os.environ.get("WERK_ANDROID_EMULATOR")
|
||||
if not serial and not os.environ.get("CI"):
|
||||
raise SystemExit("Set WERK_ANDROID_EMULATOR to your own private test emulator")
|
||||
if not serial:
|
||||
devices = subprocess.check_output(["adb", "devices"], text=True).splitlines()
|
||||
serial = next((line.split()[0] for line in devices if line.startswith("emulator-") and line.split()[-1] == "device"), None)
|
||||
@@ -20,8 +23,8 @@ if not serial or not serial.startswith("emulator-"):
|
||||
raise SystemExit("Android input tests require a private emulator")
|
||||
package = "xyz.waozi.pass"
|
||||
|
||||
def adb(*arguments, check=True):
|
||||
return subprocess.run(["adb", "-s", serial, *arguments], check=check, capture_output=True)
|
||||
def adb(*arguments, check=True, input=None):
|
||||
return subprocess.run(["adb", "-s", serial, *arguments], check=check, capture_output=True, input=input, timeout=90)
|
||||
|
||||
def shell(*arguments, check=True):
|
||||
return adb("shell", *arguments, check=check).stdout.decode()
|
||||
@@ -29,30 +32,74 @@ def shell(*arguments, check=True):
|
||||
def shot(name):
|
||||
(output / f"{name}.png").write_bytes(adb("exec-out", "screencap", "-p").stdout)
|
||||
|
||||
def find_label(word):
|
||||
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)
|
||||
raise AssertionError(f"Could not find {word!r} in the private emulator")
|
||||
def find_label(word, timeout=15, minimum_y=0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
shot("label")
|
||||
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):
|
||||
try:
|
||||
return find_label(word, timeout=2)
|
||||
except AssertionError:
|
||||
if attempt == 6:
|
||||
raise
|
||||
upper = top + int(150 * zoom)
|
||||
lower = bottom - int(80 * zoom)
|
||||
start, end = (lower, upper) if direction == "down" else (upper, lower)
|
||||
shell("input", "swipe", str(width // 2), str(start), str(width // 2), str(end), "450")
|
||||
time.sleep(PAUSE)
|
||||
|
||||
def dismiss_other_apps_not_responding():
|
||||
"""A slow emulator can show another app's "isn't responding" dialog over
|
||||
Werkzeug, as CI's did for Settings. Close that app, never Werkzeug."""
|
||||
for _ in range(3):
|
||||
shot("label")
|
||||
data = subprocess.check_output(["tesseract", str(output / "label.png"), "stdout", "--psm", "11"],
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
if "responding" not in data or "Werkzeug" in data.split("responding")[0].splitlines()[-1]:
|
||||
"""A slow emulator can show an "isn't responding" dialog for another app,
|
||||
the system or Werkzeug over Werkzeug, as CI's did. Choose Wait, found
|
||||
through the accessibility tree. A real hang does not recover, so the
|
||||
next assertion still fails."""
|
||||
for _ in range(6):
|
||||
dumped = adb("shell", "uiautomator", "dump", "/sdcard/werk-ui.xml", check=False)
|
||||
tree = shell("cat", "/sdcard/werk-ui.xml", check=False) if dumped.returncode == 0 else ""
|
||||
# The tree escapes the apostrophe in "isn't responding".
|
||||
if " responding" not in tree:
|
||||
return
|
||||
tap(*find_label("Close")); time.sleep(1.5)
|
||||
raise AssertionError("A system dialog kept covering Werkzeug")
|
||||
if "Werkzeug isn" in tree:
|
||||
print("warning: the emulator reported Werkzeug slow to respond; waiting")
|
||||
wait = re.search(r'text="Wait"[^>]*bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', tree)
|
||||
if wait:
|
||||
left, top_edge, right, bottom_edge = map(int, wait.groups())
|
||||
tap((left + right) // 2, (top_edge + bottom_edge) // 2)
|
||||
time.sleep(3)
|
||||
raise AssertionError("An \"isn't responding\" dialog kept covering Werkzeug")
|
||||
|
||||
def alive():
|
||||
if not shell("pidof", package, check=False).strip():
|
||||
@@ -64,102 +111,142 @@ def alive():
|
||||
if line.strip().startswith(("mResumedActivity:", "ResumedActivity:"))), "")
|
||||
assert package in resumed, f"Werkzeug activity closed or lost foreground: {resumed}"
|
||||
|
||||
# CI's software-rendered emulator needs longer to apply each step.
|
||||
PAUSE = 1.0 if os.environ.get("CI") else 0.25
|
||||
|
||||
def tap(x, y):
|
||||
shell("input", "tap", str(x), str(y)); time.sleep(0.25)
|
||||
shell("input", "tap", str(x), str(y)); time.sleep(PAUSE)
|
||||
|
||||
def type_text(text):
|
||||
shell("input", "text", text.replace(" ", "%s")); time.sleep(0.3)
|
||||
shell("input", "text", text.replace(" ", "%s")); time.sleep(PAUSE + 0.05)
|
||||
|
||||
def hide_keyboard():
|
||||
if "mInputShown=true" in shell("dumpsys", "input_method"):
|
||||
shell("input", "keyevent", "4")
|
||||
for _ in range(20):
|
||||
time.sleep(0.15)
|
||||
if "mInputShown=true" not in shell("dumpsys", "input_method"):
|
||||
return
|
||||
raise AssertionError("Soft keyboard did not close")
|
||||
|
||||
|
||||
def fill_field(label, text):
|
||||
hide_keyboard()
|
||||
_, y = find_label(label)
|
||||
tap(int(90 * zoom), y + int(40 * zoom))
|
||||
type_text(text)
|
||||
|
||||
|
||||
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
|
||||
|
||||
apk = root / "build/werk-android-emulator.apk"
|
||||
apk = Path(os.environ.get("WERK_ANDROID_APK", root / "build/werk-android-emulator.apk"))
|
||||
check_apk(apk)
|
||||
try:
|
||||
adb("install", "-r", str(apk))
|
||||
# This is the test emulator and only this package's fixture data is cleared.
|
||||
shell("pm", "clear", package)
|
||||
shell("am", "start", "-n", package + "/android.app.NativeActivity")
|
||||
time.sleep(2); alive(); dismiss_other_apps_not_responding(); shot("launch")
|
||||
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")
|
||||
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.
|
||||
densities = re.findall(r"density: (\d+)", shell("wm", "density"))
|
||||
zoom = int(densities[-1]) / 160
|
||||
top, bottom = system_bars(height)
|
||||
# Pass's tile on the home screen, then Pass below Werkzeug's 56-unit bar.
|
||||
tap(int(127 * zoom), top + int(132 * zoom)); time.sleep(0.5); alive(); shot("pass")
|
||||
bar = 56
|
||||
tap(int(90 * zoom), top + int((55 + bar) * zoom)); type_text("example.com")
|
||||
# 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")
|
||||
fill_field("Site", "example.com")
|
||||
assert "mInputShown=true" in shell("dumpsys", "input_method"), "Soft keyboard did not open"
|
||||
tap(int(90 * zoom), top + int((130 + bar) * zoom)); type_text("alice")
|
||||
tap(int(90 * zoom), top + int((205 + bar) * zoom)); type_text("test master")
|
||||
fill_field("Login", "alice")
|
||||
fill_field("Master", "test master")
|
||||
shot("keyboard")
|
||||
shell("input", "keyevent", "4"); time.sleep(0.4); alive()
|
||||
tap(width // 2, bottom - int(35 * zoom))
|
||||
tap(int(90 * zoom), top + int((55 + bar) * zoom)); type_text("Android test")
|
||||
shell("input", "keyevent", "4"); time.sleep(0.3)
|
||||
tap(int(100 * zoom), top + int((105 + bar) * zoom))
|
||||
hide_keyboard(); alive()
|
||||
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))
|
||||
time.sleep(0.5)
|
||||
tap(int(100 * zoom), bottom - int(119 * zoom)) # Copy, at the bottom of the scrolled form
|
||||
tap_label("Generate")
|
||||
# A slow emulator may still be deriving the password.
|
||||
time.sleep(2); dismiss_other_apps_not_responding()
|
||||
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"))
|
||||
shell("input", "keyevent", *["67" for _ in "Android test"])
|
||||
time.sleep(0.5)
|
||||
dismiss_other_apps_not_responding()
|
||||
# Type the reference password as the new name. Pasting the copy works
|
||||
# through the keyboard's clipboard suggestion, which Gboard offers only
|
||||
# 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()
|
||||
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")
|
||||
# Profile's name is one of Werkzeug's own fields. Each letter must land
|
||||
# after the last, at the caret the keyboard reports.
|
||||
tap(int(28 * zoom), top + int(28 * zoom)); time.sleep(0.5)
|
||||
tap(width - int(60 * zoom), top + int(28 * zoom)); time.sleep(0.8); alive()
|
||||
# Self's profile card: the picture, then Name.
|
||||
tap(width // 2, top + int(357 * zoom)); type_text("Ada Lovelace")
|
||||
shot("profile-name")
|
||||
shell("input", "keyevent", "4"); time.sleep(0.3)
|
||||
# Leaving Profile saves it.
|
||||
tap(int(28 * zoom), top + int(28 * zoom)); time.sleep(0.5); alive()
|
||||
print("Android: second profile, restart and private permissions verified", flush=True)
|
||||
# The shared Profile retains existing names and edits appearance.
|
||||
tap_label("Profile"); time.sleep(0.8); alive()
|
||||
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
|
||||
assert "name=Ada Lovelace\n" in settings, f"Profile name typed out of order: {settings!r}"
|
||||
tap(width - int(60 * zoom), top + int(28 * zoom)); time.sleep(0.8)
|
||||
# Self's Nodes section: the empty "Node address" field, then Add.
|
||||
tap_label("Node")
|
||||
assert "name=Fixture Person\n" in settings, "Profile lost the retained name"
|
||||
tap(*scroll_to_label("Dark")); time.sleep(0.5)
|
||||
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
|
||||
assert "theme_mode=2\n" in settings and "name=Fixture Person\n" in settings
|
||||
shot("profile-appearance")
|
||||
print("Android: retained profile name and appearance verified", flush=True)
|
||||
tap(*scroll_to_label("Light"))
|
||||
# The shared Profile manages nodes on its own page.
|
||||
hide_keyboard()
|
||||
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/")
|
||||
shell("input", "keyevent", "4"); time.sleep(1.2)
|
||||
# OCR misses Add's white label on the accent. It ends the row above
|
||||
# Appearance, wherever the keyboard left the page scrolled.
|
||||
_, appearance = find_label("Appearance")
|
||||
tap(width - int(81 * zoom), appearance - int(56 * zoom)); time.sleep(0.8)
|
||||
hide_keyboard()
|
||||
# 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
|
||||
@@ -168,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()
|
||||
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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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't responding", True),
|
||||
("Werkzeug isn't responding", False),
|
||||
("Calculator isn'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()
|
||||
@@ -5,28 +5,30 @@ 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.zib apps/auth/totp_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/totp.zib)" = 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.zib apps/auth/exports_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/exports.zib)" = 0
|
||||
"$ziran" bundle --root . --module-path apps/calculator --module-path "$ziran_root/std" \
|
||||
--entry arithmetic_test:Run -o build/app-logic-test/arithmetic.zib apps/calculator/arithmetic_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/arithmetic.zib)" = 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
|
||||
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
|
||||
"$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 \
|
||||
-o build/app-logic-test/input.zib tests/calculator_input_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/input.zib)" = 42
|
||||
--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
|
||||
${CC:-cc} -std=c99 -O2 -ffunction-sections -fdata-sections -Wl,--gc-sections \
|
||||
-I"$ziran_root/include" -Ibuild/app-logic-test/input-c build/app-logic-test/input-c/*.c -lm \
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the shared Apps controller and native tool navigation."""
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
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 = Path(os.environ.get("WERK_APPS_TEST_OUTPUT", root / "build/apps-gui-test"))
|
||||
binary = Path(os.environ.get("WERK_TEST_BINARY", root / "build/werk"))
|
||||
assets = Path(os.environ.get("WERK_TEST_ASSETS", root / "build"))
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
work.mkdir(parents=True)
|
||||
expected = (root / "apps-controller.sha256").read_text().strip()
|
||||
assert hashlib.sha256((assets / "apps/apps.zx").read_bytes()).hexdigest() == expected
|
||||
environment = 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(environment[name]).mkdir(parents=True)
|
||||
profile = Path(environment["WERK_DATA"]) / "profile"
|
||||
profile.mkdir()
|
||||
(profile / "settings.txt").write_text("theme_mode=1\n")
|
||||
|
||||
|
||||
def command(*arguments):
|
||||
return subprocess.check_output(arguments, env=environment, text=True, timeout=20)
|
||||
|
||||
|
||||
def capture(name):
|
||||
time.sleep(.3)
|
||||
picture = work / (name + ".png")
|
||||
command("import", "-window", window, str(picture))
|
||||
# Separate dark text from the soft card fills for reliable recognition.
|
||||
with Image.open(picture) as source:
|
||||
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")
|
||||
# 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))
|
||||
# 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)
|
||||
|
||||
|
||||
def word_position(word):
|
||||
capture("control")
|
||||
for target in ("labels.png", "full-text.png"):
|
||||
text = command("tesseract", str(work / target), "stdout", "--psm", "11",
|
||||
"-c", "tessedit_create_tsv=1")
|
||||
for item in csv.DictReader(io.StringIO(text), delimiter="\t"):
|
||||
if item["text"].strip() == word:
|
||||
return ((int(item["left"]) + int(item["width"]) // 2) // 3,
|
||||
(int(item["top"]) + int(item["height"]) // 2) // 3)
|
||||
raise AssertionError("Missing visible app control: " + word)
|
||||
|
||||
|
||||
def click_word(word):
|
||||
click(*word_position(word))
|
||||
|
||||
|
||||
def key(value):
|
||||
command("xdotool", "key", "--clearmodifiers", value)
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
def type_text(value):
|
||||
command("xdotool", "type", "--clearmodifiers", "--delay", "30", value)
|
||||
time.sleep(.3)
|
||||
|
||||
|
||||
def expect_title(expected):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
assert app.poll() is None, "Werkzeug exited during navigation"
|
||||
title = command("xdotool", "getwindowname", window).strip()
|
||||
if title == expected:
|
||||
return
|
||||
time.sleep(.1)
|
||||
capture("navigation-failure")
|
||||
raise AssertionError(f"Expected window title {expected!r}, got {title!r}")
|
||||
|
||||
|
||||
app = subprocess.Popen([str(binary)], env=environment)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
window = None
|
||||
while time.monotonic() < deadline:
|
||||
assert app.poll() is None, "Werkzeug exited during startup"
|
||||
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
|
||||
env=environment, capture_output=True, text=True, timeout=5)
|
||||
if found.returncode == 0:
|
||||
window = found.stdout.splitlines()[0]
|
||||
break
|
||||
time.sleep(.1)
|
||||
assert window, "Werkzeug did not show its owned window"
|
||||
command("xdotool", "windowfocus", "--sync", window)
|
||||
# Window creation precedes loading the portable apps and the first frame.
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
home = capture("home")
|
||||
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
|
||||
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}")
|
||||
assert all(name in text for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")), text
|
||||
command("xdotool", "windowsize", "--sync", window, "420", "760")
|
||||
time.sleep(.3)
|
||||
click(330, 92) # Shared List view control, beside the search field.
|
||||
preferences = Path(environment["WERK_DATA"]) / "profile/apps.json"
|
||||
assert json.loads(preferences.read_text())["list"] is True
|
||||
text = capture("list")
|
||||
assert all(name in text for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")), text
|
||||
assert not re.search(r"\d[\d.]*\s*(?:kB|MB)\b", text, re.I), text
|
||||
click(100, 92)
|
||||
type_text("clock")
|
||||
text = capture("search")
|
||||
assert "Clock" in text and "Calculator" not in text and "Workbook" not in text, text
|
||||
click(278, 92) # Clear search is part of the shared field.
|
||||
assert "Calculator" in capture("search-cleared")
|
||||
click(382, 372) # Clock's options at the end of its list row.
|
||||
text = capture("options")
|
||||
assert all(label in text for label in ("Open", "Pin", "Properties")), text
|
||||
click_word("Pin")
|
||||
capture("pinned")
|
||||
saved = json.loads(preferences.read_text())
|
||||
assert next(item for item in saved["apps"] if item["id"] == "clock")["favorite"]
|
||||
click(382, 204) # Clock now appears first, in Pinned.
|
||||
assert "Unpin" in capture("pinned-options")
|
||||
click_word("Properties")
|
||||
name = word_position("Name")
|
||||
click(120, name[1] + 34)
|
||||
key("ctrl+a")
|
||||
type_text("Timepiece")
|
||||
# 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;
|
||||
# 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
|
||||
assert "Timepiece" in capture("renamed")
|
||||
assert preferences.stat().st_mode & 0o777 == 0o600
|
||||
app.terminate()
|
||||
app.wait(timeout=10)
|
||||
app = subprocess.Popen([str(binary)], env=environment)
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
|
||||
env=environment, capture_output=True, text=True, timeout=5)
|
||||
if found.returncode == 0:
|
||||
window = found.stdout.splitlines()[0]
|
||||
if "Timepiece" in capture("restarted"):
|
||||
break
|
||||
assert time.monotonic() < deadline, "Launcher preferences did not survive restart"
|
||||
time.sleep(.1)
|
||||
click(382, 204)
|
||||
click_word("Open")
|
||||
assert command("xdotool", "getwindowname", window).strip() == "Clock"
|
||||
click(28, 28)
|
||||
click(382, 204)
|
||||
click_word("Unpin")
|
||||
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, eight tools, Entity picture resources and resized layouts verified locally")
|
||||
finally:
|
||||
if app.poll() is None:
|
||||
app.terminate()
|
||||
app.wait(timeout=10)
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||