forked from openvanilla/McBopomofo
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeyHandler.mm
More file actions
2442 lines (2158 loc) · 101 KB
/
Copy pathKeyHandler.mm
File metadata and controls
2442 lines (2158 loc) · 101 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
// Copyright (c) 2022 and onwards The McBopomofo Authors.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#import "KeyHandler.h"
#import "LanguageModelManager+Privates.h"
#import "Mandarin.h"
#import "McBopomofo-Swift.h"
#import "McBopomofoLM.h"
#import "UTF8Helper.h"
#import "UserOverrideModel.h"
#import "reading_grid.h"
#import <algorithm>
#import <optional>
#import <sstream>
#import <string>
#import <unordered_map>
#import <utility>
#import <vector>
@import CandidateUI;
@import NSStringUtils;
@import OpenCCBridge;
@import ChineseNumbers;
@import RomanNumbers;
@import BopomofoBraille;
InputMode InputModeBopomofo = @"org.openvanilla.inputmethod.McBopomofo.Bopomofo";
InputMode InputModePlainBopomofo = @"org.openvanilla.inputmethod.McBopomofo.PlainBopomofo";
@implementation KeyHandler {
std::shared_ptr<Formosa::Gramambular2::LanguageModel> _emptySharedPtr;
// the reading buffer that takes user input
Formosa::Mandarin::BopomofoReadingBuffer *_bpmfReadingBuffer;
// language model
McBopomofo::McBopomofoLM *_languageModel;
// user override model
McBopomofo::UserOverrideModel *_userOverrideModel;
Formosa::Gramambular2::ReadingGrid *_grid;
Formosa::Gramambular2::ReadingGrid::WalkResult _latestWalk;
NSString *_inputMode;
}
@synthesize delegate = _delegate;
- (NSString *)inputMode
{
return _inputMode;
}
- (void)setInputMode:(NSString *)value
{
NSString *newInputMode;
McBopomofo::McBopomofoLM *newLanguageModel;
if ([value isKindOfClass:[NSString class]] && [value isEqual:InputModePlainBopomofo]) {
newInputMode = InputModePlainBopomofo;
newLanguageModel = [LanguageModelManager languageModelPlainBopomofo];
newLanguageModel->setPhraseReplacementEnabled(false);
} else {
newInputMode = InputModeBopomofo;
newLanguageModel = [LanguageModelManager languageModelMcBopomofo];
newLanguageModel->setPhraseReplacementEnabled(Preferences.phraseReplacementEnabled);
}
newLanguageModel->setExternalConverterEnabled(Preferences.chineseConversionStyle == ChineseConversionStyleModel);
// Only apply the changes if the value is changed
if (![_inputMode isEqualToString:newInputMode]) {
_inputMode = newInputMode;
_languageModel = newLanguageModel;
if (_grid == nullptr) {
NSLog(@"warning: _grid used after release");
}
if (_grid != nullptr) {
delete _grid;
// This returns a shared_ptr that in turn points to an unmanaged object.
std::shared_ptr<Formosa::Gramambular2::LanguageModel> lm(_emptySharedPtr, _languageModel);
_grid = new Formosa::Gramambular2::ReadingGrid(lm);
_grid->setReadingSeparator("-");
}
if (!_bpmfReadingBuffer->isEmpty()) {
_bpmfReadingBuffer->clear();
}
}
}
- (void)dealloc
{
delete _bpmfReadingBuffer;
delete _grid;
}
- (instancetype)init
{
self = [super init];
if (self) {
_bpmfReadingBuffer = new Formosa::Mandarin::BopomofoReadingBuffer(Formosa::Mandarin::BopomofoKeyboardLayout::StandardLayout());
// create the lattice builder
_languageModel = [LanguageModelManager languageModelMcBopomofo];
_languageModel->setPhraseReplacementEnabled(Preferences.phraseReplacementEnabled);
_userOverrideModel = [LanguageModelManager userOverrideModel];
// This returns a shared_ptr that in turn points to an unmanaged object.
std::shared_ptr<Formosa::Gramambular2::LanguageModel> lm(_emptySharedPtr, _languageModel);
_grid = new Formosa::Gramambular2::ReadingGrid(lm);
_grid->setReadingSeparator("-");
_inputMode = InputModeBopomofo;
}
return self;
}
- (void)syncWithPreferences
{
KeyboardLayout layout = Preferences.keyboardLayout;
switch (layout) {
case KeyboardLayoutStandard:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::StandardLayout());
break;
case KeyboardLayoutEten:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::ETenLayout());
break;
case KeyboardLayoutHsu:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::HsuLayout());
break;
case KeyboardLayoutEten26:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::ETen26Layout());
break;
case KeyboardLayoutHanyuPinyin:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::HanyuPinyinLayout());
break;
case KeyboardLayoutIBM:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::IBMLayout());
break;
default:
_bpmfReadingBuffer->setKeyboardLayout(Formosa::Mandarin::BopomofoKeyboardLayout::StandardLayout());
Preferences.keyboardLayout = KeyboardLayoutStandard;
}
_languageModel->setExternalConverterEnabled(Preferences.chineseConversionStyle == ChineseConversionStyleModel);
}
- (void)fixNodeWithReading:(NSString *)reading value:(NSString *)value originalCursorIndex:(size_t)originalCursorIndex useMoveCursorAfterSelectionSetting:(BOOL)flag
{
size_t actualCursor = self.actualCandidateCursorIndex;
Formosa::Gramambular2::ReadingGrid::Candidate candidate(reading.UTF8String, value.UTF8String);
if (!_grid->overrideCandidate(actualCursor, candidate)) {
return;
}
Formosa::Gramambular2::ReadingGrid::WalkResult prevWalk = _latestWalk;
[self _walk];
// Update the user override model if warranted.
size_t accumulatedCursor = 0;
auto nodeIter = _latestWalk.findNodeAt(actualCursor, &accumulatedCursor);
if (nodeIter == _latestWalk.nodes.cend()) {
return;
}
Formosa::Gramambular2::ReadingGrid::NodePtr currentNode = *nodeIter;
if (currentNode != nullptr && currentNode->currentUnigram().score() > -8) {
_userOverrideModel->observe(prevWalk, _latestWalk, self.actualCandidateCursorIndex, [NSDate date].timeIntervalSince1970);
}
if (currentNode != nullptr && flag && Preferences.moveCursorAfterSelectingCandidate) {
_grid->setCursor(accumulatedCursor);
} else {
_grid->setCursor(originalCursorIndex);
}
}
- (void)fixNodeForAssociatedPhraseWithPrefixAt:(size_t)prefixCursorIndex prefixReading:(NSString *)pfxReading prefixValue:(NSString *)pfxValue associatedPhraseReading:(NSString *)phraseReading associatedPhraseValue:(NSString *)phraseValue
{
if (_grid->length() == 0) {
return;
}
// Unlike actualCandidateCursorIndex() which takes the Hanyin/MS IME cursor
// modes into consideration, prefixCursorIndex is *already* the actual node
// position in the grid. The only boundary condition is when prefixCursorIndex
// is at the end. That's when we should decrement by one.
size_t actualPrefixCursorIndex = (prefixCursorIndex == _grid->length())
? prefixCursorIndex - 1
: prefixCursorIndex;
// First of all, let's find the target node where the prefix is found. The
// node may not be exactly the same as the prefix.
size_t accumulatedCursor = 0;
auto nodeIter = _latestWalk.findNodeAt(actualPrefixCursorIndex, &accumulatedCursor);
// Should not happen. The end location must be >= the node's spanning length.
if (accumulatedCursor < (*nodeIter)->spanningLength()) {
return;
}
// Let's do a split override. If a node is now ABCD, let's make four overrides
// A-B-C-D, essentially splitting the node. Why? Because we're inserting an
// associated phrase. Say the phrase is BCEF with the prefix BC. If we don't
// do the override, the nodes that represent A and D may not carry the same
// values after the next walk, since the underlying reading is now a-bcef-d
// and that does not necessary guarantee that A and D will be there.
std::vector<std::string> originalNodeValues = McBopomofo::Split((*nodeIter)->value());
if (originalNodeValues.size() == (*nodeIter)->spanningLength()) {
// Only performs this if the condition is satisfied.
size_t overrideIndex = accumulatedCursor - (*nodeIter)->spanningLength();
for (const auto& value : originalNodeValues) {
_grid->overrideCandidate(overrideIndex, value);
++overrideIndex;
}
}
std::string prefixReading(pfxReading.UTF8String);
std::string prefixValue(pfxValue.UTF8String);
// Now, we override the prefix candidate again. This provides us with
// information for how many more we need to fill in to complete the
// associated phrase.
Formosa::Gramambular2::ReadingGrid::Candidate prefixCandidate { prefixReading,
prefixValue };
if (!_grid->overrideCandidate(actualPrefixCursorIndex, prefixCandidate)) {
return;
}
[self _walk];
// Now we've set ourselves up. Because associated phrases require the strict
// one-reading-for-one-value rule, we can comfortably count how many readings
// we'll need to insert. First, let's move to the end of the newly overridden
// phrase.
nodeIter = _latestWalk.findNodeAt(actualPrefixCursorIndex, &accumulatedCursor);
_grid->setCursor(accumulatedCursor);
std::string associatedPhraseReading(phraseReading.UTF8String);
std::string associatedPhraseValue(phraseValue.UTF8String);
std::vector<std::string> associatedPhraseValues = McBopomofo::Split(associatedPhraseValue);
// Compute how many more reading do we have to insert.
size_t nodeSpanningLength = (*nodeIter)->spanningLength();
std::vector<std::string> splitReadings = McBopomofo::AssociatedPhrasesV2::SplitReadings(associatedPhraseReading);
size_t splitReadingsSize = splitReadings.size();
if (nodeSpanningLength >= splitReadingsSize) {
// Shouldn't happen
return;
}
for (size_t i = nodeSpanningLength; i < splitReadingsSize; i++) {
_grid->insertReading(splitReadings[i]);
++accumulatedCursor;
if (i < associatedPhraseValues.size()) {
_grid->overrideCandidate(accumulatedCursor, associatedPhraseValues[i]);
}
_grid->setCursor(accumulatedCursor);
}
// Finally, let's override with the full associated phrase's value.
if (!_grid->overrideCandidate(actualPrefixCursorIndex,
associatedPhraseValue)) {
// Shouldn't happen
}
[self _walk];
// Cursor is already at accumulatedCursor, so no more work here.
}
- (void)clear
{
_bpmfReadingBuffer->clear();
_grid->clear();
_latestWalk = Formosa::Gramambular2::ReadingGrid::WalkResult {};
}
- (void)handleForceCommitWithStateCallback:(void (^)(InputState *))stateCallback
{
if (_bpmfReadingBuffer->isEmpty() && _grid->length() == 0) {
// No-op if both are empty.
return;
}
// Upon force-commit, clear the BPMF reading, then "steal" the composing buffer text from the built inputting state.
_bpmfReadingBuffer->clear();
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
[self clear];
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:inputting.composingBuffer];
stateCallback(committing);
}
- (std::string)_currentLayout
{
NSString *keyboardLayoutName = Preferences.keyboardLayoutName;
std::string layout = std::string(keyboardLayoutName.UTF8String) + "_";
return layout;
}
- (BOOL)handleInput:(KeyHandlerInput *)input state:(InputState *)inState stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback
{
InputState *state = inState;
UniChar charCode = input.charCode;
McBopomofoEmacsKey emacsKey = input.emacsKey;
// MARK: Handle Selecting Feature
if ([state isKindOfClass:[InputStateSelectingFeature class]] ||
[state isKindOfClass:[InputStateSelectingDateMacro class]]) {
return [self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Handle Big5 Input
if ([state isKindOfClass:[InputStateBig5 class]]) {
return [self _handleBig5State:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
if ([state isKindOfClass:[InputStateNumber class]]) {
BOOL result = [self _handleNumberState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
if (!result) {
InputStateNumber *numberState = (InputStateNumber *)state;
if (!numberState.candidates.count) {
return YES;
}
[self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
return YES;
}
// MARK: Handle Chinese Number Input
// if the inputText is empty, it's a function key combination, we ignore it
if (!input.inputText.length) {
return NO;
}
// if the composing buffer is empty and there's no reading, and there is some function key combination, we ignore it
BOOL isFunctionKey = (input.isCommandHold || input.isOptionHold || input.isNumericPad) || input.isControlHotKey;
if (![state isKindOfClass:[InputStateNotEmpty class]] && ![state isKindOfClass:[InputStateAssociatedPhrasesPlain class]] && !([state isKindOfClass:[InputStateAssociatedPhrases class]] && [(InputStateAssociatedPhrases *)state useShiftKey]) && isFunctionKey) {
return NO;
}
// Caps Lock processing : if Caps Lock is on, temporarily disable bopomofo.
if (charCode == 8 || charCode == 13 || input.isAbsorbedArrowKey || input.isExtraChooseCandidateKey || input.isCursorForward || input.isCursorBackward) {
// do nothing if backspace is pressed -- we ignore the key
} else if (input.isCapsLockOn) {
// process all possible combination, we hope.
[self clear];
InputStateEmpty *emptyState = [[InputStateEmpty alloc] init];
stateCallback(emptyState);
// first commit everything in the buffer.
if (input.isShiftHold) {
return NO;
}
// if ASCII but not printable, don't use insertText:replacementRange: as many apps don't handle non-ASCII char insertions.
if (charCode < 0x80 && !isprint(charCode)) {
return NO;
}
// when shift is pressed, don't do further processing, since it outputs capital letter anyway.
InputStateCommitting *committingState = [[InputStateCommitting alloc] initWithPoppedText:input.inputText.lowercaseString];
stateCallback(committingState);
stateCallback(emptyState);
return YES;
}
if (input.isNumericPad && !Preferences.selectCandidateWithNumericKeypad) {
if (!input.isLeft && !input.isRight && !input.isDown && !input.isUp && charCode != 32 && isprint(charCode)) {
[self clear];
InputStateEmpty *emptyState = [[InputStateEmpty alloc] init];
stateCallback(emptyState);
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:input.inputText.lowercaseString];
stateCallback(committing);
stateCallback(emptyState);
return YES;
}
}
// MARK: Handle Associated Phrases
if ([state isKindOfClass:[InputStateAssociatedPhrasesPlain class]]) {
BOOL result = [self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
if (result) {
return YES;
}
state = [[InputStateEmpty alloc] init];
stateCallback(state);
}
if ([state isKindOfClass:[InputStateAssociatedPhrases class]]) {
BOOL result = [self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
if (result) {
return YES;
}
if ([(InputStateAssociatedPhrases *)state useShiftKey]) {
state = [self buildInputtingState];
stateCallback(state);
} else {
return YES;
}
}
// MARK: Handle Candidates
if ([state isKindOfClass:[InputStateChoosingCandidate class]]) {
return [self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Handle Other States with Menu
if ([state isKindOfClass:[InputStateSelectingDictionary class]] ||
[state isKindOfClass:[InputStateShowingCharInfo class]] ||
[state isKindOfClass:[InputStateCustomMenu class]]) {
return [self _handleCandidateState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Handle Marking
if ([state isKindOfClass:[InputStateMarking class]]) {
InputStateMarking *marking = (InputStateMarking *)state;
if ([self _handleMarkingState:(InputStateMarking *)state input:input stateCallback:stateCallback errorCallback:errorCallback]) {
return YES;
}
state = [marking convertToInputting];
stateCallback(state);
}
BOOL keyConsumedByReading = NO;
BOOL skipBpmfHandling = input.isReservedKey || input.isControlHold;
// MARK: Handle BPMF Keys
// see if it's valid BPMF reading
bool isValidKey = _bpmfReadingBuffer->isValidKey((char)charCode);
if (!skipBpmfHandling && isValidKey) {
_bpmfReadingBuffer->combineKey((char)charCode);
keyConsumedByReading = YES;
// if we have a tone marker, we have to insert the reading to the
// builder in other words, if we don't have a tone marker, we just
// update the composing buffer
if (!_bpmfReadingBuffer->hasToneMarker()) {
stateCallback([self buildInputtingState]);
return YES;
}
}
// Issue 753
//
// This allows users to use tone key to change an existing reading before
// the current cursor.
if (Preferences.allowChangingPriorTone &&
_bpmfReadingBuffer->hasToneMarkerOnly() &&
_grid->readings().size() > 0 &&
_grid->cursor() > 0) {
size_t cursor = _grid->cursor() - 1;
// const std::string reading = _grid->readings()[cursor];
const std::string& reading = _grid->readings()[cursor];
if (!reading.empty() && reading[0] != '_') {
Formosa::Mandarin::BopomofoReadingBuffer tmpBuffer(_bpmfReadingBuffer->keyboardLayout());
Formosa::Mandarin::BopomofoSyllable syllable = Formosa::Mandarin::BopomofoSyllable::FromComposedString(reading);
std::string keys = _bpmfReadingBuffer->keyboardLayout()->keySequenceFromSyllable(syllable);
for (char k:keys) {
tmpBuffer.combineKey(k);
}
tmpBuffer.combineKey((char)charCode);
std::string newReading = tmpBuffer.syllable().composedString();
if (_languageModel->hasUnigrams(newReading)) {
_bpmfReadingBuffer->clear();
_grid->deleteReadingBeforeCursor();
_grid->insertReading(newReading);
[self _walk];
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
return YES;
}
}
}
BOOL composeReading = isValidKey && _bpmfReadingBuffer->hasToneMarker() && !_bpmfReadingBuffer->hasToneMarkerOnly();
// see if we have composition if Enter/Space is hit and buffer is not empty
// this is bit-OR'ed so that the tone marker key is also taken into account
composeReading |= (!_bpmfReadingBuffer->isEmpty() && (charCode == 32 || charCode == 13));
if (composeReading) {
// combine the reading
std::string reading = _bpmfReadingBuffer->syllable().composedString();
// see if we have a unigram for this
if (!_languageModel->hasUnigrams(reading)) {
errorCallback();
if (Preferences.keepReadingUponCompositionError) {
stateCallback([self buildInputtingState]);
return YES;
}
_bpmfReadingBuffer->clear();
if (!_grid->length()) {
stateCallback([[InputStateEmptyIgnoringPreviousState alloc] init]);
} else {
stateCallback([self buildInputtingState]);
}
return YES;
}
_grid->insertReading(reading);
[self _walk];
// get user override model suggestion
if (_inputMode != InputModePlainBopomofo) {
McBopomofo::UserOverrideModel::Suggestion suggestion = _userOverrideModel->suggest(_latestWalk, self.actualCandidateCursorIndex, [NSDate date].timeIntervalSince1970);
if (!suggestion.empty()) {
Formosa::Gramambular2::ReadingGrid::Node::OverrideType type = suggestion.forceHighScoreOverride ? Formosa::Gramambular2::ReadingGrid::Node::OverrideType::kOverrideValueWithHighScore : Formosa::Gramambular2::ReadingGrid::Node::OverrideType::kOverrideValueWithScoreFromTopUnigram;
_grid->overrideCandidate(self.actualCandidateCursorIndex, suggestion.candidate, type);
[self _walk];
}
}
// then update the text
_bpmfReadingBuffer->clear();
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
if (_inputMode == InputModeBopomofo && Preferences.associatedPhrasesEnabled) {
[self handleAssociatedPhraseWithState:(InputStateInputting *)inputting useVerticalMode:input.useVerticalMode stateCallback:stateCallback errorCallback:errorCallback useShiftKey:YES];
} else if (_inputMode == InputModePlainBopomofo) {
InputStateChoosingCandidate *choosingCandidates = [self _buildCandidateStateFromInputtingState:inputting useVerticalMode:input.useVerticalMode];
if (choosingCandidates.candidates.count == 1) {
[self clear];
NSString *text = choosingCandidates.candidates.firstObject.value;
NSString *candidateReading = choosingCandidates.candidates.firstObject.reading;
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:text];
stateCallback(committing);
if (!Preferences.associatedPhrasesEnabled) {
InputStateEmpty *empty = [[InputStateEmpty alloc] init];
stateCallback(empty);
} else {
InputStateAssociatedPhrasesPlain *associatedPhrases = (InputStateAssociatedPhrasesPlain *)[self buildAssociatedPhrasePlainStateWithReading:candidateReading value:text useVerticalMode:input.useVerticalMode];
if (associatedPhrases) {
stateCallback(associatedPhrases);
} else {
InputStateEmpty *empty = [[InputStateEmpty alloc] init];
stateCallback(empty);
}
}
} else {
stateCallback(choosingCandidates);
}
}
// and tells the client that the key is consumed
return YES;
}
// Indicates that the Bopomofo reading is not-empty but also not composed.
// The only possibility for this to be true is that when the reading only
// contains tone markers.
if (keyConsumedByReading) {
stateCallback([self buildInputtingState]);
return true;
}
// MARK: Space and Down
// keyCode 125 = Down, charCode 32 = Space
if (_bpmfReadingBuffer->isEmpty() &&
[state isKindOfClass:[InputStateNotEmpty class]] && (input.isExtraChooseCandidateKey || charCode == 32 || (input.useVerticalMode && (input.isVerticalModeOnlyChooseCandidateKey)))) {
if (charCode == 32) {
// if the spacebar is NOT set to be a selection key
if (input.isShiftHold || !Preferences.chooseCandidateUsingSpace) {
if (_grid->cursor() >= _grid->length()) {
NSString *composingBuffer = ((InputStateNotEmpty *)state).composingBuffer;
if (composingBuffer.length) {
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:composingBuffer];
stateCallback(committing);
}
[self clear];
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:@" "];
stateCallback(committing);
InputStateEmpty *empty = [[InputStateEmpty alloc] init];
stateCallback(empty);
} else if (_languageModel->hasUnigrams(" ")) {
_grid->insertReading(" ");
[self _walk];
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
}
return YES;
}
}
size_t originalCursorIndex = _grid->cursor();
// Note: When the cursor is at the end of the composing buffer and the
// preference that make McBopomofo be like MS Bopomofo are on, the
// cursor should be moved to the begin of the last character.
if (originalCursorIndex == _grid->length() && Preferences.selectPhraseAfterCursorAsCandidate && Preferences.moveCursorAfterSelectingCandidate) {
_grid->setCursor(originalCursorIndex - 1);
}
InputStateChoosingCandidate *choosingCandidates = [self _buildCandidateStateFromInputtingState:(InputStateInputting *)[self buildInputtingState] useVerticalMode:input.useVerticalMode];
choosingCandidates.originalCursorIndex = originalCursorIndex;
stateCallback(choosingCandidates);
return YES;
}
// MARK: Esc
if (charCode == 27) {
return [self _handleEscWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Tab
if (input.isTab) {
return [self _handleTabState:state shiftIsHold:input.isShiftHold stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Cursor backward
if (input.isCursorBackward || emacsKey == McBopomofoEmacsKeyBackward) {
return [self _handleBackwardWithState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Cursor forward
if (input.isCursorForward || emacsKey == McBopomofoEmacsKeyForward) {
return [self _handleForwardWithState:state input:input stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Home
if (input.isHome || emacsKey == McBopomofoEmacsKeyHome) {
return [self _handleHomeWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: End
if (input.isEnd || emacsKey == McBopomofoEmacsKeyEnd) {
return [self _handleEndWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: AbsorbedArrowKey
if (input.isAbsorbedArrowKey || input.isExtraChooseCandidateKey) {
return [self _handleAbsorbedArrowKeyWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Backspace
if (charCode == 8) {
return [self _handleBackspaceWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Delete
if (input.isDelete || emacsKey == McBopomofoEmacsKeyDelete) {
return [self _handleDeleteWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Enter
if (charCode == 13) {
if (_inputMode == InputModeBopomofo && input.isControlHold) {
NSString *string = @"";
if (Preferences.controlEnterOutput == ControlEnterOutputOff) {
errorCallback();
return YES;
}
switch (Preferences.controlEnterOutput) {
case ControlEnterOutputBpmfReading:
string = [self _currentBpmfReading];
break;
case ControlEnterOutputHtmlRuby:
string = [self _currentHtmlRuby];
break;
case ControlEnterOutputBraille:
string = [self _currentBraille];
break;
case ControlEnterOutputHanyuPinyin:
string = [self _currentHanyuPinyin];
break;
default:
break;
}
[self clear];
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:string];
stateCallback(committing);
InputStateEmpty *empty = [[InputStateEmpty alloc] init];
stateCallback(empty);
return YES;
}
if (Preferences.shiftEnterEnabled && _inputMode == InputModeBopomofo && input.isShiftHold &&
[state isKindOfClass:[InputStateInputting class]]) {
return [self handleAssociatedPhraseWithState:(InputStateInputting *)state useVerticalMode:input.useVerticalMode stateCallback:stateCallback errorCallback:errorCallback useShiftKey:NO];
}
return [self _handleEnterWithState:state stateCallback:stateCallback errorCallback:errorCallback];
}
// MARK: Enter Big5 code mode
if (input.isControlHold && (charCode == '`')) {
if (Preferences.big5InputEnabled) {
[self clear];
if ([state isKindOfClass:[InputStateInputting class]]) {
InputStateInputting *current = (InputStateInputting *)state;
NSString *composingBuffer = current.composingBuffer;
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:composingBuffer];
stateCallback(committing);
}
InputStateBig5 *big5 = [[InputStateBig5 alloc] initWithCode:@""];
stateCallback(big5);
return YES;
}
}
if (input.isControlHold && (input.keyCode == 42)) {
[self clear];
if ([state isKindOfClass:[InputStateInputting class]]) {
InputStateInputting *current = (InputStateInputting *)state;
NSString *composingBuffer = current.composingBuffer;
InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:composingBuffer];
stateCallback(committing);
}
InputStateSelectingFeature *selecting = [[InputStateSelectingFeature alloc] init];
stateCallback(selecting);
return YES;
}
// MARK: Punctuation list
if ((char)charCode == '`' && !(input.isControlHold || input.isCommandHold || input.isOptionHold)) {
if (_languageModel->hasUnigrams("_punctuation_list")) {
if (_bpmfReadingBuffer->isEmpty()) {
_grid->insertReading("_punctuation_list");
[self _walk];
size_t originalCursorIndex = _grid->cursor();
if (Preferences.selectPhraseAfterCursorAsCandidate) {
_grid->setCursor(originalCursorIndex - 1);
}
InputStateChoosingCandidate *choosingCandidate = [self _buildCandidateStateFromInputtingState:(InputStateInputting *)[self buildInputtingState] useVerticalMode:input.useVerticalMode];
choosingCandidate.originalCursorIndex = originalCursorIndex;
stateCallback(choosingCandidate);
} else { // If there is still unfinished bpmf reading, ignore the punctuation
errorCallback();
}
return YES;
}
}
// MARK: Punctuation
// if nothing is matched, see if it's a punctuation key for current layout.
std::string punctuationNamePrefix;
if (input.isControlHold) {
punctuationNamePrefix = "_ctrl_punctuation_";
} else if (Preferences.halfWidthPunctuationEnabled) {
punctuationNamePrefix = "_half_punctuation_";
} else {
punctuationNamePrefix = "_punctuation_";
}
std::string layout = [self _currentLayout];
std::string customPunctuation = punctuationNamePrefix + layout + std::string(1, (char)charCode);
if ([self _handlePunctuation:customPunctuation state:state usingVerticalMode:input.useVerticalMode stateCallback:stateCallback errorCallback:errorCallback]) {
return YES;
}
// if nothing is matched, see if it's a punctuation key.
std::string punctuation = punctuationNamePrefix + std::string(1, (char)charCode);
if ([self _handlePunctuation:punctuation state:state usingVerticalMode:input.useVerticalMode stateCallback:stateCallback errorCallback:errorCallback]) {
return YES;
}
if ((char)charCode >= 'A' && (char)charCode <= 'Z') {
if (Preferences.letterBehavior == 1) {
std::string letter = std::string("_letter_") + std::string(1, (char)charCode);
if ([self _handlePunctuation:letter state:state usingVerticalMode:input.useVerticalMode stateCallback:stateCallback errorCallback:errorCallback]) {
return YES;
}
} else {
if ([state isKindOfClass:[InputStateNotEmpty class]]) {
[self clear];
InputStateEmpty *empty = [[InputStateEmpty alloc] init];
stateCallback(empty);
state = empty;
}
}
}
// still nothing, then we update the composing buffer (some app has
// strange behavior if we don't do this, "thinking" the key is not
// actually consumed)
if ([state isKindOfClass:[InputStateNotEmpty class]] || !_bpmfReadingBuffer->isEmpty()) {
errorCallback();
stateCallback(state);
return YES;
}
return NO;
}
- (BOOL)_handleTabState:(InputState *)state shiftIsHold:(BOOL)shiftIsHold stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback
{
if (!_grid->length()) {
return NO;
}
if (![state isKindOfClass:[InputStateInputting class]]) {
errorCallback();
return YES;
}
if (!_bpmfReadingBuffer->isEmpty()) {
errorCallback();
return YES;
}
InputStateChoosingCandidate *candidateState = [self _buildCandidateStateFromInputtingState:(InputStateInputting *)[self buildInputtingState] useVerticalMode:NO];
NSArray *candidates = candidateState.candidates;
if (candidates.count == 0) {
errorCallback();
return YES;
}
auto nodeIter = _latestWalk.findNodeAt(self.actualCandidateCursorIndex);
if (nodeIter == _latestWalk.nodes.cend()) {
// Shouldn't happen.
errorCallback();
return true;
}
Formosa::Gramambular2::ReadingGrid::NodePtr currentNode = *nodeIter;
size_t currentIndex = 0;
if (!currentNode->isOverridden()) {
// If the user never selects a candidate for the node, we start from the
// first candidate, so the user has a chance to use the unigram with two or
// more characters when type the tab key for the first time.
//
// In other words, if a user type two BPMF readings, but the score of seeing
// them as two unigrams is higher than a phrase with two characters, the
// user can just use the longer phrase by typing the tab key.
InputStateCandidate *candidate = candidates[0];
if (currentNode->reading() == candidate.reading.UTF8String && currentNode->value() == candidate.value.UTF8String) {
// If the first candidate is the value of the current node, we use next
// one.
if (shiftIsHold) {
currentIndex = candidates.count - 1;
} else {
currentIndex = 1;
}
}
} else {
for (InputStateCandidate *candidate : candidates) {
if (currentNode->reading() == candidate.reading.UTF8String && currentNode->value() == candidate.value.UTF8String) {
if (shiftIsHold) {
currentIndex == 0 ? currentIndex = candidates.count - 1 : currentIndex--;
} else {
currentIndex++;
}
break;
}
currentIndex++;
}
}
if (currentIndex >= candidates.count) {
currentIndex = 0;
}
InputStateCandidate *candidate = candidates[currentIndex];
size_t originalCursorIndex = _grid->cursor();
[self fixNodeWithReading:candidate.reading value:candidate.value originalCursorIndex:originalCursorIndex useMoveCursorAfterSelectionSetting:NO];
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
return YES;
}
- (BOOL)_handleEscWithState:(InputState *)state stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback
{
if (![state isKindOfClass:[InputStateInputting class]]) {
return NO;
}
BOOL escToClearInputBufferEnabled = Preferences.escToCleanInputBuffer;
if (escToClearInputBufferEnabled) {
// if the option is enabled, we clear everything including the composing
// buffer, walked nodes and the reading.
[self clear];
InputStateEmptyIgnoringPreviousState *empty = [[InputStateEmptyIgnoringPreviousState alloc] init];
stateCallback(empty);
} else {
// if reading is not empty, we cancel the reading; Apple's built-in
// Zhuyin (and the erstwhile Hanin) has a default option that Esc
// "cancels" the current composed character and revert it to
// Bopomofo reading, in odds with the expectation of users from
// other platforms
if (!_bpmfReadingBuffer->isEmpty()) {
_bpmfReadingBuffer->clear();
if (!_grid->length()) {
InputStateEmptyIgnoringPreviousState *empty = [[InputStateEmptyIgnoringPreviousState alloc] init];
stateCallback(empty);
} else {
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
}
}
}
return YES;
}
- (BOOL)_handleBackwardWithState:(InputState *)state input:(KeyHandlerInput *)input stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback
{
if (![state isKindOfClass:[InputStateInputting class]]) {
return NO;
}
if (!_bpmfReadingBuffer->isEmpty()) {
errorCallback();
stateCallback(state);
return YES;
}
InputStateInputting *currentState = (InputStateInputting *)state;
if (input.isShiftHold) {
// Shift + left
if (currentState.cursorIndex > 0) {
NSInteger previousPosition = [currentState.composingBuffer previousUtf16PositionFor:currentState.cursorIndex];
InputStateMarking *marking = [[InputStateMarking alloc] initWithComposingBuffer:currentState.composingBuffer cursorIndex:currentState.cursorIndex markerIndex:previousPosition readings:[self _currentReadings]];
marking.tooltipForInputting = currentState.tooltip;
stateCallback(marking);
} else {
errorCallback();
stateCallback(state);
}
} else {
if (_grid->cursor() > 0) {
_grid->setCursor(_grid->cursor() - 1);
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
} else {
errorCallback();
stateCallback(state);
}
}
return YES;
}
- (BOOL)_handleForwardWithState:(InputState *)state input:(KeyHandlerInput *)input stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback
{
if (![state isKindOfClass:[InputStateInputting class]]) {
return NO;
}
if (!_bpmfReadingBuffer->isEmpty()) {
errorCallback();
stateCallback(state);
return YES;
}
InputStateInputting *currentState = (InputStateInputting *)state;
if (input.isShiftHold) {
// Shift + Right
if (currentState.cursorIndex < currentState.composingBuffer.length) {
NSInteger nextPosition = [currentState.composingBuffer nextUtf16PositionFor:currentState.cursorIndex];
InputStateMarking *marking = [[InputStateMarking alloc] initWithComposingBuffer:currentState.composingBuffer cursorIndex:currentState.cursorIndex markerIndex:nextPosition readings:[self _currentReadings]];
marking.tooltipForInputting = currentState.tooltip;
stateCallback(marking);
} else {
errorCallback();
stateCallback(state);
}
} else {
if (_grid->cursor() < _grid->length()) {
_grid->setCursor(_grid->cursor() + 1);
InputStateInputting *inputting = (InputStateInputting *)[self buildInputtingState];
stateCallback(inputting);
} else {
errorCallback();
stateCallback(state);
}
}
return YES;
}
- (BOOL)_handleHomeWithState:(InputState *)state stateCallback:(void (^)(InputState *))stateCallback errorCallback:(void (^)(void))errorCallback