initial commit

This commit is contained in:
Meghdad committed 2026-10-13 19:41:05 +03:30
1 parent 85342c5a8d
commit d692001f7c
58 files changed
+1855 -371

No files matched your search

+1 -3
View File
@@ -4,6 +4,7 @@ plugins {
android {
namespace = "meghdad.remember"
buildToolsVersion = "36.1.0"
compileSdk {
version = release(36) {
minorApiLevel = 1
@@ -34,9 +35,6 @@ android {
}
dependencies {
implementation(libs.androidx.appcompat)
implementation(libs.androidx.core.ktx)
implementation(libs.material)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.junit)
@@ -1,24 +0,0 @@
package meghdad.remember
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("meghdad.remember", appContext.packageName)
}
}
@@ -0,0 +1,30 @@
package meghdad.remember
import android.content.Intent
import android.widget.Button
import android.view.View
import android.view.ViewGroup
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
@RunWith(AndroidJUnit4::class)
class LaunchTest {
@Test fun homeLaunchesWithAccessibleRecordAndLibraryControls() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val activity = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
try {
instrumentation.runOnMainSync {
fun descendants(view: View): List<View> = listOf(view) +
if (view is ViewGroup) (0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
val buttons = descendants(activity.window.decorView).filterIsInstance<Button>()
assertTrue(buttons.any { it.contentDescription == "Start recording" && it.isEnabled })
assertTrue(buttons.any { it.text.startsWith("Moments") })
}
} finally { instrumentation.runOnMainSync { activity.finish() } }
}
}
@@ -0,0 +1,60 @@
package meghdad.remember
import android.Manifest
import android.content.Intent
import android.media.MediaMetadataRetriever
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
@RunWith(AndroidJUnit4::class)
class RecordingFlowTest {
@Test fun recordingPausesMarksAndSavesPlayableAudio() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
val activity = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
var id: String? = null
fun command(action: String) = instrumentation.runOnMainSync {
val intent = Intent(context, RecordingService::class.java).setAction(action)
if (action == RecordingService.START) context.startForegroundService(intent) else context.startService(intent)
}
fun awaitState(condition: () -> Boolean) {
val end = SystemClock.elapsedRealtime() + 5000
while (!condition() && SystemClock.elapsedRealtime() < end) SystemClock.sleep(50)
assertTrue("Recorder did not reach expected state", condition())
}
try {
command(RecordingService.START)
awaitState { RecordingService.activeId != null && RecordingService.elapsed > 1100 }
id = RecordingService.activeId
command(RecordingService.PAUSE)
awaitState { RecordingService.paused }
val duration = RecordingService.elapsed
SystemClock.sleep(350)
assertEquals(duration, RecordingService.elapsed)
command(RecordingService.MARK)
awaitState { RecordingService.marks.size == 1 }
command(RecordingService.PAUSE)
awaitState { !RecordingService.paused && RecordingService.elapsed > duration + 300 }
command(RecordingService.SAVE)
awaitState { RecordingService.activeId == null }
val store = Recordings(context)
val saved = store.list().first { it.id == id }
assertEquals(listOf(duration), saved.marks)
assertTrue(saved.duration > 1400)
val metadata = MediaMetadataRetriever()
try {
metadata.setDataSource(store.audio(saved.id).absolutePath)
assertTrue(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toLong() > 1000)
} finally { metadata.release() }
} finally {
if (RecordingService.activeId != null) { command(RecordingService.SAVE); awaitState { RecordingService.activeId == null } }
Recordings(context).list().firstOrNull { it.id == id }?.let { Recordings(context).delete(it) }
instrumentation.runOnMainSync { activity.finish() }
}
}
}
@@ -0,0 +1,95 @@
package meghdad.remember
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.media.MediaMetadataRetriever
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RecordingLimitsIntegrationTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = instrumentation.targetContext
private fun awaitState(timeout: Long = 5000, condition: () -> Boolean) {
val end = SystemClock.elapsedRealtime() + timeout
while (!condition() && SystemClock.elapsedRealtime() < end) SystemClock.sleep(50)
assertTrue("Recorder did not reach expected state", condition())
}
private fun command(action: String) = instrumentation.runOnMainSync {
val intent = Intent(context, RecordingService::class.java).setAction(action)
if (action == RecordingService.START) context.startForegroundService(intent) else context.startService(intent)
}
private fun checkPlayable(clip: Clip) {
val metadata = MediaMetadataRetriever()
try {
metadata.setDataSource(Recordings(context).audio(clip.id).absolutePath)
assertTrue(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toLong() > 1000)
} finally { metadata.release() }
}
private fun session(action: LimitAction, work: (Activity, String) -> Unit) {
val preferences = RecordingPreferences(context)
val previous = preferences.read()
val store = Recordings(context)
val existing = store.list().map { it.id }.toSet()
var activity: Activity? = null
try {
preferences.write(RecordingLimit(true, 1, action))
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
activity = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
command(RecordingService.START)
awaitState { RecordingService.activeId != null && RecordingService.elapsed > 1100 }
work(activity, RecordingService.activeId!!)
} finally {
if (RecordingService.activeId != null) {
command(RecordingService.SAVE)
awaitState { RecordingService.activeId == null }
}
preferences.write(previous)
store.list().filter { it.id !in existing }.forEach { store.delete(it) }
activity?.let { instrumentation.runOnMainSync { it.finish() } }
}
}
@Test fun minuteLimitExcludesPauseAndSavesAfterLeavingTheApp() = session(LimitAction.STOP) { activity, id ->
command(RecordingService.PAUSE)
awaitState { RecordingService.paused }
val elapsed = RecordingService.elapsed
SystemClock.sleep(1700)
assertEquals(elapsed, RecordingService.elapsed)
command(RecordingService.PAUSE)
awaitState { !RecordingService.paused }
instrumentation.runOnMainSync { activity.finish() }
awaitState(70_000) { RecordingService.activeId == null }
val clip = Recordings(context).list().first { it.id == id }
assertTrue("Expected one minute of captured audio", clip.duration in 60_000..62_000)
checkPlayable(clip)
}
@Test fun limitStartsNewPlayableClipAtZeroAndKeepsSessionSettings() = session(LimitAction.NEXT_CLIP) { activity, firstId ->
command(RecordingService.MARK)
awaitState { RecordingService.marks.size == 1 }
// Changes are for the next session, so this session must still roll over.
RecordingPreferences(context).write(RecordingLimit(false, 15, LimitAction.STOP))
instrumentation.runOnMainSync { activity.finish() }
awaitState(70_000) { RecordingService.activeId != null && RecordingService.activeId != firstId }
val secondId = RecordingService.activeId!!
assertEquals(2, RecordingService.part)
assertTrue(RecordingService.elapsed < 2000)
assertTrue(RecordingService.marks.isEmpty())
val first = Recordings(context).list().first { it.id == firstId }
assertTrue(first.duration in 60_000..62_000)
assertEquals(1, first.marks.size)
assertTrue(first.title.endsWith("Part 1"))
checkPlayable(first)
awaitState { RecordingService.elapsed > 1300 }
command(RecordingService.SAVE)
awaitState { RecordingService.activeId == null }
val second = Recordings(context).list().first { it.id == secondId }
assertTrue(second.duration in 1300..5000)
assertTrue(second.title.endsWith("Part 2"))
checkPlayable(second)
}
}
@@ -0,0 +1,36 @@
package meghdad.remember
import android.content.ContextWrapper
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import java.io.File
import java.util.UUID
@RunWith(AndroidJUnit4::class)
class RecordingsTest {
@Test fun clipsPersistRenameSortAndDeleteWithoutTouchingOtherAudio() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val folder = File(context.cacheDir, "test-${UUID.randomUUID()}").apply { mkdirs() }
try {
val isolated = object : ContextWrapper(context) { override fun getFilesDir() = folder }
val store = Recordings(isolated)
val old = Clip("first", "A thought", 1L, 60000L, listOf(1000L, 45000L))
val recent = Clip("second", "Street sounds", 2L, 10000L, emptyList())
store.audio(old.id).writeText("test audio")
store.audio(recent.id).writeText("test audio")
store.save(old); store.save(recent)
assertEquals(listOf(recent, old), Recordings(isolated).list())
store.save(old.copy(title = "Renamed idea"))
assertEquals("Renamed idea", store.list().last().title)
assertEquals(old.marks, store.list().last().marks)
store.delete(old)
assertFalse(store.audio(old.id).exists())
assertEquals(listOf(recent), store.list())
File(folder, "recordings/broken.json").writeText("invalid")
assertEquals(listOf(recent), store.list())
} finally { folder.deleteRecursively() }
}
}
@@ -0,0 +1,55 @@
package meghdad.remember
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.NumberPicker
import android.widget.Switch
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SettingsTest {
@Test fun settingsNavigationPersistsCustomLengthModeAndUnlimitedToggle() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val preferences = RecordingPreferences(context)
val previous = preferences.read()
val activity = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
try {
instrumentation.runOnMainSync {
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
fun button(prefix: String) = descendants(activity.window.decorView).filterIsInstance<Button>().first { it.text.startsWith(prefix) }
button("Settings").performClick()
button("Recording limit").performClick()
descendants(activity.window.decorView).filterIsInstance<Switch>().single().isChecked = true
button("Length").performClick()
descendants(activity.window.decorView).filterIsInstance<NumberPicker>().single().value = 137
button("Save").performClick()
button("At the limit").performClick()
button("Save & start next").performClick()
button("Back").performClick()
assertEquals(RecordingLimit(true, 137, LimitAction.NEXT_CLIP), preferences.read())
descendants(activity.window.decorView).filterIsInstance<Switch>().single().isChecked = false
assertEquals(RecordingLimit(false, 137, LimitAction.NEXT_CLIP), RecordingPreferences(context).read())
}
} finally {
preferences.write(previous)
instrumentation.runOnMainSync { activity.finish() }
}
}
@Test fun deviceAndAppStorageAreReportedWithoutUsagePermission() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val usage = readStorageUsage(context)
assertTrue(usage.total > 0)
assertTrue(usage.available in 0..usage.total)
assertTrue(usage.appUsed >= java.io.File(context.applicationInfo.sourceDir).length())
assertTrue(usage.recordings >= 0)
assertTrue(usage.appUsed >= usage.recordings)
}
}
+20 -14
View File
@@ -1,15 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Remember" />
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<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" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application android:allowBackup="false" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@drawable/ic_remember"
android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.Remember">
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
<activity android:name=".MainActivity" android:exported="true" android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RecordingService" android:exported="false" android:foregroundServiceType="microphone" />
</application>
</manifest>
@@ -0,0 +1,463 @@
package meghdad.remember
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.*
import android.graphics.drawable.GradientDrawable
import android.media.MediaPlayer
import android.os.*
import android.view.*
import android.widget.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.*
class MainActivity : Activity() {
private val ink = Color.rgb(13, 17, 11)
private val mint = Color.rgb(199, 234, 24)
private val muted = Color.rgb(164, 175, 143)
private lateinit var body: LinearLayout
private lateinit var scroll: ScrollView
private lateinit var store: Recordings
private var screen = "home"
private var clip: Clip? = null
private var player: MediaPlayer? = null
private var minutes: MinuteCounterView? = null
private var motionAllowed = false
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 play: Button? = null
private var seek: SeekBar? = null
private var active = false
private lateinit var preferences: RecordingPreferences
private var limitPicker: NumberPicker? = null
private val storageWorker = java.util.concurrent.Executors.newSingleThreadExecutor()
private var storageRequest = 0
private var storageBusy = false
private var lastStorageRead = 0L
private var storageChart: StorageChartView? = null
private var storageAvailable: TextView? = null
private var storageApp: TextView? = null
private val handler = Handler(Looper.getMainLooper())
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"
}
player?.let { p ->
runCatching {
updateDial(p.currentPosition.toLong())
seek?.progress = p.currentPosition
play?.text = if (p.isPlaying) "Pause" else "Play"
}
}
if (screen == "storage" && SystemClock.elapsedRealtime() - lastStorageRead > 5000 && !storageBusy) loadStorage()
RecordingService.message?.let { Toast.makeText(this@MainActivity, it, Toast.LENGTH_SHORT).show(); RecordingService.message = null }
handler.postDelayed(this, 150)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= 33) onBackInvokedDispatcher.registerOnBackInvokedCallback(0) { navigateBack() }
preferences = RecordingPreferences(this)
store = Recordings(this)
store.recover()
active = RecordingService.activeId != null
render()
}
override fun onResume() {
super.onResume()
motionAllowed = android.animation.ValueAnimator.areAnimatorsEnabled() && !getSystemService(PowerManager::class.java).isPowerSaveMode
minutes?.setFloating(motionAllowed && !RecordingService.paused && minutes?.visibility == View.VISIBLE)
handler.post(ticker)
}
override fun onPause() { handler.removeCallbacks(ticker); minutes?.setFloating(false); player?.pause(); super.onPause() }
override fun onDestroy() { releasePlayer(); storageWorker.shutdown(); super.onDestroy() }
private fun dp(value: Int) = (value * resources.displayMetrics.density).roundToInt()
private fun background(color: Int, radius: Float = 28f) = GradientDrawable().apply { setColor(color); cornerRadius = dp(radius.toInt()).toFloat() }
private fun text(value: String, size: Float, color: Int = Color.WHITE): TextView {
return TextView(this).apply {
text = value; textSize = size; setTextColor(color); gravity = Gravity.CENTER
setPadding(dp(4), dp(2), dp(4), dp(2))
setShadowLayer(dp(2).toFloat(), 0f, dp(1).toFloat(), Color.BLACK)
layoutParams = LinearLayout.LayoutParams(-1, -2)
body.addView(this)
}
}
private fun button(label: String, color: Int = Color.rgb(43, 52, 32), action: () -> Unit): Button {
return Button(this).apply {
text = label; textSize = 12f; isAllCaps = false; setTextColor(Color.WHITE)
background = if (color == mint) background(Color.argb(190, 24, 31, 16)).apply {
setStroke(dp(1), Color.argb(140, 199, 234, 24))
} else background(Color.argb(205, Color.red(color), Color.green(color), Color.blue(color)))
minHeight = 0; minimumHeight = 0
stateListAnimator = null
layoutParams = LinearLayout.LayoutParams(-1, dp(44)).apply { setMargins(dp(2), dp(3), dp(2), dp(3)) }
setOnClickListener { performHapticFeedback(HapticFeedbackConstants.CONFIRM); action() }
body.addView(this)
}
}
private fun render() {
minutes?.setFloating(false)
minutes = null; status = null; pause = null; play = null; seek = null; limitPicker = null
storageRequest++; storageChart = null; storageAvailable = null; storageApp = null
dial = SpatialDialDrawable()
val layers = FrameLayout(this).apply { background = dial }
minutes = MinuteCounterView(this).also { layers.addView(it, FrameLayout.LayoutParams(-1, -1)) }
scroll = ScrollView(this).apply { setBackgroundColor(Color.TRANSPARENT); isFillViewport = true; isVerticalScrollBarEnabled = false }
body = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
val round = resources.configuration.isScreenRound
setPadding(dp(if (round) 30 else 20), dp(16), dp(if (round) 30 else 20), dp(20))
}
scroll.addView(body)
layers.addView(scroll, FrameLayout.LayoutParams(-1, -1))
setContentView(layers)
window.decorView.windowInsetsController?.hide(WindowInsets.Type.systemBars())
window.decorView.windowInsetsController?.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
scroll.setOnTouchListener { _, event ->
val edge = screen in listOf("home", "detail") && event.x > scroll.width * .82f && event.y in scroll.height * .23f..scroll.height * .77f
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = event.x; downY = event.y
edge && (active || screen == "detail" || screen == "home")
}
MotionEvent.ACTION_MOVE -> edge && (active || screen == "detail" || screen == "home")
MotionEvent.ACTION_UP -> {
if (edge && kotlin.math.abs(event.x - downX) < dp(20) && kotlin.math.abs(event.y - downY) < dp(20)) {
when {
active && screen == "home" -> { command(RecordingService.MARK); scroll.performHapticFeedback(HapticFeedbackConstants.CONFIRM) }
screen == "detail" -> seekFromEdge(event.x, event.y)
screen == "home" -> { screen = "library"; render() }
}
scroll.performClick()
true
} else false
}
else -> false
}
}
scroll.isFocusableInTouchMode = true; scroll.requestFocus()
scroll.setOnGenericMotionListener { _, event ->
if (event.action == MotionEvent.ACTION_SCROLL) {
val movement = event.getAxisValue(MotionEvent.AXIS_SCROLL)
if (screen == "limit_minutes" && limitPicker != null) {
limitPicker?.let { picker -> picker.value = (picker.value + if (movement > 0) -1 else 1).coerceIn(picker.minValue, picker.maxValue) }
} else scroll.smoothScrollBy(0, (-movement * dp(35)).toInt())
true
} else false
}
when {
screen == "settings" -> settings()
screen == "storage" -> storage()
screen == "limits" -> limits()
screen == "limit_minutes" -> limitMinutes()
screen == "limit_action" -> limitAction()
active && screen == "home" -> recording()
screen == "library" -> library()
screen == "detail" -> detail()
else -> home()
}
}
private fun counter(elapsed: Long, saved: Boolean = false) {
minutes?.update(elapsed, saved)
// Foreground breathing room; the numeral itself lives in the full-screen layer below.
body.addView(Space(this), LinearLayout.LayoutParams(-1, dp(62)))
}
private fun updateDial(elapsed: Long) {
dial.elapsed = elapsed
dial.mode = when {
screen !in listOf("home", "detail") -> DialMode.LIBRARY
active && RecordingService.paused -> DialMode.PAUSED
active -> DialMode.RECORDING
screen == "detail" -> DialMode.PLAYBACK
screen == "library" -> DialMode.LIBRARY
else -> DialMode.READY
}
dial.duration = clip?.duration ?: 0L
dial.marks = if (active) RecordingService.marks else if (screen == "detail") clip?.marks.orEmpty() else emptyList()
// Logarithmic peak scaling makes quiet speech visible without inventing a waveform.
val peak = RecordingService.amplitude.coerceAtLeast(0)
dial.level = if (peak == 0 || RecordingService.paused) 0f else (ln(1f + peak) / ln(32768f)).coerceIn(0f, 1f)
minutes?.visibility = if (dial.mode == DialMode.LIBRARY) View.GONE else View.VISIBLE
minutes?.update(elapsed, dial.mode == DialMode.READY)
minutes?.setFloating(motionAllowed && dial.mode != DialMode.PAUSED && dial.mode != DialMode.LIBRARY)
dial.invalidateSelf()
}
private fun seekFromEdge(x: Float, y: Float) {
val item = clip ?: return
val angle = Math.toDegrees(atan2((y - scroll.height / 2f).toDouble(), (x - scroll.width / 2f).toDouble()))
val fraction = ((angle + 32) / 64).coerceIn(0.0, 1.0)
if (player == null) togglePlayback(item)
player?.seekTo((fraction * item.duration).toInt())
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)
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"
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
val moments = button("Moments · ${clips.size}") { screen = "library"; render() }.apply { textSize = 11f }
val settings = button("Settings") { screen = "settings"; render() }.apply { textSize = 11f }
body.removeView(moments); body.removeView(settings)
row.addView(moments, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginEnd = dp(3) })
row.addView(settings, LinearLayout.LayoutParams(dp(64), dp(44)).apply { marginStart = dp(3) })
body.addView(row, LinearLayout.LayoutParams(-1, dp(44)).apply { topMargin = dp(3) })
}
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) }
button("Settings") { screen = "settings"; render() }
}
private fun settings() {
updateDial(0)
text("SETTINGS", 10f, mint)
text("Make it yours.", 17f)
button("Storage") { screen = "storage"; render() }.apply { layoutParams.height = dp(56) }
button("Recording limit") { screen = "limits"; render() }.apply { layoutParams.height = dp(56) }
button(if (active) "Back to recording" else "Back") { screen = "home"; render() }
}
private fun storage() {
updateDial(0)
body.setPadding(dp(12), dp(8), dp(12), dp(20))
text("STORAGE", 10f, mint)
storageChart = StorageChartView(this).also {
// Center a large chart in the initial viewport; details and actions follow below it.
val chartHeight = (resources.displayMetrics.heightPixels - dp(52)).coerceAtLeast(dp(140))
body.addView(it, LinearLayout.LayoutParams(-1, chartHeight))
}
storageAvailable = text("● Available · …", 11f, mint)
storageApp = text("● Remember · …", 11f)
button("Refresh") { loadStorage() }
button("Back") { screen = "settings"; render() }
loadStorage()
}
private fun loadStorage() {
if (storageBusy || storageWorker.isShutdown) return
storageBusy = true; lastStorageRead = SystemClock.elapsedRealtime()
val request = storageRequest
storageWorker.execute {
val result = runCatching { readStorageUsage(applicationContext) }
handler.post {
storageBusy = false
if (isDestroyed || screen != "storage" || request != storageRequest) return@post
result.onSuccess { usage ->
fun size(bytes: Long) = android.text.format.Formatter.formatShortFileSize(this, bytes)
storageChart?.update(usage)
storageAvailable?.text = "● Available · ${size(usage.available)}"
storageApp?.text = "● Remember · ${if (usage.estimated) "≈ " else ""}${size(usage.appUsed)}"
}.onFailure {
storageChart?.showFailure()
storageAvailable?.text = "Could not read storage"
storageApp?.text = "Tap Refresh to retry"
}
}
}
}
private fun limits() {
updateDial(0)
val limit = preferences.read()
text("RECORDING LIMIT", 10f, mint)
val toggle = Switch(this).apply {
text = "Minute limit"; textSize = 12f; setTextColor(Color.WHITE)
isChecked = limit.enabled
thumbTintList = android.content.res.ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf()),
intArrayOf(mint, Color.rgb(116, 129, 96))
)
setPadding(dp(5), 0, dp(5), 0)
body.addView(this, LinearLayout.LayoutParams(-1, dp(44)))
setOnCheckedChangeListener { _, checked -> preferences.write(preferences.read().copy(enabled = checked)); render() }
}
text(if (toggle.isChecked) "Enabled" else "Unlimited recording", 10f, muted)
button("Length · ${limit.minutes} min") { screen = "limit_minutes"; render() }
button("At the limit\n${if (limit.action == LimitAction.STOP) "Save & stop" else "Save & start next"}") {
screen = "limit_action"; render()
}.apply { layoutParams.height = dp(54); textSize = 11f }
text("Applies to your next recording session.\nPaused time doesn't count.", 10f, muted)
button("Back") { screen = "settings"; render() }
}
private fun limitMinutes() {
updateDial(0)
text("CLIP LENGTH", 10f, mint)
text("Minutes", 13f)
limitPicker = NumberPicker(this).apply {
minValue = 1; maxValue = 1440; value = preferences.read().minutes; wrapSelectorWheel = false
contentDescription = "Recording limit in minutes"
setTextColor(Color.WHITE); setTextSize(android.util.TypedValue.applyDimension(android.util.TypedValue.COMPLEX_UNIT_SP, 22f, resources.displayMetrics))
body.addView(this, LinearLayout.LayoutParams(dp(116), dp(100)))
}
button("Save", mint) {
limitPicker?.clearFocus()
preferences.write(preferences.read().copy(minutes = limitPicker?.value ?: 15))
screen = "limits"; render()
}
button("Cancel") { screen = "limits"; render() }
}
private fun limitAction() {
updateDial(0)
text("AT THE LIMIT", 10f, mint)
val action = preferences.read().action
button("${if (action == LimitAction.STOP) "✓ " else ""}Save & stop", if (action == LimitAction.STOP) mint else Color.rgb(43, 52, 32)) {
preferences.write(preferences.read().copy(action = LimitAction.STOP)); render()
}
button("${if (action == LimitAction.NEXT_CLIP) "✓ " else ""}Save & start next", if (action == LimitAction.NEXT_CLIP) mint else Color.rgb(43, 52, 32)) {
preferences.write(preferences.read().copy(action = LimitAction.NEXT_CLIP)); render()
}
text("New clips start at 0.\nA brief gap can occur between clips.", 11f, muted)
button("Back") { screen = "limits"; render() }
}
private fun library() {
updateDial(0)
text("YOUR MOMENTS", 10f, mint)
val clips = store.list()
if (clips.isEmpty()) {
text("A little space\nfor big ideas.", 20f)
text("Record a thought, a song,\nor the sounds around you.", 12f, muted)
button("Record a moment", mint) { screen = "home"; render(); startRecording() }
} else {
text("${clips.size} saved", 12f, muted)
clips.forEach { item ->
button("${item.title}\n${SimpleDateFormat("MMM d", Locale.getDefault()).format(Date(item.created))} · ${timeLabel(item.duration)}") {
clip = item; screen = "detail"; render()
}.apply {
textSize = 11f
layoutParams.height = dp(54)
maxLines = 2
}
}
}
button("Back") { screen = "home"; render() }
}
private fun detail() {
val item = clip ?: run { screen = "library"; render(); return }
text("SAVED MOMENT", 10f, mint)
text(item.title, 16f)
counter(player?.currentPosition?.toLong() ?: 0)
updateDial(player?.currentPosition?.toLong() ?: 0)
seek = SeekBar(this).apply {
max = item.duration.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
progressTintList = android.content.res.ColorStateList.valueOf(mint)
thumbTintList = android.content.res.ColorStateList.valueOf(mint)
contentDescription = "Playback position"
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(bar: SeekBar?, value: Int, user: Boolean) { if (user) player?.seekTo(value) }
override fun onStartTrackingTouch(bar: SeekBar?) {}
override fun onStopTrackingTouch(bar: SeekBar?) {}
})
body.addView(this, LinearLayout.LayoutParams(-1, dp(38)))
}
play = button("Play", mint) { togglePlayback(item) }
text("${timeLabel(item.duration)} · AAC audio", 10f, muted)
item.marks.forEachIndexed { index, position ->
button("Mark ${index + 1} · ${timeLabel(position)}") {
if (player == null) togglePlayback(item)
player?.seekTo(position.coerceAtMost(Int.MAX_VALUE.toLong()).toInt())
}
}
button("Rename") {
val input = EditText(this).apply { setText(item.title); selectAll(); maxLines = 1 }
AlertDialog.Builder(this).setTitle("Name this moment").setView(input)
.setPositiveButton("Save") { _, _ ->
val name = input.text.toString().trim().take(80)
if (name.isNotEmpty()) {
val updated = item.copy(title = name)
runCatching { store.save(updated); clip = updated; render() }.onFailure { showError("Could not rename moment") }
}
}.setNegativeButton("Cancel", null).show()
}
button("Delete", Color.rgb(67, 32, 38)) {
AlertDialog.Builder(this).setTitle("Delete this moment?").setMessage("This recording will be permanently removed.")
.setPositiveButton("Delete") { _, _ ->
releasePlayer()
runCatching { store.delete(item); screen = "library"; render() }.onFailure { showError("Could not delete moment") }
}.setNegativeButton("Keep", null).show()
}
button("Back") { releasePlayer(); screen = "library"; render() }
}
private fun togglePlayback(item: Clip) {
try {
if (player == null) {
player = MediaPlayer().apply {
setDataSource(store.audio(item.id).absolutePath)
prepare()
setOnCompletionListener { play?.text = "Play"; seekTo(0); updateDial(0) }
setOnErrorListener { _, _, _ -> releasePlayer(); showError("Could not play this moment"); true }
}
}
player?.let { if (it.isPlaying) it.pause() else it.start() }
} catch (_: Exception) { releasePlayer(); showError("Could not play this moment") }
}
private fun releasePlayer() { player?.release(); player = null }
private fun showError(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() }
private fun startRecording() {
releasePlayer()
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 10); return
}
command(RecordingService.START)
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 11)
}
}
private fun command(action: String) {
try {
val intent = Intent(this, RecordingService::class.java).setAction(action)
if (action == RecordingService.START) startForegroundService(intent) else startService(intent)
} catch (_: Exception) { showError("Could not start recording. Check microphone permission.") }
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 10) {
if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) startRecording()
else AlertDialog.Builder(this).setTitle("Microphone access needed")
.setMessage("Allow microphone access to capture the sounds around you.")
.setPositiveButton("Settings") { _, _ -> startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, android.net.Uri.parse("package:$packageName"))) }
.setNegativeButton("Later", null).show()
}
}
// API 31–32 fallback; API 33+ uses the registered OnBackInvokedCallback.
@android.annotation.SuppressLint("GestureBackNavigation")
@Deprecated("Framework back navigation")
override fun onBackPressed() { navigateBack() }
private fun navigateBack() {
if (screen != "home") {
releasePlayer()
screen = when (screen) {
"detail" -> "library"
"storage", "limits" -> "settings"
"limit_minutes", "limit_action" -> "limits"
else -> "home"
}
render()
} else finish()
}
}
@@ -0,0 +1,82 @@
package meghdad.remember
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.view.View
import android.view.animation.LinearInterpolator
import kotlin.math.sin
/** Rounded numeral artwork sits behind the controls; its value is always measured minutes. */
class MinuteCounterView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND; strokeWidth = 30f
}
private val digits = (0..9).map { digitPath(it) }
private var elapsed = 0L
private var saved = false
private var floating = false
private val drift = ValueAnimator.ofFloat(0f, (Math.PI * 2).toFloat()).apply {
duration = 9000; repeatCount = ValueAnimator.INFINITE; interpolator = LinearInterpolator()
addUpdateListener {
val phase = it.animatedValue as Float
translationX = sin(phase) * width * .016f
translationY = sin(phase + .8f) * height * .012f
rotation = sin(phase) * .8f
}
}
fun setFloating(enabled: Boolean) {
floating = enabled
if (enabled && isAttachedToWindow && !drift.isStarted) drift.start()
else if (!enabled) {
drift.cancel(); translationX = 0f; translationY = 0f; rotation = 0f
}
}
fun update(time: Long, savedTotal: Boolean = false) {
val numberChanged = elapsed / 60_000 != time / 60_000 || saved != savedTotal
val secondsChanged = elapsed / 1000 != time / 1000 || saved != savedTotal
elapsed = time.coerceAtLeast(0); saved = savedTotal
if (secondsChanged || contentDescription == null) {
contentDescription = if (saved) "${elapsed / 60_000} saved minutes" else "${elapsed / 60_000} minutes, ${elapsed / 1000 % 60} seconds"
}
if (numberChanged) invalidate()
}
override fun onAttachedToWindow() { super.onAttachedToWindow(); setFloating(floating) }
override fun onDetachedFromWindow() { drift.cancel(); super.onDetachedFromWindow() }
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val numeral = (elapsed / 60_000).toString()
val artworkWidth = numeral.length * 100f - 4f
val scale = minOf(width * .67f / artworkWidth, height * .73f / 150f)
canvas.save()
canvas.translate((width - artworkWidth * scale) / 2f + width * .02f, (height - 150 * scale) / 2f - height * .025f)
canvas.scale(scale, scale)
paint.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)
numeral.forEach { character ->
canvas.drawPath(digits[character.digitToInt()], paint)
canvas.translate(100f, 0f)
}
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,24 @@
package meghdad.remember
import android.content.Context
enum class LimitAction { STOP, NEXT_CLIP }
data class RecordingLimit(val enabled: Boolean = false, val minutes: Int = 15, val action: LimitAction = LimitAction.STOP) {
init { require(minutes in 1..1440) }
val durationMs: Long get() = minutes * 60_000L
fun actionAt(elapsed: Long): LimitAction? = if (enabled && elapsed >= durationMs) action else null
}
class RecordingPreferences(context: Context) {
private val preferences = context.getSharedPreferences("recording_settings", Context.MODE_PRIVATE)
fun read() = RecordingLimit(
preferences.getBoolean("limit_enabled", false),
preferences.getInt("limit_minutes", 15).coerceIn(1, 1440),
runCatching { LimitAction.valueOf(preferences.getString("limit_action", LimitAction.STOP.name)!!) }.getOrDefault(LimitAction.STOP)
)
fun write(limit: RecordingLimit) {
preferences.edit().putBoolean("limit_enabled", limit.enabled).putInt("limit_minutes", limit.minutes)
.putString("limit_action", limit.action.name).apply()
}
}
@@ -0,0 +1,168 @@
package meghdad.remember
import android.app.*
import android.content.Intent
import android.content.pm.ServiceInfo
import android.media.MediaRecorder
import android.os.*
import java.text.SimpleDateFormat
import java.util.*
class RecordingService : Service() {
companion object {
@Volatile var activeId: String? = null; private set
@Volatile var paused = false; private set
@Volatile var elapsed = 0L; private set
@Volatile var amplitude = 0; private set
@Volatile var marks: List<Long> = emptyList(); private set
@Volatile var part = 1; private set
var message: String? = null
const val START = "start"
const val PAUSE = "pause"
const val SAVE = "save"
const val MARK = "mark"
}
private var recorder: MediaRecorder? = null
private var lock: PowerManager.WakeLock? = null
private var segmentStart = 0L
private var accumulated = 0L
private var created = 0L
private var lockRenewed = 0L
private var sessionTitle = ""
private var sessionLimit = RecordingLimit()
private var transitioning = false
private val handler = Handler(Looper.getMainLooper())
private fun capturedTime() = accumulated + if (paused) 0L else SystemClock.elapsedRealtime() - segmentStart
private val tick = object : Runnable {
override fun run() {
if (recorder == null || transitioning) return
if (!paused && SystemClock.elapsedRealtime() - lockRenewed > 9 * 60 * 1000L) {
lock?.acquire(10 * 60 * 1000L)
lockRenewed = SystemClock.elapsedRealtime()
}
elapsed = capturedTime()
amplitude = if (paused) 0 else runCatching { recorder?.maxAmplitude ?: 0 }.getOrDefault(0)
when (sessionLimit.actionAt(elapsed)) {
LimitAction.STOP -> finishRecording("Minute limit reached · saved")
LimitAction.NEXT_CLIP -> nextClip()
null -> handler.postDelayed(this, 100)
}
}
}
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()
SAVE -> if (recorder != null) finishRecording() else stopSelf()
}
} catch (_: Exception) {
message = "Recording interrupted. Please try again."
release(); stopSelf()
}
return START_NOT_STICKY
}
private fun begin() {
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(NotificationChannel("capture", "Audio recording", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
val save = PendingIntent.getService(this, 1, Intent(this, RecordingService::class.java).setAction(SAVE), PendingIntent.FLAG_IMMUTABLE)
val notification = Notification.Builder(this, "capture").setSmallIcon(R.drawable.ic_remember)
.setContentTitle("Remember is recording").setContentText("Tap to open • Save when you're done")
.setContentIntent(open).setOngoing(true).addAction(Notification.Action.Builder(null, "Save", save).build()).build()
startForeground(7, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
sessionLimit = RecordingPreferences(this).read()
sessionTitle = "Moment · " + SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())
part = 1; message = null
lock = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "remember:capture").apply {
setReferenceCounted(false); acquire(10 * 60 * 1000L)
}
lockRenewed = SystemClock.elapsedRealtime()
startClip()
}
private fun startClip() {
created = System.currentTimeMillis()
val id = UUID.randomUUID().toString()
accumulated = 0; elapsed = 0; marks = emptyList(); paused = false; amplitude = 0
val current = MediaRecorder(this)
recorder = current
current.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setAudioSamplingRate(44100); setAudioEncodingBitRate(128000); setAudioChannels(1)
setOutputFile(Recordings(this@RecordingService).pending(id).absolutePath)
setOnErrorListener { source, _, _ -> if (source === recorder && !transitioning) finishRecording("Recorder stopped · saved") }
setMaxFileSize(500L * 1024 * 1024)
setOnInfoListener { source, what, _ ->
if (source === recorder && !transitioning && what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
finishRecording("File size limit reached · saved")
}
}
prepare(); start()
}
segmentStart = SystemClock.elapsedRealtime()
// During rollover the old ID stays visible until the new recorder is ready.
activeId = id
handler.post(tick)
}
private fun togglePause() {
val current = recorder ?: return
if (transitioning) return
if (paused) { current.resume(); segmentStart = SystemClock.elapsedRealtime(); paused = false }
else {
current.pause(); accumulated += SystemClock.elapsedRealtime() - segmentStart
elapsed = accumulated; paused = true
}
}
private fun saveClip(): Boolean {
val current = recorder ?: return false
val id = activeId ?: return false
handler.removeCallbacks(tick)
elapsed = capturedTime()
return try {
current.stop()
val store = Recordings(this)
check(store.pending(id).renameTo(store.audio(id)))
val title = sessionTitle + if (sessionLimit.enabled && sessionLimit.action == LimitAction.NEXT_CLIP) " · Part $part" else ""
store.save(Clip(id, title, created, elapsed, marks))
true
} catch (_: Exception) {
message = "Could not save this clip. Recording stopped."
false
} finally {
runCatching { current.release() }; recorder = null
}
}
private fun nextClip() {
if (transitioning) return
transitioning = true
try {
if (!saveClip()) { release(); stopSelf(); return }
val savedPart = part
part++
// Keep the same microphone foreground service and wake lock, including with screen off.
startClip()
message = "Part $savedPart saved · next clip started"
} catch (_: Exception) {
message = "Clip saved, but the next recording could not start."
release(); stopSelf()
} finally { transitioning = false }
}
private fun finishRecording(successMessage: String = "Moment saved") {
if (recorder == null || transitioning) return
transitioning = true
try { if (saveClip()) message = successMessage }
finally { release(); transitioning = false; stopSelf() }
}
private fun release() {
handler.removeCallbacks(tick)
runCatching { recorder?.release() }; recorder = null
lock?.let { if (it.isHeld) it.release() }; lock = null
activeId = null; paused = false; amplitude = 0
stopForeground(STOP_FOREGROUND_REMOVE)
}
override fun onDestroy() { if (recorder != null) finishRecording(); super.onDestroy() }
}
@@ -0,0 +1,54 @@
package meghdad.remember
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
data class Clip(val id: String, val title: String, val created: Long, val duration: Long, val marks: List<Long>)
class Recordings(private val context: Context) {
private val directory = File(context.filesDir, "recordings").apply { mkdirs() }
fun audio(id: String) = File(directory, "$id.m4a")
fun pending(id: String) = File(directory, "$id.pending")
fun list(): List<Clip> = directory.listFiles().orEmpty().filter { it.extension == "json" }.mapNotNull { file ->
runCatching {
val json = JSONObject(file.readText())
val marks = json.optJSONArray("marks") ?: JSONArray()
Clip(file.nameWithoutExtension, json.getString("title"), json.getLong("created"), json.getLong("duration"),
(0 until marks.length()).map { marks.getLong(it) })
}.getOrNull()
}.filter { audio(it.id).exists() }.sortedByDescending { it.created }
fun save(clip: Clip) {
val json = JSONObject().put("title", clip.title).put("created", clip.created)
.put("duration", clip.duration).put("marks", JSONArray(clip.marks))
val temp = File(directory, "${clip.id}.tmp")
temp.writeText(json.toString())
check(temp.renameTo(File(directory, "${clip.id}.json"))) { "Could not save recording details" }
}
fun delete(clip: Clip) {
check(!audio(clip.id).exists() || audio(clip.id).delete()) { "Could not delete audio" }
File(directory, "${clip.id}.json").delete()
}
// A process interruption can leave a playable audio file without its final metadata.
fun recover() {
directory.listFiles().orEmpty().filter { it.extension == "pending" || (it.extension == "m4a" && !File(directory, "${it.nameWithoutExtension}.json").exists()) }.forEach { file ->
if (file.nameWithoutExtension == RecordingService.activeId) return@forEach
val retriever = android.media.MediaMetadataRetriever()
try {
retriever.setDataSource(file.absolutePath)
val duration = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
if (duration > 0 && (file.extension == "m4a" || file.renameTo(audio(file.nameWithoutExtension)))) {
save(Clip(file.nameWithoutExtension, "Recovered moment", file.lastModified(), duration, emptyList()))
}
} catch (_: Exception) { /* Keep interrupted files for a future recovery attempt. */ }
finally { retriever.release() }
}
}
}
fun timeLabel(ms: Long): String {
val seconds = ms / 1000
return if (seconds >= 3600) String.format(java.util.Locale.US, "%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60)
else String.format(java.util.Locale.US, "%02d:%02d", seconds / 60, seconds % 60)
}
@@ -0,0 +1,72 @@
package meghdad.remember
import android.graphics.*
import android.graphics.drawable.Drawable
import kotlin.math.*
enum class DialMode { READY, RECORDING, PAUSED, PLAYBACK, LIBRARY }
/** Time and edge instruments share one fixed dial behind the scrolling controls. */
class SpatialDialDrawable : Drawable() {
var mode = DialMode.READY
var elapsed = 0L
var duration = 0L
var level = 0f
var marks: List<Long> = emptyList()
var freeStorage = 1f
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val lime = Color.rgb(199, 234, 24)
private val track = Color.rgb(61, 73, 42)
private fun line(canvas: Canvas, ring: RectF, angle: Float, sweep: Float, color: Int, width: Float) {
paint.shader = null; paint.color = color; paint.style = Paint.Style.STROKE
paint.strokeWidth = width; paint.strokeCap = Paint.Cap.ROUND
canvas.drawArc(ring, angle, sweep, false, paint)
paint.style = Paint.Style.FILL
}
override fun draw(canvas: Canvas) {
val w = bounds.width().toFloat(); val h = bounds.height().toFloat(); val size = minOf(w, h)
val cx = w / 2; val cy = h / 2
canvas.save(); canvas.translate(bounds.left.toFloat(), bounds.top.toFloat())
canvas.drawColor(Color.rgb(13, 17, 11))
paint.shader = RadialGradient(w * .65f, h * .3f, size * .8f,
intArrayOf(Color.rgb(48, 57, 35), Color.rgb(22, 29, 18), Color.rgb(13, 17, 11)),
floatArrayOf(0f, .65f, 1f), Shader.TileMode.CLAMP)
canvas.drawRect(0f, 0f, w, h, paint); paint.shader = null
val seconds = (elapsed.coerceAtLeast(0) % 60_000) / 60_000f
val face = RectF(cx - size * .49f, cy - size * .49f, cx + size * .49f, cy + size * .49f)
// One half of the dial fills in 60 seconds, then starts again at the next minute.
paint.color = Color.argb(32, 156, 174, 105)
canvas.drawArc(face, -90f, 180f * seconds, true, paint)
if (mode == DialMode.LIBRARY) { canvas.restore(); return }
val radius = size * .46f
val ring = RectF(cx - radius, cy - radius, cx + radius, cy + radius)
val stroke = size * .014f
// Left: the real microphone peak, or remaining storage before capture.
for (i in 0..11) {
val lit = when (mode) {
DialMode.READY -> i < (freeStorage * 12).roundToInt()
DialMode.RECORDING -> i < (level * 12).roundToInt()
DialMode.PLAYBACK -> duration > 0 && i < (12 * (1f - elapsed.toFloat() / duration).coerceIn(0f, 1f)).roundToInt()
else -> false
}
line(canvas, ring, 211f - i * 5.3f, 2.4f, if (lit) lime else track, stroke)
}
// Right: bookmark locations; in playback the arc also shows total progress.
line(canvas, ring, -32f, 64f, track, stroke)
if (mode == DialMode.PLAYBACK && duration > 0) {
line(canvas, ring, -32f, 64f * (elapsed.toFloat() / duration).coerceIn(0f, 1f), lime, stroke)
}
val span = if (mode == DialMode.PLAYBACK) duration else elapsed
marks.forEach { mark ->
val angle = Math.toRadians((-32 + 64 * (mark.toFloat() / span.coerceAtLeast(1)).coerceIn(0f, 1f)).toDouble())
val x = cx + cos(angle).toFloat() * radius
val y = cy + sin(angle).toFloat() * radius
paint.color = Color.WHITE; paint.style = Paint.Style.FILL
canvas.drawCircle(x, y, stroke * .85f, paint)
}
canvas.restore()
}
override fun setAlpha(alpha: Int) { paint.alpha = alpha; invalidateSelf() }
override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter; invalidateSelf() }
@Deprecated("Drawable opacity") override fun getOpacity() = PixelFormat.OPAQUE
}
@@ -0,0 +1,64 @@
package meghdad.remember
import android.content.Context
import android.graphics.*
import android.text.format.Formatter
import android.view.View
import kotlin.math.*
/** A proportional device-storage ring. Tiny app slices get a marker, never an inflated wedge. */
class StorageChartView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var usage: StorageUsage? = null
private var failed = false
private val lime = Color.rgb(199, 234, 24)
fun update(value: StorageUsage) {
usage = value; failed = false
val available = Formatter.formatShortFileSize(context, value.available)
val total = Formatter.formatShortFileSize(context, value.total)
val app = Formatter.formatShortFileSize(context, value.appUsed)
contentDescription = "${percent(value)} percent available. $available available out of $total. Remember uses ${if (value.estimated) "approximately " else ""}$app. Gray is other used storage."
invalidate()
}
fun showFailure() { usage = null; failed = true; contentDescription = "Storage unavailable. Tap Refresh."; invalidate() }
private fun percent(value: StorageUsage) = (value.available.toDouble() / value.total.coerceAtLeast(1) * 100).roundToInt().coerceIn(0, 100)
init { contentDescription = "Loading device storage" }
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val size = min(width, height).toFloat()
val cx = width / 2f; val cy = height / 2f
val radius = size * .405f
val thickness = size * .085f
val ring = RectF(cx - radius, cy - radius, cx + radius, cy + radius)
paint.style = Paint.Style.STROKE; paint.strokeWidth = thickness; paint.strokeCap = Paint.Cap.BUTT
paint.color = Color.rgb(101, 114, 81)
canvas.drawOval(ring, paint)
val data = usage
if (data != null && data.total > 0) {
val free = (data.available.toDouble() / data.total).coerceIn(0.0, 1.0)
val app = (data.appUsed.toDouble() / data.total).coerceIn(0.0, 1.0 - free)
paint.color = lime
canvas.drawArc(ring, -90f, (free * 360).toFloat(), false, paint)
if (app > 0) {
paint.color = Color.WHITE
canvas.drawArc(ring, (-90 + free * 360).toFloat(), (app * 360).toFloat(), false, paint)
// The dot makes even a few megabytes discoverable without distorting the proportions.
val angle = Math.toRadians(-90 + (free + app / 2) * 360)
val markerRadius = radius + thickness / 2 + size * .031f
paint.style = Paint.Style.FILL
canvas.drawCircle(cx + cos(angle).toFloat() * markerRadius, cy + sin(angle).toFloat() * markerRadius, size * .012f, paint)
}
}
paint.style = Paint.Style.FILL; paint.textAlign = Paint.Align.CENTER
paint.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
paint.textSize = size * .083f; paint.color = Color.rgb(169, 183, 145)
val total = data?.let { "${Formatter.formatShortFileSize(context, it.total)} total" } ?: if (failed) "Unavailable" else "Loading"
canvas.drawText(total, cx, cy - size * .2f, paint)
paint.typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
paint.textSize = size * .285f; paint.color = Color.WHITE
canvas.drawText(data?.let { "${percent(it)}%" } ?: "—", cx, cy + size * .08f, paint)
paint.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
paint.textSize = size * .085f; paint.color = lime
canvas.drawText("FREE", cx, cy + size * .245f, paint)
}
}
@@ -0,0 +1,33 @@
package meghdad.remember
import android.app.usage.StorageStatsManager
import android.content.Context
import android.os.Process
import android.os.StatFs
import android.os.storage.StorageManager
import java.io.File
import java.nio.file.Files
data class StorageUsage(val total: Long, val available: Long, val appUsed: Long, val recordings: Long, val estimated: Boolean)
/** Called on a worker: Android's storage accounting can take several seconds. */
fun readStorageUsage(context: Context): StorageUsage {
val manager = context.getSystemService(StorageStatsManager::class.java)
val volume = context.applicationInfo.storageUuid ?: StorageManager.UUID_DEFAULT
val filesystem = StatFs(context.dataDir.absolutePath)
val total = runCatching { manager.getTotalBytes(volume) }.getOrDefault(filesystem.totalBytes)
val available = runCatching { manager.getFreeBytes(volume) }.getOrDefault(filesystem.availableBytes).coerceIn(0, total)
val stats = runCatching { manager.queryStatsForPackage(volume, context.packageName, Process.myUserHandle()) }.getOrNull()
// dataBytes already includes cacheBytes; adding cache separately would count it twice.
val appUsed = stats?.let { it.appBytes + it.dataBytes } ?: (
directoryBytes(context.dataDir) + File(context.applicationInfo.sourceDir).length() +
context.applicationInfo.splitSourceDirs.orEmpty().sumOf { File(it).length() } +
context.getExternalFilesDirs(null).filterNotNull().sumOf { directoryBytes(it) } +
context.externalCacheDirs.filterNotNull().sumOf { directoryBytes(it) }
)
return StorageUsage(total, available, appUsed, directoryBytes(File(context.filesDir, "recordings")), stats == null)
}
private fun directoryBytes(directory: File): Long = if (!directory.exists()) 0 else directory.walkTopDown()
.onEnter { !Files.isSymbolicLink(it.toPath()) }
.filter { it.isFile && !Files.isSymbolicLink(it.toPath()) }.sumOf { it.length() }
@@ -1,170 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>
@@ -1,30 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
@@ -0,0 +1,4 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="#192012" android:pathData="M0,0h48v48h-48z" />
<path android:strokeColor="#C7EA18" android:strokeWidth="5" android:strokeLineCap="round" android:pathData="M10,22v5M17,16v17M24,11v27M31,16v17M38,22v5" />
</vector>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

