-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputLogicTest.kt
More file actions
1359 lines (1231 loc) · 57.9 KB
/
Copy pathInputLogicTest.kt
File metadata and controls
1359 lines (1231 loc) · 57.9 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
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin
import android.inputmethodservice.InputMethodService
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.InputType
import android.view.KeyEvent
import android.view.WindowManager
import android.view.inputmethod.*
import androidx.core.content.edit
import helium314.keyboard.ShadowInputMethodManager2
import helium314.keyboard.ShadowLocaleManagerCompat
import helium314.keyboard.event.Event
import helium314.keyboard.keyboard.KeyboardSwitcher
import helium314.keyboard.keyboard.MainKeyboardView
import helium314.keyboard.keyboard.internal.keyboard_parser.floris.KeyCode
import helium314.keyboard.latin.ShadowFacilitator2.Companion.lastAddedWord
import helium314.keyboard.latin.SuggestedWords.SuggestedWordInfo
import helium314.keyboard.latin.common.Constants
import helium314.keyboard.latin.common.LocaleUtils.constructLocale
import helium314.keyboard.latin.common.StringUtils
import helium314.keyboard.latin.database.ClipboardDao
import helium314.keyboard.latin.inputlogic.InputLogic
import helium314.keyboard.latin.inputlogic.SpaceState
import helium314.keyboard.latin.settings.Settings
import helium314.keyboard.latin.settings.SettingsValues
import helium314.keyboard.latin.utils.ScriptUtils
import helium314.keyboard.latin.utils.SubtypeSettings
import helium314.keyboard.latin.utils.getTimestampFormatter
import helium314.keyboard.latin.utils.prefs
import org.junit.runner.RunWith
import org.junit.Ignore
import org.mockito.Mockito
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowLog
import java.util.*
import kotlin.math.min
import kotlin.streams.asSequence
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@RunWith(RobolectricTestRunner::class)
@Config(shadows = [
ShadowLocaleManagerCompat::class,
ShadowInputMethodManager2::class,
ShadowInputMethodService::class,
ShadowKeyboardSwitcher::class,
ShadowHandler::class,
ShadowFacilitator2::class,
])
class InputLogicTest {
private val latinIME = Robolectric.setupService(LatinIME::class.java)
private val settingsValues get() = Settings.getValues()
private val inputLogic get() = latinIME.mInputLogic
private val connection: RichInputConnection get() = inputLogic.mConnection
private val composerReader = InputLogic::class.java.getDeclaredField("mWordComposer").apply { isAccessible = true }
private val composer get() = composerReader.get(inputLogic) as WordComposer
private val spaceStateReader = InputLogic::class.java.getDeclaredField("mSpaceState").apply { isAccessible = true }
private val spaceState get() = spaceStateReader.get(inputLogic) as Int
private val beforeComposingReader = RichInputConnection::class.java.getDeclaredField("mCommittedTextBeforeComposingText").apply { isAccessible = true }
private val connectionTextBeforeComposingText get() = (beforeComposingReader.get(connection) as CharSequence).toString()
private val composingReader = RichInputConnection::class.java.getDeclaredField("mComposingText").apply { isAccessible = true }
private val connectionComposingText get() = (composingReader.get(connection) as CharSequence).toString()
private val commitTempReader = RichInputConnection::class.java
.getDeclaredField("mTempObjectForCommitText")
.apply { isAccessible = true }
private val connectionCommitTemp get() = (commitTempReader.get(connection) as CharSequence).toString()
init {
ShadowLog.setupLogging()
ShadowLog.stream = System.out
}
@Test fun inputCode() {
input('c')
assertEquals("c", textBeforeCursor)
assertEquals("c", getText())
assertEquals("", textAfterCursor)
assertEquals("c", composingText)
latinIME.mHandler.onFinishInput()
assertEquals("", composingText)
}
@Test fun delete() {
setText("hello there ")
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello there", text)
assertEquals("there", composingText)
}
@Test fun deleteMultiCodepointText() {
setText("hello there \uD83E\uDF00")
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello there ", text)
}
@Test fun secureComposerKeyDoesNotCommitComposingText() {
setText("hello")
input('w')
val beforeText = text
val beforeComposing = composingText
functionalKeyPress(KeyCode.SECURE_COMPOSER)
assertEquals(beforeText, text)
assertEquals(beforeComposing, composingText)
}
@Test fun secureComposerEditorNeverLearnsUnlearnsOrAdjustsLanguageConfidence() {
currentEditorPackageName = BuildConfig.APPLICATION_ID
currentPrivateImeOptions = InputAttributes.CIPHERBOARD_SECURE_EDITOR_OPTION
currentImeOptions = EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
setText("")
assertTrue(settingsValues.mIncognitoModeEnabled)
InputLogic::class.java.getDeclaredMethod(
"unlearnWord",
String::class.java,
SettingsValues::class.java,
DictionaryFacilitator.UnlearnEvent::class.java,
).apply { isAccessible = true }.invoke(
inputLogic,
"secret-unlearn-sentinel",
settingsValues,
DictionaryFacilitator.UnlearnEvent.BACKSPACE,
)
InputLogic::class.java.getDeclaredMethod(
"performAdditionToUserHistoryDictionary",
SettingsValues::class.java,
String::class.java,
NgramContext::class.java,
).apply { isAccessible = true }.invoke(
inputLogic,
settingsValues,
"secret-learn-sentinel",
NgramContext.EMPTY_PREV_WORDS_INFO,
)
assertEquals(0, ShadowFacilitator2.addCalls)
assertEquals(0, ShadowFacilitator2.unlearnCalls)
assertEquals(0, ShadowFacilitator2.adjustConfidenceCalls)
}
@Test fun secureComposerEditorForcesPrivateImeSettingsAndSecureWindow() {
latinIME.prefs().edit {
putBoolean(Settings.PREF_ENABLE_CLIPBOARD_HISTORY, true)
putBoolean(Settings.PREF_SUGGEST_CLIPBOARD_CONTENT, true)
putBoolean(Settings.PREF_SHOW_SUGGESTIONS, true)
putBoolean(Settings.PREF_ALWAYS_SHOW_SUGGESTIONS, true)
putBoolean(Settings.PREF_AUTO_CORRECTION, true)
putBoolean(Settings.PREF_POPUP_ON, true)
putBoolean(Settings.PREF_GESTURE_FLOATING_PREVIEW_TEXT, true)
}
currentEditorPackageName = BuildConfig.APPLICATION_ID
currentPrivateImeOptions = InputAttributes.CIPHERBOARD_SECURE_EDITOR_OPTION
currentImeOptions = EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
setText("")
assertTrue(!settingsValues.mClipboardHistoryEnabled)
assertTrue(!settingsValues.mSuggestClipboardContent)
assertTrue(!settingsValues.mSuggestionsEnabled)
assertTrue(!settingsValues.mAutoCorrectEnabled)
assertTrue(!settingsValues.mKeyPreviewPopupOn)
assertTrue(!settingsValues.mGestureInputEnabled)
assertTrue(!settingsValues.mGestureFloatingPreviewTextEnabled)
assertTrue(!settingsValues.mSlidingKeyInputPreviewEnabled)
assertTrue(
latinIME.window.window!!.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE != 0,
)
currentEditorPackageName = "org.example.normal"
currentPrivateImeOptions = null
currentImeOptions = 0
setText("")
assertEquals(
0,
latinIME.window.window!!.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE,
)
}
@Test fun secureComposerClipboardCommandsCannotExportPlaintext() {
currentEditorPackageName = BuildConfig.APPLICATION_ID
currentPrivateImeOptions = InputAttributes.CIPHERBOARD_SECURE_EDITOR_OPTION
currentImeOptions = EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
val clipboard = latinIME.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val history = ClipboardDao.getInstance(latinIME)
val plaintextSentinel = "secure-editor-clipboard-sentinel"
val existingClipboard = "preexisting-clipboard"
val blocked = intArrayOf(
KeyCode.CLIPBOARD,
KeyCode.CLIPBOARD_PASTE,
KeyCode.CLIPBOARD_SELECT_ALL,
KeyCode.CLIPBOARD_SELECT_WORD,
KeyCode.CLIPBOARD_COPY,
KeyCode.CLIPBOARD_COPY_ALL,
KeyCode.CLIPBOARD_CUT,
KeyCode.CLIPBOARD_CLEAR_HISTORY,
KeyCode.UNDO,
KeyCode.REDO,
)
blocked.forEach { keyCode ->
setText(plaintextSentinel)
if (keyCode == KeyCode.CLIPBOARD_COPY || keyCode == KeyCode.CLIPBOARD_CUT) {
setCursorPosition(0, plaintextSentinel.length)
}
clipboard.setPrimaryClip(ClipData.newPlainText("test", existingClipboard))
functionalKeyPress(keyCode)
assertEquals(plaintextSentinel, text)
assertEquals(
existingClipboard,
clipboard.primaryClip!!.getItemAt(0).coerceToText(latinIME).toString(),
)
assertTrue(history?.getAll().orEmpty().none { it.text.toString().contains(plaintextSentinel) })
}
}
@Test fun finishingSecureComposerOverwritesAndDisconnectsImeTextCaches() {
currentEditorPackageName = BuildConfig.APPLICATION_ID
currentPrivateImeOptions = InputAttributes.CIPHERBOARD_SECURE_EDITOR_OPTION
currentImeOptions = EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
setText("secure-cache-prefix ")
input('x')
assertTrue(connectionTextBeforeComposingText.isNotEmpty())
assertTrue(connection.isConnected)
latinIME.mHandler.onFinishInputView(true)
handleMessages()
assertEquals("", connectionTextBeforeComposingText)
assertEquals("", connectionComposingText)
assertEquals("", connectionCommitTemp)
assertTrue(!connection.isConnected)
assertTrue(!composer.isComposingWord)
assertEquals(
null,
InputLogic::class.java.getDeclaredField("mEnteredText").apply { isAccessible = true }
.get(inputLogic),
)
currentEditorPackageName = "org.example.normal"
currentPrivateImeOptions = null
currentImeOptions = 0
setText("")
assertTrue(connection.isConnected)
}
@Test fun deleteCombinedText() {
setText("hello there э́")
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello there ", text)
setText("hello there H̵̛͕̞̦̰̜͍̰̥̟͆̏͂̌͑́ͅ")
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello there ", text)
}
@Test fun deleteInsideWord() {
setText("hello you there")
setCursorPosition(8) // after o in you
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello yu there", text)
assertEquals("yu", composingText)
}
@Test fun insertLetterIntoWord() {
setText("hello")
setCursorPosition(3) // after first l
input('i')
assertEquals("helilo", getWordAtCursor())
assertEquals("helilo", getText())
assertEquals(4, getCursorPosition())
assertEquals(4, cursor)
assertEquals("", composingText)
}
@Test fun insertLetterIntoWordWithWeirdEditor() {
currentInputType = 180225 // should not change much, but just to be sure
setText("hello")
setCursorPosition(3, weirdTextField = true) // after first l
input('i')
assertEquals("helilo", getWordAtCursor())
assertEquals("helilo", getText())
assertEquals(4, getCursorPosition())
assertEquals(4, cursor)
}
@Test fun insertLetterIntoOneOfSeveralWords() {
setText("hello my friend")
setCursorPosition(7) // between m and y
input('a')
assertEquals("may", getWordAtCursor())
assertEquals("hello may friend", getText())
assertEquals(8, getCursorPosition())
assertEquals(8, cursor)
}
@Test fun combineHangul() {
val ko = SubtypeSettings.getResourceSubtypesForLocale("ko".constructLocale()).first()
latinIME.switchToSubtype(ko)
chainInput("ㅂㄱㅑ")
assertEquals("ㅂ갸", text)
}
@Test fun emojiHangul() {
val ko = SubtypeSettings.getResourceSubtypesForLocale("ko".constructLocale()).first()
latinIME.switchToSubtype(ko)
input(0x1F970)
assertEquals("\uD83E\uDD70", text)
}
// todo: make it work, but it might not be that simple because adding is done in combiner
// https://github.com/HeliBorg/HeliBoard/issues/214
@Ignore("Known upstream HeliBoard issue #214: inserting into an existing Hangul composition")
@Test fun insertLetterIntoWordHangulFails() {
latinIME.switchToSubtype(SubtypeSettings.getResourceSubtypesForLocale("ko".constructLocale()).first())
chainInput("ㅛㅎㄹㅎㅕㅛ")
setCursorPosition(3)
input('ㄲ') // fails, as expected from the hangul issue when processing the event in onCodeInput
assertEquals("ㅛㅎㄹㄲ혀ㅛ", getWordAtCursor())
assertEquals("ㅛㅎㄹㄲ혀ㅛ", getText())
assertEquals("ㅛㅎㄹㄲ혀ㅛ", textBeforeCursor + textAfterCursor)
assertEquals(4, getCursorPosition())
assertEquals(4, cursor)
}
// see issue 1447
@Test fun separatorAfterHangul() {
latinIME.switchToSubtype(SubtypeSettings.getResourceSubtypesForLocale("ko".constructLocale()).first())
chainInput("ㅛ.")
assertEquals("ㅛ.", text)
}
@Test fun deleteHangulInDebugMode() { // issue 1551, later only happened on phone
latinIME.switchToSubtype(SubtypeSettings.getResourceSubtypesForLocale("ko".constructLocale()).first())
setText("ㅛㅛ ")
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE)
}
@Test fun separatorUnselectsWord() {
setText("hello")
assertEquals("hello", composingText)
input('.')
assertEquals("", composingText)
}
@Test fun autospace() {
setText("hello")
input('.')
input('a')
assertEquals("hello.a", textBeforeCursor)
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
setText("hello")
input('.')
input('a')
assertEquals("hello. a", textBeforeCursor)
}
@Test fun autospaceButWithTextAfter() {
setText("hello there")
setCursorPosition(5) // after hello
input('.')
input('a')
assertEquals("hello.a", textBeforeCursor)
assertEquals("hello.a there", text)
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
setText("hello there")
setCursorPosition(5) // after hello
input('.')
input('a')
assertEquals("hello. a", textBeforeCursor)
assertEquals("hello. a there", text)
}
@Test fun noAutospaceInUrlField() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("example.net")
assertEquals("example. net", text)
lastAddedWord = ""
setText("")
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("example.net")
assertEquals("", lastAddedWord)
assertEquals("example.net", text)
assertEquals("example.net", composingText)
}
@Test fun noAutospaceInUrlFieldWhenPickingSuggestion() {
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("exam")
pickSuggestion("example")
assertEquals("example", text)
input('.')
assertEquals("example.", text)
}
@Test fun noAutospaceForDetectedUrl() { // "light" version, should work without url detection
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("http://example.net")
assertEquals("http://example.net", text)
assertEquals("http", lastAddedWord)
assertEquals("example.net", composingText)
}
@Test fun noAutospaceForDetectedEmail() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("mail@example.com")
assertEquals("mail@example.com", text)
assertEquals("mail@example", lastAddedWord) // todo: do we want this? not really nice, but don't want to be too aggressive with URL detection disabled
assertEquals("com", composingText) // todo: maybe this should still see the whole address as a single word? or don't be too aggressive?
setText("")
lastAddedWord = ""
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("mail@example.com")
assertEquals("", lastAddedWord)
assertEquals("mail@example.com", composingText)
}
@Test fun urlDetectionThings() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("...h")
assertEquals("...h", text)
assertEquals("h", composingText)
reset()
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("bla..")
assertEquals("bla..", text)
assertEquals("", composingText)
reset()
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("bla.c")
assertEquals("bla.c", text)
assertEquals("bla.c", composingText)
reset()
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
latinIME.prefs().edit { putBoolean(Settings.PREF_SHIFT_REMOVES_AUTOSPACE, true) }
input("bla")
input('.')
functionalKeyPress(KeyCode.SHIFT) // should remove the phantom space (in addition to normal effect)
input('c')
assertEquals("bla.c", text)
assertEquals("bla.c", composingText)
}
@Test fun stripSeparatorsBeforeAddingToHistoryWithURLDetection() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("example.com.")
assertEquals("example.com.", composingText)
input(' ')
assertEquals("example.com", lastAddedWord)
}
@Test fun dontSelectConsecutiveSeparatorsWithURLDetection() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("bla..")
assertEquals("", composingText)
assertEquals("bla..", text)
}
@Test fun selectDoesSelect() {
setText("this is some text")
setCursorPosition(3, 8)
assertEquals("s is ", text.substring(3, 8))
}
@Test fun noComposingForPasswordFields() {
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)
input('a')
input('b')
assertEquals("", composingText)
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
input('.')
input('c')
assertEquals("", composingText)
}
@Test fun `don't select whole thing as composing word if URL detection disabled`() {
setText("http://example.com")
setCursorPosition(13) // between l and e
assertEquals("example", composingText)
}
@Test fun `select whole thing except http(s) as composing word if URL detection enabled and selecting`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setText("http://example.com")
setCursorPosition(13) // between l and e
assertEquals("example.com", composingText)
setText("http://bla.com http://example.com ")
setCursorPosition(29) // between l and e
assertEquals("example.com", composingText)
}
@Test fun `select whole thing except http(s) as composing word if URL detection enabled and typing`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("http://example.com")
assertEquals("example.com", composingText)
}
@Test fun `don't add partial URL to history`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setText("http:/") // just so lastAddedWord isn't set to http
chainInput("/bla.com")
assertEquals("", lastAddedWord)
}
@Test fun urlProperlySelected() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
setText("http://example.com/here")
setCursorPosition(18) // after .com
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE) // delete com
// todo: do we really want no composing text?
// probably not... try not to break composing
assertEquals("", composingText)
chainInput("net")
assertEquals("example.net", composingText)
}
@Test fun urlProperlySelectedWhenNotDeletingFullTld() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setText("http://example.com/here")
setCursorPosition(18) // after .com
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE) // delete om
// todo: this is a weird difference to deleting the full TLD (see urlProperlySelected)
// what do we want here? (probably consistency)
assertEquals("example.c/here", composingText)
chainInput("z")
assertEquals("", composingText) // todo: this is a weird difference to deleting the full TLD
// assertEquals("example.cz", composingText) // fails, but probably would be better than above
}
@Test fun dontCommitPartialUrlBeforeFirstPeriod() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
// type http://bla. -> bla not selected, but clearly url, also means http://bla is committed which we probably don't want
chainInput("http://bla.")
assertEquals("bla.", composingText)
}
@Test fun `intermediate commits in text field without protocol`() {
chainInput("bla.")
assertEquals("bla", lastAddedWord)
chainInput("com/")
assertEquals("com", lastAddedWord)
chainInput("img.jpg")
assertEquals("img", lastAddedWord)
assertEquals("jpg", composingText)
}
@Test fun `intermediate commit in text field without protocol and with URL detection`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("bla.com/img.jpg")
assertEquals("bla", lastAddedWord)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `only protocol commit in text field with protocol and URL detection`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("http://bla.com/img.jpg")
assertEquals("http", lastAddedWord)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `no intermediate commit in URL field with protocol`() {
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("http://bla.com/img.jpg")
assertEquals("http", lastAddedWord) // todo: somehow avoid?
assertEquals("http://bla.com/img.jpg", text)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `no intermediate commit in URL field with protocol and URL detection`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("http://bla.com/img.jpg")
assertEquals("http", lastAddedWord) // todo: somehow avoid?
assertEquals("http://bla.com/img.jpg", text)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `no intermediate commit in URL field without protocol`() {
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("bla.com/img.jpg")
assertEquals("", lastAddedWord)
assertEquals("bla.com/img.jpg", text)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `no intermediate commit in URL field without protocol and with URL detection`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
chainInput("bla.com/img.jpg")
assertEquals("", lastAddedWord)
assertEquals("bla.com/img.jpg", text)
assertEquals("bla.com/img.jpg", composingText)
}
@Test fun `don't accidentally detect some other text fields as URI`() {
// see comment in InputLogic.textBeforeCursorMayBeUrlOrSimilar
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE)
chainInput("Hey,why")
assertEquals("Hey, why", text)
}
@Test fun `URL detection does not trigger on non-words`() {
// first make sure it works without URL detection
chainInput("15:50-17")
assertEquals("15:50-17", text)
assertEquals("", composingText)
// then with URL detection
reset()
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
chainInput("15:50-17")
assertEquals("15:50-17", text)
assertEquals("", composingText)
}
@Test fun `autospace after selecting a suggestion`() {
pickSuggestion("this")
input('b')
assertEquals("this b", text)
assertEquals("b", composingText)
}
@Test fun `autospace works in URL field when input isn't URL`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
pickSuggestion("this")
input('b')
assertEquals("this b", text)
assertEquals("b", composingText)
}
// https://github.com/HeliBorg/HeliBoard/issues/215
// https://github.com/HeliBorg/HeliBoard/issues/229
@Test fun `autospace works in URL field when input isn't URL, also for multiple suggestions`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
pickSuggestion("this")
pickSuggestion("is")
assertEquals("this is", text)
pickSuggestion("not")
assertEquals("this is not", text)
input('c')
assertEquals("this is not c", text)
assertEquals("c", composingText)
}
@Test fun `emoji is added to dictionary`() {
// check both text and codepoint input
chainInput("hello ")
input(0x1F36D)
assertEquals(StringUtils.newSingleCodePointString(0x1F36D), lastAddedWord)
reset()
chainInput("hello ")
input("🤗")
assertEquals("\uD83E\uDD17", lastAddedWord)
reset()
chainInput("hello ")
input("why 🤗 ") // not added because it's not only emoji (input can come from pasting)
assertEquals("hello", lastAddedWord)
}
@Test fun `emoji uses phantom space`() {
// check both text and codepoint input
pickSuggestion("hi")
input("🤗")
assertEquals("\uD83E\uDD17", lastAddedWord)
assertEquals("hi \uD83E\uDD17", text)
reset()
pickSuggestion("hi")
input(0x1F36D)
assertEquals(StringUtils.newSingleCodePointString(0x1F36D), lastAddedWord)
assertEquals("hi ${StringUtils.newSingleCodePointString(0x1F36D)}", text)
}
// https://github.com/HeliBorg/HeliBoard/issues/230
@Test fun `no autospace after opening quotes`() {
chainInput("\"Hi\" \"h")
assertEquals("\"Hi\" \"h", text)
assertEquals("h", composingText)
reset()
chainInput("\"Hi\", \"h")
assertEquals("\"Hi\", \"h", text)
assertEquals("h", composingText)
}
@Test fun `autospace works in URL field when starting with quotes`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_URL_DETECTION, true) }
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
input("\"")
pickSuggestion("this")
input("i")
assertEquals("\"this i", text)
}
@Test fun `double space results in period and space, and delete removes the period`() {
chainInput("hello")
input(' ')
input(' ')
assertEquals("hello. ", text)
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello ", text)
}
@Test fun `no weird space inside multi-"`() {
chainInput("\"\"\"")
assertEquals("\"\"\"", text)
reset()
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("\"\"\"")
assertEquals("\"\"\"", text)
}
@Test fun `autospace still happens after "`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("\"hello\"you")
assertEquals("\"hello\" you", text)
}
@Test fun `autospace still happens after " if next word is in quotes`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("\"hello\"\"you\"")
assertEquals("\"hello\" \"you\"", text)
}
@Test fun `autospace propagates over "`() {
input('"')
pickSuggestion("hello")
assertEquals(spaceState, SpaceState.PHANTOM) // picking a suggestion sets phantom space state
chainInput("\"you")
assertEquals("\"hello\" you", text)
}
@Test fun `autospace still happens after " if nex word is in " and after comma`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("\"hello\",\"you\"")
assertEquals("\"hello\", \"you\"", text)
}
@Test fun `autospace in json editor`() {
latinIME.prefs().edit { putBoolean(Settings.PREF_AUTOSPACE_AFTER_PUNCTUATION, true) }
chainInput("{\"label\":\"")
assertEquals("{\"label\": \"", text)
input('c')
assertEquals("{\"label\": \"c", text)
}
@Test fun `text input and delete`() {
input("hello")
assertEquals("hello", text)
functionalKeyPress(KeyCode.DELETE)
assertEquals("hell", text)
reset()
input("hello ")
assertEquals("hello ", text)
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello", text)
}
@Test fun `emoji text input and delete`() {
input("🕵🏼")
functionalKeyPress(KeyCode.DELETE)
assertEquals("", text)
reset()
input("\uD83D\uDD75\uD83C\uDFFC")
input(' ')
assertEquals("🕵🏼 ", text)
functionalKeyPress(KeyCode.DELETE)
functionalKeyPress(KeyCode.DELETE)
assertEquals("", text)
}
// emoRegex update to unicode 16.0 was required, https://github.com/HeliBorg/HeliBoard/issues/1760
@Test fun `emojis deleted one by one`() {
chainInput("\uD83E\uDEC6\uD83E\uDEC6\uD83E\uDEC6")
functionalKeyPress(KeyCode.DELETE)
assertEquals("\uD83E\uDEC6\uD83E\uDEC6", text)
}
@Test fun `revert autocorrect on delete`() {
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)
chainInput("hullo")
getAutocorrectedWithSpaceAfter("hello", "hullo")
assertEquals("hello ", text)
functionalKeyPress(KeyCode.DELETE)
assertEquals("hullo", text)
reset()
setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)
latinIME.prefs().edit { putBoolean(Settings.PREF_BACKSPACE_REVERTS_AUTOCORRECT, false) }
chainInput("hullo")
getAutocorrectedWithSpaceAfter("hello", "hullo")
functionalKeyPress(KeyCode.DELETE)
assertEquals("hello", text)
}
@Test fun `remove glide typing word on delete`() {
glideTypingInput("hello")
assertEquals("hello", text)
functionalKeyPress(KeyCode.DELETE)
assertEquals("", text)
// todo: now we want some way to disable delete-all on backspace, either per setting or something else
// need to avoid getting into the mWordComposer.isBatchMode() part of handleBackspaceEvent
}
@Test fun timestamp() {
chainInput("hello")
val beforeKeyPress = System.currentTimeMillis()
functionalKeyPress(KeyCode.TIMESTAMP)
val afterKeyPress = System.currentTimeMillis()
val parsedTimestamp = getTimestampFormatter(latinIME).parse(text.substring(5))!!.time
assertTrue(parsedTimestamp in (beforeKeyPress - 999)..afterKeyPress)
}
@Test fun inlineEmojiSearchStart() {
assertEquals(true, InputLogic.isStartOfInlineEmojiSearch('t'.code, ':'.code, ' '.code, settingsValues))
assertEquals(false, InputLogic.isStartOfInlineEmojiSearch(' '.code, ':'.code, ' '.code, settingsValues))
assertEquals(true, InputLogic.isStartOfInlineEmojiSearch('t'.code, ':'.code, '.'.code, settingsValues))
assertEquals(true, InputLogic.isStartOfInlineEmojiSearch('t'.code, ':'.code, "🌍".codePoints().asSequence().last(), settingsValues))
assertEquals(false, InputLogic.isStartOfInlineEmojiSearch('t'.code, ':'.code, 't'.code, settingsValues))
assertEquals(false, InputLogic.isStartOfInlineEmojiSearch('t'.code, ':'.code, '3'.code, settingsValues))
}
@Test fun inlineEmojiSearchString() {
assertEquals("test", InputLogic.getInlineEmojiSearchString(":test"))
assertEquals(null, InputLogic.getInlineEmojiSearchString("test"))
assertEquals("test", InputLogic.getInlineEmojiSearchString(" :test"))
assertEquals(null, InputLogic.getInlineEmojiSearchString("t:test"))
assertEquals(null, InputLogic.getInlineEmojiSearchString("6:test"))
assertEquals("test", InputLogic.getInlineEmojiSearchString("🌍:test"))
assertEquals("test", InputLogic.getInlineEmojiSearchString(",:test"))
assertEquals(null, InputLogic.getInlineEmojiSearchString(":test\nt"))
assertEquals("/48", InputLogic.getInlineEmojiSearchString("2606:127.0.0.1::/48")) // do we want this?
}
@Test fun moveCursorHorizontally() {
chainInput("hello")
assertEquals(5, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(-2)
assertEquals(3, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(-5)
assertEquals(0, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(-1)
assertEquals(0, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(3)
assertEquals(3, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(3)
assertEquals(5, cursor)
latinIME.mKeyboardActionListener.onHorizontalSpaceSwipe(1)
assertEquals(5, cursor)
}
// ------- helper functions ---------
// should be called before every test, so the same state is guaranteed
@BeforeTest
fun reset() {
// reset input connection & facilitator
currentScript = ScriptUtils.SCRIPT_LATIN
text = ""
batchEdit = 0
currentInputType = InputType.TYPE_CLASS_TEXT
currentEditorPackageName = null
currentPrivateImeOptions = null
currentImeOptions = 0
lastAddedWord = ""
ShadowFacilitator2.addCalls = 0
ShadowFacilitator2.unlearnCalls = 0
ShadowFacilitator2.adjustConfidenceCalls = 0
// reset settings
latinIME.prefs().edit { clear() }
setText("") // (re)sets selection and composing word
}
private fun chainInput(text: String) = text.forEach { input(it.code) }
private fun input(char: Char) = input(char.code)
private fun input(codePoint: Int) {
require(codePoint > 0) { "not a codePoint: $codePoint" }
val oldBefore = textBeforeCursor
val oldAfter = textAfterCursor
val insert = StringUtils.newSingleCodePointString(codePoint)
val phantomSpaceToInsert = if (spaceState == SpaceState.PHANTOM) " " else ""
val oldIsAtEnd = !composer.isCursorFrontOrMiddleOfComposingWord
latinIME.onEvent(Event.createEventForCodePointFromUnknownSource(codePoint))
handleMessages()
if (!latinIME.prefs().getString(Settings.PREF_SELECTED_SUBTYPE, "")!!.contains("CombiningRules") // check fails if combiner merges symbols
&& !(codePoint == Constants.CODE_SPACE && oldBefore.lastOrNull() == ' ') // check fails when 2 spaces are converted into a period
&& !latinIME.mInputLogic.mSuggestedWords.mWillAutoCorrect // autocorrect obviously creates inconsistencies
) {
if (phantomSpaceToInsert.isEmpty())
assertEquals(oldBefore + insert, textBeforeCursor)
else // in some cases autospace might be suppressed
assert(oldBefore + phantomSpaceToInsert + insert == textBeforeCursor || oldBefore + insert == textBeforeCursor)
}
assertEquals(oldAfter, textAfterCursor)
assertEquals(textBeforeCursor + textAfterCursor, getText())
if (composer.isComposingWord) // if we're not composing any more cursor is always at the end
assertEquals(oldIsAtEnd, !composer.isCursorFrontOrMiddleOfComposingWord)
checkConnectionConsistency()
}
private fun functionalKeyPress(keyCode: Int) {
require(keyCode < 0) { "not a functional key code: $keyCode" }
latinIME.onEvent(Event.createSoftwareKeypressEvent(Event.NOT_A_CODE_POINT, keyCode, 0, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE, false))
handleMessages()
checkConnectionConsistency()
}
// almost the same as codePoint input, but calls different latinIME function
private fun input(insert: String) {
val oldBefore = textBeforeCursor
val oldAfter = textAfterCursor
val phantomSpaceToInsert = if (spaceState == SpaceState.PHANTOM) " " else ""
latinIME.onTextInput(insert)
handleMessages()
if (phantomSpaceToInsert.isEmpty())
assertEquals(oldBefore + insert, textBeforeCursor)
else // in some cases autospace might be suppressed
assert(oldBefore + phantomSpaceToInsert + insert == textBeforeCursor || oldBefore + insert == textBeforeCursor)
assert(oldBefore + insert == textBeforeCursor || "$oldBefore $insert" == textBeforeCursor)
assertEquals(oldAfter, textAfterCursor)
assertEquals(textBeforeCursor + textAfterCursor, getText())
checkConnectionConsistency()
}
private fun getWordAtCursor() = connection.getWordRangeAtCursor(settingsValues.mSpacingAndPunctuations, currentScript)?.mWord
private fun setCursorPosition(start: Int, end: Int = start, weirdTextField: Boolean = false) {
val ei = EditorInfo()
ei.inputType = currentInputType
ei.packageName = currentEditorPackageName
ei.privateImeOptions = currentPrivateImeOptions
ei.imeOptions = currentImeOptions
ei.initialSelStart = start
ei.initialSelEnd = end
// imeOptions should not matter
// adjust text in inputConnection first, otherwise fixLyingCursorPosition will move cursor
// to the end of the text
val fullText = textBeforeCursor + selectedText + textAfterCursor
assertEquals(fullText, getText())
// need to update ic before, otherwise when reloading text cache from ic, ric will load wrong text before cursor
val oldStart = selectionStart
val oldEnd = selectionEnd
selectionStart = start
selectionEnd = end
assertEquals(fullText, textBeforeCursor + selectedText + textAfterCursor)
latinIME.onUpdateSelection(oldStart, oldEnd, start, end, composingStart, composingEnd)
handleMessages()
if (weirdTextField) {
latinIME.mHandler.onStartInput(ei, true) // essentially does nothing
latinIME.mHandler.onStartInputView(ei, true) // does the thing
handleMessages()
}
assertEquals(fullText, getText())
assertEquals(start, selectionStart)
assertEquals(end, selectionEnd)
checkConnectionConsistency()
}
// assumes we have nothing selected
private fun getCursorPosition(): Int {
assertEquals(cursor, connection.expectedSelectionStart)
assertEquals(cursor, connection.expectedSelectionEnd)
return cursor
}