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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Entity is pinned at its node picture reader; the lock follows Kryon master,
which changes the Apps controller bundle, so its digest is re-pinned from
the locked build.
2026-10-30 00:57:32 -03:00
waozi a2a7b97f7c Pin the Apps controller built with Kryon edffc8bf
The Entity lock bump moved Kryon, which changes the shared Apps controller
bundle; this is its digest from the locked build.
2026-10-29 23:16:09 -03:00
waozi 98d732c367 Send the chosen profile picture to the node through Entity
Werkzeug kept its profile picture on this device only, so friends saw a
default picture. A picture chosen in Profile now goes to the account's
node through Entity's shared publisher, retrying while offline, and is
sent once per choice. Profiles saved earlier with a picture other than
the first count it as chosen.
2026-10-29 23:05:13 -03:00
waozi 0199559631 Check that the Android APKs hold no Google library
Kryon's google-free action fails the release build when a Gradle file
names a Google library outside a Google Play edition or an APK holds one.
2026-10-29 16:10:51 -03:00
waozi 2a38d480a4 Wait for Workbook UI updates in platform tests 2026-10-28 14:56:37 -03:00
waozi 53cb190de7 Cover Workbook transfers on the Google Android emulator 2026-10-28 14:32:39 -03:00
waozi b2ddcb69a8 Keep bundle runtime caches matched to their toolchain 2026-10-28 13:15:42 -03:00
waozi a69631e327 Release Werkzeug 0.4.7 with Workbook on every platform 2026-10-28 12:56:43 -03:00
waozi dd550dd58b Verify the shared profile document without confusing favicon requests 2026-10-28 04:19:25 -03:00
waozi 36fd01fe5d Open the shared browser profile after the active tool has saved 2026-10-28 04:07:42 -03:00
waozi 0cb5600c14 Load the shared browser profile from the Ziran host 2026-10-28 03:54:01 -03:00
waozi ead336b215 Format the shared browser profile readiness condition 2026-10-28 03:48:57 -03:00
waozi 6cea9233ef Use the shared Waozi browser profile and Entity manager 2026-10-28 03:48:29 -03:00
waozi fbd7c4038a Select the Add action below the node input in Android tests 2026-10-27 03:52:56 -03:00
waozi 7bfa8fef2b Follow the shared Profile Nodes flow in the Android test 2026-10-27 03:08:45 -03:00
waozi bee76ab379 Read small dark-theme labels in the Android input test 2026-10-27 02:51:21 -03:00
waozi d8284a83e0 Pin the Apps controller built with Kryon 0931212f
Werkzeug 0.4.6 moved Kryon with Entity ca637d0, which changes the shared
Apps controller bundle; this is its digest from the locked build.
2026-10-27 02:19:43 -03:00
waozi f2dad4b37f Release Werkzeug 0.4.6
Entity ca637d0 saves account aliases typed with capitals, an @ or spaces
and says when an alias is taken.
2026-10-27 02:03:08 -03:00
waozi 40f2cdf731 Retry Android SDK downloads across build workflows 2026-10-26 20:06:30 -03:00
waozi b193cbfa9f Fix Android native app startup with private runtime directories 2026-10-26 19:46:29 -03:00
waozi 4e139b3ffb Identify Android controller integrity failures 2026-10-26 19:25:17 -03:00
waozi a5e69bb227 Report Android Apps controller startup failures 2026-10-26 18:04:35 -03:00
waozi b0003dc032 Capture private emulator asset diagnostics on test failure 2026-10-26 17:47:14 -03:00
waozi e26d26f5db Fix workflows for the root web app and retry Android SDK setup 2026-10-26 17:29:40 -03:00
waozi a45fd1d3ed Open the card embed page beside the root app in the browser test 2026-10-26 02:47:32 -03:00
waozi 2e5d765962 Check the site's root app files in the Pages build 2026-10-26 02:38:57 -03:00
waozi 4d499720d8 Make werk.waozi.xyz the web app itself
The site serves Werkzeug at its root instead of a separate landing page;
/app/ forwards there and download links keep their addresses. Browser
storage is per origin, so saved vaults stay.
2026-10-26 02:32:31 -03:00
waozi ae502a322d Build Auth from its package and hash with the crypto package: manifest, lock, Makefile, Pass, the host, tests, Android sources and docs 2026-10-24 23:43:18 -03:00
waozi 1a4e0e0891 Auth comes from its own Ziran package (waozixyz/auth) and SHA-256 and PBKDF2 from the crypto package, replacing apps/auth and shared/; Pass keeps reading at most 508 salt bytes, as existing vault keys need 2026-10-24 23:43:05 -03:00
waozi 3b8c4eaf64 Use Kryon shared app and render stages on Android
Compose Werkzeug frames through the shared Android pipeline and drain it before closing app state. Preserve the native linker callbacks during source generation. Pin the verified Kryon and Ziran revisions and the regenerated Apps controller validated by its native behavior fixture.
2026-10-24 06:40:35 -03:00
waozi 60a68d258a Add the Werkzeug 0.4.4 build to the F-Droid recipe
Matches fdroiddata merge request 53909. New release tags are added by
F-Droid's update checker, which copies this build for each tag.
2026-10-24 02:17:58 -03:00
waozi 0a2ab3bb45 Show only the tools as large tiles in mini mode
The ?mini embed and desktop --mini now open on the tool tiles alone, with no
Profile, search or title bar. Opening a tool keeps its bar with Back, which
returns to the tiles. Mini mode is read with Kryon's shared mini_embed.
2026-10-24 02:04:09 -03:00
waozi b9a6c6d350 Remove the Plan 9 build of the pass command 2026-10-23 22:10:21 -03:00
waozi b53050764b Keep F-Droid dependency handling upstream 2026-10-23 20:54:23 -03:00
waozi b8722b6b28 Restore compatible Werkzeug updates and reproducible builds
Keep the original Android package and signing identity for in-place Pass updates, align the portable bundles and locked toolchain, and make native builds reproducible. Fix staged installation, desktop tool icons and navigation tests.
2026-10-23 19:59:51 -03:00
waozi 26047247f9 Prepare the Werkzeug package migration and correct mobile input navigation 2026-10-23 18:53:22 -03:00
waozi c801c62542 Use xyz.waozi.werk as the Werkzeug Android application ID 2026-10-23 18:26:55 -03:00
waozi 7601d7c58c Keep private launcher displays stable across restarts 2026-10-23 18:22:03 -03:00
waozi 47d77ab0ad Use a compact Apps presentation without package sizes 2026-10-23 18:17:46 -03:00
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
waozi 0d2c2b3a88 Make the Android input test follow density and other apps' dialogs
Werkzeug scales by screen density, not width, so on CI's 320x640 mdpi
emulator every tap landed above its field. Read Android 12's ITYPE inset
names, and close another app's "isn't responding" dialog, which covered
Werkzeug on CI.
2026-10-19 18:12:32 -03:00
waozi 440da3f967 Unlock vaults wrapped with spaces or tabs on OpenSSL 3.0
OpenSSL 3.0 rejects whitespace inside single-line base64, so legacy vaults
wrapped with spaces, tabs or CRLF failed to decrypt on Debian 12 and
Ubuntu 22.04. The pass command now reads the vault, drops the whitespace
and gives openssl the result through a pipe; stdin still carries only the
passphrase.
2026-10-19 18:12:32 -03:00
waozi a63ff0658c Install GTK's development files for the desktop build
The desktop app links GTK for its native file dialog. Without
libgtk-3-dev, pkg-config failed for every library and CI's link missed
SDL, Cairo and GTK alike.
2026-10-19 18:12:32 -03:00
waozi 503995197d Release 0.4.0 with Werkzeug's own store text and screenshots
Shorten the changelog, describe today's tools on F-Droid and drop the old
Pass name from the store text and README. Replace the old Pass generator
screenshots with Werkzeug's home screen, Pass, Auth, Calculator, Clock and
Profile, and link the website's APK and Linux downloads by werk names.
2026-10-19 17:49:36 -03:00
waozi c64c6bfa91 Fit the Android input test to display cutouts and Self's profile
Werkzeug starts below a display cutout taller than the status bar, so the
test's taps landed above each field. Profile is now Self's card: the Name
field moved and a custom node is added with Node address and Add.
2026-10-19 17:49:31 -03:00
waozi e0cbc46bf2 Match package-qualified text field modules in the Android editor bridge
Bundles built as packages name the widget module with a package prefix, as
Kryon's widget host already accepts. External bundles' text fields now get
Android keyboard input too.
2026-10-19 17:49:31 -03:00
waozi 2007fbd0ed Centre Auth's countdown and stop repeating Profile's missing account
Auth's seconds left now sit level with their code. Without an account,
Profile showed "No account connected" twice; Self's own explanation now
follows the title.
2026-10-19 17:49:31 -03:00
waozi 101247ccd7 Keep Profile working after a file dialog on decimal-comma desktops
Self failed on every frame after a file dialog opened when the desktop's
language writes decimals with a comma: GTK switched the process locale and
the portable interpreter read 0.25 as 0. Ziran now parses and prints float
text with '.' whatever the locale, and Kryon's file dialog restores the
host's locale. Update the lock to both fixes and current Daochi client and
Monocypher.
2026-10-19 17:49:31 -03:00
waozi a90700d08c Repin packages to the rewritten history 2026-10-19 11:51:57 -03:00
waozi 005b0ddef1 Complete shared Self account management in Werkzeug 2026-10-18 18:21:29 -03:00
waozi 67937e6eec Bundle all tools and use the shared Self profile 2026-10-18 16:22:12 -03:00
waozi 667b6eb8fe Preserve queued text when commands or window close arrive 2026-10-18 15:05:22 -03:00
waozi b4d7720ce4 Run Werkzeug tools and external apps through the shared Kryon contract 2026-10-18 14:54:13 -03:00
waozi c681f186c4 Import an authenticator export file or a picture of its QR code in Auth
On the desktop, Auth's Import file asks zenity for a file and the host
reads its text, or decodes the QR codes of a PNG or JPEG, through the new
FileImport host call; phones and the browser report it unavailable and the
button stays hidden there. The GUI test chooses a fixture Aegis export
through a zenity stand-in.
2026-10-16 23:55:37 -03:00
waozi e954637927 List Auth imports, editing, account keys and the werk command in 0.4.0 2026-10-16 12:50:07 -03:00
waozi 2ef4abeb1f Sign in to Werkzeug with a Daochi account key, such as Inbe's
Profile on the desktop and werk sync key accept a plain or
passphrase-protected Daochi account key. The vault key derives from the
account key, so every device signed in with it opens the same Auth
accounts, and Werkzeug can share Inbe's account. werk --app ID opens the
window on one tool.
2026-10-16 12:17:20 -03:00
waozi 8bd48e39cc Import authenticator exports into Auth, edit accounts, and run Auth without a window
Auth reads Google Authenticator export links (and their QR images from the
command), Aegis's unencrypted JSON and Ente Auth's list of otpauth links,
and refuses encrypted exports. Edit renames an account, keeps the websites
where it signs in and holds Remove. werk sync and werk auth create or join
the Daochi account, list accounts without secrets, print a current code,
and import, rename or remove accounts on devices without a screen.
2026-10-16 02:28:14 -03:00
waozi a548c55e54 Date the 0.4.0 release 2026-10-15 16:19:57 -03:00
waozi 7fb12407e2 Document Werkzeug F-Droid follow-up and draft handoff 2026-10-15 02:29:36 -03:00
waozi 9396dfe752 Apply Werkzeug logo and add optional node settings and mini navigation 2026-10-15 02:14:17 -03:00
waozi 4286940564 Prepare F-Droid recipe for Werkzeug rename and 0.3.1 2026-10-15 01:43:25 -03:00
waozi e0cc0dc5f5 Bundle a fuller Noto Sans with math operators for Android before 10
Phones older than Android 10 draw text only from the bundled font, a
357-glyph subset that showed the scientific Calculator's π, √ and
superscripts as question marks. The new subset of Noto Sans adds Greek,
Cyrillic, modifier letters, super- and subscripts, punctuation, arrows
and Noto Sans Math's operators, with the old vertical metrics.
2026-10-13 23:52:50 -03:00
waozi b77cbfabfb Release 0.4.0: scientific Calculator, and Clock no longer freezes the web version
Calculator gains a Scientific mode: trigonometry in degrees or radians with
inverse and hyperbolic forms, powers, roots, ln, log, factorials, π, e,
Ans and E notation, on Ziran's new std/math. The locked Ziran also reads
the clock with Emscripten's 64-bit time_t, whose 32-bit binding trapped
and froze the page when Clock read the time zone. The browser smoke test
now opens Clock.
2026-10-13 23:39:59 -03:00
waozi 7c4fc18a07 Release 0.3.1: package the whole web app for itch.io
The itch.io build's page loads content-hashed script and Wasm names, which
the release left out, so it opened to a blank page.
2026-10-13 19:07:31 -03:00
waozi 6b0f219f7e Fix the Android release build, browser smoke test and IR core test in CI
The release passes the liboqs and Monocypher sources to Gradle as make does,
the browser test reads the browser CI names and waits for Chromium's first
tab, and the saved-IR test roots its module where every toolchain writes it.
2026-10-13 15:35:27 -03:00
waozi 98d10e86bb Keep the Werkzeug name, add its wrench logo and move to werk.waozi.xyz
Werkzeug stays the app's name; werk is its short form for the repository,
files, packages and the werk.waozi.xyz website. A new logo, a wrench with
a keyhole, replaces Pass's asterisk on every icon and image.
2026-10-13 15:17:37 -03:00
waozi c6db1e5fff Rename Werkzeug to Werk
The app, its window and launcher, packages, release files, website,
store listing, wordmarks and source now say Werk; the GitHub repository
is waozixyz/werk and the itch.io page waozi.itch.io/werk. Daochi keeps the
registered app id and record domains under the former name, and Android
keeps the package xyz.waozi.pass, so devices stay linked and installs
update in place.
2026-10-13 15:07:10 -03:00
waozi 9bd72cbf08 Call the website and web app Werkzeug instead of Pass
The landing page, link previews, web app title and install manifest name
Werkzeug and its tools. The Android note says the Internet is used only
for optional Auth sync, and the wordmark images read Werkzeug.
2026-10-13 14:57:30 -03:00
waozi ca735590c2 Keep Profile's code field above the keyboard on Android 10 and older
Kryon 159563f4 measures the keyboard from the window's visible frame where
older Android reports it only there. Checked on a Moto e6 play (Android 9):
the sync code field stays above the keyboard, and the phone rejoined an
account with a typed code.
2026-10-13 10:50:54 -03:00
waozi 4519c5db06 Keep Profile's focused field above the keyboard
The sync code field sits low in Profile, and the keyboard covered it while
you typed a code: the visible area shrank but the scroll stayed put.
Profile now scrolls the focused field just into view when it gains focus
and whenever the visible height changes, as when the keyboard opens, and
leaves scrolling by hand alone. Checked on an Android 15 emulator: the
field and Connect stay above the keyboard while typing.
2026-10-13 10:43:24 -03:00
waozi 8540b489f1 Type in order in Profile's fields on Android, and sync over Kryon's HTTP
Profile's name and sync code fields drew with the caret from before the
keyboard's last letter and sent that caret back to the editor, so every
letter landed at the start: a typed code arrived reversed and the phone
waited forever on a connection nobody answered. The fields now read the
editor's text and caret before they draw (AndroidFieldRead) and send their
own afterwards (AndroidFieldSubmit), like the tools' fields already did.

Kryon e52a91c1 lets an app without Java make HTTP requests, so sync now
works on Android. Tested against api.waozi.xyz: an Android 15 emulator
created an account and connected a desktop; a Moto e6 play (Android 9,
32-bit) joined with a typed code; Auth records and removals arrived in
every direction.

The Android input test reads the status and navigation bar insets instead
of assuming the app fills the screen, accepts Android 13's activity dump,
and types a profile name, which fails without this fix. The sync test tool
gains add and present for checks against a phone.
2026-10-13 10:39:34 -03:00
waozi 952ff6c90c Sync Auth between the owner's devices through Daochi
Profile → Sync creates a Daochi account, or connects to the account of
another device with a 12-character code, and then keeps Auth's accounts
on every device.

- Tools keep small synced records through new host calls (RecordList,
  RecordRead, RecordWrite, RecordRemove, RecordsVersion). Auth stores
  each account as one, moving its old accounts.txt over once.
- The host seals each record with XChaCha20-Poly1305 under a random
  vault key. The sealed text holds the change time and whether the
  record was removed, and the seal covers the account, collection,
  record and key, so the server can neither read, forge nor reorder a
  change. The newest change wins.
- The ML-DSA-44 account key (liboqs) signs in and, with each device's
  own Ed25519 key, signs every sync (daochi-client, protocol 6, paged
  encrypted records).
- Connecting a device swaps X25519 keys through Daochi's link mailbox;
  the account and vault keys travel sealed with a key derived from the
  exchange and the code, so the node cannot open or replace them.
- The werkzeug app is registered on api.waozi.xyz with a signed
  manifest (scripts/register_daochi_app.py).
- scripts/sync_e2e_test.sh runs two devices against a local node:
  account, connected device, record and removal; the node never stores
  the test secret in plain text.

The Android build gains INTERNET for sync, liboqs and Monocypher. The
web build leaves sync out.
2026-10-13 02:46:48 -03:00
waozi 8e38f2f476 Keep Werkzeug clear of Android's navigation bar, with Inbe's font
Tested on a Moto e6 play (Android 9, 32-bit, 3-button navigation):

- The app read no window insets, so the bottom of every screen sat under
  the navigation bar. It now reads them each frame through Kryon's
  PollAndroidWindowInsets and paints the bar strips, as Inbe does.
- Android 9 cannot name a system font and the APK's font did not load, so
  text used raylib's pixel font. The APK and the browser now carry Noto
  Sans, Inbe's font, cut from Kryon's copy to the characters Werkzeug
  draws (Latin, the secret mask, × ÷ −).
- Auth showed the code for 1970 on 32-bit phones; the locked Ziran reads
  the wall clock correctly there. Empty secret fields show their hint
  instead of dots.
- Calculator's delete key is an icon, since the font has no ⌫.
- The profile button shows the name, or Profile, beside the picture.

Locks Kryon f850a301 and Ziran 201be10.
2026-10-13 02:22:45 -03:00
waozi c25665bccc Run Werkzeug on Android and in the browser, and release it as 0.3.0
The Android app keeps its package, so it updates Pass in place: Pass's
saved profiles, settings, theme and master password carry over, every
tool types through the Android keyboard, and the interface uses the
system font. The browser app opens Werkzeug, a single tool with ?app=,
and Pass alone with ?mini for pages that embed it. Desktop installs keep
the tool bundles in lib/werkzeug, and the packages, store listing and
release files are named Werkzeug. The Plan 9 port keeps the pass
command.
2026-10-13 01:02:49 -03:00
waozi f2f4bccaf9 Turn Pass into Werkzeug: a home screen running separate tool apps
Werkzeug opens Pass, Auth, Calculator and Clock from a home screen.
Each tool is its own bundle in apps/, preinstalled with Werkzeug, and
keeps its files, assets and secret to itself. Pass keeps its LessPass
passwords, profiles and settings; the host derives its keys natively.
Auth shows two-factor codes from otpauth links or secret keys and
copies them for 30 seconds. The profile holds a name, a picture and the
appearance every tool shares. This commit brings the desktop app; the
Android and browser hosts follow.
2026-10-13 00:22:41 -03:00
waozi ef2c0d19ad Keep Pass compact and center bounded forms when resizing 2026-10-11 12:19:49 -03:00
waozi d830e09e0a Use vanilla Kryon styling and hover cursors 2026-10-11 11:54:09 -03:00
waozi fd835f4627 Build Pass with current Kryon and Ziran 2026-10-11 11:25:14 -03:00
waozi 2c7a4075da Introduce the purple asterisk and keyhole logo for Pass 0.2.10 2026-10-10 19:10:13 -03:00
waozi 17b1662aca Restore saved CLI profiles, vault unlocking and clipboard copying 2026-10-07 16:11:17 -03:00
waozi 6ab16893a5 Ignore the local Wrangler deploy cache 2026-10-02 16:57:47 -03:00
waozi 9181963a3b Gate site deployments on browser and cache upgrade checks 2026-09-30 23:39:18 -03:00
waozi a2cbd49b8a Keep cached browser loaders paired with their Wasm build 2026-09-30 22:53:32 -03:00
waozi 27e6b2ceca Clarify full-version actions and expose verified downloads 2026-09-30 22:40:45 -03:00
waozi b3e4abae8c Keep the browser generator rendering when storage is unavailable 2026-09-30 22:40:01 -03:00
waozi 942fa5a8fa Add Waozi palette for portfolio mini previews 2026-09-30 22:05:30 -03:00
waozi d15a74c444 Route native project commands through the Pass desktop host 2026-09-30 17:48:33 -03:00
waozi 1a0b952c24 Port Pass GUI and CLI to native Plan 9 libdraw in Ziran 2026-09-30 01:40:23 -03:00
waozi fee64de901 Allow desktop test startup time and capture failure diagnostics 2026-09-29 21:49:13 -03:00
waozi 45694a2e0c Fix browser copying and verify generated passwords across platforms 2026-09-29 21:43:20 -03:00
waozi c89856ba32 Check the expected password and clipboard in browser and Android tests
The browser test now types a master password, checks the generated password
against the LessPass reference, and checks that Copy reaches the system
clipboard, is cleared later, and leaves other clipboard text alone. The
Android input test checks the same generated password.
2026-09-29 21:43:17 -03:00
waozi 9ba2ea98f9 Test desktop typing, generation, clipboard, and profiles on Xvfb
make gui-input-test drives the desktop app on a private Xvfb display: typing
into the fields, the expected LessPass password, the clipboard, and saving,
restarting with, and deleting a profile. e2e now runs it.
2026-09-29 21:39:51 -03:00
waozi 0586aa16e9 Add a mini mode with only the generator
Pass opened with ?mini in the page address, or started with --mini on the
desktop, shows only the generator: site, login, master password, the
password, and Copy, without profiles, settings, or generation options. An
expand button in the top-right corner opens the full app: a page opens it
in a new tab without ?mini, and the phone-sized desktop window grows into
the full window in place.

Also update Kryon, which now opens desktop windows at a chosen size, and
add the MingCute icon package for the expand icon.
2026-09-29 21:29:34 -03:00
waozi dc6cfa0db0 Render desktop smoke tests with private light and dark fixtures 2026-09-29 21:22:23 -03:00
waozi 5972850f89 Show spinbox values in the dark theme
The theme styled spinboxes but not their value boxes, which kept Kryon's
white default fill under the theme's light text, so Length and Counter
were nearly invisible in dark mode.
2026-09-29 21:20:29 -03:00
waozi e6bfa121d2 Rebuild Pass as a Ziran app on Kryon
Pass's desktop, browser, Android, and command-line apps are now one Ziran
program on Kryon: src/app.zi draws the generator, profiles, and settings,
and thin hosts (desktop, browser canvas with a service worker for offline
use, Android, CLI) run it. The old .kry UI, the C core and hosts, the
Java activity, and the JavaScript web app are gone. Generation still
matches LessPass, and profiles and settings keep their storage formats.
2026-09-29 21:20:29 -03:00
waozi 720ad42405 Remove legacy vendored dependencies 2026-09-28 18:22:55 -03:00
waozi 88d2abba38 Use Ziran packages for Kryon 2026-09-28 17:25:29 -03:00
waozi 5349420989 Keep the Pass adapter portable to Plan 9 2026-09-28 11:42:23 -03:00
waozi 7758a9d3c0 Add a Ziran core compatibility adapter 2026-09-28 11:35:17 -03:00
waozi 133b4b08b9 Port Pass master emoji to Ziran 2026-09-28 11:21:08 -03:00
waozi e5ad25fbdd Build the Pass CLI from Ziran 2026-09-28 11:14:13 -03:00
waozi 1584763396 Generate Pass passwords in Ziran 2026-09-28 11:05:28 -03:00
waozi 7ef2e2726d Derive Pass keys in Ziran 2026-09-28 03:24:30 -03:00
waozi 99cba65af5 Start the Ziran Pass core migration 2026-09-28 03:05:43 -03:00
waozi 35e8120dbe Bump Kryon: plan9 fixes merged onto master 2026-09-22 18:15:20 -03:00
waozi bc8e59fb5a Give Pass an illustrated editorial website 2026-09-19 11:21:19 -03:00
waozi f9d721f179 Release Pass 0.2.9 2026-09-05 09:19:44 -03:00
waozi 7bb859f7df Keep Android builds aligned with the tested runtime and viewport 2026-09-05 09:19:44 -03:00
waozi 87df40db11 Use theme-aware icon tints and prevent taps through theme settings 2026-09-05 09:17:34 -03:00
waozi c0026b0b5f Redesign the Pass website around its vault mark 2026-09-02 17:24:47 -03:00
waozi 8c3e89368c Build with the shared plan9 rules 2026-08-31 17:50:54 -03:00
waozi 36e08df09e Move site deployment to Cloudflare Pages 2026-08-31 16:48:35 -03:00
waozi d930387758 Generate the Plan 9 build with k2c --plan9
The vendored Kryon compiler now emits 8c-safe C directly, so the
per-project rewriter script is gone: kry-c-plan9 runs k2c with --plan9,
writes the generated file list, and builds the embedded asset table
with the fonts. Bump vendor/kryon for the new k2c mode.
2026-08-31 15:26:04 -03:00
waozi 42bfe570e1 Define the app lifecycle hooks for the native Plan 9 entry
The k2c project host references CreateApp, DestroyApp, ApplyRoute, and
BeginScreenDraw weakly, and the native linker has no weak symbols.
The Plan 9 entry drives its own loop, so inert definitions satisfy the
host registry.
2026-08-31 13:08:39 -03:00
waozi e877f8d27d Expose the weak app lifecycle declarations for the Plan 9 rewrite
The native cpp does not define __GNUC__, so kryon_project.c's weak
declarations were compiled out and its lifecycle calls had no
prototypes for 8c. Drop the guard during the rewrite like Inbe does.
2026-08-31 12:44:54 -03:00
waozi 6d1a5ca1a5 Exit cleanly from the mkfile host-preparation check
A plan9 rc if whose condition is false and that has no else branch
returns failure, so the check rule failed exactly when the preparation
was present. Finish with an explicit exit 0.
2026-08-31 12:19:00 -03:00
waozi 5d92e65a92 Add a native Plan 9 port
- Host-side prepare script rewrites the k2c output for 8c (inferred
  declarations, compound literals, for-loop declarations) and generates
  the embedded asset table with the Noto Sans and emoji faces
- Native entry point mirrors the shared GUI main (window, Material
  theme, embedded fonts, shapes texture, frame loop) and switches to
  the user's home so profiles and app-storage settings land there
- plan9 mkfile builds and installs to /$objtype/bin against libkryon
2026-08-31 12:10:27 -03:00
waozi befbecb131 Bump Pass Kryon submodule to public master 2026-08-31 12:02:25 -03:00
waozi 3d27747a91 Move Pass Waozi return link 2026-08-31 11:56:44 -03:00
waozi b4d6a374d3 Adopt KryonActivity host and expand runtime test coverage
- Replace the custom MainActivity/TextInputBridge and android_bridge shim
  with kryon's KryonActivity and AndroidHost API; configure secure
  preferences via manifest meta-data
- Slim the pass_runtime surface: drop safe-area and biometric/master
  helpers that moved into the Android host
- Add pass_runtime_test, scripts/cli_test.sh, and a make coverage
  target; run runtime-test as part of make test
- Exclude the dom_ backend from web builds; bump vendor/kryon for the
  Android UI density scaling fix
- Refresh fastlane metadata and Linux packaging descriptions
2026-08-31 11:29:38 -03:00
waozi 42eb428c4c Package Pass HTML5 itch build 2026-08-31 11:01:51 -03:00
waozi 7a1ab6a48c Publish Pass web builds to itch 2026-08-31 10:48:43 -03:00
waozi 044024b549 Keep Pass web app on separate page 2026-08-30 00:14:16 -03:00
waozi 7b9de10d80 Refresh Pass website styling 2026-08-30 00:05:00 -03:00
waozi e527f83dd4 Use official F-Droid badge in README 2026-08-29 22:34:47 -03:00
waozi 1cffcde52d Add project README banners 2026-08-29 22:19:51 -03:00
waozi 06cd3a53ac Use Kryon Android window insets 2026-08-29 12:47:01 -03:00
waozi 45817b10e3 Bump Kryon for Android rotation fix 2026-08-29 11:21:19 -03:00
waozi 8220b3619d Update Kryon app framework 2026-08-27 19:46:13 -03:00
waozi 1e28b7e273 Fix web release backend selection 2026-08-26 16:23:03 -03:00
waozi 8db4e1b414 Prepare 0.2.8 release 2026-08-26 16:17:09 -03:00
waozi cafa4f9054 Add Sweet default theme and password output field 2026-08-26 15:38:43 -03:00
waozi 71ace783e2 Use Kryon secure store on Android 2026-08-26 15:32:09 -03:00
waozi d80b8e16f9 Version Android release APK assets 2026-08-26 15:18:08 -03:00
waozi 027b359ed7 Fix LessPass-compatible password generation 2026-08-26 15:11:06 -03:00
waozi 36e811bf74 Stabilize Android input CI emulator 2026-08-24 17:02:27 -03:00
waozi 41bb63baa7 Release Pass 0.2.7 2026-08-24 16:39:44 -03:00
waozi 423762d82f Fix Android input CI shell invocation 2026-08-24 16:33:27 -03:00
waozi 9f4f12f68a Release Pass 0.2.6 2026-08-24 16:14:56 -03:00
waozi 1497ecee17 Release Pass 0.2.5 2026-08-24 15:33:42 -03:00
waozi 3f4b8e43d5 Update desktop showcase banner 2026-08-23 23:26:13 -03:00
waozi a68e9fa3ee Bump Kryon submodule 2026-08-23 23:17:45 -03:00
waozi f70ade6adc Adopt Kryon #ui hierarchy syntax 2026-08-23 23:17:20 -03:00
waozi e636813590 Fix Android safe-area layout rotation 2026-08-23 22:46:36 -03:00
waozi 92ee741298 Add Kryon app smoke and Android rotation fixes 2026-08-23 22:30:28 -03:00
waozi 5c60cf8226 Optimize showcase banner 2026-08-23 22:29:53 -03:00
waozi 8f4121d921 Update showcase banner 2026-08-23 22:27:53 -03:00
waozi b0c7b2079a Update Kryon and expand E2E coverage 2026-08-22 20:03:28 -03:00
waozi 055d130bc3 android: tighten release changelog 2026-08-22 02:01:27 -03:00
waozi 57d52c6658 android: autosave generator defaults 2026-08-22 01:58:42 -03:00
waozi 8a601d6366 android: clear displayed secrets after timeout 2026-08-22 01:55:34 -03:00
waozi cc77006502 ci: install emscripten for release web app 2026-08-22 01:47:13 -03:00
waozi cb82a38b6a release: prepare pass 0.2.4 2026-08-22 01:45:45 -03:00
waozi d19d6edf7d Update pass logo assets 2026-08-22 01:10:18 -03:00
waozi f2eaed3c86 Add Kryon showcase metadata 2026-08-22 01:02:04 -03:00
waozi b6cdc32d52 site: full download channels with per-platform links
The Android card now offers the direct APK and the F-Droid package
page like the inbe site, the desktop card links the AppImage and
deb packages that releases already ship, and the CLI card covers
every platform. AppImage and deb asset names carry the version, so
build.sh templates it from version.go at build time. A SHA256SUMS
note closes the section now that releases publish checksums.
2026-08-21 09:12:16 -03:00
waozi 5047ce86b0 release: prepare pass 0.2.3 2026-08-21 09:04:01 -03:00
waozi 45f3f8dbc0 release: publish SHA256SUMS with the downloads
Every release now carries a SHA256SUMS file covering all published
artifacts, so the CLI, desktop, Android, and browser downloads can be
verified before use. The appcast already embedded digests for the
desktop update channels; this extends verification to every file.
2026-08-21 09:03:47 -03:00
waozi a52a4b6462 docs: describe installing the Android app
The APK has shipped since 0.2.2 but the README never mentioned it.
Document where to get it, the minimum Android version, and that the
app declares no Internet permission.
2026-08-21 09:03:47 -03:00
waozi b8bed150d0 release: push the tag only after the artifacts are ready
The tag used to be pushed before the appcast step ran, so any failure
there (v0.2.1 lost its release to a missing vendored script) orphaned
the version: later runs saw the tag and skipped publishing forever.
Publishing now happens in the safe order: build artifacts, appcast,
tag, release.
2026-08-21 09:03:33 -03:00
waozi 56be19e3a9 packaging: move the fdroiddata recipe to the fdroiddata fork
The F-Droid build recipe lives in fdroiddata, not in the app repository; the fastlane listing metadata stays because F-Droid reads it from the default branch.
2026-08-20 19:55:43 -03:00
waozi b256e9b9fd packaging: fix fdroiddata recipe from a local fdroidserver build
Point the 0.2.2 build at b4be990: the v0.2.2 tag does not survive fdroidserver signing-config stripping, and the binary scanner needs scandelete entries for unused vendored binaries in kryon submodules.
2026-08-20 19:44:04 -03:00
waozi b4be99002d droid: require the keystore password before signing release builds 2026-08-20 19:28:12 -03:00
waozi 9447c3a75c packaging: draft fdroiddata recipe for the F-Droid inclusion request 2026-08-20 19:17:34 -03:00
waozi 3deda78d54 fastlane: Android store listing metadata, changelogs, and screenshots 2026-08-20 19:17:34 -03:00
waozi c76f76ffb7 droid: build unsigned release APKs when no keystore is present 2026-08-20 19:17:34 -03:00
289 changed files with 23534 additions and 22792 deletions

No files matched your search

+11 -10
View File
@@ -1,15 +1,16 @@
build-essential
cmake
pkg-config
libssl-dev
zlib1g-dev
libbrotli-dev
libzstd-dev
libsdl2-dev
libgl-dev
libx11-dev
libdrm-dev
libgbm-dev
libegl-dev
libgles-dev
libcairo2-dev
libfreetype6-dev
libfontconfig1-dev
libpango1.0-dev
xvfb
xauth
libgtk-3-dev
python3-pil
tesseract-ocr
imagemagick
gnumeric
zenity
+126 -47
View File
@@ -15,52 +15,82 @@ concurrency:
cancel-in-progress: true
jobs:
guard-submodule-urls:
name: Submodule URLs are public HTTPS
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
steps:
# Plain checkout on purpose: the guard must not depend on fetching
# the submodules it validates (an SSH URL would break that fetch).
# Plain checkout on purpose: the guard validates URLs before fetching.
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject non-HTTPS submodule URLs
run: |
set -eu
if [ ! -f .gitmodules ]; then echo "no submodules - ok"; exit 0; fi
bad=$(grep -nE '^[[:space:]]*url[[:space:]]*=' .gitmodules \
| grep -vE '^[0-9]+:[[:space:]]*url[[:space:]]*=[[:space:]]*https://' || true)
if [ -n "$bad" ]; then
echo "::error::Non-HTTPS submodule URL(s) break fresh clones and CI:$bad"
exit 1
fi
echo "all submodule URLs HTTPS - ok"
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
test:
runs-on: ubuntu-latest
needs: guard-submodule-urls
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- name: Install CLI test dependencies
run: |
sudo apt-get update
sudo apt-get install -y openssl xclip xvfb xauth tesseract-ocr imagemagick
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Test Ziran CLI, core, and native/portable app runtime
run: make test
- uses: actions/setup-node@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
node-version: '22'
- name: Test browser input, storage, and offline launch
env:
WERK_WEB_BROWSER: google-chrome
run: make web-smoke
- name: Upload browser failure diagnostics
if: failure()
uses: actions/upload-artifact@v4
with:
go-version: 1.25.x
cache: false
- name: Test CLI and generator
run: go test ./...
- name: Build browser app
run: make site
name: werk-browser-diagnostics-ci
path: build/web-test/*.png
if-no-files-found: ignore
- name: Verify generated site
run: |
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/pass.wasm
- name: Check formatting
run: test -z "$(find . -path ./vendor -prune -o -name '*.go' -type f -print | xargs gofmt -l)"
test -s build/site/index.wasm
test -s build/site/sw.js
test -s build/site/assets.json
- name: Check fastlane metadata
run: |
set -eu
meta=fastlane/metadata/android/en-US
limit() {
n=$(wc -m < "$1")
if [ "$n" -gt "$2" ]; then
echo "::error::$1 is $n characters (max $2)"
exit 1
fi
}
limit "$meta/title.txt" 30
limit "$meta/short_description.txt" 80
limit "$meta/full_description.txt" 4000
for f in "$meta"/changelogs/*.txt; do
limit "$f" 500
done
code=$(sed -n 's/^[[:space:]]*versionCode \([0-9][0-9]*\)$/\1/p' droid/app/build.gradle | head -n 1)
test -n "$code"
test -s "$meta/changelogs/$code.txt"
test -s "$meta/images/icon.png"
echo "fastlane metadata ok (versionCode $code)"
build-gui:
name: GUI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
@@ -71,12 +101,6 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -84,25 +108,27 @@ jobs:
sudo apt-get install -y "${packages[@]}"
- name: Build GUI
run: make gui
- name: Test GUI logic
run: cd gui && go test ./...
- name: Render GUI on private display
run: make gui-smoke
- name: Build Debian package
run: make package-deb
- uses: actions/upload-artifact@v4
with:
name: pass-gui-linux-${{ matrix.arch }}
path: build/pass-gui
name: werk-linux-${{ matrix.arch }}
path: |
build/werk
build/apps
build/pfp.webp
build/tools
if-no-files-found: error
build-android:
name: Android debug build
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-submodule-urls
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-java@v4
with:
distribution: temurin
@@ -125,17 +151,70 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'native/*.c', 'droid/app/src/main/cpp/*.c', 'vendor/kryon/src/**/*.c', 'vendor/kryon/include/**/*.h', 'vendor/kryon/vendor/raylib/src/**') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'apps/*/*.zi', 'droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Build debug APK
run: |
set -euo pipefail
chmod +x droid/gradlew
make android-debug
android-input-test:
name: ${{ matrix.name }}
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
strategy:
fail-fast: false
matrix:
include:
- name: Android NativeActivity input
api: 30
image: default
test: android-profile-test
- name: Workbook Android documents
api: 35
image: google_apis
test: workbook-android-test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Install Android SDK components
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh 'platforms;android-${{ matrix.api }}'
- name: Install screenshot OCR
run: |
sudo apt-get update
sudo apt-get install -y tesseract-ocr python3-pil
# Without /dev/kvm access the emulator runs unaccelerated and is too
# slow to answer input before Android reports it not responding.
- name: Enable KVM for the emulator
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Run Android input tests
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: ${{ matrix.api }}
arch: x86_64
target: ${{ matrix.image }}
emulator-boot-timeout: 900
emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -no-metrics
script: make android-emulator ${{ matrix.test }}
- uses: actions/upload-artifact@v4
if: failure()
with:
name: android-input-test-reports-${{ matrix.api }}
path: |
build/android-input/
build/workbook-android-test/
if-no-files-found: ignore
+56
View File
@@ -0,0 +1,56 @@
name: Google Play testing bundle
on:
workflow_dispatch:
permissions:
contents: read
jobs:
bundle:
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
- name: Install build tools
run: |
sudo apt-get update
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
bash scripts/install_android_sdk.sh
- name: Prepare preserved release key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
run: |
test -n "$KEYSTORE_BASE64"
umask 077
mkdir -p "$HOME/.android"
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
- name: Build signed testing candidate
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
test -n "$KEYSTORE_PASSWORD"
test -n "$KEY_ALIAS"
make android-bundle
- name: Validate the candidate
run: |
curl --fail --show-error --location --retry 3 \
https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
--output "$RUNNER_TEMP/bundletool.jar"
python3 scripts/android-bundle-check.py "build/werk-$(cat VERSION).aab" \
--bundletool "$RUNNER_TEMP/bundletool.jar" --version "$(cat VERSION)"
- name: Remove temporary release key
if: always()
run: rm -f "$HOME/.android/pass-release.keystore"
- uses: actions/upload-artifact@v4
with:
name: werkzeug-play-testing
path: build/*.aab
if-no-files-found: error
retention-days: 14
+219 -76
View File
@@ -13,44 +13,19 @@ concurrency:
cancel-in-progress: false
jobs:
cli:
name: CLI (${{ matrix.os }}-${{ matrix.arch }})
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
strategy:
matrix:
os: [linux, darwin, windows, freebsd]
arch: [amd64, arm64]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
- name: Build archive
env:
TARGET_OS: ${{ matrix.os }}
TARGET_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
name="pass-cli-${TARGET_OS}-${TARGET_ARCH}"
mkdir -p "build/release/$name"
suffix=""
[ "$TARGET_OS" = windows ] && suffix=".exe"
CGO_ENABLED=0 GOOS="$TARGET_OS" GOARCH="$TARGET_ARCH" go build -trimpath -ldflags='-s -w' -o "build/release/$name/pass$suffix" ./cmd/pass
cp LICENSE README.md "build/release/$name/"
if [ "$TARGET_OS" = windows ]; then
(cd build/release && zip -qr "$name.zip" "$name")
else
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
fi
- uses: actions/upload-artifact@v4
with:
name: cli-${{ matrix.os }}-${{ matrix.arch }}
path: build/release/pass-cli-${{ matrix.os }}-${{ matrix.arch }}.*
if-no-files-found: error
- name: Checkout Repository
uses: actions/checkout@v4
gui:
name: GUI (${{ matrix.arch }})
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
cli:
name: CLI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
@@ -61,12 +36,33 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- name: Build archive
run: |
set -euo pipefail
make cli
name="pass-cli-linux-${{ matrix.arch }}"
mkdir -p "build/release/$name"
cp pass LICENSE README.md "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
- uses: actions/upload-artifact@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
name: cli-linux-${{ matrix.arch }}
path: build/release/pass-cli-linux-${{ matrix.arch }}.tar.gz
if-no-files-found: error
gui:
name: GUI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
- runner: ubuntu-22.04
arch: amd64
- runner: ubuntu-24.04-arm
arch: arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -75,9 +71,9 @@ jobs:
- run: make gui
- name: Package GUI tarball and Debian package
run: |
name="pass-gui-linux-${{ matrix.arch }}"
name="werk-linux-${{ matrix.arch }}"
mkdir -p "build/release/$name"
cp build/pass-gui LICENSE README.md "build/release/$name/"
cp -R build/werk build/apps build/pfp.webp build/tools LICENSE README.md assets/app/icon.png "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
make package-deb
- name: Package AppImage
@@ -94,7 +90,7 @@ jobs:
with:
name: gui-linux-${{ matrix.arch }}
path: |
build/release/pass-gui-linux-${{ matrix.arch }}.tar.gz
build/release/werk-linux-${{ matrix.arch }}.tar.gz
build/release/*.deb
build/release/*.AppImage
if-no-files-found: error
@@ -103,10 +99,9 @@ jobs:
name: Android
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-java@v4
with:
distribution: temurin
@@ -129,15 +124,12 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'native/*.c', 'droid/app/src/main/cpp/*.c', 'vendor/kryon/src/**/*.c', 'vendor/kryon/include/**/*.h', 'vendor/kryon/vendor/raylib/src/**') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'apps/*/*.zi', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Prepare Android signing key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
@@ -146,7 +138,7 @@ jobs:
test -n "$KEYSTORE_BASE64" || { echo "::error::KEYSTORE_BASE64 secret is empty or missing"; exit 1; }
mkdir -p "$HOME/.android"
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
- name: Build release APK
- name: Build release APKs
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
@@ -155,34 +147,93 @@ jobs:
test -n "$KEYSTORE_PASSWORD" || { echo "::error::KEYSTORE_PASSWORD secret is empty or missing"; exit 1; }
test -n "$KEY_ALIAS" || { echo "::error::KEY_ALIAS secret is empty or missing"; exit 1; }
chmod +x droid/gradlew
export KRYON_DIR="$(./scripts/ziran.sh pkg path Kryon --locked)"
export ZIRAN_ROOT="$(./scripts/ziran.sh pkg path ziran --locked)"
export LIBOQS_DIR="$(./scripts/ziran.sh pkg path liboqs --locked)"
export MONOCYPHER_DIR="$(./scripts/ziran.sh pkg path monocypher --locked)"
./droid/gradlew -p droid assembleRelease \
-PsplitApks=true \
-Pkeystore.path="$HOME/.android/pass-release.keystore" \
-Pkeystore.alias="$KEY_ALIAS" \
-Pkeystore.password="$KEYSTORE_PASSWORD" \
--stacktrace
VERSION=$(sed -n '1p' VERSION)
mkdir -p build/release
cp droid/app/build/outputs/apk/release/app-release.apk build/release/pass-android.apk
test -s build/release/pass-android.apk
cp droid/app/build/outputs/apk/release/app-universal-release.apk build/release/werk-android.apk
cp droid/app/build/outputs/apk/release/app-arm64-v8a-release.apk build/release/werk-android-arm64-v8a.apk
cp droid/app/build/outputs/apk/release/app-armeabi-v7a-release.apk build/release/werk-android-armeabi-v7a.apk
cp droid/app/build/outputs/apk/release/app-universal-release.apk "build/release/werk-$VERSION.apk"
cp droid/app/build/outputs/apk/release/app-arm64-v8a-release.apk "build/release/werk-$VERSION-arm64-v8a.apk"
cp droid/app/build/outputs/apk/release/app-armeabi-v7a-release.apk "build/release/werk-$VERSION-armeabi-v7a.apk"
python3 scripts/android_apk_check.py build/release/werk-android*.apk
test -s build/release/werk-android.apk
test -s build/release/werk-android-arm64-v8a.apk
test -s build/release/werk-android-armeabi-v7a.apk
test -s "build/release/werk-$VERSION.apk"
test -s "build/release/werk-$VERSION-arm64-v8a.apk"
test -s "build/release/werk-$VERSION-armeabi-v7a.apk"
# Only a Google Play edition may hold a Google library, in its build
# files as in its APK.
- name: Keep Google libraries out of the APKs and their build files
uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
with:
packages: build/release/werk-android*.apk
- uses: actions/upload-artifact@v4
with:
name: android
path: build/release/pass-android.apk
path: build/release/*.apk
if-no-files-found: error
web:
runs-on: ubuntu-latest
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- run: make site
- run: cd build/site && zip -qr ../pass-web.zip .
- name: Package web site and HTML5 app
run: |
set -euo pipefail
cd build/site
zip -qr ../werk-web.zip .
# The site root is the app: its page loads content-hashed script and
# Wasm names, and the service worker caches the files in assets.json.
mkdir -p ../werk-html5
cp -R . ../werk-html5/
sed -i \
-e 's#href="/manifest.webmanifest"#href="manifest.webmanifest"#g' \
-e 's#href="/icons/#href="icons/#g' \
-e 's#src="/icons/#src="icons/#g' \
../werk-html5/index.html
python3 - <<'PY'
import json
from pathlib import Path
root = Path("../werk-html5")
manifest = json.loads((root / "manifest.webmanifest").read_text())
manifest["start_url"] = "."
manifest["scope"] = "."
for icon in manifest.get("icons", []):
icon["src"] = icon.get("src", "").lstrip("/")
(root / "manifest.webmanifest").write_text(json.dumps(manifest, indent=2) + "\n")
PY
cd ../werk-html5
zip -qr ../werk-html5.zip .
- uses: actions/upload-artifact@v4
with:
name: web
path: build/pass-web.zip
path: |
build/werk-web.zip
build/werk-html5.zip
if-no-files-found: error
publish:
@@ -194,7 +245,6 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: recursive
- uses: actions/download-artifact@v4
with:
path: build/artifacts
@@ -203,7 +253,7 @@ jobs:
name: Resolve release version
run: |
set -euo pipefail
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' version.go)
version=$(sed -n '1p' VERSION)
test -n "$version"
tag="v$version"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
@@ -212,20 +262,13 @@ jobs:
else
echo "released=true" >> "$GITHUB_OUTPUT"
fi
- name: Create release tag
if: steps.version.outputs.released == 'true'
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
git push origin "${{ steps.version.outputs.tag }}"
- name: Generate Update Appcast
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
VERSION=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' version.go)
VERSION=$(sed -n '1p' VERSION)
TAG="v$VERSION"
BASE="https://github.com/waozixyz/pass/releases/download/$TAG"
BASE="https://github.com/${{ github.repository }}/releases/download/$TAG"
# appcast channel names use dpkg arch naming (amd64/arm64);
# the artifacts use uname -m naming (x86_64/aarch64)
arch_name() {
@@ -238,24 +281,38 @@ jobs:
channels=()
for img in build/artifacts/*.AppImage; do
[ -e "$img" ] || continue
arch=$(basename "$img" | sed -n 's/^pass-.*-\([^-]*\)\.AppImage$/\1/p')
arch=$(basename "$img" | sed -n 's/^werk-.*-\([^-]*\)\.AppImage$/\1/p')
channels+=("--channel" "appimage-$(arch_name "$arch")=$img")
done
DEB="$(find build/artifacts -maxdepth 1 -name '*.deb' -print -quit || true)"
TAR="$(find build/artifacts -maxdepth 1 -name 'pass-gui-linux-*.tar.gz' -print -quit || true)"
TAR="$(find build/artifacts -maxdepth 1 -name 'werk-linux-*.tar.gz' -print -quit || true)"
[ -n "$DEB" ] && channels+=("--channel" "deb=$DEB")
[ -n "$TAR" ] && channels+=("--channel" "tarball=$TAR")
if [ ${#channels[@]} -eq 0 ]; then
echo "no release artifacts found for the appcast"
exit 1
fi
python3 vendor/kryon/scripts/make_appcast.py \
python3 scripts/make_appcast.py \
--version "$VERSION" \
--base-url "$BASE" \
--notes-url "https://github.com/waozixyz/pass/releases/tag/$TAG" \
--notes-url "https://github.com/${{ github.repository }}/releases/tag/$TAG" \
--changelog CHANGELOG.md \
--out build/artifacts/appcast.json \
"${channels[@]}"
- name: Publish checksums
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
cd build/artifacts
# The glob expands before the redirect creates SHA256SUMS itself.
sha256sum -- * > SHA256SUMS
- name: Create release tag
if: steps.version.outputs.released == 'true'
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
git push origin "${{ steps.version.outputs.tag }}"
- name: Publish GitHub release
if: steps.version.outputs.released == 'true'
uses: softprops/action-gh-release@v2
@@ -263,3 +320,89 @@ jobs:
tag_name: ${{ steps.version.outputs.tag }}
generate_release_notes: true
files: build/artifacts/*
publish-itch:
name: Publish itch.io
runs-on: ubuntu-latest
timeout-minutes: 45
continue-on-error: true
needs:
- web
- android
- gui
- publish
if: needs.publish.outputs.released == 'true'
env:
BUTLER_API_KEY: ${{ secrets.ITCH_API_KEY }}
steps:
- name: Check itch.io Secret
run: |
set -euo pipefail
if [ -z "${BUTLER_API_KEY:-}" ]; then
echo "ITCH_API_KEY secret is required to publish itch.io"
exit 1
fi
- name: Checkout Repository
uses: actions/checkout@v4
- name: Download Release Artifacts
uses: actions/download-artifact@v4
with:
path: build/artifacts
merge-multiple: true
- name: Install Butler
timeout-minutes: 15
run: |
set -euo pipefail
curl -fsSL \
https://broth.itch.zone/butler/linux-amd64/LATEST/archive/default \
-o "$RUNNER_TEMP/butler.zip"
mkdir -p "$RUNNER_TEMP/butler"
unzip -q "$RUNNER_TEMP/butler.zip" -d "$RUNNER_TEMP/butler"
chmod +x "$RUNNER_TEMP/butler/butler"
echo "$RUNNER_TEMP/butler" >> "$GITHUB_PATH"
- name: Publish Release Builds to itch.io
run: |
set -euo pipefail
VERSION="$(sed -n '1p' VERSION)"
html5_zip="build/artifacts/werk-html5.zip"
android_apk="build/artifacts/werk-android.apk"
linux_appimage="build/artifacts/werk-$VERSION-x86_64.AppImage"
test -f "$html5_zip"
test -f "$android_apk"
test -f "$linux_appimage"
butler_push() {
target="$1"
channel="$2"
attempt=1
log_file="$(mktemp)"
while [ "$attempt" -le 6 ]; do
if butler push "$target" "waozi/werk:$channel" --userversion "$VERSION" 2>&1 | tee "$log_file"; then
rm -f "$log_file"
return 0
fi
if ! grep -q "latest build is still processing" "$log_file"; then
rm -f "$log_file"
return 1
fi
echo "itch.io channel $channel is still processing; retrying in 60s ($attempt/6)"
sleep 60
attempt=$((attempt + 1))
done
rm -f "$log_file"
echo "itch.io channel $channel was still processing after retries"
return 1
}
butler_push "$html5_zip" html5
butler_push "$android_apk" android
butler_push "$linux_appimage" linux
+57 -54
View File
@@ -1,4 +1,4 @@
name: Netlify
name: Cloudflare Pages
on:
push:
@@ -10,28 +10,62 @@ permissions:
contents: read
concurrency:
group: netlify-${{ github.ref }}
group: pages-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
build:
needs: guard-package-urls
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/setup-node@v4
with:
go-version: 1.24.x
cache: false
node-version: '22'
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
make site
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/pass.wasm
test -s build/site/index.wasm
test -s build/site/sw.js
- name: Install screenshot OCR
run: |
sudo apt-get update
sudo apt-get install -y tesseract-ocr imagemagick
- name: Verify browser input, storage, cache upgrades, and offline launch
env:
WERK_WEB_BROWSER: google-chrome
run: bash scripts/web_smoke.sh
- name: Upload browser failure diagnostics
if: failure()
uses: actions/upload-artifact@v4
with:
name: werk-browser-diagnostics
path: build/web-test/*.png
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
with:
name: pass-site
name: werk-site
path: build/site
if-no-files-found: error
@@ -43,25 +77,14 @@ jobs:
steps:
- uses: actions/download-artifact@v4
with:
name: pass-site
name: werk-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Preview To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
netlify deploy \
--dir build/site \
--no-build \
--alias "pr-${{ github.event.pull_request.number }}" \
--message "Preview ${{ github.event.pull_request.number }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Deploy Preview To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=pass --branch=${{ github.head_ref || github.ref_name }} --commit-hash=${{ github.sha }}
deploy-production:
name: Deploy Production
@@ -71,31 +94,11 @@ jobs:
steps:
- uses: actions/download-artifact@v4
with:
name: pass-site
name: werk-site
path: build/site
- name: Package Site
run: |
set -euo pipefail
test -s build/site/index.html
cd build/site
zip -qr ../pass-site.zip .
test -s ../pass-site.zip
- name: Deploy Production To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing"; exit 1; }
response="$(curl --fail-with-body --silent --show-error \
-X POST \
-H "Authorization: Bearer $auth_token" \
-H "Content-Type: application/zip" \
--data-binary "@build/pass-site.zip" \
"https://api.netlify.com/api/v1/sites/$site_id/deploys")"
python3 -c 'import json, sys; deploy = json.loads(sys.argv[1]); state = deploy.get("state", ""); url = deploy.get("ssl_url") or deploy.get("url") or deploy.get("deploy_ssl_url") or deploy.get("deploy_url") or deploy.get("id"); print(f"Netlify deploy {state}: {url}"); raise SystemExit(1 if state in ("error", "failed") else 0)' "$response"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Deploy Production To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=pass --branch=master --commit-hash=${{ github.sha }}
+8 -1
View File
@@ -1,3 +1,10 @@
/build/
/pass
/gui/pass-gui
/ziran.local.toml
__pycache__/
*.pyc
.wrangler/
/backup/
/work/
/apps/*/build/
-3
View File
@@ -1,3 +0,0 @@
[submodule "vendor/kryon"]
path = vendor/kryon
url = https://github.com/kryonlabs/kryon.git
+45
View File
@@ -0,0 +1,45 @@
# Werkzeug repository rules
Werkzeug (formerly Pass) is a public repository. Read `~/Projects/AGENTS.md`
first.
## Tools are separate apps
- Each tool builds into its own bundle, `build/apps/<tool>.zx`: Pass,
Calculator and Clock from `apps/<tool>/`, Auth and Workbook from their own
Ziran packages. The host (`src/apps.zi`) checks every call a bundle asks
for and keeps each tool's files, assets and secret separate.
- Tools never import another tool's modules. Code two tools need comes from
a Ziran package, as SHA-256 and PBKDF2 come from `crypto`; no git
submodules.
- Keep the host interface small and generic (files, clock, clipboard,
key derivation, device secret, input). A new host call needs a new host
build before any bundle can use it.
- Work the portable interpreter cannot do fast enough, such as Pass's
100,000 PBKDF2 rounds, is a native host capability, never a step-limit
increase.
## Data and secrets
- Never commit, print or log a real master password, Auth secret, otpauth
link, export file or current code. Tests use fixture values only, such as
the RFC 6238 keys.
- Keep Pass's on-disk formats and `src/migrate.zi`. The owner's latest choice
on 2026-10-23 is an update of the existing Android/F-Droid app: keep
`xyz.waozi.pass` and its signing certificate, with the display name Werkzeug.
Preserve existing Pass data and any separate `xyz.waozi.werk` installation.
- Every file Werkzeug writes is private (0600 in 0700 folders).
## Platforms and tests
- Ziran only: C, Wasm and the browser loaders are compiler outputs. The
Android app has no Java (`hasCode=false`); it reaches the platform through
JNI from Ziran.
- Desktop tests run on private Xvfb displays (`make gui-smoke gui-test`),
the browser test in private headless Chromium (`make web-smoke`), and
Android tests only on a private emulator (`make android-input-test`),
never on a connected phone.
- Run `make test` and `ziran fmt --check` before committing.
- Releases follow `~/Projects/AGENTS.md`: add the numeric entry to
`CHANGELOG.md` and run `./update_version.sh`; only the release workflow
creates tags.
+154
View File
@@ -1,5 +1,159 @@
# Changelog
## [Unreleased]
- Add Simple Calendar with Month, Week and Agenda views, recurring events, search and private local storage.
- Include Task Manager from its separate `kryonlabs/taskmgr` package with live process monitoring, filtering, sorting, task termination, command launch and performance graphs.
- Show a brief confirmation when Auth copies a code to the clipboard.
- Show your account username in the top-right profile button.
- Give Gallery matching artwork on Werkzeug Home and an icon in the Linux window switcher.
- Use Mesh account sync and client imports while keeping existing account keys and Werkzeug data compatible.
- Embedded in Harmony's Sessions window, Werkzeug draws every colour from Harmony's theme and follows its changes; started on its own it keeps its own appearance.
- Tap the whole Auth card to copy the current code as plain digits, while keeping Edit and the next-code preview.
- Browse local photo folders and albums with Gallery on desktop and Android.
- Remove the backgrounds from the five colorful tool icons.
- Read the account picture back from the node without replacing a local choice still waiting to sync.
- Auth shows grouped codes and the next code on clean cards, with a purple countdown line that turns orange halfway through.
- Password fields in Profile start empty and show one mask character for each character you type.
- Continue with an account already signed in to another Waozi app on Android, after approving the transfer there.
- Signing out skips the backup warning once this account's key is backed up.
- Open the newer account backups other waozi apps save.
- Send the profile picture you choose to your node, so friends see it in every app.
- Offer Entity's abstract profile pictures, like every other app, and keep the one you choose.
- Continue as no longer crashes the other app when it was closed.
- A fresh look: colorful artwork for each tool on Home, rounded tiles and softly tinted buttons that follow your accent color.
## [0.4.7] - 2026-10-28
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
## [0.4.6] - 2026-10-27
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
## [0.4.5] - 2026-10-26
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
## [0.4.4] - 2026-10-23
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
## [0.4.3] - 2026-10-23
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
## [0.4.2] - 2026-10-23
- Linux packages include the libraries needed for sync and importing QR-code pictures.
- Packaging a new AppImage preserves previous downloads.
## [0.4.1] - 2026-10-23
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
- Tool windows show their own names and icons in the desktop switcher.
## [0.4.0] - 2026-10-19
- A new purple W logo across the app, Android and the website.
- Calculator gets a Scientific mode.
- Auth imports Google Authenticator, Aegis and Ente Auth exports, and on the desktop a picture of their QR code.
- Rename an Auth account, note the websites it signs in to, or remove it.
- Choose your own Daochi node, and pause sync without losing your account.
- On the desktop, Profile manages your account: create it, import or back up its key, and link devices by QR code.
- Sign in with a Daochi account key you already have, such as Inbe's.
- `werk sync` and `werk auth` work without a window on Linux.
- Reach every tool from the web app's mini version.
- Fix the web version freezing when Clock opens.
- Show π, √ and other symbols on phones older than Android 10.
- Fix Profile breaking after choosing a file on desktops whose language writes decimals with a comma.
- The `pass` command unlocks vaults whose text is wrapped with spaces or tabs on systems with OpenSSL 3.0.
## [0.3.1] - 2026-10-13
- Fix the web version on itch.io, which opened to a blank page.
## [0.3.0] - 2026-10-13
- Pass is now Werkzeug: a home screen of small private tools, each its own app and all preinstalled.
- A new logo: a wrench with a keyhole. The website moves to werk.waozi.xyz.
- Add Auth for two-factor sign-in codes from otpauth links or secret keys; copied codes clear after 30 seconds.
- Add Calculator, and Clock with a stopwatch.
- Add a profile with your name, a picture and the appearance every tool shares.
- Sync Auth's accounts between your devices from Profile → Sync: create an account, then connect another device with a 12-character code. Accounts are encrypted on the device; the server never sees them.
- Keep your Pass profiles, settings, theme and saved master password when updating.
- On Android, keep every screen clear of the navigation bar and the keyboard.
- Use Inbe's font, Noto Sans, in the browser and on phones older than Android 10.
## [0.2.10] - 2026-10-05
- Introduce the purple password asterisk and keyhole logo across Pass, website icons, Android launchers, and app listings.
## [0.2.9] - 2026-09-05
- Keep bottom navigation, password controls, and dialog icons readable with
dark tints in light mode and light tints in dark mode.
- Prevent taps in Theme Settings from reaching fields underneath or opening
the keyboard when saving the theme.
## [0.2.8] - 2026-08-26
- Match LessPass clients for the same site, login, master password, counter,
character classes, and length settings.
- Limit password length to LessPass's 5 to 35 character range.
- Require Android fingerprint unlock for saved master passwords and store them
with an authenticated Android Keystore key.
- Use the Sweet Material palette by default, with Sweet-Dark matched colors in
dark mode, and show generated passwords in a dedicated output field.
- Keep settings controls fully scrollable above the bottom navigation and use
the available form width while scrolling.
- Keep theme dropdowns from opening the Android soft keyboard.
## [0.2.7] - 2026-08-24
- Fix Android source builds in stricter environments such as F-Droid builders
while keeping Kry app source generation automatic.
## [0.2.6] - 2026-08-24
- Keep Android source builds self-contained so F-Droid and other source builds
generate the Kry app sources automatically.
## [0.2.5] - 2026-08-24
- Add Android appearance settings for following device colors, choosing
light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material
fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and
landscape, keeping controls clear of system bars and navigation insets.
## [0.2.4] - 2026-08-22
- Save and reuse Android master-password defaults, with fingerprint unlock
available from the generator and settings screens.
- Clear unlocked master-password text and generated passwords from the Android
screen after a short timeout.
- Autosave Android generator defaults when length, counter, character classes,
excluded characters, or biometric display settings change.
- Keep Android form fields visible while the keyboard is open, with better
spacing around settings and excluded-character controls.
- Run the real Pass app at pass.waozi.xyz/app through the Kryon canvas UI,
replacing the standalone browser form.
- Publish Android releases as a universal APK plus per-ABI APKs.
## [0.2.3] - 2026-08-21
- Verify every download: releases now ship a SHA256SUMS file covering the
command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing
key, clearing the way for F-Droid distribution.
## [0.2.2] - 2026-08-20
- Install pass on Android: a signed APK is now downloadable from
+282 -54
View File
@@ -1,73 +1,301 @@
.PHONY: all cli gui native run test native-test web site install install-cli uninstall-cli install-gui uninstall-gui package-deb package-appimage android-debug
.DEFAULT_GOAL := all
ZIRAN ?= ./scripts/ziran.sh
# Gradle invokes make again for portable bundles. Inherited environment
# variables otherwise export these shell-derived paths while resolving them.
unexport ZIRAN_ROOT KRYON_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR TASKMGR_DIR ENTITY_DIR APPS_DIR AUTH_DIR CRYPTO_DIR
# Local overrides refer to the real root repositories. Published builds
# require the exact versions recorded in the committed lock.
LOCK_FLAGS := $(if $(wildcard ziran.local.toml),,--locked)
# Package resolution may build its compiler. Do not pass this make's target
# overrides or jobserver descriptors to that independent package build.
PACKAGE_ZIRAN = env -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(ZIRAN)
ZIRAN_ROOT = $(shell $(PACKAGE_ZIRAN) pkg path ziran $(LOCK_FLAGS))
KRYON_DIR = $(shell $(PACKAGE_ZIRAN) pkg path kryon $(LOCK_FLAGS))
MINGCUTE_DIR = $(shell $(PACKAGE_ZIRAN) pkg path mingcute $(LOCK_FLAGS))
# Account sync: ML-DSA-44 account keys from liboqs, and Ed25519, X25519,
# BLAKE2b and XChaCha20-Poly1305 from Monocypher.
LIBOQS_DIR = $(shell $(PACKAGE_ZIRAN) pkg path liboqs $(LOCK_FLAGS))
MONOCYPHER_DIR = $(shell $(PACKAGE_ZIRAN) pkg path monocypher $(LOCK_FLAGS))
QRCODE_DIR = $(shell $(PACKAGE_ZIRAN) pkg path qrcode $(LOCK_FLAGS))
WORKBOOK_DIR = $(shell $(PACKAGE_ZIRAN) pkg path workbook $(LOCK_FLAGS))
TASKMGR_DIR = $(shell $(PACKAGE_ZIRAN) pkg path taskmgr $(LOCK_FLAGS))
ENTITY_DIR = $(shell $(PACKAGE_ZIRAN) pkg path entity $(LOCK_FLAGS))
APPS_DIR = $(shell $(PACKAGE_ZIRAN) pkg path apps $(LOCK_FLAGS))
# Auth is its own package; SHA-256 and PBKDF2 come from the crypto package.
AUTH_DIR = $(shell $(PACKAGE_ZIRAN) pkg path auth $(LOCK_FLAGS))
CRYPTO_DIR = $(shell $(PACKAGE_ZIRAN) pkg path crypto $(LOCK_FLAGS))
# Qualified entries retain each package's import aliases while using the
# consumer's locked compiler, UI library and runtime.
PACKAGE_ID = $(shell python3 -c 'import json; print(json.load(open("ziran.lock"))["root"]["dependencies"]["$(1)"])')
LIBOQS_FLAGS := -DCMAKE_BUILD_TYPE=MinSizeRel -DBUILD_SHARED_LIBS=OFF -DOQS_BUILD_ONLY_LIB=ON \
-DOQS_USE_OPENSSL=OFF -DOQS_DIST_BUILD=OFF -DOQS_OPT_TARGET=generic '-DOQS_MINIMAL_BUILD=SIG_ml_dsa_44;KEM_ml_kem_768'
MONOCYPHER_SOURCES = $(MONOCYPHER_DIR)/src/monocypher.c $(MONOCYPHER_DIR)/src/optional/monocypher-ed25519.c
CC ?= cc
BIN_DIR ?= $(HOME)/bin
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
DESKTOP_DIR ?= $(shell xdg-user-dir DESKTOP 2>/dev/null)
# The tool bundles and Werkzeug's other files.
LIB_DIR ?= $(HOME)/.local/lib/werk
WEB_CC ?= $(if $(wildcard $(HOME)/emsdk/upstream/emscripten/emcc),$(HOME)/emsdk/upstream/emscripten/emcc,emcc)
SOURCES := $(wildcard src/*.zi apps/*/*.zi)
LIBRARY_SOURCES = $(wildcard $(KRYON_DIR)/src/ui/*.zi $(KRYON_DIR)/src/ui/*/module.zi $(KRYON_DIR)/src/backend/*.zi $(KRYON_DIR)/src/backend/*/module.zi $(ZIRAN_ROOT)/std/*.zi)
ZIRAN_RUNTIME_SOURCES = $(wildcard $(ZIRAN_ROOT)/cmd/zir/*.[ch] $(ZIRAN_ROOT)/include/*.h)
ENTITY_SOURCES = $(wildcard $(ENTITY_DIR)/src/*.zi $(ENTITY_DIR)/assets/entity/*)
CFLAGS := -std=c99 -O2 -Wno-unused-variable -I$(ZIRAN_ROOT)/include
PROJECT := --project $(LOCK_FLAGS)
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
KRYON_ARCH ?= $(shell uname -m)
KRYON_BUILD_DIR := vendor/kryon/build/linux-$(KRYON_ARCH)
KRYON_RUNTIME_SOURCES := $(shell find vendor/kryon/src vendor/kryon/include -type f)
.PHONY: all apps portable-apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test entity-account-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage
all: cli gui
cli:
go build -o pass ./cmd/pass
$(KRYON_BUILD_DIR)/libkryon.a: $(KRYON_RUNTIME_SOURCES) vendor/kryon/Makefile
$(MAKE) -C vendor/kryon -f Makefile all
gui: $(KRYON_BUILD_DIR)/libkryon.a
cd gui && go build -o ../build/pass-gui .
native: all
build/generated/cli/.complete: $(SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --target=c --entry cli:main -o $(@D) apps/pass/cli.zi
touch $@
build/pass: build/generated/cli/.complete
$(CC) $(CFLAGS) -Ibuild/generated/cli build/generated/cli/*.c -o $@
cli: build/pass
cp build/pass pass
# Each app is its own bundle, shared by the desktop, web and Android hosts.
APPS := pass calculator clock calendar gallery
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zx) build/apps/auth.zx build/apps/entity.zx build/apps/apps.zx build/apps/workbook.zx build/apps/taskmgr.zx
APP_BUNDLES := $(PORTABLE_BUNDLES)
CRYPTO_SOURCES = $(wildcard $(CRYPTO_DIR)/src/*.zi)
APPS_UI_SOURCES = $(wildcard $(APPS_DIR)/src/*.zi $(APPS_DIR)/ui/*.zi $(APPS_DIR)/ui/locales/*.json)
apps: $(APP_BUNDLES)
portable-apps: $(PORTABLE_BUNDLES)
# Compile the shared screen with the host's compiler and UI library. The
# reviewed payload must match both the build pin and the native host pin.
build/apps/apps.zx: $(APPS_UI_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock apps-controller.sha256 Makefile scripts/ziran.sh
mkdir -p $(@D)
python3 '$(APPS_DIR)/scripts/build-ui.py' --project $(CURDIR) --output $(abspath $(@D)) \
--compiler $(if $(findstring /,$(ZIRAN)),$(abspath $(ZIRAN)),$(ZIRAN))
test "$$(cat $(@D)/apps.sha256)" = "$$(cat apps-controller.sha256)"
.SECONDEXPANSION:
build/apps/%.zx: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root . --define KRYON_HOSTED_UI --define WERK_APP \
$(if $(wildcard apps/$*/assets),--asset-dir assets=apps/$*/assets) --entry $*:Main -o $@ apps/$*/$*.zi
build/apps/auth.zx: $(wildcard $(AUTH_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(AUTH_DIR)/src --define KRYON_HOSTED_UI --define WERK_APP \
--entry $(call PACKAGE_ID,auth)_auth:Main -o $@ $(AUTH_DIR)/src/auth.zi
build/apps/workbook.zx: $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(WORKBOOK_DIR)/src \
--define KRYON_HOSTED_UI --entry $(call PACKAGE_ID,workbook)_app:Main -o $@ $(WORKBOOK_DIR)/src/app.zi
build/apps/taskmgr.zx: $(wildcard $(TASKMGR_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(TASKMGR_DIR)/src \
--define KRYON_HOSTED_UI --entry $(call PACKAGE_ID,taskmgr)_hosted:Main -o $@ $(TASKMGR_DIR)/src/hosted.zi
# These portable apps use their public package exports. Their UI sources may
# advance independently; all bundles are emitted by this host's compiler.
build/apps/gallery.zx: $(wildcard apps/gallery/*.zi) apps/gallery/ziran.toml apps/gallery/ziran.lock ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root . --define KRYON_HOSTED_UI --entry gallery:Main -o $@ apps/gallery/gallery.zi
build/apps/entity.zx: $(ENTITY_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle $(PROJECT) --root $(ENTITY_DIR)/src --define KRYON_HOSTED_UI \
--asset-dir assets=$(ENTITY_DIR)/assets --entry $(call PACKAGE_ID,entity)_entity:Main -o $@ $(ENTITY_DIR)/src/entity.zi
# The portable bundle runtime the host links, built from the locked Ziran.
.PHONY: runtime-cache-force
runtime-cache-force:
build/ziran/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/ziran)"
build/ziran/libziran.a: ziran.lock $(ZIRAN_RUNTIME_SOURCES) build/ziran/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
build/generated/desktop/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(wildcard $(TASKMGR_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ENTITY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_DESKTOP --target=c --entry desktop:main -o $(@D) src/desktop.zi
touch $@
build/liboqs/lib/liboqs.a: ziran.lock
cmake -S $(LIBOQS_DIR) -B build/liboqs $(LIBOQS_FLAGS) > /dev/null
cmake --build build/liboqs --target oqs > /dev/null
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 $@.new
mv -f $@.new $@
build/pfp.webp: $(KRYON_DIR)/icons/pfp.webp
cp $< $@
# Launcher artwork for the bundled tools, beside the host like pfp.webp.
TOOL_ICONS := $(wildcard assets/tools/*.webp)
build/tools/%.webp: assets/tools/%.webp
mkdir -p $(@D)
cp $< $@
gui: build/werk build/pfp.webp $(TOOL_ICONS:assets/%=build/%) apps
run: gui
./build/pass-gui
./build/werk
source-check:
python3 scripts/source_check.py
$(ZIRAN) fmt --check $(SOURCES) tests/*.zi
core-test ziran-core-test:
sh scripts/ziran_core_test.sh "$(ZIRAN)"
pass-state-test:
sh scripts/pass_state_test.sh "$(ZIRAN)"
app-logic-test:
sh scripts/app_logic_test.sh "$(ZIRAN)"
cli-test: cli
sh scripts/cli_test.sh ./pass
lesspass-compat-test: cli
python3 scripts/lesspass_compat_test.py --cli ./pass
entity-account-test: build/liboqs/lib/liboqs.a
ZIRAN_BIN=$(ZIRAN) python3 scripts/entity_account_test.py
.PHONY: android-sdk-install-test
android-sdk-install-test:
python3 scripts/install_android_sdk_test.py
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test android-sdk-install-test android-apk-check-test android-startup-test runtime-cache-test gallery-test
.PHONY: android-startup-test
android-startup-test:
python3 scripts/android_startup_test.py
.PHONY: android-apk-check-test
android-apk-check-test:
python3 scripts/android_apk_check_test.py
.PHONY: runtime-cache-test
runtime-cache-test:
python3 scripts/runtime_cache_test.py
gui-smoke: gui
sh scripts/gui_smoke.sh
gui-test: gui
python3 scripts/private-display.py python3 scripts/apps_gui_test.py
python3 scripts/private-display.py python3 scripts/calendar_taskmgr_gui_test.py
sh scripts/werk_gui_test.sh
python3 scripts/private-display.py python3 scripts/workbook_gui_test.py
WERK_TEST_ZIRAN="$(ZIRAN)" python3 scripts/private-display.py python3 scripts/launcher_gui_test.py
sh scripts/migration_test.sh
python3 -I scripts/auth_command_test.py
python3 scripts/private-display.py python3 scripts/auth_gui_test.py
# The bundle runtime for the browser, built from the locked Ziran.
WEB_AR ?= $(dir $(WEB_CC))emar
build/web-runtime/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/web-runtime)"
build/web-runtime/libziran.a: Makefile ziran.lock build/web-runtime/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BOOTSTRAP=0 BUILD_DIR=$(abspath build/web-runtime) \
GEN_ZI2C=$(ZIRAN_ROOT)/build/bin/zi2c BOOTSTRAP_BIN=$(ZIRAN_ROOT)/build/bootstrap/bin/zi2c \
CC=$(WEB_CC) AR=$(WEB_AR) OBJCOPY=true CFLAGS=-O2 $(abspath $@)
build/generated/browser/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(wildcard $(TASKMGR_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target-os web --target-cpu wasm32 --target=c -o $(@D) src/browser.zi
touch $@
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(PORTABLE_BUNDLES) build/pfp.webp $(TOOL_ICONS) assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
mkdir -p $(@D)
$(WEB_CC) -O2 -Wno-parentheses-equality -I$(ZIRAN_ROOT)/include -iquote build/generated/browser build/generated/browser/*.c \
build/web-runtime/libziran.a \
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sEXPORTED_RUNTIME_METHODS=FS,IDBFS -lidbfs.js \
-sASYNCIFY -sALLOW_MEMORY_GROWTH=1 -sSTACK_SIZE=16777216 -sASYNCIFY_STACK_SIZE=1048576 -sENVIRONMENT=web \
--embed-file assets/fonts/NotoSans-Regular.ttf@/kryon-font.ttf \
$(foreach bundle,$(PORTABLE_BUNDLES),--embed-file $(bundle)@/apps/$(notdir $(bundle))) --embed-file build/pfp.webp@/pfp.webp --embed-file assets/tools@/tools --embed-file assets/app/icon.png@/icon.png -o $@
build/web-app/index.html: build/web-app/index.js web/site/index.html
cp web/site/index.html $@
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --target=c -o $(@D) src/service_worker.zi
touch $@
build/web-app/sw.js: build/generated/worker/.complete
$(WEB_CC) -O2 -I$(ZIRAN_ROOT)/include -iquote build/generated/worker build/generated/worker/*.c \
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sENVIRONMENT=worker -sNO_EXIT_RUNTIME=1 \
-sSINGLE_FILE=1 -sWASM_ASYNC_COMPILATION=0 -o $@
web-canvas: build/web-app/index.html build/web-app/sw.js
web site: web-canvas
./web/build.sh
web-smoke: site
bash scripts/web_smoke.sh
# CMake emits JNI and foreign ABI types separately for each Android ABI.
android-debug: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-universal-debug.apk build/werk-android-debug.apk
python3 scripts/android_apk_check.py build/werk-android-debug.apk
cp droid/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/werk-android-arm64-v8a-debug.apk
cp droid/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/werk-android-armeabi-v7a-debug.apk
android-emulator: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-debug.apk build/werk-android-emulator.apk
python3 scripts/android_apk_check.py build/werk-android-emulator.apk
android-release: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
.PHONY: android-bundle
android-bundle: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
cp droid/app/build/outputs/bundle/release/app-release.aab build/werk-$(shell cat VERSION).aab
.PHONY: android-fdroid
# F-Droid compares this source build with the signed upstream release.
android-fdroid:
$(MAKE) android-release GRADLE_ARGS="$(GRADLE_ARGS) -PfDroidBuild=true"
mkdir -p build/fdroid
cp droid/app/build/outputs/apk/release/app-universal-release-unsigned.apk build/fdroid/werk.apk
python3 scripts/android_apk_check.py build/fdroid/werk.apk
android-smoke:
bash scripts/android_smoke.sh
android-input-test:
$(MAKE) android-profile-test
$(MAKE) workbook-android-test
$(MAKE) gallery-android-test
.PHONY: android-profile-test workbook-android-test gallery-android-test
android-profile-test:
python3 scripts/android_input_test.py
workbook-android-test:
python3 scripts/workbook_android_test.py
gallery-android-test:
python3 scripts/android_gallery_test.py
check-package-urls:
bash scripts/check_package_urls.sh
e2e: check-package-urls test gui-smoke gui-test web-smoke android-debug
install: install-cli install-gui
install-cli: cli
mkdir -p $(BIN_DIR)
install -m 0755 pass $(BIN_DIR)/pass
install-gui: gui
mkdir -p "$(BIN_DIR)" "$(DATA_DIR)/applications" "$(DATA_DIR)/icons/hicolor/512x512/apps" "$(DATA_DIR)/mime/packages"
install -d -m 0700 "$(LIB_DIR)" "$(LIB_DIR)/apps"
install -m 0755 build/werk "$(BIN_DIR)/werk.new"
mv -f "$(BIN_DIR)/werk.new" "$(BIN_DIR)/werk"
install -m 0600 $(APP_BUNDLES) "$(LIB_DIR)/apps/"
install -m 0644 build/pfp.webp "$(LIB_DIR)/pfp.webp"
install -d -m 0755 "$(LIB_DIR)/tools"
install -m 0644 $(TOOL_ICONS) "$(LIB_DIR)/tools/"
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" --bin-dir "$(BIN_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)")
install -m 0644 packaging/linux/werk-bundle.xml "$(DATA_DIR)/mime/packages/werk-bundle.xml"
@if command -v update-mime-database >/dev/null; then update-mime-database "$(DATA_DIR)/mime"; fi
@if command -v update-desktop-database >/dev/null; then update-desktop-database "$(DATA_DIR)/applications"; fi
uninstall-cli:
rm -f $(BIN_DIR)/pass
install-gui: gui
mkdir -p $(BIN_DIR) $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
install -m 0755 build/pass-gui $(BIN_DIR)/pass-gui
cp packaging/linux/xyz.waozi.pass.desktop $(DATA_DIR)/applications/xyz.waozi.pass.desktop
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/pass.png
uninstall-gui:
rm -f $(BIN_DIR)/pass-gui $(DATA_DIR)/applications/xyz.waozi.pass.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/pass.png
test:
go test ./...
cd gui && go test ./...
# Checks the C generator (used by the Android app) against the same fixed
# vectors as the Go tests.
native-test:
cc -Wall -Wextra -O2 -Inative native/pass_core.c native/pass_core_test.c -o build/pass_core_test
./build/pass_core_test
ANDROID_DIR := droid
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
android-debug:
cd $(ANDROID_DIR) && ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS)
mkdir -p build
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-debug.apk build/pass-android-debug.apk
web:
./web/build.sh
site: web
test -f build/site/index.html
test -f build/site/app/pass.wasm
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)") --uninstall
rm -f $(BIN_DIR)/werk
rm -rf $(LIB_DIR)
package-deb: gui
./scripts/package-deb.sh
package-appimage: gui
./scripts/package-appimage.sh
.PHONY: gallery-test gallery-gui-test
gallery-test:
rm -rf build/gallery-test-generated
mkdir -p build/gallery-test-generated
$(ZIRAN) build $(PROJECT) --root . --target=c --entry gallery_test:Check -o build/gallery-test-generated tests/gallery_test.zi
printf '%s\n' '#include "tests/gallery_test.h"' 'int main(void) { return Check(); }' > build/gallery-test-generated/main.c
$(CC) -std=c11 -O2 -I$(ZIRAN_ROOT)/include -Ibuild/gallery-test-generated $$(find build/gallery-test-generated -name '*.c' -print) -o build/gallery-test
python3 scripts/gallery_gui_test.py --behavioral-only
gallery-gui-test: gui gallery-test
python3 scripts/private-display.py dbus-run-session -- python3 scripts/gallery_gui_test.py
+35 -114
View File
@@ -1,127 +1,48 @@
# pass
<p align="center">
<img src="fastlane/metadata/android/en-US/images/featureGraphic.png" alt="Werkzeug" width="100%">
</p>
Website and browser app: [pass.waozi.xyz](https://pass.waozi.xyz/)
# Werkzeug
`pass` is a stateless password generator: the same site, login, master
password, and settings produce the same result without a password database.
It is a new, independently written implementation of the LessPass generation
algorithm. Compatibility does not imply endorsement by or affiliation with the
LessPass project.
Small, private tools for everyday life. Generate passwords, manage sign-in
codes, calculate and keep time in one free, open-source app.
## Install
[Try it online](https://werk.waozi.xyz/)
· [Download the latest release](https://github.com/waozixyz/werk/releases/latest)
· [What's new](CHANGELOG.md)
Prebuilt CLI and desktop downloads are available from
[pass.waozi.xyz](https://pass.waozi.xyz/#downloads).
## Your everyday tools
With Go 1.24 or newer:
- **Pass:** generate the same password from your site, login, master password and settings. Save profiles without keeping a password database.
- **Auth:** keep two-factor sign-in codes together. Tap anywhere on a card to copy its current code, or use Edit to change the account.
- **Calculator:** everyday arithmetic and scientific functions, with a keypad or keyboard.
- **Clock:** see the local time and use a stopwatch that keeps running while the app is closed.
- **Workbook:** edit spreadsheets on Linux, Android and the web, with formulas, sheet tabs and portable workbook files.
- **Gallery:** browse local photo folders and albums on Linux and Android. Open a photo, move between pictures and zoom; your photos stay local.
```sh
go install github.com/waozixyz/pass/cmd/pass@latest
```
<p align="center">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-pass.png" alt="Pass password generation" width="30%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/03-auth.png" alt="Auth sign-in codes" width="30%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04-calculator.png" alt="Scientific calculator" width="30%">
</p>
Or build the command from a checkout:
## Make it yours
```sh
go build ./cmd/pass
```
Choose light or dark appearance, an accent color and your profile picture.
On Linux, open each tool directly from its own application-menu or Desktop
shortcut, with its own icon.
## Use
## Your data and choices
```text
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
```
Password generation and local tools work on your device. Account sync and
node connections are optional. Each tool keeps its own private files.
The default password has 16 characters and includes lowercase letters,
uppercase letters, digits, and symbols. The default counter is 1.
Werkzeug was formerly Pass. Android keeps the original `xyz.waozi.pass`
package and signing certificate so existing Pass installations can update
to Werkzeug while keeping their saved data.
Passing a master password as an argument can expose it to process inspection
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads from the controlling terminal or console
with echo disabled. Use `--prompt` to bypass the environment and always ask. For
example:
[F-Droid update submission (draft)](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/53909)
· [Report a problem](https://github.com/waozixyz/werk/issues)
· [Build, command-line tools and data details](docs/development.md)
```sh
pass --prompt example.com alice
pass --length 24 --counter 2 example.com alice
pass --no-symbols --exclude '0O1Il' example.com alice
```
`--copy` sends the result to the clipboard without printing it. On Linux a
built-in pure-Go X11 clipboard is used when an X server (X.Org, Xlibre, or
XWayland) is reachable, so no external tool is needed; otherwise `pass`
falls back to `wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe` and reports
an error if none can be used. The copied password is served by a small
detached process and disappears when another application takes the clipboard;
`--clear-after 90s` releases it automatically after a delay (built-in X11
clipboard only), and `--read-clipboard` prints the current contents.
## Profiles
An optional configuration file at `$XDG_CONFIG_HOME/pass/profiles.json`
(usually `~/.config/pass/profiles.json`) can store named profiles — a login
plus default settings — so daily invocations shrink to one flag:
```sh
pass --profile work example.com
```
```json
{
"vault": "~/.vault",
"copy": true,
"clear_after": "90s",
"profiles": {
"work": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
}
}
```
Profiles hold no secrets. Command-line flags always win over profile values,
and without a configuration file pass behaves exactly as before.
## Master password from a vault
`--vault PATH` reads the master password from a file encrypted with OpenSSL:
```sh
printf 'master password' | openssl enc -aes-256-cbc -md sha512 -a \
-pbkdf2 -iter 100000 -salt -pass pass:... > ~/.vault
pass --vault ~/.vault example.com alice
```
The vault passphrase is requested on the terminal with echo disabled, or read
from piped standard input, and the decrypted contents are used as the master
password — the master itself never appears in argv or the environment. The
vault path can also be set once in the profiles file.
Run `pass --help` for all flags.
## Desktop app
The optional desktop app is written in Go with Kryon and calls the same
generator package directly. It keeps the master password in process memory,
masks the master-password field, and clears copied passwords after 20 seconds
unless the clipboard has since been replaced.
```sh
git submodule update --init --recursive
make gui
./build/pass-gui
```
## Library
```go
settings := pass.DefaultOptions()
result, err := pass.Generate("example.com", "alice", master, settings)
```
All inputs are interpreted as UTF-8 strings. Excluded characters are removed
from every enabled character class; generation fails if a class becomes empty,
all classes are disabled, or the requested length cannot include one character
from each class.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
[`LICENSE`](LICENSE).
BSD 3-Clause. See [LICENSE](LICENSE).
+1
View File
@@ -0,0 +1 @@
0.4.7
+1
View File
@@ -0,0 +1 @@
7a9599b7e728333c237b2bf23cdf9fb985f4a3c82f9cc0ba4dd16434ac876c12
+550
View File
@@ -0,0 +1,550 @@
// Evaluates calculator expressions: + − × ÷ (also - * /), ^ for powers,
// postfix %, ², ³, ! and ⁻¹, unary signs, brackets, the functions sin cos tan
// and their inverses (sin⁻¹ or asin) and hyperbolic forms, ln, log, √, ∛,
// abs and exp, the constants π, e and Ans, and E for a power of ten, as in
// 6.02E23. A number, constant or function next to another multiplies, so
// 2π and 3sin(30) work. Brackets left open at the end are closed there.
#import "text_buffer"
#import "number_text"
#import "math"
Answer :: struct {
valid: bool
value: float64
error: string
}
source: string;
position: s32;
failure: string;
// Trigonometric angles are degrees when set, otherwise radians.
degrees: bool;
// The last result, for Ans.
last_answer: float64;
PI_VALUE :: 3.141592653589793
E_VALUE :: 2.718281828459045
EvaluateExpression :: (text: string) -> Answer {
source = text
position = 0
failure = ""
value := ParseSum()
SkipSpaces()
if failure == "" && position < cast(s32)source.count {
failure = "Cannot read this expression"
}
if failure == "" && value != value {
failure = "Not a real number"
}
if failure == "" && !Finite(value) {
failure = "Result is too large"
}
if failure != "" {
return Answer.{.error = failure}
}
if value == 0.0 {
value = 0.0
}
return Answer.{.valid = true, .value = value}
}
Finite :: (value: float64) -> bool {
return value == value && value < 1.0e300 && value > -1.0e300
}
SkipSpaces :: () {
while position < cast(s32)source.count && source[position] == cast(u8)32 {
position += 1
}
}
// Whether the next text is the given one, consuming it when it is.
Take :: (symbol: string) -> bool {
SkipSpaces()
end := position + cast(s32)symbol.count
if end > cast(s32)source.count || source[position:end] != symbol {
return false
}
position = end
return true
}
// Whether the next text is the given one, without consuming it.
Peek :: (symbol: string) -> bool {
SkipSpaces()
end := position + cast(s32)symbol.count
return end <= cast(s32)source.count && source[position:end] == symbol
}
ParseSum :: () -> float64 {
value := ParseProduct()
while failure == "" {
if Take("+") {
value += ParseProduct()
} else if Take("-") || Take("−") {
value -= ParseProduct()
} else {
return value
}
}
return value
}
ParseProduct :: () -> float64 {
value := ParseSigned()
while failure == "" {
if Take("×") || Take("*") {
value *= ParseSigned()
} else if Take("÷") || Take("/") {
divisor := ParseSigned()
if divisor == 0.0 {
failure = "Cannot divide by zero"
return 0.0
}
value /= divisor
} else if StartsFactor() {
value *= ParsePower()
} else {
return value
}
}
return value
}
// A factor follows without an operator, so the two multiply.
StartsFactor :: () -> bool {
SkipSpaces()
if position >= cast(s32)source.count {
return false
}
byte := source[position]
if IsDigit(byte) || byte == cast(u8)46 || byte == cast(u8)40 {
return true
}
// Letters start functions and constants; E alone is a number's exponent.
if byte >= cast(u8)97 && byte <= cast(u8)122 || byte == cast(u8)65 {
return true
}
return Peek("π") || Peek("√") || Peek("∛")
}
ParseSigned :: () -> float64 {
if Take("-") || Take("−") {
return 0.0 - ParseSigned()
}
if Take("+") {
return ParseSigned()
}
return ParsePower()
}
ParsePower :: () -> float64 {
base := ParsePostfix()
if failure == "" && Take("^") {
exponent := ParseSigned()
return Power(base, exponent)
}
return base
}
ParsePostfix :: () -> float64 {
value := ParseAtom()
while failure == "" {
if Take("%") {
value /= 100.0
} else if Take("²") {
value *= value
} else if Take("³") {
value = value * value * value
} else if Take("⁻¹") {
if value == 0.0 {
failure = "Cannot divide by zero"
return 0.0
}
value = 1.0 / value
} else if Take("!") {
value = Factorial(value)
} else {
return value
}
}
return value
}
ParseAtom :: () -> float64 {
if failure != "" {
return 0.0
}
if Take("(") {
return Bracketed()
}
if Take("π") || Take("pi") {
return PI_VALUE
}
if Take("Ans") {
return last_answer
}
if Take("√") || Take("sqrt") {
return Root(Argument(), 2)
}
if Take("∛") || Take("cbrt") {
return Root(Argument(), 3)
}
// Longer names first: sinh⁻¹ before sinh before sin.
names: [21]string = .["sinh⁻¹", "cosh⁻¹", "tanh⁻¹", "asinh", "acosh", "atanh",
"sin⁻¹", "cos⁻¹", "tan⁻¹", "asin", "acos", "atan",
"sinh", "cosh", "tanh", "sin", "cos", "tan", "ln", "log", "abs"]
operations: [21]s32 = .[10, 11, 12, 10, 11, 12, 4, 5, 6, 4, 5, 6, 7, 8, 9, 1, 2, 3, 13, 14, 15]
index: s32 = 0
while index < 21 {
if Take(names[index]) {
return Apply(operations[index], Argument())
}
index += 1
}
if Take("exp") {
return Exponential(Argument())
}
if Take("e") {
return E_VALUE
}
return ParseNumber()
}
Bracketed :: () -> float64 {
value := ParseSum()
// A bracket still open at the end closes there.
SkipSpaces()
if !Take(")") && position < cast(s32)source.count && failure == "" {
failure = "Missing closing bracket"
}
return value
}
// A function's argument: a bracketed expression, or the signed value that
// follows, as in √9 or sin 30.
Argument :: () -> float64 {
if Take("(") {
return Bracketed()
}
return ParseSigned()
}
Apply :: (operation: s32, value: float64) -> float64 {
if failure != "" {
return 0.0
}
if operation == 1 {
return Sine(value)
}
if operation == 2 {
return Cosine(value)
}
if operation == 3 {
return Tangent(value)
}
if operation >= 4 && operation <= 6 {
if operation != 6 && (value > 1.0 || value < -1.0) {
failure = "Not a real number"
return 0.0
}
angle := ifx operation == 4 then Asin(value) else ifx operation == 5 then Acos(value) else Atan(value)
return ifx degrees then angle * 180.0 / PI_VALUE else angle
}
if operation == 7 {
return Sinh(value)
}
if operation == 8 {
return Cosh(value)
}
if operation == 9 {
return Tanh(value)
}
if operation == 10 {
return Asinh(value)
}
if operation == 11 {
return Checked(Acosh(value))
}
if operation == 12 {
if value >= 1.0 || value <= -1.0 {
failure = ifx value == 1.0 || value == -1.0 then "Result is too large" else "Not a real number"
return 0.0
}
return Atanh(value)
}
if operation == 13 || operation == 14 {
if value <= 0.0 {
failure = ifx value == 0.0 then "Result is too large" else "Not a real number"
return 0.0
}
return ifx operation == 13 then Log(value) else Log10Exact(value)
}
return ifx value < 0.0 then 0.0 - value else value
}
// A NaN from a function outside its domain is an error, not a value.
Checked :: (value: float64) -> float64 {
if value != value && failure == "" {
failure = "Not a real number"
return 0.0
}
return value
}
// log10 exactly for powers of ten, which people expect to be whole.
Log10Exact :: (value: float64) -> float64 {
result := Log10(value)
nearest := cast(float64)RoundToInteger(result)
if nearest - result < 1.0e-12 && result - nearest < 1.0e-12 && Power(10.0, nearest) == value {
return nearest
}
return result
}
// An angle in degrees, reduced to [0, 360).
Degrees360 :: (value: float64) -> float64 {
turns := cast(float64)RoundToInteger(value / 360.0)
reduced := value - turns * 360.0
if reduced < 0.0 {
reduced += 360.0
}
return reduced
}
Radians :: (value: float64) -> float64 {
return ifx degrees then value * PI_VALUE / 180.0 else value
}
// In degrees, whole quarter turns give exact results: sin 180° is 0.
Sine :: (value: float64) -> float64 {
if degrees && value < 1.0e15 && value > -1.0e15 {
reduced := Degrees360(value)
if reduced == 0.0 || reduced == 180.0 {
return 0.0
}
if reduced == 90.0 {
return 1.0
}
if reduced == 270.0 {
return -1.0
}
if reduced == 30.0 || reduced == 150.0 {
return 0.5
}
if reduced == 210.0 || reduced == 330.0 {
return -0.5
}
}
return Sin(Radians(value))
}
Cosine :: (value: float64) -> float64 {
if degrees && value < 1.0e15 && value > -1.0e15 {
reduced := Degrees360(value)
if reduced == 90.0 || reduced == 270.0 {
return 0.0
}
if reduced == 0.0 {
return 1.0
}
if reduced == 180.0 {
return -1.0
}
if reduced == 60.0 || reduced == 300.0 {
return 0.5
}
if reduced == 120.0 || reduced == 240.0 {
return -0.5
}
}
return Cos(Radians(value))
}
Tangent :: (value: float64) -> float64 {
if degrees && value < 1.0e15 && value > -1.0e15 {
reduced := Degrees360(value)
if reduced == 90.0 || reduced == 270.0 {
failure = "Undefined"
return 0.0
}
if reduced == 0.0 || reduced == 180.0 {
return 0.0
}
if reduced == 45.0 || reduced == 225.0 {
return 1.0
}
if reduced == 135.0 || reduced == 315.0 {
return -1.0
}
}
return Tan(Radians(value))
}
Root :: (value: float64, degree: s32) -> float64 {
if failure != "" {
return 0.0
}
if degree == 2 {
if value < 0.0 {
failure = "Not a real number"
return 0.0
}
return Sqrt(value)
}
return Cbrt(value)
}
Exponential :: (value: float64) -> float64 {
if failure != "" {
return 0.0
}
return Exp(value)
}
Factorial :: (value: float64) -> float64 {
whole := RoundToInteger(value)
if value < 0.0 || cast(float64)whole != value {
failure = "Factorial needs a whole number"
return 0.0
}
if whole > 170 {
failure = "Result is too large"
return 0.0
}
result: float64 = 1.0
factor: s64 = 2
while factor <= whole {
result *= cast(float64)factor
factor += 1
}
return result
}
ParseNumber :: () -> float64 {
SkipSpaces()
value: float64 = 0.0
digits: s32 = 0
while position < cast(s32)source.count && IsDigit(source[position]) {
value = value * 10.0 + cast(float64)(source[position] - cast(u8)48)
position += 1
digits += 1
}
if position < cast(s32)source.count && source[position] == cast(u8)46 {
position += 1
scale: float64 = 0.1
while position < cast(s32)source.count && IsDigit(source[position]) {
value += cast(float64)(source[position] - cast(u8)48) * scale
scale /= 10.0
position += 1
digits += 1
}
}
if digits == 0 {
failure = ifx position >= cast(s32)source.count then "Incomplete expression" else "Cannot read this expression"
return value
}
// E and a whole power of ten: 6.02E23, 1E−5.
if position < cast(s32)source.count && source[position] == cast(u8)69 {
position += 1
negative := false
if Take("-") || Take("−") {
negative = true
} else {
unused Take("+")
}
power: s64 = 0
power_digits: s32 = 0
while position < cast(s32)source.count && IsDigit(source[position]) && power < 100000 {
power = power * 10 + cast(s64)(source[position] - cast(u8)48)
position += 1
power_digits += 1
}
if power_digits == 0 {
failure = ifx position >= cast(s32)source.count then "Incomplete expression" else "Cannot read this expression"
return value
}
value *= Power(10.0, cast(float64)(ifx negative then 0 - power else power))
}
return value
}
IsDigit :: (byte: u8) -> bool {
return byte >= cast(u8)48 && byte <= cast(u8)57
}
// Whole exponents multiply exactly; others use the real power, which a
// negative base does not have.
Power :: (base: float64, exponent: float64) -> float64 {
if failure != "" {
return 0.0
}
if base == 0.0 && exponent < 0.0 {
failure = "Cannot divide by zero"
return 0.0
}
whole := cast(float64)RoundToInteger(exponent) == exponent && exponent < 1.0e15 && exponent > -1.0e15
if base < 0.0 && !whole {
failure = "Not a real number"
return 0.0
}
return Pow(base, exponent)
}
// Up to ten significant digits; very large and very small numbers use an
// exponent, such as 1.5e20.
FormatNumber :: (value: float64, output: []u8) -> string {
magnitude := ifx value < 0.0 then 0.0 - value else value
if magnitude != 0.0 && (magnitude >= 1.0e15 || magnitude < 1.0e-9) {
return FormatExponent(value, output)
}
whole_digits: s32 = 1
bound: float64 = 10.0
while magnitude >= bound && whole_digits < 15 {
bound *= 10.0
whole_digits += 1
}
places := 10 - whole_digits
if places < 0 {
places = 0
}
if places > 9 {
places = 9
}
return FormatDecimal(value, places, output)
}
FormatExponent :: (value: float64, output: []u8) -> string {
negative := value < 0.0
mantissa := ifx negative then 0.0 - value else value
exponent: s32 = 0
while mantissa >= 10.0 {
mantissa /= 10.0
exponent += 1
}
while mantissa < 1.0 {
mantissa *= 10.0
exponent -= 1
}
digits: [32]u8
text := FormatDecimal(ifx negative then 0.0 - mantissa else mantissa, 9, digits[:])
power: [24]u8
exponent_text := FormatInteger(cast(s64)exponent, power[:])
used: s32 = 0
used = AppendTo(output, used, text)
used = AppendTo(output, used, "e")
used = AppendTo(output, used, exponent_text)
return TextView(output[0:used])
}
AppendTo :: (output: []u8, used: s32, text: string) -> s32 {
index: s32 = 0
while index < cast(s32)text.count && used < cast(s32)output.count - 1 {
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
+76
View File
@@ -0,0 +1,76 @@
// The Calculator's expressions and number formatting.
#import "arithmetic"
Shows :: (expression: string, expected: string) -> bool {
answer := EvaluateExpression(expression)
if !answer.valid {
return false
}
output: [64]u8
return FormatNumber(answer.value, output[:]) == expected
}
Refuses :: (expression: string) -> bool {
return !EvaluateExpression(expression).valid
}
#program_export
Run :: () -> s32 {
degrees = false
if !Shows("12+30×2", "72") || !Shows("12+30*2", "72") || !Shows("(1+2)×3", "9") {
return 1
}
if !Shows("7÷2", "3.5") || !Shows("1÷3", "0.333333333") || !Shows("2^10", "1024") {
return 2
}
if !Shows("50%", "0.5") || !Shows("−4+1", "-3") || !Shows("2×(3+4", "14") {
return 3
}
if !Shows("0.1+0.2", "0.3") || !Shows("10^20", "1e20") || !Shows("2^-2", "0.25") {
return 4
}
if !Refuses("1÷0") || !Refuses("3+") || !Refuses("4)") || !Refuses("(−8)^0.5") {
return 5
}
// Powers, roots and logarithms.
if !Shows("2^0.5", "1.414213562") || !Shows("√144", "12") || !Shows("√(2)", "1.414213562") ||
!Shows("∛27", "3") || !Shows("∛(−8)", "-2") || !Shows("3²", "9") || !Shows("2³", "8") {
return 6
}
if !Shows("ln(e)", "1") || !Shows("log(1000)", "3") || !Shows("e^(2)", "7.389056099") ||
!Shows("10^(3)", "1000") || !Shows("exp(1)", "2.718281828") || !Refuses("ln(−1)") || !Refuses("√(−4)") {
return 7
}
// Factorials, reciprocals, constants, Ans and E notation.
if !Shows("5!", "120") || !Shows("0!", "1") || !Shows("4⁻¹", "0.25") || !Shows("2π", "6.283185307") ||
!Shows("π", "3.141592654") || !Refuses("2.5!") || !Refuses("171!") || !Refuses("0⁻¹") {
return 8
}
last_answer = 21.0
if !Shows("Ans×2", "42") || !Shows("6.02E23", "6.02e23") || !Shows("1E−3", "0.001") || !Shows("2(3+4)", "14") ||
!Shows("abs(−7)", "7") || !Shows("3sqrt(16)", "12") {
return 9
}
// Radians.
if !Shows("sin(π÷2)", "1") || !Shows("cos(0)", "1") || !Shows("tan(π÷4)", "1") ||
!Shows("sin⁻¹(1)", "1.570796327") || !Shows("atan(1)×4", "3.141592654") {
return 10
}
// Degrees, with exact quarter turns.
degrees = true
if !Shows("sin(30)", "0.5") || !Shows("sin(180)", "0") || !Shows("cos(90)", "0") || !Shows("cos(−60)", "0.5") ||
!Shows("tan(45)", "1") || !Refuses("tan(90)") || !Shows("sin(390)", "0.5") || !Shows("sin 30 + 1", "1.5") {
return 11
}
if !Shows("sin⁻¹(0.5)", "30") || !Shows("cos⁻¹(0)", "90") || !Shows("tan⁻¹(1)", "45") || !Refuses("asin(2)") {
return 12
}
degrees = false
// Hyperbolic functions and their inverses.
if !Shows("sinh(1)", "1.175201194") || !Shows("cosh(0)", "1") || !Shows("tanh(1)", "0.761594156") ||
!Shows("sinh⁻¹(1)", "0.881373587") || !Shows("cosh⁻¹(2)", "1.316957897") ||
!Shows("tanh⁻¹(0.5)", "0.549306144") || !Refuses("acosh(0.5)") || !Refuses("atanh(1)") {
return 13
}
return 0
}
+457
View File
@@ -0,0 +1,457 @@
Box :: #import "kryon/box";
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Calculator: a keypad and keyboard calculator. Basic covers ordinary
// arithmetic with brackets; Scientific adds trigonometry in degrees or
// radians, hyperbolic functions, powers, roots, logarithms, factorials and
// constants. It keeps the expression in memory; the mode and angle unit are
// saved.
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/text_align"
#import "kryon/control_props"
#import "std/text_buffer"
#import "std/number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "arithmetic"
Icon :: #import "mingcute/mingcute_regular_counter";
DeleteBack :: #import "mingcute/mingcute_regular_delete_back";
using ButtonTone;
using ButtonEmphasis;
EXPRESSION_LIMIT :: 256
expression: [EXPRESSION_LIMIT]u8;
expression_length: s32;
result_text: [64]u8;
// The expression shows the last result, which typing a number replaces.
showing_result: bool;
loaded: bool;
scientific: bool;
// One-shot shifts for the next scientific function key.
second: bool;
hyperbolic: bool;
ExpressionText :: () -> string {
return TextView(expression[0:expression_length])
}
Clear :: () {
expression_length = 0
result_text[0] = cast(u8)0
showing_result = false
}
// Whether text begins a new value rather than continuing the last one: a
// result is replaced by a number, constant or function, and continued by
// an operator.
StartsValue :: (text: string) -> bool {
first := text[0]
if first >= cast(u8)48 && first <= cast(u8)57 || first == cast(u8)46 || first == cast(u8)40 {
return true
}
if first >= cast(u8)97 && first <= cast(u8)122 || first == cast(u8)65 {
return true
}
count := cast(s32)text.count
return count >= 2 && text[0:2] == "π" || count >= 3 && (text[0:3] == "√" || text[0:3] == "∛")
}
Append :: (text: string) {
if text.count == 0 {
return
}
if showing_result && StartsValue(text) {
expression_length = 0
}
showing_result = false
result_text[0] = cast(u8)0
if expression_length + cast(s32)text.count > EXPRESSION_LIMIT {
return
}
index: s32 = 0
while index < cast(s32)text.count {
expression[expression_length] = text[index]
expression_length += 1
index += 1
}
}
Backspace :: () {
showing_result = false
result_text[0] = cast(u8)0
if expression_length == 0 {
return
}
expression_length -= 1
// Remove a whole UTF-8 sequence, such as the multiplication sign.
while expression_length > 0 && (expression[expression_length] & cast(u8)0xC0) == cast(u8)0x80 {
expression_length -= 1
}
}
Evaluate :: () {
if expression_length == 0 {
return
}
answer := EvaluateExpression(ExpressionText())
if !answer.valid {
CopyResult(answer.error)
return
}
last_answer = answer.value
formatted: [64]u8
text := FormatNumber(answer.value, formatted[:])
expression_length = 0
Append(text)
showing_result = true
result_text[0] = cast(u8)0
}
CopyResult :: (text: string) {
index: s32 = 0
while index < cast(s32)text.count && index < 63 {
result_text[index] = text[index]
index += 1
}
result_text[index] = cast(u8)0
}
// calculator.txt holds "scientific degrees" as 0 or 1 each.
LoadSettings :: () {
buffer: [16]u8
count := ReadStore("calculator.txt", buffer[:])
if count >= 3 {
scientific = buffer[0] == cast(u8)49
degrees = buffer[2] == cast(u8)49
} else {
degrees = true
}
}
SaveSettings :: () {
buffer: [3]u8
buffer[0] = cast(u8)(ifx scientific then 49 else 48)
buffer[1] = cast(u8)32
buffer[2] = cast(u8)(ifx degrees then 49 else 48)
unused WriteStore("calculator.txt", TextView(buffer[0:3]))
}
// Typed characters and keys act like the keypad; letters spell functions
// such as sin and sqrt.
Keyboard :: () {
key := AppKey()
typed := AppFieldInput().text
index: s32 = 0
while index < cast(s32)typed.count {
byte := typed[index]
if byte >= cast(u8)48 && byte <= cast(u8)57 || byte == cast(u8)46 || byte == cast(u8)40 ||
byte == cast(u8)41 || byte == cast(u8)43 || byte == cast(u8)45 || byte == cast(u8)37 ||
byte == cast(u8)94 || byte == cast(u8)33 || byte >= cast(u8)97 && byte <= cast(u8)122 ||
byte >= cast(u8)65 && byte <= cast(u8)90 {
Append(typed[index:index + 1])
}
if byte == cast(u8)42 {
Append("×")
}
if byte == cast(u8)47 {
Append("÷")
}
if byte == cast(u8)44 {
Append(".")
}
if byte == cast(u8)61 {
Evaluate()
}
index += 1
}
// Text queued before a command key belongs to the expression it acts on.
if key == 257 || key == 335 {
Evaluate()
}
if key == 259 {
Backspace()
}
if key == 256 {
Clear()
}
}
ACTION_INSERT :: 0
ACTION_CLEAR :: 1
ACTION_DELETE :: 2
ACTION_EVALUATE :: 3
ACTION_SECOND :: 4
ACTION_HYPERBOLIC :: 5
ACTION_NEGATE :: 6
Key :: struct {
label: string
input: string
action: s32
accent: bool
// A function key whose 2nd or hyp shift is used up when pressed.
shifted: bool
}
BASIC_KEYS :: 20
BasicKey :: (index: s32) -> Key {
labels: [BASIC_KEYS]string = .["C", "(", ")", "÷",
"7", "8", "9", "×",
"4", "5", "6", "−",
"1", "2", "3", "+",
"", "0", ".", "="]
inputs: [BASIC_KEYS]string = .["", "(", ")", "÷",
"7", "8", "9", "×",
"4", "5", "6", "-",
"1", "2", "3", "+",
"", "0", ".", ""]
key := Key.{.label = labels[index], .input = inputs[index]}
if index == 0 {
key.action = ACTION_CLEAR
}
if index == 16 {
key.action = ACTION_DELETE
}
if index == 19 {
key.action = ACTION_EVALUATE
key.accent = true
}
return key
}
// Eight rows of five; = spans the last two columns.
SCIENTIFIC_KEYS :: 39
ScientificKey :: (index: s32) -> Key {
labels: [SCIENTIFIC_KEYS]string = .["2nd", "hyp", "sin", "cos", "tan",
"x²", "xʸ", "√x", "ln", "log",
"(", ")", "1/x", "n!", "π",
"C", "", "%", "÷", "e",
"7", "8", "9", "×", "EE",
"4", "5", "6", "−", "Ans",
"1", "2", "3", "+", "|x|",
"±", "0", ".", "="]
inputs: [SCIENTIFIC_KEYS]string = .["", "", "", "", "",
"²", "^", "√(", "ln(", "log(",
"(", ")", "⁻¹", "!", "π",
"", "", "%", "÷", "e",
"7", "8", "9", "×", "E",
"4", "5", "6", "-", "Ans",
"1", "2", "3", "+", "abs(",
"", "0", ".", ""]
key := Key.{.label = labels[index], .input = inputs[index]}
if index == 0 {
key.action = ACTION_SECOND
key.accent = second
}
if index == 1 {
key.action = ACTION_HYPERBOLIC
key.accent = hyperbolic
}
if index >= 2 && index <= 4 {
names: [3]string = .["sin", "cos", "tan"]
hyperbolic_names: [3]string = .["sinh", "cosh", "tanh"]
inverse_names: [3]string = .["sin⁻¹", "cos⁻¹", "tan⁻¹"]
inverse_hyperbolic_names: [3]string = .["sinh⁻¹", "cosh⁻¹", "tanh⁻¹"]
name := names[index - 2]
if hyperbolic {
name = ifx second then inverse_hyperbolic_names[index - 2] else hyperbolic_names[index - 2]
} else if second {
name = inverse_names[index - 2]
}
key.label = name
key.shifted = true
}
if second {
if index == 5 {
key.label = "x³"
key.input = "³"
}
if index == 6 {
key.label = "ʸ√x"
key.input = "^(1÷"
}
if index == 7 {
key.label = "∛x"
key.input = "∛("
}
if index == 8 {
key.label = "eˣ"
key.input = "e^("
}
if index == 9 {
key.label = "10ˣ"
key.input = "10^("
}
}
if index >= 5 && index <= 9 {
key.shifted = true
}
if index == 15 {
key.action = ACTION_CLEAR
}
if index == 16 {
key.action = ACTION_DELETE
}
if index == 35 {
key.action = ACTION_NEGATE
}
if index == 38 {
key.action = ACTION_EVALUATE
key.accent = true
}
return key
}
Press :: (key: Key) {
if key.action == ACTION_CLEAR {
Clear()
} else if key.action == ACTION_DELETE {
Backspace()
} else if key.action == ACTION_EVALUATE {
Evaluate()
} else if key.action == ACTION_SECOND {
second = !second
} else if key.action == ACTION_HYPERBOLIC {
hyperbolic = !hyperbolic
} else if key.action == ACTION_NEGATE {
Append("−")
} else if key.input != "" {
Append(key.input)
} else {
// A trigonometric key: its name and an opening bracket.
text: [24]u8
used: s32 = AppendTo(text[:], 0, key.label)
used = AppendTo(text[:], used, "(")
Append(TextView(text[0:used]))
}
if key.shifted {
second = false
hyperbolic = false
}
}
Tab :: (session: Session, id: s32, label: string, bounds: Rectangle, active: bool) -> bool {
props := Button.Props.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if active {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button.Draw(session, props) != 0
}
DrawKey :: (session: Session, index: s32, key: Key, bounds: Rectangle) {
props := Button.Props.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
.label = key.label,
.tone = cast(ButtonTone)(ifx key.accent then ButtonToneAccent else ButtonToneNeutral),
.emphasis = cast(ButtonEmphasis)(ifx key.accent then ButtonEmphasisFilled else ButtonEmphasisSoft)}
// Delete is an icon on a key as wide as the others.
if key.action == ACTION_DELETE {
props.icon_shape = DeleteBack.Shape
props.label = ""
}
if Button.Draw(session, props) != 0 {
Press(key)
}
}
Draw :: () {
session := AppSession()
area := AppBounds()
gap: float32 = 8.0
width := area.width - 32.0
if width > 460.0 {
width = 460.0
}
left := area.x + (area.width - width) * 0.5
top := area.y + 12.0
half := (width - gap) / 2.0
if Tab(session, 1, "Basic", Rectangle.{left, top, half, 36.0}, !scientific) && scientific {
scientific = false
SaveSettings()
}
if Tab(session, 2, "Scientific", Rectangle.{left + half + gap, top, half, 36.0}, scientific) && !scientific {
scientific = true
SaveSettings()
}
top += 36.0 + gap
display_height: float32 = ifx scientific then 104.0 else 112.0
display := Rectangle.{left, top, width, display_height}
Box.Draw(session, Box.Props.{.key = cast(u64)3, .bounds = display, .radius = 12.0})
shown := ExpressionText()
if shown == "" {
shown = "0"
}
font: s32 = 32
if shown.count > 18 {
font = 24
}
if shown.count > 28 {
font = 18
}
Text.Draw(session, Text.Props.{.key = cast(u64)4,
.bounds = Rectangle.{left + 16.0, top + 14.0, width - 32.0, 48.0},
.text = shown, .size = font, .align = TextAlign.TextAlignEnd, .wrap = Text.Wrap.TextWrapEllipsis})
Text.Draw(session, Text.Props.{.key = cast(u64)5,
.bounds = Rectangle.{left + 16.0, top + display_height - 36.0, width - 32.0, 24.0},
.text = TextUntilNul(result_text[:]), .size = 16, .align = TextAlign.TextAlignEnd})
if scientific {
// The angle unit, switched by tapping it.
unit := Button.Props.{.key = cast(u64)6, .id = 6, .bounds = Rectangle.{left + 10.0, top + display_height - 38.0, 64.0, 28.0},
.label = ifx degrees then "DEG" else "RAD", .size = ControlSize.ControlSizeSmall,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button.Draw(session, unit) != 0 {
degrees = !degrees
SaveSettings()
}
}
pad_top := top + display_height + gap * 2.0
columns: s32 = ifx scientific then 5 else 4
rows: s32 = ifx scientific then 8 else 5
key_width := (width - gap * cast(float32)(columns - 1)) / cast(float32)columns
key_height := (area.y + area.height - 16.0 - pad_top - gap * cast(float32)(rows - 1)) / cast(float32)rows
if key_height > 72.0 {
key_height = 72.0
}
if key_height < 34.0 {
key_height = 34.0
}
count: s32 = ifx scientific then SCIENTIFIC_KEYS else BASIC_KEYS
index: s32 = 0
while index < count {
key := ifx scientific then ScientificKey(index) else BasicKey(index)
column := cast(float32)(index % columns)
row := cast(float32)(index / columns)
bounds := Rectangle.{left + column * (key_width + gap), pad_top + row * (key_height + gap),
key_width, key_height}
if scientific && index == SCIENTIFIC_KEYS - 1 {
bounds.width = key_width * 2.0 + gap
}
DrawKey(session, index, key, bounds)
index += 1
}
}
#program_export "CalculatorMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("calculator")
AppDescribe("Calculator", Icon.Shape)
return APP_PROTOCOL
}
if AppMode() != APP_FRAME {
return 0
}
if !loaded {
LoadSettings()
loaded = true
}
Keyboard()
Draw()
return 0
}
+812
View File
@@ -0,0 +1,812 @@
// Simple Calendar: Month, Week, and Agenda views with local event creation,
// editing, deletion, recurrence, search and private persistence.
Box :: #import "kryon/box";
Button :: #import "kryon/button";
Checkbox :: #import "kryon/checkbox";
Scroll :: #import "kryon/scroll";
Text :: #import "kryon/text";
TextField :: #import "kryon/text_field";
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "kryon/control_props"
#import "kryon/drawing_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/text_align"
#import "kryon/tree"
#import "std/number_text"
#import "std/text_buffer"
#import "calendar_model"
Icon :: #import "mingcute/mingcute_regular_calendar";
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
STORE_BUFFER_CAP :: 65536;
session: Session;
store: CalendarStore;
loaded: bool;
dirty: bool;
view_mode: s32 = VIEW_MONTH;
display_year: s64 = 2026;
display_month: s32 = 1;
selected_year: s64 = 2026;
selected_month: s32 = 1;
selected_day: s32 = 1;
local_offset: s32;
local_offset_at: float64 = -61.0;
day_scroll_y: s32;
week_scroll_y: s32;
agenda_scroll_y: s32;
editor_scroll_y: s32;
// Search in Agenda view.
search_buf: [96]u8;
search_state: FieldState;
// Event editor state.
editing: bool;
edit_index: s32 = -1; // -1 when creating a new event
edit_title: [EVENT_TITLE_CAP]u8;
edit_date: [16]u8;
edit_start: [16]u8;
edit_end: [16]u8;
edit_location: [EVENT_LOCATION_CAP]u8;
edit_notes: [EVENT_NOTES_CAP]u8;
edit_all_day: bool;
edit_recurrence: s32;
edit_color: s32;
edit_error: [96]u8;
edit_fields: [6]FieldState;
focused_field: s32; // 0 none, 1..6 editor fields, 10 search
store_io_buf: [STORE_BUFFER_CAP]u8;
TodayCivil :: () -> CivilDate {
now := AppNow()
if now - local_offset_at > 60.0 {
local_offset = AppLocalOffset()
local_offset_at = now
}
secs := cast(s64)now
if cast(float64)secs > now { secs -= 1 }
local := secs + cast(s64)local_offset
days := local / 86400
if local < 0 && local % 86400 != 0 { days -= 1 }
return CivilFromDays(days)
}
JumpToday :: () {
today := TodayCivil()
display_year = today.year
display_month = today.month
selected_year = today.year
selected_month = today.month
selected_day = today.day
day_scroll_y = 0
}
LoadCalendar :: () {
StoreInit(*store)
count := ReadStore("calendar.json", store_io_buf[:])
if count > 0 {
unused DeserializeStore(TextView(store_io_buf[:count]), *store)
}
view_mode = store.default_view
JumpToday()
loaded = true
dirty = false
}
SaveCalendar :: () {
store.default_view = view_mode
used := SerializeStore(*store, store_io_buf[:])
if used > 0 {
unused WriteStore("calendar.json", TextView(store_io_buf[:used]))
dirty = false
}
}
SwatchColor :: (index: s32) -> Color {
if index == 1 { return Color.{46, 158, 102, 255} } // Green
if index == 2 { return Color.{219, 143, 36, 255} } // Amber
if index == 3 { return Color.{209, 71, 77, 255} } // Red
if index == 4 { return Color.{138, 92, 199, 255} } // Purple
if index == 5 { return Color.{36, 153, 168, 255} } // Teal
return Color.{56, 128, 219, 255} // Blue
}
SwatchName :: (index: s32) -> string {
names: [COLOR_COUNT]string = .["Blue", "Green", "Amber", "Red", "Purple", "Teal"]
if index < 0 || index >= COLOR_COUNT { return names[0] }
return names[index]
}
OpenNewEvent :: (year: s64, month: s32, day: s32) {
editing = true
edit_index = -1
edit_title[0] = cast(u8)0
edit_location[0] = cast(u8)0
edit_notes[0] = cast(u8)0
edit_error[0] = cast(u8)0
unused FormatDateISO(year, month, day, edit_date[:])
CopyField(edit_start[:], "09:00")
CopyField(edit_end[:], "10:00")
edit_all_day = false
edit_recurrence = REPEAT_NONE
edit_color = 0
for i: 0..5 { edit_fields[i] = FieldState.{} }
editor_scroll_y = 0
focused_field = 1
}
OpenEditEvent :: (index: s32) {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return }
ev := *store.events[index]
editing = true
edit_index = index
CopyField(edit_title[:], TextUntilNul(ev.title[:]))
CopyField(edit_location[:], TextUntilNul(ev.location[:]))
CopyField(edit_notes[:], TextUntilNul(ev.notes[:]))
unused FormatDateISO(ev.year, ev.month, ev.day, edit_date[:])
unused FormatTimeHHMM(ev.start_minute, edit_start[:])
unused FormatTimeHHMM(ev.end_minute, edit_end[:])
edit_all_day = ev.all_day
edit_recurrence = ev.recurrence
edit_color = ev.color
edit_error[0] = cast(u8)0
for i: 0..5 { edit_fields[i] = FieldState.{} }
editor_scroll_y = 0
focused_field = 1
}
CommitEditor :: () {
title := TextUntilNul(edit_title[:])
if title.count == 0 {
CopyField(edit_error[:], "Please enter an event title.")
return
}
parsed := ParseDateISO(TextUntilNul(edit_date[:]))
if !parsed.ok {
CopyField(edit_error[:], "Date must be YYYY-MM-DD.")
return
}
start_min: s32 = 540
end_min: s32 = 600
if !edit_all_day {
st := ParseTimeHHMM(TextUntilNul(edit_start[:]))
et := ParseTimeHHMM(TextUntilNul(edit_end[:]))
if !st.ok || !et.ok {
CopyField(edit_error[:], "Times must be HH:MM (24-hour).")
return
}
if et.minute < st.minute {
CopyField(edit_error[:], "End time must be after start time.")
return
}
start_min = st.minute
end_min = et.minute
}
ev: CalendarEvent
ev.year = parsed.year
ev.month = parsed.month
ev.day = parsed.day
ev.all_day = edit_all_day
ev.start_minute = start_min
ev.end_minute = end_min
ev.recurrence = edit_recurrence
ev.color = edit_color
CopyField(ev.title[:], title)
CopyField(ev.location[:], TextUntilNul(edit_location[:]))
CopyField(ev.notes[:], TextUntilNul(edit_notes[:]))
if edit_index >= 0 {
unused UpdateEvent(*store, edit_index, ev)
} else {
if AddEvent(*store, ev) < 0 {
CopyField(edit_error[:], "Calendar event limit reached.")
return
}
}
selected_year = parsed.year
selected_month = parsed.month
selected_day = parsed.day
display_year = parsed.year
display_month = parsed.month
editing = false
focused_field = 0
dirty = true
SaveCalendar()
}
ApplyEdit :: (buffer: []u8, edit: TextField.Edit) -> bool {
if !edit.changed { return false }
length := cast(s32)TextUntilNul(buffer).count
if edit.start < 0 || edit.end < edit.start || edit.end > length { return false }
used := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
if used >= cast(s32)buffer.count || used >= 512 { return false }
next: [512]u8
pos: s32 = 0
for i: 0..edit.start - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)edit.replacement.count - 1 { next[pos] = edit.replacement[i]; pos += 1 }
for i: edit.end..length - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)buffer.count - 1 {
buffer[i] = ifx i < used then next[i] else cast(u8)0
}
return true
}
DrawField :: (id: s32, label: string, buffer: []u8, state: *FieldState, bounds: Rectangle) -> bool {
snapshot: [512]u8
CopyField(snapshot[:], TextUntilNul(buffer))
props: TextField.Props
props.key = cast(u64)(900 + id)
props.focus_id = 900 + id
props.bounds = bounds
props.label = label
props.value = TextUntilNul(snapshot[:])
props.cursor = state.cursor
props.anchor = state.anchor
props.scroll_x = state.scroll_x
props.focused = focused_field == id
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
if props.focused { props.input = AppFieldInput() }
result := TextField.Draw(session, props)
state.cursor = result.cursor
state.anchor = result.anchor
state.scroll_x = result.scroll_x
changed := ApplyEdit(buffer, result.edit)
if result.focused { focused_field = id }
if result.escaped && focused_field == id { focused_field = 0 }
return changed
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.size = ControlSize.ControlSizeSmall
props.tone = ifx accent then ButtonTone.ButtonToneAccent else ButtonTone.ButtonToneNeutral
props.emphasis = ifx accent then ButtonEmphasis.ButtonEmphasisFilled else ButtonEmphasis.ButtonEmphasisSoft
return Button.Draw(session, props) != 0
}
DangerAction :: (id: s32, label: string, bounds: Rectangle) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.size = ControlSize.ControlSizeSmall
props.tone = ButtonTone.ButtonToneDanger
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
return Button.Draw(session, props) != 0
}
DrawText :: (key: u64, value: string, bounds: Rectangle, size: s32, align: TextAlign) {
Text.Draw(session, Text.Props.{.key = key, .bounds = bounds, .text = value, .size = size,
.align = align, .wrap = Text.Wrap.TextWrapEllipsis})
}
FormatEventTimeRange :: (ev: *CalendarEvent, out: []u8) -> string {
if ev.all_day { return "All day" }
s_buf: [12]u8
e_buf: [12]u8
used := AppendText(out, 0, FormatTimeHHMM(ev.start_minute, s_buf[:]))
used = AppendText(out, used, " - ")
used = AppendText(out, used, FormatTimeHHMM(ev.end_minute, e_buf[:]))
return TextView(out[:used])
}
DrawEventRow :: (row_id: s32, ev_index: s32, bounds: Rectangle, show_date: bool, y: s64, m: s32, d: s32) -> bool {
ev := *store.events[ev_index]
dark := AppDark()
card_bg := ifx dark then Color.{38, 41, 48, 255} else Color.{242, 245, 250, 255}
border := ifx dark then Color.{66, 71, 87, 255} else Color.{214, 219, 232, 255}
base_key := cast(u64)(5000 + row_id * 10)
Box.Draw(session, Box.Props.{.key = base_key, .bounds = bounds, .fill = card_bg, .border = border, .radius = 8.0})
// Color accent bar on the left.
Box.Draw(session, Box.Props.{.key = base_key + 1,
.bounds = Rectangle.{bounds.x + 2.0, bounds.y + 6.0, 5.0, bounds.height - 12.0},
.fill = SwatchColor(ev.color), .radius = 2.5})
time_buf: [32]u8
meta_buf: [160]u8
used: s32 = 0
if show_date {
iso: [16]u8
used = AppendText(meta_buf[:], used, FormatDateISO(y, m, d, iso[:]))
used = AppendText(meta_buf[:], used, " ")
}
used = AppendText(meta_buf[:], used, FormatEventTimeRange(ev, time_buf[:]))
if ev.recurrence != REPEAT_NONE {
used = AppendText(meta_buf[:], used, " [")
used = AppendText(meta_buf[:], used, RecurrenceLabel(ev.recurrence))
used = AppendText(meta_buf[:], used, "]")
}
loc := TextUntilNul(ev.location[:])
if loc.count > 0 {
used = AppendText(meta_buf[:], used, " @ ")
used = AppendText(meta_buf[:], used, loc)
}
text_w := bounds.width - 78.0
DrawText(base_key + 2, TextUntilNul(ev.title[:]),
Rectangle.{bounds.x + 14.0, bounds.y + 6.0, text_w, 20.0}, 14, TextAlign.TextAlignStart)
DrawText(base_key + 3, TextView(meta_buf[:used]),
Rectangle.{bounds.x + 14.0, bounds.y + 27.0, text_w, 18.0}, 12, TextAlign.TextAlignStart)
return Action(6000 + row_id, "Edit",
Rectangle.{bounds.x + bounds.width - 58.0, bounds.y + 10.0, 50.0, 30.0}, false)
}
DrawMonthView :: (area: Rectangle) {
today := TodayCivil()
// Month navigation header.
nav_y := area.y
if Action(100, "<", Rectangle.{area.x, nav_y, 34.0, 32.0}, false) {
step := StepMonth(display_year, display_month, -1)
display_year = step.year
display_month = step.month
}
if Action(101, ">", Rectangle.{area.x + 38.0, nav_y, 34.0, 32.0}, false) {
step := StepMonth(display_year, display_month, 1)
display_year = step.year
display_month = step.month
}
title_buf: [48]u8
tu := AppendText(title_buf[:], 0, MonthName(display_month))
tu = AppendText(title_buf[:], tu, " ")
tu = AppendNumber(title_buf[:], tu, display_year)
DrawText(102, TextView(title_buf[:tu]),
Rectangle.{area.x + 78.0, nav_y + 5.0, area.width - 216.0, 24.0}, 16, TextAlign.TextAlignCenter)
if Action(103, "Today", Rectangle.{area.x + area.width - 134.0, nav_y, 58.0, 32.0}, false) {
JumpToday()
}
if Action(104, ifx store.week_starts_monday then "Mon" else "Sun",
Rectangle.{area.x + area.width - 72.0, nav_y, 36.0, 32.0}, false) {
store.week_starts_monday = !store.week_starts_monday
dirty = true
SaveCalendar()
}
if Action(105, "+", Rectangle.{area.x + area.width - 32.0, nav_y, 32.0, 32.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
// Weekday headers.
wd_y := nav_y + 38.0
col_w := area.width / 7.0
for col: 0..6 {
wd_idx := ifx store.week_starts_monday then (cast(s32)col + 1) % 7 else cast(s32)col
DrawText(cast(u64)(110 + col), WeekdayShortName(wd_idx),
Rectangle.{area.x + cast(float32)col * col_w, wd_y, col_w, 18.0}, 12, TextAlign.TextAlignCenter)
}
// 6x7 Month grid.
grid: [42]GridCell
BuildMonthGrid(display_year, display_month, store.week_starts_monday, grid[:])
grid_y := wd_y + 22.0
cell_h: float32 = 38.0
if area.height < 480.0 { cell_h = 32.0 }
dark := AppDark()
today_border := Color.{56, 140, 235, 255}
dot_color := Color.{61, 173, 115, 255}
muted_fill := ifx dark then Color.{28, 31, 36, 255} else Color.{245, 247, 250, 255}
for idx: 0..41 {
row := idx / 7
col := idx % 7
cell := grid[idx]
cx := area.x + cast(float32)col * col_w + 1.5
cy := grid_y + cast(float32)row * cell_h + 1.5
cw := col_w - 3.0
ch := cell_h - 3.0
is_sel := cell.year == selected_year && cell.month == selected_month && cell.day == selected_day
is_today := cell.year == today.year && cell.month == today.month && cell.day == today.day
ev_count := DateEventCount(*store, cell.year, cell.month, cell.day)
if !cell.in_month && !is_sel {
Box.Draw(session, Box.Props.{.key = cast(u64)(200 + idx), .bounds = Rectangle.{cx, cy, cw, ch},
.fill = muted_fill, .radius = 6.0})
}
label_buf: [16]u8
lu := AppendNumber(label_buf[:], 0, cast(s64)cell.day)
if ev_count > 0 {
lu = AppendText(label_buf[:], lu, "*")
}
props: Button.Props
props.key = cast(u64)(300 + idx)
props.id = 300 + cast(s32)idx
props.bounds = Rectangle.{cx, cy, cw, ch}
props.label = TextView(label_buf[:lu])
props.size = ControlSize.ControlSizeSmall
props.tone = ifx is_sel then ButtonTone.ButtonToneAccent else ButtonTone.ButtonToneNeutral
props.emphasis = ifx is_sel then ButtonEmphasis.ButtonEmphasisFilled else (ifx cell.in_month then ButtonEmphasis.ButtonEmphasisSoft else ButtonEmphasis.ButtonEmphasisGhost)
if Button.Draw(session, props) != 0 {
selected_year = cell.year
selected_month = cell.month
selected_day = cell.day
display_year = cell.year
display_month = cell.month
day_scroll_y = 0
}
if is_today && !is_sel {
Box.Draw(session, Box.Props.{.key = cast(u64)(400 + idx), .bounds = Rectangle.{cx, cy, cw, ch},
.border = today_border, .radius = 6.0})
}
if ev_count > 0 {
Box.Draw(session, Box.Props.{.key = cast(u64)(450 + idx),
.bounds = Rectangle.{cx + cw * 0.5 - 3.0, cy + ch - 5.0, 6.0, 3.0},
.fill = ifx is_sel then Color.{255, 255, 255, 230} else dot_color, .radius = 1.5})
}
}
// Selected day agenda panel below grid.
panel_y := grid_y + cell_h * 6.0 + 10.0
date_buf: [64]u8
DrawText(500, FormatDateLong(selected_year, selected_month, selected_day, date_buf[:]),
Rectangle.{area.x, panel_y + 4.0, area.width - 102.0, 22.0}, 15, TextAlign.TextAlignStart)
if Action(501, "+ Event", Rectangle.{area.x + area.width - 94.0, panel_y, 94.0, 30.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
list_y := panel_y + 36.0
list_h := area.y + area.height - list_y
if list_h < 56.0 { list_h = 56.0 }
day_events: [64]s32
found := EventsOnDate(*store, selected_year, selected_month, selected_day, day_events[:])
if found == 0 {
DrawText(502, "No events scheduled for this day.",
Rectangle.{area.x + 4.0, list_y + 10.0, area.width - 8.0, 22.0}, 13, TextAlign.TextAlignStart)
return
}
row_h: float32 = 54.0
content_h := cast(s32)(cast(float32)found * row_h) + 8
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
scroll := Scroll.Draw(session, Scroll.Props.{.key = 505, .bounds = list_bounds,
.scroll_offset = day_scroll_y, .content_height = content_h, .scale = 1.0})
day_scroll_y = scroll.scroll_offset
if scroll.opened {
for i: 0..found - 1 {
y := scroll.content.y + cast(float32)i * row_h
if DrawEventRow(cast(s32)i, day_events[i],
Rectangle.{scroll.content.x, y, scroll.content.width - 10.0, row_h - 4.0},
false, selected_year, selected_month, selected_day) {
OpenEditEvent(day_events[i])
}
}
End(session)
}
}
DrawWeekView :: (area: Rectangle) {
sel_days := DaysFromCivil(selected_year, selected_month, selected_day)
start_days := WeekStartDays(sel_days, store.week_starts_monday)
start_c := CivilFromDays(start_days)
end_c := CivilFromDays(start_days + 6)
today := TodayCivil()
// Week navigation header.
nav_y := area.y
if Action(150, "<", Rectangle.{area.x, nav_y, 34.0, 32.0}, false) {
c := CivilFromDays(sel_days - 7)
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
if Action(151, ">", Rectangle.{area.x + 38.0, nav_y, 34.0, 32.0}, false) {
c := CivilFromDays(sel_days + 7)
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
range_buf: [64]u8
ru := AppendNumber(range_buf[:], 0, cast(s64)start_c.day)
ru = AppendText(range_buf[:], ru, " ")
ru = AppendText(range_buf[:], ru, MonthShortName(start_c.month))
ru = AppendText(range_buf[:], ru, " - ")
ru = AppendNumber(range_buf[:], ru, cast(s64)end_c.day)
ru = AppendText(range_buf[:], ru, " ")
ru = AppendText(range_buf[:], ru, MonthShortName(end_c.month))
ru = AppendText(range_buf[:], ru, " ")
ru = AppendNumber(range_buf[:], ru, end_c.year)
DrawText(152, TextView(range_buf[:ru]),
Rectangle.{area.x + 76.0, nav_y + 5.0, area.width - 176.0, 24.0}, 15, TextAlign.TextAlignCenter)
if Action(153, "Today", Rectangle.{area.x + area.width - 96.0, nav_y, 58.0, 32.0}, false) { JumpToday() }
if Action(154, "+", Rectangle.{area.x + area.width - 34.0, nav_y, 34.0, 32.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
// Scrollable 7-day breakdown.
list_y := nav_y + 40.0
list_h := area.y + area.height - list_y
if list_h < 60.0 { list_h = 60.0 }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
// Measure total content height.
day_counts: [7]s32
total_h: float32 = 8.0
for d: 0..6 {
c := CivilFromDays(start_days + cast(s64)d)
day_counts[d] = DateEventCount(*store, c.year, c.month, c.day)
total_h += 34.0 + (ifx day_counts[d] > 0 then cast(float32)day_counts[d] * 54.0 else 26.0) + 6.0
}
content_h := cast(s32)total_h
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
scroll := Scroll.Draw(session, Scroll.Props.{.key = 160, .bounds = list_bounds,
.scroll_offset = week_scroll_y, .content_height = content_h, .scale = 1.0})
week_scroll_y = scroll.scroll_offset
if scroll.opened {
cur_y := scroll.content.y
cw := scroll.content.width - 10.0
row_counter: s32 = 100
day_events: [32]s32
for d: 0..6 {
c := CivilFromDays(start_days + cast(s64)d)
is_today := c.year == today.year && c.month == today.month && c.day == today.day
is_sel := c.year == selected_year && c.month == selected_month && c.day == selected_day
hdr_buf: [64]u8
hu := AppendText(hdr_buf[:], 0, WeekdayShortName(c.weekday))
hu = AppendText(hdr_buf[:], hu, ", ")
hu = AppendNumber(hdr_buf[:], hu, cast(s64)c.day)
hu = AppendText(hdr_buf[:], hu, " ")
hu = AppendText(hdr_buf[:], hu, MonthShortName(c.month))
if is_today { hu = AppendText(hdr_buf[:], hu, " (Today)") }
if Action(700 + cast(s32)d, TextView(hdr_buf[:hu]),
Rectangle.{scroll.content.x, cur_y, cw - 66.0, 28.0}, is_sel) {
selected_year = c.year; selected_month = c.month; selected_day = c.day
display_year = c.year; display_month = c.month
}
if Action(710 + cast(s32)d, "+ Add",
Rectangle.{scroll.content.x + cw - 60.0, cur_y, 60.0, 28.0}, false) {
OpenNewEvent(c.year, c.month, c.day)
}
cur_y += 34.0
found := EventsOnDate(*store, c.year, c.month, c.day, day_events[:])
if found == 0 {
DrawText(cast(u64)(720 + d), "No events",
Rectangle.{scroll.content.x + 10.0, cur_y, cw - 20.0, 20.0}, 12, TextAlign.TextAlignStart)
cur_y += 26.0
} else {
for k: 0..found - 1 {
if DrawEventRow(row_counter, day_events[k],
Rectangle.{scroll.content.x, cur_y, cw, 50.0},
false, c.year, c.month, c.day) {
OpenEditEvent(day_events[k])
}
row_counter += 1
cur_y += 54.0
}
}
cur_y += 6.0
}
End(session)
}
}
DrawAgendaView :: (area: Rectangle) {
top_y := area.y
if DrawField(10, "Search events...", search_buf[:], *search_state,
Rectangle.{area.x, top_y, area.width - 76.0, 36.0}) {
agenda_scroll_y = 0
}
if Action(170, "+ New", Rectangle.{area.x + area.width - 70.0, top_y, 70.0, 36.0}, true) {
OpenNewEvent(selected_year, selected_month, selected_day)
}
today := TodayCivil()
items: [128]AgendaItem
query := TextUntilNul(search_buf[:])
count := CollectAgenda(*store, DaysFromCivil(today.year, today.month, today.day), 60, query, items[:])
list_y := top_y + 44.0
list_h := area.y + area.height - list_y
if list_h < 60.0 { list_h = 60.0 }
if count == 0 {
DrawText(171, ifx query.count > 0 then "No matching events found." else "No upcoming events in the next 60 days.",
Rectangle.{area.x + 4.0, list_y + 10.0, area.width - 8.0, 24.0}, 14, TextAlign.TextAlignStart)
return
}
row_h: float32 = 54.0
content_h := cast(s32)(cast(float32)count * row_h) + 8
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
scroll := Scroll.Draw(session, Scroll.Props.{.key = 175, .bounds = list_bounds,
.scroll_offset = agenda_scroll_y, .content_height = content_h, .scale = 1.0})
agenda_scroll_y = scroll.scroll_offset
if scroll.opened {
for i: 0..count - 1 {
y := scroll.content.y + cast(float32)i * row_h
it := items[i]
if DrawEventRow(400 + cast(s32)i, it.event_index,
Rectangle.{scroll.content.x, y, scroll.content.width - 10.0, row_h - 4.0},
true, it.year, it.month, it.day) {
OpenEditEvent(it.event_index)
}
}
End(session)
}
}
StepEditorDate :: (delta: s64) {
p := ParseDateISO(TextUntilNul(edit_date[:]))
if !p.ok { return }
c := CivilFromDays(DaysFromCivil(p.year, p.month, p.day) + delta)
unused FormatDateISO(c.year, c.month, c.day, edit_date[:])
}
DrawEditor :: (area: Rectangle) {
DrawText(800, ifx edit_index >= 0 then "Edit Event" else "New Event",
Rectangle.{area.x, area.y, area.width, 26.0}, 18, TextAlign.TextAlignStart)
body_y := area.y + 32.0
body_h := area.height - 84.0
if body_h < 120.0 { body_h = 120.0 }
list_bounds := Rectangle.{area.x, body_y, area.width, body_h}
content_h: s32 = 430
if content_h < cast(s32)body_h { content_h = cast(s32)body_h }
scroll := Scroll.Draw(session, Scroll.Props.{.key = 805, .bounds = list_bounds,
.scroll_offset = editor_scroll_y, .content_height = content_h, .scale = 1.0})
editor_scroll_y = scroll.scroll_offset
if scroll.opened {
y := scroll.content.y
x := scroll.content.x
w := scroll.content.width - 10.0
unused DrawField(1, "Title", edit_title[:], *edit_fields[0], Rectangle.{x, y, w, 38.0})
y += 46.0
// Date field with -1d / +1d quick step buttons.
unused DrawField(2, "Date (YYYY-MM-DD)", edit_date[:], *edit_fields[1], Rectangle.{x, y, w - 92.0, 38.0})
if Action(810, "-1d", Rectangle.{x + w - 88.0, y, 42.0, 38.0}, false) { StepEditorDate(-1) }
if Action(811, "+1d", Rectangle.{x + w - 42.0, y, 42.0, 38.0}, false) { StepEditorDate(1) }
y += 46.0
// All-day checkbox.
cb_props := Checkbox.Props.{.key = 812, .id = 812, .label = "All-day event",
.bounds = Rectangle.{x, y, w, 30.0}, .checked = edit_all_day}
edit_all_day = Checkbox.Draw(session, cb_props).checked
y += 36.0
if !edit_all_day {
half := (w - 8.0) * 0.5
unused DrawField(3, "Start (HH:MM)", edit_start[:], *edit_fields[2], Rectangle.{x, y, half, 38.0})
unused DrawField(4, "End (HH:MM)", edit_end[:], *edit_fields[3], Rectangle.{x + half + 8.0, y, half, 38.0})
y += 46.0
}
// Recurrence selector.
DrawText(813, "Repeat", Rectangle.{x, y, w, 18.0}, 13, TextAlign.TextAlignStart)
y += 22.0
rep_w := (w - 16.0) / 5.0
for r: 0..4 {
if Action(820 + cast(s32)r, RecurrenceLabel(cast(s32)r),
Rectangle.{x + cast(float32)r * (rep_w + 4.0), y, rep_w, 30.0},
edit_recurrence == cast(s32)r) {
edit_recurrence = cast(s32)r
}
}
y += 38.0
// Color swatches.
DrawText(814, "Color", Rectangle.{x, y, w, 18.0}, 13, TextAlign.TextAlignStart)
y += 22.0
sw_w := (w - 20.0) / cast(float32)COLOR_COUNT
for c: 0..COLOR_COUNT - 1 {
sx := x + cast(float32)c * (sw_w + 4.0)
if Action(830 + cast(s32)c, SwatchName(cast(s32)c),
Rectangle.{sx, y, sw_w, 28.0}, edit_color == cast(s32)c) {
edit_color = cast(s32)c
}
Box.Draw(session, Box.Props.{.key = cast(u64)(840 + c),
.bounds = Rectangle.{sx + 4.0, y + 29.0, sw_w - 8.0, 4.0},
.fill = SwatchColor(cast(s32)c), .radius = 2.0})
}
y += 42.0
unused DrawField(5, "Location (optional)", edit_location[:], *edit_fields[4], Rectangle.{x, y, w, 38.0})
y += 46.0
unused DrawField(6, "Notes (optional)", edit_notes[:], *edit_fields[5], Rectangle.{x, y, w, 38.0})
y += 46.0
err := TextUntilNul(edit_error[:])
if err.count > 0 {
DrawText(850, err, Rectangle.{x, y, w, 22.0}, 13, TextAlign.TextAlignStart)
}
End(session)
}
// Bottom buttons: Save, Cancel, Delete.
btn_y := area.y + area.height - 42.0
if Action(860, "Save", Rectangle.{area.x, btn_y, 96.0, 38.0}, true) {
CommitEditor()
}
if Action(861, "Cancel", Rectangle.{area.x + 104.0, btn_y, 96.0, 38.0}, false) {
editing = false
focused_field = 0
}
if edit_index >= 0 {
if DangerAction(862, "Delete", Rectangle.{area.x + area.width - 96.0, btn_y, 96.0, 38.0}) {
unused DeleteEvent(*store, edit_index)
editing = false
focused_field = 0
dirty = true
SaveCalendar()
}
}
}
Draw :: () {
session = AppSession()
bounds := AppBounds()
pad: float32 = 12.0
area := Rectangle.{bounds.x + pad, bounds.y + 8.0, bounds.width - pad * 2.0, bounds.height - 16.0}
if editing {
DrawEditor(area)
AppKeyboard(focused_field != 0)
return
}
// Top view switcher: Month | Week | Agenda.
tab_w := (area.width - 12.0) / 3.0
if Action(10, "Month", Rectangle.{area.x, area.y, tab_w, 34.0}, view_mode == VIEW_MONTH) {
view_mode = VIEW_MONTH
focused_field = 0
dirty = true
}
if Action(11, "Week", Rectangle.{area.x + tab_w + 6.0, area.y, tab_w, 34.0}, view_mode == VIEW_WEEK) {
view_mode = VIEW_WEEK
focused_field = 0
dirty = true
}
if Action(12, "Agenda", Rectangle.{area.x + (tab_w + 6.0) * 2.0, area.y, tab_w, 34.0}, view_mode == VIEW_AGENDA) {
view_mode = VIEW_AGENDA
dirty = true
}
body := Rectangle.{area.x, area.y + 42.0, area.width, area.height - 42.0}
if view_mode == VIEW_MONTH {
DrawMonthView(body)
} else if view_mode == VIEW_WEEK {
DrawWeekView(body)
} else {
DrawAgendaView(body)
}
AppKeyboard(focused_field != 0)
}
#program_export "CalendarMain"
Main :: () -> s32 {
mode := AppMode()
if mode == APP_IDENTIFY {
AppIdentity("calendar")
AppDescribe("Calendar", Icon.Shape)
return APP_PROTOCOL
}
if mode == APP_SAVE {
if loaded && dirty { SaveCalendar() }
return 0
}
if mode != APP_FRAME {
return 0
}
if !loaded {
LoadCalendar()
}
Draw()
return 0
}
+630
View File
@@ -0,0 +1,630 @@
// Simple Calendar model: proleptic Gregorian date math, month/week grids,
// recurring events, search, agenda queries and JSON persistence.
#import "std/json_scan"
#import "std/number_text"
#import "std/text_buffer"
#import "std/vec"
MAX_EVENTS :: 256;
EVENT_TITLE_CAP :: 128;
EVENT_LOCATION_CAP :: 128;
EVENT_NOTES_CAP :: 256;
REPEAT_NONE :: 0;
REPEAT_DAILY :: 1;
REPEAT_WEEKLY :: 2;
REPEAT_MONTHLY :: 3;
REPEAT_YEARLY :: 4;
VIEW_MONTH :: 0;
VIEW_WEEK :: 1;
VIEW_AGENDA :: 2;
COLOR_COUNT :: 6;
CivilDate :: struct {
year: s64
month: s32
day: s32
weekday: s32 // 0 = Sunday .. 6 = Saturday
}
CalendarEvent :: struct {
id: s32
active: bool
year: s64
month: s32
day: s32
all_day: bool
start_minute: s32 // 0..1439
end_minute: s32 // 0..1440
recurrence: s32
color: s32
title: [EVENT_TITLE_CAP]u8
location: [EVENT_LOCATION_CAP]u8
notes: [EVENT_NOTES_CAP]u8
}
GridCell :: struct {
year: s64
month: s32
day: s32
in_month: bool
days: s64
}
CalendarStore :: struct {
events: [MAX_EVENTS]CalendarEvent
next_id: s32
week_starts_monday: bool
default_view: s32
}
AgendaItem :: struct {
event_index: s32
days: s64
year: s64
month: s32
day: s32
}
MonthYear :: struct {
year: s64
month: s32
}
ParsedDate :: struct {
year: s64
month: s32
day: s32
ok: bool
}
ParsedTime :: struct {
minute: s32
ok: bool
}
IsLeapYear :: (year: s64) -> bool {
if year % 400 == 0 { return true }
if year % 100 == 0 { return false }
return year % 4 == 0
}
DaysInMonth :: (year: s64, month: s32) -> s32 {
if month == 2 { return ifx IsLeapYear(year) then 29 else 28 }
if month == 4 || month == 6 || month == 9 || month == 11 { return 30 }
return 31
}
// Howard Hinnant's civil/days algorithms (proleptic Gregorian, 1970-01-01 = 0).
DaysFromCivil :: (year: s64, month: s32, day: s32) -> s64 {
y := year - (ifx month <= 2 then 1 else 0)
era := ifx y >= 0 then y / 400 else (y - 399) / 400
yoe := y - era * 400
m := cast(s64)month
doy := (153 * (ifx m > 2 then m - 3 else m + 9) + 2) / 5 + cast(s64)day - 1
doe := yoe * 365 + yoe / 4 - yoe / 100 + doy
return era * 146097 + doe - 719468
}
CivilFromDays :: (days: s64) -> CivilDate {
shifted := days + 719468
era := ifx shifted >= 0 then shifted / 146097 else (shifted - 146096) / 146097
doe := shifted - era * 146097
yoe := (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
doy := doe - (365 * yoe + yoe / 4 - yoe / 100)
mp := (5 * doy + 2) / 153
result: CivilDate
result.day = cast(s32)(doy - (153 * mp + 2) / 5 + 1)
result.month = cast(s32)(ifx mp < 10 then mp + 3 else mp - 9)
result.year = yoe + era * 400 + (ifx result.month <= 2 then 1 else 0)
wd := (days + 4) % 7
if wd < 0 { wd += 7 }
result.weekday = cast(s32)wd
return result
}
WeekdayOf :: (year: s64, month: s32, day: s32) -> s32 {
return CivilFromDays(DaysFromCivil(year, month, day)).weekday
}
ValidDate :: (year: s64, month: s32, day: s32) -> bool {
if year < 1 || year > 9999 { return false }
if month < 1 || month > 12 { return false }
if day < 1 || day > DaysInMonth(year, month) { return false }
return true
}
StepMonth :: (year: s64, month: s32, delta: s32) -> MonthYear {
total := year * 12 + cast(s64)(month - 1) + cast(s64)delta
ny := total / 12
nm := total % 12
if nm < 0 {
nm += 12
ny -= 1
}
return MonthYear.{.year = ny, .month = cast(s32)(nm + 1)}
}
MonthName :: (month: s32) -> string {
names: [12]string = .["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
if month < 1 || month > 12 { return names[0] }
return names[month - 1]
}
MonthShortName :: (month: s32) -> string {
names: [12]string = .["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
if month < 1 || month > 12 { return names[0] }
return names[month - 1]
}
WeekdayName :: (weekday: s32) -> string {
names: [7]string = .["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
if weekday < 0 || weekday > 6 { return names[0] }
return names[weekday]
}
WeekdayShortName :: (weekday: s32) -> string {
names: [7]string = .["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
if weekday < 0 || weekday > 6 { return names[0] }
return names[weekday]
}
RecurrenceLabel :: (recurrence: s32) -> string {
if recurrence == REPEAT_DAILY { return "Daily" }
if recurrence == REPEAT_WEEKLY { return "Weekly" }
if recurrence == REPEAT_MONTHLY { return "Monthly" }
if recurrence == REPEAT_YEARLY { return "Yearly" }
return "Once"
}
BuildMonthGrid :: (year: s64, month: s32, week_starts_monday: bool, out: []GridCell) {
first_days := DaysFromCivil(year, month, 1)
first_wd := CivilFromDays(first_days).weekday
offset: s32 = ifx week_starts_monday then (first_wd + 6) % 7 else first_wd
start_days := first_days - cast(s64)offset
for index: 0..41 {
if index >= out.count { break }
d := start_days + cast(s64)index
c := CivilFromDays(d)
out[index] = GridCell.{.year = c.year, .month = c.month, .day = c.day,
.in_month = c.year == year && c.month == month, .days = d}
}
}
WeekStartDays :: (days: s64, week_starts_monday: bool) -> s64 {
wd := CivilFromDays(days).weekday
offset: s32 = ifx week_starts_monday then (wd + 6) % 7 else wd
return days - cast(s64)offset
}
StoreInit :: (store: *CalendarStore) {
store.* = CalendarStore.{}
store.next_id = 1
store.week_starts_monday = false
store.default_view = VIEW_MONTH
}
CopyField :: (dst: []u8, src: string) {
limit := src.count
if limit >= dst.count { limit = dst.count - 1 }
for i: 0..limit - 1 { dst[i] = src[i] }
dst[limit] = cast(u8)0
}
AppendText :: (out: []u8, used: s32, text: string) -> s32 {
pos := used
for i: 0..text.count - 1 {
if pos >= cast(s32)out.count - 1 { break }
out[pos] = text[i]
pos += 1
}
out[pos] = cast(u8)0
return pos
}
AppendTwoDigits :: (out: []u8, used: s32, value: s64) -> s32 {
v := ifx value < 0 then 0 else value
digits: [2]u8
digits[0] = cast(u8)(48 + cast(s32)((v / 10) % 10))
digits[1] = cast(u8)(48 + cast(s32)(v % 10))
return AppendText(out, used, TextView(digits[:]))
}
AppendFourDigits :: (out: []u8, used: s32, value: s64) -> s32 {
v := ifx value < 0 then 0 else value
digits: [4]u8
digits[0] = cast(u8)(48 + cast(s32)((v / 1000) % 10))
digits[1] = cast(u8)(48 + cast(s32)((v / 100) % 10))
digits[2] = cast(u8)(48 + cast(s32)((v / 10) % 10))
digits[3] = cast(u8)(48 + cast(s32)(v % 10))
return AppendText(out, used, TextView(digits[:]))
}
AppendNumber :: (out: []u8, used: s32, value: s64) -> s32 {
buf: [32]u8
return AppendText(out, used, FormatInteger(value, buf[:]))
}
FormatDateISO :: (year: s64, month: s32, day: s32, out: []u8) -> string {
used := AppendFourDigits(out, 0, year)
used = AppendText(out, used, "-")
used = AppendTwoDigits(out, used, cast(s64)month)
used = AppendText(out, used, "-")
used = AppendTwoDigits(out, used, cast(s64)day)
return TextView(out[:used])
}
ParseDateISO :: (text: string) -> ParsedDate {
bad := ParsedDate.{}
if text.count != 10 { return bad }
if text[4] != cast(u8)45 || text[7] != cast(u8)45 { return bad }
for i: 0..9 {
if i == 4 || i == 7 { continue }
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
}
year := cast(s64)(text[0] - 48) * 1000 + cast(s64)(text[1] - 48) * 100 +
cast(s64)(text[2] - 48) * 10 + cast(s64)(text[3] - 48)
month := cast(s32)(text[5] - 48) * 10 + cast(s32)(text[6] - 48)
day := cast(s32)(text[8] - 48) * 10 + cast(s32)(text[9] - 48)
if !ValidDate(year, month, day) { return bad }
return ParsedDate.{.year = year, .month = month, .day = day, .ok = true}
}
FormatTimeHHMM :: (minute_of_day: s32, out: []u8) -> string {
m := minute_of_day
if m < 0 { m = 0 }
if m > 1439 { m = 1439 }
used := AppendTwoDigits(out, 0, cast(s64)(m / 60))
used = AppendText(out, used, ":")
used = AppendTwoDigits(out, used, cast(s64)(m % 60))
return TextView(out[:used])
}
ParseTimeHHMM :: (text: string) -> ParsedTime {
bad := ParsedTime.{}
if text.count < 4 || text.count > 5 { return bad }
colon: s64 = -1
for i: 0..text.count - 1 {
if text[i] == cast(u8)58 { colon = i; break }
}
if colon < 1 || colon > 2 || text.count - colon - 1 != 2 { return bad }
hour: s32 = 0
for i: 0..colon - 1 {
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
hour = hour * 10 + cast(s32)(text[i] - 48)
}
minute: s32 = 0
for i: colon + 1..text.count - 1 {
if text[i] < cast(u8)48 || text[i] > cast(u8)57 { return bad }
minute = minute * 10 + cast(s32)(text[i] - 48)
}
if hour < 0 || hour > 23 || minute < 0 || minute > 59 { return bad }
return ParsedTime.{.minute = hour * 60 + minute, .ok = true}
}
FormatDateLong :: (year: s64, month: s32, day: s32, out: []u8) -> string {
wd := WeekdayOf(year, month, day)
used := AppendText(out, 0, WeekdayName(wd))
used = AppendText(out, used, ", ")
used = AppendNumber(out, used, cast(s64)day)
used = AppendText(out, used, " ")
used = AppendText(out, used, MonthName(month))
used = AppendText(out, used, " ")
used = AppendNumber(out, used, year)
return TextView(out[:used])
}
EventOccursOn :: (event: *CalendarEvent, year: s64, month: s32, day: s32) -> bool {
if !event.active { return false }
target_days := DaysFromCivil(year, month, day)
start_days := DaysFromCivil(event.year, event.month, event.day)
if target_days < start_days { return false }
if event.recurrence == REPEAT_NONE {
return target_days == start_days
}
if event.recurrence == REPEAT_DAILY {
return true
}
if event.recurrence == REPEAT_WEEKLY {
return (target_days - start_days) % 7 == 0
}
if event.recurrence == REPEAT_MONTHLY {
max_day := DaysInMonth(year, month)
expected_day := ifx event.day > max_day then max_day else event.day
return day == expected_day
}
if event.recurrence == REPEAT_YEARLY {
if month != event.month { return false }
max_day := DaysInMonth(year, month)
expected_day := ifx event.day > max_day then max_day else event.day
return day == expected_day
}
return false
}
EventBefore :: (a: *CalendarEvent, b: *CalendarEvent) -> bool {
if a.all_day != b.all_day { return a.all_day }
if !a.all_day && a.start_minute != b.start_minute { return a.start_minute < b.start_minute }
return a.id < b.id
}
EventsOnDate :: (store: *CalendarStore, year: s64, month: s32, day: s32, out: []s32) -> s32 {
count: s32 = 0
for i: 0..MAX_EVENTS - 1 {
if EventOccursOn(*store.events[i], year, month, day) {
if count >= cast(s32)out.count { break }
out[count] = cast(s32)i
count += 1
}
}
// Insertion sort by all_day first, then start_minute, then id.
for i: 1..count - 1 {
key := out[i]
j := i - 1
while j >= 0 && EventBefore(*store.events[key], *store.events[out[j]]) {
out[j + 1] = out[j]
j -= 1
}
out[j + 1] = key
}
return count
}
DateEventCount :: (store: *CalendarStore, year: s64, month: s32, day: s32) -> s32 {
count: s32 = 0
for i: 0..MAX_EVENTS - 1 {
if EventOccursOn(*store.events[i], year, month, day) { count += 1 }
}
return count
}
AddEvent :: (store: *CalendarStore, item: CalendarEvent) -> s32 {
for i: 0..MAX_EVENTS - 1 {
if !store.events[i].active {
ev := item
ev.active = true
if ev.id <= 0 {
ev.id = store.next_id
store.next_id += 1
} else if ev.id >= store.next_id {
store.next_id = ev.id + 1
}
if ev.color < 0 || ev.color >= COLOR_COUNT { ev.color = 0 }
if ev.recurrence < REPEAT_NONE || ev.recurrence > REPEAT_YEARLY { ev.recurrence = REPEAT_NONE }
store.events[i] = ev
return cast(s32)i
}
}
return -1
}
UpdateEvent :: (store: *CalendarStore, index: s32, item: CalendarEvent) -> bool {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return false }
ev := item
ev.id = store.events[index].id
ev.active = true
if ev.color < 0 || ev.color >= COLOR_COUNT { ev.color = 0 }
if ev.recurrence < REPEAT_NONE || ev.recurrence > REPEAT_YEARLY { ev.recurrence = REPEAT_NONE }
store.events[index] = ev
return true
}
DeleteEvent :: (store: *CalendarStore, index: s32) -> bool {
if index < 0 || index >= MAX_EVENTS || !store.events[index].active { return false }
store.events[index] = CalendarEvent.{}
return true
}
FindEventById :: (store: *CalendarStore, id: s32) -> s32 {
for i: 0..MAX_EVENTS - 1 {
if store.events[i].active && store.events[i].id == id { return cast(s32)i }
}
return -1
}
AsciiLower :: (b: u8) -> u8 {
if b >= cast(u8)65 && b <= cast(u8)90 { return b + cast(u8)32 }
return b
}
ContainsFold :: (haystack: string, needle: string) -> bool {
if needle.count == 0 { return true }
if needle.count > haystack.count { return false }
limit := haystack.count - needle.count
for start: 0..limit {
ok := true
for k: 0..needle.count - 1 {
if AsciiLower(haystack[start + k]) != AsciiLower(needle[k]) {
ok = false
break
}
}
if ok { return true }
}
return false
}
EventMatchesQuery :: (event: *CalendarEvent, query: string) -> bool {
if query.count == 0 { return true }
if ContainsFold(TextUntilNul(event.title[:]), query) { return true }
if ContainsFold(TextUntilNul(event.location[:]), query) { return true }
if ContainsFold(TextUntilNul(event.notes[:]), query) { return true }
return false
}
CollectAgenda :: (store: *CalendarStore, from_days: s64, horizon_days: s32, query: string, out: []AgendaItem) -> s32 {
count: s32 = 0
if query.count > 0 {
// When searching, list all matching events sorted by their start date.
for i: 0..MAX_EVENTS - 1 {
if !store.events[i].active { continue }
if !EventMatchesQuery(*store.events[i], query) { continue }
if count >= cast(s32)out.count { break }
ev := *store.events[i]
out[count] = AgendaItem.{.event_index = cast(s32)i,
.days = DaysFromCivil(ev.year, ev.month, ev.day),
.year = ev.year, .month = ev.month, .day = ev.day}
count += 1
}
for i: 1..count - 1 {
key := out[i]
j := i - 1
while j >= 0 && (key.days < out[j].days ||
(key.days == out[j].days && EventBefore(*store.events[key.event_index], *store.events[out[j].event_index]))) {
out[j + 1] = out[j]
j -= 1
}
out[j + 1] = key
}
return count
}
day_indices: [64]s32
for offset: 0..horizon_days - 1 {
if count >= cast(s32)out.count { break }
d := from_days + cast(s64)offset
c := CivilFromDays(d)
found := EventsOnDate(store, c.year, c.month, c.day, day_indices[:])
for k: 0..found - 1 {
if count >= cast(s32)out.count { break }
out[count] = AgendaItem.{.event_index = day_indices[k], .days = d,
.year = c.year, .month = c.month, .day = c.day}
count += 1
}
}
return count
}
WriteQuoted :: (bytes: *Vec(u8), text: string) {
BuilderPrint(bytes, "\"")
hex := "0123456789abcdef"
for byte: text {
if byte == cast(u8)34 || byte == cast(u8)92 {
BuilderPrint(bytes, "\\")
unused VecPush(bytes.*, byte)
} else if byte == cast(u8)10 {
BuilderPrint(bytes, "\\n")
} else if byte == cast(u8)13 {
BuilderPrint(bytes, "\\r")
} else if byte == cast(u8)9 {
BuilderPrint(bytes, "\\t")
} else if byte < cast(u8)32 {
BuilderPrint(bytes, "\\u00")
unused VecPush(bytes.*, hex[cast(s32)byte / 16])
unused VecPush(bytes.*, hex[cast(s32)byte % 16])
} else {
unused VecPush(bytes.*, byte)
}
}
BuilderPrint(bytes, "\"")
}
SerializeStore :: (store: *CalendarStore, out: []u8) -> s32 {
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"v\":1,\"next_id\":%,\"week_starts_monday\":%,\"default_view\":%,\"events\":[",
store.next_id, ifx store.week_starts_monday then "true" else "false", store.default_view)
first := true
for i: 0..MAX_EVENTS - 1 {
ev := *store.events[i]
if !ev.active { continue }
if !first { BuilderPrint(*bytes, ",") }
first = false
BuilderPrint(*bytes, "{\"id\":%,\"y\":%,\"m\":%,\"d\":%,\"all_day\":%,\"start\":%,\"end\":%,\"repeat\":%,\"color\":%,\"title\":",
ev.id, ev.year, ev.month, ev.day,
ifx ev.all_day then "true" else "false",
ev.start_minute, ev.end_minute, ev.recurrence, ev.color)
WriteQuoted(*bytes, TextUntilNul(ev.title[:]))
BuilderPrint(*bytes, ",\"location\":")
WriteQuoted(*bytes, TextUntilNul(ev.location[:]))
BuilderPrint(*bytes, ",\"notes\":")
WriteQuoted(*bytes, TextUntilNul(ev.notes[:]))
BuilderPrint(*bytes, "}")
}
BuilderPrint(*bytes, "]}\n")
count := cast(s32)bytes.count
if count >= cast(s32)out.count {
VecFree(bytes)
return -1
}
{
slice := VecSlice(bytes, 0, bytes.count)
for i: 0..count - 1 { out[i] = slice[i] }
}
out[count] = cast(u8)0
VecFree(bytes)
return count
}
ReadJsonInt :: (text: string, obj: s32, field: string, fallback: s64) -> s64 {
at := FieldAt(text, obj, field)
if at < 0 { return fallback }
num := ReadNumber(text, at)
return ifx num.valid then cast(s64)num.value else fallback
}
ReadJsonBool :: (text: string, obj: s32, field: string, fallback: bool) -> bool {
at := FieldAt(text, obj, field)
if at < 0 { return fallback }
if MatchLiteral(text, at, "true") { return true }
if MatchLiteral(text, at, "false") { return false }
return fallback
}
ReadJsonString :: (text: string, obj: s32, field: string, out: []u8) {
out[0] = cast(u8)0
at := FieldAt(text, obj, field)
if at < 0 { return }
used := ReadStringText(text, at, out)
if used < 0 {
out[0] = cast(u8)0
} else if used < cast(s32)out.count {
out[used] = cast(u8)0
} else {
out[out.count - 1] = cast(u8)0
}
}
DeserializeStore :: (text: string, store: *CalendarStore) -> bool {
StoreInit(store)
if text.count == 0 { return false }
root := Space(text, 0)
if root >= cast(s32)text.count || text[root] != cast(u8)123 { return false }
store.next_id = cast(s32)ReadJsonInt(text, root, "next_id", 1)
if store.next_id < 1 { store.next_id = 1 }
store.week_starts_monday = ReadJsonBool(text, root, "week_starts_monday", false)
store.default_view = cast(s32)ReadJsonInt(text, root, "default_view", VIEW_MONTH)
if store.default_view < VIEW_MONTH || store.default_view > VIEW_AGENDA {
store.default_view = VIEW_MONTH
}
arr := FieldAt(text, root, "events")
if arr < 0 { return true }
count := ArrayCount(text, arr)
at := Space(text, arr + 1)
for i: 0..count - 1 {
if at >= cast(s32)text.count { break }
if text[at] == cast(u8)123 {
ev: CalendarEvent
ev.id = cast(s32)ReadJsonInt(text, at, "id", 0)
ev.year = ReadJsonInt(text, at, "y", 2026)
ev.month = cast(s32)ReadJsonInt(text, at, "m", 1)
ev.day = cast(s32)ReadJsonInt(text, at, "d", 1)
ev.all_day = ReadJsonBool(text, at, "all_day", false)
ev.start_minute = cast(s32)ReadJsonInt(text, at, "start", 540)
ev.end_minute = cast(s32)ReadJsonInt(text, at, "end", 600)
ev.recurrence = cast(s32)ReadJsonInt(text, at, "repeat", REPEAT_NONE)
ev.color = cast(s32)ReadJsonInt(text, at, "color", 0)
ReadJsonString(text, at, "title", ev.title[:])
ReadJsonString(text, at, "location", ev.location[:])
ReadJsonString(text, at, "notes", ev.notes[:])
if ValidDate(ev.year, ev.month, ev.day) && ev.title[0] != cast(u8)0 {
unused AddEvent(store, ev)
}
}
at = Space(text, ValueEnd(text, at, 0))
if at < cast(s32)text.count && text[at] == cast(u8)44 { at = Space(text, at + 1) }
}
return true
}
+114
View File
@@ -0,0 +1,114 @@
// Unit tests for Simple Calendar date math, grid generation, recurrence,
// search, agenda ordering and JSON persistence.
#import "std/text_buffer"
#import "calendar_model"
#program_export
Run :: () -> s32 {
// Leap years and month lengths.
if !IsLeapYear(2024) || !IsLeapYear(2000) { return 1 }
if IsLeapYear(1900) || IsLeapYear(2026) { return 2 }
if DaysInMonth(2024, 2) != 29 || DaysInMonth(2026, 2) != 28 { return 3 }
if DaysInMonth(2026, 11) != 30 || DaysInMonth(2026, 12) != 31 { return 4 }
// Civil <-> Days roundtrip and weekdays (1970-01-01 = Thursday = 4; 2026-11-21 = Saturday = 6).
if DaysFromCivil(1970, 1, 1) != 0 { return 5 }
epoch := CivilFromDays(0)
if epoch.year != 1970 || epoch.month != 1 || epoch.day != 1 || epoch.weekday != 4 { return 6 }
d2026 := DaysFromCivil(2026, 11, 21)
c2026 := CivilFromDays(d2026)
if c2026.year != 2026 || c2026.month != 11 || c2026.day != 21 || c2026.weekday != 6 { return 7 }
// StepMonth across year boundaries.
s1 := StepMonth(2026, 1, -1)
if s1.year != 2025 || s1.month != 12 { return 8 }
s2 := StepMonth(2026, 12, 1)
if s2.year != 2027 || s2.month != 1 { return 9 }
// Month grid (November 2026 starts on Sunday = 0).
grid_sun: [42]GridCell
BuildMonthGrid(2026, 11, false, grid_sun[:])
if grid_sun[0].year != 2026 || grid_sun[0].month != 11 || grid_sun[0].day != 1 || !grid_sun[0].in_month { return 10 }
if grid_sun[29].day != 30 || !grid_sun[29].in_month { return 11 }
if grid_sun[30].month != 12 || grid_sun[30].day != 1 || grid_sun[30].in_month { return 12 }
grid_mon: [42]GridCell
BuildMonthGrid(2026, 11, true, grid_mon[:])
if grid_mon[0].month != 10 || grid_mon[0].day != 26 || grid_mon[0].in_month { return 13 }
if grid_mon[6].month != 11 || grid_mon[6].day != 1 || !grid_mon[6].in_month { return 14 }
// Date and time parsing/formatting.
pd := ParseDateISO("2026-11-21")
if !pd.ok || pd.year != 2026 || pd.month != 11 || pd.day != 21 { return 15 }
bad_date := ParseDateISO("2026-02-29")
if bad_date.ok { return 16 }
pt := ParseTimeHHMM("09:45")
if !pt.ok || pt.minute != 585 { return 17 }
bad_time := ParseTimeHHMM("25:00")
if bad_time.ok { return 18 }
// Store CRUD, recurrence, sorting, search.
store: CalendarStore
StoreInit(*store)
store.week_starts_monday = true
e1: CalendarEvent
e1.year = 2026; e1.month = 11; e1.day = 21
e1.all_day = false; e1.start_minute = 600; e1.end_minute = 660
e1.recurrence = REPEAT_WEEKLY; e1.color = 1
CopyField(e1.title[:], "Team Sync")
CopyField(e1.location[:], "Room \"A\"")
CopyField(e1.notes[:], "Line1\nLine2")
idx1 := AddEvent(*store, e1)
if idx1 < 0 { return 19 }
e2: CalendarEvent
e2.year = 2026; e2.month = 11; e2.day = 21
e2.all_day = true; e2.recurrence = REPEAT_NONE; e2.color = 2
CopyField(e2.title[:], "Release Day")
idx2 := AddEvent(*store, e2)
if idx2 < 0 { return 20 }
e3: CalendarEvent
e3.year = 2026; e3.month = 1; e3.day = 31
e3.all_day = false; e3.start_minute = 480; e3.end_minute = 510
e3.recurrence = REPEAT_MONTHLY; e3.color = 3
CopyField(e3.title[:], "Month End")
if AddEvent(*store, e3) < 0 { return 21 }
// Sorting on 2026-11-21: all-day event first, then timed event.
hits: [16]s32
found := EventsOnDate(*store, 2026, 11, 21, hits[:])
if found != 2 || hits[0] != idx2 || hits[1] != idx1 { return 22 }
// Weekly recurrence on 2026-11-28, and not before start date (2026-11-14).
if DateEventCount(*store, 2026, 11, 28) != 1 { return 23 }
if DateEventCount(*store, 2026, 11, 14) != 0 { return 24 }
// Monthly clamping on Feb 28 2026 for a Jan 31 monthly event.
if DateEventCount(*store, 2026, 2, 28) != 1 { return 25 }
// JSON persistence round-trip.
json_buf: [8192]u8
used := SerializeStore(*store, json_buf[:])
if used <= 0 { return 26 }
reloaded: CalendarStore
if !DeserializeStore(TextView(json_buf[:used]), *reloaded) { return 27 }
if !reloaded.week_starts_monday { return 28 }
if DateEventCount(*reloaded, 2026, 11, 21) != 2 { return 29 }
r_idx := FindEventById(*reloaded, store.events[idx1].id)
if r_idx < 0 { return 30 }
if TextUntilNul(reloaded.events[r_idx].title[:]) != "Team Sync" { return 31 }
if TextUntilNul(reloaded.events[r_idx].location[:]) != "Room \"A\"" { return 32 }
// Search via CollectAgenda.
agenda: [16]AgendaItem
qcount := CollectAgenda(*reloaded, d2026, 30, "sync", agenda[:])
if qcount != 1 || agenda[0].event_index != r_idx { return 33 }
// Delete event.
if !DeleteEvent(*reloaded, r_idx) { return 34 }
if DateEventCount(*reloaded, 2026, 11, 21) != 1 { return 35 }
return 0
}
+279
View File
@@ -0,0 +1,279 @@
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Clock: the local time and date, and a stopwatch that keeps running while
// the app is closed.
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/text_align"
#import "kryon/control_props"
#import "std/text_buffer"
#import "std/number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
Icon :: #import "mingcute/mingcute_regular_time";
VIEW_CLOCK :: 0
VIEW_STOPWATCH :: 1
Civil :: struct {
year: s64
month: s32
day: s32
weekday: s32
}
view: s32;
loaded: bool;
running: bool;
// While running, the wall time it started from; the time counted before
// that start is in elapsed.
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 {
shifted := days + 719468
era := ifx shifted >= 0 then shifted / 146097 else (shifted - 146096) / 146097
day_of_era := shifted - era * 146097
year_of_era := (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / 365
day_of_year := day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100)
month_index := (5 * day_of_year + 2) / 153
result: Civil
result.day = cast(s32)(day_of_year - (153 * month_index + 2) / 5 + 1)
result.month = cast(s32)(ifx month_index < 10 then month_index + 3 else month_index - 9)
result.year = year_of_era + era * 400 + (ifx result.month <= 2 then 1 else 0)
weekday := (days + 4) % 7
if weekday < 0 {
weekday += 7
}
result.weekday = cast(s32)weekday
return result
}
Append :: (output: []u8, used: s32, text: string) -> s32 {
index: s32 = 0
while index < cast(s32)text.count && used < cast(s32)output.count - 1 {
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
AppendTwoDigits :: (output: []u8, used: s32, value: s64) -> s32 {
digits: [3]u8
digits[0] = cast(u8)(48 + cast(s32)((value / 10) % 10))
digits[1] = cast(u8)(48 + cast(s32)(value % 10))
return Append(output, used, TextView(digits[0:2]))
}
AppendNumber :: (output: []u8, used: s32, value: s64) -> s32 {
number: [24]u8
return Append(output, used, FormatInteger(value, number[:]))
}
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)local_offset
}
TimeText :: (output: []u8) -> string {
seconds := LocalSeconds()
of_day := seconds % 86400
if of_day < 0 {
of_day += 86400
}
used := AppendTwoDigits(output, 0, of_day / 3600)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, (of_day / 60) % 60)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, of_day % 60)
return TextView(output[0:used])
}
DateText :: (output: []u8) -> string {
seconds := LocalSeconds()
days := seconds / 86400
if seconds < 0 && seconds % 86400 != 0 {
days -= 1
}
date := CivilFromDays(days)
weekdays: [7]string = .["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
months: [12]string = .["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]
used := Append(output, 0, weekdays[date.weekday])
used = Append(output, used, ", ")
used = AppendNumber(output, used, cast(s64)date.day)
used = Append(output, used, " ")
used = Append(output, used, months[date.month - 1])
used = Append(output, used, " ")
used = AppendNumber(output, used, date.year)
return TextView(output[0:used])
}
StopwatchSeconds :: () -> float64 {
total := elapsed
if running {
total += AppNow() - started_at
}
if total < 0.0 {
return 0.0
}
return total
}
// h:mm:ss.t, or m:ss.t under an hour.
StopwatchText :: (output: []u8) -> string {
tenths := cast(s64)(StopwatchSeconds() * 10.0)
seconds := tenths / 10
used: s32 = 0
if seconds >= 3600 {
used = AppendNumber(output, used, seconds / 3600)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, (seconds / 60) % 60)
} else {
used = AppendNumber(output, used, seconds / 60)
}
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, seconds % 60)
used = Append(output, used, ".")
used = AppendNumber(output, used, tenths % 10)
return TextView(output[0:used])
}
// stopwatch.txt holds "running started_at elapsed" in milliseconds.
LoadStopwatch :: () {
buffer: [128]u8
count := ReadStore("stopwatch.txt", buffer[:])
if count <= 0 {
return
}
values: [3]s64
field: s32 = 0
index: s32 = 0
negative := false
while index < count && field < 3 {
byte := buffer[index]
if byte == cast(u8)32 {
if negative {
values[field] = 0 - values[field]
}
field += 1
negative = false
} else if byte == cast(u8)45 {
negative = true
} else if byte >= cast(u8)48 && byte <= cast(u8)57 {
values[field] = values[field] * 10 + cast(s64)(byte - cast(u8)48)
} else {
return
}
index += 1
}
if field < 3 && negative {
values[field] = 0 - values[field]
}
if field < 2 {
return
}
running = values[0] == 1
started_at = cast(float64)values[1] / 1000.0
elapsed = cast(float64)values[2] / 1000.0
}
SaveStopwatch :: () {
buffer: [128]u8
used := AppendNumber(buffer[:], 0, ifx running then 1 else 0)
used = Append(buffer[:], used, " ")
used = AppendNumber(buffer[:], used, cast(s64)(started_at * 1000.0))
used = Append(buffer[:], used, " ")
used = AppendNumber(buffer[:], used, cast(s64)(elapsed * 1000.0))
unused WriteStore("stopwatch.txt", TextView(buffer[0:used]))
}
Big :: (key: u64, text: string, area: Rectangle, y: float32, font: s32) {
Text.Draw(session, Text.Props.{.key = key, .bounds = Rectangle.{area.x + 16.0, y, area.width - 32.0, cast(float32)(font + 16)},
.text = text, .size = font, .align = TextAlign.TextAlignCenter})
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props := Button.Props.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button.Draw(session, props) != 0
}
Draw :: () {
session = AppSession()
area := AppBounds()
width := area.width - 32.0
if width > 420.0 {
width = 420.0
}
left := area.x + (area.width - width) * 0.5
half := (width - 8.0) / 2.0
if Action(1, "Clock", Rectangle.{left, area.y + 16.0, half, 40.0}, view == VIEW_CLOCK) {
view = VIEW_CLOCK
}
if Action(2, "Stopwatch", Rectangle.{left + half + 8.0, area.y + 16.0, half, 40.0}, view == VIEW_STOPWATCH) {
view = VIEW_STOPWATCH
}
middle := area.y + area.height * 0.35
text: [64]u8
if view == VIEW_CLOCK {
Big(cast(u64)10, TimeText(text[:]), area, middle - 40.0, 56)
date: [96]u8
Big(cast(u64)11, DateText(date[:]), area, middle + 40.0, 18)
return
}
Big(cast(u64)20, StopwatchText(text[:]), area, middle - 40.0, 56)
buttons_y := middle + 56.0
if Action(21, ifx running then "Stop" else "Start", Rectangle.{left, buttons_y, half, 48.0}, true) {
now := AppNow()
if running {
elapsed += now - started_at
} else {
started_at = now
}
running = !running
SaveStopwatch()
}
if Action(22, "Reset", Rectangle.{left + half + 8.0, buttons_y, half, 48.0}, false) {
running = false
elapsed = 0.0
started_at = 0.0
SaveStopwatch()
}
}
#program_export "ClockMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("clock")
AppDescribe("Clock", Icon.Shape)
return APP_PROTOCOL
}
if AppMode() != APP_FRAME {
return 0
}
if !loaded {
LoadStopwatch()
loaded = true
}
Draw()
return 0
}
+196
View File
@@ -0,0 +1,196 @@
// Gallery is a separate portable tool. Only Werk knows platform file grants.
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/tree"
Text :: #import "kryon/text";
Button :: #import "kryon/button";
#import "kryon/control_props"
#import "std/number_text"
#import "std/c_string"
#import "std/text_buffer"
#import "kryon/app_context"
#import "kryon/app_protocol"
Model :: #import "gallery_model";
Icon :: #import "mingcute/mingcute_regular_photo_album";
Image :: #import "kryon/image";
Showing :: #import "kryon/image_showing";
Scroll :: #import "kryon/scroll";
listing: Model.Listing;
viewer: Model.Viewer = Model.Viewer.{.selected = -1, .zoom = 1};
loaded: bool;
status: [32]u8;
location: [1024]u8;
can_up: bool;
grid_offset: s32;
zoom_x: s32;
zoom_y: s32;
session: Session;
// The host's navigation is in the same retained tree as the active tool.
// Keep Gallery controls separate from its Home/avatar keys.
KEY_BASE :: 2000000
Call :: (request: string) -> string { return AppService("gallery.local.v1", request) }
Indexed :: (verb: string, index: s32) -> string {
number: [24]u8; buffer: [64]u8
text := FormatInteger(cast(s64)index, number[:])
for at: 0..verb.count - 1 { buffer[at] = verb[at] }
for at: 0..text.count - 1 { buffer[verb.count + at] = text[at] }
buffer[verb.count + text.count] = cast(u8)0
return Call(TextUntilNul(buffer[:]))
}
Reload :: () {
listing.count = Model.Index(Call("count"))
if listing.count < 0 { listing.count = 0 }
if listing.count > Model.LIMIT { listing.count = Model.LIMIT }
for index: 0..listing.count - 1 {
unused CopyCString(Indexed("name:", cast(s32)index), listing.entries[index].name[:])
listing.entries[index].folder = Indexed("kind:", cast(s32)index) == "folder"
listing.entries[index].path[0] = cast(u8)0
}
unused CopyCString(Call("location"), location[:]); can_up = Call("can-up") == "yes"
unused CopyCString(Call("status"), status[:])
viewer = Model.Viewer.{.selected = -1, .zoom = 1}; grid_offset = 0; zoom_x = 0; zoom_y = 0
}
Action :: (id: s32, label: string, bounds: Rectangle, disabled: bool) -> bool {
return Button.Draw(session, Button.Props.{.key = cast(u64)(KEY_BASE + id), .id = KEY_BASE + id, .bounds = bounds,
.label = label, .disabled = disabled, .tone = ButtonTone.ButtonToneNeutral,
.emphasis = ButtonEmphasis.ButtonEmphasisSoft, .fit_content = true}) != 0
}
Label :: (key: u64, text: string, bounds: Rectangle) {
Text.Draw(session, Text.Props.{.key = cast(u64)KEY_BASE + key, .bounds = bounds, .text = text, .size = 16})
}
Picture :: (index: s32, bounds: Rectangle, preview: bool = false) -> bool {
entry := *listing.entries[index]
unused CopyCString(Indexed(ifx preview then "thumb:" else "asset:", index), entry.path[:])
props := Image.Props.{.key = cast(u64)(KEY_BASE + 5000 + index), .bounds = bounds,
.asset_path = TextUntilNul(entry.path[:]), .alt_text = TextUntilNul(entry.name[:]),
.fit = Image.ImageFit.ImageFitContain, .smooth = true}
if props.asset_path == "" {
Label(cast(u64)(7000 + index), "Image unavailable", bounds)
return false
}
state := Showing.ImageShowingOf(session, props)
if state == Image.ImageShowing.ImageShowingUnavailable {
Label(cast(u64)(7000 + index), "Image unavailable", bounds)
return false
}
if state == Image.ImageShowing.ImageShowingNone { Label(cast(u64)(7000 + index), "Loading image...", bounds) }
Image.Draw(session, props)
return true
}
DrawViewer :: (area: Rectangle) {
width := (area.width - 32.0) / 3.0
if Action(30, "Albums", Rectangle.{area.x, area.y, width, 42.0}, false) { viewer.selected = -1; return }
previous := viewer; Model.Move(*previous, *listing, -1)
next := viewer; Model.Move(*next, *listing, 1)
if Action(31, "Previous", Rectangle.{area.x + width + 8.0, area.y, width, 42.0}, previous.selected == viewer.selected) { viewer = previous; zoom_x = 0; zoom_y = 0 }
if Action(32, "Next", Rectangle.{area.x + (width + 8.0) * 2.0, area.y, width, 42.0}, next.selected == viewer.selected) { viewer = next; zoom_x = 0; zoom_y = 0 }
if AppKey() == 263 { Model.Move(*viewer, *listing, -1); zoom_x = 0; zoom_y = 0 }
if AppKey() == 262 { Model.Move(*viewer, *listing, 1); zoom_x = 0; zoom_y = 0 }
if AppKey() == 256 { viewer.selected = -1; return }
Label(40, TextUntilNul(listing.entries[viewer.selected].name[:]), Rectangle.{area.x, area.y + 50.0, area.width, 28.0})
viewport := Rectangle.{area.x, area.y + 84.0, area.width - 8.0, area.height - 194.0}
if viewport.height < 40.0 { viewport.height = 40.0 }
scale := cast(float32)viewer.zoom
horizontal := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 50, .bounds = viewport, .horizontal = true,
.content_width = cast(s32)(viewport.width * scale), .scroll_offset = zoom_x, .manual_scroll = true})
zoom_x = horizontal.scroll_offset
vertical := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 51, .bounds = viewport,
.content_height = cast(s32)(viewport.height * scale), .scroll_offset = zoom_y, .manual_scroll = true})
zoom_y = vertical.scroll_offset
available := Picture(viewer.selected, Rectangle.{horizontal.content.x, vertical.content.y, viewport.width * scale, viewport.height * scale})
if vertical.opened { unused End(session) }
if horizontal.opened { unused End(session) }
if !available {
problem: [256]u8
unused CopyCString(Indexed("asset-error:", viewer.selected), problem[:])
if problem[0] == cast(u8)0 { unused CopyCString(Model.ImageError(Model.IMAGE_FORMAT_ERROR), problem[:]) }
Label(54, TextUntilNul(problem[:]), Rectangle.{viewport.x + 8.0, viewport.y + 36.0, viewport.width - 16.0, 80.0})
if Action(55, "Retry image", Rectangle.{viewport.x + 8.0, viewport.y + 122.0, 140.0, 40.0}, false) { unused Indexed("retry:", viewer.selected) }
}
pan_width := (area.width - 24.0) / 4.0
pan_y := area.y + area.height - 94.0
step_x := cast(s32)(viewport.width / 4.0)
step_y := cast(s32)(viewport.height / 4.0)
max_x := cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1))
max_y := cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1))
if Action(60, "Pan left", Rectangle.{area.x, pan_y, pan_width, 38.0}, !available || zoom_x <= 0) { zoom_x -= step_x }
if Action(61, "Pan right", Rectangle.{area.x + pan_width + 8.0, pan_y, pan_width, 38.0}, !available || zoom_x >= max_x) { zoom_x += step_x }
if Action(62, "Pan up", Rectangle.{area.x + (pan_width + 8.0) * 2.0, pan_y, pan_width, 38.0}, !available || zoom_y <= 0) { zoom_y -= step_y }
if Action(63, "Pan down", Rectangle.{area.x + (pan_width + 8.0) * 3.0, pan_y, pan_width, 38.0}, !available || zoom_y >= max_y) { zoom_y += step_y }
if zoom_x < 0 { zoom_x = 0 }; if zoom_x > max_x { zoom_x = max_x }
if zoom_y < 0 { zoom_y = 0 }; if zoom_y > max_y { zoom_y = max_y }
y := area.y + area.height - 48.0
if Action(33, "Zoom out", Rectangle.{area.x, y, width, 42.0}, !available || viewer.zoom == 1) { Model.Zoom(*viewer, -1); zoom_x = cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1) * 0.5); zoom_y = cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1) * 0.5) }
if Action(34, "Fit", Rectangle.{area.x + width + 8.0, y, width, 42.0}, false) { viewer.zoom = 1; zoom_x = 0; zoom_y = 0 }
if Action(35, "Zoom in", Rectangle.{area.x + (width + 8.0) * 2.0, y, width, 42.0}, !available || viewer.zoom == 4) { Model.Zoom(*viewer, 1); zoom_x = cast(s32)(viewport.width * cast(float32)(viewer.zoom - 1) * 0.5); zoom_y = cast(s32)(viewport.height * cast(float32)(viewer.zoom - 1) * 0.5) }
}
DrawGrid :: (area: Rectangle) {
pending := TextUntilNul(status[:]) == "pending"
if Action(10, "Choose folder", Rectangle.{area.x, area.y, 148.0, 44.0}, pending) {
unused CopyCString(Call("choose"), status[:]); pending = TextUntilNul(status[:]) == "pending"
}
if Action(11, "Refresh", Rectangle.{area.x + 156.0, area.y, 92.0, 44.0}, pending) { unused Call("refresh"); Reload() }
if can_up && Action(12, "Up", Rectangle.{area.x + 256.0, area.y, 54.0, 44.0}, pending) { unused Call("up"); Reload() }
Label(13, TextUntilNul(location[:]), Rectangle.{area.x, area.y + 52.0, area.width, 26.0})
current := TextUntilNul(status[:])
message := "Name order - folders first"
if current == "pending" { message = "Choose a local folder in the system window" }
else if current == "empty" { message = "Choose a folder to browse photos on this device" }
else if current == "cancelled" { message = "Selection cancelled - your folder is unchanged" }
else if current == "error" { message = "Cannot read this folder. Choose it again or refresh." }
else if current == "save-error" { message = "Could not save this selection. Your previous folder is unchanged. Try again." }
else if current == "chooser-missing" { message = "Folder chooser unavailable. Install Zenity, then choose the folder again." }
else if current == "unavailable" { message = "Local folders are available in the Android and desktop apps" }
else if current == "limited" { message = "Showing first 512 items by name. Open a smaller folder." }
else if listing.count == 0 { message = "No supported photos or albums in this folder" }
Label(14, message, Rectangle.{area.x, area.y + 82.0, area.width, 46.0})
columns := cast(s32)(area.width / 150.0)
if columns < 2 { columns = 2 }
tile := (area.width - cast(float32)(columns - 1) * 8.0) / cast(float32)columns
height := tile + 38.0
rows := (listing.count + columns - 1) / columns
viewport := Rectangle.{area.x, area.y + 134.0, area.width, area.height - 134.0}
grid := Scroll.Draw(session, Scroll.Props.{.key = KEY_BASE + 20, .bounds = viewport,
.content_height = cast(s32)(cast(float32)rows * (height + 8.0)), .scroll_offset = grid_offset})
grid_offset = grid.scroll_offset
for index: 0..listing.count - 1 {
x := grid.content.x + cast(float32)(index % columns) * (tile + 8.0)
y := grid.content.y + cast(float32)(index / columns) * (height + 8.0)
if y + height >= viewport.y && y < viewport.y + viewport.height {
entry := *listing.entries[index]
if !entry.folder { unused Picture(cast(s32)index, Rectangle.{x + 4.0, y + 4.0, tile - 8.0, tile - 8.0}, true) }
else { Label(cast(u64)(4000 + index), "Folder", Rectangle.{x + 8.0, y + 12.0, tile - 16.0, tile - 12.0}) }
Label(cast(u64)(6000 + index), TextUntilNul(entry.name[:]), Rectangle.{x + 8.0, y + tile, tile - 16.0, 34.0})
if Button.Draw(session, Button.Props.{.key = cast(u64)(KEY_BASE + 100 + index), .id = cast(s32)(KEY_BASE + 100 + index),
.bounds = Rectangle.{x, y, tile, height}, .label = TextUntilNul(entry.name[:]),
.invisible = true, .disabled = pending}) != 0 {
if entry.folder { unused Indexed("enter:", cast(s32)index); loaded = false; break }
else { viewer = Model.Viewer.{.selected = cast(s32)index, .zoom = 1}; zoom_x = 0; zoom_y = 0 }
}
}
}
if grid.opened { unused End(session) }
}
#program_export "GalleryMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("gallery"); AppDescribe("Gallery", Icon.Shape); return APP_PROTOCOL
}
if AppMode() == APP_BACK && viewer.selected >= 0 { viewer.selected = -1; return 1 }
if AppMode() != APP_FRAME { return 0 }
session = AppSession()
if !loaded { Reload(); loaded = true }
if TextUntilNul(status[:]) == "pending" {
value := Call("poll")
if value != "pending" { Reload() }
}
area := AppBounds()
area.x += 12.0; area.y += 12.0; area.width -= 24.0; area.height -= 24.0
if viewer.selected >= 0 { DrawViewer(area) } else { DrawGrid(area) }
return 0
}
+152
View File
@@ -0,0 +1,152 @@
// Portable gallery state. No account, network, deletion or arbitrary-path API.
#import "std/text_buffer"
#import "std/byte_text_linux"
#import "std/c_string"
LIMIT :: 512
PATH_CAPACITY :: 1024
IMAGE_BYTE_LIMIT :: 67108864
IMAGE_PIXEL_LIMIT :: 32000000
IMAGE_READ_ERROR :: 1
IMAGE_FORMAT_ERROR :: 2
IMAGE_LIMIT_ERROR :: 3
ImageError :: (reason: s32) -> string {
if reason == IMAGE_READ_ERROR { return "Cannot read image. Retry or refresh the folder." }
if reason == IMAGE_FORMAT_ERROR { return "Cannot decode image. Retry or choose another photo." }
if reason == IMAGE_LIMIT_ERROR { return "Image exceeds the viewing limit: 64 MiB or 32 megapixels." }
return ""
}
Dimensions :: struct { width: s64; height: s64 }
Big16 :: (bytes: []u8, at: s32) -> s64 { return cast(s64)bytes[at] * 256 + cast(s64)bytes[at + 1] }
Little :: (bytes: []u8, at: s32, count: s32) -> s64 {
value: s64; multiplier: s64 = 1
for index: 0..count - 1 { value += cast(s64)bytes[at + index] * multiplier; multiplier *= 256 }
return value
}
Big32 :: (bytes: []u8, at: s32) -> s64 { return Big16(bytes, at) * 65536 + Big16(bytes, at + 2) }
PixelError :: (size: Dimensions) -> s32 {
if size.width <= 0 || size.height <= 0 { return IMAGE_FORMAT_ERROR }
if size.height > IMAGE_PIXEL_LIMIT || size.width > IMAGE_PIXEL_LIMIT / size.height { return IMAGE_LIMIT_ERROR }
return 0
}
// Header-only bounds checks run before a native decoder allocates pixels.
// JPEG's variable-length segments are walked by the host with bounded I/O.
HeaderDimensions :: (bytes: []u8) -> Dimensions {
if bytes.count < 30 { return .{} }
if bytes[0] == 137 && bytes[1] == 80 && bytes[2] == 78 && bytes[3] == 71 && bytes[12] == 73 && bytes[13] == 72 && bytes[14] == 68 && bytes[15] == 82 {
return Dimensions.{Big32(bytes, 16), Big32(bytes, 20)}
}
if bytes[0] == 71 && bytes[1] == 73 && bytes[2] == 70 { return Dimensions.{Little(bytes, 6, 2), Little(bytes, 8, 2)} }
if bytes[0] == 66 && bytes[1] == 77 {
height := Little(bytes, 22, 4)
if height >= 2147483648 { height = 4294967296 - height }
return Dimensions.{Little(bytes, 18, 4), height}
}
if bytes[0] == 82 && bytes[1] == 73 && bytes[2] == 70 && bytes[3] == 70 && bytes[8] == 87 && bytes[9] == 69 && bytes[10] == 66 && bytes[11] == 80 {
if bytes[15] == 88 { return Dimensions.{Little(bytes, 24, 3) + 1, Little(bytes, 27, 3) + 1} }
if bytes[15] == 76 && bytes[20] == 47 {
bits := Little(bytes, 21, 4)
return Dimensions.{(bits & 16383) + 1, ((bits >> 14) & 16383) + 1}
}
if bytes[15] == 32 && bytes[23] == 157 && bytes[24] == 1 && bytes[25] == 42 { return Dimensions.{Little(bytes, 26, 2) & 16383, Little(bytes, 28, 2) & 16383} }
}
return .{}
}
Entry :: struct {
name: [256]u8
path: [PATH_CAPACITY]u8
folder: bool
}
Listing :: struct {
entries: [LIMIT]Entry
count: s32
truncated: bool
}
Viewer :: struct {
selected: s32
zoom: s32
pan_x: s32
pan_y: s32
}
ImageName :: (name: string) -> bool {
dot: s64 = -1
for index: 0..name.count - 1 { if name[index] == #char "." { dot = index } }
if dot < 0 || name.count - dot > 6 { return false }
extension: [8]u8
for index: dot..name.count - 1 {
byte := name[index]
if byte >= #char "A" && byte <= #char "Z" { byte += cast(u8)32 }
extension[index - dot] = byte
}
suffix := TextUntilNul(extension[:])
return suffix == ".jpg" || suffix == ".jpeg" || suffix == ".png" || suffix == ".webp" || suffix == ".bmp" || suffix == ".gif"
}
// Bytewise UTF-8 order is stable across platforms, locales and launches.
Before :: (left: Entry, right: Entry) -> bool {
if left.folder != right.folder { return left.folder }
a := TextUntilNul(left.name[:]); b := TextUntilNul(right.name[:])
count := ifx a.count < b.count then a.count else b.count
for index: 0..count - 1 { if a[index] != b[index] { return a[index] < b[index] } }
if a.count != b.count { return a.count < b.count }
a = TextUntilNul(left.path[:]); b = TextUntilNul(right.path[:])
count = ifx a.count < b.count then a.count else b.count
for index: 0..count - 1 { if a[index] != b[index] { return a[index] < b[index] } }
return a.count < b.count
}
Add :: (listing: *Listing, name: string, path: string, folder: bool) -> bool {
if name == "" || name == "." || name == ".." || name.count >= 256 || path == "" || path.count >= PATH_CAPACITY { return false }
entry: Entry
unused CopyCString(name, entry.name[:]); unused CopyCString(path, entry.path[:]); entry.folder = folder
// Retain the first LIMIT entries in sorted order even when the provider's
// enumeration order varies. Never silently present an arbitrary subset.
at := listing.count
if at == LIMIT {
listing.truncated = true
if !Before(entry, listing.entries[LIMIT - 1]) { return false }
at -= 1
} else { listing.count += 1 }
while at > 0 && Before(entry, listing.entries[at - 1]) {
listing.entries[at] = listing.entries[at - 1]; at -= 1
}
listing.entries[at] = entry
return true
}
Index :: (text: string) -> s32 {
if text == "" { return -1 }
result: s32 = 0
for index: 0..text.count - 1 {
if text[index] < #char "0" || text[index] > #char "9" || result > 10000 { return -1 }
result = result * 10 + cast(s32)(text[index] - #char "0")
}
return result
}
Move :: (viewer: *Viewer, listing: *Listing, direction: s32) {
at := viewer.selected + direction
while at >= 0 && at < listing.count {
if !listing.entries[at].folder {
viewer.selected = at; viewer.zoom = 1; viewer.pan_x = 0; viewer.pan_y = 0; return
}
at += direction
}
}
Zoom :: (viewer: *Viewer, delta: s32) {
viewer.zoom += delta
if viewer.zoom < 1 { viewer.zoom = 1 }
if viewer.zoom > 4 { viewer.zoom = 4 }
viewer.pan_x = 0; viewer.pan_y = 0
}
Within :: (root: string, path: string) -> bool {
if root == "" || path == "" { return false }
if root == path { return true }
if root == "/" { return path[0] == #char "/" }
return path.count > root.count && path[:root.count] == root && path[root.count] == #char "/"
}
+166
View File
@@ -0,0 +1,166 @@
{
"format": 1,
"packages": [
{
"commit": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"dependencies": {},
"id": "p0dd67588478f9a3e",
"name": "libsamplerate",
"ref": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"source": true,
"url": "https://github.com/libsndfile/libsamplerate.git"
},
{
"commit": "829a65d769d935c4852f8159e964312c0957260a",
"dependencies": {},
"id": "p16cd0434af3dff7b",
"name": "sdl3",
"ref": "829a65d769d935c4852f8159e964312c0957260a",
"source": true,
"url": "https://github.com/libsdl-org/SDL.git"
},
{
"commit": "f26a552247e2cd367fd33def6860d903cac6ab8a",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p274c2dd6d03a7c0c",
"name": "avif",
"ref": "f26a552247e2cd367fd33def6860d903cac6ab8a",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "p2af20e0c835b1c63",
"name": "webp",
"ref": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "1844042d1ca751e62e61df7617dba19c98588339",
"dependencies": {},
"id": "p3b3c785a0e17e605",
"name": "libwebp",
"ref": "1844042d1ca751e62e61df7617dba19c98588339",
"source": true,
"url": "https://github.com/webmproject/libwebp.git"
},
{
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
"dependencies": {},
"id": "p57c0272208aae8db",
"name": "libavif",
"ref": "1aadfad932c98c069a1204261b1856f81f3bc199",
"source": true,
"url": "https://github.com/AOMediaCodec/libavif.git"
},
{
"commit": "bd278217e2bac754d868b3d6502eac4257658d4b",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa"},
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
"id": "p5d7d12505a42f7b3",
"name": "av1",
"ref": "bd278217e2bac754d868b3d6502eac4257658d4b",
"url": "https://github.com/ziranlang/av1.git"
},
{
"commit": "360553150917f352e49e1beb78917370792ccaef",
"dependencies": {},
"id": "p69c0e968ae5735d9",
"name": "image-codec",
"ref": "360553150917f352e49e1beb78917370792ccaef",
"url": "https://github.com/ziranlang/image-codec.git"
},
{
"commit": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"dependencies": {},
"id": "p74ab3cb6eb3b86fa",
"name": "libaom",
"ref": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"source": true,
"url": "https://aomedia.googlesource.com/aom"
},
{
"commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"dependencies": {},
"id": "pb24767b9eb34d961",
"name": "dav1d",
"ref": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"source": true,
"url": "https://github.com/videolan/dav1d.git"
},
{
"commit": "ce5837f80e8ce6cb8d2d9f77915095d764da3485",
"dependencies": {"dr_libs": "pb7c2dd1c09da0c1c", "libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e", "stb": "pe4a63e2d6e0424e7"},
"dependency_refs": {"dr_libs": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c", "libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7", "stb": "9600522de53973336fa033a289858a4354cbb04c"},
"id": "pb46a53117b2530ce",
"name": "audio",
"ref": "ce5837f80e8ce6cb8d2d9f77915095d764da3485",
"url": "https://github.com/ziranlang/audio.git"
},
{
"commit": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c",
"dependencies": {},
"id": "pb7c2dd1c09da0c1c",
"name": "dr_libs",
"ref": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c",
"source": true,
"url": "https://github.com/mackron/dr_libs.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"dependencies": {},
"id": "pcc7aa76725f2fb2f",
"name": "raylib",
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"source": true,
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "9cc6872f75447c3a24c16764f9829d0f58751cb0",
"dependencies": {},
"id": "pe1027b9d16704793",
"name": "mingcute",
"ref": "master",
"url": "https://github.com/kryonlabs/mingcute.git"
},
{
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"dependencies": {},
"id": "pe1fe9bbe80bf1d6d",
"name": "libopus",
"ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"source": true,
"url": "https://github.com/xiph/opus.git"
},
{
"commit": "9600522de53973336fa033a289858a4354cbb04c",
"dependencies": {},
"id": "pe4a63e2d6e0424e7",
"name": "stb",
"ref": "9600522de53973336fa033a289858a4354cbb04c",
"source": true,
"url": "https://github.com/nothings/stb.git"
},
{
"commit": "3f72441949d4e16094834fa9220e5d7fa77a0ac0",
"dependencies": {"audio": "pb46a53117b2530ce", "avif": "p274c2dd6d03a7c0c", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "raylib": "pcc7aa76725f2fb2f", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
"dependency_refs": {"audio": "ce5837f80e8ce6cb8d2d9f77915095d764da3485", "avif": "f26a552247e2cd367fd33def6860d903cac6ab8a", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "raylib": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
"id": "peb1e86e2b07f33bb",
"name": "kryon",
"ref": "3f72441949d4e16094834fa9220e5d7fa77a0ac0",
"url": "https://github.com/kryonlabs/kryon.git"
}
],
"root": {
"dependencies": {"kryon": "peb1e86e2b07f33bb", "mingcute": "pe1027b9d16704793"},
"dependency_refs": {"kryon": "3f72441949d4e16094834fa9220e5d7fa77a0ac0", "mingcute": "master"},
"name": "werk-gallery"
},
"toolchain": {
"commit": "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda",
"ref": "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda",
"url": "https://github.com/ziranlang/ziran.git"
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "werk-gallery"
entry = "gallery.zi"
module_roots = ["."]
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "e0367fa9c5731dcf9bb84ed7f3d294570d8c0bda"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "3f72441949d4e16094834fa9220e5d7fa77a0ac0"
[dependencies.mingcute]
git = "https://github.com/kryonlabs/mingcute.git"
ref = "master"
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+189
View File
@@ -0,0 +1,189 @@
#import "pass_core"
#import "pass_text"
#import "byte_text_linux"
#import "version"
#import "c_string"
#import "text_buffer"
#import "cli_profiles"
#import "cli_native"
libc :: #system_library "libc";
Write :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
GetEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
Usage :: #string END
Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
Derive a site-specific password.
Options:
-L, --length N password length (default 16, min 5, max 35)
-C, --counter N generation counter (default 1)
-l, --lowercase include lowercase letters
-u, --uppercase include uppercase letters
-d, --digits include digits
-s, --symbols include symbols
--no-lowercase exclude lowercase letters
--no-uppercase exclude uppercase letters
--no-digits exclude digits
--no-symbols exclude symbols
--exclude CHARS remove characters from all enabled classes
-p, --prompt read the master password from stdin
-P, --profile NAME use a saved login and generation settings
--vault PATH unlock an OpenSSL-encrypted master password
--clear-after TIME release copied password after e.g. 90s
-c, --copy copy the result to the X11 clipboard
--no-copy print instead of copying
-v, --version show version
-h, --help show this help
END;
Print :: (fd: s32, value: string) {
buffer: [4096]u8
offset: s32 = 0
while offset < cast(s32)value.count {
count: s32 = cast(s32)value.count - offset
if count > 4096 { count = 4096 }
index: s32 = 0
while index < count { buffer[index] = value[offset + index]; index += 1 }
written: s32 = 0
while written < count {
result: isize = Write(fd, *buffer[written], cast(usize)(count - written))
if result <= cast(isize)0 { return }
written += cast(s32)result
}
offset += count
}
}
Error :: (message: string) -> s32 {
Print(2, "pass: "); Print(2, message); Print(2, "\n")
return 2
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
options: PassOptions
options.length = 16; options.counter = cast(u64)1
options.lowercase = true; options.uppercase = true
options.digits = true; options.symbols = true
prompt: bool; copy: bool; no_copy: bool; version: bool
profile_name: string; vault_path: string; clear_after: string
explicit: u32
positional: [3]string
count: s32 = 0
index: s32 = 1
while index < argc {
arg := TextFromCString(argv[index])
if arg == "-h" || arg == "--help" { Print(1, Usage); return 0 }
if arg == "-v" || arg == "--version" { version = true }
else if arg == "-L" || arg == "--length" || arg == "-C" ||
arg == "--counter" || arg == "--exclude" || arg == "-P" ||
arg == "--profile" || arg == "--vault" || arg == "--clear-after" {
if index + 1 >= argc {
Print(2, "pass: "); Print(2, arg); Print(2, " requires a value\n")
Print(2, Usage); return 2
}
index += 1
value := TextFromCString(argv[index])
if arg == "--exclude" { options.exclude = value; explicit |= cast(u32)64 }
else if arg == "-P" || arg == "--profile" { profile_name = value }
else if arg == "--vault" { vault_path = value }
else if arg == "--clear-after" { clear_after = value }
else {
number := ParseNumber(value)
if !number.valid { Print(2, Usage); return 2 }
if arg == "-L" || arg == "--length" {
if number.value > 2147483647 || number.value < -2147483647 { Print(2, Usage); return 2 }
options.length = cast(s32)number.value
explicit |= cast(u32)1
} else {
if number.value < 0 { number.value = 0 }
options.counter = cast(u64)number.value
explicit |= cast(u32)2
}
}
} else {
handled: bool = true
if arg == "-l" || arg == "--lowercase" { options.lowercase = true; explicit |= cast(u32)4 }
else if arg == "-u" || arg == "--uppercase" { options.uppercase = true; explicit |= cast(u32)8 }
else if arg == "-d" || arg == "--digits" { options.digits = true; explicit |= cast(u32)16 }
else if arg == "-s" || arg == "--symbols" { options.symbols = true; explicit |= cast(u32)32 }
else if arg == "--no-lowercase" { options.lowercase = false; explicit |= cast(u32)4 }
else if arg == "--no-uppercase" { options.uppercase = false; explicit |= cast(u32)8 }
else if arg == "--no-digits" { options.digits = false; explicit |= cast(u32)16 }
else if arg == "--no-symbols" { options.symbols = false; explicit |= cast(u32)32 }
else if arg == "-p" || arg == "--prompt" { prompt = true }
else if arg == "-c" || arg == "--copy" { copy = true }
else if arg == "--no-copy" { no_copy = true }
else { handled = false }
if !handled {
if arg.count > 0 && arg[0] == cast(u8)45 { return Error("unknown option") }
if count >= 3 { return Error("too many positional arguments") }
positional[count] = arg; count += 1
}
}
index += 1
}
if version { Print(1, "pass "); Print(1, Version); Print(1, "\n"); return 0 }
site: string; login: string; clear_ms: s64
// Keep the decoded profile alive until generation has finished.
profile: LegacyProfile
if profile_name != "" {
if count != 1 { return Error("expected SITE with --profile") }
} else if count < 2 { Print(2, Usage); return 2 }
candidate := profile_name
if candidate == "" && count == 2 { candidate = positional[0] }
profile = LoadLegacyProfile(candidate, profile_name != "", *options, explicit)
if !profile.valid { return Error("invalid CLI profiles configuration or unknown profile") }
if profile.found {
site = ifx profile_name != "" then positional[0] else positional[1]
login = TextUntilNul(profile.login[:])
if (explicit & cast(u32)64) == cast(u32)0 { options.exclude = TextUntilNul(profile.exclude[:]) }
} else { site = positional[0]; login = positional[1] }
if !copy { copy = profile.copy }
clear_ms = profile.clear_ms
if clear_after != "" {
clear_ms = DurationMilliseconds(clear_after)
if clear_ms < 0 { return Error("invalid --clear-after duration") }
}
if vault_path == "" && !prompt && count != 3 { vault_path = TextUntilNul(profile.vault[:]) }
if vault_path != "" && (prompt || count == 3) { return Error("--vault cannot be combined with --prompt or MASTER_PASSWORD") }
if prompt && count == 3 { return Error("MASTER_PASSWORD cannot be supplied together with --prompt") }
master: [1024]u8
defer { ClearBytes(master[:]) }
if count == 3 {
if !CopyText(positional[2], master[:]) { return Error("master password is too long") }
} else {
unlocked: bool
if vault_path != "" {
if !DecryptVault(vault_path, master[:]) { return Error("cannot unlock vault: wrong passphrase, unreadable or corrupted vault") }
unlocked = true
}
if !unlocked {
name: [32]u8
CopyCString("LESSPASS_MASTER_PASSWORD", name[:])
environment: *u8 = GetEnv(*name[0])
if !prompt && environment != null {
if !CopyText(TextFromCString(environment), master[:]) { return Error("master password is too long") }
} else {
if !ReadSecret(master[:], "Master password: ") { return Error("missing master password") }
}
}
}
generated := PassGenerate(site, login, TextUntilNul(master[:]), options)
defer { ClearBytes(generated.password[:]) }
ClearBytes(master[:])
if !generated.valid {
Print(2, "pass: "); Print(2, generated.error); Print(2, "\n"); return 1
}
if copy && !no_copy {
if !CopyPassword(TextView(generated.password[0:generated.length]), clear_ms) {
return Error("clipboard unavailable; install xclip or use --no-copy")
}
Print(2, "Password copied to the clipboard.\n"); return 0
}
Print(1, TextView(generated.password[0:generated.length])); Print(1, "\n")
return 0
}
+229
View File
@@ -0,0 +1,229 @@
#import "pass_text"
#import "std/c_string"
#import "std/text_buffer"
#import "std/byte_text_linux"
Capture :: #import "std/process_capture_linux";
Channel :: #import "std/process_channel_linux";
Socket :: #import "std/socket_linux";
Timer :: #import "std/timer_linux";
libc :: #system_library "libc";
NativeRead :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "read";
NativeWrite :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
NativeOpen :: (path: *u8, flags: s32) -> s32 #foreign libc "open";
NativeClose :: (fd: s32) -> s32 #foreign libc "close";
NativeEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
NativeIsTty :: (fd: s32) -> s32 #foreign libc "isatty";
NativeGetTerminal :: (fd: s32, state: *void) -> s32 #foreign libc "tcgetattr";
NativeSetTerminal :: (fd: s32, action: s32, state: *void) -> s32 #foreign libc "tcsetattr";
NativeSession :: () -> s32 #foreign libc "setsid";
NativeShutdown :: (fd: s32, direction: s32) -> s32 #foreign libc "shutdown";
NativePipe :: (fds: *s32) -> s32 #foreign libc "pipe";
NativeDescriptorFlags :: (fd: s32, command: s32, value: s32) -> s32 #foreign libc "fcntl";
NativeFork :: () -> s32 #foreign libc "fork";
NativeDup :: (source: s32, destination: s32) -> s32 #foreign libc "dup2";
NativeExit :: (code: s32) -> void #foreign libc "_exit";
NativeWait :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc "waitpid";
SignalHandler :: #type (signal: s32) #c_call;
NativeSignal :: (signal: s32, handler: SignalHandler) -> SignalHandler #foreign libc "signal";
terminal_fd: s32 = -1;
terminal_state: [32]u64;
RestoreTerminalOnSignal :: (signal: s32) {
if terminal_fd >= 0 { unused NativeSetTerminal(terminal_fd, 0, cast(*void)*terminal_state[0]) }
NativeExit(128 + signal)
}
EnvironmentText :: (name: string) -> string {
bytes: [128]u8
if !CopyCString(name, bytes[:]) { return "" }
value := NativeEnv(*bytes[0])
if value == null { return "" }
return TextFromCString(value)
}
ExpandHomePath :: (value: string, output: []u8) -> bool {
if value == "~" || (value.count >= 2 && value[0:2] == "~/") {
home := EnvironmentText("HOME")
if home == "" { return false }
return AppendText(output, AppendText(output, 0, home), value[1:]) >= 0
}
return CopyCString(value, output)
}
// 0 means no file; -1 is an unreadable, oversized or invalid configuration.
ReadProfileDocument :: (output: []u8) -> s32 {
path: [4096]u8
base := EnvironmentText("XDG_CONFIG_HOME")
if base != "" { if !CopyCString(base, path[:]) { return -1 } }
else if !ExpandHomePath("~/.config", path[:]) { return 0 }
if AppendText(path[:], cast(s32)TextUntilNul(path[:]).count, "/pass/profiles.json") < 0 { return -1 }
fd := NativeOpen(*path[0], 0)
if fd < 0 { if Socket.LinuxErrno() == 2 { return 0 }; return -1 }
defer { unused NativeClose(fd) }
used: s32
while used < cast(s32)output.count - 1 {
count := NativeRead(fd, *output[used], cast(usize)(cast(s32)output.count - 1 - used))
if count < cast(isize)0 { return -1 }
if count == cast(isize)0 { output[used] = cast(u8)0; return used + 1 }
used += cast(s32)count
}
return -1
}
ReadSecret :: (buffer: []u8, prompt: string) -> bool {
fd: s32 = 0
terminal := NativeIsTty(fd) == 1
previous: [4]SignalHandler
signals: [4]s32 = .[1, 2, 3, 15]
if terminal {
if NativeGetTerminal(fd, cast(*void)*terminal_state[0]) != 0 { return false }
terminal_fd = fd
for i: 0..3 { previous[i] = NativeSignal(signals[i], RestoreTerminalOnSignal) }
}
defer {
if terminal {
unused NativeSetTerminal(fd, 0, cast(*void)*terminal_state[0])
terminal_fd = -1
restored: s32 = 0
while restored < 4 {
unused NativeSignal(signals[restored], previous[restored]); restored += 1
}
newline: [1]u8 = .[cast(u8)10]
unused NativeWrite(2, *newline[0], cast(usize)1)
}
}
if terminal {
// stty owns the platform-specific termios layout. The opaque saved
// state is restored even when input is cancelled with Ctrl-C.
ignored: [128]u8
args: [8]string = .["stty", "-echo", "-isig", "-icanon", "min", "1", "time", "0"]
changed := Capture.CaptureOutput(args[:], ignored[:])
if changed.error || changed.code != 0 { return false }
message: [128]u8
if CopyCString(prompt, message[:]) { unused NativeWrite(2, *message[0], cast(usize)prompt.count) }
}
used: s32
while used < cast(s32)buffer.count - 1 {
byte: u8
if NativeRead(fd, *byte, cast(usize)1) != cast(isize)1 { return used > 0 }
if byte == cast(u8)0 || byte == cast(u8)3 || byte == cast(u8)4 { return false }
if terminal && (byte == cast(u8)8 || byte == cast(u8)127) {
if used > 0 { used -= 1; buffer[used] = cast(u8)0 }
continue
}
if terminal && byte == cast(u8)21 { ClearBytes(buffer); used = 0; continue }
if byte == cast(u8)10 {
if used > 0 && buffer[used - 1] == cast(u8)13 { used -= 1 }
buffer[used] = cast(u8)0; return true
}
buffer[used] = byte; used += 1
}
return false
}
DecryptVault :: (vault: string, output: []u8) -> bool {
path: [4096]u8
if !ExpandHomePath(vault, path[:]) { return false }
passphrase: [1024]u8
defer { ClearBytes(passphrase[:]) }
if !ReadSecret(passphrase[:], "Vault passphrase: ") { return false }
// Legacy vaults may wrap their base64 with spaces, tabs or CRLF, which
// OpenSSL 3.0 rejects. Send it without whitespace through a pipe that
// openssl opens as its input; stdin stays the passphrase.
encoded: [60000]u8
file := NativeOpen(*path[0], 0)
if file < 0 { return false }
size: s32 = 0
while true {
byte: u8
count := NativeRead(file, *byte, cast(usize)1)
if count != cast(isize)1 { break }
if byte == cast(u8)32 || (byte >= cast(u8)9 && byte <= cast(u8)13) { continue }
if size >= cast(s32)encoded.count - 1 { unused NativeClose(file); return false }
encoded[size] = byte; size += 1
}
unused NativeClose(file)
encoded[size] = cast(u8)10
pipe: [2]s32
if NativePipe(*pipe[0]) != 0 { return false }
// Only openssl keeps the reading end; the writer closes before it starts.
if NativeDescriptorFlags(pipe[1], 2, 1) != 0 ||
NativeWrite(pipe[1], *encoded[0], cast(usize)(size + 1)) != cast(isize)(size + 1) {
unused NativeClose(pipe[0]); unused NativeClose(pipe[1]); return false
}
unused NativeClose(pipe[1])
defer { unused NativeClose(pipe[0]) }
digits: [12]u8; place: s32 = 11; number := pipe[0]
while true { place -= 1; digits[place] = cast(u8)(48 + number % 10); number /= 10; if number == 0 { break } }
input: [32]u8
if AppendText(input[:], AppendText(input[:], 0, "/dev/fd/"), TextView(digits[place:11])) < 0 { return false }
args: [16]string = .["openssl", "enc", "-d", "-aes-256-cbc", "-md", "sha512", "-a", "-A", "-pbkdf2", "-iter", "100000", "-in", TextUntilNul(input[:]), "-pass", "stdin", "-salt"]
child := Channel.StartChannel(args[:], false)
if child.error != 0 { return false }
defer { unused Channel.CloseChannel(*child, 1000) }
length := cast(s32)TextUntilNul(passphrase[:]).count
passphrase[length] = cast(u8)10
if Channel.ChannelSend(child, passphrase[0:length + 1], 3000) < 0 { return false }
unused NativeShutdown(child.socket.fd, 1)
used: s32
while used < cast(s32)output.count - 1 {
count := Channel.ChannelReceive(child, output[used:cast(s32)output.count - 1], 10000)
if count < 0 { return false }
if count == 0 { break }
used += cast(s32)count
}
if used >= cast(s32)output.count - 1 || !Channel.WaitChannel(*child, 1000) || child.code != 0 { return false }
while used > 0 && output[used - 1] == cast(u8)10 { used -= 1 }
for i: 0..used - 1 { if output[i] == cast(u8)0 { return false } }
output[used] = cast(u8)0
return true
}
// A detached supervisor retains only its own clipboard child. Expiration
// releases that selection; it never clears a replacement owner's clipboard.
CopyPassword :: (value: string, clear_ms: s64) -> bool {
if EnvironmentText("DISPLAY") == "" { return false }
ready: [2]s32
if NativePipe(*ready[0]) != 0 { return false }
pid := NativeFork()
if pid < 0 { unused NativeClose(ready[0]); unused NativeClose(ready[1]); return false }
if pid == 0 {
unused NativeClose(ready[0]); unused NativeSession()
null_path: [16]u8; CopyCString("/dev/null", null_path[:])
null_fd := NativeOpen(*null_path[0], 2)
if null_fd >= 0 {
for i: 0..2 { unused NativeDup(null_fd, cast(s32)i) }
if null_fd > 2 { unused NativeClose(null_fd) }
}
args: [5]string = .["xclip", "-selection", "clipboard", "-in", "-quiet"]
child := Channel.StartChannel(args[:], false)
ok := child.error == 0
if ok {
payload: [36]u8
ok = CopyCString(value, payload[:])
if ok { ok = Channel.ChannelSend(child, payload[0:value.count], 3000) >= 0 }
ClearBytes(payload[:])
unused NativeShutdown(child.socket.fd, 1)
if Channel.WaitChannel(*child, 100) { ok = false }
}
answer: u8 = ifx ok then cast(u8)1 else cast(u8)0
unused NativeWrite(ready[1], *answer, cast(usize)1)
unused NativeClose(ready[1])
if ok {
started := Timer.MonotonicMilliseconds()
while !Channel.WaitChannel(*child, 100) {
if child.error != 0 || (clear_ms > 0 && Timer.MonotonicMilliseconds() - started >= clear_ms) { break }
}
}
unused Channel.CloseChannel(*child, 0)
NativeExit(0)
}
unused NativeClose(ready[1])
answer: u8
ok := NativeRead(ready[0], *answer, cast(usize)1) == cast(isize)1 && answer == cast(u8)1
unused NativeClose(ready[0])
if !ok { status: s32; unused NativeWait(pid, *status, 0) }
return ok
}
+106
View File
@@ -0,0 +1,106 @@
Json :: #import "std/json_scan";
#import "pass_core"
#import "pass_text"
#import "cli_native"
#import "std/text_buffer"
LegacyProfile :: struct {
found: bool
valid: bool
login: [1024]u8
vault: [4096]u8
exclude: [1024]u8
copy: bool
clear_ms: s64
}
profile_document: [65536]u8;
ProfileString :: (document: string, object: s32, name: string, output: []u8) -> bool {
at := Json.FieldAt(document, object, name)
if at < 0 || Json.MatchLiteral(document, at, "null") { return true }
return Json.ReadStringText(document, at, output) >= 0
}
ProfileBool :: (document: string, object: s32, name: string, value: *bool) -> bool {
at := Json.FieldAt(document, object, name)
if at < 0 || Json.MatchLiteral(document, at, "null") { return true }
if Json.MatchLiteral(document, at, "true") { <<value = true; return true }
if Json.MatchLiteral(document, at, "false") { <<value = false; return true }
return false
}
// The original CLI accepted Go-style durations; keep seconds, minutes, hours
// and fractional/composite values without placing any secrets in a command.
DurationMilliseconds :: (value: string) -> s64 {
if value == "0" { return 0 }
at: s32; total: float64
while at < cast(s32)value.count {
number := Json.ReadNumber(value, at)
if !number.valid || number.value < 0 { return -1 }
at = number.after
scale: float64
if at + 2 <= cast(s32)value.count && value[at:at + 2] == "ms" { scale = 1; at += 2 }
else if at < cast(s32)value.count && value[at] == cast(u8)115 { scale = 1000; at += 1 }
else if at < cast(s32)value.count && value[at] == cast(u8)109 { scale = 60000; at += 1 }
else if at < cast(s32)value.count && value[at] == cast(u8)104 { scale = 3600000; at += 1 }
else { return -1 }
total += number.value * scale
if total > 2147483647 { return -1 }
}
if at == 0 { return -1 }
return cast(s64)total
}
ProfileDefaults :: (document: string, object: s32, result: *LegacyProfile) -> bool {
if !ProfileString(document, object, "vault", result.vault[:]) ||
!ProfileBool(document, object, "copy", *result.copy) { return false }
duration: [128]u8
if !ProfileString(document, object, "clear_after", duration[:]) { return false }
if duration[0] != cast(u8)0 {
result.clear_ms = DurationMilliseconds(TextUntilNul(duration[:]))
if result.clear_ms < 0 { return false }
}
return true
}
LoadLegacyProfile :: (name: string, required: bool, options: *PassOptions,
explicit: u32) -> LegacyProfile {
result: LegacyProfile
loaded := ReadProfileDocument(profile_document[:])
if loaded < 0 { return result }
if loaded == 0 { result.valid = !required; return result }
document := TextUntilNul(profile_document[:])
start := Json.Space(document, 0)
end := Json.ValueEnd(document, start, 0)
if start >= cast(s32)document.count || document[start] != cast(u8)123 ||
end < 0 || Json.Space(document, end) != cast(s32)document.count { return result }
if !ProfileDefaults(document, start, *result) { return result }
profiles := Json.FieldAt(document, start, "profiles")
profile := Json.FieldAt(document, profiles, name)
if name == "" || profile < 0 { result.valid = !required; return result }
if document[profile] != cast(u8)123 ||
!ProfileString(document, profile, "login", result.login[:]) ||
result.login[0] == cast(u8)0 || !ProfileDefaults(document, profile, *result) { return result }
names: [2]string = .["length", "counter"]
for i: 0..1 {
at := Json.FieldAt(document, profile, names[i])
if at >= 0 && !Json.MatchLiteral(document, at, "null") {
after := Json.ValueEnd(document, at, 0)
number := ParseNumber(document[at:after])
if !number.valid || number.value < 0 { return result }
if i == 0 && number.value > 2147483647 { return result }
if number.value > 0 && (explicit & (cast(u32)1 << i)) == cast(u32)0 {
if i == 0 { options.length = cast(s32)number.value }
else { options.counter = cast(u64)number.value }
}
}
}
if (explicit & cast(u32)4) == cast(u32)0 && !ProfileBool(document, profile, "lowercase", *options.lowercase) { return result }
if (explicit & cast(u32)8) == cast(u32)0 && !ProfileBool(document, profile, "uppercase", *options.uppercase) { return result }
if (explicit & cast(u32)16) == cast(u32)0 && !ProfileBool(document, profile, "digits", *options.digits) { return result }
if (explicit & cast(u32)32) == cast(u32)0 && !ProfileBool(document, profile, "symbols", *options.symbols) { return result }
if !ProfileString(document, profile, "exclude", result.exclude[:]) { return result }
result.found = true; result.valid = true
return result
}
+483
View File
@@ -0,0 +1,483 @@
Spinbox :: #import "kryon/spinbox";
Checkbox :: #import "kryon/checkbox";
TextField :: #import "kryon/text_field";
Scroll :: #import "kryon/scroll";
Image :: #import "kryon/image";
Box :: #import "kryon/box";
Text :: #import "kryon/text";
Button :: #import "kryon/button";
// Pass: a stateless password generator. The same site, login, master
// password and settings always give the same password, with no database.
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/control_props"
#import "kryon/tree"
#import "std/text_buffer"
#import "std/utf8"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "pass_core"
#import "pass_state"
#import "pass_text"
Icon :: #import "mingcute/mingcute_regular_keyhole";
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
initialized: bool;
view: s32;
focused: s32;
fields: [5]FieldState;
site: [256]u8;
login: [256]u8;
master: [1024]u8;
profile_name: [64]u8;
reveal: bool;
scroll_offsets: [3]s32;
emoji: [32]u8;
session: Session;
Label :: (value: string, x: float32, y: float32, width: float32, font: s32) {
props: Text.Props
props.bounds = Rectangle.{x, y, width, cast(float32)(font + 8)}
props.text = value
props.size = font
Text.Draw(session, props)
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool, disabled: bool) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.disabled = disabled
props.tone = ButtonTone.ButtonToneNeutral
props.emphasis = ButtonEmphasis.ButtonEmphasisSoft
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button.Draw(session, props) == 1
}
ApplyEdit :: (buffer: []u8, edit: TextField.Edit) -> bool {
if !edit.changed {
return false
}
length: s32 = 0
while length < cast(s32)buffer.count && buffer[length] != cast(u8)0 {
length += 1
}
if edit.start < 0 || edit.end < edit.start || edit.end > length {
return false
}
replacement: [1024]u8
used := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
if used >= cast(s32)buffer.count || used >= 1024 {
return false
}
position: s32 = 0
while position < edit.start {
replacement[position] = buffer[position]
position += 1
}
index: s32 = 0
while index < cast(s32)edit.replacement.count {
replacement[position] = edit.replacement[index]
position += 1
index += 1
}
index = edit.end
while index < length {
replacement[position] = buffer[index]
position += 1
index += 1
}
index = 0
while index < cast(s32)buffer.count {
buffer[index] = ifx index < used then replacement[index] else cast(u8)0
index += 1
}
for wipe: 0..1023 {
replacement[wipe] = cast(u8)0
}
return true
}
Field :: (index: s32, label: string, buffer: []u8, bounds: Rectangle, secure: bool) {
snapshot: [1024]u8
mask: [1024]u8
// The views of the copies end with this block, before they are wiped.
{
props: TextField.Props
position: s32 = 0
while position < cast(s32)buffer.count && position < 1023 {
snapshot[position] = buffer[position]
if buffer[position] == cast(u8)0 {
break
}
position += 1
}
props.key = cast(u64)(100 + index)
props.focus_id = 100 + index
props.bounds = bounds
props.label = label
props.value = TextUntilNul(snapshot[:])
props.cursor = fields[index].cursor
props.anchor = fields[index].anchor
props.scroll_x = fields[index].scroll_x
props.focused = focused == index + 1
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
props.secure = secure
if secure {
count := Codepoints(props.value)
if count > 1023 {
count = 1023
}
masked: s32 = 0
while masked < count {
mask[masked] = cast(u8)42
masked += 1
}
props.display_value = TextView(mask[0:count])
}
if props.focused {
props.input = AppFieldInput()
}
result := TextField.Draw(session, props)
fields[index].cursor = result.cursor
fields[index].anchor = result.anchor
fields[index].scroll_x = result.scroll_x
unused ApplyEdit(buffer, result.edit)
if result.focused {
focused = index + 1
}
if result.escaped && focused == index + 1 {
focused = 0
}
}
for wipe: 0..1023 {
snapshot[wipe] = cast(u8)0
mask[wipe] = cast(u8)0
}
}
// The number of characters in UTF-8 text.
Codepoints :: (text: string) -> s32 {
count: s32 = 0
index: s64 = 0
while index < text.count {
if (text[index] & cast(u8)0xC0) != cast(u8)0x80 {
count += 1
}
index += 1
}
return count
}
Check :: (id: s32, label: string, value: bool, bounds: Rectangle) -> bool {
props: Checkbox.Props
props.key = cast(u64)id
props.id = id
props.label = label
props.bounds = bounds
props.checked = value
return Checkbox.Draw(session, props).checked
}
Integer :: (id: s32, label: string, value: s32, low: s32, high: s32, x: float32, y: float32, width: float32) -> s32 {
Label(label, x, y + 8.0, width - 160.0, 16)
props: Spinbox.Props
props.key = cast(u64)id
props.id = id
props.label = label
props.bounds = Rectangle.{x + width - 150.0, y, 150.0, 38.0}
props.value = value
props.min = low
props.max = high
props.step = 1
return Spinbox.Draw(session, props).value
}
CurrentOptions :: () -> PassOptions {
options: PassOptions
options.length = runtime.settings.length
options.counter = cast(u64)runtime.settings.counter
options.lowercase = runtime.settings.lower
options.uppercase = runtime.settings.upper
options.digits = runtime.settings.digits
options.symbols = runtime.settings.symbols
options.exclude = TextUntilNul(runtime.settings.exclude[:])
return options
}
CurrentProfile :: () -> Profile {
profile: Profile
profile.name = profile_name
profile.site = site
profile.login = login
profile.exclude = runtime.settings.exclude
profile.length = runtime.settings.length
profile.counter = runtime.settings.counter
profile.lower = runtime.settings.lower
profile.upper = runtime.settings.upper
profile.digits = runtime.settings.digits
profile.symbols = runtime.settings.symbols
return profile
}
// The four fingerprint emoji that let you notice a mistyped master password.
Fingerprint :: (x: float32, y: float32) {
used := MasterEmoji(TextUntilNul(master[:]), emoji[:])
atlas := AppAssetPath("fingerprint.png")
position: s32 = 0
for index: 0..3 {
decoded := Decode(TextView(emoji[0:used]), position)
glyph: s32 = 0
while glyph < 63 && cast(u32)master_emoji_codepoints[glyph] != decoded.value {
glyph += 1
}
props: Image.Props
props.asset_path = atlas
props.alt_text = TextView(emoji[position:decoded.after])
props.bounds = Rectangle.{x + cast(float32)index * 28.0, y, 24.0, 24.0}
props.source = Rectangle.{cast(float32)(glyph % 8) * 64.0, cast(float32)(glyph / 8) * 64.0, 64.0, 64.0}
props.tint = ifx AppDark() then cast(u32)0xe8e8e8ff else cast(u32)0x202c29ff
Image.Draw(session, props)
position = decoded.after
}
}
MasterField :: (x: float32, y: float32, width: float32) -> float32 {
Label("Master password", x, y, width, 14)
Field(2, "Master password", master[:], Rectangle.{x, y + 24.0, width - 86.0, 40.0}, !reveal)
if Action(13, ifx reveal then "Hide" else "Show", Rectangle.{x + width - 78.0, y + 24.0, 78.0, 40.0}, false, false) {
reveal = !reveal
}
y += 76.0
if runtime.settings.show_fingerprint && master[0] != cast(u8)0 {
Fingerprint(x, y)
y += 34.0
}
if HasSavedMaster() {
if Action(14, "Unlock master password", Rectangle.{x, y, width, 38.0}, false, false) {
focused = 0
unused UnlockMaster()
}
y += 48.0
}
return y
}
OptionsForm :: (x: float32, y: float32, width: float32) -> float32 {
runtime.settings.length = Integer(20, "Length", runtime.settings.length, 5, 35, x, y, width)
y += 50.0
runtime.settings.counter = Integer(21, "Counter", runtime.settings.counter, 1, 999999, x, y, width)
y += 50.0
part := width / 4.0
runtime.settings.lower = Check(31, "a-z", runtime.settings.lower, Rectangle.{x, y, part, 36.0})
runtime.settings.upper = Check(32, "A-Z", runtime.settings.upper, Rectangle.{x + part, y, part, 36.0})
runtime.settings.digits = Check(33, "0-9", runtime.settings.digits, Rectangle.{x + part * 2.0, y, part, 36.0})
runtime.settings.symbols = Check(34, "#", runtime.settings.symbols, Rectangle.{x + part * 3.0, y, part, 36.0})
y += 48.0
Label("Exclude", x, y, width, 14)
Field(3, "Exclude", runtime.settings.exclude[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
return y + 76.0
}
GenerateForm :: (x: float32, y: float32, width: float32) {
Label("Site", x, y, width, 14)
Field(0, "Site", site[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
Label("Login", x, y, width, 14)
Field(1, "Login", login[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
y = MasterField(x, y, width)
y = OptionsForm(x, y, width)
if Action(40, "Generate", Rectangle.{x, y, width, 44.0}, true, false) {
focused = 0
unused Generate(TextUntilNul(site[:]), TextUntilNul(login[:]), TextUntilNul(master[:]), CurrentOptions())
scroll_offsets[0] = 10000
}
y += 60.0
Label("Generated password", x, y, width, 14)
y += 28.0
props: Box.Props
props.key = cast(u64)42
props.bounds = Rectangle.{x, y, width, 54.0}
props.radius = 8.0
Box.Draw(session, props)
Label(ifx Generated() == "" then "Password will appear here" else Generated(), x + 10.0, y + 16.0, width - 20.0, 16)
y += 68.0
if Action(41, "Copy", Rectangle.{x, y, width, 40.0}, false, false) {
unused CopyPassword()
}
}
ProfilesForm :: (x: float32, y: float32, width: float32) {
Label("Profile name", x, y, width, 14)
Field(4, "Profile name", profile_name[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
if Action(210, "Save Current Profile", Rectangle.{x, y, width, 42.0}, true, false) {
unused SaveProfile(CurrentProfile())
}
y += 60.0
if runtime.profile_count == 0 {
Label("No saved profiles", x, y, width, 16)
}
index: s32 = 0
while index < runtime.profile_count {
Label(TextUntilNul(runtime.profiles[index].name[:]), x, y, width, 16)
Label(TextUntilNul(runtime.profiles[index].site[:]), x, y + 26.0, width, 12)
if Action(300 + index, "Generate", Rectangle.{x, y + 50.0, width * 0.6 - 4.0, 36.0}, false, false) {
unused GenerateProfile(index, TextUntilNul(master[:]))
view = 0
focused = 0
scroll_offsets[0] = 10000
}
if Action(400 + index, "Delete", Rectangle.{x + width * 0.6 + 4.0, y + 50.0, width * 0.4 - 4.0, 36.0}, false, false) {
unused DeleteProfile(index)
break
}
y += 102.0
index += 1
}
}
SettingsForm :: (x: float32, y: float32, width: float32) {
runtime.settings.auto_copy = Check(501, "Auto-copy after Generate", runtime.settings.auto_copy, Rectangle.{x, y, width, 36.0})
y += 48.0
runtime.settings.clear_seconds = Integer(502, "Clipboard seconds", runtime.settings.clear_seconds, 0, 3600, x, y, width)
y += 50.0
runtime.settings.show_fingerprint = Check(503, "Show master fingerprint", runtime.settings.show_fingerprint, Rectangle.{x, y, width, 36.0})
y += 54.0
Label("Generation defaults", x, y, width, 20)
y += 38.0
y = OptionsForm(x, y, width)
if Action(510, "Save Settings", Rectangle.{x, y, width, 42.0}, true, false) {
unused SaveSettings()
}
y += 60.0
Label("Secure master password", x, y, width, 20)
y += 38.0
y = MasterField(x, y, width)
Label(FingerprintStatus(), x, y, width, 12)
y += 36.0
if Action(520, "Save", Rectangle.{x, y, width / 2.0 - 4.0, 42.0}, true, !CanSaveMaster()) {
focused = 0
unused SaveMaster(TextUntilNul(master[:]))
}
if Action(522, "Forget", Rectangle.{x + width / 2.0 + 4.0, y, width / 2.0 - 4.0, 42.0}, false, !HasSavedMaster()) {
unused ForgetMaster()
}
}
// Tab moves between the fields of the current view.
FocusNext :: () {
if AppKey() != 258 {
return
}
if view == 0 {
if (AppModifiers() & 1) != 0 {
focused = ((focused + 2) % 4) + 1
} else {
focused = (focused % 4) + 1
}
}
if view == 1 {
focused = 5
}
if view == 2 {
focused = 3
}
}
Draw :: () {
session = AppSession()
area := AppBounds()
if runtime.has_unlocked_master {
master = runtime.unlocked_master
runtime.unlocked_master = .{}
runtime.has_unlocked_master = false
fields[2] = FieldState.{}
}
FocusNext()
pad: float32 = 18.0
width := area.width - pad * 2.0
if width > 480.0 {
width = 480.0
}
left := area.x + (area.width - width) * 0.5
height := area.height - 110.0
if height < 60.0 {
height = 60.0
}
content_height: s32 = 648
if runtime.settings.show_fingerprint && master[0] != cast(u8)0 {
content_height += 34
}
if HasSavedMaster() {
content_height += 48
}
if view == 1 {
content_height = 180 + runtime.profile_count * 102
}
if view == 2 {
content_height = 760
}
props: Scroll.Props
props.key = cast(u64)(10 + view)
props.bounds = Rectangle.{left, area.y + 12.0, width, height}
props.content_height = content_height
props.scroll_offset = scroll_offsets[view]
props.scale = 1.0
scroll := Scroll.Draw(session, props)
scroll_offsets[view] = scroll.scroll_offset
if scroll.opened {
if view == 0 {
GenerateForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
if view == 1 {
ProfilesForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
if view == 2 {
SettingsForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
End(session)
}
Label(Status(), left, area.y + area.height - 88.0, width, 12)
labels: [3]string = .{"Generate", "Profiles", "Settings"}
for index: 0..2 {
tab := cast(s32)index
bounds := Rectangle.{left + cast(float32)index * width / 3.0, area.y + area.height - 58.0, width / 3.0 - 4.0, 46.0}
if Action(700 + tab, labels[index], bounds, view == tab, false) {
view = tab
focused = 0
}
}
AppKeyboard(focused != 0)
}
#program_export "PassMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("pass")
AppDescribe("Pass", Icon.Shape)
return APP_PROTOCOL
}
if AppMode() != APP_FRAME {
return 0
}
if !initialized {
Initialize()
initialized = true
}
Tick()
Draw()
return 0
}
+334
View File
@@ -0,0 +1,334 @@
#import "crypto/sha256"
#if #defined(WERK_APP) {
#import "kryon/app_context"
}
PassOptions :: struct {
length: s32
counter: u64
lowercase: bool
uppercase: bool
digits: bool
symbols: bool
exclude: string
}
PassClass :: struct {
bytes: [32]u8
count: s32
}
PassResult :: struct {
valid: bool
password: [36]u8
length: s32
error: string
}
EntropyState :: struct {
bytes: [32]u8
}
EntropyResult :: struct {
entropy: EntropyState
value: s32
}
master_emoji_codepoints: [64]s32 = .[
0x1F436, 0x1F431, 0x1F42D, 0x1F439, 0x1F430, 0x1F98A, 0x1F43B, 0x1F43C,
0x1F428, 0x1F42F, 0x1F981, 0x1F42E, 0x1F437, 0x1F438, 0x1F435, 0x1F414,
0x1F427, 0x1F989, 0x1F43A, 0x1F434, 0x1F984, 0x1F41D, 0x1F98B, 0x1F422,
0x1F34E, 0x1F34A, 0x1F34B, 0x1F349, 0x1F347, 0x1F353, 0x1F352, 0x1F351,
0x1F951, 0x1F33D, 0x1F355, 0x1F354, 0x1F35F, 0x1F369, 0x1F335, 0x1F332,
0x1F333, 0x1F334, 0x1F331, 0x1F33B, 0x1F338, 0x1F308, 0x2B50, 0x1F319,
0x1F525, 0x1F4A7, 0x26C4, 0x1F389, 0x1F3B8, 0x1F3AF, 0x1F3B2, 0x1F381,
0x1F680, 0x1F697, 0x2693, 0x1F3A8, 0x1F511, 0x1F4A1, 0x1F4DA, 0x1F3A7
];
// Whether the last DeriveKey failed; only the Werkzeug host can refuse.
derive_failed: bool;
DeriveKey :: (password: string, salt: string) -> [32]u8 {
derive_failed = false
// Inside Werkzeug the host derives the key natively; the portable
// interpreter would take minutes for 100,000 rounds.
#if #defined(WERK_APP) {
output: [32]u8
derive_failed = !AppPbkdf2Sha256(password, salt, 100000, output[:])
return output
} else {
return Pbkdf2Sha256(password, ifx salt.count > PASS_SALT_LIMIT then salt[0:PASS_SALT_LIMIT] else salt, 100000)
}
}
// Werkzeug's key derivation has always read at most this many salt bytes,
// and existing vault keys depend on it; the host derives the same way.
PASS_SALT_LIMIT :: 508
PassClassEmptyError :: (class_index: s32) -> string {
if class_index == 0 {
return "enabled lowercase character class is empty after exclusions"
}
if class_index == 1 {
return "enabled uppercase character class is empty after exclusions"
}
if class_index == 2 {
return "enabled digits character class is empty after exclusions"
}
return "enabled symbols character class is empty after exclusions"
}
PassFailure :: (message: string) -> PassResult {
result: PassResult
result.error = message
return result
}
PassFilterClass :: (characters: string, options: PassOptions) -> PassClass {
result: PassClass
character_index: s32 = 0
while character_index < cast(s32)characters.count {
excluded := false
exclude_index: s32 = 0
while exclude_index < cast(s32)options.exclude.count {
if options.exclude[exclude_index] == characters[character_index] {
excluded = true
break
}
exclude_index += 1
}
if !excluded && result.count < cast(s32)result.bytes.count {
result.bytes[result.count] = characters[character_index]
result.count += 1
}
character_index += 1
}
return result
}
PassAppendCounter :: (salt: []u8, offset: s32, counter: u64) -> s32 {
digits: [16]u8
digit_count: s32 = 0
value := counter
while value > cast(u64)0 {
nibble: u64 = value % cast(u64)16
if nibble < cast(u64)10 {
digits[digit_count] = cast(u8)(nibble + cast(u64)48)
} else {
digits[digit_count] = cast(u8)(nibble + cast(u64)87)
}
digit_count += 1
value /= cast(u64)16
}
if digit_count == 0 {
salt[offset] = cast(u8)48
return offset + 1
}
digit_index: s32 = digit_count - 1
while digit_index >= 0 {
salt[offset + (digit_count - digit_index - 1)] = digits[digit_index]
digit_index -= 1
}
return offset + digit_count
}
EntropyTake :: (entropy: EntropyState, divisor: s32) -> EntropyResult {
carry: u32 = 0
index: s32 = 0
while index < 32 {
current: u32 = carry * cast(u32)256 +
cast(u32)entropy.bytes[index]
entropy.bytes[index] = cast(u8)(current / cast(u32)divisor)
carry = current % cast(u32)divisor
index += 1
}
return EntropyResult.{entropy, cast(s32)carry}
}
PassGenerate :: (site: string, login: string, master: string,
options: PassOptions) -> PassResult {
if options.length < 5 || options.length > 35 {
return PassFailure(
"password length must be between 5 and 35")
}
class_sets: [4]string = .[
"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
]
class_names: [4]string = .[
"lowercase", "uppercase", "digits", "symbols"
]
class_enabled: [4]bool = .[
options.lowercase, options.uppercase,
options.digits, options.symbols
]
classes: [4]PassClass
class_count: s32 = 0
alphabet: [128]u8
alphabet_count: s32 = 0
class_index: s32 = 0
while class_index < 4 {
if class_enabled[class_index] {
classes[class_count] = PassFilterClass(
class_sets[class_index], options)
if classes[class_count].count == 0 {
return PassFailure(PassClassEmptyError(class_index))
}
copy_index: s32 = 0
while copy_index < classes[class_count].count {
alphabet[alphabet_count] =
classes[class_count].bytes[copy_index]
alphabet_count += 1
copy_index += 1
}
class_count += 1
}
class_index += 1
}
if class_count == 0 {
return PassFailure("at least one character class must be enabled")
}
if options.length < class_count {
return PassFailure(
"password length is smaller than the enabled character classes")
}
if options.length == class_count {
return PassFailure(
"password length must leave room for generated characters")
}
salt: [640]u8
salt_length: s32 = 0
if cast(s32)site.count >= cast(s32)salt.count {
return PassFailure("site name is too long")
}
site_index: s32 = 0
while site_index < cast(s32)site.count {
salt[salt_length] = site[site_index]
salt_length += 1
site_index += 1
}
if cast(s64)salt_length + login.count + 16 > salt.count {
return PassFailure("login is too long")
}
login_index: s32 = 0
while login_index < cast(s32)login.count {
salt[salt_length] = login[login_index]
salt_length += 1
login_index += 1
}
salt_length = PassAppendCounter(salt[:], salt_length, options.counter)
entropy: EntropyState
entropy.bytes = DeriveKey(master, TextView(salt[0:salt_length]))
if derive_failed { return PassFailure("Could not derive the password") }
password_length := options.length - class_count
password: [36]u8
generated_index: s32 = 0
while generated_index < password_length {
taken := EntropyTake(entropy, alphabet_count)
entropy = taken.entropy
password[generated_index] = alphabet[taken.value]
generated_index += 1
}
required: [4]u8
required_index: s32 = 0
while required_index < class_count {
taken := EntropyTake(entropy, classes[required_index].count)
entropy = taken.entropy
required[required_index] = classes[required_index].bytes[taken.value]
required_index += 1
}
insertion_index: s32 = 0
while insertion_index < class_count {
taken := EntropyTake(entropy, password_length)
entropy = taken.entropy
position := taken.value
move_index := password_length
while move_index > position {
password[move_index] = password[move_index - 1]
move_index -= 1
}
password[position] = required[insertion_index]
password_length += 1
insertion_index += 1
}
result: PassResult
result.valid = true
result.length = password_length
result_index: s32 = 0
while result_index < password_length {
result.password[result_index] = password[result_index]
result_index += 1
}
return result
}
MasterEmojiAppendUtf8 :: (output: []u8, used: s32, codepoint: u32) -> s32 {
if used < 0 || used >= cast(s32)output.count { return used }
length: s32 = 0
if codepoint <= cast(u32)0x7f {
length = 1
} else if codepoint <= cast(u32)0x7ff {
length = 2
} else if codepoint <= cast(u32)0xffff {
length = 3
} else if codepoint <= cast(u32)0x10ffff {
length = 4
} else {
output[used] = cast(u8)0
return used
}
if used + length >= cast(s32)output.count {
output[used] = cast(u8)0
return used
}
if length == 1 {
output[used] = cast(u8)codepoint
} else if length == 2 {
output[used] = cast(u8)(cast(u32)0xc0 | (codepoint >> cast(u32)6))
output[used + 1] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
} else if length == 3 {
output[used] = cast(u8)(cast(u32)0xe0 | (codepoint >> cast(u32)12))
output[used + 1] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)6) & cast(u32)0x3f))
output[used + 2] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
} else {
output[used] = cast(u8)(cast(u32)0xf0 | (codepoint >> cast(u32)18))
output[used + 1] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)12) & cast(u32)0x3f))
output[used + 2] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)6) & cast(u32)0x3f))
output[used + 3] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
}
used += length
output[used] = cast(u8)0
return used
}
MasterEmoji :: (master: string, output: []u8) -> s32 {
if output.count <= 0 { return 0 }
output[0] = cast(u8)0
digest := Sha256Of(master)
used: s32 = 0
for index: 0..3 {
codepoint: u32 = cast(u32)master_emoji_codepoints[
cast(s32)digest[index] & 63]
used = MasterEmojiAppendUtf8(output, used, codepoint)
}
return used
}
+160
View File
@@ -0,0 +1,160 @@
#import "pass_core"
#import "crypto/sha256"
#program_export
DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
for index: 0..31 {
if left[index] != right[index] { return false }
}
return true
}
#program_export
Answer :: () -> s32 {
empty := Sha256Of("")
abc := Sha256Of("abc")
derived := DeriveKey("password", "salt")
if empty[0] != cast(u8)0xe3 || empty[31] != cast(u8)0x55 { return 1 }
if abc[0] != cast(u8)0xba || abc[31] != cast(u8)0xad { return 2 }
expected: [32]u8 = .[
0x03, 0x94, 0xa2, 0xed, 0xe3, 0x32, 0xc9, 0xa1,
0x3e, 0xb8, 0x2e, 0x9b, 0x24, 0x63, 0x16, 0x04,
0xc3, 0x1d, 0xf9, 0x78, 0xb4, 0xe2, 0xf0, 0xfb,
0xd2, 0xc5, 0x49, 0x94, 0x4f, 0x9d, 0x79, 0xa5
]
if !DigestMatches(derived, expected) { return 3 }
long_password: [80]u8
for index: 0..79 { long_password[index] = cast(u8)97 }
long_derived := DeriveKey(TextView(long_password[0:80]), "salt")
long_password_expected: [32]u8 = .[
0x2f, 0xf0, 0x41, 0xc8, 0x08, 0x5d, 0xbc, 0xe4,
0x6f, 0x9d, 0xc5, 0xa4, 0xe8, 0xb9, 0xe5, 0xeb,
0x1d, 0x17, 0x27, 0x31, 0x8c, 0x54, 0x0f, 0x66,
0x97, 0xb5, 0xb0, 0xa3, 0x68, 0xe1, 0x58, 0xad
]
if !DigestMatches(long_derived, long_password_expected) { return 4 }
long_salt: [700]u8
for index: 0..699 { long_salt[index] = cast(u8)98 }
truncated_salt := DeriveKey("password", TextView(long_salt[0:700]))
truncated_salt_expected: [32]u8 = .[
0x3a, 0x4d, 0x1a, 0xf4, 0xf5, 0x39, 0x07, 0x0e,
0x6f, 0xb4, 0xb2, 0xa0, 0x70, 0x90, 0x71, 0xd0,
0x3e, 0x01, 0xc7, 0xfb, 0x6c, 0x26, 0x59, 0xf6,
0xa8, 0x48, 0x11, 0xea, 0xe8, 0x50, 0x15, 0x0b
]
if !DigestMatches(truncated_salt, truncated_salt_expected) { return 5 }
defaults := DefaultPassOptions()
generated := PassGenerate(
"example.com", "alice", "correct horse battery staple", defaults)
if !PassTextMatches(generated, "&Lf4'/-cSk4DPv_8") { return 6 }
excluded := defaults
excluded.length = 24
excluded.exclude = "0Ool1I!|"
generated = PassGenerate(
"example.com", "alice", "correct horse battery staple", excluded)
if !PassTextMatches(
generated, "7,.Cp}YnF'eeHHaqbX7#PQhg") { return 7 }
subset: PassOptions
subset.length = 12
subset.counter = 7
subset.lowercase = true
subset.digits = true
subset.exclude = ""
generated = PassGenerate(
"δοκιμή.example", "ユーザー", "pässword", subset)
if !PassTextMatches(generated, "oih5omhygh2v") { return 8 }
empty_subset: PassOptions
empty_subset.length = 5
empty_subset.uppercase = true
empty_subset.digits = true
generated = PassGenerate("x", "y", "", empty_subset)
if !PassTextMatches(generated, "C9O9I") { return 9 }
lesspass := PassGenerate(
"lesspass.com", "[email protected]", "password", defaults)
if !PassTextMatches(lesspass, "\\g-A1-.OHEwrXjT#") { return 10 }
counters := defaults
counters.counter = 10
generated = PassGenerate("site", "login", "test", counters)
if !PassTextMatches(generated, "XFt0F*,r619:+}[.") { return 11 }
counters.counter = 16
generated = PassGenerate("site", "login", "test", counters)
if !PassTextMatches(generated, "l:`nzj>S7+0#uL_d") { return 12 }
empty_inputs := PassGenerate("", "", "", defaults)
if !PassTextMatches(empty_inputs, "bb8^CBroRNj%4sP_") { return 13 }
invalid := defaults
invalid.digits = true
invalid.exclude = "0123456789"
if PassGenerate("", "", "", invalid).valid { return 14 }
emoji: [64]u8
emoji_length := MasterEmoji(
"correct horse battery staple", emoji[:])
if !TextMatches(TextView(emoji[0:emoji_length]),
"🐰🎨🐮🍑") { return 15 }
empty_emoji: [64]u8
empty_emoji_length := MasterEmoji("", empty_emoji[:])
if empty_emoji_length != 16 ||
!TextMatches(TextView(empty_emoji[0:empty_emoji_length]),
"🍔🔥🐰🐭") { return 16 }
tiny_emoji: [2]u8
tiny_emoji[0] = cast(u8)120
tiny_emoji_length := MasterEmoji(
"correct horse battery staple", tiny_emoji[:])
if tiny_emoji_length != 0 || tiny_emoji[0] != cast(u8)0 {
return 17
}
return 42
}
#program_export
PortableAnswer :: () -> s32 {
digest := HmacSha256Of("password", "salt")
if digest[0] != cast(u8)0xfc || digest[31] != cast(u8)0xd0 {
return 1
}
return 42
}
TextMatches :: (actual: string, expected: string) -> bool {
if actual.count != expected.count { return false }
index: s32 = 0
while index < cast(s32)actual.count {
if actual[index] != expected[index] { return false }
index += 1
}
return true
}
PassTextMatches :: (result: PassResult, expected: string) -> bool {
if !result.valid || result.length != cast(s32)expected.count {
return false
}
index: s32 = 0
while index < result.length {
if result.password[index] != expected[index] { return false }
index += 1
}
return true
}
DefaultPassOptions :: () -> PassOptions {
options: PassOptions
options.length = 16
options.counter = 1
options.lowercase = true
options.uppercase = true
options.digits = true
options.symbols = true
options.exclude = ""
return options
}
+345
View File
@@ -0,0 +1,345 @@
// Pass's settings, saved profiles and generation. Everything is computed on
// the device; the master password is never written unless the device keeps
// it behind its own authentication.
#import "pass_core"
#import "pass_text"
#import "text_buffer"
#import "number_text"
#import "kryon/app_context"
Profile :: struct {
name: [64]u8
site: [256]u8
login: [256]u8
exclude: [128]u8
length: s32
counter: s32
lower: bool
upper: bool
digits: bool
symbols: bool
}
Settings :: struct {
auto_copy: bool
clear_seconds: s32
show_fingerprint: bool
length: s32
counter: s32
lower: bool
upper: bool
digits: bool
symbols: bool
exclude: [128]u8
}
Runtime :: struct {
settings: Settings
profiles: [64]Profile
profile_count: s32
generated: [36]u8
status: [256]u8
unlocked_master: [1024]u8
has_unlocked_master: bool
secure_action: s32
}
runtime: Runtime;
store_buffer: [65536]u8;
SetStatus :: (value: string) { CopyText(value, runtime.status[:]) }
Status :: () -> string { return TextUntilNul(runtime.status[:]) }
Generated :: () -> string { return TextUntilNul(runtime.generated[:]) }
Clamp :: (value: s32, low: s32, high: s32) -> s32 {
if value < low { return low }
if value > high { return high }
return value
}
DefaultSettings :: () -> Settings {
settings: Settings
settings.length = 16; settings.counter = 1; settings.clear_seconds = 20
settings.show_fingerprint = true
settings.lower = true; settings.upper = true
settings.digits = true; settings.symbols = true
return settings
}
StoreName :: (key: string, output: []u8) -> string {
used := AppendText(output, 0, ".kryon_pass_")
used = AppendText(output, used, key)
used = AppendText(output, used, ".txt")
if used < 0 { return "" }
return TextUntilNul(output)
}
ReadSetting :: (key: string, output: []u8) -> bool {
name: [256]u8
return ReadStore(StoreName(key, name[:]), output) >= 0
}
WriteSetting :: (key: string, value: string) -> bool {
name: [256]u8
return WriteStore(StoreName(key, name[:]), value)
}
ReadInteger :: (key: string, fallback: s32) -> s32 {
buffer: [64]u8
if !ReadSetting(key, buffer[:]) { return fallback }
number := ParseNumber(TextUntilNul(buffer[:]))
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { return fallback }
return cast(s32)number.value
}
WriteInteger :: (key: string, value: s32) -> bool {
buffer: [32]u8
return WriteSetting(key, FormatInteger(cast(s64)value, buffer[:]))
}
ApplySetting :: (key: string, value: string) {
number := ParseNumber(value)
if key == "exclude" { CopyText(value, runtime.settings.exclude[:]); return }
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { return }
integer := cast(s32)number.value
if key == "auto_copy" { runtime.settings.auto_copy = integer != 0 }
if key == "clear_after_seconds" { runtime.settings.clear_seconds = integer }
if key == "show_fingerprint" { runtime.settings.show_fingerprint = integer != 0 }
if key == "length" { runtime.settings.length = integer }
if key == "counter" { runtime.settings.counter = integer }
if key == "lower" { runtime.settings.lower = integer != 0 }
if key == "upper" { runtime.settings.upper = integer != 0 }
if key == "digits" { runtime.settings.digits = integer != 0 }
if key == "symbols" { runtime.settings.symbols = integer != 0 }
}
LoadSettings :: () {
count := ReadStore("settings.cfg", store_buffer[:])
if count > 0 {
text := TextView(store_buffer[0:count])
start: s32 = 0
index: s32 = 0
separator: s32 = -1
while index <= count {
if index == count || text[index] == cast(u8)10 {
end := index
if end > start && text[end - 1] == cast(u8)13 { end -= 1 }
if separator >= start { ApplySetting(text[start:separator], text[separator + 1:end]) }
start = index + 1; separator = -1
} else {
if text[index] == cast(u8)61 && separator < 0 { separator = index }
}
index += 1
}
}
keys: [10]string = .{"auto_copy", "clear_after_seconds", "show_fingerprint", "length", "counter", "lower", "upper", "digits", "symbols", "exclude"}
for index: 0..9 {
buffer: [256]u8
if ReadSetting(keys[index], buffer[:]) { ApplySetting(keys[index], TextUntilNul(buffer[:])) }
}
runtime.settings.length = Clamp(runtime.settings.length, 5, 35)
runtime.settings.counter = Clamp(runtime.settings.counter, 1, 999999)
runtime.settings.clear_seconds = Clamp(runtime.settings.clear_seconds, 0, 3600)
}
SaveSettings :: () -> bool {
settings := runtime.settings
ok := WriteInteger("auto_copy", cast(s32)settings.auto_copy)
ok = WriteInteger("clear_after_seconds", settings.clear_seconds) && ok
ok = WriteInteger("show_fingerprint", cast(s32)settings.show_fingerprint) && ok
ok = WriteInteger("length", settings.length) && ok
ok = WriteInteger("counter", settings.counter) && ok
ok = WriteInteger("lower", cast(s32)settings.lower) && ok
ok = WriteInteger("upper", cast(s32)settings.upper) && ok
ok = WriteInteger("digits", cast(s32)settings.digits) && ok
ok = WriteInteger("symbols", cast(s32)settings.symbols) && ok
ok = WriteSetting("exclude", TextUntilNul(runtime.settings.exclude[:])) && ok
if ok { SetStatus("Settings saved") } else { SetStatus("Could not save settings") }
return ok
}
ProfileOptions :: (profile: Profile) -> PassOptions {
options: PassOptions
options.length = profile.length
options.counter = cast(u64)Clamp(profile.counter, 0, 2147483647)
options.lowercase = profile.lower; options.uppercase = profile.upper
options.digits = profile.digits; options.symbols = profile.symbols
return options
}
Generate :: (site: string, login: string, master: string, options: PassOptions) -> bool {
result := PassGenerate(site, login, master, options)
runtime.generated = result.password
if !result.valid { SetStatus(result.error); return false }
SetStatus("Password generated locally")
if runtime.settings.auto_copy { CopyPassword() }
return true
}
CopyPassword :: () -> bool {
value := Generated()
if value == "" { SetStatus("Generate a password first"); return false }
if !ClipboardCopy(value, runtime.settings.clear_seconds) { SetStatus("Clipboard is unavailable"); return false }
SetStatus("Copied")
return true
}
LoadProfiles :: () {
runtime.profile_count = 0
count := ReadStore("profiles.tsv", store_buffer[:])
if count <= 0 { return }
text := TextView(store_buffer[0:count])
start: s32 = 0
index: s32 = 0
while index <= count && runtime.profile_count < 64 {
if index == count || text[index] == cast(u8)10 {
end := index
if end > start && text[end - 1] == cast(u8)13 { end -= 1 }
line := text[start:end]
fields: [10]string
field: s32 = 0
position: s32 = 0
previous: s32 = 0
while position <= cast(s32)line.count && field < 10 {
if position == cast(s32)line.count || line[position] == cast(u8)9 {
fields[field] = line[previous:position]
field += 1; previous = position + 1
}
position += 1
}
if field >= 9 {
profile: Profile
valid := CopyText(fields[0], profile.name[:]) && CopyText(fields[1], profile.site[:]) && CopyText(fields[2], profile.login[:]) && CopyText(fields[9], profile.exclude[:])
numbers: [6]s32
for number_index: 0..5 {
number := ParseNumber(fields[number_index + 3])
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { valid = false }
numbers[number_index] = cast(s32)number.value
}
profile.length = Clamp(numbers[0], 5, 35); profile.counter = numbers[1]
profile.lower = numbers[2] != 0; profile.upper = numbers[3] != 0
profile.digits = numbers[4] != 0; profile.symbols = numbers[5] != 0
if valid && profile.name[0] != cast(u8)0 {
runtime.profiles[runtime.profile_count] = profile
runtime.profile_count += 1
}
}
start = index + 1
}
index += 1
}
}
WriteProfiles :: () -> bool {
used: s32 = 0
index: s32 = 0
while index < runtime.profile_count {
profile := runtime.profiles[index]
used = AppendText(store_buffer[:], used, TextUntilNul(profile.name[:]))
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.site[:]))
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.login[:]))
values: [6]s32 = .{profile.length, profile.counter, cast(s32)profile.lower, cast(s32)profile.upper, cast(s32)profile.digits, cast(s32)profile.symbols}
for number_index: 0..5 {
buffer: [32]u8
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, FormatInteger(cast(s64)values[number_index], buffer[:]))
}
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.exclude[:]))
used = AppendText(store_buffer[:], used, "\n")
if used < 0 { SetStatus("Could not save profiles"); return false }
index += 1
}
if !WriteStore("profiles.tsv", TextView(store_buffer[0:used])) { SetStatus("Could not save profiles"); return false }
return true
}
SaveProfile :: (profile: Profile) -> bool {
candidate := profile
name := TextUntilNul(candidate.name[:])
if name == "" { SetStatus("Profile name required"); return false }
if !SafeField(name) || !SafeField(TextUntilNul(candidate.site[:])) || !SafeField(TextUntilNul(candidate.login[:])) || !SafeField(TextUntilNul(candidate.exclude[:])) { SetStatus("Profile fields cannot contain tabs or newlines"); return false }
index: s32 = 0
while index < runtime.profile_count {
if TextUntilNul(runtime.profiles[index].name[:]) == name { break }
index += 1
}
if index >= 64 { SetStatus("Profile limit reached"); return false }
original := runtime.profiles[index]
original_count := runtime.profile_count
runtime.profiles[index] = candidate
if index == runtime.profile_count { runtime.profile_count += 1 }
if !WriteProfiles() { runtime.profiles[index] = original; runtime.profile_count = original_count; return false }
SetStatus("Profile saved"); return true
}
DeleteProfile :: (index: s32) -> bool {
if index < 0 || index >= runtime.profile_count { SetStatus("Profile not found"); return false }
original := runtime.profiles
count := runtime.profile_count
position := index
while position + 1 < runtime.profile_count { runtime.profiles[position] = runtime.profiles[position + 1]; position += 1 }
runtime.profile_count -= 1
if !WriteProfiles() { runtime.profiles = original; runtime.profile_count = count; return false }
runtime.profiles[runtime.profile_count] = Profile.{}
SetStatus("Profile deleted"); return true
}
GenerateProfile :: (index: s32, master: string) -> bool {
if index < 0 || index >= runtime.profile_count { SetStatus("Profile not found"); return false }
profile := runtime.profiles[index]
options := ProfileOptions(profile)
options.exclude = TextUntilNul(profile.exclude[:])
return Generate(TextUntilNul(profile.site[:]), TextUntilNul(profile.login[:]), master, options)
}
SaveMaster :: (master: string) -> bool {
if master == "" { SetStatus("Enter master password first"); return false }
if !SecureAvailable() { SetStatus("Device authentication unavailable"); return false }
if !SecureRequest(master, true) { SetStatus("Secure master failed"); return false }
runtime.secure_action = 1; SetStatus("Saving master"); return true
}
UnlockMaster :: () -> bool {
if !SecureSaved() { SetStatus("No saved master password"); return false }
if !SecureRequest("", false) { SetStatus("Secure master failed"); return false }
runtime.secure_action = 2; SetStatus("Unlock requested"); return true
}
ForgetMaster :: () -> bool {
if !SecureForget() { SetStatus("Could not forget saved master"); return false }
runtime.unlocked_master = .{}
runtime.has_unlocked_master = false; runtime.secure_action = 0
SetStatus("Saved master forgotten"); return true
}
FingerprintStatus :: () -> string {
if !SecureAvailable() { return "Device authentication is not available" }
if SecureSaved() { return "Saved master uses device authentication" }
return "No saved master password"
}
HasSavedMaster :: () -> bool { return SecureSaved() }
CanSaveMaster :: () -> bool { return SecureAvailable() }
Tick :: () {
buffer: [1024]u8
result := SecurePoll(buffer[:])
if result == 2 {
if runtime.secure_action == 2 {
runtime.unlocked_master = buffer
runtime.has_unlocked_master = true
SetStatus("Master unlocked")
} else {
SetStatus("Master password saved")
}
runtime.secure_action = 0
}
if result == 3 { SetStatus("Secure master failed or cancelled"); runtime.secure_action = 0 }
for index: 0..1023 { buffer[index] = cast(u8)0 }
}
Initialize :: () {
runtime = Runtime.{}
runtime.settings = DefaultSettings()
SetStatus("Ready")
LoadSettings(); LoadProfiles()
}
Shutdown :: () {
runtime.generated = .{}; runtime.unlocked_master = .{}
runtime.has_unlocked_master = false
}
+57
View File
@@ -0,0 +1,57 @@
#import "c_string"
#import "text_buffer"
ClearBytes :: (bytes: []u8) {
at: s32 = 0
while at < cast(s32)bytes.count { bytes[at] = cast(u8)0; at += 1 }
}
CopyText :: (value: string, output: []u8) -> bool {
if output.count == 0 { return false }
if value.count >= output.count { return false }
return CopyCString(value, output)
}
AppendText :: (output: []u8, used: s32, value: string) -> s32 {
if used < 0 || cast(s64)used + cast(s64)value.count >= cast(s64)output.count { return -1 }
index: s32 = 0
while index < cast(s32)value.count {
output[used + index] = value[index]
index += 1
}
used += cast(s32)value.count
output[used] = cast(u8)0
return used
}
Number :: struct { valid: bool; value: s64; }
ParseNumber :: (text: string) -> Number {
result: Number
if text.count == 0 { return result }
index: s32 = 0
negative: bool = text[0] == cast(u8)45
if negative || text[0] == cast(u8)43 { index = 1 }
if index == cast(s32)text.count { return result }
while index < cast(s32)text.count {
byte: u8 = text[index]
if byte < cast(u8)48 || byte > cast(u8)57 { return result }
digit: s64 = cast(s64)(byte - cast(u8)48)
if result.value > (9223372036854775807 - digit) / 10 { return Number.{} }
result.value = result.value * 10 + digit
index += 1
}
if negative { result.value = 0 - result.value }
result.valid = true
return result
}
SafeField :: (value: string) -> bool {
index: s32 = 0
while index < cast(s32)value.count {
if value[index] == cast(u8)0 || value[index] == cast(u8)9 ||
value[index] == cast(u8)10 || value[index] == cast(u8)13 { return false }
index += 1
}
return true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

File renamed without changes.
Binary file not shown.
+94
View File
@@ -0,0 +1,94 @@
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/)
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 753 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 637 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 675 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 819 KiB

-63
View File
@@ -1,63 +0,0 @@
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
type clipboardCommand struct {
program string
args []string
}
func copyToClipboard(value string, clearAfter time.Duration) error {
// The built-in pure-Go X11 clipboard doubles as the only backend that can
// auto-clear: it owns the selection from a daemon and releases it on time.
if handled, err := copyViaX11(value, clearAfter); handled {
return err
}
if clearAfter > 0 {
fmt.Fprintln(os.Stderr, "warning: --clear-after needs the built-in X11 clipboard; copying without auto-clear")
}
commands := clipboardCommands()
var failures []error
for _, candidate := range commands {
path, err := exec.LookPath(candidate.program)
if err != nil {
continue
}
command := exec.Command(path, candidate.args...)
command.Stdin = strings.NewReader(value)
if output, err := command.CombinedOutput(); err == nil {
return nil
} else if len(output) > 0 {
failures = append(failures, fmt.Errorf("%s: %w: %s", candidate.program, err, output))
} else {
failures = append(failures, fmt.Errorf("%s: %w", candidate.program, err))
}
}
if len(failures) > 0 {
return fmt.Errorf("clipboard command failed: %w", errors.Join(failures...))
}
return errors.New("clipboard unavailable: install wl-copy, xclip, xsel, pbcopy, or clip.exe")
}
func clipboardCommands() []clipboardCommand {
switch runtime.GOOS {
case "darwin":
return []clipboardCommand{{program: "pbcopy"}}
case "windows":
return []clipboardCommand{{program: "clip.exe"}}
default:
return []clipboardCommand{
{program: "wl-copy"},
{program: "xclip", args: []string{"-selection", "clipboard", "-in"}},
{program: "xsel", args: []string{"--clipboard", "--input"}},
}
}
}
-23
View File
@@ -1,23 +0,0 @@
//go:build !linux
package main
import (
"errors"
"time"
)
// The built-in X11 clipboard is Linux-only; other platforms always fall back
// to external clipboard tools.
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
return false, nil
}
func runClipboardDaemon(timeout time.Duration) error {
return errors.New("the built-in clipboard daemon is Linux-only")
}
func readClipboardSelection() (string, error) {
return "", errors.New("reading the clipboard is Linux-only")
}
-318
View File
@@ -1,318 +0,0 @@
//go:build linux
package main
import (
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
)
// Pure-Go X11 clipboard. Xlibre is protocol-compatible with X.Org, so the
// regular CLIPBOARD selection works there too. No xclip/xsel/wl-copy needed.
const (
selClipboard = "CLIPBOARD"
atomUTF8 = "UTF8_STRING"
atomString = "STRING"
atomText = "TEXT"
atomTextPlain = "text/plain"
atomPlainUTF8 = "text/plain;charset=utf-8"
atomTargets = "TARGETS"
atomMultiple = "MULTIPLE"
propName = "PASS_SELECTION"
)
type xAtoms map[string]xproto.Atom
func allAtomNames() []string {
return []string{selClipboard, atomUTF8, atomString, atomText, atomTextPlain,
atomPlainUTF8, atomTargets, atomMultiple, propName}
}
func internAtoms(c *xgb.Conn, names ...string) (xAtoms, error) {
m := make(xAtoms, len(names))
for _, n := range names {
rep, err := xproto.InternAtom(c, false, uint16(len(n)), n).Reply()
if err != nil {
return nil, err
}
m[n] = rep.Atom
}
return m, nil
}
// serveClipboard takes ownership of the X11 CLIPBOARD selection and answers
// paste requests until another client takes ownership or timeout elapses
// (timeout <= 0 means "until replaced"). If ready is non-nil it is closed once
// ownership has been confirmed.
func serveClipboard(text string, timeout time.Duration, ready chan<- struct{}) error {
c, err := xgb.NewConn()
if err != nil {
return fmt.Errorf("cannot connect to X server: %v", err)
}
defer c.Close()
atoms, err := internAtoms(c, allAtomNames()...)
if err != nil {
return err
}
screen := xproto.Setup(c).DefaultScreen(c)
wid, err := c.NewId()
if err != nil {
return err
}
err = xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check()
if err != nil {
return err
}
xproto.SetSelectionOwner(c, xproto.Window(wid), atoms[selClipboard], xproto.TimeCurrentTime)
rep, err := xproto.GetSelectionOwner(c, atoms[selClipboard]).Reply()
if err != nil {
return err
}
if rep.Owner != xproto.Window(wid) {
return errors.New("failed to acquire CLIPBOARD ownership")
}
if ready != nil {
close(ready)
}
done := make(chan error, 1)
go func() { done <- selectionEventLoop(c, text, atoms) }()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sig)
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case err := <-done:
return err
case <-timer.C:
return nil
case <-sig:
return nil
}
}
select {
case err := <-done:
return err
case <-sig:
return nil
}
}
func selectionEventLoop(c *xgb.Conn, text string, atoms xAtoms) error {
for {
ev, err := c.WaitForEvent()
if err != nil { // connection closed or protocol error
return err
}
switch e := ev.(type) {
case xproto.SelectionClearEvent:
return nil // another client owns the clipboard now
case xproto.DestroyNotifyEvent:
return nil
case xproto.SelectionRequestEvent:
handleSelectionRequest(c, e, text, atoms)
}
}
}
func handleSelectionRequest(c *xgb.Conn, e xproto.SelectionRequestEvent, text string, atoms xAtoms) {
prop := e.Property
if prop == xproto.AtomNone {
prop = e.Target
}
ok := false
switch e.Target {
case atoms[atomTargets]:
targets := []xproto.Atom{
atoms[atomTargets], atoms[atomMultiple],
atoms[atomUTF8], atoms[atomPlainUTF8],
atoms[atomText], atoms[atomTextPlain], atoms[atomString],
}
buf := make([]byte, 4*len(targets))
for i, t := range targets {
binary.LittleEndian.PutUint32(buf[i*4:], uint32(t))
}
ok = changeProperty(c, e.Requestor, prop, xproto.AtomAtom, 32, buf)
case atoms[atomUTF8], atoms[atomPlainUTF8], atoms[atomText], atoms[atomTextPlain], atoms[atomString]:
// Generated passwords are plain ASCII, so serving the same bytes for
// STRING (Latin-1) and TEXT targets is safe.
ok = changeProperty(c, e.Requestor, prop, e.Target, 8, []byte(text))
}
if !ok {
prop = xproto.AtomNone // refuse this target
}
// Reply with a SelectionNotify event (event code 31).
b := make([]byte, 32)
b[0] = 31
binary.LittleEndian.PutUint32(b[4:], uint32(e.Time))
binary.LittleEndian.PutUint32(b[8:], uint32(e.Requestor))
binary.LittleEndian.PutUint32(b[12:], uint32(e.Selection))
binary.LittleEndian.PutUint32(b[16:], uint32(e.Target))
binary.LittleEndian.PutUint32(b[20:], uint32(prop))
xproto.SendEvent(c, false, e.Requestor, 0, string(b))
}
func changeProperty(c *xgb.Conn, win xproto.Window, prop, typ xproto.Atom, format byte, data []byte) bool {
units := uint32(len(data))
if format == 32 {
units /= 4
}
return xproto.ChangePropertyChecked(c, xproto.PropModeReplace, win, prop,
typ, format, units, data).Check() == nil
}
// copyViaX11 copies through the built-in clipboard server. It reports false
// when no X server is reachable, so the caller can fall back to external
// clipboard tools.
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
if os.Getenv("DISPLAY") == "" {
return false, nil
}
probe, err := xgb.NewConn()
if err != nil {
return false, nil
}
probe.Close()
return true, spawnClipboardDaemon(text, clearAfter)
}
// spawnClipboardDaemon re-executes this binary detached (new session) so the
// clipboard keeps working after the terminal is closed. The password travels
// over a pipe; it is never in argv or the environment.
func spawnClipboardDaemon(text string, timeout time.Duration) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
cmd := exec.Command(selfPath(), "--serve-clipboard", "--clear-after="+timeout.String())
cmd.ExtraFiles = []*os.File{r}
cmd.Env = os.Environ() // keep DISPLAY for the child
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
r.Close()
w.Close()
return err
}
if _, err := io.WriteString(w, text); err != nil {
return err
}
w.Close()
r.Close()
return nil
}
// selfPath returns the absolute path of this running executable, so the
// detached clipboard daemon can re-exec itself reliably.
func selfPath() string {
if p, err := os.Executable(); err == nil {
return p
}
return os.Args[0]
}
// runClipboardDaemon is the detached child process: it receives the password
// over the pipe passed as fd 3 and serves the X11 clipboard until it is
// replaced or the timeout elapses.
func runClipboardDaemon(timeout time.Duration) error {
f := os.NewFile(uintptr(3), "pipe")
if f == nil {
return errors.New("no pipe on fd 3")
}
data := make([]byte, 0, 64)
buf := make([]byte, 64)
for {
n, err := f.Read(buf)
data = append(data, buf[:n]...)
if err != nil {
break
}
}
f.Close()
if len(data) == 0 {
return errors.New("empty clipboard payload")
}
return serveClipboard(string(data), timeout, nil)
}
// readClipboardSelection requests the current CLIPBOARD contents as
// UTF8_STRING (equivalent of "xclip -o -selection clipboard").
func readClipboardSelection() (string, error) {
c, err := xgb.NewConn()
if err != nil {
return "", fmt.Errorf("cannot connect to X server: %v", err)
}
defer c.Close()
atoms, err := internAtoms(c, allAtomNames()...)
if err != nil {
return "", err
}
screen := xproto.Setup(c).DefaultScreen(c)
wid, err := c.NewId()
if err != nil {
return "", err
}
if err := xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check(); err != nil {
return "", err
}
xproto.ConvertSelection(c, xproto.Window(wid), atoms[selClipboard],
atoms[atomUTF8], atoms[propName], xproto.TimeCurrentTime)
// Wait for the SelectionNotify reply.
var prop xproto.Atom
found := false
deadline := time.Now().Add(5 * time.Second)
for !found {
if time.Now().After(deadline) {
return "", errors.New("timed out waiting for the clipboard owner")
}
ev, err := c.WaitForEvent()
if err != nil {
return "", err
}
if sn, ok := ev.(xproto.SelectionNotifyEvent); ok {
if sn.Selection != atoms[selClipboard] {
continue
}
if sn.Property == xproto.AtomNone {
return "", errors.New("clipboard owner refused the request")
}
prop = sn.Property
found = true
}
}
rep, err := xproto.GetProperty(c, false, xproto.Window(wid), prop,
xproto.GetPropertyTypeAny, 0, 1<<20).Reply()
if err != nil {
return "", err
}
return string(rep.Value), nil
}
-44
View File
@@ -1,44 +0,0 @@
//go:build linux
package main
import (
"os"
"testing"
"time"
)
// Live X11 round trip: take ownership of the CLIPBOARD selection, then read
// it back as a separate X client.
func TestClipboardRoundTrip(t *testing.T) {
if os.Getenv("DISPLAY") == "" {
t.Skip("no X11 display available")
}
text := "TestPassword123"
ready := make(chan struct{})
done := make(chan error, 1)
go func() { done <- serveClipboard(text, 10*time.Second, ready) }()
select {
case <-ready:
case err := <-done:
t.Fatalf("clipboard server exited early: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for clipboard ownership")
}
// Reading immediately can race with clipboard managers stealing the
// selection; poll briefly for the expected content.
deadline := time.Now().Add(5 * time.Second)
for {
got, err := readClipboardSelection()
if err == nil && got == text {
return // success
}
if time.Now().After(deadline) {
t.Fatalf("clipboard round trip failed: last read = %q, err = %v", got, err)
}
time.Sleep(100 * time.Millisecond)
}
}
-322
View File
@@ -1,322 +0,0 @@
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
"time"
password "github.com/waozixyz/pass"
"github.com/waozixyz/pass/vault"
)
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
// promptVaultPassphrase asks for the vault passphrase on the terminal, or
// reads it from standard input when stdin is piped ("echo pw | pass ...").
func promptVaultPassphrase() (string, error) {
if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 {
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && line == "" {
return "", err
}
return strings.TrimRight(line, "\r\n"), nil
}
return readPassword("Vault passphrase: ")
}
// readVaultPassphrase is the hook tests replace to decrypt a synthetic vault.
var readVaultPassphrase = promptVaultPassphrase
func main() {
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "pass: %v\n", err)
os.Exit(1)
}
}
func run(arguments []string, stdout, stderr io.Writer) error {
config, err := loadConfig()
if err != nil {
return err
}
options := password.DefaultOptions()
flags := flag.NewFlagSet("pass", flag.ContinueOnError)
flags.SetOutput(stderr)
flags.Usage = func() { printHelp(stderr) }
flags.IntVar(&options.Length, "L", options.Length, "password length")
flags.IntVar(&options.Length, "length", options.Length, "password length")
flags.Uint64Var(&options.Counter, "C", options.Counter, "generation counter")
flags.Uint64Var(&options.Counter, "counter", options.Counter, "generation counter")
flags.BoolVar(&options.Lowercase, "l", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Lowercase, "lowercase", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Uppercase, "u", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Uppercase, "uppercase", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Digits, "d", options.Digits, "include digits")
flags.BoolVar(&options.Digits, "digits", options.Digits, "include digits")
flags.BoolVar(&options.Symbols, "s", options.Symbols, "include symbols")
flags.BoolVar(&options.Symbols, "symbols", options.Symbols, "include symbols")
var noLowercase, noUppercase, noDigits, noSymbols bool
flags.BoolVar(&noLowercase, "no-lowercase", false, "exclude lowercase letters")
flags.BoolVar(&noUppercase, "no-uppercase", false, "exclude uppercase letters")
flags.BoolVar(&noDigits, "no-digits", false, "exclude digits")
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
var forcePrompt, copyPassword, noCopy, showVersion, readClipboard, serveClipboard bool
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
flags.BoolVar(&copyPassword, "c", false, "copy the password to the clipboard")
flags.BoolVar(&copyPassword, "copy", false, "copy the password to the clipboard")
flags.BoolVar(&noCopy, "no-copy", false, "print instead of copying when the profile says to copy")
flags.BoolVar(&showVersion, "v", false, "show version")
flags.BoolVar(&showVersion, "version", false, "show version")
var profileName, vaultFlag string
var clearAfter time.Duration
flags.StringVar(&profileName, "P", "", "use a named profile from the configuration file")
flags.StringVar(&profileName, "profile", "", "use a named profile from the configuration file")
flags.StringVar(&vaultFlag, "vault", "", "read the master password from an OpenSSL-encrypted vault")
flags.DurationVar(&clearAfter, "clear-after", 0, "clear the clipboard after this long; 0 keeps it until replaced (built-in X11 clipboard only)")
flags.BoolVar(&readClipboard, "read-clipboard", false, "print the current clipboard contents")
flags.BoolVar(&serveClipboard, "serve-clipboard", false, "") // internal: detached clipboard daemon mode
if err := flags.Parse(normalizeArguments(arguments)); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
explicit := map[string]bool{}
flags.Visit(func(f *flag.Flag) { explicit[f.Name] = true })
if noLowercase {
options.Lowercase = false
}
if noUppercase {
options.Uppercase = false
}
if noDigits {
options.Digits = false
}
if noSymbols {
options.Symbols = false
}
if showVersion {
fmt.Fprintf(stdout, "pass %s\n", password.Version)
return nil
}
if serveClipboard {
return runClipboardDaemon(clearAfter)
}
if readClipboard {
text, err := readClipboardSelection()
if err != nil {
return err
}
fmt.Fprintln(stdout, text)
return nil
}
positional := flags.Args()
if profileName == "" && len(positional) == 2 && config != nil {
if _, ok := config.Profiles[positional[0]]; ok {
profileName = positional[0]
positional = positional[1:]
}
}
var profile Profile
if profileName != "" {
if config == nil {
return fmt.Errorf("unknown profile %q: no configuration file at %s", profileName, configPath())
}
found, ok := config.Profiles[profileName]
if !ok {
return fmt.Errorf("unknown profile %q", profileName)
}
if found.Login == "" {
return fmt.Errorf("profile %q has no login", profileName)
}
profile = found
profile.apply(&options, explicit)
}
if profileName != "" {
if len(positional) != 1 {
printHelp(stderr)
return errors.New("expected SITE with --profile")
}
} else if len(positional) < 2 || len(positional) > 3 {
printHelp(stderr)
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
}
if forcePrompt && len(positional) == 3 {
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
}
site, login := positional[0], ""
if profileName != "" {
login = profile.Login
} else {
login = positional[1]
}
// Explicit command-line password sources win. A configured vault beats
// LESSPASS_MASTER_PASSWORD because profiles are meant to be complete
// saved identities, including the master source.
vaultPath := vaultFlag
if vaultPath == "" {
if !forcePrompt && len(positional) < 3 {
switch {
case profile.Vault != "":
vaultPath = expandHome(profile.Vault)
case config != nil && config.Vault != "":
vaultPath = expandHome(config.Vault)
}
}
}
if !noCopy && !anySet(explicit, "c", "copy") {
switch {
case profile.Copy != nil:
copyPassword = *profile.Copy
case config != nil && config.Copy != nil:
copyPassword = *config.Copy
}
}
if noCopy {
copyPassword = false
}
if !anySet(explicit, "clear-after") {
setting := profile.ClearAfter
if setting == "" && config != nil {
setting = config.ClearAfter
}
if setting != "" {
duration, err := time.ParseDuration(setting)
if err != nil {
return fmt.Errorf("clear_after: %w", err)
}
clearAfter = duration
}
}
master, err := masterPassword(positional, forcePrompt, vaultPath)
if err != nil {
return err
}
generated, err := password.Generate(site, login, master, options)
if err != nil {
return err
}
if copyPassword {
if err := copyToClipboard(generated, clearAfter); err != nil {
return err
}
if clearAfter > 0 {
fmt.Fprintf(stderr, "Password copied to the clipboard (auto-clears in %s).\n", clearAfter)
} else {
fmt.Fprintln(stderr, "Password copied to the clipboard.")
}
return nil
}
fmt.Fprintln(stdout, generated)
return nil
}
// normalizeArguments lets callers place options before or after SITE and
// LOGIN. The standard flag package stops at the first positional argument,
// while command wrappers naturally append profile options after the site.
func normalizeArguments(arguments []string) []string {
valueFlags := map[string]bool{
"-L": true, "--length": true,
"-C": true, "--counter": true,
"--exclude": true,
"-P": true, "--profile": true,
"--vault": true, "--clear-after": true,
}
options := make([]string, 0, len(arguments))
positional := make([]string, 0, 3)
for i := 0; i < len(arguments); i++ {
argument := arguments[i]
if argument == "--" {
positional = append(positional, arguments[i+1:]...)
break
}
if strings.HasPrefix(argument, "-") && argument != "-" {
options = append(options, argument)
if valueFlags[argument] && i+1 < len(arguments) {
i++
options = append(options, arguments[i])
}
continue
}
positional = append(positional, argument)
}
return append(options, positional...)
}
func masterPassword(positional []string, forcePrompt bool, vaultPath string) (string, error) {
if vaultPath != "" {
if forcePrompt {
return "", errors.New("--vault cannot be combined with --prompt")
}
if len(positional) == 3 {
return "", errors.New("--vault cannot be combined with MASTER_PASSWORD")
}
passphrase, err := readVaultPassphrase()
if err != nil {
return "", err
}
return vault.Decrypt(vaultPath, passphrase)
}
if !forcePrompt && len(positional) == 3 {
return positional[2], nil
}
if !forcePrompt {
if value, exists := os.LookupEnv(environmentVariable); exists {
return value, nil
}
}
return readPassword("Master password: ")
}
func printHelp(output io.Writer) {
fmt.Fprintln(output, `Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
Derive a site-specific password. If MASTER_PASSWORD is omitted, pass reads
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal. With
--vault it instead decrypts an OpenSSL-encrypted vault and uses its contents
as the master password. A named profile from the configuration file can be
used either as "pass PROFILE SITE" or with --profile; it supplies the login
and default settings.
Options:
-L, --length N password length (default 16)
-C, --counter N generation counter (default 1)
-l, --lowercase include lowercase letters
-u, --uppercase include uppercase letters
-d, --digits include digits
-s, --symbols include symbols
--no-lowercase exclude lowercase letters
--no-uppercase exclude uppercase letters
--no-digits exclude digits
--no-symbols exclude symbols
--exclude CHARS remove characters from all enabled classes
-p, --prompt always ask for the master password
-c, --copy copy result without printing it
--no-copy print instead of copying when the profile says to copy
-P, --profile NAME use a named profile from the configuration file
--vault PATH read the master password from an OpenSSL-encrypted vault
--clear-after DUR clear the clipboard after DUR; 0 keeps it until replaced
--read-clipboard print the current clipboard contents
-v, --version show version
-h, --help show this help`)
}
-101
View File
@@ -1,101 +0,0 @@
package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
password "github.com/waozixyz/pass"
)
// TestMain isolates every test in this package from the developer's real
// profiles file: without this, a machine with ~/.config/pass/profiles.json
// would feed private configuration into the tests.
func TestMain(m *testing.M) {
configPath = func() string {
return filepath.Join(os.TempDir(), "pass-tests-absent-profiles.json")
}
os.Exit(m.Run())
}
func TestRunWithArgument(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "correct horse battery staple"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got, want := output.String(), "&vLf44D'/cSkP-_8\n"; got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestRunUsesEnvironmentAndFlags(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"--length", "10", "--no-symbols", "--exclude", "aA0", "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(output.String())
if len(got) != 10 {
t.Fatalf("output length = %d, want 10", len(got))
}
if strings.ContainsAny(got, "aA0"+"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
t.Fatalf("output %q contains a disabled character", got)
}
}
func TestRunAcceptsFlagsAfterSiteAndLogin(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "-C", "9", "-L", "23", "--no-symbols"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); len(got) != 23 {
t.Fatalf("output length = %d, want 23", len(got))
}
}
func TestRunInformationOptions(t *testing.T) {
for _, test := range []struct {
argument string
want string
}{
{"--version", "pass " + password.Version},
{"--help", "Usage: pass"},
} {
var output, diagnostics bytes.Buffer
if err := run([]string{test.argument}, &output, &diagnostics); err != nil {
t.Errorf("run(%s): %v", test.argument, err)
}
combined := output.String() + diagnostics.String()
if !strings.Contains(combined, test.want) {
t.Errorf("run(%s) output %q does not contain %q", test.argument, combined, test.want)
}
}
}
func TestRunRejectsConflictingPasswordSources(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"--prompt", "example.com", "alice", "master"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "cannot be supplied") {
t.Fatalf("error = %v, want source conflict", err)
}
}
func TestClipboardCommandsDoNotCarryPasswordData(t *testing.T) {
secret := "this must travel only over standard input"
for _, command := range clipboardCommands() {
if command.program == secret {
t.Fatal("secret appeared as clipboard executable")
}
for _, argument := range command.args {
if strings.Contains(argument, secret) {
t.Fatal("secret appeared in clipboard command arguments")
}
}
}
}
-119
View File
@@ -1,119 +0,0 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
password "github.com/waozixyz/pass"
)
// Profile holds the saved settings for one named identity: a login plus the
// generator options and clipboard behavior to use with it. Profiles contain
// no secrets — the master password always comes from a prompt, the
// environment, or an encrypted vault referenced by path.
type Profile struct {
Login string `json:"login"`
Counter uint64 `json:"counter,omitempty"`
Length int `json:"length,omitempty"`
Lowercase *bool `json:"lowercase,omitempty"`
Uppercase *bool `json:"uppercase,omitempty"`
Digits *bool `json:"digits,omitempty"`
Symbols *bool `json:"symbols,omitempty"`
Exclude string `json:"exclude,omitempty"`
Vault string `json:"vault,omitempty"`
Copy *bool `json:"copy,omitempty"`
ClearAfter string `json:"clear_after,omitempty"`
}
// Config is the optional profiles file. Every field is a default that flags
// and profile entries override; a missing file leaves pass fully stateless.
type Config struct {
Vault string `json:"vault,omitempty"`
Copy *bool `json:"copy,omitempty"`
ClearAfter string `json:"clear_after,omitempty"`
Profiles map[string]Profile `json:"profiles"`
}
// configPath is a variable so tests can point it at a temporary file.
var configPath = defaultConfigPath
func defaultConfigPath() string {
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
return filepath.Join(dir, "pass", "profiles.json")
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".config", "pass", "profiles.json")
}
// loadConfig reads the profiles file. A missing file is not an error: the
// feature is simply off and pass behaves as a plain stateless generator.
func loadConfig() (*Config, error) {
path := configPath()
if path == "" {
return nil, nil
}
raw, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var config Config
if err := json.Unmarshal(raw, &config); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return &config, nil
}
// apply fills the option fields that were not set explicitly on the command
// line, so the precedence is always flag > profile > built-in default.
func (p Profile) apply(options *password.Options, explicit map[string]bool) {
if p.Length > 0 && !anySet(explicit, "L", "length") {
options.Length = p.Length
}
if p.Counter > 0 && !anySet(explicit, "C", "counter") {
options.Counter = p.Counter
}
if p.Lowercase != nil && !anySet(explicit, "l", "lowercase", "no-lowercase") {
options.Lowercase = *p.Lowercase
}
if p.Uppercase != nil && !anySet(explicit, "u", "uppercase", "no-uppercase") {
options.Uppercase = *p.Uppercase
}
if p.Digits != nil && !anySet(explicit, "d", "digits", "no-digits") {
options.Digits = *p.Digits
}
if p.Symbols != nil && !anySet(explicit, "s", "symbols", "no-symbols") {
options.Symbols = *p.Symbols
}
if p.Exclude != "" && !anySet(explicit, "exclude") {
options.Exclude = p.Exclude
}
}
func anySet(explicit map[string]bool, names ...string) bool {
for _, name := range names {
if explicit[name] {
return true
}
}
return false
}
// expandHome resolves a leading ~ so config entries stay portable.
func expandHome(path string) string {
if path == "~" || strings.HasPrefix(path, "~/") {
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, strings.TrimPrefix(path, "~"))
}
}
return path
}
-257
View File
@@ -1,257 +0,0 @@
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
password "github.com/waozixyz/pass"
)
// withConfig points the config loader at a temporary file for one test.
func withConfig(t *testing.T, content string) {
t.Helper()
path := filepath.Join(t.TempDir(), "profiles.json")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
original := configPath
configPath = func() string { return path }
t.Cleanup(func() { configPath = original })
}
func withVaultPassphrase(t *testing.T, passphrase string) {
t.Helper()
original := readVaultPassphrase
readVaultPassphrase = func() (string, error) { return passphrase, nil }
t.Cleanup(func() { readVaultPassphrase = original })
}
func TestRunWithProfileSettings(t *testing.T) {
withConfig(t, `{
"copy": true,
"clear_after": "90s",
"profiles": {
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
}
}`)
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
})
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestRunWithProfileShorthand(t *testing.T) {
withConfig(t, `{
"profiles": {
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
}
}`)
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"w", "example.com", "--no-copy"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
})
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestProfileSettingsDoNotOverrideExplicitFlags(t *testing.T) {
withConfig(t, `{"profiles": {"w": {"login": "alice", "length": 23, "symbols": false}}}`)
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "-L", "10", "example.com"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); len(got) != 10 {
t.Fatalf("output length = %d, want 10 (flag must beat profile)", len(got))
}
}
func TestRunRejectsBadProfileNames(t *testing.T) {
withConfig(t, `{"profiles": {"w": {"login": "alice"}, "n": {}}}`)
t.Setenv(environmentVariable, "x")
var output, diagnostics bytes.Buffer
if err := run([]string{"-P", "x", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "unknown profile") {
t.Fatalf("error = %v, want unknown profile", err)
}
if err := run([]string{"-P", "n", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "has no login") {
t.Fatalf("error = %v, want missing login", err)
}
// A profile without a configuration file at all.
original := configPath
configPath = func() string { return filepath.Join(t.TempDir(), "absent.json") }
defer func() { configPath = original }()
if err := run([]string{"-P", "w", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "no configuration file") {
t.Fatalf("error = %v, want missing configuration", err)
}
}
func TestRunRejectsInvalidConfig(t *testing.T) {
withConfig(t, `{"profiles":`)
var output, diagnostics bytes.Buffer
if err := run([]string{"example.com", "alice", "master"}, &output, &diagnostics); err == nil {
t.Fatal("expected error for malformed configuration")
}
}
func TestRunRejectsInvalidClearAfter(t *testing.T) {
withConfig(t, `{"clear_after": "not-a-duration", "profiles": {"w": {"login": "alice"}}}`)
t.Setenv(environmentVariable, "x")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "clear_after") {
t.Fatalf("error = %v, want clear_after parse failure", err)
}
}
func TestVaultMasterPasswordBeatsEnvironmentAndPositional(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".vault")
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
withVaultPassphrase(t, "masterpw")
t.Setenv(environmentVariable, "environment-must-be-ignored")
var output, diagnostics bytes.Buffer
err := run([]string{"--vault", vaultFile, "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "my-top-secret", password.DefaultOptions())
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
if err := run([]string{"--vault", vaultFile, "example.com", "alice", "master"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "cannot be combined") {
t.Fatalf("error = %v, want source conflict with MASTER_PASSWORD", err)
}
if err := run([]string{"--vault", vaultFile, "--prompt", "example.com", "alice"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "cannot be combined") {
t.Fatalf("error = %v, want source conflict with --prompt", err)
}
}
func TestConfigVaultIsUsedForProfile(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".vault")
encrypt := `printf 'cfg-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
withConfig(t, `{"vault": "`+vaultFile+`", "profiles": {"w": {"login": "alice"}}}`)
withVaultPassphrase(t, "masterpw")
t.Setenv(environmentVariable, "environment-must-be-ignored")
var output, diagnostics bytes.Buffer
if err := run([]string{"w", "example.com", "--no-copy"}, &output, &diagnostics); err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "cfg-secret", password.DefaultOptions())
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestExpandHome(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Skip("no home directory")
}
for _, test := range []struct{ in, want string }{
{"~", home},
{"~/bin/.vault", filepath.Join(home, "bin", ".vault")},
{"/abs/path", "/abs/path"},
{"relative", "relative"},
} {
if got := expandHome(test.in); got != test.want {
t.Errorf("expandHome(%q) = %q, want %q", test.in, got, test.want)
}
}
}
func TestVaultPassphraseFromPipedStdin(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".vault")
encrypt := `printf 'piped-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
for _, test := range []struct {
name string
contents string
}{
{"newline", "masterpw\n"},
{"crlf", "masterpw\r\n"},
{"no trailing newline", "masterpw"},
} {
t.Run(test.name, func(t *testing.T) {
input, err := os.CreateTemp(t.TempDir(), "stdin")
if err != nil {
t.Fatal(err)
}
if _, err := input.WriteString(test.contents); err != nil {
t.Fatal(err)
}
if _, err := input.Seek(0, 0); err != nil {
t.Fatal(err)
}
previous := os.Stdin
os.Stdin = input
defer func() { os.Stdin = previous }()
got, err := promptVaultPassphrase()
if err != nil {
t.Fatal(err)
}
if got != "masterpw" {
t.Fatalf("passphrase = %q, want %q", got, "masterpw")
}
})
}
}
-53
View File
@@ -1,53 +0,0 @@
//go:build linux
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
state, err := terminalState(terminal.Fd(), syscall.TCGETS, nil)
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
noEcho := *state
noEcho.Lflag &^= syscall.ECHO
if _, err := terminalState(terminal.Fd(), syscall.TCSETS, &noEcho); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = terminalState(terminal.Fd(), syscall.TCSETS, state) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func terminalState(fd uintptr, request uintptr, replacement *syscall.Termios) (*syscall.Termios, error) {
state := replacement
if state == nil {
state = new(syscall.Termios)
}
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, uintptr(unsafe.Pointer(state)))
if errno != 0 {
return nil, errno
}
return state, nil
}
-9
View File
@@ -1,9 +0,0 @@
//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !windows
package main
import "errors"
func readPassword(_ string) (string, error) {
return "", errors.New("secure terminal prompting is not supported on this operating system; use LESSPASS_MASTER_PASSWORD")
}
-50
View File
@@ -1,50 +0,0 @@
//go:build darwin || dragonfly || freebsd || netbsd || openbsd || solaris
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
stty, err := exec.LookPath("stty")
if err != nil {
return "", fmt.Errorf("cannot securely prompt because stty is unavailable: %w", err)
}
original, err := runStty(stty, terminal, "-g")
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
if _, err := runStty(stty, terminal, "-echo"); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = runStty(stty, terminal, strings.TrimSpace(original)) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func runStty(path string, terminal *os.File, argument string) (string, error) {
command := exec.Command(path, argument)
command.Stdin = terminal
command.Stderr = terminal
output, err := command.Output()
return string(output), err
}
-63
View File
@@ -1,63 +0,0 @@
//go:build windows
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
const enableEchoInput = 0x0004
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getConsoleMode = kernel32.NewProc("GetConsoleMode")
setConsoleMode = kernel32.NewProc("SetConsoleMode")
)
func readPassword(label string) (string, error) {
input, err := os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a console: %w", err)
}
defer input.Close()
output, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0)
if err != nil {
return "", fmt.Errorf("cannot open the console for prompting: %w", err)
}
defer output.Close()
var original uint32
if err := windowsCall(getConsoleMode, input.Fd(), uintptr(unsafe.Pointer(&original))); err != nil {
return "", fmt.Errorf("cannot read console settings: %w", err)
}
if err := windowsCall(setConsoleMode, input.Fd(), uintptr(original&^enableEchoInput)); err != nil {
return "", fmt.Errorf("cannot disable console echo: %w", err)
}
defer func() { _ = windowsCall(setConsoleMode, input.Fd(), uintptr(original)) }()
if _, err := fmt.Fprint(output, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(input).ReadString('\n')
fmt.Fprintln(output)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func windowsCall(procedure *syscall.LazyProc, arguments ...uintptr) error {
result, _, callErr := procedure.Call(arguments...)
if result != 0 {
return nil
}
if callErr != nil && callErr != syscall.Errno(0) {
return callErr
}
return syscall.EINVAL
}
+240
View File
@@ -0,0 +1,240 @@
# Werkzeug development and data
[Back to Werkzeug](../README.md).
## Privacy
Everything is computed on the device. Werkzeug makes no network requests
unless you set up sync or explicitly request an account or device-link action.
Each tool keeps its own files, readable only by your user:
| Platform | Data |
|---|---|
| Linux | `$XDG_DATA_HOME/werk` (or `~/.local/share/werk`) |
| Android | the app's private storage |
| Browser | IndexedDB on this site |
Auth's accounts are synced records: `otpauth` links in the private
`records/auth.txt`, protected by the file permissions of your account or the
Android app sandbox.
## Sync
Profile uses the shared Self bundle. Desktop Account management shows the
public ID, alias, sync status and queued changes, and provides account creation,
key-file import, backups, device linking and logout. Switching accounts asks
whether to keep and merge local Auth records or replace them. A private rollback
journal preserves the previous key and records if a switch is interrupted.
The account can use a [Mesh](https://github.com/ziranlang/mesh) node,
`api.waozi.xyz` by default. Tools work locally without an account. Saved nodes
and the preferred node live in Profile → Nodes; choosing a node preserves the
account and its paused state. The sync switch pauses automatic synchronization
and stays paused after restarting. Logout keeps local Auth records.
Desktop key backups retain Werkzeug's Auth vault key as protected recovery
context. Use a passphrase to encrypt the backup. Importing a legacy account key
for the already-connected identity preserves its existing vault key. The shared
QR workflow also preserves that context and asks both devices to compare digits
before connecting. Legacy clients cannot read the extended QR payload when
Werkzeug vault context is included.
Desktop Self and participating native apps share public profile preferences only
for the same verified account ID. Account keys and Auth records stay in the
host's private store. Android retains its existing native Account screen and
legacy device-link flow. In the browser, Profile opens the shared manager at
https://entity.waozi.xyz. Public name, picture and appearance follow the active
waozi.xyz profile. Werkzeug's browser tool data stays local; account sync for
those tool records is unavailable.
The embedded web app (`/app/?mini`) shows only the tools, as large tiles,
with no Profile; `werk --mini` does the same on the desktop. Use
`?mini&app=pass`, `auth`, `calculator` or `clock` to open a particular tool
first; Back returns to the tiles. Browser sync is currently unavailable.
- Each record is sealed on the device with XChaCha20-Poly1305 under a random
vault key that is never sent to the node unencrypted. The seal covers the
account, the record and the time of the change, so the server can neither
read nor alter a record or a removal.
- The account key (ML-DSA-44) signs in and signs each sync together with
the device's own Ed25519 key.
- Desktop device linking uses the shared Self QR/code exchange with X25519
and encrypted key transfer. Confirm the matching number on both devices.
Android's existing 12-character connection code remains available in its
native account screen.
- The server can still withhold changes or serve an older copy to a device
that has not seen a newer one. A lost device keeps the keys it had: stop
syncing there if you can, and replace two-factor secrets you care about.
`scripts/sync_e2e_test.sh` runs two devices against a local Mesh node.
## The `werk sync` and `werk auth` commands
On Linux, the same data works without a window, for devices without a
screen and for scripts:
```text
werk sync status | create | show | join [CODE] | key [FILE] | now
werk auth list
werk auth code ID
werk auth import [FILE]
werk auth rename ID SERVICE ACCOUNT
werk auth sites ID [WEBSITE ...]
werk auth remove ID
```
`werk sync show` prints a code for another device to enter; `werk sync join`
reads one from its argument or standard input. `werk sync key` signs in with
an account key from FILE or standard input; for a key with a passphrase, give
FILE and the passphrase on standard input. `werk auth list` prints the
accounts as JSON with their ids and websites, never their secrets.
`werk auth code ID` prints the current code and the seconds it stays valid.
`werk auth import` reads a file, or standard input: otpauth links, Google
Authenticator export links, an unencrypted Aegis export, or a PNG or JPEG of
an export's QR code when GdkPixbuf and ZBar (`libzbar0`) are installed.
Changes sync right away when the device has an account. `werk --app auth`
opens the window on one tool, as Harmony's Auth entry does.
## Tools are separate apps
Each tool is built into its own portable bundle, `build/apps/<tool>.zx`:
Pass, Calculator and Clock from `apps/<tool>/`, Auth from its own Ziran
package ([waozixyz/auth](https://github.com/waozixyz/auth)), and Workbook from
[kryonlabs/workbook](https://github.com/kryonlabs/workbook). All five are
preinstalled. A tool reaches the host only through Kryon's app context (its
private files, clipboard, clock, key derivation and device-protected
secret), and the host checks every call a bundle asks for before it runs.
Tools never import each other; what two need, such as SHA-256 and PBKDF2,
comes from a Ziran package (`crypto`).
## Build and test
Dependencies and the compiler are pinned in `ziran.lock`. Desktop builds need
SDL2, Cairo, FreeType, Fontconfig, Pango, GTK 3 and X11 development packages.
Workbook uses its built-in spreadsheet engine on Android and the web; Linux
also uses the installed Gnumeric library for imported documents. Linux file choosers need Zenity. Browser
builds need Emscripten; Android builds need JDK 21 and the SDK/NDK versions in
`droid/app/build.gradle`. Desktop tests use Xvfb, xdotool, xclip and
ImageMagick on private displays.
```sh
make gui # build/werk and the app bundles in build/apps
make install-gui # Werkzeug and each tool in the app menu and on the desktop
make test # Pass/CLI, Auth, Calculator and private account recovery fixtures
make gui-smoke # light and dark home screens on a private Xvfb display
make gui-test # every tool, clipboard and profile on a private display,
# and werk auth without one
make site # build/site: browser app and offline worker
make web-smoke # private headless Chromium
make android-debug # ARM32, ARM64 and universal APKs
make android-fdroid # unsigned F-Droid candidate, same Android ID and version
make android-emulator # the x86_64 APK for a private emulator
```
Android input tests require an explicitly owned private emulator through
`WERK_ANDROID_EMULATOR`. `python3 scripts/private-emulator.py make android-input-test`
owns a headless API 31 Google APIs emulator, including Workbook's system document picker.
CI also retains API 30 input, profile and in-place update coverage through
`make android-profile-test`.
Linux installs include separate Pass, Auth, Calculator, Clock, Workbook and Gallery
launchers, each with its own icon. They open the selected tool directly and
share Werkzeug's existing private data. `make install-gui` also adds shortcuts
to the desktop folder configured by `xdg-user-dir`; set `DESKTOP_DIR=` to skip
those shortcuts. Debian packages include the same application-menu entries.
F-Droid metadata is maintained in `packaging/fdroid`. The `android-fdroid`
target disables developer signing even when a release keystore is configured
and writes `build/fdroid/werk.apk` for comparison with the signed release. It adds no version or
package suffix, preserving existing installations and reference-APK checks.
The unsigned candidate is for builders, not installation. Werkzeug currently
has no built-in updater: F-Droid or your chosen installer handles updates.
Android requires the same signing certificate for an in-place update; the
F-Droid recipe retains the developer-signature reproducibility requirement.
The [F-Droid TODO](../packaging/fdroid/TODO.md) records completed checks, the
remaining submission/reproducibility steps and the prepared merge-request text.
For development with the real project repositories, create an ignored
`ziran.local.toml`:
```toml
[overrides]
kryon = "../../kryonlabs/kryon"
ziran = "../../ziranlang/ziran"
```
## The `pass` command
```text
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
```
`make cli` builds it and `make install-cli` installs it. The default password
has 16 characters and includes lowercase letters, uppercase letters, digits
and symbols. Length must be between 5 and 35, matching LessPass clients. The
default counter is 1.
Passing a master password as an argument can expose it to process inspection
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
`--prompt` to bypass the environment and read from standard input:
```sh
pass --prompt example.com alice
pass --length 24 --counter 2 example.com alice
pass --no-symbols --exclude '0O1Il' example.com alice
```
The Linux CLI also reads saved identities from
`$XDG_CONFIG_HOME/pass/profiles.json` (or `~/.config/pass/profiles.json`).
`pass w example.com` and `pass --profile w example.com` use the saved login
and generation options. Existing OpenSSL-encrypted vaults are unlocked with
a hidden `Vault passphrase:` prompt. A configured vault takes precedence over
`LESSPASS_MASTER_PASSWORD`; `--prompt` bypasses it. Explicit flags override
profile defaults. Profiles and vaults are read without changing them.
`--copy` or a profile's `copy` setting copies through `xclip` on X11;
`--clear-after 90s` releases that clipboard selection after the given time
without erasing a later copy from another application. Use `--no-copy` to
print the generated password instead. Run `pass --help` for all flags.
## Source layout
```text
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
auth (package) Auth: TOTP, otpauth links, exports, accounts and screens (waozixyz/auth)
apps/calculator/ Calculator
apps/clock/ Clock and stopwatch
src/werk.zi home screen, profile screen and the bar above a tool
src/apps.zi loads, checks and runs the app bundles
src/platform.zi files, clock, clipboard and secrets per platform
src/desktop.zi, src/android_main.zi, src/browser.zi platform main loops
src/command.zi werk sync and werk auth without a window
```
## Profile-picture diagnostics
`make entity-account-test` uses a private local HTTP fixture to fetch a
picture through the normal background pump while Profile is closed. It checks
the challenge and signed login, saves the returned picture locally and in the
shared profile, and preserves another app's name. Its sanitized result is
`build/entity-account-test/picture-sync-diagnostics.json`; it contains no account
identifiers, keys, signatures or tokens.
`make gui-test` also extracts and decodes all 17 Entity picture resources in a
private display. Its resource names, dimensions and permissions are recorded
in `build/apps-gui-test/entity-resource-diagnostics.json`. This distinguishes
bundled-resource failures from sync failures without reading a real account.
Werkzeug previously skipped starting the background picture reader when
Profile was closed and no local picture was pending. Sync-enabled accounts
now start it automatically. These tests cover that reproduced failure. The
reported shared-resource failure across other apps has not been reproduced;
the tests do not establish its server-side or cross-app cause.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
[`LICENSE`](../LICENSE).
+67 -14
View File
@@ -7,11 +7,6 @@ android {
compileSdk 36
ndkVersion "28.2.13676358"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
def keystorePropsFile = rootProject.file("local.properties")
def keystoreProps = new Properties()
if (keystorePropsFile.exists()) {
@@ -19,16 +14,28 @@ 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
// Sign release builds only when a keystore is actually available: CI and
// local release builds pass -Pkeystore.* properties, while clean checkouts
// (for example an F-Droid builder) produce an unsigned APK instead.
def fdroidBuild = (project.findProperty('fDroidBuild') ?: 'false').toString().toBoolean()
def signRelease = !fdroidBuild \
&& releaseKeystore != null && releaseKeystore.exists() \
&& releasePassword != ""
signingConfigs {
release {
storeFile getKeystorePath() ? file(getKeystorePath()) : null
storePassword releasePassword
keyAlias getKeystoreAlias()
keyPassword releasePassword
if (signRelease) {
storeFile releaseKeystore
storePassword releasePassword
keyAlias getKeystoreAlias()
keyPassword releasePassword
}
}
}
@@ -36,8 +43,8 @@ android {
applicationId 'xyz.waozi.pass'
minSdk 21
targetSdk 36
versionCode 3
versionName "0.2.2"
versionCode 21
versionName "0.4.7"
// Default to the two realistic phone targets; override with
// -Pabi=x86_64 etc. for emulator builds.
def abis = project.findProperty('abi') ?: 'armeabi-v7a,arm64-v8a'
@@ -46,9 +53,18 @@ android {
}
}
splits {
abi {
enable = (project.findProperty('splitApks') ?: 'false').toString().toBoolean()
reset()
include 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
buildTypes {
release {
signingConfig project.hasProperty('fDroidBuild') ? null : signingConfigs.release
signingConfig signRelease ? signingConfigs.release : null
minifyEnabled false
}
debug {
@@ -64,6 +80,7 @@ android {
dependenciesInfo {
includeInApk = false
includeInBundle = false
}
packaging {
@@ -72,3 +89,39 @@ android {
}
}
}
// Bundle fonts without adding app or host Java code.
def prepareFonts = tasks.register('prepareFonts', Copy) {
into layout.buildDirectory.dir('generated/passAssets/fonts')
from('../../assets/fonts/NotoSans-Regular.ttf') { rename { 'ui.ttf' } }
from('../../assets/fonts/NotoSans-OFL.txt')
from('../../assets/fonts/emoji.ttf')
from('../../assets/fonts/emoji-OFL.txt')
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/passAssets'))
tasks.named('preBuild').configure { dependsOn prepareFonts }
// The tool apps are portable bundles, built once for every ABI.
def makeApps = tasks.register('makeApps', Exec) {
workingDir rootProject.file('..')
if (System.getenv('WERK_ZIRAN_COMMAND')) {
environment 'ZIRAN', System.getenv('WERK_ZIRAN_COMMAND')
}
commandLine 'make', 'portable-apps'
}
def kryonSource = providers.environmentVariable('KRYON_DIR').orElse(providers.exec {
workingDir rootProject.file('..')
commandLine (System.getenv('WERK_ZIRAN_COMMAND') ?: rootProject.file('../scripts/ziran.sh').absolutePath), 'pkg', 'path', 'kryon'
}.standardOutput.asText.map { it.trim() })
// Entity owns the account policy; Kryon supplies the shared Android consent UI.
apply from: new File(kryonSource.get(), 'templates/android-account-handoff.gradle')
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
def prepareImages = tasks.register('prepareImages', Sync) {
dependsOn makeApps
from('../../assets/app/icon.png')
from(kryonSource.map { "${it}/icons/pfp.webp" })
from('../../assets/tools') { include '*.webp'; into 'tools' }
from('../../build/apps') { include '*.zx'; into 'apps' }
into layout.buildDirectory.dir('generated/appAssets')
}
tasks.named('preBuild').configure { dependsOn prepareImages }
+4 -1
View File
@@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<!-- Only for sync, which is off until the owner sets up an account. -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:hasCode="true"
@@ -9,11 +11,12 @@
android:label="@string/app_name"
android:allowBackup="false">
<activity
android:name="xyz.waozi.pass.MainActivity"
android:name="android.app.NativeActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|uiMode"
android:exported="true"
android:launchMode="singleTask"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
android:windowSoftInputMode="adjustResize"
android:windowLayoutInDisplayCutoutMode="never">
<meta-data
android:name="android.app.lib_name"
+109 -125
View File
@@ -1,126 +1,110 @@
cmake_minimum_required(VERSION 3.22)
project(Pass C)
set(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../..")
set(KRYON_DIR "${REPO_ROOT}/vendor/kryon")
set(RAYLIB_DIR "${KRYON_DIR}/vendor/raylib/src")
set(PASS_NATIVE_DIR "${REPO_ROOT}/native")
set(NATIVE_APP_GLUE_DIR "${ANDROID_NDK}/sources/android/native_app_glue")
file(GLOB_RECURSE KRYON_SOURCES CONFIGURE_DEPENDS "${KRYON_DIR}/src/*.c")
# The src/backend/ software renderer implements raylib-named functions for
# no-raylib hosts; Android links real raylib, so compiling both is a
# duplicate-symbol link error.
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/backend/.*")
# pass uses no 2D physics; mirror the desktop Makefile's physics filter.
list(REMOVE_ITEM KRYON_SOURCES
"${KRYON_DIR}/src/scene/physics_world.c"
"${KRYON_DIR}/src/scene/node_body2d.c"
"${KRYON_DIR}/src/scene/node_area2d.c"
"${KRYON_DIR}/src/scene/node_collision_shape2d.c")
# Ksync account crypto requires liboqs and pass never syncs; runtime asset
# downloads need an Android download backend pass does not provide.
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/ksync/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/runtime_assets/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/notification/.*")
list(REMOVE_ITEM KRYON_SOURCES "${KRYON_DIR}/src/file_dialog/file_dialog.c")
set(PASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
set(PASS_EMOJI_FONT_ASSET "gui/assets/emoji.ttf")
set(PASS_EMBEDDED_ASSETS_C "${CMAKE_BINARY_DIR}/pass_embedded_assets.c")
add_custom_command(
OUTPUT "${PASS_EMBEDDED_ASSETS_C}"
COMMAND sh "${KRYON_DIR}/scripts/embed-assets.sh" "${PASS_EMBEDDED_ASSETS_C}" "${PASS_FONT_ASSET}" "${PASS_EMOJI_FONT_ASSET}"
DEPENDS "${KRYON_DIR}/scripts/embed-assets.sh" "${KRYON_DIR}/fonts/noto/NotoSans-Regular.ttf" "${REPO_ROOT}/${PASS_EMOJI_FONT_ASSET}"
WORKING_DIRECTORY "${REPO_ROOT}"
VERBATIM
)
add_library(raylib STATIC
"${RAYLIB_DIR}/rcore.c"
"${RAYLIB_DIR}/rshapes.c"
"${RAYLIB_DIR}/rtextures.c"
"${RAYLIB_DIR}/rtext.c"
"${RAYLIB_DIR}/raudio.c"
)
target_compile_definitions(raylib PRIVATE
PLATFORM_ANDROID
GRAPHICS_API_OPENGL_ES2
SUPPORT_SCREEN_CAPTURE=0
SUPPORT_COMPRESSION_API=0
SUPPORT_AUTOMATION_EVENTS=0
SUPPORT_CLIPBOARD_IMAGE=0
SUPPORT_FILEFORMAT_BMP=0
SUPPORT_FILEFORMAT_GIF=0
SUPPORT_FILEFORMAT_QOI=0
SUPPORT_FILEFORMAT_DDS=0
SUPPORT_FILEFORMAT_TTF=1
SUPPORT_FILEFORMAT_JPG=1
SUPPORT_FILEFORMAT_PNG=1
SUPPORT_FILEFORMAT_OGG=1
SUPPORT_MODULE_RAUDIO=1
)
target_compile_options(raylib PRIVATE
-Os
-ffunction-sections
-fdata-sections
)
target_include_directories(raylib PUBLIC
"${RAYLIB_DIR}"
"${NATIVE_APP_GLUE_DIR}"
)
add_library(main SHARED
main.c
pass_app.c
android_bridge.c
"${PASS_NATIVE_DIR}/pass_core.c"
"${PASS_EMBEDDED_ASSETS_C}"
${KRYON_SOURCES}
"${NATIVE_APP_GLUE_DIR}/android_native_app_glue.c"
)
target_include_directories(main PRIVATE
"${KRYON_DIR}/include"
"${KRYON_DIR}/src"
"${PASS_NATIVE_DIR}"
"${NATIVE_APP_GLUE_DIR}"
)
target_compile_definitions(main PRIVATE
PLATFORM_ANDROID
ANDROID_BUILD=1
_DEFAULT_SOURCE
_GNU_SOURCE
_FILE_OFFSET_BITS=64
UI_EMBEDDED_ONLY=1
KRYON_WITH_PHYSICS=0
)
target_compile_options(main PRIVATE
-Os
-ffunction-sections
-fdata-sections
-fvisibility=hidden
)
target_link_options(main PRIVATE
-Wl,--gc-sections
-Wl,--strip-all
-Wl,--wrap=fopen
-Wl,-z,max-page-size=16384
-Wl,-z,common-page-size=16384
)
target_link_libraries(main
raylib
android
log
OpenSLES
EGL
GLESv2
m
)
project(Werkzeug C ASM)
get_filename_component(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../.." ABSOLUTE)
set(ZIRAN "${REPO_ROOT}/scripts/ziran.sh")
if(DEFINED ENV{WERK_ZIRAN_COMMAND} AND NOT "$ENV{WERK_ZIRAN_COMMAND}" STREQUAL "")
get_filename_component(ZIRAN "$ENV{WERK_ZIRAN_COMMAND}" ABSOLUTE BASE_DIR "${REPO_ROOT}")
endif()
set(GENERATED "${CMAKE_BINARY_DIR}/ziran")
set(DEFINES --define ANDROID_BUILD --target-os android)
if(ANDROID_ABI STREQUAL "arm64-v8a")
list(APPEND DEFINES --define __aarch64__ --target-cpu arm64)
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
list(APPEND DEFINES --define __arm__ --target-cpu none)
elseif(ANDROID_ABI STREQUAL "x86_64")
list(APPEND DEFINES --define __x86_64__ --target-cpu x64)
elseif(ANDROID_ABI STREQUAL "x86")
list(APPEND DEFINES --define __i386__ --target-cpu none)
else()
message(FATAL_ERROR "Unsupported Android ABI: ${ANDROID_ABI}")
endif()
set(LOCK_FLAGS --locked)
if(EXISTS "${REPO_ROOT}/ziran.local.toml")
set(LOCK_FLAGS)
endif()
# Plain Gradle builds resolve the same packages as Make. F-Droid needs no
# source patches or machine-specific environment variables in its recipe.
function(werk_package variable package suffix)
if(NOT "$ENV{${variable}}" STREQUAL "")
set(path "$ENV{${variable}}")
else()
execute_process(COMMAND "${ZIRAN}" pkg path "${package}" ${LOCK_FLAGS}
WORKING_DIRECTORY "${REPO_ROOT}" OUTPUT_VARIABLE path
OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
string(APPEND path "${suffix}")
endif()
set(${variable} "${path}" CACHE PATH "Locked ${package} source" FORCE)
endfunction()
werk_package(KRYON_DIR kryon "")
werk_package(ZIRAN_ROOT ziran "")
werk_package(WEBP_DIR libwebp "")
werk_package(AVIF_DIR libavif "")
werk_package(AOM_DIR libaom "")
werk_package(LIBOQS_DIR liboqs "")
werk_package(MONOCYPHER_DIR monocypher "")
werk_package(WORKBOOK_DIR workbook "")
werk_package(TASKMGR_DIR taskmgr "")
file(GLOB_RECURSE SOURCE_INPUTS CONFIGURE_DEPENDS
"${REPO_ROOT}/src/*.zi" "${REPO_ROOT}/apps/gallery/*.zi" "${WORKBOOK_DIR}/src/*.zi" "${TASKMGR_DIR}/src/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock" "${REPO_ROOT}/scripts/runtime_cache.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SOURCE_INPUTS})
file(REMOVE_RECURSE "${GENERATED}")
execute_process(COMMAND "${ZIRAN}" build --project ${LOCK_FLAGS} ${DEFINES}
# NativeActivity and JNI callbacks are native linker roots.
--target=c --no-main -o "${GENERATED}" src/android_main.zi
"${KRYON_DIR}/src/backend/android_fopen.zi"
WORKING_DIRECTORY "${REPO_ROOT}" COMMAND_ERROR_IS_FATAL ANY)
file(GLOB GENERATED_SOURCES CONFIGURE_DEPENDS "${GENERATED}/*.c")
# Kryon's Android glue compiles its thread configurator with the same zi2c.
foreach(candidate "${ZIRAN_ROOT}/build/bin/zi2c" "${REPO_ROOT}/build/ziran-bootstrap/build/bin/zi2c")
if(NOT ZI2C_BIN AND EXISTS "${candidate}")
set(ZI2C_BIN "${candidate}")
endif()
endforeach()
include("${KRYON_DIR}/cmake/KryonAndroid.cmake")
kryon_android_codecs("${WEBP_DIR}" "${AVIF_DIR}" "${AOM_DIR}")
# The portable runtime that runs the app bundles, built from the locked Ziran
# for this ABI.
set(BUNDLE_RUNTIME_DIR "${CMAKE_BINARY_DIR}/bundle-runtime")
# Use the host's installed GNU Make, including an SDK-provided executable.
# All code generators run on the host; only runtime objects target the ABI.
find_program(WERK_MAKE_COMMAND NAMES make gmake REQUIRED)
execute_process(COMMAND "${WERK_MAKE_COMMAND}" -j4 -C "${ZIRAN_ROOT}"
"BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
"CC=${CMAKE_C_COMPILER} --target=${CMAKE_C_COMPILER_TARGET} --sysroot=${CMAKE_SYSROOT}"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}"
"GEN_ZI2C=${ZIRAN_ROOT}/build/bin/zi2c"
"CFLAGS=-O2 -fPIC" "FRAMEFLAGS=-Wframe-larger-than=16384"
"${BUNDLE_RUNTIME_DIR}/libziran.a"
COMMAND_ERROR_IS_FATAL ANY)
# Account sync: liboqs for ML-DSA-44 account keys, Monocypher for the rest.
set(OQS_BUILD_ONLY_LIB ON CACHE BOOL "" FORCE)
set(OQS_USE_OPENSSL OFF CACHE BOOL "" FORCE)
set(OQS_MINIMAL_BUILD "SIG_ml_dsa_44;KEM_ml_kem_768" CACHE STRING "" FORCE)
set(OQS_DIST_BUILD OFF CACHE BOOL "" FORCE)
set(OQS_OPT_TARGET generic CACHE STRING "" FORCE)
foreach(oqs_x86_feature
ADX AES AVX AVX2 AVX512 AVX512BW AVX512DQ AVX512F
BMI1 BMI2 FMA PCLMULQDQ POPCNT SSE SSE2 SSE3 VPCLMULQDQ)
set(OQS_USE_${oqs_x86_feature}_INSTRUCTIONS OFF CACHE BOOL "" FORCE)
endforeach()
add_subdirectory("${LIBOQS_DIR}" "${CMAKE_BINARY_DIR}/liboqs")
# JNI_OnLoad is discovered by Android's loader, outside the native entry graph.
set_source_files_properties("${GENERATED}/android_glue.c"
PROPERTIES COMPILE_OPTIONS "-fvisibility=default")
add_library(main SHARED ${GENERATED_SOURCES}
"${MONOCYPHER_DIR}/src/monocypher.c" "${MONOCYPHER_DIR}/src/optional/monocypher-ed25519.c")
target_compile_options(main PRIVATE "-iquote${GENERATED}")
target_include_directories(main PRIVATE "${ZIRAN_ROOT}/include"
"${MONOCYPHER_DIR}/src" "${MONOCYPHER_DIR}/src/optional")
target_link_libraries(main PRIVATE oqs z kryon_android_codecs)
kryon_android_app(main)
# Save hosted documents after the canonical NativeActivity loop returns.
target_link_options(main PRIVATE -Wl,--wrap=android_main)
target_link_libraries(main PRIVATE "${BUNDLE_RUNTIME_DIR}/libziran.a")
# Linker build IDs include debug-path differences even after stripping. The
# installed code is identical; omit this note for reproducible signed APKs.
# https://f-droid.org/docs/Reproducible_Builds/#ndk-build-id
target_link_options(main PRIVATE -Wl,--build-id=none)
# Werkzeug has no handwritten native sources; every app translation unit above is
# generated from .zi for this ABI. Kryon and the NDK own native_app_glue.
-492
View File
@@ -1,492 +0,0 @@
/* Minimal JNI bridge for the pass Android app: safe-area insets, display
* density, soft-keyboard visibility, and soft-keyboard text input. Modeled
* on inbe's android_device.c / android_insets.c. */
#include "android_bridge.h"
#if ANDROID_BUILD
#include "kryon.h"
#include "theme.h"
#include "ui_dpi.h"
#include <android/log.h>
#include <android_native_app_glue.h>
#include <jni.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
extern struct android_app *GetAndroidApp(void);
#ifndef JNI_VERSION_1_6
#define JNI_VERSION_1_6 0x10060000
#endif
#define LOG_TAG "PASS_JNI"
static pthread_mutex_t bridge_mutex = PTHREAD_MUTEX_INITIALIZER;
static int insets_status_bar = 0;
static int insets_nav_bar = 0;
static int insets_cutout_top = 0;
static int insets_cutout_bottom = 0;
static int insets_ready = 0;
static float device_density = 0.0f;
static int
scaled_inset(int java_px, float density)
{
if(density <= 0.0f)
density = 1.0f;
return (int)(java_px / density + 0.5f);
}
static int
activity_env(JNIEnv **env_out, JavaVM **jvm_out, jobject *activity_out)
{
struct android_app *app = GetAndroidApp();
JavaVM *jvm;
JNIEnv *env = NULL;
int attached = 0;
if(env_out == NULL || jvm_out == NULL || activity_out == NULL ||
app == NULL || app->activity == NULL || app->activity->vm == NULL ||
app->activity->clazz == NULL)
return -1;
jvm = app->activity->vm;
if((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
if((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK || env == NULL)
return -1;
attached = 1;
}
*env_out = env;
*jvm_out = jvm;
*activity_out = app->activity->clazz;
return attached;
}
static void
activity_env_done(JNIEnv *env, JavaVM *jvm, int attached)
{
if(env != NULL && (*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
if(attached && jvm != NULL)
(*jvm)->DetachCurrentThread(jvm);
}
void
android_bridge_init(void)
{
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = 0;
insets_nav_bar = 0;
insets_cutout_top = 0;
insets_cutout_bottom = 0;
insets_ready = 0;
device_density = 0.0f;
pthread_mutex_unlock(&bridge_mutex);
}
static Color
color_from_argb(jint argb)
{
Color color;
color.a = (unsigned char)((argb >> 24) & 0xff);
color.r = (unsigned char)((argb >> 16) & 0xff);
color.g = (unsigned char)((argb >> 8) & 0xff);
color.b = (unsigned char)(argb & 0xff);
if(color.a == 0)
color.a = 0xff;
return color;
}
void
android_bridge_apply_system_theme(void)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
jintArray array;
jint values[9];
jsize len;
int attached;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return;
memset(values, 0, sizeof(values));
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "systemThemeColors", "()[I");
if(method == NULL) {
__android_log_write(ANDROID_LOG_ERROR, LOG_TAG, "systemThemeColors not found");
goto done;
}
array = (jintArray)(*env)->CallObjectMethod(env, activity, method);
if(array == NULL)
goto done;
len = (*env)->GetArrayLength(env, array);
if(len < 9)
goto done;
(*env)->GetIntArrayRegion(env, array, 0, 9, values);
SetSystemThemePalette("Android",
color_from_argb(values[1]),
color_from_argb(values[2]),
color_from_argb(values[3]),
color_from_argb(values[4]),
color_from_argb(values[5]),
color_from_argb(values[6]),
color_from_argb(values[7]),
color_from_argb(values[8]),
values[0] != 0,
1);
done:
activity_env_done(env, jvm, attached);
}
int
android_bridge_top_reserved(void)
{
int status, cutout, top, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
status = insets_status_bar;
cutout = insets_cutout_top;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 28; /* conservative status-bar guess until Java reports */
top = status > cutout ? status : cutout;
return scaled_inset(top, density);
}
int
android_bridge_bottom_reserved(void)
{
int nav, cutout, bottom, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
nav = insets_nav_bar;
cutout = insets_cutout_bottom;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 48; /* conservative nav-bar guess until Java reports */
bottom = nav > cutout ? nav : cutout;
return scaled_inset(bottom, density);
}
void
android_bridge_set_soft_keyboard(int visible)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
int attached;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "setSoftKeyboardVisible", "(Z)V");
if(method == NULL) {
__android_log_write(ANDROID_LOG_ERROR, LOG_TAG, "setSoftKeyboardVisible not found");
goto done;
}
(*env)->CallVoidMethod(env, activity, method, visible ? JNI_TRUE : JNI_FALSE);
done:
activity_env_done(env, jvm, attached);
}
static int
call_boolean_method(const char *name)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
int attached;
int result = 0;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return 0;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, name, "()Z");
if(method == NULL)
goto done;
result = (*env)->CallBooleanMethod(env, activity, method) ? 1 : 0;
done:
activity_env_done(env, jvm, attached);
return result;
}
int
android_bridge_biometric_available(void)
{
return call_boolean_method("isBiometricAvailable");
}
int
android_bridge_biometric_setup_required(void)
{
return call_boolean_method("isBiometricSetupRequired");
}
int
android_bridge_master_saved(void)
{
return call_boolean_method("hasStoredMasterPassword");
}
int
android_bridge_master_biometric(void)
{
return call_boolean_method("isStoredMasterBiometric");
}
void
android_bridge_save_master(const char *master, int require_biometric)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
jstring jmaster;
int attached;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "saveMasterPassword", "(Ljava/lang/String;Z)V");
if(method == NULL)
goto done;
jmaster = (*env)->NewStringUTF(env, master != NULL ? master : "");
if(jmaster == NULL)
goto done;
(*env)->CallVoidMethod(env, activity, method, jmaster, require_biometric ? JNI_TRUE : JNI_FALSE);
(*env)->DeleteLocalRef(env, jmaster);
done:
activity_env_done(env, jvm, attached);
}
static void
call_void_method(const char *name)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
int attached;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, name, "()V");
if(method == NULL)
goto done;
(*env)->CallVoidMethod(env, activity, method);
done:
activity_env_done(env, jvm, attached);
}
void
android_bridge_unlock_master(void)
{
call_void_method("unlockMasterPassword");
}
void
android_bridge_clear_master(void)
{
call_void_method("clearMasterPassword");
}
int
android_bridge_secure_status(void)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
int attached;
int result = 0;
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return 0;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "secureMasterStatus", "()I");
if(method == NULL)
goto done;
result = (int)(*env)->CallIntMethod(env, activity, method);
done:
activity_env_done(env, jvm, attached);
return result;
}
int
android_bridge_take_secure_result(char *out, int out_size)
{
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
jstring result;
const char *chars;
int attached;
int status = 0;
if(out != NULL && out_size > 0)
out[0] = '\0';
attached = activity_env(&env, &jvm, &activity);
if(attached < 0)
return 0;
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "secureMasterStatus", "()I");
if(method == NULL)
goto done;
status = (int)(*env)->CallIntMethod(env, activity, method);
method = (*env)->GetMethodID(env, activity_class, "takeSecureMasterResult", "()Ljava/lang/String;");
if(method == NULL)
goto done;
result = (jstring)(*env)->CallObjectMethod(env, activity, method);
if(result == NULL)
goto done;
chars = (*env)->GetStringUTFChars(env, result, NULL);
if(chars != NULL) {
if(out != NULL && out_size > 0)
snprintf(out, (size_t)out_size, "%s", chars);
(*env)->ReleaseStringUTFChars(env, result, chars);
}
(*env)->DeleteLocalRef(env, result);
done:
activity_env_done(env, jvm, attached);
return status;
}
/* ---- Java -> C natives (exported JNI symbols; RegisterNatives from
* JNI_OnLoad resolves through the boot loader here and does not bind to the
* activity's class, so we rely on standard dlsym resolution instead) ---- */
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeSetInsets(JNIEnv *env, jobject thiz,
jint status_bar, jint nav_bar,
jint cutout_left, jint cutout_top,
jint cutout_right, jint cutout_bottom)
{
(void)env;
(void)thiz;
(void)cutout_left;
(void)cutout_right;
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = status_bar;
insets_nav_bar = nav_bar;
insets_cutout_top = cutout_top;
insets_cutout_bottom = cutout_bottom;
insets_ready = 1;
pthread_mutex_unlock(&bridge_mutex);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeSetDeviceDensity(JNIEnv *env, jobject thiz, jfloat density)
{
(void)env;
(void)thiz;
if(density <= 0.0f)
return;
pthread_mutex_lock(&bridge_mutex);
device_density = density;
pthread_mutex_unlock(&bridge_mutex);
SetUIDeviceDensity(density);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputCommit(JNIEnv *env, jobject thiz, jint codepoint)
{
(void)env;
(void)thiz;
QueueUITextInputCodepoint((int)codepoint);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputBackspace(JNIEnv *env, jobject thiz)
{
(void)env;
(void)thiz;
QueueUITextInputBackspace();
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputEnter(JNIEnv *env, jobject thiz)
{
(void)env;
(void)thiz;
QueueUITextInputEnter();
}
#else /* !ANDROID_BUILD */
void android_bridge_init(void) {}
void android_bridge_apply_system_theme(void) {}
int android_bridge_top_reserved(void) { return 0; }
int android_bridge_bottom_reserved(void) { return 0; }
void android_bridge_set_soft_keyboard(int visible) { (void)visible; }
int android_bridge_biometric_available(void) { return 0; }
int android_bridge_biometric_setup_required(void) { return 0; }
int android_bridge_master_saved(void) { return 0; }
int android_bridge_master_biometric(void) { return 0; }
void android_bridge_save_master(const char *master, int require_biometric) { (void)master; (void)require_biometric; }
void android_bridge_unlock_master(void) {}
void android_bridge_clear_master(void) {}
int android_bridge_secure_status(void) { return 0; }
int android_bridge_take_secure_result(char *out, int out_size) { if(out != NULL && out_size > 0) out[0] = '\0'; return 0; }
#endif
-35
View File
@@ -1,35 +0,0 @@
#ifndef PASS_ANDROID_BRIDGE_H
#define PASS_ANDROID_BRIDGE_H
#if defined(__cplusplus)
extern "C" {
#endif
/* Call once before InitWindow. */
void android_bridge_init(void);
void android_bridge_apply_system_theme(void);
/* Safe-area insets converted to UI units (java px / density). Returns 0
* until Java has reported real values; callers should treat 0 as "unknown"
* and keep a conservative margin. */
int android_bridge_top_reserved(void);
int android_bridge_bottom_reserved(void);
/* Shows or hides the soft keyboard through the activity. */
void android_bridge_set_soft_keyboard(int visible);
int android_bridge_biometric_available(void);
int android_bridge_biometric_setup_required(void);
int android_bridge_master_saved(void);
int android_bridge_master_biometric(void);
void android_bridge_save_master(const char *master, int require_biometric);
void android_bridge_unlock_master(void);
void android_bridge_clear_master(void);
int android_bridge_secure_status(void);
int android_bridge_take_secure_result(char *out, int out_size);
#if defined(__cplusplus)
}
#endif
#endif
-132
View File
@@ -1,132 +0,0 @@
/* Android entry point for pass. Raylib's Android backend provides
* android_main and calls main(); this file owns window, theme, fonts, and
* the frame loop. */
#include "kryon.h"
#include "embedded_assets.h"
#include "ui_dpi.h"
#include "ui_core.h"
#include "ui_scaling.h"
#include "ui_text.h"
#include "android_bridge.h"
#include "pass_app.h"
#include <stdio.h>
#include <string.h>
#if ANDROID_BUILD
#include <android/log.h>
#include <unistd.h>
#endif
static const char *const FONT_ASSET_PATH = "vendor/kryon/fonts/noto/NotoSans-Regular.ttf";
static const char *const EMOJI_FONT_ASSET_PATH = "gui/assets/emoji.ttf";
/* Kryon's shape drawing rides on a 1x1 white texture so rectangles tint
* cleanly on the GL ES surface (same setup inbe performs on Android). */
static void
setup_shapes_texture(void)
{
Image white = GenImageColor(1, 1, WHITE);
Texture2D texture = LoadTextureFromImage(white);
UnloadImage(white);
if(texture.id == 0)
return;
SetTextureFilter(texture, TEXTURE_FILTER_POINT);
SetShapesTexture(texture, (Rectangle){0.0f, 0.0f, 1.0f, 1.0f});
}
static int
setup_ui_font(void)
{
const EmbeddedAsset *asset = GetEmbeddedAsset(FONT_ASSET_PATH);
if(asset == NULL || asset->data == NULL || asset->size == 0) {
TraceLog(LOG_WARNING, "PASS: missing embedded font asset");
return 0;
}
if(!RegisterUIFontSource("ui", GetEmbeddedAssetExtension(FONT_ASSET_PATH),
asset->data, asset->size, NULL, 0)) {
TraceLog(LOG_WARNING, "PASS: RegisterUIFontSource failed");
return 0;
}
if(!UseUIFont("ui")) {
TraceLog(LOG_WARNING, "PASS: UseUIFont failed");
return 0;
}
return 1;
}
static int
setup_emoji_font(void)
{
const EmbeddedAsset *asset = GetEmbeddedAsset(EMOJI_FONT_ASSET_PATH);
int codepoint_count = 0;
const int *codepoints = pass_app_master_emoji_codepoints(&codepoint_count);
if(asset == NULL || asset->data == NULL || asset->size == 0) {
TraceLog(LOG_WARNING, "PASS: missing embedded emoji font asset");
return 0;
}
if(!RegisterUIFixedFontSource("pass-emoji", GetEmbeddedAssetExtension(EMOJI_FONT_ASSET_PATH),
asset->data, asset->size, codepoints, codepoint_count)) {
TraceLog(LOG_WARNING, "PASS: RegisterUIFixedFontSource failed for emoji");
return 0;
}
return 1;
}
int
main(int argc, char **argv)
{
PassApp *app;
(void)argc;
(void)argv;
#if ANDROID_BUILD
__android_log_write(ANDROID_LOG_INFO, "PASS_MAIN", "main start");
android_bridge_init();
if(chdir("/data/user/0/xyz.waozi.pass/files") != 0)
TraceLog(LOG_WARNING, "PASS: failed to switch to files directory");
#endif
InitWindow(0, 0, "pass");
if(!IsWindowReady()) {
TraceLog(LOG_ERROR, "PASS: InitWindow failed");
return 1;
}
InitUIDPI();
SetThemeStyle(THEME_STYLE_MATERIAL);
SetCurrentTheme(GetDefaultThemeForThemeStyle(THEME_STYLE_MATERIAL), 0);
android_bridge_apply_system_theme();
SetThemeSource(THEME_SOURCE_SYSTEM);
SetThemeMode(THEME_MODE_SYSTEM);
setup_ui_font();
setup_emoji_font();
setup_shapes_texture();
SetUITextInputPlatformCallback(android_bridge_set_soft_keyboard);
SetTargetFPS(60);
app = pass_app();
while(!WindowShouldClose()) {
int width = GetScreenWidth();
int height = GetScreenHeight();
Vector2 scale = GetWindowScaleDPI();
float dpi = scale.x > 0.0f ? scale.x : 1.0f;
BeginDrawing();
BeginUIFrame(width, height, dpi);
pass_app_draw(app, width, height, dpi,
android_bridge_top_reserved(),
android_bridge_bottom_reserved());
EndUIFrame();
EndDrawing();
}
pass_app_shutdown(app);
CloseWindow();
return 0;
}
File diff suppressed because it is too large. Load diff
-17
View File
@@ -1,17 +0,0 @@
#ifndef PASS_APP_H
#define PASS_APP_H
typedef struct PassApp PassApp;
PassApp *pass_app(void);
const int *pass_app_master_emoji_codepoints(int *count);
/* Draws one frame. Surface sizes are physical pixels; dpi is the display
* scale. top/bottom_reserved are safe-area insets in UI units (dp). */
void pass_app_draw(PassApp *app, int surface_w, int surface_h, float dpi,
int top_reserved, int bottom_reserved);
/* Clears secrets held in memory. */
void pass_app_shutdown(PassApp *app);
#endif
@@ -1,498 +0,0 @@
package xyz.waozi.pass;
import android.app.NativeActivity;
import android.app.KeyguardManager;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Insets;
import android.hardware.biometrics.BiometricPrompt;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.TypedValue;
import android.view.DisplayCutout;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.concurrent.Executor;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
/**
* NativeActivity glue for the kryon UI: routes soft-keyboard input and
* window insets to the native side. Modeled on inbe's MainActivity.
*/
public class MainActivity extends NativeActivity {
private static final String SECURE_PREFS = "pass_secure";
private static final String KEY_ALIAS = "pass_master_key";
private static final String PREF_CIPHERTEXT = "master_ciphertext";
private static final String PREF_IV = "master_iv";
private static final String PREF_BIOMETRIC = "master_biometric";
private static final int SECURE_IDLE = 0;
private static final int SECURE_PENDING = 1;
private static final int SECURE_OK = 2;
private static final int SECURE_ERROR = 3;
static {
// Associate libmain with this class's loader so ART can resolve the
// native methods below (NativeActivity loads it via the boot loader).
System.loadLibrary("main");
}
private int lastDeleteRepeatCount = -1;
private final Object secureLock = new Object();
private int secureStatus = SECURE_IDLE;
private String secureResult = "";
private native void nativeSetInsets(int status, int nav,
int cutoutLeft, int cutoutTop, int cutoutRight, int cutoutBottom);
private native void nativeSetDeviceDensity(float density);
private native void nativeTextInputCommit(int codepoint);
private native void nativeTextInputBackspace();
private native void nativeTextInputEnter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applySystemBars();
setupInsetsListener();
}
public int[] systemThemeColors() {
boolean dark = (getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
int background = dark ? 0xFF141218 : 0xFFFFFBFE;
int surface = dark ? 0xFF211F26 : 0xFFF7F2FA;
int text = dark ? 0xFFE6E0E9 : 0xFF1D1B20;
int accent = resolveThemeColor(android.R.attr.colorAccent,
dark ? 0xFFD0BCFF : 0xFF6750A4);
int control = dark ? 0xFFE6E0E9 : 0xFF1D1B20;
int button = blend(accent, background, dark ? 65 : 80);
int buttonHover = blend(accent, background, dark ? 45 : 60);
return new int[] {
dark ? 1 : 0,
background,
surface,
text,
accent,
button,
buttonHover,
control,
accent
};
}
private void applySystemBars() {
int[] colors = systemThemeColors();
boolean dark = colors[0] != 0;
getWindow().setStatusBarColor(colors[1]);
getWindow().setNavigationBarColor(colors[1]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = getWindow().getDecorView().getSystemUiVisibility();
if (!dark) {
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
}
} else {
flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
}
}
getWindow().getDecorView().setSystemUiVisibility(flags);
}
}
private int resolveThemeColor(int attr, int fallback) {
TypedValue value = new TypedValue();
if (!getTheme().resolveAttribute(attr, value, true)) {
return fallback;
}
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
&& value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
return value.data;
}
if (value.resourceId != 0) {
try {
ColorStateList list;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
list = getResources().getColorStateList(value.resourceId, getTheme());
} else {
list = getResources().getColorStateList(value.resourceId);
}
if (list != null) {
return list.getDefaultColor();
}
} catch (Exception ignored) {
}
}
return fallback;
}
private static int blend(int from, int to, int percentTo) {
int p = Math.max(0, Math.min(100, percentTo));
int a = (((from >>> 24) & 0xff) * (100 - p) + ((to >>> 24) & 0xff) * p) / 100;
int r = (((from >>> 16) & 0xff) * (100 - p) + ((to >>> 16) & 0xff) * p) / 100;
int g = (((from >>> 8) & 0xff) * (100 - p) + ((to >>> 8) & 0xff) * p) / 100;
int b = ((from & 0xff) * (100 - p) + (to & 0xff) * p) / 100;
return (a << 24) | (r << 16) | (g << 8) | b;
}
public boolean hasStoredMasterPassword() {
SharedPreferences prefs = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE);
return prefs.contains(PREF_CIPHERTEXT) && prefs.contains(PREF_IV);
}
public boolean isStoredMasterBiometric() {
return getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).getBoolean(PREF_BIOMETRIC, false);
}
@SuppressWarnings("deprecation")
public boolean isBiometricAvailable() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
try {
FingerprintManager fm = (FingerprintManager)getSystemService(Context.FINGERPRINT_SERVICE);
if (fm != null && fm.isHardwareDetected() && fm.hasEnrolledFingerprints()) return true;
} catch (SecurityException ignored) {
}
return false;
}
@SuppressWarnings("deprecation")
public boolean isBiometricSetupRequired() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
try {
FingerprintManager fm = (FingerprintManager)getSystemService(Context.FINGERPRINT_SERVICE);
if (fm == null || !fm.isHardwareDetected()) return false;
KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
return !fm.hasEnrolledFingerprints() || km == null || !km.isDeviceSecure();
} catch (SecurityException ignored) {
return false;
}
}
private String biometricUnavailableMessage() {
if (isBiometricSetupRequired()) {
return "Set up Android screen lock and fingerprint first";
}
return "Biometric unlock is not available on this device";
}
public int secureMasterStatus() {
synchronized (secureLock) {
return secureStatus;
}
}
public String takeSecureMasterResult() {
synchronized (secureLock) {
String value = secureResult == null ? "" : secureResult;
secureResult = "";
secureStatus = SECURE_IDLE;
return value;
}
}
public void saveMasterPassword(final String master, final boolean requireBiometric) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (master == null || master.length() == 0) {
setSecureError("Enter a master password first");
return;
}
if (requireBiometric && !isBiometricAvailable()) {
setSecureError(biometricUnavailableMessage());
return;
}
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateMasterKey());
byte[] encrypted = cipher.doFinal(master.getBytes(StandardCharsets.UTF_8));
byte[] iv = cipher.getIV();
if (iv == null || iv.length == 0) {
setSecureError("Save failed: missing encryption IV");
return;
}
SharedPreferences.Editor editor = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).edit();
editor.putString(PREF_IV, b64(iv));
editor.putString(PREF_CIPHERTEXT, b64(encrypted));
editor.putBoolean(PREF_BIOMETRIC, requireBiometric);
editor.apply();
setSecureOk("Master password saved");
} catch (Exception e) {
setSecureError("Save failed: " + e.getMessage());
}
}
});
}
public void unlockMasterPassword() {
if (!hasStoredMasterPassword()) {
setSecureError("No saved master password");
return;
}
if (isStoredMasterBiometric()) {
authenticateThenDecrypt();
return;
}
decryptStoredMaster();
}
public void clearMasterPassword() {
getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).edit().clear().apply();
setSecureOk("Saved master password removed");
}
private void authenticateThenDecrypt() {
if (!isBiometricAvailable()) {
setSecureError(biometricUnavailableMessage());
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
setSecureError("Biometric prompt requires Android 9 or newer");
return;
}
synchronized (secureLock) {
secureStatus = SECURE_PENDING;
secureResult = "Waiting for biometric unlock";
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
runOnUiThread(command);
}
};
BiometricPrompt prompt = new BiometricPrompt.Builder(MainActivity.this)
.setTitle("Unlock master password")
.setSubtitle("Use your fingerprint or device credential")
.setDescription("pass will decrypt the saved master password after unlock")
.setNegativeButton("Cancel", executor, (dialog, which) -> setSecureError("Unlock canceled"))
.build();
prompt.authenticate(new CancellationSignal(), executor,
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
decryptStoredMaster();
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
setSecureError(errString == null ? "Unlock failed" : errString.toString());
}
@Override
public void onAuthenticationFailed() {
setSecureError("Biometric unlock failed");
}
});
}
});
}
private void decryptStoredMaster() {
try {
SharedPreferences prefs = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE);
String ivText = prefs.getString(PREF_IV, "");
String encryptedText = prefs.getString(PREF_CIPHERTEXT, "");
if (ivText.length() == 0 || encryptedText.length() == 0) {
setSecureError("No saved master password");
return;
}
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, getOrCreateMasterKey(), new GCMParameterSpec(128, unb64(ivText)));
byte[] decrypted = cipher.doFinal(unb64(encryptedText));
setSecureOk(new String(decrypted, StandardCharsets.UTF_8));
} catch (Exception e) {
setSecureError("Unlock failed: " + e.getMessage());
}
}
private SecretKey getOrCreateMasterKey() throws Exception {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (keyStore.containsAlias(KEY_ALIAS)) {
return (SecretKey)keyStore.getKey(KEY_ALIAS, null);
}
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(true)
.build();
generator.init(spec);
return generator.generateKey();
}
private void setSecureOk(String value) {
synchronized (secureLock) {
secureStatus = SECURE_OK;
secureResult = value == null ? "" : value;
}
}
private void setSecureError(String value) {
synchronized (secureLock) {
secureStatus = SECURE_ERROR;
secureResult = value == null ? "Secure storage failed" : value;
}
}
private static String b64(byte[] data) {
return android.util.Base64.encodeToString(data, android.util.Base64.NO_WRAP);
}
private static byte[] unb64(String text) {
return android.util.Base64.decode(text, android.util.Base64.NO_WRAP);
}
public void setSoftKeyboardVisible(final boolean visible) {
runOnUiThread(new Runnable() {
@Override
public void run() {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getWindow() != null ? getWindow().getDecorView() : null;
if (imm == null || view == null) return;
if (visible) {
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_DEL) {
int repeatCount = event.getRepeatCount();
int deleteCount = lastDeleteRepeatCount < 0
? 1
: Math.max(1, repeatCount - lastDeleteRepeatCount);
lastDeleteRepeatCount = repeatCount;
for (int i = 0; i < deleteCount; i++) {
nativeTextInputBackspace();
}
} else if (keyCode == KeyEvent.KEYCODE_ENTER ||
keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
lastDeleteRepeatCount = -1;
nativeTextInputEnter();
} else {
lastDeleteRepeatCount = -1;
int unicode = event.getUnicodeChar();
if (unicode >= 32) {
nativeTextInputCommit(unicode);
}
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
lastDeleteRepeatCount = -1;
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_MULTIPLE &&
event.getCharacters() != null) {
lastDeleteRepeatCount = -1;
String chars = event.getCharacters();
for (int i = 0; i < chars.length();) {
int codepoint = chars.codePointAt(i);
if (codepoint >= 32) {
nativeTextInputCommit(codepoint);
}
i += Character.charCount(codepoint);
}
}
return super.dispatchKeyEvent(event);
}
private void setupInsetsListener() {
final View decorView = getWindow().getDecorView();
nativeSetDeviceDensity(getResources().getDisplayMetrics().density);
decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
updateInsets(insets);
return insets;
}
});
// Startup safety net: catch the initial layout pass.
decorView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
WindowInsets insets = decorView.getRootWindowInsets();
if (insets != null) {
updateInsets(insets);
}
}
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
decorView.post(new Runnable() {
@Override
public void run() {
decorView.requestApplyInsets();
}
});
}
private void updateInsets(WindowInsets insets) {
if (insets == null) return;
nativeSetDeviceDensity(getResources().getDisplayMetrics().density);
int statusBar = 0;
int navBar = 0;
int cLeft = 0, cTop = 0, cRight = 0, cBottom = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Insets systemBars = insets.getInsetsIgnoringVisibility(
WindowInsets.Type.systemBars());
statusBar = systemBars.top;
navBar = systemBars.bottom;
} else {
statusBar = insets.getSystemWindowInsetTop();
navBar = insets.getSystemWindowInsetBottom();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
DisplayCutout cutout = insets.getDisplayCutout();
if (cutout != null) {
cLeft = cutout.getSafeInsetLeft();
cTop = cutout.getSafeInsetTop();
cRight = cutout.getSafeInsetRight();
cBottom = cutout.getSafeInsetBottom();
}
}
nativeSetInsets(statusBar, navBar, cLeft, cTop, cRight, cBottom);
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 25 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">pass</string>
<string name="app_name">Werkzeug</string>
</resources>
+1 -1
View File
@@ -13,5 +13,5 @@ dependencyResolutionManagement {
}
}
rootProject.name = "pass"
rootProject.name = "werk"
include ':app'
@@ -0,0 +1 @@
Initial release: deterministic, LessPass-compatible password generation with configurable length, counter, character classes, and excluded characters. Everything is computed locally; nothing is stored or uploaded.
@@ -0,0 +1,2 @@
- Keep bottom navigation, password controls, and dialog icons readable with dark tints in light mode and light tints in dark mode.
- Prevent taps in Theme Settings from reaching fields underneath or opening the keyboard when saving the theme.
@@ -0,0 +1 @@
- Introduce the purple password asterisk and keyhole logo across Pass, website icons, Android launchers, and app listings.
@@ -0,0 +1,5 @@
- Pass is now Werkzeug: a home screen of small private tools, each its own app and all preinstalled.
- A new logo: a wrench with a keyhole. The website moves to werk.waozi.xyz.
- Add Auth for two-factor sign-in codes from otpauth links or secret keys; copied codes clear after 30 seconds.
- Add Calculator, and Clock with a stopwatch.
- Add a profile with your name, a picture and the appearance every tool shares.
@@ -0,0 +1 @@
- Fix the web version on itch.io, which opened to a blank page.
@@ -0,0 +1,6 @@
- A new purple W logo.
- Calculator gets a Scientific mode.
- Auth imports Google Authenticator, Aegis and Ente Auth exports.
- Rename an Auth account, note its websites, or remove it.
- Choose your own Daochi node, and pause sync without losing your account.
- Show π, √ and other symbols on phones older than Android 10.
@@ -0,0 +1,3 @@
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
- Tool windows show their own names and icons in the desktop switcher.
@@ -0,0 +1,2 @@
- Linux packages include the libraries needed for sync and importing QR-code pictures.
- Packaging a new AppImage preserves previous downloads.
@@ -0,0 +1,2 @@
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
@@ -0,0 +1,2 @@
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
@@ -0,0 +1 @@
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
@@ -0,0 +1 @@
New clipboard handling, vault support, and named profiles in the CLI, plus self-update checks in the desktop app. Android keeps the same local, stateless generator.
@@ -0,0 +1 @@
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
@@ -0,0 +1,2 @@
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
@@ -0,0 +1,2 @@
- Install pass on Android: a signed APK is now downloadable from pass.waozi.xyz alongside the desktop, terminal, and browser downloads.
- Fix the Android master-password fingerprint and secure storage so the stored master password unlocks reliably across launches.
@@ -0,0 +1,2 @@
- Verify every download: releases now ship a SHA256SUMS file covering the command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing key, clearing the way for F-Droid distribution.
@@ -0,0 +1,6 @@
- Save and reuse Android master-password defaults with fingerprint unlock.
- Clear unlocked master text and generated passwords after a timeout.
- Autosave length, counter, character classes, excluded characters, and biometric display settings.
- Keep Android fields visible while the keyboard is open.
- Run the real Pass app at pass.waozi.xyz/app.
- Publish universal and per-ABI Android APKs.
@@ -0,0 +1,3 @@
- Add Android appearance settings for following device colors, choosing light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and landscape, keeping controls clear of system bars and navigation insets.
@@ -0,0 +1 @@
- Keep Android source builds self-contained so F-Droid and other source builds generate the Kry app sources automatically.
@@ -0,0 +1 @@
- Fix Android source builds in stricter environments such as F-Droid builders while keeping Kry app source generation automatic.
@@ -0,0 +1,4 @@
- Match LessPass clients for the same site, login, master password, counter, character classes, and length settings.
- Limit password length to LessPass's 5 to 35 character range.
- Require Android fingerprint unlock for saved master passwords and store them with an authenticated Android Keystore key.
- Use the Sweet Material palette by default, with Sweet-Dark matched colors in dark mode, and show generated passwords in a dedicated output field.
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff. Show more