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 @@ -20,6 +20,7 @@ object Links {
const val FEATURES_URL = "$GITHUB/blob/main/docs/FEATURES.md"
const val KEYCODES_URL = "$FEATURES_URL#30-comprehensive-keycodes--actions-reference"
const val TEXT_EXPANDER_GUIDE_URL = "$FEATURES_URL#12-versatile-text-expander--modifiers"
const val CUSTOM_TEXT_STYLES_GUIDE_URL = "$FEATURES_URL#46-custom-text-styles"
// Original HeliBoard wiki and community links
const val ORIGINAL_GITHUB = "https://github.com/Helium314/HeliBoard"
const val LAYOUT_WIKI_URL = "$ORIGINAL_GITHUB/wiki/2.-Layouts"
Expand Down
17 changes: 16 additions & 1 deletion app/src/main/java/helium314/keyboard/latin/common/StringUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,22 @@ fun getFullEmojiAtEnd(text: CharSequence): String {
}
val result = s.substring(offset)
if (isEmoji(result)) return result
return if (offset == 0) result else s.substring(s.length - Character.charCount(lastCodepoint))
// Reaching the start of the text only means that everything before the cursor consists of codepoints that
// might be emoji. That is also true for circled letters, arrows or math symbols, and deleting all of those
// at once is wrong, so keep the whole text only if it has emoji sequence parts.
return if (offset == 0 && hasEmojiSequenceParts(result)) result else s.substring(s.length - Character.charCount(lastCodepoint))
}

