Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ object Defaults {
const val PREF_REMOVE_REDUNDANT_POPUPS = true
const val PREF_SPACE_BAR_TEXT = ""
const val PREF_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss"
const val PREF_CUSTOM_TEXT_STYLES = ""
const val PREF_EMOJI_RECENT_KEYS = ""
const val PREF_LAST_SHOWN_EMOJI_CATEGORY_PAGE_ID = 0
const val PREF_SHOW_DEBUG_SETTINGS = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ class Settings private constructor() : SharedPreferences.OnSharedPreferenceChang
try {
val prefs = mPrefs ?: appContext.prefs().also { mPrefs = it }
Log.i(TAG, "loadSettings")
helium314.keyboard.latin.style.UnicodeStyleEngine.setCustomStyles(prefs.getString(PREF_CUSTOM_TEXT_STYLES, Defaults.PREF_CUSTOM_TEXT_STYLES) ?: "")
val actualLocale = locale ?: context.resources.configuration.locale()
mSettingsValues = runInLocale(appContext, actualLocale) { ctx ->
SettingsValues(ctx, prefs, ctx.resources, inputAttributes, currentKeyboardScript)
Expand Down Expand Up @@ -575,6 +576,7 @@ class Settings private constructor() : SharedPreferences.OnSharedPreferenceChang
const val PREF_REMOVE_REDUNDANT_POPUPS = "remove_redundant_popups"
const val PREF_SPACE_BAR_TEXT = "space_bar_text"
const val PREF_TIMESTAMP_FORMAT = "timestamp_format"
const val PREF_CUSTOM_TEXT_STYLES = "custom_text_styles"
const val PREF_TOOLBAR_MODE = "toolbar_mode"
const val PREF_TOOLBAR_HIDING_GLOBAL = "toolbar_hiding_global"
const val PREF_SPLIT_TOOLBAR = "split_toolbar"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,20 @@ import helium314.keyboard.latin.utils.InputTypeUtils
*/
object UnicodeStyleEngine {

val STYLES: List<StyleDefinition> by lazy { initializeStyles() }
private val STYLES_BY_ID: Map<String, StyleDefinition> by lazy { STYLES.associateBy { it.id } }
private val REVERSE_MAP: Map<Int, Int> by lazy { initializeReverseMap() }
/** Built-in styles plus user-defined ones, with lookups derived from them. Replaced as a whole, never mutated. */
private class StyleSet(val styles: List<StyleDefinition>) {
val byId: Map<String, StyleDefinition> = styles.associateBy { it.id }
val reverse: Map<Int, Int> = buildReverseMap(styles)
}

private val builtinStyles: List<StyleDefinition> by lazy { initializeStyles() }
@Volatile private var styleSet: StyleSet? = null
private var customStylesRaw = ""

private fun currentSet(): StyleSet =
styleSet ?: synchronized(this) { styleSet ?: StyleSet(builtinStyles + parseCustomStyles(customStylesRaw)).also { styleSet = it } }

val STYLES: List<StyleDefinition> get() = currentSet().styles

var activeLiveStyleId: String? = null

Expand Down Expand Up @@ -49,12 +60,12 @@ object UnicodeStyleEngine {
* Checks whether a codepoint is a styled Unicode character or combining mark.
*/
fun isStyledCharacter(codePoint: Int): Boolean {
return REVERSE_MAP.containsKey(codePoint) || isCombiningMark(codePoint)
return currentSet().reverse.containsKey(codePoint) || isCombiningMark(codePoint)
}

fun getStyle(styleId: String): StyleDefinition? = STYLES_BY_ID[styleId]
fun getStyle(styleId: String): StyleDefinition? = currentSet().byId[styleId]

fun getAllStyles(): List<StyleDefinition> = STYLES
fun getAllStyles(): List<StyleDefinition> = currentSet().styles

/**
* Transforms an entire text string to the target style safely.
Expand Down Expand Up @@ -101,6 +112,7 @@ object UnicodeStyleEngine {
* Strips styling and combining marks, reverting styled Unicode back to plain text.
*/
fun toPlainText(styledText: String): String {
val reverse = currentSet().reverse
val sb = StringBuilder(styledText.length)
var i = 0
val len = styledText.length
Expand All @@ -110,7 +122,7 @@ object UnicodeStyleEngine {
i += Character.charCount(cp)
continue
}
val plain = REVERSE_MAP[cp] ?: cp
val plain = reverse[cp] ?: cp
sb.appendCodePoint(plain)
i += Character.charCount(cp)
}
Expand Down Expand Up @@ -656,15 +668,74 @@ object UnicodeStyleEngine {
)
}

private fun initializeReverseMap(): Map<Int, Int> {
/**
* Replaces the user-defined styles. Called whenever settings are (re)loaded, so it must be cheap
* when nothing changed. See [parseCustomStyles] for the accepted format.
*/
fun setCustomStyles(raw: String) {
synchronized(this) {
if (raw == customStylesRaw && styleSet != null) return
customStylesRaw = raw
styleSet = null
}
}

/** True if [raw] is empty or every non-blank line is a valid style definition with a unique name. */
fun isValidCustomStylesText(raw: String): Boolean {
val names = HashSet<String>()
return raw.lineSequence().filter { it.isNotBlank() }.all { line ->
val parsed = parseCustomStyleLine(line)
parsed != null && names.add(parsed.first)
}
}

/**
* Each line is `Name: <letters>` (the colon may be full-width), where the letters (whitespace ignored) are the styled A-Z, then a-z,
* optionally followed by 0-9, i.e. 52 or 62 characters. Invalid or duplicate lines are skipped.
*/
private fun parseCustomStyles(raw: String): List<StyleDefinition> {
val seen = HashSet<String>()
return raw.lineSequence().filter { it.isNotBlank() }.mapNotNull { line ->
val (name, cps) = parseCustomStyleLine(line) ?: return@mapNotNull null
if (!seen.add(name)) return@mapNotNull null
val sample = StringBuilder()
for (c in "Abc") sample.appendCodePoint(cps[if (c.isUpperCase()) c - 'A' else 26 + (c - 'a')])
StyleDefinition(
id = "custom_$name",
name = name,
category = StyleCategory.DECORATIVE,
samplePreview = sample.toString(),
mapCodePoint = { cp ->
when (cp) {
in 'A'.code..'Z'.code -> cps[cp - 'A'.code]
in 'a'.code..'z'.code -> cps[26 + cp - 'a'.code]
in '0'.code..'9'.code -> if (cps.size == 62) cps[52 + cp - '0'.code] else cp
else -> cp
}
}
)
}.toList()
}

private fun parseCustomStyleLine(line: String): Pair<String, IntArray>? {
// also accept the full-width colon that CJK keyboards type
val colon = line.indexOfFirst { it == ':' || it == '\uFF1A' }
if (colon < 0) return null
val name = line.substring(0, colon).trim()
if (name.isEmpty()) return null
val cps = line.substring(colon + 1).codePoints().filter { !Character.isWhitespace(it) }.toArray()
return if (cps.size == 52 || cps.size == 62) name to cps else null
}

private fun buildReverseMap(styles: List<StyleDefinition>): Map<Int, Int> {
val reverse = HashMap<Int, Int>(2048)
val testChars = StringBuilder()
for (c in 'a'..'z') testChars.append(c)
for (c in 'A'..'Z') testChars.append(c)
for (c in '0'..'9') testChars.append(c)
testChars.append("+-=() .,?!'\"<>_")

for (style in STYLES) {
for (style in styles) {
if (style.combiningMark != 0) continue
var i = 0
val len = testChars.length
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ fun TextInputPreference(
default: String,
@DrawableRes icon: Int = 0,
checkTextValid: (String) -> Boolean = { true },
singleLine: Boolean = true,
showValue: Boolean = true,
onConfirmed: (String) -> Unit = { }
) {
var showDialog by rememberSaveable { mutableStateOf(false) }
Expand All @@ -29,7 +31,7 @@ fun TextInputPreference(
name = setting.title,
icon = icon.takeIf { it != 0 },
onClick = { showDialog = true },
description = prefs.getString(setting.key, default)?.takeIf { it.isNotEmpty() }
description = if (showValue) prefs.getString(setting.key, default)?.takeIf { it.isNotEmpty() } else null
)
if (showDialog) {
TextInputDialog(
Expand All @@ -41,7 +43,8 @@ fun TextInputPreference(
},
initialText = prefs.getString(setting.key, default) ?: "",
title = { Text(setting.title) },
checkTextValid = checkTextValid
checkTextValid = checkTextValid,
singleLine = singleLine
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import helium314.keyboard.latin.BuildConfig
import helium314.keyboard.latin.R
import helium314.keyboard.latin.settings.Defaults
import helium314.keyboard.latin.settings.Settings
import helium314.keyboard.latin.style.UnicodeStyleEngine
import helium314.keyboard.settings.preferences.TextInputPreference
import helium314.keyboard.latin.utils.Log
import helium314.keyboard.latin.utils.ToolbarMode
import helium314.keyboard.latin.utils.dpToPx
Expand Down Expand Up @@ -82,6 +84,7 @@ fun ToolbarScreen(
Settings.PREF_TOOLBAR_KEYS,
Settings.PREF_PINNED_TOOLBAR_KEYS,
Settings.PREF_CLIPBOARD_TOOLBAR_KEYS,
Settings.PREF_CUSTOM_TEXT_STYLES,
if (BuildConfig.FLAVOR == "standard" || BuildConfig.FLAVOR == "standardfull")
Settings.PREF_SHOW_DOWNLOAD_BUTTON_IN_TOOLBAR else null,
Settings.PREF_EXPAND_FINE_TUNE_TOOLBAR,
Expand Down Expand Up @@ -175,6 +178,13 @@ fun createToolbarSettings(context: Context): List<Setting> {
Setting(context, Settings.PREF_CLIPBOARD_TOOLBAR_KEYS, R.string.clipboard_toolbar_keys) {
ReorderSwitchPreference(it, Defaults.PREF_CLIPBOARD_TOOLBAR_KEYS, filter)
},
Setting(context, Settings.PREF_CUSTOM_TEXT_STYLES, R.string.custom_text_styles_title, R.string.custom_text_styles_summary) { setting ->
TextInputPreference(
setting, Defaults.PREF_CUSTOM_TEXT_STYLES,
checkTextValid = { it.isBlank() || UnicodeStyleEngine.isValidCustomStylesText(it) },
singleLine = false, showValue = false
)
},
Setting(context, Settings.PREF_TOOLBAR_KEYS_ALIGNMENT, R.string.toolbar_keys_alignment, R.string.toolbar_keys_alignment_summary) { setting ->
val items = listOf(
stringResource(R.string.toolbar_keys_alignment_left) to "left",
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1772,4 +1772,6 @@
<string name="voice_transcribe_while_speaking_summary">في كل توقف في الكلام، يتم بالفعل نسخ الجزء الذي تم التحدث به حتى الآن. بعد التوقف، بقي الجزء الأخير فقط: انتظار الإملاءات الطويلة أقصر بكثير.</string>
<string name="voice_piecewise_field_changed">توقف الإملاء: تم تغيير حقل النص، ولم يتم إدراج الباقي</string>
<string name="settings_search_show_in_screen">تظهر في شاشته</string>
<string name="custom_text_styles_title">أنماط النص المخصصة</string>
<string name="custom_text_styles_summary">نمط واحد لكل سطر. التنسيق: الاسم: بالنمط A-Z a-z 0-9 (52 أو 62 حرفًا).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-be/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1749,4 +1749,6 @@
<string name="voice_transcribe_while_speaking_summary">Пры кожнай паўзе ў маўленні прамоўленая частка ўжо транскрыбуецца. Пасля прыпынку застаецца толькі апошняя частка: доўгія дыктоўкі чакаюць значна карацей.</string>
<string name="voice_piecewise_field_changed">Дыктоўка спынена: тэкставае поле змянілася, астатняе не ўстаўлена</string>
<string name="settings_search_show_in_screen">Паказаць на сваім экране</string>
<string name="custom_text_styles_title">Карыстальніцкія стылі тэксту</string>
<string name="custom_text_styles_summary">Адзін стыль на радок. Фармат: Імя: у стылі A-Z a-z 0-9 (52 або 62 сімвалы).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-bg/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1749,4 +1749,6 @@
<string name="voice_transcribe_while_speaking_summary">При всяка пауза в речта изречената до момента част вече е транскрибирана. След спиране остава само последната част: много по-кратко изчакване за дълги диктовки.</string>
<string name="voice_piecewise_field_changed">Диктовката е спряна: текстовото поле е променено, останалото не е вмъкнато</string>
<string name="settings_search_show_in_screen">Показване на екрана му</string>
<string name="custom_text_styles_title">Персонализирани текстови стилове</string>
<string name="custom_text_styles_summary">Един стил на ред. Формат: Име: стилизирано A-Z a-z 0-9 (52 или 62 знака).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-cs/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1714,4 +1714,6 @@ Umožňuje lokální inferenci GGUF / llama.cpp na zařízení pro korektury a p
<string name="voice_transcribe_while_speaking_summary">Při každé pauze v řeči je dosud mluvená část již přepsána. Po zastavení zbývá už jen poslední část: mnohem kratší čekání na dlouhé diktáty.</string>
<string name="voice_piecewise_field_changed">Diktování zastaveno: textové pole se změnilo, zbytek nebyl vložen</string>
<string name="settings_search_show_in_screen">Zobrazit na jeho obrazovce</string>
<string name="custom_text_styles_title">Vlastní styly textu</string>
<string name="custom_text_styles_summary">Jeden styl na řádek. Formát: Název: stylizovaný A-Z a-z 0-9 (52 nebo 62 znaků).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1765,4 +1765,6 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben
<string name="voice_piecewise_field_changed">Diktat beendet: Das Textfeld hat gewechselt, der Rest wurde nicht eingefügt</string>
<!-- Long press on a search result in the settings (accessibility action) -->
<string name="settings_search_show_in_screen">Auf seiner Seite zeigen</string>
<string name="custom_text_styles_title">Benutzerdefinierte Textstile</string>
<string name="custom_text_styles_summary">Ein Stil pro Zeile. Format: Name: Stil A-Z a-z 0-9 (52 oder 62 Zeichen).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-el/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1815,4 +1815,6 @@
<string name="voice_transcribe_while_speaking_summary">Σε κάθε παύση στην ομιλία το μέρος που ειπώθηκε μέχρι τώρα έχει ήδη μεταγραφεί. Μετά τη διακοπή, απομένει μόνο το τελευταίο μέρος: πολύ μικρότερη αναμονή για μεγάλες υπαγορεύσεις.</string>
<string name="voice_piecewise_field_changed">Η υπαγόρευση σταμάτησε: το πεδίο κειμένου άλλαξε, το υπόλοιπο δεν εισήχθη</string>
<string name="settings_search_show_in_screen">Εμφάνιση στην οθόνη του</string>
<string name="custom_text_styles_title">Προσαρμοσμένα στυλ κειμένου</string>
<string name="custom_text_styles_summary">Ένα στυλ ανά γραμμή. Μορφή: Όνομα: στυλ A-Z a-z 0-9 (52 ή 62 χαρακτήρες).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-es-rUS/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1781,4 +1781,6 @@ Permite la inferencia GGUF / llama.cpp en el dispositivo para corrección y rees
<string name="voice_transcribe_while_speaking_summary">En cada pausa del discurso ya se transcribe la parte hablada hasta el momento. Después de parar, sólo queda la última parte: una espera mucho más corta para dictados largos.</string>
<string name="voice_piecewise_field_changed">Dictado detenido: el campo de texto cambió, el resto no fue insertado</string>
<string name="settings_search_show_in_screen">Mostrar en su pantalla</string>
<string name="custom_text_styles_title">Estilos de texto personalizados</string>
<string name="custom_text_styles_summary">Un estilo por línea. Formato: Nombre: estilo A-Z a-z 0-9 (52 o 62 caracteres).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1711,4 +1711,6 @@ Permite la inferencia GGUF / llama.cpp en el dispositivo para corrección y rees
<string name="voice_transcribe_while_speaking_summary">En cada pausa del discurso ya se transcribe la parte hablada hasta el momento. Después de parar, sólo queda la última parte: una espera mucho más corta para dictados largos.</string>
<string name="voice_piecewise_field_changed">Dictado detenido: el campo de texto cambió, el resto no fue insertado</string>
<string name="settings_search_show_in_screen">Mostrar en su pantalla</string>
<string name="custom_text_styles_title">Estilos de texto personalizados</string>
<string name="custom_text_styles_summary">Un estilo por línea. Formato: Nombre: estilo A-Z a-z 0-9 (52 o 62 caracteres).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-et/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1749,4 +1749,6 @@ Võimaldab seadmesisese GGUF / llama.cpp järelduse korrektuuri ja ümbersõnast
<string name="voice_transcribe_while_speaking_summary">Igal kõnepausil on seni räägitud osa juba transkribeeritud. Pärast peatumist on jäänud vaid viimane osa: pikkade dikteerimiste jaoks palju lühem ootamine.</string>
<string name="voice_piecewise_field_changed">Dikteerimine peatus: tekstiväli muutus, ülejäänud jäi sisestamata</string>
<string name="settings_search_show_in_screen">Kuva selle ekraanil</string>
<string name="custom_text_styles_title">Kohandatud tekstistiilid</string>
<string name="custom_text_styles_summary">Üks stiil rea kohta. Vorming: Nimi: stiilis A-Z a-z 0-9 (52 või 62 tähemärki).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1770,4 +1770,6 @@ Permet l\'inférence GGUF / llama.cpp sur l\'appareil pour la correction et la r
<string name="voice_transcribe_while_speaking_summary">A chaque pause dans le discours, la partie prononcée jusqu\'à présent est déjà transcrite. Après l\'arrêt, il ne reste que la dernière partie : attente beaucoup plus courte pour les longues dictées.</string>
<string name="voice_piecewise_field_changed">Dictée arrêtée : le champ de texte a changé, le reste n\'a pas été inséré</string>
<string name="settings_search_show_in_screen">Afficher sur son écran</string>
<string name="custom_text_styles_title">Styles de texte personnalisés</string>
<string name="custom_text_styles_summary">Un style par ligne. Format : Nom : stylisé A-Z a-z 0-9 (52 ou 62 caractères).</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-hi/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1741,4 +1741,6 @@
<string name="voice_transcribe_while_speaking_summary">भाषण में प्रत्येक विराम पर अब तक बोला गया भाग पहले ही प्रतिलेखित हो चुका होता है। रुकने के बाद, केवल अंतिम भाग ही बचा है: लंबे श्रुतलेखों के लिए बहुत कम प्रतीक्षा।</string>
<string name="voice_piecewise_field_changed">डिक्टेशन बंद हो गया: टेक्स्ट फ़ील्ड बदल गया, बाकी नहीं डाला गया</string>
<string name="settings_search_show_in_screen">इसकी स्क्रीन में दिखाएँ</string>
<string name="custom_text_styles_title">कस्टम पाठ शैलियाँ</string>
<string name="custom_text_styles_summary">प्रति पंक्ति एक शैली. प्रारूप: नाम: शैली A-Z a-z 0-9 (52 या 62 अक्षर)।</string>
</resources>
Loading
Loading