20 Commits
Author SHA1 Message Date
waozi 09ac0a29f1 Install ImageMagick for existing browser OCR tests 2026-10-23 17:53:18 -03:00
waozi 0fd42f7574 Include desktop package dependencies and preserve previous AppImages 2026-10-23 17:45:05 -03:00
waozi f5ea95a4ad Use the shared Apps launcher with working views and menus 2026-10-23 17:43:47 -03:00
waozi a46090bb61 Install direct desktop tools and prepare Play testing bundles 2026-10-23 17:22:18 -03:00
waozi f596eadcd9 Leave the desktop-only Workbook bundle out of the web and Android apps 2026-10-22 21:57:53 -03:00
waozi dd313c6497 Open the embedded mini version on Home and pin Workbook's fresh-checkout bundle fix 2026-10-22 21:45:53 -03:00
waozi bd283650e7 Read Clock's time zone once a minute and follow the shared Apps home in the web test 2026-10-22 21:45:08 -03:00
waozi cdc1a27eaa Use Entity as the shared profile module and repository 2026-10-22 17:02:13 -03:00
waozi 7cbcba75d7 Include spreadsheet runtime and file associations in Linux packages 2026-10-20 12:03:01 -03:00
waozi 1532a077cc Read popup labels independently from spreadsheet grid lines 2026-10-20 11:58:40 -03:00
waozi bf4c5aa90a Pin the visible spreadsheet selection and verify its contrast 2026-10-20 11:51:55 -03:00
waozi af2cbb8700 Show installed Workbook in the shared Apps home 2026-10-20 11:46:04 -03:00
waozi 3df6755173 Run and download Workbook bundles in the Linux toolkit 2026-10-20 11:45:41 -03:00
waozi d777510144 Give CI's Android emulator KVM so it runs accelerated
The runner user lacked /dev/kvm access, so the emulator ran with -accel off
and Android reported Werkzeug as not responding while it worked through
the input test. The same test passes on a local, accelerated API 30
emulator configured like CI's.
2026-10-19 20:51:49 -03:00
waozi b66e4adac0 Give CI's emulator a second per Android test step
On CI's software-rendered emulator the tab switch after copying the
password had not happened before the next taps arrived.
2026-10-19 19:43:07 -03:00
waozi d768923212 Let the Android input test wait out a slow emulator
CI's emulator reported Werkzeug as not responding after the test sent a
dozen deletes while a password was still being derived. Pause after
generating, send each delete on its own, and choose Wait on a slow-app
dialog; a real hang still fails the next check.
2026-10-19 19:17:54 -03:00
waozi 0702855958 Choose Wait on CI's "isn't responding" dialogs and drop ripgrep from the GUI smoke test
CI's emulator showed "Process system isn't responding", which no stop or
broadcast clears. Find Wait through uiautomator's tree and tap it. The GUI
smoke test now uses grep, which CI's runners have, and installs tesseract.
2026-10-19 18:56:08 -03:00
waozi 1b7056e520 Build liboqs for the Self account test and fix CI's GUI and Android checks
The Self account test links liboqs, which only an earlier GUI build had
made locally. CI's GUI smoke test needs Pillow. On CI's emulator another
app's "isn't responding" dialog has no reliably readable label, so close
it through the window list and the system-dialog broadcast instead of OCR.
2026-10-19 18:38:34 -03:00
waozi 3559cc6232 Point the F-Droid recipe at Werkzeug 0.4.0
The listing becomes Werkzeug at the tagged 0.4.0 commit, with the Self and
QR code source libraries the release lock now uses. 0.3.0 and 0.3.1 are
dropped: their locks pin dependency commits that upstream no longer has.
The public 0.4.0 APK's package, version, label, ABIs and signing key were
checked.
2026-10-19 18:20:44 -03:00
waozi ac00936501 Install tesseract where the browser and Android tests read the screen
The browser smoke test and the Android input test find labels with
tesseract OCR, which neither the CI runners nor the website build had.
2026-10-19 18:20:44 -03:00
59 changed files with 1882 additions and 323 deletions

No files matched your search

