fretfret

learn the notes on a guitar from the comfort of your android phone
Log | Files | Refs

commit cda10ccabf50c2283bd1cc8bbd831b282d0c1912
parent 7af374b7989c019c649e738f8a9902e7f0402997
Author: massi <mdsiboldi@gmail.com>
Date:   Fri, 12 Jul 2024 01:59:41 -0700

rename project to fretfret

Diffstat:
D.idea/.name | 2--
Mapp/build.gradle.kts | 4++--
Dapp/src/androidTest/java/com/example/fretboardtrainer/ExampleInstrumentedTest.kt | 25-------------------------
Mapp/src/main/AndroidManifest.xml | 5++---
Dapp/src/main/java/com/example/fretboardtrainer/MainActivity.kt | 525-------------------------------------------------------------------------------
Dapp/src/main/java/com/example/fretboardtrainer/ui/theme/Color.kt | 12------------
Dapp/src/main/java/com/example/fretboardtrainer/ui/theme/Theme.kt | 59-----------------------------------------------------------
Dapp/src/main/java/com/example/fretboardtrainer/ui/theme/Type.kt | 35-----------------------------------
Aapp/src/main/java/com/massi/fretfret/MainActivity.kt | 525+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/src/main/java/com/massi/fretfret/ui/theme/Color.kt | 12++++++++++++
Aapp/src/main/java/com/massi/fretfret/ui/theme/Theme.kt | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/src/main/java/com/massi/fretfret/ui/theme/Type.kt | 35+++++++++++++++++++++++++++++++++++
Mapp/src/main/res/values/strings.xml | 2+-
Mapp/src/main/res/values/themes.xml | 2+-
Dapp/src/test/java/com/example/fretboardtrainer/ExampleUnitTest.kt | 18------------------
Aapp/src/test/java/com/massi/fretfret/ExampleUnitTest.kt | 18++++++++++++++++++
Msettings.gradle.kts | 2+-
17 files changed, 655 insertions(+), 684 deletions(-)

