Polish recorder and tile controls with smooth transitions

This commit is contained in:
Meghdad committed 2026-10-15 01:57:06 +03:30
1 parent bf5d92f430
commit 8a86b4186f
25 files changed
+555 -75

No files matched your search

+1
View File
@@ -35,6 +35,7 @@ android {
}
dependencies {
implementation(libs.androidx.annotation.experimental)
implementation(libs.wear.tiles)
implementation(libs.wear.protolayout)
implementation(libs.wear.protolayout.expression)
@@ -0,0 +1,138 @@
package meghdad.remember
import android.Manifest
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Rect
import android.media.MediaMetadataRetriever
import android.os.SystemClock
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageButton
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
@RunWith(AndroidJUnit4::class)
class RecorderControlsTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = instrumentation.targetContext
private fun descendants(view: View): List<View> = listOf(view) +
if (view is ViewGroup) (0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
private fun bounds(view: View) = IntArray(2).let { point ->
view.getLocationOnScreen(point); Rect(point[0], point[1], point[0] + view.width, point[1] + view.height)
}
private fun await(condition: () -> Boolean) {
val end = SystemClock.elapsedRealtime() + 6000
while (!condition() && SystemClock.elapsedRealtime() < end) SystemClock.sleep(50)
assertTrue("Recorder controls did not reach expected state", condition())
}
@Test fun controlsFitRoundScreensAndKeepThePrimaryButtonFixed() {
instrumentation.runOnMainSync {
for (size in listOf(192, 227)) {
val configured = context.createConfigurationContext(Configuration(context.resources.configuration).apply { screenWidthDp = size })
val density = configured.resources.displayMetrics.density
val pixels = (size * density).toInt()
val parent = FrameLayout(configured).apply { setPadding((22 * density).toInt(), (16 * density).toInt(), (22 * density).toInt(), 0) }
val controls = RecorderControlsView(configured, {}, {}, {})
parent.addView(controls, FrameLayout.LayoutParams(-1, -2))
var primaryBounds: Rect? = null
for ((active, paused) in listOf(false to false, true to false, true to true, false to false)) {
controls.bind(active, paused, 1, animate = false)
parent.measure(View.MeasureSpec.makeMeasureSpec(pixels, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(pixels, View.MeasureSpec.EXACTLY))
parent.layout(0, 0, pixels, pixels)
val buttons = descendants(controls).filter { it.isClickable && it.isEnabled }
assertEquals(if (active) 3 else 1, buttons.size)
buttons.forEach { button ->
val rect = Rect(0, 0, button.width, button.height)
parent.offsetDescendantRectToMyCoords(button, rect)
assertTrue("Tap area must be at least 48 dp", rect.width() >= 48 * density && rect.height() >= 48 * density)
val radius = rect.height() / 2.0
for (x in listOf(rect.left + radius, rect.right - radius)) {
assertTrue("Control clipped on $size dp: $rect", kotlin.math.hypot(x - pixels / 2.0, rect.exactCenterY() - pixels / 2.0) + radius <= pixels / 2.0 + 1)
}
if (button !is ImageButton) {
primaryBounds?.let { assertEquals(it, rect) }; primaryBounds = rect
} else {
val menu = Rect((pixels - 48 * density).toInt() / 2, (pixels - 48 * density).toInt(), (pixels + 48 * density).toInt() / 2, pixels)
assertFalse("Floating menu must not cover the icon controls", Rect.intersects(rect, menu))
}
}
}
}
}
}
@Test fun actualAppKeepsItsViewsAndRecordsThroughFloatingIconControls() {
assertNull("Use a disposable emulator without an active recording", RecordingService.activeId)
val store = Recordings(context)
val existing = store.list().map { it.id }.toSet()
val preferences = RecordingPreferences(context)
val previous = preferences.read()
preferences.write(RecordingLimit())
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.POST_NOTIFICATIONS)
val activity = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
fun control(label: String): View? {
var found: View? = null
instrumentation.runOnMainSync { found = descendants(activity.window.decorView).firstOrNull { it.contentDescription == label && it.isShown } }
return found
}
fun click(label: String) {
await { control(label) != null }
val button = control(label)!!
instrumentation.runOnMainSync { assertTrue(button.performClick()) }
}
fun screenshot(name: String) {
// The numeral deliberately keeps floating; wait only for the finite control transition.
SystemClock.sleep(400)
instrumentation.waitForIdleSync()
val bitmap = instrumentation.uiAutomation.takeScreenshot()!!
File(context.getExternalFilesDir(null), name).outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
}
try {
val primary = control("Start recording")!!
val originalBounds = bounds(primary)
val numeral = descendants(activity.window.decorView).filterIsInstance<MinuteCounterView>().single()
screenshot("home-controls-idle.png")
click("Start recording")
await { RecordingService.elapsed > 1200 && control("Pause") != null }
assertSame(primary, control("Save"))
assertEquals(originalBounds, bounds(control("Save")!!))
assertSame(numeral, descendants(activity.window.decorView).filterIsInstance<MinuteCounterView>().single())
assertTrue(control("Pause") is ImageButton)
assertTrue(control("Mark") is ImageButton)
val id = RecordingService.activeId!!
screenshot("home-controls-recording.png")
click("Pause"); await { RecordingService.paused && control("Resume") != null }
val elapsed = RecordingService.elapsed
SystemClock.sleep(500); assertEquals(elapsed, RecordingService.elapsed)
click("Mark"); await { RecordingService.marks.size == 1 }
SystemClock.sleep(2200) // Keep the transient bookmark toast out of the screenshot.
screenshot("home-controls-paused.png")
click("Resume"); await { !RecordingService.paused && RecordingService.elapsed > elapsed + 300 }
click("Save"); await { RecordingService.activeId == null && control("Start recording") != null }
assertSame(primary, control("Start recording"))
assertEquals(originalBounds, bounds(primary))
val saved = store.list().first { it.id == id }
assertEquals(listOf(elapsed), saved.marks)
MediaMetadataRetriever().also { reader ->
try { reader.setDataSource(store.audio(id).absolutePath); assertTrue(reader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toLong() > 1000) }
finally { reader.release() }
}
} 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) }
preferences.write(previous)
instrumentation.runOnMainSync { activity.finish() }
}
}
}
@@ -23,7 +23,8 @@ class RecordingTileLayoutTest {
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))) {
var primaryBounds: android.graphics.Rect? = null
for (state in listOf(RecordingTileState(), RecordingTileState("clip", false, 59_000, 0, 1), 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 {
@@ -31,7 +32,7 @@ class RecordingTileLayoutTest {
// 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()
.setRoot(RecordingTileLayout(context, RecordingTileActions(), animateTransitions = false).build(state)).build()
future = renderer.inflateAsync(layout, RecordingTileArtwork.resources, parent)
}
val view = future.get(10, TimeUnit.SECONDS)
@@ -50,6 +51,10 @@ class RecordingTileLayoutTest {
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("Record", "Save")) {
primaryBounds?.let { assertEquals("Record and Save must occupy the same fixed position", it, bounds) }
primaryBounds = android.graphics.Rect(bounds)
}
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
@@ -60,11 +65,17 @@ class RecordingTileLayoutTest {
}
}
val texts = all.filterIsInstance<TextView>()
assertTrue(controls.any { it.contentDescription?.toString()?.contains(state.time) == true })
// The live host clock can cross a second/minute boundary while inflating.
val descriptions = controls.map { it.contentDescription?.toString().orEmpty() }
assertTrue("Missing spoken timer: $descriptions", descriptions.any {
if (state.active && !state.paused) Regex("[0-9]+:[0-9]{2}").containsMatchIn(it)
else it.contains(state.time)
})
val images = all.filterIsInstance<ImageView>()
assertEquals(1 + (state.elapsedMillis / 60_000).toString().length, images.size)
assertEquals(1 + (state.elapsedMillis / 60_000).toString().length + if (state.active) 2 else 0, 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(":") })
assertFalse("Secondary controls must be icon-only", texts.any { it.text.toString() in listOf("Pause", "Resume", "Mark") })
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,84 @@
package meghdad.remember
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.wear.protolayout.LayoutElementBuilders.*
import androidx.wear.protolayout.ModifiersBuilders.Modifiers
import androidx.wear.protolayout.ProtoLayoutScope
import androidx.wear.protolayout.ActionBuilders
import androidx.wear.protolayout.expression.VersionBuilders.VersionInfo
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@androidx.annotation.OptIn(markerClass = [androidx.wear.protolayout.expression.ProtoLayoutExperimental::class])
class RecordingTileMotionTest {
@Test fun nativeStartActionUsesAnImmutableActivityIntentWithAnOlderHostFallback() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
for (minor in listOf(500, 600)) {
val scope = ProtoLayoutScope(VersionInfo.Builder().setMajor(1).setMinor(minor).build())
val root = RecordingTileLayout(context, RecordingTileActions(), animateTransitions = false, scope = scope)
.build(RecordingTileState())
val start = descendants(root).mapNotNull { modifiers(it)?.clickable }.first { it.id == "start" }
@Suppress("DEPRECATION")
val pending = scope.collectPendingIntents().getParcelable<android.app.PendingIntent>("start")
if (minor == 600) {
assertNotNull(pending)
assertTrue(pending!!.isActivity)
assertTrue(pending.isImmutable)
} else {
assertNull(pending)
assertTrue(start.onClick is ActionBuilders.LaunchAction)
}
}
}
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()
}
private fun modifiers(element: LayoutElement): Modifiers? = when (element) {
is Box -> element.modifiers
is Column -> element.modifiers
is Row -> element.modifiers
is Text -> element.modifiers
is Image -> element.modifiers
else -> null
}
@Test fun reducedMotionOmitsAllTransitionsAndKeepsControls() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
for (state in listOf(RecordingTileState(), RecordingTileState("clip", false), RecordingTileState("clip", true))) {
val root = RecordingTileLayout(context, RecordingTileActions(), animateTransitions = false).build(state)
val all = descendants(root)
assertTrue(all.none { modifiers(it)?.contentUpdateAnimation != null })
val labels = all.mapNotNull { modifiers(it)?.semantics?.contentDescription?.value }
assertTrue(if (state.active) labels.containsAll(listOf("Save", "Mark", if (state.paused) "Resume" else "Pause")) else "Record" in labels)
}
}
@Test fun transitionsAreFiniteAndDoNotAnimateTheWholeTileOrTimer() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val root = RecordingTileLayout(context, RecordingTileActions(), animateTransitions = true)
.build(RecordingTileState("clip", false, 9000))
assertNull(modifiers(root)?.contentUpdateAnimation)
val all = descendants(root)
val timer = all.first { modifiers(it)?.clickable?.id == "refresh" }
assertTrue("The numeral must stay visible throughout control transitions",
descendants(timer).none { modifiers(it)?.contentUpdateAnimation != null })
assertFalse("Avoid the renderer's pressed-state flash over the numeral", modifiers(timer)!!.clickable!!.isVisualFeedbackEnabled)
val transitions = all.mapNotNull { modifiers(it)?.contentUpdateAnimation }
assertTrue(transitions.any { it.enterTransition?.slideIn != null })
val specs = transitions.flatMap { transition -> listOfNotNull(
transition.enterTransition?.fadeIn?.animationSpec,
transition.enterTransition?.slideIn?.animationSpec,
transition.exitTransition?.fadeOut?.animationSpec,
) }
assertTrue(specs.isNotEmpty())
specs.forEach { spec ->
assertNull("Interaction transitions must never loop", spec.repeatable)
assertTrue("Keep transitions brief", spec.animationParameters!!.durationMillis in 75..320)
}
}
}
@@ -34,8 +34,8 @@ class MainActivity : Activity() {
private lateinit var dial: SpatialDialDrawable
private var downX = 0f
private var downY = 0f
private var status: TextView? = null
private var pause: Button? = null
private var recorderControls: RecorderControlsView? = null
private var savedHomeDuration = 0L
private var play: Button? = null
private var seek: SeekBar? = null
private var active = false
@@ -52,12 +52,12 @@ class MainActivity : Activity() {
private val ticker = object : Runnable {
override fun run() {
val now = RecordingService.activeId != null
if (now != active) { active = now; if (screen == "home") render() }
if (now && screen == "home") {
updateDial(RecordingService.elapsed)
status?.text = if (RecordingService.paused) "PAUSED" else if (RecordingService.part > 1) "● RECORDING · ${RecordingService.part}" else "● RECORDING"
pause?.text = if (RecordingService.paused) "Resume" else "Pause"
val changed = now != active
if (changed) {
active = now
if (!now && screen == "home") savedHomeDuration = store.list().sumOf { it.duration }
}
if (screen == "home" && (now || changed)) updateHomeControls()
player?.let { p ->
runCatching {
updateDial(p.currentPosition.toLong())
@@ -91,7 +91,7 @@ class MainActivity : Activity() {
minutes?.setFloating(motionAllowed && !RecordingService.paused && minutes?.visibility == View.VISIBLE)
handler.post(ticker)
}
override fun onPause() { foreground = false; floatingMenu?.pause(); handler.removeCallbacks(ticker); minutes?.setFloating(false); player?.pause(); super.onPause() }
override fun onPause() { recorderControls?.finishTransitions(); foreground = false; floatingMenu?.pause(); handler.removeCallbacks(ticker); minutes?.setFloating(false); player?.pause(); super.onPause() }
override fun onDestroy() { floatingMenu?.dispose(); releasePlayer(); storageWorker.shutdown(); super.onDestroy() }
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
val handled = super.dispatchTouchEvent(event)
@@ -139,7 +139,8 @@ class MainActivity : Activity() {
val menuWasVisible = floatingMenu?.button?.visibility == View.VISIBLE
floatingMenu?.dispose(); floatingMenu = null
minutes?.setFloating(false)
minutes = null; status = null; pause = null; play = null; seek = null; limitPicker = null
recorderControls?.finishTransitions(); recorderControls = null
minutes = null; play = null; seek = null; limitPicker = null
storageRequest++; storageChart = null; storageAvailable = null; storageApp = null
dial = SpatialDialDrawable()
val layers = FrameLayout(this).apply { background = dial }
@@ -148,7 +149,8 @@ class MainActivity : Activity() {
body = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
val round = resources.configuration.isScreenRound
setPadding(dp(if (round) 30 else 28), dp(if (screen == "home") 16 else 14), dp(if (round) 30 else 28), dp(24))
val horizontal = if (screen == "home") 22 else if (round) 30 else 28
setPadding(dp(horizontal), dp(if (screen == "home") 16 else 14), dp(horizontal), dp(if (screen == "home") 20 else 24))
}
scroll.addView(body)
layers.addView(scroll, FrameLayout.LayoutParams(-1, -1))
@@ -200,7 +202,6 @@ class MainActivity : Activity() {
screen == "limits" -> limits()
screen == "limit_minutes" -> limitMinutes()
screen == "limit_action" -> limitAction()
active && screen == "home" -> recording()
screen == "library" -> library()
screen == "detail" -> detail()
else -> home()
@@ -240,31 +241,22 @@ class MainActivity : Activity() {
scroll.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
private fun home() {
val clips = store.list()
val total = clips.sumOf { it.duration }
text("REMEMBER", 10f).apply { letterSpacing = .2f }
counter(total, true)
savedHomeDuration = store.list().sumOf { it.duration }
recorderControls = RecorderControlsView(this,
onPrimary = { showingRecording -> if (showingRecording) command(RecordingService.SAVE) else startRecording() },
onPause = { command(RecordingService.PAUSE) },
onMark = {
command(RecordingService.MARK)
Toast.makeText(this, R.string.recorder_moment_marked, Toast.LENGTH_SHORT).show()
}).also { body.addView(it, LinearLayout.LayoutParams(-1, -2)) }
dial.freeStorage = (filesDir.usableSpace.toDouble() / filesDir.totalSpace.coerceAtLeast(1)).toFloat()
updateDial(total)
// Saved total has no running seconds; the sweep starts when capture starts.
dial.elapsed = 0
button("● Record", mint) { startRecording() }.contentDescription = "Start recording"
updateHomeControls(animate = false)
}
private fun recording() {
status = text(if (RecordingService.paused) "PAUSED" else "● RECORDING", 10f, mint)
counter(RecordingService.elapsed)
updateDial(RecordingService.elapsed)
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
pause = button(if (RecordingService.paused) "Resume" else "Pause") { command(RecordingService.PAUSE) }
val mark = button("Mark") {
command(RecordingService.MARK)
Toast.makeText(this, "Moment marked", Toast.LENGTH_SHORT).show()
}
body.removeView(pause); body.removeView(mark)
row.addView(pause, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginEnd = dp(3) })
row.addView(mark, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginStart = dp(3) })
body.addView(row)
button("■ Save", mint) { command(RecordingService.SAVE) }
private fun updateHomeControls(animate: Boolean = true) {
updateDial(if (active) RecordingService.elapsed else savedHomeDuration)
if (!active) dial.elapsed = 0
recorderControls?.bind(active, RecordingService.paused, RecordingService.part,
animate && foreground && motionAllowed)
}
private fun menu() {
updateDial(0)
@@ -0,0 +1,129 @@
package meghdad.remember
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.InsetDrawable
import android.graphics.drawable.RippleDrawable
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.animation.PathInterpolator
import android.widget.*
import kotlin.math.roundToInt
/** Stable home controls: only labels and the small satellite controls transition. */
internal class RecorderControlsView(context: Context, onPrimary: (Boolean) -> Unit,
onPause: () -> Unit, onMark: () -> Unit) : LinearLayout(context) {
private fun dp(value: Int) = WatchDesign.dp(context, value)
private val easing = PathInterpolator(.4f, 0f, .2f, 1f)
private val heading = WatchDesign.label(context, "", 10f)
private var recording = false
private var paused = false
private var boundPart = 0
private var initialized = false
private val primary = WatchDesign.action(context, "", action = { onPrimary(recording) }).apply {
setTextColor(Color.rgb(228, 237, 206))
background = WatchDesign.shape(context, Color.argb(190, 24, 31, 16), 28, Color.argb(140, 199, 234, 24))
layoutParams = LayoutParams(-1, dp(48))
}
private val pauseButton = satellite(context.getString(R.string.tile_pause), WatchIcon.PAUSE, onPause)
private val markButton = satellite(context.getString(R.string.tile_mark), WatchIcon.MARK, onMark)
private val satellites = LinearLayout(context).apply {
orientation = HORIZONTAL; gravity = Gravity.CENTER_VERTICAL
layoutParams = LayoutParams(dp((resources.configuration.screenWidthDp * .77f).roundToInt()), dp(48))
addView(pauseButton, LayoutParams(dp(48), dp(48)))
addView(Space(context), LayoutParams(0, 1, 1f))
addView(markButton, LayoutParams(dp(48), dp(48)))
visibility = INVISIBLE
}
init {
orientation = VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
addView(heading, LayoutParams(-1, -2))
addView(Space(context), LayoutParams(1, dp(if (resources.configuration.screenWidthDp <= 200) 38 else 62)))
addView(primary)
addView(Space(context), LayoutParams(1, dp(8)))
addView(satellites)
}
fun bind(active: Boolean, isPaused: Boolean, part: Int, animate: Boolean) {
val motion = animate && ValueAnimator.areAnimatorsEnabled()
if (initialized && active == recording && isPaused == paused && part == boundPart) {
if (!motion) finishTransitions()
return
}
val changed = initialized && active != recording
val pauseChanged = initialized && isPaused != paused
recording = active; paused = isPaused; boundPart = part
val title = if (!active) context.getString(R.string.tile_brand)
else if (isPaused) context.getString(R.string.tile_paused)
else if (part == 1) context.getString(R.string.tile_recording)
else context.getString(R.string.recorder_recording_part, part)
heading.setTextColor(if (active) WatchDesign.lime else Color.WHITE)
heading.letterSpacing = if (active) 0f else .2f
fadeText(heading, title, motion)
fadeText(primary, context.getString(if (active) R.string.tile_save_button else R.string.tile_record_button), motion)
primary.contentDescription = context.getString(if (active) R.string.tile_save else R.string.recorder_start)
if (!initialized || changed) {
satellites.animate().cancel()
satellites.importantForAccessibility = if (active) IMPORTANT_FOR_ACCESSIBILITY_AUTO else IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
pauseButton.isEnabled = active; markButton.isEnabled = active
if (motion) {
if (active) {
satellites.visibility = VISIBLE; satellites.alpha = 0f; satellites.translationY = dp(8).toFloat()
satellites.animate().alpha(1f).translationY(0f).setDuration(280).setInterpolator(easing).start()
} else satellites.animate().alpha(0f).translationY(dp(6).toFloat()).setDuration(160)
.setInterpolator(easing).withEndAction { if (!recording) satellites.visibility = INVISIBLE }.start()
} else {
satellites.visibility = if (active) VISIBLE else INVISIBLE
satellites.alpha = if (active) 1f else 0f; satellites.translationY = 0f
}
}
if (!initialized || pauseChanged || changed) {
pauseButton.animate().cancel()
pauseButton.setImageDrawable(WatchGlyph(if (isPaused) WatchIcon.PLAY else WatchIcon.PAUSE, Color.rgb(228, 237, 206)))
pauseButton.contentDescription = context.getString(if (isPaused) R.string.tile_resume else R.string.tile_pause)
if (motion && active && pauseChanged) {
pauseButton.alpha = .35f
pauseButton.animate().alpha(1f).setDuration(180).setInterpolator(easing).start()
} else pauseButton.alpha = 1f
}
if (!motion) finishTransitions()
initialized = true
}
private fun fadeText(view: TextView, value: String, motion: Boolean) {
if (view.tag == value) return
view.tag = value; view.animate().cancel()
if (motion && initialized) view.animate().alpha(0f).setDuration(80).withEndAction {
view.text = value
view.animate().alpha(1f).setDuration(180).setInterpolator(easing).start()
}.start() else { view.text = value; view.alpha = 1f }
}
fun finishTransitions() {
listOf(heading, primary).forEach { view ->
view.animate().cancel()
(view.tag as? String)?.let { if (view.text.toString() != it) view.text = it }
view.alpha = 1f
}
satellites.animate().cancel(); pauseButton.animate().cancel()
satellites.visibility = if (recording) VISIBLE else INVISIBLE
satellites.alpha = if (recording) 1f else 0f; satellites.translationY = 0f; pauseButton.alpha = 1f
}
private fun satellite(label: String, icon: WatchIcon, action: () -> Unit) = ImageButton(context).apply {
contentDescription = label; setImageDrawable(WatchGlyph(icon, Color.rgb(228, 237, 206)))
scaleType = ImageView.ScaleType.FIT_CENTER
setPadding(dp(13), dp(13), dp(13), dp(13))
val surface = InsetDrawable(WatchDesign.shape(context, Color.argb(229, 24, 31, 16), 18, 0x547d8b58), dp(6))
val mask = InsetDrawable(WatchDesign.shape(context, Color.WHITE, 18), dp(6))
background = RippleDrawable(ColorStateList.valueOf(0x3cc7ea18), surface, mask)
stateListAnimator = null
setOnClickListener { performHapticFeedback(HapticFeedbackConstants.CONFIRM); action() }
}
override fun onDetachedFromWindow() { finishTransitions(); super.onDetachedFromWindow() }
}
@@ -6,7 +6,7 @@ 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"
const val VERSION = "recording-spatial-2"
val resources: ResourceBuilders.Resources by lazy {
ResourceBuilders.Resources.Builder().setVersion(VERSION).apply {
for (digit in 0..9) addIdToImageMapping("digit-$digit", image(160, 240) { canvas ->
@@ -20,6 +20,23 @@ internal object RecordingTileArtwork {
}
canvas.drawPath(MinuteNumeralArtwork.path(digit), paint)
})
for (name in listOf("pause", "resume", "mark")) addIdToImageMapping("control-$name", image(64, 64) { canvas ->
canvas.scale(2f, 2f)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.rgb(228, 237, 206); strokeWidth = 2.4f
strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND; style = Paint.Style.STROKE
}
when (name) {
"pause" -> { canvas.drawLine(12f, 9f, 12f, 23f, paint); canvas.drawLine(20f, 9f, 20f, 23f, paint) }
"resume" -> {
paint.style = Paint.Style.FILL
canvas.drawPath(Path().apply { moveTo(11f, 7f); lineTo(24f, 16f); lineTo(11f, 25f); close() }, paint)
}
"mark" -> canvas.drawPath(Path().apply {
moveTo(10f, 7f); lineTo(22f, 7f); lineTo(22f, 25f); lineTo(16f, 21f); lineTo(10f, 25f); close()
}, paint)
}
})
addIdToImageMapping("dial", image(300, 300) { canvas ->
canvas.drawPaint(Paint().apply {
shader = RadialGradient(195f, 90f, 240f,
@@ -1,6 +1,10 @@
package meghdad.remember
import android.content.Context
import android.content.Intent
import android.app.PendingIntent
import android.app.ActivityOptions
import androidx.wear.protolayout.ProtoLayoutScope
import androidx.wear.protolayout.ActionBuilders
import androidx.wear.protolayout.ColorBuilders.argb
import androidx.wear.protolayout.DimensionBuilders.*
@@ -14,7 +18,10 @@ 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) {
@androidx.annotation.OptIn(markerClass = [androidx.wear.protolayout.expression.ProtoLayoutExperimental::class])
internal class RecordingTileLayout(private val context: Context, private val actions: RecordingTileActions,
private val animateTransitions: Boolean = RecordingTileMotion.allowed(context),
private val scope: ProtoLayoutScope? = null) {
private val commands = mutableMapOf<TileRecordingAction, Clickable>()
private val lime = 0xffc7ea18.toInt()
@@ -40,7 +47,8 @@ internal class RecordingTileLayout(private val context: Context, private val act
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()))
// Keep layer positions stable as bookmark count changes, preserving renderer diffing.
root.addContent(edge(size, 58f + i * 5.3f, 2.4f, if (i < state.bookmarks) 0xffe4edce.toInt() else 0x00000000))
}
val clockDescription = TypeBuilders.StringProp.Builder(context.getString(R.string.tile_timer_description, state.time))
val digits = IntFormatter.Builder().setMinIntegerDigits(2).setGroupingUsed(false).build()
@@ -52,7 +60,7 @@ internal class RecordingTileLayout(private val context: Context, private val act
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")
.setModifiers(Modifiers.Builder().setClickable(Clickable.Builder().setId("refresh").setVisualFeedbackEnabled(false)
.setOnClick(ActionBuilders.LoadAction.Builder().build()).build())
.setSemantics(counterSemantics.build())
.setTransformation(Transformation.Builder().setTranslationX(dp(size * .02f)).setTranslationY(dp(-size * .025f)).build()).build())
@@ -75,49 +83,82 @@ internal class RecordingTileLayout(private val context: Context, private val act
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(
val statusModifiers = animatedModifiers()
if (state.active) statusModifiers.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())
context.resources.getQuantityString(R.plurals.tile_bookmarks, state.bookmarks, state.bookmarks))).build())
status.setModifiers(statusModifiers.build())
val primaryLabel = context.getString(if (state.active) R.string.tile_save else R.string.tile_start)
val primaryAction = if (state.active) command(state, TileRecordingAction.SAVE) else startAction()
val controls = Column.Builder().setWidth(dp(width)).setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER)
.addContent(status.build())
.addContent(gap(if (compact) 38f else 62f))
.addContent(status.build()).addContent(gap(if (compact) 38f else 62f))
// Same position, size, chrome, and child order for both Record and Save.
.addContent(button(primaryLabel, primaryAction, width)).addContent(gap(8f))
val satellites = Box.Builder().setWidth(dp(width)).setHeight(dp(64f))
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))
satellites.addContent(Row.Builder().setVerticalAlignment(VERTICAL_ALIGN_CENTER)
.setModifiers(animatedModifiers(rise = true).build())
.addContent(iconButton(context.getString(if (state.paused) R.string.tile_resume else R.string.tile_pause),
if (state.paused) "control-resume" else "control-pause", command(state, pause)))
.addContent(Spacer.Builder().setWidth(dp(28f)).build())
.addContent(iconButton(context.getString(R.string.tile_mark), "control-mark", command(state, TileRecordingAction.MARK))).build())
}
controls.addContent(satellites.build())
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 startAction(): Clickable {
if (scope?.hasCapability(ProtoLayoutScope.RendererCapability.PENDING_INTENT_ACTION) == true) {
// A direct activity PendingIntent skips the host's shared-button launch animation.
val intent = Intent(context, TileRecordingActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
val pending = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
ActivityOptions.makeCustomAnimation(context, 0, 0).toBundle())
return Clickable.Builder(scope, "start").setVisualFeedbackEnabled(false).setOnClick(pending).build()
}
return Clickable.Builder().setId("start").setVisualFeedbackEnabled(false)
.setOnClick(ActionBuilders.LaunchAction.Builder().setAndroidActivity(ActionBuilders.AndroidActivity.Builder()
.setPackageName(context.packageName).setClassName(TileRecordingActivity::class.java.name).build()).build()).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()
Clickable.Builder().setId(actions.issue(state.clipId!!, action)).setVisualFeedbackEnabled(false).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()
private fun animatedModifiers(rise: Boolean = false) = Modifiers.Builder().apply {
if (animateTransitions) setContentUpdateAnimation(RecordingTileMotion.transition(rise))
}
private fun iconButton(label: String, resource: String, click: Clickable) = Box.Builder()
.setWidth(dp(48f)).setHeight(dp(48f))
.setModifiers(Modifiers.Builder().setClickable(click)
.setSemantics(Semantics.Builder().setRole(SEMANTICS_ROLE_BUTTON).setContentDescription(label).build()).build())
.addContent(Box.Builder().setWidth(dp(36f)).setHeight(dp(36f))
.setModifiers(Modifiers.Builder()
.setBorder(Border.Builder().setWidth(dp(1f)).setColor(argb(0x547d8b58)).build())
.setBackground(Background.Builder().setColor(argb(0xe5181f10.toInt()))
.setCorner(Corner.Builder().setRadius(dp(18f)).build()).build()).build())
.addContent(Image.Builder().setResourceId(resource).setWidth(dp(22f)).setHeight(dp(22f)).build()).build()).build()
private fun button(label: String, click: Clickable, 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()))
.setBorder(Border.Builder().setWidth(dp(1f)).setColor(argb(0x8cc7ea18.toInt())).build())
.setBackground(Background.Builder().setColor(argb(0xbe181f10.toInt()))
.setCorner(Corner.Builder().setRadius(dp(28f)).build()).build()).build())
.addContent(text(when (label) {
.addContent(Text.Builder().setText(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()
}).setFontStyle(FontStyle.Builder().setSize(sp(12f)).setColor(argb(0xffe4edce.toInt())).build())
.setMaxLines(1).setModifiers(animatedModifiers().build()).build()).build()
}
@@ -0,0 +1,30 @@
package meghdad.remember
import android.animation.ValueAnimator
import android.content.Context
import android.os.PowerManager
import androidx.wear.protolayout.ModifiersBuilders.*
import androidx.wear.protolayout.expression.AnimationParameterBuilders.*
/** Short, host-owned interaction transitions; no loops, timers, or animation wake locks. */
@androidx.annotation.OptIn(markerClass = [androidx.wear.protolayout.expression.ProtoLayoutExperimental::class])
internal object RecordingTileMotion {
fun allowed(context: Context): Boolean = ValueAnimator.areAnimatorsEnabled() &&
!context.getSystemService(PowerManager::class.java).isPowerSaveMode
fun transition(rise: Boolean = false): AnimatedVisibility {
val enterSpec = spec(if (rise) 280 else 180, if (rise) 30 else 0)
val enter = EnterTransition.Builder().setFadeIn(FadeInTransition.Builder()
.setInitialAlpha(0f).setAnimationSpec(enterSpec).build())
if (rise) enter.setSlideIn(SlideInTransition.Builder().setDirection(SLIDE_DIRECTION_BOTTOM_TO_TOP)
.setInitialSlideBound(SlideParentBound.Builder().setSnapTo(SLIDE_PARENT_SNAP_TO_INSIDE).build())
.setAnimationSpec(enterSpec).build())
return AnimatedVisibility.Builder().setEnterTransition(enter.build())
.setExitTransition(ExitTransition.Builder().setFadeOut(FadeOutTransition.Builder()
.setTargetAlpha(0f).setAnimationSpec(spec(90)).build()).build()).build()
}
private fun spec(duration: Long, delay: Long = 0) = AnimationSpec.Builder()
.setAnimationParameters(AnimationParameters.Builder().setDurationMillis(duration).setDelayMillis(delay)
.setEasing(Easing.FAST_OUT_SLOW_IN_EASING).build()).build()
}
@@ -1,15 +1,17 @@
package meghdad.remember
import android.content.Context
import androidx.wear.protolayout.ProtoLayoutScope
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 {
fun tile(context: Context, state: RecordingTileState, actions: RecordingTileActions, now: Long = System.currentTimeMillis(),
scope: ProtoLayoutScope? = null): TileBuilders.Tile {
val anchor = now - state.elapsedMillis
val layout = RecordingTileLayout(context, actions)
val layout = RecordingTileLayout(context, actions, scope = scope)
val timeline = TimelineBuilders.Timeline.Builder()
fun entry(minutes: Long, start: Long? = null, end: Long? = null, original: Boolean = true) {
val item = TimelineBuilders.TimelineEntry.Builder().setLayout(
@@ -24,7 +24,7 @@ class RecordingTileService : TileService() {
actions.consume(requestParams.currentState.lastClickableId, before.clipId)?.let { action ->
before.clipId?.let { RecordingService.tileCommand(it, action) }
}
return immediate(RecordingTilePresentation.tile(this, RecordingService.tileState(), actions))
return immediate(RecordingTilePresentation.tile(this, RecordingService.tileState(), actions, scope = requestParams.scope))
}
public override fun onTileResourcesRequest(requestParams: RequestBuilders.ResourcesRequest): ListenableFuture<ResourceBuilders.Resources> =
@@ -9,6 +9,7 @@ import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.widget.Toast
import android.widget.FrameLayout
/** A visible, tile-host-only entry point for microphone permission and foreground capture. */
class TileRecordingActivity : Activity() {
@@ -30,11 +31,33 @@ class TileRecordingActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This permission/foreground handoff must not run a full-screen activity transition.
setContentView(FrameLayout(this).apply { setBackgroundColor(android.graphics.Color.TRANSPARENT) })
suppressWindowTransition()
permissionPending = savedInstanceState?.getBoolean("permissionPending") ?: false
dispatched = savedInstanceState?.getBoolean("dispatched") ?: false
deadline = savedInstanceState?.getLong("deadline") ?: 0
}
private fun suppressWindowTransition() {
if (android.os.Build.VERSION.SDK_INT >= 34) {
overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, 0, 0)
overrideActivityTransition(OVERRIDE_TRANSITION_CLOSE, 0, 0)
} else {
@Suppress("DEPRECATION")
overridePendingTransition(0, 0)
}
}
override fun finish() {
suppressWindowTransition()
super.finish()
if (android.os.Build.VERSION.SDK_INT < 34) {
@Suppress("DEPRECATION")
overridePendingTransition(0, 0)
}
}
override fun onResume() {
super.onResume()
resumed = true
@@ -88,7 +88,7 @@ object WatchDesign {
}
}
enum class WatchIcon { RECORD, MOMENTS, STORAGE, LIMIT, BACKUP, SERVER, TRANSFERS, REMOTE, AUTOMATIC, ADVANCED, MENU, PLAY }
enum class WatchIcon { RECORD, MOMENTS, STORAGE, LIMIT, BACKUP, SERVER, TRANSFERS, REMOTE, AUTOMATIC, ADVANCED, MENU, PLAY, PAUSE, MARK }
/** Each destination has an identifiable silhouette, without fonts or bitmap assets. */
class WatchGlyph(private val icon: WatchIcon, private val tint: Int, private val orb: Boolean = false) : Drawable() {
@@ -123,6 +123,8 @@ class WatchGlyph(private val icon: WatchIcon, private val tint: Int, private val
WatchIcon.ADVANCED -> { for (i in 0..2) { val y = 12f + i * 12; line(7f, y, 41f, y); box(if (i == 1) 26f else 12f, y - 4, if (i == 1) 32f else 18f, y + 4, 2f) } }
WatchIcon.MENU -> { paint.style = Paint.Style.FILL; for (x in listOf(15f, 33f)) for (y in listOf(15f, 33f)) canvas.drawCircle(x, y, 5f, paint) }
WatchIcon.PLAY -> { val path = Path().apply { moveTo(17f, 9f); lineTo(38f, 24f); lineTo(17f, 39f); close() }; canvas.drawPath(path, paint) }
WatchIcon.PAUSE -> { line(18f, 12f, 18f, 36f); line(30f, 12f, 30f, 36f) }
WatchIcon.MARK -> { val path = Path().apply { moveTo(14f, 9f); lineTo(34f, 9f); lineTo(34f, 39f); lineTo(24f, 32f); lineTo(14f, 39f); close() }; canvas.drawPath(path, paint) }
}
canvas.restore()
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+3
View File
@@ -1,4 +1,7 @@
<resources>
<string name="recorder_start">Start recording</string>
<string name="recorder_recording_part">● RECORDING · %1$d</string>
<string name="recorder_moment_marked">Moment marked</string>
<string name="menu">Menu</string>
<string name="open_menu">Open all sections</string>
<string name="recorder">Recorder</string>
+1
View File
@@ -8,6 +8,7 @@
<item name="android:windowNoTitle">true</item>
</style>
<style name="Theme.Remember.TileStart" parent="Theme.Remember">
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowDisablePreview">true</item>