+5
View File
@@ -9,3 +9,8 @@ libpango1.0-dev
xvfb
xauth
libgtk-3-dev
python3-pil
tesseract-ocr
imagemagick
gnumeric
zenity
+12 -1
View File
@@ -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
@@ -175,6 +175,17 @@ jobs:
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"
- name: Install screenshot OCR
run: |
sudo apt-get update
sudo apt-get install -y tesseract-ocr
# 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:
+58
View File
@@ -0,0 +1,58 @@
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
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'
- 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
+4
View File
@@ -48,6 +48,10 @@ jobs:
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/index.wasm
- 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
+11
View File
@@ -1,5 +1,16 @@
# Changelog
## [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.
+59 -25
View File
@@ -12,25 +12,28 @@ MINGCUTE_DIR = $(shell $(ZIRAN) pkg path mingcute $(LOCK_FLAGS))
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))
WORKBOOK_DIR = $(shell $(ZIRAN) pkg path workbook $(LOCK_FLAGS))
ENTITY_DIR = $(shell $(ZIRAN) pkg path entity $(LOCK_FLAGS))
APPS_DIR = $(shell $(ZIRAN) pkg path apps $(LOCK_FLAGS))
LIBOQS_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
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)
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 plan9-c
all: cli gui
native: all
@@ -44,28 +47,45 @@ 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.
# Each app is its own bundle; Werkzeug runs them in one window. Workbook runs
# only in the Linux desktop app, so the web and Android apps leave it out.
APPS := pass auth calculator clock
APP_BUNDLES := $(APPS:%=build/apps/%.zib) build/apps/self.zib
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zib) build/apps/entity.zib build/apps/apps.zib
APP_BUNDLES := $(PORTABLE_BUNDLES) build/apps/workbook.zib
SHARED_SOURCES := $(wildcard shared/*.zi)
APPS_UI_SOURCES = $(wildcard $(APPS_DIR)/src/*.zi $(APPS_DIR)/ui/*.zi $(APPS_DIR)/ui/locales/*.json)
APP_MODULE_PATHS = --module-path shared --module-path kryon=$(KRYON_DIR)/src/backend --module-path kryon=$(KRYON_DIR)/src/ui --module-path $(KRYON_DIR)/src/ui --module-path $(MINGCUTE_DIR)/src --module-path $(ZIRAN_ROOT)/std
apps: $(APP_BUNDLES)
portable-apps: $(PORTABLE_BUNDLES)
# Compile the shared screen with the host's compiler and UI library. The
# reviewed payload must match both the build pin and the native host pin.
build/apps/apps.zib: $(APPS_UI_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock apps-controller.sha256 Makefile scripts/ziran.sh
mkdir -p $(@D)
python3 '$(APPS_DIR)/scripts/generate-ui-locales.py' --check
$(ZIRAN) bundle --root $(APPS_DIR)/ui --module-path $(APPS_DIR)/src $(APP_MODULE_PATHS) \
--define KRYON_HOSTED_UI --entry apps:Main -o $@ $(APPS_DIR)/ui/apps.zi
sha256sum $@ | cut -d ' ' -f 1 > $(@D)/apps.sha256
test "$$(cat $(@D)/apps.sha256)" = "$$(cat apps-controller.sha256)"
.SECONDEXPANSION:
build/apps/%.zib: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle --root . --module-path apps/$* $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
$(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/workbook.zib: $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(WORKBOOK_DIR)/Makefile ziran.lock
$(MAKE) -C $(WORKBOOK_DIR) ZIRAN=$(ZIRAN_ROOT)/build/bin/ziran bundle
install -m 0600 $(WORKBOOK_DIR)/build/workbook.zib $@
build/apps/entity.zib: $(ENTITY_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
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 --root $(ENTITY_DIR) --module-path $(ENTITY_DIR)/src $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI \
--module-path qrcode=$(QRCODE_DIR)/src --asset-dir assets=$(ENTITY_DIR)/assets --entry entity:Main -o $@ $(ENTITY_DIR)/src/entity.zi
# 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 $@)
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) $(SHARED_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,7 +96,8 @@ 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 $@
$(shell pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo gtk+-3.0) -lX11 -l:libcurl.so.4 -lm -lpthread -o $@.new
mv -f $@.new $@
build/pfp.png: $(KRYON_DIR)/icons/pfp.png
cp $< $@
gui: build/werk build/pfp.png apps
@@ -96,13 +117,16 @@ 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
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test
gui-smoke: gui
sh scripts/gui_smoke.sh
gui-test: gui
python3 scripts/private-display.py python3 scripts/apps_gui_test.py
sh scripts/werk_gui_test.sh
python3 scripts/private-display.py python3 scripts/workbook_gui_test.py
python3 scripts/private-display.py python3 scripts/launcher_gui_test.py
sh scripts/migration_test.sh
python3 -I scripts/auth_command_test.py
@@ -116,14 +140,14 @@ build/generated/browser/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBR
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --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.png 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 $@
$(foreach bundle,$(PORTABLE_BUNDLES),--embed-file $(bundle)@/apps/$(notdir $(bundle))) --embed-file build/pfp.png@/pfp.png --embed-file assets/app/icon.png@/icon.png -o $@
build/web-app/index.html: build/web-app/index.js web/site/app/index.html
cp web/site/app/index.html $@
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
@@ -142,20 +166,24 @@ web-smoke: site
bash scripts/web_smoke.sh
# CMake emits JNI and foreign ABI types separately for each Android ABI.
android-debug: apps
android-debug: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
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
android-emulator: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
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
android-release: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
.PHONY: android-bundle
android-bundle: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
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.
@@ -182,16 +210,22 @@ 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.png "$(LIB_DIR)/pfp.png"
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
@if command -v gtk-update-icon-cache >/dev/null; then gtk-update-icon-cache -f -t "$(DATA_DIR)/icons/hicolor"; 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
+13 -3
View File
@@ -28,6 +28,8 @@ Small private tools in one app. The home screen opens each one:
- **Clock**: the local time and date, and a stopwatch that keeps running
while the app is closed.
- **Workbook** (Linux): a spreadsheet editor with bottom sheet tabs and File/Edit menus. Its own `workbook.zib` bundle runs inside Werkzeug. File → Download Workbook.zib saves a copy you can share or open with `werk --bundle FILE.zib`.
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.
@@ -81,8 +83,8 @@ 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
The embedded web app (`/app/?mini`) opens on Home with every tool, and also
provides Profile. Use `?mini&app=pass`, `auth`, `calculator` or `clock` to
open a particular tool first. Browser sync is currently unavailable.
- Each record is sealed on the device with XChaCha20-Poly1305 under a random
@@ -140,13 +142,15 @@ 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
SDL2, Cairo, FreeType, Fontconfig, Pango, GTK 3 and X11 development packages.
Workbook uses the installed Gnumeric library; 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,
@@ -158,6 +162,12 @@ make android-fdroid # unsigned F-Droid candidate, same Android ID and version
make android-emulator # the x86_64 APK for a private emulator
```
Linux installs include separate Pass, Auth, Calculator, Clock and Workbook
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/werk-VERSION-fdroid-unsigned.apk`. It adds no version or
+1 -1
View File
@@ -1 +1 @@
0.4.0
0.4.2
+1
View File
@@ -0,0 +1 @@
8c5806d7ff5a4fdaf6b98a7668acbf0aad236ece1d5e68ffe1f7b268a1afb077
+7 -1
View File
@@ -32,6 +32,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 +80,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 {
+7 -6
View File
@@ -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 16
versionName "0.4.2"
// 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 {
@@ -103,14 +104,14 @@ 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'
commandLine 'make', 'portable-apps'
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
def prepareImages = tasks.register('prepareImages', Copy) {
dependsOn makeApps
from('../../assets/app/icon.png')
from("${System.getenv('KRYON_DIR')}/icons/pfp.png")
from('../../build/apps') { include '*.zib'; into 'apps' }
from('../../build/apps') { include '*.zib'; exclude 'workbook.zib'; into 'apps' }
into layout.buildDirectory.dir('generated/appAssets')
}
tasks.named('preBuild').configure { dependsOn prepareImages }
@@ -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.
+14 -17
View File
@@ -1,26 +1,23 @@
# Draft: xyz.waozi.pass: rename to Werkzeug and update to 0.3.1
# Draft: xyz.waozi.pass: rename to Werkzeug and update to 0.4.0
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.
The app on F-Droid is now Werkzeug: Pass, Auth, Calculator and Clock in one
app. The current recipe still selects Pass 0.2.9 with its old name, website
and APK name. Update the existing package to the public Werkzeug 0.4.0
release, its links, description, screenshots and versioned APK name.
Preserve `xyz.waozi.pass` and the allowed signing certificate so existing
installations update in place.
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.
The build uses the exact Ziran toolchain and nine 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.
0.2.9 build keeps 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.
Werkzeug 0.3.0 and 0.3.1 are not offered: their locks pin dependency commits
that upstream history no longer contains, so they cannot be rebuilt.
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.
Keep this request in draft until those checks pass.
- [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)
- [Werkzeug 0.4.0 release](https://github.com/waozixyz/werk/releases/tag/v0.4.0)
+16 -23
View File
@@ -1,25 +1,22 @@
# Werkzeug F-Droid TODO
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.
Updated 2026-10-19. The recipe now targets the public Werkzeug 0.4.0 release
(Android versionCode 14) with new store text and screenshots. GitLab
authentication is still blocked and no new merge request has been created.
## Prepared and verified
- [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).
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.
- [x] Rename the listing to Werkzeug and pin 0.4.0's toolchain and nine
source dependencies, including Self and its QR code library.
- [x] Drop 0.3.0 and 0.3.1: their locks pin dependency commits that the
2026-10-19 history rewrite removed upstream, so they cannot be rebuilt.
- [x] Replace the old Pass screenshots with Werkzeug's home screen and tools.
- [x] Verify the public 0.4.0 universal APK: package `xyz.waozi.pass`,
versionCode 14, label Werkzeug, both ARM ABIs and the allowed signing
certificate. The recipe pins its tagged commit. `make android-fdroid`
builds the unsigned F-Droid candidate from the same lock.
## Resume the F-Droid submission
@@ -30,7 +27,7 @@ F-Droid can reproducibly build the 0.3.1 recipe.
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.
against the signed public 0.4.0 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.
@@ -39,14 +36,10 @@ F-Droid can reproducibly build the 0.3.1 recipe.
Merge request URL: pending submission.
## Later 0.4.0 release
## Later
- [ ] 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.
- [ ] Unfinished Clock/alarm work waits in the git stash "clock features
WIP 2". It is not part of 0.4.0; preserve it.
## Handoff files
+15 -13
View File
@@ -30,9 +30,9 @@ Builds:
- vendor/kryon/vendor
ndk: 28.2.13676358
- versionName: 0.3.1
versionCode: 13
commit: bde94573f4eda34fbc9ff46d7d1af2b60f0ce941
- versionName: 0.4.0
versionCode: 14
commit: 0d2c2b3a88e1080d3249848815b185757a1915c2
subdir: droid/app
sudo:
- apt-get update
@@ -41,19 +41,21 @@ Builds:
- yes
output: build/outputs/apk/release/app-universal-release-unsigned.apk
srclibs:
- Ziran@201be1072cfb2ad59b4060f8579db36f6848b8cb
- Kryon@159563f46c9f6cb4aa011f7372e175042b10fa68
- Monocypher@e65d27722a43e9ed88da1987f3ad5675503c8cad
- Oqs@5cc7677b290f0448462410f7c7e85f518664b943
- Mingcute@933691600cf10e81b1f53d9919dbcb371c1968e1
- Ziran@1ad0264d9f6ce3df29e9071ab16eae0e1e557049
- Kryon@a78576db722b25216e0096870d313b7d2ace96b0
- Monocypher@d1895c3799005122b2e68f47f442cc5ba709d866
- Oqs@22d2ddbdc236796953c905a05a2cebf5ab1b4ff3
- Mingcute@9cc6872f75447c3a24c16764f9829d0f58751cb0
- raylib@fafa2cea97d0cb379d832086ba45a989fa6f9c8e
- DaochiClient@d453a26642d7e35265d5d4fe2cc33a6a0725b0ca
- DaochiClient@42aa3ee773d8abdc6b3a10fbcb1b73c992f0f564
- liboqs@fd44469daeffe6b28f031f54f9bb66cbae69a572
- Self@1ce89cff5a807cca817aec5d1347e18d2f229b27
- Qrcode@2944b2e668e735438d8ce24e47a39be3f5c36af5
prebuild:
- printf '[overrides]\nziran = "$$Ziran$$"\nkryon = "$$Kryon$$"\nmingcute =
"$$Mingcute$$"\ndaochi_client = "$$DaochiClient$$"\noqs = "$$Oqs$$"\nliboqs
= "$$liboqs$$"\nmonocypher = "$$Monocypher$$"\nraylib = "$$raylib$$"\n' >
../../ziran.local.toml
= "$$liboqs$$"\nmonocypher = "$$Monocypher$$"\nraylib = "$$raylib$$"\nself
= "$$Self$$"\nqrcode = "$$Qrcode$$"\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
@@ -71,5 +73,5 @@ AllowedAPKSigningKeys: 1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee1
AutoUpdateMode: Version
UpdateCheckMode: Tags
CurrentVersion: 0.3.1
CurrentVersionCode: 13
CurrentVersion: 0.4.0
CurrentVersionCode: 14
+2
View File
@@ -0,0 +1,2 @@
RepoType: git
Repo: https://github.com/ziranlang/qrcode.git
+2
View File
@@ -0,0 +1,2 @@
RepoType: git
Repo: https://github.com/waozixyz/entity.git
+202
View File
@@ -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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+7
View File
@@ -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="*.zib"/>
</mime-type>
</mime-info>
+1 -1
View File
@@ -11,5 +11,5 @@
<launchable type="desktop-id">xyz.waozi.werk.desktop</launchable>
<url type="homepage">https://github.com/waozixyz/werk</url>
<provides><binary>werk</binary></provides>
<releases><release version="0.4.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.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=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
+5 -2
View File
@@ -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=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=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
+55
View File
@@ -0,0 +1,55 @@
#!/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
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", "Preserve the installed app ID"
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:
for app in ("pass", "auth", "calculator", "clock", "entity", "apps"):
assert f"base/assets/apps/{app}.zib" in archive.namelist(), f"Missing {app}"
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))
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"))
+31 -17
View File
@@ -43,16 +43,24 @@ def tap_label(word):
tap(*find_label(word))
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,11 +72,14 @@ 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 system_bars(height):
"""The app's first and last rows in pixels: Werkzeug keeps its content
@@ -116,13 +127,16 @@ try:
assert "test master" not in saved
# Generate from the saved profile and copy it.
tap(int(100 * zoom), top + int((210 + bar) * zoom))
time.sleep(0.5)
# A slow emulator may still be deriving the password.
time.sleep(2); dismiss_other_apps_not_responding()
tap(int(100 * zoom), bottom - int(119 * zoom)) # Copy, at the bottom of the scrolled form
shot("generated")
tap(width // 2, bottom - int(35 * zoom))
tap(int(90 * zoom), top + int((55 + bar) * zoom))
shell("input", "keyevent", "123") # Move to the end.
shell("input", "keyevent", *("67" for _ in "Android test"))
for _ in "Android test":
shell("input", "keyevent", "67"); time.sleep(0.1)
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.
@@ -135,7 +149,7 @@ try:
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()
time.sleep(1); 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")
@@ -143,7 +157,7 @@ try:
# 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.
# Entity'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)
@@ -152,7 +166,7 @@ try:
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.
# Entity's Nodes section: the empty "Node address" field, then Add.
tap_label("Node")
type_text("https://sync.example.invalid:8443/")
shell("input", "keyevent", "4"); time.sleep(1.2)
@@ -169,7 +183,7 @@ try:
shell("am", "force-stop", package)
adb("install", "-r", str(apk))
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(1); alive()
time.sleep(1); 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")
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Verify the shared Apps controller and native tool navigation."""
import csv
import hashlib
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 = 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.zib").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")
return command("tesseract", str(work / "labels.png"), "stdout", "--psm", "11")
def click(x, y):
command("xdotool", "mousemove", "--window", window, str(x), str(y))
command("xdotool", "click", "--window", window, "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", "--window", window, value)
time.sleep(.2)
def type_text(value):
command("xdotool", "type", "--window", window, "--delay", "30", value)
time.sleep(.3)
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)
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")
# The native fallback does not display package sizes.
if "kB" in home or "MB" in home:
break
assert app.poll() is None, "Werkzeug exited while loading Apps"
assert time.monotonic() < deadline, "Shared Apps controller did not render: " + home
for name in ("Auth", "Calculator", "Clock", "Workbook", "Pass"):
click_word(name)
assert command("xdotool", "getwindowname", window).strip() == name
assert "stopped" not in capture(name.lower()).lower(), name + " failed to run"
click(28, 28)
assert command("xdotool", "getwindowname", window).strip() == "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
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, Workbook.
click(name[0] - 16 + 120, name[1] + 116)
# White text on the filled Save button is not reliably recognized by OCR.
click(310, name[1] + 182)
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)
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, five tools and resized layouts verified locally")
finally:
if app.poll() is None:
app.terminate()
app.wait(timeout=10)
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Test native Self account transitions with private fixture data only."""
"""Test native Entity account transitions with private fixture data only."""
import os
from pathlib import Path
import shutil
@@ -16,15 +16,15 @@ def package(name):
std_root = package('ziran')
monocypher = package('monocypher')
output = ROOT / 'build/self-account-test'
output = ROOT / 'build/entity-account-test'
output.mkdir(parents=True, exist_ok=True)
generated = output / 'generated'
shutil.rmtree(generated, ignore_errors=True)
subprocess.run([ZIRAN, 'build', '--project', '--root', str(ROOT), '--define', 'PLATFORM_DESKTOP', '--target=c',
'--entry', 'self_account_test:Check', '-o', str(generated),
'tests/self_account_test.zi'], cwd=ROOT, env=ENV, check=True)
(generated / 'main.c').write_text('#include "tests/self_account_test.h"\n#include <stdio.h>\n#include <string.h>\n'
'int main(void) { int result = Check(); if (result) fprintf(stderr, "Self account fixture %d failed\\n", result); return result != 0; }\n')
'--entry', 'entity_account_test:Check', '-o', str(generated),
'tests/entity_account_test.zi'], cwd=ROOT, env=ENV, check=True)
(generated / 'main.c').write_text('#include "tests/entity_account_test.h"\n#include <stdio.h>\n#include <string.h>\n'
'int main(void) { int result = Check(); if (result) fprintf(stderr, "Entity account fixture %d failed\\n", result); return result != 0; }\n')
executable = output / 'test'
subprocess.run([os.environ.get('CC', 'cc'), '-std=c11', '-O2', '-ffunction-sections', '-fdata-sections',
'-Wl,--gc-sections', f'-I{std_root / "include"}', f'-I{generated}', f'-I{monocypher / "src"}',
@@ -59,4 +59,4 @@ finally:
ready.unlink(missing_ok=True)
for path in data.rglob('*'):
assert path.stat().st_mode & 0o077 == 0, f'Non-private fixture path: {path.name}'
print('Self: vault retention, merge/replace, tombstones, pause choice, failed writes, interrupted-switch recovery, concurrent reader locking and logout passed.')
print('Entity: vault retention, merge/replace, tombstones, pause choice, failed writes, interrupted-switch recovery, concurrent reader locking and logout passed.')
+2 -2
View File
@@ -17,7 +17,7 @@ for mode in light dark; do
value=2
fi
printf 'theme_mode=%s\n' "$value" > "$work/$mode/data/profile/settings.txt"
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS xvfb-run -a -e /dev/stderr \
python3 scripts/private-display.py \
env -u WERK_ASSETS HOME="$work/home" WERK_DATA="$work/$mode/data" XDG_CACHE_HOME="$work/$mode/cache" \
KRYON_CAPTURE_PATH="$work/werk-$mode.png" "$root/build/werk"
test -s "$work/werk-$mode.png"
@@ -34,7 +34,7 @@ with Image.open(work / "werk-light.png") as source:
PY
rendered=$(tesseract "$work/labels.png" stdout --psm 11 2>/dev/null)
for app in Pass Auth Calculator Clock; do
printf '%s\n' "$rendered" | rg -q "$app" || { echo "Missing preinstalled app: $app" >&2; exit 1; }
printf '%s\n' "$rendered" | grep -q "$app" || { echo "Missing preinstalled app: $app" >&2; exit 1; }
done
if cmp -s "$work/werk-light.png" "$work/werk-dark.png"; then
echo 'Werkzeug light and dark themes rendered the same frame' >&2
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Install the same tool launchers in user installs and Linux packages."""
import argparse
from pathlib import Path
import shutil
import subprocess
root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data-dir", type=Path, required=True)
parser.add_argument("--bin-dir", type=Path)
parser.add_argument("--desktop-dir", type=Path)
parser.add_argument("--uninstall", action="store_true")
args = parser.parse_args()
def executable(path):
# Desktop Entry Exec quoting has an additional escaping layer.
value = str(path).replace("\\", "\\\\\\\\").replace('"', '\\\\"')
value = value.replace("`", "\\\\`").replace("$", "\\\\$").replace("%", "%%")
return '"' + value + '"'
for source in sorted((root / "packaging/linux").glob("xyz.waozi.werk*.desktop")):
destinations = [args.data_dir / "applications" / source.name]
if args.desktop_dir:
destinations.append(args.desktop_dir / source.name)
content = source.read_text()
if args.bin_dir:
content = content.replace("Exec=werk ", "Exec=" + executable(args.bin_dir / "werk") + " ")
content = content.replace("TryExec=werk", "TryExec=" + str(args.bin_dir / "werk"))
for target in destinations:
if args.uninstall:
target.unlink(missing_ok=True)
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
target.chmod(0o755 if target.parent == args.desktop_dir else 0o644)
if target.parent == args.desktop_dir and shutil.which("gio"):
subprocess.run(["gio", "set", str(target), "metadata::trusted", "true"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
icons = {"werk": root / "assets/app/icon.png"}
icons.update({path.stem: path for path in (root / "packaging/linux/icons").glob("*.png")})
for name, source in icons.items():
target = args.data_dir / "icons/hicolor/512x512/apps" / (name + ".png")
if args.uninstall:
target.unlink(missing_ok=True)
else:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
target.chmod(0o644)
notice = args.data_dir / "doc/werk/MingCute-LICENSE.txt"
if args.uninstall:
notice.unlink(missing_ok=True)
else:
notice.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / "packaging/linux/icons/LICENSE-MingCute.txt", notice)
notice.chmod(0o644)
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Launch the installed desktop entries against disposable private data."""
import configparser
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import time
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
root = Path(__file__).resolve().parents[1]
work = root / "build/launcher-gui-test"
shutil.rmtree(work, ignore_errors=True)
stage = work / "install with spaces"
share = stage / "share"
desktop = stage / "Desktop"
library = stage / "lib/werk"
subprocess.run(["make", "install-gui", f"BIN_DIR={stage / 'bin'}", f"DATA_DIR={share}",
f"LIB_DIR={library}", f"DESKTOP_DIR={desktop}"], cwd=root, check=True)
environment = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
WERK_ASSETS=str(library), ENTITY_DATA=str(work / "entity"),
XDG_DATA_HOME=str(share), XDG_CONFIG_HOME=str(work / "config"),
XDG_CACHE_HOME=str(work / "cache"))
for key in ("HOME", "WERK_DATA", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"):
Path(environment[key]).mkdir(parents=True, exist_ok=True)
profile = work / "data/profile"
profile.mkdir(parents=True)
(profile / "settings.txt").write_text("theme_mode=1\n")
def command(*args):
return subprocess.check_output(args, env=environment, text=True, timeout=20)
for tool, name in (("", "Werkzeug"), ("pass", "Pass"), ("auth", "Auth"),
("calculator", "Calculator"), ("clock", "Clock"), ("workbook", "Workbook")):
identity = "xyz.waozi.werk" + ("." + tool if tool else "")
entry = share / "applications" / (identity + ".desktop")
assert entry.read_bytes() == (desktop / entry.name).read_bytes()
assert (desktop / entry.name).stat().st_mode & 0o100
subprocess.run(["desktop-file-validate", str(entry)], check=True)
config = configparser.ConfigParser(interpolation=None)
config.read(entry)
values = config["Desktop Entry"]
assert values["Name"] == name
assert (share / "icons/hicolor/512x512/apps" / (values["Icon"] + ".png")).is_file()
argv = shlex.split(values["Exec"])
if not tool:
argv = argv[:1]
process = subprocess.Popen(argv, env=environment)
try:
window = None
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
assert process.poll() is None, f"{name} exited during startup"
result = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(process.pid)],
env=environment, text=True, capture_output=True)
if result.returncode == 0:
window = result.stdout.splitlines()[0]
if command("xdotool", "getwindowname", window).strip() == name:
break
time.sleep(.1)
assert window and command("xdotool", "getwindowname", window).strip() == name
wm_class = command("xprop", "-id", window, "WM_CLASS")
assert values["StartupWMClass"] in wm_class, wm_class
picture = work / ((tool or "werkzeug") + ".png")
deadline = time.monotonic() + 15
text = ""
while time.monotonic() < deadline:
assert process.poll() is None, f"{name} exited before rendering"
time.sleep(.3)
command("import", "-window", window, str(picture))
text = command("tesseract", str(picture), "stdout", "--psm", "11")
if name in text: break
assert name in text, f"{name} did not render its direct tool screen: {text}"
assert "unavailable" not in text.lower(), text
print(f"Installed {name} entry opened the correct screen and window identity", flush=True)
finally:
if process.poll() is None:
process.terminate()
process.wait(timeout=10)
subprocess.run(["python3", str(root / "scripts/install-launchers.py"), "--data-dir", str(share),
"--desktop-dir", str(desktop), "--uninstall"], check=True)
assert not list((share / "applications").glob("xyz.waozi.werk*.desktop"))
assert not list(desktop.glob("xyz.waozi.werk*.desktop"))
print("All six installed launchers, distinct icons and shortcut removal verified locally")
+11 -10
View File
@@ -5,24 +5,25 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
version=$(sed -n '1p' "$root/VERSION")
arch=${APPIMAGE_ARCH:-$(uname -m)}
linuxdeploy=${LINUXDEPLOY:-linuxdeploy}
artifacts=${WERK_BUILD_DIR:-$root/build}
appdir="$root/build/package/appimage/werk.AppDir"
out="$root/build/release/werk-${version}-${arch}.AppImage"
test -n "$version"
rm -rf "$appdir"
mkdir -p "$appdir/usr/bin" "$appdir/usr/lib/werk/apps" "$appdir/usr/share/applications" \
"$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
cp "$root/build/werk" "$appdir/usr/bin/werk"
cp "$root"/build/apps/*.zib "$appdir/usr/lib/werk/apps/"
cp "$root/build/pfp.png" "$appdir/usr/lib/werk/pfp.png"
cp "$root/packaging/linux/xyz.waozi.werk.desktop" "$appdir/usr/share/applications/xyz.waozi.werk.desktop"
"$appdir/usr/share/mime/packages" "$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
cp "$artifacts/werk" "$appdir/usr/bin/werk"
cp "$artifacts"/apps/*.zib "$appdir/usr/lib/werk/apps/"
cp "$artifacts/pfp.png" "$appdir/usr/lib/werk/pfp.png"
python3 "$root/scripts/install-launchers.py" --data-dir "$appdir/usr/share"
cp "$root/packaging/linux/werk-bundle.xml" "$appdir/usr/share/mime/packages/werk-bundle.xml"
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$appdir/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
cp "$root/assets/app/icon.png" "$appdir/usr/share/icons/hicolor/512x512/apps/werk.png"
cp "$root/assets/app/icon.png" "$root/build/package/appimage/werk.png"
rm -f "$root"/Werkzeug-*.AppImage "$root"/werk-*.AppImage
ARCH="$arch" "$linuxdeploy" --appdir "$appdir" --desktop-file "$root/packaging/linux/xyz.waozi.werk.desktop" \
--icon-file "$root/build/package/appimage/werk.png" --output appimage
image=$(find "$root" -maxdepth 1 -type f -name '*.AppImage' -print | head -n 1)
run_dir=$(mktemp -d "$root/build/package/appimage/output.XXXXXX")
(cd "$run_dir" && ARCH="$arch" "$linuxdeploy" --appdir "$appdir" --desktop-file "$root/packaging/linux/xyz.waozi.werk.desktop" \
--icon-file "$root/build/package/appimage/werk.png" --output appimage)
image=$(find "$run_dir" -maxdepth 1 -type f -name '*.AppImage' -print | head -n 1)
test -n "$image"
mv "$image" "$out"
chmod 0755 "$out"
+8 -7
View File
@@ -4,19 +4,20 @@ set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
version=$(sed -n '1p' "$root/VERSION")
arch=${DEB_ARCH:-$(dpkg --print-architecture)}
artifacts=${WERK_BUILD_DIR:-$root/build}
stage="$root/build/package/deb/werk"
out="$root/build/release"
test -n "$version"
rm -rf "$stage"
mkdir -p "$stage/DEBIAN" "$stage/usr/bin" "$stage/usr/lib/werk/apps" "$stage/usr/share/applications" \
"$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/werk" "$out"
cp "$root/build/werk" "$stage/usr/bin/werk"
cp "$root"/build/apps/*.zib "$stage/usr/lib/werk/apps/"
cp "$root/build/pfp.png" "$stage/usr/lib/werk/pfp.png"
cp "$root/packaging/linux/xyz.waozi.werk.desktop" "$stage/usr/share/applications/xyz.waozi.werk.desktop"
"$stage/usr/share/mime/packages" "$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/werk" "$out"
cp "$artifacts/werk" "$stage/usr/bin/werk"
cp "$artifacts"/apps/*.zib "$stage/usr/lib/werk/apps/"
cp "$artifacts/pfp.png" "$stage/usr/lib/werk/pfp.png"
python3 "$root/scripts/install-launchers.py" --data-dir "$stage/usr/share"
cp "$root/packaging/linux/werk-bundle.xml" "$stage/usr/share/mime/packages/werk-bundle.xml"
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$stage/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
cp "$root/assets/app/icon.png" "$stage/usr/share/icons/hicolor/512x512/apps/werk.png"
cp "$root/LICENSE" "$root/README.md" "$stage/usr/share/doc/werk/"
find "$stage" -type d -exec chmod 0755 {} \;
chmod 0755 "$stage/usr/bin/werk"
@@ -28,7 +29,7 @@ Version: $version
Architecture: $arch
Maintainer: Waozi <[email protected]>
Installed-Size: $installed
Depends: libc6, libsdl2-2.0-0, libcairo2, libfreetype6, libfontconfig1, libpangocairo-1.0-0, libgtk-3-0, libx11-6
Depends: libc6, libsdl2-2.0-0, libcairo2, libfreetype6, libfontconfig1, libpangocairo-1.0-0, libgtk-3-0, libx11-6, libcurl4 | libcurl4t64, libzbar0, gnumeric, zenity
Section: utils
Priority: optional
Homepage: https://werk.waozi.xyz/
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Run a GUI test under a verified, owned Xvfb server."""
import os
from pathlib import Path
import select
import shutil
import subprocess
import sys
environment = dict(os.environ)
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"):
environment.pop(key, None)
environment["YUE_DESKTOP_RECOVERY"] = "0"
environment["WERK_TEST_PRIVATE_DISPLAY"] = "1"
environment["SDL_RENDER_DRIVER"] = "software"
read_fd, write_fd = os.pipe()
server = subprocess.Popen(["Xvfb", "-displayfd", str(write_fd), "-screen", "0", "1280x1024x24", "-nolisten", "tcp"],
pass_fds=(write_fd,), env=environment)
os.close(write_fd)
try:
assert select.select([read_fd], [], [], 20)[0], "Xvfb did not allocate a private display"
display = os.read(read_fd, 32).decode().strip()
assert display.isdecimal() and server.poll() is None, "Private Xvfb did not start"
process = Path(f"/proc/{server.pid}")
executable = process.joinpath("exe").resolve()
assert executable == Path(shutil.which("Xvfb")).resolve(), "Unexpected X server executable"
assert process.stat().st_uid == os.getuid(), "Private server has another owner"
command = process.joinpath("cmdline").read_bytes().replace(b"\0", b" ").decode()
assert f"-displayfd {write_fd} " in command, "Unexpected display allocation source"
evidence = Path(__file__).resolve().parents[1] / "build/desktop-task"
evidence.mkdir(parents=True, exist_ok=True)
with (evidence / "private-displays.log").open("a") as receipt:
receipt.write(f"pid={server.pid} executable={executable} display=:{display} command={command}\n")
environment["DISPLAY"] = ":" + display
print(f"Verified owned private Xvfb for {sys.argv[1]}", flush=True)
result = subprocess.run(sys.argv[1:], env=environment)
raise SystemExit(result.returncode)
finally:
os.close(read_fd)
if server.poll() is None:
server.terminate()
server.wait(timeout=10)
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Render the tools' existing MingCute vector icons as Linux launcher PNGs."""
from pathlib import Path
import subprocess
import xml.etree.ElementTree as ET
import cairosvg
root = Path(__file__).resolve().parents[1]
mingcute = Path(subprocess.check_output([str(root / "scripts/ziran.sh"), "pkg", "path", "mingcute"], text=True).strip())
output = root / "packaging/linux/icons"
output.mkdir(exist_ok=True)
icons = {
"pass": ("regular/system/keyhole.svg", "#6750A4"),
"auth": ("regular/system/shield.svg", "#146B58"),
"calculator": ("regular/education/counter.svg", "#245F9B"),
"clock": ("regular/system/time.svg", "#9A4F19"),
"workbook": ("extra/table_row_add.svg", "#356B30"),
}
for app, (relative, color) in icons.items():
source = ET.parse(mingcute / "svg" / relative).getroot()
for node in source.iter():
for attribute in ("stroke", "fill"):
if node.get(attribute) not in (None, "none"):
node.set(attribute, "#FFFFFF")
body = "".join(ET.tostring(node, encoding="unicode") for node in source)
svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><rect x="16" y="16" width="480" height="480" rx="112" fill="{color}"/><g transform="translate(88 88) scale(14)">{body}</g></svg>'
cairosvg.svg2png(bytestring=svg.encode(), write_to=str(output / f"werk-{app}.png"))
(output / "LICENSE-MingCute.txt").write_bytes((mingcute / "LICENSE").read_bytes())
+55 -11
View File
@@ -1,6 +1,6 @@
// Exercise the built site's Werkzeug app in a private headless browser with a
// disposable profile: the home screen, a tool opened by ?app=, Calculator
// typing, Clock, and every tool plus navigation in embedded mini mode.
// disposable profile: the home screen, a tool opened by clicking Home and by
// ?app=, Calculator typing, Clock, and every tool in embedded mini mode.
import {spawn, spawnSync} from 'node:child_process';
import {readFile, writeFile, mkdir, mkdtemp} from 'node:fs/promises';
import {createServer} from 'node:http';
@@ -95,9 +95,18 @@ try {
};
const expectText = async (name, expected) => {
await screenshot(name);
const result = spawnSync('tesseract', [join(output, name + '.png'), 'stdout', '--psm', '11'],
let result = spawnSync('tesseract', [join(output, name + '.png'), 'stdout', '--psm', '11'],
{env: environment, encoding: 'utf8', timeout: 20000});
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
if (!result.stdout.toLowerCase().includes(expected.toLowerCase())) {
const readable = join(output, name + '-labels.png');
const prepared = spawnSync('convert', [join(output, name + '.png'), '-colorspace', 'Gray',
'-threshold', '55%', '-resize', '300%', readable], {env: environment, encoding: 'utf8'});
if (prepared.status !== 0) throw Error('Could not prepare UI text: ' + prepared.stderr);
result = spawnSync('tesseract', [readable, 'stdout', '--psm', '11'],
{env: environment, encoding: 'utf8', timeout: 20000});
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
}
if (!result.stdout.toLowerCase().includes(expected.toLowerCase()))
throw Error(`${name}: expected ${expected}, saw ${result.stdout}`);
};
@@ -106,6 +115,21 @@ try {
await command('Input.dispatchMouseEvent', {type: 'mouseReleased', x, y, button: 'left', clickCount: 1});
await delay(350);
};
const clickText = async label => {
await screenshot('control');
const readable = join(output, 'control-labels.png');
const prepared = spawnSync('convert', [join(output, 'control.png'), '-colorspace', 'Gray',
'-threshold', '55%', '-resize', '300%', readable], {env: environment, encoding: 'utf8'});
if (prepared.status !== 0) throw Error('Could not prepare UI text: ' + prepared.stderr);
const result = spawnSync('tesseract', [readable, 'stdout', '--psm', '11',
'-c', 'tessedit_create_tsv=1'], {env: environment, encoding: 'utf8', timeout: 20000});
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
const rows = result.stdout.trim().split('\n').slice(1).map(line => line.split('\t'));
const row = rows.find(values => values[11]?.trim() === label);
if (!row) throw Error('Missing visible app control: ' + label);
await click((Number(row[6]) + Number(row[8]) / 2) / 3,
(Number(row[7]) + Number(row[9]) / 2) / 3);
};
// The canvas has drawn a frame with something besides the background.
const painted = `(() => {
const canvas = document.querySelector('canvas');
@@ -140,29 +164,49 @@ try {
};
await command('Runtime.enable');
await command('Page.enable');
await command('Page.addScriptToEvaluateOnNewDocument', {source: `
window.__timezoneReads = 0;
const getTimezoneOffset = Date.prototype.getTimezoneOffset;
Date.prototype.getTimezoneOffset = function() {
window.__timezoneReads++;
return getTimezoneOffset.call(this);
};
`});
await command('Emulation.setDeviceMetricsOverride', {width: 420, height: 760, deviceScaleFactor: 1, mobile: false});
await open('', 'home');
const timezoneReadsBefore = await evaluate('window.__timezoneReads');
await click(330, 92); // Shared List view.
await clickText('Clock');
await expectText('home-clock', 'Clock');
await delay(1200);
const timezoneReads = (await evaluate('window.__timezoneReads')) - timezoneReadsBefore;
if (timezoneReads > 6) throw Error(`Clock read the time zone ${timezoneReads} times in 1.2 seconds`);
await click(28, 28);
await expectText('home-returned', 'Werkzeug');
await open('?app=calculator', 'calculator');
await type('12+30*2=');
await delay(400);
await expectText('calculator-typed', '72');
// Clock reads the local time zone every frame; a broken time binding
// froze the page here.
// Clock also opens directly, where a broken time binding froze the page.
await open('?app=clock', 'clock');
await open('?mini', 'pass-mini');
await expectText('pass-mini', 'Pass');
for (const [index, app] of ['pass', 'auth', 'calculator', 'clock'].entries()) {
// The embedded mini version opens on Home with every tool; a tool
// would show its own name as the title.
await open('?mini', 'mini-home');
await expectText('mini-home', 'Werkzeug');
for (const app of ['pass', 'auth', 'calculator', 'clock']) {
await open('?mini&app=' + app, app + '-mini-direct');
await expectText(app + '-mini-direct', app);
await click(28, 28);
await expectText(app + '-mini-home', 'Werkzeug');
await click(142 + (index % 2) * 136, 132 + Math.floor(index / 2) * 136);
await clickText(app[0].toUpperCase() + app.slice(1));
await expectText(app + '-mini-reopened', app);
}
await command('Emulation.setDeviceMetricsOverride', {width: 280, height: 480, deviceScaleFactor: 1, mobile: false});
await open('?mini&app=unknown', 'mini-narrow-home');
await expectText('mini-narrow-home', 'Werkzeug');
await click(206, 264);
await expectText('mini-narrow-home', 'Find an app');
await click(100, 92);
await type('clock');
await clickText('Clock');
await expectText('mini-narrow-clock', 'Clock');
await click(28, 28);
await click(250, 28);
+35 -27
View File
@@ -26,10 +26,12 @@ data = output / "data"
cache = output / "cache"
data.mkdir(parents=True)
cache.mkdir(parents=True)
(data / "profile").mkdir()
(data / "profile/settings.txt").write_text("name=Fixture Person\ntheme_mode=1\n")
environment = dict(os.environ)
environment.pop("WAYLAND_DISPLAY", None)
environment["WERK_DATA"] = str(data)
environment["SELF_DATA"] = str(output / "shared-self")
environment["ENTITY_DATA"] = str(output / "shared-entity")
environment["XDG_DATA_HOME"] = str(output / "xdg-data")
environment["XDG_CONFIG_HOME"] = str(output / "xdg-config")
environment["XDG_CACHE_HOME"] = str(cache)
@@ -125,10 +127,10 @@ def click_word(word, toggle=False, last=False, exact_case=False):
raise AssertionError(f"Could not find {word!r} in the private test window")
def click_scrolled(word):
def click_scrolled(word, **options):
for attempt in range(12):
try:
return click_word(word)
return click_word(word, **options)
except AssertionError:
command("xdotool", "mousemove", "--window", window, "200", "650")
command("xdotool", "click", "--window", window, "--repeat", "3", "--delay", "50", "5")
@@ -188,10 +190,9 @@ def clipboard():
return command("xclip", "-selection", "clipboard", "-out")
def tile(index):
"""The centre of a home screen tile; the window is 420 wide."""
left = (420 - (2 * 120 + 16)) // 2
return left + (index % 2) * 136 + 60, 56 + 16 + (index // 2) * 136 + 60
def open_tool(name):
click_word(name, exact_case=True)
assert command("xdotool", "getwindowname", window).strip() == name
def home():
@@ -265,7 +266,7 @@ try:
capture("home")
# Pass: the same inputs give the LessPass reference password.
click(*tile(0))
open_tool("Pass")
capture("pass-open")
left = (420 - 384) // 2
click(left + 100, 56 + 12 + 24 + 20)
@@ -284,18 +285,29 @@ try:
home()
# Calculator: keyboard input.
click(*tile(2))
open_tool("Calculator")
type_text("12+30*2=")
capture("calculator")
assert "72" in screen_text(), "Calculator did not show the expected result"
home()
# Clock.
click(*tile(3))
open_tool("Clock")
capture("clock")
click_word("Stopwatch")
click(110, 382)
time.sleep(1.2)
click(110, 382)
stopwatch = next(data.rglob("stopwatch.txt"))
state = [int(value) for value in stopwatch.read_text().split()]
assert state[0] == 0 and state[2] >= 1000, "Stopwatch did not advance and stop"
capture("stopwatch")
click(310, 382)
assert stopwatch.read_text().split() == ["0", "0", "0"], "Stopwatch did not reset"
home()
# Auth: import a fixture link and copy its code.
click(*tile(1))
open_tool("Auth")
capture("auth-empty")
click(210, 56 + 12 + 20)
click(210, 56 + 12 + 24 + 20)
@@ -356,12 +368,8 @@ try:
assert saved.count("\tV\t") == 2 and "Third:carol" in saved, saved.count("\tV\t")
home()
# Profile: a name and dark appearance are saved privately.
click(420 - 30, 28)
click(*field_below("Name"))
type_text("Fixture Person")
home()
assert "name=Fixture Person\n" in (data / "profile/settings.txt").read_text(), "Leaving Self lost the pending name edit"
# Entity retains existing names; its current profile edits appearance.
assert "name=Fixture Person\n" in (data / "profile/settings.txt").read_text()
click(390, 28)
scroll_down()
click_word("Dark")
@@ -369,8 +377,10 @@ try:
settings = (data / "profile/settings.txt").read_text()
assert "name=Fixture Person\n" in settings and "theme_mode=2\n" in settings, settings
assert (data / "profile/settings.txt").stat().st_mode & 0o077 == 0
# Nodes belong to the common Self bundle; choosing one creates no account.
# Nodes belong to the common Entity bundle; choosing one creates no account.
click_word("Light")
scroll_up()
click_word("Connect", exact_case=True)
node_field = field_below("Nodes", 120)
click(*node_field)
type_text("https://example.invalid/path")
@@ -387,14 +397,11 @@ try:
stop()
start()
click(390, 28)
click_word("Connect", exact_case=True)
capture("node-restarted")
assert "node=https://sync.example.invalid:8443\n" in (data / "profile/settings.txt").read_text()
assert not (data / "account/keys.txt").exists()
# OCR uses light controls; the dark appearance was checked above.
scroll_down()
click_word("Light")
scroll_down()
click_word("Account")
scroll_up()
# The filled action's painted bounds are stable even when OCR misses
# white labels. Creating an account explicitly asks to merge Auth data.
click_filled()
@@ -403,17 +410,19 @@ try:
time.sleep(.8)
account_file = data / "account/keys.txt"
assert account_file.exists() and "paused=0\n" in account_file.read_text()
click_word("Sync", toggle=True)
assert "paused=1\n" in account_file.read_text(), "Self's sync switch did not pause"
click_scrolled("Sync", toggle=True)
assert "paused=1\n" in account_file.read_text(), "Entity's sync switch did not pause"
capture("sync-paused")
stop()
start()
assert "paused=1\n" in account_file.read_text()
click(390, 28)
# The connected account's public-ID button opens management.
click(210, 310)
capture("sync-paused-restarted")
previous_account = account_file.read_text()
scroll_down()
node_field = click_word("Node", exact_case=True)
node_field = click_scrolled("address")
type_text("https://second.example.invalid")
add_node(node_field)
account = account_file.read_text()
@@ -422,7 +431,6 @@ try:
assert ([line for line in previous_account.splitlines() if not line.startswith("server=")]
== [line for line in account.splitlines() if not line.startswith("server=")]), "Changing node altered account credentials"
scroll_up()
click_scrolled("Manage")
click_scrolled("out")
click_filled()
time.sleep(.8)
+1 -2
View File
@@ -4,5 +4,4 @@
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
exec env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS xvfb-run -a -e /dev/stderr \
env WERK_TEST_PRIVATE_DISPLAY=1 python3 scripts/werk_gui_test.py
exec python3 scripts/private-display.py python3 scripts/werk_gui_test.py
+147
View File
@@ -0,0 +1,147 @@
"""Exercise the Workbook bundle on the caller's private Xvfb display."""
from pathlib import Path
import csv
import gzip
import io
import os
import shutil
import subprocess
import time
import xml.etree.ElementTree as ET
from PIL import Image
assert os.environ.get('WERK_TEST_PRIVATE_DISPLAY') == '1', 'Use private Xvfb'
root = Path(__file__).resolve().parents[1]
work = root / 'build/workbook-gui-test'
shutil.rmtree(work, ignore_errors=True)
for directory in ('home', 'data/profile', 'cache', 'bin'):
(work / directory).mkdir(parents=True, exist_ok=True)
(work / 'data/profile/settings.txt').write_text('theme_mode=1\n')
selector = work / 'selection.txt'
fake = work / 'bin/zenity'
fake.write_text('#!/bin/sh\ncat "$WORKBOOK_TEST_SELECTION"\n')
fake.chmod(0o700)
fixture = work / 'source.gnumeric'
fixture.write_text('''<?xml version="1.0"?><gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd"><gnm:SheetNameIndex><gnm:SheetName>Fixture</gnm:SheetName></gnm:SheetNameIndex><gnm:Sheets><gnm:Sheet><gnm:Name>Fixture</gnm:Name><gnm:MaxCol>1</gnm:MaxCol><gnm:MaxRow>0</gnm:MaxRow><gnm:Cells><gnm:Cell Row="0" Col="0" ValueType="40">11</gnm:Cell><gnm:Cell Row="0" Col="1">=A1*3</gnm:Cell></gnm:Cells></gnm:Sheet></gnm:Sheets></gnm:Workbook>''')
original = fixture.read_bytes()
env = dict(os.environ, HOME=str(work/'home'), WERK_DATA=str(work/'data'),
XDG_CACHE_HOME=str(work/'cache'), XDG_CONFIG_HOME=str(work/'home/.config'),
XDG_DATA_HOME=str(work/'home/.local/share'), ENTITY_DATA=str(work/'entity'),
WERK_ASSETS=str(root/'build'), WORKBOOK_TEST_SELECTION=str(selector),
PATH=str(work/'bin')+':'+os.environ['PATH'])
app = None
window = None
def command(*args):
return subprocess.check_output(args, env=env, text=True, timeout=20)
def start():
global app, window
app = subprocess.Popen([str(root/'build/werk'), '--app', 'workbook'], env=env)
for _ in range(100):
assert app.poll() is None, 'Werkzeug exited'
found = subprocess.run(['xdotool','search','--onlyvisible','--pid',str(app.pid)], env=env, capture_output=True, text=True)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
command('xdotool','windowsize',window,'960','600')
command('xdotool','windowfocus','--sync',window)
time.sleep(.6)
return
time.sleep(.1)
raise AssertionError('No private Workbook window')
def stop():
if app and app.poll() is None:
app.terminate()
app.wait(timeout=10)
def click(x,y):
command('xdotool','mousemove','--window',window,str(x),str(y))
time.sleep(.1)
command('xdotool','click','1')
time.sleep(.35)
def key(value):
command('xdotool','key','--clearmodifiers',value)
time.sleep(.3)
def type_text(value):
command('xdotool','type','--clearmodifiers','--delay','30',value)
time.sleep(.3)
def cell(path,row=0,col=0):
data = path.read_bytes()
if data[:2] == b'\x1f\x8b': data = gzip.decompress(data)
doc = ET.fromstring(data)
for item in doc.iter('{http://www.gnumeric.org/v10.dtd}Cell'):
if item.get('Row') == str(row) and item.get('Col') == str(col): return item.text or ''
return ''
saved = work/'data/apps/workbook/documents/workbook.gnumeric'
def expect(value,row=0,col=0,path=saved):
for _ in range(80):
if path.exists() and cell(path,row,col) == value: return
time.sleep(.1)
raise AssertionError(f'Missing saved fixture value {value!r}')
def menu(word):
click(28,68)
picture = work/'menu.png'
command('import','-window',window,str(picture))
# Isolate the popup so spreadsheet grid lines do not dominate OCR.
target = work/'menu-labels.png'
factor = 3
with Image.open(picture) as image:
popup = image.crop((0,82,175,195))
popup.resize((popup.width*factor,popup.height*factor)).save(target)
text = command('tesseract',str(target),'stdout','--psm','6','-c','tessedit_create_tsv=1')
for item in csv.DictReader(io.StringIO(text), delimiter='\t'):
if word.lower() in item['text'].lower():
click((int(item['left'])+int(item['width'])//2)//factor,
82+(int(item['top'])+int(item['height'])//2)//factor)
return
raise AssertionError('Missing menu command '+word)
try:
start()
selection_picture = work/'selection.png'
command('import','-window',window,str(selection_picture))
with Image.open(selection_picture) as image:
pixels = image.convert('RGB')
assert pixels.getpixel((88,177)) != pixels.getpixel((184,177)), 'Selected cell needs a visible fill'
assert pixels.getpixel((40,177)) != pixels.getpixel((184,177)), 'Selected cell needs a visible outline'
assert pixels.getpixel((88,154)) != pixels.getpixel((184,177)), 'Headers need to be distinct from cells'
click(88,177)
type_text('5'); key('Return'); expect('5')
key('ctrl+z'); expect('')
key('ctrl+y'); expect('5')
bundle = work/'downloaded.zib'
selector.write_text(str(bundle)+'\n')
menu('Download')
for _ in range(50):
if bundle.exists(): break
time.sleep(.1)
assert bundle.read_bytes() == (root/'build/apps/workbook.zib').read_bytes(), 'Downloaded bytes differ'
selector.write_text(str(fixture)+'\n')
menu('Open')
expect('11'); expect('=A1*3',col=1)
assert fixture.read_bytes() == original, 'Import changed the chosen source'
exported = work/'export.gnumeric'
selector.write_text(str(exported)+'\n')
menu('As')
expect('11',path=exported); expect('=A1*3',col=1,path=exported)
invalid = work/'invalid.gnumeric'
invalid.write_text('invalid spreadsheet fixture')
selector.write_text(str(invalid)+'\n')
menu('Open')
time.sleep(.5)
expect('11'); expect('=A1*3',col=1)
click(88,177); type_text('7'); key('Return'); expect('7')
command('import','-window',window,str(work/'workbook.png'))
stop(); start()
click(88,199); type_text('9'); key('Return'); expect('9',row=1)
expect('7')
assert saved.stat().st_mode & 0o777 == 0o600
print('Workbook in Werkzeug: editing, undo/redo, bundle download, document import/export, failed-import preservation and restart passed')
finally:
stop()
+3 -3
View File
@@ -1,7 +1,7 @@
// Native Self recovery joins Werkzeug's existing account and Auth store.
// Native Entity recovery joins Werkzeug's existing account and Auth store.
// A switch is staged until its data choice is explicit and its writes succeed.
Recovery :: #import "self/recovery";
#import "self/recovery"
Recovery :: #import "entity/recovery";
#import "entity/recovery"
#import "daochi_client/keys"
#import "daochi_client/crypto"
#import "account"
+168 -23
View File
@@ -4,6 +4,8 @@
#import "std/bundle_host"
#import "std/byte_text_linux"
#import "std/text_buffer"
#import "std/vec"
#import "std/number_text"
#import "std/c_string"
#import "std/file"
#import "kryon/hosted_app"
@@ -20,8 +22,8 @@ using UI :: #import "kryon/Widgets";
#import "files"
#import "sha256"
#import "records"
#import "self_host"
#import "self_management"
#import "entity_host"
#import "entity_management"
#if !#defined(PLATFORM_WEB) {
#import "sync"
}
@@ -32,6 +34,12 @@ using UI :: #import "kryon/Widgets";
#import "android_fields"
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
Spreadsheet :: #import "workbook/service";
Font :: #import "kryon/font_metrics";
Picker :: #import "kryon/file_picker";
Json :: #import "std/json_scan";
}
using HostValueKind;
APP_LIMIT :: 8
@@ -51,6 +59,9 @@ App :: struct {
document_root: [PATH_LIMIT]u8
bundled: bool
started: bool
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
spreadsheet: Spreadsheet.Context
}
}
// What the running app sees this frame.
@@ -65,7 +76,7 @@ AppView :: struct {
apps: [APP_LIMIT]App;
app_count: s32;
self_index: s32 = -1;
entity_index: s32 = -1;
app_keyboard: bool;
// The app whose call the host is answering, for the asset policy.
running: s32 = -1;
@@ -94,7 +105,11 @@ AppCount :: () -> s32 {
AppServiceAllowed :: (context: *void, name: string) -> bool {
app := cast(*App)context
id := TextUntilNul(app.id[:])
if name == "self.assets" || name == "self.management" { return id == "self" }
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
if name == "spreadsheet.v1" { return app.bundled && id == "workbook" }
if name == "input.v1" || name == "document.pick.v1" || name == "app.bundle.export.v1" { return true }
}
if name == "entity.assets" || name == "entity.management" { return id == "entity" }
if name == "media.asset" || name == "media.query" || name == "media.pick" {
return AppLocalAllows(cast(*void)(*app.local), name)
}
@@ -295,11 +310,11 @@ AppCall :: (context: *void, module: *u8, function: *u8,
arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
app := cast(*App)context
name := TextFromCString(function)
if TextUntilNul(app.id[:]) == "self" && name == "AppServiceHost" && count == 2 && ArgumentText(arguments[0]) == "self.assets" {
if TextUntilNul(app.id[:]) == "entity" && name == "AppServiceHost" && count == 2 && ArgumentText(arguments[0]) == "entity.assets" {
ReturnText(result, TextUntilNul(app.asset_folder[:]))
return 1
}
if TextUntilNul(app.id[:]) == "self" && name == "AppServiceHost" && count == 2 && ArgumentText(arguments[0]) == "self.management" {
if TextUntilNul(app.id[:]) == "entity" && name == "AppServiceHost" && count == 2 && ArgumentText(arguments[0]) == "entity.management" {
request := ArgumentText(arguments[1])
if request == "" {
document := WerkManagementRead()
@@ -308,8 +323,8 @@ AppCall :: (context: *void, module: *u8, function: *u8,
} else { ReturnText(result, ifx WerkManagementEnqueue(request) then "queued" else "rejected") }
return 1
}
if TextUntilNul(app.id[:]) == "self" && name == "ReadStoreHost" && count == 2 && ArgumentText(arguments[0]) == "self.json" {
text := WerkSelfRead()
if TextUntilNul(app.id[:]) == "entity" && name == "ReadStoreHost" && count == 2 && ArgumentText(arguments[0]) == "entity.json" {
text := WerkEntityRead()
output := arguments[1]
used := cast(s32)text.count
if output.kind != cast(s32)HostSlice || output.elements == null || cast(usize)(used + 1) > output.length { return 0 }
@@ -321,8 +336,8 @@ AppCall :: (context: *void, module: *u8, function: *u8,
result.* = HostScalar("s32", used)
return 1
}
if TextUntilNul(app.id[:]) == "self" && name == "WriteStoreHost" && count == 2 && ArgumentText(arguments[0]) == "self.json" {
ReturnBool(result, WerkSelfWrite(ArgumentText(arguments[1])))
if TextUntilNul(app.id[:]) == "entity" && name == "WriteStoreHost" && count == 2 && ArgumentText(arguments[0]) == "entity.json" {
ReturnBool(result, WerkEntityWrite(ArgumentText(arguments[1])))
return 1
}
if name == "AppServiceHost" || name == "AppLocaleHost" || name == "DocumentReadHost" ||
@@ -335,6 +350,20 @@ AppCall :: (context: *void, module: *u8, function: *u8,
return 0
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
if name == "AppServiceHost" && count == 2 {
service := ArgumentText(arguments[0])
request := ArgumentText(arguments[1])
if service == "spreadsheet.v1" {
text := Spreadsheet.Call(*app.spreadsheet, *app.local.files, request)
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return 1
}
if service == "app.bundle.export.v1" { ReturnText(result, ExportBundle(app)); return 1 }
if service == "input.v1" { InputCall(app, request, result); return 1 }
if service == "document.pick.v1" { ReturnText(result, DocumentPick(app, request)); return 1 }
}
}
return AppLocalCall(cast(*void)(*app.local), module, function, arguments, count, result)
}
if name == "ReadStoreHost" && count == 2 {
@@ -465,15 +494,15 @@ UnpackAssets :: (app: *App) {
while index < count {
name := TextFromCString(BundleAssetPath(bundle, index))
prefix := "assets/"
self_picture := TextUntilNul(app.id[:]) == "self" &&
(name == "assets/self/pfp.png" || name == "assets/self/flowers.png")
entity_picture := TextUntilNul(app.id[:]) == "entity" &&
(name == "assets/entity/pfp.png" || name == "assets/entity/flowers.png")
flat_asset := name.count > prefix.count && name[0:prefix.count] == prefix && SafeName(name[prefix.count:name.count])
if self_picture || flat_asset {
if entity_picture || flat_asset {
data := TextFromBytes(BytesFromPointer(BundleAssetBytes(bundle, index), BundleAssetLength(bundle, index)))
path: [PATH_LIMIT]u8
if self_picture {
if entity_picture {
parent: [PATH_LIMIT]u8
if EnsureDirectory(PathJoin(parent[:], folder, "assets/self")) {
if EnsureDirectory(PathJoin(parent[:], folder, "assets/entity")) {
unused WritePrivate(PathJoin(path[:], folder, name), data)
}
} else {
@@ -555,16 +584,20 @@ LoadApps :: () {
path: [PATH_LIMIT]u8
unused LoadApp(ids[index], PathJoin(path[:], root, TextUntilNul(file[:])))
}
self_path: [PATH_LIMIT]u8
self_index = app_count
if !LoadApp("self", PathJoin(self_path[:], root, "self.zib")) { self_index = -1 }
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
workbook_path: [PATH_LIMIT]u8
unused LoadApp("workbook", PathJoin(workbook_path[:], root, "workbook.zib"))
}
entity_path: [PATH_LIMIT]u8
entity_index = app_count
if !LoadApp("entity", PathJoin(entity_path[:], root, "entity.zib")) { entity_index = -1 }
}
SelfAppIndex :: () -> s32 { return self_index }
SelfAppBack :: () -> bool {
if self_index < 0 { return false }
apps[self_index].portable.command = "back"
return AppContextRun(*apps[self_index].portable, APP_COMMAND) && apps[self_index].portable.reply == "handled"
EntityAppIndex :: () -> s32 { return entity_index }
EntityAppBack :: () -> bool {
if entity_index < 0 { return false }
apps[entity_index].portable.command = "back"
return AppContextRun(*apps[entity_index].portable, APP_COMMAND) && apps[entity_index].portable.reply == "handled"
}
AppFrameReply :: (index: s32) -> string {
@@ -636,6 +669,12 @@ SaveApps :: () -> bool {
// Explicit local bundle launch uses the same checked lifecycle as built-ins.
LoadExternalApp :: (path: string) -> s32 {
bytes, found := ReadBundle(path)
if !found { return -1 }
defer { AppFileFree(bytes) }
for current: 0..app_count - 1 {
if apps[current].bytes == bytes { return cast(s32)current }
}
index := app_count
return ifx LoadApp("", path) then index else -1
}
@@ -649,3 +688,109 @@ AppWidgetCall :: (context: *void, module: *u8, function: *u8,
return WidgetHostCall(context, module, function, arguments, count, result)
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
input_text: [8192]u8;
InputCall :: (app: *App, request: string, result: *HostValue) {
if request == "clipboard-has-text" { ReturnText(result, ifx SystemClipboardHasText() then "true" else "false"); return }
if request == "clipboard" {
text := SystemClipboardText(input_text[:])
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return
}
if request.count > 0 && request[0] == cast(u8)123 {
operation: [32]u8
used := Json.ReadStringText(request, Json.FieldAt(request, 0, "op"), operation[:])
if used == 7 && TextUntilNul(operation[:]) == "measure" {
content: [8192]u8
length := Json.ReadStringText(request, Json.FieldAt(request, 0, "text"), content[:])
if length >= 0 {
digits: [24]u8
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"width\":%}", Font.GlyphWidth(TextView(content[:length]), 14, ""))
value := BuilderFinish(bytes)
ReturnText(result, value); AppFileFree(value); return
}
}
}
if request != "frame" { ReturnText(result, "{}"); return }
session := app.portable.session
p := PointerSample(session); q := SecondaryPointerSample(session)
wheel := PointerWheelTake(session, app.portable.bounds)
text: Vec(u8)
BuilderPrint(*text, "{\"x\":%,\"y\":%,\"down\":%,\"pressed\":%,\"released\":%,\"secondary_down\":%,\"secondary_pressed\":%,\"secondary_released\":%,\"wheel\":%}",
cast(s32)p.x, cast(s32)p.y, ifx p.down then 1 else 0, ifx p.pressed then 1 else 0, ifx p.released then 1 else 0,
ifx q.down then 1 else 0, ifx q.pressed then 1 else 0, ifx q.released then 1 else 0, cast(s32)wheel)
value := BuilderFinish(text)
ReturnText(result, value)
AppFileFree(value)
}
// A picker grants just the selected transfer. Bundles never receive an
// arbitrary filesystem path; their editable copy remains in their folder.
DocumentPick :: (app: *App, request: string) -> string {
if request.count > 4096 { return "error" }
operation_bytes: [32]u8
name_bytes: [256]u8
filter_bytes: [256]u8
suggestion_bytes: [256]u8
operation := ServiceText(request, "op", operation_bytes[:])
name := ServiceText(request, "name", name_bytes[:])
if (operation != "import" && operation != "export") || !AppFileNameValid(name) { return "error" }
props: Picker.FilePickerProps
props.title = ifx operation == "export" then "Save document" else "Open document"
props.filter = ServiceText(request, "filter", filter_bytes[:])
props.suggested_name = ServiceText(request, "suggested_name", suggestion_bytes[:])
props.save = operation == "export"
path: [4096]u8
selected := Picker.PickFile(props, path[:])
if selected == 0 { return "cancelled" }
if selected != 1 { return "error" }
if operation == "export" {
value := AppFileRead(*app.local.files, name)
defer { AppFileFree(value) }
return ifx app.local.files.status == 1 && WritePrivate(TextUntilNul(path[:]), value) then "ready" else "error"
}
file := OpenRead(TextUntilNul(path[:]))
if !file.valid { return "error" }
defer { unused CloseFile(file) }
count := FileSize(file)
if count < 1 || count > 67108864 { return "error" }
bytes: Vec(u8)
chunk: [4096]u8
offset: s64 = 0
while offset < count {
used := ReadAt(file, chunk[:], offset)
if used <= 0 { return "error" }
for index: 0..used - 1 { if !VecPush(bytes, chunk[index]) { return "error" } }
offset += used
if offset > 67108864 { return "error" }
}
value := BuilderFinish(bytes)
defer { AppFileFree(value) }
return ifx AppFileWrite(*app.local.files, name, value) then "ready" else "error"
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
ExportBundle :: (app: *App) -> string {
name: [256]u8
CopyField(name[:], TextUntilNul(app.id[:]))
used := TextUntilNul(name[:]).count
suffix := ".zib"
for index: 0..3 { name[used + index] = suffix[index] }
name[used + 4] = 0
path: [4096]u8
props := Picker.FilePickerProps.{.title = "Download app bundle", .filter = "App bundle | *.zib", .save = true, .suggested_name = TextUntilNul(name[:])}
selected := Picker.PickFile(props, path[:])
if selected == 0 { return "cancelled" }
if selected != 1 { return "error" }
return ifx WritePrivate(TextUntilNul(path[:]), app.bytes) then "ready" else "error"
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
ServiceText :: (request: string, field: string, out: []u8) -> string {
count := Json.ReadStringText(request, Json.FieldAt(request, 0, field), out)
return ifx count >= 0 && count < out.count then TextView(out[:count]) else ""
}
}
+4 -9
View File
@@ -1,5 +1,5 @@
// The browser host. ?app=ID opens a tool at start. Embedded ?mini opens
// Pass first unless ?app selects another, with navigation to every tool.
// the home screen with every tool unless ?app selects one.
#import "werk"
#import "apps"
#import "browser_storage"
@@ -43,14 +43,9 @@ main :: () -> s32 {
}
WerkStart()
query := BrowserQuery()
if QueryValue(query, "mini") != "" {
selected := QueryValue(query, "app")
if selected == "" {
selected = "pass"
}
unused WerkOpen(selected, true)
} else if QueryValue(query, "app") != "" {
unused WerkOpen(QueryValue(query, "app"), false)
selected := QueryValue(query, "app")
if selected != "" {
unused WerkOpen(selected, QueryValue(query, "mini") != "")
}
ok: bool = true
while ok && Browser.PollCanvas() {
+21 -5
View File
@@ -8,7 +8,7 @@ using UI :: #import "kryon/Widgets";
#import "kryon/Frame"
sdl :: #system_library "SDL2";
SetTitle :: (window: *void, title: *u8) #foreign sdl "SDL_SetWindowTitle";
SetEnvironment :: (name: *u8, value: *u8, overwrite: s32) -> s32 #foreign sdl "SDL_setenv";
libc :: #system_library "libc";
WriteError :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
@@ -23,6 +23,7 @@ Report :: (message: string) {
}
DrawDesktop :: (session: Session) -> bool {
unused Desktop.DesktopSetTitle(WerkWindowTitle())
Desktop.BeginDesktopFrame()
// After BeginDesktopFrame, which applies a resize from the last frame.
viewport := Desktop.DesktopViewport()
@@ -60,6 +61,19 @@ main :: (argc: s32, argv: **u8) -> s32 {
return Command.RunCommand(argc, argv)
}
}
window_class: [64]u8
unused CopyCString("werk", window_class[:])
if argc >= 3 && TextFromCString(argv[1]) == "--app" {
id := TextFromCString(argv[2])
if id == "pass" { unused CopyCString("werk-pass", window_class[:]) }
if id == "auth" { unused CopyCString("werk-auth", window_class[:]) }
if id == "calculator" { unused CopyCString("werk-calculator", window_class[:]) }
if id == "clock" { unused CopyCString("werk-clock", window_class[:]) }
if id == "workbook" { unused CopyCString("werk-workbook", window_class[:]) }
}
hint: [32]u8
unused CopyCString("SDL_VIDEO_X11_WMCLASS", hint[:])
unused SetEnvironment(*hint[0], *window_class[0], 1)
if !Desktop.OpenDesktopSized(DESKTOP_WIDTH, DESKTOP_HEIGHT) {
Desktop.CloseDesktop()
Report("Werkzeug: could not open desktop\n")
@@ -69,9 +83,6 @@ main :: (argc: s32, argv: **u8) -> s32 {
Desktop.CloseDesktop()
return 1
}
title: [16]u8
unused CopyCString("Werkzeug", title[:])
SetTitle(Desktop.window, *title[0])
session := SessionOpen()
if !SessionValid(session) {
Desktop.CloseDesktop()
@@ -80,7 +91,12 @@ main :: (argc: s32, argv: **u8) -> s32 {
WerkStart()
// `werk --app auth` opens one tool first, as Harmony's Auth entry does.
if argc >= 3 && TextFromCString(argv[1]) == "--app" {
unused WerkOpen(TextFromCString(argv[2]), false)
if !WerkOpen(TextFromCString(argv[2]), false) {
Report("Werkzeug: app is unavailable\n")
SessionClose(session)
Desktop.CloseDesktop()
return 1
}
}
if argc >= 3 && TextFromCString(argv[1]) == "--bundle" {
index := LoadExternalApp(TextFromCString(argv[2]))
+14 -14
View File
@@ -1,6 +1,6 @@
// Werkzeug supplies its existing preferences to Self. Tool secrets and
// Werkzeug supplies its existing preferences to Entity. Tool secrets and
// account credentials never cross this document boundary.
Self :: #import "self/model";
Entity :: #import "entity/model";
#import "profile"
#import "std/c_string"
#import "std/text_buffer"
@@ -9,15 +9,15 @@ Self :: #import "self/model";
#import "sync"
#import "device_link"
#import "records"
Shared :: #import "self/native_files";
Shared :: #import "entity/native_files";
}
self_document: string;
entity_document: string;
WerkSelfRead :: () -> string {
Self.SelfFree(self_document)
state := Self.SelfDefault()
state.controls |= Self.SELF_APPEARANCE | Self.SELF_ACCENT | Self.SELF_WIDGETS
WerkEntityRead :: () -> string {
Entity.EntityFree(entity_document)
state := Entity.EntityDefault()
state.controls |= Entity.ENTITY_APPEARANCE | Entity.ENTITY_ACCENT | Entity.ENTITY_WIDGETS
state.name = profile.name
state.picture = profile.picture
state.theme = profile.theme_mode
@@ -35,14 +35,14 @@ WerkSelfRead :: () -> string {
#if !#defined(PLATFORM_WEB) {
if AccountReady() { state.owner_id = account.keys.public_id; unused Shared.SharedProfileLoad(AccountId(), *state) }
}
Self.SelfAddExtension(*state, "account", "Account")
self_document = Self.SelfEncode(state)
return self_document
Entity.EntityAddExtension(*state, "account", "Account")
entity_document = Entity.EntityEncode(state)
return entity_document
}
WerkSelfWrite :: (document: string) -> bool {
state: Self.SelfState
if !Self.SelfDecode(document, *state) { return false }
WerkEntityWrite :: (document: string) -> bool {
state: Entity.EntityState
if !Entity.EntityDecode(document, *state) { return false }
#if !#defined(PLATFORM_WEB) {
if TextUntilNul(state.owner_id[:]) != AccountId() { return false }
}
@@ -1,16 +1,16 @@
// Native capabilities for the common Self UI. Account keys, Auth records,
// Native capabilities for the common Entity UI. Account keys, Auth records,
// pairing payloads and file selections stay outside the portable bundle.
#import "std/c_string"
#import "std/text_buffer"
#import "std/vec"
#import "profile"
#if !#defined(PLATFORM_WEB) {
Self :: #import "self/model";
#import "self/management"
#import "self/native_management"
#import "self/recovery"
Pairing :: #import "self/pairing_client";
#import "self/pairing"
Entity :: #import "entity/model";
#import "entity/management"
#import "entity/native_management"
#import "entity/recovery"
Pairing :: #import "entity/pairing_client";
#import "entity/pairing"
#import "daochi_client/client"
#import "account"
#import "account_transition"
@@ -63,7 +63,7 @@
output.capabilities = ACCOUNT_CREATE | ACCOUNT_IMPORT | ACCOUNT_SWITCH | ACCOUNT_LINK
if AccountReady() { output.capabilities |= ACCOUNT_BACKUP | ACCOUNT_ALIAS | ACCOUNT_SYNC | ACCOUNT_LOGOUT | ACCOUNT_CLEAR_REMOTE }
status := SyncStatus()
// Without an account Self's title already says so; it explains the rest.
// Without an account Entity's title already says so; it explains the rest.
if status == "" && AccountReady() { status = ifx AccountSyncEnabled() then "Sync is on" else "Sync paused" }
unused CopyCString(status, output.status[:])
if RecordsOpen("auth") {
@@ -82,7 +82,7 @@
BuilderPrint(*message, "Compare this number on both devices: %", Pairing.device_link.confirmation)
text := BuilderFinish(message)
unused CopyCString(text, output.link_message[:])
Self.SelfFree(text)
Entity.EntityFree(text)
} else if output.link_stage == 4 { unused CopyCString("Send your account to this device?", output.link_message[:]) }
else if output.link_stage == 7 { unused CopyCString("The connection could not finish. Start a new code to try again.", output.link_message[:]) }
}
@@ -129,7 +129,7 @@
text: Vec(u8)
BuilderPrint(*text, "%\n%", AccountId(), TextUntilNul(request.value[:]))
document := BuilderFinish(text)
defer { Self.SelfFree(document) }
defer { Entity.EntityFree(document) }
if !WritePrivate(WerkAliasPath(path[:]), document) { return 0 }
unused CopyCString(TextUntilNul(request.value[:]), werk_management_alias[:])
return 1
+301
View File
@@ -0,0 +1,301 @@
// Werkzeug supplies tools and private preferences to the shared Apps screen.
#import "apps"
#import "platform"
#import "files"
#import "std/c_string"
#import "std/text_buffer"
#import "std/vec"
#import "std/json_scan"
#import "kryon/widget_host"
#import "kryon/app_files"
#import "kryon/app_protocol"
#import "std/bundle_host"
using UI :: #import "kryon/Widgets";
Launcher :: #import "apps/launcher";
Controller :: #import "apps/controller";
Rules :: #import "apps/protocol";
AppsControllerSha256 :: "8c5806d7ff5a4fdaf6b98a7668acbf0aad236ece1d5e68ffe1f7b268a1afb077";
HomePreference :: struct {
title: [256]u8
icon: [64]u8
favorite: bool
}
HomeState :: struct {
controller: Controller.AppController
view: Launcher.AppLauncherState
preferences: [APP_LIMIT]HomePreference
indices: [APP_LIMIT]s32
bytes: string
body: string
catalog: string
response: string
revision: s64
sequence: s64
status: string
selected: s32
session: Session
opened: s32
pending: Rules.AppsRequest
has_pending: bool
loaded: bool
unavailable: bool
}
home: HomeState;
HomeIndex :: (id: string) -> s32 {
for index: cast(s32)0..AppCount() - 1 {
if AppId(index) == id && id != "entity" { return index }
}
return -1
}
HomeTitle :: (index: s32) -> string {
title := TextUntilNul(home.preferences[index].title[:])
return ifx title == "" then AppName(index) else title
}
HomeIcon :: (index: s32) -> string {
choice := HomeIndex(TextUntilNul(home.preferences[index].icon[:]))
return AppIcon(ifx choice >= 0 then choice else index)
}
HomePreferencesPath :: (output: []u8) -> string {
folder: [PATH_LIMIT]u8
path := PathJoin(folder[:], DataRoot(), "profile")
if !EnsureDirectory(path) { return "" }
return PathJoin(output, path, "apps.json")
}
HomeBool :: (text: string, at: s32) -> bool { return at >= 0 && MatchLiteral(text, at, "true") }
HomeLoad :: () {
home.loaded = true
home.view.grid = true
path: [PATH_LIMIT]u8
bytes: [8192]u8
count := ReadPrivate(HomePreferencesPath(path[:]), bytes[:])
if count <= 0 { return }
text := TextView(bytes[:count])
if HomeBool(text, FieldAt(text, 0, "list")) { home.view.grid = false }
entries := FieldAt(text, 0, "apps")
at := Space(text, entries + 1)
for index: cast(s32)0..ArrayCount(text, entries) - 1 {
id: [128]u8
if Rules.AppsReadText(text, at, "id", id[:]) {
tool := HomeIndex(TextUntilNul(id[:]))
if tool >= 0 {
preference: HomePreference
if Rules.AppsReadText(text, at, "title", preference.title[:]) &&
Rules.AppTitleValid(TextUntilNul(preference.title[:])) &&
Rules.AppsReadText(text, at, "icon", preference.icon[:]) &&
(preference.icon[0] == 0 || HomeIndex(TextUntilNul(preference.icon[:])) >= 0) {
preference.favorite = HomeBool(text, FieldAt(text, at, "favorite"))
home.preferences[tool] = preference
}
}
}
at = Space(text, ValueEnd(text, at, 0))
if at < text.count && text[at] == cast(u8)44 { at = Space(text, at + 1) }
}
}
HomeSave :: () -> bool {
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"v\":1,\"list\":%,\"apps\":[", ifx home.view.grid then "false" else "true")
first := true
for index: cast(s32)0..AppCount() - 1 {
if AppId(index) == "entity" { continue }
if !first { BuilderPrint(*bytes, ",") }
first = false
BuilderPrint(*bytes, "{\"id\":")
Rules.AppsWriteQuoted(*bytes, AppId(index))
BuilderPrint(*bytes, ",\"title\":")
Rules.AppsWriteQuoted(*bytes, TextUntilNul(home.preferences[index].title[:]))
BuilderPrint(*bytes, ",\"icon\":")
Rules.AppsWriteQuoted(*bytes, TextUntilNul(home.preferences[index].icon[:]))
BuilderPrint(*bytes, ",\"favorite\":%}", ifx home.preferences[index].favorite then "true" else "false")
}
BuilderPrint(*bytes, "]}\n")
path: [PATH_LIMIT]u8
saved := WritePrivate(HomePreferencesPath(path[:]), TextView(VecSlice(bytes, 0, bytes.count)))
VecFree(bytes)
return saved
}
HomeReply :: (status: string) -> string {
AppFileFree(home.response)
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"v\":1,\"status\":\"%\",\"request\":%}", status, home.sequence)
home.response = BuilderFinish(bytes)
return home.response
}
HomeIcons :: (tool: s32) -> string {
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"v\":1,\"icons\":[{\"id\":\"\",\"shape\":")
Rules.AppsWriteQuoted(*bytes, AppIcon(tool))
BuilderPrint(*bytes, "}")
for index: cast(s32)0..AppCount() - 1 {
if AppId(index) == "entity" { continue }
BuilderPrint(*bytes, ",{\"id\":")
Rules.AppsWriteQuoted(*bytes, AppId(index))
BuilderPrint(*bytes, ",\"shape\":")
Rules.AppsWriteQuoted(*bytes, AppIcon(index))
BuilderPrint(*bytes, "}")
}
BuilderPrint(*bytes, "]}")
AppFileFree(home.response)
home.response = BuilderFinish(bytes)
return home.response
}
HomeService :: (context: *void, text: string) -> string {
request: Rules.AppsRequest
if !Rules.AppsReadRequest(text, *request) { return "" }
if request.operation == Rules.APPS_CATALOG {
if request.revision > 0 && request.revision == home.revision { return "{\"v\":1,\"unchanged\":true}" }
return home.catalog
}
if request.operation == Rules.APPS_STATUS {
if request.request != home.sequence { return "" }
return HomeReply(home.status)
}
tool := HomeIndex(TextUntilNul(request.id[:]))
if tool < 0 { return HomeReply("rejected") }
if request.operation == Rules.APPS_ICONS { return HomeIcons(tool) }
if home.has_pending || (request.operation != Rules.APPS_OPEN && request.operation != Rules.APPS_PIN &&
request.operation != Rules.APPS_UNPIN && request.operation != Rules.APPS_PROPERTIES) { return HomeReply("rejected") }
home.pending = request
home.has_pending = true
home.sequence += 1
home.status = "queued"
return HomeReply(home.status)
}
HomeDrain :: () {
if !home.has_pending { return }
home.has_pending = false
request := home.pending
index := HomeIndex(TextUntilNul(request.id[:]))
home.status = "rejected"
if index < 0 { return }
if request.operation == Rules.APPS_OPEN {
home.opened = index
home.status = "applied"
return
}
before := home.preferences[index]
if request.operation == Rules.APPS_PIN || request.operation == Rules.APPS_UNPIN {
home.preferences[index].favorite = request.operation == Rules.APPS_PIN
} else if request.operation == Rules.APPS_PROPERTIES {
if request.icon[0] != 0 && HomeIndex(TextUntilNul(request.icon[:])) < 0 { return }
home.preferences[index].title = request.title
home.preferences[index].icon = request.icon
} else { return }
if HomeSave() { home.status = "applied" }
else { home.preferences[index] = before }
}
HomeWidgets :: (context: *void, module: *u8, function: *u8,
arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
return AppWidgetCall(context, module, function, arguments, count, result)
}
HomeAssetAllowed :: (path: string) -> bool { return path == "" }
HomeCards :: (context: *void, indices: []s32, bounds: Rectangle,
input: TextFieldInput, section_break: s32, columns: s32) -> bool {
bytes: Vec(u8)
BuilderPrint(*bytes, "\"title\":\"Werkzeug\",\"locale\":\"en\",\"presentation\":{\"mode\":\"%\",\"columns\":%",
ifx home.view.grid then "icon" else "list", columns)
if section_break >= 0 { BuilderPrint(*bytes, ",\"section_break\":%", section_break) }
BuilderPrint(*bytes, "},\"children\":[")
for at: cast(s32)0..cast(s32)indices.count - 1 {
index := home.indices[indices[at]]
if at > 0 { BuilderPrint(*bytes, ",") }
BuilderPrint(*bytes, "{\"id\":")
Rules.AppsWriteQuoted(*bytes, AppId(index))
BuilderPrint(*bytes, ",\"title\":")
Rules.AppsWriteQuoted(*bytes, HomeTitle(index))
BuilderPrint(*bytes, ",\"original_title\":")
Rules.AppsWriteQuoted(*bytes, AppName(index))
BuilderPrint(*bytes, ",\"icon_choice\":")
Rules.AppsWriteQuoted(*bytes, TextUntilNul(home.preferences[index].icon[:]))
BuilderPrint(*bytes, ",\"icon_shape\":")
Rules.AppsWriteQuoted(*bytes, HomeIcon(index))
BuilderPrint(*bytes, ",\"installed\":true,\"on_device\":true,\"favorite\":%,\"selected\":%,\"bytes\":%,\"actions\":[\"open\",\"%\",\"properties\"]}",
ifx home.preferences[index].favorite then "true" else "false", ifx index == home.selected then "true" else "false",
apps[index].bytes.count, ifx home.preferences[index].favorite then "unpin" else "pin")
}
BuilderPrint(*bytes, "]}")
body := BuilderFinish(bytes)
if body == home.body { AppFileFree(body) }
else {
AppFileFree(home.body)
home.body = body
home.revision += 1
catalog: Vec(u8)
BuilderPrint(*catalog, "{\"v\":1,\"revision\":%,%", home.revision, home.body)
AppFileFree(home.catalog)
home.catalog = BuilderFinish(catalog)
}
home.controller.app.session = home.session
home.controller.app.bounds = bounds
home.controller.app.input = input
WidgetHostBegin(home.controller.app.session, HomeAssetAllowed)
ran := Controller.AppControllerRun(*home.controller, APP_FRAME)
WidgetHostEnd()
return ran
}
SharedHome :: (session: Session, bounds: Rectangle, dark: bool, selected: s32,
input: TextFieldInput, key: s32, modifiers: s32) -> bool {
if !home.loaded { HomeLoad() }
home.opened = -1
if home.unavailable { return false }
if !home.controller.ready {
path: [PATH_LIMIT]u8
bytes, found := ReadBundle(PathJoin(path[:], BundledAppsRoot(), "apps.zib"))
if !found { home.unavailable = true; return false }
home.bytes = bytes
if !Controller.AppControllerOpen(*home.controller, home.bytes, AppsControllerSha256,
Controller.AppControllerPlatform.{.service = HomeService, .widgets = HomeWidgets}) {
home.unavailable = true
return false
}
}
home.session = session
home.selected = selected
home.controller.app.dark = dark
home.controller.app.scale = 1.0
home.controller.app.font = 16
home.controller.app.key = key
home.controller.app.modifiers = modifiers
count: s32
items: [APP_LIMIT]Launcher.AppLauncherItem
titles: [APP_LIMIT][256]u8
for index: cast(s32)0..AppCount() - 1 {
if AppId(index) == "entity" { continue }
home.indices[count] = index
unused CopyCString(HomeTitle(index), titles[count][:])
items[count] = Launcher.AppLauncherItem.{.title = TextUntilNul(titles[count][:]),
.search = AppName(index), .favorite = home.preferences[index].favorite}
count += 1
}
area := Rectangle.{bounds.x + 16.0, bounds.y + 12.0, bounds.width - 32.0, bounds.height - 24.0}
result := Launcher.AppLauncherScreen(session, *home.view,
Launcher.AppLauncherProps.{.bounds = area, .scale = 1.0, .locale = "en", .input = input,
.cards = HomeCards}, items[:count])
if result.clipboard_write { unused SetClipboard(TextUntilNul(result.clipboard_text[:])) }
if result.changed { unused HomeSave() }
HomeDrain()
AppFileFree(home.response)
home.response = ""
return result.ran
}
SharedHomeOpened :: () -> s32 { return home.opened }
SharedHomeKeyboard :: () -> bool { return home.view.focused || home.controller.app.keyboard }
+1 -1
View File
@@ -1 +1 @@
Version :: "0.4.0";
Version :: "0.4.2";
+33 -49
View File
@@ -8,7 +8,8 @@ using UI :: #import "kryon/Widgets";
#import "kryon/ScrollDevice"
#import "kryon/Theme"
#import "apps"
#import "self_management"
#import "home"
#import "entity_management"
#import "profile"
#import "platform"
#import "migrate"
@@ -36,8 +37,8 @@ FieldState :: struct {
}
screen: s32;
self_account: bool;
self_reload: bool;
entity_account: bool;
entity_reload: bool;
open_app: s32 = -1;
// Started in a page embedding the toolkit, with navigation still available.
mini: bool;
@@ -96,6 +97,12 @@ WerkOpen :: (id: string, alone: bool) -> bool {
return false
}
// The desktop shell uses the open tool's name for its window title.
WerkWindowTitle :: () -> string {
if screen == SCREEN_APP && open_app >= 0 { return AppName(open_app) }
return "Werkzeug"
}
// Whether the touch keyboard should show.
WerkKeyboard :: () -> bool {
return keyboard_wanted
@@ -121,7 +128,7 @@ OpenHome :: () {
return
}
if screen == SCREEN_PROFILE {
if !self_account && !SaveApp(SelfAppIndex()) { return }
if !entity_account && !SaveApp(EntityAppIndex()) { return }
name_field.focused = false
code_field.focused = false
node_field.focused = false
@@ -145,10 +152,10 @@ TopBar :: (session: Session, viewport: Rectangle) {
.icon_shape = Back.Shape, .icon_only = true,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, back) != 0 {
if screen == SCREEN_PROFILE && !self_account && SelfAppBack() { return }
if screen == SCREEN_PROFILE && self_account {
self_account = false
self_reload = true
if screen == SCREEN_PROFILE && !entity_account && EntityAppBack() { return }
if screen == SCREEN_PROFILE && entity_account {
entity_account = false
entity_reload = true
return
}
OpenHome()
@@ -156,7 +163,7 @@ TopBar :: (session: Session, viewport: Rectangle) {
}
left = bar.x + 56.0
title = ifx screen == SCREEN_APP then AppName(open_app) else "Profile"
if screen == SCREEN_PROFILE && self_account { title = "Account" }
if screen == SCREEN_PROFILE && entity_account { title = "Account" }
}
// The profile button names itself, with the picture beside the name.
profile_width: float32 = 0.0
@@ -173,47 +180,24 @@ TopBar :: (session: Session, viewport: Rectangle) {
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, avatar) != 0 {
screen = SCREEN_PROFILE
self_account = false
self_reload = true
entity_account = false
entity_reload = true
}
}
}
Home :: (session: Session, area: Rectangle) {
visible := AppCount() - ifx SelfAppIndex() >= 0 then 1 else 0
tile: float32 = 120.0
gap: float32 = 16.0
columns := cast(s32)((area.width - gap) / (tile + gap))
if columns < 2 {
columns = 2
tile = (area.width - gap * 3.0) / 2.0
}
if columns > visible && visible > 0 {
columns = visible
}
if visible == 0 {
Label(session, cast(u64)20, "No apps are installed.", Rectangle.{area.x + 16.0, area.y + 16.0,
area.width - 32.0, 24.0}, 16)
return
}
row_width := cast(float32)columns * tile + cast(float32)(columns - 1) * gap
left := area.x + (area.width - row_width) * 0.5
index: s32 = 0
while index < AppCount() {
if AppId(index) == "self" { index += 1; continue }
column := cast(float32)(index % columns)
row := cast(float32)(index / columns)
bounds := Rectangle.{left + column * (tile + gap), area.y + gap + row * (tile + gap), tile, tile}
props := ButtonProps.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
.label = AppName(index), .icon_shape = AppIcon(index),
.icon_placement = IconPlacement.IconPlacementAbove,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, props) != 0 {
open_app = index
Home :: (session: Session, area: Rectangle, input: TextFieldInput, key: s32, modifiers: s32) {
if SharedHome(session, area, ProfileDark(), open_app, input, key, modifiers) {
opened := SharedHomeOpened()
if opened >= 0 {
open_app = opened
screen = SCREEN_APP
}
index += 1
keyboard_wanted = SharedHomeKeyboard()
return
}
Label(session, cast(u64)20, "Apps are unavailable.",
Rectangle.{area.x + 16.0, area.y + 16.0, area.width - 32.0, 28.0}, 16)
}
// Applies a text field's edit to a terminated buffer.
@@ -344,7 +328,7 @@ RevealFocusedField :: (area: Rectangle) {
}
ProfileScreen :: (session: Session, area: Rectangle, input: TextFieldInput, key: s32, modifiers: s32) {
if self_account {
if entity_account {
width := area.width - 32.0
scroll := Scroll(session, ScrollProps.{.key = cast(u64)40,
.bounds = Rectangle.{area.x + 16.0, area.y, width, area.height},
@@ -357,21 +341,21 @@ ProfileScreen :: (session: Session, area: Rectangle, input: TextFieldInput, key:
keyboard_wanted = code_field.focused || account_key_field.focused || passphrase_field.focused
return
}
index := SelfAppIndex()
if self_reload { ReloadApp(index); self_reload = false }
index := EntityAppIndex()
if entity_reload { ReloadApp(index); entity_reload = false }
container := Group(session, ColumnProps.{.key = cast(u64)69, .bounds = area})
if !container.opened { return }
ran := index >= 0 && RunApp(index, AppView.{.session = session, .bounds = area,
.dark = ProfileDark(), .key = key, .modifiers = modifiers, .input = input})
unused End(session)
if !ran {
Label(session, cast(u64)40, "Self could not be loaded", area, 16)
Label(session, cast(u64)40, "Entity could not be loaded", area, 16)
return
}
keyboard_wanted = AppWantsKeyboard()
if AppFrameReply(index) == "account" {
unused CopyCString(ProfileNode(), node_text[:])
self_account = true
entity_account = true
profile_scroll = 0
}
}
@@ -727,7 +711,7 @@ WerkFrame :: (session: Session, viewport: Rectangle) -> s32 {
TopBar(session, viewport)
content = Rectangle.{viewport.x, viewport.y + BAR_HEIGHT, viewport.width, viewport.height - BAR_HEIGHT}
if screen == SCREEN_HOME {
Home(session, content)
Home(session, content, input, key, modifiers)
} else if screen == SCREEN_PROFILE {
ProfileScreen(session, content, input, key, modifiers)
} else if screen == SCREEN_APP && open_app >= 0 {
@@ -6,7 +6,7 @@
#import "files"
#import "platform"
#import "sync_keys"
#import "self/recovery"
#import "entity/recovery"
#import "daochi_client/keys"
#import "std/file"
#import "std/c_string"
+62 -30
View File
@@ -2,13 +2,12 @@
"format": 1,
"packages": [
{
"commit": "d1895c3799005122b2e68f47f442cc5ba709d866",
"dependencies": {},
"id": "p0bd527640057f7d4",
"name": "monocypher",
"commit": "ac9489451a93903030c50550a99ce234a49716ce",
"dependencies": {"oqs": "p7098ac9cd92f7e5f"},
"id": "p0cff069893bdc938",
"name": "DaochiClient",
"ref": "master",
"source": true,
"url": "https://github.com/LoupVaillant/Monocypher.git"
"url": "https://github.com/ziranlang/daochi-client.git"
},
{
"commit": "2944b2e668e735438d8ce24e47a39be3f5c36af5",
@@ -18,6 +17,31 @@
"ref": "master",
"url": "https://github.com/ziranlang/qrcode.git"
},
{
"commit": "6a5f6189ca51e45a59c9ef77c4ec4112393225e0",
"dependencies": {"kryon": "pc9c8f901448f635c", "kss": "p1b13dda539ed2a39", "mingcute": "pe1027b9d16704793"},
"id": "p0e0131936e76f979",
"name": "workbook",
"ref": "master",
"url": "https://github.com/waozixyz/workbook.git"
},
{
"commit": "1cb9df183089a77c8a16448a556186f30b261a98",
"dependencies": {"kryon": "pc9c8f901448f635c"},
"id": "p1b13dda539ed2a39",
"name": "Kss",
"ref": "master",
"url": "https://github.com/kryonlabs/kss.git"
},
{
"commit": "e1f480f382d9443c4412133b55948374c77a5c21",
"dependencies": {},
"id": "p4b0a50b49959e674",
"name": "liboqs",
"ref": "main",
"source": true,
"url": "https://github.com/open-quantum-safe/liboqs.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"dependencies": {},
@@ -27,34 +51,35 @@
"source": true,
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "1ce89cff5a807cca817aec5d1347e18d2f229b27",
"dependencies": {"daochi_client": "pd5ac70667dc1e0bd", "kryon": "pdea5c7ef014ed1a7", "monocypher": "p0bd527640057f7d4", "qrcode": "p0dfa70137405b096"},
"id": "p6bdf184e35c8cf13",
"name": "Self",
"ref": "master",
"url": "https://github.com/waozixyz/self.git"
},
{
"commit": "22d2ddbdc236796953c905a05a2cebf5ab1b4ff3",
"dependencies": {"liboqs": "pfb3df7cb222b1bdc"},
"dependencies": {"liboqs": "p4b0a50b49959e674"},
"id": "p7098ac9cd92f7e5f",
"name": "Oqs",
"ref": "master",
"url": "https://github.com/ziranlang/oqs.git"
},
{
"commit": "42aa3ee773d8abdc6b3a10fbcb1b73c992f0f564",
"dependencies": {"oqs": "p7098ac9cd92f7e5f"},
"id": "pd5ac70667dc1e0bd",
"name": "DaochiClient",
"commit": "f5f0a19a5dc6c14a49adb3cd63ea79a60f6ba77b",
"dependencies": {},
"id": "p809b4d31a48625a3",
"name": "monocypher",
"ref": "master",
"url": "https://github.com/ziranlang/daochi-client.git"
"source": true,
"url": "https://github.com/LoupVaillant/Monocypher.git"
},
{
"commit": "a78576db722b25216e0096870d313b7d2ace96b0",
"commit": "f7449b379540f6f6f53c64c980cb5d4d4abcf399",
"dependencies": {"daochi_client": "p0cff069893bdc938", "kryon": "pc9c8f901448f635c", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "pb7942f184eef21db",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "b1d4faa4de66ff799c8907ba131061be979bcc7a",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "pdea5c7ef014ed1a7",
"id": "pc9c8f901448f635c",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
@@ -68,21 +93,28 @@
"url": "https://github.com/kryonlabs/mingcute.git"
},
{
"commit": "fd44469daeffe6b28f031f54f9bb66cbae69a572",
"commit": "08bbad051379813d0fd1c3bb7bb6814f3491da75",
"dependencies": {},
"id": "pfb3df7cb222b1bdc",
"name": "liboqs",
"ref": "main",
"source": true,
"url": "https://github.com/open-quantum-safe/liboqs.git"
"id": "pf039d7a776333200",
"name": "crypto",
"ref": "master",
"url": "https://github.com/ziranlang/crypto.git"
},
{
"commit": "d016377ab37ba4fb754a799569e15a4c0d195b90",
"dependencies": {"crypto": "pf039d7a776333200", "kryon": "pc9c8f901448f635c"},
"id": "pf87aa276a2b568b4",
"name": "Apps",
"ref": "master",
"url": "https://github.com/waozixyz/apps.git"
}
],
"root": {
"dependencies": {"daochi_client": "pd5ac70667dc1e0bd", "kryon": "pdea5c7ef014ed1a7", "liboqs": "pfb3df7cb222b1bdc", "mingcute": "pe1027b9d16704793", "monocypher": "p0bd527640057f7d4", "oqs": "p7098ac9cd92f7e5f", "self": "p6bdf184e35c8cf13"},
"dependencies": {"apps": "pf87aa276a2b568b4", "daochi_client": "p0cff069893bdc938", "entity": "pb7942f184eef21db", "kryon": "pc9c8f901448f635c", "liboqs": "p4b0a50b49959e674", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "workbook": "p0e0131936e76f979"},
"name": "Werkzeug"
},
"toolchain": {
"commit": "1ad0264d9f6ce3df29e9071ab16eae0e1e557049",
"commit": "ec43f576478d4a0028d560be560585749a92f3ed",
"ref": "master",
"url": "https://github.com/ziranlang/ziran.git"
}
+10 -2
View File
@@ -12,6 +12,10 @@ ref = "master"
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
[dependencies.apps]
git = "https://github.com/waozixyz/apps.git"
ref = "master"
[install]
bin = "werk"
@@ -44,6 +48,10 @@ git = "https://github.com/LoupVaillant/Monocypher.git"
ref = "master"
source = true
[dependencies.self]
git = "https://github.com/waozixyz/self.git"
[dependencies.entity]
git = "https://github.com/waozixyz/entity.git"
ref = "master"
[dependencies.workbook]
git = "https://github.com/waozixyz/workbook.git"
ref = "master"