diff --git a/README.md b/README.md index 0f07635..c7116fa 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ # Pakkit -**Pocket to Wrist.** A standalone Wear OS application for sending an APK from any browser on your Wi-Fi to your watch, then approving installation on your wrist. +**Pack it. Send it. Wear it.** Give your next app a place on your wrist. -Pack it. Send it. Wear it. +Send an APK from your browser to your Wear OS watch, then approve installation on your watch. ## Use -1. Open Pakkit on a supported watch and allow it to request installations through the system settings screen. +1. Open Pakkit on a supported watch. 2. Connect the watch and browser device to the same trusted Wi-Fi. -3. Tap **Start receiving** and scan the QR code or type the complete private link. Opening only the address lets you enter the session key separately. +3. Tap **Start receiving** and scan the QR code. For manual entry, tap **View link** on the watch and open the complete link in your browser. 4. Select one complete `.apk` up to **50 MiB**. Watch transfer progress in the browser and on the watch. -5. Review the package on the watch, tap **Install**, and complete Android’s system approval. +5. Review the app on your watch. If prompted, tap **Allow installs** to grant source permission, then tap **Install** and approve it. 6. End the receiving session when finished. Sessions automatically end after ten minutes or on Wi-Fi loss. The local connection uses **unencrypted HTTP**. Use trusted Wi-Fi and keep the private link secret. Package inspection checks format and compatibility; it does not certify app safety. Source approval, firmware security policy and Android’s installer determine whether installation is available. Split packages and app bundles are unsupported. See [platform constraints](docs/PLATFORM.md). @@ -49,8 +49,8 @@ Routine development uses emulators. No physical watch is required. ```sh ./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest -python 3 scripts/test-emulators.py --watch emulator-5554 --skip-build -python 3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build +python3 scripts/test-emulators.py --watch emulator-5554 --skip-build +python3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build ``` For browser tests and real Android-Emulator-to-Wear-Emulator uploads, see [development and testing](docs/DEVELOPMENT.md). Results and screenshots are generated under `app/build/reports/validation`, not checked into source control. diff --git a/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt b/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt index 0eaf153..0592107 100644 --- a/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt @@ -67,7 +67,7 @@ class LocalReceiveTest : WatchTest() { head.toString() + bytes.toString(Charsets.UTF_8) } } - assertTrue(request("GET", "/").contains("Pocket")) + assertTrue(request("GET", "/").contains("Pack it.")) assertTrue(request("GET", "/api/status", token = null).startsWith("HTTP/1.1 403")) assertTrue(request("GET", "/api/status", token = "wrong").startsWith("HTTP/1.1 403")) assertTrue( diff --git a/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt b/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt index f0eba52..7ce51b6 100644 --- a/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt @@ -28,7 +28,7 @@ class ServerExpiryTest : WatchTest() { socket.getInputStream().bufferedReader().readText() } assertTrue(response.startsWith("HTTP/1.1 400")) - assertTrue(response.contains("session ended")) + assertTrue(response.contains("didn’t arrive")) assertNull(store.pending()) } } diff --git a/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt b/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt new file mode 100644 index 0000000..03257f6 --- /dev/null +++ b/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt @@ -0,0 +1,132 @@ +package meghdad.pakkit + +import android.graphics.Bitmap +import android.graphics.Rect +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.TextView +import androidx.test.ext.junit.runners.AndroidJUnit4 +import java.io.File +import meghdad.pakkit.apk.InstallState +import meghdad.pakkit.transfer.Receiving +import meghdad.pakkit.ui.RoundScrollView +import meghdad.pakkit.ui.WatchActivity +import meghdad.pakkit.ui.WatchDesign +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class WatchExperienceTest : WatchTest() { + private fun views(view: View): List = + listOf(view) + + if (view is ViewGroup) (0 until view.childCount).flatMap { views(view.getChildAt(it)) } + else emptyList() + + private fun screen() = views(requireNotNull(activity).window.decorView) + + private fun capture(name: String) { + instrumentation.waitForIdleSync() + Thread.sleep(220) // Finite screen entrance; screenshots capture the settled UI. + val bitmap = requireNotNull(instrumentation.uiAutomation.takeScreenshot()) + val folder = File(context.getExternalFilesDir(null), "product-review").apply { mkdirs() } + File(folder, "$name.png").outputStream().use { + bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) + } + bitmap.recycle() + } + + private fun assertActionsReachable() { + instrumentation.runOnMainSync { + val all = screen() + val scroll = all.filterIsInstance().single() + for (button in all.filterIsInstance
-

A LITTLE MAGIC. RIGHT ON YOUR WRIST.

-

Pocket
to Wrist.

-

- Your favorite apps, with a shorter journey.
One watch. Any browser. All yours. -

+

A LITTLE POSSIBILITY. ON YOUR WRIST.

+

Pack it.
Send it.
Wear it.

+

Give your next app a place on your wrist.

- DIRECT TO YOUR WATCHYOUR NEXT APP↗ On your Wi-Fi
-

A new home
for your next app.

-

Choose a compatible APK. We’ll take it from here.

+

Good things
come in Pakkits.

+

Choose an app for your watch. We’ll deliver it.

+
    +
  1. Choose
  2. +
  3. Send
  4. +
  5. Wear
  6. +
- Drop a little possibility.Drag your APK here, or choose a file below.A little app. A new possibility.Drop an APK here to get started.Single .apk file · up to 50 MiB + />APK files · up to 50 MB
-
-
-
- 01 -

Pick your app.
A complete APK you trust.

-
-
- 02 -

Send it over.
Straight across your Wi-Fi.

-
-
- 03 -

Make it yours.
Approve it on your wrist.

-
-
- Pakkit / A lighter way to wear your apps.Local HTTP session · trusted Wi-Fi only + Pakkit / Pack it. Send it. Wear it.
+ About this connection +

+ Use Wi-Fi you trust. Files travel across your network without encryption. Keep your + watch’s link private. +

