Add a Wear OS recording tile with Spatial-style controls

This commit is contained in:
Meghdad committed 2026-10-14 22:49:29 +03:30
1 parent 1487d65fbd
commit bf5d92f430
30 files changed
+1141 -25

No files matched your search

+5
View File
@@ -35,6 +35,11 @@ android {
}
dependencies {
implementation(libs.wear.tiles)
implementation(libs.wear.protolayout)
implementation(libs.wear.protolayout.expression)
implementation(libs.concurrent.futures)
androidTestImplementation(libs.wear.tiles.renderer)
implementation(libs.jsch)
implementation(libs.bcprov)
testImplementation(libs.junit)
@@ -0,0 +1,75 @@
package meghdad.remember
import android.content.res.Configuration
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.wear.protolayout.LayoutElementBuilders
import androidx.wear.tiles.renderer.TileRenderer
import com.google.common.util.concurrent.ListenableFuture
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
class RecordingTileLayoutTest {
@Test fun controlsAndLargeMinuteValuesFitSmallAndLargeRoundViewports() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
for (size in listOf(192, 227)) {
val base = instrumentation.targetContext
val context = base.createConfigurationContext(Configuration(base.resources.configuration).apply { screenWidthDp = size })
for (state in listOf(RecordingTileState(), RecordingTileState("clip", true, 7_205_000, 12, 3), RecordingTileState("clip", true, 86_400_000, 0, 1))) {
lateinit var parent: FrameLayout
lateinit var future: ListenableFuture<View>
instrumentation.runOnMainSync {
parent = FrameLayout(context)
// Renderer resources live in the test APK, while the layout uses app strings.
val renderer = TileRenderer(instrumentation.context, context.mainExecutor) { }
val layout = LayoutElementBuilders.Layout.Builder()
.setRoot(RecordingTileLayout(context, RecordingTileActions()).build(state)).build()
future = renderer.inflateAsync(layout, RecordingTileArtwork.resources, parent)
}
val view = future.get(10, TimeUnit.SECONDS)
instrumentation.runOnMainSync {
val pixels = (size * context.resources.displayMetrics.density).toInt()
parent.measure(View.MeasureSpec.makeMeasureSpec(pixels, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(pixels, View.MeasureSpec.EXACTLY))
parent.layout(0, 0, pixels, pixels)
fun descendants(node: View): List<View> = listOf(node) + if (node is ViewGroup) (0 until node.childCount).flatMap { descendants(node.getChildAt(it)) } else emptyList()
val all = descendants(view)
val controls = all.filter { it.isClickable }
assertEquals(if (state.active) 4 else 2, controls.size)
controls.forEach { control ->
val bounds = android.graphics.Rect(0, 0, control.width, control.height)
parent.offsetDescendantRectToMyCoords(control, bounds)
assertTrue("Control outside $size dp viewport: $bounds", bounds.left >= 0 && bounds.top >= 0 && bounds.right <= pixels && bounds.bottom <= pixels)
val minimum = (48 * context.resources.displayMetrics.density).toInt()
assertTrue("Tap target too small", bounds.width() >= minimum && bounds.height() >= minimum)
assertFalse("Missing spoken description", control.contentDescription.isNullOrEmpty())
if (control.contentDescription.toString() in listOf("Resume", "Mark", "Save", "Record")) {
// Buttons are capsules: both rounded ends must fit inside the watch circle.
val radius = bounds.height() / 2.0
for (x in listOf(bounds.left + radius, bounds.right - radius)) {
val distance = kotlin.math.hypot(x - pixels / 2.0, bounds.exactCenterY() - pixels / 2.0)
assertTrue("Button clipped by round screen at $size dp: $bounds", distance + radius <= pixels / 2.0 + 1)
}
}
}
val texts = all.filterIsInstance<TextView>()
assertTrue(controls.any { it.contentDescription?.toString()?.contains(state.time) == true })
val images = all.filterIsInstance<ImageView>()
assertEquals(1 + (state.elapsedMillis / 60_000).toString().length, images.size)
assertTrue("Original numeral artwork must render", images.all { it.drawable != null })
assertFalse("No caption or duplicate digital timer below the numeral", texts.any { it.text.toString().contains(":") })
texts.forEach { text ->
assertTrue("Text is clipped: ${text.text}", text.layout != null && (0 until text.layout.lineCount).all { text.layout.getEllipsisCount(it) == 0 })
}
}
}
}
}
}
@@ -0,0 +1,75 @@
package meghdad.remember
import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
/** Requires a fresh disposable watch emulator with microphone permission still ungranted. */
@RunWith(AndroidJUnit4::class)
class RecordingTilePermissionTest {
@Test fun tileRequestsMicrophonePermissionAndDenialNeverStartsRecording() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val automation = instrumentation.uiAutomation
assertNull(RecordingService.activeId)
assumeTrue("Run the permission flow before other recording tests on a fresh disposable watch",
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED)
val activity = context.packageManager.getActivityInfo(ComponentName(context, TileRecordingActivity::class.java), 0)
assertEquals("com.google.android.wearable.permission.BIND_TILE_PROVIDER", activity.permission)
fun shell(command: String) = automation.executeShellCommand(command).use {
android.os.ParcelFileDescriptor.AutoCloseInputStream(it).bufferedReader().readText()
}
fun nodes(root: AccessibilityNodeInfo? = automation.rootInActiveWindow): List<AccessibilityNodeInfo> =
if (root == null) emptyList() else listOf(root) + (0 until root.childCount).flatMap { nodes(root.getChild(it)) }
fun await(condition: () -> Boolean) {
val end = SystemClock.elapsedRealtime() + 10_000
while (!condition() && SystemClock.elapsedRealtime() < end) SystemClock.sleep(100)
assertTrue("Permission flow did not reach the expected state", condition())
}
fun record() = nodes().firstOrNull { it.contentDescription?.toString() == "Record" && it.isClickable }
fun permissionButton(id: String): AccessibilityNodeInfo? {
nodes().firstOrNull { it.viewIdResourceName?.endsWith(":id/$id") == true }?.let { return it }
// Wear OS 7 renders permission choices with Compose instead of resource IDs.
val labels = if (id == "permission_deny_button") listOf("Don’t allow", "Don't allow")
else listOf("While using app", "While using the app")
var node = nodes().firstOrNull { it.packageName == "com.google.android.permissioncontroller" && it.text?.toString() in labels }
while (node != null && !node.isClickable) node = node.parent
return node
}
val store = Recordings(context)
val existing = store.list().map { it.id }.toSet()
try {
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile --ecn component meghdad.remember/meghdad.remember.RecordingTileService")
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0")
await { record() != null }
assertTrue(record()!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { permissionButton("permission_deny_button") != null }
assertNull(RecordingService.activeId)
assertTrue(permissionButton("permission_deny_button")!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { record() != null }
assertNull(RecordingService.activeId)
assertTrue(record()!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { permissionButton("permission_allow_foreground_only_button") != null }
assertNull(RecordingService.activeId)
assertTrue(permissionButton("permission_allow_foreground_only_button")!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { RecordingService.activeId != null && RecordingService.elapsed > 1200 }
// Returning to the carousel must happen automatically, without opening MainActivity.
await { nodes().any { it.contentDescription?.toString() == "Pause" && it.isClickable } }
} finally {
if (RecordingService.activeId != null) {
instrumentation.runOnMainSync { context.startService(Intent(context, RecordingService::class.java).setAction(RecordingService.SAVE)) }
await { RecordingService.activeId == null }
}
store.list().filter { it.id !in existing }.forEach { store.delete(it) }
}
}
}
@@ -0,0 +1,145 @@
package meghdad.remember
import android.Manifest
import android.content.Intent
import android.media.MediaMetadataRetriever
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
/** Run only on a disposable Wear OS emulator; exercises the actual system tile host. */
@RunWith(AndroidJUnit4::class)
class RecordingTileTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = instrumentation.targetContext
private val automation = instrumentation.uiAutomation
private fun shell(command: String): String = automation.executeShellCommand(command).use {
android.os.ParcelFileDescriptor.AutoCloseInputStream(it).bufferedReader().readText()
}
private fun await(condition: () -> Boolean) {
val end = SystemClock.elapsedRealtime() + 10_000
while (!condition() && SystemClock.elapsedRealtime() < end) SystemClock.sleep(100)
assertTrue("Tile or recorder did not reach expected state", condition())
}
private fun nodes(root: AccessibilityNodeInfo? = automation.rootInActiveWindow): List<AccessibilityNodeInfo> =
if (root == null) emptyList() else listOf(root) + (0 until root.childCount).flatMap { nodes(root.getChild(it)) }
private fun control(label: String) = nodes().firstOrNull { it.contentDescription?.toString() == label && it.isClickable }
private fun click(label: String) {
await { control(label) != null }
assertTrue(control(label)!!.performAction(AccessibilityNodeInfo.ACTION_CLICK))
}
private fun clock() = nodes().mapNotNull { node ->
Regex("[0-9]+:[0-9]{2}").find(node.contentDescription?.toString().orEmpty())?.value
}.firstOrNull()
private fun screenshot(name: String) {
automation.waitForIdle(400, 5000)
val bitmap = automation.takeScreenshot() ?: error("No screenshot")
File(context.getExternalFilesDir(null), name).outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
}
@Test fun minuteArtworkAdvancesInTheActualCarousel() {
assertNull("Use a disposable emulator without an active recording", RecordingService.activeId)
val preferences = RecordingPreferences(context)
val previous = preferences.read()
val store = Recordings(context)
val existing = store.list().map { it.id }.toSet()
try {
preferences.write(RecordingLimit())
automation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile --ecn component meghdad.remember/meghdad.remember.RecordingTileService")
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0")
click("Record")
await { RecordingService.activeId != null && control("Pause") != null }
assertTrue(nodes().any { it.stateDescription?.toString() == "0 minutes" })
val end = SystemClock.elapsedRealtime() + 70_000
while (RecordingService.elapsed < 61_000 && SystemClock.elapsedRealtime() < end) SystemClock.sleep(200)
assertTrue(RecordingService.elapsed >= 61_000)
await { nodes().any { it.stateDescription?.toString() == "1 minute" } }
screenshot("tile-one-minute.png")
click("Save")
await { RecordingService.activeId == null }
} finally {
if (RecordingService.activeId != null) {
instrumentation.runOnMainSync { context.startService(Intent(context, RecordingService::class.java).setAction(RecordingService.SAVE)) }
await { RecordingService.activeId == null }
}
preferences.write(previous)
store.list().filter { it.id !in existing }.forEach { store.delete(it) }
}
}
@Test fun carouselStartsAndControlsRecordingOnlyAfterAnExplicitTap() {
assertNull("Use a disposable emulator without an active recording", RecordingService.activeId)
val preferences = RecordingPreferences(context)
val previous = preferences.read()
val store = Recordings(context)
val existing = store.list().map { it.id }.toSet()
try {
preferences.write(RecordingLimit())
automation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
assertTrue(shell("am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile --ecn component meghdad.remember/meghdad.remember.RecordingTileService").contains("result=1"))
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0")
await { control("Record") != null }
assertNull(RecordingService.activeId)
screenshot("tile-idle.png")
click("Record")
await { RecordingService.activeId != null && RecordingService.elapsed > 1200 }
val id = RecordingService.activeId!!
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0")
await { control("Pause") != null && clock() != null }
val initial = clock()
SystemClock.sleep(2200)
assertNotEquals("The host should advance the timer without another app request", initial, clock())
screenshot("tile-recording.png")
click("Pause")
await { RecordingService.paused && control("Resume") != null }
val pausedTime = RecordingService.elapsed
val pausedClock = clock()
SystemClock.sleep(1300)
assertEquals(pausedTime, RecordingService.elapsed)
assertEquals(pausedClock, clock())
click("Mark")
await { RecordingService.marks.size == 1 }
assertEquals(listOf(pausedTime), RecordingService.marks)
screenshot("tile-paused.png")
// An already-paused command must not toggle back into capture.
instrumentation.runOnMainSync { RecordingService.tileCommand(id, TileRecordingAction.PAUSE) }
assertTrue(RecordingService.paused)
click("Resume")
await { !RecordingService.paused && RecordingService.elapsed > pausedTime + 300 }
shell("input keyevent 223") // Screen off must not end recording.
val beforeSleep = RecordingService.elapsed
SystemClock.sleep(1200)
assertTrue(RecordingService.elapsed > beforeSleep + 800)
shell("input keyevent 224")
shell("am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0")
click("Save")
await { RecordingService.activeId == null && control("Record") != null }
val saved = store.list().first { it.id == id }
assertEquals(listOf(pausedTime), saved.marks)
MediaMetadataRetriever().also { retriever ->
try {
retriever.setDataSource(store.audio(id).absolutePath)
assertTrue(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toLong() > 1000)
} finally { retriever.release() }
}
// A queued command for the previous clip must not save the next one.
click("Record")
await { RecordingService.activeId != null && RecordingService.elapsed > 1200 }
val nextId = RecordingService.activeId
instrumentation.runOnMainSync { RecordingService.tileCommand(id, TileRecordingAction.SAVE) }
assertEquals(nextId, RecordingService.activeId)
} finally {
if (RecordingService.activeId != null) {
instrumentation.runOnMainSync { context.startService(Intent(context, RecordingService::class.java).setAction(RecordingService.SAVE)) }
await { RecordingService.activeId == null }
}
preferences.write(previous)
store.list().filter { it.id !in existing }.forEach { store.delete(it) }
}
}
}
@@ -0,0 +1,58 @@
package meghdad.remember
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.wear.protolayout.LayoutElementBuilders.*
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RecordingTileTimelineTest {
private fun serializedSize(value: Any): Int {
// Proto implementation classes are runtime-only dependencies of the public builders.
val proto = value.javaClass.getMethod("toProto").invoke(value)
return proto.javaClass.getMethod("getSerializedSize").invoke(proto) as Int
}
private fun descendants(element: LayoutElement): List<LayoutElement> = listOf(element) + when (element) {
is Box -> element.contents.flatMap(::descendants)
is Column -> element.contents.flatMap(::descendants)
is Row -> element.contents.flatMap(::descendants)
else -> emptyList()
}
@Test fun minuteArtworkCrossesDigitBoundariesWithoutExpiringCurrentControls() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val actions = RecordingTileActions(3)
val now = 1_800_000_000_000L
val state = RecordingTileState("clip", false, 599_000, 2, 1)
val tile = RecordingTilePresentation.tile(context, state, actions, now)
val entries = tile.tileTimeline!!.timelineEntries
assertEquals(61, entries.size)
assertNull(entries.first().validity) // Honest dynamic fallback beyond the cached artwork hour.
assertEquals(now + 1000, entries[1].validity!!.endMillis)
assertEquals(entries[1].validity!!.endMillis, entries[2].validity!!.startMillis)
fun numeral(index: Int) = descendants(entries[index].layout!!.root!!).filterIsInstance<Image>()
.mapNotNull { it.resourceId?.value?.takeIf { id -> id.startsWith("digit-") } }.joinToString("") { it.removePrefix("digit-") }
assertEquals("9", numeral(1))
assertEquals("10", numeral(2))
assertEquals("68", numeral(60))
fun commands(index: Int) = descendants(entries[index].layout!!.root!!).filterIsInstance<Box>()
.mapNotNull { it.modifiers?.clickable?.id }.filter { it != "refresh" }.toSet()
assertEquals(3, commands(1).size)
assertEquals(commands(1), commands(60))
commands(1).forEach { token ->
assertNotNull("Generating future frames must not evict current controls", actions.consume(token, "clip"))
assertNull(actions.consume(token, "clip"))
}
assertTrue("Keep the tile response comfortably below the Binder limit", serializedSize(tile) < 700_000)
assertTrue(serializedSize(RecordingTileArtwork.resources) < 200_000)
}
@Test fun pausedAndIdleTilesKeepOneStaticMinuteArtworkFrame() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
for (state in listOf(RecordingTileState(), RecordingTileState("clip", true, 7_205_000, 3, 2))) {
val tile = RecordingTilePresentation.tile(context, state, RecordingTileActions())
assertEquals(1, tile.tileTimeline!!.timelineEntries.size)
assertNull(tile.tileTimeline!!.timelineEntries.single().validity)
}
}
}
+15 -1
View File
@@ -1,5 +1,5 @@
<?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" xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.type.watch" />
<uses-feature android:name="android.hardware.microphone" android:required="true" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -19,6 +19,20 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Keep this activity alive while the full-screen microphone permission prompt is open.
It excludes itself from Recents and finishes as soon as capture starts. -->
<activity android:name=".TileRecordingActivity" android:exported="true" tools:ignore="WearRecents"
android:permission="com.google.android.wearable.permission.BIND_TILE_PROVIDER"
android:excludeFromRecents="true" android:taskAffinity="" android:theme="@style/Theme.Remember.TileStart" />
<service android:name=".RecordingTileService" android:exported="true"
android:label="@string/tile_label" android:description="@string/tile_description"
android:icon="@drawable/ic_remember"
android:permission="com.google.android.wearable.permission.BIND_TILE_PROVIDER">
<intent-filter>
<action android:name="androidx.wear.tiles.action.BIND_TILE_PROVIDER" />
</intent-filter>
<meta-data android:name="androidx.wear.tiles.PREVIEW" android:resource="@drawable/tile_preview" />
</service>
<service android:name=".RecordingService" android:exported="false" android:foregroundServiceType="microphone" />
<activity android:name=".BackupActivity" android:exported="false" android:taskAffinity="" android:windowSoftInputMode="stateAlwaysHidden|adjustResize" />
<service android:name=".BackupWorker" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true" />
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -13,7 +13,7 @@ class MinuteCounterView(context: Context) : View(context) {
style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND; strokeWidth = 30f
}
private val digits = (0..9).map { digitPath(it) }
private val digits = (0..9).map { MinuteNumeralArtwork.path(it) }
private var elapsed = 0L
private var saved = false
private var floating = false
@@ -62,21 +62,4 @@ class MinuteCounterView(context: Context) : View(context) {
paint.shader = null
canvas.restore()
}
private fun digitPath(digit: Int) = Path().apply {
when (digit) {
0 -> addRoundRect(RectF(23f, 25f, 73f, 125f), 25f, 25f, Path.Direction.CW)
1 -> { moveTo(31f, 43f); lineTo(58f, 25f); lineTo(58f, 125f) }
2 -> { moveTo(23f, 41f); cubicTo(27f, 14f, 73f, 17f, 73f, 47f); cubicTo(73f, 65f, 47f, 82f, 24f, 112f); quadTo(19f, 125f, 32f, 125f); lineTo(75f, 125f) }
3 -> { moveTo(24f, 29f); cubicTo(77f, 7f, 90f, 72f, 48f, 73f); cubicTo(94f, 75f, 76f, 142f, 23f, 121f) }
4 -> { moveTo(52f, 25f); lineTo(22f, 84f); quadTo(17f, 92f, 29f, 92f); lineTo(77f, 92f); moveTo(66f, 25f); lineTo(66f, 125f) }
5 -> { moveTo(73f, 25f); lineTo(26f, 25f); lineTo(23f, 70f); cubicTo(84f, 45f, 96f, 141f, 24f, 121f) }
6 -> { moveTo(68f, 26f); cubicTo(21f, 14f, 15f, 72f, 24f, 106f); cubicTo(35f, 145f, 86f, 125f, 72f, 89f); cubicTo(62f, 65f, 28f, 73f, 22f, 92f) }
7 -> { moveTo(22f, 25f); lineTo(76f, 25f); lineTo(31f, 125f) }
8 -> {
addRoundRect(RectF(25f, 24f, 71f, 74f), 23f, 23f, Path.Direction.CW)
addRoundRect(RectF(22f, 74f, 74f, 126f), 26f, 26f, Path.Direction.CW)
}
9 -> { moveTo(27f, 124f); cubicTo(75f, 139f, 84f, 79f, 72f, 44f); cubicTo(57f, 6f, 10f, 28f, 25f, 64f); cubicTo(36f, 87f, 69f, 77f, 75f, 61f) }
}
}
}
@@ -0,0 +1,25 @@
package meghdad.remember
import android.graphics.Path
import android.graphics.RectF
/** Shared original rounded numeral paths for the app and its recording tile. */
internal object MinuteNumeralArtwork {
fun path(digit: Int) = Path().apply {
when (digit) {
0 -> addRoundRect(RectF(23f, 25f, 73f, 125f), 25f, 25f, Path.Direction.CW)
1 -> { moveTo(31f, 43f); lineTo(58f, 25f); lineTo(58f, 125f) }
2 -> { moveTo(23f, 41f); cubicTo(27f, 14f, 73f, 17f, 73f, 47f); cubicTo(73f, 65f, 47f, 82f, 24f, 112f); quadTo(19f, 125f, 32f, 125f); lineTo(75f, 125f) }
3 -> { moveTo(24f, 29f); cubicTo(77f, 7f, 90f, 72f, 48f, 73f); cubicTo(94f, 75f, 76f, 142f, 23f, 121f) }
4 -> { moveTo(52f, 25f); lineTo(22f, 84f); quadTo(17f, 92f, 29f, 92f); lineTo(77f, 92f); moveTo(66f, 25f); lineTo(66f, 125f) }
5 -> { moveTo(73f, 25f); lineTo(26f, 25f); lineTo(23f, 70f); cubicTo(84f, 45f, 96f, 141f, 24f, 121f) }
6 -> { moveTo(68f, 26f); cubicTo(21f, 14f, 15f, 72f, 24f, 106f); cubicTo(35f, 145f, 86f, 125f, 72f, 89f); cubicTo(62f, 65f, 28f, 73f, 22f, 92f) }
7 -> { moveTo(22f, 25f); lineTo(76f, 25f); lineTo(31f, 125f) }
8 -> {
addRoundRect(RectF(25f, 24f, 71f, 74f), 23f, 23f, Path.Direction.CW)
addRoundRect(RectF(22f, 74f, 74f, 126f), 26f, 26f, Path.Direction.CW)
}
9 -> { moveTo(27f, 124f); cubicTo(75f, 139f, 84f, 79f, 72f, 44f); cubicTo(57f, 6f, 10f, 28f, 25f, 64f); cubicTo(36f, 87f, 69f, 77f, 75f, 61f) }
}
}
}
@@ -1,6 +1,9 @@
package meghdad.remember
import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.IntentFilter
import android.content.Intent
import android.content.pm.ServiceInfo
import android.media.MediaRecorder
@@ -17,6 +20,31 @@ class RecordingService : Service() {
@Volatile var marks: List<Long> = emptyList(); private set
@Volatile var part = 1; private set
var message: String? = null
private var running: RecordingService? = null
// Tile callbacks and recorder commands share the main thread.
internal fun tileState(): RecordingTileState = running?.let { service ->
if (service.recorder == null) RecordingTileState() else RecordingTileState(
activeId, paused, service.capturedTime(), marks.size, part,
)
} ?: RecordingTileState()
internal fun tileCommand(clipId: String, action: TileRecordingAction) {
val service = running ?: return
if (activeId != clipId || service.recorder == null || service.transitioning) return
try {
when (action) {
TileRecordingAction.PAUSE -> if (!paused) service.togglePause()
TileRecordingAction.RESUME -> if (paused) service.togglePause()
TileRecordingAction.MARK -> service.addMark()
TileRecordingAction.SAVE -> service.finishRecording()
}
} catch (_: Exception) {
message = "Recording interrupted. Please try again."
service.release(); service.stopSelf()
}
}
const val START = "start"
const val PAUSE = "pause"
const val SAVE = "save"
@@ -49,13 +77,28 @@ class RecordingService : Service() {
}
}
}
private val clockChanges = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { refreshTile() }
}
override fun onCreate() {
super.onCreate()
running = this
registerReceiver(clockChanges, IntentFilter(Intent.ACTION_TIME_CHANGED))
}
private fun refreshTile() = RecordingTileService.refresh(this)
private fun addMark() {
if (recorder != null && !transitioning) {
marks = marks + capturedTime()
refreshTile()
}
}
override fun onBind(intent: Intent?) = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
try {
when (intent?.action) {
START -> if (recorder == null) begin()
PAUSE -> togglePause()
MARK -> if (recorder != null && !transitioning) marks = marks + capturedTime()
MARK -> addMark()
SAVE -> if (recorder != null) finishRecording() else stopSelf()
}
} catch (_: Exception) {
@@ -107,6 +150,7 @@ class RecordingService : Service() {
// During rollover the old ID stays visible until the new recorder is ready.
activeId = id
handler.post(tick)
refreshTile()
}
private fun togglePause() {
val current = recorder ?: return
@@ -116,6 +160,7 @@ class RecordingService : Service() {
current.pause(); accumulated += SystemClock.elapsedRealtime() - segmentStart
elapsed = accumulated; paused = true
}
refreshTile()
}
private fun saveClip(): Boolean {
val current = recorder ?: return false
@@ -163,6 +208,12 @@ class RecordingService : Service() {
lock?.let { if (it.isHeld) it.release() }; lock = null
activeId = null; paused = false; amplitude = 0
stopForeground(STOP_FOREGROUND_REMOVE)
refreshTile()
}
override fun onDestroy() {
if (recorder != null) finishRecording()
if (running === this) running = null
unregisterReceiver(clockChanges)
super.onDestroy()
}
override fun onDestroy() { if (recorder != null) finishRecording(); super.onDestroy() }
}
@@ -0,0 +1,44 @@
package meghdad.remember
import android.graphics.*
import androidx.wear.protolayout.ResourceBuilders
import java.io.ByteArrayOutputStream
/** Small, process-cached resources drawn from the same original paths as MinuteCounterView. */
internal object RecordingTileArtwork {
const val VERSION = "recording-spatial-1"
val resources: ResourceBuilders.Resources by lazy {
ResourceBuilders.Resources.Builder().setVersion(VERSION).apply {
for (digit in 0..9) addIdToImageMapping("digit-$digit", image(160, 240) { canvas ->
canvas.scale(1.6f, 1.6f)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE; strokeWidth = 30f
strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND
shader = LinearGradient(0f, 15f, 75f, 143f,
intArrayOf(Color.rgb(145, 157, 126), Color.rgb(197, 211, 155), Color.rgb(204, 235, 40), Color.rgb(162, 203, 0)),
floatArrayOf(0f, .3f, .5f, 1f), Shader.TileMode.CLAMP)
}
canvas.drawPath(MinuteNumeralArtwork.path(digit), paint)
})
addIdToImageMapping("dial", image(300, 300) { canvas ->
canvas.drawPaint(Paint().apply {
shader = RadialGradient(195f, 90f, 240f,
intArrayOf(Color.rgb(48, 57, 35), Color.rgb(22, 29, 18), Color.rgb(13, 17, 11)),
floatArrayOf(0f, .65f, 1f), Shader.TileMode.CLAMP)
})
})
}.build()
}
private fun image(width: Int, height: Int, draw: (Canvas) -> Unit): ResourceBuilders.ImageResource {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
return try {
draw(Canvas(bitmap))
val output = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
ResourceBuilders.ImageResource.Builder().setInlineResource(ResourceBuilders.InlineImageResource.Builder()
.setData(output.toByteArray()).setFormat(ResourceBuilders.IMAGE_FORMAT_UNDEFINED)
.setWidthPx(width).setHeightPx(height).build()).build()
} finally { bitmap.recycle() }
}
}
@@ -0,0 +1,123 @@
package meghdad.remember
import android.content.Context
import androidx.wear.protolayout.ActionBuilders
import androidx.wear.protolayout.ColorBuilders.argb
import androidx.wear.protolayout.DimensionBuilders.*
import androidx.wear.protolayout.LayoutElementBuilders.*
import androidx.wear.protolayout.ModifiersBuilders.*
import androidx.wear.protolayout.TypeBuilders
import androidx.wear.protolayout.expression.DynamicBuilders.DynamicInstant
import androidx.wear.protolayout.expression.DynamicBuilders.DynamicInt32.IntFormatter
import androidx.wear.protolayout.expression.DynamicBuilders.DynamicString
import java.time.Instant
import kotlin.math.min
/** Spatial home-screen composition, expressed as a system-rendered tile. */
internal class RecordingTileLayout(private val context: Context, private val actions: RecordingTileActions) {
private val commands = mutableMapOf<TileRecordingAction, Clickable>()
private val lime = 0xffc7ea18.toInt()
fun build(state: RecordingTileState, displayedMinutes: Long = state.elapsedMillis / 60_000,
anchorMillis: Long = System.currentTimeMillis() - state.elapsedMillis, originalArtwork: Boolean = true): LayoutElement {
val size = context.resources.configuration.screenWidthDp.coerceIn(180, 260).toFloat()
val compact = size <= 200
val width = size * .74f
val root = Box.Builder().setWidth(expand()).setHeight(expand())
.setModifiers(Modifiers.Builder().setBackground(Background.Builder().setColor(argb(0xff0d110b.toInt())).build()).build())
.addContent(Image.Builder().setResourceId("dial").setWidth(expand()).setHeight(expand()).build())
val duration = if (state.active && !state.paused) DynamicInstant.withSecondsPrecision(Instant.ofEpochMilli(anchorMillis))
.durationUntil(DynamicInstant.platformTimeWithSecondsPrecision()) else null
val seconds = DegreesProp.Builder(if (state.active) (state.elapsedMillis % 60_000) / 1000f * 3f else 0f)
duration?.let { seconds.setDynamicValue(it.secondsPart.asFloat().times(3f)) }
// A thick, flat-ended arc reaches the center, forming the home's half-dial seconds sweep.
root.addContent(Box.Builder().setWidth(dp(size * .98f)).setHeight(dp(size * .98f))
.addContent(Arc.Builder().setAnchorAngle(degrees(0f)).setAnchorType(ARC_ANCHOR_START)
.addContent(ArcLine.Builder().setLength(seconds.build()).setThickness(dp(size * .49f))
.setLayoutConstraintsForDynamicLength(AngularLayoutConstraint.Builder(180f).setAngularAlignment(ANGULAR_ALIGNMENT_START).build())
.setStrokeCap(STROKE_CAP_BUTT).setColor(argb(0x209cae69)).build()).build()).build())
// The side instruments represent capture/paused state and the current bookmark count.
root.addContent(edge(size, 58f, 64f, 0xff3d492a.toInt()))
for (i in 0..11) {
root.addContent(edge(size, 301f - i * 5.3f, 2.4f, if (state.active && !state.paused) lime else 0xff3d492a.toInt()))
if (i < state.bookmarks) root.addContent(edge(size, 58f + i * 5.3f, 2.4f, 0xffe4edce.toInt()))
}
val clockDescription = TypeBuilders.StringProp.Builder(context.getString(R.string.tile_timer_description, state.time))
val digits = IntFormatter.Builder().setMinIntegerDigits(2).setGroupingUsed(false).build()
// Build one compact expression for the spoken timer; it also makes tap-to-refresh useful on older hosts.
if (duration != null) clockDescription.setDynamicValue(duration.toIntMinutes().format(digits)
.concat(DynamicString.constant(":"))
.concat(duration.secondsPart.format(digits)))
val counterSemantics = Semantics.Builder().setContentDescription(clockDescription.build())
if (originalArtwork) counterSemantics.setStateDescription(TypeBuilders.StringProp.Builder(
context.resources.getQuantityString(R.plurals.tile_minutes, displayedMinutes.toInt(), displayedMinutes)).build())
val numeral = Box.Builder().setWidth(dp(size * .74f)).setHeight(dp(size * .76f))
.setModifiers(Modifiers.Builder().setClickable(Clickable.Builder().setId("refresh")
.setOnClick(ActionBuilders.LoadAction.Builder().build()).build())
.setSemantics(counterSemantics.build())
.setTransformation(Transformation.Builder().setTranslationX(dp(size * .02f)).setTranslationY(dp(-size * .025f)).build()).build())
if (originalArtwork) {
val number = displayedMinutes.toString()
val scale = min(size * .67f / (number.length * 100f - 4f), size * .73f / 150f)
val row = Row.Builder().setVerticalAlignment(VERTICAL_ALIGN_CENTER)
number.forEach { row.addContent(Image.Builder().setResourceId("digit-$it")
.setWidth(dp(100f * scale)).setHeight(dp(150f * scale)).build()) }
numeral.addContent(row.build())
} else {
// A dynamic fallback keeps the value honest if a host retains a tile beyond its artwork timeline.
val minutes = TypeBuilders.StringProp.Builder(displayedMinutes.toString())
duration?.let { minutes.setDynamicValue(it.toIntMinutes().format()) }
numeral.addContent(Text.Builder().setText(minutes.build())
.setLayoutConstraintsForDynamicText(TypeBuilders.StringLayoutConstraint.Builder("8888").build())
.setFontStyle(FontStyle.Builder().setSize(sp(48f)).setWeight(FONT_WEIGHT_BOLD).setColor(argb(lime)).build()).build())
}
root.addContent(numeral.build())
val statusLabel = context.getString(if (!state.active) R.string.tile_brand else if (state.paused) R.string.tile_paused else R.string.tile_recording)
val status = Text.Builder().setText(statusLabel).setFontStyle(FontStyle.Builder().setSize(sp(10f))
.setLetterSpacing(em(if (state.active) 0f else .2f)).setColor(argb(if (state.active) lime else 0xffffffff.toInt())).build())
if (state.active) status.setModifiers(Modifiers.Builder().setSemantics(Semantics.Builder().setContentDescription(
statusLabel + ". " + context.getString(R.string.tile_details, state.part,
context.resources.getQuantityString(R.plurals.tile_bookmarks, state.bookmarks, state.bookmarks))).build()).build())
val controls = Column.Builder().setWidth(dp(width)).setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER)
.addContent(status.build())
.addContent(gap(if (compact) 38f else 62f))
if (state.active) {
val pause = if (state.paused) TileRecordingAction.RESUME else TileRecordingAction.PAUSE
controls.addContent(Row.Builder().addContent(button(context.getString(if (state.paused) R.string.tile_resume else R.string.tile_pause),
command(state, pause), false, (width - 6f) / 2))
.addContent(Spacer.Builder().setWidth(dp(6f)).build())
.addContent(button(context.getString(R.string.tile_mark), command(state, TileRecordingAction.MARK), false, (width - 6f) / 2)).build())
.addContent(gap(if (compact) 4f else 6f))
.addContent(button(context.getString(R.string.tile_save), command(state, TileRecordingAction.SAVE), true, width))
} else controls.addContent(button(context.getString(R.string.tile_start), Clickable.Builder().setId("start")
.setOnClick(ActionBuilders.LaunchAction.Builder().setAndroidActivity(ActionBuilders.AndroidActivity.Builder()
.setPackageName(context.packageName).setClassName(TileRecordingActivity::class.java.name).build()).build()).build(), true, width))
root.addContent(Box.Builder().setWidth(expand()).setHeight(expand()).setVerticalAlignment(VERTICAL_ALIGN_TOP)
.setModifiers(Modifiers.Builder().setPadding(Padding.Builder().setTop(dp(if (compact) 12f else 16f)).build()).build())
.addContent(controls.build()).build())
return root.build()
}
private fun command(state: RecordingTileState, action: TileRecordingAction) = commands.getOrPut(action) {
Clickable.Builder().setId(actions.issue(state.clipId!!, action)).setOnClick(ActionBuilders.LoadAction.Builder().build()).build()
}
private fun edge(size: Float, angle: Float, length: Float, color: Int) = Box.Builder()
.setWidth(dp(size * .92f)).setHeight(dp(size * .92f)).addContent(Arc.Builder()
.setAnchorAngle(degrees(angle)).setAnchorType(ARC_ANCHOR_START)
.addContent(ArcLine.Builder().setLength(degrees(length)).setThickness(dp(size * .014f)).setColor(argb(color)).build()).build()).build()
private fun text(value: String, size: Float, color: Int) = Text.Builder().setText(value)
.setFontStyle(FontStyle.Builder().setSize(sp(size)).setColor(argb(color)).build()).setMaxLines(1).build()
private fun gap(height: Float) = Spacer.Builder().setHeight(dp(height)).build()
private fun button(label: String, click: Clickable, primary: Boolean, width: Float) = Box.Builder()
.setWidth(dp(width)).setHeight(dp(48f))
.setModifiers(Modifiers.Builder().setClickable(click)
.setSemantics(Semantics.Builder().setRole(SEMANTICS_ROLE_BUTTON).setContentDescription(label).build())
.setBorder(Border.Builder().setWidth(dp(if (primary) 1f else 0f)).setColor(argb(0x8cc7ea18.toInt())).build())
.setBackground(Background.Builder().setColor(argb(if (primary) 0xbe181f10.toInt() else 0xcd2b3420.toInt()))
.setCorner(Corner.Builder().setRadius(dp(28f)).build()).build()).build())
.addContent(text(when (label) {
context.getString(R.string.tile_start) -> context.getString(R.string.tile_record_button)
context.getString(R.string.tile_save) -> context.getString(R.string.tile_save_button)
else -> label
}, 12f, 0xffe4edce.toInt())).build()
}
@@ -0,0 +1,37 @@
package meghdad.remember
import android.content.Context
import androidx.wear.protolayout.LayoutElementBuilders.Layout
import androidx.wear.protolayout.TimelineBuilders
import androidx.wear.tiles.TileBuilders
/** Bounded minute artwork timeline, with one shared set of commands and a live time fallback. */
internal object RecordingTilePresentation {
fun tile(context: Context, state: RecordingTileState, actions: RecordingTileActions, now: Long = System.currentTimeMillis()): TileBuilders.Tile {
val anchor = now - state.elapsedMillis
val layout = RecordingTileLayout(context, actions)
val timeline = TimelineBuilders.Timeline.Builder()
fun entry(minutes: Long, start: Long? = null, end: Long? = null, original: Boolean = true) {
val item = TimelineBuilders.TimelineEntry.Builder().setLayout(
Layout.Builder()
.setRoot(layout.build(state, minutes, anchor, original)).build())
if (start != null && end != null) item.setValidity(TimelineBuilders.TimeInterval.Builder()
.setStartMillis(start).setEndMillis(end).build())
timeline.addTimelineEntry(item.build())
}
val minute = state.elapsedMillis / 60_000
if (state.active && !state.paused) {
// Static glyphs advance through a host timeline. Share action tokens across frames so
// rendering future minutes neither evicts current controls nor introduces app polling.
entry(minute, original = false)
repeat(60) { offset ->
val value = minute + offset
entry(value, anchor + value * 60_000, anchor + (value + 1) * 60_000)
}
} else entry(minute)
return TileBuilders.Tile.Builder().setResourcesVersion(RecordingTileArtwork.VERSION)
.setFreshnessIntervalMillis(if (state.active) 60_000 else 0)
.setTileTimeline(timeline.build()).build()
}
}
@@ -0,0 +1,42 @@
package meghdad.remember
import android.content.Context
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.wear.protolayout.ResourceBuilders
import androidx.wear.tiles.EventBuilders
import androidx.wear.tiles.RequestBuilders
import androidx.wear.tiles.TileBuilders
import androidx.wear.tiles.TileService
import com.google.common.util.concurrent.ListenableFuture
/** A system-rendered remote control for the current clip; never starts microphone capture. */
class RecordingTileService : TileService() {
companion object {
private val actions = RecordingTileActions()
internal fun refresh(context: Context) {
// Tile availability must never interfere with saving or capturing audio.
runCatching { getUpdater(context).requestUpdate(RecordingTileService::class.java) }
}
}
public override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture<TileBuilders.Tile> {
val before = RecordingService.tileState()
actions.consume(requestParams.currentState.lastClickableId, before.clipId)?.let { action ->
before.clipId?.let { RecordingService.tileCommand(it, action) }
}
return immediate(RecordingTilePresentation.tile(this, RecordingService.tileState(), actions))
}
public override fun onTileResourcesRequest(requestParams: RequestBuilders.ResourcesRequest): ListenableFuture<ResourceBuilders.Resources> =
immediate(RecordingTileArtwork.resources)
override fun onRecentInteractionEventsAsync(events: List<EventBuilders.TileInteractionEvent>): ListenableFuture<Void> {
if (events.any { it.eventType == EventBuilders.TileInteractionEvent.ENTER }) refresh(this)
return immediate<Void>(null)
}
private fun <T> immediate(value: T?): ListenableFuture<T> = CallbackToFutureAdapter.getFuture { completer ->
completer.set(value)
"Recording tile response"
}
}
@@ -0,0 +1,34 @@
package meghdad.remember
import java.util.Locale
import java.util.UUID
internal data class RecordingTileState(
val clipId: String? = null,
val paused: Boolean = false,
val elapsedMillis: Long = 0,
val bookmarks: Int = 0,
val part: Int = 1,
) {
val active: Boolean get() = clipId != null
val time: String get() = String.format(Locale.ROOT, "%02d:%02d", elapsedMillis / 60_000, elapsedMillis / 1000 % 60)
}
internal enum class TileRecordingAction { PAUSE, RESUME, MARK, SAVE }
/** Opaque, one-shot commands. A cached tile can never operate on a different clip. */
internal class RecordingTileActions(private val capacity: Int = 128) {
private val issued = LinkedHashMap<String, Pair<String, TileRecordingAction>>()
@Synchronized fun issue(clipId: String, action: TileRecordingAction): String {
val token = UUID.randomUUID().toString()
issued[token] = clipId to action
while (issued.size > capacity) issued.remove(issued.keys.first())
return token
}
@Synchronized fun consume(token: String, currentClipId: String?): TileRecordingAction? {
val (clipId, action) = issued.remove(token) ?: return null
return action.takeIf { clipId == currentClipId }
}
}
@@ -0,0 +1,98 @@
package meghdad.remember
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.widget.Toast
/** A visible, tile-host-only entry point for microphone permission and foreground capture. */
class TileRecordingActivity : Activity() {
private val handler = Handler(Looper.getMainLooper())
private var resumed = false
private var permissionPending = false
private var dispatched = false
private var deadline = 0L
private val awaitRecorder = object : Runnable {
override fun run() {
if (!resumed) return
when {
RecordingService.activeId != null -> finish()
SystemClock.elapsedRealtime() >= deadline -> fail()
else -> handler.postDelayed(this, 50)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
permissionPending = savedInstanceState?.getBoolean("permissionPending") ?: false
dispatched = savedInstanceState?.getBoolean("dispatched") ?: false
deadline = savedInstanceState?.getLong("deadline") ?: 0
}
override fun onResume() {
super.onResume()
resumed = true
window.decorView.post { startWhenVisible() }
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) startWhenVisible()
}
private fun startWhenVisible() {
if (!resumed || isFinishing || !hasWindowFocus()) return
if (RecordingService.activeId != null) { finish(); return }
if (permissionPending) return
if (dispatched) { handler.removeCallbacks(awaitRecorder); handler.post(awaitRecorder); return }
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
permissionPending = true
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 1)
return
}
try {
// Start only while this activity is visible; a background TileService cannot use mic.
dispatched = true
deadline = SystemClock.elapsedRealtime() + 5000
startForegroundService(Intent(this, RecordingService::class.java).setAction(RecordingService.START))
handler.post(awaitRecorder)
} catch (_: Exception) { fail() }
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != 1) return
permissionPending = false
if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) startWhenVisible()
else {
Toast.makeText(this, R.string.tile_microphone_needed, Toast.LENGTH_SHORT).show()
finish()
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean("permissionPending", permissionPending)
outState.putBoolean("dispatched", dispatched)
outState.putLong("deadline", deadline)
super.onSaveInstanceState(outState)
}
override fun onPause() {
resumed = false
handler.removeCallbacks(awaitRecorder)
super.onPause()
}
override fun onDestroy() { handler.removeCallbacksAndMessages(null); super.onDestroy() }
private fun fail() {
Toast.makeText(this, R.string.tile_start_failed, Toast.LENGTH_LONG).show()
finish()
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

@@ -0,0 +1 @@
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/recording_tile_preview" android:gravity="fill" />
@@ -0,0 +1 @@
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/recording_tile_preview" android:gravity="fill" />
+24
View File
@@ -82,4 +82,28 @@
<string name="backup_trust_server_address">%1$s:%2$d</string>
<string name="backup_remember_server">Remember this server.</string>
<string name="backup_view_fingerprint">View fingerprint</string>
<string name="tile_label">Current recording</string>
<string name="tile_description">Start recording, see elapsed time, pause, resume, mark, or save your current recording.</string>
<string name="tile_brand">REMEMBER</string>
<string name="tile_recording">● RECORDING</string>
<string name="tile_paused">PAUSED</string>
<string name="tile_start">Record</string>
<string name="tile_record_button">● Record</string>
<string name="tile_save_button">■ Save</string>
<string name="tile_microphone_needed">Microphone access is needed to record.</string>
<string name="tile_start_failed">Could not start recording. Please try again in Remember.</string>
<string name="tile_pause">Pause</string>
<string name="tile_resume">Resume</string>
<string name="tile_mark">Mark</string>
<string name="tile_save">Save</string>
<string name="tile_details">Part %1$d · %2$s</string>
<plurals name="tile_minutes">
<item quantity="one">%d minute</item>
<item quantity="other">%d minutes</item>
</plurals>
<plurals name="tile_bookmarks">
<item quantity="one">%d bookmark</item>
<item quantity="other">%d bookmarks</item>
</plurals>
<string name="tile_timer_description">Elapsed recording time %1$s. Tap to refresh.</string>
</resources>
+6
View File
@@ -7,4 +7,10 @@
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowNoTitle">true</item>
</style>
<style name="Theme.Remember.TileStart" parent="Theme.Remember">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowDisablePreview">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
@@ -0,0 +1,37 @@
package meghdad.remember
import org.junit.Assert.*
import org.junit.Test
class RecordingTileStateTest {
@Test fun durationKeepsTotalMinutesBeyondOneHour() {
assertEquals("00:00", RecordingTileState().time)
assertEquals("01:02", RecordingTileState(elapsedMillis = 62_999).time)
assertEquals("120:05", RecordingTileState(elapsedMillis = 7_205_000).time)
}
@Test fun commandsAreSingleUseEvenWhenHostRepeatsTheClickId() {
val actions = RecordingTileActions()
val token = actions.issue("clip", TileRecordingAction.MARK)
assertEquals(TileRecordingAction.MARK, actions.consume(token, "clip"))
assertNull(actions.consume(token, "clip"))
}
@Test fun staleCommandsCannotControlAnotherPartOrSession() {
val actions = RecordingTileActions()
val token = actions.issue("old", TileRecordingAction.SAVE)
assertNull(actions.consume(token, "new"))
assertNull(actions.consume(token, "old"))
assertNull(actions.consume("untrusted", "new"))
}
@Test fun expiredAndIdleCommandsFailClosed() {
val actions = RecordingTileActions(2)
val expired = actions.issue("clip", TileRecordingAction.PAUSE)
val idle = actions.issue("clip", TileRecordingAction.SAVE)
val valid = actions.issue("clip", TileRecordingAction.RESUME)
assertNull(actions.consume(expired, "clip"))
assertNull(actions.consume(idle, null))
assertEquals(TileRecordingAction.RESUME, actions.consume(valid, "clip"))
}
}