diff --git a/.idea/.name b/.idea/.name @@ -1 +0,0 @@ -fretboard trainer -\ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts @@ -4,11 +4,11 @@ plugins { } android { - namespace = "com.example.fretboardtrainer" + namespace = "com.massi.fretfret" compileSdk = 34 defaultConfig { - applicationId = "com.example.fretboardtrainer" + applicationId = "com.massi.fretfret" minSdk = 28 targetSdk = 34 versionCode = 1 diff --git a/app/src/androidTest/java/com/example/fretboardtrainer/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/example/fretboardtrainer/ExampleInstrumentedTest.kt @@ -1,24 +0,0 @@ -package com.example.fretboardtrainer - -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("com.example.fretboardtrainer", appContext.packageName) - } -} -\ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml @@ -10,13 +10,12 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" - android:theme="@style/Theme.FretboardTrainer" + android:theme="@style/Theme.Fretfret" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true" - android:label="@string/app_name" - android:theme="@style/Theme.FretboardTrainer"> + android:theme="@style/Theme.Fretfret"> <intent-filter> <action android:name="android.intent.action.MAIN" /> diff --git a/app/src/main/java/com/example/fretboardtrainer/MainActivity.kt b/app/src/main/java/com/example/fretboardtrainer/MainActivity.kt @@ -1,524 +0,0 @@ -package com.example.fretboardtrainer - -import android.app.Application -import android.content.Context -import android.content.pm.ActivityInfo -import android.os.Bundle -import android.util.Log -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.activity.enableEdgeToEdge -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.absoluteOffset -import androidx.compose.foundation.layout.displayCutoutPadding -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Settings -import androidx.compose.material3.Button -import androidx.compose.material3.Checkbox -import androidx.compose.material3.Divider -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.em -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.Preferences -import androidx.datastore.preferences.core.byteArrayPreferencesKey -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.preferencesDataStore -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel -import com.example.fretboardtrainer.ui.theme.FretboardTrainerTheme -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch - -data object Constants { - val STRINGS = listOf("E", "B", "G", "D", "A", "E") - val FRETS = listOf( - "open", "1", "2", "3", "4", "5", "6", - "7", "8", "9", "10", "11", "12" - ) - val NOTES = listOf( - "A", "A♯/B♭", "B", "C", "C♯/D♭", "D", - "D♯/E♭", "E", "F", "F♯/G♭", "G", "G♯/A♭" - ) - const val FRETBOARD_HEIGHT = 200 - val STRING_KEY = byteArrayPreferencesKey("string_key") - val FRET_KEY = byteArrayPreferencesKey("fret_key") -} - -data class Note( - val string: Int, - val fret: Int, -) - -data class FretfretState( - val showSettings: Boolean = false, - val stringSettings: List<Boolean> = List(Constants.STRINGS.size) { true }, - val fretSettings: List<Boolean> = List(Constants.FRETS.size) { true }, - val note: Note? = null, - val lastNote: Note? = null, -) - -val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") - - -fun weightForFret(fretIdx: Int): Float { - var weight = 24 - fretIdx * 1.0f - if (fretIdx == 0) { - weight /= 2 - } - return weight -} - - -class MainViewModel(application: Application) : AndroidViewModel(application) { - private val _uiState = MutableStateFlow(FretfretState()) - val uiState = _uiState.asStateFlow() - - private fun encodeBoolList(l: List<Boolean>): ByteArray { - return ByteArray(l.size) { - when (l[it]) { - true -> 1.toByte() - else -> 0.toByte() - } - } - } - - private fun decodeBoolList(arr: ByteArray): List<Boolean> { - return arr.toList().map { n -> - when (n) { - 1.toByte() -> true - else -> false - } - } - } - - init { - viewModelScope.launch { - try { - _uiState.update { currentState -> - currentState.copy( - stringSettings = application.dataStore.data.map { prefs -> - when (prefs[Constants.STRING_KEY]) { - is ByteArray -> decodeBoolList(prefs[Constants.STRING_KEY]!!) - else -> List(Constants.STRINGS.size) { true } - } - }.first(), - fretSettings = application.dataStore.data.map { prefs -> - when (prefs[Constants.FRET_KEY]) { - is ByteArray -> decodeBoolList(prefs[Constants.FRET_KEY]!!) - else -> List(Constants.FRETS.size) { true } - } - }.first(), - ) - } - updateNote() - } catch (e: Exception) { - Log.w( - "WARN", - "Error while reading settings. Starting fresh." - ) - } - } - } - - fun toggleString(idx: Int) { - - _uiState.update { currentState -> - val res = currentState.stringSettings.toMutableList() - res[idx] = !res[idx] - if (!res.any { it }) { - currentState - } else { - currentState.copy( - stringSettings = res.toList() - ) - } - } - viewModelScope.launch { updateSettings() } - } - - fun toggleFret(idx: Int) { - _uiState.update { currentState -> - val res = currentState.fretSettings.toMutableList() - res[idx] = !res[idx] - if (!res.any { it }) { - currentState - } else { - currentState.copy( - fretSettings = res.toList() - ) - } - } - viewModelScope.launch { updateSettings() } - } - - private fun pickNote(): Note { - val notes = mutableSetOf<Note>() - for (stringIdx in uiState.value.stringSettings.indices) { - if (uiState.value.stringSettings[stringIdx]) { - for (fretIdx in uiState.value.fretSettings.indices) { - if (uiState.value.fretSettings[fretIdx]) { - notes.add(Note(fret = fretIdx, string = stringIdx)) - } - } - } - } - var newNote = notes.random() - while (newNote == uiState.value.note) { - newNote = notes.random() - } - return newNote - } - - fun updateNote() { - _uiState.update { currentState -> - currentState.copy( - lastNote = uiState.value.note, - note = pickNote() - ) - } - } - - private suspend fun updateSettings() { - getApplication<Application>().dataStore.edit { settings -> - settings[Constants.STRING_KEY] = encodeBoolList(uiState.value.stringSettings) - settings[Constants.FRET_KEY] = encodeBoolList(uiState.value.fretSettings) - } - } - - private fun isValidNote(note: Note?): Boolean { - return note != null && uiState.value.stringSettings[note.string] && - uiState.value.fretSettings[note.fret] - } - - fun toggleSettings() { - val show = !uiState.value.showSettings - _uiState.update { currentState -> - var note = currentState.note - var lastNote = currentState.lastNote - if (!show && !isValidNote(note)) { - lastNote = note - note = pickNote() - } - currentState.copy( - lastNote = lastNote, - note = note, - showSettings = show - ) - } - } -} - -class MainActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - enableEdgeToEdge() - requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE - setContent { - Fretfret() - } - } -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun Fretfret(viewModel: MainViewModel = viewModel()) { - val uiState by viewModel.uiState.collectAsState() - fun noteName(note: Note): String { - val startIdx = Constants.NOTES.indexOf(Constants.STRINGS[note.string]) - return Constants.NOTES[(startIdx + note.fret) % Constants.NOTES.size] - } - FretboardTrainerTheme { - Scaffold( - modifier = Modifier.fillMaxSize(), - topBar = { - TopAppBar( - modifier = Modifier.displayCutoutPadding(), - title = { - if (uiState.showSettings) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text("settings - ") - Text( - fontSize = 3.em, - text = "choose which strings and frets you'll be tested on" - ) - } - } else { - Text("fretfret") - } - }, - actions = { - IconButton(onClick = { viewModel.toggleSettings() }) { - Icon( - imageVector = Icons.Filled.Settings, - contentDescription = "Choose Notes" - ) - } - }) - } - ) { innerPadding -> - Column( - modifier = Modifier - .fillMaxSize() - .padding(innerPadding) - .padding(horizontal = 20.dp) - .displayCutoutPadding() - .verticalScroll(state = rememberScrollState()), - verticalArrangement = Arrangement.SpaceAround - ) { - Row { - if (uiState.showSettings) { - StringSettings( - settings = uiState.stringSettings, - toggle = { n -> viewModel.toggleString(n) }) - } - Column { - Fretboard( - modifier = Modifier.fillMaxWidth(), - note = uiState.note - ) - if (uiState.showSettings) { - FretSettings( - settings = uiState.fretSettings, - toggle = { n -> viewModel.toggleFret((n)) } - ) - } - } - } - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - if (uiState.showSettings) { - Row {} - Button( - onClick = { viewModel.toggleSettings() }, - shape = RoundedCornerShape(5.dp) - ) { - Text("done") - } - } else { - Row { - if (uiState.lastNote != null) { - Text("last answer: ") - Text(noteName(uiState.lastNote!!)) - } - } - Button( - onClick = { viewModel.updateNote() }, - shape = RoundedCornerShape(5.dp) - ) { - Text("next") - } - } - } - } - } - } -} - -@Preview -@Composable -fun StringSettings( - settings: List<Boolean> = List(Constants.STRINGS.size) { n -> n % 3 == 0 }, - toggle: (n: Int) -> Unit = {}, -) { - Column { - repeat(Constants.STRINGS.size) { n -> - Row( - modifier = Modifier.height( - (Constants.FRETBOARD_HEIGHT / Constants.STRINGS.size).dp - ), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.End - ) { - Text(modifier = Modifier.width(10.dp), text = Constants.STRINGS[n]) - Checkbox(modifier = Modifier - .padding(0.dp), - checked = settings[n], - onCheckedChange = { toggle(n) }) - } - } - } -} - -@Preview -@Composable -fun FretSettings( - settings: List<Boolean> = List(Constants.FRETS.size) { n -> n % 3 == 0 }, - toggle: (n: Int) -> Unit = {}, -) { - Row(horizontalArrangement = Arrangement.SpaceBetween) { - repeat(Constants.FRETS.size) { n -> - Column( - modifier = Modifier - .weight(weightForFret(n)), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Top - ) { - Checkbox(modifier = Modifier - .padding(end = 15.dp, start = 12.dp), - checked = settings[n], - onCheckedChange = { toggle(n) }) - Text( - modifier = Modifier.absoluteOffset(y = (-10).dp), - text = Constants.FRETS[n] - ) - } - } - } -} - -@Composable -fun Fretboard(modifier: Modifier = Modifier, note: Note?) { - Surface( - color = MaterialTheme.colorScheme.surfaceVariant, - tonalElevation = 0.dp, - shadowElevation = 1.dp, - shape = RoundedCornerShape(5.dp) - ) { - val lineColor = MaterialTheme.colorScheme.onSurfaceVariant - val dotColor = MaterialTheme.colorScheme.outline - Row( - modifier = modifier - .fillMaxWidth() - .height(Constants.FRETBOARD_HEIGHT.dp) - ) { - repeat(Constants.FRETS.size) { n: Int -> - val weight = weightForFret(n) - val nutWidth = 12.dp - val fretWidth = if (n == 0) nutWidth else 6.dp - Box( - modifier = Modifier - .fillMaxHeight() - .weight(weight) - ) { - Dots(n, color = dotColor) - Strings( - n, - noteAt = if (note != null && n == note.fret) note.string else null, - color = lineColor, - openStringColor = dotColor - ) - } - Divider( - modifier = Modifier - .fillMaxHeight() - .width(fretWidth) - .align(Alignment.CenterVertically), - color = lineColor - ) - } - } - } -} - -@Composable -fun Strings(fretIdx: Int, noteAt: Int?, color: Color, openStringColor: Color) { - val noteIndicatorDiameter = 20.dp - val stringThickness = 2.dp - Column(modifier = Modifier.fillMaxSize()) { - repeat(Constants.STRINGS.size) { n: Int -> - Box( - modifier = Modifier - .fillMaxWidth() - .weight(1.0f), contentAlignment = Alignment.Center - ) { - Divider( - modifier = Modifier.fillMaxWidth(), thickness = stringThickness, - color = if (fretIdx == 0) openStringColor else color - ) - if (noteAt == n) { - Box( - modifier = Modifier - .width(noteIndicatorDiameter) - .height(noteIndicatorDiameter) - .background( - color = color, shape = CircleShape - ) - ) - } - } - } - } -} - -@Composable -fun Dots(fretIdx: Int, color: Color) { - val circleDiameter = 10.dp - when (fretIdx) { - in intArrayOf(3, 5, 7, 9) -> { - Box( - modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center - ) { - Box( - modifier = Modifier - .width(circleDiameter) - .height(circleDiameter) - .background(color, CircleShape) - ) - } - } - - 12 -> { - Column( - modifier = Modifier - .fillMaxSize(), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.SpaceAround - - ) { - Box( - modifier = Modifier - .width(circleDiameter) - .height(circleDiameter) - .absoluteOffset(y = 16.dp) - .background(color, CircleShape) - ) - Box( - modifier = Modifier - .width(circleDiameter) - .height(circleDiameter) - .absoluteOffset(y = (-16).dp) - .background(color, CircleShape) - ) - } - } - - else -> {} - } -} -\ No newline at end of file diff --git a/app/src/main/java/com/example/fretboardtrainer/ui/theme/Color.kt b/app/src/main/java/com/example/fretboardtrainer/ui/theme/Color.kt @@ -1,11 +0,0 @@ -package com.example.fretboardtrainer.ui.theme - -import androidx.compose.ui.graphics.Color - -val Purple80 = Color(0xFFD0BCFF) -val PurpleGrey80 = Color(0xFFCCC2DC) -val Pink80 = Color(0xFFEFB8C8) - -val Purple40 = Color(0xFF6650a4) -val PurpleGrey40 = Color(0xFF625b71) -val Pink40 = Color(0xFF7D5260) -\ No newline at end of file diff --git a/app/src/main/java/com/example/fretboardtrainer/ui/theme/Theme.kt b/app/src/main/java/com/example/fretboardtrainer/ui/theme/Theme.kt @@ -1,58 +0,0 @@ -package com.example.fretboardtrainer.ui.theme - -import android.app.Activity -import android.os.Build -import androidx.compose.foundation.isSystemInDarkTheme -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.darkColorScheme -import androidx.compose.material3.dynamicDarkColorScheme -import androidx.compose.material3.dynamicLightColorScheme -import androidx.compose.material3.lightColorScheme -import androidx.compose.runtime.Composable -import androidx.compose.ui.platform.LocalContext - -private val DarkColorScheme = darkColorScheme( - primary = Purple80, - secondary = PurpleGrey80, - tertiary = Pink80 -) - -private val LightColorScheme = lightColorScheme( - primary = Purple40, - secondary = PurpleGrey40, - tertiary = Pink40 - - /* Other default colors to override - background = Color(0xFFFFFBFE), - surface = Color(0xFFFFFBFE), - onPrimary = Color.White, - onSecondary = Color.White, - onTertiary = Color.White, - onBackground = Color(0xFF1C1B1F), - onSurface = Color(0xFF1C1B1F), - */ -) - -@Composable -fun FretboardTrainerTheme( - darkTheme: Boolean = isSystemInDarkTheme(), - // Dynamic color is available on Android 12+ - dynamicColor: Boolean = true, - content: @Composable () -> Unit -) { - val colorScheme = when { - dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { - val context = LocalContext.current - if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) - } - - darkTheme -> DarkColorScheme - else -> LightColorScheme - } - - MaterialTheme( - colorScheme = colorScheme, - typography = Typography, - content = content - ) -} -\ No newline at end of file diff --git a/app/src/main/java/com/example/fretboardtrainer/ui/theme/Type.kt b/app/src/main/java/com/example/fretboardtrainer/ui/theme/Type.kt @@ -1,34 +0,0 @@ -package com.example.fretboardtrainer.ui.theme - -import androidx.compose.material3.Typography -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.sp - -// Set of Material typography styles to start with -val Typography = Typography( - bodyLarge = TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Normal, - fontSize = 16.sp, - lineHeight = 24.sp, - letterSpacing = 0.5.sp - ) - /* Other default text styles to override - titleLarge = TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Normal, - fontSize = 22.sp, - lineHeight = 28.sp, - letterSpacing = 0.sp - ), - labelSmall = TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Medium, - fontSize = 11.sp, - lineHeight = 16.sp, - letterSpacing = 0.5.sp - ) - */ -) -\ No newline at end of file diff --git a/app/src/main/java/com/massi/fretfret/MainActivity.kt b/app/src/main/java/com/massi/fretfret/MainActivity.kt @@ -0,0 +1,524 @@ +package com.massi.fretfret + +import android.app.Application +import android.content.Context +import android.content.pm.ActivityInfo +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.absoluteOffset +import androidx.compose.foundation.layout.displayCutoutPadding +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Divider +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.byteArrayPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.preferencesDataStore +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import com.massi.fretfret.ui.theme.FretfretTheme +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +data object Constants { + val STRINGS = listOf("E", "B", "G", "D", "A", "E") + val FRETS = listOf( + "open", "1", "2", "3", "4", "5", "6", + "7", "8", "9", "10", "11", "12" + ) + val NOTES = listOf( + "A", "A♯/B♭", "B", "C", "C♯/D♭", "D", + "D♯/E♭", "E", "F", "F♯/G♭", "G", "G♯/A♭" + ) + const val FRETBOARD_HEIGHT = 200 + val STRING_KEY = byteArrayPreferencesKey("string_key") + val FRET_KEY = byteArrayPreferencesKey("fret_key") +} + +data class Note( + val string: Int, + val fret: Int, +) + +data class FretfretState( + val showSettings: Boolean = false, + val stringSettings: List<Boolean> = List(Constants.STRINGS.size) { true }, + val fretSettings: List<Boolean> = List(Constants.FRETS.size) { true }, + val note: Note? = null, + val lastNote: Note? = null, +) + +val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") + + +fun weightForFret(fretIdx: Int): Float { + var weight = 24 - fretIdx * 1.0f + if (fretIdx == 0) { + weight /= 2 + } + return weight +} + + +class MainViewModel(application: Application) : AndroidViewModel(application) { + private val _uiState = MutableStateFlow(FretfretState()) + val uiState = _uiState.asStateFlow() + + private fun encodeBoolList(l: List<Boolean>): ByteArray { + return ByteArray(l.size) { + when (l[it]) { + true -> 1.toByte() + else -> 0.toByte() + } + } + } + + private fun decodeBoolList(arr: ByteArray): List<Boolean> { + return arr.toList().map { n -> + when (n) { + 1.toByte() -> true + else -> false + } + } + } + + init { + viewModelScope.launch { + try { + _uiState.update { currentState -> + currentState.copy( + stringSettings = application.dataStore.data.map { prefs -> + when (prefs[Constants.STRING_KEY]) { + is ByteArray -> decodeBoolList(prefs[Constants.STRING_KEY]!!) + else -> List(Constants.STRINGS.size) { true } + } + }.first(), + fretSettings = application.dataStore.data.map { prefs -> + when (prefs[Constants.FRET_KEY]) { + is ByteArray -> decodeBoolList(prefs[Constants.FRET_KEY]!!) + else -> List(Constants.FRETS.size) { true } + } + }.first(), + ) + } + updateNote() + } catch (e: Exception) { + Log.w( + "WARN", + "Error while reading settings. Starting fresh." + ) + } + } + } + + fun toggleString(idx: Int) { + + _uiState.update { currentState -> + val res = currentState.stringSettings.toMutableList() + res[idx] = !res[idx] + if (!res.any { it }) { + currentState + } else { + currentState.copy( + stringSettings = res.toList() + ) + } + } + viewModelScope.launch { updateSettings() } + } + + fun toggleFret(idx: Int) { + _uiState.update { currentState -> + val res = currentState.fretSettings.toMutableList() + res[idx] = !res[idx] + if (!res.any { it }) { + currentState + } else { + currentState.copy( + fretSettings = res.toList() + ) + } + } + viewModelScope.launch { updateSettings() } + } + + private fun pickNote(): Note { + val notes = mutableSetOf<Note>() + for (stringIdx in uiState.value.stringSettings.indices) { + if (uiState.value.stringSettings[stringIdx]) { + for (fretIdx in uiState.value.fretSettings.indices) { + if (uiState.value.fretSettings[fretIdx]) { + notes.add(Note(fret = fretIdx, string = stringIdx)) + } + } + } + } + var newNote = notes.random() + while (newNote == uiState.value.note) { + newNote = notes.random() + } + return newNote + } + + fun updateNote() { + _uiState.update { currentState -> + currentState.copy( + lastNote = uiState.value.note, + note = pickNote() + ) + } + } + + private suspend fun updateSettings() { + getApplication<Application>().dataStore.edit { settings -> + settings[Constants.STRING_KEY] = encodeBoolList(uiState.value.stringSettings) + settings[Constants.FRET_KEY] = encodeBoolList(uiState.value.fretSettings) + } + } + + private fun isValidNote(note: Note?): Boolean { + return note != null && uiState.value.stringSettings[note.string] && + uiState.value.fretSettings[note.fret] + } + + fun toggleSettings() { + val show = !uiState.value.showSettings + _uiState.update { currentState -> + var note = currentState.note + var lastNote = currentState.lastNote + if (!show && !isValidNote(note)) { + lastNote = note + note = pickNote() + } + currentState.copy( + lastNote = lastNote, + note = note, + showSettings = show + ) + } + } +} + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + setContent { + Fretfret() + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun Fretfret(viewModel: MainViewModel = viewModel()) { + val uiState by viewModel.uiState.collectAsState() + fun noteName(note: Note): String { + val startIdx = Constants.NOTES.indexOf(Constants.STRINGS[note.string]) + return Constants.NOTES[(startIdx + note.fret) % Constants.NOTES.size] + } + FretfretTheme { + Scaffold( + modifier = Modifier.fillMaxSize(), + topBar = { + TopAppBar( + modifier = Modifier.displayCutoutPadding(), + title = { + if (uiState.showSettings) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("settings - ") + Text( + fontSize = 3.em, + text = "choose which strings and frets you'll be tested on" + ) + } + } else { + Text("fretfret") + } + }, + actions = { + IconButton(onClick = { viewModel.toggleSettings() }) { + Icon( + imageVector = Icons.Filled.Settings, + contentDescription = "Choose Notes" + ) + } + }) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .padding(horizontal = 20.dp) + .displayCutoutPadding() + .verticalScroll(state = rememberScrollState()), + verticalArrangement = Arrangement.SpaceAround + ) { + Row { + if (uiState.showSettings) { + StringSettings( + settings = uiState.stringSettings, + toggle = { n -> viewModel.toggleString(n) }) + } + Column { + Fretboard( + modifier = Modifier.fillMaxWidth(), + note = uiState.note + ) + if (uiState.showSettings) { + FretSettings( + settings = uiState.fretSettings, + toggle = { n -> viewModel.toggleFret((n)) } + ) + } + } + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + if (uiState.showSettings) { + Row {} + Button( + onClick = { viewModel.toggleSettings() }, + shape = RoundedCornerShape(5.dp) + ) { + Text("done") + } + } else { + Row { + if (uiState.lastNote != null) { + Text("last answer: ") + Text(noteName(uiState.lastNote!!)) + } + } + Button( + onClick = { viewModel.updateNote() }, + shape = RoundedCornerShape(5.dp) + ) { + Text("next") + } + } + } + } + } + } +} + +@Preview +@Composable +fun StringSettings( + settings: List<Boolean> = List(Constants.STRINGS.size) { n -> n % 3 == 0 }, + toggle: (n: Int) -> Unit = {}, +) { + Column { + repeat(Constants.STRINGS.size) { n -> + Row( + modifier = Modifier.height( + (Constants.FRETBOARD_HEIGHT / Constants.STRINGS.size).dp + ), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.End + ) { + Text(modifier = Modifier.width(10.dp), text = Constants.STRINGS[n]) + Checkbox(modifier = Modifier + .padding(0.dp), + checked = settings[n], + onCheckedChange = { toggle(n) }) + } + } + } +} + +@Preview +@Composable +fun FretSettings( + settings: List<Boolean> = List(Constants.FRETS.size) { n -> n % 3 == 0 }, + toggle: (n: Int) -> Unit = {}, +) { + Row(horizontalArrangement = Arrangement.SpaceBetween) { + repeat(Constants.FRETS.size) { n -> + Column( + modifier = Modifier + .weight(weightForFret(n)), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Top + ) { + Checkbox(modifier = Modifier + .padding(end = 15.dp, start = 12.dp), + checked = settings[n], + onCheckedChange = { toggle(n) }) + Text( + modifier = Modifier.absoluteOffset(y = (-10).dp), + text = Constants.FRETS[n] + ) + } + } + } +} + +@Composable +fun Fretboard(modifier: Modifier = Modifier, note: Note?) { + Surface( + color = MaterialTheme.colorScheme.surfaceVariant, + tonalElevation = 0.dp, + shadowElevation = 1.dp, + shape = RoundedCornerShape(5.dp) + ) { + val lineColor = MaterialTheme.colorScheme.onSurfaceVariant + val dotColor = MaterialTheme.colorScheme.outline + Row( + modifier = modifier + .fillMaxWidth() + .height(Constants.FRETBOARD_HEIGHT.dp) + ) { + repeat(Constants.FRETS.size) { n: Int -> + val weight = weightForFret(n) + val nutWidth = 12.dp + val fretWidth = if (n == 0) nutWidth else 6.dp + Box( + modifier = Modifier + .fillMaxHeight() + .weight(weight) + ) { + Dots(n, color = dotColor) + Strings( + n, + noteAt = if (note != null && n == note.fret) note.string else null, + color = lineColor, + openStringColor = dotColor + ) + } + Divider( + modifier = Modifier + .fillMaxHeight() + .width(fretWidth) + .align(Alignment.CenterVertically), + color = lineColor + ) + } + } + } +} + +@Composable +fun Strings(fretIdx: Int, noteAt: Int?, color: Color, openStringColor: Color) { + val noteIndicatorDiameter = 20.dp + val stringThickness = 2.dp + Column(modifier = Modifier.fillMaxSize()) { + repeat(Constants.STRINGS.size) { n: Int -> + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1.0f), contentAlignment = Alignment.Center + ) { + Divider( + modifier = Modifier.fillMaxWidth(), thickness = stringThickness, + color = if (fretIdx == 0) openStringColor else color + ) + if (noteAt == n) { + Box( + modifier = Modifier + .width(noteIndicatorDiameter) + .height(noteIndicatorDiameter) + .background( + color = color, shape = CircleShape + ) + ) + } + } + } + } +} + +@Composable +fun Dots(fretIdx: Int, color: Color) { + val circleDiameter = 10.dp + when (fretIdx) { + in intArrayOf(3, 5, 7, 9) -> { + Box( + modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .width(circleDiameter) + .height(circleDiameter) + .background(color, CircleShape) + ) + } + } + + 12 -> { + Column( + modifier = Modifier + .fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceAround + + ) { + Box( + modifier = Modifier + .width(circleDiameter) + .height(circleDiameter) + .absoluteOffset(y = 16.dp) + .background(color, CircleShape) + ) + Box( + modifier = Modifier + .width(circleDiameter) + .height(circleDiameter) + .absoluteOffset(y = (-16).dp) + .background(color, CircleShape) + ) + } + } + + else -> {} + } +} +\ No newline at end of file diff --git a/app/src/main/java/com/massi/fretfret/ui/theme/Color.kt b/app/src/main/java/com/massi/fretfret/ui/theme/Color.kt @@ -0,0 +1,11 @@ +package com.massi.fretfret.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) +\ No newline at end of file diff --git a/app/src/main/java/com/massi/fretfret/ui/theme/Theme.kt b/app/src/main/java/com/massi/fretfret/ui/theme/Theme.kt @@ -0,0 +1,57 @@ +package com.massi.fretfret.ui.theme + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalContext + +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80 +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40 + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun FretfretTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} +\ No newline at end of file diff --git a/app/src/main/java/com/massi/fretfret/ui/theme/Type.kt b/app/src/main/java/com/massi/fretfret/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package com.massi.fretfret.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) +\ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml @@ -1,3 +1,3 @@ <resources> - <string name="app_name">fretboard trainer</string> + <string name="app_name">fretfret</string> </resources> \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <resources> - <style name="Theme.FretboardTrainer" parent="android:Theme.Material.Light.NoActionBar" /> + <style name="Theme.Fretfret" parent="android:Theme.Material.Light.NoActionBar" /> </resources> \ No newline at end of file diff --git a/app/src/test/java/com/example/fretboardtrainer/ExampleUnitTest.kt b/app/src/test/java/com/example/fretboardtrainer/ExampleUnitTest.kt @@ -1,17 +0,0 @@ -package com.example.fretboardtrainer - -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) - } -} -\ No newline at end of file diff --git a/app/src/test/java/com/massi/fretfret/ExampleUnitTest.kt b/app/src/test/java/com/massi/fretfret/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.massi.fretfret + +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) + } +} +\ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts @@ -19,6 +19,6 @@ dependencyResolutionManagement { } } -rootProject.name = "fretboard trainer" +rootProject.name = "fretfret" include(":app") \ No newline at end of file