initial project
No files matched your search
@@ -13,3 +13,7 @@
|
|||||||
.externalNativeBuild
|
.externalNativeBuild
|
||||||
.cxx
|
.cxx
|
||||||
local.properties
|
local.properties
|
||||||
|
|
||||||
|
**/build/
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Pakkit
|
||||||
|
|
||||||
|
**Pocket to Wrist.** A phone-to-Wear OS APK companion with an original luminous parcel identity, electric violet, mint and midnight themes, and explicit watch-side consent.
|
||||||
|
|
||||||
|
Pack it. Send it. Wear it. See [the implemented brand system](design/README.md) and the supplied [creative reference](design/brand-concept.png).
|
||||||
|
|
||||||
|
**Status: implemented device-validation build, not a production-certified or Play-approved release.** No debugging, root, hidden APIs, automatic installation, APK marketplace or security bypass appears in the consumer flow. Universal no-setup sideloading on Wear OS is not technically guaranteed. See [the feasibility decision](docs/FEASIBILITY.md) before making product claims.
|
||||||
|
|
||||||
|
## What is implemented
|
||||||
|
|
||||||
|
- Cohesive vector launcher/splash/parcel artwork, themed native components, a persisted phone appearance chooser, finite motion, and a midnight round-watch interface.
|
||||||
|
|
||||||
|
- Separate phone (`app`) and round-screen watch (`wear`) applications with the same application ID and distinct version codes.
|
||||||
|
- Pakkit capability discovery over Google's Wearable Data Layer; nonce-based live capability checks and explicit selection when multiple watches are available.
|
||||||
|
- Android's file picker, private APK storage, bounded streaming (50 MiB), archive/package inspection, signing-metadata checks, SHA-256 transfer integrity, API/ABI/storage preflight.
|
||||||
|
- Persistent, retried work and Data Layer asset syncing. No fabricated percentages or success states. One active transfer per phone and one active received APK per watch.
|
||||||
|
- Watch review and explicit install action, public PackageInstaller sessions with required user action, system confirmation handoff, optional approval notification, and structured installation results.
|
||||||
|
- Hardware/firmware limitations, unsupported package formats, errors, transfer history, privacy explanation and a Google Play fallback.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
Use Android Studio's Java 21 runtime, Android SDK 36.1, and the included Gradle wrapper. Both apps support Android API 31+ and target API 36.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew :app:assembleDebug :wear:assembleDebug :shared:testDebugUnitTest :app:lintDebug :wear:lintDebug
|
||||||
|
```
|
||||||
|
|
||||||
|
Google Maven returned HTTP 404 in the original development environment. An **optional**, explicitly selected mirror is supported; Google's repository remains the default:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew :app:assembleDebug :wear:assembleDebug -PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google
|
||||||
|
```
|
||||||
|
|
||||||
|
Review mirror provenance and validate dependency checksums through your trusted build environment before production distribution. Dependency versions are pinned; no dynamically versioned libraries are used.
|
||||||
|
|
||||||
|
Open both app modules in Android Studio. Install the phone build on the phone and the watch build on a **paired** Wear OS device, using the same signing certificate. Open the watch app first and allow external installs if its firmware exposes that setting. Refresh the phone connection. A reachable watch with the install capability and source approval is required before sending.
|
||||||
|
|
||||||
|
APK outputs: `app/build/outputs/apk/debug/app-debug.apk` and `wear/build/outputs/apk/debug/wear-debug.apk`. Release bundles are produced with `:app:bundleRelease :wear:bundleRelease`. Release signing uses optional environment variables described in [RELEASE.md](docs/RELEASE.md); without them bundles remain unsigned.
|
||||||
|
|
||||||
|
## Development guide
|
||||||
|
|
||||||
|
- `shared`: package inspection, bounded IO, protocol, persistence, workers, and visual primitives.
|
||||||
|
- `app`: file selection, connection, file review, activity and guidance.
|
||||||
|
- `wear`: review, unknown-source settings, installation and result receiver.
|
||||||
|
- [Architecture and security](docs/ARCHITECTURE.md)
|
||||||
|
- [Feasibility and official sources](docs/FEASIBILITY.md)
|
||||||
|
- [Release preparation](docs/RELEASE.md)
|
||||||
|
- [Validation record and physical-device checklist](docs/VALIDATION.md)
|
||||||
|
|
||||||
|
Never replace a real capability, transfer result or installer result with a timed simulation. Do not introduce ADB pairing, privileged installation or security-setting automation to make an unsupported watch appear supported. Test-only emulator tooling is distinct from consumer functionality.
|
||||||
@@ -1,43 +1,49 @@
|
|||||||
plugins {
|
plugins { alias(libs.plugins.android.application) }
|
||||||
alias(libs.plugins.android.application)
|
|
||||||
}
|
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "meghdad.pakkit"
|
namespace = "meghdad.pakkit"
|
||||||
compileSdk {
|
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||||
version = release(36) {
|
|
||||||
minorApiLevel = 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "meghdad.pakkit"
|
applicationId = "meghdad.pakkit"
|
||||||
minSdk = 31
|
minSdk = 31
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = 100001
|
||||||
versionName = "1.0"
|
versionName = "0.1.0"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
|
val releaseKey = providers.environmentVariable("PAKKIT_KEYSTORE").orNull
|
||||||
buildTypes {
|
val releaseStorePassword = providers.environmentVariable("PAKKIT_KEYSTORE_PASSWORD").orNull
|
||||||
release {
|
val releaseAlias = providers.environmentVariable("PAKKIT_KEY_ALIAS").orNull
|
||||||
optimization {
|
val releaseKeyPassword = providers.environmentVariable("PAKKIT_KEY_PASSWORD").orNull
|
||||||
enable = false
|
if (listOf(releaseKey, releaseStorePassword, releaseAlias, releaseKeyPassword).all { it != null }) {
|
||||||
|
signingConfigs.create("production") {
|
||||||
|
storeFile = file(requireNotNull(releaseKey)); storePassword = releaseStorePassword
|
||||||
|
keyAlias = releaseAlias; keyPassword = releaseKeyPassword
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
buildTypes { release { signingConfig = signingConfigs.findByName("production"); isMinifyEnabled = true; isShrinkResources = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "../proguard-rules.pro") } }
|
||||||
|
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
|
||||||
}
|
}
|
||||||
compileOptions {
|
|
||||||
sourceCompatibility = JavaVersion.VERSION_11
|
|
||||||
targetCompatibility = JavaVersion.VERSION_11
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(libs.androidx.appcompat)
|
implementation(project(":shared"))
|
||||||
implementation(libs.androidx.core.ktx)
|
|
||||||
implementation(libs.material)
|
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
abstract class StageFixtureApk : DefaultTask() {
|
||||||
|
@get:InputFile abstract val fixtureFile: RegularFileProperty
|
||||||
|
@get:OutputDirectory abstract val outputDirectory: DirectoryProperty
|
||||||
|
@TaskAction fun stage() {
|
||||||
|
val output = outputDirectory.file("fixture.apk").get().asFile
|
||||||
|
output.parentFile.mkdirs()
|
||||||
|
fixtureFile.get().asFile.copyTo(output, overwrite = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val stageTestFixture by tasks.registering(StageFixtureApk::class) {
|
||||||
|
dependsOn(":qaFixture:assembleDebug")
|
||||||
|
fixtureFile.set(project(":qaFixture").layout.buildDirectory.file("outputs/apk/debug/qaFixture-debug.apk"))
|
||||||
|
outputDirectory.set(layout.buildDirectory.dir("generated/testAssets"))
|
||||||
|
}
|
||||||
|
androidComponents.onVariants(androidComponents.selector().withBuildType("debug")) { variant ->
|
||||||
|
variant.androidTest?.sources?.assets?.addGeneratedSourceDirectory(stageTestFixture, StageFixtureApk::outputDirectory)
|
||||||
|
}
|
||||||
@@ -1,24 +1,107 @@
|
|||||||
package meghdad.pakkit
|
package meghdad.pakkit
|
||||||
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.TextView
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import meghdad.pakkit.core.Design
|
||||||
|
import meghdad.pakkit.core.BrandPalette
|
||||||
|
import androidx.test.espresso.Espresso.onView
|
||||||
|
import androidx.test.espresso.action.ViewActions.click
|
||||||
|
import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||||
|
import meghdad.pakkit.core.Packages
|
||||||
|
import meghdad.pakkit.core.Store
|
||||||
|
import org.junit.Assert.*
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import org.junit.runner.RunWith
|
import org.junit.runner.RunWith
|
||||||
|
import java.io.File
|
||||||
|
import java.util.zip.ZipEntry
|
||||||
|
import java.util.zip.ZipOutputStream
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instrumented test, which will execute on an Android device.
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
@RunWith(AndroidJUnit4::class)
|
||||||
class ExampleInstrumentedTest {
|
class ProductInstrumentedTest {
|
||||||
@Test
|
private val instrumentation get() = InstrumentationRegistry.getInstrumentation()
|
||||||
fun useAppContext() {
|
private val context get() = instrumentation.targetContext
|
||||||
// Context of the app under test.
|
private fun texts(view: View): List<TextView> = when(view) {
|
||||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
is ViewGroup -> (0 until view.childCount).flatMap { texts(view.getChildAt(it)) }
|
||||||
assertEquals("meghdad.pakkit", appContext.packageName)
|
is TextView -> listOf(view)
|
||||||
|
else -> emptyList()
|
||||||
|
}
|
||||||
|
@Test fun navigationAndRecreationRetainSelectedPage() {
|
||||||
|
val monitor=instrumentation.addMonitor(MainActivity::class.java.name,null,false)
|
||||||
|
context.startActivity(Intent(context,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
|
val activity=monitor.waitForActivityWithTimeout(5000) as Activity
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
assertEquals("Pocket to Wrist.", activity.findViewById<TextView>(R.id.page_heading).text.toString())
|
||||||
|
activity.findViewById<View>(R.id.nav_guide).performClick()
|
||||||
|
assertEquals("Good to know.", activity.findViewById<TextView>(R.id.page_heading).text.toString())
|
||||||
|
activity.recreate()
|
||||||
|
}
|
||||||
|
val recreated=monitor.waitForActivityWithTimeout(5000)
|
||||||
|
assertNotNull(recreated)
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
assertEquals("Good to know.", recreated.findViewById<TextView>(R.id.page_heading).text.toString())
|
||||||
|
recreated.finish()
|
||||||
|
}
|
||||||
|
instrumentation.removeMonitor(monitor)
|
||||||
|
}
|
||||||
|
@Test fun themeChooserAppliesAndPersistsMidnightTheme() {
|
||||||
|
val original = Design.themeMode(context)
|
||||||
|
Design.setThemeMode(context, "light")
|
||||||
|
val monitor = instrumentation.addMonitor(MainActivity::class.java.name, null, false)
|
||||||
|
try {
|
||||||
|
context.startActivity(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
|
val light = monitor.waitForActivityWithTimeout(5000)
|
||||||
|
assertNotNull(light)
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
assertEquals(BrandPalette.Light.text, light.findViewById<TextView>(R.id.page_heading).currentTextColor)
|
||||||
|
light.findViewById<View>(R.id.appearance).performClick()
|
||||||
|
}
|
||||||
|
onView(withText("Midnight dark")).perform(click())
|
||||||
|
val dark = monitor.waitForActivityWithTimeout(5000)
|
||||||
|
assertNotNull(dark)
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
assertEquals("dark", Design.themeMode(context))
|
||||||
|
assertEquals(BrandPalette.Dark.text, dark.findViewById<TextView>(R.id.page_heading).currentTextColor)
|
||||||
|
dark.recreate()
|
||||||
|
}
|
||||||
|
val restored = monitor.waitForActivityWithTimeout(5000)
|
||||||
|
assertNotNull(restored)
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
assertEquals(BrandPalette.Dark.text, restored.findViewById<TextView>(R.id.page_heading).currentTextColor)
|
||||||
|
restored.finish()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
instrumentation.removeMonitor(monitor)
|
||||||
|
Design.setThemeMode(context, original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Test fun readsSignedCompleteWearApk() {
|
||||||
|
val file=File(context.cacheDir,"fixture.apk")
|
||||||
|
try {
|
||||||
|
val digest=instrumentation.context.assets.open("fixture.apk").use { input -> file.outputStream().use { meghdad.pakkit.core.TransferRules.copyBounded(input,it).second } }
|
||||||
|
val apk=Packages.inspect(context,file,digest)
|
||||||
|
assertEquals("meghdad.pakkit.fixture",apk.packageName)
|
||||||
|
assertTrue(apk.wear)
|
||||||
|
assertEquals(31,apk.minSdk)
|
||||||
|
assertTrue(apk.bytes>0)
|
||||||
|
} finally { file.delete() }
|
||||||
|
}
|
||||||
|
@Test fun rejectsOwnPackageForSelfUpdates() {
|
||||||
|
val file=File(context.applicationInfo.sourceDir)
|
||||||
|
val failure=runCatching { Packages.inspect(context,file,"test") }.exceptionOrNull()
|
||||||
|
assertNotNull(failure)
|
||||||
|
assertTrue(failure!!.message.orEmpty().contains("Google Play"))
|
||||||
|
}
|
||||||
|
@Test fun rejectsNonApkArchivesAndPathTraversal() {
|
||||||
|
val file=File(context.cacheDir,"invalid.apk")
|
||||||
|
ZipOutputStream(file.outputStream()).use { it.putNextEntry(ZipEntry("readme.txt")); it.write("hello".toByteArray()); it.closeEntry() }
|
||||||
|
try {
|
||||||
|
assertNotNull(runCatching { Packages.inspect(context,file,"test") }.exceptionOrNull())
|
||||||
|
assertNotNull(runCatching { Store(context).file("../outside") }.exceptionOrNull())
|
||||||
|
} finally { file.delete() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<application android:allowBackup="false" android:dataExtractionRules="@xml/pakkit_data_rules" android:icon="@mipmap/pakkit_launcher" android:label="@string/pakkit_name" android:supportsRtl="true" android:theme="@style/Theme.Pakkit">
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
<activity android:name=".MainActivity" android:exported="true">
|
||||||
|
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
|
||||||
<application
|
</activity>
|
||||||
android:allowBackup="true"
|
</application>
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
|
||||||
android:supportsRtl="true"
|
|
||||||
android:theme="@style/Theme.Pakkit" />
|
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
package meghdad.pakkit
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.widget.*
|
||||||
|
import androidx.work.*
|
||||||
|
import com.google.android.gms.wearable.*
|
||||||
|
import meghdad.pakkit.core.*
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class MainActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeListener {
|
||||||
|
private val io = Executors.newSingleThreadExecutor()
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
private val colors by lazy { Design.palette(this) }
|
||||||
|
private lateinit var store: Store
|
||||||
|
private lateinit var content: LinearLayout
|
||||||
|
private lateinit var scroll: ScrollView
|
||||||
|
private var renderedPage = -1
|
||||||
|
private var page = 0
|
||||||
|
private var finding = false
|
||||||
|
private var importing = false
|
||||||
|
private var watch: Node? = null
|
||||||
|
private var capabilities: DataMap? = null
|
||||||
|
private var capabilitiesReceivedAt = 0L
|
||||||
|
private var connectionText = "Open Pakkit on your paired watch to begin."
|
||||||
|
private var message: String? = null
|
||||||
|
private var nonce = ""
|
||||||
|
private var appearanceDialog: Dialog? = null
|
||||||
|
private val redraw = Runnable { if (!isDestroyed) render() }
|
||||||
|
private val listener = DataClient.OnDataChangedListener { events ->
|
||||||
|
for (e in events) {
|
||||||
|
if (e.type == DataEvent.TYPE_CHANGED && e.dataItem.uri.path?.startsWith("/pakkit/cap/") == true) {
|
||||||
|
val map = DataMapItem.fromDataItem(e.dataItem).dataMap
|
||||||
|
if (e.dataItem.uri.host == watch?.id && map.getString("nonce") == nonce) {
|
||||||
|
capabilities = map
|
||||||
|
capabilitiesReceivedAt = android.os.SystemClock.elapsedRealtime()
|
||||||
|
connectionText = "Your watch is connected. You’re ready to send."
|
||||||
|
finding = false
|
||||||
|
render()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
setTheme(if (Design.isDark(this)) R.style.Theme_Pakkit_Dark else R.style.Theme_Pakkit_Light)
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
store = Store(this)
|
||||||
|
store.clean()
|
||||||
|
page = savedInstanceState?.getInt("page") ?: 0
|
||||||
|
render()
|
||||||
|
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
|
||||||
|
}
|
||||||
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
|
outState.putInt("page", page)
|
||||||
|
outState.putInt("scroll", scroll.scrollY)
|
||||||
|
super.onSaveInstanceState(outState)
|
||||||
|
}
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
store.prefs.registerOnSharedPreferenceChangeListener(this)
|
||||||
|
Wearable.getDataClient(this).addListener(listener).addOnFailureListener {
|
||||||
|
connectionText = "Google Play services is unavailable. Reopen Pakkit after it’s available."
|
||||||
|
render()
|
||||||
|
}
|
||||||
|
discover()
|
||||||
|
}
|
||||||
|
override fun onPause() {
|
||||||
|
store.prefs.unregisterOnSharedPreferenceChangeListener(this)
|
||||||
|
Wearable.getDataClient(this).removeListener(listener)
|
||||||
|
super.onPause()
|
||||||
|
}
|
||||||
|
override fun onDestroy() { appearanceDialog?.dismiss(); main.removeCallbacksAndMessages(null); io.shutdown(); super.onDestroy() }
|
||||||
|
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
|
||||||
|
if (key == "outgoing" || key == "history" || key == null) {
|
||||||
|
main.removeCallbacks(redraw)
|
||||||
|
main.postDelayed(redraw, 32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun dp(n: Int) = Design.dp(this, n)
|
||||||
|
private fun text(value: String, size: Float = 16f, color: Int = colors.text, bold: Boolean = false) = Design.text(this, value, size, color, bold)
|
||||||
|
private fun add(v: View, parent: LinearLayout = content, top: Int = 0) {
|
||||||
|
parent.addView(v, LinearLayout.LayoutParams(-1, v.layoutParams?.height ?: -2).apply { topMargin = dp(top) })
|
||||||
|
}
|
||||||
|
private fun card(color: Int = colors.surface) = Design.column(this).apply {
|
||||||
|
setPadding(dp(20), dp(20), dp(20), dp(20))
|
||||||
|
background = Design.shape(color, dp(26).toFloat(), colors.border)
|
||||||
|
}
|
||||||
|
private fun action(label: String, primary: Boolean = true, callback: () -> Unit) = Design.button(this, label, primary, callback)
|
||||||
|
private fun icon(glyph: Glyph, tint: Int = colors.accent, size: Int = 24) = ImageView(this).apply {
|
||||||
|
setImageDrawable(GlyphDrawable(glyph, tint))
|
||||||
|
layoutParams = LinearLayout.LayoutParams(dp(size), dp(size))
|
||||||
|
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||||
|
}
|
||||||
|
private fun heading(value: String, caption: String) {
|
||||||
|
add(text(value, 38f, bold = true).apply { id = R.id.page_heading; letterSpacing = -.045f }, top = 26)
|
||||||
|
add(text(caption, 15f, colors.secondary), top = 10)
|
||||||
|
}
|
||||||
|
private fun render(animate: Boolean = false) {
|
||||||
|
if (isDestroyed || isFinishing) return
|
||||||
|
val y = if (::scroll.isInitialized && renderedPage == page) scroll.scrollY else 0
|
||||||
|
renderedPage = page
|
||||||
|
val root = Design.column(this).apply { background = AuroraDrawable(colors) }
|
||||||
|
root.setOnApplyWindowInsetsListener { v, insets ->
|
||||||
|
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars())
|
||||||
|
v.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
||||||
|
insets
|
||||||
|
}
|
||||||
|
scroll = ScrollView(this).apply { isFillViewport = true; clipToPadding = false; isVerticalScrollBarEnabled = false }
|
||||||
|
val frame = FrameLayout(this)
|
||||||
|
content = Design.column(this).apply { setPadding(dp(20), dp(18), dp(20), dp(24)) }
|
||||||
|
frame.addView(content, FrameLayout.LayoutParams(minOf(resources.displayMetrics.widthPixels, dp(640)), -2, Gravity.TOP or Gravity.CENTER_HORIZONTAL))
|
||||||
|
scroll.addView(frame)
|
||||||
|
root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||||
|
header()
|
||||||
|
when (page) { 0 -> transferPage(); 1 -> activityPage(); else -> guidePage() }
|
||||||
|
root.addView(navigation())
|
||||||
|
setContentView(root)
|
||||||
|
root.requestApplyInsets()
|
||||||
|
scroll.post { scroll.scrollTo(0, y) }
|
||||||
|
if (animate) Design.entrance(content)
|
||||||
|
}
|
||||||
|
private fun header() {
|
||||||
|
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
row.addView(ImageView(this).apply {
|
||||||
|
setImageResource(meghdad.pakkit.core.R.drawable.pakkit_icon)
|
||||||
|
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||||
|
}, LinearLayout.LayoutParams(dp(48), dp(48)).apply { marginStart = -dp(8) })
|
||||||
|
row.addView(text("Pakkit", 27f, bold = true).apply { letterSpacing = -.05f }, LinearLayout.LayoutParams(0, -2, 1f))
|
||||||
|
row.addView(ImageButton(this).apply {
|
||||||
|
id = R.id.appearance
|
||||||
|
setImageDrawable(GlyphDrawable(Glyph.APPEARANCE, colors.text))
|
||||||
|
scaleType = ImageView.ScaleType.FIT_CENTER
|
||||||
|
setPadding(dp(14), dp(14), dp(14), dp(14))
|
||||||
|
background = android.graphics.drawable.RippleDrawable(android.content.res.ColorStateList.valueOf(0x227150EF), Design.shape(colors.surface, dp(18).toFloat(), colors.border), null)
|
||||||
|
contentDescription = "Appearance: ${Design.themeMode(this@MainActivity)}. Change theme"
|
||||||
|
setOnClickListener { appearance() }
|
||||||
|
}, LinearLayout.LayoutParams(dp(48), dp(48)))
|
||||||
|
add(row)
|
||||||
|
}
|
||||||
|
private fun navigation(): View {
|
||||||
|
val frame = FrameLayout(this).apply { background = Design.shape(colors.surface, 0f, colors.border) }
|
||||||
|
val row = LinearLayout(this).apply { setPadding(dp(16), dp(8), dp(16), dp(8)) }
|
||||||
|
val labels = listOf("Transfer", "Activity", "Guide")
|
||||||
|
val glyphs = listOf(Glyph.TRANSFER, Glyph.HISTORY, Glyph.GUIDE)
|
||||||
|
val ids = listOf(R.id.nav_transfer, R.id.nav_activity, R.id.nav_guide)
|
||||||
|
labels.forEachIndexed { index, label ->
|
||||||
|
row.addView(action(label, false) { if (page != index) { page = index; render(animate = true) } }.apply {
|
||||||
|
id = ids[index]
|
||||||
|
isSelected = page == index
|
||||||
|
textSize = 12f
|
||||||
|
minHeight = dp(60)
|
||||||
|
setPadding(dp(8), dp(8), dp(8), dp(8))
|
||||||
|
background = android.graphics.drawable.RippleDrawable(android.content.res.ColorStateList.valueOf(0x227150EF), Design.shape(if (isSelected) colors.accentSoft else Color.TRANSPARENT, dp(18).toFloat()), null)
|
||||||
|
setTextColor(if (isSelected) colors.accent else colors.secondary)
|
||||||
|
val glyph = GlyphDrawable(glyphs[index], if (isSelected) colors.accent else colors.secondary).apply { setBounds(0, 0, dp(21), dp(21)) }
|
||||||
|
setCompoundDrawables(null, glyph, null, null)
|
||||||
|
compoundDrawablePadding = dp(5)
|
||||||
|
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(5) })
|
||||||
|
}
|
||||||
|
frame.addView(row, FrameLayout.LayoutParams(minOf(resources.displayMetrics.widthPixels, dp(640)), -2, Gravity.CENTER))
|
||||||
|
return frame
|
||||||
|
}
|
||||||
|
private fun appearance() {
|
||||||
|
val dialog = Dialog(this)
|
||||||
|
appearanceDialog = dialog
|
||||||
|
val sheet = Design.column(this).apply { setPadding(dp(24), dp(26), dp(24), dp(20)) }
|
||||||
|
add(text("Make it yours.", 25f, bold = true), sheet)
|
||||||
|
add(text("Choose your atmosphere.", 14f, colors.secondary), sheet, 8)
|
||||||
|
listOf("system" to "Follow device theme", "light" to "Lavender light", "dark" to "Midnight dark").forEach { (mode, label) ->
|
||||||
|
val selected = Design.themeMode(this) == mode
|
||||||
|
add(action(label, false) {
|
||||||
|
Design.setThemeMode(this, mode)
|
||||||
|
dialog.dismiss()
|
||||||
|
recreate()
|
||||||
|
}.apply {
|
||||||
|
gravity = Gravity.CENTER_VERTICAL or Gravity.START
|
||||||
|
isSelected = selected
|
||||||
|
if (selected) {
|
||||||
|
background = Design.shape(colors.accentSoft, dp(18).toFloat(), colors.accent)
|
||||||
|
setTextColor(colors.accent)
|
||||||
|
setCompoundDrawablesRelative(null, null, GlyphDrawable(Glyph.CHECK, colors.accent).apply { setBounds(0, 0, dp(20), dp(20)) }, null)
|
||||||
|
}
|
||||||
|
}, sheet, 14)
|
||||||
|
}
|
||||||
|
add(action("Close", false) { dialog.dismiss() }, sheet, 20)
|
||||||
|
dialog.setContentView(ScrollView(this).apply { addView(sheet) })
|
||||||
|
dialog.window?.setBackgroundDrawable(Design.shape(colors.surface, dp(28).toFloat()))
|
||||||
|
dialog.show()
|
||||||
|
dialog.window?.setLayout(minOf(resources.displayMetrics.widthPixels - dp(40), dp(420)), -2)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun transferPage() {
|
||||||
|
val job = store.read("outgoing")
|
||||||
|
if (job != null) {
|
||||||
|
heading("A little closer.", getString(meghdad.pakkit.core.R.string.brand_secondary_tagline))
|
||||||
|
fileCard(job)
|
||||||
|
connectionCard(compact = true)
|
||||||
|
} else {
|
||||||
|
heading(getString(meghdad.pakkit.core.R.string.brand_tagline), "Your next favorite app. A little closer.")
|
||||||
|
connectionCard()
|
||||||
|
val box = card()
|
||||||
|
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
row.addView(icon(Glyph.FILE, size = 30))
|
||||||
|
row.addView(Design.column(this).apply {
|
||||||
|
add(text("A new wrist essential.", 19f, bold = true), this)
|
||||||
|
add(text("Single APK · up to 50 MB", 13f, colors.secondary), this, 6)
|
||||||
|
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(14) })
|
||||||
|
add(row, box)
|
||||||
|
add(action(if (importing) "Reading your APK…" else "Choose an APK") { pick() }.apply { isEnabled = !importing }, box, 18)
|
||||||
|
add(box, top = 16)
|
||||||
|
}
|
||||||
|
message?.let { notice("A small detour", it, warning = true) }
|
||||||
|
add(text(getString(meghdad.pakkit.core.R.string.brand_secondary_tagline), 13f, colors.secondary, true).apply { gravity = Gravity.CENTER }, top = 24)
|
||||||
|
add(text("Only send apps you trust. You approve installation on your watch.", 12f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 8)
|
||||||
|
}
|
||||||
|
private fun connectionCard(compact: Boolean = false) {
|
||||||
|
val box = card()
|
||||||
|
if (!compact) box.background = Design.gradient(if (colors.dark) intArrayOf(0xFF24203E.toInt(), 0xFF112A31.toInt()) else intArrayOf(0xFFF0E9FF.toInt(), 0xFFE2F7F6.toInt()), dp(26).toFloat())
|
||||||
|
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
row.addView(icon(Glyph.WATCH, if (capabilities != null) colors.mint else colors.accent, 20))
|
||||||
|
row.addView(text(if (capabilities != null) "Connected" else if (finding) "Finding your watch" else "Your watch", 12f, colors.secondary, true), LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(8) })
|
||||||
|
row.addView(text("WEAR OS", 10f, colors.secondary, true).apply { letterSpacing = .12f })
|
||||||
|
add(row, box)
|
||||||
|
if (!compact) add(ParcelSceneView(this).apply { active = finding; layoutParams = LinearLayout.LayoutParams(-1, dp(174)) }, box, 4)
|
||||||
|
add(text(if (finding) "Making the introduction…" else watch?.displayName ?: "Let’s find your watch.", if (compact) 17f else 20f, bold = true), box, if (compact) 14 else 0)
|
||||||
|
add(text(connectionText, 13f, colors.secondary), box, 8)
|
||||||
|
add(action(if (finding) "Looking for Pakkit…" else if (capabilities != null) "Refresh connection" else "Connect a watch", false) { discover() }.apply { isEnabled = !finding }, box, 16)
|
||||||
|
add(box, top = 20)
|
||||||
|
capabilities?.let { cap ->
|
||||||
|
if (!supported(cap)) notice("A different route", "This watch’s software does not expose the approval controls Pakkit needs. Install compatible apps through Google Play on the watch.", true)
|
||||||
|
else if (!cap.getBoolean("allowed")) notice("One permission, on your watch", "Open Pakkit on your watch and tap “Allow installs”. Then refresh the connection here.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun notice(title: String, description: String, warning: Boolean = false) {
|
||||||
|
val box = card(if (warning) colors.errorSoft else colors.accentSoft)
|
||||||
|
val tint = if (warning) colors.error else colors.accent
|
||||||
|
add(text(title, 16f, tint, true), box)
|
||||||
|
add(text(description, 14f, if (warning) colors.error else colors.text), box, 8)
|
||||||
|
add(box, top = 16)
|
||||||
|
}
|
||||||
|
private fun fileCard(job: JSONObject) {
|
||||||
|
val apk = Apk.from(job.getJSONObject("apk"))
|
||||||
|
val state = job.optString("state", "draft")
|
||||||
|
val box = card()
|
||||||
|
val success = state == "installed"
|
||||||
|
val failed = state == "failed"
|
||||||
|
val title = when (state) {
|
||||||
|
"draft" -> "Packed and ready"
|
||||||
|
"sending" -> "Preparing your parcel"
|
||||||
|
"syncing" -> "On its way"
|
||||||
|
"receiving" -> "A final check, on your watch"
|
||||||
|
"ready" -> "Ready on your wrist"
|
||||||
|
"confirm" -> "Over to you"
|
||||||
|
"installing" -> "With the system installer"
|
||||||
|
"installed" -> "Right where it belongs."
|
||||||
|
"declined" -> "Dismissed on your watch"
|
||||||
|
else -> "A small detour"
|
||||||
|
}
|
||||||
|
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
row.addView(icon(if (success) Glyph.CHECK else if (failed) Glyph.ALERT else Glyph.FILE, if (success) colors.mint else if (failed) colors.error else colors.accent, 28))
|
||||||
|
row.addView(Design.badge(this, if (success) "Installed" else if (failed) "Needs attention" else "Your APK", positive = success, warning = failed), LinearLayout.LayoutParams(-2, -2).apply { marginStart = dp(12) })
|
||||||
|
add(row, box)
|
||||||
|
add(text(title, 23f, bold = true), box, 18)
|
||||||
|
add(text(apk.label, 19f, bold = true), box, 18)
|
||||||
|
add(text("${apk.version} · ${"%.1f".format(apk.bytes / 1048576.0)} MB", 13f, colors.secondary), box, 6)
|
||||||
|
add(text(apk.packageName, 12f, colors.secondary), box, 6)
|
||||||
|
if (state == "draft") {
|
||||||
|
add(text(if (apk.wear) "Watch support declared. Hardware is checked before sending." else "Watch support is unverified. This app may not fit or work on a round screen.", 13f, if (apk.wear) colors.secondary else colors.error), box, 16)
|
||||||
|
add(text("Package details are readable. This is not a malware scan or a guarantee of compatibility.", 12f, colors.secondary), box, 10)
|
||||||
|
add(action("Send to my watch") { send(job) }.apply { isEnabled = capabilities?.let { supported(it) && it.getBoolean("allowed") } == true }, box, 20)
|
||||||
|
add(action("Choose another file", false) { discard(job); pick() }, box, 8)
|
||||||
|
} else {
|
||||||
|
add(text(job.optString("detail"), 14f, colors.secondary), box, 16)
|
||||||
|
transferSteps(state, box)
|
||||||
|
if (state in setOf("installed", "failed", "declined")) add(action("Choose another APK") { discard(job); pick() }, box, 20)
|
||||||
|
else {
|
||||||
|
if (state in setOf("sending", "syncing", "receiving")) add(Design.progress(this), box, 14)
|
||||||
|
add(text("Open Pakkit on your watch to continue. Brief disconnections are handled by syncing. Files expire 24 hours after selection.", 12f, colors.secondary), box, 14)
|
||||||
|
add(action("Transfer help", false) { page = 2; render(animate = true) }, box, 12)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
add(box, top = 22)
|
||||||
|
}
|
||||||
|
private fun transferSteps(state: String, parent: LinearLayout) {
|
||||||
|
val current = when (state) { "sending", "syncing", "receiving" -> 1; "ready", "confirm", "installing" -> 2; "installed" -> 3; else -> 0 }
|
||||||
|
val row = LinearLayout(this)
|
||||||
|
listOf("Choose", "Send", "Approve", "Wear").forEachIndexed { index, label ->
|
||||||
|
row.addView(Design.column(this).apply {
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
if (index < current) addView(icon(Glyph.CHECK, colors.accent, 18))
|
||||||
|
else addView(text("0${index + 1}", 13f, if (index == current) colors.accent else colors.secondary, true).apply { gravity = Gravity.CENTER })
|
||||||
|
addView(text(label, 11f, if (index <= current) colors.text else colors.secondary).apply { gravity = Gravity.CENTER; setPadding(0, dp(6), 0, 0) })
|
||||||
|
}, LinearLayout.LayoutParams(0, -2, 1f))
|
||||||
|
}
|
||||||
|
add(row, parent, 22)
|
||||||
|
}
|
||||||
|
private fun activityPage() {
|
||||||
|
heading("Little journeys.", "Your last 20 transfers, kept on this phone.")
|
||||||
|
val entries = JSONArray(store.prefs.getString("history", "[]"))
|
||||||
|
if (entries.length() == 0) {
|
||||||
|
add(ParcelSceneView(this).apply { layoutParams = LinearLayout.LayoutParams(-1, dp(170)) }, top = 24)
|
||||||
|
add(text("The first one is yours.", 24f, bold = true).apply { gravity = Gravity.CENTER }, top = 18)
|
||||||
|
add(text("Send an APK and follow its journey here, from your pocket to your wrist.", 15f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 12)
|
||||||
|
add(action("Choose your first APK") { page = 0; render(animate = true); pick() }, top = 24)
|
||||||
|
} else {
|
||||||
|
for (i in 0 until entries.length()) {
|
||||||
|
val entry = entries.getJSONObject(i)
|
||||||
|
val box = card()
|
||||||
|
val state = entry.optString("state")
|
||||||
|
add(Design.badge(this, when (state) { "installed" -> "Installed"; "failed" -> "Needs attention"; "declined" -> "Dismissed"; else -> "In progress" }, state == "installed", state == "failed"), box)
|
||||||
|
add(text(entry.getString("label"), 20f, bold = true), box, 14)
|
||||||
|
add(text(entry.getString("detail"), 14f, colors.secondary), box, 8)
|
||||||
|
add(text(android.text.format.DateFormat.format("MMM d · HH:mm", entry.getLong("time")).toString(), 12f, colors.secondary), box, 12)
|
||||||
|
add(box, top = 16)
|
||||||
|
}
|
||||||
|
add(action("Clear activity", false) { store.prefs.edit().remove("history").apply() }, top = 20)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun guidePage() {
|
||||||
|
heading("Good to know.", "A little bridge. You’re always in control.")
|
||||||
|
val sections = listOf(
|
||||||
|
"Make the introduction" to "Pair your watch with its normal companion app, then install Pakkit from Google Play on both devices. Open Pakkit on your watch and allow installs if its software offers that setting.",
|
||||||
|
"Pack it. Send it." to "Choose a complete APK from a source you trust. Pakkit checks readable signing metadata, file size, Android version and processor support. Split APKs, APKM, XAPK and app bundles aren’t supported.",
|
||||||
|
"Wear it. With your approval." to "When the APK is ready, review it in Pakkit on your watch and tap Install. Follow the system’s approval screen. Receiving a file never installs it automatically.",
|
||||||
|
"Every watch is different" to "Some watch firmware does not offer external installation controls. Pakkit cannot enable them. Google Play on the watch is the supported alternative. Phone apps may also be difficult to use on a round screen.",
|
||||||
|
"Give your parcel a moment" to "Keep the devices charged and connected. Google Play services manages syncing; a byte percentage isn’t available. Files expire 24 hours after selection. If a connection is lost, reopen both apps and refresh.",
|
||||||
|
"Your files, thoughtfully handled" to "No Pakkit account, ads or analytics. APKs are stored privately and shared using Google Play services. The Data Layer may route encrypted data through Google servers. Temporary APKs are removed after completion or expiry. You can clear activity here.",
|
||||||
|
"Trust comes first" to "Pakkit does not certify an APK’s safety. System protections, developer verification, device policy or Play Protect may block installation. Pakkit respects those decisions and does not offer debugging or security bypasses."
|
||||||
|
)
|
||||||
|
sections.forEachIndexed { index, (title, body) ->
|
||||||
|
val box = card()
|
||||||
|
add(text("0${index + 1}", 12f, colors.accent, true), box)
|
||||||
|
add(text(title, 19f, bold = true), box, 12)
|
||||||
|
add(text(body, 14f, colors.secondary), box, 10)
|
||||||
|
add(box, top = 16)
|
||||||
|
}
|
||||||
|
add(action("Open Google Play", false) { openPlay() }, top = 20)
|
||||||
|
add(text(getString(meghdad.pakkit.core.R.string.brand_secondary_tagline), 14f, colors.accent, true).apply { gravity = Gravity.CENTER }, top = 28)
|
||||||
|
add(text("Pakkit 0.1 · Device validation build", 12f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 10)
|
||||||
|
}
|
||||||
|
private fun supported(cap: DataMap) = cap.getBoolean("installer") && (cap.getBoolean("settings") || cap.getBoolean("allowed"))
|
||||||
|
private fun discover() {
|
||||||
|
if(finding) return
|
||||||
|
finding=true; capabilities=null; connectionText="Looking for Pakkit on nearby paired watches."; render()
|
||||||
|
Wearable.getCapabilityClient(this).getCapability(Link.CAPABILITY,CapabilityClient.FILTER_REACHABLE)
|
||||||
|
.addOnSuccessListener { info ->
|
||||||
|
if (isDestroyed || isFinishing) return@addOnSuccessListener
|
||||||
|
val nodes=info.nodes.sortedBy { it.displayName }
|
||||||
|
if(nodes.isEmpty()) { finding=false; watch=null; connectionText="No watch found. Install and open Pakkit on your paired watch, then try again."; render() }
|
||||||
|
else if(nodes.size==1) probe(nodes.first())
|
||||||
|
else AlertDialog.Builder(this).setTitle("Choose your watch").setItems(nodes.map { it.displayName }.toTypedArray()) { _,i -> probe(nodes[i]) }
|
||||||
|
.setOnCancelListener { finding=false; render() }.show()
|
||||||
|
}.addOnFailureListener { finding=false; connectionText="Couldn’t reach your watch. Check Google Play services and the companion connection."; render() }
|
||||||
|
}
|
||||||
|
private fun probe(node: Node) {
|
||||||
|
watch=node; nonce=UUID.randomUUID().toString(); val request=nonce
|
||||||
|
Wearable.getMessageClient(this).sendMessage(node.id,"/pakkit/probe",nonce.toByteArray()).addOnFailureListener {
|
||||||
|
if(nonce==request) { finding=false; connectionText="Watch connection interrupted. Reopen Pakkit on your watch and retry."; render() }
|
||||||
|
}
|
||||||
|
main.postDelayed({ if(nonce==request && finding) { finding=false; connectionText="Your watch hasn’t replied. Open Pakkit there, then try again."; render() } },15000)
|
||||||
|
}
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun pick() {
|
||||||
|
message=null
|
||||||
|
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type="application/vnd.android.package-archive"; addCategory(Intent.CATEGORY_OPENABLE) },41)
|
||||||
|
}
|
||||||
|
@Deprecated("Platform result bridge")
|
||||||
|
override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
|
||||||
|
super.onActivityResult(requestCode,resultCode,data)
|
||||||
|
if(requestCode!=41 || resultCode!=RESULT_OK) return
|
||||||
|
val uri=data?.data ?: return
|
||||||
|
importing=true; render()
|
||||||
|
io.execute {
|
||||||
|
val id=UUID.randomUUID().toString(); val part=File(store.directory,"$id.part")
|
||||||
|
try {
|
||||||
|
require(Packages.free(this)>TransferRules.MAX_BYTES+20*1024*1024) { "Free some storage on your phone first." }
|
||||||
|
val hash=contentResolver.openInputStream(uri)?.use { input -> part.outputStream().use { TransferRules.copyBounded(input,it).second } } ?: error("Could not read this file.")
|
||||||
|
val apk=Packages.inspect(this,part,hash)
|
||||||
|
require(part.renameTo(store.file(id))) { "Could not save this file." }
|
||||||
|
store.write("outgoing",JSONObject().put("id",id).put("apk",apk.json()).put("created",System.currentTimeMillis()).put("state","draft"))
|
||||||
|
WorkManager.getInstance(this).enqueueUniqueWork("expire-$id",ExistingWorkPolicy.KEEP,
|
||||||
|
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay(24,TimeUnit.HOURS).setInputData(workDataOf("id" to id)).build())
|
||||||
|
} catch(e: Exception) { part.delete(); main.post { message=e.message ?: "Couldn’t read this APK." } }
|
||||||
|
main.post { importing=false; if(!isDestroyed) render() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun send(job: JSONObject) {
|
||||||
|
val cap=capabilities ?: return
|
||||||
|
val node=watch ?: return
|
||||||
|
try {
|
||||||
|
require(android.os.SystemClock.elapsedRealtime()-capabilitiesReceivedAt < 120000) { "Refresh your watch connection before sending." }
|
||||||
|
require(supported(cap) && cap.getBoolean("allowed")) { "Allow installations in Pakkit on your watch first." }
|
||||||
|
val apk=Apk.from(job.getJSONObject("apk"))
|
||||||
|
Packages.checkForWatch(apk,cap.getInt("sdk"),cap.getStringArrayList("abis").orEmpty().toSet(),cap.getLong("free"))
|
||||||
|
require(TransferRules.fresh(job.optLong("created"),System.currentTimeMillis())) { "This file expired. Choose it again." }
|
||||||
|
val sendNow = {
|
||||||
|
val now=job.getLong("created")
|
||||||
|
job.put("target",node.id).put("created",now).put("state","sending").put("offer",Uri.Builder().scheme("wear").authority("*").path("/pakkit/offer/${job.getString("id")}").build().toString())
|
||||||
|
.put("detail","Preparing your file for Google Play services.")
|
||||||
|
store.write("outgoing",job)
|
||||||
|
store.history(job.getString("id"),apk.label,"sending","Preparing your file for transfer.")
|
||||||
|
WorkManager.getInstance(this).enqueueUniqueWork("send-${job.getString("id")}",ExistingWorkPolicy.KEEP,
|
||||||
|
OneTimeWorkRequestBuilder<SendWorker>().setInputData(workDataOf("id" to job.getString("id"))).build())
|
||||||
|
render()
|
||||||
|
}
|
||||||
|
AlertDialog.Builder(this).setTitle("Send ${apk.label}?")
|
||||||
|
.setMessage("Send this APK to ${node.displayName} using Google Play services. Only continue if you trust its source.${if(!apk.wear) "\n\nThis app does not declare watch support. It may not fit or work on your watch." else ""}\n\nYou’ll review and approve installation on the watch.")
|
||||||
|
.setNegativeButton("Keep here",null).setPositiveButton("Send") { _,_ -> sendNow() }.show()
|
||||||
|
} catch(e: Exception) { message=e.message; render() }
|
||||||
|
}
|
||||||
|
private fun discard(job: JSONObject) { store.file(job.getString("id")).delete(); store.clear("outgoing"); render() }
|
||||||
|
private fun openPlay() { runCatching { startActivity(Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q=Wear%20OS&c=apps"))) }.onFailure { message="Open Google Play on your watch and search for compatible apps."; render() } }
|
||||||
|
}
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path
|
|
||||||
android:fillColor="#3DDC84"
|
|
||||||
android:pathData="M0,0h108v108h-108z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M9,0L9,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,0L19,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,0L29,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,0L39,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,0L49,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,0L59,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,0L69,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,0L79,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M89,0L89,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M99,0L99,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,9L108,9"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,19L108,19"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,29L108,29"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,39L108,39"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,49L108,49"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,59L108,59"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,69L108,69"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,79L108,79"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,89L108,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,99L108,99"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,29L89,29"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,39L89,39"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,49L89,49"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,59L89,59"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,69L89,69"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,79L89,79"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,19L29,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,19L39,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,19L49,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,19L59,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,19L69,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,19L79,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:aapt="http://schemas.android.com/aapt"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
|
||||||
<aapt:attr name="android:fillColor">
|
|
||||||
<gradient
|
|
||||||
android:endX="85.84757"
|
|
||||||
android:endY="92.4963"
|
|
||||||
android:startX="42.9492"
|
|
||||||
android:startY="49.59793"
|
|
||||||
android:type="linear">
|
|
||||||
<item
|
|
||||||
android:color="#44000000"
|
|
||||||
android:offset="0.0" />
|
|
||||||
<item
|
|
||||||
android:color="#00000000"
|
|
||||||
android:offset="1.0" />
|
|
||||||
</gradient>
|
|
||||||
</aapt:attr>
|
|
||||||
</path>
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:fillType="nonZero"
|
|
||||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
|
||||||
android:strokeWidth="1"
|
|
||||||
android:strokeColor="#00000000" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
|
Before Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 982 B |
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
@@ -1,16 +1 @@
|
|||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
<resources><style name="Theme.Pakkit" parent="Theme.Pakkit.Dark"/></resources>
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="Theme.Pakkit" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
|
||||||
<!-- Primary brand color. -->
|
|
||||||
<item name="colorPrimary">@color/purple_200</item>
|
|
||||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
|
||||||
<item name="colorOnPrimary">@color/black</item>
|
|
||||||
<!-- Secondary brand color. -->
|
|
||||||
<item name="colorSecondary">@color/teal_200</item>
|
|
||||||
<item name="colorSecondaryVariant">@color/teal_200</item>
|
|
||||||
<item name="colorOnSecondary">@color/black</item>
|
|
||||||
<!-- Status bar color. -->
|
|
||||||
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
|
|
||||||
<!-- Customize your theme here. -->
|
|
||||||
</style>
|
|
||||||
</resources>
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<color name="purple_200">#FFBB86FC</color>
|
|
||||||
<color name="purple_500">#FF6200EE</color>
|
|
||||||
<color name="purple_700">#FF3700B3</color>
|
|
||||||
<color name="teal_200">#FF03DAC5</color>
|
|
||||||
<color name="teal_700">#FF018786</color>
|
|
||||||
<color name="black">#FF000000</color>
|
|
||||||
<color name="white">#FFFFFFFF</color>
|
|
||||||
</resources>
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<resources><item name="page_heading" type="id"/><item name="nav_transfer" type="id"/><item name="nav_activity" type="id"/><item name="nav_guide" type="id"/><item name="appearance" type="id"/></resources>
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
<resources>
|
|
||||||
<string name="app_name">pakkit</string>
|
|
||||||
</resources>
|
|
||||||
@@ -1,16 +1,9 @@
|
|||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
<resources>
|
||||||
<!-- Base application theme. -->
|
<style name="Theme.Pakkit" parent="Theme.Pakkit.Light"/>
|
||||||
<style name="Theme.Pakkit" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
<style name="Theme.Pakkit.Light" parent="android:style/Theme.Material.Light.NoActionBar">
|
||||||
<!-- Primary brand color. -->
|
<item name="android:fontFamily">sans</item><item name="android:windowLightStatusBar">true</item><item name="android:windowLightNavigationBar">true</item><item name="android:colorAccent">#6140D8</item><item name="android:windowBackground">#F6F5FC</item><item name="android:windowActionModeOverlay">true</item><item name="android:windowSplashScreenBackground">#090B17</item><item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
|
||||||
<item name="colorPrimary">@color/purple_500</item>
|
</style>
|
||||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
<style name="Theme.Pakkit.Dark" parent="android:style/Theme.Material.NoActionBar">
|
||||||
<item name="colorOnPrimary">@color/white</item>
|
<item name="android:fontFamily">sans</item><item name="android:windowLightStatusBar">false</item><item name="android:windowLightNavigationBar">false</item><item name="android:colorAccent">#BAA6FF</item><item name="android:windowBackground">#090B17</item><item name="android:windowActionModeOverlay">true</item><item name="android:windowSplashScreenBackground">#090B17</item><item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
|
||||||
<!-- Secondary brand color. -->
|
|
||||||
<item name="colorSecondary">@color/teal_200</item>
|
|
||||||
<item name="colorSecondaryVariant">@color/teal_700</item>
|
|
||||||
<item name="colorOnSecondary">@color/black</item>
|
|
||||||
<!-- Status bar color. -->
|
|
||||||
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
|
|
||||||
<!-- Customize your theme here. -->
|
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?><!--
|
|
||||||
Sample backup rules file; uncomment and customize as necessary.
|
|
||||||
See https://developer.android.com/guide/topics/data/autobackup
|
|
||||||
for details.
|
|
||||||
Note: This file is ignored for devices older than API 31
|
|
||||||
See https://developer.android.com/about/versions/12/backup-restore
|
|
||||||
-->
|
|
||||||
<full-backup-content>
|
|
||||||
<!--
|
|
||||||
<include domain="sharedpref" path="."/>
|
|
||||||
<exclude domain="sharedpref" path="device.xml"/>
|
|
||||||
-->
|
|
||||||
</full-backup-content>
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?><!--
|
|
||||||
Sample data extraction rules file; uncomment and customize as necessary.
|
|
||||||
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
|
||||||
for details.
|
|
||||||
-->
|
|
||||||
<data-extraction-rules>
|
|
||||||
<cloud-backup>
|
|
||||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
|
||||||
<include .../>
|
|
||||||
<exclude .../>
|
|
||||||
-->
|
|
||||||
</cloud-backup>
|
|
||||||
<!--
|
|
||||||
<device-transfer>
|
|
||||||
<include .../>
|
|
||||||
<exclude .../>
|
|
||||||
</device-transfer>
|
|
||||||
-->
|
|
||||||
</data-extraction-rules>
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Pakkit — Pocket to Wrist.
|
||||||
|
|
||||||
|
The supplied `brand-concept.png` is a creative reference, not a screen specification or feature promise. The product uses the user's official taglines, **Pocket to Wrist.** and **Pack it. Send it. Wear it.** Copy such as “Apps, on your wrist” or percentages in the reference does not override those decisions or actual platform capabilities.
|
||||||
|
|
||||||
|
## Identity
|
||||||
|
|
||||||
|
An open parcel and a floating app tile form Pakkit's mark. Cyan and mint illuminate one face; electric violet lights the other. The detached tile suggests a small app making a deliberate journey. The same silhouette appears in the adaptive launcher, monochrome icon, splash, phone illustration and watch header. The work is implemented as vector paths, native shaders and reusable Android components; the reference board is never rendered as application UI.
|
||||||
|
|
||||||
|
## Color and typography
|
||||||
|
|
||||||
|
`BrandPalette` in `shared/.../Design.kt` provides semantic tokens for light and dark canvas, cards, body text, secondary text, borders, actions, mint statuses and errors. Principal colors: midnight `#090B17`, action purple `#7150EF`, mint `#68E9CF`, cyan `#37D7F2`. Action buttons use a readable violet gradient. Text colors are adapted rather than copying a bright accent onto every surface.
|
||||||
|
|
||||||
|
Lavender light uses subtly tinted backgrounds and white cards. Midnight dark uses restrained illumination, deep surfaces and soft lavender text. The phone follows the device theme by default; its appearance control offers explicit light and dark preferences and preserves the choice. The watch stays midnight in either system theme to limit lit pixels on OLED displays.
|
||||||
|
|
||||||
|
Typography uses Android's native sans family with explicit 400/600/650 weights, slightly tightened large headings and scalable SP sizes. Copy remains real text, not outlined lettering. The scale is deliberate: phone headlines 38 SP, section titles 19–23 SP, body 14–16 SP; watch titles 21–25 SP and supporting text 12–14 SP. Small metadata remains scrollable. There are no fixed-height text containers.
|
||||||
|
|
||||||
|
## Components and interaction
|
||||||
|
|
||||||
|
- `ParcelSceneView`: prebuilt parcel geometry, static radial lighting, a floating app tile and a finite 1.1-second entrance. No bitmap assets, blur layers or continuous particle simulation.
|
||||||
|
- `GlyphDrawable`: a consistent stroke family for navigation, watch, file, trust and status icons. Icons supplement text; decorative art is excluded from accessibility focus.
|
||||||
|
- Native buttons: gradient primary, tonal secondary, ripple feedback, meaningful disabled colors and platform confirmation haptics. Minimum height 52 DP on phone and 48 DP on watch.
|
||||||
|
- Phone cards: 26-DP corners, 20-DP padding, quiet borders and consistent spacing. Content is centered and bounded on wide windows. Navigation remains semantic and selected states are exposed to accessibility.
|
||||||
|
- `RoundScrollView`: symmetric proportional watch margins, generous end padding, rotary scrolling and an on-demand scroll indicator following the bezel. TextClock updates with the platform; no custom clock loop.
|
||||||
|
- Scroll position is retained during ordinary status refreshes. New transfer stages on the watch return to the heading so the current decision remains discoverable.
|
||||||
|
- Motion respects system animation settings and battery saver. Decorative watch art is static. Phone transitions are short, finite and cancelled when detached or the window loses focus. Receiving progress remains indeterminate because the Data Layer does not supply a trustworthy byte percentage.
|
||||||
|
|
||||||
|
## Product truth
|
||||||
|
|
||||||
|
Brand language must never imply a compatibility guarantee or a security bypass. An APK is “Installed” only after Android reports success. Source approval, explicit watch review, system consent, unsupported firmware handling, signature/integrity checks and Google Play policy boundaries remain in force. The reference's installed-app catalog and imagined battery percentages are not implemented features.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Automated contrast checks cover normal body and secondary copy on all base surfaces, status badges and both action-gradient endpoints at 4.5:1 or better. Device tests exercise the actual appearance chooser and theme persistence, navigation restoration and the unchanged installation consent boundary. Full TalkBack and physical-watch accessibility validation remain release gates.
|
||||||
|
|
||||||
|
Design references: [Wear accessibility](https://developer.android.com/training/wearables/accessibility), [round screen guidance](https://developer.android.com/design/ui/wear/guides/get-started/design-for-wearables), [Wear app quality](https://developer.android.com/docs/quality-guidelines/wear-app-quality), and [power guidance](https://developer.android.com/training/wearables/apps/power). These inform the implementation; their requirements are not a substitute for Play review or physical-device testing.
|
||||||
|
After Width: | Height: | Size: 1.7 MiB |
@@ -0,0 +1,36 @@
|
|||||||
|
# Architecture and operating boundaries
|
||||||
|
|
||||||
|
## Protocol v1
|
||||||
|
|
||||||
|
Google Play services enforces matching app ID and certificate. The watch advertises `pakkit_watch_v1`. A reachable node is queried using `/pakkit/probe` with a random nonce. The watch publishes `/pakkit/cap/{node}` with that nonce, API, ABIs, available bytes and installation controls. The phone accepts only the selected node's fresh response. Capabilities expire for send purposes after two minutes.
|
||||||
|
|
||||||
|
A selected document is copied from its content URI into app-private storage. The temporary filename is a generated UUID; URI-supplied paths and display names never determine a filesystem path. SHA-256 is computed while enforcing the size cap. The original document is not modified. Persisted URI permission and broad storage access are unnecessary.
|
||||||
|
|
||||||
|
`SendWorker` publishes `/pakkit/offer/{UUID}`, containing target node, creation time, APK metadata, digest and an Asset. This publication means queued for sync, not delivered. Google Play services owns transport and retransmission; it can route through Google infrastructure. There is no percentage or speed estimate. There is no automatic installation.
|
||||||
|
|
||||||
|
`LinkService` schedules unique `ReceiveWorker` work. The worker checks target, identifier and age; rejects a busy watch; bounds the received bytes; verifies digest and parsed package information; and renames the complete private file. Readiness is sent only after verification. The watch keeps a small recent-ID replay guard. Terminal and ready states are idempotent for a given active transfer. Assets are deleted after verification or a permanent failure, rather than retained as storage.
|
||||||
|
|
||||||
|
The watch publishes `/pakkit/status/{UUID}` with target phone and an explicit state. The phone only accepts the current transfer ID from its selected destination node and monotonically increasing status revisions. A status publication worker retries temporary API errors. Phone and watch hold one current job each, plus phone-local history capped at 20 entries. SharedPreferences commits are used for the small durable records; files are not placed in preferences or WorkManager input. WorkManager persists bounded jobs and handles process restart.
|
||||||
|
|
||||||
|
## Installation boundary
|
||||||
|
|
||||||
|
Only a foreground button in the watch app creates a PackageInstaller session. The file's age, digest, metadata and hardware compatibility are checked again. The session requests `USER_ACTION_REQUIRED`. The status receiver is not exported. Its explicit mutable PendingIntent is scoped to the session and transfer ID; mutable extras are required for Android's installer result.
|
||||||
|
|
||||||
|
Pending approval is presented inside Pakkit, with an optional notification containing the system confirmation Intent. No background activity launch is attempted by the receiver. Notification permission is optional and requested only from an explanatory watch button. If approval state is interrupted and cannot be recovered in memory or from its notification, the user can explicitly retry, abandoning the previous session first. A transfer can only be reported as installed after `STATUS_SUCCESS`.
|
||||||
|
|
||||||
|
The system owns final package validation, update signatures, policy checks, verification and approval UI. No install result is inferred from a file transfer, countdown or launch attempt. Installation failures are mapped to understandable messages without logging APK contents or private paths.
|
||||||
|
|
||||||
|
## Storage and battery
|
||||||
|
|
||||||
|
- 50 MiB maximum package, 64 KiB buffers, no entire APK byte arrays, no ZIP extraction.
|
||||||
|
- Approximate watch space budget: three APK sizes plus 20 MiB. This is a preflight, not a reservation; the system may still report insufficient storage.
|
||||||
|
- TTL: 24 hours from file selection. Workers remove retained offers/files when scheduled; background scheduling can be deferred by the OS. Stale files are additionally cleaned on app startup and after receive.
|
||||||
|
- One outstanding offer per phone, one reviewable file per watch; no parallel sync queue. Keep the watch app open for the most predictable receiving experience.
|
||||||
|
- No always-on service, app-managed wake lock, polling scan loop, custom networking, analytics or account system.
|
||||||
|
- The parcel artwork uses a short finite entrance, respects system animation and battery saver settings, and stops when its window is hidden or detached. Decorative watch artwork remains static. See the semantic palettes and components in Design.kt and the brand guide in design/README.md.
|
||||||
|
|
||||||
|
## Known engineering limits before production
|
||||||
|
|
||||||
|
Native Android views keep the runtime and dependencies small. Touch controls and text remain semantic views; the parcel art is decorative. The first locale is English; RTL mirroring uses platform layouts but localized copy and real RTL QA remain release work. Ordinary refreshes preserve scroll position. The watch returns to the heading when its transfer stage changes so the next decision is visible.
|
||||||
|
|
||||||
|
Single-file inspection does not fully classify all unusual/vendor split manifests, malicious parser edge cases or expanded installed size. Android remains the security authority. Asset transfer latency, cloud behavior, retry timing, UI interruption and consent recovery require paired-device testing. The initial implementation intentionally excludes automatic recovery that might open an installer without another user action. Cross-device cancellation of an already queued offer is deferred; current jobs can be dismissed on the watch after receipt or expire.
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Feasibility decision
|
||||||
|
|
||||||
|
Research date: October 15, 2026. Reference hardware: Samsung Galaxy Watch 7; no physical hardware has been verified in this workspace.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Build a **capability-gated companion**, rather than promise a universal installer. Official APIs support file transfer and user-initiated package installation. Their presence in Android does not prove that a particular Wear OS firmware provides usable unknown-source settings and installation confirmation. Pakkit never changes security settings itself.
|
||||||
|
|
||||||
|
The desired no-debugging path is conditional: paired Android phone and watch → install Pakkit through Play on both → approve Pakkit as an install source on supported watch firmware → choose a complete compatible APK → send → review on watch → explicitly request installation → approve the system screen. Source approval is an unavoidable extra setup step where Android requires it.
|
||||||
|
|
||||||
|
## Confirmed platform capabilities
|
||||||
|
|
||||||
|
1. The [Wearable Data Layer overview](https://developer.android.com/training/wearables/data/overview) documents app-private phone/watch communication and requires matching package names and signing certificates. The transport can use Bluetooth or encrypted cloud routing. Pakkit uses it without its own network backend, direct sockets, Bluetooth discovery permissions or accounts. [Asset synchronization](https://developer.android.com/training/wearables/data/sync) allows queued transfer when disconnected; it is not an application database. Pakkit keeps its own state and private files. Asset APIs do not provide Pakkit with an accurate network byte-progress signal.
|
||||||
|
|
||||||
|
2. [PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) supports sessions and reports success, failure or pending user action. Pakkit explicitly requires user action and handles the returned confirmation intent. This general Android capability is not proof of a usable Wear installation UI on every OEM firmware.
|
||||||
|
|
||||||
|
3. [PackageManager.canRequestPackageInstalls](https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()) reports whether the caller is trusted as an installation source. Pakkit checks this on the watch. If allowed-source settings are unavailable and source approval is absent, Pakkit blocks sending. Resolver availability is a conservative preflight, not a compatibility certification.
|
||||||
|
|
||||||
|
## Google Play eligibility is conditional
|
||||||
|
|
||||||
|
[Play's sensitive permissions policy](https://support.google.com/googleplay/android-developer/answer/16558241?hl=en) includes phone-to-wearable companion synchronization among permitted REQUEST_INSTALL_PACKAGES purposes. This makes the proposed purpose potentially eligible; it does **not** guarantee permission approval or listing acceptance. Core functionality must be accurately described, declared and reviewed. Pakkit requests this permission only on the watch, offers no self-update mechanism, bundles no third-party APK and never starts an installation just because a transfer arrived. A reviewer must assess the final implementation and listing.
|
||||||
|
|
||||||
|
[Wear app packaging guidance](https://developer.android.com/training/wearables/packaging) requires a separate watch artifact, watch feature declaration and form-factor versioning. Pakkit's watch app declares itself non-standalone because selecting and sending requires the phone. Both artifacts must use the same production signing identity for the Data Layer.
|
||||||
|
|
||||||
|
[Current target API policy](https://support.google.com/googleplay/android-developer/answer/11926878) requires API 36 for new phone apps and API 35 for Wear OS as of August 31, 2026. Both modules target 36. Recheck Play Console requirements at submission time.
|
||||||
|
|
||||||
|
## Developer verification changes the promise
|
||||||
|
|
||||||
|
[Android's developer-verification guidance](https://developer.android.com/developer-verification/guides) describes regional enforcement beginning September 30, 2026. Its [FAQ](https://developer.android.com/developer-verification/guides/faq) explains an advanced flow for unverified developers that includes developer mode and a protective delay. Pakkit does not implement or recommend this flow: it conflicts with the requested no-developer-options experience. Applicability to a particular Wear firmware must be tested; do not infer a verified exemption or rollout from the generic Android guidance. Respect any system block and direct users to a supported distribution of the app.
|
||||||
|
|
||||||
|
## Limits and assumptions
|
||||||
|
|
||||||
|
- **Unverified:** Galaxy Watch 7 firmware versions, region-specific security settings, actual approval activity behavior and developer-verifier enforcement. Run the physical-device matrix before advertising support.
|
||||||
|
- **Supported intentionally:** complete single APKs up to 50 MiB. No APKM/XAPK/APKS/AAB or split installation support.
|
||||||
|
- **Preflight only:** SDK minimum, native-library ABI, approximate space, readable signing information and integrity. These do not prove safety, runtime usability, feature availability, signature validity under all platform rules, successful update or a wearable layout. The OS makes the final install decision.
|
||||||
|
- **No bypass:** if watch installation is unavailable, Google Play on that watch is the fallback. Pakkit does not silently enable debugging, root, hidden services or elevated privileges.
|
||||||
|
- **Release gate:** if physical tests show the reference device cannot complete the public consent path, do not publish the installer listing as broadly compatible. Narrow support to tested firmware or reconsider the product's scope.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Pakkit privacy text — draft for developer review
|
||||||
|
|
||||||
|
Pakkit helps you transfer an APK you select on your Android phone to your paired Wear OS watch and request its installation. You decide which file to send and approve installation on the watch.
|
||||||
|
|
||||||
|
Pakkit stores the selected APK, package details, file-integrity digest and transfer state in its private app storage. The phone keeps the latest state of up to 20 transfers. You can clear this activity within Pakkit. Temporary package files are removed after completion or expiry (24 hours from selection); cleanup may be delayed by Android background scheduling. Removing Pakkit removes its local app data.
|
||||||
|
|
||||||
|
Transfers use the Wearable Data Layer provided by Google Play services. Depending on device connectivity, data may travel over Bluetooth or encrypted cloud transport through Google infrastructure. Pakkit does not operate its own APK server, require an account, contain advertising or include analytics SDKs.
|
||||||
|
|
||||||
|
The watch requests permission to ask Android to install a package. It does not silently install applications. Optional watch notifications help you return to a pending system approval screen. You can decline notifications and continue in the app.
|
||||||
|
|
||||||
|
Only send software from a source you trust. Pakkit's file checks are not a malware scan or a guarantee of safety or watch compatibility. Android and the watch's security policy control whether installation can proceed.
|
||||||
|
|
||||||
|
Before publication, the developer must add its legal identity, effective date, support contact and any required jurisdiction-specific terms to a publicly accessible policy. This repository draft is not itself a published policy or completed Play Data safety declaration.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Google Play release preparation
|
||||||
|
|
||||||
|
This is a release checklist, not an assertion that the app is already approved or ready for a public production rollout.
|
||||||
|
|
||||||
|
## Technical artifacts
|
||||||
|
|
||||||
|
- Phone and watch use application ID `meghdad.pakkit`; namespaces differ by module.
|
||||||
|
- Phone version code: 100001; watch: 100002. Increment monotonically and keep codes unique across form factors.
|
||||||
|
- Compile SDK 36.1; min SDK 31; target SDK 36. Confirm supported-device filtering in Play Console.
|
||||||
|
- Separate watch artifact declares required `android.hardware.type.watch` and `standalone=false`.
|
||||||
|
- Release minification and resource-safe platform UI. Worker constructors are kept for background reconstruction.
|
||||||
|
- Use the **same app-signing certificate** across phone and watch. Different debug/release certificates cannot communicate through the Data Layer. Play App Signing key upgrades must be evaluated on both devices.
|
||||||
|
- Optional release signing environment: `PAKKIT_KEYSTORE`, `PAKKIT_KEYSTORE_PASSWORD`, `PAKKIT_KEY_ALIAS`, `PAKKIT_KEY_PASSWORD`. Keep the keystore outside the repository. No secret defaults or debug signing for release. Without a complete set of variables, output is unsigned and must be signed through the release pipeline.
|
||||||
|
- Build with `./gradlew :app:bundleRelease :wear:bundleRelease`, inspect merged manifests and upload each artifact to the proper form factor/test track. Check version code handling in Play Console before promoting.
|
||||||
|
|
||||||
|
## Permission declaration
|
||||||
|
|
||||||
|
`REQUEST_INSTALL_PACKAGES` exists only in the watch app. Justification for review: the core function transfers a user-selected APK from the paired phone to the user's watch and requests installation after the user explicitly reviews it on that watch. Submit the permissions declaration and an accurate screencast showing selection, transfer, source approval, app review, system approval, cancellation and unsupported-device handling.
|
||||||
|
|
||||||
|
Explain in the listing that firmware and package restrictions apply. Do not advertise one-tap installation, compatibility with all Wear OS devices, malware certification, silent installation or guaranteed approval. No packaged third-party APK, in-app self-update, package catalog or download service is included.
|
||||||
|
|
||||||
|
`POST_NOTIFICATIONS` is optional and watch-only, used for pending installer consent. Declining it leaves in-app consent usable. WorkManager contributes its standard boot-rescheduling/network-state/wake permissions through manifest merging; its unused foreground service and permission are explicitly removed. Review the final manifest rather than just source manifests. No broad storage, package visibility, location or Bluetooth runtime permissions are requested.
|
||||||
|
|
||||||
|
## Listing and disclosures
|
||||||
|
|
||||||
|
1. Finalize legal developer identity, support email and public privacy-policy URL. No invented identity or placeholder contact should be published.
|
||||||
|
2. Publish privacy text based on [PRIVACY.md](PRIVACY.md); confirm SDK behavior and the final Data safety answers. Google Play services may route encrypted APK data through Google's infrastructure. “No Pakkit server” does not mean all transport is local.
|
||||||
|
3. Upload genuine phone and round-watch screenshots, adaptive launcher assets and required store artwork. The same premium identity should appear in both listings.
|
||||||
|
4. State Wear OS support and the companion requirement clearly. Reference-device claims require recorded results for the specific model and firmware.
|
||||||
|
5. Complete content rating, target audience, ads declaration (none), Data safety, external-package permission declaration and Wear OS quality review.
|
||||||
|
6. Run internal/closed testing, pre-launch reports and physical-device compatibility matrix. Check current target API and developer-verification requirements again.
|
||||||
|
7. Promote only after every blocker in VALIDATION.md is resolved and the permission declaration is accepted. Google Play approval cannot be guaranteed.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Validation record
|
||||||
|
|
||||||
|
Date: October 15, 2026. This record separates what ran from what still needs paired physical devices and Play review.
|
||||||
|
|
||||||
|
## Brand integration update — October 15, 2026
|
||||||
|
|
||||||
|
The official Pakkit identity is now implemented in both consumer apps. See [the brand guide](../design/README.md) and [current previews](screenshots/brand/). Earlier screenshots outside that subfolder document the previous visual direction. Brand test results are saved in [validation/brand](validation/brand/).
|
||||||
|
|
||||||
|
- Custom open-parcel mark, adaptive/monochrome launcher assets, unified midnight splash and branded approval notification.
|
||||||
|
- Lavender light and midnight dark phone themes with a native custom appearance dialog, persisted selection and actual chooser/recreation testing.
|
||||||
|
- New phone navigation, connection illustration, file review, truthful transfer stages, history, empty states and guide.
|
||||||
|
- Midnight watch home, review, receiving, consent, success and error components, with proportional round-screen margins, a bezel scroll indicator and native clock.
|
||||||
|
- 9 shared JVM tests pass, including 3 new contrast checks; 5 phone instrumentation tests and 1 strengthened watch review/target-size test pass. The watch test also passed at an emulated 192-DP round size with 1.3× text, checking that install/dismiss actions remain fully reachable and at least 48 DP tall. This is an additional tested configuration, not physical-device certification.
|
||||||
|
- Both debug builds and optimized unsigned release bundles build; Android lint reports zero errors. Existing informational dependency/SDK/style warnings remain.
|
||||||
|
- A local signed QA fixture was updated through the redesigned watch review, genuine system confirmation and success screen.
|
||||||
|
- Android’s real document picker was used to select the signed local QA APK and verify the phone review screen.
|
||||||
|
- Package transfer, source approval, explicit install/session consent and policy boundaries are preserved. No capability or fake progress state was added from the creative reference.
|
||||||
|
|
||||||
|
## Completed
|
||||||
|
|
||||||
|
| Check | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| Phone debug APK | Built successfully |
|
||||||
|
| Wear OS debug APK | Built successfully |
|
||||||
|
| Optimized phone release bundle | Built successfully; unsigned without production signing variables |
|
||||||
|
| Optimized watch release bundle | Built successfully; unsigned without production signing variables |
|
||||||
|
| Android lint, phone | 0 errors; informational SDK/dependency/style warnings remain |
|
||||||
|
| Android lint, watch | 0 errors; informational SDK/style warnings remain |
|
||||||
|
| Bounded copy, known SHA-256, empty/oversize rejection, identifier safety, expiry, ABI matching | 6 JVM tests passed |
|
||||||
|
| Phone device tests: navigation and recreation, signed complete APK inspection, self-update rejection, invalid archive/path rejection | 4 passed on Pixel 10 Pro emulator, API 37 |
|
||||||
|
| Watch review test: signed fixture can be reviewed without creating any install session | 1 passed on round Wear OS 7 emulator, API 37, 454×454 |
|
||||||
|
| Visual inspection | Phone home and round watch review/controls inspected; explicit illustration height corrected |
|
||||||
|
| System source approval | Opened via public settings intent; normal system warning and approval completed on watch emulator |
|
||||||
|
| Watch PackageInstaller path | Explicit Install → pending-user-action callback → Continue → genuine system confirmation → system Install → STATUS_SUCCESS and Pakkit “Installed on your watch” → Open app launched the fixture |
|
||||||
|
| Installed-file cleanup | Confirmed the successful transfer’s private APK was deleted after installation |
|
||||||
|
| Merged release manifests | Installation and notification permissions watch-only; no broad storage/visibility/Bluetooth/location permission; unused foreground service and its permission removed |
|
||||||
|
| Release contents | QA APK absent from consumer bundles; no production signature created in this workspace |
|
||||||
|
| Git whitespace check | Passed |
|
||||||
|
|
||||||
|
The manual install used `qaFixture`, a small signed local test application. Instrumentation staged it into the watch's private review state to isolate the installation boundary. **This was not a test of Data Layer delivery.** The fixture is packaged only into Android test assets, never consumer APKs or bundles. The UI uses the exact same file revalidation, PackageInstaller session and result receiver as the consumer install flow. Developer tooling deployed Pakkit's debug builds; the fixture itself was installed through ordinary watch UI and system consent, without an ADB package install, app-op grant, root or hidden API.
|
||||||
|
|
||||||
|
Raw device test summaries: [phone](validation/phone-tests.txt), [watch](validation/watch-tests.txt). Screenshots are in [screenshots](screenshots/): phone home, watch launch/home/controls, real system approval and successful installation. Test fixture screens are labelled accordingly and are not store marketing screenshots.
|
||||||
|
|
||||||
|
## Not yet verified — release blockers
|
||||||
|
|
||||||
|
1. **Paired Data Layer integration:** the available phone/watch emulators were not configured as a paired Wear network, and discovery on the phone returned an availability/connection failure. Capability nonce exchange, real asset delivery, background receive, acknowledgement routing, delayed retries and cloud routing are implemented but remain unverified end-to-end.
|
||||||
|
2. **Galaxy Watch 7:** test exact One UI Watch / Wear OS / Android build and region. Confirm source settings, resolver behavior, consent UI, blocked cases, normal launch and developer-verification enforcement. No compatibility claim should be made before this.
|
||||||
|
3. **Interruptions and limits:** Bluetooth off/on, phone process killed, watch process killed, reboot during sync, missed status acknowledgement, system approval dismissed, user denied source/notification permission, second phone or second watch, no space, low battery and 50 MiB boundary. Test expiry while a job or install session is active. Background workers are OS-scheduled and may run later than their target time.
|
||||||
|
4. **Package coverage:** real compatible standalone APK, wrong ABI, newer minimum SDK, wrong update signature, downgrade, invalid certificate, isolated/config split, base requiring splits, corrupt resource table and restricted packages. Preflight is intentionally not a full certification or malware scan.
|
||||||
|
5. **Accessibility and layout:** TalkBack, large fonts, touch exploration, reduced animation, rotary input on hardware, 192/208/227 dp round displays and an actual tablet/phone rotation. Semantic controls and scrolling are implemented; full accessibility certification has not been performed.
|
||||||
|
6. **Performance:** battery and transfer latency on real Bluetooth/cloud links, background job timing and memory on low-RAM watches. The 50 MiB cap, bounded buffers and lack of continuous watch animation are implementation constraints, not measured performance claims.
|
||||||
|
7. **Release identity and policy:** production signing identity shared across form factors, verified dependency provenance, public privacy URL/support contact, listing assets, completed permission/Data safety declarations, internal/closed testing and Wear OS review. Google Play approval is not guaranteed.
|
||||||
|
|
||||||
|
## Intentional v1 boundaries
|
||||||
|
|
||||||
|
Single complete APK, 50 MiB maximum, one in-flight job per phone and one reviewable APK per watch, expiry 24 hours from selection, no percentage estimate, no direct third-party downloads or catalog. Waiting transfers do not currently offer a cross-device cancel action; dismiss on the watch when delivered, or let the job expire. English is the first locale. Background transfers and approval recovery require device validation before public rollout.
|
||||||
|
|
||||||
|
## Reproduce
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew :app:assembleDebug :wear:assembleDebug :shared:testDebugUnitTest :app:lintDebug :wear:lintDebug :app:bundleRelease :wear:bundleRelease
|
||||||
|
./gradlew :app:assembleDebugAndroidTest :wear:assembleDebugAndroidTest
|
||||||
|
```
|
||||||
|
|
||||||
|
In environments where Google Maven returns HTTP 404, append `-PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google` after reviewing the mirror's suitability. Run each instrumentation APK against its matching phone/watch app, rather than deploying both variants to the same device: they intentionally share an application ID. Standard Android Studio device-test tooling can run the tests. The watch test leaves its fixture ready for manual consent checks.
|
||||||
|
After Width: | Height: | Size: 279 KiB |
|
After Width: | Height: | Size: 235 KiB |
|
After Width: | Height: | Size: 414 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 295 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
meghdad.pakkit.ProductInstrumentedTest:.....
|
||||||
|
|
||||||
|
Time: 3.951
|
||||||
|
|
||||||
|
OK (5 tests)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
meghdad.pakkit.wear.WatchReviewTest:.
|
||||||
|
|
||||||
|
Time: 0.854
|
||||||
|
|
||||||
|
OK (1 test)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
meghdad.pakkit.wear.WatchReviewTest:.
|
||||||
|
|
||||||
|
Time: 0.772
|
||||||
|
|
||||||
|
OK (1 test)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
meghdad.pakkit.ProductInstrumentedTest:....
|
||||||
|
|
||||||
|
Time: 1.434
|
||||||
|
|
||||||
|
OK (4 tests)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
meghdad.pakkit.wear.WatchReviewTest:.
|
||||||
|
|
||||||
|
Time: 1.014
|
||||||
|
|
||||||
|
OK (1 test)
|
||||||
|
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[versions]
|
[versions]
|
||||||
agp = "9.2.1"
|
agp = "9.2.1"
|
||||||
coreKtx = "1.19.1"
|
coreKtx = "1.15.0"
|
||||||
junit = "4.13.2"
|
junit = "4.13.2"
|
||||||
junitVersion = "1.3.0"
|
junitVersion = "1.3.0"
|
||||||
espressoCore = "3.7.0"
|
espressoCore = "3.7.0"
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# WorkManager uses class names to recreate persistent work after process death.
|
||||||
|
-keep class * extends androidx.work.ListenableWorker { public <init>(android.content.Context, androidx.work.WorkerParameters); }
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
plugins { id("com.android.application") }
|
||||||
|
android {
|
||||||
|
namespace = "meghdad.pakkit.fixture"
|
||||||
|
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||||
|
defaultConfig { applicationId = "meghdad.pakkit.fixture"; minSdk = 31; targetSdk = 36; versionCode = 1; versionName = "1.0-test" }
|
||||||
|
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-feature android:name="android.hardware.type.watch" android:required="true"/>
|
||||||
|
<application android:label="Pakkit QA fixture" android:theme="@android:style/Theme.Material.NoActionBar" android:allowBackup="false">
|
||||||
|
<activity android:name=".FixtureActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
|
||||||
|
</application></manifest>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package meghdad.pakkit.fixture;
|
||||||
|
public final class FixtureActivity extends android.app.Activity {
|
||||||
|
@Override public void onCreate(android.os.Bundle state) {
|
||||||
|
super.onCreate(state);
|
||||||
|
android.widget.TextView text = new android.widget.TextView(this);
|
||||||
|
text.setText("Installation verified\nPakkit QA fixture");
|
||||||
|
text.setTextColor(0xffd9f99d); text.setBackgroundColor(0xff0e211b);
|
||||||
|
text.setGravity(android.view.Gravity.CENTER); text.setTextSize(18);
|
||||||
|
text.setPadding(36,36,36,36); setContentView(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,10 @@ plugins {
|
|||||||
dependencyResolutionManagement {
|
dependencyResolutionManagement {
|
||||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
repositories {
|
repositories {
|
||||||
|
// Optional for environments where Google Maven is inaccessible; official repository remains the default.
|
||||||
|
providers.gradleProperty("pakkitGoogleMavenMirror").orNull?.let { mirror ->
|
||||||
|
maven(mirror) { content { includeGroupByRegex("androidx.*"); includeGroupByRegex("com\\.google\\.android.*") } }
|
||||||
|
}
|
||||||
google()
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
@@ -24,3 +28,7 @@ dependencyResolutionManagement {
|
|||||||
|
|
||||||
rootProject.name = "pakkit"
|
rootProject.name = "pakkit"
|
||||||
include(":app")
|
include(":app")
|
||||||
|
include(":shared", ":wear")
|
||||||
|
// Test-only APK used by instrumentation. Never bundled in either consumer artifact.
|
||||||
|
include(":qaFixture")
|
||||||
|
project(":qaFixture").projectDir = file("qa/fixture")
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
plugins { id("com.android.library") }
|
||||||
|
android {
|
||||||
|
namespace = "meghdad.pakkit.core"
|
||||||
|
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||||
|
defaultConfig { minSdk = 31 }
|
||||||
|
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
api("com.google.android.gms:play-services-wearable:19.0.0")
|
||||||
|
api("androidx.work:work-runtime-ktx:2.10.1")
|
||||||
|
api(libs.androidx.core.ktx)
|
||||||
|
testImplementation(libs.junit)
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
<!-- Transfers use normal bounded workers; no foreground worker is started. -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove"/>
|
||||||
|
<application>
|
||||||
|
<service android:name="androidx.work.impl.foreground.SystemForegroundService" tools:node="remove"/>
|
||||||
|
<service android:name="meghdad.pakkit.core.LinkService" android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
|
||||||
|
<data android:scheme="wear" android:host="*" android:pathPrefix="/pakkit/" />
|
||||||
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
|
||||||
|
<data android:scheme="wear" android:host="*" android:path="/pakkit/probe" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.animation.ValueAnimator
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.ColorStateList
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import android.graphics.*
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import android.graphics.drawable.GradientDrawable
|
||||||
|
import android.graphics.drawable.RippleDrawable
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.View
|
||||||
|
import android.view.animation.DecelerateInterpolator
|
||||||
|
import android.widget.*
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.pow
|
||||||
|
|
||||||
|
/** Semantic colors: mint is an accent, never low-contrast body text on a light surface. */
|
||||||
|
data class BrandPalette(
|
||||||
|
val dark: Boolean, val canvas: Int, val surface: Int, val raised: Int,
|
||||||
|
val text: Int, val secondary: Int, val border: Int, val accent: Int,
|
||||||
|
val accentSoft: Int, val mint: Int, val mintSoft: Int, val error: Int, val errorSoft: Int
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
val Light = BrandPalette(false, 0xFFF6F5FC.toInt(), 0xFFFFFFFF.toInt(), 0xFFEEEBFA.toInt(),
|
||||||
|
0xFF19172C.toInt(), 0xFF646078.toInt(), 0xFFDCD8ED.toInt(), 0xFF6140D8.toInt(),
|
||||||
|
0xFFEAE3FF.toInt(), 0xFF09665E.toInt(), 0xFFDDF7F0.toInt(), 0xFFA32E4B.toInt(), 0xFFFCE8EE.toInt())
|
||||||
|
val Dark = BrandPalette(true, 0xFF090B17.toInt(), 0xFF141727.toInt(), 0xFF1C2035.toInt(),
|
||||||
|
0xFFF4F2FF.toInt(), 0xFFB7B6CE.toInt(), 0xFF32364E.toInt(), 0xFFBAA6FF.toInt(),
|
||||||
|
0xFF30234E.toInt(), 0xFF68E9CF.toInt(), 0xFF123931.toInt(), 0xFFFFA7BC.toInt(), 0xFF422330.toInt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object Design {
|
||||||
|
const val PURPLE = 0xFF7150EF.toInt()
|
||||||
|
const val MIDNIGHT = 0xFF090B17.toInt()
|
||||||
|
const val MINT = 0xFF68E9CF.toInt()
|
||||||
|
const val CYAN = 0xFF37D7F2.toInt()
|
||||||
|
private const val THEME = "theme"
|
||||||
|
fun themeMode(c: Context): String = c.getSharedPreferences("appearance", Context.MODE_PRIVATE).getString(THEME, "system") ?: "system"
|
||||||
|
fun setThemeMode(c: Context, mode: String) {
|
||||||
|
require(mode in setOf("system", "light", "dark"))
|
||||||
|
c.getSharedPreferences("appearance", Context.MODE_PRIVATE).edit().putString(THEME, mode).apply()
|
||||||
|
}
|
||||||
|
fun isDark(c: Context): Boolean = when (themeMode(c)) {
|
||||||
|
"dark" -> true
|
||||||
|
"light" -> false
|
||||||
|
else -> c.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
|
||||||
|
}
|
||||||
|
fun palette(c: Context): BrandPalette = if (Link.isWatch(c) || isDark(c)) BrandPalette.Dark else BrandPalette.Light
|
||||||
|
fun dp(c: Context, n: Int) = (n * c.resources.displayMetrics.density).toInt()
|
||||||
|
fun motionAllowed(c: Context) = ValueAnimator.areAnimatorsEnabled() && !c.getSystemService(PowerManager::class.java).isPowerSaveMode
|
||||||
|
fun shape(color: Int, radius: Float = 24f, stroke: Int? = null) = GradientDrawable().apply {
|
||||||
|
setColor(color); cornerRadius = radius; stroke?.let { setStroke(1, it) }
|
||||||
|
}
|
||||||
|
fun gradient(colors: IntArray, radius: Float) = GradientDrawable(GradientDrawable.Orientation.TL_BR, colors).apply { cornerRadius = radius }
|
||||||
|
fun column(c: Context) = LinearLayout(c).apply { orientation = LinearLayout.VERTICAL }
|
||||||
|
fun text(c: Context, value: String, size: Float, color: Int = palette(c).text, bold: Boolean = false) = TextView(c).apply {
|
||||||
|
text = value; textSize = size; setTextColor(color)
|
||||||
|
typeface = Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), if (bold) 650 else 400, false)
|
||||||
|
setLineSpacing(dp(c, 2).toFloat(), 1f)
|
||||||
|
includeFontPadding = false
|
||||||
|
}
|
||||||
|
fun button(c: Context, label: String, primary: Boolean = true, action: () -> Unit) = Button(c).apply {
|
||||||
|
val p = palette(c)
|
||||||
|
text = label; isAllCaps = false; textSize = 15f; minHeight = dp(c, 52)
|
||||||
|
typeface = Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), 600, false)
|
||||||
|
setTextColor(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())
|
||||||
|
else shape(p.raised, dp(c, 20).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))
|
||||||
|
addState(intArrayOf(), fill)
|
||||||
|
}
|
||||||
|
background = RippleDrawable(ColorStateList.valueOf(if (primary) 0x33FFFFFF else 0x226F4EF0), states, null)
|
||||||
|
stateListAnimator = null
|
||||||
|
setPadding(dp(c, 18), dp(c, 12), dp(c, 18), dp(c, 12))
|
||||||
|
setOnClickListener { performHapticFeedback(android.view.HapticFeedbackConstants.CONFIRM); action() }
|
||||||
|
}
|
||||||
|
fun badge(c: Context, label: String, positive: Boolean = false, warning: Boolean = false) = text(c, label, 12f,
|
||||||
|
if (warning) palette(c).error else if (positive) palette(c).mint else palette(c).accent, true).apply {
|
||||||
|
val p = palette(c)
|
||||||
|
setPadding(dp(c, 12), dp(c, 7), dp(c, 12), dp(c, 7))
|
||||||
|
background = shape(if (warning) p.errorSoft else if (positive) p.mintSoft else p.accentSoft, dp(c, 16).toFloat())
|
||||||
|
}
|
||||||
|
fun progress(c: Context) = ProgressBar(c, null, android.R.attr.progressBarStyleHorizontal).apply {
|
||||||
|
isIndeterminate = true
|
||||||
|
indeterminateTintList = ColorStateList.valueOf(palette(c).accent)
|
||||||
|
contentDescription = c.getString(R.string.transfer_waiting)
|
||||||
|
}
|
||||||
|
fun entrance(v: View) {
|
||||||
|
if (!motionAllowed(v.context)) return
|
||||||
|
v.alpha = 0f; v.translationY = dp(v.context, 6).toFloat()
|
||||||
|
v.animate().alpha(1f).translationY(0f).setDuration(240).setInterpolator(DecelerateInterpolator()).start()
|
||||||
|
}
|
||||||
|
fun contrast(a: Int, b: Int): Double {
|
||||||
|
fun luminance(color: Int): Double {
|
||||||
|
fun channel(shift: Int): Double {
|
||||||
|
val v = ((color shr shift) and 255) / 255.0
|
||||||
|
return if (v <= 0.04045) v / 12.92 else ((v + .055) / 1.055).pow(2.4)
|
||||||
|
}
|
||||||
|
return .2126 * channel(16) + .7152 * channel(8) + .0722 * channel(0)
|
||||||
|
}
|
||||||
|
val x = luminance(a); val y = luminance(b)
|
||||||
|
return (maxOf(x, y) + .05) / (minOf(x, y) + .05)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Static ambient lighting; shaders are rebuilt only when bounds change. */
|
||||||
|
class AuroraDrawable(private val p: BrandPalette) : Drawable() {
|
||||||
|
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private var glow: Shader? = null
|
||||||
|
override fun onBoundsChange(bounds: Rect) {
|
||||||
|
glow = RadialGradient(bounds.width() * .9f, 0f, bounds.width() * 1.1f,
|
||||||
|
if (p.dark) 0xFF211738.toInt() else 0xFFEDE5FF.toInt(), p.canvas, Shader.TileMode.CLAMP)
|
||||||
|
}
|
||||||
|
override fun draw(canvas: Canvas) { paint.shader = glow; canvas.drawRect(bounds, paint) }
|
||||||
|
override fun setAlpha(alpha: Int) { paint.alpha = alpha }
|
||||||
|
override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter }
|
||||||
|
@Deprecated("Drawable API") override fun getOpacity() = PixelFormat.OPAQUE
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class Glyph { TRANSFER, HISTORY, GUIDE, APPEARANCE, WATCH, FILE, CHECK, ALERT, SHIELD }
|
||||||
|
|
||||||
|
/** One stroke family for navigation, metadata and status. No font-dependent symbol icons. */
|
||||||
|
class GlyphDrawable(private val glyph: Glyph, private val color: Int) : Drawable() {
|
||||||
|
override fun getIntrinsicWidth() = 24
|
||||||
|
override fun getIntrinsicHeight() = 24
|
||||||
|
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.8f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
|
||||||
|
private val path = Path()
|
||||||
|
override fun draw(c: Canvas) {
|
||||||
|
val save = c.save(); c.translate(bounds.left.toFloat(), bounds.top.toFloat()); c.scale(bounds.width() / 24f, bounds.height() / 24f)
|
||||||
|
paint.color = color
|
||||||
|
path.rewind()
|
||||||
|
when (glyph) {
|
||||||
|
Glyph.TRANSFER -> { path.moveTo(4f, 8f); path.lineTo(19f, 8f); path.lineTo(15f, 4f); path.moveTo(20f, 16f); path.lineTo(5f, 16f); path.lineTo(9f, 20f) }
|
||||||
|
Glyph.HISTORY -> { c.drawCircle(12f, 12f, 8f, paint); path.moveTo(12f, 7f); path.lineTo(12f, 12f); path.lineTo(16f, 14f) }
|
||||||
|
Glyph.GUIDE -> { c.drawRoundRect(4f, 3f, 20f, 21f, 4f, 4f, paint); path.moveTo(9f, 8f); path.lineTo(15f, 8f); path.moveTo(9f, 12f); path.lineTo(15f, 12f); path.moveTo(9f, 16f); path.lineTo(12f, 16f) }
|
||||||
|
Glyph.APPEARANCE -> { c.drawCircle(12f, 12f, 8f, paint); paint.style = Paint.Style.FILL; c.drawArc(4f, 4f, 20f, 20f, 90f, 180f, true, paint); paint.style = Paint.Style.STROKE }
|
||||||
|
Glyph.WATCH -> { c.drawRoundRect(5f, 6f, 19f, 18f, 5f, 5f, paint); path.moveTo(8f, 6f); path.lineTo(9f, 2f); path.lineTo(15f, 2f); path.lineTo(16f, 6f); path.moveTo(8f, 18f); path.lineTo(9f, 22f); path.lineTo(15f, 22f); path.lineTo(16f, 18f) }
|
||||||
|
Glyph.FILE -> { path.moveTo(14f, 3f); path.lineTo(5f, 3f); path.lineTo(5f, 21f); path.lineTo(19f, 21f); path.lineTo(19f, 8f); path.close(); path.moveTo(14f, 3f); path.lineTo(14f, 8f); path.lineTo(19f, 8f); path.moveTo(9f, 13f); path.lineTo(15f, 13f); path.moveTo(9f, 17f); path.lineTo(13f, 17f) }
|
||||||
|
Glyph.CHECK -> { path.moveTo(5f, 12f); path.lineTo(10f, 17f); path.lineTo(19f, 7f) }
|
||||||
|
Glyph.ALERT -> { path.moveTo(12f, 3f); path.lineTo(22f, 20f); path.lineTo(2f, 20f); path.close(); path.moveTo(12f, 9f); path.lineTo(12f, 13f); path.moveTo(12f, 16f); path.lineTo(12f, 16.2f) }
|
||||||
|
Glyph.SHIELD -> { path.moveTo(12f, 2f); path.lineTo(20f, 6f); path.lineTo(19f, 15f); path.quadTo(16f, 20f, 12f, 22f); path.quadTo(8f, 20f, 5f, 15f); path.lineTo(4f, 6f); path.close(); path.moveTo(8f, 12f); path.lineTo(11f, 15f); path.lineTo(16f, 9f) }
|
||||||
|
}
|
||||||
|
c.drawPath(path, paint); c.restoreToCount(save)
|
||||||
|
}
|
||||||
|
override fun setAlpha(alpha: Int) { paint.alpha = alpha }
|
||||||
|
override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter }
|
||||||
|
@Deprecated("Drawable API") override fun getOpacity() = PixelFormat.TRANSLUCENT
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A reusable parcel illustration. Geometry and shaders are allocated once, never per frame. */
|
||||||
|
class ParcelSceneView(c: Context, private val compact: Boolean = false) : View(c) {
|
||||||
|
private val p = Design.palette(c)
|
||||||
|
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val left = polygon(106f, 111f, 180f, 140f, 180f, 211f, 106f, 180f)
|
||||||
|
private val right = polygon(180f, 140f, 254f, 111f, 254f, 180f, 180f, 211f)
|
||||||
|
private val inside = polygon(106f, 111f, 180f, 81f, 254f, 111f, 180f, 143f)
|
||||||
|
private val flapLeft = polygon(106f, 111f, 180f, 143f, 137f, 166f, 63f, 132f)
|
||||||
|
private val flapRight = polygon(180f, 143f, 254f, 111f, 297f, 132f, 223f, 166f)
|
||||||
|
private val flapBack = polygon(106f, 111f, 180f, 81f, 153f, 61f, 82f, 92f)
|
||||||
|
private val flapBackRight = polygon(180f, 81f, 254f, 111f, 278f, 92f, 207f, 61f)
|
||||||
|
private val faceLeft = LinearGradient(106f, 111f, 186f, 213f, intArrayOf(0xFF36D5F4.toInt(), 0xFF7762FA.toInt(), 0xFFA66CF2.toInt()), null, Shader.TileMode.CLAMP)
|
||||||
|
private val faceRight = LinearGradient(180f, 140f, 260f, 190f, intArrayOf(0xFF6845EC.toInt(), 0xFF8D52F5.toInt(), 0xFFE79BD3.toInt()), null, Shader.TileMode.CLAMP)
|
||||||
|
private val mintFlap = LinearGradient(63f, 112f, 180f, 157f, 0xFF8EF7E2.toInt(), 0xFF6B80FF.toInt(), Shader.TileMode.CLAMP)
|
||||||
|
private val violetFlap = LinearGradient(180f, 133f, 284f, 148f, 0xFFE3CAFF.toInt(), 0xFFA98CFF.toInt(), Shader.TileMode.CLAMP)
|
||||||
|
private val tile = LinearGradient(-23f, -23f, 24f, 23f, intArrayOf(0xFF6EEFD8.toInt(), 0xFF56CCF4.toInt(), 0xFF8554F3.toInt()), null, Shader.TileMode.CLAMP)
|
||||||
|
private val glow = RadialGradient(180f, 126f, 135f, if (p.dark) 0x665D3ACF else 0x335F3BE2, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||||
|
private val ground = RadialGradient(180f, 211f, 100f, if (p.dark) 0x55533DA7 else 0x22715AC1, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||||
|
private var lift = 0f
|
||||||
|
private var played = false
|
||||||
|
var active = false
|
||||||
|
set(value) { if (field != value) { field = value; play() } }
|
||||||
|
private val animator = ValueAnimator.ofFloat(0f, 1f).apply {
|
||||||
|
duration = 1100
|
||||||
|
interpolator = DecelerateInterpolator()
|
||||||
|
addUpdateListener { lift = it.animatedValue as Float; invalidate() }
|
||||||
|
}
|
||||||
|
init { importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
|
||||||
|
private fun polygon(vararg xy: Float) = Path().apply { moveTo(xy[0], xy[1]); for (i in 2 until xy.size step 2) lineTo(xy[i], xy[i + 1]); close() }
|
||||||
|
override fun onAttachedToWindow() { super.onAttachedToWindow(); play() }
|
||||||
|
override fun onDetachedFromWindow() { animator.cancel(); super.onDetachedFromWindow() }
|
||||||
|
override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility); if (visibility != VISIBLE) animator.cancel() else if (isAttachedToWindow) play() }
|
||||||
|
override fun onWindowFocusChanged(hasWindowFocus: Boolean) { super.onWindowFocusChanged(hasWindowFocus); if (!hasWindowFocus) animator.cancel() else play() }
|
||||||
|
private fun play() {
|
||||||
|
if (!isAttachedToWindow || compact || !hasWindowFocus() || windowVisibility != VISIBLE || played || !Design.motionAllowed(context)) { lift = 1f; return }
|
||||||
|
played = true; animator.start()
|
||||||
|
}
|
||||||
|
private fun face(c: Canvas, path: Path, shader: Shader) {
|
||||||
|
paint.style = Paint.Style.FILL; paint.alpha = 255; paint.shader = shader; c.drawPath(path, paint); paint.shader = null
|
||||||
|
paint.style = Paint.Style.STROKE; paint.strokeWidth = .8f; paint.color = 0x88FFFFFF.toInt(); c.drawPath(path, paint); paint.style = Paint.Style.FILL
|
||||||
|
}
|
||||||
|
override fun onDraw(c: Canvas) {
|
||||||
|
super.onDraw(c)
|
||||||
|
val save = c.save(); c.translate(width / 2f, height / 2f)
|
||||||
|
val scale = min(width / 350f, height / 235f)
|
||||||
|
c.scale(scale, scale); c.translate(-180f, -120f)
|
||||||
|
if (!compact) {
|
||||||
|
paint.shader = glow; c.drawCircle(180f, 126f, 135f, paint); paint.shader = ground; c.drawOval(65f, 181f, 295f, 236f, paint); paint.shader = null
|
||||||
|
paint.style = Paint.Style.STROKE; paint.strokeWidth = 1f; paint.color = if (p.dark) 0x4458DCCB else 0x336749C9
|
||||||
|
c.drawOval(24f, 148f, 336f, 220f, paint); c.drawOval(42f, 137f, 318f, 231f, paint)
|
||||||
|
paint.style = Paint.Style.FILL
|
||||||
|
}
|
||||||
|
paint.color = 0xFF352355.toInt(); c.drawPath(inside, paint)
|
||||||
|
face(c, flapBack, violetFlap); face(c, flapBackRight, mintFlap)
|
||||||
|
face(c, left, faceLeft); face(c, right, faceRight); face(c, flapLeft, mintFlap); face(c, flapRight, violetFlap)
|
||||||
|
c.save(); c.translate(184f, 46f - 8f * lift); c.rotate(18f)
|
||||||
|
paint.alpha = 255; paint.shader = tile; c.drawRoundRect(-23f, -23f, 23f, 23f, 11f, 11f, paint); paint.shader = null
|
||||||
|
paint.style = Paint.Style.STROKE; paint.strokeWidth = 1.4f; paint.color = 0xDDFFFFFF.toInt(); c.drawRoundRect(-23f, -23f, 23f, 23f, 11f, 11f, paint)
|
||||||
|
paint.style = Paint.Style.FILL; paint.color = 0xCCFFFFFF.toInt(); c.drawRoundRect(-9f, -7f, 9f, 7f, 4f, 4f, paint)
|
||||||
|
c.restore()
|
||||||
|
if (!compact) {
|
||||||
|
spark(c, 70f, 65f, 4f, p.accent); spark(c, 282f, 52f, 5f, Design.MINT); spark(c, 308f, 189f, 3f, p.accent)
|
||||||
|
paint.color = Design.CYAN; c.drawCircle(44f, 186f, 3f, paint)
|
||||||
|
paint.color = 0xFFFFB980.toInt(); c.drawCircle(296f, 97f, 3f, paint)
|
||||||
|
}
|
||||||
|
c.restoreToCount(save)
|
||||||
|
}
|
||||||
|
private fun spark(c: Canvas, x: Float, y: Float, r: Float, color: Int) {
|
||||||
|
paint.color = color; paint.strokeWidth = 1.5f; paint.strokeCap = Paint.Cap.ROUND
|
||||||
|
c.drawLine(x - r, y, x + r, y, paint); c.drawLine(x, y - r, x, y + r, paint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scroll position indicator follows the circular bezel and redraws only in response to scrolling. */
|
||||||
|
class RoundScrollView(c: Context) : ScrollView(c) {
|
||||||
|
private val track = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = Design.dp(c, 2).toFloat(); strokeCap = Paint.Cap.ROUND }
|
||||||
|
init { isVerticalScrollBarEnabled = false; isFillViewport = true; clipToPadding = false }
|
||||||
|
override fun onDrawForeground(canvas: Canvas) {
|
||||||
|
super.onDrawForeground(canvas)
|
||||||
|
val range = computeVerticalScrollRange().toFloat(); val extent = height.toFloat()
|
||||||
|
if (range <= extent + 1) return
|
||||||
|
val inset = Design.dp(context, 4).toFloat()
|
||||||
|
track.color = 0x3356557F
|
||||||
|
canvas.drawArc(inset, scrollY + inset, width - inset, scrollY + height - inset, -32f, 64f, false, track)
|
||||||
|
val sweep = (64f * extent / range).coerceAtLeast(12f)
|
||||||
|
val position = (scrollY / (range - extent)).coerceIn(0f, 1f)
|
||||||
|
track.color = 0xFFBAA6FF.toInt()
|
||||||
|
canvas.drawArc(inset, scrollY + inset, width - inset, scrollY + height - inset, -32f + (64f - sweep) * position, sweep, false, track)
|
||||||
|
}
|
||||||
|
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
|
||||||
|
if (event.action == MotionEvent.ACTION_SCROLL) {
|
||||||
|
scrollBy(0, (-event.getAxisValue(MotionEvent.AXIS_SCROLL) * Design.dp(context, 42)).toInt()); return true
|
||||||
|
}
|
||||||
|
return super.onGenericMotionEvent(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.provider.Settings
|
||||||
|
import com.google.android.gms.tasks.Tasks
|
||||||
|
import com.google.android.gms.wearable.*
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
object Link {
|
||||||
|
const val ROOT = "/pakkit/"
|
||||||
|
const val CAPABILITY = "pakkit_watch_v1"
|
||||||
|
fun isWatch(c: Context) = c.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
|
||||||
|
fun settings(c: Context) = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${c.packageName}"))
|
||||||
|
fun installer(c: Context): Boolean = Intent(Intent.ACTION_INSTALL_PACKAGE)
|
||||||
|
.setDataAndType(Uri.parse("content://meghdad.pakkit/probe.apk"), "application/vnd.android.package-archive")
|
||||||
|
.resolveActivity(c.packageManager) != null
|
||||||
|
fun capability(c: Context, nonce: String = "") {
|
||||||
|
val node = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
|
||||||
|
val request = PutDataMapRequest.create("${ROOT}cap/${node.id}")
|
||||||
|
request.dataMap.apply {
|
||||||
|
putString("nonce", nonce); putLong("time", System.currentTimeMillis()); putInt("sdk", Build.VERSION.SDK_INT)
|
||||||
|
putStringArrayList("abis", ArrayList(Build.SUPPORTED_ABIS.toList()))
|
||||||
|
putLong("free", Packages.free(c)); putBoolean("installer", installer(c))
|
||||||
|
putBoolean("settings", settings(c).resolveActivity(c.packageManager) != null)
|
||||||
|
putBoolean("allowed", c.packageManager.canRequestPackageInstalls())
|
||||||
|
}
|
||||||
|
Tasks.await(Wearable.getDataClient(c).putDataItem(request.asPutDataRequest().setUrgent()), 20, TimeUnit.SECONDS)
|
||||||
|
}
|
||||||
|
@Synchronized
|
||||||
|
fun status(c: Context, job: JSONObject, state: String, detail: String, persist: Boolean = true) {
|
||||||
|
val store = Store(c)
|
||||||
|
val revision = store.prefs.getLong("statusRevision", 0) + 1
|
||||||
|
store.prefs.edit().putLong("statusRevision", revision).commit()
|
||||||
|
val updated = JSONObject(job.toString()).put("state", state).put("detail", detail).put("revision", revision)
|
||||||
|
if (persist) Store(c).write("incoming", updated)
|
||||||
|
Store(c).history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, detail)
|
||||||
|
val req = PutDataMapRequest.create("${ROOT}status/${job.getString("id")}")
|
||||||
|
req.dataMap.apply {
|
||||||
|
putString("id", job.getString("id")); putString("target", job.getString("source"))
|
||||||
|
putString("state", state); putString("detail", detail.take(400)); putLong("time", System.currentTimeMillis()); putLong("revision", revision)
|
||||||
|
}
|
||||||
|
// A durable worker retries publication if connectivity or Play services is temporarily unavailable.
|
||||||
|
androidx.work.WorkManager.getInstance(c).enqueueUniqueWork("status-${job.getString("id")}",
|
||||||
|
androidx.work.ExistingWorkPolicy.REPLACE, androidx.work.OneTimeWorkRequestBuilder<StatusWorker>()
|
||||||
|
.setInputData(androidx.work.workDataOf("path" to req.uri.path, "map" to req.dataMap.toByteArray())).build())
|
||||||
|
}
|
||||||
|
fun delete(c: Context, uri: Uri) = Wearable.getDataClient(c).deleteDataItems(uri)
|
||||||
|
}
|
||||||
|
|
||||||
|
class StatusWorker(c: Context, p: androidx.work.WorkerParameters) : androidx.work.Worker(c, p) {
|
||||||
|
override fun doWork(): Result { return try {
|
||||||
|
val req = PutDataMapRequest.create(requireNotNull(inputData.getString("path")))
|
||||||
|
req.dataMap.putAll(DataMap.fromByteArray(requireNotNull(inputData.getByteArray("map"))))
|
||||||
|
val current = Store(applicationContext).read("incoming")
|
||||||
|
if (current != null && current.optString("id") == req.dataMap.getString("id") && current.optLong("revision") > req.dataMap.getLong("revision")) return Result.success()
|
||||||
|
Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 30, TimeUnit.SECONDS)
|
||||||
|
Result.success()
|
||||||
|
} catch (_: Exception) { if (runAttemptCount < 5) Result.retry() else Result.failure() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.work.*
|
||||||
|
import com.google.android.gms.tasks.Tasks
|
||||||
|
import com.google.android.gms.wearable.*
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class LinkService : WearableListenerService() {
|
||||||
|
override fun onMessageReceived(event: MessageEvent) {
|
||||||
|
if (Link.isWatch(this) && event.path == "/pakkit/probe" && event.data.size <= 100) {
|
||||||
|
runCatching { Link.capability(this, event.data.toString(Charsets.UTF_8)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onDataChanged(events: DataEventBuffer) {
|
||||||
|
for (event in events) {
|
||||||
|
if (event.type != DataEvent.TYPE_CHANGED) continue
|
||||||
|
val item = event.dataItem
|
||||||
|
when {
|
||||||
|
Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/offer/") == true -> {
|
||||||
|
WorkManager.getInstance(this).enqueueUniqueWork("receive-${item.uri.lastPathSegment}", ExistingWorkPolicy.KEEP,
|
||||||
|
OneTimeWorkRequestBuilder<ReceiveWorker>().setInputData(workDataOf("uri" to item.uri.toString())).build())
|
||||||
|
}
|
||||||
|
!Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/status/") == true -> acceptStatus(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun acceptStatus(item: DataItem) = synchronized(Store::class.java) {
|
||||||
|
runCatching {
|
||||||
|
val map = DataMapItem.fromDataItem(item).dataMap
|
||||||
|
val store = Store(this)
|
||||||
|
val job = store.read("outgoing") ?: return@runCatching
|
||||||
|
if (map.getString("id") != job.optString("id") || item.uri.host != job.optString("target")) return@runCatching
|
||||||
|
val revision = map.getLong("revision")
|
||||||
|
if (revision <= job.optLong("revision", -1)) return@runCatching
|
||||||
|
val state = map.getString("state") ?: return@runCatching
|
||||||
|
if (state !in setOf("receiving", "ready", "confirm", "installing", "installed", "failed", "declined")) return@runCatching
|
||||||
|
job.put("revision", revision).put("state", state).put("detail", map.getString("detail").orEmpty().take(400))
|
||||||
|
store.write("outgoing", job)
|
||||||
|
store.history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, job.getString("detail"))
|
||||||
|
if (state in setOf("installed", "failed", "declined")) {
|
||||||
|
store.file(job.getString("id")).delete()
|
||||||
|
job.optString("offer").takeIf { it.isNotEmpty() }?.let { Link.delete(this, Uri.parse(it)) }
|
||||||
|
Link.delete(this, item.uri)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReceiveWorker(c: android.content.Context, p: WorkerParameters) : Worker(c, p) {
|
||||||
|
override fun doWork(): Result {
|
||||||
|
val c = applicationContext
|
||||||
|
val store = Store(c)
|
||||||
|
var job: JSONObject? = null
|
||||||
|
var part: File? = null
|
||||||
|
var itemUri: Uri? = null
|
||||||
|
return try {
|
||||||
|
if (!Link.isWatch(c)) return Result.failure()
|
||||||
|
val uri = Uri.parse(requireNotNull(inputData.getString("uri")))
|
||||||
|
itemUri = uri
|
||||||
|
val item = Tasks.await(Wearable.getDataClient(c).getDataItem(uri), 30, TimeUnit.SECONDS) ?: return Result.success()
|
||||||
|
val map = DataMapItem.fromDataItem(item).dataMap
|
||||||
|
val local = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
|
||||||
|
if (map.getString("target") != local.id) return Result.success()
|
||||||
|
val id = requireNotNull(map.getString("id"))
|
||||||
|
require(TransferRules.validId(id) && uri.lastPathSegment == id)
|
||||||
|
val expected = Apk.from(JSONObject(requireNotNull(map.getString("apk"))))
|
||||||
|
job = JSONObject().put("id", id).put("source", uri.host).put("apk", expected.json()).put("created", map.getLong("created"))
|
||||||
|
if (store.prefs.getStringSet("received", emptySet()).orEmpty().contains(id)) return Result.success()
|
||||||
|
val old = store.read("incoming")
|
||||||
|
if (old?.optString("id") == id && old.optString("state") !in setOf("receiving")) return Result.success()
|
||||||
|
if (old != null && old.optString("id") != id && old.optString("state") !in setOf("installed", "failed", "declined")) {
|
||||||
|
Link.status(c, job, "failed", "Finish or dismiss the current APK on your watch first.", persist = false)
|
||||||
|
Link.delete(c, uri)
|
||||||
|
return Result.success()
|
||||||
|
}
|
||||||
|
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again from your phone." }
|
||||||
|
require(expected.bytes in 1..TransferRules.MAX_BYTES)
|
||||||
|
require(Link.installer(c) && (c.packageManager.canRequestPackageInstalls() || Link.settings(c).resolveActivity(c.packageManager) != null)) { "This watch does not expose the system installation controls. Use Google Play on your watch." }
|
||||||
|
Packages.checkForWatch(expected, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
|
||||||
|
WorkManager.getInstance(c).enqueueUniqueWork("expire-$id", ExistingWorkPolicy.KEEP,
|
||||||
|
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay((map.getLong("created") + TransferRules.TTL_MS - System.currentTimeMillis()).coerceAtLeast(0), TimeUnit.MILLISECONDS)
|
||||||
|
.setInputData(workDataOf("id" to id)).build())
|
||||||
|
Link.status(c, job, "receiving", "Verifying the APK on your watch")
|
||||||
|
part = File(store.directory, "$id.part")
|
||||||
|
val asset = requireNotNull(map.getAsset("file"))
|
||||||
|
val response = Tasks.await(Wearable.getDataClient(c).getFdForAsset(asset), 90, TimeUnit.SECONDS)
|
||||||
|
val result = try {
|
||||||
|
requireNotNull(response.inputStream).use { input -> part.outputStream().use { output -> TransferRules.copyBounded(input, output) } }
|
||||||
|
} finally { response.release() }
|
||||||
|
require(result.first == expected.bytes && result.second == expected.sha256) { "The file did not pass its integrity check. Send it again." }
|
||||||
|
val actual = Packages.inspect(c, part, result.second)
|
||||||
|
require(actual.packageName == expected.packageName) { "Package details did not match." }
|
||||||
|
Packages.checkForWatch(actual, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
|
||||||
|
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again." }
|
||||||
|
require(part.renameTo(store.file(id))) { "Could not save this APK." }
|
||||||
|
job.put("apk", actual.json())
|
||||||
|
Link.status(c, job, "ready", "Ready. Review and install on your watch.")
|
||||||
|
store.prefs.edit().putStringSet("received", (store.prefs.getStringSet("received", emptySet()).orEmpty().toList().takeLast(99) + id).toSet()).commit()
|
||||||
|
|
||||||
|
Link.delete(c, uri)
|
||||||
|
store.clean()
|
||||||
|
Result.success()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
part?.delete()
|
||||||
|
if (job != null && e !is IllegalArgumentException && e !is IllegalStateException && runAttemptCount < 3) {
|
||||||
|
Result.retry()
|
||||||
|
} else if (job != null) {
|
||||||
|
runCatching { Link.status(c, job, "failed", e.message ?: "Could not receive this APK. Try again.") }
|
||||||
|
itemUri?.let { Link.delete(c, it) }
|
||||||
|
Result.failure()
|
||||||
|
} else if (runAttemptCount < 3) Result.retry() else Result.failure()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.StatFs
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.zip.ZipFile
|
||||||
|
|
||||||
|
data class Apk(val label: String, val packageName: String, val version: String, val minSdk: Int,
|
||||||
|
val bytes: Long, val sha256: String, val abis: Set<String>, val wear: Boolean) {
|
||||||
|
fun json() = JSONObject().put("label", label).put("package", packageName).put("version", version)
|
||||||
|
.put("minSdk", minSdk).put("bytes", bytes).put("sha256", sha256)
|
||||||
|
.put("abis", abis.joinToString(",")).put("wear", wear)
|
||||||
|
companion object {
|
||||||
|
fun from(j: JSONObject) = Apk(j.getString("label"), j.getString("package"), j.getString("version"),
|
||||||
|
j.getInt("minSdk"), j.getLong("bytes"), j.getString("sha256"),
|
||||||
|
j.getString("abis").split(',').filter { it.isNotBlank() }.toSet(), j.getBoolean("wear"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
object Packages {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun inspect(context: Context, file: File, hash: String): Apk {
|
||||||
|
require(file.length() in 1..TransferRules.MAX_BYTES) { "Choose an APK smaller than 50 MB." }
|
||||||
|
val abis = mutableSetOf<String>()
|
||||||
|
ZipFile(file).use { zip ->
|
||||||
|
require(zip.getEntry("AndroidManifest.xml") != null) { "This file is not an Android APK." }
|
||||||
|
require(zip.size() < 100_000) { "This archive contains too many entries." }
|
||||||
|
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." }
|
||||||
|
expanded += entry.size
|
||||||
|
require(expanded <= 200L * 1024 * 1024) { "This APK expands beyond Pakkit’s package limit." }
|
||||||
|
if (entry.name == "AndroidManifest.xml") require(entry.size <= 2 * 1024 * 1024) { "This APK manifest is too large." }
|
||||||
|
val parts = entry.name.split('/')
|
||||||
|
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so")) abis += parts[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val info = 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." }
|
||||||
|
require(info.signingInfo?.apkContentsSigners?.isNotEmpty() == true) { "This APK has no readable signing certificate." }
|
||||||
|
require(info.packageName != context.packageName) { "Update Pakkit through Google Play." }
|
||||||
|
val app = requireNotNull(info.applicationInfo)
|
||||||
|
app.sourceDir = file.path
|
||||||
|
app.publicSourceDir = file.path
|
||||||
|
context.packageManager.getResourcesForApplication(app).assets.openXmlResourceParser("AndroidManifest.xml").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." }
|
||||||
|
if (xml.name == "manifest") require(xml.getAttributeValue(null, "split").isNullOrEmpty()) { "This is a split APK. Choose a complete APK." }
|
||||||
|
if (xml.name == "application") require(!xml.getAttributeBooleanValue("http://schemas.android.com/apk/res/android", "isSplitRequired", false)) { "This APK requires additional splits." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Apk(app.loadLabel(context.packageManager).toString().take(100), info.packageName,
|
||||||
|
info.versionName.orEmpty().take(64), app.minSdkVersion, file.length(), hash, abis,
|
||||||
|
info.reqFeatures?.any { it.name == PackageManager.FEATURE_WATCH } == true)
|
||||||
|
}
|
||||||
|
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>, free: Long) {
|
||||||
|
require(apk.minSdk <= sdk) { "This APK needs Android API ${apk.minSdk}; your watch runs API $sdk." }
|
||||||
|
require(TransferRules.compatibleAbis(apk.abis, abis)) { "This APK was built for a different processor." }
|
||||||
|
require(free > apk.bytes * 3 + 20 * 1024 * 1024) { "Free more storage on your watch, then try again." }
|
||||||
|
}
|
||||||
|
fun free(context: Context) = StatFs(context.filesDir.path).availableBytes
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.work.*
|
||||||
|
import com.google.android.gms.tasks.Tasks
|
||||||
|
import com.google.android.gms.wearable.*
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class SendWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
|
||||||
|
override fun doWork(): Result {
|
||||||
|
val store = Store(applicationContext)
|
||||||
|
val job = store.read("outgoing") ?: return Result.failure()
|
||||||
|
if (job.optString("id") != inputData.getString("id") || job.optString("state") != "sending") return Result.success()
|
||||||
|
return try {
|
||||||
|
require(TransferRules.fresh(job.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Choose the file again." }
|
||||||
|
val req = PutDataMapRequest.create("/pakkit/offer/${job.getString("id")}")
|
||||||
|
req.dataMap.apply {
|
||||||
|
putString("id", job.getString("id")); putString("target", job.getString("target"))
|
||||||
|
putLong("created", job.getLong("created")); putString("apk", job.getJSONObject("apk").toString())
|
||||||
|
putAsset("file", Asset.createFromUri(Uri.fromFile(store.file(job.getString("id")))))
|
||||||
|
}
|
||||||
|
val item = Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 45, TimeUnit.SECONDS)
|
||||||
|
// Do not overwrite an acknowledgement that arrived while publication was in flight.
|
||||||
|
synchronized(Store::class.java) {
|
||||||
|
val latest = store.read("outgoing")
|
||||||
|
if (latest?.optString("id") == job.getString("id")) {
|
||||||
|
latest.put("offer", item.uri.toString())
|
||||||
|
if (latest.optString("state") == "sending") latest.put("state", "syncing")
|
||||||
|
.put("detail", "Syncing to your watch. Open Pakkit there to continue.")
|
||||||
|
store.write("outgoing", latest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WorkManager.getInstance(applicationContext).enqueueUniqueWork("expire-${job.getString("id")}", ExistingWorkPolicy.KEEP,
|
||||||
|
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay(24, TimeUnit.HOURS)
|
||||||
|
.setInputData(workDataOf("id" to job.getString("id"), "uri" to item.uri.toString())).build())
|
||||||
|
Result.success()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (runAttemptCount < 3) Result.retry() else {
|
||||||
|
synchronized(Store::class.java) {
|
||||||
|
val latest = store.read("outgoing")
|
||||||
|
if (latest?.optString("id") == job.getString("id") && latest.optString("state") == "sending")
|
||||||
|
store.write("outgoing", latest.put("state", "failed").put("detail", "Could not sync. Check your connection and choose the file again."))
|
||||||
|
}
|
||||||
|
Result.failure()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class ExpireWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
|
||||||
|
override fun doWork(): Result {
|
||||||
|
val store = Store(applicationContext)
|
||||||
|
val id = inputData.getString("id") ?: return Result.failure()
|
||||||
|
return try {
|
||||||
|
inputData.getString("uri")?.let { Tasks.await(Link.delete(applicationContext, Uri.parse(it)), 30, TimeUnit.SECONDS) }
|
||||||
|
store.file(id).delete()
|
||||||
|
for (key in listOf("incoming", "outgoing")) {
|
||||||
|
val job = store.read(key) ?: continue
|
||||||
|
if (job.optString("id") == id && job.optString("state") !in setOf("installed", "failed", "declined")) {
|
||||||
|
if (key == "incoming") {
|
||||||
|
job.optInt("session", -1).takeIf { it >= 0 }?.let { runCatching { applicationContext.packageManager.packageInstaller.abandonSession(it) } }
|
||||||
|
applicationContext.getSystemService(android.app.NotificationManager::class.java).cancel(42)
|
||||||
|
}
|
||||||
|
if (key == "incoming") Link.status(applicationContext, job, "failed", "This APK expired. Send it again from your phone.")
|
||||||
|
else store.write(key, job.put("state", "failed").put("detail", "This transfer expired. Choose the file again."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
store.clean()
|
||||||
|
Result.success()
|
||||||
|
} catch (_: Exception) { if (runAttemptCount < 3) Result.retry() else Result.failure() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
class Store(context: Context) {
|
||||||
|
val prefs: SharedPreferences = context.getSharedPreferences("pakkit", Context.MODE_PRIVATE)
|
||||||
|
val directory = File(context.filesDir, "packages").apply { mkdirs() }
|
||||||
|
fun file(id: String): File { require(TransferRules.validId(id)); return File(directory, "$id.apk") }
|
||||||
|
fun read(key: String): JSONObject? = runCatching { JSONObject(prefs.getString(key, null) ?: return null) }.getOrNull()
|
||||||
|
fun write(key: String, value: JSONObject) { check(prefs.edit().putString(key, value.toString()).commit()) }
|
||||||
|
fun clear(key: String) { prefs.edit().remove(key).commit() }
|
||||||
|
fun history(id: String, label: String, state: String, detail: String) = synchronized(Store::class.java) {
|
||||||
|
val old = runCatching { JSONArray(prefs.getString("history", "[]")) }.getOrDefault(JSONArray())
|
||||||
|
val next = JSONArray().put(JSONObject().put("id", id).put("label", label).put("state", state)
|
||||||
|
.put("detail", detail).put("time", System.currentTimeMillis()))
|
||||||
|
for (i in 0 until old.length()) if (old.getJSONObject(i).optString("id") != id && next.length() < 20) next.put(old.getJSONObject(i))
|
||||||
|
prefs.edit().putString("history", next.toString()).commit()
|
||||||
|
}
|
||||||
|
fun clean() {
|
||||||
|
val keep = listOfNotNull(read("outgoing")?.optString("id"), read("incoming")?.optString("id"))
|
||||||
|
directory.listFiles()?.forEach {
|
||||||
|
if (it.name.substringBefore('.') !in keep && System.currentTimeMillis() - it.lastModified() > TransferRules.TTL_MS) it.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
object TransferRules {
|
||||||
|
const val MAX_BYTES = 50L * 1024 * 1024
|
||||||
|
const val TTL_MS = 24L * 60 * 60 * 1000
|
||||||
|
fun validId(id: String) = Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id)
|
||||||
|
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
|
||||||
|
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) = packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
|
||||||
|
fun copyBounded(input: InputStream, output: OutputStream, max: Long = MAX_BYTES): Pair<Long, String> {
|
||||||
|
val hash = MessageDigest.getInstance("SHA-256")
|
||||||
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
var total = 0L
|
||||||
|
while (true) {
|
||||||
|
val count = input.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
if (count == 0) continue
|
||||||
|
total += count
|
||||||
|
require(total <= max) { "Choose an APK smaller than 50 MB." }
|
||||||
|
hash.update(buffer, 0, count)
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
require(total > 0) { "This file is empty." }
|
||||||
|
return total to hash.digest().joinToString("") { "%02x".format(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
|
||||||
|
<path android:pathData="M31,48L54,38L77,48L54,59Z" android:fillColor="#38265F"/>
|
||||||
|
<path android:pathData="M31,48L54,58L54,81L31,71Z">
|
||||||
|
<aapt:attr name="android:fillColor"><gradient android:startX="31" android:startY="48" android:endX="55" android:endY="81" android:startColor="#42DDF1" android:endColor="#8B5CF6" android:type="linear"/></aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path android:pathData="M54,58L77,48L77,71L54,81Z">
|
||||||
|
<aapt:attr name="android:fillColor"><gradient android:startX="54" android:startY="58" android:endX="78" android:endY="76" android:startColor="#7049F2" android:endColor="#D99AE5" android:type="linear"/></aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path android:pathData="M31,48L54,58L40,65L18,54Z" android:strokeColor="#C8FFF0" android:strokeWidth="0.5">
|
||||||
|
<aapt:attr name="android:fillColor"><gradient android:startX="18" android:startY="48" android:endX="54" android:endY="66" android:startColor="#8FF9E1" android:endColor="#7B94FF" android:type="linear"/></aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path android:pathData="M54,58L77,48L90,54L68,65Z" android:strokeColor="#EAE1FF" android:strokeWidth="0.5">
|
||||||
|
<aapt:attr name="android:fillColor"><gradient android:startX="54" android:startY="58" android:endX="90" android:endY="54" android:startColor="#E9D5FF" android:endColor="#AD8AFF" android:type="linear"/></aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path android:pathData="M31,48L54,38L45,32L23,42Z" android:fillColor="#A79BFF"/>
|
||||||
|
<path android:pathData="M54,38L77,48L85,42L63,32Z" android:fillColor="#79EBD9"/>
|
||||||
|
<path android:pathData="M49,21Q50,18 54,19L65,23Q68,24 67,28L63,39Q62,42 58,41L47,37Q44,36 45,32Z" android:strokeColor="#D8FFF8" android:strokeWidth="0.7">
|
||||||
|
<aapt:attr name="android:fillColor"><gradient android:startX="46" android:startY="20" android:endX="67" android:endY="41" android:startColor="#83F5DD" android:endColor="#8055F2" android:type="linear"/></aapt:attr>
|
||||||
|
</path>
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
|
||||||
|
<path android:pathData="M0,0H108V108H0Z"><aapt:attr name="android:fillColor"><gradient android:type="radial" android:centerX="70" android:centerY="22" android:gradientRadius="100" android:startColor="#302052" android:endColor="#090B17"/></aapt:attr></path>
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
|
||||||
|
<path android:fillColor="#FFFFFF" android:pathData="M30,50L52,60L52,81L30,71ZM56,60L78,50L78,71L56,81ZM30,46L52,56L40,62L18,52ZM56,56L78,46L90,52L68,62ZM31,44L52,35L44,29L23,39ZM56,35L77,44L85,39L64,29ZM49,19Q50,17 53,18L65,22Q68,23 67,26L63,37Q62,40 59,39L47,35Q44,34 45,31Z"/>
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"><background android:drawable="@drawable/pakkit_launcher_background"/><foreground android:drawable="@drawable/pakkit_icon"/><monochrome android:drawable="@drawable/pakkit_mark"/></adaptive-icon>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<resources>
|
||||||
|
<color name="pakkit_ink">#090B17</color>
|
||||||
|
<string name="pakkit_name">Pakkit</string>
|
||||||
|
<string name="brand_tagline">Pocket to Wrist.</string>
|
||||||
|
<string name="brand_secondary_tagline">Pack it. Send it. Wear it.</string>
|
||||||
|
<string name="transfer_waiting">Waiting for the watch to acknowledge this transfer</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<data-extraction-rules>
|
||||||
|
<cloud-backup disableIfNoEncryptionCapabilities="true">
|
||||||
|
<exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/><exclude domain="external" path="."/>
|
||||||
|
</cloud-backup>
|
||||||
|
<device-transfer><exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/><exclude domain="external" path="."/></device-transfer>
|
||||||
|
</data-extraction-rules>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BrandPaletteTest {
|
||||||
|
@Test fun bodyAndSecondaryCopyMeetNormalTextContrast() {
|
||||||
|
for (palette in listOf(BrandPalette.Light, BrandPalette.Dark)) {
|
||||||
|
for (surface in listOf(palette.canvas, palette.surface, palette.raised)) {
|
||||||
|
assertTrue("Body contrast", Design.contrast(palette.text, surface) >= 4.5)
|
||||||
|
assertTrue("Secondary contrast", Design.contrast(palette.secondary, surface) >= 4.5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Test fun semanticBadgesRemainReadableInBothThemes() {
|
||||||
|
for (p in listOf(BrandPalette.Light, BrandPalette.Dark)) {
|
||||||
|
assertTrue("Purple badge", Design.contrast(p.accent, p.accentSoft) >= 4.5)
|
||||||
|
assertTrue("Mint badge", Design.contrast(p.mint, p.mintSoft) >= 4.5)
|
||||||
|
assertTrue("Error badge", Design.contrast(p.error, p.errorSoft) >= 4.5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Test fun primaryButtonTextContrastsWithBothGradientStops() {
|
||||||
|
for (stop in listOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt())) {
|
||||||
|
assertTrue(Design.contrast(0xFFFFFFFF.toInt(), stop) >= 4.5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package meghdad.pakkit.core
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
|
||||||
|
class TransferRulesTest {
|
||||||
|
@Test fun copyComputesKnownDigest() {
|
||||||
|
val output=ByteArrayOutputStream()
|
||||||
|
val result=TransferRules.copyBounded(ByteArrayInputStream("abc".toByteArray()),output)
|
||||||
|
assertEquals(3L,result.first)
|
||||||
|
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",result.second)
|
||||||
|
assertEquals("abc",output.toString("UTF-8"))
|
||||||
|
}
|
||||||
|
@Test(expected=IllegalArgumentException::class) fun stopsBeforeWritingOverLimit() {
|
||||||
|
TransferRules.copyBounded(ByteArrayInputStream(ByteArray(1025)),ByteArrayOutputStream(),1024)
|
||||||
|
}
|
||||||
|
@Test(expected=IllegalArgumentException::class) fun refusesEmptyFiles() {
|
||||||
|
TransferRules.copyBounded(ByteArrayInputStream(byteArrayOf()),ByteArrayOutputStream())
|
||||||
|
}
|
||||||
|
@Test fun rejectsTraversalAndInvalidIdentifiers() {
|
||||||
|
assertFalse(TransferRules.validId("../apk")); assertFalse(TransferRules.validId("file.apk"))
|
||||||
|
assertTrue(TransferRules.validId("05b414ab-a230-42f8-9a6d-1be25dcc3224"))
|
||||||
|
}
|
||||||
|
@Test fun expirationAndClockSkewAreBounded() {
|
||||||
|
val now=1_000_000_000L
|
||||||
|
assertTrue(TransferRules.fresh(now-1000,now))
|
||||||
|
assertFalse(TransferRules.fresh(now-TransferRules.TTL_MS,now))
|
||||||
|
assertFalse(TransferRules.fresh(now+120000,now))
|
||||||
|
}
|
||||||
|
@Test fun nativeLibrariesNeedMatchingProcessor() {
|
||||||
|
assertTrue(TransferRules.compatibleAbis(emptySet(),setOf("arm64-v8a")))
|
||||||
|
assertTrue(TransferRules.compatibleAbis(setOf("armeabi-v7a","arm64-v8a"),setOf("arm64-v8a")))
|
||||||
|
assertFalse(TransferRules.compatibleAbis(setOf("x86_64"),setOf("arm64-v8a")))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
plugins { alias(libs.plugins.android.application) }
|
||||||
|
android {
|
||||||
|
namespace = "meghdad.pakkit.wear"
|
||||||
|
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "meghdad.pakkit"
|
||||||
|
minSdk = 31
|
||||||
|
targetSdk = 36
|
||||||
|
versionCode = 100002
|
||||||
|
versionName = "0.1.0"
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
}
|
||||||
|
val releaseKey = providers.environmentVariable("PAKKIT_KEYSTORE").orNull
|
||||||
|
val releaseStorePassword = providers.environmentVariable("PAKKIT_KEYSTORE_PASSWORD").orNull
|
||||||
|
val releaseAlias = providers.environmentVariable("PAKKIT_KEY_ALIAS").orNull
|
||||||
|
val releaseKeyPassword = providers.environmentVariable("PAKKIT_KEY_PASSWORD").orNull
|
||||||
|
if (listOf(releaseKey, releaseStorePassword, releaseAlias, releaseKeyPassword).all { it != null }) {
|
||||||
|
signingConfigs.create("production") {
|
||||||
|
storeFile = file(requireNotNull(releaseKey)); storePassword = releaseStorePassword
|
||||||
|
keyAlias = releaseAlias; keyPassword = releaseKeyPassword
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buildTypes { release { signingConfig = signingConfigs.findByName("production"); isMinifyEnabled = true; isShrinkResources = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "../proguard-rules.pro") } }
|
||||||
|
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
|
||||||
|
}
|
||||||
|
dependencies { implementation(project(":shared")); androidTestImplementation(libs.androidx.junit); androidTestImplementation(libs.androidx.espresso.core) }
|
||||||
|
|
||||||
|
abstract class StageFixtureApk : DefaultTask() {
|
||||||
|
@get:InputFile abstract val fixtureFile: RegularFileProperty
|
||||||
|
@get:OutputDirectory abstract val outputDirectory: DirectoryProperty
|
||||||
|
@TaskAction fun stage() {
|
||||||
|
val output = outputDirectory.file("fixture.apk").get().asFile
|
||||||
|
output.parentFile.mkdirs()
|
||||||
|
fixtureFile.get().asFile.copyTo(output, overwrite = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val stageTestFixture by tasks.registering(StageFixtureApk::class) {
|
||||||
|
dependsOn(":qaFixture:assembleDebug")
|
||||||
|
fixtureFile.set(project(":qaFixture").layout.buildDirectory.file("outputs/apk/debug/qaFixture-debug.apk"))
|
||||||
|
outputDirectory.set(layout.buildDirectory.dir("generated/testAssets"))
|
||||||
|
}
|
||||||
|
androidComponents.onVariants(androidComponents.selector().withBuildType("debug")) { variant ->
|
||||||
|
variant.androidTest?.sources?.assets?.addGeneratedSourceDirectory(stageTestFixture, StageFixtureApk::outputDirectory)
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package meghdad.pakkit.wear
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Button
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import meghdad.pakkit.core.*
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class WatchReviewTest {
|
||||||
|
@Test fun receivingAFileDoesNotCreateAnInstallSession() {
|
||||||
|
val instrumentation=InstrumentationRegistry.getInstrumentation()
|
||||||
|
val c=instrumentation.targetContext
|
||||||
|
val store=Store(c)
|
||||||
|
val id=UUID.randomUUID().toString()
|
||||||
|
val file=store.file(id)
|
||||||
|
val digest=instrumentation.context.assets.open("fixture.apk").use { input -> file.outputStream().use { TransferRules.copyBounded(input,it).second } }
|
||||||
|
val apk=Packages.inspect(c,file,digest)
|
||||||
|
assertEquals("meghdad.pakkit.fixture",apk.packageName)
|
||||||
|
val before=c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet()
|
||||||
|
store.write("incoming",JSONObject().put("id",id).put("source","qa-fixture")
|
||||||
|
.put("created",System.currentTimeMillis()).put("apk",apk.json()).put("state","ready")
|
||||||
|
.put("detail","Ready. Review and install on your watch."))
|
||||||
|
val monitor=instrumentation.addMonitor(WatchActivity::class.java.name,null,false)
|
||||||
|
c.startActivity(Intent(c,WatchActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
|
val activity=monitor.waitForActivityWithTimeout(5000)
|
||||||
|
assertNotNull(activity)
|
||||||
|
instrumentation.waitForIdleSync()
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
fun texts(v:View):List<String> = when(v) {
|
||||||
|
is ViewGroup -> (0 until v.childCount).flatMap { texts(v.getChildAt(it)) }
|
||||||
|
is TextView -> listOf(v.text.toString())
|
||||||
|
else -> emptyList()
|
||||||
|
}
|
||||||
|
assertTrue(texts(activity.window.decorView).contains("Pakkit QA fixture"))
|
||||||
|
fun views(v: View): List<View> = listOf(v) + if (v is ViewGroup) (0 until v.childCount).flatMap { views(v.getChildAt(it)) } else emptyList()
|
||||||
|
val all = views(activity.window.decorView)
|
||||||
|
val scroll = all.filterIsInstance<RoundScrollView>().single()
|
||||||
|
val buttons = all.filterIsInstance<Button>()
|
||||||
|
assertTrue(buttons.any { it.text == "Install" || it.text == "Allow installs" })
|
||||||
|
for (button in buttons) {
|
||||||
|
assertTrue("48 dp target height", button.height >= Design.dp(c, 48))
|
||||||
|
scroll.scrollTo(0, (button.top + button.height / 2 - scroll.height / 2).coerceAtLeast(0))
|
||||||
|
val visible = Rect()
|
||||||
|
assertTrue("Action is reachable", button.getGlobalVisibleRect(visible))
|
||||||
|
assertEquals("Action is fully visible", button.height, visible.height())
|
||||||
|
assertTrue("Action is horizontally readable", visible.width() >= Design.dp(c, 48))
|
||||||
|
}
|
||||||
|
scroll.scrollTo(0, 0)
|
||||||
|
}
|
||||||
|
assertEquals(before,c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet())
|
||||||
|
instrumentation.removeMonitor(monitor)
|
||||||
|
// Deliberately leave the actual signed fixture on the review screen for manual consent QA.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-feature android:name="android.hardware.type.watch" android:required="true"/>
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||||
|
<queries>
|
||||||
|
<intent><action android:name="android.settings.MANAGE_UNKNOWN_APP_SOURCES"/><data android:scheme="package"/></intent>
|
||||||
|
<intent><action android:name="android.intent.action.INSTALL_PACKAGE"/><data android:mimeType="application/vnd.android.package-archive"/></intent>
|
||||||
|
</queries>
|
||||||
|
<application android:allowBackup="false" android:dataExtractionRules="@xml/pakkit_data_rules" android:icon="@mipmap/pakkit_launcher" android:label="@string/pakkit_name" android:supportsRtl="true" android:theme="@style/Theme.Pakkit.Wear">
|
||||||
|
<meta-data android:name="com.google.android.wearable.standalone" android:value="false"/>
|
||||||
|
<activity android:name=".WatchActivity" android:exported="true" android:launchMode="singleTop" android:taskAffinity="">
|
||||||
|
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
|
||||||
|
</activity>
|
||||||
|
<receiver android:name=".InstallReceiver" android:exported="false"/>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package meghdad.pakkit.wear
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.*
|
||||||
|
import android.content.*
|
||||||
|
import android.content.pm.PackageInstaller
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import meghdad.pakkit.core.*
|
||||||
|
import java.lang.ref.WeakReference
|
||||||
|
|
||||||
|
/** Only the installer can fill in this explicit, mutable PendingIntent. No exported receiver. */
|
||||||
|
class InstallReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val store=Store(context)
|
||||||
|
val job=store.read("incoming") ?: return
|
||||||
|
if(intent.getStringExtra("job")!=job.optString("id") || intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID,-1)!=job.optInt("session",-2)) return
|
||||||
|
val status=intent.getIntExtra(PackageInstaller.EXTRA_STATUS,PackageInstaller.STATUS_FAILURE)
|
||||||
|
when(status) {
|
||||||
|
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||||
|
@Suppress("DEPRECATION") val confirmation=intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
|
||||||
|
if(confirmation==null) { Link.status(context,job,"failed","The system did not provide an approval screen."); return }
|
||||||
|
PendingApproval.id=job.getString("id"); PendingApproval.intent=confirmation
|
||||||
|
Link.status(context,job,"confirm","Continue the system approval on your watch.")
|
||||||
|
val activity=PendingApproval.activity?.get()
|
||||||
|
if(activity!=null) activity.refresh()
|
||||||
|
val manager=context.getSystemService(NotificationManager::class.java)
|
||||||
|
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",job.getString("id"))
|
||||||
|
val pending=PendingIntent.getActivity(context,job.getInt("session"),open,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||||
|
manager.notify(42,Notification.Builder(context,"installation").setSmallIcon(meghdad.pakkit.core.R.drawable.pakkit_mark).setColor(Design.PURPLE)
|
||||||
|
.setContentTitle("Approve installation").setContentText("Open Pakkit to continue on your watch.")
|
||||||
|
.setContentIntent(pending).setAutoCancel(true).build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PackageInstaller.STATUS_SUCCESS -> {
|
||||||
|
PendingApproval.intent=null
|
||||||
|
Link.status(context,job,"installed","Installed on your watch.")
|
||||||
|
store.file(job.getString("id")).delete()
|
||||||
|
context.getSystemService(NotificationManager::class.java).cancel(42)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
PendingApproval.intent=null
|
||||||
|
val detail=when(status) {
|
||||||
|
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."
|
||||||
|
PackageInstaller.STATUS_FAILURE_CONFLICT -> "This APK conflicts with an installed app or its signature. Ask the developer for a compatible version."
|
||||||
|
PackageInstaller.STATUS_FAILURE_INCOMPATIBLE -> "This APK is not compatible with your watch."
|
||||||
|
PackageInstaller.STATUS_FAILURE_INVALID -> "The system rejected this APK’s format or signature."
|
||||||
|
PackageInstaller.STATUS_FAILURE_STORAGE -> "Your watch needs more free storage."
|
||||||
|
else -> "The system could not finish installing. Try again or use Google Play."
|
||||||
|
}
|
||||||
|
Link.status(context,job,"failed",detail)
|
||||||
|
context.getSystemService(NotificationManager::class.java).cancel(42)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
object PendingApproval {
|
||||||
|
var id: String?=null
|
||||||
|
var intent: Intent?=null
|
||||||
|
var activity: WeakReference<WatchActivity>?=null
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
package meghdad.pakkit.wear
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.*
|
||||||
|
import android.content.*
|
||||||
|
import android.content.pm.PackageInstaller
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.*
|
||||||
|
import android.view.*
|
||||||
|
import android.widget.*
|
||||||
|
import meghdad.pakkit.core.*
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.lang.ref.WeakReference
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeListener {
|
||||||
|
private lateinit var store: Store
|
||||||
|
private lateinit var column: LinearLayout
|
||||||
|
private lateinit var scroll: RoundScrollView
|
||||||
|
private val colors = BrandPalette.Dark
|
||||||
|
private val io = Executors.newSingleThreadExecutor()
|
||||||
|
private var busy = false
|
||||||
|
private var error: String? = null
|
||||||
|
private var renderedState = ""
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
store = Store(this)
|
||||||
|
acceptIntent(intent)
|
||||||
|
refresh()
|
||||||
|
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
|
||||||
|
}
|
||||||
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
|
outState.putInt("scroll", scroll.scrollY)
|
||||||
|
super.onSaveInstanceState(outState)
|
||||||
|
}
|
||||||
|
override fun onNewIntent(intent: Intent) { super.onNewIntent(intent); setIntent(intent); acceptIntent(intent); refresh() }
|
||||||
|
private fun acceptIntent(intent: Intent) {
|
||||||
|
val job = store.read("incoming")
|
||||||
|
@Suppress("DEPRECATION") val approval = intent.getParcelableExtra<Intent>("approval")
|
||||||
|
if (approval != null && job != null && job.optString("id") == intent.getStringExtra("job") && job.optString("state") == "confirm") {
|
||||||
|
PendingApproval.intent = approval
|
||||||
|
PendingApproval.id = job.getString("id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
PendingApproval.activity = WeakReference(this)
|
||||||
|
store.prefs.registerOnSharedPreferenceChangeListener(this)
|
||||||
|
refresh()
|
||||||
|
io.execute { runCatching { Link.capability(this) } }
|
||||||
|
}
|
||||||
|
override fun onPause() { store.prefs.unregisterOnSharedPreferenceChangeListener(this); PendingApproval.activity = null; super.onPause() }
|
||||||
|
override fun onDestroy() { io.shutdown(); super.onDestroy() }
|
||||||
|
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
|
||||||
|
if (key == "incoming" || key == null) runOnUiThread { refresh() }
|
||||||
|
}
|
||||||
|
private fun dp(n: Int) = Design.dp(this, n)
|
||||||
|
private fun line(value: String, size: Float = 14f, color: Int = colors.text, bold: Boolean = false) = Design.text(this, value, size, color, bold).apply {
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
breakStrategy = android.graphics.text.LineBreaker.BREAK_STRATEGY_BALANCED
|
||||||
|
}
|
||||||
|
private fun add(v: View, top: Int = 0) {
|
||||||
|
column.addView(v, LinearLayout.LayoutParams(-1, v.layoutParams?.height ?: -2).apply { topMargin = dp(top) })
|
||||||
|
}
|
||||||
|
private fun button(label: String, primary: Boolean = true, action: () -> Unit) {
|
||||||
|
add(Design.button(this, label, primary, action).apply {
|
||||||
|
textSize = 15f
|
||||||
|
minHeight = dp(48)
|
||||||
|
isEnabled = !busy
|
||||||
|
}, 10)
|
||||||
|
}
|
||||||
|
private fun parcel(size: Int = 48) {
|
||||||
|
add(ImageView(this).apply {
|
||||||
|
setImageResource(meghdad.pakkit.core.R.drawable.pakkit_icon)
|
||||||
|
scaleType = ImageView.ScaleType.FIT_CENTER
|
||||||
|
layoutParams = LinearLayout.LayoutParams(-1, dp(size))
|
||||||
|
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||||
|
}, 9)
|
||||||
|
}
|
||||||
|
private fun statusIcon(glyph: Glyph, success: Boolean) {
|
||||||
|
add(FrameLayout(this).apply {
|
||||||
|
layoutParams = LinearLayout.LayoutParams(-1, dp(56))
|
||||||
|
addView(ImageView(this@WatchActivity).apply {
|
||||||
|
setImageDrawable(GlyphDrawable(glyph, if (success) colors.mint else colors.error))
|
||||||
|
setPadding(dp(12), dp(12), dp(12), dp(12))
|
||||||
|
background = Design.shape(if (success) colors.mintSoft else colors.errorSoft, dp(24).toFloat())
|
||||||
|
scaleType = ImageView.ScaleType.FIT_CENTER
|
||||||
|
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||||
|
}, FrameLayout.LayoutParams(dp(48), dp(48), Gravity.CENTER))
|
||||||
|
}, 8)
|
||||||
|
}
|
||||||
|
private fun badge(value: String, positive: Boolean = false) {
|
||||||
|
val text = Design.badge(this, value, positive).apply { gravity = Gravity.CENTER }
|
||||||
|
column.addView(text, LinearLayout.LayoutParams(-2, -2).apply { gravity = Gravity.CENTER_HORIZONTAL; topMargin = dp(10) })
|
||||||
|
}
|
||||||
|
fun refresh() {
|
||||||
|
if (isDestroyed || isFinishing) return
|
||||||
|
val job = store.read("incoming")
|
||||||
|
val stateKey = job?.let { "${it.optString("id")}:${it.optString("state")}" } ?: "home"
|
||||||
|
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
|
||||||
|
renderedState = stateKey
|
||||||
|
scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) }
|
||||||
|
val width = resources.configuration.screenWidthDp
|
||||||
|
val side = (width * .15f).roundToInt().coerceAtLeast(26)
|
||||||
|
column = Design.column(this).apply {
|
||||||
|
gravity = Gravity.CENTER_HORIZONTAL
|
||||||
|
setPadding(dp(side), dp(12), dp(side), dp((width * .24f).roundToInt().coerceAtLeast(44)))
|
||||||
|
}
|
||||||
|
scroll.addView(column)
|
||||||
|
add(TextClock(this).apply {
|
||||||
|
format12Hour = "h:mm"; format24Hour = "HH:mm"
|
||||||
|
gravity = Gravity.CENTER; textSize = 12f; setTextColor(colors.secondary)
|
||||||
|
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||||
|
})
|
||||||
|
if (job == null) home() else incoming(job)
|
||||||
|
error?.let { add(line(it, 13f, colors.error), 12) }
|
||||||
|
scroll.isFocusable = true
|
||||||
|
scroll.isFocusableInTouchMode = true
|
||||||
|
setContentView(scroll)
|
||||||
|
scroll.requestFocus()
|
||||||
|
scroll.post { scroll.scrollTo(0, y) }
|
||||||
|
}
|
||||||
|
private fun home() {
|
||||||
|
parcel(54)
|
||||||
|
add(line("Pakkit", 25f, bold = true), 4)
|
||||||
|
add(line(getString(meghdad.pakkit.core.R.string.brand_tagline), 12f, colors.secondary), 5)
|
||||||
|
val supported = Link.installer(this)
|
||||||
|
val allowed = packageManager.canRequestPackageInstalls()
|
||||||
|
when {
|
||||||
|
!supported -> {
|
||||||
|
badge("Use Google Play")
|
||||||
|
add(line("This watch does not expose a system installer.", 13f, colors.secondary), 12)
|
||||||
|
button("Open Google Play") { play() }
|
||||||
|
}
|
||||||
|
allowed -> {
|
||||||
|
badge("Ready to receive", positive = true)
|
||||||
|
add(line("Choose an APK on your phone. Review it here before installing.", 13f, colors.secondary), 12)
|
||||||
|
}
|
||||||
|
Link.settings(this).resolveActivity(packageManager) != null -> {
|
||||||
|
badge("One small permission")
|
||||||
|
add(line("Allow Pakkit to request installs. You still approve every app.", 13f, colors.secondary), 12)
|
||||||
|
button("Allow installs") { settings() }
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
badge("Use Google Play")
|
||||||
|
add(line("External installation is not available on this watch’s software.", 13f, colors.secondary), 12)
|
||||||
|
button("Open Google Play") { play() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
add(line("Optional alerts bring you back to system approval.", 12f, colors.secondary), 18)
|
||||||
|
button("Enable alerts", false) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun incoming(job: JSONObject) {
|
||||||
|
val apk = Apk.from(job.getJSONObject("apk"))
|
||||||
|
val state = job.optString("state")
|
||||||
|
when (state) {
|
||||||
|
"installed" -> statusIcon(Glyph.CHECK, success = true)
|
||||||
|
"failed" -> statusIcon(Glyph.ALERT, success = false)
|
||||||
|
else -> parcel(42)
|
||||||
|
}
|
||||||
|
when (state) {
|
||||||
|
"installed" -> {
|
||||||
|
add(line("All yours.", 25f, bold = true), 5)
|
||||||
|
add(line(apk.label, 17f, bold = true), 10)
|
||||||
|
}
|
||||||
|
"failed" -> {
|
||||||
|
add(line("A small detour.", 22f, bold = true), 5)
|
||||||
|
add(line(apk.label, 16f), 10)
|
||||||
|
}
|
||||||
|
else -> add(line(apk.label, 21f, bold = true), 5)
|
||||||
|
}
|
||||||
|
add(line("${apk.version} · ${"%.1f".format(apk.bytes / 1048576.0)} MB", 12f, colors.secondary), 7)
|
||||||
|
if (busy) add(line("Preparing installer…", 13f, colors.secondary), 12)
|
||||||
|
else if (state == "ready") badge("Ready to install", positive = true)
|
||||||
|
else add(line(job.optString("detail"), 13f, colors.secondary), 12)
|
||||||
|
when (state) {
|
||||||
|
"receiving" -> {
|
||||||
|
add(Design.progress(this).apply { contentDescription = "Receiving and verifying the APK" }, 14)
|
||||||
|
add(line("A final check before it’s yours.", 12f, colors.secondary), 10)
|
||||||
|
}
|
||||||
|
"ready", "failed" -> {
|
||||||
|
if (!TransferRules.fresh(job.optLong("created"), System.currentTimeMillis())) {
|
||||||
|
add(line("This APK expired. Send it again from your phone.", 13f, colors.error), 12)
|
||||||
|
} else if (store.file(job.getString("id")).exists()) {
|
||||||
|
add(line(apk.packageName, 12f, colors.secondary), 12)
|
||||||
|
if (!apk.wear) add(line("Watch support is unverified. The layout may not fit.", 12f, colors.error), 10)
|
||||||
|
add(line("Only install apps you trust.", 13f, colors.secondary), 10)
|
||||||
|
if (packageManager.canRequestPackageInstalls()) button(if (state == "failed") "Try installation" else "Install") { install(job) }
|
||||||
|
else button("Allow installs") { settings() }
|
||||||
|
}
|
||||||
|
button("Dismiss", false) { dismiss(job) }
|
||||||
|
}
|
||||||
|
"confirm" -> {
|
||||||
|
if (PendingApproval.intent != null && PendingApproval.id == job.getString("id")) button("Continue") {
|
||||||
|
val confirm = PendingApproval.intent ?: return@button
|
||||||
|
runCatching { startActivity(confirm) }.onFailure {
|
||||||
|
error = "The system approval screen could not open. Try the installation again."
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
} else add(line("Open the approval notification, or retry if interrupted.", 12f, colors.secondary), 10)
|
||||||
|
button("Retry approval", false) { install(job) }
|
||||||
|
}
|
||||||
|
"installing" -> {
|
||||||
|
add(line("Follow the system approval. If interrupted, you can retry.", 12f, colors.secondary), 10)
|
||||||
|
button("Retry installation", false) { install(job) }
|
||||||
|
}
|
||||||
|
"installed" -> {
|
||||||
|
button("Open app") { launch(apk.packageName) }
|
||||||
|
button("Done", false) { store.clear("incoming"); refresh() }
|
||||||
|
}
|
||||||
|
else -> button("Done") { store.clear("incoming"); refresh() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun settings() {
|
||||||
|
runCatching { startActivity(Link.settings(this)) }.onFailure { error="This watch does not offer that setting. Install compatible apps through Google Play."; refresh() }
|
||||||
|
}
|
||||||
|
private fun install(job:JSONObject) {
|
||||||
|
if(busy) return
|
||||||
|
if(!packageManager.canRequestPackageInstalls()) { settings(); return }
|
||||||
|
busy=true; error=null; refresh()
|
||||||
|
io.execute {
|
||||||
|
val installer=packageManager.packageInstaller
|
||||||
|
var sessionId: Int?=null
|
||||||
|
try {
|
||||||
|
require(TransferRules.fresh(job.getLong("created"),System.currentTimeMillis())) { "This APK expired. Send it again." }
|
||||||
|
val file=store.file(job.getString("id"))
|
||||||
|
val digest=file.inputStream().use { TransferRules.copyBounded(it,object:java.io.OutputStream() { override fun write(b:Int) {} ; override fun write(b:ByteArray,off:Int,len:Int) {} }).second }
|
||||||
|
require(digest==job.getJSONObject("apk").getString("sha256")) { "This APK changed. Send it again." }
|
||||||
|
val apk=Packages.inspect(this,file,digest)
|
||||||
|
Packages.checkForWatch(apk,Build.VERSION.SDK_INT,Build.SUPPORTED_ABIS.toSet(),Packages.free(this))
|
||||||
|
job.optInt("session",-1).takeIf { it>=0 }?.let { runCatching { installer.abandonSession(it) } }
|
||||||
|
val params=PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||||
|
setAppPackageName(apk.packageName); setSize(file.length())
|
||||||
|
setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_REQUIRED)
|
||||||
|
if(Build.VERSION.SDK_INT>=33) setPackageSource(PackageInstaller.PACKAGE_SOURCE_LOCAL_FILE)
|
||||||
|
}
|
||||||
|
sessionId=installer.createSession(params)
|
||||||
|
job.put("session",sessionId)
|
||||||
|
Link.status(this,job,"installing","Waiting for the watch’s system installer.")
|
||||||
|
installer.openSession(sessionId).use { session ->
|
||||||
|
session.openWrite("base.apk",0,file.length()).use { output -> file.inputStream().use { it.copyTo(output,64*1024) }; session.fsync(output) }
|
||||||
|
val callback=Intent(this,InstallReceiver::class.java).putExtra("job",job.getString("id"))
|
||||||
|
val pending=PendingIntent.getBroadcast(this,sessionId,callback,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
|
||||||
|
session.commit(pending.intentSender)
|
||||||
|
}
|
||||||
|
} catch(e:Exception) {
|
||||||
|
sessionId?.let { runCatching { installer.abandonSession(it) } }
|
||||||
|
Link.status(this,job,"failed",e.message ?: "Could not open the system installer. Use Google Play.")
|
||||||
|
}
|
||||||
|
runOnUiThread { busy=false; refresh() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun dismiss(job:JSONObject) {
|
||||||
|
Link.status(this,job,"declined","Dismissed on your watch.")
|
||||||
|
store.file(job.getString("id")).delete(); store.clear("incoming"); refresh()
|
||||||
|
}
|
||||||
|
private fun launch(packageName:String) {
|
||||||
|
runCatching {
|
||||||
|
if(Build.VERSION.SDK_INT>=33) packageManager.getLaunchIntentSenderForPackage(packageName).sendIntent(this,0,null,null,null)
|
||||||
|
else startActivity(packageManager.getLaunchIntentForPackage(packageName) ?: error("No launcher"))
|
||||||
|
}.onFailure { error="This app has no available watch launcher. Look in your watch’s app list."; refresh() }
|
||||||
|
}
|
||||||
|
private fun play() {
|
||||||
|
runCatching { startActivity(Intent(Intent.ACTION_VIEW,Uri.parse("market://search?q=wear%20os&c=apps"))) }
|
||||||
|
.onFailure { error="Open Google Play from your watch’s app list."; refresh() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@array/android_wear_capabilities"/>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<resources><style name="Theme.Pakkit.Wear" 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:windowLightStatusBar">false</item><item name="android:windowSplashScreenBackground">#090B17</item><item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
|
||||||
|
</style></resources>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<resources xmlns:tools="http://schemas.android.com/tools"><string-array name="android_wear_capabilities" translatable="false" tools:ignore="Typos,UnusedResources"><item>pakkit_watch_v1</item></string-array></resources>
|
||||||