diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt index d8fc070..151911b 100644 --- a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt @@ -15,6 +15,7 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.tooling.preview.Preview import androidx.core.app.ActivityCompat import androidx.core.view.WindowCompat @@ -112,8 +113,7 @@ class MainActivity : ComponentActivity() { WindowCompat.setDecorFitsSystemWindows(window, false) if (isFullScreen) { - windowInsetsController.hide(WindowInsetsCompat.Type.navigationBars()) - windowInsetsController.show(WindowInsetsCompat.Type.statusBars()) + windowInsetsController.hide(WindowInsetsCompat.Type.systemBars()) windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TUODetailDialog.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TUODetailDialog.kt index 4a41382..c95dc0c 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TUODetailDialog.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TUODetailDialog.kt @@ -66,6 +66,7 @@ fun TUODetailDialog( DisposableEffect(Unit) { keyboardState.isDialogActive = true + keyboardState.dialogPosition = menuPosition onDispose { keyboardState.hide() keyboardState.isDialogActive = false @@ -201,6 +202,12 @@ fun TUODetailDialog( } } + val isEditMode by sharedScreenModel.modeEditor.collectAsState() + LaunchedEffect(isEditMode) { + if (!isEditMode) { + onDismiss() + } + } Popup( offset = menuPosition, diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/CustomKeyboard.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/CustomKeyboard.kt index 17e6d48..67452f6 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/CustomKeyboard.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/CustomKeyboard.kt @@ -28,7 +28,9 @@ fun CustomKeyboard( onDeleteClick: () -> Unit, onClearClick: () -> Unit, onPrefixClick: (String) -> Unit, + onToggleKeyboardClick: () -> Unit, isFullScreen: Boolean, + isAndroidLandscape: Boolean, modifier: Modifier = Modifier ) { Surface( @@ -46,6 +48,7 @@ fun CustomKeyboard( ), verticalArrangement = Arrangement.spacedBy(8.dp) ) { + val keyboardButtonHeight = if (isAndroidLandscape) 35.dp else 44.dp val prefixes = listOf("EWS", "FFPM", "FF", "Antema", "Tsanta", "Salamo") LazyRow( modifier = Modifier.fillMaxWidth(), @@ -55,7 +58,7 @@ fun CustomKeyboard( items(prefixes) { prefix -> Button( onClick = { onPrefixClick("$prefix ") }, - modifier = Modifier.height(38.dp), + modifier = Modifier.height(keyboardButtonHeight-6.dp), shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.15f), @@ -85,39 +88,87 @@ fun CustomKeyboard( horizontalArrangement = Arrangement.spacedBy(8.dp) ) { for (key in row) { - val isActionKey = key == "⌫" || key == "↓" - Button( - onClick = { - when (key) { - "⌫" -> onDeleteClick() - "↓" -> onClearClick() - else -> onDigitClick(key) + if (key == "⌫") { + Row( + modifier = Modifier.weight(1f), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Button( + onClick = onDeleteClick, + modifier = Modifier + .weight(1f) + .height(keyboardButtonHeight), + shape = RoundedCornerShape(10.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.6f), + contentColor = MaterialTheme.colorScheme.onErrorContainer + ), + contentPadding = PaddingValues(0.dp) + ) { + Text( + text = "⌫", + fontSize = MaterialTheme.typography.headlineMedium.fontSize, + fontWeight = FontWeight.Bold, + maxLines = 1, + softWrap = false + ) } - }, - modifier = Modifier - .weight(1f) - .height(44.dp), - shape = RoundedCornerShape(10.dp), - colors = ButtonDefaults.buttonColors( - containerColor = if (isActionKey) - MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.6f) - else - MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.2f), - contentColor = if (isActionKey) - MaterialTheme.colorScheme.onErrorContainer - else - Color.White - ) - ) { - Text( - text = key, - fontSize = MaterialTheme.typography.headlineLarge.fontSize, - fontWeight = FontWeight.Bold - ) + Button( + onClick = onToggleKeyboardClick, + modifier = Modifier + .weight(1f) + .height(keyboardButtonHeight), + shape = RoundedCornerShape(10.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.tertiary, + contentColor = MaterialTheme.colorScheme.onTertiary + ), + contentPadding = PaddingValues(0.dp) + ) { + Text( + text = "ABC", + fontSize = MaterialTheme.typography.titleMedium.fontSize, + fontWeight = FontWeight.Bold, + maxLines = 1, + softWrap = false + ) + } + } + } else { + val isActionKey = key == "↓" + Button( + onClick = { + when (key) { + "⌫" -> onDeleteClick() + "↓" -> onClearClick() + else -> onDigitClick(key) + } + }, + modifier = Modifier + .weight(1f) + .height(keyboardButtonHeight), + shape = RoundedCornerShape(10.dp), + colors = ButtonDefaults.buttonColors( + containerColor = if (isActionKey) + MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.6f) + else + MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.2f), + contentColor = if (isActionKey) + MaterialTheme.colorScheme.onErrorContainer + else + Color.White + ) + ) { + Text( + text = key, + fontSize = if(isAndroidLandscape) MaterialTheme.typography.labelLarge.fontSize else MaterialTheme.typography.headlineLarge.fontSize, + fontWeight = FontWeight.Bold + ) + } } } } } } } -} +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt index 796af35..f2888d1 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt @@ -5,21 +5,19 @@ import androidx.compose.animation.* import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.* +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape -import mg.dot.feufaro.data.ActivePlaylistSong import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight -import androidx.compose.material.icons.automirrored.filled.PlaylistAdd -import androidx.compose.material.icons.automirrored.filled.Undo +import androidx.compose.material.icons.automirrored.filled.* import androidx.compose.material.icons.filled.* import androidx.compose.material3.* import androidx.compose.runtime.* @@ -29,13 +27,18 @@ import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.scale import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.font.FontWeight @@ -53,11 +56,14 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import mg.dot.feufaro.data.ActivePlaylistSong import mg.dot.feufaro.data.DrawerItem import mg.dot.feufaro.getPlatform +import mg.dot.feufaro.midi.FMediaPlayer import mg.dot.feufaro.pdf.PrintSettings import mg.dot.feufaro.pdf.defaultPrintSettings import mg.dot.feufaro.pdf.rememberPdfExportAction +import mg.dot.feufaro.provideSettings import mg.dot.feufaro.solfa.Solfa import mg.dot.feufaro.solfa.Transpose import mg.dot.feufaro.viewmodel.SolfaScreenModel @@ -136,7 +142,7 @@ fun MainScreenWithDrawer( val fileContent = sharedScreenModel.fileContent.value ?: "" LaunchedEffect(Unit) { if(fileContent == "") { - sharedScreenModel.loadNewSong("$midiFile") + sharedScreenModel.loadNewSong(midiFile) } } val isEditMode by sharedScreenModel.modeEditor.collectAsState() @@ -248,9 +254,8 @@ fun MainScreenWithDrawer( } ) }, content = { - val scope = rememberCoroutineScope() var showPrintSettings by remember { mutableStateOf(false) } - var pendingPrintSettings by remember { mutableStateOf(null) } + //var pendingPrintSettings by remember { mutableStateOf(null) } val pdfExportAction: (PrintSettings) -> Unit = rememberPdfExportAction( scope = scope, @@ -376,16 +381,46 @@ fun MainScreenWithDrawer( val favoritePaths by sharedScreenModel.favItems.collectAsState() val keyboardController = LocalSoftwareKeyboardController.current + val focusManager = LocalFocusManager.current var isNumericKeyboard by remember { mutableStateOf(true) } - LaunchedEffect(isNumericKeyboard, isSearchActive) { - if (isSearchActive) { - if (isAndroid && isNumericKeyboard) { - keyboardController?.hide() - } else { + var isCustomKeyboardVisible by remember { mutableStateOf(true) } + var isScrollKeyboardGuard by remember { mutableStateOf(false) } + var scrollGuardToken by remember { mutableStateOf(0) } + + val hideSearchKeyboards: () -> Unit = { + isCustomKeyboardVisible = false + keyboardController?.hide() + scrollGuardToken++ + val token = scrollGuardToken + isScrollKeyboardGuard = true + scope.launch { + delay(60) + keyboardController?.hide() + delay(740) + if (scrollGuardToken == token) isScrollKeyboardGuard = false + } + } + + val toggleNumericKeyboard: () -> Unit = { + isNumericKeyboard = !isNumericKeyboard + isCustomKeyboardVisible = true + if (!isNumericKeyboard) { + scope.launch { + delay(50) + focusRequester.requestFocus() keyboardController?.show() } } } + + LaunchedEffect(isNumericKeyboard, isCustomKeyboardVisible, isSearchActive) { + if (isSearchActive && isCustomKeyboardVisible) { + if (isAndroid && isNumericKeyboard) keyboardController?.hide() else keyboardController?.show() + } else { + keyboardController?.hide() + } + } + val solfaKeyboardState = remember { SolfaKeyboardState() } val searchTitleFlow by sharedScreenModel.searchTitle.collectAsState() var textInput by remember { mutableStateOf(TextFieldValue(searchTitleFlow, TextRange(searchTitleFlow.length))) } @@ -396,10 +431,33 @@ fun MainScreenWithDrawer( } } - CompositionLocalProvider(LocalSolfaKeyboardState provides solfaKeyboardState) { - BoxWithConstraints(modifier = Modifier.fillMaxSize()) { - val isLandscape = maxWidth > maxHeight + val prefs = remember { provideSettings() } + val rotationMode = prefs.getString("screen_rotation_mode", "LANDSCAPE") + val isLandscape = when (rotationMode) { + "LANDSCAPE" -> true + "PORTRAIT" -> false + "AUTO" -> maxWidth > maxHeight + else -> true + } + val isAndroidLandscape = isAndroid && isLandscape + + val isCustomKeyboardShown = isSearchActive && isAndroid && isNumericKeyboard && isCustomKeyboardVisible + val searchOverlayBottomPadding by animateDpAsState( + targetValue = /*if (isCustomKeyboardShown) keyboardHeightDp else*/ 0.dp, + label = "searchOverlayBottomPadding" + ) + + LaunchedEffect(isAndroidLandscape) { + if (isAndroidLandscape) fullscreenController(true) + } + + val layoutDirection = LocalLayoutDirection.current + val displayCutoutInsets = WindowInsets.displayCutout + val leftCutoutWidth = displayCutoutInsets.asPaddingValues().calculateLeftPadding(layoutDirection) + val navigationBarsInsets = WindowInsets.navigationBars + val rightNavBarWidth = navigationBarsInsets.asPaddingValues().calculateEndPadding(layoutDirection) + val topAppBarHeight = if (isAndroid) { if(isLandscape) { 55.dp @@ -422,728 +480,213 @@ fun MainScreenWithDrawer( } }, topBar = { - TopAppBar( - modifier = Modifier.height(topAppBarHeight), - windowInsets = if (!isLandscape) { - WindowInsets.safeDrawing.only( - WindowInsetsSides.Horizontal + WindowInsetsSides.Top - ) - } else { - WindowInsets(0, 0, 0, 0) - }, - title = { - AnimatedContent( - targetState = isSearchActive, - label = "SearchTransition" - ) { searchActive -> - if (searchActive) { - Box( - modifier = Modifier.fillMaxHeight(), - contentAlignment = Alignment.Center - ) { - BasicTextField( - value = textInput, - onValueChange = { newValue -> - textInput = newValue - sharedScreenModel.updateSearchTxt(newValue.text) - }, - readOnly = isAndroid && isNumericKeyboard, - textStyle = LocalTextStyle.current.copy( - color = Color.White, - fontSize = 16.sp - ), - singleLine = true, - cursorBrush = SolidColor(Color.White), - keyboardOptions = KeyboardOptions( - keyboardType = if (isAndroid && isNumericKeyboard) KeyboardType.Text else KeyboardType.Number - ), - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .focusRequester(focusRequester) - .background( - color = Color.White.copy(alpha = 0.15f), - shape = RoundedCornerShape(20.dp) - ), - decorationBox = { innerTextField -> - TextFieldDefaults.DecorationBox( - value = textInput.text, - innerTextField = innerTextField, - enabled = true, - singleLine = true, - visualTransformation = VisualTransformation.None, - interactionSource = sharedInteractionSource, - placeholder = { - Text( - text = "FFPM 1 Andriananahary ...", - color = Color.White.copy(alpha = 0.5f), - fontSize = 16.sp - ) - }, - leadingIcon = { - Icon( - imageVector = Icons.Default.Search, - contentDescription = "Icon search on leading", - tint = Color.White.copy(alpha = 0.8f), - modifier = Modifier.size(20.dp) - ) - }, - trailingIcon = { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(2.dp) - ) { - if (isAndroid) { - IconButton( - onClick = { - isNumericKeyboard = !isNumericKeyboard - }, - modifier = Modifier.size(32.dp) - ) { - Icon( - imageVector = if (isNumericKeyboard) Icons.Default.Abc else Icons.Filled._123, - contentDescription = "Btn to switch abc 123", - tint = MaterialTheme.colorScheme.tertiary, - modifier = Modifier.size(22.dp) - ) - } - } - - IconButton( - onClick = { - textInput = TextFieldValue("", TextRange.Zero) - sharedScreenModel.updateSearchTxt("") - }, - modifier = Modifier.size(32.dp) - ) { - Icon( - imageVector = Icons.Default.Clear, - contentDescription = "Annuler recherche", - tint = Color.White.copy(alpha = 0.8f), - modifier = Modifier.size(18.dp) - ) - } - } - }, - contentPadding = PaddingValues( - horizontal = 10.dp, - vertical = 0.dp - ), - colors = TextFieldDefaults.colors( - focusedContainerColor = Color.Transparent, - unfocusedContainerColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent - ) - ) - } - ) - if (isAndroid && isNumericKeyboard) { - Box( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .clickable( - interactionSource = remember { MutableInteractionSource() }, - indication = null - ) { - isNumericKeyboard = false - focusRequester.requestFocus() - keyboardController?.show() - } - ) - } - } - } else { - Column( - modifier = Modifier.fillMaxSize().verticalScroll(scrollState), - verticalArrangement = Arrangement.Center - ) { - Row { - Text( - songTitle, - modifier = Modifier.weight(1f, fill = true), - maxLines = 1, - softWrap = false, - overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.headlineLarge - ) - } + if (!isAndroidLandscape || isSearchActive) { + MainTopBar( + modifier = Modifier.height(topAppBarHeight), + isSearchActive = isSearchActive, + isLandscape = isLandscape, + textInput = textInput, + onTextChanged = { newValue -> + textInput = newValue + sharedScreenModel.updateSearchTxt(newValue.text) + }, + isAndroid = isAndroid, + isNumericKeyboard = isNumericKeyboard, + onToggleNumericKeyboard = toggleNumericKeyboard, + onClearSearch = { + textInput = TextFieldValue("", TextRange.Zero) + sharedScreenModel.updateSearchTxt("") + }, + onEnableNumericClick = { + isCustomKeyboardVisible = true + }, + songTitle = songTitle, + scrollState = scrollState, + focusRequester = focusRequester, + onFieldFocused = { + if (isScrollKeyboardGuard) { + scope.launch { + delay(30) + keyboardController?.hide() } } - } - }, navigationIcon = { - if (!isQrVisible) { - IconButton(onClick = { - scope.launch { drawerState.open() } - }) { - Icon(Icons.Filled.Menu, contentDescription = "Ouvrir Menu Latéral") - } - } - }, actions = { - val appliedInterval by sharedScreenModel.transpositionInterval.collectAsState() - var tempInterval by remember(fileContent, appliedInterval) { mutableStateOf(appliedInterval) } - var isEyeVisible by remember { mutableStateOf(false) } - val isMinor = songKey.endsWith("m", ignoreCase = true) - val cleanSongKey = if (isMinor) songKey.dropLast(1) else songKey - val keysOrder = Transpose.keyToNumber - val songKeyIndex = keysOrder.indexOf(cleanSongKey).takeIf { it != -1 } ?: 0 - val rawKeyIndex = (songKeyIndex + tempInterval) % 12 - val tempUiKey = keysOrder[if (rawKeyIndex < 0) rawKeyIndex + 12 else rawKeyIndex] - val isPendingChange = tempInterval != appliedInterval - val isCurrentlyTransposed = appliedInterval != 0 - val formattedKey = if (isMinor) "${tempUiKey}m" else tempUiKey - Box( - modifier = Modifier.padding(end = 16.dp), - contentAlignment = Alignment.TopCenter - ) { - Row( - modifier = Modifier.fillMaxHeight(), - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = formattedKey, - style = MaterialTheme.typography.displaySmall, - fontWeight = FontWeight.Black, - textAlign = TextAlign.Center, - color = if (isCurrentlyTransposed || isPendingChange) MaterialTheme.colorScheme.tertiary else Color.White, - modifier = Modifier - .clickable( - interactionSource = sharedInteractionSource, - indication = null - ) { - isEyeVisible = !isEyeVisible - } - .width(65.dp) - ) - } - - DropdownMenu( - expanded = isEyeVisible, - onDismissRequest = { - tempInterval = appliedInterval - isEyeVisible = false - }, - containerColor = Color(0xFF2C3135).copy(alpha = 0.75f), - shape = RoundedCornerShape(16.dp), - modifier = Modifier.padding(12.dp) - ) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(8.dp) - ) { - /* < = > */ - val isOriginalKeyC = cleanSongKey.equals("C", ignoreCase = true) - val isTransposedToC = tempUiKey.equals("C", ignoreCase = true) && !isOriginalKeyC - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceEvenly, - modifier = Modifier.padding(horizontal = 4.dp) - ) { - /* < */ - val currentIndex = keysOrder.indexOf(tempUiKey).takeIf { it != -1 } ?: 0 - val targetKeyLeft = keysOrder[(currentIndex - 1 + 12) % 12] - - TooltipBox( - positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), - tooltip = { - PlainTooltip( - containerColor = Color.DarkGray, - contentColor = Color.White - ) { Text(targetKeyLeft, fontSize = 12.sp) } - }, - state = rememberTooltipState() - ) { - IconButton( - modifier = Modifier.size(36.dp), - onClick = { tempInterval-- } - ) { - Icon( - imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, - contentDescription = "Transposer de moins", - tint = Color.White - ) - } - } - - val centralIcon = - if (isPendingChange && !isTransposedToC) Icons.Filled.Check else Icons.Filled.SwapHoriz - val centralTint = - if (isPendingChange) MaterialTheme.colorScheme.tertiary else Color.White - val tooltipText = - if (isPendingChange) "Écoutez en $tempUiKey" else if (isCurrentlyTransposed) "Revenir en $songKey" else "" - - TooltipBox( - positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), - tooltip = { - PlainTooltip( - containerColor = Color.DarkGray, - contentColor = Color.White - ) { Text(text = tooltipText, fontSize = 12.sp) } - }, - state = rememberTooltipState() - ) { - IconButton( - modifier = Modifier.size(36.dp), - onClick = { - if (isPendingChange) { - sharedScreenModel.setTranspositionInterval(tempInterval) - sharedScreenModel.stopMidi() - sharedScreenModel.seekTo(0f) - solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value) - } else if (isCurrentlyTransposed) { - tempInterval = 0 - sharedScreenModel.setTranspositionInterval(0) - sharedScreenModel.stopMidi() - sharedScreenModel.seekTo(0f) - solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value) - } - isEyeVisible = false - } - ) { - Icon( - imageVector = centralIcon, - contentDescription = "Valider transpose", - tint = centralTint - ) - } - } - - /* > */ - val targetKeyRight = keysOrder[(currentIndex + 1) % 12] - TooltipBox( - positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), - tooltip = { - PlainTooltip( - containerColor = Color.DarkGray, - contentColor = Color.White - ) { Text(targetKeyRight, fontSize = 12.sp) } - }, - state = rememberTooltipState() - ) { - IconButton( - modifier = Modifier.size(36.dp), - onClick = { tempInterval++ } - ) { - Icon( - imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = "Transposer de plus", - tint = Color.White - ) - } - } - } - - val cIndex = keysOrder.indexOf("C") - val intervalToC = if (cIndex != -1) cIndex - songKeyIndex else 0 - val buttonText = if (isTransposedToC) "Revenir en $songKey" else "Transposer en C" - val tooltipTextC = if (isTransposedToC) "Revenir en clé $songKey" else "Écrire les notes en Do (C)" - TooltipBox( - positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), - tooltip = { - PlainTooltip( - containerColor = Color.DarkGray, - contentColor = Color.White - ) { Text(text = tooltipTextC, fontSize = 12.sp) } - }, - state = rememberTooltipState() - ) { - OutlinedButton( - onClick = { - if (isTransposedToC) { - tempInterval = 0 - sharedScreenModel.setTranspositionInterval(0) - sharedScreenModel.setTranspToC(0) - sharedScreenModel.stopMidi() - sharedScreenModel.seekTo(0f) - } else { - val currentKey = sharedScreenModel.songKey.value - val intervalC = getIntervalToC(currentKey) - - tempInterval = -intervalC - sharedScreenModel.setTranspToC(intervalC) - sharedScreenModel.stopMidi() - sharedScreenModel.seekTo(0f) - } - isEyeVisible = false - }, - modifier = Modifier.fillMaxWidth().height(36.dp), - shape = RoundedCornerShape(8.dp), - border = BorderStroke( - 1.dp, - MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5f) - ), - colors = ButtonDefaults.outlinedButtonColors( - contentColor = MaterialTheme.colorScheme.tertiary - ) - ) { - Text( - text = buttonText, - fontSize = 12.sp, - fontWeight = FontWeight.Bold - ) - } - } - } - } - } - }, colors = TopAppBarColors( - containerColor = MaterialTheme.colorScheme.primary, - titleContentColor = MaterialTheme.colorScheme.onPrimary, - actionIconContentColor = MaterialTheme.colorScheme.onPrimary, - navigationIconContentColor = MaterialTheme.colorScheme.onPrimary, - scrolledContainerColor = MaterialTheme.colorScheme.onPrimary, + }, + sharedInteractionSource = sharedInteractionSource, + onOpenDrawer = { scope.launch { drawerState.open() } }, + isQrVisible = isQrVisible, + isAndroidLandscape = isAndroidLandscape, + songKey = songKey, + fileContent = fileContent, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel ) - ) - }, floatingActionButton = { - Row( - modifier = Modifier.fillMaxWidth() - ) { - if (!solfaKeyboardState.isVisible) { - Row( - modifier = Modifier.fillMaxWidth().padding(5.dp), - horizontalArrangement = Arrangement.spacedBy(7.dp, Alignment.End), - verticalAlignment = Alignment.CenterVertically - ) { - if (isEditMode) { - AnimatedVisibility( - visible = true, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - MyFAB( - onClick = { - scope.launch { - codeContent = sourceContent - - withContext(Dispatchers.Main) { - solfaScreenModel.loadExternalFile(originalPath) - } - } - }, - icon = Icons.AutoMirrored.Default.Undo - ) - } - - AnimatedVisibility( - visible = true, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - MyFAB( - onClick = { - scope.launch { - try { - val initialDir = solfaScreenModel.fileRepository.getAppPublicFolder().absolutePath - saveLauncher.launch(fileName, initialDir) - } catch (e: Exception) { - e.printStackTrace() - } - } - }, - icon = Icons.Filled.SaveAs - ) - } - - AnimatedVisibility( - visible = true, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - MyFAB( - onClick = { - sharedScreenModel.toggleEditorMode(false) - }, - icon = Icons.Default.Close - ) - } - } else if (!isQrVisible) { - if (!showMidiCtrl) { - AnimatedVisibility( - visible = isExpanded, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp) - ) { - MyFAB( - onClick = { sharedScreenModel.descGridCount(1) }, - size = 30.dp, - icon = Icons.Default.Remove - ) - MyFAB( - onClick = { sharedScreenModel.addGridCount(1) }, - size = 30.dp, - icon = Icons.Default.Add - ) - } - } - - AnimatedVisibility( - visible = isExpanded, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - MyFAB( - onClick = { - sharedScreenModel.showSearchMenu(true) - scope.launch { - delay(100) - focusRequester.requestFocus() - } - sharedScreenModel.setExpandedFAB(!isExpanded) - }, - icon = if (isSearchActive) Icons.Default.Close else Icons.Default.Search - ) - } - - AnimatedVisibility( - visible = isExpanded, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - Box( - modifier = Modifier.size(55.dp), - contentAlignment = Alignment.BottomEnd - ) { - androidx.compose.animation.AnimatedVisibility( - visible = isShareExpanded, - enter = fadeIn() + slideInVertically { it / 2 } + scaleIn(), - exit = fadeOut() + slideOutVertically { it / 2 } + scaleOut(), - modifier = Modifier - .align(Alignment.BottomEnd) - .offset(y = (-65).dp) - .wrapContentWidth(unbounded = true) - ) { - Row( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically - ) { - MyFAB( - onClick = { - sharedScreenModel.toggleQRCodeVisibility() - sharedScreenModel.setExpandedFAB(false) - isShareExpanded = false - }, - icon = Icons.Filled.QrCode2 - ) - - MyFAB( - onClick = { - showPrintSettings = !showPrintSettings - isShareExpanded = false - }, - icon = Icons.Filled.Print - ) - - MyFAB( - onClick = { - isShareExpanded = false - scope.launch { - withContext(Dispatchers.IO) { - try { - val cleanS = - songTitle.replace(' ', '_') - val exportName = - "${cleanS.ifEmpty { "partition" }}.mid" - val savedPath = - solfaScreenModel.fileRepository.pickSavePath( - defaultName = exportName, - title = "Enregistrer le fichier MIDI" - ) - - if (!savedPath.isNullOrEmpty()) { - val transpositionInterval = - sharedScreenModel.transpositionInterval.value - val bpm = - sharedScreenModel.getBpmFlow().value - ?: 120f - solfaScreenModel.generateMidiFile( - bpm, - savedPath, - transpositionInterval - ) - println("Fichier MIDI enregistré avec succès sous : $savedPath") - } - } catch (e: Exception) { - e.printStackTrace() - } - } - } - }, - icon = Icons.Filled.AudioFile - ) - } - } - - MyFAB( - onClick = { isShareExpanded = !isShareExpanded }, - icon = Icons.Filled.Share - ) - } - } - } - if (!showMidiCtrl && !isSearchActive) { - AnimatedVisibility( - visible = isExpanded, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - MyFAB( - onClick = { - sharedScreenModel.setMidiCtrl(!showMidiCtrl) - }, - icon = Icons.Filled.PlayCircle - ) - } - MyFAB( - onClick = { - sharedScreenModel.setExpandedFAB(!isExpanded) - refreshTrigeer++ - sharedScreenModel.loadNewSong("$midiFile") - }, - icon = if (isExpanded) Icons.Filled.Close else Icons.Filled.Menu, - isOpaque = false - ) + } + }, + floatingActionButton = { + if (!isAndroidLandscape) { + MainFloatingActionButtons( + isEditMode = isEditMode, + isQrVisible = isQrVisible, + showMidiCtrl = showMidiCtrl, + isExpanded = isExpanded, + isSearchActive = isSearchActive, + isShareExpanded = isShareExpanded, + onToggleShareExpanded = { isShareExpanded = !isShareExpanded }, + onUndoEdit = { + scope.launch { + codeContent = sourceContent + withContext(Dispatchers.Main) { solfaScreenModel.loadExternalFile(originalPath) } + } + }, + onSaveEdit = { + scope.launch { + try { + val initialDir = solfaScreenModel.fileRepository.getAppPublicFolder().absolutePath + saveLauncher.launch(fileName, initialDir) + } catch (e: Exception) { + e.printStackTrace() } } - AnimatedVisibility( - visible = showMidiCtrl, - enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, - exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 } - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.Start, - verticalAlignment = Alignment.CenterVertically - ) { - Box( - modifier = Modifier.fillMaxWidth() - .padding(top = 15.dp) - ) { - if (player != null) { - MidiControlPanel( - isPause = isPos, - currentPos = currentPos, - volume = volumelevel, - duration = duration, - solfaScrollState, - onPlayPauseClick = { - sharedScreenModel.togglePlayPause() - }, - onSeek = { newPos -> - sharedScreenModel.setDragging(true) - sharedScreenModel.seekTo(newPos) - scope.launch { - delay(100) - sharedScreenModel.setDragging(false) - } - //println("DrawerUI:335: mihetsika $newPos") - }, - mediaPlayer = player, - onVolumeChange = { newVolume -> - sharedScreenModel.setVolume(newVolume) - // println("Changement volume $newVolume -l $volumelevel") - }, - onVoiceVolumeChange = { index, volume -> - player?.updateVoiceVolume(index, volume) - }, - sharedScreenModel = sharedScreenModel - ) - } else { - Text("Sélectionner un morceau") + }, + onCloseEdit = { sharedScreenModel.toggleEditorMode(false) }, + onDescGrid = { sharedScreenModel.descGridCount(1) }, + onAddGrid = { sharedScreenModel.addGridCount(1) }, + onToggleSearch = { + sharedScreenModel.showSearchMenu(true) + isCustomKeyboardVisible = true + scope.launch { + delay(100) + focusRequester.requestFocus() + } + sharedScreenModel.setExpandedFAB(!isExpanded) + }, + onToggleQRCode = { + sharedScreenModel.toggleQRCodeVisibility() + sharedScreenModel.setExpandedFAB(false) + isShareExpanded = false + }, + onTogglePrint = { showPrintSettings = !showPrintSettings; isShareExpanded = false }, + onExportMidi = { + isShareExpanded = false + scope.launch { + withContext(Dispatchers.IO) { + try { + val cleanS = songTitle.replace(' ', '_') + val exportName = "${cleanS.ifEmpty { "partition" }}.mid" + val savedPath = solfaScreenModel.fileRepository.pickSavePath(defaultName = exportName, title = "Enregistrer le fichier MIDI") + if (!savedPath.isNullOrEmpty()) { + val transpositionInterval = sharedScreenModel.transpositionInterval.value + val bpm = sharedScreenModel.getBpmFlow().value ?: 120f + solfaScreenModel.generateMidiFile(bpm, savedPath, transpositionInterval) } - Box( - modifier = Modifier - .align(Alignment.TopEnd) - .offset(y = (-30).dp, x = (-10).dp) - ) { - MyFAB( - onClick = { - sharedScreenModel.setMidiCtrl(false) - }, - icon = Icons.Filled.StopCircle - ) - } - } + } catch (e: Exception) { e.printStackTrace() } } } - } - } + }, + onToggleMidiCtrl = { sharedScreenModel.setMidiCtrl(!showMidiCtrl) }, + onToggleExpandedFAB = { + sharedScreenModel.setExpandedFAB(!isExpanded) + refreshTrigeer++ + sharedScreenModel.loadNewSong(midiFile) + }, + player = player, + isPos = isPos, + currentPos = currentPos, + volumelevel = volumelevel, + duration = duration, + solfaScrollState = solfaScrollState, + sharedScreenModel = sharedScreenModel, + scope = scope + ) + } else { + LandscapeFloatingActionButtons( + isEditMode = isEditMode, + isQrVisible = isQrVisible, + showMidiCtrl = showMidiCtrl, + isExpanded = isExpanded, + isSearchActive = isSearchActive, + isShareExpanded = isShareExpanded, + leftCutoutWidth = leftCutoutWidth, + onToggleShareExpanded = { isShareExpanded = !isShareExpanded }, + onUndoEdit = { + scope.launch { + codeContent = sourceContent + withContext(Dispatchers.Main) { solfaScreenModel.loadExternalFile(originalPath) } + } + }, + onSaveEdit = { + scope.launch { + try { + val initialDir = solfaScreenModel.fileRepository.getAppPublicFolder().absolutePath + saveLauncher.launch(fileName, initialDir) + } catch (e: Exception) { e.printStackTrace() } + } + }, + onCloseEdit = { sharedScreenModel.toggleEditorMode(false) }, + onDescGrid = { sharedScreenModel.descGridCount(1) }, + onAddGrid = { sharedScreenModel.addGridCount(1) }, + onToggleQRCode = { + sharedScreenModel.toggleQRCodeVisibility() + sharedScreenModel.setExpandedFAB(false) + isShareExpanded = false + }, + onTogglePrint = { showPrintSettings = !showPrintSettings; isShareExpanded = false }, + onExportMidi = { + isShareExpanded = false + scope.launch { + withContext(Dispatchers.IO) { + try { + val cleanS = songTitle.replace(' ', '_') + val exportName = "${cleanS.ifEmpty { "partition" }}.mid" + val savedPath = solfaScreenModel.fileRepository.pickSavePath(defaultName = exportName, title = "Enregistrer le fichier MIDI") + if (!savedPath.isNullOrEmpty()) { + val transpositionInterval = sharedScreenModel.transpositionInterval.value + val bpm = sharedScreenModel.getBpmFlow().value ?: 120f + solfaScreenModel.generateMidiFile(bpm, savedPath, transpositionInterval) + } + } catch (e: Exception) { e.printStackTrace() } + } + } + }, + onToggleMidiCtrl = { sharedScreenModel.setMidiCtrl(!showMidiCtrl) }, + onToggleExpandedFAB = { sharedScreenModel.setExpandedFAB(false) }, + player = player, + isPos = isPos, + currentPos = currentPos, + volumelevel = volumelevel, + duration = duration, + solfaScrollState = solfaScrollState, + sharedScreenModel = sharedScreenModel, + scope = scope + ) } } ) { paddingValues -> - - Column( - modifier = Modifier - .fillMaxSize() - .padding(paddingValues) - ) { - Box( - modifier = Modifier - .fillMaxWidth() - .weight(1f) - ) { - content(PaddingValues(0.dp)) - - androidx.compose.animation.AnimatedVisibility( - visible = isQrVisible, - enter = slideInVertically( - initialOffsetY = { fullHeight -> fullHeight } - ) + fadeIn(), - exit = slideOutVertically( - targetOffsetY = { fullHeight -> fullHeight } - ) + fadeOut() - ) { - QRDisplay( - sharedScreenModel = sharedScreenModel, - fileRepository = solfaScreenModel.fileRepository, - playlistName = qrData?.playlistName, - playlistRawText = qrData?.rawText, - onClose = { sharedScreenModel.hideQRCode() } - ) - } - - if (createMode) { - NewPartition( - onCreate = { partMtdata -> - solfaScreenModel.newSolfa(partMtdata) - sharedScreenModel.toggleCreateMode(!createMode) - sharedScreenModel.toggleEditorMode(createMode) - if (!isAndroid) { - sharedScreenModel.toggleSourceMode() - } - }, - onDismissRequest = { - sharedScreenModel.toggleCreateMode(false) - }, - isAndroid - ) - } - - var isHovered by remember { mutableStateOf(false) } - val offsetX by animateDpAsState(targetValue = if (isHovered || isSearchActive) 0.dp else 15.dp) - - androidx.compose.animation.AnimatedVisibility( - visible = !isEditMode && !isQrVisible && !createMode && !isExpanded, + if (isAndroidLandscape) { + Row(modifier = Modifier.fillMaxSize().padding(paddingValues)) { + // Colonne Gauche Paysage + Column( modifier = Modifier - .align(Alignment.TopEnd) - .padding(top = 15.dp) - .offset(x = offsetX) - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent() - when (event.type) { - PointerEventType.Enter -> isHovered = true - PointerEventType.Exit -> isHovered = false - } - } - } - } + .fillMaxHeight() + .width(maxOf(leftCutoutWidth, 48.dp)) + .background(MaterialTheme.colorScheme.primary) + .padding(top = if(isFullScreenEnabled) 0.dp else 20.dp ,bottom = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceBetween ) { + IconButton(onClick = { scope.launch { drawerState.open() } }, modifier = Modifier.size(50.dp)) { + Icon(imageVector = Icons.Filled.Menu, contentDescription = "Ouvrir Menu Latéral", tint = MaterialTheme.colorScheme.onPrimary) + } + Spacer(modifier = Modifier.height(10.dp)) + TranspositionDropdown( + songKey = songKey, + fileContent = fileContent, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + sharedInteractionSource = sharedInteractionSource, + isLandscapeMode = true + ) + Spacer(modifier = Modifier.weight(1f)) IconButton( onClick = { if (isSearchActive) { @@ -1152,315 +695,1205 @@ fun MainScreenWithDrawer( textInput = TextFieldValue("", TextRange.Zero) } else { sharedScreenModel.showSearchMenu(true) + isCustomKeyboardVisible = true scope.launch { delay(100) focusRequester.requestFocus() } } }, - modifier = Modifier - .size(55.dp) - .alpha(0.6f) - .background( - color = MaterialTheme.colorScheme.tertiary, - shape = CircleShape - ) + modifier = Modifier.size(50.dp).background(color = MaterialTheme.colorScheme.tertiary, shape = CircleShape) ) { Icon( imageVector = if (isSearchActive) Icons.Default.Close else Icons.Default.Search, contentDescription = "Btn search", - tint = MaterialTheme.colorScheme.onTertiary + tint = MaterialTheme.colorScheme.onTertiary, + modifier = Modifier.size(30.dp) + ) + } + if(!isEditMode) { + Spacer(modifier = Modifier.height(20.dp)) + MyFAB( + onClick = { + sharedScreenModel.setExpandedFAB(!isExpanded) + refreshTrigeer++ + sharedScreenModel.loadNewSong(midiFile) + }, + size = 50.dp, + icon = if (isExpanded) Icons.Filled.Close else Icons.AutoMirrored.Default.MenuOpen, + isOpaque = true ) } } - androidx.compose.animation.AnimatedVisibility( - visible = isSearchActive && textInput.text.isNotEmpty(), - enter = fadeIn() + expandVertically(), - exit = fadeOut() + shrinkVertically(), - modifier = Modifier - .align(Alignment.TopCenter) - .fillMaxWidth(0.85f) - .padding(top = 8.dp) - .padding(bottom = if (isAndroid && isNumericKeyboard) keyboardHeightDp else 0.dp) - ) { - Card( - elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), - shape = RoundedCornerShape(12.dp), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), - modifier = Modifier.fillMaxHeight() + // Centre Paysage + Column(modifier = Modifier.weight(1f).fillMaxHeight()) { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f) ) { - var sortedSongs by remember { mutableStateOf(emptyList()) } - var isSearching by remember { mutableStateOf(true) } + content(PaddingValues(0.dp)) - LaunchedEffect(filteredSongs, textInput.text) { - isSearching = true - val query = textInput.text - val result = withContext(Dispatchers.Default) { - val naturalComparator = Comparator { a, b -> - val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)") - val chunksA = a.title.lowercase().split(regex) - val chunksB = b.title.lowercase().split(regex) - var result = 0 - val size = minOf(chunksA.size, chunksB.size) - for (i in 0 until size) { - val chunkA = chunksA[i] - val chunkB = chunksB[i] - val numA = chunkA.toLongOrNull() - val numB = chunkB.toLongOrNull() - result = if (numA != null && numB != null) { - numA.compareTo(numB) - } else { - chunkA.compareTo(chunkB) - } - if (result != 0) break - } - if (result == 0) chunksA.size.compareTo(chunksB.size) else result - } - - if (query.isBlank()) { - filteredSongs.sortedWith( - compareBy { item -> !item.path.startsWith("assets://") } - .thenComparing(naturalComparator) - ) - } else { - filteredSongs.sortedWith( - compareByDescending { item -> item.getSearchScore(query) } - .thenBy { item -> !item.path.startsWith("assets://") } - .thenComparing(naturalComparator) - ) - } - } - sortedSongs = result - isSearching = false + androidx.compose.animation.AnimatedVisibility( + visible = isQrVisible, + enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(), + exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut() + ) { + QRDisplay( + sharedScreenModel = sharedScreenModel, + fileRepository = solfaScreenModel.fileRepository, + playlistName = qrData?.playlistName, + playlistRawText = qrData?.rawText, + onClose = { sharedScreenModel.hideQRCode() } + ) } - val searchListState = rememberLazyListState() - - LaunchedEffect(textInput.text) { - if (sortedSongs.isNotEmpty()) { - searchListState.scrollToItem(0) - } + if (createMode) { + NewPartition( + onCreate = { partMtdata -> + solfaScreenModel.newSolfa(partMtdata) + sharedScreenModel.toggleCreateMode(!createMode) + sharedScreenModel.toggleEditorMode(createMode) + if (!isAndroid) sharedScreenModel.toggleSourceMode() + }, + onDismissRequest = { sharedScreenModel.toggleCreateMode(false) }, + isAndroid + ) } - Box(modifier = Modifier.fillMaxSize()) { - LazyColumn( - state = searchListState, - modifier = Modifier.fillMaxSize() - ) { - if (!isSearching && sortedSongs.isEmpty() && textInput.text.isNotEmpty()) { - item { - ListItem( - headlineContent = { - Text( - text = "Partition non trouvée pour \"${textInput.text}\"", - color = MaterialTheme.colorScheme.error, - fontWeight = FontWeight.Medium, - fontSize = 14.sp - ) - }, - supportingContent = { - Text( - text = "Essayez un autre.", - fontSize = 12.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - }, - leadingContent = { - Icon( - imageVector = Icons.Default.SearchOff, - contentDescription = "Not result search", - tint = MaterialTheme.colorScheme.error - ) - } + androidx.compose.animation.AnimatedVisibility( + visible = isSearchActive && textInput.text.isNotEmpty(), + enter = fadeIn() + expandVertically(), + exit = fadeOut() + shrinkVertically(), + modifier = Modifier + .align(Alignment.TopCenter) + .fillMaxWidth(0.85f) + .fillMaxHeight() + .padding(top = 8.dp) + .padding(bottom = searchOverlayBottomPadding) + ) { + SearchOverlayCard( + isSearchActive = isSearchActive, + textInput = textInput, + filteredSongs = filteredSongs, + favoritePaths = favoritePaths.toSet(), + lastPlaylistPaths = lastPlaylistPaths, + keyboardHeightDp = keyboardHeightDp, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isNumericKeyboard = isNumericKeyboard, + isCustomKeyboardVisible = isCustomKeyboardVisible, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + midiFile = midiFile, + scope = scope, + onScrollAction = hideSearchKeyboards + ) + } + + CustomKeyboardSection( + isSearchActive = isSearchActive, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isCustomKeyboardVisible = isCustomKeyboardVisible, + isNumericKeyboard = isNumericKeyboard, + textInput = textInput, + onTextChanged = { textInput = it }, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + isFullScreenEnabled = isFullScreenEnabled, + density = density, + onKeyboardHeightMeasured = { keyboardHeightDp = it }, + onToggleKeyboard = toggleNumericKeyboard, + onHideKeyboard = { + isCustomKeyboardVisible = false + focusManager.clearFocus(force = true) + keyboardController?.hide() + }, + modifier = Modifier + .align(Alignment.BottomEnd) + .fillMaxWidth(0.4f) + ) + SolfaKeyboardSection( + solfaKeyboardState = solfaKeyboardState, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isEditMode = isEditMode + ) + } + + } + + // Colonne Droite Paysage + BoxWithConstraints( + modifier = Modifier + .fillMaxHeight() + .width(maxOf(rightNavBarWidth, 36.dp)) + .background(color = MaterialTheme.colorScheme.primary) + .padding(25.dp), + contentAlignment = Alignment.Center + ) { + val screenHeight = maxHeight + Text( + text = songTitle, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onPrimary, + maxLines = 1, + softWrap = false, + modifier = Modifier.requiredWidth(screenHeight).graphicsLayer(rotationZ = 90f), + textAlign = TextAlign.Start + ) + } + } + } else { + // Portrait / Desktop + Column( + modifier = Modifier.fillMaxSize() + .padding(paddingValues) + ) { + Box( + modifier = Modifier.fillMaxWidth().weight(1f) + ) { + content(PaddingValues(0.dp)) + + androidx.compose.animation.AnimatedVisibility( + visible = isQrVisible, + enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(), + exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut() + ) { + QRDisplay( + sharedScreenModel = sharedScreenModel, + fileRepository = solfaScreenModel.fileRepository, + playlistName = qrData?.playlistName, + playlistRawText = qrData?.rawText, + onClose = { sharedScreenModel.hideQRCode() } + ) + } + + if (createMode) { + NewPartition( + onCreate = { partMtdata -> + solfaScreenModel.newSolfa(partMtdata) + sharedScreenModel.toggleCreateMode(!createMode) + sharedScreenModel.toggleEditorMode(createMode) + if (!isAndroid) sharedScreenModel.toggleSourceMode() + }, + onDismissRequest = { sharedScreenModel.toggleCreateMode(false) }, + isAndroid + ) + } + androidx.compose.animation.AnimatedVisibility( + visible = isSearchActive && textInput.text.isNotEmpty(), + enter = fadeIn() + expandVertically(), + exit = fadeOut() + shrinkVertically(), + modifier = Modifier + .align(Alignment.TopCenter) + .fillMaxWidth(0.85f) + .fillMaxHeight() + .padding(top = 8.dp) + .padding(bottom = searchOverlayBottomPadding) + ) { + SearchOverlayCard( + isSearchActive = isSearchActive, + textInput = textInput, + filteredSongs = filteredSongs, + favoritePaths = favoritePaths.toSet(), + lastPlaylistPaths = lastPlaylistPaths, + keyboardHeightDp = keyboardHeightDp, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isNumericKeyboard = isNumericKeyboard, + isCustomKeyboardVisible = isCustomKeyboardVisible, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + midiFile = midiFile, + scope = scope, + onScrollAction = hideSearchKeyboards + ) + } + + HoverSearchButton( + isEditMode = isEditMode, + isQrVisible = isQrVisible, + createMode = createMode, + isExpanded = isExpanded, + isSearchActive = isSearchActive, + textInput = textInput, + sharedScreenModel = sharedScreenModel, + focusRequester = focusRequester, + scope = scope, + onSearchOpened = { isCustomKeyboardVisible = true }, + modifier = if (isAndroid) Modifier.align(Alignment.TopEnd) else Modifier + ) + CustomKeyboardSection( + isSearchActive = isSearchActive, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isCustomKeyboardVisible = isCustomKeyboardVisible, + isNumericKeyboard = isNumericKeyboard, + textInput = textInput, + onTextChanged = { textInput = it }, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + isFullScreenEnabled = isFullScreenEnabled, + density = density, + onKeyboardHeightMeasured = { keyboardHeightDp = it }, + onToggleKeyboard = toggleNumericKeyboard, + onHideKeyboard = { + isCustomKeyboardVisible = false + focusManager.clearFocus(force = true) + keyboardController?.hide() + }, + modifier = Modifier.align(Alignment.BottomCenter) + ) + SolfaKeyboardSection( + solfaKeyboardState = solfaKeyboardState, + isAndroid = isAndroid, + isAndroidLandscape = isAndroidLandscape, + isEditMode = isEditMode + ) + } + } + } + } + } + } + }) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun MainTopBar( + modifier: Modifier, + isSearchActive: Boolean, + isLandscape: Boolean, + textInput: TextFieldValue, + onTextChanged: (TextFieldValue) -> Unit, + isAndroid: Boolean, + isNumericKeyboard: Boolean, + onToggleNumericKeyboard: () -> Unit, + onClearSearch: () -> Unit, + onEnableNumericClick: () -> Unit, + onFieldFocused: () -> Unit = {}, + songTitle: String, + scrollState: ScrollState, + focusRequester: FocusRequester, + sharedInteractionSource: MutableInteractionSource, + onOpenDrawer: () -> Unit, + isQrVisible: Boolean, + isAndroidLandscape: Boolean, + songKey: String, + fileContent: String, + sharedScreenModel: SharedScreenModel, + solfaScreenModel: SolfaScreenModel +) { + TopAppBar( + modifier = modifier, + windowInsets = if (!isLandscape) WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top) else WindowInsets(0, 0, 0, 0), + title = { + AnimatedContent(targetState = isSearchActive, label = "SearchTransition") { searchActive -> + if (searchActive) { + Box(modifier = Modifier.fillMaxHeight(), contentAlignment = Alignment.Center) { + BasicTextField( + value = textInput, + onValueChange = onTextChanged, + readOnly = isAndroid && isNumericKeyboard, + textStyle = LocalTextStyle.current.copy(color = Color.White, fontSize = 16.sp), + singleLine = true, + cursorBrush = SolidColor(Color.White), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), + modifier = Modifier + .fillMaxWidth() + .height(38.dp) + .focusRequester(focusRequester) + .onFocusChanged { if (it.isFocused) onFieldFocused() } + .background(color = Color.White.copy(alpha = 0.15f), shape = RoundedCornerShape(20.dp)), + decorationBox = { innerTextField -> + TextFieldDefaults.DecorationBox( + value = textInput.text, + innerTextField = innerTextField, + enabled = true, + singleLine = true, + visualTransformation = VisualTransformation.None, + interactionSource = sharedInteractionSource, + placeholder = { Text(text = "FFPM 1 Andriananahary ...", color = Color.White.copy(alpha = 0.5f), fontSize = 16.sp) }, + leadingIcon = { Icon(imageVector = Icons.Default.Search, contentDescription = null, tint = Color.White.copy(alpha = 0.8f), modifier = Modifier.size(20.dp)) }, + trailingIcon = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp)) { + if (isAndroid) { + IconButton(onClick = onToggleNumericKeyboard, modifier = Modifier.size(32.dp)) { + Icon( + imageVector = if (isNumericKeyboard) Icons.Default.Abc else Icons.Filled._123, + contentDescription = null, + tint = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.size(22.dp) ) } } - itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item -> - val isFavorite = favoritePaths.contains(item) - val onPlaylist = item.path in lastPlaylistPaths - val dismissState = rememberSwipeToDismissBoxState( - confirmValueChange = { dismissValue -> - if (dismissValue == SwipeToDismissBoxValue.StartToEnd || dismissValue == SwipeToDismissBoxValue.EndToStart) { - sharedScreenModel.toFavorite(item.path) - sharedScreenModel.updateSearchTxt("") - sharedScreenModel.reset() - solfaScreenModel.loadFromFile(item.path) - sharedScreenModel.stopMidi() - sharedScreenModel.seekTo(0f) - sharedScreenModel.setTranspositionInterval(0) - false - } else { - false - } - } - ) - SwipeToDismissBox( - state = dismissState, - backgroundContent = { - val color = if (isFavorite) Color.Gray else MaterialTheme.colorScheme.tertiary - val scale by animateFloatAsState( - targetValue = if (dismissState.progress > 0.1f) 1.2f else 0.8f, - label = "iconScale" - ) - Box( - modifier = Modifier - .fillMaxSize() - .background(color) - .padding(horizontal = 20.dp), - contentAlignment = if (dismissState.dismissDirection == SwipeToDismissBoxValue.StartToEnd) - Alignment.CenterStart else Alignment.CenterEnd - ) { - Icon( - imageVector = if (isFavorite) Icons.Default.FavoriteBorder else Icons.Default.Favorite, - contentDescription = "Favorite btn", - modifier = Modifier.scale(scale), - tint = MaterialTheme.colorScheme.onSecondary - ) - } - } - ) { - ListItem( - leadingContent = { - Icon( - imageVector = if (item.path.startsWith("assets://")) Icons.Default.ArrowDropDownCircle else Icons.Default.Folder, - contentDescription = "Part interne ou personnel", - modifier = Modifier.size(30.dp) - ) - }, - headlineContent = { Text(item.title) }, - supportingContent = { Text(item.contentTitle, maxLines = 1) }, - trailingContent = { - IconButton( - onClick = { - scope.launch { - sharedScreenModel.addSongToPlaylist(songTitle = item.title, path = item.path) - } - }, - modifier = Modifier.size(35.dp) - ) { - Icon( - imageVector = Icons.AutoMirrored.Default.PlaylistAdd, - contentDescription = if (onPlaylist) "Déjà dans la playlist" else "Btn add playlist", - tint = if (!onPlaylist) Color.LightGray else Color( - 0xFFFFD700 - ) - ) - } - }, - modifier = Modifier.clickable { - sharedScreenModel.updateSearchTxt("") - sharedScreenModel.reset() - solfaScreenModel.loadFromFile(item.path) - sharedScreenModel.loadNewSong(midiFile) - }) - } - HorizontalDivider() + IconButton(onClick = onClearSearch, modifier = Modifier.size(32.dp)) { + Icon(imageVector = Icons.Default.Clear, contentDescription = null, tint = Color.White.copy(alpha = 0.8f), modifier = Modifier.size(18.dp)) } } + }, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 0.dp), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent + ) + ) + } + ) + if (isAndroid && isNumericKeyboard) { + Box( + modifier = Modifier + .align(Alignment.CenterStart) + .fillMaxWidth() + .padding(end = 80.dp) + .height(38.dp) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onEnableNumericClick) + ) + } + } + } else { + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState), verticalArrangement = Arrangement.Center) { + Row { + Text( + songTitle, + modifier = Modifier.weight(1f, fill = true), + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.headlineLarge + ) + } + } + } + } + }, + navigationIcon = { + if (!isQrVisible && !isAndroidLandscape) { + IconButton(onClick = onOpenDrawer) { + Icon(Icons.Filled.Menu, contentDescription = "Ouvrir Menu Latéral") + } + } + }, + actions = { + TranspositionDropdown( + songKey = songKey, + fileContent = fileContent, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel, + sharedInteractionSource = sharedInteractionSource, + isLandscapeMode = false + ) + }, + colors = TopAppBarColors( + containerColor = MaterialTheme.colorScheme.primary, + titleContentColor = MaterialTheme.colorScheme.onPrimary, + actionIconContentColor = MaterialTheme.colorScheme.onPrimary, + navigationIconContentColor = MaterialTheme.colorScheme.onPrimary, + scrolledContainerColor = MaterialTheme.colorScheme.onPrimary + ) + ) +} - if (isSearching) { - Box( - modifier = Modifier.fillMaxSize(), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - modifier = Modifier.size(40.dp), - color = MaterialTheme.colorScheme.primary, - strokeWidth = 3.dp - ) - } +@Composable +private fun TranspositionDropdown( + songKey: String, + fileContent: String, + sharedScreenModel: SharedScreenModel, + solfaScreenModel: SolfaScreenModel, + sharedInteractionSource: MutableInteractionSource, + isLandscapeMode: Boolean +) { + val appliedInterval by sharedScreenModel.transpositionInterval.collectAsState() + var tempInterval by remember(fileContent, appliedInterval) { mutableStateOf(appliedInterval) } + var isEyeVisible by remember { mutableStateOf(false) } + val isMinor = songKey.endsWith("m", ignoreCase = true) + val cleanSongKey = if (isMinor) songKey.dropLast(1) else songKey + val keysOrder = Transpose.keyToNumber + val songKeyIndex = keysOrder.indexOf(cleanSongKey).takeIf { it != -1 } ?: 0 + val rawKeyIndex = (songKeyIndex + tempInterval) % 12 + val tempUiKey = keysOrder[if (rawKeyIndex < 0) rawKeyIndex + 12 else rawKeyIndex] + val isPendingChange = tempInterval != appliedInterval + val isCurrentlyTransposed = appliedInterval != 0 + val formattedKey = if (isMinor) "${tempUiKey}m" else tempUiKey + + Box( + modifier = if (isLandscapeMode) Modifier.padding(vertical = 4.dp) else Modifier.padding(end = 16.dp), + contentAlignment = if (isLandscapeMode) Alignment.Center else Alignment.TopCenter + ) { + Row(modifier = if (isLandscapeMode) Modifier.wrapContentSize() else Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically) { + Text( + text = formattedKey, + style = if (isLandscapeMode) MaterialTheme.typography.titleMedium else MaterialTheme.typography.displaySmall, + fontWeight = FontWeight.Black, + textAlign = TextAlign.Center, + color = if (isCurrentlyTransposed || isPendingChange) MaterialTheme.colorScheme.tertiary else Color.White, + modifier = Modifier + .clickable(interactionSource = sharedInteractionSource, indication = null) { isEyeVisible = !isEyeVisible } + .then(if (isLandscapeMode) Modifier.padding(vertical = 4.dp) else Modifier.width(65.dp)) + ) + } + + DropdownMenu( + expanded = isEyeVisible, + onDismissRequest = { + tempInterval = appliedInterval + isEyeVisible = false + }, + containerColor = Color(0xFF2C3135).copy(alpha = 0.75f), + shape = RoundedCornerShape(16.dp), + modifier = Modifier.padding(12.dp) + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { + val isOriginalKeyC = cleanSongKey.equals("C", ignoreCase = true) + val isTransposedToC = tempUiKey.equals("C", ignoreCase = true) && !isOriginalKeyC + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.padding(horizontal = 4.dp)) { + val currentIndex = keysOrder.indexOf(tempUiKey).takeIf { it != -1 } ?: 0 + + IconButton(modifier = Modifier.size(if (isLandscapeMode) 32.dp else 36.dp), onClick = { tempInterval-- }) { + Icon(imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = null, tint = Color.White) + } + + val centralIcon = if (isPendingChange && !isTransposedToC) Icons.Filled.Check else Icons.Filled.SwapHoriz + val centralTint = if (isPendingChange) MaterialTheme.colorScheme.tertiary else Color.White + + IconButton( + modifier = Modifier.size(if (isLandscapeMode) 32.dp else 36.dp), + onClick = { + if (isPendingChange) { + sharedScreenModel.setTranspositionInterval(tempInterval) + sharedScreenModel.stopMidi() + sharedScreenModel.seekTo(0f) + solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value) + } else if (isCurrentlyTransposed) { + tempInterval = 0 + sharedScreenModel.setTranspositionInterval(0) + sharedScreenModel.stopMidi() + sharedScreenModel.seekTo(0f) + solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value) + } + isEyeVisible = false + } + ) { + Icon(imageVector = centralIcon, contentDescription = null, tint = centralTint) + } + + IconButton(modifier = Modifier.size(if (isLandscapeMode) 32.dp else 36.dp), onClick = { tempInterval++ }) { + Icon(imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null, tint = Color.White) + } + } + + val cIndex = keysOrder.indexOf("C") + val intervalToC = if (cIndex != -1) cIndex - songKeyIndex else 0 + val buttonText = if (isTransposedToC) "Revenir en $songKey" else "Transposer en C" + OutlinedButton( + onClick = { + if (isTransposedToC) { + tempInterval = 0 + sharedScreenModel.setTranspositionInterval(0) + sharedScreenModel.setTranspToC(0) + sharedScreenModel.stopMidi() + sharedScreenModel.seekTo(0f) + } else { + val currentKey = sharedScreenModel.songKey.value + val intervalC = getIntervalToC(currentKey) + + tempInterval = -intervalC + sharedScreenModel.setTranspToC(intervalC) + sharedScreenModel.stopMidi() + sharedScreenModel.seekTo(0f) + } + isEyeVisible = false + }, + modifier = Modifier.fillMaxWidth().height(if (isLandscapeMode) 32.dp else 36.dp), + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5f)), + colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.tertiary) + ) { + Text(text = buttonText, fontSize = if (isLandscapeMode) 10.sp else 12.sp, fontWeight = FontWeight.Bold) + } + } + } + } +} + +@Composable +private fun MainFloatingActionButtons( + isEditMode: Boolean, + isQrVisible: Boolean, + showMidiCtrl: Boolean, + isExpanded: Boolean, + isSearchActive: Boolean, + isShareExpanded: Boolean, + onToggleShareExpanded: () -> Unit, + onUndoEdit: () -> Unit, + onSaveEdit: () -> Unit, + onCloseEdit: () -> Unit, + onDescGrid: () -> Unit, + onAddGrid: () -> Unit, + onToggleSearch: () -> Unit, + onToggleQRCode: () -> Unit, + onTogglePrint: () -> Unit, + onExportMidi: () -> Unit, + onToggleMidiCtrl: () -> Unit, + onToggleExpandedFAB: () -> Unit, + player: FMediaPlayer?, + isPos: Boolean, + currentPos: Float, + volumelevel: Float, + duration: Float, + solfaScrollState: ScrollState, + sharedScreenModel: SharedScreenModel, + scope: kotlinx.coroutines.CoroutineScope +) { + val solfaKeyboardState = LocalSolfaKeyboardState.current + val isSolfaKeyboardVisible = solfaKeyboardState.isVisible && solfaKeyboardState.isDialogActive + Row(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth().padding(5.dp), + horizontalArrangement = Arrangement.spacedBy(7.dp, Alignment.End), + verticalAlignment = Alignment.CenterVertically + ) { + if (isEditMode) { + if (!isSolfaKeyboardVisible) { + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onUndoEdit, icon = Icons.AutoMirrored.Default.Undo) + } + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onSaveEdit, icon = Icons.Filled.SaveAs) + } + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onCloseEdit, icon = Icons.Default.Close) + } + } + } else if (!isQrVisible) { + if (!showMidiCtrl) { + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + MyFAB(onClick = onDescGrid, size = 30.dp, icon = Icons.Default.Remove) + MyFAB(onClick = onAddGrid, size = 30.dp, icon = Icons.Default.Add) + } + } + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onToggleSearch, icon = if (isSearchActive) Icons.Default.Close else Icons.Default.Search) + } + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + Box(modifier = Modifier.size(55.dp), contentAlignment = Alignment.BottomEnd) { + androidx.compose.animation.AnimatedVisibility( + visible = isShareExpanded, + enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), + exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut(), + modifier = Modifier.align(Alignment.BottomEnd).offset(y = (-65).dp).wrapContentWidth(unbounded = true) + ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + MyFAB(onClick = onToggleQRCode, icon = Icons.Filled.QrCode2) + MyFAB(onClick = onTogglePrint, icon = Icons.Filled.Print) + MyFAB(onClick = onExportMidi, icon = Icons.Filled.AudioFile) + } + } + MyFAB(onClick = onToggleShareExpanded, icon = Icons.Filled.Share) + } + } + } + if (!showMidiCtrl && !isSearchActive) { + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onToggleMidiCtrl, icon = Icons.Filled.PlayCircle) + } + if(!isSolfaKeyboardVisible) { + MyFAB( + onClick = onToggleExpandedFAB, + icon = if (isExpanded) Icons.Filled.Close else Icons.Filled.Menu, + isOpaque = false + ) + } + } + } + AnimatedVisibility(visible = showMidiCtrl, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically) { + Box(modifier = Modifier.fillMaxWidth().padding(top = 15.dp)) { + if (player != null) { + MidiControlPanel( + isPause = isPos, + currentPos = currentPos, + volume = volumelevel, + duration = duration, + solfaScrollState, + onPlayPauseClick = { sharedScreenModel.togglePlayPause() }, + onSeek = { newPos -> + sharedScreenModel.setDragging(true) + sharedScreenModel.seekTo(newPos) + scope.launch { delay(100); sharedScreenModel.setDragging(false) } + }, + mediaPlayer = player, + onVolumeChange = { newVolume -> sharedScreenModel.setVolume(newVolume) }, + onVoiceVolumeChange = { index, volume -> player.updateVoiceVolume(index, volume) }, + sharedScreenModel = sharedScreenModel + ) + } else { + Text("Sélectionner un morceau") + } + Box(modifier = Modifier.align(Alignment.TopEnd).offset(y = (-30).dp, x = (-10).dp)) { + MyFAB(onClick = { sharedScreenModel.setMidiCtrl(false) }, icon = Icons.Filled.StopCircle) + } + } + } + } + } + } +} + +@Composable +private fun LandscapeFloatingActionButtons( + isEditMode: Boolean, + isQrVisible: Boolean, + showMidiCtrl: Boolean, + isExpanded: Boolean, + isSearchActive: Boolean, + isShareExpanded: Boolean, + leftCutoutWidth: Dp, + onToggleShareExpanded: () -> Unit, + onUndoEdit: () -> Unit, + onSaveEdit: () -> Unit, + onCloseEdit: () -> Unit, + onDescGrid: () -> Unit, + onAddGrid: () -> Unit, + onToggleQRCode: () -> Unit, + onTogglePrint: () -> Unit, + onExportMidi: () -> Unit, + onToggleMidiCtrl: () -> Unit, + onToggleExpandedFAB: () -> Unit, + player: FMediaPlayer?, + isPos: Boolean, + currentPos: Float, + volumelevel: Float, + duration: Float, + solfaScrollState: ScrollState, + sharedScreenModel: SharedScreenModel, + scope: kotlinx.coroutines.CoroutineScope +) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = leftCutoutWidth + 70.dp, bottom = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.Start), + verticalAlignment = Alignment.CenterVertically + ) { + if (isEditMode) { + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onUndoEdit, icon = Icons.AutoMirrored.Default.Undo) + } + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onSaveEdit, icon = Icons.Filled.SaveAs) + } + AnimatedVisibility(visible = true, enter = fadeIn() + scaleIn() + slideInHorizontally { it / 2 }, exit = fadeOut() + scaleOut() + slideOutHorizontally { it / 2 }) { + MyFAB(onClick = onCloseEdit, icon = Icons.Default.Close) + } + } else if (!isQrVisible) { + if (!showMidiCtrl && !isSearchActive) { + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut()) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + MyFAB(onClick = onDescGrid, size = 35.dp, icon = Icons.Default.Remove) + MyFAB(onClick = onAddGrid, size = 35.dp, icon = Icons.Default.Add) + } + } + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut()) { + Box(modifier = Modifier.size(55.dp), contentAlignment = Alignment.BottomStart) { + androidx.compose.animation.AnimatedVisibility( + visible = isShareExpanded, + enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), + exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut(), + modifier = Modifier.align(Alignment.BottomStart).offset(y = (-60).dp).wrapContentWidth(unbounded = true) + ) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) { + MyFAB(onClick = onToggleQRCode, size = 55.dp, icon = Icons.Filled.QrCode2) + MyFAB(onClick = onTogglePrint, size = 55.dp, icon = Icons.Filled.Print) + MyFAB(onClick = onExportMidi, size = 55.dp, icon = Icons.Filled.AudioFile) + } + } + MyFAB(onClick = onToggleShareExpanded, size = 55.dp, icon = Icons.Filled.Share) + } + } + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut()) { + MyFAB(onClick = onToggleMidiCtrl, icon = Icons.Filled.PlayCircle) + } + AnimatedVisibility(visible = isExpanded, enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut()) { + MyFAB(onClick = onToggleExpandedFAB, icon = Icons.Filled.Close, isOpaque = false) + } + } + } + } + AnimatedVisibility(visible = showMidiCtrl, enter = fadeIn() + slideInHorizontally { it / 2 } + scaleIn(), exit = fadeOut() + slideOutHorizontally { it / 2 } + scaleOut()) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically) { + Box(modifier = Modifier.fillMaxWidth().padding(top = 15.dp)) { + if (player != null) { + MidiControlPanel( + isPause = isPos, + currentPos = currentPos, + volume = volumelevel, + duration = duration, + solfaScrollState, + onPlayPauseClick = { sharedScreenModel.togglePlayPause() }, + onSeek = { newPos -> + sharedScreenModel.setDragging(true) + sharedScreenModel.seekTo(newPos) + scope.launch { delay(100); sharedScreenModel.setDragging(false) } + }, + mediaPlayer = player, + onVolumeChange = { newVolume -> sharedScreenModel.setVolume(newVolume) }, + onVoiceVolumeChange = { index, volume -> player.updateVoiceVolume(index, volume) }, + sharedScreenModel = sharedScreenModel + ) + } else { + Text("Sélectionner un morceau") + } + Box(modifier = Modifier.align(Alignment.TopEnd).offset(y = (-30).dp, x = (-10).dp)) { + MyFAB(onClick = { sharedScreenModel.setMidiCtrl(false) }, icon = Icons.Filled.StopCircle) + } + } + } + } +} + +@Composable +private fun SearchOverlayCard( + isSearchActive: Boolean, + textInput: TextFieldValue, + filteredSongs: List, + favoritePaths: Set, + lastPlaylistPaths: Set, + keyboardHeightDp: Dp, + isAndroid: Boolean, + isAndroidLandscape: Boolean, + isNumericKeyboard: Boolean, + isCustomKeyboardVisible: Boolean, + sharedScreenModel: SharedScreenModel, + solfaScreenModel: SolfaScreenModel, + midiFile: String, + scope: kotlinx.coroutines.CoroutineScope, + onScrollAction: () -> Unit +) { + Card( + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + shape = RoundedCornerShape(12.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + modifier = Modifier.fillMaxHeight() + ) { + var sortedSongs by remember { mutableStateOf(emptyList()) } + var isSearching by remember { mutableStateOf(true) } + + LaunchedEffect(filteredSongs, textInput.text) { + isSearching = true + val query = textInput.text + val result = withContext(Dispatchers.Default) { + val naturalComparator = Comparator { a, b -> + val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)") + val chunksA = a.title.lowercase().split(regex) + val chunksB = b.title.lowercase().split(regex) + var result = 0 + val size = minOf(chunksA.size, chunksB.size) + for (i in 0 until size) { + val chunkA = chunksA[i] + val chunkB = chunksB[i] + val numA = chunkA.toLongOrNull() + val numB = chunkB.toLongOrNull() + result = if (numA != null && numB != null) { + numA.compareTo(numB) + } else { + chunkA.compareTo(chunkB) + } + if (result != 0) break + } + if (result == 0) chunksA.size.compareTo(chunksB.size) else result + } + + if (query.isBlank()) { + filteredSongs.sortedWith( + compareBy { item -> !item.path.startsWith("assets://") } + .thenComparing(naturalComparator) + ) + } else { + filteredSongs.sortedWith( + compareByDescending { item -> item.getSearchScore(query) } + .thenBy { item -> !item.path.startsWith("assets://") } + .thenComparing(naturalComparator) + ) + } + } + sortedSongs = result + isSearching = false + } + + Box(modifier = Modifier.fillMaxSize()) { + if (isSearching) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator( + color = MaterialTheme.colorScheme.primary + ) + } + } else { + val searchListState = rememberLazyListState() + val currentOnScrollAction by rememberUpdatedState(onScrollAction) + // masquer le clavier whn scroll + LaunchedEffect(searchListState) { + searchListState.interactionSource.interactions.collect { interaction -> + if (interaction is DragInteraction.Start) currentOnScrollAction() + } + } + LaunchedEffect(textInput.text) { + if (sortedSongs.isNotEmpty()) searchListState.scrollToItem(0) + } + + LazyColumn( + state = searchListState, + modifier = Modifier.fillMaxSize() + .pointerInput(Unit) { + val touchSlop = viewConfiguration.touchSlop + awaitPointerEventScope { + var movedY = 0f + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + val change = event.changes.firstOrNull() ?: continue + if (!change.pressed || !change.previousPressed) { + movedY = 0f + } else { + movedY += kotlin.math.abs(change.position.y - change.previousPosition.y) + if (movedY > touchSlop) { + onScrollAction() + movedY = 0f } } } } - - // --- CLAVIER NUMÉRIQUE PERSONNALISÉ (Sur couche supérieure) --- - androidx.compose.animation.AnimatedVisibility( - visible = isSearchActive && isAndroid && isNumericKeyboard, - enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(), - exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut(), - modifier = Modifier.align(Alignment.BottomCenter) - ) { - CustomKeyboard( - modifier = Modifier.onGloballyPositioned { coordinates -> - keyboardHeightDp = with(density) { coordinates.size.height.toDp() } - }, - onDigitClick = { digit -> - val newText = textInput.text + digit - textInput = TextFieldValue(newText, TextRange(newText.length)) - sharedScreenModel.updateSearchTxt(newText) - }, - onDeleteClick = { - if (textInput.text.isNotEmpty()) { - val newText = textInput.text.dropLast(1) - textInput = TextFieldValue(newText, TextRange(newText.length)) - sharedScreenModel.updateSearchTxt(newText) - } - }, - onClearClick = { - textInput = TextFieldValue("", TextRange.Zero) - sharedScreenModel.updateSearchTxt("") - }, - onPrefixClick = { prefix -> - val digits = textInput.text.trim() - val cleanPrefix = prefix.trim().lowercase() - - if (digits.isNotEmpty() && digits.all { it.isDigit() }) { - val candidateSuffixes = listOf("", "-1", "-2") - - val matchingItem = candidateSuffixes.firstNotNullOfOrNull { suffix -> - val targetFileName = "$cleanPrefix-$digits$suffix.txt" - sharedScreenModel.drawerItems.value.find { item -> - item.path.endsWith(targetFileName, ignoreCase = true) - } - } - if (matchingItem != null) { - textInput = TextFieldValue("", TextRange.Zero) - sharedScreenModel.updateSearchTxt("") - sharedScreenModel.reset() - solfaScreenModel.loadFromFile(matchingItem.path) - } else { - textInput = TextFieldValue(prefix, TextRange(prefix.length)) - sharedScreenModel.updateSearchTxt(prefix) - } - } else { - textInput = TextFieldValue(prefix, TextRange(prefix.length)) - sharedScreenModel.updateSearchTxt(prefix) - } - }, - isFullScreen = isFullScreenEnabled - ) - } - } - - AnimatedVisibility( - visible = solfaKeyboardState.isVisible && solfaKeyboardState.isDialogActive && isAndroid, - enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(), - exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut() - ) { - SolfaKeyboard( - currentVoiceIndex = solfaKeyboardState.activeVoiceIndex, - currentValue = solfaKeyboardState.currentText, - onNoteClick = { note -> solfaKeyboardState.onNoteInput?.invoke(note) }, - onTabClick = { solfaKeyboardState.onTabNextVoice?.invoke() }, - onBackspaceClick = { solfaKeyboardState.onBackspace?.invoke() }, - onCloseClick = { solfaKeyboardState.onCloseDialog?.invoke() }, - onBuildClick = { solfaKeyboardState.onBuildEdit?.invoke() }, - onCustomSymbolClick = { symbol -> solfaKeyboardState.onCustomSymbol?.invoke(symbol) }, - modifier = Modifier - .fillMaxWidth() - .fillMaxHeight(0.3f) + ) { + if (!isSearching && sortedSongs.isEmpty() && textInput.text.isNotEmpty()) { + item { + ListItem( + headlineContent = { + Text( + text = "Partition non trouvée pour \"${textInput.text}\"", + color = MaterialTheme.colorScheme.error, + fontWeight = FontWeight.Medium, + fontSize = 14.sp + ) + }, + supportingContent = { + Text( + text = "Essayez un autre.", + fontSize = 12.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + leadingContent = { + Icon( + imageVector = Icons.Default.SearchOff, + contentDescription = "Not result search", + tint = MaterialTheme.colorScheme.error + ) + } ) } } - + itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item -> + val isFavorite = favoritePaths.contains(item) + val onPlaylist = item.path in lastPlaylistPaths + val dismissState = rememberSwipeToDismissBoxState( + confirmValueChange = { dismissValue -> + if (dismissValue == SwipeToDismissBoxValue.StartToEnd || dismissValue == SwipeToDismissBoxValue.EndToStart) { + sharedScreenModel.toFavorite(item.path) + sharedScreenModel.updateSearchTxt("") + sharedScreenModel.reset() + solfaScreenModel.loadFromFile(item.path) + sharedScreenModel.stopMidi() + sharedScreenModel.seekTo(0f) + sharedScreenModel.setTranspositionInterval(0) + false + } else { + false + } + } + ) + SwipeToDismissBox( + state = dismissState, + backgroundContent = { + val color = if (isFavorite) Color.Gray else MaterialTheme.colorScheme.tertiary + val scale by animateFloatAsState(targetValue = if (dismissState.progress > 0.1f) 1.2f else 0.8f, label = "iconScale") + Box( + modifier = Modifier.fillMaxSize().background(color).padding(horizontal = 20.dp), + contentAlignment = if (dismissState.dismissDirection == SwipeToDismissBoxValue.StartToEnd) Alignment.CenterStart else Alignment.CenterEnd + ) { + Icon( + imageVector = if (isFavorite) Icons.Default.FavoriteBorder else Icons.Default.Favorite, + contentDescription = null, + modifier = Modifier.scale(scale), + tint = MaterialTheme.colorScheme.onSecondary + ) + } + } + ) { + ListItem( + leadingContent = { Icon(imageVector = if (item.path.startsWith("assets://")) Icons.Default.ArrowDropDownCircle else Icons.Default.Folder, contentDescription = null, modifier = Modifier.size(24.dp)) }, + headlineContent = { Text(item.title) }, + supportingContent = { Text(item.contentTitle, maxLines = 1) }, + trailingContent = { + IconButton( + onClick = { scope.launch { sharedScreenModel.addSongToPlaylist(songTitle = item.title, path = item.path) } }, + modifier = Modifier.size(35.dp) + ) { + Icon( + imageVector = Icons.AutoMirrored.Default.PlaylistAdd, + contentDescription = null, + tint = if (!onPlaylist) Color.LightGray else Color(0xFFFFD700) + ) + } + }, + modifier = Modifier.clickable { + sharedScreenModel.updateSearchTxt("") + sharedScreenModel.reset() + solfaScreenModel.loadFromFile(item.path) + sharedScreenModel.loadNewSong(midiFile) + } + ) + HorizontalDivider() + } + } } } } + } +} + +@Composable +private fun CustomKeyboardSection( + isSearchActive: Boolean, + isAndroid: Boolean, + isAndroidLandscape: Boolean = false, + isCustomKeyboardVisible: Boolean, + isNumericKeyboard: Boolean, + textInput: TextFieldValue, + onTextChanged: (TextFieldValue) -> Unit, + sharedScreenModel: SharedScreenModel, + solfaScreenModel: SolfaScreenModel, + isFullScreenEnabled: Boolean, + density: androidx.compose.ui.unit.Density, + onKeyboardHeightMeasured: (Dp) -> Unit, + onHideKeyboard: () -> Unit, + onToggleKeyboard: () -> Unit, + modifier: Modifier = Modifier +) { + AnimatedVisibility( + visible = isSearchActive && isAndroid && isCustomKeyboardVisible && isNumericKeyboard, + enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(), + exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut(), + modifier = modifier + ) { + CustomKeyboard( + modifier = Modifier + .fillMaxWidth() + .fillMaxHeight(if (isAndroidLandscape) 0.6f else 0.38f) + .onGloballyPositioned { coordinates -> + onKeyboardHeightMeasured(with(density) { coordinates.size.height.toDp() }) + }, + isAndroidLandscape = isAndroidLandscape, + onDigitClick = { digit -> + val newText = textInput.text + digit + onTextChanged(TextFieldValue(newText, TextRange(newText.length))) + sharedScreenModel.updateSearchTxt(newText) + }, + onDeleteClick = { + if (textInput.text.isNotEmpty()) { + val newText = textInput.text.dropLast(1) + onTextChanged(TextFieldValue(newText, TextRange(newText.length))) + sharedScreenModel.updateSearchTxt(newText) + } + }, + onClearClick = onHideKeyboard, + onToggleKeyboardClick = onToggleKeyboard, + onPrefixClick = { prefix -> + val digits = textInput.text.trim() + val cleanPrefix = prefix.trim().lowercase() + if (digits.isNotEmpty() && digits.all { it.isDigit() }) { + val candidateSuffixes = listOf("", "-1", "-2") + val matchingItem = candidateSuffixes.firstNotNullOfOrNull { suffix -> + val targetFileName = "$cleanPrefix-$digits$suffix.txt" + sharedScreenModel.drawerItems.value.find { item -> item.path.endsWith(targetFileName, ignoreCase = true) } + } + if (matchingItem != null) { + onTextChanged(TextFieldValue("", TextRange.Zero)) + sharedScreenModel.updateSearchTxt("") + sharedScreenModel.reset() + solfaScreenModel.loadFromFile(matchingItem.path) + } else { + onTextChanged(TextFieldValue(prefix, TextRange(prefix.length))) + sharedScreenModel.updateSearchTxt(prefix) + } + } else { + onTextChanged(TextFieldValue(prefix, TextRange(prefix.length))) + sharedScreenModel.updateSearchTxt(prefix) + } + }, + isFullScreen = isFullScreenEnabled + ) + } +} + +@Composable +private fun SolfaKeyboardSection( + solfaKeyboardState: SolfaKeyboardState, + isAndroid: Boolean, + isAndroidLandscape: Boolean, + isEditMode: Boolean +) { + val density = LocalDensity.current + + BoxWithConstraints( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.TopStart + ) { + val screenWidth = maxWidth + val screenHeight = maxHeight + + AnimatedVisibility( + visible = solfaKeyboardState.isVisible && solfaKeyboardState.isDialogActive && isAndroid && isEditMode, + enter = fadeIn() + scaleIn(initialScale = 0.92f), + exit = fadeOut() + scaleOut(targetScale = 0.92f), + modifier = if (isAndroidLandscape) { + val keyboardWidth = 360.dp + val keyboardHeight = screenHeight * 0.35f + + val currentOffset = solfaKeyboardState.customOffset ?: run { + val dialogX = solfaKeyboardState.dialogPosition.x.toFloat() + val dialogY = solfaKeyboardState.dialogPosition.y.toFloat() + + with(density) { + val dialogXDp = dialogX.toDp() + val dialogYDp = dialogY.toDp() + + val spaceOnRight = screenWidth - dialogXDp - 150.dp + val targetX = if (spaceOnRight >= keyboardWidth) { + dialogXDp + 140.dp + } else { + (dialogXDp - keyboardWidth - 10.dp).coerceAtLeast(10.dp) + } + + val spaceBelow = screenHeight - dialogYDp - 50.dp + val targetY = if (spaceBelow >= keyboardHeight) { + dialogYDp.coerceAtMost(screenHeight - keyboardHeight - 10.dp) + } else { + (screenHeight - keyboardHeight - 10.dp).coerceAtLeast(10.dp) + } + androidx.compose.ui.unit.DpOffset(targetX, targetY) + } + } + + Modifier + .padding(start = currentOffset.x, top = currentOffset.y) + .width(keyboardWidth) + .height(keyboardHeight) + } else { + Modifier + .fillMaxWidth() + .fillMaxHeight(0.3f) + .align(Alignment.BottomCenter) + } + ) { + SolfaKeyboard( + isAndroidLandscape = isAndroidLandscape, + currentVoiceIndex = solfaKeyboardState.activeVoiceIndex, + currentValue = solfaKeyboardState.currentText, + onNoteClick = { note -> solfaKeyboardState.onNoteInput?.invoke(note) }, + onTabClick = { solfaKeyboardState.onTabNextVoice?.invoke() }, + onBackspaceClick = { solfaKeyboardState.onBackspace?.invoke() }, + onCloseClick = { solfaKeyboardState.onCloseDialog?.invoke() }, + onBuildClick = { solfaKeyboardState.onBuildEdit?.invoke() }, + onCustomSymbolClick = { symbol -> solfaKeyboardState.onCustomSymbol?.invoke(symbol) }, + modifier = Modifier + .fillMaxWidth() + .fillMaxHeight() + .pointerInput(Unit) { + detectDragGestures { change, dragAmount -> + change.consume() + with(density) { + val current = solfaKeyboardState.customOffset ?: androidx.compose.ui.unit.DpOffset(0.dp, 0.dp) + val newX = (current.x + dragAmount.x.toDp()).coerceIn(0.dp, screenWidth - 100.dp) + val newY = (current.y + dragAmount.y.toDp()).coerceIn(0.dp, screenHeight - 50.dp) + solfaKeyboardState.updateCustomOffset(androidx.compose.ui.unit.DpOffset(newX, newY)) + } + } + } + ) } - }) + } +} + +@Composable +private fun HoverSearchButton( + isEditMode: Boolean, + isQrVisible: Boolean, + createMode: Boolean, + isExpanded: Boolean, + isSearchActive: Boolean, + textInput: TextFieldValue, + sharedScreenModel: SharedScreenModel, + focusRequester: FocusRequester, + scope: kotlinx.coroutines.CoroutineScope, + onSearchOpened: () -> Unit = {}, + modifier: Modifier = Modifier +) { + var isHovered by remember { mutableStateOf(false) } + val offsetX by animateDpAsState(targetValue = if (isHovered || isSearchActive) 0.dp else 15.dp) + + AnimatedVisibility( + visible = !isEditMode && !isQrVisible && !createMode && !isExpanded, + modifier = modifier + .padding(top = 15.dp) + .offset(x = offsetX) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + when (event.type) { + PointerEventType.Enter -> isHovered = true + PointerEventType.Exit -> isHovered = false + } + } + } + } + ) { + IconButton( + onClick = { + if (isSearchActive) { + sharedScreenModel.showSearchMenu(false) + sharedScreenModel.updateSearchTxt("") + } else { + sharedScreenModel.showSearchMenu(true) + onSearchOpened() + scope.launch { + delay(100) + focusRequester.requestFocus() + } + } + }, + modifier = Modifier + .size(55.dp) + .alpha(0.6f) + .background(color = MaterialTheme.colorScheme.tertiary, shape = CircleShape) + ) { + Icon( + imageVector = if (isSearchActive) Icons.Default.Close else Icons.Default.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.onTertiary + + ) + } + } } private fun getIntervalToC(key: String): Int { val cleanKey = key.removeSuffix("m").trim().uppercase() diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SolfaKeyboard.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SolfaKeyboard.kt index e814d97..f9c99e9 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SolfaKeyboard.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SolfaKeyboard.kt @@ -18,8 +18,10 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import mg.dot.feufaro.provideSettings import mg.dot.feufaro.solfa.Transpose enum class OctaveMode { @@ -29,6 +31,7 @@ val SOLFA_NOTES = Transpose.noteToNumber @Composable fun SolfaKeyboard( + isAndroidLandscape: Boolean, currentVoiceIndex: Int, currentValue: String = "", onNoteClick: (String) -> Unit, @@ -39,7 +42,7 @@ fun SolfaKeyboard( onCustomSymbolClick: (String) -> Unit, modifier: Modifier = Modifier ) { - var selectedOctave by remember { mutableStateOf("") } + val selectedOctave by remember { mutableStateOf("") } val voiceLabels = listOf("S", "A", "T", "B") Surface( @@ -49,6 +52,7 @@ fun SolfaKeyboard( color = Color(0xFF232323), tonalElevation = 8.dp ) { + val firstLineKeyboardheight = if(isAndroidLandscape) 25.dp else 36.dp Row( modifier = Modifier .padding(6.dp) @@ -69,7 +73,7 @@ fun SolfaKeyboard( colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary), shape = RoundedCornerShape(4.dp), contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), - modifier = Modifier.height(36.dp) + modifier = Modifier.height(firstLineKeyboardheight) ) { Icon( imageVector = Icons.AutoMirrored.Default.KeyboardTab, @@ -95,30 +99,22 @@ fun SolfaKeyboard( ), modifier = Modifier .weight(1.5f) - .height(36.dp) + .height(firstLineKeyboardheight) .background(Color.Black.copy(alpha = 0.4f), RoundedCornerShape(4.dp)) .padding(horizontal = 8.dp, vertical = 8.dp) ) OutlinedButton( - onClick = { - onNoteClick(",") - }, - colors = ButtonDefaults.buttonColors( - containerColor = Color(0xFF383838) - ), - modifier = Modifier.height(36.dp).weight(0.7f) + onClick = { onNoteClick(",") }, + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF383838)), + modifier = Modifier.height(firstLineKeyboardheight).weight(0.7f) ) { Text(",", fontSize = 14.sp, fontWeight = FontWeight.Bold) } OutlinedButton( - onClick = { - onNoteClick("'") - }, - colors = ButtonDefaults.buttonColors( - containerColor = Color(0xFF383838) - ), - modifier = Modifier.height(36.dp) + onClick = { onNoteClick("'") }, + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF383838)), + modifier = Modifier.height(firstLineKeyboardheight) ) { Text("'", fontSize = 14.sp, fontWeight = FontWeight.Bold) } @@ -129,12 +125,12 @@ fun SolfaKeyboard( horizontalArrangement = Arrangement.spacedBy(4.dp) ) { Spacer(modifier = Modifier.weight(0.5f)) - KeyButton("di", Modifier.weight(1f)) { onNoteClick("di") } - KeyButton("ri", Modifier.weight(1f)) { onNoteClick("ri") } + KeyButton("di", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("di") } + KeyButton("ri", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("ri") } Spacer(modifier = Modifier.weight(1.3f)) - KeyButton("fi", Modifier.weight(1f)) { onNoteClick("fi") } - KeyButton("si", Modifier.weight(1f)) { onNoteClick("si") } - KeyButton("ta", Modifier.weight(1f)) { onNoteClick("ta") } + KeyButton("fi", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("fi") } + KeyButton("si", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("si") } + KeyButton("ta", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("ta") } Spacer(modifier = Modifier.weight(0.5f)) } @@ -144,7 +140,7 @@ fun SolfaKeyboard( ) { val diatonicNotes = listOf("d", "r", "m", "f", "s", "l", "t") for (note in diatonicNotes) { - KeyButton(note, Modifier.weight(1f)) { onNoteClick(note) } + KeyButton(note, Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick(note) } } } @@ -152,70 +148,51 @@ fun SolfaKeyboard( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp) ) { - KeyButton("―", Modifier.weight(1f)) { onCustomSymbolClick("-") } - KeyButton("• ,", Modifier.weight(1f)) { onCustomSymbolClick(";") } - KeyButton("•", Modifier.weight(0.5f)) { onCustomSymbolClick(".") } - KeyButton(",", Modifier.weight(0.5f)) { onCustomSymbolClick(" ,") } - KeyButton("Espace", Modifier.weight(1.6f)) { onCustomSymbolClick(" ") } - KeyButton("(", Modifier.weight(0.6f)) { onCustomSymbolClick("(") } - KeyButton(")", Modifier.weight(0.6f)) { onCustomSymbolClick(")") } - KeyButton("<", Modifier.weight(0.5f)) { onCustomSymbolClick("<") } - KeyButton(">", Modifier.weight(0.5f)) { onCustomSymbolClick(">") } - KeyButton("z", Modifier.weight(1f)) { onNoteClick("z") } + KeyButton("―", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick("-") } + KeyButton("• ,", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(";") } + KeyButton("•", Modifier.weight(0.5f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(".") } + KeyButton(",", Modifier.weight(0.5f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(" ,") } + KeyButton("Espace", Modifier.weight(1.6f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(" ") } + KeyButton("(", Modifier.weight(0.6f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick("(") } + KeyButton(")", Modifier.weight(0.6f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(")") } + KeyButton("<", Modifier.weight(0.5f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick("<") } + KeyButton(">", Modifier.weight(0.5f), isAndroidLandscape = isAndroidLandscape) { onCustomSymbolClick(">") } + KeyButton("z", Modifier.weight(1f), isAndroidLandscape = isAndroidLandscape) { onNoteClick("z") } } } Column( - modifier = Modifier - .width(48.dp), + modifier = Modifier.width(48.dp), verticalArrangement = Arrangement.spacedBy(4.dp) ) { Button( onClick = onCloseClick, - modifier = Modifier - .fillMaxWidth() - .weight(1f), + modifier = Modifier.fillMaxWidth().weight(1f), shape = RoundedCornerShape(4.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.errorContainer), contentPadding = PaddingValues(0.dp) ) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = "Solfakey close", - tint = MaterialTheme.colorScheme.onErrorContainer - ) + Icon(imageVector = Icons.Default.Close, contentDescription = "Solfakey close", tint = MaterialTheme.colorScheme.onErrorContainer) } Button( onClick = onBackspaceClick, - modifier = Modifier - .fillMaxWidth() - .weight(1f), + modifier = Modifier.fillMaxWidth().weight(1f), shape = RoundedCornerShape(4.dp), colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4A4A4A)), contentPadding = PaddingValues(0.dp) ) { - Icon( - imageVector = Icons.AutoMirrored.Default.KeyboardBackspace, - contentDescription = "Solfakey backspace", - tint = Color.White - ) + Icon(imageVector = Icons.AutoMirrored.Default.KeyboardBackspace, contentDescription = "Solfakey backspace", tint = Color.White) } Button( onClick = onBuildClick, - modifier = Modifier - .fillMaxWidth() - .weight(1.2f), + modifier = Modifier.fillMaxWidth().weight(1.2f), shape = RoundedCornerShape(4.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary), contentPadding = PaddingValues(0.dp) ) { - Icon( - imageVector = Icons.Default.Save, - contentDescription = "Solfakey save", - tint = Color.White - ) + Icon(imageVector = Icons.Default.Save, contentDescription = "Solfakey save", tint = Color.White) } } } @@ -227,11 +204,13 @@ private fun KeyButton( text: String, modifier: Modifier = Modifier, containerColor: Color = Color(0xFF383838), + isAndroidLandscape: Boolean, onClick: () -> Unit ) { + val keyboardHeight = if(isAndroidLandscape) 30.dp else 49.dp Button( onClick = onClick, - modifier = modifier.height(49.dp), + modifier = modifier.height(keyboardHeight), shape = RoundedCornerShape(4.dp), colors = ButtonDefaults.buttonColors(containerColor = containerColor), contentPadding = PaddingValues(0.dp) @@ -239,7 +218,7 @@ private fun KeyButton( Text( text = text, color = Color.White, - fontSize = 14.sp, + fontSize = MaterialTheme.typography.labelMedium.fontSize, fontWeight = FontWeight.Bold ) } @@ -261,6 +240,24 @@ class SolfaKeyboardState { var onCustomSymbol: ((String) -> Unit)? = null var onTabNextVoice: (() -> Unit)? = null var onMarker: (() -> Unit)? = null + var dialogPosition by mutableStateOf(IntOffset.Max) + + var customOffset by mutableStateOf(null) + private val prefs = provideSettings() + + init { + val savedX = prefs.getFloat("solfa_keyboard_x", -1f) + val savedY = prefs.getFloat("solfa_keyboard_y", -1f) + if (savedX != -1f && savedY != -1f) { + customOffset = androidx.compose.ui.unit.DpOffset(savedX.dp, savedY.dp) + } + } + + fun updateCustomOffset(newOffset: androidx.compose.ui.unit.DpOffset) { + customOffset = newOffset + prefs.putFloat("solfa_keyboard_x", newOffset.x.value) + prefs.putFloat("solfa_keyboard_y", newOffset.y.value) + } fun show( initialVoice: Int = 0,