Optimize application performance and reduce slowdowns

This commit is contained in:
Hasinjato 2026-11-20 11:55:37 +03:00
parent 6b810c8142
commit 20d12924d6
8 changed files with 264 additions and 197 deletions

View file

@ -44,11 +44,11 @@ class MainActivity : ComponentActivity() {
else -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE else -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} }
ActivityCompat.requestPermissions( /*ActivityCompat.requestPermissions(
this, this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
1 1
) )*/
enableEdgeToEdge() enableEdgeToEdge()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
window.attributes.layoutInDisplayCutoutMode = window.attributes.layoutInDisplayCutoutMode =
@ -82,11 +82,13 @@ class MainActivity : ComponentActivity() {
AppContext.instance = applicationContext AppContext.instance = applicationContext
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions( ActivityCompat.requestPermissions(
this, this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
1 1
) )
}
setContent { setContent {
KoinAndroidContext { KoinAndroidContext {
@ -130,12 +132,12 @@ class MainActivity : ComponentActivity() {
windowInsetsController.isAppearanceLightNavigationBars = !isNightMode windowInsetsController.isAppearanceLightNavigationBars = !isNightMode
} }
} }
@Suppress("OVERRIDE_DEPRECATION") /*@Suppress("OVERRIDE_DEPRECATION")
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
setIntent(intent) setIntent(intent)
handleDeepLinkIntent(intent) handleDeepLinkIntent(intent)
} }*/
override fun onNewIntent(intent: Intent, caller: ComponentCaller) { override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
super.onNewIntent(intent, caller) super.onNewIntent(intent, caller)
setIntent(intent) setIntent(intent)

View file

@ -95,7 +95,7 @@ private fun bestColWidthPt(
.split("\n") .split("\n")
.forEach { line -> .forEach { line ->
val trimmedLine = cleanSyllable(line) val trimmedLine = cleanSyllable(line)
val x = measureNoteWidth(font, lyricFontSize, trimmedLine) val x = measureNoteWidth(lyricFont, lyricFontSize, trimmedLine)
if (x > maxLyrW) { if (x > maxLyrW) {
maxLyrW = x maxLyrW = x
} }

View file

@ -10,6 +10,10 @@ import java.io.File
fun String.normalizeForSearch(): String { fun String.normalizeForSearch(): String {
return this.lowercase().filter { it.isLetterOrDigit() } 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( data class DrawerItem(
val id: Int, val id: Int,
val title: String, val title: String,
@ -26,24 +30,32 @@ data class DrawerItem(
private fun parseComponents(str: String): TitleComponents? { private fun parseComponents(str: String): TitleComponents? {
// préfixe (lettres), numéro (chiffres), version optionnelle // préfixe (lettres), numéro (chiffres), version optionnelle
val regex = Regex("""^([a-zA-Z]+)[-_\s]*(\d+)(?:[-_\s]*(\d+))?""") val match = TITLE_COMPONENTS_REGEX.find(str.trim()) ?: return null
val match = regex.find(str.trim()) ?: return null
val prefix = match.groupValues[1].lowercase() val prefix = match.groupValues[1].lowercase()
val number = match.groupValues[2] val number = match.groupValues[2]
val version = match.groupValues[3].ifEmpty { null } val version = match.groupValues[3].ifEmpty { null }
return TitleComponents(prefix, number, version) 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<String> by lazy {
DIGIT_BLOCKS_REGEX.findAll(title).map { it.value }.toList()
}
fun matchesQuery(query: String): Boolean { fun matchesQuery(query: String): Boolean {
if (query.isBlank()) return true if (query.isBlank()) return true
val cleanQuery = query.normalizeForSearch() val cleanQuery = query.normalizeForSearch()
val cleanTitle = title.normalizeForSearch()
val cleanContent = contentTitle.normalizeForSearch()
if ((cleanTitle + cleanContent).contains(cleanQuery) || (cleanContent + cleanTitle).contains(cleanQuery)) { if ((cleanTitle + cleanContent).contains(cleanQuery) || (cleanContent + cleanTitle).contains(cleanQuery)) {
return true return true
} }
val queryComponents = parseComponents(query) val queryComponents = parseComponents(query)
val cleanTitle = title.normalizeForSearch()
val cleanContent = contentTitle.normalizeForSearch()
val titleComponents = parseComponents(title) val titleComponents = parseComponents(title)
if (queryComponents != null && titleComponents != null) { if (queryComponents != null && titleComponents != null) {
if (queryComponents.prefix == titleComponents.prefix) { if (queryComponents.prefix == titleComponents.prefix) {
@ -69,11 +81,12 @@ data class DrawerItem(
if (query.isBlank()) return 0 if (query.isBlank()) return 0
val cleanQuery = query.normalizeForSearch() val cleanQuery = query.normalizeForSearch()
val queryComponents = parseComponents(query)
val cleanTitle = title.normalizeForSearch() val cleanTitle = title.normalizeForSearch()
val cleanContent = contentTitle.normalizeForSearch() val cleanContent = contentTitle.normalizeForSearch()
val queryComponents = parseComponents(query)
val titleComponents = parseComponents(title) val titleComponents = parseComponents(title)
val titleDigitBlocks = Regex("\\d+").findAll(title).map { it.value }.toList()
if (queryComponents != null && titleComponents != null) { if (queryComponents != null && titleComponents != null) {
val samePrefix = queryComponents.prefix == titleComponents.prefix val samePrefix = queryComponents.prefix == titleComponents.prefix
@ -99,7 +112,6 @@ data class DrawerItem(
if (cleanTitle == cleanQuery) return 1000 if (cleanTitle == cleanQuery) return 1000
val titleDigitBlocks = Regex("\\d+").findAll(title).map { it.value }.toList()
val queryDigits = query.filter { it.isDigit() } val queryDigits = query.filter { it.isDigit() }
val queryLetters = query.filter { it.isLetter() }.lowercase() val queryLetters = query.filter { it.isLetter() }.lowercase()

View file

@ -39,6 +39,9 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
private val pitches = mutableListOf<MidiPitch>() private val pitches = mutableListOf<MidiPitch>()
private val globalDComments = mutableListOf<String>() private val globalDComments = mutableListOf<String>()
private var currentJob: Job? = null
private val solfaScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
companion object { companion object {
var currentFile = "" var currentFile = ""
val REGEX_SHIFT_PAREN_UPWARD = Regex("([^a-yA-Y\\(\\[]+)([\\)\\]])") 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_OVERRIDE_TOKEN = Regex("""\$\{O:\d+\}""")
val REGEX_VOICE_MARKER = Regex("\\$\\{v:([^\\}]+)\\}") val REGEX_VOICE_MARKER = Regex("\\$\\{v:([^\\}]+)\\}")
val KEEP_MARKERS = listOf("\${L}", "\$T") 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("(?<![\\?:,\\.; ])_")
val REGEX_ADD_HYPHENS2 = Regex("_-(?=_)")
val REGEX_ADD_HYPHENS3 = Regex("_$")
val REGEX_SILENT_DUR = Regex("""z([^:]):""")
val validKeys = Transpose.keyToNumber.sortedByDescending { it.length }
val REGEX_KEY= Regex("\\b(${validKeys.joinToString("|")})(m)?\\b", RegexOption.IGNORE_CASE)
} }
fun parseNoteSplit(input: String): String { fun parseNoteSplit(input: String): String {
@ -90,10 +111,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val lastTUO = accumulator.lastOrNull() val lastTUO = accumulator.lastOrNull()
nextTIndex++ nextTIndex++
if (T.getOrNull(nextTIndex) == null) { if (T.getOrNull(nextTIndex) == null) {
withContext(Dispatchers.Main) { //withContext(Dispatchers.Main) {
sharedScreenModel.updateFullTUOList(accumulator) sharedScreenModel.updateFullTUOList(accumulator)
//sharedScreenModel.doneTUOList() //sharedScreenModel.doneTUOList()
} //}
return return
} }
/*if (nextTIndex == 5) { /*if (nextTIndex == 5) {
@ -257,15 +278,15 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
fun parse(sourceFile: String) { fun parse(sourceFile: String) {
//println("37: lFL bien reçu $sourceFile") //println("37: lFL bien reçu $sourceFile")
currentFile = sourceFile currentFile = sourceFile
val parseScope = CoroutineScope(Dispatchers.Default) currentJob?.cancel()
parseScope.launch { currentJob = solfaScope.launch {
val lines = try { val lines = try {
fileRepository.readFileLines(sourceFile) fileRepository.readFileLines(sourceFile)
} catch (e: Exception) { } catch (e: Exception) {
println("Opening $sourceFile raised exception {${e.message}") println("Opening $sourceFile raised exception {${e.message}")
emptyList() emptyList()
} }
val contentString = fileRepository.readFileLines(sourceFile).joinToString("\n") val contentString = lines.joinToString("\n")
sharedScreenModel.setFileContent(contentString, sourceFile) sharedScreenModel.setFileContent(contentString, sourceFile)
O.clear() O.clear()
T.clear() T.clear()
@ -293,10 +314,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
sharedScreenModel.setNbStanzas(0) sharedScreenModel.setNbStanzas(0)
TimeUnitObject.hasMarker(false) TimeUnitObject.hasMarker(false)
lines.forEach { line -> lines.forEach { line ->
run {
parseOneLine(line) parseOneLine(line)
} }
}
unparsedNote.forEach { unparsedNote.forEach {
preloadN(it) preloadN(it)
} }
@ -330,8 +349,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
private val prefs: Settings = provideSettings() private val prefs: Settings = provideSettings()
fun generateMidiFile(bpm: Float, outputPath: String = "whawyd3.mid", transpI: Int = 0) { fun generateMidiFile(bpm: Float, outputPath: String = "whawyd3.mid", transpI: Int = 0) {
val parseScope = CoroutineScope(Dispatchers.Default) currentJob?.cancel()
parseScope.launch { currentJob = solfaScope.launch {
val nbStanzas = sharedScreenModel.nbStanzas.value.takeIf { it > 0 } ?: 1 val nbStanzas = sharedScreenModel.nbStanzas.value.takeIf { it > 0 } ?: 1
val currentTuoList = sharedScreenModel.tuoList.value val currentTuoList = sharedScreenModel.tuoList.value
val basePitches = pitches.filter { it.metaType != 0x05 }.map { it.copy() } 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) { fun justBuild(sourceFile: String, sourceContent: String) {
currentFile = sourceFile currentFile = sourceFile
val parseScope = CoroutineScope(Dispatchers.Default) currentJob?.cancel()
parseScope.launch { currentJob = solfaScope.launch {
val lines = try { val lines = try {
fileRepository.readFileLines(sourceFile) fileRepository.readFileLines(sourceFile)
} catch (e: Exception) { } catch (e: Exception) {
println("Opening $sourceFile raised exception {${e.message}") println("Opening $sourceFile raised exception {${e.message}")
emptyList() emptyList()
} }
val contentString = fileRepository.readFileLines(sourceFile).joinToString("\n") val contentString = lines.joinToString("\n")
sharedScreenModel.setFileContent(contentString, sourceFile) sharedScreenModel.setFileContent(contentString, sourceFile)
O.clear() O.clear()
T.clear() T.clear()
@ -470,10 +489,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
lyricsComment.clear() lyricsComment.clear()
TimeUnitObject.hasMarker(false) TimeUnitObject.hasMarker(false)
lines.forEach { line -> lines.forEach { line ->
run {
parseOneLine(line) parseOneLine(line)
} }
}
unparsedNote.forEach { unparsedNote.forEach {
preloadN(it) preloadN(it)
} }
@ -702,7 +719,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
return "// Erreur lecture: $filePath" 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 -> myLines.forEach { line ->
var lastIndex = 0 var lastIndex = 0
@ -718,7 +739,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val parts = fullTag.split(":", limit = 3) val parts = fullTag.split(":", limit = 3)
if (parts.size >= 2) { 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 fullPath = directory + fileName
val rawIncludedContent = fileRepository.readFileLines(fullPath) val rawIncludedContent = fileRepository.readFileLines(fullPath)
@ -740,6 +764,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
lineBuilder.append(rawIncludedContent.joinToString("\n")) lineBuilder.append(rawIncludedContent.joinToString("\n"))
} }
} }
}
} catch (e: Exception) { } catch (e: Exception) {
lineBuilder.append("// Erreur inclusion: ${e.message}") lineBuilder.append("// Erreur inclusion: ${e.message}")
} }
@ -1473,7 +1498,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
} }
private fun parseNoteAndOctave(s: String): Pair<String, Int> { private fun parseNoteAndOctave(s: String): Pair<String, Int> {
val base = s.replace(Regex("[^drmfsltDRFSTzw]"), "") val base = s.replace(REGEX_NOTA_NOTE, "")
var level = 0 var level = 0
level += s.count { it == '\'' || it == '¹' || it == '²' || it == '³' } level += s.count { it == '\'' || it == '¹' || it == '²' || it == '³' }
@ -1691,11 +1716,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val consumedBlocks = mutableSetOf<Int>() val consumedBlocks = mutableSetOf<Int>()
fun getDurationAt(targetStr: String, targetCharIdx: Int, blockIdx: Int): Int { 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] val charAtIdx = targetStr[targetCharIdx]
if (blockIdx > 0) { 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 { val isFirstActiveChar = targetCharIdx == 0 || targetStr.substring(0, targetCharIdx).all {
"., !:|(){}$".contains(it) || consumedGlobally.contains(blockIdx to targetStr.indexOf(it)) "., !:|(){}$".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') { if (charAtIdx == 'D' || charAtIdx == 'z') {
val textAfter = targetStr.substring(targetCharIdx + 1) 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 == '-' }) { if (cleanAfter.startsWith(".") && !cleanAfter.substring(1).any { it == 'D' || it == 'z' || it == '-' }) {
return 4 return 4
} }
@ -1725,7 +1750,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
if (!cleanStr.contains(".") && !cleanStr.contains(",")) return 4 if (!cleanStr.contains(".") && !cleanStr.contains(",")) return 4
val pByPoint = cleanStr.split(".") 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 val cleanIdx = prefixBefore.length
var curPos = 0 var curPos = 0
@ -1760,8 +1785,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
// println("Pour $k = $currentStr") // println("Pour $k = $currentStr")
if (k > 0) { if (k > 0) {
val prevBlock = buff[k - 1].replace(Regex("\\$\\{.*?\\}|\\$."), "") val prevBlock = buff[k - 1].replace(REGEX_TARGET_CHAR, "")
val cleanCurrent = currentStr.replace(Regex("\\$\\{.*?\\}|\\$."), "") val cleanCurrent = currentStr.replace(REGEX_TARGET_CHAR, "")
if (prevBlock.endsWith("-./") || prevBlock.endsWith("-.)/")) { if (prevBlock.endsWith("-./") || prevBlock.endsWith("-.)/")) {
if (cleanCurrent.contains(".") && cleanCurrent.startsWith("D") && cleanCurrent.count { it == 'D' } >= 2) { if (cleanCurrent.contains(".") && cleanCurrent.startsWith("D") && cleanCurrent.count { it == 'D' } >= 2) {
@ -1842,7 +1867,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
} else { } else {
var hasFutureResonance = false var hasFutureResonance = false
if (k + 1 < buff.size) { if (k + 1 < buff.size) {
if (buff[k + 1].replace(Regex("\\$\\{.*?\\}|\\$."), "") if (buff[k + 1].replace(REGEX_TARGET_CHAR, "")
.startsWith("-") .startsWith("-")
) hasFutureResonance = true ) hasFutureResonance = true
} }
@ -1871,7 +1896,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
while (lookingForSilence && nextBlockIdx < buff.size) { while (lookingForSilence && nextBlockIdx < buff.size) {
val nextBlockRaw = buff[nextBlockIdx] val nextBlockRaw = buff[nextBlockIdx]
val nextBlockClean = nextBlockRaw.replace(Regex("\\$\\{.*?\\}|\\$."), "").trim() val nextBlockClean = nextBlockRaw.replace(REGEX_TARGET_CHAR, "").trim()
if (nextBlockClean.isNotEmpty() && nextBlockClean.all { if (nextBlockClean.isNotEmpty() && nextBlockClean.all {
it == 'z' || "., !:|()/{}".contains( it == 'z' || "., !:|()/{}".contains(
@ -1959,8 +1984,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
} }
private fun expandNotes(text: String): String { private fun expandNotes(text: String): String {
val regex = Regex("([drmfsltDRFSTzw])([,']*)(\\d+)") return REGEX_NOTE_W_OCT.replace(text) { matchResult ->
return regex.replace(text) { matchResult ->
val note = matchResult.groupValues[1] val note = matchResult.groupValues[1]
val octaves = matchResult.groupValues[2] val octaves = matchResult.groupValues[2]
val count = matchResult.groupValues[3].toInt() val count = matchResult.groupValues[3].toInt()
@ -2000,8 +2024,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
fun countNotesInSegment(segment: String): Int { fun countNotesInSegment(segment: String): Int {
val withoutComments = segment val withoutComments = segment
.replace(REGEX_TEMPLATE_COMMENT, "") .replace(REGEX_TEMPLATE_COMMENT, "")
.replace(Regex("#[drmfsltDRFSTz][',]*"), "") .replace(REGEX_ANCHOR_NOTE, "")
.replace(Regex("<\\s*\\{[^\\}]*\\}"), "") .replace(REGEX_SPLIT_BRACE, "")
.replace(" ", "") .replace(" ", "")
val expanded = REGEX_REPETITION.replace(withoutComments) { m -> val expanded = REGEX_REPETITION.replace(withoutComments) { m ->
m.groupValues[1].repeat(m.groupValues[2].toInt()) m.groupValues[1].repeat(m.groupValues[2].toInt())
@ -2034,14 +2058,12 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val splitBlocks = mutableListOf<String>() val splitBlocks = mutableListOf<String>()
val noteLineWithoutSplits = parsedNoteLine val noteLineWithoutSplits = parsedNoteLine
.replace(REGEX_TEMPLATE_COMMENT, "") .replace(REGEX_TEMPLATE_COMMENT, "")
.replace(Regex("<\\s*\\{[^\\}]*\\}")) { matchResult -> .replace(REGEX_SPLIT_BRACE) { matchResult ->
splitBlocks.add(matchResult.value) splitBlocks.add(matchResult.value)
"§" "§"
} }
fun insertZToCharArray(input: String): CharArray { fun insertZToCharArray(input: String): CharArray {
val delim = "/:!|" val insertedZ = input.replace(REGEX_INSERT_Z) { it.value + "z"}
val reDelim = "[$delim](?=[$delim])".toRegex()
val insertedZ = input.replace(reDelim) { it.value + "z"}
return insertedZ.toCharArray() return insertedZ.toCharArray()
} }
val templateCharArray = insertZToCharArray(templateStripped) val templateCharArray = insertZToCharArray(templateStripped)
@ -2059,10 +2081,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
lineRepeated.toCharArray().forEach { lineRepeated.toCharArray().forEach {
if (it == '§') { if (it == '§') {
val rawSplit = splitBlocks.removeAt(0) val rawSplit = splitBlocks.removeAt(0)
val anchorSuffix = anchor.replace(Regex("^[drmfslt]"), "") val anchorSuffix = anchor.replace(REGEX_ANCHOR_SUFFIX, "")
val processedSplit = rawSplit.replace(Regex("\\{([^\\}]+)\\}")) { match -> val processedSplit = rawSplit.replace(REGEX_BRACES_CONTENT) { match ->
val innerContent = match.groupValues[1] 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 n = noteMatch.groupValues[1]
val oct = noteMatch.groupValues[2] val oct = noteMatch.groupValues[2]
var res = n var res = n
@ -2238,39 +2260,46 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
suspend fun loadI(line: String, regexIgnoreString: String = "") { suspend fun loadI(line: String, regexIgnoreString: String = "") {
val lineSplit = line.split(":") 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 lastSlashInFilename = currentFile.lastIndexOf('/')
val fileNamePrefix = if (lastSlashInFilename != -1) { val fileNamePrefix = if (lastSlashInFilename != -1) {
currentFile.substring(0, lastSlashInFilename + 1) currentFile.substring(0, lastSlashInFilename + 1)
} else { } else {
"" ""
} }
val regexIgnoreString = try { val combinedIgnore = try {
if (regexIgnoreString != "") { if (regexIgnoreString.isNotEmpty() && lineSplit.size > 1 && lineSplit[1].isNotEmpty()) {
regexIgnoreString + "|" + lineSplit[1] "$regexIgnoreString|${lineSplit[1]}"
} else { } else if (lineSplit.size > 1 && lineSplit[1].isNotEmpty()) {
lineSplit[1] lineSplit[1]
} else {
regexIgnoreString.ifEmpty { "^:" }
} }
} catch (e: Exception) { } 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 { val lines = try {
fileRepository.readFileLines(filePath) fileRepository.readFileLines(filePath)
} catch (e: Exception) { } catch (e: Exception) {
println("Opening $filePath raised exception {${e.message}") println("Opening $filePath raised exception {${e.message}")
emptyList() emptyList()
} }
try { lines.forEach { itemLine ->
val ignoredLines = Regex(regexIgnoreString) if (ignoredLines.find(itemLine) == null) {
lines.forEach { parseOneLine(itemLine, combinedIgnore)
val match = ignoredLines.find(it)
if (match == null) {
parseOneLine(it, regexIgnoreString)
} }
} }
} catch (e: Exception) {
}
} }
private fun loadM(value: String) { private fun loadM(value: String) {
@ -2692,8 +2721,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val parsedULine = uObject.parsed() val parsedULine = uObject.parsed()
loadT(parsedULine) loadT(parsedULine)
val regex = Regex("""z([^:]):""") val match = REGEX_SILENT_DUR.find(line)
val match = regex.find(line)
val silentDuration = match?.groupValues?.get(1) ?: "0" val silentDuration = match?.groupValues?.get(1) ?: "0"
sharedScreenModel.setMeasureInt(measure) sharedScreenModel.setMeasureInt(measure)
@ -2728,10 +2756,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
meta[subKey] = line.substring(2) meta[subKey] = line.substring(2)
} }
if ("c" == subKey) { 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 rawText = line.substringAfter("c:")
val matchResult = keyRegex.find(rawText) val matchResult = REGEX_KEY.find(rawText)
if (matchResult != null) { if (matchResult != null) {
val rawBaseKey = matchResult.groupValues[1] val rawBaseKey = matchResult.groupValues[1]
@ -2756,11 +2782,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
private fun String.addHyphens(): String { private fun String.addHyphens(): String {
return this return this
.replace(Regex("(?<![\\?:,\\.; ])_"), "-_") .replace(REGEX_ADD_HYPHENS1, "-_")
.replace(Regex("_-(?=_)"), "_") .replace(REGEX_ADD_HYPHENS2, "_")
.replace(" -_", "_") .replace(" -_", "_")
.replace("--_", "-_") .replace("--_", "-_")
.replace(Regex("_$"), "") .replace(REGEX_ADD_HYPHENS3, "")
} }
private fun unpackLyrics(lyrics: String): String { private fun unpackLyrics(lyrics: String): String {
@ -2802,12 +2828,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
positionDS.add(i) positionDS.add(i)
} }
val originalLyrics = REGEX_STRIP_DC.replace(lyricsItem, "") val originalLyrics = REGEX_STRIP_DC.replace(lyricsItem, "")
val REGEX_OVERRIDE = Regex("\\$\\{O:(\\d+)\\}")
REGEX_OVERRIDE.findAll(lyricsItem).forEach { matchResult -> REGEX_OVERRIDE.findAll(lyricsItem).forEach { matchResult ->
val overrideNumber = matchResult.groupValues[1].toInt() val overrideNumber = matchResult.groupValues[1].toInt()
val override = O.getOrElse(overrideNumber) { null } val override = O.getOrElse(overrideNumber) { null }
override?.forEachIndexed { index, value -> 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") // 1. Extraire le numéro de voix (ex: "2")
val voiceNum = matchResult?.groupValues?.get(1) ?: "" val voiceNum = matchResult?.groupValues?.get(1) ?: ""
val prefix = if (voiceNum.isNotEmpty()) { val prefix = if (voiceNum.isNotEmpty()) {

View file

@ -55,6 +55,7 @@ import feufaro.composeapp.generated.resources.Res
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import mg.dot.feufaro.ContextualMenu import mg.dot.feufaro.ContextualMenu
import mg.dot.feufaro.DisplayConfigManager import mg.dot.feufaro.DisplayConfigManager
import mg.dot.feufaro.FileRepository 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" return "$separatorBefore\n$separatorBefore\n$separatorBefore\n$separatorBefore"
} }
val retour = tuNotes.drop(1).joinToString (separator = "\n"){ 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 return retour
} }
@ -288,43 +289,33 @@ class TimeUnitObject (val pTemplate: PTemplate, val prevTUO: TimeUnitObject?, co
return finalLines return finalLines
} }
private var cachedCumulativeMod: Int? = null
fun getCumulativeModulationInterval(): Int { fun getCumulativeModulationInterval(): Int {
cachedCumulativeMod?.let { return it }
val notes = noteAsMultiString() val notes = noteAsMultiString()
val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)")
val tokens = notes.split(Regex("(?<=[:|•\\s])|(?=[:|•\\s])"))
var modDelta = 0 var modDelta = 0
for (token in notes.split(MOD_TOKEN_SPLIT_REGEX)) {
for (token in tokens) { val modMatch = MODULATION_REGEX.matchEntire(token.trim()) ?: continue
val trimmed = token.trim() val oldIdx = Transpose.noteToNumber.indexOf(modMatch.groupValues[1])
val modMatch = MODULATION_REGEX.matchEntire(trimmed) val newIdx = Transpose.noteToNumber.indexOf(modMatch.groupValues[3])
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) { if (oldIdx != -1 && newIdx != -1) {
val oldOctaveVal = Transpose.octaveToInt(oldOctaveStr) val oldTotal = oldIdx + Transpose.octaveToInt(modMatch.groupValues[2]) * 12
val newOctaveVal = Transpose.octaveToInt(newOctaveStr) val newTotal = newIdx + Transpose.octaveToInt(modMatch.groupValues[4]) * 12
modDelta = oldTotal - newTotal
val oldTotalSemitones = oldIdx + (oldOctaveVal * 12)
val newTotalSemitones = newIdx + (newOctaveVal * 12)
modDelta = oldTotalSemitones - newTotalSemitones
break break
} }
} }
} val result = (prevTUO?.getCumulativeModulationInterval() ?: 0) + modDelta
cachedCumulativeMod = result
val prevDelta = prevTUO?.getCumulativeModulationInterval() ?: 0 return result
return prevDelta + modDelta
} }
} }
private val REGEX_CLEAN_PREFIX = Regex("(\\d+\\.)+") 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 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( private val musicForEmmentRegex = Regex(
"""^(?:[mfp]+|sfz|sf|fz|rfz)$""", """^(?:[mfp]+|sfz|sf|fz|rfz)$""",
@ -364,14 +355,11 @@ fun TimeUnitComposable(
val focusRequesters = remember { List(4) { FocusRequester() } } val focusRequesters = remember { List(4) { FocusRequester() } }
val isLitany = tuo.isLitany() val isLitany = tuo.isLitany()
val rawText = remember(tuo, transpositionInterval) {
val notes = tuo.noteAsMultiString() val notes = tuo.noteAsMultiString()
val initialMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0 val initialMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0
// Mettre en cache les annotations et les chaînes transposées // Mettre en cache les annotations et les chaînes transposées
val rawText = remember(tuo, transpositionInterval) { Transpose.transposeText(text = notes, interval = transpositionInterval, initialModulationInterval = initialMod)
Transpose.transposeText(
text = notes, interval = transpositionInterval,
initialModulationInterval = initialMod
)
} }
val rawLines = remember(rawText) { rawText.lines() } val rawLines = remember(rawText) { rawText.lines() }
val multiLineText = remember(tuo, transpositionInterval, isLitany) { val multiLineText = remember(tuo, transpositionInterval, isLitany) {
@ -533,44 +521,28 @@ fun bestTUOWidth(
LaunchedEffect(items, noteStyle, transpositionInterval) { LaunchedEffect(items, noteStyle, transpositionInterval) {
isReady = false isReady = false
var max = 0.dp val widthCache = HashMap<String, Int>()
// println("=== [DEBUG TUO] Début mesure de ${items.size} blocs TUO ===") var maxPx = 0
items.forEachIndexed { i, tuo ->
items.forEach { tuo ->
val prevMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0 val prevMod = tuo.prevTUO?.getCumulativeModulationInterval() ?: 0
val rawNotes = Transpose.transposeText( val rawNotes = Transpose.transposeText(
text = tuo.noteAsMultiString(), text = tuo.noteAsMultiString(),
interval = transpositionInterval, interval = transpositionInterval,
initialModulationInterval = prevMod initialModulationInterval = prevMod
) )
val transposedNotes = if (tuo.isLitany()) SolfaLabels.toLabels(rawNotes) else rawNotes val transposed = if (tuo.isLitany()) SolfaLabels.toLabels(rawNotes) else rawNotes
val noteLines = transposedNotes.lines() transposed.lines().forEach { line ->
var maxNoteWidthPx = 0 val w = widthCache.getOrPut(line) {
textMeasurer.measure(
noteLines.forEachIndexed { lineIdx, line -> text = parseNoteToAnnotatedString(line),
val annotatedNote = parseNoteToAnnotatedString(line) style = noteStyle, maxLines = 1, softWrap = false
val noteResult = textMeasurer.measure( ).size.width
text = annotatedNote,
style = noteStyle,
maxLines = 1,
softWrap = false
)
val widthPx = noteResult.size.width
if (widthPx > maxNoteWidthPx) {
maxNoteWidthPx = widthPx
} }
// println("TUO #${tuo.getNum()} | Ligne $lineIdx | Brut: \"$line\" | Annoté: \"${annotatedNote.text}\" -> Largeur: ${widthPx}px") if (w > maxPx) maxPx = w
} }
if (i % 8 == 7) yield()
val tuoMaxWidthDp = with(density) { maxNoteWidthPx.toDp() }
// println("--> TUO #${tuo.getNum()} | Largeur max du bloc: $tuoMaxWidthDp ou ${maxNoteWidthPx}px")
if (tuoMaxWidthDp > max) {
max = tuoMaxWidthDp
} }
} maxWidth = with(density) { maxPx.toDp() } + 5.dp
maxWidth = max + 5.dp //marge
isReady = true isReady = true
// println("=== [DEBUG TUO] Largeur retenue (maxWidth finale) : $maxWidth ===") // println("=== [DEBUG TUO] Largeur retenue (maxWidth finale) : $maxWidth ===")
} }
@ -669,7 +641,7 @@ fun LazyVerticalGridTUO(
val currentDisplayConfig by displayConfigManager.displayConfig.collectAsState() val currentDisplayConfig by displayConfigManager.displayConfig.collectAsState()
val tuoList = viewModel.tuoList val tuoList = viewModel.tuoList
key(tuoList) { /*key(tuoList)*/ /*{*/
var menuPosition by remember { mutableStateOf(Offset.Zero) } var menuPosition by remember { mutableStateOf(Offset.Zero) }
var showAddDialog by remember { mutableStateOf(false) } var showAddDialog by remember { mutableStateOf(false) }
@ -706,7 +678,7 @@ fun LazyVerticalGridTUO(
val loopState by produceState(Triple(-1L, -1L, false), sharedScreenModel.mediaPlayer) { val loopState by produceState(Triple(-1L, -1L, false), sharedScreenModel.mediaPlayer) {
while (true) { while (true) {
value = sharedScreenModel.mediaPlayer?.getLoopState() ?: Triple(-1L, -1L, false) value = sharedScreenModel.mediaPlayer?.getLoopState() ?: Triple(-1L, -1L, false)
kotlinx.coroutines.delay(100) kotlinx.coroutines.delay(250)
} }
} }
val prefs: Settings = provideSettings() val prefs: Settings = provideSettings()
@ -894,7 +866,7 @@ fun LazyVerticalGridTUO(
val textMeasurer = rememberTextMeasurer() val textMeasurer = rememberTextMeasurer()
val containerWidthDp = gridWidthDp / gridColumnCount 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 -> val allMeasuresSyllables = tuoList.drop(1).chunked(gridColumnCount).map { measureTUOss ->
measureTUOss.map { it.getSingleSyllable(currentStanza) }.map { column -> measureTUOss.map { it.getSingleSyllable(currentStanza) }.map { column ->
column.map { syllable -> syllable.replace(REGEX_CLEAN_PREFIX, "").trim() } column.map { syllable -> syllable.replace(REGEX_CLEAN_PREFIX, "").trim() }
@ -914,7 +886,7 @@ fun LazyVerticalGridTUO(
} }
} }
} }
} }*/
val litanyLabels: Map<Int, Pair<String, String>> = remember(tuoList, currentStanza) { val litanyLabels: Map<Int, Pair<String, String>> = remember(tuoList, currentStanza) {
val map = LinkedHashMap<Int, Pair<String, String>>() val map = LinkedHashMap<Int, Pair<String, String>>()
@ -1112,11 +1084,16 @@ fun LazyVerticalGridTUO(
if (isHovered) MaterialTheme.colorScheme.onSecondary.copy(alpha = 0.05f) else Color.Transparent, if (isHovered) MaterialTheme.colorScheme.onSecondary.copy(alpha = 0.05f) else Color.Transparent,
RoundedCornerShape(4.dp) 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, interactionSource = interactionSource,
indication = LocalIndication.current, indication = LocalIndication.current,
onClick = { } onClick = { }
) )*/
.pointerInput(globalIndex) { .pointerInput(globalIndex) {
detectTapGestures( detectTapGestures(
onTap = { offset -> onTap = { offset ->
@ -1296,6 +1273,23 @@ fun LazyVerticalGridTUO(
syllable.replace(REGEX_CLEAN_PREFIX, "").trim() 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 -> allTemps.forEachIndexed { syls_i, syllables ->
/*val fragmentU0 = measureTUOs[syls_i].pTemplate.template /*val fragmentU0 = measureTUOs[syls_i].pTemplate.template
println("Fragment=[$fragmentU0] -> Syllabes=$syllables")*/ println("Fragment=[$fragmentU0] -> Syllabes=$syllables")*/
@ -1372,7 +1366,7 @@ fun LazyVerticalGridTUO(
} }
} }
} }
} /*}*/
} }
@Composable @Composable
@ -1654,44 +1648,59 @@ fun makeSpaceBetweenSyllables(
fontSize: TextUnit = 16.sp fontSize: TextUnit = 16.sp
): (String, List<List<String>>, Int, Int) -> Pair<String, Alignment> { ): (String, List<List<String>>, Int, Int) -> Pair<String, Alignment> {
val density = LocalDensity.current val density = LocalDensity.current
val noteWidthPx = with(density) { noteWidthDp.toPx() } val noteWidthPx = remember(density, noteWidthDp) {
val style = TextStyle(fontSize = fontSize) with(density) { noteWidthDp.toPx() }
}
val style = remember(fontSize) {
TextStyle(fontSize = fontSize)
}
val spaceWidthPx = remember(textMeasurer, style) { 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 -> return { currentSyl, allT, s_i, index ->
var textAlign = Alignment.Center val textAlign = Alignment.Center
if (currentSyl.isEmpty()) "" to textAlign if (currentSyl.isEmpty() || noteWidthPx <= 0f || spaceWidthPx <= 0) {
else { currentSyl to textAlign
val currentWidth = textMeasurer.measure(currentSyl, style).size.width } 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 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 prev_syl = if (s_i > 0) allT.getOrNull(s_i - 1)?.getOrNull(index) ?: "" else ""
val excessPx = currentWidth - noteWidthPx val excessPx = currentWidth - noteWidthPx
val isExcess = (excessPx > 0) val isExcess = excessPx > 0
val neededSpaces = if (isExcess && spaceWidthPx > 0) (excessPx / spaceWidthPx).toInt() + 1 else 0 val neededSpaces = if (isExcess) (excessPx / spaceWidthPx).toInt() + 1 else 0
var resultAlign = textAlign
val resultText = when { val resultText = when {
!isExcess && (noteWidthPx > 0 && spaceWidthPx > 0) -> { !isExcess -> {
val totalSpacesPossible = (noteWidthPx / spaceWidthPx).toInt() val totalSpacesPossible = (noteWidthPx / spaceWidthPx).toInt()
val paddingNeeded = totalSpacesPossible - (currentSyl.length + 4) val paddingNeeded = totalSpacesPossible - (currentSyl.length + 4)
if (paddingNeeded > 0) { if (paddingNeeded > 0) {
textAlign = Alignment.TopStart resultAlign = Alignment.TopStart
currentSyl + "\u00A0".repeat(paddingNeeded) currentSyl + "\u00A0".repeat(paddingNeeded)
} else { } else {
currentSyl currentSyl
} }
} }
isExcess && spaceWidthPx > 0 && next_syl.length < prev_syl.length -> { next_syl.length < prev_syl.length -> {
"\u00A0".repeat(neededSpaces) + currentSyl "\u00A0".repeat(neededSpaces) + currentSyl
} }
isExcess && spaceWidthPx > 0 -> { else -> {
currentSyl + "\u00A0".repeat(neededSpaces) currentSyl + "\u00A0".repeat(neededSpaces)
} }
else -> currentSyl
} }
resultText to textAlign resultText to resultAlign
} }
} }
} }

View file

@ -21,6 +21,9 @@ import androidx.compose.ui.unit.dp
class Transpose { class Transpose {
companion object { companion object {
val REGEX_ONE_NOTE = Regex("^([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)(.*)") 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 octaveSigns = listOf("₄", "₃", "₂", "₁", "", "¹", "²", "³", "⁴")
val noteToNumber = listOf("d", "di", "r", "ri", "m", "f", "fi", "s", "si", "l", "ta", "t") 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" ) 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 if (text.isEmpty()) return text
var currentModulationInterval = initialModulationInterval var currentModulationInterval = initialModulationInterval
val MODULATION_REGEX = Regex(">([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)>([drmfslt][ia]?)([₄₃₂₁¹²³⁴',]*)") val tokens = text.split(TOKEN_SPLIT_REGEX)
val NOTE_UNIT_REGEX = Regex("([drmfslt][ia]?)([₄₃₂₁¹²³⁴]*)")
val tokens = text.split(Regex("(?<=[:|•\\s])|(?=[:|•\\s])"))
val finalResult = tokens.joinToString("") { token -> val finalResult = tokens.joinToString("") { token ->
val trimmed = token.trim() val trimmed = token.trim()
if (trimmed.isEmpty() || trimmed.matches(Regex("[:|•\\s]+"))) { if (trimmed.isEmpty() || trimmed.all { it == ':' || it == '|' || it == '•' || it.isWhitespace() }) {
token token
} else { } else {
val modMatch = MODULATION_REGEX.matchEntire(trimmed) val modMatch = MODULATION_REGEX.matchEntire(trimmed)

View file

@ -1522,6 +1522,8 @@ private fun LandscapeFloatingActionButtons(
} }
} }
private val NATURAL_SPLIT_REGEX = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
@Composable @Composable
private fun SearchOverlayCard( private fun SearchOverlayCard(
isSearchActive: Boolean, isSearchActive: Boolean,
@ -1549,42 +1551,56 @@ private fun SearchOverlayCard(
var sortedSongs by remember { mutableStateOf(emptyList<DrawerItem>()) } var sortedSongs by remember { mutableStateOf(emptyList<DrawerItem>()) }
var isSearching by remember { mutableStateOf(true) } 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 isSearching = true
val query = textInput.text val query = textInput.text
if (query.isNotEmpty()) {
kotlinx.coroutines.delay(60L)
}
val result = withContext(Dispatchers.Default) { val result = withContext(Dispatchers.Default) {
val naturalComparator = Comparator<DrawerItem> { a, b -> val tokenComparator = Comparator<Pair<DrawerItem, List<Comparable<*>>>> { (_, tokensA), (_, tokensB) ->
val regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)") var cmp = 0
val chunksA = a.title.lowercase().split(regex) val size = minOf(tokensA.size, tokensB.size)
val chunksB = b.title.lowercase().split(regex)
var result = 0
val size = minOf(chunksA.size, chunksB.size)
for (i in 0 until size) { for (i in 0 until size) {
val chunkA = chunksA[i] val aPart = tokensA[i]
val chunkB = chunksB[i] val bPart = tokensB[i]
val numA = chunkA.toLongOrNull() cmp = if (aPart is Long && bPart is Long) {
val numB = chunkB.toLongOrNull() aPart.compareTo(bPart)
result = if (numA != null && numB != null) {
numA.compareTo(numB)
} else { } 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()) { if (query.isBlank()) {
filteredSongs.sortedWith( tokenizedSongs
compareBy<DrawerItem> { item -> !item.path.startsWith("assets://") } .sortedWith(
.thenComparing(naturalComparator) compareBy<Pair<DrawerItem, List<Comparable<*>>>> { (item, _) -> !item.path.startsWith("assets://") }
.thenComparing(tokenComparator)
) )
.map { it.first }
} else { } else {
filteredSongs.sortedWith( val scores = HashMap<String, Int>(tokenizedSongs.size).also { m ->
compareByDescending<DrawerItem> { item -> item.getSearchScore(query) } tokenizedSongs.forEach { (item, _) -> m[item.path] = item.getSearchScore(query) }
.thenBy { item -> !item.path.startsWith("assets://") } }
.thenComparing(naturalComparator) tokenizedSongs
.sortedWith(
compareByDescending<Pair<DrawerItem, List<Comparable<*>>>> { (item, _) -> scores[item.path] ?: 0 }
.thenBy { (item, _) -> !item.path.startsWith("assets://") }
.thenComparing(tokenComparator)
) )
.map { it.first }
} }
} }
sortedSongs = result sortedSongs = result

View file

@ -665,8 +665,10 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode
if (query.isBlank()) { if (query.isBlank()) {
items items
} else { } else {
items.filter { item -> item.matchesQuery(query) } items.filter { it.matchesQuery(query) }
.sortedByDescending { item -> item.getSearchScore(query) } .map { it to it.getSearchScore(query) }
.sortedByDescending { it.second }
.map { it.first }
} }
}.stateIn ( }.stateIn (
scope = CoroutineScope(Dispatchers.Default), scope = CoroutineScope(Dispatchers.Default),