/** Whether [s] contains something that joins or modifies emoji: ZWJ, variation selector, keycap, skin tone, flag letter, tag. */
private fun hasEmojiSequenceParts(s: String): Boolean {
var i = 0
while (i < s.length) {
val cp = s.codePointAt(i)
if (cp == 0x200D || cp == 0xFE0F || cp == 0xFE0E || cp == 0x20E3
|| cp in 0x1F3FB..0x1F3FF || cp in 0x1F1E6..0x1F1FF || cp in 0xE0020..0xE007F) return true
i += Character.charCount(cp)
}
return false
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -683,20 +683,20 @@ object UnicodeStyleEngine {
/** 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)
return raw.lineSequence().filter { it.isNotBlank() }.withIndex().all { (index, line) ->
val parsed = parseCustomStyleLine(line, index)
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,
* Each line is `Name: <letters>` (the colon may be full-width, the name may be left out), 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
return raw.lineSequence().filter { it.isNotBlank() }.withIndex().mapNotNull { (index, line) ->
val (name, cps) = parseCustomStyleLine(line, index) ?: 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')])
Expand All @@ -717,19 +717,27 @@ object UnicodeStyleEngine {
}.toList()
}

private fun parseCustomStyleLine(line: String): Pair<String, IntArray>? {
/**
* Characters that pasting often adds without being visible: variation selectors (e.g. after circled M, which is
* also an emoji) and format characters such as zero-width space, joiner and BOM. They would change the count.
*/
private fun isInvisibleFormatting(cp: Int): Boolean =
cp in 0xFE00..0xFE0F || cp in 0xE0100..0xE01EF || Character.getType(cp) == Character.FORMAT.toInt()

/** [index] is the position among the non-blank lines, used to name a line that is only an alphabet. */
private fun parseCustomStyleLine(line: String, index: Int): 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()
// a bare pasted alphabet without "Name:" still works and gets a generated name
val name = if (colon < 0) "Custom ${index + 1}" else line.substring(0, colon).trim()
if (name.isEmpty()) return null
// plain loop: String.codePoints() and IntStream need API 24, the app supports API 21/23
val rest = line.substring(colon + 1)
val rest = if (colon < 0) line else line.substring(colon + 1)
val cps = ArrayList<Int>(62)
var i = 0
while (i < rest.length) {
val cp = rest.codePointAt(i)
if (!Character.isWhitespace(cp)) cps.add(cp)
if (!Character.isWhitespace(cp) && !isInvisibleFormatting(cp)) cps.add(cp)
i += Character.charCount(cp)
}
return if (cps.size == 52 || cps.size == 62) name to cps.toIntArray() else null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -408,10 +408,11 @@ class SuggestionStripView(context: Context, attrs: AttributeSet?, defStyle: Int)
} else {
val mode = Settings.getValues().mToolbarMode
val isPassword = Settings.getValues().mInputAttributes.mIsPasswordField
val suppressToolbarForAutofill = isExternalSuggestionVisible && (isPassword || !isToolbarManuallyOpen)
// the voice status must stay visible even when the toolbar was opened manually (typing a recognized piece updates the strip)
val suppressToolbarForAutofill = isExternalSuggestionVisible && (isPassword || !isToolbarManuallyOpen || isVoiceActive)
val forceToolbar = mode == ToolbarMode.TOOLBAR_KEYS && !suppressToolbarForAutofill
val effectiveToolbarVisible = !suppressToolbarForAutofill && (forceToolbar || toolbarVisible)
val showPinned = !locked && !effectiveToolbarVisible && mode != ToolbarMode.SUGGESTION_STRIP
val showPinned = !locked && !effectiveToolbarVisible && mode != ToolbarMode.SUGGESTION_STRIP && !isVoiceActive
val duration = Settings.getAnimationDuration(60)
val prevToolbarVisible = toolbarContainer.isVisible
val nextToolbarVisible = !locked && effectiveToolbarVisible
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ fun TextInputPreference(
checkTextValid: (String) -> Boolean = { true },
singleLine: Boolean = true,
showValue: Boolean = true,
neutralButtonText: String? = null,
onNeutral: () -> Unit = { },
onConfirmed: (String) -> Unit = { }
) {
var showDialog by rememberSaveable { mutableStateOf(false) }
Expand All @@ -44,7 +46,9 @@ fun TextInputPreference(
initialText = prefs.getString(setting.key, default) ?: "",
title = { Text(setting.title) },
checkTextValid = checkTextValid,
singleLine = singleLine
singleLine = singleLine,
neutralButtonText = neutralButtonText,
onNeutral = onNeutral
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import android.content.Intent
import android.net.Uri
import androidx.compose.ui.platform.LocalContext
import helium314.keyboard.latin.common.Links
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.res.painterResource
Expand Down Expand Up @@ -179,10 +182,17 @@ fun createToolbarSettings(context: Context): List<Setting> {
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 ->
val ctx = LocalContext.current
TextInputPreference(
setting, Defaults.PREF_CUSTOM_TEXT_STYLES,
checkTextValid = { it.isBlank() || UnicodeStyleEngine.isValidCustomStylesText(it) },
singleLine = false, showValue = false
singleLine = false, showValue = false,
neutralButtonText = stringResource(R.string.libraries_features_guide_title),
onNeutral = {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Links.CUSTOM_TEXT_STYLES_GUIDE_URL))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { ctx.startActivity(intent) }
}
)
},
Setting(context, Settings.PREF_TOOLBAR_KEYS_ALIGNMENT, R.string.toolbar_keys_alignment, R.string.toolbar_keys_alignment_summary) { setting ->
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1769,9 +1769,9 @@
<string name="voice_futo_models_summary">نماذج Whisper المضبوطة بدقة والمُحسّنة للإملاء على الهاتف المحمول</string>
<string name="button_browse">تصفح</string>
<string name="voice_transcribe_while_speaking_title">نسخ أثناء التحدث</string>
<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>
<string name="voice_transcribe_while_speaking_summary">انتظار أقصر للإملاءات الطويلة</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-be/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1746,9 +1746,9 @@
<string name="voice_futo_models_summary">Дакладна наладжаныя мадэлі Whisper, аптымізаваныя для мабільнай дыктоўкі</string>
<string name="button_browse">Праглядзіце</string>
<string name="voice_transcribe_while_speaking_title">Расшыфроўка падчас размовы</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Карацей чакаць доўгіх дыктовак</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-bg/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1746,9 +1746,9 @@
<string name="voice_futo_models_summary">Фино настроени модели Whisper, оптимизирани за мобилно диктовка</string>
<string name="button_browse">Прегледайте</string>
<string name="voice_transcribe_while_speaking_title">Транскрибирайте, докато говорите</string>
<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>
<string name="voice_transcribe_while_speaking_summary">По-кратко изчакване за дълги диктовки</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-cs/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1711,9 +1711,9 @@ Umožňuje lokální inferenci GGUF / llama.cpp na zařízení pro korektury a p
<string name="voice_futo_models_summary">Vyladěné modely Whisper optimalizované pro mobilní diktování</string>
<string name="button_browse">Prohlížet</string>
<string name="voice_transcribe_while_speaking_title">Přepisujte při mluvení</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Kratší čekání na dlouhé diktáty</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1761,10 +1761,10 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben
<string name="voice_futo_models_summary">Fein abgestimmte Whisper-Modelle, optimiert für mobiles Diktieren</string>
<string name="button_browse">Durchsuchen</string>
<string name="voice_transcribe_while_speaking_title">Schon beim Sprechen erkennen</string>
<string name="voice_transcribe_while_speaking_summary">Bei jeder Sprechpause wird das bisher Gesagte schon erkannt. Nach dem Stopp bleibt nur das letzte Stück: viel kürzeres Warten bei langen Diktaten.</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Kürzere Wartezeiten bei langen Diktaten</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-el/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1812,9 +1812,9 @@
<string name="voice_futo_models_summary">Βελτιστοποιημένα μοντέλα Whisper βελτιστοποιημένα για υπαγόρευση μέσω κινητού</string>
<string name="button_browse">Ξεφυλλίζω</string>
<string name="voice_transcribe_while_speaking_title">Μεταγραφή ενώ μιλάτε</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Συντομότερη αναμονή για μεγάλες υπαγορεύσεις</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-es-rUS/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1778,9 +1778,9 @@ Permite la inferencia GGUF / llama.cpp en el dispositivo para corrección y rees
<string name="voice_futo_models_summary">Modelos Whisper optimizados para dictado móvil</string>
<string name="button_browse">Navegar</string>
<string name="voice_transcribe_while_speaking_title">Transcribe mientras hablas</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Espera más corta para dictados largos</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1708,9 +1708,9 @@ Permite la inferencia GGUF / llama.cpp en el dispositivo para corrección y rees
<string name="voice_futo_models_summary">Modelos Whisper optimizados para dictado móvil</string>
<string name="button_browse">Navegar</string>
<string name="voice_transcribe_while_speaking_title">Transcribe mientras hablas</string>
<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>
<string name="voice_transcribe_while_speaking_summary">Espera más corta para dictados largos</string>
</resources>
Loading
Loading