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
}
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
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)

View file

@ -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
}

View file

@ -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<String> 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()

View file

@ -39,6 +39,9 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
private val pitches = mutableListOf<MidiPitch>()
private val globalDComments = mutableListOf<String>()
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("(?<![\\?:,\\.; ])_")
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 {
@ -90,10 +111,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
val lastTUO = accumulator.lastOrNull()
nextTIndex++
if (T.getOrNull(nextTIndex) == null) {
withContext(Dispatchers.Main) {
//withContext(Dispatchers.Main) {
sharedScreenModel.updateFullTUOList(accumulator)
//sharedScreenModel.doneTUOList()
}
//}
return
}
/*if (nextTIndex == 5) {
@ -257,15 +278,15 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
fun parse(sourceFile: String) {
//println("37: lFL bien reçu $sourceFile")
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()
@ -293,10 +314,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
sharedScreenModel.setNbStanzas(0)
TimeUnitObject.hasMarker(false)
lines.forEach { line ->
run {
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,10 +489,8 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
lyricsComment.clear()
TimeUnitObject.hasMarker(false)
lines.forEach { line ->
run {
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)
@ -740,6 +764,7 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
lineBuilder.append(rawIncludedContent.joinToString("\n"))
}
}
}
} catch (e: Exception) {
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> {
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<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]
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<String>()
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,39 +2260,46 @@ 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) {
}
}
private fun loadM(value: String) {
@ -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("(?<![\\?:,\\.; ])_"), "-_")
.replace(Regex("_-(?=_)"), "_")
.replace(REGEX_ADD_HYPHENS1, "-_")
.replace(REGEX_ADD_HYPHENS2, "_")
.replace(" -_", "_")
.replace("--_", "-_")
.replace(Regex("_$"), "")
.replace(REGEX_ADD_HYPHENS3, "")
}
private fun unpackLyrics(lyrics: String): String {
@ -2802,12 +2828,11 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
positionDS.add(i)
}
val originalLyrics = REGEX_STRIP_DC.replace(lyricsItem, "")
val REGEX_OVERRIDE = Regex("\\$\\{O:(\\d+)\\}")
REGEX_OVERRIDE.findAll(lyricsItem).forEach { matchResult ->
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()) {

View file

@ -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)
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 oldOctaveVal = Transpose.octaveToInt(oldOctaveStr)
val newOctaveVal = Transpose.octaveToInt(newOctaveStr)
val oldTotalSemitones = oldIdx + (oldOctaveVal * 12)
val newTotalSemitones = newIdx + (newOctaveVal * 12)
modDelta = oldTotalSemitones - newTotalSemitones
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 rawText = remember(tuo, transpositionInterval) {
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
)
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<String, Int>()
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")
if (w > maxPx) maxPx = w
}
val tuoMaxWidthDp = with(density) { maxNoteWidthPx.toDp() }
// println("--> TUO #${tuo.getNum()} | Largeur max du bloc: $tuoMaxWidthDp ou ${maxNoteWidthPx}px")
if (tuoMaxWidthDp > max) {
max = tuoMaxWidthDp
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<Int, Pair<String, String>> = remember(tuoList, currentStanza) {
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,
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<List<String>>, Int, Int) -> Pair<String, Alignment> {
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
}
}
}

View file

@ -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)

View file

@ -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<DrawerItem>()) }
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<DrawerItem> { 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<Pair<DrawerItem, List<Comparable<*>>>> { (_, 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<DrawerItem> { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
tokenizedSongs
.sortedWith(
compareBy<Pair<DrawerItem, List<Comparable<*>>>> { (item, _) -> !item.path.startsWith("assets://") }
.thenComparing(tokenComparator)
)
.map { it.first }
} else {
filteredSongs.sortedWith(
compareByDescending<DrawerItem> { item -> item.getSearchScore(query) }
.thenBy { item -> !item.path.startsWith("assets://") }
.thenComparing(naturalComparator)
val scores = HashMap<String, Int>(tokenizedSongs.size).also { m ->
tokenizedSongs.forEach { (item, _) -> m[item.path] = item.getSearchScore(query) }
}
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

View file

@ -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),