-
-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathSimpleKeyboardIME.kt
More file actions
523 lines (455 loc) · 21.5 KB
/
SimpleKeyboardIME.kt
File metadata and controls
523 lines (455 loc) · 21.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
package com.simplemobiletools.keyboard.services
import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.drawable.Icon
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.icu.text.BreakIterator
import android.icu.util.ULocale
import android.inputmethodservice.InputMethodService
import android.os.Build
import android.os.Bundle
import android.text.InputType.*
import android.text.TextUtils
import android.util.Log
import android.util.Size
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.*
import android.view.inputmethod.EditorInfo.IME_ACTION_NONE
import android.view.inputmethod.EditorInfo.IME_FLAG_NO_ENTER_ACTION
import android.view.inputmethod.EditorInfo.IME_MASK_ACTION
import android.widget.inline.InlinePresentationSpec
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
import androidx.appcompat.widget.SearchView
import androidx.autofill.inline.UiVersions
import androidx.autofill.inline.common.ImageViewStyle
import androidx.autofill.inline.common.TextViewStyle
import androidx.autofill.inline.common.ViewStyle
import androidx.autofill.inline.v1.InlineSuggestionUi
import androidx.core.graphics.drawable.toBitmap
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isNougatPlus
import com.simplemobiletools.keyboard.R
import com.simplemobiletools.keyboard.databinding.KeyboardViewKeyboardBinding
import com.simplemobiletools.keyboard.extensions.config
import com.simplemobiletools.keyboard.extensions.getStrokeColor
import com.simplemobiletools.keyboard.extensions.safeStorageContext
import com.simplemobiletools.keyboard.helpers.*
import com.simplemobiletools.keyboard.interfaces.OnKeyboardActionListener
import com.simplemobiletools.keyboard.views.MyKeyboardView
import java.io.ByteArrayOutputStream
import java.util.Locale
// based on https://www.androidauthority.com/lets-build-custom-keyboard-android-832362/
class SimpleKeyboardIME : InputMethodService(), OnKeyboardActionListener, SharedPreferences.OnSharedPreferenceChangeListener {
private var SHIFT_PERM_TOGGLE_SPEED = 500 // how quickly do we have to doubletap shift to enable permanent caps lock
private val KEYBOARD_LETTERS = 0
private val KEYBOARD_SYMBOLS = 1
private val KEYBOARD_SYMBOLS_SHIFT = 2
private val KEYBOARD_NUMBERS = 3
private val KEYBOARD_PHONE = 4
private var keyboard: MyKeyboard? = null
private var keyboardView: MyKeyboardView? = null
private var lastShiftPressTS = 0L
private var keyboardMode = KEYBOARD_LETTERS
private var inputTypeClass = TYPE_CLASS_TEXT
private var inputTypeClassVariation = TYPE_CLASS_TEXT
private var enterKeyType = IME_ACTION_NONE
private var switchToLetters = false
private var breakIterator: BreakIterator? = null
private var otherInputConnection:OtherInputConnection? = null
private lateinit var binding: KeyboardViewKeyboardBinding
companion object{
/*true and false define the inputconnection where is input is send like
* if true-> send to emoji searchview
* if false -> send to currentinputconnection*/
var searching=false
}
override fun onInitializeInterface() {
super.onInitializeInterface()
safeStorageContext.getSharedPrefs().registerOnSharedPreferenceChangeListener(this)
}
override fun onCreateInputView(): View {
binding = KeyboardViewKeyboardBinding.inflate(layoutInflater)
keyboardView = binding.keyboardView.apply {
setKeyboardHolder(binding)
setKeyboard(keyboard!!)
setEditorInfo(currentInputEditorInfo)
mOnKeyboardActionListener = this@SimpleKeyboardIME
}
return binding.root
}
override fun onPress(primaryCode: Int) {
if (primaryCode != 0) {
keyboardView?.vibrateIfNeeded()
}
}
override fun onStartInput(attribute: EditorInfo?, restarting: Boolean) {
super.onStartInput(attribute, restarting)
inputTypeClass = attribute!!.inputType and TYPE_MASK_CLASS
inputTypeClassVariation = attribute.inputType and TYPE_MASK_VARIATION
enterKeyType = attribute.imeOptions and (IME_MASK_ACTION or IME_FLAG_NO_ENTER_ACTION)
keyboard = createNewKeyboard()
keyboardView?.setKeyboard(keyboard!!)
keyboardView?.setEditorInfo(attribute)
if (isNougatPlus()) {
breakIterator = BreakIterator.getCharacterInstance(ULocale.getDefault())
}
updateShiftKeyState()
}
private fun updateShiftKeyState() {
if (keyboard?.mShiftState == ShiftState.ON_PERMANENT) {
return
}
val editorInfo = currentInputEditorInfo
if (config.enableSentencesCapitalization && editorInfo != null && editorInfo.inputType != TYPE_NULL) {
if (currentInputConnection.getCursorCapsMode(editorInfo.inputType) != 0 && !searching) {
keyboard?.setShifted(ShiftState.ON_ONE_CHAR)
keyboardView?.invalidateAllKeys()
return
}
}
keyboard?.setShifted(ShiftState.OFF)
keyboardView?.invalidateAllKeys()
}
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreateInlineSuggestionsRequest(uiExtras: Bundle): InlineSuggestionsRequest {
val maxWidth = resources.getDimensionPixelSize(R.dimen.suggestion_max_width)
return InlineSuggestionsRequest.Builder(
listOf(
InlinePresentationSpec.Builder(
Size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT),
Size(maxWidth, ViewGroup.LayoutParams.WRAP_CONTENT)
).setStyle(buildSuggestionTextStyle()).build()
)
).setMaxSuggestionCount(InlineSuggestionsRequest.SUGGESTION_COUNT_UNLIMITED)
.build()
}
@RequiresApi(Build.VERSION_CODES.R)
override fun onInlineSuggestionsResponse(response: InlineSuggestionsResponse): Boolean {
keyboardView?.clearClipboardViews()
response.inlineSuggestions.forEach {
it.inflate(this, Size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT), this.mainExecutor) { view ->
// If inflation fails for whatever reason, passed view will be null
if (view != null) {
keyboardView?.addToClipboardViews(view, addToFront = it.info.isPinned)
}
}
}
return true
}
override fun onKey(code: Int) {
val inputConnection = getMyCurrentInputConnection()
if (keyboard == null || inputConnection == null) {
return
}
if (code != MyKeyboard.KEYCODE_SHIFT) {
lastShiftPressTS = 0
}
when (code) {
MyKeyboard.KEYCODE_DELETE -> {
val selectedText = inputConnection.getSelectedText(0)
if (TextUtils.isEmpty(selectedText)) {
val count = getCountToDelete(inputConnection)
inputConnection.deleteSurroundingText(count, 0)
} else {
inputConnection.commitText("", 1)
}
}
MyKeyboard.KEYCODE_SHIFT -> {
if (keyboardMode == KEYBOARD_LETTERS) {
when {
keyboard!!.mShiftState == ShiftState.ON_PERMANENT -> keyboard!!.mShiftState = ShiftState.OFF
System.currentTimeMillis() - lastShiftPressTS < SHIFT_PERM_TOGGLE_SPEED -> keyboard!!.mShiftState = ShiftState.ON_PERMANENT
keyboard!!.mShiftState == ShiftState.ON_ONE_CHAR -> keyboard!!.mShiftState = ShiftState.OFF
keyboard!!.mShiftState == ShiftState.OFF -> keyboard!!.mShiftState = ShiftState.ON_ONE_CHAR
}
lastShiftPressTS = System.currentTimeMillis()
} else {
val keyboardXml = if (keyboardMode == KEYBOARD_SYMBOLS) {
keyboardMode = KEYBOARD_SYMBOLS_SHIFT
R.xml.keys_symbols_shift
} else {
keyboardMode = KEYBOARD_SYMBOLS
R.xml.keys_symbols
}
keyboard = MyKeyboard(this, keyboardXml, enterKeyType)
keyboardView!!.setKeyboard(keyboard!!)
}
keyboardView!!.invalidateAllKeys()
}
MyKeyboard.KEYCODE_ENTER -> {
val imeOptionsActionId = getImeOptionsActionId()
if (imeOptionsActionId != IME_ACTION_NONE) {
inputConnection.performEditorAction(imeOptionsActionId)
} else {
inputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
inputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
}
}
MyKeyboard.KEYCODE_MODE_CHANGE -> {
val keyboardXml = if (keyboardMode == KEYBOARD_LETTERS) {
keyboardMode = KEYBOARD_SYMBOLS
R.xml.keys_symbols
} else {
keyboardMode = KEYBOARD_LETTERS
getKeyboardLayoutXML()
}
keyboard = MyKeyboard(this, keyboardXml, enterKeyType)
keyboardView!!.setKeyboard(keyboard!!)
}
MyKeyboard.KEYCODE_EMOJI -> {
if(!searching){
keyboardView?.openEmojiPalette()
}
}
else -> {
var codeChar = code.toChar()
val originalText = inputConnection.getExtractedText(ExtractedTextRequest(), 0)?.text
if (Character.isLetter(codeChar) && keyboard!!.mShiftState > ShiftState.OFF) {
if (baseContext.config.keyboardLanguage == LANGUAGE_TURKISH_Q) {
codeChar = codeChar.toString().uppercase(Locale.forLanguageTag("tr")).single()
} else {
codeChar = Character.toUpperCase(codeChar)
}
}
// If the keyboard is set to symbols and the user presses space, we usually should switch back to the letters keyboard.
// However, avoid doing that in cases when the EditText for example requires numbers as the input.
// We can detect that by the text not changing on pressing Space.
if (keyboardMode != KEYBOARD_LETTERS && inputTypeClass == TYPE_CLASS_TEXT && code == MyKeyboard.KEYCODE_SPACE) {
inputConnection.commitText(codeChar.toString(), 1)
val newText = inputConnection.getExtractedText(ExtractedTextRequest(), 0)?.text
if (originalText != newText) {
switchToLetters = true
}
} else {
when {
!originalText.isNullOrEmpty() && cachedVNTelexData.isNotEmpty() -> {
val fullText = originalText.toString() + codeChar.toString()
val lastIndexEmpty = if (fullText.contains(" ")) {
fullText.lastIndexOf(" ")
} else 0
if (lastIndexEmpty >= 0) {
val word = fullText.subSequence(lastIndexEmpty, fullText.length).trim().toString()
val wordChars = word.toCharArray()
val predictWord = StringBuilder()
for (char in wordChars.size - 1 downTo 0) {
predictWord.append(wordChars[char])
val shouldChangeText = predictWord.reverse().toString()
if (cachedVNTelexData.containsKey(shouldChangeText)) {
inputConnection.setComposingRegion(fullText.length - shouldChangeText.length, fullText.length)
inputConnection.setComposingText(cachedVNTelexData[shouldChangeText], fullText.length)
inputConnection.setComposingRegion(fullText.length, fullText.length)
return
}
}
inputConnection.commitText(codeChar.toString(), 1)
updateShiftKeyState()
}
}
else -> {
inputConnection.commitText(codeChar.toString(), 1)
updateShiftKeyState()
}
}
}
}
}
}
private fun getCountToDelete(inputConnection: InputConnection): Int {
if (breakIterator == null || !isNougatPlus()) {
return 1
}
val prevText = inputConnection.getTextBeforeCursor(8, 0)
if (!TextUtils.isEmpty(prevText)) {
return breakIterator?.let {
it.setText(prevText.toString())
val end = it.last()
val start = it.previous()
(end - (if (start == BreakIterator.DONE) 0 else start)).coerceIn(0, prevText?.length)
} ?: 1
}
return 1
}
override fun onActionUp() {
if (switchToLetters) {
// TODO: Change keyboardMode to enum class
keyboardMode = KEYBOARD_LETTERS
keyboard = MyKeyboard(this, getKeyboardLayoutXML(), enterKeyType)
val editorInfo = currentInputEditorInfo
if (editorInfo != null && editorInfo.inputType != TYPE_NULL && keyboard?.mShiftState != ShiftState.ON_PERMANENT) {
if (currentInputConnection.getCursorCapsMode(editorInfo.inputType) != 0) {
keyboard?.setShifted(ShiftState.ON_ONE_CHAR)
}
}
keyboardView!!.setKeyboard(keyboard!!)
switchToLetters = false
}
}
override fun moveCursorLeft() {
moveCursor(false)
}
override fun moveCursorRight() {
moveCursor(true)
}
override fun onText(text: String) {
getMyCurrentInputConnection().commitText(text, 1)
}
override fun reloadKeyboard() {
val keyboard = createNewKeyboard()
this.keyboard = keyboard
keyboardView?.setKeyboard(keyboard)
}
override fun searchViewFocused(searchView: AppCompatAutoCompleteTextView) {
otherInputConnection = OtherInputConnection(searchView)
}
private fun createNewKeyboard(): MyKeyboard {
val keyboardXml = when (inputTypeClass) {
TYPE_CLASS_NUMBER -> {
keyboardMode = KEYBOARD_NUMBERS
R.xml.keys_numbers
}
TYPE_CLASS_PHONE -> {
keyboardMode = KEYBOARD_PHONE
R.xml.keys_phone
}
TYPE_CLASS_DATETIME -> {
keyboardMode = KEYBOARD_SYMBOLS
R.xml.keys_symbols
}
else -> {
keyboardMode = KEYBOARD_LETTERS
getKeyboardLayoutXML()
}
}
return MyKeyboard(
context = this,
xmlLayoutResId = keyboardXml,
enterKeyType = enterKeyType,
)
}
override fun onUpdateSelection(oldSelStart: Int, oldSelEnd: Int, newSelStart: Int, newSelEnd: Int, candidatesStart: Int, candidatesEnd: Int) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd)
if (newSelStart == newSelEnd) {
keyboardView?.closeClipboardManager()
}
updateShiftKeyState()
}
override fun onUpdateCursorAnchorInfo(cursorAnchorInfo: CursorAnchorInfo?) {
super.onUpdateCursorAnchorInfo(cursorAnchorInfo)
updateShiftKeyState()
}
private fun moveCursor(moveRight: Boolean) {
val extractedText = currentInputConnection?.getExtractedText(ExtractedTextRequest(), 0) ?: return
var newCursorPosition = extractedText.selectionStart
newCursorPosition = if (moveRight) {
newCursorPosition + 1
} else {
newCursorPosition - 1
}
currentInputConnection?.setSelection(newCursorPosition, newCursorPosition)
}
private fun getImeOptionsActionId(): Int {
return if (currentInputEditorInfo.imeOptions and IME_FLAG_NO_ENTER_ACTION != 0) {
IME_ACTION_NONE
} else {
currentInputEditorInfo.imeOptions and IME_MASK_ACTION
}
}
private fun getKeyboardLayoutXML(): Int {
return when (baseContext.config.keyboardLanguage) {
LANGUAGE_BENGALI -> R.xml.keys_letters_bengali
LANGUAGE_BULGARIAN -> R.xml.keys_letters_bulgarian
LANGUAGE_DANISH -> R.xml.keys_letters_danish
LANGUAGE_ENGLISH_DVORAK -> R.xml.keys_letters_english_dvorak
LANGUAGE_ENGLISH_QWERTZ -> R.xml.keys_letters_english_qwertz
LANGUAGE_FRENCH_AZERTY -> R.xml.keys_letters_french_azerty
LANGUAGE_FRENCH_BEPO -> R.xml.keys_letters_french_bepo
LANGUAGE_GERMAN -> R.xml.keys_letters_german
LANGUAGE_GREEK -> R.xml.keys_letters_greek
LANGUAGE_LITHUANIAN -> R.xml.keys_letters_lithuanian
LANGUAGE_NORWEGIAN -> R.xml.keys_letters_norwegian
LANGUAGE_POLISH -> R.xml.keys_letters_polish
LANGUAGE_ROMANIAN -> R.xml.keys_letters_romanian
LANGUAGE_RUSSIAN -> R.xml.keys_letters_russian
LANGUAGE_SLOVENIAN -> R.xml.keys_letters_slovenian
LANGUAGE_SWEDISH -> R.xml.keys_letters_swedish
LANGUAGE_SPANISH -> R.xml.keys_letters_spanish_qwerty
LANGUAGE_TURKISH_Q -> R.xml.keys_letters_turkish_q
LANGUAGE_UKRAINIAN -> R.xml.keys_letters_ukrainian
else -> R.xml.keys_letters_english_qwerty
}
}
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("RestrictedApi", "UseCompatLoadingForDrawables")
private fun buildSuggestionTextStyle(): Bundle {
val stylesBuilder = UiVersions.newStylesBuilder()
val verticalPadding = resources.getDimensionPixelSize(R.dimen.small_margin)
val horizontalPadding = resources.getDimensionPixelSize(R.dimen.activity_margin)
val textSize = resources.getDimension(R.dimen.label_text_size) / resources.displayMetrics.scaledDensity
val rippleBg = resources.getDrawable(R.drawable.clipboard_background, theme) as RippleDrawable
val layerDrawable = rippleBg.findDrawableByLayerId(R.id.clipboard_background_holder) as LayerDrawable
layerDrawable.findDrawableByLayerId(R.id.clipboard_background_stroke).applyColorFilter(getStrokeColor())
layerDrawable.findDrawableByLayerId(R.id.clipboard_background_shape).applyColorFilter(getProperBackgroundColor())
val maxWidth = resources.getDimensionPixelSize(R.dimen.suggestion_max_width)
val height = resources.getDimensionPixelSize(R.dimen.label_text_size) + verticalPadding * 2
val chipBackgroundIcon: Icon = rippleBg.toBitmap(width = maxWidth, height = height).toIcon()
val chipStyle =
ViewStyle.Builder()
// don't use Icon.createWithBitmap(), it crashes the app. Issue https://github.com/SimpleMobileTools/Simple-Keyboard/issues/248
.setBackground(chipBackgroundIcon)
.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
.build()
val iconStyle = ImageViewStyle.Builder().build()
val style = InlineSuggestionUi.newStyleBuilder()
.setSingleIconChipStyle(chipStyle)
.setChipStyle(chipStyle)
.setStartIconStyle(iconStyle)
.setEndIconStyle(iconStyle)
.setSingleIconChipIconStyle(iconStyle)
.setTitleStyle(
TextViewStyle.Builder()
.setLayoutMargin(0, 0, horizontalPadding, 0)
.setTextColor(getProperTextColor())
.setTextSize(textSize)
.build()
)
.setSubtitleStyle(
TextViewStyle.Builder()
.setTextColor(getProperTextColor())
.setTextSize(textSize)
.build()
)
.build()
stylesBuilder.addStyle(style)
return stylesBuilder.build()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
keyboardView?.setupKeyboard()
}
private fun Bitmap.toIcon(): Icon {
val byteArray: ByteArray = ByteArrayOutputStream().let { outputStream ->
this.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
outputStream.toByteArray()
}
this.recycle()
return Icon.createWithData(byteArray, 0, byteArray.size)
}
fun getMyCurrentInputConnection():InputConnection{
if (searching){
if(otherInputConnection==null){
Log.i("thisISrunn", "yes2")
return currentInputConnection
}else{
Log.i("thisISrunn", "yes")
return otherInputConnection!!
}
}else{
Log.i("thisISrunn", "yes3")
return currentInputConnection
}
}
}