-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathKeyboardViewController.swift
3147 lines (2779 loc) · 112 KB
/
KeyboardViewController.swift
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
/**
* Classes for the parent keyboard view controller that language keyboards.
*
* Copyright (C) 2024 Scribe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import GRDB
import UIKit
/// The parent KeyboardViewController class that is inherited by all Scribe keyboards.
class KeyboardViewController: UIInputViewController {
var keyboardView: UIView!
// Stack views that are populated with they keyboard rows.
@IBOutlet var stackViewNum: UIStackView!
@IBOutlet var stackView0: UIStackView!
@IBOutlet var stackView1: UIStackView!
@IBOutlet var stackView2: UIStackView!
@IBOutlet var stackView3: UIStackView!
private var tipView: ToolTipView?
/// Changes the height of `stackViewNum` depending on device type and size.
func conditionallyShowTopNumbersRow() {
if DeviceType.isPhone {
if let stackViewNum = stackViewNum {
view.addConstraint(
NSLayoutConstraint(
item: stackViewNum, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0
)
)
}
} else if DeviceType.isPad {
// Update the size of the numbers row to add it to the view.
if usingExpandedKeyboard {
let numbersRowHeight = scribeKey.frame.height * 1.8
if let stackViewNum = stackViewNum {
view.addConstraint(
NSLayoutConstraint(
item: stackViewNum,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: numbersRowHeight
)
)
}
} else {
if let stackViewNum = stackViewNum {
view.addConstraint(
NSLayoutConstraint(
item: stackViewNum, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0
)
)
}
}
}
}
/// Changes the keyboard state such that the letters view will be shown.
func changeKeyboardToLetterKeys() {
keyboardState = .letters
loadKeys()
}
/// Changes the keyboard state such that the numbers view will be shown.
func changeKeyboardToNumberKeys() {
keyboardState = .numbers
shiftButtonState = .normal
loadKeys()
}
/// Changes the keyboard state such that the symbols view will be shown.
func changeKeyboardToSymbolKeys() {
keyboardState = .symbols
loadKeys()
}
// MARK: Display Activation Functions
/// Function to load the keyboard interface into which keyboardView is instantiated.
func loadInterface() {
let keyboardNib = UINib(nibName: "Keyboard", bundle: nil)
keyboardView = keyboardNib.instantiate(withOwner: self, options: nil)[0] as? UIView
keyboardView.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(keyboardView)
// Override prior command states from previous sessions.
commandState = .idle
loadKeys()
// Set tap handler for info button on CommandBar.
commandBar.infoButtonTapHandler = { [weak self] in
commandState = .displayInformation
conjViewShiftButtonsState = .leftInactive
self?.loadKeys()
}
}
/// Activates a button by assigning key touch functions for their given actions.
///
/// - Parameters
/// - btn: the button to be activated.
func activateBtn(btn: UIButton) {
btn.addTarget(self, action: #selector(executeKeyActions), for: .touchUpInside)
btn.addTarget(self, action: #selector(keyTouchDown), for: .touchDown)
btn.addTarget(self, action: #selector(keyUntouched), for: .touchDragExit)
btn.isUserInteractionEnabled = true
}
/// Deactivates a button by removing key touch functions for their given actions and making it clear.
///
/// - Parameters
/// - btn: the button to be deactivated.
func deactivateBtn(btn: UIButton) {
btn.setTitle("", for: .normal)
btn.configuration?.image = nil
btn.backgroundColor = UIColor.clear
btn.removeTarget(self, action: #selector(executeKeyActions), for: .touchUpInside)
btn.removeTarget(self, action: #selector(keyTouchDown), for: .touchDown)
btn.removeTarget(self, action: #selector(keyUntouched), for: .touchDragExit)
btn.isUserInteractionEnabled = false
}
// MARK: Override UIInputViewController Functions
/// Includes adding custom view sizing constraints.
override func updateViewConstraints() {
super.updateViewConstraints()
checkLandscapeMode()
if DeviceType.isPhone {
if isLandscapeView {
keyboardHeight = 200
} else {
keyboardHeight = 270
}
} else if DeviceType.isPad {
// Expanded keyboard on larger iPads can be higher.
if UIScreen.main.bounds.width > 768 {
if isLandscapeView {
keyboardHeight = 430
} else {
keyboardHeight = 360
}
} else {
if isLandscapeView {
keyboardHeight = 420
} else {
keyboardHeight = 340
}
}
}
guard let view = view else {
fatalError("The view is nil.")
}
let heightConstraint = NSLayoutConstraint(
item: view,
attribute: NSLayoutConstraint.Attribute.height,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1.0,
constant: keyboardHeight
)
view.addConstraint(heightConstraint)
keyboardView.frame.size = view.frame.size
}
// Button to be assigned as the select keyboard button if necessary.
@IBOutlet var selectKeyboardButton: UIButton!
/// Includes the following:
/// - Assignment of the proxy
/// - Loading the Scribe interface
/// - Making keys letters
/// - Adding the keyboard selector target
override func viewDidLoad() {
super.viewDidLoad()
// If alternateKeysView is already added than remove it so it's not colored wrong.
if view.viewWithTag(1001) != nil {
let viewWithTag = view.viewWithTag(1001)
viewWithTag?.removeFromSuperview()
alternatesShapeLayer.removeFromSuperlayer()
}
proxy = textDocumentProxy as UITextDocumentProxy
keyboardState = .letters
annotationState = false
isFirstKeyboardLoad = true
loadInterface()
isFirstKeyboardLoad = false
selectKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
}
/// Includes hiding the keyboard selector button if it is not needed for the current device.
override func viewWillLayoutSubviews() {
selectKeyboardButton.isHidden = !needsInputModeSwitchKey
super.viewWillLayoutSubviews()
}
/// Includes updateViewConstraints to change the keyboard height given device type and orientation.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateViewConstraints()
isFirstKeyboardLoad = true
loadKeys()
isFirstKeyboardLoad = false
}
/// Includes:
/// - updateViewConstraints to change the keyboard height
/// - A call to loadKeys to reload the display after an orientation change
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.updateViewConstraints()
self.loadKeys()
})
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { _ in
isFirstKeyboardLoad = true
self.loadKeys()
isFirstKeyboardLoad = false
}
}
/// Overrides the previous color variables if the user switches between light and dark mode.
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// If alternateKeysView is already added than remove it so it's not colored wrong.
if view.viewWithTag(1001) != nil {
let viewWithTag = view.viewWithTag(1001)
viewWithTag?.removeFromSuperview()
alternatesShapeLayer.removeFromSuperlayer()
}
annotationState = false
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { _ in
isFirstKeyboardLoad = true
self.loadKeys()
isFirstKeyboardLoad = false
}
}
// MARK: Scribe Command Elements
// Partitions for autocomplete and autosuggest
@IBOutlet var leftAutoPartition: UILabel!
@IBOutlet var rightAutoPartition: UILabel!
/// Sets the user interaction potential of the partitions for autocomplete and autosuggest.
func setAutoActionPartitions() {
leftAutoPartition.isUserInteractionEnabled = false
rightAutoPartition.isUserInteractionEnabled = false
}
/// Shows the partitions for autocomplete and autosuggest.
func conditionallyShowAutoActionPartitions() {
if commandState == .idle {
if UITraitCollection.current.userInterfaceStyle == .light {
leftAutoPartition.backgroundColor = specialKeyColor
rightAutoPartition.backgroundColor = specialKeyColor
} else if UITraitCollection.current.userInterfaceStyle == .dark {
leftAutoPartition.backgroundColor = UIColor(cgColor: commandBarPlaceholderColorCG)
rightAutoPartition.backgroundColor = UIColor(cgColor: commandBarPlaceholderColorCG)
}
}
}
/// Hides the partitions for autocomplete and autosuggest.
/// Note: this function is called during command mode when the commandBar is viewable and the Scribe key state.
func hideAutoActionPartitions() {
leftAutoPartition.backgroundColor = .clear
rightAutoPartition.backgroundColor = .clear
}
// Logic to create notification tooltip.
func createInformationStateDatasource(text: NSMutableAttributedString, backgroundColor: UIColor) -> ToolTipViewDatasource {
let theme = ToolTipViewTheme(backgroundColor: backgroundColor, textFont: nil, textColor: keyCharColor, textAlignment: .center, cornerRadius: 10, masksToBounds: true)
return ToolTipViewDatasource(content: text, theme: theme)
}
/// Sets the tooltip to display information to the user.
func setInformationState() {
setFormDisplay1x1View()
let contentData = InformationToolTipData.getContent()
let datasources = contentData.compactMap { text in
createInformationStateDatasource(text: text, backgroundColor: keyColor)
}
tipView = ToolTipView(datasources: datasources)
bindTooltipview()
guard let tipView = tipView else { return }
tipView.translatesAutoresizingMaskIntoConstraints = false
formKeySingle.addSubview(tipView)
formKeySingle.isUserInteractionEnabled = false
tipView.leadingAnchor.constraint(
equalTo: formKeySingle.leadingAnchor
).isActive = true
tipView.trailingAnchor.constraint(
equalTo: formKeySingle.trailingAnchor
).isActive = true
tipView.topAnchor.constraint(equalTo: formKeySingle.topAnchor).isActive = true
tipView.bottomAnchor.constraint(equalTo: formKeySingle.bottomAnchor).isActive = true
styleBtn(btn: formKeySingle, title: "", radius: keyCornerRadius)
}
// Shifts the view of the information tooltip view.
private func bindTooltipview() {
tipView?.didUpdatePage = { [weak self] currentState in
conjViewShiftButtonsState = currentState
guard let weakSelf = self else { return }
switch currentState {
case .rightInactive:
weakSelf.shiftFormsDisplayRight.isUserInteractionEnabled = false
case .leftInactive:
weakSelf.shiftFormsDisplayLeft.isUserInteractionEnabled = false
case .bothActive:
weakSelf.activateBtn(btn: weakSelf.shiftFormsDisplayLeft)
weakSelf.activateBtn(btn: weakSelf.shiftFormsDisplayRight)
default:
break
}
weakSelf.styleShiftButtons()
}
}
/// Styles the shift buttons for the displayInformation states.
private func styleShiftButtons() {
styleBtn(btn: shiftFormsDisplayLeft, title: "", radius: keyCornerRadius)
styleIconBtn(
btn: shiftFormsDisplayLeft,
color: ![.bothInactive, .leftInactive].contains(conjViewShiftButtonsState) ? keyCharColor : commandBarPlaceholderColor,
iconName: "chevron.left"
)
styleBtn(btn: shiftFormsDisplayRight, title: "", radius: keyCornerRadius)
styleIconBtn(
btn: shiftFormsDisplayRight,
color: ![.bothInactive, .rightInactive].contains(conjViewShiftButtonsState) ? keyCharColor : commandBarPlaceholderColor,
iconName: "chevron.right"
)
}
/// Generate emoji suggestions or completions for a given word.
///
/// - Parameters
/// - word: the word for which corresponding emojis should be shown for.
func getEmojiAutoSuggestions(for word: String) {
let emojisToDisplay = LanguageDBManager.shared.queryEmojis(of: word.lowercased())
if !emojisToDisplay[0].isEmpty {
emojisToDisplayArray = [String]()
currentEmojiTriggerWord = word.lowercased()
if !emojisToDisplay[2].isEmpty && DeviceType.isPad {
for i in 0 ..< 3 {
emojisToDisplayArray.append(emojisToDisplay[i])
}
autoAction2Visible = false
emojisToShow = .three
if UITraitCollection.current.userInterfaceStyle == .light {
padEmojiDivider0.backgroundColor = specialKeyColor
padEmojiDivider1.backgroundColor = specialKeyColor
} else if UITraitCollection.current.userInterfaceStyle == .dark {
padEmojiDivider0.backgroundColor = UIColor(cgColor: commandBarPlaceholderColorCG)
padEmojiDivider1.backgroundColor = UIColor(cgColor: commandBarPlaceholderColorCG)
}
conditionallyHideEmojiDividers()
} else if !emojisToDisplay[1].isEmpty {
for i in 0 ..< 2 {
emojisToDisplayArray.append(emojisToDisplay[i])
}
autoAction2Visible = false
emojisToShow = .two
if UITraitCollection.current.userInterfaceStyle == .light {
phoneEmojiDivider.backgroundColor = specialKeyColor
} else if UITraitCollection.current.userInterfaceStyle == .dark {
phoneEmojiDivider.backgroundColor = UIColor(cgColor: commandBarPlaceholderColorCG)
}
conditionallyHideEmojiDividers()
} else {
emojisToDisplayArray.append(emojisToDisplay[0])
emojisToShow = .one
}
}
}
/// Generates an array of the three autocomplete words.
func getAutocompletions() {
completionWords = [" ", " ", " "]
if let documentContext = proxy.documentContextBeforeInput, !documentContext.isEmpty {
if let inString = proxy.documentContextBeforeInput {
// To only focus on the current word as prefix in autocomplete.
currentPrefix = inString.replacingOccurrences(of: pastStringInTextProxy, with: "")
if currentPrefix.hasPrefix("(") || currentPrefix.hasPrefix("#") ||
currentPrefix.hasPrefix("/") || currentPrefix.hasPrefix("\"") {
currentPrefix = currentPrefix.replacingOccurrences(of: #"[\"(#\/]"#, with: "", options: .regularExpression)
}
// Post commands pastStringInTextProxy is "", so take last word.
if currentPrefix.contains(" ") {
currentPrefix = currentPrefix.components(
separatedBy: " "
).last ?? ""
}
// If there's a line break, take the word after it.
if currentPrefix.contains("\n") {
currentPrefix = currentPrefix.components(
separatedBy: "\n"
).last ?? ""
}
// Trigger autocompletions for selected text instead.
if proxy.selectedText != nil && [.idle, .selectCommand, .alreadyPlural, .invalid].contains(commandState) {
if let selectedText = proxy.selectedText {
currentPrefix = selectedText
}
}
// Get options for completion that start with the current prefix and are not just one letter.
let completionOptions = LanguageDBManager.shared.queryAutocompletions(word: currentPrefix)
if !completionOptions[0].isEmpty {
if completionOptions.count <= 3 {
for i in 0 ..< completionOptions.count {
if shiftButtonState == .shift {
completionWords[i] = completionOptions[i].capitalize()
} else if capsLockButtonState == .locked {
completionWords[i] = completionOptions[i].uppercased()
} else if currentPrefix.isCapitalized {
if completionOptions[i].isUppercase {
completionWords[i] = completionOptions[i]
} else {
completionWords[i] = completionOptions[i].capitalize()
}
} else {
completionWords[i] = completionOptions[i]
}
}
} else {
for i in 0 ..< 3 {
if shiftButtonState == .shift {
completionWords[i] = completionOptions[i].capitalize()
} else if capsLockButtonState == .locked {
completionWords[i] = completionOptions[i].uppercased()
} else if currentPrefix.isCapitalized {
if completionOptions[i].isUppercase {
completionWords[i] = completionOptions[i]
} else {
completionWords[i] = completionOptions[i].capitalize()
}
} else {
completionWords[i] = completionOptions[i]
}
}
}
}
// Disable the third auto action button if we'll have emoji suggestions.
if emojiAutosuggestIsEnabled() {
getEmojiAutoSuggestions(for: currentPrefix)
}
} else {
getDefaultAutosuggestions()
}
} else {
// For getting words on launch when the user hasn't typed anything in the proxy.
getDefaultAutosuggestions()
}
}
/// Gets consistent autosguestions for all pronouns in the given language.
/// Note: currently only works for German, Spanish and French languages.
func getPronounAutosuggestions() {
let prefix = proxy.documentContextBeforeInput?.components(separatedBy: " ").secondToLast() ?? ""
completionWords = [String]()
for i in 0 ..< 3 {
// Get conjugations of the preselected verbs.
if let tense = pronounAutosuggestionTenses[prefix.lowercased()] {
let outputCols = [tense]
var suggestion = LanguageDBManager.shared.queryVerb(of: verbsAfterPronounsArray[i], with: outputCols)[0]
if suggestion == "" {
suggestion = verbsAfterPronounsArray[i]
}
if suggestion == "REFLEXIVE_PRONOUN" && controllerLanguage == "Spanish" {
suggestion = getESReflexivePronoun(pronoun: prefix.lowercased())
}
if shiftButtonState == .shift {
completionWords.append(suggestion.capitalize())
} else if capsLockButtonState == .locked {
completionWords.append(suggestion.uppercased())
} else {
completionWords.append(suggestion)
}
}
}
}
/// Generates an array of three words that serve as baseline autosuggestions.
func getDefaultAutosuggestions() {
completionWords = [String]()
for i in 0 ..< 3 {
if allowUndo {
completionWords.append(previousWord)
continue
}
if shiftButtonState == .shift {
completionWords.append(baseAutosuggestions[i].capitalize())
} else if capsLockButtonState == .locked {
completionWords.append(baseAutosuggestions[i].uppercased())
} else {
completionWords.append(baseAutosuggestions[i])
}
}
}
/// Generates an array of the three autosuggest words.
func getAutosuggestions() {
var prefix = proxy.documentContextBeforeInput?.components(
separatedBy: " "
).secondToLast() ?? ""
if emojiAutoActionRepeatPossible {
prefix = currentEmojiTriggerWord
}
// If there's a line break, take the word after it.
if prefix.contains("\n") {
prefix = prefix.components(
separatedBy: "\n"
).last ?? ""
}
// Trigger autocompletions for selected text instead.
if proxy.selectedText != nil && [.idle, .selectCommand, .alreadyPlural, .invalid].contains(commandState) {
if let selectedText = proxy.selectedText {
prefix = selectedText
}
}
if prefix.isNumeric {
completionWords = numericAutosuggestions
} else if ["English", "French", "German", "Spanish"].contains(controllerLanguage) && pronounAutosuggestionTenses.keys.contains(prefix.lowercased()) {
getPronounAutosuggestions()
} else {
// We have to consider these different cases as the key always has to match.
// Else, even if the lowercased prefix is present in the dictionary, if the actual prefix isn't present we won't get an output.
let suggestionsLowerCasePrefix = LanguageDBManager.shared.queryAutosuggestions(of: prefix.lowercased())
let suggestionsCapitalizedPrefix = LanguageDBManager.shared.queryAutosuggestions(of: prefix.capitalized)
if !suggestionsLowerCasePrefix[0].isEmpty {
completionWords = [String]()
for i in 0 ..< 3 {
if allowUndo {
completionWords.append(previousWord)
continue
}
if shiftButtonState == .shift {
completionWords.append(suggestionsLowerCasePrefix[i].capitalize())
} else if capsLockButtonState == .locked {
completionWords.append(suggestionsLowerCasePrefix[i].uppercased())
} else {
let nounForm = LanguageDBManager.shared.queryNounForm(of: suggestionsLowerCasePrefix[i])[0]
hasNounForm = !nounForm.isEmpty
if !hasNounForm {
completionWords.append(suggestionsLowerCasePrefix[i].lowercased())
} else {
completionWords.append(suggestionsLowerCasePrefix[i])
}
}
}
} else if !suggestionsCapitalizedPrefix[0].isEmpty {
completionWords = [String]()
for i in 0 ..< 3 {
if allowUndo {
completionWords.append(previousWord)
continue
}
if shiftButtonState == .shift {
completionWords.append(suggestionsCapitalizedPrefix[i].capitalize())
} else if capsLockButtonState == .locked {
completionWords.append(suggestionsCapitalizedPrefix[i].uppercased())
} else {
completionWords.append(suggestionsCapitalizedPrefix[i])
}
}
} else {
getDefaultAutosuggestions()
}
}
// Disable the third auto action button if we'll have emoji suggestions.
if emojiAutosuggestIsEnabled() {
getEmojiAutoSuggestions(for: prefix)
}
}
/// Sets up command buttons to execute autocomplete and autosuggest.
func conditionallySetAutoActionBtns() {
// Clear noun auto action annotations.
autoActionAnnotationBtns.forEach { $0.removeFromSuperview() }
autoActionAnnotationBtns.removeAll()
autoActionAnnotationSeparators.forEach { $0.removeFromSuperview() }
autoActionAnnotationSeparators.removeAll()
if autoActionState == .suggest {
getAutosuggestions()
} else {
getAutocompletions()
}
if commandState == .idle {
deactivateBtn(btn: translateKey)
deactivateBtn(btn: conjugateKey)
deactivateBtn(btn: pluralKey)
deactivateBtn(btn: phoneEmojiKey0)
deactivateBtn(btn: phoneEmojiKey1)
deactivateBtn(btn: padEmojiKey0)
deactivateBtn(btn: padEmojiKey1)
deactivateBtn(btn: padEmojiKey2)
if autoAction0Visible {
allowUndo = false
firstCompletionIsHighlighted = false
// Highlight if the current prefix is the first autocompletion.
if currentPrefix == completionWords[0] && completionWords[1] != " " {
firstCompletionIsHighlighted = true
}
setBtn(
btn: translateKey,
color: firstCompletionIsHighlighted ? keyColor.withAlphaComponent(0.5) : keyboardBgColor,
name: "AutoAction0",
canBeCapitalized: false,
isSpecial: false
)
styleBtn(
btn: translateKey,
title: completionWords[0],
radius: firstCompletionIsHighlighted ? commandKeyCornerRadius / 2.5 : commandKeyCornerRadius
)
if translateKey.currentTitle != " " {
activateBtn(btn: translateKey)
}
autoActionAnnotation(autoActionWord: completionWords[0], index: 0, KVC: self)
}
// Add the current word being typed to the completion words if there is only one option that's highlighted.
if firstCompletionIsHighlighted && completionWords[1] == " " && completionWords[0] != currentPrefix {
// spaceAutoInsertIsPossible = true
completionWords[1] = currentPrefix
}
setBtn(
btn: conjugateKey,
color: keyboardBgColor, name: "AutoAction1",
canBeCapitalized: false,
isSpecial: false
)
styleBtn(
btn: conjugateKey,
title: !autoAction0Visible ? completionWords[0] : completionWords[1],
radius: commandKeyCornerRadius
)
if conjugateKey.currentTitle != " " {
activateBtn(btn: conjugateKey)
}
autoActionAnnotation(
autoActionWord: !autoAction0Visible ? completionWords[0] : completionWords[1], index: 1, KVC: self
)
if autoAction2Visible && emojisToShow == .zero {
setBtn(
btn: pluralKey,
color: keyboardBgColor,
name: "AutoAction2",
canBeCapitalized: false,
isSpecial: false
)
styleBtn(
btn: pluralKey,
title: !autoAction0Visible ? completionWords[1] : completionWords[2],
radius: commandKeyCornerRadius
)
if pluralKey.currentTitle != " " {
activateBtn(btn: pluralKey)
}
autoActionAnnotation(
autoActionWord: !autoAction0Visible ? completionWords[1] : completionWords[2], index: 2, KVC: self
)
conditionallyHideEmojiDividers()
} else if autoAction2Visible && emojisToShow == .one {
setBtn(
btn: pluralKey,
color: keyboardBgColor,
name: "AutoAction2",
canBeCapitalized: false,
isSpecial: false
)
styleBtn(
btn: pluralKey,
title: emojisToDisplayArray[0],
radius: commandKeyCornerRadius
)
if DeviceType.isPhone {
pluralKey.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPhone)
} else if DeviceType.isPad {
pluralKey.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPad)
}
activateBtn(btn: pluralKey)
conditionallyHideEmojiDividers()
} else if !autoAction2Visible && emojisToShow == .two {
setBtn(
btn: phoneEmojiKey0,
color: keyboardBgColor,
name: "EmojiKey0",
canBeCapitalized: false,
isSpecial: false
)
setBtn(
btn: phoneEmojiKey1,
color: keyboardBgColor,
name: "EmojiKey1",
canBeCapitalized: false,
isSpecial: false
)
styleBtn(btn: phoneEmojiKey0, title: emojisToDisplayArray[0], radius: commandKeyCornerRadius)
styleBtn(btn: phoneEmojiKey1, title: emojisToDisplayArray[1], radius: commandKeyCornerRadius)
if DeviceType.isPhone {
phoneEmojiKey0.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPhone)
phoneEmojiKey1.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPhone)
} else if DeviceType.isPad {
phoneEmojiKey0.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPad)
phoneEmojiKey1.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarFontPad)
}
activateBtn(btn: phoneEmojiKey0)
activateBtn(btn: phoneEmojiKey1)
conditionallyHideEmojiDividers()
} else if !autoAction2Visible && emojisToShow == .three {
setBtn(btn: padEmojiKey0, color: keyboardBgColor, name: "EmojiKey0", canBeCapitalized: false, isSpecial: false)
setBtn(btn: padEmojiKey1, color: keyboardBgColor, name: "EmojiKey1", canBeCapitalized: false, isSpecial: false)
setBtn(btn: padEmojiKey2, color: keyboardBgColor, name: "EmojiKey2", canBeCapitalized: false, isSpecial: false)
styleBtn(btn: padEmojiKey0, title: emojisToDisplayArray[0], radius: commandKeyCornerRadius)
styleBtn(btn: padEmojiKey1, title: emojisToDisplayArray[1], radius: commandKeyCornerRadius)
styleBtn(btn: padEmojiKey2, title: emojisToDisplayArray[2], radius: commandKeyCornerRadius)
padEmojiKey0.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarEmojiKeyFont)
padEmojiKey1.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarEmojiKeyFont)
padEmojiKey2.titleLabel?.font = .systemFont(ofSize: scribeKey.frame.height * scalarEmojiKeyFont)
activateBtn(btn: padEmojiKey0)
activateBtn(btn: padEmojiKey1)
activateBtn(btn: padEmojiKey2)
conditionallyHideEmojiDividers()
}
translateKey.layer.shadowColor = UIColor.clear.cgColor
conjugateKey.layer.shadowColor = UIColor.clear.cgColor
pluralKey.layer.shadowColor = UIColor.clear.cgColor
}
// Reset autocorrect and autosuggest button visibility.
autoAction0Visible = true
autoAction2Visible = true
}
/// Clears the text proxy when inserting using an auto action.
/// Note: the completion is appended after the typed text if this is not ran.
func clearPrefixFromTextFieldProxy() {
// Only delete characters for autocomplete, not autosuggest.
guard !currentPrefix.isEmpty, autoActionState != .suggest else {
return
}
guard let documentContext = proxy.documentContextBeforeInput, !documentContext.isEmpty else {
return
}
// Delete characters in text proxy.
for _ in 0 ..< currentPrefix.count {
proxy.deleteBackward()
}
}
/// Inserts the word that appears on the given auto action key and executes all following actions.
///
/// - Parameters
/// - keyPressed: the auto action button that was executed.
func executeAutoAction(keyPressed: UIButton) {
// Remove all prior annotations.
annotationBtns.forEach { $0.removeFromSuperview() }
annotationBtns.removeAll()
annotationSeparators.forEach { $0.removeFromSuperview() }
annotationSeparators.removeAll()
// If user doesn't want the completion and wants what they typed back,
// Completion is made the currentPrefix to be removed from the proxy.
// Then autoActionButton title is inserted like normal.
if allowUndo && completionWords.contains(previousWord) {
// Auto Action state has to be .complete else clearPrefixFromTextFieldProxy() won't work.
autoActionState = .complete
currentPrefix = (proxy.documentContextBeforeInput?.components(separatedBy: " ").secondToLast() ?? "") + " "
previousWord = ""
allowUndo = false
}
clearPrefixFromTextFieldProxy()
emojisToDisplayArray = [String]()
// Remove the space from the previous auto action or replace the current prefix.
if emojiAutoActionRepeatPossible && (
(keyPressed == phoneEmojiKey0 || keyPressed == phoneEmojiKey1)
|| (keyPressed == padEmojiKey0 || keyPressed == padEmojiKey1 || keyPressed == padEmojiKey2)
|| (keyPressed == pluralKey && emojisToShow == .one)
) {
proxy.deleteBackward()
} else {
currentPrefix = ""
}
proxy.insertText(keyPressed.titleLabel?.text ?? "")
proxy.insertText(" ")
autoActionState = .suggest
if shiftButtonState == .shift {
shiftButtonState = .normal
loadKeys()
}
conditionallyDisplayAnnotation()
if (keyPressed == phoneEmojiKey0 || keyPressed == phoneEmojiKey1)
|| (keyPressed == padEmojiKey0 || keyPressed == padEmojiKey1 || keyPressed == padEmojiKey2)
|| (keyPressed == pluralKey && emojisToShow == .one) {
emojiAutoActionRepeatPossible = true
}
}
// The background for the Scribe command elements.
@IBOutlet var commandBackground: UILabel!
/// Sets the background and user interactivity of the command bar.
func setCommandBackground() {
commandBackground.backgroundColor = keyboardBgColor
commandBackground.isUserInteractionEnabled = false
}
// The bar that displays language logic or is typed into for Scribe commands.
@IBOutlet var commandBar: CommandBar!
@IBOutlet var commandBarShadow: UIButton!
/// Deletes in the proxy or command bar given the current constraints.
func handleDeleteButtonPressed() {
if [.idle, .selectCommand, .alreadyPlural, .invalid].contains(commandState) {
proxy.deleteBackward()
} else if [.translate, .conjugate, .plural].contains(commandState) && !(allPrompts.contains(commandBar.text ?? "") || allColoredPrompts.contains(commandBar.attributedText ?? NSAttributedString())) {
guard let inputText = commandBar.text, !inputText.isEmpty else {
return
}
commandBar.text = inputText.deletePriorToCursor()
} else {
backspaceTimer?.invalidate()
backspaceTimer = nil
}
}
// The button used to display Scribe commands and its shadow.
@IBOutlet var scribeKey: ScribeKey!
@IBOutlet var scribeKeyShadow: UIButton!
/// Links various UI elements that interact concurrently.
func linkShadowBlendElements() {
scribeKey.shadow = scribeKeyShadow
commandBar.shadow = commandBarShadow
}
// Buttons used to trigger Scribe command functionality.
@IBOutlet var translateKey: UIButton!
@IBOutlet var conjugateKey: UIButton!
@IBOutlet var pluralKey: UIButton!
@IBOutlet var phoneEmojiKey0: UIButton!
@IBOutlet var phoneEmojiKey1: UIButton!
@IBOutlet var phoneEmojiDivider: UILabel!
@IBOutlet var padEmojiKey0: UIButton!
@IBOutlet var padEmojiKey1: UIButton!
@IBOutlet var padEmojiKey2: UIButton!
@IBOutlet var padEmojiDivider0: UILabel!
@IBOutlet var padEmojiDivider1: UILabel!
/// Sets up all buttons that are associated with Scribe commands.
func setCommandBtns() {
setBtn(btn: translateKey, color: commandKeyColor, name: "Translate", canBeCapitalized: false, isSpecial: false)
setBtn(btn: conjugateKey, color: commandKeyColor, name: "Conjugate", canBeCapitalized: false, isSpecial: false)
setBtn(btn: pluralKey, color: commandKeyColor, name: "Plural", canBeCapitalized: false, isSpecial: false)
activateBtn(btn: translateKey)
activateBtn(btn: conjugateKey)
activateBtn(btn: pluralKey)
}
/// Hides all emoji dividers based on conditions determined by the keyboard state.
func conditionallyHideEmojiDividers() {
if commandState == .idle {
if [.zero, .one, .three].contains(emojisToShow) {
phoneEmojiDivider.backgroundColor = .clear
}
if [.zero, .one, .two].contains(emojisToShow) {
padEmojiDivider0.backgroundColor = .clear
padEmojiDivider1.backgroundColor = .clear
}
} else {
phoneEmojiDivider.backgroundColor = .clear
padEmojiDivider0.backgroundColor = .clear
padEmojiDivider1.backgroundColor = .clear
}
}
// MARK: Conjugation Variables and Functions
// Note that we use "form" to describe both conjugations and declensions.
@IBOutlet var shiftFormsDisplayLeft: UIButton!
@IBOutlet var shiftFormsDisplayRight: UIButton!
@IBOutlet var formKeyFPS: UIButton!
@IBOutlet var formKeySPS: UIButton!
@IBOutlet var formKeyTPS: UIButton!
@IBOutlet var formKeyFPP: UIButton!
@IBOutlet var formKeySPP: UIButton!
@IBOutlet var formKeyTPP: UIButton!
/// Returns all buttons for the 3x2 conjugation display.
func get3x2FormDisplayButtons() -> [UIButton] {
let conjugationButtons: [UIButton] = [
formKeyFPS, formKeySPS, formKeyTPS, formKeyFPP, formKeySPP, formKeyTPP
]
return conjugationButtons
}
// Labels for the conjugation view buttons.
// Note that we're using buttons as labels weren't allowing for certain constraints to be set.
@IBOutlet var formLblFPS: UIButton!
@IBOutlet var formLblSPS: UIButton!
@IBOutlet var formLblTPS: UIButton!
@IBOutlet var formLblFPP: UIButton!
@IBOutlet var formLblSPP: UIButton!
@IBOutlet var formLblTPP: UIButton!
/// Returns all labels for the 3x2 conjugation display.
func get3x2FormDisplayLabels() -> [UIButton] {
let conjugationLabels: [UIButton] = [
formLblFPS, formLblSPS, formLblTPS, formLblFPP, formLblSPP, formLblTPP
]
return conjugationLabels
}
/// Sets up all buttons and labels that are associated with the 3x2 conjugation display.
func setFormDisplay3x2View() {
let conjugationNames: [String] = [
"firstPersonSingular",
"secondPersonSingular",
"thirdPersonSingular",
"firstPersonPlural",