-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathKeyboardUIManager.kt
More file actions
995 lines (875 loc) · 41.5 KB
/
Copy pathKeyboardUIManager.kt
File metadata and controls
995 lines (875 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
// SPDX-License-Identifier: GPL-3.0-or-later
package be.scri.helpers.ui
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.graphics.toColorInt
import be.scri.R
import be.scri.R.color.white
import be.scri.databinding.InputMethodViewBinding
import be.scri.helpers.KeyboardBase
import be.scri.helpers.LanguageMappingConstants.conjugatePlaceholder
import be.scri.helpers.LanguageMappingConstants.getLanguageAlias
import be.scri.helpers.LanguageMappingConstants.pluralPlaceholder
import be.scri.helpers.LanguageMappingConstants.translatePlaceholder
import be.scri.helpers.PreferencesHelper
import be.scri.helpers.PreferencesHelper.getIsDarkModeOrNot
import be.scri.helpers.english.ENInterfaceVariables.ALREADY_PLURAL_MSG
import be.scri.services.GeneralKeyboardIME
import be.scri.services.GeneralKeyboardIME.ScribeState
import be.scri.views.KeyboardView
/**
* Manages the UI elements and state transitions for the GeneralKeyboardIME.
* This class handles View interactions, visibility toggling, and layout updates.
*/
@Suppress("TooManyFunctions", "LargeClass")
class KeyboardUIManager(
val binding: InputMethodViewBinding,
private val context: Context,
private val listener: KeyboardUIListener,
) {
interface KeyboardUIListener {
fun onScribeKeyOptionsClicked()
fun onScribeKeyToolbarClicked()
fun onTranslateClicked()
fun onConjugateClicked()
fun onPluralClicked()
fun onCloseClicked()
fun onEmojiSelected(emoji: String)
fun onSuggestionClicked(suggestion: String)
fun getKeyboardLayoutXML(): Int
fun getCurrentEnterKeyType(): Int
fun commitText(text: String)
fun onKeyboardActionListener(): KeyboardView.OnKeyboardActionListener
fun processLinguisticSuggestions(word: String)
}
var keyboardView: KeyboardView = binding.keyboardView
var keyboard: KeyboardBase? = null
// UI Elements
var pluralBtn: Button? = binding.pluralBtn
var emojiBtnPhone1: Button? = binding.emojiBtnPhone1
var emojiSpacePhone: View? = binding.emojiSpacePhone
var emojiBtnPhone2: Button? = binding.emojiBtnPhone2
var emojiBtnTablet1: Button? = binding.emojiBtnTablet1
var emojiSpaceTablet1: View? = binding.emojiSpaceTablet1
var emojiBtnTablet2: Button? = binding.emojiBtnTablet2
var emojiSpaceTablet2: View? = binding.emojiSpaceTablet2
var emojiBtnTablet3: Button? = binding.emojiBtnTablet3
var genderSuggestionLeft: Button? = binding.translateBtnLeft
var genderSuggestionRight: Button? = binding.translateBtnRight
// 6-slot phone colon emoji row buttons
private val emojiColonPhoneButtons: List<Button> by lazy {
listOf(
binding.emojiColonPhone1,
binding.emojiColonPhone2,
binding.emojiColonPhone3,
binding.emojiColonPhone4,
binding.emojiColonPhone5,
binding.emojiColonPhone6,
)
}
// 9-slot tablet colon emoji row buttons
private val emojiColonTabletButtons: List<Button> by lazy {
listOf(
binding.emojiColonTablet1,
binding.emojiColonTablet2,
binding.emojiColonTablet3,
binding.emojiColonTablet4,
binding.emojiColonTablet5,
binding.emojiColonTablet6,
binding.emojiColonTablet7,
binding.emojiColonTablet8,
binding.emojiColonTablet9,
)
}
// State variables specific to UI rendering.
var currentCommandBarHint: String = ""
var commandBarHintColor: Int = Color.GRAY
var commandBarTextColor: Int = Color.BLACK
private var earlierValue: Int? = keyboardView.setEnterKeyIcon(ScribeState.IDLE)
private var currentPage = 0
private val totalPages = 3
private var currentInvalidTexts: Array<String> = HintUtils.getInvalidTextsWikidata("English")
init {
setupClickListeners()
}
private fun setupClickListeners() {
binding.scribeKeyOptions.setOnClickListener { listener.onScribeKeyOptionsClicked() }
binding.scribeKeyToolbar.setOnClickListener { listener.onScribeKeyToolbarClicked() }
binding.translateBtn.setOnClickListener { listener.onTranslateClicked() }
binding.conjugateBtn.setOnClickListener { listener.onConjugateClicked() }
binding.pluralBtn.setOnClickListener { listener.onPluralClicked() }
binding.scribeKeyClose.setOnClickListener { listener.onCloseClicked() }
// Info button listener for INVALID state.
binding.ivInfo.setOnClickListener { showInvalidInfo() }
}
/**
* Updates the color of the Enter key based on the current Scribe state and theme (dark/light mode).
*
* @param isDarkMode The current dark mode status. If null, it will be determined from context.
* @param currentState The current state of the keyboard.
*/
fun updateEnterKeyColor(
isDarkMode: Boolean?,
currentState: ScribeState,
) {
val resolvedIsDarkMode = isDarkMode ?: getIsDarkModeOrNot(context)
when (currentState) {
ScribeState.IDLE, ScribeState.SELECT_COMMAND -> {
keyboardView.setEnterKeyIcon(ScribeState.IDLE, earlierValue)
keyboardView.setEnterKeyColor(null, isDarkMode = resolvedIsDarkMode)
}
else -> {
keyboardView.setEnterKeyColor(context.getColor(R.color.color_primary))
keyboardView.setEnterKeyIcon(ScribeState.PLURAL, earlierValue)
}
}
val scribeKeyTint = if (resolvedIsDarkMode) R.color.light_key_color else R.color.light_key_text_color
binding.scribeKeyOptions.foregroundTintList = ContextCompat.getColorStateList(context, scribeKeyTint)
binding.scribeKeyToolbar.foregroundTintList = ContextCompat.getColorStateList(context, scribeKeyTint)
}
/**
* The main dispatcher for updating the entire keyboard UI. It calls the appropriate setup function
* based on the current [ScribeState].
*/
fun updateUI(
currentState: ScribeState,
language: String,
emojiAutoSuggestionEnabled: Boolean,
autoSuggestEmojis: MutableList<String>?,
conjugateOutput: Map<String, Map<String, Collection<String>>>?,
conjugateLabels: Set<String>?,
selectedConjugationSubCategory: String?,
currentVerbForConjugation: String?,
invalidCommandSource: ScribeState = ScribeState.IDLE,
) {
val isUserDarkMode = getIsDarkModeOrNot(context)
when (currentState) {
ScribeState.IDLE -> setupIdleView(language, emojiAutoSuggestionEnabled, autoSuggestEmojis)
ScribeState.SELECT_COMMAND -> setupSelectCommandView(language)
ScribeState.INVALID -> setupInvalidView(language, invalidCommandSource)
ScribeState.TRANSLATE -> {
setupToolbarView(currentState, language, conjugateOutput, conjugateLabels, selectedConjugationSubCategory, currentVerbForConjugation)
binding.translateBtn.text = translatePlaceholder[getLanguageAlias(language)] ?: "Translate"
binding.translateBtn.visibility = View.VISIBLE
}
ScribeState.CONJUGATE, ScribeState.SELECT_VERB_CONJUNCTION, ScribeState.PLURAL -> {
setupToolbarView(currentState, language, conjugateOutput, conjugateLabels, selectedConjugationSubCategory, currentVerbForConjugation)
}
ScribeState.ALREADY_PLURAL -> setupAlreadyPluralView()
}
updateEnterKeyColor(isUserDarkMode, currentState)
}
/**
* Configures the UI for the `IDLE` state, showing default suggestions or emoji suggestions.
*/
private fun setupIdleView(
language: String,
emojiAutoSuggestionEnabled: Boolean,
autoSuggestEmojis: MutableList<String>?,
) {
binding.commandOptionsBar.visibility = View.VISIBLE
binding.toolbarBar.visibility = View.GONE
val isUserDarkMode = getIsDarkModeOrNot(context)
binding.commandOptionsBar.setBackgroundColor(
ContextCompat.getColor(
context,
if (isUserDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color,
),
)
val textColor = if (isUserDarkMode) Color.WHITE else "#1E1E1E".toColorInt()
listOf(binding.translateBtn, binding.conjugateBtn, binding.pluralBtn).forEachIndexed { index, button ->
button.visibility = View.VISIBLE
button.background = null
button.setTextColor(textColor)
button.text = HintUtils.getBaseAutoSuggestions(language).getOrNull(index)
button.isAllCaps = false
button.textSize = GeneralKeyboardIME.SUGGESTION_SIZE
button.setOnClickListener(null)
}
listOf(binding.separator2, binding.separator3).forEach { separator ->
separator.setBackgroundColor(ContextCompat.getColor(context, R.color.special_key_light))
val params = separator.layoutParams
// Convert 0.5dp to pixels. coerceAtLeast(1) ensures it's never zero.
params.width = (0.5f * context.resources.displayMetrics.density).toInt().coerceAtLeast(1)
separator.layoutParams = params
separator.visibility = View.VISIBLE
}
binding.separator1.visibility = View.GONE
binding.ivInfo.visibility = View.GONE
binding.conjugateGridContainer.visibility = View.GONE
binding.keyboardView.visibility = View.VISIBLE
binding.invalidInfoBar.visibility = View.GONE
currentPage = 0
binding.scribeKeyOptions.foreground = AppCompatResources.getDrawable(context, R.drawable.ic_scribe_icon_vector)
initializeKeyboard(listener.getKeyboardLayoutXML())
updateButtonVisibility(ScribeState.IDLE, emojiAutoSuggestionEnabled, autoSuggestEmojis)
updateEmojiSuggestion(ScribeState.IDLE, emojiAutoSuggestionEnabled, autoSuggestEmojis)
binding.commandBar.setText("")
disableAutoSuggest(language)
}
/**
* Configures the UI for the `SELECT_COMMAND` state, showing the main command buttons
* (Translate, Conjugate, Plural).
*/
private fun setupSelectCommandView(language: String) {
binding.commandOptionsBar.visibility = View.VISIBLE
binding.toolbarBar.visibility = View.GONE
val isUserDarkMode = getIsDarkModeOrNot(context)
binding.commandOptionsBar.setBackgroundColor(
ContextCompat.getColor(
context,
if (isUserDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color,
),
)
val langAlias = getLanguageAlias(language)
updateButtonVisibility(ScribeState.SELECT_COMMAND, false, null)
binding.translateBtn.setOnClickListener { listener.onTranslateClicked() }
binding.conjugateBtn.setOnClickListener { listener.onConjugateClicked() }
binding.pluralBtn.setOnClickListener { listener.onPluralClicked() }
val buttonTextColor = if (isUserDarkMode) Color.WHITE else Color.BLACK
listOf(binding.translateBtn, binding.conjugateBtn, binding.pluralBtn).forEach { button ->
button.visibility = View.VISIBLE
button.background = ContextCompat.getDrawable(context, R.drawable.button_background_rounded)
button.backgroundTintList = ContextCompat.getColorStateList(context, R.color.theme_scribe_blue)
button.setTextColor(buttonTextColor)
button.textSize = GeneralKeyboardIME.SUGGESTION_SIZE
}
binding.translateBtn.text = translatePlaceholder[langAlias] ?: "Translate"
binding.conjugateBtn.text = conjugatePlaceholder[langAlias] ?: "Conjugate"
binding.pluralBtn.text = pluralPlaceholder[langAlias] ?: "Plural"
val separatorColor = (if (isUserDarkMode) GeneralKeyboardIME.DARK_THEME else GeneralKeyboardIME.LIGHT_THEME).toColorInt()
binding.separator2.setBackgroundColor(separatorColor)
binding.separator3.setBackgroundColor(separatorColor)
val spaceInDp = 4
val spaceInPx = (spaceInDp * context.resources.displayMetrics.density).toInt()
listOf(binding.separator2, binding.separator3).forEach { separator ->
separator.setBackgroundColor(Color.TRANSPARENT)
val params = separator.layoutParams
params.width = spaceInPx
separator.layoutParams = params
}
binding.separator1.visibility = View.GONE
binding.separator2.visibility = View.VISIBLE
binding.separator3.visibility = View.VISIBLE
binding.separator4.visibility = View.GONE
binding.separator5.visibility = View.GONE
binding.separator6.visibility = View.GONE
binding.ivInfo.visibility = View.GONE
binding.scribeKeyOptions.foreground = AppCompatResources.getDrawable(context, R.drawable.close)
}
/**
* Configures the UI for command modes (`TRANSLATE`, `CONJUGATE`, etc.), showing the command bar and toolbar.
*/
@SuppressLint("InflateParams")
private fun setupToolbarView(
currentState: ScribeState,
language: String,
conjugateOutput: Map<String, Map<String, Collection<String>>>?,
conjugateLabels: Set<String>?,
selectedConjugationSubCategory: String?,
currentVerbForConjugation: String?,
) {
binding.commandOptionsBar.visibility = View.GONE
binding.toolbarBar.visibility = View.VISIBLE
val isDarkMode = getIsDarkModeOrNot(context)
binding.toolbarBar.setBackgroundColor(
ContextCompat.getColor(
context,
if (isDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color,
),
)
binding.ivInfo.visibility = View.GONE
binding.scribeKeyToolbar.foreground = AppCompatResources.getDrawable(context, R.drawable.close)
var hintWord: String? = null
var promptText: String? = null
if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) {
binding.conjugateGridContainer.visibility = View.VISIBLE
binding.keyboardView.visibility = View.GONE
binding.conjugateGridContainer.setBackgroundColor(
ContextCompat.getColor(
context,
if (isDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color,
),
)
val grid = binding.conjugateGrid
grid.removeAllViews()
val conjugateIndex = getValidatedConjugateIndex(conjugateOutput)
val title = conjugateOutput?.keys?.elementAtOrNull(conjugateIndex)
val languageOutput = title?.let { conjugateOutput[it] }
val isSubSelection = selectedConjugationSubCategory != null
val showCategories = !isSubSelection && (languageOutput?.containsKey(title) != true)
val forms =
if (isSubSelection) {
languageOutput?.get(selectedConjugationSubCategory)?.toList() ?: listOf("", "", "", "")
} else if (showCategories) {
languageOutput?.map { (_, values) ->
if (values.size == 1) values.first() else values.joinToString(" / ")
} ?: listOf("", "", "", "")
} else {
languageOutput?.get(title)?.toList() ?: listOf("", "", "", "")
}
val layoutResId =
when {
isSubSelection -> R.layout.conjugate_grid_2x1
language == "English" && forms.size <= 4 -> R.layout.conjugate_grid_2x2
language in listOf("Russian", "Swedish") && forms.size <= 4 -> R.layout.conjugate_grid_2x2
forms.size > 4 -> R.layout.conjugate_grid_3x2
else -> R.layout.conjugate_grid_2x2
}
val layoutInflater = LayoutInflater.from(context)
val gridContent = layoutInflater.inflate(layoutResId, grid, false) as LinearLayout
grid.addView(gridContent)
val buttonIds =
listOf(
R.id.conjugate_btn_1,
R.id.conjugate_btn_2,
R.id.conjugate_btn_3,
R.id.conjugate_btn_4,
R.id.conjugate_btn_5,
R.id.conjugate_btn_6,
)
buttonIds.forEachIndexed { i, btnId ->
val btn = gridContent.findViewById<Button?>(btnId)
if (btn != null) {
btn.text = forms.getOrNull(i) ?: ""
btn.backgroundTintList =
ContextCompat.getColorStateList(
context,
if (isDarkMode) R.color.dark_key_color else R.color.light_key_color,
)
btn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK)
btn.setOnClickListener {
val label = btn.text.toString()
if (label.isNotEmpty()) {
var handledAsCategory = false
if (showCategories) {
val matchingEntry =
languageOutput?.entries?.find { (_, values) ->
if (values.size == 1) values.first() == label else values.joinToString(" / ") == label
}
if (matchingEntry != null) {
val (key, values) = matchingEntry
if (values.size > 1) {
// Category logic is handled in IME's commitText.
}
}
}
if (!handledAsCategory) {
listener.commitText("$label ")
listener.processLinguisticSuggestions(label)
}
}
}
}
}
setupConjugateArrows(gridContent, context)
promptText = if (isSubSelection) selectedConjugationSubCategory else (title ?: "___")
hintWord = conjugateLabels?.lastOrNull()
} else {
binding.conjugateGridContainer.visibility = View.GONE
binding.keyboardView.visibility = View.VISIBLE
}
updateCommandBarHintAndPrompt(currentState, language, promptText, isDarkMode, hintWord, currentVerbForConjugation)
}
/**
* Sets up the navigation arrow buttons for the conjugation grid view.
*/
private fun setupConjugateArrows(
gridContent: View,
context: Context,
) {
val isDarkMode = getIsDarkModeOrNot(context)
val arrowButtonIds =
listOf(
"conjugate_arrow_left_1",
"conjugate_arrow_right_1",
"conjugate_arrow_left_2",
"conjugate_arrow_right_2",
"conjugate_arrow_left_3",
"conjugate_arrow_right_3",
"conjugate_arrow_left",
"conjugate_arrow_right",
)
arrowButtonIds.forEach { arrowBtnName ->
val arrowBtnId = context.resources.getIdentifier(arrowBtnName, "id", context.packageName)
if (arrowBtnId != 0) {
val arrowBtn = gridContent.findViewById<Button?>(arrowBtnId)
if (arrowBtn != null) {
arrowBtn.background = ContextCompat.getDrawable(context, R.drawable.button_background_rounded)
arrowBtn.backgroundTintList =
ContextCompat.getColorStateList(
context,
if (isDarkMode) R.color.dark_key_color else R.color.light_key_color,
)
val iconTint = if (isDarkMode) R.color.white else R.color.light_key_text_color
arrowBtn.compoundDrawableTintList = ContextCompat.getColorStateList(context, iconTint)
arrowBtn.setTextColor(if (isDarkMode) Color.WHITE else Color.BLACK)
arrowBtn.setOnClickListener {
val isLeft = arrowBtnName.contains("left")
val prefs = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE)
val current = prefs.getInt("conjugate_index", 0)
val newValue = if (isLeft) current - 1 else current + 1
prefs.edit { putInt("conjugate_index", newValue) }
listener.onConjugateClicked()
}
}
}
}
}
/**
* Configures the UI for the `INVALID` state, which is shown when a command (e.g., translation) fails.
* Shows Wikidata info for conjugate/plural commands, and Wiktionary info for the translate command.
*/
@SuppressLint("SetTextI18n")
private fun setupInvalidView(
language: String,
invalidCommandSource: ScribeState,
) {
binding.commandOptionsBar.visibility = View.GONE
binding.toolbarBar.visibility = View.VISIBLE
// Original logic: Invalid state actually uses the toolbarBar layout initially.
binding.invalidInfoBar.visibility = View.GONE
val isDarkMode = getIsDarkModeOrNot(context)
// Restore original logic: Set background on toolbarBar, not invalidInfoBar.
binding.toolbarBar.setBackgroundColor(
if (isDarkMode) "#1E1E1E".toColorInt() else "#d2d4da".toColorInt(),
)
val isWikidata = invalidCommandSource != ScribeState.TRANSLATE
val invalidMsg =
if (isWikidata) {
HintUtils.getInvalidHintWikidata(language)
} else {
HintUtils.getInvalidHintWiktionary(language)
}
currentInvalidTexts =
if (isWikidata) {
HintUtils.getInvalidTextsWikidata(language)
} else {
HintUtils.getInvalidTextsWiktionary(language)
}
binding.ivInfo.visibility = View.VISIBLE
binding.promptText.text = "$invalidMsg: "
binding.commandBar.hint = ""
binding.scribeKeyToolbar.foreground = AppCompatResources.getDrawable(context, R.drawable.ic_scribe_icon_vector)
}
/**
* Configures the UI for the `ALREADY_PLURAL` state, which is shown when the user
* attempts to pluralize a word that is already plural.
*/
@SuppressLint("SetTextI18n")
private fun setupAlreadyPluralView() {
binding.commandOptionsBar.visibility = View.GONE
binding.toolbarBar.visibility = View.VISIBLE
val isDarkMode = getIsDarkModeOrNot(context)
binding.toolbarBar.setBackgroundColor(if (isDarkMode) "#1E1E1E".toColorInt() else "#d2d4da".toColorInt())
binding.ivInfo.visibility = View.VISIBLE
binding.promptText.text = "$ALREADY_PLURAL_MSG: "
binding.commandBar.hint = ""
binding.scribeKeyToolbar.foreground = AppCompatResources.getDrawable(context, R.drawable.ic_scribe_icon_vector)
}
/**
* Updates the hint and prompt text displayed in the command bar area based on the current state.
*
* @param currentState The current keyboard state.
* @param language The current language.
* @param text Specific text for the prompt (optional).
* @param isUserDarkMode The current dark mode status.
* @param word A word to include in the hint (optional).
*/
@SuppressLint("SetTextI18n")
fun updateCommandBarHintAndPrompt(
currentState: ScribeState,
language: String,
text: String? = null,
isUserDarkMode: Boolean? = null,
word: String? = null,
currentVerbForConjugation: String? = null,
) {
val resolvedIsDarkMode = isUserDarkMode ?: getIsDarkModeOrNot(context)
val commandBarEditText = binding.commandBar
val promptTextView = binding.promptText
commandBarHintColor = if (resolvedIsDarkMode) context.getColor(R.color.hint_white) else context.getColor(R.color.hint_black)
commandBarTextColor = if (resolvedIsDarkMode) context.getColor(white) else Color.BLACK
val backgroundColor = if (resolvedIsDarkMode) R.color.command_bar_color_dark else white
binding.commandBarLayout.backgroundTintList = ContextCompat.getColorStateList(context, backgroundColor)
val promptTextStr = HintUtils.getPromptText(currentState, language, context, text)
promptTextView.text = promptTextStr
promptTextView.setTextColor(commandBarTextColor)
promptTextView.setBackgroundColor(context.getColor(backgroundColor))
if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) {
val verbInfinitive = currentVerbForConjugation ?: ""
commandBarEditText.setText(": $verbInfinitive")
commandBarEditText.setTextColor(commandBarTextColor)
commandBarEditText.isFocusable = false
commandBarEditText.isFocusableInTouchMode = false
} else {
currentCommandBarHint = HintUtils.getCommandBarHint(currentState, language, word)
commandBarEditText.isFocusable = true
commandBarEditText.isFocusableInTouchMode = true
commandBarEditText.setTextColor(commandBarHintColor)
setCommandBarTextWithCursor(currentCommandBarHint, cursorAtStart = true)
commandBarEditText.requestFocus()
}
}
/**
* Initializes or re-initializes the keyboard with a new layout.
*
* @param xmlId The resource ID of the keyboard layout XML.
*/
fun initializeKeyboard(xmlId: Int) {
val enterKeyType = listener.getCurrentEnterKeyType()
keyboard = KeyboardBase(context, xmlId, enterKeyType)
keyboardView.setKeyboard(keyboard!!)
keyboardView.mOnKeyboardActionListener = listener.onKeyboardActionListener()
keyboardView.requestLayout()
}
/**
* Sets up the currency symbol on the keyboard based on user preferences.
*
* @param language The current language.
*/
fun setupCurrencySymbol(language: String) {
val currencySymbol = PreferencesHelper.getDefaultCurrencySymbol(context, language)
keyboardView.setKeyLabel(currencySymbol, "", KeyboardBase.CODE_CURRENCY)
}
/**
* Retrieves and validates the stored index for the current conjugation view.
* Ensures the index is within the bounds of available conjugation types.
*/
private fun getValidatedConjugateIndex(conjugateOutput: Map<String, Any>?): Int {
val prefs = context.getSharedPreferences("keyboard_preferences", Context.MODE_PRIVATE)
var index = prefs.getInt("conjugate_index", 0)
val maxIndex = conjugateOutput?.keys?.count()?.minus(1) ?: -1
index = if (maxIndex >= 0) index.coerceIn(0, maxIndex) else 0
prefs.edit { putInt("conjugate_index", index) }
return index
}
// MARK: Suggestion and Visibility
/**
* Updates the visibility of the suggestion buttons based on device type (phone/tablet)
* and whether auto-suggestions are currently active.
*/
fun updateButtonVisibility(
currentState: ScribeState,
isAutoSuggestEnabled: Boolean,
autoSuggestEmojis: MutableList<String>?,
) {
if (currentState != ScribeState.IDLE) {
setupDefaultButtonVisibility()
return
}
val isTablet =
(context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK) >=
Configuration.SCREENLAYOUT_SIZE_LARGE
val emojiCount = if (isAutoSuggestEnabled) autoSuggestEmojis?.size ?: 0 else 0
if (isTablet) updateTabletButtonVisibility(emojiCount) else updatePhoneButtonVisibility(emojiCount)
}
/**
* Sets the default visibility for buttons when not in the `IDLE` state.
* Hides all suggestion-related buttons.
*/
private fun setupDefaultButtonVisibility() {
pluralBtn?.visibility = View.VISIBLE
emojiBtnPhone1?.visibility = View.GONE
emojiBtnPhone2?.visibility = View.GONE
emojiBtnTablet1?.visibility = View.GONE
emojiBtnTablet2?.visibility = View.GONE
emojiBtnTablet3?.visibility = View.GONE
binding.separator4.visibility = View.GONE
binding.separator5.visibility = View.GONE
binding.separator6.visibility = View.GONE
}
/**
* Handles the logic for showing/hiding suggestion buttons specifically on tablet layouts.
*
* @param emojiCount The number of available emoji suggestions.
*/
private fun updateTabletButtonVisibility(emojiCount: Int) {
pluralBtn?.visibility = if (emojiCount > 0) View.INVISIBLE else View.VISIBLE
when (emojiCount) {
0 -> {
emojiBtnTablet1?.visibility = View.GONE
emojiSpaceTablet1?.visibility = View.GONE
emojiBtnTablet2?.visibility = View.GONE
emojiSpaceTablet2?.visibility = View.GONE
emojiBtnTablet3?.visibility = View.GONE
}
1 -> {
emojiBtnTablet1?.visibility = View.VISIBLE
emojiSpaceTablet1?.visibility = View.GONE
emojiBtnTablet2?.visibility = View.GONE
emojiSpaceTablet2?.visibility = View.GONE
emojiBtnTablet3?.visibility = View.GONE
}
2 -> {
emojiBtnTablet1?.visibility = View.VISIBLE
emojiSpaceTablet1?.visibility = View.VISIBLE
emojiBtnTablet2?.visibility = View.VISIBLE
emojiSpaceTablet2?.visibility = View.GONE
emojiBtnTablet3?.visibility = View.GONE
}
else -> {
emojiBtnTablet1?.visibility = View.VISIBLE
emojiSpaceTablet1?.visibility = View.VISIBLE
emojiBtnTablet2?.visibility = View.VISIBLE
emojiSpaceTablet2?.visibility = View.VISIBLE
emojiBtnTablet3?.visibility = View.VISIBLE
}
}
binding.separator5.visibility = View.GONE
binding.separator6.visibility = View.GONE
emojiBtnPhone1?.visibility = View.GONE
emojiSpacePhone?.visibility = View.GONE
emojiBtnPhone2?.visibility = View.GONE
binding.separator4.visibility = View.GONE
}
/**
* Handles the logic for showing/hiding suggestion buttons specifically on phone layouts.
*
* @param emojiCount The number of available emoji suggestions.
*/
private fun updatePhoneButtonVisibility(emojiCount: Int) {
pluralBtn?.visibility = if (emojiCount > 0) View.INVISIBLE else View.VISIBLE
when {
emojiCount == 1 -> {
emojiBtnPhone1?.visibility = View.VISIBLE
emojiSpacePhone?.visibility = View.GONE
emojiBtnPhone2?.visibility = View.GONE
}
emojiCount >= 2 -> {
emojiBtnPhone1?.visibility = View.VISIBLE
emojiSpacePhone?.visibility = View.VISIBLE
emojiBtnPhone2?.visibility = View.VISIBLE
}
else -> {
emojiBtnPhone1?.visibility = View.GONE
emojiSpacePhone?.visibility = View.GONE
emojiBtnPhone2?.visibility = View.GONE
}
}
binding.separator4.visibility = if (emojiCount > 1) View.VISIBLE else View.GONE
emojiBtnTablet1?.visibility = View.GONE
emojiSpaceTablet1?.visibility = View.GONE
emojiBtnTablet2?.visibility = View.GONE
emojiSpaceTablet2?.visibility = View.GONE
emojiBtnTablet3?.visibility = View.GONE
binding.separator5.visibility = View.GONE
binding.separator6.visibility = View.GONE
}
/**
* Updates the text of the suggestion buttons, primarily for displaying emoji suggestions.
*
* @param currentState The current state of the keyboard.
* @param isAutoSuggestEnabled true if suggestions are active.
* @param autoSuggestEmojis The list of emojis to display.
*/
fun updateEmojiSuggestion(
currentState: ScribeState,
isAutoSuggestEnabled: Boolean,
autoSuggestEmojis: MutableList<String>?,
emojiColonModeOn: Boolean = false,
) {
if (currentState != ScribeState.IDLE) return
val isTablet =
(
context.resources.configuration.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK
) >= Configuration.SCREENLAYOUT_SIZE_LARGE
val tabletButtons = listOf(binding.emojiBtnTablet1, binding.emojiBtnTablet2, binding.emojiBtnTablet3)
val legacyPhoneButtons = listOf(binding.emojiBtnPhone1, binding.emojiBtnPhone2)
if (isAutoSuggestEnabled && autoSuggestEmojis != null) {
val emojiListener = { emoji: String -> View.OnClickListener { listener.onEmojiSelected(emoji) } }
if (emojiColonModeOn && !isTablet) {
// Phone colon mode: show the dedicated 6-slot row, hide word buttons and separators.
binding.translateBtn.visibility = View.GONE
binding.conjugateBtn.visibility = View.GONE
binding.pluralBtn.visibility = View.GONE
binding.separator2.visibility = View.GONE
binding.separator3.visibility = View.GONE
legacyPhoneButtons.forEach { it.visibility = View.GONE }
binding.emojiColonRowPhone.visibility = View.VISIBLE
emojiColonPhoneButtons.forEachIndexed { index, button ->
val emoji = autoSuggestEmojis.getOrNull(index) ?: ""
button.text = emoji
button.setOnClickListener(if (emoji.isNotEmpty()) emojiListener(emoji) else null)
}
} else if (emojiColonModeOn && isTablet) {
// Tablet colon mode: show the dedicated 9-slot row, hide word buttons and separators.
binding.translateBtn.visibility = View.GONE
binding.conjugateBtn.visibility = View.GONE
binding.pluralBtn.visibility = View.GONE
binding.separator2.visibility = View.GONE
binding.separator3.visibility = View.GONE
legacyPhoneButtons.forEach { it.visibility = View.GONE }
tabletButtons.forEach { it.visibility = View.GONE }
binding.emojiColonRowPhone.visibility = View.GONE
binding.emojiColonRowTablet.visibility = View.VISIBLE
emojiColonTabletButtons.forEachIndexed { index, button ->
val emoji = autoSuggestEmojis.getOrNull(index) ?: ""
button.text = emoji
button.setOnClickListener(if (emoji.isNotEmpty()) emojiListener(emoji) else null)
}
} else {
// Non-colon mode: ensure both colon rows are hidden, use existing emoji buttons.
binding.emojiColonRowPhone.visibility = View.GONE
binding.emojiColonRowTablet.visibility = View.GONE
tabletButtons.forEachIndexed { index, button ->
val emoji = autoSuggestEmojis.getOrNull(index) ?: ""
button.text = emoji
button.setOnClickListener(if (emoji.isNotEmpty()) emojiListener(emoji) else null)
}
legacyPhoneButtons.forEachIndexed { index, button ->
val emoji = autoSuggestEmojis.getOrNull(index) ?: ""
button.text = emoji
button.setOnClickListener(if (emoji.isNotEmpty()) emojiListener(emoji) else null)
}
}
} else {
binding.emojiColonRowPhone.visibility = View.GONE
binding.emojiColonRowTablet.visibility = View.GONE
(tabletButtons + legacyPhoneButtons).forEach { button ->
button.text = ""
button.setOnClickListener(null)
}
}
}
/**
* Disables all auto-suggestions and resets the suggestion buttons to their default, inactive state.
*/
fun disableAutoSuggest(language: String) {
// Ensure both colon emoji rows are hidden and word buttons are fully restored.
binding.emojiColonRowPhone.visibility = View.GONE
binding.emojiColonRowTablet.visibility = View.GONE
binding.separator2.visibility = View.VISIBLE
binding.separator3.visibility = View.VISIBLE
binding.conjugateBtn.visibility = View.VISIBLE
binding.pluralBtn.visibility = View.VISIBLE
binding.translateBtnRight.visibility = View.INVISIBLE
binding.translateBtnLeft.visibility = View.INVISIBLE
binding.translateBtn.visibility = View.VISIBLE
val createSuggestionClickListener = { suggestion: String ->
View.OnClickListener { listener.onSuggestionClicked(suggestion) }
}
val suggestions = HintUtils.getBaseAutoSuggestions(language)
val suggestion1 = suggestions.getOrNull(0) ?: ""
binding.translateBtn.text = suggestion1
binding.translateBtn.background = null
binding.translateBtn.setOnClickListener(createSuggestionClickListener(suggestion1))
val suggestion2 = suggestions.getOrNull(1) ?: ""
binding.conjugateBtn.text = suggestion2
binding.conjugateBtn.setOnClickListener(createSuggestionClickListener(suggestion2))
val suggestion3 = suggestions.getOrNull(2) ?: ""
binding.pluralBtn.text = suggestion3
binding.pluralBtn.setOnClickListener(createSuggestionClickListener(suggestion3))
handleTextSizeForSuggestion(binding.translateBtn)
}
/**
* Sets the text size and color for a default, non-active suggestion button.
*
* @param button The button to style.
*/
private fun handleTextSizeForSuggestion(button: Button) {
button.textSize = GeneralKeyboardIME.SUGGESTION_SIZE
val isUserDarkMode = getIsDarkModeOrNot(context)
val colorRes = if (isUserDarkMode) R.color.white else android.R.color.black
button.setTextColor(ContextCompat.getColor(context, colorRes))
}
/**
* Sets the command bar text and ensures it ends with the custom cursor.
*
* @param text The text to set (without cursor).
* @param cursorAtStart The flag to check if the text in the EditText is empty to determine the position of the cursor.
*/
internal fun setCommandBarTextWithCursor(
text: String,
cursorAtStart: Boolean = false,
) {
if (cursorAtStart) {
val hintWithCursor = GeneralKeyboardIME.CUSTOM_CURSOR + text
val spannable = SpannableString(hintWithCursor)
spannable.setSpan(
ForegroundColorSpan(commandBarTextColor),
0,
1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
binding.commandBar.setText(spannable, TextView.BufferType.SPANNABLE)
} else {
val textWithCursor = text + GeneralKeyboardIME.CUSTOM_CURSOR
binding.commandBar.setText(textWithCursor)
}
binding.commandBar.setSelection(binding.commandBar.text.length)
}
/**
* Gets the current text in the command bar without the cursor.
*
* @return The text content without the trailing cursor character.
*/
internal fun getCommandBarTextWithoutCursor(): String {
val currentText = binding.commandBar.text.toString()
return when {
currentText.startsWith(GeneralKeyboardIME.CUSTOM_CURSOR) -> currentText.drop(1)
currentText.endsWith(GeneralKeyboardIME.CUSTOM_CURSOR) -> currentText.dropLast(1)
else -> currentText
}
}
/**
* Show information about Wikidata when the user clicks the information icon.
*/
private fun showInvalidInfo() {
binding.ivInfo.isClickable = true
binding.ivInfo.isFocusable = true
keyboardView.visibility = View.GONE
binding.invalidInfoBar.visibility = View.VISIBLE
setupWikidataButtons()
updateWikidataPage()
}
private fun setupWikidataButtons() {
binding.buttonLeft.setOnClickListener {
if (currentPage > 0) {
currentPage--
updateWikidataPage()
}
}
binding.buttonRight.setOnClickListener {
if (currentPage < totalPages - 1) {
currentPage++
updateWikidataPage()
}
}
}
/**
* Update invalid info text based on current navigation state.
*/
private fun updateWikidataPage() {
binding.middleTextview.text = currentInvalidTexts[currentPage]
updateDotIndicators()
}
/**
* Update page indicators to show which Wikidata explanation the user is currently viewing.
*/
private fun updateDotIndicators() {
val pageIndicators = binding.pageIndicators
for (i in 0 until pageIndicators.childCount) {
val dot = pageIndicators.getChildAt(i)
dot.background =
ContextCompat.getDrawable(
context,
if (i == currentPage) R.drawable.dot_active else R.drawable.dot_inactive,
)
}
}
}