Render voice label marker on first row on print pdf for desktop & android

This commit is contained in:
Hasinjato 2026-11-19 16:00:01 +03:00
parent 5c73b79809
commit 6b810c8142
2 changed files with 330 additions and 63 deletions

View file

@ -17,6 +17,7 @@ import mg.dot.feufaro.data.GridTUOData
import mg.dot.feufaro.solfa.TimeUnitObject import mg.dot.feufaro.solfa.TimeUnitObject
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import kotlin.math.ceil
private data class PdfColor(val r: Float, val g: Float, val b: Float) private data class PdfColor(val r: Float, val g: Float, val b: Float)
@ -25,6 +26,7 @@ private val COLOR_SOPRANO = PdfColor(180 / 255f, 0f, 0f)
private val COLOR_ALTO = PdfColor(0f, 120 / 255f, 0f) private val COLOR_ALTO = PdfColor(0f, 120 / 255f, 0f)
private val COLOR_TENOR = PdfColor(0f, 0f, 180 / 255f) private val COLOR_TENOR = PdfColor(0f, 0f, 180 / 255f)
private val COLOR_BASSE = PdfColor(0f, 100 / 255f, 120 / 255f) private val COLOR_BASSE = PdfColor(0f, 100 / 255f, 120 / 255f)
private val COLOR_VOICE_LABEL = PdfColor(80 / 255f, 80 / 255f, 80 / 255f)
private fun PDPageContentStream.setNonStrokingPdfColor(c: PdfColor) = private fun PDPageContentStream.setNonStrokingPdfColor(c: PdfColor) =
setNonStrokingColor(c.r, c.g, c.b) setNonStrokingColor(c.r, c.g, c.b)
@ -435,6 +437,74 @@ private fun drawFooterLogo(
} }
} }
private fun collectVoiceLabelMap(tuoList: List<TimeUnitObject>): Map<Int, String> {
val aggregatedMarkers = mutableMapOf<Int, String>()
tuoList.take(10).forEach { tuo ->
tuo.voiceMarkers.forEach { (voiceNum, text) ->
if (text.isNotBlank() && !aggregatedMarkers.containsKey(voiceNum)) {
aggregatedMarkers[voiceNum] = text.trim()
}
}
}
return aggregatedMarkers.toSortedMap()
}
private fun computeVoiceLabelColumnWidth(
voiceLabelMap: Map<Int, String>,
italicFont: PDType0Font,
labelFontSize: Float,
satbBlockWidth: Float
): Float {
if (voiceLabelMap.isEmpty()) return 0f
var maxRequiredWidth = 0f
voiceLabelMap.values.forEach { rawLabel ->
val clean = rawLabel.trim()
if (clean.isEmpty()) return@forEach
val wordCount = clean.split(Regex("\\s+")).count { it.isNotEmpty() }
val measuredTextW = textWidth(italicFont, labelFontSize, clean)
val wordSpacingAllowance = (wordCount - 1).coerceAtLeast(0) * (labelFontSize * 0.35f)
val totalNeeded = measuredTextW + wordSpacingAllowance + 8f
if (totalNeeded > maxRequiredWidth) {
maxRequiredWidth = totalNeeded
}
}
return (maxRequiredWidth + satbBlockWidth).coerceAtLeast(65f)
}
private fun drawVoiceLabels(
cs: PDPageContentStream,
voiceLabelMap: Map<Int, String>,
italicFont: PDType0Font,
labelFontSize: Float,
startX: Float,
notesStartY: Float,
noteLineH: Float,
customSpacing: List<Int>
) {
if (voiceLabelMap.isEmpty()) return
val maxVoiceNum = maxOf(voiceLabelMap.keys.maxOrNull() ?: 4, 4)
val voiceNumbers = (1..maxVoiceNum).toList()
voiceNumbers.forEach { voiceNum ->
val labelText = voiceLabelMap[voiceNum]?.trim().orEmpty()
val voiceLineIndex = voiceNum - 1
val vLi = getVirtualLineIndex(voiceLineIndex, customSpacing)
val labelY = notesStartY - (vLi * noteLineH)
cs.saveGraphicsState()
cs.beginText()
cs.setFont(italicFont, labelFontSize)
cs.setNonStrokingPdfColor(COLOR_VOICE_LABEL)
cs.newLineAtOffset(startX, labelY)
cs.showText(labelText.sanitize())
cs.endText()
cs.restoreGraphicsState()
}
}
// ── actual fun ──────────────────────────────────────────────────────────────── // ── actual fun ────────────────────────────────────────────────────────────────
actual fun rememberPdfExportAction( actual fun rememberPdfExportAction(
scope: CoroutineScope, scope: CoroutineScope,
@ -536,6 +606,35 @@ private suspend fun generatePdfToBytes(
} }
val colWidth = usableWidth / colCount val colWidth = usableWidth / colCount
val hasVoiceLabels = tuoList.any { it.voiceMarkers.isNotEmpty() }
val voiceLabelMap = if (hasVoiceLabels) collectVoiceLabelMap(tuoList) else emptyMap()
val voiceLabelFontSize = noteFontSize * 0.85f
val satbLabelFont = lyricFont
val satbLabelSize = noteFontSize * 0.85f
val maxSatbCharW = listOf("S", "A", "T", "B").maxOfOrNull {
textWidth(satbLabelFont, satbLabelSize, it)
} ?: 8f
val estimatedBraceW = 14f
val satbBlockWidth = if (hasVoiceLabels) maxSatbCharW + estimatedBraceW + 6f else 0f
val voiceLabelColumnWidth = if (hasVoiceLabels) {
computeVoiceLabelColumnWidth(
voiceLabelMap = voiceLabelMap,
italicFont = markerItalicFont,
labelFontSize = voiceLabelFontSize,
satbBlockWidth = satbBlockWidth
)
} else {
0f
}
val reductionCols = if (hasVoiceLabels && colWidth > 0f) {
ceil(voiceLabelColumnWidth / colWidth).toInt().coerceAtLeast(1)
} else {
0
}
val firstRowColCount = if (hasVoiceLabels) (colCount - reductionCols).coerceAtLeast(1) else colCount
val maxSylsSize = tuoList.maxOfOrNull { tuo -> val maxSylsSize = tuoList.maxOfOrNull { tuo ->
(1..nbStanza).maxOfOrNull { sz -> tuo.getSingleSyllable(sz).size } ?: 1 (1..nbStanza).maxOfOrNull { sz -> tuo.getSingleSyllable(sz).size } ?: 1
} ?: 1 } ?: 1
@ -773,7 +872,20 @@ private suspend fun generatePdfToBytes(
!pitchPattern.containsMatchIn(noteContent) !pitchPattern.containsMatchIn(noteContent)
} }
} }
val allRows = tuoList.chunked(colCount)
val allRows: List<List<TimeUnitObject>> = buildList {
if (tuoList.isNotEmpty()) {
val firstChunkSize = minOf(tuoList.size, firstRowColCount)
add(tuoList.take(firstChunkSize))
var idx = firstChunkSize
while (idx < tuoList.size) {
val nextSize = minOf(tuoList.size - idx, colCount)
add(tuoList.subList(idx, idx + nextSize))
idx += nextSize
}
}
}
val rows = if (allRows.size > 1 && isRowEmptyOrSeparatorOnly(allRows.last())) { val rows = if (allRows.size > 1 && isRowEmptyOrSeparatorOnly(allRows.last())) {
allRows.dropLastWhile { isRowEmptyOrSeparatorOnly(it) } allRows.dropLastWhile { isRowEmptyOrSeparatorOnly(it) }
} else { } else {
@ -781,6 +893,18 @@ private suspend fun generatePdfToBytes(
} }
rows.forEachIndexed { rowIdx, rowTuos -> rows.forEachIndexed { rowIdx, rowTuos ->
val isFirstRow = (rowIdx == 0)
val isFirstRowWithVoiceLabels = isFirstRow && hasVoiceLabels
val currentRowColCount = if (isFirstRowWithVoiceLabels) firstRowColCount else colCount
val notesStartX = if (isFirstRowWithVoiceLabels) marginX + voiceLabelColumnWidth else marginX
val currentRowUsableWidth = if (isFirstRowWithVoiceLabels) {
(usableWidth - voiceLabelColumnWidth).coerceAtLeast(1f)
} else {
usableWidth
}
val currentRowColWidth = currentRowUsableWidth / currentRowColCount
val maxNoteLines = (rowTuos.maxOfOrNull { it.noteAsMultiString().split("\n").size } ?: 1) + 1 val maxNoteLines = (rowTuos.maxOfOrNull { it.noteAsMultiString().split("\n").size } ?: 1) + 1
val maxLyricLines = rowTuos.maxOfOrNull { it.getSingleSyllable(stanza).size } ?: 0 val maxLyricLines = rowTuos.maxOfOrNull { it.getSingleSyllable(stanza).size } ?: 0
@ -866,26 +990,36 @@ private suspend fun generatePdfToBytes(
// ---- 1. Marqueurs ---- // ---- 1. Marqueurs ----
if (rowHasMarkers) { if (rowHasMarkers) {
rowTuos.forEachIndexed { colIdx, tuo -> rowTuos.forEachIndexed { colIdx, tuo ->
val x = marginX + colIdx * colWidth val x = notesStartX + colIdx * currentRowColWidth
// ⚠️ Pas de emmentalerTTF sur Android → signature sans ce param // ⚠️ Pas de emmentalerTTF sur Android → signature sans ce param
drawMarkers(cs, tuo, x, colWidth, y, markerBoldFont, markerItalicFont, markerEmmetFont, noteFontSize) drawMarkers(cs, tuo, x, currentRowColWidth, y, markerBoldFont, markerItalicFont, markerEmmetFont, noteFontSize)
drawHairPinForTUO(cs, tuo, colCount, x, colWidth, y, noteLineH) drawHairPinForTUO(cs, tuo, currentRowColCount, x, currentRowColWidth, y, noteLineH)
} }
} }
// ---- 2. Accolade & étiquettes SATB ---- // ---- Voice label 2. Accolade & étiquettes SATB ----
val braceTop = notesStartY + noteLineH * 0.85f val braceTop = notesStartY + noteLineH * 0.85f
val lastVoiceIdx = (maxNoteLines - 1).coerceIn(0, 3) val lastVoiceIdx = (maxNoteLines - 1).coerceIn(0, 3)
val totalVirtualSlots = getVirtualLineIndex(lastVoiceIdx, customSpacings) + 1 val totalVirtualSlots = getVirtualLineIndex(lastVoiceIdx, customSpacings) + 1
val braceBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH val braceBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH
drawCurlyBrace(cs, marginX, braceTop, braceBottom)
val lineBottom = braceBottom
val voiceLabels = listOf("S", "A", "T", "B")
val labelFont = lyricFont
val labelSize = noteFontSize * 0.85f
val braceW = ((braceTop - braceBottom) * 0.12f).coerceIn(8f, 22f) val braceW = ((braceTop - braceBottom) * 0.12f).coerceIn(8f, 22f)
val labelX = marginX - braceW - 3f
if (isFirstRowWithVoiceLabels) {
drawVoiceLabels(
cs = cs,
voiceLabelMap = voiceLabelMap,
italicFont = markerItalicFont,
labelFontSize = voiceLabelFontSize,
startX = marginX,
notesStartY = notesStartY,
noteLineH = noteLineH,
customSpacing = customSpacings
)
}
val satbRightEdge = notesStartX - braceW - 3f
val voiceLabels = listOf("S", "A", "T", "B")
voiceLabels.take(maxNoteLines).forEachIndexed { li, label -> voiceLabels.take(maxNoteLines).forEachIndexed { li, label ->
val vLi = getVirtualLineIndex(li, customSpacings) val vLi = getVirtualLineIndex(li, customSpacings)
@ -900,19 +1034,22 @@ private suspend fun generatePdfToBytes(
} }
cs.saveGraphicsState() cs.saveGraphicsState()
cs.beginText() cs.beginText()
cs.setFont(labelFont, labelSize) cs.setFont(satbLabelFont, satbLabelSize)
cs.setNonStrokingPdfColor(labelColor) cs.setNonStrokingPdfColor(labelColor)
cs.newLineAtOffset(labelX - textWidth(labelFont, labelSize, label), labelY) cs.newLineAtOffset(satbRightEdge - textWidth(satbLabelFont, satbLabelSize, label), labelY)
cs.showText(label) cs.showText(label)
cs.endText() cs.endText()
cs.restoreGraphicsState() cs.restoreGraphicsState()
} }
drawCurlyBrace(cs, notesStartX, braceTop, braceBottom)
val lineBottom = braceBottom
// ---- 3. Notes ---- // ---- 3. Notes ----
val lineTop = notesStartY + noteLineH * 0.85f val lineTop = notesStartY + noteLineH * 0.85f
rowTuos.forEachIndexed { colIdx, tuo -> rowTuos.forEachIndexed { colIdx, tuo ->
val x = marginX + colIdx * colWidth val x = notesStartX + colIdx * currentRowColWidth
val sepW = textWidth(customFont, noteFontSize, "|") val sepW = textWidth(customFont, noteFontSize, "|")
val noteX = when (tuo.sep0) { val noteX = when (tuo.sep0) {
"/", "|" -> { "/", "|" -> {
@ -936,7 +1073,7 @@ private suspend fun generatePdfToBytes(
} }
} }
drawTUOUnderlines(cs, tuo, customFont, noteFontSize, x, notesStartY, noteLineH, colWidth, customSpacings) drawTUOUnderlines(cs, tuo, customFont, noteFontSize, x, notesStartY, noteLineH, currentRowColWidth, customSpacings)
} }
// ---- 4. Paroles ---- // ---- 4. Paroles ----
@ -963,7 +1100,7 @@ private suspend fun generatePdfToBytes(
val stanzaNumW = try { lyricFont.getStringWidth(stanzaNumTxt) / 1000f * stanzaNumSize } catch (e: Exception) { 0f } val stanzaNumW = try { lyricFont.getStringWidth(stanzaNumTxt) / 1000f * stanzaNumSize } catch (e: Exception) { 0f }
cs.beginText(); cs.setFont(lyricFont, stanzaNumSize) cs.beginText(); cs.setFont(lyricFont, stanzaNumSize)
cs.setNonStrokingColor(0f, 0f, 0f) // ← remplace setNonStrokingColor(Color.BLACK) cs.setNonStrokingColor(0f, 0f, 0f) // ← remplace setNonStrokingColor(Color.BLACK)
cs.newLineAtOffset(marginX - stanzaNumW - 4f, currentYLyric) cs.newLineAtOffset(notesStartX - stanzaNumW - 4f, currentYLyric)
cs.showText(stanzaNumTxt); cs.endText() cs.showText(stanzaNumTxt); cs.endText()
// ── drawInOverrideSlot (closure locale) ─────────────────────── // ── drawInOverrideSlot (closure locale) ───────────────────────
@ -975,7 +1112,7 @@ private suspend fun generatePdfToBytes(
lineIdx: Int, lineIdx: Int,
allTemps: List<List<String>>, allTemps: List<List<String>>,
noteX: Float, noteX: Float,
colWidth: Float, colWidthPt: Float,
customFont: PDType0Font, customFont: PDType0Font,
lyricFontSize: Float, lyricFontSize: Float,
notesStartY: Float, notesStartY: Float,
@ -996,7 +1133,7 @@ private suspend fun generatePdfToBytes(
val vLi = getVirtualLineIndex(targetIdx, customSpacings) val vLi = getVirtualLineIndex(targetIdx, customSpacings)
notesStartY - ((vLi + 1) * noteLineH) + 2f notesStartY - ((vLi + 1) * noteLineH) + 2f
} }
val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidthPt, customFont, lyricFontSize)
val lyricX = noteX + offsetX val lyricX = noteX + offsetX
cs.saveGraphicsState() cs.saveGraphicsState()
@ -1011,14 +1148,14 @@ private suspend fun generatePdfToBytes(
// Syllabes // Syllabes
allTemps.forEachIndexed { sIdx, syllables -> allTemps.forEachIndexed { sIdx, syllables ->
val x = marginX + sIdx * colWidth val x = notesStartX + sIdx * currentRowColWidth
val noteX = if (rowTuos.getOrNull(sIdx)?.sep0 in listOf("/", "|")) x + 3f else x val noteX = if (rowTuos.getOrNull(sIdx)?.sep0 in listOf("/", "|")) x + 3f else x
val filledSlots = mutableSetOf<Int>() val filledSlots = mutableSetOf<Int>()
val isStandardLayout = customSpacings.all { it == 0 } val isStandardLayout = customSpacings.all { it == 0 }
syllables.forEachIndexed { lineIdx, rawSyl -> syllables.forEachIndexed { lineIdx, rawSyl ->
if (lineIdx == 0) { if (lineIdx == 0) {
val (spacedSyl, offsetX) = spacedSyllable(rawSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(rawSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
val lyricX = noteX + offsetX val lyricX = noteX + offsetX
cs.beginText() cs.beginText()
cs.setFont(lyricFont, lyricFontSize) cs.setFont(lyricFont, lyricFontSize)
@ -1041,8 +1178,8 @@ private suspend fun generatePdfToBytes(
if (prefixes.contains(1) && isAllZeroSpacing && lignePrincipaleEstLibre) { if (prefixes.contains(1) && isAllZeroSpacing && lignePrincipaleEstLibre) {
// FORCE LE DESSIN SUR LA LIGNE PRINCIPALE (SYL0) // FORCE LE DESSIN SUR LA LIGNE PRINCIPALE (SYL0)
val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/ val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (currentRowColWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/
cs.beginText() cs.beginText()
cs.setFont(if (lyricFont is PDType0Font) lyricFont else customFont, lyricFontSize) cs.setFont(if (lyricFont is PDType0Font) lyricFont else customFont, lyricFontSize)
@ -1054,7 +1191,7 @@ private suspend fun generatePdfToBytes(
val cleanSyl = cleanSyllable(rawSyl) val cleanSyl = cleanSyllable(rawSyl)
if (cleanSyl.isNotBlank()) { if (cleanSyl.isNotBlank()) {
val thisLineY = currentYLyric - lineIdx * extraSylLineH val thisLineY = currentYLyric - lineIdx * extraSylLineH
val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
val lyricX = noteX + offsetX val lyricX = noteX + offsetX
cs.beginText() cs.beginText()
cs.setFont(lyricFont, lyricFontSize) cs.setFont(lyricFont, lyricFontSize)
@ -1064,31 +1201,26 @@ private suspend fun generatePdfToBytes(
cs.endText() cs.endText()
} }
} else { } else {
val prefixes = REGEX_PREFIX_DIGITS2.findAll(rawSyl).map { it.groupValues[1].toInt() }.toList() val prefixes2 = REGEX_PREFIX_DIGITS2.findAll(rawSyl).map { it.groupValues[1].toInt() }.toList()
val cleanSyl = cleanSyllable(rawSyl)
val rawSyl0 = syllables.getOrNull(0) ?: ""
val cleanSyl0 = cleanSyllable(rawSyl0)
val lignePrincipaleEstLibre = !REGEX_HAS_LYRIC.containsMatchIn(cleanSyl0) ||
cleanSyl0.all { it == '―' || it == '-' || it == '—' }
val hasActualText = REGEX_HAS_LYRIC.containsMatchIn(cleanSyl) && val hasActualText = REGEX_HAS_LYRIC.containsMatchIn(cleanSyl) &&
!cleanSyl.all { it == '―' || it == '-' } !cleanSyl.all { it == '―' || it == '-' }
if (prefixes.isNotEmpty() && hasActualText) { if (prefixes2.isNotEmpty() && hasActualText) {
prefixes.forEach { voiceNum -> prefixes2.forEach { voiceNum ->
val targetIdx = voiceNum - 1 val targetIdx = voiceNum - 1
if (voiceNum == 1) { if (voiceNum == 1) {
if (lignePrincipaleEstLibre && !filledSlots.contains(-1)) { if (lignePrincipaleEstLibre && !filledSlots.contains(-1)) {
drawInOverrideSlot(cs, -1, cleanSyl, sIdx, lineIdx, allTemps, noteX, colWidth, drawInOverrideSlot(cs, -1, cleanSyl, sIdx, lineIdx, allTemps, noteX, currentRowColWidth,
customFont, lyricFontSize, currentYLyric, noteLineH, customSpacings, isDirectY = true) customFont, lyricFontSize, currentYLyric, noteLineH, customSpacings, isDirectY = true)
filledSlots.add(-1) filledSlots.add(-1)
} else if (customSpacings.getOrElse(0) { 0 } == 1 && !filledSlots.contains(0)) { } else if (customSpacings.getOrElse(0) { 0 } == 1 && !filledSlots.contains(0)) {
drawInOverrideSlot(cs, 0, cleanSyl, sIdx, lineIdx, allTemps, noteX, colWidth, drawInOverrideSlot(cs, 0, cleanSyl, sIdx, lineIdx, allTemps, noteX, currentRowColWidth,
customFont, lyricFontSize, notesStartY - yLyricOffset, noteLineH, customSpacings) customFont, lyricFontSize, notesStartY - yLyricOffset, noteLineH, customSpacings)
filledSlots.add(0) filledSlots.add(0)
} }
} else { } else {
if (customSpacings.getOrElse(targetIdx) { 0 } == 1 && !filledSlots.contains(targetIdx)) { if (customSpacings.getOrElse(targetIdx) { 0 } == 1 && !filledSlots.contains(targetIdx)) {
drawInOverrideSlot(cs, targetIdx, cleanSyl, sIdx, lineIdx, allTemps, noteX, colWidth, drawInOverrideSlot(cs, targetIdx, cleanSyl, sIdx, lineIdx, allTemps, noteX, currentRowColWidth,
customFont, lyricFontSize, notesStartY, noteLineH, customSpacings) customFont, lyricFontSize, notesStartY, noteLineH, customSpacings)
filledSlots.add(targetIdx) filledSlots.add(targetIdx)
} }

View file

@ -23,6 +23,7 @@ import java.awt.geom.GeneralPath
import java.awt.geom.PathIterator import java.awt.geom.PathIterator
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import kotlin.math.ceil
import java.io.File as JFile import java.io.File as JFile
@ -671,6 +672,74 @@ fun drawWatermark(
} }
} }
private fun collectVoiceLabelMap(tuoList: List<TimeUnitObject>): Map<Int, String> {
val aggregatedMarkers = mutableMapOf<Int, String>()
tuoList.take(10).forEach { tuo ->
tuo.voiceMarkers.forEach { (voiceNum, text) ->
if (text.isNotBlank() && !aggregatedMarkers.containsKey(voiceNum)) {
aggregatedMarkers[voiceNum] = text.trim()
}
}
}
return aggregatedMarkers.toSortedMap()
}
private fun computeVoiceLabelColumnWidth(
voiceLabelMap: Map<Int, String>,
italicFont: PDType0Font,
labelFontSize: Float,
satbBlockWidth: Float
): Float {
if (voiceLabelMap.isEmpty()) return 0f
var maxRequiredWidth = 0f
voiceLabelMap.values.forEach { rawLabel ->
val clean = rawLabel.trim()
if (clean.isEmpty()) return@forEach
val wordCount = clean.split(Regex("\\s+")).count { it.isNotEmpty() }
val measuredTextW = textWidth(italicFont, labelFontSize, clean)
val wordSpacingAllowance = (wordCount - 1).coerceAtLeast(0) * (labelFontSize * 0.35f)
val totalNeeded = measuredTextW + wordSpacingAllowance + 8f
if (totalNeeded > maxRequiredWidth) {
maxRequiredWidth = totalNeeded
}
}
return (maxRequiredWidth + satbBlockWidth).coerceAtLeast(65f)
}
private fun drawVoiceLabels(
cs: PDPageContentStream,
voiceLabelMap: Map<Int, String>,
italicFont: PDType0Font,
labelFontSize: Float,
startX: Float,
notesStartY: Float,
noteLineH: Float,
customSpacing: List<Int>
) {
if (voiceLabelMap.isEmpty()) return
val maxVoiceNum = maxOf(voiceLabelMap.keys.maxOrNull() ?: 4, 4)
val voiceNumbers = (1..maxVoiceNum).toList()
voiceNumbers.forEach { voiceNum ->
val labelText = voiceLabelMap[voiceNum]?.trim().orEmpty()
val voiceLineIndex = voiceNum - 1
val vLi = getVirtualLineIndex(voiceLineIndex, customSpacing)
val labelY = notesStartY - (vLi * noteLineH)
cs.saveGraphicsState()
cs.beginText()
cs.setFont(italicFont, labelFontSize)
cs.setNonStrokingColor(Color(80, 80, 80))
cs.newLineAtOffset(startX, labelY)
cs.showText(labelText.sanitize())
cs.endText()
cs.restoreGraphicsState()
}
}
actual fun rememberPdfExportAction( actual fun rememberPdfExportAction(
scope: CoroutineScope, scope: CoroutineScope,
fileRepository: FileRepository, fileRepository: FileRepository,
@ -718,12 +787,8 @@ private suspend fun generatePdfToBytes(
// "2.4.Mai" -> [2, 4] // "2.4.Mai" -> [2, 4]
val REGEX_PREFIX_DIGITS = Regex("(\\d+)\\.") val REGEX_PREFIX_DIGITS = Regex("(\\d+)\\.")
val REGEX_CLEAN = Regex("^(\\d+\\.)+")
fun getVoicesFromPrefix(syl: String): List<Int> { val REGEX_HAS_LYRIC = Regex("[a-zA-Z0-9]")
return REGEX_PREFIX_DIGITS.findAll(syl)
.map { it.groupValues[1].toInt() }
.toList()
}
val markerHeight = settings. markerHeight val markerHeight = settings. markerHeight
val noteFontSize = settings.noteFontSize val noteFontSize = settings.noteFontSize
@ -799,6 +864,34 @@ private suspend fun generatePdfToBytes(
// println("│ Final Col Count : $colCount") // println("│ Final Col Count : $colCount")
// println("│ Final Col Width : $finalColWidth pt") // println("│ Final Col Width : $finalColWidth pt")
// println("└──────────────────────────────────────────────────────────┘") // println("└──────────────────────────────────────────────────────────┘")
val hasVoiceLabels = tuoList.any { it.voiceMarkers.isNotEmpty() }
val voiceLabelMap = if (hasVoiceLabels) collectVoiceLabelMap(tuoList) else emptyMap()
val voiceLabelFontSize = noteFontSize * 0.85f
val satbLabelFont = if (lyricFont is PDType0Font) lyricFont else customFont
val satbLabelSize = noteFontSize * 0.85f
val maxSatbCharW = listOf("S", "A", "T", "B").maxOfOrNull {
textWidth(satbLabelFont, satbLabelSize, it)
} ?: 8f
val estimatedBraceW = 14f
val satbBlockWidth = if (hasVoiceLabels) maxSatbCharW + estimatedBraceW + 6f else 0f
val voiceLabelColumnWidth = if (hasVoiceLabels) {
computeVoiceLabelColumnWidth(
voiceLabelMap = voiceLabelMap,
italicFont = markerItalicFont,
labelFontSize = voiceLabelFontSize,
satbBlockWidth = satbBlockWidth
)
} else {
0f
}
val reductionCols = if (hasVoiceLabels && colWidth > 0f) {
ceil(voiceLabelColumnWidth / colWidth).toInt().coerceAtLeast(1)
} else {
0
}
val firstRowColCount = if (hasVoiceLabels) (colCount - reductionCols).coerceAtLeast(1) else colCount
val maxSylsSize = tuoList.maxOfOrNull { tuo -> // lyrics Alt val maxSylsSize = tuoList.maxOfOrNull { tuo -> // lyrics Alt
(1..nbStanza).maxOfOrNull { sz -> (1..nbStanza).maxOfOrNull { sz ->
@ -1055,7 +1148,20 @@ private suspend fun generatePdfToBytes(
!pitchPattern.containsMatchIn(noteContent) !pitchPattern.containsMatchIn(noteContent)
} }
} }
val allRows = tuoList.chunked(colCount)
val allRows: List<List<TimeUnitObject>> = buildList {
if (tuoList.isNotEmpty()) {
val firstChunkSize = minOf(tuoList.size, firstRowColCount)
add(tuoList.take(firstChunkSize))
var idx = firstChunkSize
while (idx < tuoList.size) {
val nextSize = minOf(tuoList.size - idx, colCount)
add(tuoList.subList(idx, idx + nextSize))
idx += nextSize
}
}
}
val rows = if (allRows.size > 1 && isRowEmptyOrSeparatorOnly(allRows.last())) { val rows = if (allRows.size > 1 && isRowEmptyOrSeparatorOnly(allRows.last())) {
allRows.dropLastWhile { isRowEmptyOrSeparatorOnly(it) } allRows.dropLastWhile { isRowEmptyOrSeparatorOnly(it) }
} else { } else {
@ -1072,6 +1178,17 @@ private suspend fun generatePdfToBytes(
val rows = if (hasTrailingBarlineRow) allRows.dropLast(1) else allRows*/ val rows = if (hasTrailingBarlineRow) allRows.dropLast(1) else allRows*/
rows.forEachIndexed { rowIdx, rowTuos -> rows.forEachIndexed { rowIdx, rowTuos ->
val isFirstRow = (rowIdx == 0)
val isFirstRowWithVoiceLabels = isFirstRow && hasVoiceLabels
val currentRowColCount = if (isFirstRowWithVoiceLabels) firstRowColCount else colCount
val notesStartX = if (isFirstRowWithVoiceLabels) marginX + voiceLabelColumnWidth else marginX
val currentRowUsableWidth = if (isFirstRowWithVoiceLabels) {
(usableWidth - voiceLabelColumnWidth).coerceAtLeast(1f)
} else {
usableWidth
}
val currentRowColWidth = currentRowUsableWidth / currentRowColCount
// println("Portée n°: $rowIdx: && rs ${rows.size}") // println("Portée n°: $rowIdx: && rs ${rows.size}")
val isLastVisualRow = rowIdx == rows.size - 1 val isLastVisualRow = rowIdx == rows.size - 1
val maxNoteLines = (rowTuos.maxOfOrNull { it.noteAsMultiString().split("\n").size } ?: 1) + 1 val maxNoteLines = (rowTuos.maxOfOrNull { it.noteAsMultiString().split("\n").size } ?: 1) + 1
@ -1244,16 +1361,20 @@ private suspend fun generatePdfToBytes(
// ---- 1. Marqueurs (si présents) ---- // ---- 1. Marqueurs (si présents) ----
if (rowHasMarkers) { if (rowHasMarkers) {
rowTuos.forEachIndexed { colIdx, tuo -> rowTuos.forEachIndexed { colIdx, tuo ->
val x = marginX + colIdx * colWidth val x = notesStartX + colIdx * currentRowColWidth
drawMarkers(cs, tuo, x, colWidth, y, markerBoldFont, markerItalicFont, markerEmmetFont, noteFontSize, emmentalerTTF) drawMarkers(
cs, tuo, x, currentRowColWidth, y,
markerBoldFont, markerItalicFont, markerEmmetFont,
noteFontSize, emmentalerTTF
)
// ➕ AJOUT ICI : hairpins (même boucle, mêmes coords !) // ➕ AJOUT ICI : hairpins (même boucle, mêmes coords !)
drawHairPinForTUO( drawHairPinForTUO(
cs = cs, cs = cs,
tuo = tuo, tuo = tuo,
gridColumnCount = colCount, gridColumnCount = currentRowColCount,
colX = x, colX = x,
colWidth = colWidth, colWidth = currentRowColWidth,
markerY = y, markerY = y,
noteLineH = noteLineH noteLineH = noteLineH
) )
@ -1262,16 +1383,26 @@ private suspend fun generatePdfToBytes(
// val customSpacings = listOf(1, 1, 1, 0) // 1 ligne vide après chaque voix // val customSpacings = listOf(1, 1, 1, 0) // 1 ligne vide après chaque voix
// ---- 2. Accolade et étiquettes SATB ---- // ---- 2. Voice label & Accolade et étiquettes SATB ----
val braceTop = notesStartY + noteLineH * 0.85f val braceTop = notesStartY + noteLineH * 0.85f
// val braceBottom = notesStartY - (maxNoteLines - 1) * noteLineH // val braceBottom = notesStartY - (maxNoteLines - 1) * noteLineH
val lastVoiceIdx = (maxNoteLines - 1).coerceIn(0, 3) val lastVoiceIdx = (maxNoteLines - 1).coerceIn(0, 3)
val totalVirtualSlots = getVirtualLineIndex(lastVoiceIdx, customSpacings) + 1 val totalVirtualSlots = getVirtualLineIndex(lastVoiceIdx, customSpacings) + 1
val braceBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH val braceBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH
drawCurlyBrace(cs, marginX, braceTop, braceBottom)
val lineBottom = braceBottom if (isFirstRowWithVoiceLabels) {
drawVoiceLabels(
cs = cs,
voiceLabelMap = voiceLabelMap,
italicFont = markerItalicFont,
labelFontSize = voiceLabelFontSize,
startX = marginX,
notesStartY = notesStartY,
noteLineH = noteLineH,
customSpacing = customSpacings
)
}
val voiceLabels = listOf("S", "A", "T", "B") val voiceLabels = listOf("S", "A", "T", "B")
val labelFont = if (lyricFont is PDType0Font) lyricFont else customFont val labelFont = if (lyricFont is PDType0Font) lyricFont else customFont
@ -1280,6 +1411,7 @@ private suspend fun generatePdfToBytes(
val braceW = ((braceTop - braceBottom) * 0.12f).coerceIn(8f, 22f) val braceW = ((braceTop - braceBottom) * 0.12f).coerceIn(8f, 22f)
val labelX = marginX - braceW - 3f val labelX = marginX - braceW - 3f
val satbRightEdge = notesStartX - braceW - 3f
voiceLabels.take(maxNoteLines).forEachIndexed { li, label -> voiceLabels.take(maxNoteLines).forEachIndexed { li, label ->
val vLi = getVirtualLineIndex(li, customSpacings) val vLi = getVirtualLineIndex(li, customSpacings)
val labelY = notesStartY - (vLi * noteLineH) val labelY = notesStartY - (vLi * noteLineH)
@ -1294,25 +1426,28 @@ private suspend fun generatePdfToBytes(
} }
cs.saveGraphicsState() cs.saveGraphicsState()
cs.beginText() cs.beginText()
cs.setFont(labelFont, labelSize) cs.setFont(satbLabelFont, satbLabelSize)
cs.setNonStrokingColor(labelColor) cs.setNonStrokingColor(labelColor)
cs.newLineAtOffset(labelX - textWidth(labelFont, labelSize, label), labelY) cs.newLineAtOffset(satbRightEdge - textWidth(satbLabelFont, satbLabelSize, label), labelY)
cs.showText(label) cs.showText(label)
cs.endText() cs.endText()
cs.restoreGraphicsState() cs.restoreGraphicsState()
} }
drawCurlyBrace(cs, notesStartX, braceTop, braceBottom)
// ---- 3. Notes ---- // ---- 3. Notes ----
// Calcul des positions des barres verticales (communes à toute la rangée) // Calcul des positions des barres verticales (communes à toute la rangée)
val lineBottom = braceBottom
val lineTop = notesStartY + noteLineH * 0.85f val lineTop = notesStartY + noteLineH * 0.85f
// val lineBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH // val lineBottom = notesStartY - (totalVirtualSlots - 1) * noteLineH
rowTuos.forEachIndexed { colIdx, tuo -> rowTuos.forEachIndexed { colIdx, tuo ->
val x = marginX + colIdx * colWidth val x = notesStartX + colIdx * currentRowColWidth
// on dessine à droite // on dessine à droite
if (hasTrailingBarlineRow && isLastVisualRow && colIdx == rowTuos.size - 1) { if (hasTrailingBarlineRow && isLastVisualRow && colIdx == rowTuos.size - 1) {
val finalX = x + colWidth val finalX = x + currentRowColWidth
val sepToDraw = allRows.last().first().sep0 val sepToDraw = allRows.last().first().sep0
cs.setStrokingColor(0f, 0f, 0f) cs.setStrokingColor(0f, 0f, 0f)
@ -1396,7 +1531,7 @@ private suspend fun generatePdfToBytes(
colX = x, colX = x,
y = notesStartY, y = notesStartY,
noteLineH = noteLineH, noteLineH = noteLineH,
colWidth = colWidth, colWidth = currentRowColWidth,
customSpacing = customSpacings customSpacing = customSpacings
) )
} }
@ -1457,7 +1592,7 @@ private suspend fun generatePdfToBytes(
cs.beginText() cs.beginText()
cs.setFont(stanzaNumFont, stanzaNumSize) cs.setFont(stanzaNumFont, stanzaNumSize)
cs.setNonStrokingColor(Color.BLACK) cs.setNonStrokingColor(Color.BLACK)
cs.newLineAtOffset(marginX - stanzaNumW - 4f, currentYLyric) cs.newLineAtOffset(notesStartX - stanzaNumW - 4f, currentYLyric)
cs.showText(stanzaNumTxt) cs.showText(stanzaNumTxt)
cs.endText() cs.endText()
@ -1517,7 +1652,7 @@ private suspend fun generatePdfToBytes(
allTemps.forEachIndexed { sIdx, syllables -> allTemps.forEachIndexed { sIdx, syllables ->
val x = marginX + sIdx * colWidth val x = notesStartX + sIdx * currentRowColWidth
val noteX = if (rowTuos.getOrNull(sIdx)?.sep0 in listOf("/", "|")) x + 3f else x val noteX = if (rowTuos.getOrNull(sIdx)?.sep0 in listOf("/", "|")) x + 3f else x
// On suit quels slots (0,1,2,3) ont déjà reçu du texte pour CETTE colonne // On suit quels slots (0,1,2,3) ont déjà reçu du texte pour CETTE colonne
@ -1531,9 +1666,9 @@ private suspend fun generatePdfToBytes(
if (lineIdx == 0) { if (lineIdx == 0) {
// SYL0 : On dessine normalement en bas (comportement standard) // SYL0 : On dessine normalement en bas (comportement standard)
val (spacedSyl, offsetX) = spacedSyllable(rawSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(rawSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
// val lyricX = if (alignLeft) noteX else noteX + colWidth - textWidth(customFont, lyricFontSize, spacedSyl) // val lyricX = if (alignLeft) noteX else noteX + currentRowColWidth - textWidth(customFont, lyricFontSize, spacedSyl)
val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/ val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (currentRowColWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/
cs.beginText() cs.beginText()
cs.setFont(if (lyricFont is PDType0Font) lyricFont else customFont, lyricFontSize) cs.setFont(if (lyricFont is PDType0Font) lyricFont else customFont, lyricFontSize)
@ -1555,7 +1690,7 @@ private suspend fun generatePdfToBytes(
if (prefixes.contains(1) && isAllZeroSpacing && syl0LyricsIsFree) { if (prefixes.contains(1) && isAllZeroSpacing && syl0LyricsIsFree) {
println("DEBUG: Force SYL1 sur ligne principale (Rouge) -> $cleanSyl") println("DEBUG: Force SYL1 sur ligne principale (Rouge) -> $cleanSyl")
val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/ val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/
cs.saveGraphicsState() cs.saveGraphicsState()
@ -1573,7 +1708,7 @@ private suspend fun generatePdfToBytes(
if (cleanSyl.isNotBlank()) { if (cleanSyl.isNotBlank()) {
val thisLineY = currentYLyric - lineIdx * extraSylLineH val thisLineY = currentYLyric - lineIdx * extraSylLineH
val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, colWidth, customFont, lyricFontSize) val (spacedSyl, offsetX) = spacedSyllable(cleanSyl, allTemps, sIdx, lineIdx, currentRowColWidth, customFont, lyricFontSize)
val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/ val lyricX = noteX + offsetX /*if (alignLeft) noteX else noteX + (colWidth / 2f) - (textWidth(customFont, lyricFontSize, spacedSyl) / 2f)*/
cs.beginText() cs.beginText()
@ -1612,7 +1747,7 @@ private suspend fun generatePdfToBytes(
lineIdx, lineIdx,
allTemps, allTemps,
noteX, noteX,
colWidth, currentRowColWidth,
customFont, customFont,
lyricFontSize, lyricFontSize,
notesStartY - yLyricOffset, notesStartY - yLyricOffset,
@ -1627,7 +1762,7 @@ private suspend fun generatePdfToBytes(
targetIdx targetIdx
)) { )) {
drawInOverrideSlot( drawInOverrideSlot(
cs, targetIdx, cleanSyl, sIdx, lineIdx, allTemps, noteX, colWidth, cs, targetIdx, cleanSyl, sIdx, lineIdx, allTemps, noteX, currentRowColWidth,
customFont, lyricFontSize, notesStartY, noteLineH, customSpacings customFont, lyricFontSize, notesStartY, noteLineH, customSpacings
) )
filledSlots.add(targetIdx) filledSlots.add(targetIdx)