diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt index 151911b..867621b 100644 --- a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/MainActivity.kt @@ -44,11 +44,11 @@ class MainActivity : ComponentActivity() { else -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } - ActivityCompat.requestPermissions( + /*ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1 - ) + )*/ enableEdgeToEdge() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { window.attributes.layoutInDisplayCutoutMode = @@ -82,11 +82,13 @@ class MainActivity : ComponentActivity() { AppContext.instance = applicationContext - ActivityCompat.requestPermissions( - this, - arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), - 1 - ) + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { + ActivityCompat.requestPermissions( + this, + arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), + 1 + ) + } setContent { KoinAndroidContext { @@ -130,12 +132,12 @@ class MainActivity : ComponentActivity() { windowInsetsController.isAppearanceLightNavigationBars = !isNightMode } } - @Suppress("OVERRIDE_DEPRECATION") + /*@Suppress("OVERRIDE_DEPRECATION") override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) handleDeepLinkIntent(intent) - } + }*/ override fun onNewIntent(intent: Intent, caller: ComponentCaller) { super.onNewIntent(intent, caller) setIntent(intent) diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/pdf/PdfExport.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/pdf/PdfExport.kt index 383fb02..bb93bf6 100644 --- a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/pdf/PdfExport.kt +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/pdf/PdfExport.kt @@ -95,7 +95,7 @@ private fun bestColWidthPt( .split("\n") .forEach { line -> val trimmedLine = cleanSyllable(line) - val x = measureNoteWidth(font, lyricFontSize, trimmedLine) + val x = measureNoteWidth(lyricFont, lyricFontSize, trimmedLine) if (x > maxLyrW) { maxLyrW = x } diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DrawerItem.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DrawerItem.kt index 132a948..2add60e 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DrawerItem.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DrawerItem.kt @@ -10,6 +10,10 @@ import java.io.File fun String.normalizeForSearch(): String { return this.lowercase().filter { it.isLetterOrDigit() } } + +private val TITLE_COMPONENTS_REGEX = Regex("""^([a-zA-Z]+)[-_\s]*(\d+)(?:[-_\s]*(\d+))?""") +private val DIGIT_BLOCKS_REGEX = Regex("\\d+") + data class DrawerItem( val id: Int, val title: String, @@ -26,24 +30,32 @@ data class DrawerItem( private fun parseComponents(str: String): TitleComponents? { // préfixe (lettres), numéro (chiffres), version optionnelle - val regex = Regex("""^([a-zA-Z]+)[-_\s]*(\d+)(?:[-_\s]*(\d+))?""") - val match = regex.find(str.trim()) ?: return null + val match = TITLE_COMPONENTS_REGEX.find(str.trim()) ?: return null val prefix = match.groupValues[1].lowercase() val number = match.groupValues[2] val version = match.groupValues[3].ifEmpty { null } return TitleComponents(prefix, number, version) } + + private val cleanTitle: String by lazy { title.normalizeForSearch() } + private val cleanContent: String by lazy { contentTitle.normalizeForSearch() } + private val titleComponents: TitleComponents? by lazy { parseComponents(title) } + private val titleDigitBlocks: List by lazy { + DIGIT_BLOCKS_REGEX.findAll(title).map { it.value }.toList() + } + fun matchesQuery(query: String): Boolean { if (query.isBlank()) return true val cleanQuery = query.normalizeForSearch() - val cleanTitle = title.normalizeForSearch() - val cleanContent = contentTitle.normalizeForSearch() + if ((cleanTitle + cleanContent).contains(cleanQuery) || (cleanContent + cleanTitle).contains(cleanQuery)) { return true } val queryComponents = parseComponents(query) + val cleanTitle = title.normalizeForSearch() + val cleanContent = contentTitle.normalizeForSearch() val titleComponents = parseComponents(title) if (queryComponents != null && titleComponents != null) { if (queryComponents.prefix == titleComponents.prefix) { @@ -69,11 +81,12 @@ data class DrawerItem( if (query.isBlank()) return 0 val cleanQuery = query.normalizeForSearch() + val queryComponents = parseComponents(query) + val cleanTitle = title.normalizeForSearch() val cleanContent = contentTitle.normalizeForSearch() - - val queryComponents = parseComponents(query) val titleComponents = parseComponents(title) + val titleDigitBlocks = Regex("\\d+").findAll(title).map { it.value }.toList() if (queryComponents != null && titleComponents != null) { val samePrefix = queryComponents.prefix == titleComponents.prefix @@ -99,7 +112,6 @@ data class DrawerItem( if (cleanTitle == cleanQuery) return 1000 - val titleDigitBlocks = Regex("\\d+").findAll(title).map { it.value }.toList() val queryDigits = query.filter { it.isDigit() } val queryLetters = query.filter { it.isLetter() }.lowercase() diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt index 730b904..0aed48a 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt @@ -39,6 +39,9 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository private val pitches = mutableListOf() private val globalDComments = mutableListOf() + private var currentJob: Job? = null + private val solfaScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + companion object { var currentFile = "" val REGEX_SHIFT_PAREN_UPWARD = Regex("([^a-yA-Y\\(\\[]+)([\\)\\]])") @@ -69,6 +72,24 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository val REGEX_OVERRIDE_TOKEN = Regex("""\$\{O:\d+\}""") val REGEX_VOICE_MARKER = Regex("\\$\\{v:([^\\}]+)\\}") val KEEP_MARKERS = listOf("\${L}", "\$T") + val REGEX_TARGET_CHAR = Regex("\\$\\{.*?\\}|\\$.") + val REGEX_SPLIT_BRACE = Regex("<\\s*\\{[^\\}]*\\}") + val REGEX_ANCHOR_NOTE = Regex("#[drmfsltDRFSTz][',]*") + val REGEX_NOTA_NOTE = Regex("[^drmfsltDRFSTzw]") + val REGEX_NOTE_W_OCT = Regex("([drmfsltDRFSTzw])([,']*)(\\d+)") + const val DELIM = "/:!|" + val REGEX_INSERT_Z = Regex("[$DELIM](?=[$DELIM])") + val REGEX_ANCHOR_SUFFIX = Regex("^[drmfslt]") + val REGEX_BRACES_CONTENT = Regex("\\{([^\\}]+)\\}") + val REGEX_NOTE_OCTAVE = Regex("([drmfsltDRFSTz])([,']*)") + val REGEX_OVERRIDE = Regex("\\$\\{O:(\\d+)\\}") + val REGEX_VOICE_OVERRIDE = Regex("v(\\d+):(.*)") + val REGEX_ADD_HYPHENS1 = Regex("(? - run { - parseOneLine(line) - } + parseOneLine(line) } unparsedNote.forEach { preloadN(it) @@ -330,8 +349,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository private val prefs: Settings = provideSettings() fun generateMidiFile(bpm: Float, outputPath: String = "whawyd3.mid", transpI: Int = 0) { - val parseScope = CoroutineScope(Dispatchers.Default) - parseScope.launch { + currentJob?.cancel() + currentJob = solfaScope.launch { val nbStanzas = sharedScreenModel.nbStanzas.value.takeIf { it > 0 } ?: 1 val currentTuoList = sharedScreenModel.tuoList.value val basePitches = pitches.filter { it.metaType != 0x05 }.map { it.copy() } @@ -440,15 +459,15 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository fun justBuild(sourceFile: String, sourceContent: String) { currentFile = sourceFile - val parseScope = CoroutineScope(Dispatchers.Default) - parseScope.launch { + currentJob?.cancel() + currentJob = solfaScope.launch { val lines = try { fileRepository.readFileLines(sourceFile) } catch (e: Exception) { println("Opening $sourceFile raised exception {${e.message}") emptyList() } - val contentString = fileRepository.readFileLines(sourceFile).joinToString("\n") + val contentString = lines.joinToString("\n") sharedScreenModel.setFileContent(contentString, sourceFile) O.clear() T.clear() @@ -470,9 +489,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository lyricsComment.clear() TimeUnitObject.hasMarker(false) lines.forEach { line -> - run { - parseOneLine(line) - } + parseOneLine(line) } unparsedNote.forEach { preloadN(it) @@ -702,7 +719,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository return "// Erreur lecture: $filePath" } - val inclusionRegex = Regex("""I\d+:[^ \n\r]+""") + val inclusionRegex = try { + Regex("""I\d+:[^ \n\r]+""") + } catch (e: Exception) { + return "// Erreur regex inclusion: ${e.message}" + } myLines.forEach { line -> var lastIndex = 0 @@ -718,7 +739,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository val parts = fullTag.split(":", limit = 3) if (parts.size >= 2) { - val fileName = parts[1] + val fileName = parts[1].trim() + if (fileName.isEmpty() || fileName.contains("..")) { + lineBuilder.append("// Chemin d'inclusion interdit: $fileName") + } else { val fullPath = directory + fileName val rawIncludedContent = fileRepository.readFileLines(fullPath) @@ -738,6 +762,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository lineBuilder.append(filteredLines.joinToString("\n")) } else { lineBuilder.append(rawIncludedContent.joinToString("\n")) + } } } } catch (e: Exception) { @@ -1473,7 +1498,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository } private fun parseNoteAndOctave(s: String): Pair { - val base = s.replace(Regex("[^drmfsltDRFSTzw]"), "") + val base = s.replace(REGEX_NOTA_NOTE, "") var level = 0 level += s.count { it == '\'' || it == '¹' || it == '²' || it == '³' } @@ -1691,11 +1716,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository val consumedBlocks = mutableSetOf() fun getDurationAt(targetStr: String, targetCharIdx: Int, blockIdx: Int): Int { - val cleanStr = targetStr.replace(Regex("\\$\\{.*?\\}|\\$."), "") + val cleanStr = targetStr.replace(REGEX_TARGET_CHAR, "") val charAtIdx = targetStr[targetCharIdx] if (blockIdx > 0) { - val prevBlock = buff[blockIdx - 1].replace(Regex("\\$\\{.*?\\}|\\$."), "") + val prevBlock = buff[blockIdx - 1].replace(REGEX_TARGET_CHAR, "") val isFirstActiveChar = targetCharIdx == 0 || targetStr.substring(0, targetCharIdx).all { "., !:|(){}$".contains(it) || consumedGlobally.contains(blockIdx to targetStr.indexOf(it)) } @@ -1716,7 +1741,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository if (charAtIdx == 'D' || charAtIdx == 'z') { val textAfter = targetStr.substring(targetCharIdx + 1) - val cleanAfter = textAfter.replace(Regex("\\$\\{.*?\\}|\\$."), "") + val cleanAfter = textAfter.replace(REGEX_TARGET_CHAR, "") if (cleanAfter.startsWith(".") && !cleanAfter.substring(1).any { it == 'D' || it == 'z' || it == '-' }) { return 4 } @@ -1725,7 +1750,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository if (!cleanStr.contains(".") && !cleanStr.contains(",")) return 4 val pByPoint = cleanStr.split(".") - val prefixBefore = targetStr.substring(0, targetCharIdx).replace(Regex("\\$\\{.*?\\}|\\$."), "") + val prefixBefore = targetStr.substring(0, targetCharIdx).replace(REGEX_TARGET_CHAR, "") val cleanIdx = prefixBefore.length var curPos = 0 @@ -1760,8 +1785,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository // println("Pour $k = $currentStr") if (k > 0) { - val prevBlock = buff[k - 1].replace(Regex("\\$\\{.*?\\}|\\$."), "") - val cleanCurrent = currentStr.replace(Regex("\\$\\{.*?\\}|\\$."), "") + val prevBlock = buff[k - 1].replace(REGEX_TARGET_CHAR, "") + val cleanCurrent = currentStr.replace(REGEX_TARGET_CHAR, "") if (prevBlock.endsWith("-./") || prevBlock.endsWith("-.)/")) { if (cleanCurrent.contains(".") && cleanCurrent.startsWith("D") && cleanCurrent.count { it == 'D' } >= 2) { @@ -1842,7 +1867,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository } else { var hasFutureResonance = false if (k + 1 < buff.size) { - if (buff[k + 1].replace(Regex("\\$\\{.*?\\}|\\$."), "") + if (buff[k + 1].replace(REGEX_TARGET_CHAR, "") .startsWith("-") ) hasFutureResonance = true } @@ -1871,7 +1896,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository while (lookingForSilence && nextBlockIdx < buff.size) { val nextBlockRaw = buff[nextBlockIdx] - val nextBlockClean = nextBlockRaw.replace(Regex("\\$\\{.*?\\}|\\$."), "").trim() + val nextBlockClean = nextBlockRaw.replace(REGEX_TARGET_CHAR, "").trim() if (nextBlockClean.isNotEmpty() && nextBlockClean.all { it == 'z' || "., !:|()/{}".contains( @@ -1959,8 +1984,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository } private fun expandNotes(text: String): String { - val regex = Regex("([drmfsltDRFSTzw])([,']*)(\\d+)") - return regex.replace(text) { matchResult -> + return REGEX_NOTE_W_OCT.replace(text) { matchResult -> val note = matchResult.groupValues[1] val octaves = matchResult.groupValues[2] val count = matchResult.groupValues[3].toInt() @@ -2000,8 +2024,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository fun countNotesInSegment(segment: String): Int { val withoutComments = segment .replace(REGEX_TEMPLATE_COMMENT, "") - .replace(Regex("#[drmfsltDRFSTz][',]*"), "") - .replace(Regex("<\\s*\\{[^\\}]*\\}"), "") + .replace(REGEX_ANCHOR_NOTE, "") + .replace(REGEX_SPLIT_BRACE, "") .replace(" ", "") val expanded = REGEX_REPETITION.replace(withoutComments) { m -> m.groupValues[1].repeat(m.groupValues[2].toInt()) @@ -2034,14 +2058,12 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository val splitBlocks = mutableListOf() val noteLineWithoutSplits = parsedNoteLine .replace(REGEX_TEMPLATE_COMMENT, "") - .replace(Regex("<\\s*\\{[^\\}]*\\}")) { matchResult -> + .replace(REGEX_SPLIT_BRACE) { matchResult -> splitBlocks.add(matchResult.value) "§" } fun insertZToCharArray(input: String): CharArray { - val delim = "/:!|" - val reDelim = "[$delim](?=[$delim])".toRegex() - val insertedZ = input.replace(reDelim) { it.value + "z"} + val insertedZ = input.replace(REGEX_INSERT_Z) { it.value + "z"} return insertedZ.toCharArray() } val templateCharArray = insertZToCharArray(templateStripped) @@ -2059,10 +2081,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository lineRepeated.toCharArray().forEach { if (it == '§') { val rawSplit = splitBlocks.removeAt(0) - val anchorSuffix = anchor.replace(Regex("^[drmfslt]"), "") - val processedSplit = rawSplit.replace(Regex("\\{([^\\}]+)\\}")) { match -> + val anchorSuffix = anchor.replace(REGEX_ANCHOR_SUFFIX, "") + val processedSplit = rawSplit.replace(REGEX_BRACES_CONTENT) { match -> val innerContent = match.groupValues[1] - val updatedInner = innerContent.replace(Regex("([drmfsltDRFSTz])([,']*)")) { noteMatch -> + val updatedInner = innerContent.replace(REGEX_NOTE_OCTAVE) { noteMatch -> val n = noteMatch.groupValues[1] val oct = noteMatch.groupValues[2] var res = n @@ -2238,38 +2260,45 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository suspend fun loadI(line: String, regexIgnoreString: String = "") { val lineSplit = line.split(":") + val fileName = lineSplit.firstOrNull().orEmpty().trim() + if (fileName.isEmpty() || fileName.contains("..")) { + println("Chemin d'inclusion invalide ou interdit : $fileName") + return + } val lastSlashInFilename = currentFile.lastIndexOf('/') val fileNamePrefix = if (lastSlashInFilename != -1) { currentFile.substring(0, lastSlashInFilename + 1) } else { "" } - val regexIgnoreString = try { - if (regexIgnoreString != "") { - regexIgnoreString + "|" + lineSplit[1] - } else { + val combinedIgnore = try { + if (regexIgnoreString.isNotEmpty() && lineSplit.size > 1 && lineSplit[1].isNotEmpty()) { + "$regexIgnoreString|${lineSplit[1]}" + } else if (lineSplit.size > 1 && lineSplit[1].isNotEmpty()) { lineSplit[1] + } else { + regexIgnoreString.ifEmpty { "^:" } } } catch (e: Exception) { "^:" } - val filePath = fileNamePrefix + lineSplit[0] + val ignoredLines = try { + Regex(combinedIgnore) + } catch (e: Exception) { + println("Regex invalide dans loadI ($combinedIgnore) : ${e.message}") + Regex("^:") + } + val filePath = fileNamePrefix + fileName val lines = try { fileRepository.readFileLines(filePath) } catch (e: Exception) { println("Opening $filePath raised exception {${e.message}") emptyList() } - try { - val ignoredLines = Regex(regexIgnoreString) - lines.forEach { - val match = ignoredLines.find(it) - if (match == null) { - parseOneLine(it, regexIgnoreString) - } + lines.forEach { itemLine -> + if (ignoredLines.find(itemLine) == null) { + parseOneLine(itemLine, combinedIgnore) } - } catch (e: Exception) { - } } @@ -2692,8 +2721,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository val parsedULine = uObject.parsed() loadT(parsedULine) - val regex = Regex("""z([^:]):""") - val match = regex.find(line) + val match = REGEX_SILENT_DUR.find(line) val silentDuration = match?.groupValues?.get(1) ?: "0" sharedScreenModel.setMeasureInt(measure) @@ -2728,10 +2756,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository meta[subKey] = line.substring(2) } if ("c" == subKey) { - val validKeys = Transpose.keyToNumber.sortedByDescending { it.length } - val keyRegex = Regex("\\b(${validKeys.joinToString("|")})(m)?\\b", RegexOption.IGNORE_CASE) val rawText = line.substringAfter("c:") - val matchResult = keyRegex.find(rawText) + val matchResult = REGEX_KEY.find(rawText) if (matchResult != null) { val rawBaseKey = matchResult.groupValues[1] @@ -2756,11 +2782,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository private fun String.addHyphens(): String { return this - .replace(Regex("(? val overrideNumber = matchResult.groupValues[1].toInt() val override = O.getOrElse(overrideNumber) { null } override?.forEachIndexed { index, value -> - val matchResult = Regex("v(\\d+):(.*)").find(value) + val matchResult = REGEX_VOICE_OVERRIDE.find(value) // 1. Extraire le numéro de voix (ex: "2") val voiceNum = matchResult?.groupValues?.get(1) ?: "" val prefix = if (voiceNum.isNotEmpty()) { diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt index af09ec8..1359e2b 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt @@ -55,6 +55,7 @@ import feufaro.composeapp.generated.resources.Res import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.yield import mg.dot.feufaro.ContextualMenu import mg.dot.feufaro.DisplayConfigManager import mg.dot.feufaro.FileRepository @@ -238,7 +239,7 @@ class TimeUnitObject (val pTemplate: PTemplate, val prevTUO: TimeUnitObject?, co return "$separatorBefore\n$separatorBefore\n$separatorBefore\n$separatorBefore" } val retour = tuNotes.drop(1).joinToString (separator = "\n"){ - separatorBefore + markersBefore + it.toString(transposeFrom, transposeTo).replace(Regex("[\\(\\)\\[\\]]"), "") + separatorBefore + markersBefore + it.toString(transposeFrom, transposeTo).replace(BRACKETS_REGEX, "") } return retour } @@ -288,43 +289,33 @@ class TimeUnitObject (val pTemplate: PTemplate, val prevTUO: TimeUnitObject?, co return finalLines } + private var cachedCumulativeMod: Int? = null + fun getCumulativeModulationInterval(): Int { + cachedCumulativeMod?.let { return it } val notes = noteAsMultiString() - val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)") - val tokens = notes.split(Regex("(?<=[:|•\\s])|(?=[:|•\\s])")) var modDelta = 0 - - for (token in tokens) { - val trimmed = token.trim() - val modMatch = MODULATION_REGEX.matchEntire(trimmed) - if (modMatch != null) { - val oldNoteCore = modMatch.groupValues[1] - val oldOctaveStr = modMatch.groupValues[2] - val newNoteCore = modMatch.groupValues[3] - val newOctaveStr = modMatch.groupValues[4] - - val oldIdx = Transpose.noteToNumber.indexOf(oldNoteCore) - val newIdx = Transpose.noteToNumber.indexOf(newNoteCore) - - if (oldIdx != -1 && newIdx != -1) { - val oldOctaveVal = Transpose.octaveToInt(oldOctaveStr) - val newOctaveVal = Transpose.octaveToInt(newOctaveStr) - - val oldTotalSemitones = oldIdx + (oldOctaveVal * 12) - val newTotalSemitones = newIdx + (newOctaveVal * 12) - - modDelta = oldTotalSemitones - newTotalSemitones - break - } + for (token in notes.split(MOD_TOKEN_SPLIT_REGEX)) { + val modMatch = MODULATION_REGEX.matchEntire(token.trim()) ?: continue + val oldIdx = Transpose.noteToNumber.indexOf(modMatch.groupValues[1]) + val newIdx = Transpose.noteToNumber.indexOf(modMatch.groupValues[3]) + if (oldIdx != -1 && newIdx != -1) { + val oldTotal = oldIdx + Transpose.octaveToInt(modMatch.groupValues[2]) * 12 + val newTotal = newIdx + Transpose.octaveToInt(modMatch.groupValues[4]) * 12 + modDelta = oldTotal - newTotal + break } } - - val prevDelta = prevTUO?.getCumulativeModulationInterval() ?: 0 - return prevDelta + modDelta + val result = (prevTUO?.getCumulativeModulationInterval() ?: 0) + modDelta + cachedCumulativeMod = result + return result } } private val REGEX_CLEAN_PREFIX = Regex("(\\d+\\.)+") +private val BRACKETS_REGEX = Regex("[\\(\\)\\[\\]]") +private val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)") +private val MOD_TOKEN_SPLIT_REGEX = Regex("(?<=[:|•\\s])|(?=[:|•\\s])") private val musicForPtSerifBIRegex = Regex("""^(Largh\.|Grave|Largo|Lento|Adagio|And\.|Andantino|Mod\.|Moderato|Alleg\.|All\.|Viv\.|Vivacissimo|Presto|Prestiss\.|accel\.|rit\.|rall\.|riten\.|string\.|allarg\.|a tempo|Tempo I|rubato|meno mosso|più mosso|cres\.|<|decresc\.|dim\.|>|rfz|fp|pf|sub\.p|sub\.f)""",RegexOption.IGNORE_CASE) private val musicForEmmentRegex = Regex( """^(?:[mfp]+|sfz|sf|fz|rfz)$""", @@ -364,14 +355,11 @@ fun TimeUnitComposable( val focusRequesters = remember { List(4) { FocusRequester() } } val isLitany = tuo.isLitany() - val notes = tuo.noteAsMultiString() - val initialMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0 - // Mettre en cache les annotations et les chaînes transposées val rawText = remember(tuo, transpositionInterval) { - Transpose.transposeText( - text = notes, interval = transpositionInterval, - initialModulationInterval = initialMod - ) + val notes = tuo.noteAsMultiString() + val initialMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0 + // Mettre en cache les annotations et les chaînes transposées + Transpose.transposeText(text = notes, interval = transpositionInterval, initialModulationInterval = initialMod) } val rawLines = remember(rawText) { rawText.lines() } val multiLineText = remember(tuo, transpositionInterval, isLitany) { @@ -533,44 +521,28 @@ fun bestTUOWidth( LaunchedEffect(items, noteStyle, transpositionInterval) { isReady = false - var max = 0.dp -// println("=== [DEBUG TUO] Début mesure de ${items.size} blocs TUO ===") - - items.forEach { tuo -> + val widthCache = HashMap() + var maxPx = 0 + items.forEachIndexed { i, tuo -> val prevMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0 val rawNotes = Transpose.transposeText( text = tuo.noteAsMultiString(), interval = transpositionInterval, initialModulationInterval = prevMod ) - val transposedNotes = if (tuo.isLitany()) SolfaLabels.toLabels(rawNotes) else rawNotes - val noteLines = transposedNotes.lines() - var maxNoteWidthPx = 0 - - noteLines.forEachIndexed { lineIdx, line -> - val annotatedNote = parseNoteToAnnotatedString(line) - val noteResult = textMeasurer.measure( - text = annotatedNote, - style = noteStyle, - maxLines = 1, - softWrap = false - ) - val widthPx = noteResult.size.width - if (widthPx > maxNoteWidthPx) { - maxNoteWidthPx = widthPx + val transposed = if (tuo.isLitany()) SolfaLabels.toLabels(rawNotes) else rawNotes + transposed.lines().forEach { line -> + val w = widthCache.getOrPut(line) { + textMeasurer.measure( + text = parseNoteToAnnotatedString(line), + style = noteStyle, maxLines = 1, softWrap = false + ).size.width } -// println("TUO #${tuo.getNum()} | Ligne $lineIdx | Brut: \"$line\" | Annoté: \"${annotatedNote.text}\" -> Largeur: ${widthPx}px") - } - - val tuoMaxWidthDp = with(density) { maxNoteWidthPx.toDp() } -// println("--> TUO #${tuo.getNum()} | Largeur max du bloc: $tuoMaxWidthDp ou ${maxNoteWidthPx}px") - - if (tuoMaxWidthDp > max) { - max = tuoMaxWidthDp + if (w > maxPx) maxPx = w } + if (i % 8 == 7) yield() } - - maxWidth = max + 5.dp //marge + maxWidth = with(density) { maxPx.toDp() } + 5.dp isReady = true // println("=== [DEBUG TUO] Largeur retenue (maxWidth finale) : $maxWidth ===") } @@ -669,7 +641,7 @@ fun LazyVerticalGridTUO( val currentDisplayConfig by displayConfigManager.displayConfig.collectAsState() val tuoList = viewModel.tuoList - key(tuoList) { + /*key(tuoList)*/ /*{*/ var menuPosition by remember { mutableStateOf(Offset.Zero) } var showAddDialog by remember { mutableStateOf(false) } @@ -706,7 +678,7 @@ fun LazyVerticalGridTUO( val loopState by produceState(Triple(-1L, -1L, false), sharedScreenModel.mediaPlayer) { while (true) { value = sharedScreenModel.mediaPlayer?.getLoopState() ?: Triple(-1L, -1L, false) - kotlinx.coroutines.delay(100) + kotlinx.coroutines.delay(250) } } val prefs: Settings = provideSettings() @@ -894,7 +866,7 @@ fun LazyVerticalGridTUO( val textMeasurer = rememberTextMeasurer() val containerWidthDp = gridWidthDp / gridColumnCount - val isAnySyllableTooLong = remember(currentStanza, gridWidthDp, gridColumnCount) { + /*val isAnySyllableTooLong = remember(currentStanza, gridWidthDp, gridColumnCount) { val allMeasuresSyllables = tuoList.drop(1).chunked(gridColumnCount).map { measureTUOss -> measureTUOss.map { it.getSingleSyllable(currentStanza) }.map { column -> column.map { syllable -> syllable.replace(REGEX_CLEAN_PREFIX, "").trim() } @@ -914,7 +886,7 @@ fun LazyVerticalGridTUO( } } } - } + }*/ val litanyLabels: Map> = remember(tuoList, currentStanza) { val map = LinkedHashMap>() @@ -1112,11 +1084,16 @@ fun LazyVerticalGridTUO( if (isHovered) MaterialTheme.colorScheme.onSecondary.copy(alpha = 0.05f) else Color.Transparent, RoundedCornerShape(4.dp) ) - .combinedClickable( + .then(if (isSelectedByKeyboard && editMode) + Modifier.border(2.dp, MaterialTheme.colorScheme.error, RoundedCornerShape(4.dp)) else Modifier) + .then(if (isHovered) + Modifier.background(MaterialTheme.colorScheme.onSecondary.copy(alpha = 0.05f), RoundedCornerShape(4.dp)) else Modifier) + .hoverable(interactionSource) + /*.combinedClickable( interactionSource = interactionSource, indication = LocalIndication.current, onClick = { } - ) + )*/ .pointerInput(globalIndex) { detectTapGestures( onTap = { offset -> @@ -1296,6 +1273,23 @@ fun LazyVerticalGridTUO( syllable.replace(REGEX_CLEAN_PREFIX, "").trim() } } + val isAnySyllableTooLong = remember(cleanAllTemps, columnWidthDp, density) { + cleanAllTemps.any { column -> + column.any { syl -> + if (syl.isEmpty()) false + else { + val measuredDp = with(density) { + textMeasurer.measure( + text = syl, + maxLines = 1, + softWrap = false + ).size.width.toDp() + } + measuredDp > columnWidthDp + } + } + } + } allTemps.forEachIndexed { syls_i, syllables -> /*val fragmentU0 = measureTUOs[syls_i].pTemplate.template println("Fragment=[$fragmentU0] -> Syllabes=$syllables")*/ @@ -1372,7 +1366,7 @@ fun LazyVerticalGridTUO( } } } -} +/*}*/ } @Composable @@ -1654,44 +1648,59 @@ fun makeSpaceBetweenSyllables( fontSize: TextUnit = 16.sp ): (String, List>, Int, Int) -> Pair { val density = LocalDensity.current - val noteWidthPx = with(density) { noteWidthDp.toPx() } - val style = TextStyle(fontSize = fontSize) + val noteWidthPx = remember(density, noteWidthDp) { + with(density) { noteWidthDp.toPx() } + } + val style = remember(fontSize) { + TextStyle(fontSize = fontSize) + } val spaceWidthPx = remember(textMeasurer, style) { - textMeasurer.measure("\u00A0", style).size.width + textMeasurer.measure( + text = "\u00A0", + style = style, + maxLines = 1, + softWrap = false + ).size.width } return { currentSyl, allT, s_i, index -> - var textAlign = Alignment.Center - if (currentSyl.isEmpty()) "" to textAlign - else { - val currentWidth = textMeasurer.measure(currentSyl, style).size.width + val textAlign = Alignment.Center + if (currentSyl.isEmpty() || noteWidthPx <= 0f || spaceWidthPx <= 0) { + currentSyl to textAlign + } else { + val currentWidth = textMeasurer.measure( + text = currentSyl, + style = style, + maxLines = 1, + softWrap = false + ).size.width val next_syl = allT.getOrNull(s_i + 1)?.getOrNull(index) ?: "" val prev_syl = if (s_i > 0) allT.getOrNull(s_i - 1)?.getOrNull(index) ?: "" else "" val excessPx = currentWidth - noteWidthPx - val isExcess = (excessPx > 0) - val neededSpaces = if (isExcess && spaceWidthPx > 0) (excessPx / spaceWidthPx).toInt() + 1 else 0 + val isExcess = excessPx > 0 + val neededSpaces = if (isExcess) (excessPx / spaceWidthPx).toInt() + 1 else 0 + var resultAlign = textAlign val resultText = when { - !isExcess && (noteWidthPx > 0 && spaceWidthPx > 0) -> { + !isExcess -> { val totalSpacesPossible = (noteWidthPx / spaceWidthPx).toInt() val paddingNeeded = totalSpacesPossible - (currentSyl.length + 4) if (paddingNeeded > 0) { - textAlign = Alignment.TopStart + resultAlign = Alignment.TopStart currentSyl + "\u00A0".repeat(paddingNeeded) } else { currentSyl } } - isExcess && spaceWidthPx > 0 && next_syl.length < prev_syl.length -> { + next_syl.length < prev_syl.length -> { "\u00A0".repeat(neededSpaces) + currentSyl } - isExcess && spaceWidthPx > 0 -> { + else -> { currentSyl + "\u00A0".repeat(neededSpaces) } - else -> currentSyl } - resultText to textAlign + resultText to resultAlign } } } diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Transpose.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Transpose.kt index e0f5b1c..a32e8ed 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Transpose.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Transpose.kt @@ -21,6 +21,9 @@ import androidx.compose.ui.unit.dp class Transpose { companion object { val REGEX_ONE_NOTE = Regex("^([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)(.*)") + private val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)") + private val NOTE_UNIT_REGEX = Regex("([drmfslt][ia]?)([₄₃₂₁¹²³⁴]*)") + private val TOKEN_SPLIT_REGEX = Regex("(?<=[:|•\\s])|(?=[:|•\\s])") val octaveSigns = listOf("₄", "₃", "₂", "₁", "", "¹", "²", "³", "⁴") val noteToNumber = listOf("d", "di", "r", "ri", "m", "f", "fi", "s", "si", "l", "ta", "t") val keyToNumber = listOf("C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" ) @@ -29,14 +32,12 @@ class Transpose { if (text.isEmpty()) return text var currentModulationInterval = initialModulationInterval - val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)") - val NOTE_UNIT_REGEX = Regex("([drmfslt][ia]?)([₄₃₂₁¹²³⁴]*)") - val tokens = text.split(Regex("(?<=[:|•\\s])|(?=[:|•\\s])")) + val tokens = text.split(TOKEN_SPLIT_REGEX) val finalResult = tokens.joinToString("") { token -> val trimmed = token.trim() - if (trimmed.isEmpty() || trimmed.matches(Regex("[:|•\\s]+"))) { + if (trimmed.isEmpty() || trimmed.all { it == ':' || it == '|' || it == '•' || it.isWhitespace() }) { token } else { val modMatch = MODULATION_REGEX.matchEntire(trimmed) 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 29fff15..e04fa24 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt @@ -1522,6 +1522,8 @@ private fun LandscapeFloatingActionButtons( } } +private val NATURAL_SPLIT_REGEX = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)") + @Composable private fun SearchOverlayCard( isSearchActive: Boolean, @@ -1549,42 +1551,56 @@ private fun SearchOverlayCard( var sortedSongs by remember { mutableStateOf(emptyList()) } var isSearching by remember { mutableStateOf(true) } - LaunchedEffect(filteredSongs, textInput.text) { + val tokenizedSongs = remember(filteredSongs) { + filteredSongs.map { item -> + val tokens = NATURAL_SPLIT_REGEX.split(item.title.lowercase()) + .filter { it.isNotEmpty() } + .map { part -> part.toLongOrNull() ?: part } + item to tokens + } + } + + LaunchedEffect(tokenizedSongs, textInput.text) { isSearching = true val query = textInput.text + if (query.isNotEmpty()) { + kotlinx.coroutines.delay(60L) + } 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) + val tokenComparator = Comparator>>> { (_, tokensA), (_, tokensB) -> + var cmp = 0 + val size = minOf(tokensA.size, tokensB.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) + val aPart = tokensA[i] + val bPart = tokensB[i] + cmp = if (aPart is Long && bPart is Long) { + aPart.compareTo(bPart) } else { - chunkA.compareTo(chunkB) + aPart.toString().compareTo(bPart.toString()) } - if (result != 0) break + if (cmp != 0) break } - if (result == 0) chunksA.size.compareTo(chunksB.size) else result + if (cmp == 0) tokensA.size.compareTo(tokensB.size) else cmp } if (query.isBlank()) { - filteredSongs.sortedWith( - compareBy { item -> !item.path.startsWith("assets://") } - .thenComparing(naturalComparator) - ) + tokenizedSongs + .sortedWith( + compareBy>>> { (item, _) -> !item.path.startsWith("assets://") } + .thenComparing(tokenComparator) + ) + .map { it.first } } else { - filteredSongs.sortedWith( - compareByDescending { item -> item.getSearchScore(query) } - .thenBy { item -> !item.path.startsWith("assets://") } - .thenComparing(naturalComparator) - ) + val scores = HashMap(tokenizedSongs.size).also { m -> + tokenizedSongs.forEach { (item, _) -> m[item.path] = item.getSearchScore(query) } + } + tokenizedSongs + .sortedWith( + compareByDescending>>> { (item, _) -> scores[item.path] ?: 0 } + .thenBy { (item, _) -> !item.path.startsWith("assets://") } + .thenComparing(tokenComparator) + ) + .map { it.first } } } sortedSongs = result diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt index e33bf99..2956b09 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt @@ -665,8 +665,10 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode if (query.isBlank()) { items } else { - items.filter { item -> item.matchesQuery(query) } - .sortedByDescending { item -> item.getSearchScore(query) } + items.filter { it.matchesQuery(query) } + .map { it to it.getSearchScore(query) } + .sortedByDescending { it.second } + .map { it.first } } }.stateIn ( scope = CoroutineScope(Dispatchers.Default),