This repository has been archived by the owner on Jul 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
OctopusBeast.mm
878 lines (714 loc) · 23.9 KB
/
OctopusBeast.mm
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
//
// OctopusBeast.m
// Octopus
//
// Created by K3A on 5/20/12.
// Copyright (c) 2012 K3A. All rights reserved.
//
#include <objc/runtime.h>
#import <UIKit/UITextInputPrivate.h>
#import <UIKit/UIKeyboardImpl.h>
#include <string>
enum sandbox_filter_type {
SANDBOX_FILTER_NONE = 0,
SANDBOX_FILTER_PATH = 1,
SANDBOX_FILTER_GLOBAL_NAME =2,
SANDBOX_FILTER_LOCAL_NAME = 3,
SANDBOX_CHECK_NO_REPORT = 0x40000000
};
extern "C" int sandbox_check(pid_t pid, const char *operation, int type, ...);
#import "OctopusBeast.h"
void OLog(int level, const char* format, ...)
{
#ifndef DEBUG
if (level>1) return;
#endif
std::string strf(format);
strf.insert(0, "OK INF: ");
strf.append("\n");
va_list args;
va_start( args, format );
NSLogv([NSString stringWithUTF8String:strf.c_str()], args);
va_end( args );
}
void OErr(const char* format, ...)
{
std::string strf(format);
strf.insert(0, "OK ERR: ");
strf.append("\n");
va_list args;
va_start( args, format );
NSLogv([NSString stringWithUTF8String:strf.c_str()], args);
va_end( args );
}
static mach_port_t GetServerPort()
{
kern_return_t kr;
static mach_port_t bsPort = 0;
mach_port_t srvPort = 0;
if (bsPort == 0)
{
kr = task_get_bootstrap_port( mach_task_self(), &bsPort );
if (kr != MACH_MSG_SUCCESS)
{
OErr("Failed to get the boostrap port!");
//mach_error("task_get_bootstrap_port:", kr);
return 0;
}
}
if (srvPort == 0)
{
if (IS_IOS7)
{
int sandbox_result = sandbox_check(getpid(), "mach-lookup", SANDBOX_FILTER_LOCAL_NAME | SANDBOX_CHECK_NO_REPORT, "me.k3a.octopusd");
if (sandbox_result)
{
OErr("Mach lookup disabled by seatbelt");
return 0;
}
}
kr = bootstrap_look_up( bsPort, "me.k3a.octopusd", &srvPort );
if (kr != MACH_MSG_SUCCESS)
{
OErr("Could not lookup the service, is daemon running?");
//mach_error("Could not lookup the service, is daemon running?", kr);
return 0;
}
}
return srvPort;
}
static void printKBTree(id tree, NSString* indent)
{
if (strcmp(class_getName([tree class]), "UIKBTree")) return;
NSDictionary* props = [tree properties];
NSLog(@"%@-[disp:%@, rep:%@, shap:%@] %@", indent,
[props objectForKey:@"KBdisplayString"], [props objectForKey:@"KBrepresentedString"],
[props objectForKey:@"KBshape"], [tree name]);
indent = [indent stringByAppendingString:@" "];
for (id t in [tree subtrees])
printKBTree(t, indent);
}
NSDictionary* s_prefs = nil;
static BOOL prefsLoad()
{
if (s_prefs) [s_prefs release];
s_prefs = [[NSDictionary alloc] initWithContentsOfFile:@PREF_FILE];
return s_prefs!=nil;
}
static NSString* prefString(NSString* key, NSString* def)
{
NSString* str = [s_prefs objectForKey:key];
if (!str) return def;
if ([str isKindOfClass:[NSString class]])
return str;
else
return [str description];
}
static int prefInt(NSString* key, int def)
{
id v = [s_prefs objectForKey:key];
if (!v) return def;
return [v intValue];
}
static void prefsLoadApply(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
OLog(1, "Client is reloading prefs...");
prefsLoad();
[[OctopusBeast inst] applyPrefs];
}
@implementation OctopusBeast
static OctopusBeast* s_inst = nil;
+(OctopusBeast*)inst
{
return s_inst;
}
@synthesize keyplane, input, traits;
static UIColor* Int2Color(int c)
{
if (c == 0)
return [UIColor blackColor];
else if (c == 1)
return [UIColor darkGrayColor];
else if (c == 2)
return [UIColor lightGrayColor];
else if (c == 3)
return [UIColor whiteColor];
else if (c == 4)
return [UIColor grayColor];
else if (c == 5)
return [UIColor redColor];
else if (c == 6)
return [UIColor greenColor];
else if (c == 7)
return [UIColor blueColor];
else if (c == 8)
return [UIColor cyanColor];
else if (c == 9)
return [UIColor yellowColor];
else if (c == 10)
return [UIColor magentaColor];
else if (c == 11)
return [UIColor orangeColor];
else if (c == 12)
return [UIColor purpleColor];
else if (c == 13)
return [UIColor brownColor];
else if (c == 14)
return [UIColor clearColor];
return [UIColor blackColor];
}
-(void)applyPrefs
{
_swipeLength = prefInt(@"swipeLength", 1);
_autocapitalization = prefInt(@"autocapitalization", 1) != 0;
_enabled = prefInt(@"enabled", 1) != 0;
_downPlural = prefInt(@"downplural", 1) != 0;
_abovekeys = prefInt(@"abovekeys", 1) != 0;
_minChars = prefInt(@"minChars", 0);
// update colors
[_textColor release];
[_outlineColor release];
_textColor = [Int2Color(prefInt(@"textColor", 0)) retain];
_outlineColor = [Int2Color(prefInt(@"outlineColor", 3)) retain];
oReloadPrefs(GetServerPort());
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
/*if (GetServerPort() == 0)
{
[self release];
return nil;
}*/
s_inst = self;
prefsLoad();
[self applyPrefs];
self.autoresizingMask = 0xFFFFFFFF;
self.backgroundColor = [UIColor clearColor];
self.input = @"";
_inputMode = [NSString new];
_input = [NSMutableString new];
_keysDrawn = [NSMutableSet new];
_isPad = isPad();
_suggs_struct.count = 0;
for (int i=0; i<MAX_SUGGS; i++)
_suggs[i] = [NSMutableString new];
self.userInteractionEnabled = NO;
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, prefsLoadApply, CFSTR("me.k3a.OctopusKeyboard/reloadPrefs"), NULL, CFNotificationSuspensionBehaviorCoalesce);
hasPendingChanges=NO;
processingUpdate=NO;
}
return self;
}
-(void)dealloc
{
s_inst = nil;
[_keysDrawn release];
[_prevWord release];
[_inputMode release];
[_input release];
for (int i=0; i<MAX_SUGGS; i++)
[_suggs[i] release];
[_textColor release];
[_outlineColor release];
[super dealloc];
}
-(int)swipeLength
{
return _swipeLength;
}
-(BOOL)pluralOnSwipeDown
{
return _downPlural;
}
// returns TRUE if no intersecting line found and adds that line to the list
-(BOOL)checkAndInsertLineX1:(float)x1 X2:(float)x2 Y:(float)y
{
sLine inpLine(x1, x2, y);
BOOL colides = NO;
for(LineVector::const_iterator it = _lines.begin(); it != _lines.end(); it++)
{
const sLine& ln = *it;
if (ln.CollidesWith(inpLine))
{
colides = YES;
break;
}
}
if (!colides)
{
_lines.push_back(inpLine);
return TRUE;
}
else
return FALSE;
}
static BOOL digitsOnly(NSString* objcstr)
{
if (!objcstr) return NO;
const char* str = [objcstr UTF8String];
for (unsigned i=0; i<strlen(str); i++)
{
if (!isdigit(str[i]))
return NO;
}
return YES;
}
-(void)drawKBTree:(id)tree
{
if (GetServerPort() == 0 || !_enabled) return;
if (strcmp(class_getName([tree class]), "UIKBTree")) return;
NSDictionary* props = [tree properties];
NSString* key = [props objectForKey:@"KBrepresentedString"];
if ([_keysDrawn containsObject:key]) return; // key already drawn
if (key) [_keysDrawn addObject:key];
//NSLog(@"KEY '%@'", key);
CGContextRef context = UIGraphicsGetCurrentContext();
static UIFont* font = [[UIFont systemFontOfSize:isPad()?14:12] retain];
static UIFont* fontInp = [[UIFont boldSystemFontOfSize:isPad()?14:12] retain];
CGColor* whiteColor = [_outlineColor CGColor];
CGColor* blackColor = [_textColor CGColor];
static CGColor* redColor = [[[UIColor colorWithRed:.5f green:0 blue:0 alpha:1] retain] CGColor];
// compute length of input
NSString* inp = _input;//TODO:ios7 not sure if _input is a good alternative
if (!IS_IOS7) inp = [self inputString]; // this was ok on ios6
unsigned inpLen = [inp length];
// get completed word
NSString* sugg; BOOL isCorrection = FALSE;
if (key && [key length] == 1 /*keys are one-char only*/ && (sugg = [self suggestionForKey:key isCorrection:&isCorrection]))
{
CGRect frame = [[props objectForKey:@"KBshape"] frame];
CGPoint kpos = frame.origin; kpos.y -= (_abovekeys?12:1) + self.frame.origin.y;
float ksize = frame.size.width;
unsigned suggLen = [sugg length];
unsigned postLen = suggLen - inpLen;
// TODO: becaue kptapi does not report it correctly,
// use prefix comparison to detect whether the sugg is a correction
if (inpLen>0 && suggLen >= inpLen)
{
isCorrection = ![[sugg lowercaseString] hasPrefix:[inp lowercaseString]];
//NSLog(@"NOT COMPARE '%@' '%@' range 0, %d", inp, sugg, inpLen);
// use the prefix from suggestion (to fix cases)
inp = [sugg substringToIndex:[inp length]];
}
// compute pixel size of input string
float inpSize = 0;
if (inpLen) inpSize = [inp sizeWithFont:fontInp].width;
if (isCorrection/*!prefixTheSame && suggLen>0*/) // draw autocorrected word sugg
{
float totalSize = [sugg sizeWithFont:font].width;
float inpPos = kpos.x + ksize/2 - totalSize/2;
if ([self checkAndInsertLineX1:inpPos X2:inpPos+totalSize Y:kpos.y])
{
// Draw outlined text
CGContextSetTextDrawingMode(context, kCGTextStroke);
CGContextSetLineWidth(context,2);
CGContextSetStrokeColorWithColor(context, whiteColor);
[sugg drawAtPoint:CGPointMake(inpPos, kpos.y) withFont:font];
// Draw filled text
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetFillColorWithColor(context, redColor);
[sugg drawAtPoint:CGPointMake(inpPos, kpos.y) withFont:font];
}
}
else if (postLen>0) // draw prefix from inp + suggestion from sugg
{
// get sugg postfix
NSString* suggPost = [sugg substringFromIndex:inpLen];
// compute sugg font size
float suggSize = [suggPost sizeWithFont:font].width;
float totalSize = inpSize + suggSize;
float inpPos = kpos.x + ksize/2 - totalSize/2;
float suggPos = inpPos + inpSize;
if (_rightToLeft && !digitsOnly(sugg))
{
suggPos = kpos.x + ksize/2 - totalSize/2;
inpPos = suggPos + totalSize - inpSize;
}
//NSLog(@"INP '%@' SUGG: '%@' post: '%@' totalsize = %.0f", inp, sugg, suggPos, totalSize);
//NSLog(@"ORIGIN [%.0f,%.0f;%.0f] Draw [%.0f,%.0f]", kpos.x, kpos.y, ksize, inpPos, kpos.y);
if ([self checkAndInsertLineX1:inpPos X2:inpPos+totalSize Y:kpos.y])
{
// input part
if (inpLen>0)
{
UIFont* fnt = font;
if (prefInt(@"boldtext",1) != 0) fnt = fontInp;
// Draw outlined text
CGContextSetTextDrawingMode(context, kCGTextStroke);
CGContextSetLineWidth(context,2);
CGContextSetStrokeColorWithColor(context, whiteColor);
[inp drawAtPoint:CGPointMake(inpPos, kpos.y) withFont:fnt];
// draw underline
/*CGContextSetLineWidth(context, 1);
CGContextMoveToPoint(context, inpPos, kpos.y+10);
CGContextAddLineToPoint(context, inpPos + inpSize, kpos.y+10);
CGContextStrokePath(context);*/
// Draw filled text
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetFillColorWithColor(context, blackColor);
[inp drawAtPoint:CGPointMake(inpPos, kpos.y) withFont:fnt];
}
// suggestion part
{
// Draw outlined text
CGContextSetTextDrawingMode(context, kCGTextStroke);
CGContextSetLineWidth(context,2);
CGContextSetStrokeColorWithColor(context, whiteColor);
[suggPost drawAtPoint:CGPointMake(suggPos, kpos.y) withFont:font];
// Draw filled text
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetFillColorWithColor(context, blackColor);
[suggPost drawAtPoint:CGPointMake(suggPos, kpos.y) withFont:font];
}
}
}
}
for (id t in [tree subtrees])
[self drawKBTree:t];
}
-(void)printKeyplane
{
printKBTree([self keyplane], @"");
}
-(BOOL)canComplete
{
if (GetServerPort() == 0 || !_enabled) return NO;
BOOL secureTextEntry = NO;
if ([self.traits respondsToSelector:@selector(isSecureTextEntry)])
secureTextEntry = [self.traits isSecureTextEntry];
UIKeyboardType type = [self.traits keyboardType];
return !secureTextEntry &&
(type == UIKeyboardTypeDefault || type == UIKeyboardTypeASCIICapable || type == UIKeyboardTypeTwitter) /*&&
([self.traits autocorrectionType] != UITextAutocorrectionTypeNo)*/;
}
-(BOOL)shouldCapitalize
{
if (!_autocapitalization) return NO;
if ([self.traits respondsToSelector:@selector(autocapitalizationType)])
return [self.traits autocapitalizationType] == UITextAutocapitalizationTypeSentences || [self.traits autocapitalizationType] == UITextAutocapitalizationTypeWords;
}
-(void)drawRect:(CGRect)rect
{
if (![self canComplete]) return;
_lines.clear();
[_keysDrawn removeAllObjects];
[self drawKBTree:self.keyplane];
}
-(void)releaseCompletionEngine
{
OLog(0, "Client shutdown");
oProfileSave(GetServerPort());
/*db_refresh();
db_sync();
db_shutdown();*/
}
-(void)initCompletionEngine
{
if (![_inputMode length]) return;
OLog(0, "Client init (mode %s)", [_inputMode UTF8String]);
if (GetServerPort() == 0)
{
OErr(0, "Error connecting to the daemon!!");
return;
}
// clearing input may be needed, but normally input should be set by
// UIKeyboardImpl updateForChangedSelection
}
-(void)setInputMode:(NSString*)inpM
{
if (inpM && ![inpM isEqualToString:_inputMode])
{
[_inputMode release];
_inputMode = [inpM copy];
// is right-to-left language?
_rightToLeft = [inpM hasPrefix:@"he"] || [inpM hasPrefix:@"ar"];
[self releaseCompletionEngine];
[self initCompletionEngine];
}
}
-(NSString*)inputMode
{
return _inputMode;
}
-(NSString*)inputString
{
return _input;
}
-(void)updateSuggestions {
if (!_enabled) { _numSuggs=0; return; } // TODO: also delete existing suggs
if (GetServerPort() == 0) { _numSuggs=0; return; } // no daemon conn
//
if (processingUpdate) {
hasPendingChanges=YES;
return;
}
processingUpdate=YES;
//
self.hidden=YES;
static Class _UIKeyboardImpl = objc_getClass("UIKeyboardImpl");
UIKeyboardImpl* ki = [_UIKeyboardImpl sharedInstance];
id inpd = [ki inputDelegate];
// HACK: set input from input manager directly
UIKeyboardInputManager* im = [ki inputManager];
NSString* wstr = _input;//TODO:ios7 not sure if this is a good alternative
if (!IS_IOS7) wstr = [im inputString]; // this was fine on ios6
if (wstr) [_input setString:wstr];
// check if input length is long enough
if ([wstr length] < _minChars)
{
OLog(0, "Input too short");
processingUpdate = NO;
_numSuggs = 0;
return;
}
UITextRange* selRange = [inpd selectedTextRange];
UITextRange* wordRange = nil;
if (selRange)
{
wordRange = [inpd _rangeOfEnclosingWord:[selRange start]];
if (!wordRange) wordRange = selRange;
}
OLog(3, "UPDATING SUGGS FOR INPUT WORD '%s'", [_input UTF8String]);
// should capitalize?
_capitalizeWord = NO;
if (wordRange)
{
NSString* context = _input;//TODO:ios7 not sure if that is a good alternative
if (!IS_IOS7) context = [ki currentInputContextFromInputDelegateWithWordRange:wordRange];
if (context)
{
int offset = [inpd offsetFromPosition:[wordRange end] toPosition:[selRange start]];
[self setContext:context word:_input offset:offset];
const char* cctx = [context UTF8String];
unsigned cctxLen = strlen(cctx);
for (int i=cctxLen-1; i>=0; i--)
{
if (cctx[i] == ' ')
continue;
else if (cctx[i] == '.' || cctx[i] == '!' || cctx[i] == '?')
{
_capitalizeWord = [self shouldCapitalize]; // capitalize if possible
break;
}
else
break;
}
}
if (!context || [context length] == 0)
_capitalizeWord = [self shouldCapitalize]; // no context -> capitalize if possible
}
else
_capitalizeWord = [self shouldCapitalize]; // no selected range -> capitalize if possible
OLog(3, "CAPITALIZE: %s", _capitalizeWord?"YES":"NO");
if (_capitalizeWord)
[_input setString:[_input capitalizedString]];
else if ([_input length]>0)
{
// maybe user started the word with uppercase?
NSString *character = [_input substringWithRange:NSMakeRange(0, 1)];
_capitalizeWord = [character isEqualToString:[character uppercaseString]];
}
[self performSelectorInBackground:@selector(updateSuggestionsBg) withObject:nil];
}
-(void)updateSuggestionsBg {
_suggs_struct.count = 0;
oSuggGetSuggestions(GetServerPort(), &_suggs_struct);
_numSuggs = _suggs_struct.count;
[self performSelectorOnMainThread:@selector(updateSuggestionsRest) withObject:nil waitUntilDone:NO];
}
-(void)updateSuggestionsRest {
/*if (hasPendingChanges) {
hasPendingChanges=NO;
processingUpdate=NO;
[self updateSuggestions];
return;
}//*/
for (int i=0; i<_suggs_struct.count; i++)
{
NSString* suggStr = [NSString stringWithUTF8String:_suggs_struct.suggs[i].word];
if (!suggStr) suggStr = @"";
// fix case where there is "@" or "#" at the beginning of input buffer
//if ([_input hasPrefix:@"@"])
// suggStr = [NSString stringWithFormat:@"@%@", suggStr];
//else if ([_input hasPrefix:@"#"])
// suggStr = [NSString stringWithFormat:@"#%@", suggStr];
// caps lock?
if ([[UIKeyboardImpl sharedInstance] isShiftLocked])
[_suggs[i] setString:[suggStr uppercaseString]];
else
{
if (_capitalizeWord)
[_suggs[i] setString:[suggStr capitalizedString]];
else
[_suggs[i] setString:suggStr];
}
_isCorrection[i] = (_suggs_struct.suggs[i].type & ST_ERRORCORRECTION) ||
(_suggs_struct.suggs[i].type & ST_PROXIMITYSUGGESTION);
OLog(3,"- %s%s", [_suggs[i] UTF8String], _isCorrection[i]?" (corr)":"");
}
//[self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO];
if (hasPendingChanges) {
hasPendingChanges=NO;
processingUpdate=NO;
[self updateSuggestions];
return;
}
[self setNeedsDisplay];
self.hidden=NO;
processingUpdate=NO;
}
-(void)inputAdd:(NSString*)str
{
if (GetServerPort() == 0 || !_enabled) return;
if (!str || ![str length]) return;
// prevent suggestins looking as corrections when there is @ or # at the beginning of input buffer
if (![_input length] && ([str isEqualToString:@"#"] || [str isEqualToString:@"@"])) return;
OLog(3, "INPUT ADD %s", [str UTF8String]);
const char* cstr = [str UTF8String];
// append fake space after punctuations (just in case)
bool clear = false;
if (cstr && (*cstr == '.' || *cstr == ',' || *cstr == '!' || *cstr == '?' /*|| *cstr == '\"' || *cstr == ':'*/))
{
str = [str stringByAppendingString:@" "];
clear = true;
}
[_input appendString:str];
oInputInsertString(GetServerPort(), [str UTF8String], CM_NONE, false);
if (cstr && (clear || *cstr == ' ' || *cstr == '\r' || *cstr == '\n'))
[self inputClearWord];
[self updateSuggestions];
}
-(void)inputClearWord
{
[_input setString:@""];
}
-(void)inputClear
{
OLog(3, "INP CLEAR");
[self inputClearWord];
oInputClear(GetServerPort());
/*if (_prevWord)
{
char phrase[1024];
sprintf(phrase, "%s ", [_prevWord UTF8String]);
oInputInsertString(GetServerPort(), phrase, CM_NONE, false);
} */
[self updateSuggestions];
}
-(void)inputSet:(NSString*)str
{
if (GetServerPort() == 0 || !str || !_enabled) return;
[_input setString:str];
oInputClear(GetServerPort());
oInputInsertString(GetServerPort(), [str UTF8String], CM_NONE, false);
}
-(void)setContext:(NSString*)ctx word:(NSString*)word offset:(int)offset
{
if (GetServerPort() == 0 || !_enabled) return;
oInputClear(GetServerPort());
int begOff = [word length]+offset;
OLog(3, "CONTEXT WORD '%s' begOff %d", [word UTF8String], begOff);
if (begOff > 0 && begOff <= [word length])
[_input setString:[word substringWithRange:NSMakeRange(0, begOff)]];
else
[_input setString:@""];
oInputInsertString(GetServerPort(), [[NSString stringWithFormat:@"%@%@", ctx, word] UTF8String], CM_NONE, false);
oInputCursorMove(GetServerPort(), SO_END, offset);
}
// original accept word (just insert)
-(void)acceptWord:(NSString*)w
{
if (![self canComplete]) return;
OLog(3,"ORIG ACCEPT WORD");
//TODO: here I suppose that the user wrote complete word, in this case, only thing needed is just send space to the daemon.
// If the input was IOS autocompletion or simply not complete, I would need to replace the current word with this one in the daemon.
if (prefInt(@"learn",1)!=0)
oInputLearn(GetServerPort()); // learn the current buffer
oInputInsertString(GetServerPort(), [@" " UTF8String], CM_NONE, false);
//[_prevWord release];
//_prevWord = [w copy];
//[self inputClear];
}
-(NSString*)acceptWordFromSuggestionKey:(NSString *)k
{
OLog(3, "acceptWordFromSuggestionKey - canComplete %s longPressed %s", [self canComplete]?"y":"n", _longPressed?"y":"n");
if (![self canComplete]) return nil;
if (_longPressed) return nil;
BOOL isCorrection = FALSE;
int suggIdx = [self suggestionIndexForKey:k];
if (suggIdx == -1) return nil;
NSString* sugg = _suggs[suggIdx];
NSString* suggPost = nil;
if (sugg)
{
OLog(3, "ACCEPT FROM SUGG WITH KEY %s => '%s'", [k UTF8String], [sugg UTF8String]);
unsigned inpLen = [_input length];
/* if ([sugg length]>inpLen)
suggPost = [sugg substringFromIndex:inpLen];*/
suggPost = [[sugg copy] autorelease];
// send sugg insert to the daemon
oInputInsertSugg(GetServerPort(), _suggs_struct.set, _suggs_struct.suggs[suggIdx].ident, true);
[self updateSuggestions];
// clear our internal buffer
[_input setString:@""];
}
return suggPost;//[suggPost stringByAppendingString:@" "]; //TODO: appending spaces!
}
-(void)inputBackspace
{
if ([_input length] == 0)
{
/*static Class _UIKeyboardImpl = objc_getClass("UIKeyboardImpl");
UIKeyboardImpl* ki = [_UIKeyboardImpl sharedInstance];
UIKeyboardInputManager* im = [ki inputManager];
NSString* wstr = [im inputString];
if (wstr) [_input setString:wstr];
*/
[self updateSuggestions];
return;
}
OLog(3, "BACKSPACE");
oInputRemove(GetServerPort(), 1, 0);
[_input deleteCharactersInRange:NSMakeRange([_input length]-1, 1)];
[self updateSuggestions];
}
-(int)suggestionIndexForKey:(NSString*)k
{
if (processingUpdate) return -1;
unsigned inpLen = [_input length];
for (int i=0; i<_numSuggs; i++)
{
unsigned suggLen = [_suggs[i] length];
if (suggLen <= inpLen) continue;
NSString* nextSuggChar = [_suggs[i] substringWithRange:NSMakeRange(inpLen, 1)];
//NSLog(@"suggestionIndexForKey '%s' '%s'", nextSuggChar, k);
if ([nextSuggChar compare:k options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch|NSWidthInsensitiveSearch] == NSOrderedSame)
return i;
}
return -1;
}
-(NSString*)suggestionForKey:(NSString*)k isCorrection:(BOOL*)corr
{
unsigned inpLen = [_input length];
int idx = [self suggestionIndexForKey:k];
if (idx == -1) return nil;
if (corr) *corr = _isCorrection[idx];
//NSLog(@"nextSugg char '%@' for key '%@' => %@", nextSuggChar, k, _suggs[i]);
return _suggs[idx];
}
-(void)longPress
{
_longPressed = YES;
}
-(void)resetLongPress
{
_longPressed = NO;
}
-(BOOL)isLongPressed
{
return _longPressed;
}
@end