feat: polish Pakkit and strengthen release readiness

- Improve Wear splash, ongoing status, and progress focus
- Refine browser accessibility and connection recovery
- Add offline privacy and open-source notices
- Harden installation approval and storage error handling
- Expand emulator coverage and release artifact checks
- Document Play publication gates and hardware validation
This commit is contained in:
Meghdad committed 2026-10-15 23:25:36 +03:30
1 parent 6e41db2a74
commit 17f0609a3a
34 files changed
+1027 -111

No files matched your search

+3
View File
@@ -43,6 +43,9 @@ android {
dependencies {
implementation(libs.zxing)
implementation(libs.androidx.core)
implementation(libs.wear.ongoing)
implementation(libs.splashscreen)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.runner)
@@ -14,6 +14,68 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class InstallSafetyTest : WatchTest() {
@Test
fun watchActionAndSystemConfirmationCompleteInstallation() {
assumeTrue(context.packageManager.canRequestPackageInstalls())
val apk = fixture()
store.stage(apk)
openWatch()
instrumentation.runOnMainSync {
fun views(view: android.view.View): List<android.view.View> =
listOf(view) +
if (view is android.view.ViewGroup)
(0 until view.childCount).flatMap { views(view.getChildAt(it)) }
else emptyList()
views(requireNotNull(activity).window.decorView)
.filterIsInstance<android.widget.Button>()
.single { it.text == "Install" }
.performClick()
}
await(15_000) { store.pending()?.state == InstallState.CONFIRM }
// Exercise the real system button. No shell install or source-permission grant.
var consentClicked = false
try {
await(15_000) {
if (consentClicked) return@await true
val root = instrumentation.uiAutomation.rootInActiveWindow
val button =
root
?.let { node ->
listOf("Install", "Update").flatMap {
node.findAccessibilityNodeInfosByText(it)
}
}
?.firstOrNull {
it.text?.toString() in setOf("Install", "Update") &&
it.isClickable &&
it.isEnabled &&
it.packageName?.toString() != context.packageName
}
consentClicked =
button?.performAction(
android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK
) == true
consentClicked
}
} catch (failure: Exception) {
fun labels(node: android.view.accessibility.AccessibilityNodeInfo): List<String> =
listOf(
"${node.packageName}: ${node.text} / ${node.contentDescription} clickable=${node.isClickable}"
) +
(0 until node.childCount).flatMap {
node.getChild(it)?.let(::labels) ?: emptyList()
}
println(instrumentation.uiAutomation.rootInActiveWindow?.let(::labels))
throw failure
}
await(30_000) {
store.pending()?.state in setOf(InstallState.INSTALLED, InstallState.FAILED)
}
assertEquals(store.pending()?.detail, InstallState.INSTALLED, store.pending()?.state)
assertFalse(store.file(apk.id).exists())
assertNull(PendingApproval.intent)
}
@Test
fun receiptAndForgedCallbacksCannotMarkPackageInstalled() {
val apk = fixture()
@@ -36,6 +36,11 @@ class PackageStoreTest : WatchTest() {
}
return written
}
override fun remove(key: String): android.content.SharedPreferences.Editor {
editor.remove(key)
return this
}
}
}
}
@@ -45,11 +50,15 @@ class PackageStoreTest : WatchTest() {
}
assertTrue(
runCatching {
PackageStore(wrapped).update(apk.id, InstallState.INSTALLING, "Preparing")
}
PackageStore(wrapped).update(apk.id, InstallState.INSTALLING, "Preparing")
}
.isFailure
)
assertEquals(apk, store.pending())
failNext = true
assertTrue(runCatching { PackageStore(wrapped).dismiss(apk.id) }.isFailure)
assertEquals(apk, store.pending())
assertTrue("Failed removal keeps the original APK", store.file(apk.id).exists())
}
@Test
@@ -11,6 +11,53 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ReceiverLifecycleTest : WatchTest() {
@Test
fun ongoingActivityReflectsReviewAndStopActionEndsReceiving() {
val permission = android.Manifest.permission.POST_NOTIFICATIONS
val granted =
context.checkSelfPermission(permission) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
if (android.os.Build.VERSION.SDK_INT >= 33 && !granted)
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, permission)
// Keep this optional notification grant on the disposable emulator. Revoking a
// runtime permission kills the target process and its instrumentation runner.
run {
openWatch()
context.startForegroundService(
android.content.Intent(context, meghdad.pakkit.transfer.ReceiveService::class.java)
)
await(30_000) { meghdad.pakkit.transfer.Receiving.state.url != null }
val manager = context.getSystemService(android.app.NotificationManager::class.java)
await { androidx.wear.ongoing.OngoingActivity.recoverOngoingActivity(context) != null }
val ongoing =
requireNotNull(
androidx.wear.ongoing.OngoingActivity.recoverOngoingActivity(context)
)
assertTrue(ongoing.touchIntent.isImmutable)
store.stage(fixture())
try {
await {
manager.activeNotifications.any {
it.id == ongoing.notificationId &&
it.notification.extras.getString(
android.app.Notification.EXTRA_TITLE
) == "Ready to install"
}
}
} catch (failure: Exception) {
throw AssertionError(
"Notifications: ${manager.activeNotifications.map { it.id to it.notification.extras.getString(android.app.Notification.EXTRA_TITLE) }}; review=${store.pending()?.state}; receiving=${meghdad.pakkit.transfer.Receiving.state}",
failure,
)
}
val notification =
manager.activeNotifications.single { it.id == ongoing.notificationId }.notification
notification.actions.single { it.title == "Stop receiving" }.actionIntent.send()
await { !meghdad.pakkit.transfer.Receiving.state.active }
await { manager.activeNotifications.none { it.id == ongoing.notificationId } }
}
}
@Test
fun ipv6ListenerAcceptsCanonicalBrowserAuthority() {
LocalHttpServer(context, InetAddress.getByName("::1"), Any()).use { server ->
@@ -27,6 +27,11 @@ class WatchExperienceTest : WatchTest() {
private fun screen() = views(requireNotNull(activity).window.decorView)
private fun capture(name: String) {
await {
var focused = false
instrumentation.runOnMainSync { focused = activity?.hasWindowFocus() == true }
focused
}
instrumentation.waitForIdleSync()
Thread.sleep(220) // Finite screen entrance; screenshots capture the settled UI.
val bitmap = requireNotNull(instrumentation.uiAutomation.takeScreenshot())
@@ -56,6 +61,83 @@ class WatchExperienceTest : WatchTest() {
}
}
@Test
fun privacyIsAvailableWithoutStartingReceiving() {
openWatch()
val monitor =
instrumentation.addMonitor(
meghdad.pakkit.ui.AboutActivity::class.java.name,
null,
false,
)
instrumentation.runOnMainSync {
screen().filterIsInstance<Button>().single { it.text == "Privacy" }.performClick()
}
activity = requireNotNull(monitor.waitForActivityWithTimeout(5000))
instrumentation.removeMonitor(monitor)
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
assertTrue(
screen().filterIsInstance<TextView>().any { it.text.contains("without encryption") }
)
}
assertFalse(Receiving.state.active)
assertActionsReachable()
capture("privacy")
}
@Test
fun uploadProgressKeepsFocusAndViewIdentity() {
val owner = Any()
try {
Receiving.begin(owner)
Receiving.update(owner) {
it.copy(
url = "http://10.0.2.16:8787/",
total = Long.MAX_VALUE,
received = Long.MAX_VALUE / 2,
)
}
openWatch()
val original = screen().filterIsInstance<RoundScrollView>().single()
instrumentation.runOnMainSync {
screen()
.filterIsInstance<Button>()
.single { it.text == "Stop receiving" }
.requestFocus()
}
val focused = requireNotNull(activity).currentFocus
Receiving.update(owner) { it.copy(received = Long.MAX_VALUE) }
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
assertSame(original, screen().filterIsInstance<RoundScrollView>().single())
assertSame(focused, requireNotNull(activity).currentFocus)
assertTrue(screen().filterIsInstance<TextView>().any { it.text == "100%" })
assertTrue(
screen().filterIsInstance<TextView>().any { it.text == "Just checking…" }
)
}
} finally {
Receiving.end(owner, "Receiving stopped")
}
}
@Test
fun externalActivityExtrasCannotSupplyAnInstallerIntent() {
val apk = fixture()
store.stage(apk.copy(state = InstallState.CONFIRM, sessionId = 123))
val intent =
android.content
.Intent(context, WatchActivity::class.java)
.putExtra("job", apk.id)
.putExtra("approval", android.content.Intent("untrusted.action"))
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
instrumentation.waitForIdleSync()
assertNull(meghdad.pakkit.install.PendingApproval.intent)
openWatch()
}
@Test
fun homeLeadsWithBrandAndReceiving() {
openWatch()
+2
View File
@@ -23,12 +23,14 @@
android:name=".ui.WatchActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/Theme.Pakkit.Starting"
android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ui.AboutActivity" android:exported="false" android:taskAffinity="" />
<service
android:name=".transfer.ReceiveService"
android:exported="false"
+216
View File
@@ -0,0 +1,216 @@
Pakkit — Open-source acknowledgements
Pakkit includes ZXing (ZXing Authors), AndroidX (The Android Open Source Project), Kotlin and kotlinx.coroutines (JetBrains and contributors), JetBrains annotations, JSpecify and Guava ListenableFuture (Google and contributors).
These libraries are distributed under the Apache License, Version 2.0, reproduced below. Their original copyright notices are retained in the distributed library metadata where supplied.
Projects:
https://github.com/zxing/zxing
https://android.googlesource.com/platform/frameworks/support/
https://github.com/JetBrains/kotlin
https://github.com/Kotlin/kotlinx.coroutines
https://github.com/JetBrains/java-annotations
https://github.com/jspecify/jspecify
https://github.com/google/guava
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
ZXing release source NOTICE
The upstream project-wide notice is reproduced below; it is not an additional runtime dependency list.
--------------------------------------------------------------------------------
NOTICES FOR BARCODE4J
--------------------------------------------------------------------------------
Barcode4J
Copyright 2002-2010 Jeremias Märki
Copyright 2005-2006 Dietmar Bürkle
Portions of this software were contributed under section 5 of the
Apache License. Contributors are listed under:
http://barcode4j.sourceforge.net/contributors.html
--------------------------------------------------------------------------------
NOTICES FOR JCOMMANDER
--------------------------------------------------------------------------------
Copyright 2010 Cedric Beust cedric@beust.com
+17
View File
@@ -0,0 +1,17 @@
Pakkit — Privacy
Pakkit sends the APK you choose directly from your browser to your Wear OS watch over Wi-Fi. There are no accounts, analytics, ads, cloud storage or remote services in Pakkit.
Your connection
Your watch asks before allowing a browser to connect. Access ends when you stop receiving or Pakkit’s process ends. Your browser remembers a random access credential in storage for this watch address. You can remove it using your browser’s site settings. An old credential cannot reopen a stopped session. Browser and device names are hints from the browser; your watch also shows the network address.
Use Wi-Fi you trust. Files and access credentials travel without encryption. Someone with access to your network traffic could read or alter them. Browser approval does not encrypt the connection.
Your files
APKs and their package details are saved in private watch storage. Pakkit checks package information and a file fingerprint before installation; it does not certify that an app is safe. Installation always requires your action and Android’s approval. Android may perform its own checks.
Rejected and interrupted uploads are removed. A received file stays until you remove it, replace a failed review, or finish installation. Files left by an interrupted process are removed when Pakkit next starts. Backups of Pakkit’s private files are disabled. Uninstalling Pakkit removes its private files; apps you installed are separate.
Receiving continues until you stop it or your watch ends it. Losing Wi-Fi interrupts a transfer, and receiving resumes when Wi-Fi returns. Stopping receiving does not cancel an installation already handed to Android.
+46 -17
View File
@@ -14,11 +14,20 @@ function accessHeaders() {
} catch {}
return credential ? { Authorization: 'Bearer ' + credential } : {};
}
let savedTheme;
try {
savedTheme = localStorage.getItem('pakkitTheme');
} catch {}
const initialTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
document.documentElement.dataset.theme = initialTheme;
document.documentElement.dataset.theme = ['light', 'dark'].includes(savedTheme)
? savedTheme
: initialTheme;
$('theme').onclick = () => {
document.documentElement.dataset.theme =
document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem('pakkitTheme', document.documentElement.dataset.theme);
} catch {}
};
function setText(id, value) {
if ($(id).textContent !== value) $(id).textContent = value;
@@ -27,6 +36,8 @@ function message(text = '') {
setText('message', text);
}
function panel(id) {
const active = document.activeElement;
const moveFocus = active && active !== document.body && active.closest('[data-panel]')?.id !== id;
const step = id === 'progress-panel' ? 1 : id === 'result' ? 2 : 0;
document.querySelectorAll('.steps li').forEach((item, index) => {
if (index === step) item.setAttribute('aria-current', 'step');
@@ -37,6 +48,14 @@ function panel(id) {
['pairing', 'dropzone', 'selection', 'progress-panel', 'result'].forEach(
(key) => ($(key).hidden = key !== id),
);
// Move keyboard focus only when its control disappears. Polling must never steal it.
if (moveFocus && active.closest('[data-panel]')) {
const destination = $(id).querySelector('h3, button:not([disabled]), strong');
if (destination) {
destination.tabIndex = destination.matches('button') ? 0 : -1;
destination.focus({ preventScroll: true });
}
}
}
function selected(next) {
if (!online || pending || upload) return;
@@ -82,13 +101,16 @@ zone.addEventListener('drop', (e) => {
});
window.addEventListener('dragover', (e) => e.preventDefault());
window.addEventListener('drop', (e) => e.preventDefault());
function result(title, detail, success = false) {
function result(title, detail, state = 'ready') {
panel('result');
setText('result-title', title);
setText('result-detail', detail);
$('result-icon').textContent = success ? '✓' : '↗';
$('result').dataset.state = success ? 'success' : 'waiting';
$('again').hidden = true;
setText(
'result-icon',
state === 'installed' || state === 'waiting' ? '✓' : state === 'failed' ? '!' : '↗',
);
if ($('result').dataset.state !== state) $('result').dataset.state = state;
$('again').hidden = !['installed', 'failed', 'waiting'].includes(state);
}
$('send').onclick = () => {
if (!file || !online || upload) return;
@@ -182,13 +204,25 @@ function pairing(state) {
);
$('retry-connection').hidden = state !== 'denied';
}
async function request(path, options = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(path, { ...options, signal: controller.signal });
// Keep the probe bounded until its small status body arrives as well as headers.
const data = await response.json();
return { ok: response.ok, status: response.status, data };
} finally {
clearTimeout(timeout);
}
}
async function connect(retry = false) {
const response = await fetch(retry ? '/api/retry' : '/api/connect', {
const response = await request(retry ? '/api/retry' : '/api/connect', {
method: 'POST',
headers: accessHeaders(),
});
if (!response.ok) throw new Error('disconnected');
const data = await response.json();
const data = response.data;
if (data.credential) {
credential = data.credential;
try {
@@ -205,19 +239,18 @@ async function poll() {
if (polling) return;
polling = true;
try {
const response = await fetch('/api/status', {
const response = await request('/api/status', {
headers: accessHeaders(),
cache: 'no-store',
signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
});
if (response.status === 403) {
const data = await response.json();
const data = response.data;
if (data.connection === 'unknown') await connect();
else pairing(data.connection);
return;
}
if (!response.ok) throw new Error('disconnected');
const data = await response.json();
const data = response.data;
if (!online) {
message();
if (!pending && !upload) panel(file ? 'selection' : 'dropzone');
@@ -240,14 +273,10 @@ async function poll() {
failed: ['Let’s try that again', data.detail],
};
const content = states[data.state] || ['Check your watch.', data.detail];
result(content[0], content[1], data.state === 'installed');
$('result').dataset.state = data.state;
if (['installed', 'failed'].includes(data.state)) $('again').hidden = false;
if (data.state === 'failed') $('result-icon').textContent = '!';
result(content[0], content[1], data.state);
} else if (pending) {
((pending = false), (choosingNext = false));
result('Ready for another?', 'Your watch is ready to receive a new app.', true);
$('again').hidden = false;
result('Ready for another?', 'Your watch is ready to receive a new app.', 'waiting');
}
} catch {
online = false;
+10 -5
View File
@@ -145,7 +145,8 @@
</div>
<h2 id="card-title">Good things<br />come in Pakkits.</h2>
<p class="card-description">Choose an app for your watch. We’ll deliver it.</p>
<div id="pairing" role="status" aria-live="polite">
<noscript><p>Turn on JavaScript in your browser to send apps to your watch.</p></noscript>
<div id="pairing" data-panel role="status" aria-live="polite">
<div class="pairing-symbol" aria-hidden="true">↗</div>
<h3 id="pairing-title">A quick hello</h3>
<p id="pairing-detail">Tap Allow browser on your watch.</p>
@@ -156,7 +157,7 @@
<li>Send</li>
<li>Wear</li>
</ol>
<div id="dropzone" class="dropzone">
<div id="dropzone" data-panel class="dropzone">
<div class="upload-symbol" aria-hidden="true">↑</div>
<strong>A little app. A new possibility.</strong
><span>Drop an APK here to get started.</span
@@ -169,7 +170,7 @@
hidden
/><small>APK files · sent directly to your watch</small>
</div>
<div id="selection" hidden>
<div id="selection" data-panel hidden>
<div class="file-row">
<div class="file-icon" aria-hidden="true">◇</div>
<div><strong id="filename"></strong><small id="filesize"></small></div>
@@ -179,7 +180,7 @@
Send to watch <span aria-hidden="true">→</span>
</button>
</div>
<div id="progress-panel" hidden>
<div id="progress-panel" data-panel hidden>
<div class="progress-heading">
<strong id="progress-title">On its way</strong><span id="percentage">0%</span>
</div>
@@ -187,7 +188,7 @@
<p id="progress-detail">Keep this page open. Your app is on its way.</p>
<button id="cancel" class="secondary" type="button">Cancel transfer</button>
</div>
<div id="result" role="status" aria-live="polite" aria-atomic="true" hidden>
<div id="result" data-panel role="status" aria-live="polite" aria-atomic="true" hidden>
<div id="result-icon" aria-hidden="true">✓</div>
<h3 id="result-title">Made it to your watch</h3>
<p id="result-detail">Tap Install on your watch when you’re ready.</p>
@@ -213,6 +214,10 @@
</p>
</details>
</span>
<span class="legal-links"
><a href="/privacy.txt" target="_blank" rel="noopener">Privacy</a
><a href="/licenses.txt" target="_blank" rel="noopener">Open-source licenses</a></span
>
</footer>
</div>
</body>
+11
View File
@@ -890,3 +890,14 @@ small {
background: #9e82ff12;
font-size: 28px;
}
.legal-links {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.legal-links a {
color: var(--muted);
text-underline-offset: 4px;
min-height: 24px;
}
@@ -47,8 +47,13 @@ class PackageStore(context: Context) {
fun dismiss(id: String) =
synchronized(lock) {
if (pending()?.id != id) return@synchronized
val previous = preferences.getString(PENDING_KEY, null)
if (!preferences.edit().remove(PENDING_KEY).commit()) {
if (!preferences.edit().putString(PENDING_KEY, previous).commit())
android.util.Log.w("PakkitStore", "Could not persist removal rollback")
throw UserMessage("Couldn’t remove this app. Try again.")
}
file(id).delete()
check(preferences.edit().remove(PENDING_KEY).commit())
}
/** Called at process startup, before any transfer can own an uncommitted file. */
@@ -92,7 +92,7 @@ class InstallReceiver : BroadcastReceiver() {
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
if (PendingApproval.intent == null) return
val manager = context.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(
@@ -106,10 +106,7 @@ class InstallReceiver : BroadcastReceiver() {
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
val open =
Intent(context, WatchActivity::class.java)
.putExtra("approval", confirmation)
.putExtra("job", apk.id)
val open = Intent(context, WatchActivity::class.java)
val pending =
PendingIntent.getActivity(
context,
@@ -113,7 +113,7 @@ class LocalHttpServer(
response.send(
200,
asset.second,
context.assets.open("web/${asset.first}").use { it.readBytes() },
context.assets.open(asset.first).use { it.readBytes() },
)
return
}
@@ -310,9 +310,11 @@ class LocalHttpServer(
const val PORT = 8787
private val ASSETS =
mapOf(
"/" to ("index.html" to "text/html; charset=utf-8"),
"/style.css" to ("style.css" to "text/css; charset=utf-8"),
"/app.js" to ("app.js" to "text/javascript; charset=utf-8"),
"/" to ("web/index.html" to "text/html; charset=utf-8"),
"/style.css" to ("web/style.css" to "text/css; charset=utf-8"),
"/app.js" to ("web/app.js" to "text/javascript; charset=utf-8"),
"/privacy.txt" to ("legal/privacy.txt" to "text/plain; charset=utf-8"),
"/licenses.txt" to ("legal/licenses.txt" to "text/plain; charset=utf-8"),
)
}
}
@@ -1,6 +1,5 @@
package meghdad.pakkit.transfer
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
@@ -14,10 +13,14 @@ import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Handler
import android.os.Looper
import androidx.core.app.NotificationCompat
import androidx.wear.ongoing.OngoingActivity
import androidx.wear.ongoing.Status
import java.net.BindException
import java.net.Inet4Address
import java.net.InetAddress
import meghdad.pakkit.R
import meghdad.pakkit.data.PackageStore
import meghdad.pakkit.ui.WatchActivity
/** User-controlled receiving; network loss suspends the listener, never the user's intent. */
@@ -29,6 +32,16 @@ class ReceiveService : Service() {
private var address: InetAddress? = null
private var registered = false
private var ended = false
private lateinit var notification: NotificationCompat.Builder
private lateinit var ongoing: OngoingActivity
private var notificationState = ""
private val store by lazy { PackageStore(this) }
private val notificationUpdate = Runnable { updateNotification() }
private val sessionObserver: () -> Unit = { scheduleNotification() }
private val reviewObserver =
android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == PackageStore.PENDING_KEY || key == null) main.post { scheduleNotification() }
}
private val access = BrowserAccess { request ->
Receiving.update(this) { it.copy(browserRequest = request) }
}
@@ -76,7 +89,10 @@ class ReceiveService : Service() {
finish("Receiving stopped")
return START_NOT_STICKY
}
if (registered || ended) return START_NOT_STICKY
if (registered || ended) {
if (!ended) scheduleNotification()
return START_NOT_STICKY
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel("receive", "App transfers", NotificationManager.IMPORTANCE_LOW)
@@ -95,20 +111,29 @@ class ReceiveService : Service() {
Intent(this, ReceiveService::class.java).setAction(STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val notification =
Notification.Builder(this, "receive")
notification =
NotificationCompat.Builder(this, "receive")
.setSmallIcon(R.drawable.pakkit_mark)
.setContentTitle("Receiving is on")
.setContentText("Open Pakkit to connect your browser.")
.setContentIntent(open)
.setOngoing(true)
.addAction(Notification.Action.Builder(null, "Stop receiving", stop).build())
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.addAction(0, getString(R.string.watch_end_session), stop)
ongoing =
OngoingActivity.Builder(this, NOTIFICATION, notification)
.setStaticIcon(R.drawable.pakkit_mark)
.setTouchIntent(open)
.build()
ongoing.apply(this)
startForeground(
NOTIFICATION,
notification,
notification.build(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
)
Receiving.observe(sessionObserver)
store.preferences.registerOnSharedPreferenceChangeListener(reviewObserver)
Receiving.begin(this, access)
try {
registered = true
@@ -127,6 +152,52 @@ class ReceiveService : Service() {
return START_NOT_STICKY
}
private fun scheduleNotification() {
// Coalesce quick phase changes and stay below the system's notification rate limit.
// No repeating idle timer; the latest state is read only after an actual change.
if (!ended && !main.hasCallbacks(notificationUpdate))
main.postDelayed(notificationUpdate, 1000)
}
private fun updateNotification() {
if (ended || !::ongoing.isInitialized) return
if (
android.os.Build.VERSION.SDK_INT >= 33 &&
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
android.content.pm.PackageManager.PERMISSION_GRANTED
)
return
val live = Receiving.state
val job = store.pending()
val (title, detail) =
when {
live.browserRequest != null ->
"Connect browser?" to "Open Pakkit to approve this browser."
live.total > 0 -> "Your app is on its way" to "Open Pakkit to follow the transfer."
job != null ->
when (job.state) {
meghdad.pakkit.apk.InstallState.READY ->
"Ready to install" to "Review ${job.apk.label} on your watch."
meghdad.pakkit.apk.InstallState.CONFIRM ->
"Ready for your approval" to "Open Pakkit to continue."
meghdad.pakkit.apk.InstallState.INSTALLING ->
"Getting ready" to "Your watch will ask you to approve installation."
meghdad.pakkit.apk.InstallState.INSTALLED ->
"All yours." to "${job.apk.label} is ready to wear."
meghdad.pakkit.apk.InstallState.FAILED ->
"Couldn’t install" to "Open Pakkit to try again."
}
live.url == null ->
"Waiting for Wi-Fi" to "Receiving will resume when your watch reconnects."
else -> "Receiving is on" to "Open Pakkit to connect your browser."
}
val state = "$title:$detail"
if (notificationState == state) return
notificationState = state
notification.setContentTitle(title).setContentText(detail)
ongoing.update(this, Status.forPart(Status.TextPart(detail)))
}
private fun open(network: Network, address: InetAddress) {
suspendListener()
this.network = network
@@ -166,6 +237,8 @@ class ReceiveService : Service() {
private fun release(message: String) {
main.removeCallbacksAndMessages(null)
Receiving.removeObserver(sessionObserver)
store.preferences.unregisterOnSharedPreferenceChangeListener(reviewObserver)
server?.close()
server = null
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
@@ -0,0 +1,74 @@
package meghdad.pakkit.ui
import android.app.Activity
import android.os.Bundle
import android.view.Gravity
import meghdad.pakkit.R
/** Offline disclosures remain available even when receiving is off. */
class AboutActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val scroll = RoundScrollView(this).apply { setBackgroundColor(WatchColors.canvas) }
val column =
WatchDesign.column(this).apply {
val side =
WatchDesign.dp(
this@AboutActivity,
(resources.configuration.screenWidthDp * .15f).toInt(),
)
setPadding(
side,
WatchDesign.dp(this@AboutActivity, 28),
side,
WatchDesign.dp(this@AboutActivity, 64),
)
}
val licenses = intent.getBooleanExtra("licenses", false)
val text =
assets
.open(if (licenses) "legal/licenses.txt" else "legal/privacy.txt")
.bufferedReader()
.use { it.readText() }
text.trim().split("\n\n").forEachIndexed { index, paragraph ->
val heading = index == 0 || (!licenses && paragraph.length < 40)
column.addView(
WatchDesign.text(
this,
paragraph,
if (index == 0) 20f else if (heading) 16f else 13f,
bold = heading,
)
.apply {
gravity = if (index == 0) Gravity.CENTER else Gravity.START
isAccessibilityHeading = heading
},
android.widget.LinearLayout.LayoutParams(-1, -2).apply {
bottomMargin = WatchDesign.dp(this@AboutActivity, 14)
},
)
}
if (!licenses)
column.addView(
WatchDesign.button(this, getString(R.string.watch_licenses), false) {
startActivity(
android.content
.Intent(this, AboutActivity::class.java)
.putExtra("licenses", true)
)
}
)
column.addView(WatchDesign.button(this, getString(R.string.watch_done), false) { finish() })
scroll.addView(column)
setContentView(scroll)
scroll.isFocusableInTouchMode = true
scroll.requestFocus()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
}
override fun onSaveInstanceState(outState: Bundle) {
val content = findViewById<android.view.ViewGroup>(android.R.id.content)
outState.putInt("scroll", (content.getChildAt(0) as RoundScrollView).scrollY)
super.onSaveInstanceState(outState)
}
}
@@ -16,6 +16,8 @@ import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextClock
import android.widget.TextView
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import java.util.concurrent.Executors
import kotlin.math.roundToInt
import meghdad.pakkit.R
@@ -42,13 +44,17 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
private var resumed = false
private var approvalLaunched: Int? = null
private var requestedInstallId: String? = null
private var progressTitle: TextView? = null
private var progressPercent: TextView? = null
private var progressDetail: TextView? = null
private var progressBar: ProgressBar? = null
private var qrUrl = ""
private var qrBitmap: android.graphics.Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
store = PackageStore(this)
acceptIntent(intent)
requestedInstallId = savedInstanceState?.getString("requestedInstallId")
approvalLaunched = savedInstanceState?.getInt("approvalLaunched", -1)?.takeIf { it >= 0 }
refresh()
@@ -65,24 +71,9 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
acceptIntent(intent)
refresh()
}
private fun acceptIntent(intent: Intent) {
val job = store.pending()
@Suppress("DEPRECATION") val approval = intent.getParcelableExtra<Intent>("approval")
if (
approval != null &&
job != null &&
job.id == intent.getStringExtra("job") &&
job.state == InstallState.CONFIRM
) {
PendingApproval.intent = approval
PendingApproval.id = job.id
}
}
override fun onResume() {
super.onResume()
resumed = true
@@ -207,6 +198,12 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
live.active -> "connecting"
else -> "home"
}
// Keep the same view tree while bytes arrive: TalkBack, rotary focus and
// scroll position must survive progress updates without repeated layout work.
if (stateKey == "uploading" && renderedState == stateKey && error == null) {
updateProgress(live)
return
}
val previousState = renderedState
if (stateKey != previousState) error = null
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
@@ -248,6 +245,18 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
button(getString(R.string.watch_start_receiving), false) { startReceiving() }
}
}
if (
live.active &&
live.browserRequest == null &&
job?.state != InstallState.CONFIRM &&
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)
}
}
scroll.isFocusable = true
scroll.isFocusableInTouchMode = true
@@ -288,35 +297,20 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
if (url != null) {
if (live.total > 0) {
parcel(48)
val percent = (live.received * 100 / live.total).coerceAtMost(100)
add(
line(
if (percent == 100L) getString(R.string.watch_just_checking)
else getString(R.string.watch_on_its_way),
22f,
bold = true,
),
10,
)
add(line("$percent%", 30f, colors.mint, true), 10)
add(
progressTitle = line(getString(R.string.watch_on_its_way), 22f, bold = true)
add(requireNotNull(progressTitle), 10)
progressPercent = line("0%", 30f, colors.mint, true)
add(requireNotNull(progressPercent), 10)
progressBar =
ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
max = 100
progress = percent.toInt()
progressTintList = android.content.res.ColorStateList.valueOf(colors.mint)
contentDescription = getString(R.string.watch_percent_received, percent)
},
12,
)
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,
)
}
add(requireNotNull(progressBar), 12)
progressDetail =
line(getString(R.string.watch_keep_your_browser_open), 13f, colors.secondary)
add(requireNotNull(progressDetail), 10)
updateProgress(live)
} else {
if (qrUrl != url || qrBitmap == null) {
val matrix =
@@ -414,6 +408,31 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
refresh()
}
}
if (!live.active)
button(getString(R.string.watch_privacy), false) {
startActivity(Intent(this, AboutActivity::class.java))
}
}
private fun updateProgress(live: Receiving.State) {
val percent = ((live.received.toDouble() / live.total) * 100).toInt().coerceIn(0, 100)
val title =
getString(
if (percent == 100) R.string.watch_just_checking else R.string.watch_on_its_way
)
val detail =
getString(
if (percent == 100) R.string.watch_getting_your_app_ready
else R.string.watch_keep_your_browser_open
)
if (progressTitle?.text != title) progressTitle?.text = title
if (progressDetail?.text != detail) progressDetail?.text = detail
val label = "$percent%"
if (progressPercent?.text != label) {
progressPercent?.text = label
progressBar?.progress = percent
progressBar?.contentDescription = getString(R.string.watch_percent_received, percent)
}
}
private fun startReceiving() {
@@ -548,8 +567,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
InstallState.INSTALLED -> {
button(getString(R.string.watch_open_app)) { launch(apk.packageName) }
button(getString(R.string.watch_done), false) {
store.dismiss(job.id)
refresh()
dismiss(job)
}
}
}
@@ -563,6 +581,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 52) {
meghdad.pakkit.install.InstallReceiver.notifyApproval(this)
if (Receiving.state.active) startService(Intent(this, ReceiveService::class.java))
refresh()
}
}
@@ -599,7 +618,10 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
private fun dismiss(job: PendingApk) {
PendingApproval.clear()
store.dismiss(job.id)
runCatching { store.dismiss(job.id) }
.onFailure {
error = it.userMessage("Couldn’t remove this app. Try again.")
}
refresh()
}
@@ -11,7 +11,7 @@ import android.widget.LinearLayout
import android.widget.TextView
object WatchColors {
const val canvas = 0xFF090B17.toInt()
const val canvas = Color.BLACK
const val raised = 0xFF1C2035.toInt()
const val text = 0xFFF4F2FF.toInt()
const val secondary = 0xFFB7B6CE.toInt()
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:width="48dp" android:height="48dp"
android:drawable="@mipmap/pakkit_launcher" android:gravity="center" />
</layer-list>
+2
View File
@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="watch_privacy">Privacy</string>
<string name="watch_licenses">Open-source licenses</string>
<string name="watch_end_session">Stop receiving</string>
<string name="watch_just_checking">Just checking…</string>
<string name="watch_on_its_way">On its way</string>
+7 -3
View File
@@ -3,9 +3,13 @@
<style name="Theme.Pakkit" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:colorAccent">#BAA6FF</item>
<item name="android:windowBackground">#090B17</item>
<item name="android:windowBackground">@android:color/black</item>
<item name="android:windowSwipeToDismiss">true</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowSplashScreenBackground">#090B17</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
</style>
<style name="Theme.Pakkit.Starting" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@android:color/black</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/pakkit_splash</item>
<item name="postSplashScreenTheme">@style/Theme.Pakkit</item>
</style>
</resources>