diff --git a/.github/workflows/psprecomp-release.yml b/.github/workflows/psprecomp-release.yml index 127f9da..456d0e7 100644 --- a/.github/workflows/psprecomp-release.yml +++ b/.github/workflows/psprecomp-release.yml @@ -147,7 +147,7 @@ jobs: path: psprecomp/dist/* android-app: - # The Android setup app (DissidiaRecomp-Setup--android.apk): a wizard that builds the game ON the phone from the player's own disc. + # The Android setup app (DissidiaRecomp-Setup--android.apk): an Android app (native views + the C++ install engine over JNI) that builds the game ON the phone from the player's own disc. # It carries its own compiler (zig), recompiler, Python and the prebuilt Android core, so nothing but the APK is downloaded. # Design and the verified steps: docs/android.md "Building on the phone". runs-on: ubuntu-22.04 diff --git a/psprecomp/ARCHITECTURE.md b/psprecomp/ARCHITECTURE.md index 5353eb9..2febd10 100644 --- a/psprecomp/ARCHITECTURE.md +++ b/psprecomp/ARCHITECTURE.md @@ -150,6 +150,7 @@ All under `runtime/` (headers in `runtime/include/`, sources in `runtime/src/`): | Core library + SDK | `runtime/CMakeLists.txt`, `runtime/sdk/CMakeLists.txt` | Everything under `runtime/src` (plus the selected game module) builds as the static library `psprecomp_core`; `psprecomp_runtime` is `main.cpp` (the only file that includes the generated `funcs.h`) linked with it, the generated libraries and the overlay libraries in one link group. `cmake --install --component sdk` writes an SDK (`lib/libpsprecomp_core.a`, headers, `src/main.cpp`, `sdk/CMakeLists.txt`) that builds a game from a recompiled output directory without the runtime sources: a release ships the prebuilt core and the player's machine compiles only the generated C++ (design: [docs/installer.md](docs/installer.md)) | | Toolchain bundle | `toolchain/` (`build_bundle.py`, `versions.json`, `zigwrap.c`) | The portable compiler a release ships and CI builds the core with: pinned zig (clang + lld + libc++) with cmake, ninja and static zlib/FreeType/SDL2/libavcodec built by it, driven through a generated `toolchain.cmake` + `deps.cmake` (`PSPRECOMP_DEPS_CMAKE` makes the runtime CMake use them instead of pkg-config). Reason: the prebuilt core and the code the player compiles are linked into one program, so both must come from the same compiler and C++ library; `toolchain.json` is installed in the SDK and `psp_build.py` refuses a mismatched bundle (details: [docs/installer.md](docs/installer.md)) | | Setup wizard | `setup/` (`setup_main.cpp`, `install.cpp`, `proc.cpp`) | `psprecomp_setup`: the installer / launcher, an SDL2 program for Linux and Windows that reuses the runtime's menu renderer (`runtime/src/hle/psp_savedata_dialog.cpp`), picks files with the system dialog (portable-file-dialogs) and imports saves (`psp_savemgr`) as an optional last step, drives `games/dissidia/tools/setup_from_iso.py` + `psp_build.py` (+ optional `fetch_textures.py`, `jp_audio.py`) through a small cross-platform process helper; shows progress/ETA, runs the update check, starts the game. Independent of the game's generated code (design: [docs/installer.md](docs/installer.md)) | +| Android setup app | `android/setup/` (Java pages), `setup/android_engine.cpp` (JNI), `android/build_setup_app.py`, `android/pack_setup_app.py`, `release/build_android_app.py` | Builds the game on the phone. Native Android views (no SDL) for the pages, controller and touch input, the live build log, log sharing and crash reports; the install logic is not duplicated: `setup/install.cpp` (plans, progress, `install.ini`), `proc.cpp` and `payload.cpp` are compiled into `libsetupcore.so` and reached through JNI, so the desktop wizard and the app run the same steps. The extras are one list (`setup/extras.cpp`) that both installers build their pages, install.ini and steps from, so an extra is added once for both. The SDL wizard's Android build was replaced by it (rotation, controller focus and Android-native pickers / share sheets are simpler with views than with the canvas renderer) ([docs/android.md](docs/android.md)) | | Release pipeline | `release/` (`build_release.py`, `assemble.py`, `make_manifest.py`, `sign_manifest.py`, `third_party_notices.py`), `.github/workflows/release.yml` | Builds a platform's archive from source: bundle -> header-only stub (`psprecomp recompile --headers-only`, so CI needs no game) -> runtime core + SDK -> wizard -> archive with `release.json` (file hashes + rebuild/relink fingerprints) and a `manifest.json` (+ Ed25519 `.sig` when a signing key is configured) per release, plus `licenses/THIRD-PARTY-NOTICES.txt` (incl. the FFmpeg LGPL source offer). The player's machine only compiles the generated code (`psp_build.py --sdk --toolchain`) | | Vulkan backend | `runtime/src/vk/` (`psp_vk_context`, `psp_vk_glsl`, `vkgl_core`, `vkgl_api`), `runtime/include/psp_gl_table.h`, `runtime/include/psp_gl_window.h`, `runtime/third_party/vk_mem_alloc.h` | `PSPRECOMP_RENDERER=vulkan` replaces glad's GL function pointers (on Android a pointer table behind the `gl*` names) with an implementation on Vulkan, so the GE renderer is one code base for both APIs. Images are stored in GL orientation (row 0 = bottom) and only the window present flips; GL-style GLSL (loose uniforms, location-less varyings) is converted to Vulkan GLSL (one std140 block, locations by name, clip-depth fix) and compiled to SPIR-V with glslang, cached on disk by hash; Android carries glslang too: a shader pack (`android/shaders/` -> `assets/shaders.pack`, kept current from the shader sources phones record) is compiled at start behind a "Preparing graphics" screen (`vk/psp_vk_warmup.cpp`), and anything else is compiled when first needed. State becomes pipelines (cached by key), render passes are begun lazily, uniforms/vertices go through per-frame rings, and GL's sequential buffer semantics are kept by copy-on-conflict. [docs/VULKAN_PORT.md](docs/VULKAN_PORT.md) | | Custom GPU drivers (Android) | `runtime/src/psp_gpu_driver.{h,cpp}`, `runtime/src/vk/psp_vk_loader.cpp`, `android/build_deps.py` (libadrenotools) | On an Adreno phone the Vulkan loader is opened through libadrenotools (`adrenotools_open_libvulkan`) with a community driver (Mesa Turnip) chosen in Settings instead of the phone's own; the surface is then created with `vkCreateAndroidSurfaceKHR` because SDL's helper talks to the system loader. Drivers are adrenotools packages (zip: `meta.json` + `vulkan.*.so`) unpacked under the app's internal storage (dlopen refuses the sd card); the Settings > Drivers tab (only listed where `psp_gpu::supported()`) lists them from the GitHub releases of `K11MCH1/AdrenoToolsDrivers` (`PSPRECOMP_GPU_DRIVER_FEEDS`), downloads over `psp_http` and unpacks without trusting zip paths. A crash marker skips a driver that killed the process while Vulkan was brought up. The four libadrenotools hook libraries ship in the APK next to `libmain.so`. List/zip/meta code is host-testable (`tests/test_gpu_driver.cpp`). | diff --git a/psprecomp/android/build_setup_app.py b/psprecomp/android/build_setup_app.py index b1e452e..e09f062 100644 --- a/psprecomp/android/build_setup_app.py +++ b/psprecomp/android/build_setup_app.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 -"""Build libmain.so of the Android setup app (the wizard in setup/, as a shared library for SDL's Java activity) with zig and the NDK sysroot. +"""Build libsetupcore.so of the Android setup app: the install engine of setup/ (plans, processes, progress, payload; setup/android_engine.cpp +is its JNI face) for the app's Java UI (android/setup/java). Built with zig and the NDK sysroot. - build_setup_app.py --zig ZIG --ndk NDK_ROOT --deps DEPS_DIR --out libmain.so [--jobs N] + build_setup_app.py --zig ZIG --ndk NDK_ROOT --out libsetupcore.so [--jobs N] -DEPS_DIR is the Android part's deps/deps (SDL2 headers + libSDL2.so, FreeType). The same compiler and flags the phone uses to build the game -(games/dissidia/tools/android_build.py device_build): zig as clang + lld against the NDK sysroot, linked with c++_static. Standard library only. +The same compiler and flags the phone uses to build the game (games/dissidia/tools/android_build.py device_build): zig as clang + lld against +the NDK sysroot, linked with c++_static. No SDL: the pages are Android views. Standard library only. """ import argparse, concurrent.futures, glob, hashlib, os, subprocess, sys, tempfile @@ -17,7 +18,8 @@ def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--zig", required=True); ap.add_argument("--ndk", required=True); ap.add_argument("--deps", required=True) + ap.add_argument("--zig", required=True); ap.add_argument("--ndk", required=True) + ap.add_argument("--deps", help="(ignored; the engine needs no SDL)") ap.add_argument("--out", required=True); ap.add_argument("--jobs", type=int, default=os.cpu_count() or 2) a = ap.parse_args() sysroot = os.path.join(a.ndk, SYSROOT) @@ -25,18 +27,12 @@ def main(): rt = os.path.join(a.ndk, CLANG_RT) work = tempfile.mkdtemp(prefix="setupapp-") env = dict(os.environ, ZIG_GLOBAL_CACHE_DIR=os.path.join(work, "zig-cache"), HOME=work) - # the menu fonts, embedded as C++ (the same cmake script setup/CMakeLists.txt uses) - fonts = os.path.join(work, "psp_ui_fonts.cpp") - subprocess.check_call(["cmake", "-DFONT_DIR=" + REPO + "/runtime/assets/fonts", "-DOUT=" + fonts, "-P", REPO + "/runtime/assets/embed_fonts.cmake"]) - rtsrc = REPO + "/runtime/src/hle/" - cxx = [REPO + "/setup/" + f for f in ("setup_main.cpp", "install.cpp", "proc.cpp", "payload.cpp", "android.cpp")] + \ - [rtsrc + f for f in ("psp_savedata_dialog.cpp", "psp_savemgr.cpp", "psp_savedata_crypto.cpp")] + [fonts] + cxx = [REPO + "/setup/" + f for f in ("install.cpp", "extras.cpp", "proc.cpp", "payload.cpp", "android_engine.cpp")] c = [REPO + "/setup/third_party/miniz.c"] common = ["-target", "aarch64-linux-android", "-DANDROID", "-U__ANDROID_API__", "-D__ANDROID_API__=%d" % API, "-fPIC", "-O2", "-fdata-sections", "-ffunction-sections", "-funwind-tables", "-fstack-protector-strong", "-Wno-everything", "-isystem", sysroot + "/usr/include/aarch64-linux-android", "-isystem", sysroot + "/usr/include", - "-I" + REPO + "/runtime/include", "-I" + rtsrc, "-isystem", a.deps + "/include/SDL2", "-isystem", a.deps + "/include/freetype2", - "-isystem", a.deps + "/include"] + "-I" + REPO + "/setup"] cxxflags = ["-std=gnu++17", "-nostdinc++", "-I" + sysroot + "/usr/include/c++/v1"] objs = [] @@ -52,11 +48,10 @@ def build(src): with concurrent.futures.ThreadPoolExecutor(a.jobs) as ex: objs = list(ex.map(build, cxx + c)) - d = a.deps + "/lib" cl = lib + "/%d" % API cmd = [a.zig, "ld.lld", "-m", "aarch64linux", "-shared", "-z", "noexecstack", "-z", "relro", "-z", "now", "-z", "max-page-size=16384", "--hash-style=gnu", - "--eh-frame-hdr", "--build-id=sha1", "--gc-sections", "--threads=1", "-s", "--no-undefined", "-soname", "libmain.so", "-o", a.out, - cl + "/crtbegin_so.o"] + objs + [d + "/libSDL2.so", d + "/libfreetype.a", cl + "/libz.so", "-L" + cl, "-L" + lib, "-llog", "-landroid", "-lGLESv3", + "--eh-frame-hdr", "--build-id=sha1", "--gc-sections", "--threads=1", "-s", "--no-undefined", "-soname", os.path.basename(a.out), "-o", a.out, + cl + "/crtbegin_so.o"] + objs + ["-L" + cl, "-L" + lib, "-llog", "-lm", lib + "/libc++_static.a", lib + "/libc++abi.a", rt + "/aarch64/libunwind.a", rt + "/aarch64/libatomic.a", "-ldl", "-lc", rt + "/libclang_rt.builtins-aarch64-android.a", cl + "/crtend_so.o"] r = subprocess.run(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) diff --git a/psprecomp/android/make_skeleton.py b/psprecomp/android/make_skeleton.py index e14d733..829bbca 100644 --- a/psprecomp/android/make_skeleton.py +++ b/psprecomp/android/make_skeleton.py @@ -2,7 +2,7 @@ """Build the unsigned APK skeleton (manifest + compiled resources + classes.dex of SDL's Java activity), zip-aligned, for apk_pack.py. Release-time tool (needs a JDK, the Android SDK build-tools + platform, SDL2 source): the player's machine only runs apk_pack.py. - make_skeleton.py --sdk SDK --sdl-src SDL2_SRC [--package org.psprecomp.game] [--label "Dissidia 012"] [--api 29] -o skeleton.apk + make_skeleton.py --sdk SDK (--sdl-src SDL2_SRC | --no-sdl) [--package org.psprecomp.game] [--label "Dissidia 012"] [--api 29] -o skeleton.apk """ import argparse, glob, os, shutil, subprocess, sys, tempfile @@ -14,7 +14,10 @@ def run(cmd): def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--sdk", required=True); ap.add_argument("--sdl-src", required=True) + ap.add_argument("--sdk", required=True); ap.add_argument("--sdl-src") + ap.add_argument("--no-sdl", action="store_true", help="no SDL Java classes (the setup app: plain Android views)") + ap.add_argument("--extra-res", help="a second resource folder (the setup app's theme)") + ap.add_argument("--assets", help="a folder packed as the APK's assets/ (the setup app's fonts)") ap.add_argument("--package", default="org.psprecomp.game"); ap.add_argument("--label", default="Dissidia 012") ap.add_argument("--api", default="29"); ap.add_argument("-o", "--output", required=True) ap.add_argument("--manifest", help="manifest template (default: hello/AndroidManifest.xml); its package is replaced by --package") @@ -28,7 +31,9 @@ def main(): jar = sorted(glob.glob(sdk + "/platforms/android-*/android.jar"))[-1] work = tempfile.mkdtemp(prefix="skeleton-") classes = work + "/classes"; os.makedirs(classes) - srcs = glob.glob(os.path.abspath(a.sdl_src) + "/android-project/app/src/main/java/org/libsdl/app/*.java") + if not a.no_sdl and not a.sdl_src: + ap.error("--sdl-src is needed (or --no-sdl)") + srcs = [] if a.no_sdl else glob.glob(os.path.abspath(a.sdl_src) + "/android-project/app/src/main/java/org/libsdl/app/*.java") if a.extra_java: srcs += glob.glob(os.path.abspath(a.extra_java) + "/**/*.java", recursive=True) run(["javac", "-source", "8", "-target", "8", "-Xlint:-options", "-cp", jar, "-d", classes] + srcs) @@ -46,7 +51,12 @@ def main(): base = work + "/base.apk" compiled = work + "/res.zip" run([bt + "/aapt2", "compile", "--dir", os.path.abspath(a.icon_res) if a.icon_res else here + "/icon/res", "-o", compiled]) # launcher icon (icon/make_icon.py) - run([bt + "/aapt2", "link", "-o", base, "-I", jar, "--manifest", man, "-R", compiled, "--min-sdk-version", a.api, "--target-sdk-version", "34"]) + extra = [] + if a.extra_res: + extra = [work + "/res_extra.zip"] # a base input (not an overlay): it adds resources + run([bt + "/aapt2", "compile", "--dir", os.path.abspath(a.extra_res), "-o", extra[0]]) + run([bt + "/aapt2", "link", "-o", base, "-I", jar, "--manifest", man, "-R", compiled] + extra + [ "--min-sdk-version", a.api, "--target-sdk-version", "34"] + + (["-A", os.path.abspath(a.assets)] if a.assets else [])) import zipfile unaligned = work + "/unaligned.apk" shutil.copy(base, unaligned) diff --git a/psprecomp/android/pack_setup_app.py b/psprecomp/android/pack_setup_app.py index f866480..0b0ad31 100644 --- a/psprecomp/android/pack_setup_app.py +++ b/psprecomp/android/pack_setup_app.py @@ -2,12 +2,12 @@ """Assemble the Android setup app (APK): the wizard, the tools it runs on the phone, and the payload they work from. pack_setup_app.py --android-part DIR --ndk NDK --zig-tree DIR --python-tree DIR --musl FILE --psprecomp FILE --pspdecrypt FILE - --skeleton APK --libmain SO [--game DIR] [--patchelf PATCHELF] -o setup.apk + --skeleton APK --engine SO [--game DIR] [--patchelf PATCHELF] -o setup.apk Executables go into lib/arm64-v8a/ as lib*.so (the only place an app may run files from since Android 10): libzig.so (zig 0.15, static, clang + lld in one), libpsprecomp.so (the recompiler, static musl), libpspdecrypt.so, libpython.so (python-build-standalone, musl; its -interpreter is patched to /data/data/org.psprecomp.setup/files/ld-musl, a link the app makes to libmusl.so = Alpine's musl loader), libmain.so -(the wizard) and libSDL2.so. Everything else (Python's library, zig's lib, the NDK sysroot, the Android core + libraries, the game's tools +interpreter is patched to /data/data/org.psprecomp.setup/files/ld-musl, a link the app makes to libmusl.so = Alpine's musl loader) and +libsetupcore.so (the install engine behind the app's Java pages, android/build_setup_app.py). Everything else (Python's library, zig's lib, the NDK sysroot, the Android core + libraries, the game's tools and analysis) is one zip, lib/arm64-v8a/libpayload.so, that the wizard unpacks on its first start. Standard library only (+ patchelf). """ import argparse, hashlib, os, shutil, subprocess, sys, tempfile, zipfile @@ -32,7 +32,7 @@ def add_tree(z, src, arc, skip=lambda rel: False): def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - for n in ("android-part", "ndk", "zig-tree", "python-tree", "musl", "psprecomp", "pspdecrypt", "skeleton", "libmain"): + for n in ("android-part", "ndk", "zig-tree", "python-tree", "musl", "psprecomp", "pspdecrypt", "skeleton", "engine"): ap.add_argument("--" + n, required=True) ap.add_argument("--game", default=os.path.join(REPO, "games", "dissidia")) ap.add_argument("--patchelf", default="patchelf") @@ -117,8 +117,7 @@ def main(): shutil.copy2(os.path.join(a.python_tree, "bin", "python3.13"), py) subprocess.check_call([a.patchelf, "--set-interpreter", INTERP, py]) - libs = [("libmain.so", a.libmain), ("libSDL2.so", os.path.join(a.android_part, "deps", "deps", "lib", "libSDL2.so")), - ("libzig.so", os.path.join(a.zig_tree, "zig")), ("libpsprecomp.so", a.psprecomp), ("libpspdecrypt.so", a.pspdecrypt), + libs = [("libsetupcore.so", a.engine), ("libzig.so", os.path.join(a.zig_tree, "zig")), ("libpsprecomp.so", a.psprecomp), ("libpspdecrypt.so", a.pspdecrypt), ("libpython.so", py), ("libmusl.so", a.musl), ("libpayload.so", payload)] cmd = [sys.executable, "-I", os.path.join(HERE, "apk_pack.py"), "--skeleton", a.skeleton, "--key", os.path.join(a.android_part, "apk", "debug_key.json"), "-o", a.output] for name, path in libs: diff --git a/psprecomp/android/setup/AndroidManifest.xml b/psprecomp/android/setup/AndroidManifest.xml index 9f68a9f..d936820 100644 --- a/psprecomp/android/setup/AndroidManifest.xml +++ b/psprecomp/android/setup/AndroidManifest.xml @@ -9,20 +9,29 @@ - + + + + + + + android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation|density" + android:screenOrientation="fullUser" android:theme="@style/SetupTheme" android:windowSoftInputMode="adjustResize"> + + + + diff --git a/psprecomp/android/setup/java/org/psprecomp/setup/BackdropView.java b/psprecomp/android/setup/java/org/psprecomp/setup/BackdropView.java new file mode 100644 index 0000000..9aeea19 --- /dev/null +++ b/psprecomp/android/setup/java/org/psprecomp/setup/BackdropView.java @@ -0,0 +1,223 @@ +package org.psprecomp.setup; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RadialGradient; +import android.graphics.Shader; +import android.os.SystemClock; +import android.view.View; + +import java.util.Random; + +/** + * The living background behind every page: a night sky gradient, slowly turning light rays, a large wireframe crystal that rotates in + * space, a horizon ring and drifting motes of light. Its mood (crystal / gold / chaos red) fades between pages: gold when something is + * finished, red when it failed. `energy` speeds the motes up while the game is being built. + */ +final class BackdropView extends View { + static final int MOOD_CRYSTAL = 0, MOOD_GOLD = 1, MOOD_CHAOS = 2; + private static final int[] MOOD_COLOR = {Theme.CRYSTAL, Theme.GOLD, Theme.DANGER}; + + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG), glow = new Paint(Paint.ANTI_ALIAS_FLAG), line = new Paint(Paint.ANTI_ALIAS_FLAG); + private final float[] px, py, pz, pphase; + private final Random rnd = new Random(12); + private long last = 0; + private float t = 0; + private int moodColor = Theme.CRYSTAL, fromColor = Theme.CRYSTAL, toColor = Theme.CRYSTAL; + private float moodT = 1; + private float energy = 0, energyTarget = 0; + private float crystalA = 1, crystalTarget = 1; // the wireframe crystal fades out behind pages that show their own (the hero) + private boolean slow = false; // ~30 fps (during the long build: leaves the CPU to the compiler) + private long nextFrame = 0; + private Shader sky; + private int skyH = -1; + private final Path path = new Path(); + + // the crystal: an elongated octahedron with an inner ring + private static final float[][] V = {{0, -1.6f, 0}, {0, 1.6f, 0}, {1, 0, 0}, {0, 0, 1}, {-1, 0, 0}, {0, 0, -1}, {0.62f, -0.55f, 0.62f}, {-0.62f, -0.55f, -0.62f}}; + private static final int[][] E = {{0, 2}, {0, 3}, {0, 4}, {0, 5}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {3, 4}, {4, 5}, {5, 2}}; + + BackdropView(Context c) { + super(c); + int n = 90; + px = new float[n]; + py = new float[n]; + pz = new float[n]; + pphase = new float[n]; + for (int i = 0; i < n; i++) { + px[i] = rnd.nextFloat(); + py[i] = rnd.nextFloat(); + pz[i] = 0.25f + rnd.nextFloat() * 0.75f; + pphase[i] = rnd.nextFloat() * 6.283f; + } + line.setStyle(Paint.Style.STROKE); + line.setStrokeCap(Paint.Cap.ROUND); + glow.setStyle(Paint.Style.STROKE); + glow.setStrokeCap(Paint.Cap.ROUND); + } + + void setMood(int mood) { + int c = MOOD_COLOR[Math.max(0, Math.min(2, mood))]; + if (c == toColor) return; + fromColor = moodColor; + toColor = c; + moodT = 0; + } + + void setEnergy(float e) { + energyTarget = e; + } + + void setCrystal(boolean on) { + crystalTarget = on ? 1 : 0; + } + + void setSlow(boolean s) { + slow = s; + } + + @Override + protected void onDraw(Canvas c) { + if (getWidth() < 4 || getHeight() < 4) return; // not laid out (yet): gradients need a size + long now = SystemClock.uptimeMillis(); + float dt = last == 0 ? 0.016f : Math.min(0.1f, (now - last) / 1000f); + last = now; + t += dt; + energy += (energyTarget - energy) * Math.min(1, dt * 1.5f); + crystalA += (crystalTarget - crystalA) * Math.min(1, dt * 3f); + if (moodT < 1) { + moodT = Math.min(1, moodT + dt * 1.2f); + moodColor = Theme.mix(fromColor, toColor, moodT); + } + final int w = getWidth(), h = getHeight(); + final boolean landscape = w > h; + + // sky + if (skyH != h) { + sky = new LinearGradient(0, 0, 0, h, new int[] {Theme.BG_TOP, Theme.BG_MID, Theme.BG_BOTTOM}, new float[] {0, 0.45f, 1}, Shader.TileMode.CLAMP); + skyH = h; + } + paint.setColor(0xFFFFFFFF); // a shader is multiplied by the paint's alpha + paint.setShader(sky); + c.drawRect(0, 0, w, h, paint); + + // the glow the crystal sits in + float gx = landscape ? w * 0.27f : w * 0.5f, gy = landscape ? h * 0.48f : h * 0.2f; + float gr = Math.max(w, h) * 0.55f; + paint.setColor(0xFFFFFFFF); // a shader is multiplied by the paint's alpha + paint.setShader(new RadialGradient(gx, gy, gr, new int[] {Theme.alpha(moodColor, 0.22f), Theme.alpha(moodColor, 0.06f), 0}, new float[] {0, 0.45f, 1}, + Shader.TileMode.CLAMP)); + c.drawCircle(gx, gy, gr, paint); + paint.setShader(null); + + // light rays + c.save(); + c.translate(gx, gy); + c.rotate(t * 2.2f); + paint.setColor(Theme.alpha(Theme.GOLD_LIGHT, 0.035f)); + float rl = Math.max(w, h) * 1.2f; + for (int i = 0; i < 12; i++) { + path.reset(); + path.moveTo(0, 0); + double a0 = i * Math.PI * 2 / 12, a1 = a0 + 0.11 + 0.05 * Math.sin(t * 0.4 + i); + path.lineTo((float) Math.cos(a0) * rl, (float) Math.sin(a0) * rl); + path.lineTo((float) Math.cos(a1) * rl, (float) Math.sin(a1) * rl); + path.close(); + c.drawPath(path, paint); + } + c.restore(); + + // horizon ring + float ry = landscape ? h * 0.86f : h * 0.9f; + line.setStrokeWidth(Theme.dpf(1.2f)); + line.setColor(Theme.alpha(Theme.GOLD, 0.16f)); + c.drawOval(-w * 0.2f, ry - h * 0.06f, w * 1.2f, ry + h * 0.06f, line); + line.setColor(Theme.alpha(moodColor, 0.10f)); + c.drawOval(-w * 0.35f, ry - h * 0.11f, w * 1.35f, ry + h * 0.11f, line); + + // the crystal + if (crystalA > 0.02f) { + // landscape: in the glow on the left (pages put their text right of it); portrait: low down, under the cards' usual reach + int save = c.saveLayerAlpha(0, 0, w, h, Math.round(255 * crystalA * (landscape ? 0.45f : 0.55f))); + if (landscape) drawCrystal(c, gx, gy, Math.min(w, h) * 0.2f); + else drawCrystal(c, w * 0.5f, h * 0.8f, Math.min(w, h) * 0.17f); + c.restoreToCount(save); + } + + // motes + float speed = 0.012f + energy * 0.05f; + for (int i = 0; i < px.length; i++) { + py[i] -= dt * speed * pz[i]; + px[i] += dt * 0.004f * (float) Math.sin(t * 0.3f + pphase[i]); + if (py[i] < -0.02f) { py[i] = 1.02f; px[i] = rnd.nextFloat(); } + float tw = 0.5f + 0.5f * (float) Math.sin(t * (1.2f + pz[i]) + pphase[i]); + float r = Theme.dpf(0.8f + 1.6f * pz[i]); + int col = i % 3 == 0 ? Theme.GOLD_LIGHT : moodColor; + paint.setColor(Theme.alpha(col, 0.15f + 0.55f * tw * pz[i])); + c.drawCircle(px[i] * w, py[i] * h, r, paint); + if (pz[i] > 0.85f) { + paint.setColor(Theme.alpha(col, 0.08f * tw)); + c.drawCircle(px[i] * w, py[i] * h, r * 4, paint); + } + } + + if (slow) { + long due = Math.max(now + 33, nextFrame + 33); + nextFrame = due; + postInvalidateDelayed(33); + } else postInvalidateOnAnimation(); + } + + private void drawCrystal(Canvas c, float cx, float cy, float size) { + float ay = t * 0.35f, ax = 0.35f + 0.08f * (float) Math.sin(t * 0.5f); + float[][] p = new float[V.length][3]; + float cyy = (float) Math.cos(ay), syy = (float) Math.sin(ay), cxx = (float) Math.cos(ax), sxx = (float) Math.sin(ax); + float bob = (float) Math.sin(t * 0.8f) * size * 0.06f; + for (int i = 0; i < V.length; i++) { + float x = V[i][0], y = V[i][1], z = V[i][2]; + float x1 = x * cyy + z * syy, z1 = -x * syy + z * cyy; + float y1 = y * cxx - z1 * sxx, z2 = y * sxx + z1 * cxx; + float persp = 3.2f / (3.2f + z2); + p[i][0] = cx + x1 * size * persp; + p[i][1] = cy + bob + y1 * size * persp; + p[i][2] = z2; + } + // faces, faintly filled (back to front is not needed at this alpha) + paint.setColor(Theme.alpha(moodColor, 0.05f)); + int[][] faces = {{0, 2, 3}, {0, 3, 4}, {0, 4, 5}, {0, 5, 2}, {1, 2, 3}, {1, 3, 4}, {1, 4, 5}, {1, 5, 2}}; + for (int[] f : faces) { + path.reset(); + path.moveTo(p[f[0]][0], p[f[0]][1]); + path.lineTo(p[f[1]][0], p[f[1]][1]); + path.lineTo(p[f[2]][0], p[f[2]][1]); + path.close(); + c.drawPath(path, paint); + } + glow.setStrokeWidth(Theme.dpf(5)); + line.setStrokeWidth(Theme.dpf(1.1f)); + for (int[] e : E) { + float depth = (p[e[0]][2] + p[e[1]][2]) * 0.5f; // nearer edges brighter + float a = 0.22f + 0.3f * (1 - (depth + 1) / 2); + glow.setColor(Theme.alpha(moodColor, a * 0.25f)); + c.drawLine(p[e[0]][0], p[e[0]][1], p[e[1]][0], p[e[1]][1], glow); + line.setColor(Theme.alpha(Theme.mix(moodColor, 0xFFFFFFFF, 0.4f), a)); + c.drawLine(p[e[0]][0], p[e[0]][1], p[e[1]][0], p[e[1]][1], line); + } + // the inner ring orbiting the crystal + line.setColor(Theme.alpha(Theme.GOLD, 0.28f)); + c.save(); + c.translate(cx, cy + bob); + c.rotate(-12); + float rw = size * 1.55f, rh = size * 0.32f; + c.drawOval(-rw, -rh, rw, rh, line); + float oa = t * 0.9f; + paint.setColor(Theme.alpha(Theme.GOLD_LIGHT, 0.85f)); + c.drawCircle((float) Math.cos(oa) * rw, (float) Math.sin(oa) * rh, Theme.dpf(2.2f), paint); + paint.setColor(Theme.alpha(Theme.GOLD_LIGHT, 0.15f)); + c.drawCircle((float) Math.cos(oa) * rw, (float) Math.sin(oa) * rh, Theme.dpf(7), paint); + c.restore(); + } +} diff --git a/psprecomp/android/setup/java/org/psprecomp/setup/BuildRunner.java b/psprecomp/android/setup/java/org/psprecomp/setup/BuildRunner.java new file mode 100644 index 0000000..76ddd61 --- /dev/null +++ b/psprecomp/android/setup/java/org/psprecomp/setup/BuildRunner.java @@ -0,0 +1,229 @@ +package org.psprecomp.setup; + +import android.os.Handler; +import android.os.Looper; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.ArrayDeque; +import java.util.Date; +import java.util.Locale; + +/** + * Runs a plan (Engine.plan) on its own thread, one step after the other: commands through the engine (their output becomes progress there), + * download steps with Downloader. Every output line goes to setup.log in the work folder and, as it arrives, to the listener (the live log + * on the page). One runner at a time (current); the page reattaches to it after a rotation or when the app comes back. + */ +final class BuildRunner { + interface Listener { + void lines(String[] lines); + void progress(JSONObject p); + void finished(boolean ok, String error, String note); + } + + static volatile BuildRunner current; + + final String kind; + final JSONArray plan; + final File log; + final ArrayList history = new ArrayList<>(); // what the live log shows (capped) + private final ArrayDeque recent = new ArrayDeque<>(); // the last lines (the failure page shows them) + private final Handler ui = new Handler(Looper.getMainLooper()); + private volatile Listener listener; + private volatile boolean cancel; + private Downloader dl; + volatile boolean running = true, ok = false; + volatile String error = "", note = ""; + volatile JSONObject lastProgress; + private Writer out; + + BuildRunner(String kind, JSONArray plan, File log) { + this.kind = kind; + this.plan = plan; + this.log = log; + } + + void setListener(Listener l) { + listener = l; + } + + String recentText() { + synchronized (recent) { + StringBuilder b = new StringBuilder(); + for (String s : recent) b.append(s).append('\n'); + return b.toString().trim(); + } + } + + void start() { + current = this; + new Thread(this::run, "setup-build").start(); + } + + void cancel() { + cancel = true; + Engine.kill(); + Downloader d = dl; + if (d != null) d.cancel(); + } + + private void log(String s) { + synchronized (history) { + history.add(s); + if (history.size() > 6000) history.subList(0, 1000).clear(); + } + if (!s.trim().isEmpty() && !s.startsWith("FAILED:")) { + synchronized (recent) { + recent.addLast(s); + while (recent.size() > 14) recent.removeFirst(); + } + } + try { + if (out != null) { + out.write(s); + out.write('\n'); + } + } catch (Exception e) { + // the log file is a convenience + } + } + + private void emit(String[] lines) { + final Listener l = listener; + if (l != null && lines != null) ui.post(() -> { if (listener == l) l.lines(lines); }); + } + + private long lastProg = 0; + + private void emitProgress(boolean force) { + long now = System.currentTimeMillis(); + if (!force && now - lastProg < 200) return; + lastProg = now; + try { + JSONObject p = new JSONObject(Engine.progress()); + lastProgress = p; + final Listener l = listener; + if (l != null) ui.post(() -> { if (listener == l) l.progress(p); }); + } catch (Exception e) { + // never mind one frame + } + } + + private void say(String s) { + log(s); + emit(new String[] {s}); + } + + private void run() { + try { + log.getParentFile().mkdirs(); + out = new OutputStreamWriter(new FileOutputStream(log, true), "UTF-8"); + } catch (Exception e) { + out = null; + } + String stamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(new Date()); + say("===== psprecomp_setup run (" + kind + ", " + stamp + ") ====="); + String fail = null; + try { + for (int i = 0; i < plan.length() && fail == null; i++) { + JSONObject step = plan.getJSONObject(i); + say("===== step " + (i + 1) + "/" + plan.length() + ": " + step.optString("label") + " ====="); + String err = Engine.startStep(i); + emitProgress(true); + if (!err.isEmpty()) { fail = "Could not start: " + err; break; } + JSONArray dls = step.optJSONArray("downloads"); + int code = 0; + if (dls != null && dls.length() > 0) { + String r = downloads(dls); + if (r != null) { + fail = cancel ? "The installation was cancelled." : "The download failed (" + r + "). Check your connection and try again; finished files are kept."; + break; + } + } else { + while (true) { + String[] lines = Engine.readLines(); + if (lines != null) { + for (String s : lines) log(s); + emit(lines); + } + emitProgress(false); + if (lines == null && !Engine.busy()) break; + if (lines == null) Thread.sleep(60); + } + code = Engine.exitCode(); + } + if (cancel) { fail = "The installation was cancelled."; break; } + JSONObject p = new JSONObject(Engine.progress()); + String perr = p.optString("error"); + if (code != 0 || !perr.isEmpty()) { + if (step.optBoolean("optional")) { + String why = perr.isEmpty() ? p.optString("last") : perr; + note = step.optString("label") + " did not work" + (why.isEmpty() ? "." : ": " + why); + say("optional step failed: " + note); + Engine.clearError(); + } else { + fail = perr.isEmpty() ? "A step failed (exit code " + code + "). The log shows what happened." : perr + "."; + } + } + } + } catch (Exception e) { + fail = "The setup stopped: " + e; + } + if (fail != null) say("FAILED: " + fail); + else say("===== finished ====="); + emitProgress(true); + try { + if (out != null) out.close(); + } catch (Exception e) { + // closed anyway + } + ok = fail == null; + error = fail == null ? "" : fail; + running = false; + final Listener l = listener; + if (l != null) ui.post(() -> { if (listener == l) l.finished(ok, error, note); }); + } + + /** A download step: every file that is not there yet (a finished one from an earlier try is kept). null = done. */ + private String downloads(JSONArray dls) throws Exception { + int n = dls.length(); + for (int k = 0; k < n; k++) { + JSONObject d = dls.getJSONObject(k); + File f = new File(d.getString("file")); + if (f.isFile()) { say("already downloaded: " + f.getName()); continue; } + f.getParentFile().mkdirs(); + final int idx = k; + say("downloading " + d.getString("url")); + dl = new Downloader(); + if (cancel) return "cancelled"; + final long[] lastLog = {0}; + String r = dl.fetch(d.getString("url"), f, (done, total) -> { + double frac = total > 0 ? (double) done / total : 0; + String detail = "File " + (idx + 1) + " of " + n + ": " + size(done) + (total > 0 ? " of " + size(total) : ""); + Engine.noteDownload((idx + frac) / n, detail); + if (done - lastLog[0] >= (50L << 20)) { // a log line every 50 MB + lastLog[0] = done; + say(" " + detail); + } + emitProgress(false); + }); + dl = null; + if (r != null) return r; + say(" done: " + f.getName() + " (" + size(f.length()) + ")"); + } + return null; + } + + static String size(long n) { + if (n >= (1L << 30)) return String.format(Locale.US, "%.1f GB", n / (double) (1L << 30)); + if (n >= (1L << 20)) return String.format(Locale.US, "%.0f MB", n / (double) (1L << 20)); + return (n >> 10) + " KB"; + } +} diff --git a/psprecomp/android/setup/java/org/psprecomp/setup/BuildService.java b/psprecomp/android/setup/java/org/psprecomp/setup/BuildService.java new file mode 100644 index 0000000..1989997 --- /dev/null +++ b/psprecomp/android/setup/java/org/psprecomp/setup/BuildService.java @@ -0,0 +1,107 @@ +package org.psprecomp.setup; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ServiceInfo; +import android.os.Build; +import android.os.IBinder; + +/** + * Keeps the app alive while the game is built (10 to 20 minutes): a foreground service with a progress notification, so switching to + * another app does not stop the build. The work itself runs in BuildRunner; this only holds the process in the foreground and shows + * where it is. When the build ends while the app is not on screen, a notification says so. + */ +public class BuildService extends Service { + private static final String CHANNEL = "build", CHANNEL_DONE = "build_done"; + private static final int ID = 7101, ID_DONE = 7102; + private static volatile String title = "Building the game", text = ""; + private static volatile int percent = -1; + + static void start(Context c) { + try { + Intent i = new Intent(c, BuildService.class); + if (Build.VERSION.SDK_INT >= 26) c.startForegroundService(i); else c.startService(i); + } catch (Exception e) { + // without it the build still runs while the app is open (the wake lock keeps the CPU on) + } + } + + static void stop(Context c) { + c.stopService(new Intent(c, BuildService.class)); + } + + /** New progress for the notification (cheap: only posted when something visible changed). */ + static void update(Context c, String t, String x, int pct) { + if (pct == percent && t.equals(title) && x.equals(text)) return; + title = t; + text = x; + percent = pct; + NotificationManager nm = (NotificationManager) c.getSystemService(NOTIFICATION_SERVICE); + if (nm != null && allowed(c)) nm.notify(ID, build(c)); + } + + /** The build ended while the player was elsewhere. */ + static void finished(Context c, boolean ok, String msg) { + NotificationManager nm = (NotificationManager) c.getSystemService(NOTIFICATION_SERVICE); + if (nm == null || !allowed(c)) return; + channels(nm); + Notification.Builder b = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(c, CHANNEL_DONE) : new Notification.Builder(c); + b.setSmallIcon(c.getResources().getIdentifier("ic_stat_crystal", "drawable", c.getPackageName())).setContentTitle(ok ? "The game is ready" : "The setup stopped").setContentText(msg) + .setStyle(new Notification.BigTextStyle().bigText(msg)).setContentIntent(open(c)).setAutoCancel(true); + nm.notify(ID_DONE, b.build()); + } + + static void clearFinished(Context c) { + NotificationManager nm = (NotificationManager) c.getSystemService(NOTIFICATION_SERVICE); + if (nm != null) nm.cancel(ID_DONE); + } + + private static boolean allowed(Context c) { + return Build.VERSION.SDK_INT < 33 || c.checkSelfPermission("android.permission.POST_NOTIFICATIONS") == PackageManager.PERMISSION_GRANTED; + } + + private static void channels(NotificationManager nm) { + if (Build.VERSION.SDK_INT < 26) return; + NotificationChannel ch = new NotificationChannel(CHANNEL, "Build progress", NotificationManager.IMPORTANCE_LOW); + ch.setShowBadge(false); + nm.createNotificationChannel(ch); + nm.createNotificationChannel(new NotificationChannel(CHANNEL_DONE, "Build finished", NotificationManager.IMPORTANCE_DEFAULT)); + } + + private static PendingIntent open(Context c) { + Intent i = new Intent(c, SetupActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + return PendingIntent.getActivity(c, 0, i, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + } + + private static Notification build(Context c) { + NotificationManager nm = (NotificationManager) c.getSystemService(NOTIFICATION_SERVICE); + if (nm != null) channels(nm); + Notification.Builder b = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(c, CHANNEL) : new Notification.Builder(c); + b.setSmallIcon(c.getResources().getIdentifier("ic_stat_crystal", "drawable", c.getPackageName())).setContentTitle(title).setContentText(text).setOngoing(true).setOnlyAlertOnce(true) + .setContentIntent(open(c)).setProgress(100, Math.max(0, percent), percent < 0); + if (Build.VERSION.SDK_INT >= 31) b.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE); + return b.build(); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + try { + if (Build.VERSION.SDK_INT >= 29) startForeground(ID, build(this), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC); + else startForeground(ID, build(this)); + } catch (Exception e) { + stopSelf(); + } + return START_NOT_STICKY; + } + + @Override + public IBinder onBind(Intent i) { + return null; + } +} diff --git a/psprecomp/android/setup/java/org/psprecomp/setup/Card.java b/psprecomp/android/setup/java/org/psprecomp/setup/Card.java new file mode 100644 index 0000000..0f98f66 --- /dev/null +++ b/psprecomp/android/setup/java/org/psprecomp/setup/Card.java @@ -0,0 +1,396 @@ +package org.psprecomp.setup; + +import android.animation.ValueAnimator; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.Rect; +import android.graphics.Shader; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.DecelerateInterpolator; +import android.view.animation.OvershootInterpolator; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** + * One choice on a page: a panel with chamfered corners and a thin gold frame (the game's menu windows), an icon in a crystal badge, a + * title, a line of explanation and, at the end, a chevron, a value, an On/Off crystal switch or a two-way choice. Focus (d-pad / controller) + * lights the frame and sends a shine across; a press sinks it a little. Left / right flip a switch or a choice. + */ +final class Card extends LinearLayout { + static final int ACTION = 0, TOGGLE = 1, CHOICE = 2, INFO = 3; + static final int STYLE_NORMAL = 0, STYLE_PRIMARY = 1, STYLE_DANGER = 2, STYLE_QUIET = 3; + + interface OnChange { + void changed(Card c); + } + + final int kind; + int style = STYLE_NORMAL; + private final TextView titleView, summaryView, valueView; + private final Icons.IconView iconView; + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG), stroke = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Path shape = new Path(); + private float focusT = 0, shineT = 2, switchT = 0, pulse = 0; + private ValueAnimator focusAnim, shineAnim, switchAnim; + private boolean on; + private String[] choices; + private int choice; + private OnChange onChange; + private final int chamfer = Theme.dp(12); + private boolean enabledLook = true; + + Card(Context c, int kind, int icon, String title, String summary) { + super(c); + this.kind = kind; + setOrientation(HORIZONTAL); + setGravity(Gravity.CENTER_VERTICAL); + setWillNotDraw(false); + setClipToPadding(false); + int ph = Theme.dp(16), pv = Theme.dp(kind == INFO ? 12 : 14); + setPadding(ph, pv, ph, pv); + setMinimumHeight(Theme.dp(kind == INFO ? 52 : 64)); + if (kind != INFO) { + setFocusable(true); + setClickable(true); + } + + iconView = new Icons.IconView(c, icon, Theme.GOLD); + iconView.strokeDp = 1.7f; + LayoutParams ip = new LayoutParams(Theme.dp(26), Theme.dp(26)); + ip.rightMargin = Theme.dp(16); + ip.leftMargin = Theme.dp(4); + if (icon != Icons.NONE) addView(iconView, ip); + + LinearLayout col = new LinearLayout(c); + col.setOrientation(VERTICAL); + titleView = Theme.text(c, title, 16.5f, Theme.TEXT, Theme.bodyBold); + summaryView = Theme.text(c, summary == null ? "" : summary, 13, Theme.TEXT_DIM, Theme.body); + summaryView.setLineSpacing(Theme.dpf(1.5f), 1f); + summaryView.setVisibility(summary == null || summary.isEmpty() ? GONE : VISIBLE); + col.addView(titleView); + LayoutParams sp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + sp.topMargin = Theme.dp(2); + col.addView(summaryView, sp); + addView(col, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1)); + + valueView = Theme.text(c, "", 13.5f, Theme.GOLD_LIGHT, Theme.bodyBold); + if (kind == CHOICE) { // the choice sits under the title as a chip (room for the explanation on narrow screens) + android.graphics.drawable.GradientDrawable chip = new android.graphics.drawable.GradientDrawable(); + chip.setColor(0x40E2C47A); + chip.setStroke(Theme.dp(1), 0x90E2C47A); + chip.setCornerRadius(Theme.dp(14)); + valueView.setBackground(chip); + valueView.setPadding(Theme.dp(12), Theme.dp(4), Theme.dp(12), Theme.dp(5)); + LayoutParams vp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + vp.topMargin = Theme.dp(6); + vp.bottomMargin = Theme.dp(2); + col.addView(valueView, 1, vp); + } else { + valueView.setGravity(Gravity.END | Gravity.CENTER_VERTICAL); + valueView.setMaxWidth(Theme.dp(220)); + LayoutParams vp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + vp.leftMargin = Theme.dp(12); + addView(valueView, vp); + } + // room for what is drawn at the end (chevron or switch) + View endSpace = new View(c); + int endW = kind == TOGGLE ? 54 : kind == ACTION ? 22 : kind == CHOICE ? 6 : 0; + if (endW > 0) addView(endSpace, new LayoutParams(Theme.dp(endW), 1)); + + setOnFocusChangeListener((v, has) -> { + animateFocus(has); + if (has) shine(); + }); + } + + Card style(int s) { + style = s; + if (s == STYLE_DANGER) iconView.set(iconView.icon, Theme.DANGER); + if (s == STYLE_PRIMARY) titleView.setTextColor(Theme.GOLD_LIGHT); + if (s == STYLE_QUIET) { + titleView.setTextSize(15); + setMinimumHeight(Theme.dp(54)); + } + invalidate(); + return this; + } + + Card value(String v) { + valueView.setText(v == null ? "" : v); + return this; + } + + Card summary(String s) { + summaryView.setText(s == null ? "" : s); + summaryView.setVisibility(s == null || s.isEmpty() ? GONE : VISIBLE); + return this; + } + + Card title(String s) { + titleView.setText(s); + return this; + } + + Card icon(int icon, int color) { + iconView.set(icon, color); + return this; + } + + Card onClick(OnClickListener l) { + setOnClickListener(l); + return this; + } + + Card onChange(OnChange l) { + onChange = l; + return this; + } + + Card toggle(boolean v) { + on = v; + switchT = v ? 1 : 0; + valueView.setText(""); + setContentDescription(titleView.getText() + (v ? ", on" : ", off")); + setOnClickListener(x -> flip(+1)); + return this; + } + + Card choices(String[] c, int sel) { + choices = c; + choice = sel; + valueView.setText("‹ " + c[sel] + " ›"); + setOnClickListener(x -> flip(+1)); + return this; + } + + boolean isOn() { + return on; + } + + int choice() { + return choice; + } + + /** Greys the card out (a feature this release does not have yet): it stays readable but cannot be changed or focused. */ + Card disabled(String why) { + enabledLook = false; + setFocusable(false); + setClickable(false); + setAlpha(0.5f); + if (why != null) valueView.setText(why); + valueView.setTextColor(Theme.TEXT_FAINT); + return this; + } + + private void flip(int dir) { + if (!enabledLook) return; + if (kind == TOGGLE) { + on = !on; + setContentDescription(titleView.getText() + (on ? ", on" : ", off")); + if (switchAnim != null) switchAnim.cancel(); + switchAnim = ValueAnimator.ofFloat(switchT, on ? 1 : 0); + switchAnim.setDuration(260); + switchAnim.setInterpolator(new OvershootInterpolator(1.6f)); + switchAnim.addUpdateListener(a -> { switchT = (float) a.getAnimatedValue(); invalidate(); }); + switchAnim.start(); + } else if (kind == CHOICE && choices != null) { + choice = (choice + dir + choices.length) % choices.length; + valueView.setText("‹ " + choices[choice] + " ›"); + valueView.setAlpha(0); + valueView.setTranslationX(Theme.dp(10) * dir); + valueView.animate().alpha(1).translationX(0).setDuration(220).setInterpolator(new DecelerateInterpolator()).start(); + } + shine(); + if (onChange != null) onChange.changed(this); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent e) { + if ((kind == TOGGLE || kind == CHOICE) && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { + if (kind == TOGGLE) { + boolean want = keyCode == KeyEvent.KEYCODE_DPAD_RIGHT; + if (want != on) flip(1); + } else flip(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : -1); + return true; + } + return super.onKeyDown(keyCode, e); + } + + @Override + public void setPressed(boolean p) { + super.setPressed(p); + if (!enabledLook || kind == INFO) return; + animate().scaleX(p ? 0.975f : 1f).scaleY(p ? 0.975f : 1f).setDuration(p ? 90 : 220).setInterpolator(new DecelerateInterpolator()).start(); + invalidate(); + } + + @Override + public boolean onTouchEvent(MotionEvent e) { + if (e.getActionMasked() == MotionEvent.ACTION_UP && isPressed()) shine(); + return super.onTouchEvent(e); + } + + private void animateFocus(boolean has) { + if (focusAnim != null) focusAnim.cancel(); + focusAnim = ValueAnimator.ofFloat(focusT, has ? 1 : 0); + focusAnim.setDuration(200); + focusAnim.addUpdateListener(a -> { focusT = (float) a.getAnimatedValue(); invalidate(); }); + focusAnim.start(); + animate().scaleX(has ? 1.015f : 1f).scaleY(has ? 1.015f : 1f).setDuration(200).start(); + } + + private void shine() { + if (shineAnim != null) shineAnim.cancel(); + shineAnim = ValueAnimator.ofFloat(-0.3f, 1.3f); + shineAnim.setDuration(650); + shineAnim.setInterpolator(new DecelerateInterpolator()); + shineAnim.addUpdateListener(a -> { shineT = (float) a.getAnimatedValue(); invalidate(); }); + shineAnim.start(); + } + + /** A soft breathing glow on the frame (the suggested next step). */ + Card pulse() { + ValueAnimator a = ValueAnimator.ofFloat(0, 1); + a.setDuration(1800); + a.setRepeatCount(ValueAnimator.INFINITE); + a.setRepeatMode(ValueAnimator.REVERSE); + a.addUpdateListener(x -> { pulse = (float) x.getAnimatedValue(); invalidate(); }); + a.start(); + addOnAttachStateChangeListener(new OnAttachStateChangeListener() { + public void onViewAttachedToWindow(View v) {} + public void onViewDetachedFromWindow(View v) { a.cancel(); } + }); + return this; + } + + static void chamferPath(Path p, float l, float t, float r, float b, float ch) { + p.reset(); + p.moveTo(l + ch, t); + p.lineTo(r, t); + p.lineTo(r, b - ch); + p.lineTo(r - ch, b); + p.lineTo(l, b); + p.lineTo(l, t + ch); + p.close(); + } + + @Override + protected void onDraw(Canvas c) { + if (getWidth() < 4 || getHeight() < 4) return; // not laid out (yet): gradients need a size + final float w = getWidth(), h = getHeight(), inset = Theme.dpf(1); + chamferPath(shape, inset, inset, w - inset, h - inset, chamfer); + int accent = style == STYLE_DANGER ? Theme.DANGER : style == STYLE_PRIMARY ? Theme.GOLD : Theme.GOLD; + boolean pressed = isPressed(); + + // fill: dark glass, brighter on focus / press; the primary card carries a warm gold tint + int top = style == STYLE_PRIMARY ? 0xE8473C26 : style == STYLE_DANGER ? 0xC02A1420 : kind == INFO ? 0x80101830 : Theme.PANEL_HI; + int bottom = style == STYLE_PRIMARY ? 0xE81E1A2E : style == STYLE_DANGER ? 0xC0160A12 : kind == INFO ? 0x700A1024 : Theme.PANEL; + float lift = Math.max(focusT, pressed ? 0.7f : 0); + paint.setColor(0xFFFFFFFF); // a shader is multiplied by the paint's alpha + paint.setShader(new LinearGradient(0, 0, 0, h, Theme.mix(top, 0xF0344070, lift * 0.35f), Theme.mix(bottom, 0xF0202A50, lift * 0.35f), Shader.TileMode.CLAMP)); + c.drawPath(shape, paint); + paint.setShader(null); + + // glow around the frame when focused (drawn as wide faint strokes) + float glowA = Math.max(focusT, pulse * 0.45f); + if (glowA > 0.01f) { + stroke.setStyle(Paint.Style.STROKE); + for (int i = 3; i >= 1; i--) { + stroke.setStrokeWidth(Theme.dpf(2.5f * i)); + stroke.setColor(Theme.alpha(accent, 0.07f * glowA)); + c.drawPath(shape, stroke); + } + } + // the frame: a gold line, brighter at the top-left like light on metal + stroke.setStyle(Paint.Style.STROKE); + stroke.setStrokeWidth(Theme.dpf(style == STYLE_PRIMARY ? 1.4f : 1)); + int frameA = Theme.alpha(accent, 0.30f + 0.6f * Math.max(glowA, style == STYLE_PRIMARY ? 0.45f : 0)); + stroke.setColor(0xFFFFFFFF); // a shader is multiplied by the paint's alpha + stroke.setShader(new LinearGradient(0, 0, w, h, new int[] {Theme.mix(frameA, 0xFFFFFFFF, 0.25f), frameA, Theme.alpha(accent, 0.18f + 0.4f * glowA)}, + null, Shader.TileMode.CLAMP)); + c.drawPath(shape, stroke); + stroke.setShader(null); + // corner ticks at the chamfers + stroke.setColor(Theme.alpha(accent, 0.55f + 0.45f * glowA)); + stroke.setStrokeWidth(Theme.dpf(2)); + c.drawLine(inset + chamfer * 0.15f, inset + chamfer * 0.85f, inset + chamfer * 0.85f, inset + chamfer * 0.15f, stroke); + c.drawLine(w - inset - chamfer * 0.85f, h - inset - chamfer * 0.15f, w - inset - chamfer * 0.15f, h - inset - chamfer * 0.85f, stroke); + + // the shine that runs across once on focus / tap + if (shineT > -0.3f && shineT < 1.3f) { + c.save(); + c.clipPath(shape); + float x = shineT * (w + h) - h; + paint.setColor(0xFFFFFFFF); // a shader is multiplied by the paint's alpha + paint.setShader(new LinearGradient(x, 0, x + h * 0.9f, h, new int[] {0, 0x30FFF4D6, 0}, null, Shader.TileMode.CLAMP)); + c.drawRect(0, 0, w, h, paint); + paint.setShader(null); + c.restore(); + } + // the icon's crystal badge + if (iconView.getParent() != null && iconView.icon != Icons.NONE) { + float cx = iconView.getLeft() + iconView.getWidth() / 2f, cy = iconView.getTop() + iconView.getHeight() / 2f, r = Theme.dpf(21); + Path d = new Path(); + d.moveTo(cx, cy - r); + d.lineTo(cx + r, cy); + d.lineTo(cx, cy + r); + d.lineTo(cx - r, cy); + d.close(); + paint.setColor(Theme.alpha(style == STYLE_DANGER ? Theme.DANGER : Theme.GOLD, 0.08f + 0.1f * glowA)); + c.drawPath(d, paint); + stroke.setColor(Theme.alpha(style == STYLE_DANGER ? Theme.DANGER : Theme.GOLD, 0.25f + 0.35f * glowA)); + stroke.setStrokeWidth(Theme.dpf(1)); + c.drawPath(d, stroke); + } + // end decoration + if (kind == ACTION && enabledLook) { + float cx = w - Theme.dpf(22), cy = h / 2; + Icons.draw(c, Icons.CHEVRON, cx + Theme.dpf(3) * focusT, cy, Theme.dpf(16), Theme.alpha(accent, 0.5f + 0.5f * focusT), Theme.dpf(1.8f)); + } else if (kind == TOGGLE) { + drawSwitch(c, w - Theme.dpf(16) - Theme.dpf(44), h / 2); + } + } + + private void drawSwitch(Canvas c, float x, float cy) { + float tw = Theme.dpf(44), th = Theme.dpf(20); + int track = Theme.mix(0x40FFFFFF, Theme.alpha(Theme.CRYSTAL_DEEP, 0.85f), switchT); + paint.setColor(track); + c.drawRoundRect(x, cy - th / 2, x + tw, cy + th / 2, th / 2, th / 2, paint); + stroke.setStyle(Paint.Style.STROKE); + stroke.setStrokeWidth(Theme.dpf(1)); + stroke.setColor(Theme.mix(0x50FFFFFF, Theme.CRYSTAL, switchT)); + c.drawRoundRect(x, cy - th / 2, x + tw, cy + th / 2, th / 2, th / 2, stroke); + // the thumb is a small crystal + float tx = x + th / 2 + (tw - th) * Math.max(0, Math.min(1.08f, switchT)), r = th * 0.62f; + if (switchT > 0.05f) { + paint.setColor(Theme.alpha(Theme.CRYSTAL, 0.25f * switchT)); + c.drawCircle(tx, cy, r * 1.6f, paint); + } + Path d = new Path(); + d.moveTo(tx, cy - r); + d.lineTo(tx + r * 0.62f, cy); + d.lineTo(tx, cy + r); + d.lineTo(tx - r * 0.62f, cy); + d.close(); + paint.setColor(Theme.mix(0xFFB8BED0, 0xFFE9FFF7, switchT)); + c.drawPath(d, paint); + stroke.setColor(Theme.mix(0xFF7A8098, Theme.CRYSTAL_DEEP, switchT)); + c.drawPath(d, stroke); + stroke.setColor(0x60FFFFFF); + c.drawLine(tx - r * 0.62f, cy, tx + r * 0.62f, cy, stroke); + } + + @Override + protected void onFocusChanged(boolean gain, int dir, Rect prev) { + super.onFocusChanged(gain, dir, prev); + if (gain) { // keep the focused card in view inside a scroller + requestRectangleOnScreen(new Rect(0, -Theme.dp(24), getWidth(), getHeight() + Theme.dp(24)), false); + } + } +} diff --git a/psprecomp/android/setup/java/org/psprecomp/setup/CrashReports.java b/psprecomp/android/setup/java/org/psprecomp/setup/CrashReports.java new file mode 100644 index 0000000..56a02e7 --- /dev/null +++ b/psprecomp/android/setup/java/org/psprecomp/setup/CrashReports.java @@ -0,0 +1,110 @@ +package org.psprecomp.setup; + +import android.content.Context; +import android.os.Build; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * Crash reports of the setup app itself: an uncaught exception writes files/crash/crash-