+
+
diff --git a/app/src/main/assets/web/style.css b/app/src/main/assets/web/style.css index dc4b4ba..b389055 100644 --- a/app/src/main/assets/web/style.css +++ b/app/src/main/assets/web/style.css @@ -19,31 +19,38 @@ 'Segoe UI', sans-serif; } + * { box-sizing: border-box; } + body { margin: 0; background: var(--bg); color: var(--text); min-width: 300px; } + button, input { font: inherit; } + button, a, input { -webkit-tap-highlight-color: transparent; } + button { cursor: pointer; } + button:disabled { cursor: default; opacity: 0.5; } + button:focus-visible, a:focus-visible, input:focus-visible, @@ -51,9 +58,11 @@ input:focus-visible, outline: 3px solid var(--mint); outline-offset: 5px; } + [hidden] { display: none !important; } + .ambient { position: absolute; top: 0; @@ -65,17 +74,20 @@ input:focus-visible, radial-gradient(ellipse at 10% 40%, #7145ec19, transparent 50%), radial-gradient(ellipse at 95% 10%, #28e0d60b, transparent 45%); } + .shell { max-width: 1260px; margin: auto; padding: 34px 52px 24px; position: relative; } + header { display: flex; align-items: center; gap: 20px; } + .wordmark { font-size: 30px; font-weight: 780; @@ -86,6 +98,7 @@ header { align-items: center; gap: 9px; } + .brand-icon { background: linear-gradient(140deg, #bda8ff, #7049ed); border-radius: 11px; @@ -97,10 +110,12 @@ header { font-size: 31px; line-height: 1; } + .brand-dot { color: var(--mint); margin-left: -9px; } + .connection { margin-left: auto; display: flex; @@ -109,6 +124,7 @@ header { font-size: 12px; color: var(--muted); } + .connection > span:first-child { width: 6px; height: 6px; @@ -116,23 +132,28 @@ header { border-radius: 50%; box-shadow: 0 0 12px #80efd855; } + .icon-button { border: 1px solid var(--border); border-radius: 50%; background: var(--soft); color: var(--text); - width: 40px; - height: 40px; + width: 44px; + height: 44px; font-size: 22px; flex-shrink: 0; + min-width: 44px; } + main { display: grid; grid-template-columns: 1fr 1fr; - gap: 70px; + gap: 88px; align-items: center; padding: 76px 0 54px; + padding-top: 56px; } + .eyebrow { font-size: 10px; letter-spacing: 2.6px; @@ -140,34 +161,41 @@ main { font-weight: 750; margin: 0 0 24px; } + h1 { - font-size: clamp(66px, 7.6vw, 104px); - line-height: 0.99; - letter-spacing: -6px; + font-size: clamp(64px, 6.4vw, 88px); + line-height: 1.06; + letter-spacing: -4.8px; font-weight: 740; margin: 0; } + h1 em { font-style: normal; background: linear-gradient(110deg, #bd9fff, #91befc 60%, #79e7d6); background-clip: text; color: transparent; } + .lede { - font-size: 16px; - line-height: 1.8; + font-size: 17px; + line-height: 1.65; color: var(--muted); margin: 24px 0 0; + max-width: 320px; } + .parcel-stage { position: relative; - height: 250px; + height: 215px; max-width: 390px; margin: 0 auto; display: flex; align-items: center; justify-content: center; + margin-top: 12px; } + .parcel-stage:before { content: ''; position: absolute; @@ -175,13 +203,15 @@ h1 em { background: radial-gradient(ellipse, #8752ff29, transparent 65%); border-radius: 50%; } + .parcel { - width: 285px; - height: 270px; + width: 260px; + height: 245px; position: relative; filter: drop-shadow(0 16px 26px #8560e522); animation: arrive 0.8s ease-out both; } + .orbit { position: absolute; width: 300px; @@ -191,27 +221,23 @@ h1 em { transform: rotate(-13deg); bottom: 36px; } + .orbit-two { width: 340px; bottom: 26px; border-color: #8df2de0c; } -.stage-caption { - position: absolute; - bottom: -5px; - font-size: 9px; - letter-spacing: 3px; - color: var(--muted); -} + .transfer-card { background: linear-gradient(145deg, var(--surface), var(--bg)); border: 1px solid var(--border); - border-radius: 30px; - padding: 30px; + border-radius: 32px; + padding: 32px; box-shadow: 0 24px 80px var(--shadow); position: relative; overflow: hidden; } + .transfer-card:before { content: ''; height: 2px; @@ -221,12 +247,14 @@ h1 em { top: 0; background: linear-gradient(90deg, transparent, #a088ff77, transparent); } + .card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; } + .pill { font-size: 9px; font-weight: 750; @@ -237,10 +265,12 @@ h1 em { border-radius: 30px; padding: 8px 10px; } + .private-label { font-size: 10px; color: var(--muted); } + h2 { font-size: 34px; line-height: 1.13; @@ -248,12 +278,14 @@ h2 { margin: 28px 0 12px; font-weight: 650; } + .card-description { color: var(--muted); - font-size: 13px; + font-size: 14px; line-height: 1.7; margin: 0 0 24px; } + .dropzone { border: 1px dashed #a596d047; background: var(--soft); @@ -267,11 +299,13 @@ h2 { border-color 0.2s, transform 0.2s; } + .dropzone.dragging { border-color: var(--mint); background: #7aefd513; transform: scale(1.01); } + .upload-symbol { width: 45px; height: 45px; @@ -284,17 +318,20 @@ h2 { font-size: 28px; margin-bottom: 18px; } + .dropzone strong { font-size: 16px; font-weight: 600; letter-spacing: -0.3px; } + .dropzone > span { font-size: 11px; color: var(--muted); margin: 8px 0 20px; text-align: center; } + .primary { border: 1px solid #c3abff40; border-radius: 12px; @@ -314,25 +351,31 @@ h2 { gap: 25px; width: 100%; } + .dropzone .primary { width: 90%; max-width: 255px; } + .primary:hover:enabled { transform: translateY(-2px); box-shadow: 0 9px 28px #6840db40; } + .primary:active:enabled { transform: translateY(0); } + small { color: var(--muted); font-size: 10px; display: block; } + .dropzone small { margin-top: 14px; } + .consent-note { display: flex; gap: 12px; @@ -341,63 +384,34 @@ small { margin-top: 24px; padding-top: 20px; } + .consent-note > span { color: var(--mint); font-size: 24px; } + .consent-note p { font-size: 11px; line-height: 1.8; margin: 0; } + .consent-note p span { color: var(--muted); font-size: 10px; } + #message { font-size: 12px; line-height: 1.65; color: var(--error); margin: 12px 0 0; } + #message:empty { display: none; } -.journey { - display: grid; - grid-template-columns: repeat(3, 1fr); - gap: 30px; - border-top: 1px solid var(--border); - padding: 29px 0; -} -.journey > div { - display: flex; - gap: 17px; - align-items: center; -} -.journey > div > span { - color: var(--violet); - font-size: 11px; - font-variant-numeric: tabular-nums; - border: 1px solid var(--border); - border-radius: 50%; - width: 34px; - height: 34px; - display: grid; - place-items: center; - flex-shrink: 0; -} -.journey p { - margin: 0; - font-size: 11px; - color: var(--muted); - line-height: 1.9; -} -.journey strong { - color: var(--text); - font-size: 12px; - font-weight: 600; -} + footer { display: flex; justify-content: space-between; @@ -405,12 +419,16 @@ footer { border-top: 1px solid var(--border); padding-top: 22px; color: var(--muted); - font-size: 9px; + font-size: 11px; line-height: 1.8; + align-items: baseline; + flex-wrap: wrap; } + .muted { opacity: 0.7; } + .file-row { display: flex; align-items: center; @@ -421,21 +439,26 @@ footer { padding: 16px; margin-bottom: 18px; } + .file-row > div:nth-child(2) { min-width: 0; flex: 1; } + .file-row strong { font-size: 13px; overflow-wrap: anywhere; } + .file-row small { margin-top: 7px; } + .file-icon { color: var(--mint); font-size: 30px; } + .secondary { color: var(--text); border: 1px solid var(--border); @@ -446,42 +469,51 @@ footer { width: 100%; font-size: 12px; } + .progress-heading { display: flex; justify-content: space-between; font-size: 14px; margin-top: 30px; } + progress { width: 100%; - height: 8px; + height: 10px; border: 0; border-radius: 8px; overflow: hidden; accent-color: var(--mint); margin: 20px 0 6px; } + progress::-webkit-progress-bar { background: #a09abd22; border-radius: 8px; } + progress::-webkit-progress-value { background: linear-gradient(90deg, #8560ed, #7be6da); border-radius: 8px; } + progress::-moz-progress-bar { background: #80efd8; } + #progress-detail, #result-detail { font-size: 12px; line-height: 1.8; color: var(--muted); } + #result { text-align: center; padding: 18px 4px; + min-height: 230px; } + #result-icon { border-radius: 50%; width: 55px; @@ -493,22 +525,27 @@ progress::-moz-progress-bar { display: grid; place-items: center; } + h3 { font-size: 24px; letter-spacing: -0.8px; margin: 12px 0; } + #access-form { margin-bottom: 24px; } + #access-form label { font-size: 13px; } + #access-form p { font-size: 12px; color: var(--muted); line-height: 1.6; } + input:not([type='file']) { width: 100%; background: var(--bg); @@ -518,6 +555,7 @@ input:not([type='file']) { padding: 12px; margin: 4px 0 12px; } + [data-theme='light'] { color-scheme: light; --bg: #f6f5fc; @@ -531,13 +569,126 @@ input:not([type='file']) { --shadow: #4420800c; --error: #a52445; } + [data-theme='light'] h1 em { background: linear-gradient(110deg, #7144d7, #3669ba 65%, #16866f); background-clip: text; } + [data-theme='light'] .parcel-stage:before { background: radial-gradient(ellipse, #8158e51c, transparent 70%); } + +.brand-icon svg { + width: 29px; + height: 29px; +} + +.steps { + display: flex; + list-style: none; + padding: 0; + margin: 0 0 24px; + gap: 8px; + counter-reset: step; +} + +.steps li { + flex: 1; + display: flex; + align-items: center; + gap: 7px; + font-size: 12px; + color: var(--muted); + counter-increment: step; +} + +.steps li::before { + content: counter(step); + display: grid; + place-items: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: var(--soft); + border: 1px solid var(--border); + font-size: 10px; +} + +.steps [aria-current] { + color: var(--text); +} + +.steps [aria-current]::before { + background: #7854ee; + color: white; + border-color: #bca6ff; +} + +.steps .complete::before { + content: '✓'; + color: var(--mint); +} + +.connection[data-online='false'] > span:first-child { + background: var(--muted); + box-shadow: none; +} + +#result[data-state='failed'] #result-icon { + color: var(--error); + background: #e3677d16; +} + +#result[data-state='installed'] #result-icon { + animation: settle 420ms ease-out; +} + +#result:focus { + outline: none; +} + +#result-title { + outline: none; +} + +.connection-help { + max-width: 290px; +} + +.connection-help summary { + cursor: pointer; + font-size: 11px; + min-height: 24px; +} + +.connection-help p { + font-size: 12px; + line-height: 1.7; +} + +#expiry { + font-variant-numeric: tabular-nums; +} + +.dropzone > span, +small { + font-size: 12px; + line-height: 1.6; +} + +.consent-note p, +.consent-note p span { + font-size: 12px; +} + +.primary, +.secondary { + font-size: 14px; + border-radius: 16px; + min-height: 48px; +} + @keyframes arrive { from { opacity: 0; @@ -548,6 +699,18 @@ input:not([type='file']) { transform: translateY(0); } } + +@keyframes settle { + from { + transform: scale(0.85); + opacity: 0.4; + } + to { + transform: scale(1); + opacity: 1; + } +} + @media (prefers-reduced-motion: reduce) { *, *:before, @@ -557,129 +720,169 @@ input:not([type='file']) { scroll-behavior: auto !important; } } + @media (max-width: 900px) { .shell { padding: 26px 30px; } + main { gap: 30px; padding-top: 55px; } + h1 { font-size: 78px; } + .transfer-card { padding: 24px; } + .private-label { display: none; } } + @media (max-width: 680px) { .shell { padding: 22px; } + header { gap: 12px; } + .wordmark { font-size: 26px; } + .connection { font-size: 10px; max-width: 145px; } + main { display: flex; flex-direction: column; - gap: 32px; + gap: 28px; padding: 48px 0 32px; + padding-top: 32px; } + .intro { width: 100%; + position: relative; } + .eyebrow { font-size: 9px; margin-bottom: 18px; + letter-spacing: 1.6px; } + h1 { - font-size: 76px; - letter-spacing: -4px; + font-size: clamp(52px, 13vw, 76px); + letter-spacing: -3px; } + .lede { font-size: 14px; } + .parcel-stage { position: absolute; - right: 12px; - top: 170px; - width: 160px; - height: 180px; - opacity: 0.65; + right: -10px; + top: 42px; + width: 140px; + height: 170px; + opacity: 0.85; pointer-events: none; } + .parcel { width: 170px; + height: 180px; } + .orbit { - width: 145px; + width: 130px; height: 40px; bottom: 30px; } + .orbit-two { - width: 160px; - } - .stage-caption { - display: none; + width: 145px; } + .intro .lede { position: relative; max-width: 75%; + font-size: 14px; + margin-top: 16px; } + .transfer-card { width: 100%; - border-radius: 24px; - } - .journey { - gap: 18px; - grid-template-columns: 1fr; - } - .journey > div { - gap: 14px; - } - .journey p br { - display: none; - } - .journey p strong { - margin-right: 8px; + border-radius: 28px; + padding: 24px; } + footer { flex-direction: column; - gap: 8px; + gap: 12px; + margin-top: 4px; } + .card-top .private-label { display: block; } + h2 { - font-size: 32px; - } -} -@media (max-width: 370px) { - .parcel-stage { - opacity: 0.25; - } - .connection { - max-width: 100px; - } - .shell { - padding: 17px; - } - .card-top .private-label { - display: none; + font-size: 30px; + margin-top: 22px; } } -.brand-icon svg { - width: 29px; - height: 29px; +@media (max-width: 370px) { + .parcel-stage { + opacity: 0.5; + right: -12px; + } + + .connection { + max-width: 100px; + } + + .shell { + padding: 17px; + } + + .card-top .private-label { + display: none; + } + + .transfer-card { + padding: 20px; + } +} + +@media (max-width: 1000px) and (min-width: 681px) { + main { + gap: 36px; + } + + .transfer-card { + padding: 24px; + } + + h1 { + font-size: 65px; + letter-spacing: -3px; + } + + .steps li { + gap: 4px; + font-size: 11px; + } } diff --git a/app/src/main/java/meghdad/pakkit/apk/ApkRules.kt b/app/src/main/java/meghdad/pakkit/apk/ApkRules.kt index 12ac29e..abb6032 100644 --- a/app/src/main/java/meghdad/pakkit/apk/ApkRules.kt +++ b/app/src/main/java/meghdad/pakkit/apk/ApkRules.kt @@ -29,11 +29,11 @@ object ApkRules { if (count < 0) break if (count == 0) continue total += count - require(total <= max) { "Choose an APK up to 50 MiB." } + requireUser(total <= max) { "Choose an APK up to 50 MB." } hash.update(buffer, 0, count) output?.write(buffer, 0, count) } - require(total > 0) { "This file is empty." } + requireUser(total > 0) { "This file is empty. Choose another APK." } return total to hash.digest().joinToString("") { "%02x".format(it) } } } diff --git a/app/src/main/java/meghdad/pakkit/apk/PackageInspector.kt b/app/src/main/java/meghdad/pakkit/apk/PackageInspector.kt index 4316569..6cab657 100644 --- a/app/src/main/java/meghdad/pakkit/apk/PackageInspector.kt +++ b/app/src/main/java/meghdad/pakkit/apk/PackageInspector.kt @@ -9,24 +9,28 @@ import java.util.zip.ZipFile object PackageInspector { @Suppress("DEPRECATION") fun inspect(context: Context, file: File, hash: String): Apk { - require(file.length() in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MiB." } + requireUser(file.length() in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MB." } val abis = mutableSetOf() ZipFile(file).use { zip -> - require(zip.getEntry("AndroidManifest.xml") != null) { + requireUser(zip.getEntry("AndroidManifest.xml") != null) { "This file is not an Android APK." } - require(zip.size() < 100_000) { "This archive contains too many entries." } + requireUser(zip.size() < 100_000) { + "This file is too complex to open. Try another APK." + } var expanded = 0L zip.entries().asSequence().forEach { entry -> - require(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) { - "This APK contains an unusually large archive entry." + requireUser(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) { + "This app is too large to unpack. Try a smaller APK." } expanded += entry.size - require(expanded <= 200L * 1024 * 1024) { - "This APK expands beyond Pakkit’s package limit." + requireUser(expanded <= 200L * 1024 * 1024) { + "This app is too large to unpack. Try a smaller APK." } if (entry.name == "AndroidManifest.xml") - require(entry.size <= 2 * 1024 * 1024) { "This APK manifest is too large." } + requireUser(entry.size <= 2 * 1024 * 1024) { + "This file can’t be opened. Try another APK." + } val parts = entry.name.split('/') if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so")) abis += parts[1] @@ -36,17 +40,16 @@ object PackageInspector { context.packageManager.getPackageArchiveInfo( file.path, PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.GET_CONFIGURATIONS, - ) - ?: error( - "Android could not read this APK. Split packages and bundles are not supported.", - ) - require(info.splitNames.isNullOrEmpty()) { - "Choose a complete, single APK rather than a split package." + ) ?: throw UserMessage("This file can’t be opened. Choose a complete APK.") + requireUser(info.splitNames.isNullOrEmpty()) { + "This is only part of an app. Choose a complete APK." } - require(info.signingInfo?.apkContentsSigners?.isNotEmpty() == true) { - "This APK has no readable signing certificate." + requireUser(info.signingInfo?.apkContentsSigners?.isNotEmpty() == true) { + "This app’s signature can’t be verified. Get a fresh copy from its source." + } + requireUser(info.packageName != context.packageName) { + "Update Pakkit through Google Play." } - require(info.packageName != context.packageName) { "Update Pakkit through Google Play." } val app = requireNotNull(info.applicationInfo) app.sourceDir = file.path app.publicSourceDir = file.path @@ -57,22 +60,22 @@ object PackageInspector { .use { xml -> while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) { if (xml.eventType != org.xmlpull.v1.XmlPullParser.START_TAG) continue - require(xml.name != "uses-split") { - "Choose a complete APK; this file requires other splits." + requireUser(xml.name != "uses-split") { + "This is only part of an app. Choose a complete APK." } if (xml.name == "manifest") - require(xml.getAttributeValue(null, "split").isNullOrEmpty()) { - "This is a split APK. Choose a complete APK." + requireUser(xml.getAttributeValue(null, "split").isNullOrEmpty()) { + "This is only part of an app. Choose a complete APK." } if (xml.name == "application") - require( + requireUser( !xml.getAttributeBooleanValue( "http://schemas.android.com/apk/res/android", "isSplitRequired", false, - ), + ) ) { - "This APK requires additional splits." + "This is only part of an app. Choose a complete APK." } } } @@ -89,17 +92,17 @@ object PackageInspector { } fun checkForWatch(apk: Apk, sdk: Int, abis: Set, free: Long) { - require(apk.minSdk <= sdk) { - "This APK needs Android API ${apk.minSdk}; your watch runs API $sdk." + requireUser(apk.minSdk <= sdk) { + "This app needs a newer version of Android. Check your watch for updates." } - require(ApkRules.compatibleAbis(apk.abis, abis)) { - "This APK was built for a different processor." + requireUser(ApkRules.compatibleAbis(apk.abis, abis)) { + "This version doesn’t work on your watch. Try a version made for it." } requireSpace(apk.bytes, free) } fun requireSpace(bytes: Long, free: Long) { - require(free > bytes * 3 + 20 * 1024 * 1024) { + requireUser(free > bytes * 3 + 20 * 1024 * 1024) { "Free more storage on your watch, then try again." } } diff --git a/app/src/main/java/meghdad/pakkit/apk/PendingApk.kt b/app/src/main/java/meghdad/pakkit/apk/PendingApk.kt index 8f637f9..f811960 100644 --- a/app/src/main/java/meghdad/pakkit/apk/PendingApk.kt +++ b/app/src/main/java/meghdad/pakkit/apk/PendingApk.kt @@ -8,7 +8,7 @@ data class PendingApk( val created: Long, val apk: Apk, val state: InstallState = InstallState.READY, - val detail: String = "Review this app and approve installation on your watch.", + val detail: String = "Ready when you are.", val sessionId: Int? = null, ) { init { diff --git a/app/src/main/java/meghdad/pakkit/apk/UserMessage.kt b/app/src/main/java/meghdad/pakkit/apk/UserMessage.kt new file mode 100644 index 0000000..5bbce37 --- /dev/null +++ b/app/src/main/java/meghdad/pakkit/apk/UserMessage.kt @@ -0,0 +1,11 @@ +package meghdad.pakkit.apk + +/** Only deliberately written product copy may cross an exception boundary into the UI. */ +class UserMessage(message: String) : IllegalArgumentException(message) + +inline fun requireUser(value: Boolean, message: () -> String) { + if (!value) throw UserMessage(message()) +} + +fun Throwable.userMessage(fallback: String): String = + if (this is UserMessage) message ?: fallback else fallback diff --git a/app/src/main/java/meghdad/pakkit/install/ApkInstaller.kt b/app/src/main/java/meghdad/pakkit/install/ApkInstaller.kt index bd881e7..76bc55a 100644 --- a/app/src/main/java/meghdad/pakkit/install/ApkInstaller.kt +++ b/app/src/main/java/meghdad/pakkit/install/ApkInstaller.kt @@ -12,6 +12,8 @@ import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.InstallState import meghdad.pakkit.apk.PackageInspector import meghdad.pakkit.apk.PendingApk +import meghdad.pakkit.apk.requireUser +import meghdad.pakkit.apk.userMessage import meghdad.pakkit.data.PackageStore /** Called only after the watch's explicit Install action, on a worker thread. */ @@ -26,15 +28,17 @@ class ApkInstaller(private val context: Context) { context .getSystemService(NotificationManager::class.java) .cancel(InstallReceiver.NOTIFICATION) - check(context.packageManager.canRequestPackageInstalls()) { - "Allow Pakkit to request installs first." + requireUser(context.packageManager.canRequestPackageInstalls()) { + "Allow Pakkit to install apps, then try again." } - require(ApkRules.fresh(apk.created, System.currentTimeMillis())) { - "This APK expired. Upload it again." + requireUser(ApkRules.fresh(apk.created, System.currentTimeMillis())) { + "This file has expired. Send it again to install." } val file = store.file(apk.id) val digest = file.inputStream().use { ApkRules.copyBounded(it).second } - require(digest == apk.apk.sha256) { "This APK changed. Upload it again." } + requireUser(digest == apk.apk.sha256) { + "This file has changed. Send a fresh copy to install." + } val inspected = PackageInspector.inspect(context, file, digest) PackageInspector.checkForWatch( inspected, @@ -57,9 +61,9 @@ class ApkInstaller(private val context: Context) { store.update( apk.id, InstallState.INSTALLING, - "Waiting for the watch’s system installer.", + "Getting ready to install…", sessionId, - ), + ) ) { "This package review is no longer available." } @@ -79,11 +83,12 @@ class ApkInstaller(private val context: Context) { session.commit(pending.intentSender) } } catch (error: Exception) { + android.util.Log.w("PakkitInstall", "Installation preparation failed", error) sessionId?.let { runCatching { installer.abandonSession(it) } } store.update( apk.id, InstallState.FAILED, - error.message ?: "Could not open the system installer. Use Google Play.", + error.userMessage("Couldn’t start installation. Try again."), ) } } diff --git a/app/src/main/java/meghdad/pakkit/install/InstallReceiver.kt b/app/src/main/java/meghdad/pakkit/install/InstallReceiver.kt index 5f7311c..eb4a7db 100644 --- a/app/src/main/java/meghdad/pakkit/install/InstallReceiver.kt +++ b/app/src/main/java/meghdad/pakkit/install/InstallReceiver.kt @@ -41,7 +41,7 @@ class InstallReceiver : BroadcastReceiver() { store.update( apk.id, InstallState.FAILED, - "The system did not provide an approval screen.", + "Couldn’t open approval. Try again.", ) return } @@ -50,43 +50,9 @@ class InstallReceiver : BroadcastReceiver() { store.update( apk.id, InstallState.CONFIRM, - "Continue the system approval on your watch.", + "Ready for your approval.", ) - manager.createNotificationChannel( - NotificationChannel( - "installation", - "Installation approval", - NotificationManager.IMPORTANCE_DEFAULT, - ), - ) - if ( - Build.VERSION.SDK_INT < 33 || - context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == - PackageManager.PERMISSION_GRANTED - ) { - val open = - Intent(context, WatchActivity::class.java) - .putExtra("approval", confirmation) - .putExtra("job", apk.id) - val pending = - PendingIntent.getActivity( - context, - apk.sessionId, - open, - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, - ) - manager.notify( - NOTIFICATION, - Notification.Builder(context, "installation") - .setSmallIcon(R.drawable.pakkit_mark) - .setColor(WatchDesign.PURPLE) - .setContentTitle("Approve installation") - .setContentText("Open Pakkit to continue on your watch.") - .setContentIntent(pending) - .setAutoCancel(true) - .build(), - ) - } + notifyApproval(context) } PackageInstaller.STATUS_SUCCESS -> { PendingApproval.clear() @@ -101,17 +67,17 @@ class InstallReceiver : BroadcastReceiver() { PackageInstaller.STATUS_FAILURE_ABORTED -> "Installation was cancelled. You can try again." PackageInstaller.STATUS_FAILURE_BLOCKED -> - "The watch’s security policy blocked this installation. Use Google Play or contact the app developer." + "Your watch blocked this app. Look for it on Google Play." PackageInstaller.STATUS_FAILURE_CONFLICT -> - "This APK conflicts with an installed app or its signature. Ask the developer for a compatible version." + "A different version is already installed. Get a matching update from the app’s source." PackageInstaller.STATUS_FAILURE_INCOMPATIBLE -> - "This APK is not compatible with your watch." + "This app doesn’t work on your watch. Try a version made for it." PackageInstaller.STATUS_FAILURE_INVALID -> - "The system rejected this APK’s format or signature." + "Your watch couldn’t verify this app. Get a fresh copy from its source." PackageInstaller.STATUS_FAILURE_STORAGE -> - "Your watch needs more free storage." + "Free some space on your watch, then try again." else -> - "The system could not finish installing. Try again or use Google Play." + "Couldn’t finish installing. Try again or find the app on Google Play." } store.update(apk.id, InstallState.FAILED, detail) manager.cancel(NOTIFICATION) @@ -121,5 +87,48 @@ class InstallReceiver : BroadcastReceiver() { companion object { const val NOTIFICATION = 42 + + fun notifyApproval(context: Context) { + val apk = PackageStore(context).pending() ?: return + if (apk.state != InstallState.CONFIRM || PendingApproval.id != apk.id) return + val sessionId = apk.sessionId ?: return + val confirmation = PendingApproval.intent ?: return + val manager = context.getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel( + "installation", + "App installation", + NotificationManager.IMPORTANCE_DEFAULT, + ) + ) + if ( + Build.VERSION.SDK_INT < 33 || + context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + ) { + val open = + Intent(context, WatchActivity::class.java) + .putExtra("approval", confirmation) + .putExtra("job", apk.id) + val pending = + PendingIntent.getActivity( + context, + sessionId, + open, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + manager.notify( + NOTIFICATION, + Notification.Builder(context, "installation") + .setSmallIcon(R.drawable.pakkit_mark) + .setColor(WatchDesign.PURPLE) + .setContentTitle("Your app is ready to install") + .setContentText("Open Pakkit to give it the go-ahead.") + .setContentIntent(pending) + .setAutoCancel(true) + .build(), + ) + } + } } } diff --git a/app/src/main/java/meghdad/pakkit/transfer/LocalHttpServer.kt b/app/src/main/java/meghdad/pakkit/transfer/LocalHttpServer.kt index 255dd1d..15bc91a 100644 --- a/app/src/main/java/meghdad/pakkit/transfer/LocalHttpServer.kt +++ b/app/src/main/java/meghdad/pakkit/transfer/LocalHttpServer.kt @@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicBoolean import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.PackageInspector import meghdad.pakkit.apk.PendingApk +import meghdad.pakkit.apk.userMessage import meghdad.pakkit.data.PackageStore import org.json.JSONObject @@ -94,7 +95,7 @@ class LocalHttpServer( val input = BufferedInputStream(socket.getInputStream(), 8192) val request = HttpProtocol.read(input) check(!closed.get() && SystemClock.elapsedRealtime() < deadline) { - "The receiving session ended. Start a new one." + "Receiving has ended. Open a fresh link from your watch." } if (request.headers["host"] != authority) { response.error(403, "Open the address shown on your watch.") @@ -118,7 +119,7 @@ class LocalHttpServer( response.json(200, status()) request.method == "POST" && request.path == "/api/upload" -> { if (request.headers["origin"] != "http://$authority") - response.error(403, "Use Pakkit’s local page.") + response.error(403, "Open the link shown on your watch to send an app.") else upload(request, input, response) } else -> response.error(404, "Not found") @@ -128,7 +129,7 @@ class LocalHttpServer( runCatching { response.error( 400, - error.message?.take(180) ?: "Transfer interrupted. Try again.", + error.userMessage("Your app didn’t arrive. Choose the file and try again."), ) } } @@ -155,7 +156,7 @@ class LocalHttpServer( var partial: File? = null try { if (store.pending() != null) { - response.error(409, "Finish or dismiss the current app on your watch first.") + response.error(409, "Finish with the app on your watch before sending another.") return } PackageInspector.requireSpace(length, PackageInspector.free(context)) @@ -163,7 +164,7 @@ class LocalHttpServer( val file = store.file(id) partial = file Receiving.update(owner) { - it.copy(detail = "Receiving APK…", total = length, received = 0) + it.copy(detail = "Your app is on its way…", total = length, received = 0) } val body = UploadBody( @@ -174,7 +175,7 @@ class LocalHttpServer( }, ) val digest = file.outputStream().use { ApkRules.copyBounded(body, it).second } - Receiving.update(owner) { it.copy(detail = "Checking APK…") } + Receiving.update(owner) { it.copy(detail = "Getting your app ready…") } val apk = PackageInspector.inspect(context, file, digest) PackageInspector.checkForWatch( apk, @@ -183,7 +184,7 @@ class LocalHttpServer( PackageInspector.free(context), ) check(!closed.get() && SystemClock.elapsedRealtime() < deadline) { - "The receiving session ended. Try again." + "Receiving has ended. Open a fresh link from your watch." } store.stage(PendingApk(id, System.currentTimeMillis(), apk)) partial = null diff --git a/app/src/main/java/meghdad/pakkit/transfer/ReceiveService.kt b/app/src/main/java/meghdad/pakkit/transfer/ReceiveService.kt index 9389b02..8ee20a1 100644 --- a/app/src/main/java/meghdad/pakkit/transfer/ReceiveService.kt +++ b/app/src/main/java/meghdad/pakkit/transfer/ReceiveService.kt @@ -42,7 +42,7 @@ class ReceiveService : Service() { this@ReceiveService.network == network && properties.linkAddresses.none { it.address == address } ) { - finish("Wi-Fi address changed. Start a new session.") + finish("Wi-Fi changed. Ready to reconnect?") } } } @@ -50,7 +50,7 @@ class ReceiveService : Service() { override fun onLost(network: Network) { main.post { if (network == this@ReceiveService.network) - finish("Wi-Fi disconnected. Start a new session.") + finish("Wi-Fi disconnected. Ready to reconnect?") } } @@ -71,7 +71,7 @@ class ReceiveService : Service() { manager.createNotificationChannel( NotificationChannel( "receive", - "Receiving sessions", + "App transfers", NotificationManager.IMPORTANCE_LOW, ), ) @@ -92,8 +92,8 @@ class ReceiveService : Service() { val notification = Notification.Builder(this, "receive") .setSmallIcon(R.drawable.pakkit_mark) - .setContentTitle("Pakkit is ready to receive") - .setContentText("Private Wi-Fi session · ends in 10 minutes") + .setContentTitle("Ready for your next app") + .setContentText("Open Pakkit to connect your browser.") .setContentIntent(open) .setOngoing(true) .addAction(Notification.Action.Builder(null, "End session", stop).build()) @@ -105,7 +105,7 @@ class ReceiveService : Service() { ) Receiving.begin(this) deadline = SystemClock.elapsedRealtime() + DURATION_MS - main.postDelayed({ finish("Session expired. Start a new session.") }, DURATION_MS) + main.postDelayed({ finish("Time’s up. Ready for another app?") }, DURATION_MS) try { registered = true connectivity.requestNetwork( @@ -117,7 +117,7 @@ class ReceiveService : Service() { 25_000, ) } catch (_: Exception) { - finish("Wi-Fi is unavailable. Check watch settings.") + finish("Can’t reach Wi-Fi. Check your watch’s connection.") } return START_NOT_STICKY } @@ -142,7 +142,7 @@ class ReceiveService : Service() { Receiving.update(this) { it.copy(url = listener.url, detail = "Ready to receive") } } catch (error: Exception) { android.util.Log.w("PakkitReceive", "Cannot open receiving session", error) - finish("Could not open local Wi-Fi. Check the network and try again.") + finish("Couldn’t connect. Check Wi-Fi and try again.") } } diff --git a/app/src/main/java/meghdad/pakkit/transfer/UploadBody.kt b/app/src/main/java/meghdad/pakkit/transfer/UploadBody.kt index 62cbe99..7160f76 100644 --- a/app/src/main/java/meghdad/pakkit/transfer/UploadBody.kt +++ b/app/src/main/java/meghdad/pakkit/transfer/UploadBody.kt @@ -1,6 +1,7 @@ package meghdad.pakkit.transfer import java.io.InputStream +import meghdad.pakkit.apk.requireUser /** Exact-length stream: truncation is an error, and extra bytes cannot become another request. */ internal class UploadBody( @@ -22,7 +23,7 @@ internal class UploadBody( if (count == 0) return 0 if (received == length) return -1 val read = input.read(bytes, offset, minOf(count.toLong(), length - received).toInt()) - require(read > 0) { "Transfer interrupted. Choose the file again." } + requireUser(read > 0) { "The transfer stopped early. Choose the file and try again." } received += read val now = clock() if (now - lastUpdate >= 250_000_000 || received == length) { diff --git a/app/src/main/java/meghdad/pakkit/ui/WatchActivity.kt b/app/src/main/java/meghdad/pakkit/ui/WatchActivity.kt index 54136e7..716c2a3 100644 --- a/app/src/main/java/meghdad/pakkit/ui/WatchActivity.kt +++ b/app/src/main/java/meghdad/pakkit/ui/WatchActivity.kt @@ -38,6 +38,15 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList private var busy = false private var error: String? = null private var renderedState = "" + private var showingLink = false + private var backRegistered = false + private val linkBack = + if (Build.VERSION.SDK_INT >= 33) + android.window.OnBackInvokedCallback { + showingLink = false + refresh() + } + else null private var qrUrl = "" private var qrBitmap: android.graphics.Bitmap? = null @@ -46,12 +55,14 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList store = PackageStore(this) store.clean() acceptIntent(intent) + showingLink = savedInstanceState?.getBoolean("showingLink") ?: false refresh() savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } } } override fun onSaveInstanceState(outState: Bundle) { outState.putInt("scroll", scroll.scrollY) + outState.putBoolean("showingLink", showingLink) super.onSaveInstanceState(outState) } @@ -90,6 +101,9 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList } override fun onDestroy() { + if (Build.VERSION.SDK_INT >= 33 && backRegistered) { + onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack)) + } io.shutdown() super.onDestroy() } @@ -108,6 +122,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList ) = WatchDesign.text(this, value, size, color, bold).apply { gravity = Gravity.CENTER + isAccessibilityHeading = bold && size >= 18f breakStrategy = android.graphics.text.LineBreaker.BREAK_STRATEGY_BALANCED } @@ -150,7 +165,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList addView( ImageView(this@WatchActivity).apply { setImageDrawable( - GlyphDrawable(glyph, if (success) colors.mint else colors.error), + GlyphDrawable(glyph, if (success) colors.mint else colors.error) ) setPadding(dp(12), dp(12), dp(12), dp(12)) background = @@ -183,14 +198,29 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList if (isDestroyed || isFinishing) return val job = store.pending() val live = Receiving.state + if (live.url == null || job != null || live.total > 0) showingLink = false val stateKey = job?.let { "${it.id}:${it.state}" } ?: when { + showingLink && live.url != null -> "link" live.total > 0 -> "uploading" live.url != null -> "receiving" live.active -> "connecting" else -> "home" } + if (Build.VERSION.SDK_INT >= 33) { + val handleBack = showingLink && job == null && live.url != null && live.total == 0L + if (handleBack && !backRegistered) { + onBackInvokedDispatcher.registerOnBackInvokedCallback( + android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, + requireNotNull(linkBack), + ) + } else if (!handleBack && backRegistered) { + onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack)) + } + backRegistered = handleBack + } + val previousState = renderedState val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0 renderedState = stateKey scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) } @@ -215,13 +245,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList textSize = 12f setTextColor(colors.secondary) importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO - }, + } ) if (job == null) home() else { incoming(job) if (Receiving.state.url != null) - button("End Wi-Fi session", false) { + button(getString(R.string.watch_end_session), false) { stopService(Intent(this, ReceiveService::class.java)) refresh() } @@ -231,37 +261,56 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList scroll.isFocusableInTouchMode = true setContentView(scroll) scroll.requestFocus() + if ( + y == 0 && + stateKey != previousState && + android.animation.ValueAnimator.areAnimatorsEnabled() + ) { + column.alpha = 0f + column.animate().alpha(1f).setDuration(180).start() + } scroll.post { scroll.scrollTo(0, y) } } private fun home() { - val url = Receiving.state.url - if (url == null) { - parcel(54) - add(line("Pakkit", 25f, bold = true), 4) - add(line(getString(R.string.brand_tagline), 12f, colors.secondary), 5) - } + val live = Receiving.state + val url = live.url if (url != null) { - val received = Receiving.state.received - val total = Receiving.state.total - if (total > 0) { + if (showingLink && live.total == 0L) { + showLink(url) + return + } + if (live.total > 0) { + parcel(48) + val percent = (live.received * 100 / live.total).coerceAtMost(100) add( line( - "${(received * 100 / total).coerceAtMost(100)}% received", - 21f, + if (percent == 100L) getString(R.string.watch_just_checking) + else getString(R.string.watch_on_its_way), + 22f, bold = true, ), - 12, + 10, ) + add(line("$percent%", 30f, colors.mint, true), 10) add( ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 100 - progress = (received * 100 / total).toInt() + progress = percent.toInt() progressTintList = android.content.res.ColorStateList.valueOf(colors.mint) + contentDescription = getString(R.string.watch_percent_received, percent) }, 12, ) - add(line("Keep your browser open.", 12f, colors.secondary), 8) + add( + line( + if (percent == 100L) getString(R.string.watch_getting_your_app_ready) + else getString(R.string.watch_keep_your_browser_open), + 13f, + colors.secondary, + ), + 10, + ) } else { if (qrUrl != url || qrBitmap == null) { val matrix = @@ -298,211 +347,226 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList dp( (resources.configuration.screenWidthDp * .6f) .roundToInt() - .coerceAtMost(138), + .coerceAtMost(138) ), ) - contentDescription = - "QR code for your private receiving link. The full link is below." + contentDescription = getString(R.string.scan_code_description) }, 14, ) - add(line("Scan to send", 18f, bold = true), 12) - badge("Private Wi-Fi session", positive = true) - add( - line( - "Use the same Wi-Fi. Session ends automatically in 10 minutes.", - 12f, - colors.secondary, - ), - 8, - ) - add( - line(url, 11f, colors.mint).apply { - textDirection = View.TEXT_DIRECTION_LTR - setTextIsSelectable(true) - }, - 14, - ) - add( - line( - "Local HTTP · use a trusted network. Anyone with this link can send a file; only you can approve installation.", - 11f, - colors.secondary, - ), - 12, - ) + add(line(getString(R.string.watch_scan_to_send), 20f, bold = true), 12) + add(line(getString(R.string.watch_scan_description), 13f, colors.secondary), 8) + add(line(getString(R.string.watch_ready_for_10_minutes), 12f, colors.mint), 10) + button(getString(R.string.watch_view_link), false) { + showingLink = true + refresh() + } } - button("End session", false) { + button(getString(R.string.watch_end_session), false) { stopService(Intent(this, ReceiveService::class.java)) refresh() } return } - if (!packageManager.canRequestPackageInstalls()) { - badge("Allow installation") - add( - line( - "Pakkit needs your permission to request installs. You approve every app on your watch.", - 13f, - colors.secondary, - ), - 12, - ) - button("Allow installs") { settings() } - add( - line( - "If your watch does not offer this permission, use Google Play. Pakkit cannot bypass its security settings.", - 12f, - colors.secondary, - ), - 12, - ) - button("Open Google Play", false) { play() } + add( + LinearLayout(this).apply { + gravity = Gravity.CENTER + addView( + ImageView(this@WatchActivity).apply { + setImageResource(R.drawable.pakkit_icon) + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + }, + LinearLayout.LayoutParams(dp(30), dp(30)), + ) + addView( + line(getString(R.string.pakkit_name), 22f, bold = true), + LinearLayout.LayoutParams(-2, -2).apply { leftMargin = dp(6) }, + ) + }, + 12, + ) + if (live.active) { + badge(getString(R.string.watch_finding_wi_fi)) + add(line(getString(R.string.watch_connecting_description), 13f, colors.secondary), 12) + button(getString(R.string.watch_cancel), false) { + stopService(Intent(this, ReceiveService::class.java)) + } } else { - badge("Any device. Any browser.", positive = true) - add( - line( - "Choose an APK in your browser. Review it here before installing.", - 14f, - colors.secondary, - ), - 12, - ) - if (!Receiving.state.active) - button("Start receiving") { - error = null - runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) } - .onFailure { - error = "Could not start receiving. Check Wi-Fi and try again." - refresh() - } - } - add(line(Receiving.state.detail, 12f, colors.secondary), 12) - if (Receiving.state.active) - button("Cancel session", false) { - stopService(Intent(this, ReceiveService::class.java)) - } - button("Wi-Fi settings", false) { - runCatching { - startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)) - } + button(getString(R.string.watch_start_receiving)) { + error = null + runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) } .onFailure { - error = "Open Wi-Fi from your watch’s Settings app." + error = getString(R.string.watch_connection_error) + refresh() + } + } + add(line(getString(R.string.brand_tagline), 12f, colors.accent), 14) + if (live.detail != Receiving.State().detail) + add(line(live.detail, 13f, colors.secondary), 12) + button(getString(R.string.watch_wi_fi), false) { + runCatching { + startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)) + } + .onFailure { + error = getString(R.string.watch_wifi_unavailable) refresh() } } } - if ( - Build.VERSION.SDK_INT >= 33 && - checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != - PackageManager.PERMISSION_GRANTED - ) { - button("Enable session alerts", false) { - requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) - } + } + + private fun showLink(url: String) { + add(line(getString(R.string.watch_your_watch_link), 20f, bold = true), 14) + add(line(getString(R.string.watch_link_description), 13f, colors.secondary), 12) + add( + line(url, 12f, colors.mint).apply { + textDirection = View.TEXT_DIRECTION_LTR + setTextIsSelectable(true) + }, + 14, + ) + add(line(getString(R.string.watch_connection_privacy), 12f, colors.secondary), 14) + button(getString(R.string.watch_back_to_code), false) { + showingLink = false + refresh() } } + // Android 12 uses this callback; Android 13+ registers the platform callback above. + @Suppress("DEPRECATION") + @android.annotation.SuppressLint("GestureBackNavigation") + @Deprecated("Legacy callback for Android 12") + override fun onBackPressed() { + if (showingLink) { + showingLink = false + refresh() + } else super.onBackPressed() + } + private fun incoming(job: PendingApk) { val apk = job.apk val state = job.state when (state) { InstallState.INSTALLED -> statusIcon(Glyph.CHECK, success = true) InstallState.FAILED -> statusIcon(Glyph.ALERT, success = false) - else -> parcel(42) + else -> parcel(32) } when (state) { InstallState.INSTALLED -> { - add(line("All yours.", 25f, bold = true), 5) - add(line(apk.label, 17f, bold = true), 10) + add(line(getString(R.string.watch_all_yours), 22f, bold = true), 5) + add(line(apk.label, 16f, bold = true), 10) } InstallState.FAILED -> { - add(line("A small detour.", 22f, bold = true), 5) + add(line(getString(R.string.watch_couldn_t_install), 22f, bold = true), 5) add(line(apk.label, 16f), 10) } - else -> add(line(apk.label, 21f, bold = true), 5) + else -> add(line(apk.label, 20f, bold = true), 5) } add( line( - "${apk.version} · ${"%.1f".format(apk.bytes / 1048576.0)} MiB", + getString( + R.string.watch_app_summary, + apk.version, + "%.1f".format(apk.bytes / 1048576.0), + ), 12f, colors.secondary, ), 7, ) - if (busy) add(line("Preparing installer…", 13f, colors.secondary), 12) - else if (state == InstallState.READY) badge("Ready to install", positive = true) - else add(line(job.detail, 13f, colors.secondary), 12) + if (busy) add(line(getString(R.string.watch_getting_ready), 13f, colors.secondary), 12) + else if (state == InstallState.READY) + badge(getString(R.string.watch_ready_to_install), positive = true) + else if (state != InstallState.INSTALLED) add(line(job.detail, 13f, colors.secondary), 12) when (state) { InstallState.READY, InstallState.FAILED -> { if (!ApkRules.fresh(job.created, System.currentTimeMillis())) { add( line( - "This APK expired. Upload it again from your browser.", + getString(R.string.watch_file_expired), 13f, colors.error, ), 12, ) } else if (store.file(job.id).exists()) { - add(line(apk.packageName, 12f, colors.secondary), 12) if (!apk.wear) add( line( - "Watch support is unverified. The layout may not fit.", + getString(R.string.watch_fit_notice), 12f, colors.error, ), 10, ) - add(line("Only install apps you trust.", 13f, colors.secondary), 10) if (packageManager.canRequestPackageInstalls()) button( - if (state == InstallState.FAILED) "Try installation" else "Install", + if (state == InstallState.FAILED) getString(R.string.watch_try_again) + else getString(R.string.watch_install) ) { install(job) } - else button("Allow installs") { settings() } + else { + add( + line( + getString(R.string.watch_permission_description), + 13f, + colors.secondary, + ), + 10, + ) + button(getString(R.string.watch_allow_installs)) { settings() } + button(getString(R.string.watch_google_play), false) { play() } + } } - button("Dismiss", false) { dismiss(job) } + add(line(getString(R.string.watch_trust_notice), 12f, colors.secondary), 10) + button(getString(R.string.watch_remove_file), false) { dismiss(job) } } InstallState.CONFIRM -> { if (PendingApproval.intent != null && PendingApproval.id == job.id) - button("Continue") { + button(getString(R.string.watch_continue)) { val confirm = PendingApproval.intent ?: return@button runCatching { startActivity(confirm) } .onFailure { - error = - "The system approval screen could not open. Try the installation again." + error = getString(R.string.watch_approval_error) refresh() } } else add( line( - "Open the approval notification, or retry if interrupted.", + getString(R.string.watch_approval_recovery), 12f, colors.secondary, ), 10, ) - button("Retry approval", false) { install(job) } + button(getString(R.string.watch_try_again), false) { install(job) } + if ( + Build.VERSION.SDK_INT >= 33 && + checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + button(getString(R.string.watch_enable_alerts), false) { + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) + } + } } InstallState.INSTALLING -> { add( line( - "Follow the system approval. If interrupted, you can retry.", + getString(R.string.watch_installing_description), 12f, colors.secondary, ), 10, ) - button("Retry installation", false) { install(job) } + button(getString(R.string.watch_try_again), false) { install(job) } } InstallState.INSTALLED -> { - button("Open app") { launch(apk.packageName) } - button("Done", false) { + button(getString(R.string.watch_open_app)) { launch(apk.packageName) } + button(getString(R.string.watch_done), false) { store.dismiss(job.id) refresh() } @@ -510,11 +574,22 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList } } + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray, + ) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == 52) { + meghdad.pakkit.install.InstallReceiver.notifyApproval(this) + refresh() + } + } + private fun settings() { runCatching { startActivity(ApkInstaller.settings(this)) } .onFailure { - error = - "This watch does not offer that setting. Install compatible apps through Google Play." + error = getString(R.string.watch_permission_unavailable) refresh() } } @@ -551,11 +626,11 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList .sendIntent(this, 0, null, null, null) else startActivity( - packageManager.getLaunchIntentForPackage(packageName) ?: error("No launcher"), + packageManager.getLaunchIntentForPackage(packageName) ?: error("No launcher") ) } .onFailure { - error = "This app has no available watch launcher. Look in your watch’s app list." + error = getString(R.string.watch_launch_unavailable) refresh() } } @@ -563,11 +638,11 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList private fun play() { runCatching { startActivity( - Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=wear%20os&c=apps")), + Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=wear%20os&c=apps")) ) } .onFailure { - error = "Open Google Play from your watch’s app list." + error = getString(R.string.watch_play_unavailable) refresh() } } diff --git a/app/src/main/java/meghdad/pakkit/ui/WatchDesign.kt b/app/src/main/java/meghdad/pakkit/ui/WatchDesign.kt index ddb5c3a..552bd29 100644 --- a/app/src/main/java/meghdad/pakkit/ui/WatchDesign.kt +++ b/app/src/main/java/meghdad/pakkit/ui/WatchDesign.kt @@ -74,20 +74,20 @@ object WatchDesign { ColorStateList( arrayOf(intArrayOf(-android.R.attr.state_enabled), intArrayOf()), intArrayOf(p.secondary, if (primary) Color.WHITE else p.text), - ), + ) ) val fill = if (primary) gradient( intArrayOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt()), - dp(c, 20).toFloat(), + dp(c, 24).toFloat(), ) - else shape(p.raised, dp(c, 20).toFloat(), p.border) + else shape(p.raised, dp(c, 24).toFloat(), p.border) val states = android.graphics.drawable.StateListDrawable().apply { addState( intArrayOf(-android.R.attr.state_enabled), - shape(p.raised, dp(c, 20).toFloat(), p.border), + shape(p.raised, dp(c, 24).toFloat(), p.border), ) addState(intArrayOf(), fill) } diff --git a/app/src/main/res/values/brand.xml b/app/src/main/res/values/brand.xml index 9d1014c..43c0e2a 100644 --- a/app/src/main/res/values/brand.xml +++ b/app/src/main/res/values/brand.xml @@ -1,5 +1,5 @@ Pakkit - Pocket to Wrist. + Pack it. Send it. Wear it. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..604eafa --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,49 @@ + + + End session + Just checking… + On its way + Getting your app ready. + Keep your browser open. + Scan to send + Both devices on the same Wi-Fi. + Ready for 10 minutes + View link + Finding Wi-Fi + Getting ready for your next app. + Cancel + Start receiving + Couldn’t connect. Check Wi-Fi and try again. + Wi-Fi + Open Wi-Fi in your watch’s Settings. + Your watch link + Open this link on a device using the same Wi-Fi. + Use Wi-Fi you trust. Transfers aren’t encrypted. Keep this link private. + Back to code + All yours. + Couldn’t install + Getting ready… + Ready to install + This file has expired. Send it again to install. + Made for a phone? It may not fit your watch. + Only install apps you trust. + Try again + Install + Allow Pakkit to install apps. You’ll approve each one. + Allow installs + Google Play + Remove file + Enable alerts + Continue + Couldn’t open approval. Try again. + Approval was interrupted. Try again to continue. + Your watch will ask you to approve installation. + Open app + Done + Your watch doesn’t offer this setting. Find apps on Google Play instead. + This app can’t be opened here. Check your watch’s app list. + Find Google Play in your watch’s app list. + QR code to connect your browser. Use View link for the full address. + %1$d%% received + %1$s · %2$s MB + diff --git a/app/src/test/java/meghdad/pakkit/apk/UserMessageTest.kt b/app/src/test/java/meghdad/pakkit/apk/UserMessageTest.kt new file mode 100644 index 0000000..93c2760 --- /dev/null +++ b/app/src/test/java/meghdad/pakkit/apk/UserMessageTest.kt @@ -0,0 +1,24 @@ +package meghdad.pakkit.apk + +import org.junit.Assert.* +import org.junit.Test + +class UserMessageTest { + @Test + fun hidesUnexpectedPlatformAndFileErrors() { + for (error in + listOf( + java.io.IOException("/data/private/file.apk"), + IllegalArgumentException("Invalid request headers"), + SecurityException("Permission denial"), + )) { + assertEquals("Try again.", error.userMessage("Try again.")) + } + } + + @Test + fun retainsDeliberateRecoveryCopy() { + val error = runCatching { requireUser(false) { "Choose another APK." } }.exceptionOrNull()!! + assertEquals("Choose another APK.", error.userMessage("Try again.")) + } +} diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 89ed11b..ca0b127 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,6 @@ # Pakkit design -**Pakkit — Pocket to Wrist.** Secondary tagline: **Pack it. Send it. Wear it.** The identity is friendly, playful and polished: an open parcel with a floating app tile, soft geometry, violet lighting and mint/cyan accents. +**Pakkit — Pack it. Send it. Wear it.** This is the official brand tagline. The identity is friendly, playful and polished: an open parcel with a floating app tile, soft geometry, violet lighting and mint/cyan accents. ## Implemented assets @@ -13,14 +13,31 @@ ## Themes and layout -The native watch UI uses midnight `#090 B 17` to limit lit OLED pixels, lavender-white text and semantic mint/error surfaces. Body and secondary copy, badges and action gradient endpoints have automated contrast checks. Actions have a minimum 48 dp height and scalable text. Proportional margins and bottom padding allow controls to move into the usable center of a round display. The QR is sized to screen width and positioned within the circular safe area; the full URL and trust disclosure remain scrollable below it. +The native watch UI uses midnight `#090B17` to limit lit OLED pixels, lavender-white text and semantic mint/error surfaces. Body and secondary copy, badges and action gradient endpoints have automated contrast checks. Actions have a minimum 48 dp height and scalable text. Proportional margins and bottom padding allow controls to move into the usable center of a round display. The QR is sized to screen width and positioned within the circular safe area; the full URL and connection disclosure are available through **View link**, with native back navigation. The home screen pairs a compact parcel/wordmark with a visible receiving action. Source permission is requested at the app review, where its purpose is clear. -The browser follows prefers-color-scheme with an explicit in-session toggle. Dark is midnight with violet/cyan lighting; light uses soft lavender and white surfaces. A two-column desktop layout becomes a single-column layout at smaller widths. The maintained CSS, HTML and JavaScript are readable source files, formatted with the optional web development tools. Native browser controls, semantic headings, focus rings, file labels and a live status region support keyboard and assistive access. +The browser leads with the official tagline, original parcel artwork and a compact Choose / Send / Wear indicator. Mobile layouts omit the redundant journey explainer. It follows prefers-color-scheme with an explicit in-session toggle. Dark is midnight with violet/cyan lighting; light uses soft lavender and white surfaces. A two-column desktop layout becomes a single-column layout at smaller widths. The maintained CSS, HTML and JavaScript are readable source files, formatted with the optional web development tools. Native browser controls, semantic headings, focus rings, file labels and a live status region support keyboard and assistive access. ## Motion and product states -The watch has static decorative artwork. Browser motion is a finite parcel entrance and short hover/press feedback; prefers-reduced-motion disables these. There are no continuous particle effects or decorative render loops. Polling pauses in hidden tabs. +The watch has static decorative artwork and a finite 180 ms screen entrance when system animation is enabled. Progress updates do not restart it. Browser motion is a finite parcel entrance and short hover/press feedback; prefers-reduced-motion disables these. There are no continuous particle effects or decorative render loops. Polling pauses in hidden tabs. Upload progress reflects actual XHR bytes sent and socket bytes read. “100% sent” transitions to package checking, never to an installation-success claim. The browser distinguishes upload, verification, watch review, system approval, failure and success. Android STATUS_SUCCESS is the authority for “installed”. Cancelling an HTTP request does not imply a rollback of a file the watch may already have received. Keep copy precise: preflight does not certify safety or runtime compatibility. Source approval and system consent are explicit decisions. The trust disclosure describes unencrypted local HTTP without claiming encryption. + +## Product voice + +Write for the person wearing the watch: short, warm, specific and calm. Let the parcel, color and interactions carry the playfulness. Use APK when a file type matters; use app in actions and outcomes. Never introduce architectural history, development setup or platform API names into the product interface. Keep necessary connection privacy information accessible in context rather than repeating warnings throughout the journey. + +| Moment | Watch | Browser | +| --- | --- | --- | +| Start | Pakkit + official tagline; Start receiving | Official tagline; Choose app | +| Connect | Scan to send; View link | Connected to your watch | +| Transfer | On its way + actual percentage | On its way + actual percentage | +| Check | Just checking… | Just checking… | +| Review | Ready to install; Install or contextual Allow installs | Made it to your watch | +| Approval | Continue, with recovery action | One tap closer | +| Success | All yours.; Open app | Looks good on you. | +| Failure | Couldn’t install + specific recovery | Let’s try that again + specific recovery | + +Watch screen copy lives in Android string resources. Deliberately written package-validation messages are marked with `UserMessage`; unknown file/platform exceptions are replaced with recovery copy at the UI boundary, while installer diagnostics stay in logs. Notification copy follows the same voice. The app name and official tagline are shared branding resources. Browser result changes are announced with a live region, and color is never the only state indicator. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index e153fe2..575f3c7 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -20,7 +20,7 @@ python 3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build Use actual serials from `adb devices`. The runner refuses serials that do not start with `emulator-` and requires the watch feature. It never selects a physical device. It connects the watch to the virtual AndroidWifi access point, installs only the app/test APKs and saves results under `app/build/reports/validation`. The small-screen run temporarily uses 192 dp and 1.3x font scaling, restoring the previous size, density and font setting in a finally block. -For install tests, first open Pakkit on the emulator and use **Allow installs** to approve it through the normal system UI. No shell permission grant is needed. Tests mark missing source approval as an assumption; the runner treats skipped tests as incomplete validation. Native tests clean up staged files, pending system sessions, notifications and activities. The official-installer test stops at required system consent and abandons its test session afterward. +For install tests, first send an APK to Pakkit on the emulator and use **Allow installs** on its review screen, or open Android Settings → Apps → Special app access → Install unknown apps → Pakkit. Approve it through the normal system UI. No shell permission grant is needed. Tests mark missing source approval as an assumption; the runner treats skipped tests as incomplete validation. Native tests clean up staged files, pending system sessions, notifications and activities. The official-installer test stops at required system consent and abandons its test session afterward. The optional Google Maven mirror property is documented in README.md. If needed, build with that property and pass --skip-build to the runner; its default build uses standard repositories. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 75be29f..c97b79c 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -21,18 +21,18 @@ Browser UI fixtures exercise interactions independently; the separate Android Em ## Latest completed run -Refactoring validation date: October 15, 2026. No physical device was accessed. +Product experience validation date: October 15, 2026. No physical device was accessed. -- **19 JVM tests passed**, with zero failures/errors. -- **14 native tests passed** on the round Wear OS API 37 emulator, with no skipped assumptions. This includes the public installer’s required-consent callback and refusal of requests after a session deadline. -- **Two round UI tests passed again** at 192 dp / 1.3x text: reachable review actions and a decodable QR whose full square fits inside the circular bezel. Size, density and font scale were restored. -- **13 browser UI checks passed** on Chromium 140.0.7339.16 across four viewport widths and both themes, with zero JavaScript errors. +- **21 JVM tests passed**, with zero failures/errors. +- **17 native tests passed** on the round Wear OS API 37 emulator, with no skipped assumptions. This includes the public installer’s required-consent callback and refusal of requests after a session deadline. +- **Five round UI tests passed again** at 192 dp / 1.3x text: the initial receiving action stays visible, review/approval/error/success controls are reachable, connection details and transfer feedback work, and a decodable QR fits inside the circular bezel. Size, density and font scale were restored. +- **16 browser UI checks passed** on Chromium 140.0.7339.16 across four viewport widths and both themes, including connection recovery, keyboard focus, reduced motion and 200% zoom at an effective 320 px layout width, with zero JavaScript errors. - **Real Android Emulator Chrome 145.0.7632.218 uploaded the signed fixture directly to the Wear OS Emulator over virtual Wi-Fi**, receiving READY review state. The test dismissed its package, ended receiving and removed its local debug forward. -- **Clean builds succeeded** for the debug app, instrumentation APK, unit tests, lint and optimized release AAB. Lint has zero errors; three remaining warnings are SDK/Gradle/library update notices, not unused code/resources. +- **Debug, test and release builds succeeded** for the debug app, instrumentation APK, unit tests, lint and optimized release AAB. Lint has zero errors; three remaining warnings are SDK/Gradle/library update notices, not unused code/resources. - Release inspection found exactly the three bundled web assets, no fixture APK/test payload, no package-visibility queries, one exported launcher and non-exported service/installer receiver. The release dependency graph contains ZXing Core, Kotlin stdlib and its annotations dependency. - The unchanged Gradle distribution version is checksum-pinned to its official download. Release output is unsigned when signing inputs are absent; incomplete signing configuration fails clearly. -Detailed XML, text logs, screenshots and browser summaries are generated under app/build/reports and app/build/test-results. They are not source assets or claims of universal hardware/browser support. +Ten watch product-state screenshots at each tested size, browser screenshots, detailed XML, text logs and browser summaries are generated under app/build/reports and app/build/test-results. They are not source assets or claims of universal hardware/browser support. ## Hardware-specific release matrix diff --git a/scripts/emulator_utils.py b/scripts/emulator_utils.py index a695a06..82df375 100644 --- a/scripts/emulator_utils.py +++ b/scripts/emulator_utils.py @@ -61,11 +61,13 @@ def tap_text(serial, label, attempts=6): def session_url(serial): + tap_text(serial, "View link") for _ in range(6): tree = ui(serial) for node in tree.iter("node"): value = node.get("text", "") if value.startswith("http://") and "#" in value: + tap_text(serial, "Back to code") return value bounds = next(tree.iter("node")).get("bounds") _, _, width, height = map(int, re.findall(r"\d+", bounds)) diff --git a/scripts/test-emulators.py b/scripts/test-emulators.py index 9242121..04063dc 100755 --- a/scripts/test-emulators.py +++ b/scripts/test-emulators.py @@ -44,11 +44,17 @@ try: adb(args.watch, "shell", "wm", "size", "384x384") adb(args.watch, "shell", "wm", "density", "320") adb(args.watch, "shell", "settings", "put", "system", "font_scale", "1.3") - test_args = ["-e", "class", "meghdad.pakkit.WatchReviewTest,meghdad.pakkit.WatchSessionTest"] + test_args = ["-e", "class", "meghdad.pakkit.WatchReviewTest,meghdad.pakkit.WatchSessionTest,meghdad.pakkit.WatchExperienceTest"] output = adb(args.watch, "shell", "am", "instrument", "-w", "-r", *test_args, "meghdad.pakkit.test/androidx.test.runner.AndroidJUnitRunner").decode() (report_dir / ("watch-small.txt" if args.small else "watch.txt")).write_text(output) print(output, flush=True) + screenshots = report_dir / ("watch-product-small" if args.small else "watch-product") + screenshots.mkdir(exist_ok=True) + for name in ["home", "scan", "link", "sending", "checking", "ready", "installing", "confirm", "failed", "installed"]: + image = adb(args.watch, "exec-out", "cat", f"/sdcard/Android/data/meghdad.pakkit/files/product-review/{name}.png") + (screenshots / f"{name}.png").write_bytes(image) + if re.search(r"INSTRUMENTATION_STATUS_CODE: -[34]", output): raise RuntimeError("Tests skipped: allow Pakkit as an install source through the emulator’s system UI, then rerun.") if not re.search(r"OK \(\d+ tests?\)", output) or "FAILURES" in output: @@ -74,7 +80,7 @@ if args.browser: env = dict(os.environ, PAKKIT_SESSION_URL=url, PAKKIT_CDP_URL=f"http://127.0.0.1:{endpoint}") subprocess.run(["node", str(ROOT / "web-tests/emulator.test.cjs")], cwd=ROOT, env=env, check=True) adb(args.watch, "shell", "am", "start", "-W", "-n", "meghdad.pakkit/.ui.WatchActivity") - tap_text(args.watch, "Dismiss") + tap_text(args.watch, "Remove file") tap_text(args.watch, "End session") finally: adb(args.browser, "forward", "--remove", f"tcp:{endpoint}") diff --git a/web-tests/browser.test.cjs b/web-tests/browser.test.cjs index 055a869..c4dc06d 100644 --- a/web-tests/browser.test.cjs +++ b/web-tests/browser.test.cjs @@ -10,7 +10,8 @@ const reports = path.resolve(__dirname, '../app/build/reports/validation'); let state = 'waiting', failure = false, hold = false, - bytesReceived = 0; + bytesReceived = 0, + disconnected = false; const server = http.createServer(async (request, response) => { response.setHeader('Cache-Control', 'no-store'); const routes = { @@ -28,6 +29,10 @@ const server = http.createServer(async (request, response) => { if (request.headers.authorization !== 'Bearer test-key') { response.writeHead(403).end('{}'); } else if (request.url === '/api/status') { + if (disconnected) { + response.writeHead(503).end('{}'); + return; + } response.end( JSON.stringify({ state, @@ -37,7 +42,7 @@ const server = http.createServer(async (request, response) => { }), ); } else if (request.url === '/api/upload') { - bytesReceived = 0; + ((bytesReceived = 0), (disconnected = false)); for await (const chunk of request) bytesReceived += chunk.length; if (hold) return; // Cancellation while awaiting a response. if (failure) @@ -102,10 +107,7 @@ const server = http.createServer(async (request, response) => { mimeType: 'text/plain', buffer: Buffer.from('test'), }); - await page - .getByRole('status') - .getByText('Choose a complete .apk file', { exact: false }) - .waitFor(); + await page.locator('#message').getByText('Choose a single APK', { exact: false }).waitFor(); checks++; const file = { name: 'test.apk', @@ -114,30 +116,67 @@ const server = http.createServer(async (request, response) => { }; await page.locator('#file').setInputFiles(file); failure = true; - await page.getByRole('button', { name: 'Send to my watch' }).click(); + await page.getByRole('button', { name: 'Send to watch' }).click(); await page - .getByRole('status') + .locator('#message') .getByText('This APK is not compatible with your watch.') .waitFor(); checks++; failure = false; - await page.getByRole('button', { name: 'Send to my watch' }).click(); - await page.getByRole('heading', { name: 'Over to your wrist.' }).waitFor(); + await page.getByRole('button', { name: 'Send to watch' }).click(); + await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor(); assert.equal(bytesReceived, file.buffer.length); state = 'confirm'; - await page.getByRole('heading', { name: 'Your watch. Your call.' }).waitFor(); + await page.getByRole('heading', { name: 'One tap closer' }).waitFor(); + state = 'installing'; + await page.getByRole('heading', { name: 'Getting ready', exact: true }).waitFor(); + state = 'failed'; + await page.getByRole('heading', { name: 'Let’s try that again' }).waitFor(); + assert.equal(await page.locator('#result').getAttribute('data-state'), 'failed'); + checks++; state = 'installed'; await page.getByRole('heading', { name: 'Looks good on you.' }).waitFor(); state = 'waiting'; - await page.getByRole('button', { name: 'Choose another APK' }).click(); + await page.getByRole('button', { name: 'Send another app' }).click(); checks++; await page.locator('#file').setInputFiles(file); hold = true; - await page.getByRole('button', { name: 'Send to my watch' }).click(); + await page.getByRole('button', { name: 'Send to watch' }).click(); await page.getByRole('button', { name: 'Cancel transfer' }).click(); - await page.getByRole('status').getByText('Transfer cancelled.', { exact: false }).waitFor(); + await page.locator('#message').getByText('Transfer cancelled.', { exact: false }).waitFor(); + checks++; + disconnected = true; + await page.getByText('Watch out of reach', { exact: true }).waitFor(); + assert.equal(await page.locator('#send').isDisabled(), true); + disconnected = false; + await page.getByText('Connected to your watch', { exact: true }).waitFor(); checks++; await page.getByRole('button', { name: 'Change color theme' }).click(); + await page.setViewportSize({ width: 640, height: 1136 }); + await page.evaluate(() => { + document.body.style.zoom = '2'; + }); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), + false, + '200% zoom reflows', + ); + await page.evaluate(() => { + document.body.style.zoom = ''; + }); + await page.getByRole('button', { name: 'Remove selected file' }).click(); + await page.locator('#choose').focus(); + assert.equal( + await page.locator('#choose').evaluate((el) => el === document.activeElement), + true, + ); + await page.emulateMedia({ reducedMotion: 'reduce' }); + assert.equal( + await page.locator('.parcel').evaluate((el) => getComputedStyle(el).animationName), + 'none', + ); + checks++; + assert.deepEqual(errors, []); const result = { browser: await browser.version(), diff --git a/web-tests/emulator.test.cjs b/web-tests/emulator.test.cjs index 12d9777..76c3dea 100644 --- a/web-tests/emulator.test.cjs +++ b/web-tests/emulator.test.cjs @@ -34,8 +34,8 @@ const path = require('node:path'); path.resolve(__dirname, '../qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk'), ), }); - await page.getByRole('button', { name: 'Send to my watch' }).click(); - await page.getByRole('heading', { name: 'Over to your wrist.' }).waitFor({ timeout: 30000 }); + await page.getByRole('button', { name: 'Send to watch' }).click(); + await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor({ timeout: 30000 }); await page.screenshot({ path: path.join(reports, 'android-browser-review.png'), fullPage: true,