/
HyperloopModule.m
1177 lines (1066 loc) · 40.4 KB
/
HyperloopModule.m
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
/**
* Hyperloop Module
* Copyright (c) 2015-present by Appcelerator, Inc.
*/
#import "HyperloopModule.h"
#import "define.h"
#import "class.h"
#import "pointer.h"
#import "utils.h"
#ifdef TIMODULE
#import "TiBase.h"
#import "KrollContext.h"
#import "KrollBridge.h"
#import "KrollCallback.h"
#import "TiHost.h"
#import "TiModule.h"
#import "KrollObject.h"
#import "TiEvaluator.h"
#import "TiHost.h"
#import "HyperloopView.h"
#import "TiViewProxy.h"
#else
#import "UIKit/UIKit.h"
// for unit testing
@interface KrollContext : NSObject
-(JSContextRef)context;
@end
@interface KrollBridge : NSObject
-(id)require:(KrollContext*)kroll path:(NSString*)path;
@end
@interface KrollObject : NSObject
+(id)toID:(KrollContext *)c value:(JSValueRef)ref;
-(JSObjectRef) propsObject;
@end
@interface KrollWrapper : NSObject
@property (nonatomic,readwrite,assign) JSObjectRef jsobject;
@end
@interface KrollCallback : NSObject
@end
@interface TiViewProxy : NSObject
@property(nonatomic,readwrite,retain) UIView * view;
@end
#endif
#if TARGET_OS_SIMULATOR
extern void JSSynchronousGarbageCollectForDebugging(JSContextRef);
#endif
static JSClassRef classClassRef;
static JSClassRef pointerClassRef;
static JSClassRef constructorClassRef;
static JSClassRef objectClassRef;
static KrollContext *context = nil;
static KrollBridge *bridge = nil;
static NSMutableDictionary <NSString *, KrollCallback *> * callbacks = nil;
static NSMutableDictionary <NSString *, KrollWrapper *> * modules = nil;
static CFMutableDictionaryRef javaScriptWrappers = NULL;
static NSString* HyperloopGetMemoryAddressOfId(id data);
static void HyperloopRegisterWrapper(id pointer, JSValueRef thisObject);
static JSObjectRef HLObjectMake(JSContextRef ctx, JSClassRef cls, id obj);
JSObjectRef HyperloopGetWrapperForId(id obj);
static void HyperloopRelease () {
if (context) {
[callbacks removeAllObjects];
[modules removeAllObjects];
ARCRelease(callbacks);
ARCRelease(modules);
classClassRef = NULL;
pointerClassRef = NULL;
constructorClassRef = NULL;
objectClassRef = NULL;
bridge = nil;
context = nil;
callbacks = nil;
modules = nil;
}
if (javaScriptWrappers) {
CFRelease(javaScriptWrappers);
javaScriptWrappers = NULL;
}
}
/**
* gets the memory address of an Objective-C object as a string
*/
static NSString* HyperloopGetMemoryAddressOfId (id data) {
if (data == nil) { return nil; }
if ([data isKindOfClass:[HyperloopPointer class]]) {
HyperloopPointer* pointer = (HyperloopPointer*)data;
if ([pointer structure]) {
return [NSString stringWithFormat:@"%p", [[pointer structure] pointer]];
}
if ([pointer pointer]) {
return [NSString stringWithFormat:@"%p", [pointer pointer]];
}
if ([pointer value]) {
id rObj = [[pointer value] object];
#ifdef TIMODULE
if ([rObj isKindOfClass:[HyperloopView class]]) {
id v = [[(HyperloopView*)rObj subviews] objectAtIndex:0];
return [NSString stringWithFormat:@"%p%@", v,[v class]];
}
#endif
return [NSString stringWithFormat:@"%p%@", rObj,[rObj class]];
}
if ([pointer nativeObject]) {
return [NSString stringWithFormat:@"%p%@", [pointer nativeObject],[[pointer nativeObject] class]];
}
} else if ([data isKindOfClass:[HyperloopClass class]]) {
return [NSString stringWithFormat:@"%p%@", [(HyperloopClass*)data target],[[(HyperloopClass*)data target] class]];
}
return [NSString stringWithFormat:@"%p%@", data, [data class]];
}
/**
* stores the JS object in a non-retaining dictionay, `javaScriptWrappers`, using the memory
* address (as a string) from an Objective-C object as the key
*/
static void HyperloopRegisterWrapper (id pointer, JSValueRef thisObject) {
if (pointer == nil || thisObject == NULL) {
return;
}
if (javaScriptWrappers == NULL) {
javaScriptWrappers = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, NULL);
CFRetain(javaScriptWrappers);
}
CFStringRef pointerString = (__bridge CFStringRef)HyperloopGetMemoryAddressOfId(pointer);
if (CFDictionaryContainsKey(javaScriptWrappers, pointerString)) {
// NSLog(@"[HYPERLOOP] Wrapper replaced %@ %@",pointerString, [pointer class]);
CFDictionaryReplaceValue(javaScriptWrappers, javaScriptWrappers, thisObject);
} else {
// NSLog(@"[HYPERLOOP] Wrapper registered %@ %@", pointerString, [pointer class]);
CFDictionaryAddValue(javaScriptWrappers, pointerString, thisObject);
}
}
/**
* gets the js object stored in the `javaScriptWrappers` dictionary using the memory
* address (as a string) from an Objective-C object as the key. Returns NULL if not found
*/
JSObjectRef HyperloopGetWrapperForId (id obj) {
if (javaScriptWrappers == NULL || obj == nil) { return NULL; }
CFStringRef key = (__bridge CFStringRef)HyperloopGetMemoryAddressOfId(obj);
JSObjectRef result = NULL;
if (CFDictionaryContainsKey(javaScriptWrappers, key)) {
result = (JSObjectRef)CFDictionaryGetValue(javaScriptWrappers, key);
}
return result;
}
/**
* replacement function for creating JS Objects. It looks for a wrapper in the `javaScriptWrappers` and
* returns it if found, otherwise calls `JSObjectMake`
*/
static JSObjectRef HLObjectMake (JSContextRef ctx, JSClassRef cls, id obj) {
JSObjectRef jsObject = HyperloopGetWrapperForId(obj);
if (jsObject != nil) {
#ifdef TIMODULE
if ([[obj nativeObject] isKindOfClass:[HyperloopView class]]) {
// Special case. If this is a UIView attached to a Titanium view, then grab the Titnaium view that owns it
JSStringRef prop = JSStringCreateWithUTF8CString("$native");
if (JSObjectHasProperty(ctx, jsObject, prop)) {
JSObjectSetProperty(ctx, jsObject, prop, JSObjectMake(ctx, pointerClassRef, (__bridge void *)(obj)), kJSPropertyAttributeNone, NULL);
}
JSStringRelease(prop);
}
#endif
// NSLog(@"[HYPERLOOP] Recycling object %@", [obj class]);
return jsObject;
}
return JSObjectMake(ctx, cls, (__bridge void *)(obj));
}
/**
* return a registered callback for a given identifier
*/
KrollCallback* HyperloopGetCallbackForIdentifier (NSString *identifier) {
return [callbacks objectForKey:identifier];
}
/**
* register a callback for a given identifier
*/
void HyperloopRegisterCallbackForIdentifier (KrollCallback *callback, NSString *identifier) {
if (callbacks == nil) {
callbacks = [NSMutableDictionary dictionary];
ARCRetain(callbacks);
}
[callbacks setValue:callback forKey:identifier];
}
/**
* convert a JSStringRef into a NSString *
*/
static NSString* NSStringFromJSStringRef (JSContextRef ctx, JSStringRef string, JSValueRef *exception) {
CFStringRef str = JSStringCopyCFString(NULL, string);
NSString* nsstring = [NSString stringWithString: (__bridge NSString *)str];
CFRelease(str);
return nsstring;
}
/**
* convert a JSValueRef into a NSString *
*/
static NSString* NSStringFromJSValueRef (JSContextRef ctx, JSValueRef value, JSValueRef *exception) {
JSStringRef string = JSValueToStringCopy(ctx, value, exception);
return NSStringFromJSStringRef(ctx, string, exception);
}
/**
* generate a unique and consistent identifier for a given class name, method name and instance type
*/
#ifdef TIMODULE
static
#endif
NSString* GenerateIdentifier (NSString *className, NSString *methodName, BOOL instance) {
NSError *error = nil;
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"[\\s\\^\\(\\)\\\\<\\\\>\\*\\:\\+,]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *safeName = [re stringByReplacingMatchesInString:methodName options:0 range:NSMakeRange(0,[methodName length]) withTemplate:@"_"];
return [NSString stringWithFormat:@"%@_%@_%s", className, safeName, instance ? "1" : "0"];
}
/**
* returns true if JSObjectRef is a JS RegExp instance
*/
BOOL isJSRegExp (JSContextRef ctx, JSObjectRef obj, JSValueRef *exception) {
JSStringRef script = JSStringCreateWithUTF8CString("RegExp");
JSObjectRef global = JSContextGetGlobalObject(ctx);
JSValueRef classRef = JSObjectGetProperty(ctx, global, script, exception);
JSObjectRef classObj = JSValueToObject(ctx, classRef, exception);
JSStringRelease(script);
return JSValueIsInstanceOfConstructor(ctx, obj, classObj, exception);
}
/**
* returns the property for the JSObjectRef as a boolean or false if not found
*/
static BOOL TiPropToBool (JSContextRef ctx, JSObjectRef obj, const char *prop, JSValueRef *exception) {
JSStringRef propString = JSStringCreateWithUTF8CString(prop);
JSValueRef value = JSObjectGetProperty(ctx, obj, propString, exception);
JSStringRelease(propString);
if (JSValueIsBoolean(ctx, value)) {
return JSValueToBoolean(ctx, value);
}
return false;
}
/**
* returns an NSError as a JS Error object
*/
static JSValueRef NSErrorToJSException (JSContextRef ctx, NSError *exception) {
JSStringRef message = JSStringCreateWithUTF8CString([[exception localizedDescription] UTF8String]);
JSValueRef args[1];
args[0] = JSValueMakeString(ctx, message);
JSObjectRef result = JSObjectMakeError(ctx, 1, args, NULL);
JSValueRef messageRef = JSValueMakeString(ctx, message);
JSStringRef prop = JSStringCreateWithUTF8CString("description");
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
prop = JSStringCreateWithUTF8CString("name");
message = JSStringCreateWithUTF8CString([[exception domain] UTF8String]);
messageRef = JSValueMakeString(ctx, message);
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
NSArray *array = [NSThread callStackSymbols];
array = [array subarrayWithRange:NSMakeRange(1, [array count] - 1)];
NSString *stack = [array componentsJoinedByString:@"\n"];
message = JSStringCreateWithUTF8CString([stack UTF8String]);
prop = JSStringCreateWithUTF8CString("nativeStack");
messageRef = JSValueMakeString(ctx, message);
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
return result;
}
/**
* returns an NSException as a JS Error object
*/
static JSValueRef NSExceptionToJSException (JSContextRef ctx, NSException *exception) {
JSStringRef message = JSStringCreateWithUTF8CString([[exception reason] UTF8String]);
JSValueRef args[1];
args[0] = JSValueMakeString(ctx, message);
JSObjectRef result = JSObjectMakeError(ctx, 1, args, NULL);
JSValueRef messageRef = JSValueMakeString(ctx, message);
JSStringRef prop = JSStringCreateWithUTF8CString("description");
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
prop = JSStringCreateWithUTF8CString("name");
message = JSStringCreateWithUTF8CString([[exception name] UTF8String]);
messageRef = JSValueMakeString(ctx, message);
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
NSArray *array = [exception callStackSymbols];
array = [array subarrayWithRange:NSMakeRange(1, [array count] - 1)];
NSString *stack = [array componentsJoinedByString:@"\n"];
message = JSStringCreateWithUTF8CString([stack UTF8String]);
prop = JSStringCreateWithUTF8CString("nativeStack");
messageRef = JSValueMakeString(ctx, message);
JSObjectSetProperty(ctx, result, prop, messageRef, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(message);
JSStringRelease(prop);
return result;
}
/**
* attempt to get a class wrapper
*/
static JSObjectRef CreateJSClassFromModulePath (NSString *path, id obj, JSClassRef classRef, BOOL newInstance) {
JSContextRef ctx = context.context;
if (modules == nil) {
modules = [NSMutableDictionary dictionary];
ARCRetain(modules);
}
KrollWrapper *wrapper = nil;
if (modules && [modules objectForKey:path]) {
wrapper = [modules objectForKey:path];
}
if (!wrapper) {
wrapper = [bridge require:context path:path];
if (wrapper) {
// we cache so that titanium doesn't attempt to reload on subsequent constructors
[modules setValue:wrapper forKey:path];
}
}
if (wrapper) {
JSObjectRef function = [wrapper jsobject];
JSObjectRef ref = HLObjectMake(ctx, pointerClassRef, obj);
if (newInstance) {
JSValueRef args [] = {ref};
return JSObjectCallAsConstructor(ctx, function, 1, args, NULL);
} else {
// we need to store our pointer since this is a KrollWrapper and it's native pointer
// will be a KrollContext but we want to get back to our class
JSStringRef prop = JSStringCreateWithUTF8CString("$native");
if (!JSObjectHasProperty(ctx, function, prop)) {
JSObjectSetProperty(ctx, function, prop, ref, kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, 0);
}
JSStringRelease(prop);
return function;
}
} else {
return HLObjectMake(ctx, classRef, obj);
}
}
/**
* create a JS wrapper class for a given framework / class. the pointer should be obj
* returns a generic wrapper if not found
*/
static JSObjectRef CreateJSClassFromNSClass (NSString *framework, NSString *clsname, id obj, JSClassRef classRef) {
NSString *path = [NSString stringWithFormat:@"/hyperloop/%@/%@", [framework lowercaseString], [clsname lowercaseString]];
return CreateJSClassFromModulePath(path, obj, classRef, YES);
}
/**
* for a given object, return a JSValueRef
*/
JSValueRef NSObjectToJSObject (id object) {
JSObjectRef thisObject = HyperloopGetWrapperForId(object);
if (thisObject != nil) return thisObject;
if (!object || [object isEqual:[NSNull null]]) {
return JSValueMakeNull(context.context);
} else if ([object isKindOfClass:[NSNumber class]]) {
return JSValueMakeNumber(context.context, [object doubleValue]);
} else if ([object isKindOfClass:[HyperloopPointer class]]) {
HyperloopPointer *pointer = (HyperloopPointer *)object;
if (pointer.framework && pointer.classname) {
// if this pointer has a framework and classname reference, we can return the JS wrapped class instance
return CreateJSClassFromNSClass(pointer.framework, pointer.classname, object, pointerClassRef);
}
return HLObjectMake(context.context, pointerClassRef, object);
} else if ([object isKindOfClass:[HyperloopClass class]]) {
return HLObjectMake(context.context, classClassRef, object);
} else {
return HLObjectMake(context.context, constructorClassRef, object);
}
return JSValueMakeUndefined(context.context);
}
/**
* return the current JSContextRef
*/
JSContextRef HyperloopCurrentContext () {
return context.context;
}
#define CHECKEXCEPTION \
if (exception && *exception != NULL) {\
id ex = JSValueRefToId(ctx, *exception, NULL);\
NSLog(@"[ERROR] JS Exception detected %@", ex);\
return JSValueMakeUndefined(ctx); \
}\
#define CHECKEXCEPTION_NSNULL \
if (exception && *exception != NULL) {\
id ex = JSValueRefToId(ctx, *exception, NULL);\
NSLog(@"[ERROR] JS Exception detected %@", ex);\
return [NSNull null];\
}\
#define BEGIN_METHOD \
@autoreleasepool {\
@try {\
#define END_METHOD \
} @catch (NSException *ex) {\
NSLog(@"[ERROR] %@", ex); \
*exception = NSExceptionToJSException(ctx, ex);\
return JSValueMakeUndefined(ctx); \
}\
}
#define JS_CALLBACK(name) \
static JSValueRef name (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {\
BEGIN_METHOD \
#define JS_CALLBACK_END \
END_METHOD \
}\
/**
* convert a JSValueRef to an NSObject
*/
id JSValueRefToId (JSContextRef ctx, const JSValueRef value, JSValueRef *exception) {
switch (JSValueGetType(ctx, value)) {
case kJSTypeUndefined:
case kJSTypeNull: {
return [NSNull null];
}
case kJSTypeBoolean: {
return [NSNumber numberWithBool:JSValueToBoolean(ctx, value)];
}
case kJSTypeNumber: {
return [NSNumber numberWithDouble:JSValueToNumber(ctx, value, exception)];
}
case kJSTypeString: {
return NSStringFromJSValueRef(ctx, value, exception);
}
case kJSTypeObject: {
JSObjectRef obj = JSValueToObject(ctx, value, exception);
CHECKEXCEPTION_NSNULL
if (JSValueIsObjectOfClass(ctx, value, pointerClassRef) ||
JSValueIsObjectOfClass(ctx, value, classClassRef) ||
JSValueIsObjectOfClass(ctx, value, constructorClassRef)) {
return (__bridge id)JSObjectGetPrivate(obj);
} else if (HLValueIsDate(ctx, value)) {
double ms = JSValueToNumber(ctx, value, exception);
CHECKEXCEPTION_NSNULL
return [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval) (ms / 1000)];
} else if (JSObjectIsFunction(ctx, obj)) {
if (context == nil) {
@throw [NSException exceptionWithName:@"InvalidArgument" reason:@"argument passed was not a valid Hyperloop object" userInfo:nil];
}
return [KrollObject toID:context value:value];
} else if (HLValueIsArray(ctx, obj)) {
JSStringRef prop = JSStringCreateWithUTF8CString("length");
JSValueRef lengthValue = JSObjectGetProperty(ctx, obj, prop, exception);
CHECKEXCEPTION_NSNULL
double len = JSValueToNumber(ctx, lengthValue, exception);
CHECKEXCEPTION_NSNULL
NSMutableArray *result = [NSMutableArray arrayWithCapacity:len];
for (unsigned c = 0; c < len; c++) {
JSValueRef val = JSObjectGetPropertyAtIndex(ctx, obj, c, exception);
CHECKEXCEPTION_NSNULL
id value = JSValueRefToId(ctx, val, exception);
[result addObject:value];
}
JSStringRelease(prop);
return result;
} else if (isJSRegExp(ctx, obj, exception)) {
NSRegularExpressionOptions options = 0;
NSError *error = nil;
JSStringRef source = JSStringCreateWithUTF8CString("source");
JSValueRef sourceValue = JSObjectGetProperty(ctx, obj, source, exception);
CHECKEXCEPTION_NSNULL
if (TiPropToBool(ctx, obj, "multiline", exception)) {
options |= NSRegularExpressionAnchorsMatchLines;
}
if (TiPropToBool(ctx, obj, "ignoreCase", exception)) {
options |= NSRegularExpressionCaseInsensitive;
}
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:JSValueRefToId(ctx, sourceValue, exception) options:options error:&error];
JSStringRelease(source);
if (error) {
if (exception) {
*exception = NSErrorToJSException(ctx, error);
}
return [NSNull null];
}
return re;
} else {
// check to see if it's a KrollObject where we're receiving a Ti object
// passed to Hyperloop
void *p = JSObjectGetPrivate(obj);
if (p) {
id po = (__bridge id)p;
if ([po isKindOfClass:[KrollObject class]]) {
// check to see if this is a view proxy in which case we want to
// wrap to the UIView itself and return it
id target = [po performSelector:@selector(target)];
if ([target isKindOfClass:[TiViewProxy class]]) {
return [target performSelector:@selector(view)];
}
return target;
}
return po;
}
JSStringRef prop = JSStringCreateWithUTF8CString("$native");
if (JSObjectHasProperty(ctx, obj, prop)) {
JSValueRef nativeRef = JSObjectGetProperty(ctx, obj, prop, exception);
CHECKEXCEPTION_NSNULL
id nativeObj = JSValueRefToId(ctx, nativeRef, exception);
CHECKEXCEPTION_NSNULL
JSStringRelease(prop);
return nativeObj;
}
JSStringRelease(prop);
NSMutableDictionary *result = [NSMutableDictionary dictionary];
JSPropertyNameArrayRef props = JSObjectCopyPropertyNames(ctx, obj);
size_t len = JSPropertyNameArrayGetCount(props);
for (unsigned c = 0; c < len; c++) {
JSStringRef name = JSPropertyNameArrayGetNameAtIndex(props, c);
JSValueRef val = JSObjectGetProperty(ctx, obj, name, exception);
id value = JSValueRefToId(ctx, val, exception);
[result setObject:value forKey:NSStringFromJSStringRef(ctx, name, exception)];
}
// if it looks like an exception, add the message to the output
// FIXME: test for constructor instead
if ([result objectForKey:@"line"] && [result objectForKey:@"column"]) {
JSStringRef prop = JSStringCreateWithUTF8CString("message");
JSValueRef val = JSObjectGetProperty(ctx, obj, prop, exception);
id value = JSValueRefToId(ctx, val, exception);
[result setObject:value forKey:NSStringFromJSStringRef(ctx, prop, exception)];
JSStringRelease(prop);
prop = JSStringCreateWithUTF8CString("stack");
val = JSObjectGetProperty(ctx, obj, prop, exception);
value = JSValueRefToId(ctx, val, exception);
[result setObject:value forKey:NSStringFromJSStringRef(ctx, prop, exception)];
JSStringRelease(prop);
}
JSPropertyNameArrayRelease(props);
return result;
}
}
}
return [NSNull null];
}
/**
* called when a new JS instance is created to retain the native object
*/
static void Initializer (JSContextRef ctx, JSObjectRef object) {
id obj = (__bridge id)JSObjectGetPrivate(object);
if (obj) {
ARCRetain(obj);
#ifdef DEBUG_INITIALIZE
NSLog(@"[HYPERLOOP] Initalizer %@ (%p)", [obj class], obj);
#endif
}
}
/**
* called when a new JS instance is garbage collected, need to release the native object
*/
static void Finalizer (JSObjectRef object) {
id obj = (__bridge id)JSObjectGetPrivate(object);
if (!obj) return;
#ifdef DEBUG_FINALIZE
if ([obj isKindOfClass:[HyperloopClass class]]) {
NSLog(@"[HYPERLOOP] Finalizer %@ %p", [[(HyperloopClass*)obj target] class], [(HyperloopClass*)obj target]);
} else if ([obj isKindOfClass:[HyperloopPointer class]]) {
HyperloopPointer* p = (HyperloopPointer*)obj;
if ([p objectValue]) {
NSLog(@"[HYPERLOOP] Finalizer %@ %p", [[p objectValue] class], [p objectValue]);
}
} else if ([obj isKindOfClass:[KrollObject class]]) {
NSLog(@"[HYPERLOOP] Finalizer %@ %p", [[obj target] class], [obj target]);
}
#endif
if (javaScriptWrappers != NULL) {
CFStringRef key = (__bridge CFStringRef)HyperloopGetMemoryAddressOfId(obj);
if (CFDictionaryContainsKey(javaScriptWrappers, key)) {
CFDictionaryRemoveValue(javaScriptWrappers, key);
}
}
ARCRelease(obj);
}
/**
* called when a new JS wrapper is constructed
*/
static JSObjectRef Constructor (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) {
id obj;
if (argumentCount) {
obj = JSValueRefToId(ctx, arguments[0], exception);
} else {
HyperloopClass *cls = (__bridge HyperloopClass *)JSObjectGetPrivate(constructor);
Class customClass = (Class)[cls target];
obj = [[customClass alloc] init];
if (cls.customClass) {
return CreateJSClassFromNSClass(@"hyperloop", NSStringFromClass(cls.customClass), obj, constructorClassRef);
}
}
return HLObjectMake(ctx, constructorClassRef, obj);
}
#define CHECKVAL(var) \
if (var == nil) { \
NSString *message = [NSString stringWithFormat:@"property %s is required", STR(var)];\
@throw [NSException exceptionWithName:@"InvalidArgument" reason:message userInfo:nil];\
}\
/**
* forces a garbage collection, this is called from JavaScript, `Hyperloop.garbageCollect()`
*/
#if TARGET_OS_SIMULATOR
JS_CALLBACK(GarbageCollect)
NSLog(@"[HYPERLOOP] 🚚\tGarbage Collection");
JSSynchronousGarbageCollectForDebugging(ctx);
return JSValueMakeUndefined(ctx);
JS_CALLBACK_END
#endif
JS_CALLBACK(GetWrapper)
JSObjectRef thisObject = JSValueToObject(ctx, arguments[0], exception);
CHECKEXCEPTION
id nativePointer = (__bridge id)(JSObjectGetPrivate(thisObject));
if (nativePointer == nil) {
return JSValueMakeUndefined(ctx);
}
JSValueRef result = HyperloopGetWrapperForId(nativePointer);
if (result == NULL) {
return JSValueMakeUndefined(ctx);
}
// if ([nativePointer isKindOfClass:[HyperloopClass class]] || [nativePointer isKindOfClass:[KrollObject class]]) {
// NSLog(@"[HYPERLOOP] GetWrapper %@ %p", [[nativePointer target] class], [nativePointer target]);
// }
return result;
JS_CALLBACK_END
/**
* stores the javascript wrapper inside the `javaScriptWrappers` dictionary.
*/
/**
* if (ti_proxy) {
* wrapper.$native.__TI.__$internal__ = wrapper
* } else {
* wrapper.$native.__$internal__ = wrapper
* }
*/
JS_CALLBACK(RegisterWrapper)
JSObjectRef thisObject = JSValueToObject(ctx, arguments[0], exception);
CHECKEXCEPTION
id nativePointer = nil;
{
JSStringRef str;
JSObjectRef jsObject;
{
str = JSStringCreateWithUTF8CString("$native");
JSValueRef value = JSObjectGetProperty(ctx, thisObject, str, exception);
JSStringRelease(str);
CHECKEXCEPTION
jsObject = JSValueToObject(ctx, value, exception);
CHECKEXCEPTION;
}
nativePointer = (__bridge id)(JSObjectGetPrivate(jsObject));
{
str = JSStringCreateWithUTF8CString("__wrapper__");
if ([nativePointer isKindOfClass:[KrollObject class]]) {
jsObject = [(KrollObject*)nativePointer propsObject];
}
JSObjectSetProperty(ctx, jsObject, str, thisObject, kJSPropertyAttributeDontDelete, exception);
JSStringRelease(str);
CHECKEXCEPTION;
}
// if ([nativePointer isKindOfClass:[HyperloopClass class]] || [nativePointer isKindOfClass:[KrollObject class]]) {
// NSLog(@"[HYPERLOOP] RegisterWrapper %@ %p", [[nativePointer target] class], [nativePointer target]);
// }
}
HyperloopRegisterWrapper(nativePointer, thisObject);
return JSValueMakeUndefined(ctx);
JS_CALLBACK_END
/**
* create a new Class proxy
*/
JS_CALLBACK(NewProxy)
NSDictionary *properties = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
NSString *cls = [properties valueForKey:@"class"];
NSString *init = [properties valueForKey:@"init"];
NSNumber *alloc = [properties valueForKey:@"alloc"];
CHECKVAL(cls);
CHECKVAL(init)
CHECKVAL(alloc)
NSArray *args = [properties valueForKey:@"args"];
if ([args isEqual:[NSNull null]]) {
args = nil;
}
HyperloopClass *newClass = [[HyperloopClass alloc] initWithClassName:cls alloc: [alloc boolValue] init:NSSelectorFromString(init) args:args];
// if ([alloc boolValue]) {
// NSLog(@"[HYPERLOOP] NewProxy %@ %p", [[(HyperloopClass*)newClass target] class], [(HyperloopClass*)newClass target]);
// } else {
// NSLog(@"[HYPERLOOP] NewProxy [%@ class] %p", [[(HyperloopClass*)newClass target] class], [(HyperloopClass*)newClass target]);
// }
return HLObjectMake(ctx, classClassRef, newClass);
JS_CALLBACK_END
/**
* create a new Pointer
*/
JS_CALLBACK(CreatePointer)
NSString *encoding = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
HyperloopPointer *pointer = [HyperloopPointer encoding:[encoding UTF8String]];
if (argumentCount == 3) {
NSString *framework = JSValueRefToId(ctx, arguments[1], exception);
CHECKEXCEPTION
NSString *classname = JSValueRefToId(ctx, arguments[2], exception);
CHECKEXCEPTION
return CreateJSClassFromNSClass(framework, classname, pointer, pointerClassRef);
}
return HLObjectMake(ctx, pointerClassRef, pointer);
JS_CALLBACK_END
/**
* dispatch a method / property call
*/
JS_CALLBACK(Dispatch)
if (argumentCount < 2) {
@throw [NSException exceptionWithName:@"InvalidArgument" reason:@"you must pass at least 2 arguments to dispatch" userInfo:nil];
}
NSString *selector = NSStringFromJSValueRef(ctx, arguments[1], exception);
CHECKEXCEPTION
id args = argumentCount > 2 ? JSValueRefToId(ctx, arguments[2], exception) : nil;
CHECKEXCEPTION
id target = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
if ([args isEqual:[NSNull null]]) {
args = nil;
}
// dispatch can take just one argument, in which case, we need to turn it into an array of 1
if (args && [args isKindOfClass:[NSArray class]] == NO) {
args = @[args];
}
BOOL isInstance = argumentCount > 3 ? JSValueToBoolean(ctx, arguments[3]) : YES;
id result = [HyperloopUtils invokeSelector:NSSelectorFromString(selector) args:args target:target instance:isInstance];
if (result == nil || [result isEqual:[NSNull null]]) {
return JSValueMakeNull(ctx);
}
// NSLog(@"[DEBUG] dispatch %@ %@", target, selector);
if ([result isKindOfClass:[HyperloopPointer class]]) {
#ifdef TIMODULE
id obj = [(HyperloopPointer *)result objectValue];
// we need to return the container if we're trying to get the UIView contained by the Hyperloop View
if (obj && [obj isKindOfClass:[UIView class]] && [[(UIView *)obj superview] isKindOfClass:[HyperloopView class]]) {
obj = [obj superview];
result = [HyperloopPointer pointer:(__bridge void *)(obj) encoding:@encode(id)];
}
#endif
return HLObjectMake(ctx, pointerClassRef, result);
} else if ([result isKindOfClass:[NSNumber class]]) {
return JSValueMakeNumber(ctx, [result doubleValue]);
}
return JSValueMakeUndefined(ctx);
JS_CALLBACK_END
/**
* define a custom class
*/
JS_CALLBACK(DefineClass)
if (argumentCount < 1) {
@throw [NSException exceptionWithName:@"InvalidArgument" reason:@"you must pass at least 1 arguments to DefineClass" userInfo:nil];
}
// no-op since the bulk of the work is done at compile time
NSString *name = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
HyperloopClass *cls = [[HyperloopClass alloc] initWithClassName:name alloc:NO init:@selector(class) args:nil];
cls.customClass = NSClassFromString(name);
Class classMapping = NSClassFromString(@"HyperloopCustomClassMapping");
if (classMapping) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
NSString *modulePath = [classMapping performSelector:@selector(mappingForClass:) withObject:name];
#pragma clang diagnostic pop
return CreateJSClassFromModulePath(modulePath, cls, classClassRef, NO);
}
return HLObjectMake(ctx, classClassRef, cls);
JS_CALLBACK_END
/**
* dynamically add a method to a class
*/
JS_CALLBACK(AddMethod)
id targetClass = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
NSDictionary *props = JSValueRefToId(ctx, arguments[1], exception);
CHECKEXCEPTION
BOOL isInstance = [props objectForKey:@"instance"] ? [HyperloopUtils booleanify:[props objectForKey:@"instance"]] : YES;
HyperloopClass *cls = (HyperloopClass *)targetClass;
NSString *classname = NSStringFromClass([[cls target] class]);
NSString *selector = [props objectForKey:@"selector"];
KrollCallback *callback = [props objectForKey:@"callback"];
// generate the identifier
NSString *identifier = GenerateIdentifier(classname, selector, isInstance);
// register only once if not already registered
if (!callbacks || [callbacks objectForKey:identifier] == nil) {
HyperloopRegisterCallbackForIdentifier(callback, identifier);
}
return JSValueMakeNull(ctx);
JS_CALLBACK_END
/**
* return true if object is of type [NSNull class]
*/
JS_CALLBACK(IsNull)
id target = JSValueRefToId(ctx, arguments[0], exception);
CHECKEXCEPTION
if (!target || [target isEqual:[NSNull null]]) {
return JSValueMakeBoolean(ctx, YES);
}
return JSValueMakeBoolean(ctx, NO);
JS_CALLBACK_END
/**
* protect the passed in JS value from garbage collection
*/
JS_CALLBACK(Protect)
JSValueProtect(ctx, arguments[0]);
return JSValueMakeBoolean(ctx, YES);
JS_CALLBACK_END
/**
* unprotect the passed in JS value so that it can be garbage collected
*/
JS_CALLBACK(Unprotect)
JSValueUnprotect(ctx, arguments[0]);
return JSValueMakeBoolean(ctx, YES);
JS_CALLBACK_END
/**
* logger utility which will correctly handle serialization of JS / native objects
*/
JS_CALLBACK(Logger)
NSMutableArray *array = [NSMutableArray arrayWithCapacity:argumentCount];
for (size_t c = 0; c < argumentCount; c++) {
JSStringRef s = JSValueToStringCopy(ctx, arguments[c], exception);
CHECKEXCEPTION
NSString *str = NSStringFromJSStringRef(ctx, s, exception);
CHECKEXCEPTION
[array addObject:str];
}
NSLog(@"[INFO] %@", [array componentsJoinedByString:@" "]);
return JSValueMakeNull(ctx);
JS_CALLBACK_END
/**
* coerce is JS value from one type to another
*/
static JSValueRef Convert (JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception) {
id ref = (__bridge id)(JSObjectGetPrivate(object));
switch (type) {
case kJSTypeUndefined: {
return JSValueMakeUndefined(ctx);
}
case kJSTypeNull: {
return JSValueMakeNull(ctx);
}
case kJSTypeBoolean: {
if ([ref respondsToSelector:@selector(boolValue)]) {
return JSValueMakeBoolean(ctx, [ref boolValue]);
}
return JSValueMakeBoolean(ctx, false);
}
case kJSTypeNumber: {
if ([ref respondsToSelector:@selector(doubleValue)]) {
return JSValueMakeNumber(ctx, [ref doubleValue]);
}
return JSValueMakeNumber(ctx, NAN);
}
case kJSTypeString: {
JSStringRef str = JSStringCreateWithUTF8CString([[ref description] UTF8String]);
JSValueRef result = JSValueMakeString(ctx, str);
JSStringRelease(str);
return result;
}
case kJSTypeObject: {
return object;
}
}
return JSValueMakeUndefined(ctx);
}
/**
* stringify a JS object
*/
static JSValueRef String (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {
@autoreleasepool {
if (JSValueIsObject(ctx, arguments[0])) {
JSObjectRef obj = JSValueToObject(ctx, arguments[0], exception);
CHECKEXCEPTION
id target = (__bridge id)(JSObjectGetPrivate(obj));
if (target) {
JSStringRef str = JSStringCreateWithUTF8CString([[target description] UTF8String]);
JSValueRef result = JSValueMakeString(ctx, str);
JSStringRelease(str);
return result;
}
return Convert(ctx, obj, kJSTypeString, exception);
} else if (JSValueIsString(ctx, arguments[0])) {
return arguments[0];
} else if (JSValueIsBoolean(ctx, arguments[0])) {
if (JSValueToBoolean(ctx, arguments[0])) {
JSStringRef str = JSStringCreateWithUTF8CString("true");
JSValueRef result = JSValueMakeString(ctx, str);
JSStringRelease(str);
return result;
} else {
JSStringRef str = JSStringCreateWithUTF8CString("false");
JSValueRef result = JSValueMakeString(ctx, str);
JSStringRelease(str);
return result;
}
} else if (JSValueIsNumber(ctx, arguments[0])) {
double n = JSValueToNumber(ctx, arguments[0], exception);
CHECKEXCEPTION
NSNumber *num = [NSNumber numberWithDouble:n];
JSStringRef str = JSStringCreateWithUTF8CString([[num stringValue] UTF8String]);
JSValueRef result = JSValueMakeString(ctx, str);
JSStringRelease(str);
return result;
} else {
return JSValueMakeNull(ctx);
}
}
}
#define GETNUMVALUE(type, name, fn, def) \
JS_CALLBACK(name)\
if (JSValueIsObject(ctx, arguments[0])) {\
JSObjectRef obj = JSValueToObject(ctx, arguments[0], exception);\
CHECKEXCEPTION\
id target = (__bridge id)JSObjectGetPrivate(obj);\
NSNumber *result = [NSNumber numberWith##name:[HyperloopPointer type##Value:target]];\
return fn(ctx, [result type##Value]); \
} else if (JSValueIsBoolean(ctx, arguments[0])) {\
return fn(ctx, JSValueToBoolean(ctx, arguments[0]));\
} else if (JSValueIsNumber(ctx, arguments[0])) { \
return fn(ctx, JSValueToNumber(ctx, arguments[0], exception));\
}\
return JSValueMakeBoolean(ctx, def);\
JS_CALLBACK_END
GETNUMVALUE(bool, Bool, JSValueMakeBoolean, false);
GETNUMVALUE(float, Float, JSValueMakeNumber, NAN);
GETNUMVALUE(int, Int, JSValueMakeNumber, NAN);
GETNUMVALUE(short, Short, JSValueMakeNumber, NAN);
GETNUMVALUE(double, Double, JSValueMakeNumber, NAN);
GETNUMVALUE(long, Long, JSValueMakeNumber, NAN);
GETNUMVALUE(longLong, LongLong, JSValueMakeNumber, NAN);
GETNUMVALUE(char, Char, JSValueMakeNumber, NAN);
GETNUMVALUE(unsignedInt, UnsignedInt, JSValueMakeNumber, NAN);
GETNUMVALUE(unsignedLong, UnsignedLong, JSValueMakeNumber, NAN);
GETNUMVALUE(unsignedLongLong, UnsignedLongLong, JSValueMakeNumber, NAN);
GETNUMVALUE(unsignedShort, UnsignedShort, JSValueMakeNumber, NAN);
GETNUMVALUE(unsignedChar, UnsignedChar, JSValueMakeNumber, NAN);
// directly from titanium_prep