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 5
/
main.mm
2768 lines (2325 loc) · 93.7 KB
/
main.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
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
//
// Created by K3A on 5/20/12.
// Copyright (c) 2012 K3A.
// Released under GNU GPL v2
//
// SpeakEvents Source Code
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AddressBook/AddressBook.h>
#import <SpringBoard/SBTelephonyManager.h>
#import <SpringBoard/SBMediaController.h>
#import <SpringBoard/SBAwayController.h>
#import <AVFoundation/AVFoundation.h>
#import <Celestial/AVSystemController.h>
#import <SpringBoard/VolumeControl.h>
//#include <sys/statvfs.h> // VFS stat
#include <cld/cld.h>
#import <locale.h>
#import <objc/runtime.h>
#import "substrate.h"
#import "main.h"
#import "log.h"
#include "AntiGDB.h"
#import "KStringAdditions.h"
#import "K3AStringFormatter.h"
#import "PrivateAPIs.h"
#import "SEActivatorSupport.h"
#import <LibDisplay.h>
#include <sys/sysctl.h>
#include <notify.h>
static NSRecursiveLock* s_abLock = nil;
static BOOL s_isDND = NO;
// 0 - normal, 1 - more info, 2 - debug
static void SELog(int level, NSString *format, ...)
{
#ifndef DEBUG
if (level>1) return; // UNCOMMENT ON OFFICIAL RELEASE
#endif
if (format == nil) {
printf("nil\n");
return;
}
// Get a reference to the arguments that follow the format parameter
va_list argList;
va_start(argList, format);
// Perform format string argument substitution, reinstate %% escapes, then print
NSString *s = [[NSString alloc] initWithFormat:format arguments:argList];
NSLog(@"SE: %@", s);
[s release];
va_end(argList);
}
@implementation SESpeakableMessage
@synthesize messageIdentifier,firstPart,secondPart,thirdPart,numPartsRead;
-(id)initWithApp:(SESpeakableApp*)app
{
if ((self = [super init]))
{
_app = [app retain];
}
return self;
}
-(void)dealloc
{
[_app release];
[super dealloc];
}
-(SESpeakableApp*)app
{
return _app;
}
@end
@implementation SESpeakableApp
+(id)speakableAppWithIdentifier:(NSString*)ident
{
return [[SESpeakableApp alloc] initWithIdentifier:ident];
}
-(id)initWithIdentifier:(NSString*)ident
{
if ( (self = [super init]) )
{
_msgs = [[NSMutableArray alloc] init];
_appIdent = [ident copy];
}
return self;
}
-(void)dealloc
{
[_msgs release];
[_appIdent release];
[super dealloc];
}
-(NSString*)appIdentifier
{
return _appIdent;
}
-(void)pushMessage:(SESpeakableMessage*)msg
{
@synchronized(_msgs)
{
[_msgs addObject:msg];
}
}
-(SESpeakableMessage*)popMessage // returns nil if no more messages
{
@synchronized(_msgs)
{
if ([_msgs count] == 0) return nil;
SESpeakableMessage* obj = [[_msgs objectAtIndex:0] retain];
[_msgs removeObjectAtIndex:0];
return [obj autorelease];
}
}
-(SESpeakableMessage*)findMessage:(NSString*)messageIdentifier // may return nil
{
if (!messageIdentifier) return nil;
@synchronized(_msgs)
{
for (SESpeakableMessage* msg in _msgs)
{
if ([msg.messageIdentifier isEqualToString:messageIdentifier])
{
return msg;
}
}
}
return nil;
}
-(void)removeAllMessages
{
[_msgs removeAllObjects];
}
-(unsigned)numOfRemainingMessages
{
return [_msgs count];
}
@end
static NSString* getAppIdentifier()
{
NSString* appIdent = nil;
if (!appIdent)
{
NSString *returnString = nil;
int mib[4], maxarg = 0, numArgs = 0;
size_t size = 0;
char *args = NULL, *namePtr = NULL, *stringPtr = NULL;
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
size = sizeof(maxarg);
if ( sysctl(mib, 2, &maxarg, &size, NULL, 0) == -1 ) {
return @"Unknown";
}
args = (char *)malloc( maxarg );
if ( args == NULL ) {
return @"Unknown";
}
mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS2;
mib[2] = getpid();
size = (size_t)maxarg;
if ( sysctl(mib, 3, args, &size, NULL, 0) == -1 ) {
free( args );
return @"Unknown";
}
memcpy( &numArgs, args, sizeof(numArgs) );
stringPtr = args + sizeof(numArgs);
if ( (namePtr = strrchr(stringPtr, '/')) != NULL ) {
namePtr++;
returnString = [[NSString alloc] initWithUTF8String:namePtr];
} else {
returnString = [[NSString alloc] initWithUTF8String:stringPtr];
}
return [returnString autorelease];
}
if (!appIdent) appIdent = [[NSBundle mainBundle] bundleIdentifier];
return appIdent;
}
HOOK(SBApplication, _fireNotification$, void, UILocalNotification* notif)
{
/*
SE: Local notification: <UIConcreteLocalNotification: 0xf293190>{fire date = středa, 25. dubna 2012 15:53:27 Středoevropský letní čas, time zone = Europe/Prague (CEST) offset 7200 (Daylight), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = (null)} alertBody: Local Push Notification Test soundName: UILocalNotificationDefaultSoundName isSystem: N
*/
/*
SELog(0, @"Local notification: %@ alertBody: %@ soundName: %@ isSystem: %s", notif, notif.alertBody, notif.soundName, notif.isSystemAlert?"Y":"N");*/
if (notif.isSystemAlert) // alarm
{
[[SESpeakEventsServer sharedInstance] handleSystemNotification:notif];
}/*
else // send as a push
{
BBBulletin* bul = [[[BBBulletin alloc] init] autorelease];
bul.section = notif.
[[SESpeakEventsServer sharedInstance] observer:nil addBulletin:bul forFeed:0];
}*/
ORIG(notif);
}
END
// Notificator support
HOOK(SBBulletinBannerController, observer$addBulletin$forFeed$, void, BBObserver* observer, BBBulletin* bulletin, unsigned feed)
{
ORIG(observer, bulletin, feed);
//SELog(0, @"SBBulletinBannerController %@", bulletin);
if (bulletin && [bulletin.bulletinID isEqualToString:@"NotificatorBulletin"])
{
SELog(0, @"Adding Notificator bulletin.");
[[SESpeakEventsServer sharedInstance] observer:observer addBulletin:bulletin forFeed:feed];
}
else if (bulletin && [bulletin.bulletinID isEqualToString:@"NowListeningBulletin"])
{
SELog(0, @"Adding NowListening bulletin.");
[[SESpeakEventsServer sharedInstance] observer:observer addBulletin:bulletin forFeed:feed];
}
else if (bulletin && [bulletin.publisherBulletinID isEqualToString:@"AMCbanner"])
{
SELog(0, @"Adding AMC bulletin.");
[bulletin setSection:@"com.apple.mobileipod"];
[[SESpeakEventsServer sharedInstance] observer:observer addBulletin:bulletin forFeed:feed];
}
}
END
HOOK(BBServer, publishBulletin$destinations$, void, BBBulletin* bullReq, int dests)
{
//SELog(3, @"publishBulletin: %@ dests %d", bullReq, dests);
[[SESpeakEventsServer sharedInstance] observer:nil addBulletin:bullReq forFeed:dests];
return ORIG(bullReq, dests);
}
END
//ios6
HOOK(BBServer, publishBulletin$destinations$alwaysToLockScreen$, void, BBBulletin* bullReq, int dests, BOOL toLock)
{
[[SESpeakEventsServer sharedInstance] observer:nil addBulletin:bullReq forFeed:dests];
return ORIG(bullReq, dests, toLock);
}
END
HOOK(SBApplication, launchSucceeded$, void, BOOL success)
{
NSString* ident = [self displayIdentifier];
SELog(3, @"launch succeeded %@", ident);
[[SESpeakEventsServer sharedInstance] handleLaunchSucceeded:ident];
return ORIG(success);
}
END
//ios6
HOOK(SBApplication, didBeginLaunch$, void, id app)
{
NSString* ident = [self displayIdentifier];
SELog(3, @"launch succeeded %@", ident);
[[SESpeakEventsServer sharedInstance] handleLaunchSucceeded:ident];
return ORIG(app);
}
END
/*HOOK(TLToneManager, currentNewMailToneSoundID, int)
{
SELog(0, @"currentNewMailToneSoundID");
if ([[SESpeakEventsServer sharedInstance] shouldSuppressNewMailSound])
return 0;
else
return ORIG();
}
END
HOOK(TLToneManager, currentTextToneSoundID, int)
{
SELog(0, @"currentTextToneSoundID");
if ([[SESpeakEventsServer sharedInstance] shouldSuppressNewMessageSound])
return 0;
else
return ORIG();
}
END*/
// support code
/*HOOK(MFMailBulletin, bulletinRequest, BBBulletin*)
{
BBBulletin* b = ORIG();
NSDictionary* origContext = [b context];
NSMutableDictionary* context = nil;
if (origContext)
context = [NSMutableDictionary dictionaryWithDictionary:origContext];
else
context = [NSMutableDictionary dictionary];
if ([self respondsToSelector:@selector(mailAccountId)])
[context setObject:[self mailAccountId] forKey:@"SEAccountID"];
[b setContext:context];
return b;
}
END*/
/*static BOOL InMessages()
{
static DSDisplayController* dctrl = nil;
if (!dctrl) dctrl = [DSDisplayController sharedInstance];
SBApplication *actApp = [dctrl activeApp];
if (!actApp) return FALSE;
NSString *actAppIdent = [actApp displayIdentifier];
//SELog(0, @"I am in the %@", actAppIdent);
BOOL inMessages = [actAppIdent isEqualToString:@"com.apple.MobileSMS"];
if (inMessages) return TRUE;
BOOL inBiteSMS = [actAppIdent isEqualToString:@"com.bitesms"];
if (inBiteSMS) return TRUE;
BOOL inReadSMS2 = [actAppIdent isEqualToString:@"com.spiritoflogic.iRealSMS2"];
if (inReadSMS2) return TRUE;
BOOL inReadSMS3 = [actAppIdent isEqualToString:@"com.spiritoflogic.iRealSMS3"];
if (inReadSMS3) return TRUE;
BOOL inReadSMS4 = [actAppIdent isEqualToString:@"com.spiritoflogic.iRealSMS4"];
if (inReadSMS4) return TRUE;
return FALSE;
}*/
static BOOL IsInNotAllowedApp()
{
@try {
//static DSDisplayController* dctrl = nil;
//if (!dctrl) dctrl = [DSDisplayController sharedInstance];
SBApplication *actApp = [LibDisplay sharedInstance].topApplication;
if (!actApp) {/* SELog(0, @"Failed to get foremost app!");*/ return FALSE;}
NSString *actAppIdent = [actApp bundleIdentifier];
if (!actAppIdent) return FALSE;
SELog(3, @"I am in '%@'", actAppIdent);
BOOL inSkype = [actAppIdent isEqualToString: @"com.skype.skype"];
if (inSkype) return TRUE;
}@catch(NSException* ex) {
SELog(0, @"LibDisplay Exception: %@", [ex description]);
}
return FALSE;
}
static NSString* GetSystemLanguage()
{
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
/*NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSArray* arrayLanguages = [userDefaults objectForKey:@"AppleLanguages"];
NSString* language = [arrayLanguages objectAtIndex:0];*/
char lang[16];
strcpy(lang, [language UTF8String]);
unsigned sepIdx = strlen(lang);
bool afterSep = false;
for (unsigned i=0; i<strlen(lang); i++)
{
if (lang[i] == '_' || lang[i] == '-')
{
lang[i] = '-';
sepIdx = i;
afterSep = true;
}
else if (afterSep)
lang[i] = toupper(lang[i]);
}
// try to find the exact language code
NSArray* langArr = [VSSpeechSynthesizer availableLanguageCodes];
bool found = false;
bool exact = false;
for(NSString* l in langArr)
{
const char* cl = [l UTF8String];
if (!strcmp(cl, lang))
{
found = true;
exact = true;
break;
}
}
// if not exact, try to find prefix
if (!found)
{
for(NSString* l in langArr)
{
const char* cl = [l UTF8String];
if (!strncmp(cl, lang, sepIdx))
{
strcpy(lang, cl);
found = true;
break;
}
}
}
if (!found) strcpy(lang, "en-US");
if (!strcmp(lang, "en-GB") && !exact)
strcpy(lang, "en-US");
return [NSString stringWithUTF8String:lang];
}
static NSString* MainLangPart(NSString* lang)
{
NSArray* l = [lang componentsSeparatedByString:@"-"];
if ([l count] == 1) l = [lang componentsSeparatedByString:@"_"];
return [l objectAtIndex:0];
}
static NSString* getPhoneticNameByName(NSString* firstName, NSString* lastName)
{
NSMutableString *ContactName = [[[NSMutableString alloc] initWithFormat:@"%@ %@", firstName, lastName] autorelease];
[s_abLock lock];
ABAddressBookRef addressBook = ABAddressBookCreate();
if (!addressBook) { [s_abLock unlock]; return ContactName; }
NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
if ( people==nil )
{
if (addressBook) CFRelease(addressBook);
[s_abLock unlock];
SELog(0, @"Unable to copy array of all people from AB for phonetic name match");
return nil;
}
for (unsigned i=0; i<[people count]; i++ )
{
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
BOOL shouldQuit = NO;
CFStringRef firstNameValue = (CFStringRef)ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef lastNameValue = (CFStringRef)ABRecordCopyValue(person, kABPersonLastNameProperty);
CFStringRef firstNamePhoneticValue = nil;
CFStringRef lastNamePhoneticValue = nil;
CFStringRef nickValue = nil;
if ( [(NSString*)firstNameValue isEqualToString:firstName] && [(NSString*)lastNameValue isEqualToString:lastName] )
{
firstNamePhoneticValue = (CFStringRef)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
lastNamePhoneticValue = (CFStringRef)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
if (firstNamePhoneticValue == nil && lastNamePhoneticValue != nil)
{
[ContactName setString:(NSString*)lastNamePhoneticValue];
}
else if (firstNamePhoneticValue != nil)
{
[ContactName setString:(NSString*)firstNamePhoneticValue];
if (lastNamePhoneticValue != nil)
[ContactName appendFormat:@" %@", (NSString*)lastNamePhoneticValue];
}
else if (firstNamePhoneticValue == nil && lastNamePhoneticValue == nil)
{
if (firstNameValue == nil && lastNameValue == nil)
{
nickValue = (CFStringRef)ABRecordCopyValue(person, kABPersonNicknameProperty);
if (nickValue != nil) [ContactName setString:(NSString*)nickValue];
}
else if (firstNameValue == nil && lastNameValue != nil)
[ContactName setString:(NSString*)lastNameValue];
else if (firstNameValue != nil)
{
[ContactName setString:(NSString*)firstNameValue];
if (lastNameValue != nil)
[ContactName appendFormat:@" %@", (NSString*)lastNameValue];
}
}
shouldQuit = YES;
}
if (firstNameValue != nil) CFRelease(firstNameValue);
if (lastNameValue != nil) CFRelease(lastNameValue);
if (firstNamePhoneticValue != nil) CFRelease(firstNamePhoneticValue);
if (lastNamePhoneticValue != nil) CFRelease(lastNamePhoneticValue);
if (nickValue != nil) CFRelease(nickValue);
if (shouldQuit)
break;
}
if (addressBook) CFRelease(addressBook);
[s_abLock unlock];
[people release];
return ContactName;
}
static NSString* Number2Digits(NSString* number)
{
const char* inp = [number UTF8String];
unsigned len = strlen(inp);
char* buf = (char*)malloc(len*3);
for(unsigned i=0; i<len; i++)
{
buf[2*i] = inp[i];
buf[2*i+1] = ' ';
}
buf[len*2] = 0;
NSString* outStr = [NSString stringWithUTF8String:buf];
free(buf);
return outStr;
}
static unsigned NumSameDigits(NSString* first, NSString* second)
{
if (first == nil || second == nil) return 0;
char c;
const char* ac = [first UTF8String];
const char* bc = [second UTF8String];
unsigned al = strlen(ac);
char* bufa = (char*)malloc(al+2);
bufa[0]=0;
char* ptra = bufa+1;
while( (c = *(ac++)) )
{
if (isdigit(c))
*(ptra++) = c;
}
*ptra = 0;
ptra--;
unsigned bl = strlen(bc);
char* bufb = (char*)malloc(bl+2);
bufb[0]=0;
char* ptrb = bufb+1;
while( (c = *(bc++)) )
{
if (isdigit(c))
*(ptrb++) = c;
}
*ptrb = 0;
ptrb--;
//SELog(0, @"Comparing %s %s", bufa+1, bufb+1);
unsigned numMatched = 0;
while( *ptra && *ptrb && *ptra == *ptrb )
{
numMatched++;
ptra--;
ptrb--;
}
free(bufa);
free(bufb);
return numMatched;
}
static NSString* getPhoneticNameByNumber(NSString* number)
{
if (!number || ![number length]) return @"Unknown";
unsigned int inputLen = [number length];
NSMutableString *ContactName = [[Number2Digits(number) mutableCopy] autorelease];
unsigned longestNumberMatch = 0;
[s_abLock lock];
ABAddressBookRef addressBook = ABAddressBookCreate();
if (!addressBook) { [s_abLock unlock]; return @"Unknown";}
NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
if ( people==nil )
{
if (addressBook) CFRelease(addressBook);
[s_abLock unlock];
SELog(0, @"Unable copy people from addressbook!");
return nil;
}
//SELog(3, @"Num people: %d", [people count]);
for (unsigned i=0; i<[people count]; i++ )
{
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (phoneNumbers == nil) continue;
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
BOOL foundNumberInThisPerson = NO;
for ( int k=0; k<phoneNumberCount; k++ )
{
NSString* phoneNumberValueInput = (NSString*)ABMultiValueCopyValueAtIndex( phoneNumbers, k );
if (phoneNumberValueInput == nil) continue; // could not get phone value
NSString* phoneNumberValue = [NSString stringWithString:phoneNumberValueInput];
CFRelease(phoneNumberValueInput);
unsigned strLen = [phoneNumberValue length];
if (strLen < longestNumberMatch)
continue; // not interesting, too short
// check length
unsigned numberMatch = NumSameDigits(phoneNumberValue, number);
if (numberMatch == 0) continue; // no one digit matched
else if (numberMatch < inputLen/2) continue; // too low number of digits matched
longestNumberMatch = numberMatch;
foundNumberInThisPerson = YES;
break;
}
CFStringRef firstNameValue = nil;
CFStringRef lastNameValue = nil;
CFStringRef firstNamePhoneticValue = nil;
CFStringRef lastNamePhoneticValue = nil;
CFStringRef nickValue = nil;
if (foundNumberInThisPerson)
{
firstNamePhoneticValue = (CFStringRef)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
lastNamePhoneticValue = (CFStringRef)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
if (firstNamePhoneticValue == nil && lastNamePhoneticValue != nil)
{
[ContactName setString:(NSString*)lastNamePhoneticValue];
}
else if (firstNamePhoneticValue != nil)
{
[ContactName setString:(NSString*)firstNamePhoneticValue];
if (lastNamePhoneticValue != nil)
[ContactName appendFormat:@" %@", (NSString*)lastNamePhoneticValue];
}
else if (firstNamePhoneticValue == nil && lastNamePhoneticValue == nil)
{
firstNameValue = (CFStringRef)ABRecordCopyValue(person, kABPersonFirstNameProperty);
lastNameValue = (CFStringRef)ABRecordCopyValue(person, kABPersonLastNameProperty);
if (firstNameValue == nil && lastNameValue == nil)
{
nickValue = (CFStringRef)ABRecordCopyValue(person, kABPersonNicknameProperty);
if (nickValue != nil) [ContactName setString:(NSString*)nickValue];
}
else if (firstNameValue == nil && lastNameValue != nil)
[ContactName setString:(NSString*)lastNameValue];
else if (firstNameValue != nil)
{
[ContactName setString:(NSString*)firstNameValue];
if (lastNameValue != nil)
[ContactName appendFormat:@" %@", (NSString*)lastNameValue];
}
}
}
if (firstNameValue != nil) CFRelease(firstNameValue);
if (lastNameValue != nil) CFRelease(lastNameValue);
if (firstNamePhoneticValue != nil) CFRelease(firstNamePhoneticValue);
if (lastNamePhoneticValue != nil) CFRelease(lastNamePhoneticValue);
if (nickValue != nil) CFRelease(nickValue);
}
if (addressBook) CFRelease(addressBook);
[s_abLock unlock];
[people release];
return ContactName;
}
#pragma mark - SPRINGBOARD PART
HOOK(SBUIController, updateBatteryState$, void, id p1)
{
//SELog(2, @">> SBUIController::updateBatteryState <%s>", object_getClassName(p1));
[[SESpeakEventsServer sharedInstance] batteryStateChanged:p1];
CALL_ORIG(p1);
}
END
@implementation SESpeakEventsServer
static SESpeakEventsServer* s_ses_instance = nil;
extern id AVController_PickedRouteAttribute;
-(void)handleLaunchSucceeded:(NSString*)ident
{
NSString* speakIdent = nil;
if (ident && m_currentlySpeakingObject)
speakIdent = [[m_currentlySpeakingObject app] appIdentifier];
if (speakIdent && [ident isEqualToString:speakIdent])
[self stopSpeaking];
}
-(BOOL)shouldSuppressNewMailSound
{
NSNumber* suppressSound = [m_settings objectForKey:@"suppressSound"];
return suppressSound && [suppressSound boolValue];
}
-(BOOL)shouldSuppressNewMessageSound
{
NSNumber* suppressSound = [m_settings objectForKey:@"suppressSound"];
return suppressSound && [suppressSound boolValue];
}
-(void)startBluetooth
{
if (m_voiceCtrl) return; // already present
SELog(3, @"Starting bluetooth");
[synth setMaintainPersistentConnection:YES];
// will create music interruption
NSError* err = nil;
m_voiceCtrl = [AVVoiceController alloc];
if ([m_voiceCtrl respondsToSelector:@selector(initWithHardwareConfig:error:)])
m_voiceCtrl = [m_voiceCtrl initWithHardwareConfig:2 error:&err];
else
m_voiceCtrl = [m_voiceCtrl initWithContext:[NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:1752132965] forKey:@"activation trigger"] error:&err];
if (err) SELog(0, @"Audio system problem: %@", [err description]);
// like we needed bluetooth input
int allowBluetoothInput = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, sizeof (allowBluetoothInput), &allowBluetoothInput);
// for sure "select route"
AVSystemController* sysCtrl = nil;
if (!sysCtrl) sysCtrl = [AVSystemController sharedAVSystemController];
NSArray* routes = [sysCtrl pickableRoutesForCategory:@"PlayAndRecord_WithBluetooth"];
for (NSDictionary* route in routes)
{
if (![[route objectForKey:@"RouteType"] isEqualToString:@"Override"] && ![[route objectForKey:@"RouteType"] isEqualToString:@"Default"])
{
NSError* err = nil;
[sysCtrl setAttribute:route forKey:AVController_PickedRouteAttribute error:&err];
SELog(0, @"Selected external audio route");
break;
}
}
// probably not needed, but...
if ([m_voiceCtrl respondsToSelector:@selector(setHardwareConfiguration:)]) [m_voiceCtrl setHardwareConfiguration:2];
AudioSessionSetActive(1);
m_bluetoothWasUsed = YES;
}
-(void)stopBluetooth
{
/*AudioSessionSetActive(0);
int allowBluetoothInput = 10;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, sizeof (allowBluetoothInput), &allowBluetoothInput);*/
if (!m_voiceCtrl) return; // already stopped
SELog(3, @"Stopping bluetooth");
[synth setMaintainPersistentConnection:NO];
if (m_voiceCtrl)
{
// resume from interruption
[m_voiceCtrl releaseAudioSession];
[m_voiceCtrl release];
m_voiceCtrl = nil;
// disable bluetooth just in case...
int allowBluetoothInput = 0;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, sizeof (allowBluetoothInput), &allowBluetoothInput);
}
m_bluetoothWasUsed = NO;
}
-(NSString*)detectLanguageUsingCLD:(NSString*)str
{
bool is_plain_text = true;
bool do_allow_extended_languages = true;
bool do_pick_summary_language = false;
bool do_remove_weak_matches = false;
bool is_reliable;
const char* tld_hint = NULL;
int encoding_hint = UNKNOWN_ENCODING;
Language language_hint = UNKNOWN_LANGUAGE;
double normalized_score3[3];
Language language3[3];
int percent3[3];
int text_bytes;
const char* src = [str UTF8String];
if (!src) return @"en-US";
Language lang;
lang = CompactLangDet::DetectLanguage(0,
src, strlen(src),
is_plain_text,
do_allow_extended_languages,
do_pick_summary_language,
do_remove_weak_matches,
tld_hint,
encoding_hint,
language_hint,
language3,
percent3,
normalized_score3,
&text_bytes,
&is_reliable);
//printf("LANG=%s\n", LanguageName(lang));
char lcodec[32];
strcpy(lcodec, LanguageCodeWithDialects(lang));
SELog(0, @"Langs scores: %s (%.2f), %s (%.2f), %s (%.2f)", LanguageCodeWithDialects(language3[0]), normalized_score3[0], LanguageCodeWithDialects(language3[1]), normalized_score3[1], LanguageCodeWithDialects(language3[2]), normalized_score3[2] );
// is language preference set?
NSArray* langPrefs = [m_settings objectForKey:@"langPrefs"];
if (langPrefs)
{
const char* clp0 = LanguageCodeWithDialects(language3[0]);
const char* clp1 = LanguageCodeWithDialects(language3[1]);
const char* clp2 = LanguageCodeWithDialects(language3[2]);
for (NSString* lp in langPrefs)
{
const char* clp = [lp UTF8String];
if (!strncmp(clp, clp0, 2) || !strncmp(clp, clp1, 2) || !strncmp(clp, clp2, 2))
{
strcpy(lcodec, clp);
SELog(1, @"Prefering lang %s", clp);
break;
}
}
}
// if default lang set and one of these langs is detected, use the default voice
if ( m_defaultLang && (!strncmp(lcodec, "en", 2) || !strncmp(lcodec, "pt", 2) || !strncmp(lcodec, "es", 2)) )
{
// prefer selected default voice if first two chars with detected and default matches
const char* defaultLang = [m_defaultLang UTF8String];
if (strlen(defaultLang)>2 && !strncmp(defaultLang, lcodec, 2))
{
strcpy(lcodec, defaultLang);
}
}
if (!strncmp(lcodec, "uk", 2)) return @"ru-RU";
if (!strncmp(lcodec, "nb", 2)) return @"no-NO";
NSArray* availableLanguageCodes = [VSSpeechSynthesizer availableLanguageCodes];
char bestLang[8]; bestLang[0]=0;
for (NSString* l in availableLanguageCodes)
{
const char* curLang = [l UTF8String];
if (!strcasecmp(curLang, lcodec))
return l; // exact match
else if (!strncasecmp(curLang, lcodec, 2))
strcpy(bestLang, curLang);
}
if (bestLang[0])
return [NSString stringWithUTF8String:bestLang];
else
return @"en-US";
}
-(NSString*)detectLanguageUsingGoogle:(NSString*)str
{
NSString* url = [NSString stringWithFormat:@"http://www.google.com/uds/GlangDetect?v=1.0&q=%@", [str urlEncodedString]];
NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLResponse* resp = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:nil];
if (!data)
return @"en-US";
else
{
NSString* parsedText = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
const char* cstr = [parsedText UTF8String];
if (!cstr) return @"en-US";
const char* languagePos = strstr(cstr, "language\":\"");
if (!languagePos) return @"en-US";
languagePos += 11;
int llen = 0;
for(int i=0; i<10; i++)
{
if (languagePos[llen] == '\"' || languagePos[llen] == '\0')
break;
llen++;
}
if (llen < 2) return @"en-US";
if (!strncmp(languagePos, "en", 2)) return @"en-US";
char lcodec[8];
strncpy(lcodec, languagePos, 2);
lcodec[2]=0;
NSArray* availableLanguageCodes = [VSSpeechSynthesizer availableLanguageCodes];
for (NSString* l in availableLanguageCodes)
{
if (!strncmp([l UTF8String], lcodec, 2))
return l;
}
return @"en-US";
}
}
-(NSString*)detectLanguage:(NSString*)str
{
NSNumber* detectLang = [m_settings objectForKey:@"detectLang"];
if (!detectLang || [detectLang boolValue])
{
//old return [self detectLanguageUsingGoogle:str];
NSString* langDet = [self detectLanguageUsingCLD:str];
SELog(0, @"Lang detected: %@", langDet);
return langDet;
}
else // autodetect disabled
return m_defaultLang;
}
-(NSString*)smiley:(NSString*)key
{
NSString* val = [m_smileys objectForKey:key];
if (!val) return key;
return val;
}
-(NSMutableString*)postprocessText:(NSString*)input
{
NSMutableString* output = [input mutableCopy];
NSError* err = nil;
// ----- Remove URLs -------------------------------------
static NSRegularExpression* regexpURL = nil;
if (regexpURL == nil)
{
regexpURL = [[NSRegularExpression alloc] initWithPattern:@"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&err];
if (err) SELog(0, @"regexpURL error %@", [err description]);
}
[regexpURL replaceMatchesInString:output options:0 range:NSMakeRange(0, [output length]) withTemplate:@""];
// ----- Remove unwanted sequences -----------------------
static NSRegularExpression* doubleSeq = nil;
if (!doubleSeq)
{
doubleSeq = [[NSRegularExpression alloc] initWithPattern:@"==|--|##|$$|\\*\\*|^^|@@" options:NSRegularExpressionCaseInsensitive error:&err];
if (err) SELog(0, @"doubleSeq error %@", [err description]);