+9 -15
View File
@@ -1,16 +1,10 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Remember" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<resources>
<style name="Theme.Remember" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowBackground">#0D110B</item>
<item name="android:colorAccent">#C7EA18</item>
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
</resources>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
+1 -3
View File
@@ -1,3 +1 @@
<resources>
<string name="app_name">remember</string>
</resources>
<resources><string name="app_name">Remember</string></resources>
+9 -15
View File
@@ -1,16 +1,10 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Remember" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<resources>
<style name="Theme.Remember" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowBackground">#0D110B</item>
<item name="android:colorAccent">#C7EA18</item>
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
</resources>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
+3 -18
View File
@@ -1,19 +1,4 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>
<cloud-backup><exclude domain="root" path="." /></cloud-backup>
<device-transfer><exclude domain="root" path="." /></device-transfer>
</data-extraction-rules>
@@ -1,17 +0,0 @@
package meghdad.remember
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
@@ -0,0 +1,23 @@
package meghdad.remember
import org.junit.Assert.*
import org.junit.Test
class RecordingLimitTest {
@Test fun unlimitedNeverStopsAtConfiguredLength() {
assertNull(RecordingLimit(false, 1, LimitAction.STOP).actionAt(60_000))
assertNull(RecordingLimit(false, 1, LimitAction.NEXT_CLIP).actionAt(Long.MAX_VALUE))
}
@Test fun exactBoundarySelectsTheConfiguredAction() {
val stop = RecordingLimit(true, 15, LimitAction.STOP)
assertNull(stop.actionAt(899_999))
assertEquals(LimitAction.STOP, stop.actionAt(900_000))
val next = RecordingLimit(true, 1, LimitAction.NEXT_CLIP)
assertNull(next.actionAt(59_999))
assertEquals(LimitAction.NEXT_CLIP, next.actionAt(60_000))
assertEquals(LimitAction.NEXT_CLIP, next.actionAt(60_100))
}
@Test fun longLimitsDoNotOverflowMilliseconds() {
assertEquals(86_400_000L, RecordingLimit(true, 1440).durationMs)
}
}
@@ -0,0 +1,15 @@
package meghdad.remember
import org.junit.Assert.assertEquals
import org.junit.Test
class TimeLabelTest {
@Test fun elapsedTimeFormatsMinuteAndHourBoundaries() {
assertEquals("00:00", timeLabel(0))
assertEquals("00:59", timeLabel(59_999))
assertEquals("01:00", timeLabel(60_000))
assertEquals("59:59", timeLabel(3_599_999))
assertEquals("1:00:00", timeLabel(3_600_000))
assertEquals("2:03:04", timeLabel(7_384_000))
}
}