diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0333d90..2908c75 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,9 @@ jobs: tag_name: tag, name: `JSONPrism ${tag}`, body: [ - 'Native desktop builds for Windows, macOS, and Linux.', + 'Native desktop builds for Windows, macOS, and Linux, plus an Android APK (sideload, Android 12+).', + '', + 'Android: download the `.apk`, then enable "install unknown apps" for your browser/file manager to sideload.', '', 'See the [CHANGELOG](https://github.com/poli0981/jsonPrism/blob/main/CHANGELOG.md) for details.', ].join('\n'), @@ -118,3 +120,102 @@ jobs: # duplicate drafts + split assets). The maintainer un-drafts manually. releaseId: ${{ needs.create-release.outputs.release_id }} args: ${{ matrix.platform.args }} + + # Android is built separately: tauri-action does not build mobile targets, so + # this job drives the Tauri CLI directly (Java + Android SDK/NDK + Rust android + # targets), signs with the release keystore from secrets, and uploads the + # universal APK into the same draft release as the desktop bundles. + # + # Requires these repository secrets (see docs/TAURI-NOTES.md): + # ANDROID_KEYSTORE_BASE64 base64 of upload-keystore.jks + # ANDROID_KEYSTORE_PASSWORD the keystore (store) password + # ANDROID_KEY_PASSWORD the key password (optional; defaults to store password) + # ANDROID_KEY_ALIAS the key alias (optional; defaults to "upload") + android: + name: Build · Android (APK) + needs: create-release + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup Java 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Setup Android SDK + uses: android-actions/setup-android@v3 + + - name: Install SDK platform + NDK + run: | + sdkmanager "platforms;android-36" "ndk;27.2.12479018" + echo "NDK_HOME=$ANDROID_HOME/ndk/27.2.12479018" >> "$GITHUB_ENV" + + - name: Setup Rust (stable) + Android targets + uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android + + - name: Cache Cargo build artifacts + uses: swatinem/rust-cache@v2 + with: + workspaces: './src-tauri -> target' + key: android + + - name: Setup Node 22 + uses: actions/setup-node@v6 + with: + node-version: 22.x + cache: npm + + - name: Install npm dependencies + run: npm ci --no-audit --no-fund + + - name: Generate icons + run: npm run tauri:icon + + - name: Decode release keystore + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + run: | + if [ -z "$ANDROID_KEYSTORE_BASE64" ]; then + echo "::error::ANDROID_KEYSTORE_BASE64 secret is not set — cannot sign the release APK." + exit 1 + fi + KEYSTORE_PATH="$RUNNER_TEMP/upload-keystore.jks" + echo "$ANDROID_KEYSTORE_BASE64" | base64 -d > "$KEYSTORE_PATH" + { + echo "storePassword=$ANDROID_KEYSTORE_PASSWORD" + echo "keyPassword=${ANDROID_KEY_PASSWORD:-$ANDROID_KEYSTORE_PASSWORD}" + echo "keyAlias=${ANDROID_KEY_ALIAS:-upload}" + echo "storeFile=$KEYSTORE_PATH" + } > src-tauri/gen/android/keystore.properties + + - name: Build signed universal APK + run: npm run tauri -- android build --apk + + - name: Upload APK to release + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const tag = context.ref.replace('refs/tags/', '').replace('refs/heads/', ''); + const dir = 'src-tauri/gen/android/app/build/outputs/apk/universal/release'; + const apks = fs.readdirSync(dir).filter((f) => f.endsWith('.apk')); + if (apks.length === 0) throw new Error(`No APK found in ${dir}`); + const src = `${dir}/${apks[0]}`; + const name = `JSONPrism-${tag}-android-universal.apk`; + await github.rest.repos.uploadReleaseAsset({ + owner: context.repo.owner, + repo: context.repo.repo, + release_id: ${{ needs.create-release.outputs.release_id }}, + name, + data: fs.readFileSync(src), + }); + core.info(`Uploaded ${name} from ${src}`); diff --git a/.gitignore b/.gitignore index adb1249..d6732da 100644 --- a/.gitignore +++ b/.gitignore @@ -32,13 +32,19 @@ dist-ssr # Tauri (Phase 2C) src-tauri/target -src-tauri/gen +# gen/android is committed (source). Build outputs inside it are ignored by its own +# nested .gitignore files. Only the generated JSON schemas are ignored here. +src-tauri/gen/schemas src-tauri/icons/*.png src-tauri/icons/*.ico src-tauri/icons/*.icns src-tauri/icons/android/ src-tauri/icons/ios/ +# Android signing keystore — never commit the keystore binary. +*.jks +*.keystore + # Test artifacts coverage .nyc_output diff --git a/README.md b/README.md index 5cc3e99..b092a72 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,43 @@ Output: **Automated releases**: pushing a `v*` tag triggers `.github/workflows/release.yml`, which builds for all platforms in parallel and creates a draft GitHub release. +## Android app (Tauri 2) + +JSONPrism also ships as an Android app you sideload from a `.apk`. Same React UI; native file picker via the dialog plugin. **Requires Android 12 (API 31) or newer** — the OS refuses to install it on older versions. + +### Install (users) + +1. Download `JSONPrism--android-universal.apk` from the [Releases](https://github.com/poli0981/jsonPrism/releases) page. +2. Open it; Android will ask you to allow "install unknown apps" for your browser/file manager — enable it, then install. +3. Needs Android 12+. The app runs fully offline. + +### Build (developers) + +**Additional requirements** (on top of the desktop Rust toolchain): + +- **Android Studio** with SDK Platform **31+**, Build-Tools, Platform-Tools, Command-line Tools, and an **NDK** +- **JDK** — the JBR bundled with Android Studio is fine +- Environment variables: `JAVA_HOME`, `ANDROID_HOME`, `NDK_HOME` (see [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md)) +- Rust Android targets: `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android` + +The Android Gradle project lives in `src-tauri/gen/android/` and is committed. You do **not** need to run `tauri android init` for a normal build. + +**Run on a device/emulator** (Android 12+): + +```bash +npm run tauri:android:dev +``` + +**Build a universal release APK**: + +```bash +npm run tauri:android:build +``` + +Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Release signing is read from `src-tauri/gen/android/keystore.properties` (gitignored); without it the APK builds unsigned. See [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) for keystore setup and the CI signing secrets. + +**Automated releases**: the same `v*` tag also runs the `android` job in `release.yml`, which signs the APK with the keystore from repository secrets and attaches it to the draft release. + ### Scripts | Script | What it does | diff --git a/README.vi.md b/README.vi.md index ef2e5ad..23b6e43 100644 --- a/README.vi.md +++ b/README.vi.md @@ -105,6 +105,43 @@ Output: **Release tự động**: push tag `v*` sẽ trigger `.github/workflows/release.yml`, build cho tất cả platform song song và tạo draft GitHub release. +## Bản Android (Tauri 2) + +JSONPrism còn có bản Android để bạn sideload từ file `.apk`. Cùng React UI; chọn file qua dialog native. **Yêu cầu Android 12 (API 31) trở lên** — máy cũ hơn sẽ bị hệ điều hành chặn cài. + +### Cài đặt (người dùng) + +1. Tải `JSONPrism--android-universal.apk` từ trang [Releases](https://github.com/poli0981/jsonPrism/releases). +2. Mở file; Android sẽ hỏi cho phép "cài app không rõ nguồn" cho trình duyệt/trình quản lý file — bật lên rồi cài. +3. Cần Android 12+. App chạy hoàn toàn offline. + +### Build (lập trình viên) + +**Yêu cầu thêm** (ngoài Rust toolchain của bản desktop): + +- **Android Studio** với SDK Platform **31+**, Build-Tools, Platform-Tools, Command-line Tools và một bản **NDK** +- **JDK** — dùng JBR đi kèm Android Studio là được +- Biến môi trường: `JAVA_HOME`, `ANDROID_HOME`, `NDK_HOME` (xem [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md)) +- Rust Android targets: `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android` + +Project Gradle nằm ở `src-tauri/gen/android/` và đã được commit. Bạn **không** cần chạy `tauri android init` cho build thường. + +**Chạy trên thiết bị/emulator** (Android 12+): + +```bash +npm run tauri:android:dev +``` + +**Build APK release universal**: + +```bash +npm run tauri:android:build +``` + +Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Thông tin ký lấy từ `src-tauri/gen/android/keystore.properties` (gitignored); thiếu file này thì APK build ra chưa ký. Xem [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) để biết cách tạo keystore và các secret ký trong CI. + +**Release tự động**: cùng tag `v*` cũng chạy job `android` trong `release.yml`, ký APK bằng keystore từ repository secrets và đính vào draft release. + ### Các script | Script | Chức năng | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 92a7fd5..b865e4a 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -259,6 +259,34 @@ Compliance + reliability + first-paint performance. No converter behavior change --- +## Phase 7 — Android (sideload APK) 🔜 + +**Status**: in progress + +Goal: ship JSONPrism as an Android app users sideload from a `.apk`. Same React UI, no behavior change to the converters. **Minimum Android 12 (API 31)** — older devices are blocked by the OS. + +### Tasks + +- [x] `bundle.android` in `tauri.conf.json`: `minSdkVersion: 31`, deterministic `versionCode` (`MAJOR*10000+MINOR*100+PATCH`) +- [x] `tauri android init` → Android Gradle project at `src-tauri/gen/android/`, **committed** (source only; build outputs + secrets gitignored via nested + root `.gitignore`) +- [x] Verified `minSdk = 31` propagated to `app/build.gradle.kts`; Rust compiles for all 4 ABIs (validated against NDK r27/r30) +- [x] Release signing wired in `app/build.gradle.kts` from a gitignored `keystore.properties` (graceful unsigned fallback when absent) +- [x] Self-hosted fonts via `@fontsource` (Geist / Instrument Serif / JetBrains Mono) — removed Google Fonts ``, tightened CSP, app renders correctly **offline** +- [x] Local scripts: `tauri:android:init` / `tauri:android:dev` / `tauri:android:build` (universal APK; chains `tauri:icon`) +- [x] CI: `android` job in `release.yml` builds + signs (keystore from secrets) + uploads the universal APK to the same draft release +- [x] Docs: README / README.vi "Android" sections + maintainer notes in `docs/TAURI-NOTES.md` +- [x] Emulator-validated: signed APK installs on Android 12+, **blocked on API < 31** (`INSTALL_FAILED_OLDER_SDK`), launches, renders (CodeMirror + self-hosted fonts), runs converters, fully offline +- [x] Native file open works — `plugin-dialog` fires the SAF picker, `plugin-fs` reads the `content://` URI; `basenameFromPath()` recovers a clean filename (unit-tested) +- [x] Found: layout needs WebView **Chromium ≥ 111** (Tailwind v4); fine on updated Android 12+ devices, broken on the API 31 emulator's stock Chromium 91 — see `docs/TAURI-NOTES.md` +- [ ] Add CI signing secrets (`ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, …) — maintainer action +- [ ] Remaining manual checks: save `.zip` via SAF, all 12 converters end-to-end, theme + 4 locales, upgrade-in-place on a real device + +### Deliverable + +A signed universal `.apk` attached to each GitHub release, installable on Android 12+. Same converter feature set as web/desktop, fully offline. + +--- + ## Beyond — Ideas (no commitment) - **JSON → Excel (.xlsx)** via SheetJS — possible if Markdown/CSV doesn't cover the use case diff --git a/docs/TAURI-NOTES.md b/docs/TAURI-NOTES.md index 5972fba..a92f494 100644 --- a/docs/TAURI-NOTES.md +++ b/docs/TAURI-NOTES.md @@ -61,3 +61,155 @@ Widening the scope requires both a capability edit and a CSP review in The release matrix in `.github/workflows/release.yml` builds all four combinations (Linux, macOS Intel, macOS Apple Silicon, Windows) on a `v*` tag push. + +## Android (sideload APK) + +JSONPrism ships an Android APK that users sideload. **Minimum Android 12 +(API 31)** — set via `bundle.android.minSdkVersion` in `tauri.conf.json`; the +OS installer refuses older devices. The build target is a **universal APK** +(all ABIs in one file) so users only ever download one `.apk`. + +### Toolchain (local, Windows) + +Environment variables Tauri's CLI reads: + +- `JAVA_HOME` → Android Studio's JBR, e.g. `C:\Jetbrains\Android Studio\jbr` +- `ANDROID_HOME` → `C:\Users\\AppData\Local\Android\Sdk` +- `NDK_HOME` → `…\Android\Sdk\ndk\` + +Rust targets: `rustup target add aarch64-linux-android armv7-linux-androideabi +i686-linux-android x86_64-linux-android`. Verify with `npm run tauri info`. + +> **NDK selection.** The CLI auto-picks the **highest** NDK under +> `$ANDROID_HOME/ndk`, regardless of `NDK_HOME`. If you keep multiple NDKs and +> want a specific one, leave only that version installed. Builds are validated +> against NDK r27+; CI pins `ndk;27.2.12479018`. + +### The `gen/android` project + +`src-tauri/gen/android/` (the Gradle project from `tauri android init`) is +**committed** — source only. Its nested `.gitignore` files exclude build +outputs (`build/`, `.gradle/`, `.cxx/`, `*.so`, `local.properties`, +`keystore.properties`). Committing it keeps the signing edits in +`app/build.gradle.kts` and `minSdkVersion` stable, and makes CI reproducible. + +You normally do **not** run `tauri android init` again. Only re-run it after a +major `@tauri-apps/cli` bump, and re-apply the signing block + verify +`minSdk = 31` in `app/build.gradle.kts` afterward (the init overwrites it). + +Launcher icons (`res/mipmap-*/ic_launcher*.png`) are generated by +`npm run tauri:icon` and gitignored, like the desktop icons — both the local +`tauri:android:build` script and CI regenerate them before building. + +### versionCode + +`bundle.android.versionCode` in `tauri.conf.json` must increase monotonically +(needed for in-place upgrades). Derive it deterministically from semver: + +``` +versionCode = MAJOR*10000 + MINOR*100 + PATCH +``` + +e.g. `1.6.1 → 10601`, `1.7.0 → 10700`. Bump it together with `version` in +`package.json` / `Cargo.toml` / `tauri.conf.json` at release time. + +### Signing + +Release signing is read from `src-tauri/gen/android/keystore.properties` +(gitignored), which points at a keystore `.jks` (also gitignored, kept outside +the repo). If the file is absent the release variant builds **unsigned** — fine +for contributors, but a release APK must be signed so it installs and so future +versions can upgrade in place. + +Generate a keystore once: + +```powershell +& "$env:JAVA_HOME\bin\keytool.exe" -genkeypair -v ` + -keystore "$env:USERPROFILE\jsonprism-upload-keystore.jks" -storetype JKS ` + -keyalg RSA -keysize 2048 -validity 10000 -alias upload +``` + +Then create `src-tauri/gen/android/keystore.properties`: + +``` +storePassword=… +keyPassword=… +keyAlias=upload +storeFile=C:/Users//jsonprism-upload-keystore.jks +``` + +> Use forward slashes in `storeFile` — `.properties` treats `\` as an escape. +> **Back up the `.jks` and its passwords** (password manager). Losing the key +> means users can no longer upgrade in place — they'd have to uninstall first. + +### CI signing secrets + +The `android` job in `release.yml` needs these repository secrets: + +| Secret | Value | +| --- | --- | +| `ANDROID_KEYSTORE_BASE64` | base64 of the `.jks` (required) | +| `ANDROID_KEYSTORE_PASSWORD` | the store password (required) | +| `ANDROID_KEY_PASSWORD` | the key password (optional; defaults to store password) | +| `ANDROID_KEY_ALIAS` | the alias (optional; defaults to `upload`) | + +Produce the base64 (PowerShell): + +```powershell +[Convert]::ToBase64String([IO.File]::ReadAllBytes("$env:USERPROFILE\jsonprism-upload-keystore.jks")) | Set-Clipboard +``` + +CI decodes it to a temp path, writes `keystore.properties`, builds with +`tauri android build --apk`, and uploads the universal APK to the same draft +release as the desktop bundles. If `ANDROID_KEYSTORE_BASE64` is unset the job +fails fast rather than shipping an unsigned APK. + +### Output + +`src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk` + +### Offline fonts + +Fonts (Geist / Instrument Serif / JetBrains Mono) are self-hosted via +`@fontsource` (imported in `src/main.tsx`), not loaded from Google Fonts, so the +app renders correctly offline. The CSP in `tauri.conf.json` no longer allows the +Google Fonts hosts — keep it that way unless fonts move back to a CDN. + +### WebView version requirement (important) + +The Android app renders inside the device's **Android System WebView**, which is +Chromium. Tailwind v4 (our CSS) requires **Chromium ≥ 111** (`@layer`, `oklch()`, +`@property`). On an older WebView the layout breaks badly (giant icons, unhidden +elements, no responsive layout) even though the app installs and runs. + +- Real Android 12+ devices keep WebView updated via Play Store → modern Chromium + → renders correctly. This is the normal case. +- The bundled WebView in the **API 31 emulator system image is Chromium 91** and + shows the broken layout. Use a newer emulator image (e.g. `android-34`+, which + ships Chromium ≥ 120) or update the emulator's WebView via Play to test + rendering. The `android-31` install/`minSdk` gate can still be tested on the + stock API 31 image. + +This is inherent to the Tailwind v4 stack (the web app has the same requirement); +it is not Android-specific code. No action needed unless you must support devices +with a very outdated WebView. + +### Native file I/O on Android + +`plugin-dialog` `open()` returns a percent-encoded `content://` URI on Android +(not a filesystem path). `plugin-fs` `readTextFile()` reads it fine — validated on +an emulator for both URI flavours. `fileFromNativePath()` (`src/lib/tauri.ts`) +runs the URI through `basenameFromPath()` to recover a filename for the editor, +the extension filter, and toasts. `stat()` on a content URI is unreliable, so +`lastModified` falls back to a deterministic path hash — dedup still works. + +Two URI flavours show up: +- **`raw:` URIs** (most local/Downloads files) embed the real path → + `basenameFromPath()` recovers `data.json`. +- **`msf:` URIs** (MediaStore-indexed files) are opaque document ids with no + filename → they collapse to a numeric id (e.g. `18`) and **carry no + extension**. The native open path therefore filters leniently + (`filterByExtension(..., true)` / the `extOf(name) && !allowed` guard in + `InputPanel`) so a file the user explicitly picked is never wrongly rejected. + The real display name would need a content-resolver `DISPLAY_NAME` query via a + custom Rust command — not worth it; the file content loads correctly either way. diff --git a/index.html b/index.html index 696ae71..00fd649 100644 --- a/index.html +++ b/index.html @@ -36,13 +36,11 @@ - - - - + JSONPrism · Disperse JSON diff --git a/package-lock.json b/package-lock.json index 2f7b0ed..1666469 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,9 @@ "@codemirror/lint": "^6.9.7", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.43.1", + "@fontsource-variable/geist": "^5.2.9", + "@fontsource-variable/jetbrains-mono": "^5.2.8", + "@fontsource/instrument-serif": "^5.2.8", "@lezer/highlight": "^1.2.0", "@msgpack/msgpack": "^3.1.3", "@radix-ui/react-dialog": "^1.1.16", @@ -870,6 +873,33 @@ } } }, + "node_modules/@fontsource-variable/geist": { + "version": "5.2.9", + "resolved": "https://registry.npmjs.org/@fontsource-variable/geist/-/geist-5.2.9.tgz", + "integrity": "sha512-TP+QSBG3wxKGPE33CbMy/L0Nu3qvJ6Fy81Yc4LnQ95xH+i+cfEp8fyU8/kfV14YwszxIFPhnoMTbjL71waVpyQ==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/jetbrains-mono": { + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.2.8.tgz", + "integrity": "sha512-WBA9elru6Jdp5df2mES55wuOO0WIrn3kpXnI4+W2ek5u3ZgLS9XS4gmIlcQhiZOWEKl95meYdvK7xI+ETLCq/Q==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/instrument-serif": { + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@fontsource/instrument-serif/-/instrument-serif-5.2.8.tgz", + "integrity": "sha512-s+bkz+syj2rO00Rmq9g0P+PwuLig33DR1xDR8pTWmovH1pUjwnncrFk++q9mmOex8fUQ7oW80gPpPDaw7V1MMw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", diff --git a/package.json b/package.json index 81afb2c..631a4cd 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,10 @@ "tauri": "tauri", "tauri:dev": "tauri dev", "tauri:build": "tauri build", - "tauri:icon": "tauri icon src-tauri/icons/icon.svg" + "tauri:icon": "tauri icon src-tauri/icons/icon.svg", + "tauri:android:init": "tauri android init", + "tauri:android:dev": "npm run tauri:icon && tauri android dev", + "tauri:android:build": "npm run tauri:icon && tauri android build --apk" }, "dependencies": { "@codemirror/lang-json": "^6.0.0", @@ -44,6 +47,9 @@ "@codemirror/lint": "^6.9.7", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.43.1", + "@fontsource-variable/geist": "^5.2.9", + "@fontsource-variable/jetbrains-mono": "^5.2.8", + "@fontsource/instrument-serif": "^5.2.8", "@lezer/highlight": "^1.2.0", "@msgpack/msgpack": "^3.1.3", "@radix-ui/react-dialog": "^1.1.16", diff --git a/src-tauri/.gitignore b/src-tauri/.gitignore index 29caa0a..72ec5ab 100644 --- a/src-tauri/.gitignore +++ b/src-tauri/.gitignore @@ -4,9 +4,20 @@ # Icon binaries are generated from icon.svg via `npm run tauri:icon`. # Comment these out and commit the binaries if your CI doesn't run the generation step. icons/32x32.png +icons/64x64.png icons/128x128.png icons/128x128@2x.png +icons/icon.png icons/icon.icns icons/icon.ico icons/Square*.png icons/StoreLogo.png +icons/ios/ + +# Android launcher icons are also generated by `npm run tauri:icon` (run before each Android build). +gen/android/app/src/main/res/mipmap-*/ic_launcher*.png + +# Android signing — never commit the keystore binary. +# (keystore.properties / key.properties are already ignored by gen/android/.gitignore) +*.jks +*.keystore diff --git a/src-tauri/gen/android/.editorconfig b/src-tauri/gen/android/.editorconfig new file mode 100644 index 0000000..ebe51d3 --- /dev/null +++ b/src-tauri/gen/android/.editorconfig @@ -0,0 +1,12 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = false +insert_final_newline = false \ No newline at end of file diff --git a/src-tauri/gen/android/.gitignore b/src-tauri/gen/android/.gitignore new file mode 100644 index 0000000..1c636c3 --- /dev/null +++ b/src-tauri/gen/android/.gitignore @@ -0,0 +1,20 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +build +/captures +.externalNativeBuild +.cxx +local.properties +key.properties +keystore.properties + +/.tauri +/tauri.settings.gradle \ No newline at end of file diff --git a/src-tauri/gen/android/app/.gitignore b/src-tauri/gen/android/app/.gitignore new file mode 100644 index 0000000..6c4d56b --- /dev/null +++ b/src-tauri/gen/android/app/.gitignore @@ -0,0 +1,6 @@ +/src/main/**/generated +/src/main/jniLibs/**/*.so +/src/main/assets/tauri.conf.json +/tauri.build.gradle.kts +/proguard-tauri.pro +/tauri.properties \ No newline at end of file diff --git a/src-tauri/gen/android/app/build.gradle.kts b/src-tauri/gen/android/app/build.gradle.kts new file mode 100644 index 0000000..92720dd --- /dev/null +++ b/src-tauri/gen/android/app/build.gradle.kts @@ -0,0 +1,97 @@ +import java.io.FileInputStream +import java.util.Properties + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("rust") +} + +val tauriProperties = Properties().apply { + val propFile = file("tauri.properties") + if (propFile.exists()) { + propFile.inputStream().use { load(it) } + } +} + +// Release signing — loaded from `keystore.properties` at the gen/android root. +// That file (and the .jks it points to) is gitignored; it lives only on the +// maintainer's machine and is decoded from GitHub Secrets in CI. When it's +// absent (e.g. a contributor build) the release variant simply stays unsigned. +val keystorePropertiesFile = rootProject.file("keystore.properties") +val hasReleaseKeystore = keystorePropertiesFile.exists() +val keystoreProperties = Properties().apply { + if (hasReleaseKeystore) { + FileInputStream(keystorePropertiesFile).use { load(it) } + } +} + +android { + compileSdk = 36 + namespace = "com.poli0981.jsonprism" + defaultConfig { + manifestPlaceholders["usesCleartextTraffic"] = "false" + applicationId = "com.poli0981.jsonprism" + minSdk = 31 + targetSdk = 36 + versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt() + versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0") + } + signingConfigs { + if (hasReleaseKeystore) { + create("release") { + keyAlias = keystoreProperties.getProperty("keyAlias") + keyPassword = keystoreProperties.getProperty("keyPassword") + storeFile = file(keystoreProperties.getProperty("storeFile")) + storePassword = keystoreProperties.getProperty("storePassword") + } + } + } + buildTypes { + getByName("debug") { + manifestPlaceholders["usesCleartextTraffic"] = "true" + isDebuggable = true + isJniDebuggable = true + isMinifyEnabled = false + packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so") + jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so") + jniLibs.keepDebugSymbols.add("*/x86/*.so") + jniLibs.keepDebugSymbols.add("*/x86_64/*.so") + } + } + getByName("release") { + isMinifyEnabled = true + proguardFiles( + *fileTree(".") { include("**/*.pro") } + .plus(getDefaultProguardFile("proguard-android-optimize.txt")) + .toList().toTypedArray() + ) + if (hasReleaseKeystore) { + signingConfig = signingConfigs.getByName("release") + } + } + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + buildConfig = true + } +} + +rust { + rootDirRel = "../../../" +} + +dependencies { + implementation("androidx.webkit:webkit:1.14.0") + implementation("androidx.appcompat:appcompat:1.7.1") + implementation("androidx.activity:activity-ktx:1.10.1") + implementation("com.google.android.material:material:1.12.0") + implementation("androidx.lifecycle:lifecycle-process:2.10.0") + testImplementation("junit:junit:4.13.2") + androidTestImplementation("androidx.test.ext:junit:1.1.4") + androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0") +} + +apply(from = "tauri.build.gradle.kts") \ No newline at end of file diff --git a/src-tauri/gen/android/app/proguard-rules.pro b/src-tauri/gen/android/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/src-tauri/gen/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src-tauri/gen/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..00aadff --- /dev/null +++ b/src-tauri/gen/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src-tauri/gen/android/app/src/main/java/com/poli0981/jsonprism/MainActivity.kt b/src-tauri/gen/android/app/src/main/java/com/poli0981/jsonprism/MainActivity.kt new file mode 100644 index 0000000..9ebe816 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/java/com/poli0981/jsonprism/MainActivity.kt @@ -0,0 +1,11 @@ +package com.poli0981.jsonprism + +import android.os.Bundle +import androidx.activity.enableEdgeToEdge + +class MainActivity : TauriActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + } +} diff --git a/src-tauri/gen/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/src-tauri/gen/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/drawable/ic_launcher_background.xml b/src-tauri/gen/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src-tauri/gen/android/app/src/main/res/layout/activity_main.xml b/src-tauri/gen/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..4fc2444 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..2ffbf24 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/values-night/themes.xml b/src-tauri/gen/android/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..42af0a6 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/src-tauri/gen/android/app/src/main/res/values/colors.xml b/src-tauri/gen/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml b/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..ea9c223 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #fff + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/values/strings.xml b/src-tauri/gen/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..ab8bd32 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + JSONPrism + JSONPrism + \ No newline at end of file diff --git a/src-tauri/gen/android/app/src/main/res/values/themes.xml b/src-tauri/gen/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..42af0a6 --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/values/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml b/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..782d63b --- /dev/null +++ b/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src-tauri/gen/android/build.gradle.kts b/src-tauri/gen/android/build.gradle.kts new file mode 100644 index 0000000..607240b --- /dev/null +++ b/src-tauri/gen/android/build.gradle.kts @@ -0,0 +1,22 @@ +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath("com.android.tools.build:gradle:8.11.0") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.25") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +tasks.register("clean").configure { + delete("build") +} + diff --git a/src-tauri/gen/android/buildSrc/build.gradle.kts b/src-tauri/gen/android/buildSrc/build.gradle.kts new file mode 100644 index 0000000..5c55bba --- /dev/null +++ b/src-tauri/gen/android/buildSrc/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { + `kotlin-dsl` +} + +gradlePlugin { + plugins { + create("pluginsForCoolKids") { + id = "rust" + implementationClass = "RustPlugin" + } + } +} + +repositories { + google() + mavenCentral() +} + +dependencies { + compileOnly(gradleApi()) + implementation("com.android.tools.build:gradle:8.11.0") +} + diff --git a/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/BuildTask.kt b/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/BuildTask.kt new file mode 100644 index 0000000..a3de125 --- /dev/null +++ b/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/BuildTask.kt @@ -0,0 +1,68 @@ +import java.io.File +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.logging.LogLevel +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction + +open class BuildTask : DefaultTask() { + @Input + var rootDirRel: String? = null + @Input + var target: String? = null + @Input + var release: Boolean? = null + + @TaskAction + fun assemble() { + val executable = """npm"""; + try { + runTauriCli(executable) + } catch (e: Exception) { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + // Try different Windows-specific extensions + val fallbacks = listOf( + "$executable.exe", + "$executable.cmd", + "$executable.bat", + ) + + var lastException: Exception = e + for (fallback in fallbacks) { + try { + runTauriCli(fallback) + return + } catch (fallbackException: Exception) { + lastException = fallbackException + } + } + throw lastException + } else { + throw e; + } + } + } + + fun runTauriCli(executable: String) { + val rootDirRel = rootDirRel ?: throw GradleException("rootDirRel cannot be null") + val target = target ?: throw GradleException("target cannot be null") + val release = release ?: throw GradleException("release cannot be null") + val args = listOf("run", "--", "tauri", "android", "android-studio-script"); + + project.exec { + workingDir(File(project.projectDir, rootDirRel)) + executable(executable) + args(args) + if (project.logger.isEnabled(LogLevel.DEBUG)) { + args("-vv") + } else if (project.logger.isEnabled(LogLevel.INFO)) { + args("-v") + } + if (release) { + args("--release") + } + args(listOf("--target", target)) + }.assertNormalExitValue() + } +} \ No newline at end of file diff --git a/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/RustPlugin.kt b/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/RustPlugin.kt new file mode 100644 index 0000000..4aa7fca --- /dev/null +++ b/src-tauri/gen/android/buildSrc/src/main/java/com/poli0981/jsonprism/kotlin/RustPlugin.kt @@ -0,0 +1,85 @@ +import com.android.build.api.dsl.ApplicationExtension +import org.gradle.api.DefaultTask +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.kotlin.dsl.configure +import org.gradle.kotlin.dsl.get + +const val TASK_GROUP = "rust" + +open class Config { + lateinit var rootDirRel: String +} + +open class RustPlugin : Plugin { + private lateinit var config: Config + + override fun apply(project: Project) = with(project) { + config = extensions.create("rust", Config::class.java) + + val defaultAbiList = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64"); + val abiList = (findProperty("abiList") as? String)?.split(',') ?: defaultAbiList + + val defaultArchList = listOf("arm64", "arm", "x86", "x86_64"); + val archList = (findProperty("archList") as? String)?.split(',') ?: defaultArchList + + val targetsList = (findProperty("targetList") as? String)?.split(',') ?: listOf("aarch64", "armv7", "i686", "x86_64") + + extensions.configure { + @Suppress("UnstableApiUsage") + flavorDimensions.add("abi") + productFlavors { + create("universal") { + dimension = "abi" + ndk { + abiFilters += abiList + } + } + defaultArchList.forEachIndexed { index, arch -> + create(arch) { + dimension = "abi" + ndk { + abiFilters.add(defaultAbiList[index]) + } + } + } + } + } + + afterEvaluate { + for (profile in listOf("debug", "release")) { + val profileCapitalized = profile.replaceFirstChar { it.uppercase() } + val buildTask = tasks.maybeCreate( + "rustBuildUniversal$profileCapitalized", + DefaultTask::class.java + ).apply { + group = TASK_GROUP + description = "Build dynamic library in $profile mode for all targets" + } + + tasks["mergeUniversal${profileCapitalized}JniLibFolders"].dependsOn(buildTask) + + for (targetPair in targetsList.withIndex()) { + val targetName = targetPair.value + val targetArch = archList[targetPair.index] + val targetArchCapitalized = targetArch.replaceFirstChar { it.uppercase() } + val targetBuildTask = project.tasks.maybeCreate( + "rustBuild$targetArchCapitalized$profileCapitalized", + BuildTask::class.java + ).apply { + group = TASK_GROUP + description = "Build dynamic library in $profile mode for $targetArch" + rootDirRel = config.rootDirRel + target = targetName + release = profile == "release" + } + + buildTask.dependsOn(targetBuildTask) + tasks["merge$targetArchCapitalized${profileCapitalized}JniLibFolders"].dependsOn( + targetBuildTask + ) + } + } + } + } +} \ No newline at end of file diff --git a/src-tauri/gen/android/gradle.properties b/src-tauri/gen/android/gradle.properties new file mode 100644 index 0000000..2a7ec69 --- /dev/null +++ b/src-tauri/gen/android/gradle.properties @@ -0,0 +1,24 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true +android.nonFinalResIds=false \ No newline at end of file diff --git a/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.jar b/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.properties b/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c5f9a53 --- /dev/null +++ b/src-tauri/gen/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 10 19:22:52 CST 2022 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/src-tauri/gen/android/gradlew b/src-tauri/gen/android/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/src-tauri/gen/android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/src-tauri/gen/android/gradlew.bat b/src-tauri/gen/android/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/src-tauri/gen/android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src-tauri/gen/android/settings.gradle b/src-tauri/gen/android/settings.gradle new file mode 100644 index 0000000..3939116 --- /dev/null +++ b/src-tauri/gen/android/settings.gradle @@ -0,0 +1,3 @@ +include ':app' + +apply from: 'tauri.settings.gradle' diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9ad26d2..073164c 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -26,7 +26,7 @@ } ], "security": { - "csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost https://fonts.googleapis.com https://fonts.gstatic.com" + "csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost" } }, "bundle": { @@ -75,6 +75,10 @@ "deb": { "depends": [] } + }, + "android": { + "minSdkVersion": 31, + "versionCode": 10601 } }, "plugins": { diff --git a/src/components/converter/BatchPanel.tsx b/src/components/converter/BatchPanel.tsx index 1d402f0..4e902a1 100644 --- a/src/components/converter/BatchPanel.tsx +++ b/src/components/converter/BatchPanel.tsx @@ -54,8 +54,8 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B const { start, cancel, downloadZip } = useBatchActions(format, direction, options); const handleAddFiles = useCallback( - (files: File[]) => { - const { valid, wrongFormat } = filterByExtension(files, allowedExtensions); + (files: File[], lenientExt = false) => { + const { valid, wrongFormat } = filterByExtension(files, allowedExtensions, lenientExt); if (wrongFormat > 0) { toast.warning(t('batch.toast.wrong_format', { count: wrongFormat })); } @@ -108,7 +108,9 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B const paths = await nativeOpenFiles({ multiple: true }); if (!paths || paths.length === 0) return; const files = await Promise.all(paths.map(fileFromNativePath)); - handleAddFiles(files); + // The native dialog already filtered; Android content URIs may carry no + // extension, so don't re-reject them here. + handleAddFiles(files, true); return; } fileInputRef.current?.click(); diff --git a/src/components/converter/InputPanel.tsx b/src/components/converter/InputPanel.tsx index 4f969bf..6e6733d 100644 --- a/src/components/converter/InputPanel.tsx +++ b/src/components/converter/InputPanel.tsx @@ -106,7 +106,11 @@ export function InputPanel({ if (!paths || paths.length === 0) return; try { const file = await fileFromNativePath(paths[0]!); - if (!hasAllowedExt(file.name)) { + // The native dialog already filtered; reject only when the name carries + // a recognizable, disallowed extension. Android content URIs often have + // no extension at all (opaque document ids) — don't reject those. + const pickedExt = extOf(file.name); + if (pickedExt && !allowedExtensions.includes(pickedExt)) { toast.warning(t('batch.toast.wrong_format', { count: 1 })); return; } diff --git a/src/lib/__tests__/file-filter.test.ts b/src/lib/__tests__/file-filter.test.ts index 4c1615b..8f5a5f3 100644 --- a/src/lib/__tests__/file-filter.test.ts +++ b/src/lib/__tests__/file-filter.test.ts @@ -51,4 +51,21 @@ describe('filterByExtension', () => { it('returns empty result for empty input', () => { expect(filterByExtension([], ['json'])).toEqual({ valid: [], wrongFormat: 0 }); }); + + it('rejects extensionless names by default', () => { + const opaque = f('1000000123'); + const result = filterByExtension([opaque], ['json', 'txt']); + expect(result.valid).toEqual([]); + expect(result.wrongFormat).toBe(1); + }); + + it('accepts extensionless names when lenient (Android content URIs)', () => { + const opaque = f('1000000123'); + const json = f('b.json'); + const png = f('c.png'); + const result = filterByExtension([opaque, json, png], ['json', 'txt'], true); + // opaque (no ext) + json pass; png has a recognizable, disallowed ext. + expect(result.valid).toEqual([opaque, json]); + expect(result.wrongFormat).toBe(1); + }); }); diff --git a/src/lib/__tests__/tauri.test.ts b/src/lib/__tests__/tauri.test.ts index f73b24c..f68f751 100644 --- a/src/lib/__tests__/tauri.test.ts +++ b/src/lib/__tests__/tauri.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { pathHashAsMillis } from '../tauri'; +import { basenameFromPath, pathHashAsMillis } from '../tauri'; describe('pathHashAsMillis', () => { it('is deterministic for the same input', () => { @@ -20,3 +20,28 @@ describe('pathHashAsMillis', () => { expect(h).toBeLessThanOrEqual(0xffffffff); }); }); + +describe('basenameFromPath', () => { + it('returns the basename of a desktop path unchanged', () => { + expect(basenameFromPath('C:\\Users\\me\\data.json')).toBe('data.json'); + expect(basenameFromPath('/home/me/data.json')).toBe('data.json'); + expect(basenameFromPath('data.json')).toBe('data.json'); + }); + + it('decodes an Android content URI with an embedded raw path', () => { + // What plugin-dialog returns for a file picked from Downloads. + const uri = + 'content://com.android.providers.downloads.documents/document/' + + 'raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ftest-open.json'; + expect(basenameFromPath(uri)).toBe('test-open.json'); + }); + + it('collapses an opaque document id to a short token', () => { + const uri = 'content://com.android.providers.media.documents/document/msf%3A1000000123'; + expect(basenameFromPath(uri)).toBe('1000000123'); + }); + + it('survives a malformed percent-escape by falling back to the raw basename', () => { + expect(basenameFromPath('/tmp/100%-done.json')).toBe('100%-done.json'); + }); +}); diff --git a/src/lib/file-filter.ts b/src/lib/file-filter.ts index 5273ef8..8cbae7c 100644 --- a/src/lib/file-filter.ts +++ b/src/lib/file-filter.ts @@ -29,12 +29,25 @@ export interface FilterByExtensionResult { wrongFormat: number; } -/** Split files into (accepted, wrong-format count) by extension whitelist. */ -export function filterByExtension(files: File[], allowed: string[]): FilterByExtensionResult { +/** + * Split files into (accepted, wrong-format count) by extension whitelist. + * + * `treatUnknownExtAsValid` accepts files whose name has no detectable + * extension. Android's native picker returns opaque `content://` document ids + * (e.g. `…/document/msf:1000000123`) that carry no filename, so re-filtering a + * file the user already chose through the native dialog would wrongly reject + * it. Use it only on the native-open path — web drag-drop stays strict. + */ +export function filterByExtension( + files: File[], + allowed: string[], + treatUnknownExtAsValid = false, +): FilterByExtensionResult { const valid: File[] = []; let wrongFormat = 0; for (const f of files) { - if (allowed.includes(extOf(f.name))) valid.push(f); + const ext = extOf(f.name); + if (allowed.includes(ext) || (treatUnknownExtAsValid && ext === '')) valid.push(f); else wrongFormat += 1; } return { valid, wrongFormat }; diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index 2f6c550..e6d09e6 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -99,6 +99,29 @@ export function pathHashAsMillis(path: string): number { return h >>> 0; } +/** + * Derive a clean basename from a native path or an Android content URI. + * + * Desktop paths (`C:\…\data.json`, `/home/…/data.json`) pass through + * unchanged. Android's dialog returns a percent-encoded `content://` URI + * whose document id usually embeds the real path + * (e.g. `…/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fdata.json`). + * Decode it, then strip everything up to the last `/` or `:` so the editor, + * the format-extension filter, and toasts see `data.json` instead of the raw + * URI. Providers that hand back an opaque id (e.g. `msf:1000000123`) still + * collapse to a short, stable token. + */ +export function basenameFromPath(path: string): string { + let decoded = path; + try { + decoded = decodeURIComponent(path); + } catch { + // malformed %-escape — fall back to the raw string + } + const afterSlash = decoded.replace(/^.*[\\/]/, ''); + return afterSlash.replace(/^.*:/, '') || afterSlash; +} + /** * Convert a native file path to a browser-style File so the * existing batch store and editor flows can consume it unchanged. @@ -106,11 +129,12 @@ export function pathHashAsMillis(path: string): number { * `lastModified` is read from the file's real mtime via `stat()` so that * re-dropping the same file dedups correctly (batchStore keys on * name|size|lastModified). Falling back to `Date.now()` would break dedup - * because every drop produces a fresh timestamp. + * because every drop produces a fresh timestamp. On Android `stat()` on a + * content URI is unreliable, so the hash fallback covers it. */ export async function fileFromNativePath(path: string): Promise { const text = await nativeReadText(path); - const name = path.replace(/^.*[\\/]/, ''); // basename + const name = basenameFromPath(path); const ext = (name.split('.').pop() ?? '').toLowerCase(); const type = TYPE_BY_EXT[ext] ?? 'application/octet-stream'; diff --git a/src/main.tsx b/src/main.tsx index e2d50e1..7983890 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,6 +1,13 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; +// Self-hosted fonts (bundled into the build) so the app renders correctly +// offline — required for the desktop/Android sideload builds and a privacy win +// for web. Replaces the former Google Fonts tags in index.html. +import '@fontsource-variable/geist/index.css'; +import '@fontsource-variable/jetbrains-mono/index.css'; +import '@fontsource/instrument-serif/400.css'; +import '@fontsource/instrument-serif/400-italic.css'; import './styles/globals.css'; import './i18n'; import { App } from './app/App'; diff --git a/src/styles/globals.css b/src/styles/globals.css index 56a9dcb..352ea97 100644 --- a/src/styles/globals.css +++ b/src/styles/globals.css @@ -10,10 +10,13 @@ */ @theme inline { - /* Fonts */ + /* Fonts — self-hosted via @fontsource (imported in src/main.tsx). + Family names match the @fontsource packages: variable fonts expose the + "… Variable" family; the static Instrument Serif keeps its plain name. */ --font-display: 'Instrument Serif', ui-serif, Georgia, serif; - --font-sans: 'Geist', ui-sans-serif, system-ui, sans-serif; - --font-mono: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace; + --font-sans: 'Geist Variable', 'Geist', ui-sans-serif, system-ui, sans-serif; + --font-mono: + 'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace; /* Core shadcn tokens — map to CSS vars below */ --color-background: var(--background);