-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
KrollBridge.m
1337 lines (1163 loc) Β· 39.8 KB
/
KrollBridge.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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#import "TiToJS.h"
#import "KrollBridge.h"
#import "KrollCallback.h"
#import "KrollObject.h"
#import "TiHost.h"
#import "TopTiModule.h"
#import "TiUtils.h"
#import "TiApp.h"
#import "ApplicationMods.h"
#import <libkern/OSAtomic.h>
#import "KrollContext.h"
#import "TiConsole.h"
#import "TiExceptionHandler.h"
#import "APSAnalytics.h"
#ifdef KROLL_COVERAGE
# include "KrollCoverage.h"
#endif
#ifndef USE_JSCORE_FRAMEWORK
#import "TiDebugger.h"
#endif
extern BOOL const TI_APPLICATION_ANALYTICS;
extern NSString * const TI_APPLICATION_DEPLOYTYPE;
extern NSString * const TI_APPLICATION_GUID;
extern NSString * const TI_APPLICATION_BUILD_TYPE;
NSString * TitaniumModuleRequireFormat = @"(function(exports){"
"var __OXP=exports;var module={'exports':exports};var __dirname=\"%@\";var __filename=\"%@\";%@;\n"
"if(module.exports !== __OXP){return module.exports;}"
"return exports;})({})";
//Defined private method inside TiBindingRunLoop.m (Perhaps to move to .c?)
void TiBindingRunLoopAnnounceStart(TiBindingRunLoop runLoop);
@implementation TitaniumObject
-(NSDictionary*)modules
{
return modules;
}
-(id)initWithContext:(KrollContext*)context_ host:(TiHost*)host_ context:(id<TiEvaluator>)pageContext_ baseURL:(NSURL*)baseURL_
{
TopTiModule *module = [[[TopTiModule alloc] _initWithPageContext:pageContext_] autorelease];
[module setHost:host_];
[module _setBaseURL:baseURL_];
if (self = [super initWithTarget:module context:context_])
{
pageContext = pageContext_;
modules = [[NSMutableDictionary alloc] init];
host = [host_ retain];
[(KrollBridge *)pageContext_ registerProxy:module krollObject:self];
// pre-cache a few modules we always use
TiModule *ui = [host moduleNamed:@"UI" context:pageContext_];
[self addModule:@"UI" module:ui];
TiModule *api = [host moduleNamed:@"API" context:pageContext_];
[self addModule:@"API" module:api];
if (TI_APPLICATION_ANALYTICS)
{
APSAnalytics *sharedAnalytics = [APSAnalytics sharedInstance];
if (TI_APPLICATION_BUILD_TYPE != nil || (TI_APPLICATION_BUILD_TYPE.length > 0)) {
[sharedAnalytics performSelector:@selector(setBuildType:) withObject:TI_APPLICATION_BUILD_TYPE];
}
[sharedAnalytics performSelector:@selector(setSDKVersion:) withObject:[NSString stringWithFormat:@"ti.%@",[module performSelector:@selector(version)]]];
[sharedAnalytics enableWithAppKey:TI_APPLICATION_GUID andDeployType:TI_APPLICATION_DEPLOYTYPE];
}
}
return self;
}
#if KROLLBRIDGE_MEMORY_DEBUG==1
-(id)retain
{
NSLog(@"[MEMORY DEBUG] RETAIN: %@ (%d)",self,[self retainCount]+1);
return [super retain];
}
-(oneway void)release
{
NSLog(@"[MEMORY DEBUG] RELEASE: %@ (%d)",self,[self retainCount]-1);
[super release];
}
#endif
-(void)dealloc
{
RELEASE_TO_NIL(host);
RELEASE_TO_NIL(modules);
RELEASE_TO_NIL(dynprops);
[super dealloc];
}
-(void)gc
{
}
-(id)valueForKey:(NSString *)key
{
// allow dynprops to override built-in modules
// in case you want to re-define them
if (dynprops!=nil)
{
id result = [dynprops objectForKey:key];
if (result!=nil)
{
if (result == [NSNull null])
{
return nil;
}
return result;
}
}
id module = [modules objectForKey:key];
if (module!=nil)
{
return module;
}
module = [host moduleNamed:key context:pageContext];
if (module!=nil)
{
return [self addModule:key module:module];
}
//go against module
return [super valueForKey:key];
}
-(void)setValue:(id)value forKey:(NSString *)key
{
if (dynprops==nil)
{
dynprops = [[NSMutableDictionary dictionary] retain];
}
if (value == nil)
{
value = [NSNull null];
}
[dynprops setValue:value forKey:key];
}
- (id) valueForUndefinedKey: (NSString *) key
{
if ([key isEqualToString:@"toString"] || [key isEqualToString:@"valueOf"])
{
return [self description];
}
if (dynprops != nil)
{
return [dynprops objectForKey:key];
}
//NOTE: we need to return nil here since in JS you can ask for properties
//that don't exist and it should return undefined, not an exception
return nil;
}
-(id)addModule:(NSString*)name module:(TiModule*)module
{
// Have we received a JS Module?
if (![module respondsToSelector:@selector(unboundBridge:)])
{
[modules setObject:module forKey:name];
return module;
}
KrollObject *ko = [pageContext registerProxy:module];
if (ko == nil)
{
return nil;
}
[self noteKrollObject:ko forKey:name];
[modules setObject:ko forKey:name];
return ko;
}
-(TiModule*)moduleNamed:(NSString*)name context:(id<TiEvaluator>)context
{
return [modules objectForKey:name];
}
@end
OSSpinLock krollBridgeRegistryLock = OS_SPINLOCK_INIT;
CFMutableSetRef krollBridgeRegistry = nil;
@implementation KrollBridge
+(void)initialize
{
if (krollBridgeRegistry == nil)
{
CFSetCallBacks doNotRetain = kCFTypeSetCallBacks;
doNotRetain.retain = NULL;
doNotRetain.release = NULL;
krollBridgeRegistry = CFSetCreateMutable(NULL, 3, &doNotRetain);
}
}
@synthesize currentURL;
-(void)registerForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
-(void)unregisterForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
-(id)init
{
if (self = [super init])
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[DEBUG] INIT: %@",self);
#endif
modules = [[NSMutableDictionary alloc] init];
proxyLock = OS_SPINLOCK_INIT;
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetAddValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
TiThreadPerformOnMainThread(^{[self registerForMemoryWarning];}, NO);
}
return self;
}
-(void)didReceiveMemoryWarning:(NSNotification*)notification
{
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
[self gc];
return;
}
BOOL keepWarning = YES;
signed long proxiesCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
//During a memory panic, we may not get the chance to copy proxies.
while (keepWarning)
{
keepWarning = NO;
for (id proxy in (NSDictionary *)registeredProxies)
{
[proxy didReceiveMemoryWarning:notification];
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
break;
}
signed long newCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
if (newCount != proxiesCount)
{
proxiesCount = newCount;
keepWarning = YES;
break;
}
}
}
[self gc];
}
#if KROLLBRIDGE_MEMORY_DEBUG==1
-(id)retain
{
NSLog(@"[MEMORY DEBUG] RETAIN: %@ (%d)",self,[self retainCount]+1);
return [super retain];
}
-(oneway void)release
{
NSLog(@"[MEMORY DEBUG] RELEASE: %@ (%d)",self,[self retainCount]-1);
[super release];
}
#endif
-(void)removeProxies
{
OSSpinLockLock(&proxyLock);
CFDictionaryRef oldProxies = registeredProxies;
registeredProxies = NULL;
OSSpinLockUnlock(&proxyLock);
for (id thisProxy in (NSDictionary *)oldProxies)
{
KrollObject * thisKrollObject = (id)CFDictionaryGetValue(oldProxies, thisProxy);
[thisProxy contextShutdown:self];
[thisKrollObject unprotectJsobject];
}
if (oldProxies != NULL)
{
CFRelease(oldProxies);
}
for (NSString * thisModuleKey in modules) {
id thisModule = [modules objectForKey:thisModuleKey];
if ([thisModule respondsToSelector:@selector(unprotectJsobject)]) {
[thisModule unprotectJsobject];
}
}
RELEASE_TO_NIL(modules);
}
-(void)dealloc
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[MEMORY DEBUG] DEALLOC: %@",self);
#endif
[self removeProxies];
RELEASE_TO_NIL(preload);
RELEASE_TO_NIL(context);
RELEASE_TO_NIL(titanium);
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetRemoveValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
[super dealloc];
}
- (TiHost*)host
{
return host;
}
- (KrollContext*) krollContext
{
return context;
}
- (id)preloadForKey:(id)key name:(id)name
{
if (preload!=nil)
{
NSDictionary* dict = [preload objectForKey:name];
if (dict!=nil)
{
return [dict objectForKey:key];
}
}
return nil;
}
- (void)boot:(id)callback url:(NSURL*)url_ preload:(NSDictionary*)preload_
{
preload = [preload_ retain];
[super boot:callback url:url_ preload:preload_];
context = [[KrollContext alloc] init];
context.delegate = self;
[context start];
}
- (void)evalJSWithoutResult:(NSString*)code
{
[context evalJS:code];
}
// NOTE: this must only be called on the JS thread or an exception will be raised
- (id)evalJSAndWait:(NSString*)code
{
return [context evalJSAndWait:code];
}
-(BOOL)evaluationError
{
return evaluationError;
}
- (void)evalFileOnThread:(NSString*)path context:(KrollContext*)context_
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
TiValueRef exception = NULL;
TiContextRef jsContext = [context_ context];
NSURL *url_ = [path hasPrefix:@"file:"] ? [NSURL URLWithString:path] : [NSURL fileURLWithPath:path];
if (![path hasPrefix:@"/"] && ![path hasPrefix:@"file:"])
{
url_ = [NSURL URLWithString:path relativeToURL:url];
}
NSString *jcode = nil;
if ([url_ isFileURL])
{
NSData *data = [TiUtils loadAppResource:url_];
if (data==nil)
{
jcode = [NSString stringWithContentsOfFile:[url_ path] encoding:NSUTF8StringEncoding error:&error];
}
else
{
jcode = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
}
else
{
jcode = [NSString stringWithContentsOfURL:url_ encoding:NSUTF8StringEncoding error:&error];
}
if (error!=nil)
{
NSLog(@"[ERROR] Error loading path: %@, %@",path,error);
evaluationError = YES;
TiScriptError *scriptError = nil;
// check for file not found a give a friendlier message
if ([error code]==260 && [error domain]==NSCocoaErrorDomain) {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Could not find the file %@",[path lastPathComponent]] sourceURL:nil lineNo:0];
} else {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Error loading script %@. %@",[path lastPathComponent],[error description]] sourceURL:nil lineNo:0];
}
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:scriptError];
[scriptError release];
return;
}
const char *urlCString = [[url_ absoluteString] UTF8String];
TiStringRef jsCode = TiStringCreateWithCFString((CFStringRef) jcode);
TiStringRef jsURL = TiStringCreateWithUTF8CString(urlCString);
if (exception == NULL) {
#ifndef USE_JSCORE_FRAMEWORK
if ([[self host] debugMode]) {
TiDebuggerBeginScript(context_, urlCString);
}
#endif
TiEvalScript(jsContext, jsCode, NULL, jsURL, 1, &exception);
#ifndef USE_JSCORE_FRAMEWORK
if ([[self host] debugMode]) {
TiDebuggerEndScript(context_);
}
#endif
if (exception == NULL) {
evaluationError = NO;
} else {
evaluationError = YES;
}
}
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
evaluationError = YES;
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
}
TiStringRelease(jsCode);
TiStringRelease(jsURL);
[pool release];
}
- (void)evalFile:(NSString*)path callback:(id)callback selector:(SEL)selector
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:path callback:callback selector:selector];
}
- (void)evalFile:(NSString *)file
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:file condition:nil];
}
- (void)fireEvent:(id)listener withObject:(id)obj remove:(BOOL)yn thisObject:(TiProxy*)thisObject_
{
if (![listener isKindOfClass:[KrollCallback class]])
{
DebugLog(@"[ERROR] Listener callback is of a non-supported type: %@",[listener class]);
return;
}
KrollEvent *event = [[KrollEvent alloc] initWithCallback:listener eventObject:obj thisObject:thisObject_];
[context enqueue:event];
[event release];
}
-(void)enqueueEvent:(NSString*)type forProxy:(TiProxy *)proxy withObject:(id)obj
{
KrollObject* eventKrollObject = [self krollObjectForProxy:proxy];
KrollEvent * newEvent = [[KrollEvent alloc]
initWithType:type
ForKrollObject:eventKrollObject
eventObject:obj
thisObject:eventKrollObject];
[context enqueue:newEvent];
[newEvent release];
}
-(void)shutdown:(NSCondition*)condition
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[MEMORY DEBUG] DESTROY: %@",self);
#endif
if (shutdown==NO)
{
shutdownCondition = [condition retain];
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
[context stop];
}
else
{
[condition lock];
[condition signal];
[condition unlock];
}
}
-(void)gc
{
[context gc];
[titanium gc];
}
#pragma mark Delegate
-(void)willStartNewContext:(KrollContext*)kroll
{
#ifdef HYPERLOOP
// Start Hyperloop engine if present
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(willStartNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[self retain]; // Hold onto ourselves as long as the context needs us
}
-(void)didStartNewContext:(KrollContext*)kroll
{
// create Titanium global object
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Load the "Titanium" object into the global scope
NSString *basePath = (url==nil) ? [TiHost resourcePath] : [[[url path] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"."];
titanium = [[TitaniumObject alloc] initWithContext:kroll host:host context:self baseURL:[NSURL fileURLWithPath:basePath]];
TiContextRef jsContext = [kroll context];
TiValueRef tiRef = [KrollObject toValue:kroll value:titanium];
NSString *titaniumNS = [NSString stringWithFormat:@"T%sanium","it"];
TiStringRef prop = TiStringCreateWithCFString((CFStringRef) titaniumNS);
TiStringRef prop2 = TiStringCreateWithCFString((CFStringRef) [NSString stringWithFormat:@"%si","T"]);
TiObjectRef globalRef = TiContextGetGlobalObject(jsContext);
TiObjectSetProperty(jsContext, globalRef, prop, tiRef,
kTiPropertyAttributeDontDelete | kTiPropertyAttributeDontEnum,
NULL);
TiObjectSetProperty(jsContext, globalRef, prop2, tiRef,
kTiPropertyAttributeDontDelete | kTiPropertyAttributeDontEnum,
NULL);
TiStringRelease(prop);
TiStringRelease(prop2);
// Load the "console" object into the global scope
console = [[KrollObject alloc] initWithTarget:[[[TiConsole alloc] _initWithPageContext:self] autorelease] context:kroll];
prop = TiStringCreateWithCFString((CFStringRef)@"console");
TiObjectSetProperty(jsContext, globalRef, prop, [KrollObject toValue:kroll value:console], kTiPropertyAttributeNone, NULL);
//if we have a preload dictionary, register those static key/values into our namespace
if (preload!=nil)
{
for (NSString *name in preload)
{
KrollObject *ti = (KrollObject*)[titanium valueForKey:name];
NSDictionary *values = [preload valueForKey:name];
for (id key in values)
{
id target = [values objectForKey:key];
KrollObject *ko = [self krollObjectForProxy:target];
if (ko==nil)
{
ko = [self registerProxy:target];
}
[ti noteKrollObject:ko forKey:key];
[ti setStaticValue:ko forKey:key purgable:NO];
}
}
//We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[url path] callback:self selector:@selector(booted)];
}
else
{
// now load the app.js file and get started
NSURL *startURL = [host startURL];
//We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[startURL absoluteString] callback:self selector:@selector(booted)];
}
#ifdef HYPERLOOP
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(didStartNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[pool release];
}
-(void)willStopNewContext:(KrollContext*)kroll
{
#ifdef HYPERLOOP
// Stop Hyperloop engine if present
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(willStopNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
if (shutdown==NO)
{
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
[titanium gc];
if (shutdownCondition)
{
[shutdownCondition lock];
[shutdownCondition signal];
[shutdownCondition unlock];
RELEASE_TO_NIL(shutdownCondition);
}
}
-(void)didStopNewContext:(KrollContext*)kroll
{
TiThreadPerformOnMainThread(^{[self unregisterForMemoryWarning];}, NO);
[self removeProxies];
RELEASE_TO_NIL(titanium);
RELEASE_TO_NIL(console);
RELEASE_TO_NIL(context);
RELEASE_TO_NIL(preload);
#ifdef HYPERLOOP
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(didStopNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[self autorelease]; // Safe to release now that the context is done
}
-(void)registerProxy:(id)proxy krollObject:(KrollObject *)ourKrollObject
{
OSSpinLockLock(&proxyLock);
if (registeredProxies==NULL)
{
registeredProxies = CFDictionaryCreateMutable(NULL, 10, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
//NOTE: Do NOT treat registeredProxies like a mutableDictionary; mutable dictionaries copy keys,
//CFMutableDictionaryRefs only retain keys, which lets them work with proxies properly.
CFDictionaryAddValue(registeredProxies, proxy, ourKrollObject);
OSSpinLockUnlock(&proxyLock);
[proxy boundBridge:self withKrollObject:ourKrollObject];
}
- (id)registerProxy:(id)proxy
{
KrollObject * ourKrollObject = [self krollObjectForProxy:proxy];
if (ourKrollObject != nil)
{
return ourKrollObject;
}
if (![context isKJSThread])
{
return nil;
}
#ifdef KROLL_COVERAGE
ourKrollObject = [[KrollCoverageObject alloc] initWithTarget:proxy context:context];
#else
ourKrollObject = [[KrollObject alloc] initWithTarget:proxy context:context];
#endif
[self registerProxy:proxy krollObject:ourKrollObject];
return [ourKrollObject autorelease];
}
- (void)unregisterProxy:(id)proxy
{
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
CFDictionaryRemoveValue(registeredProxies, proxy);
//Don't bother with removing the empty registry. It's small and leaves on dealloc anyways.
}
OSSpinLockUnlock(&proxyLock);
[proxy unboundBridge:self];
}
- (BOOL)usesProxy:(id)proxy
{
if (proxy == nil)
{
return NO;
}
BOOL result=NO;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
result = (CFDictionaryGetCountOfKey(registeredProxies, proxy) != 0);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
- (id)krollObjectForProxy:(id)proxy
{
id result=nil;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
result = (id)CFDictionaryGetValue(registeredProxies, proxy);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
-(id)loadCommonJSModule:(NSString*)code withSourceURL:(NSURL *)sourceURL
{
// This takes care of resolving paths like `../../foo.js`
sourceURL = [NSURL fileURLWithPath:[[sourceURL path] stringByStandardizingPath]];
// Get the relative path to the Resources directory
NSString *filename = [[sourceURL path] stringByReplacingOccurrencesOfString:[[[NSBundle mainBundle] resourceURL] path] withString:@""];
NSString *dirname = [filename stringByDeletingLastPathComponent];
NSString *js = [[NSString alloc] initWithFormat:TitaniumModuleRequireFormat, dirname, filename, code];
/* This most likely should be integrated with normal code flow, but to
* minimize impact until a in-depth reconsideration of KrollContext can be
* done, we should have as little footprint
*/
KrollEval *eval = [[KrollEval alloc] initWithCode:js sourceURL:sourceURL startingLineNo:1];
TiValueRef exception = NULL;
TiValueRef resultRef = [eval jsInvokeInContext:context exception:&exception];
[js release];
[eval release];
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
return nil;
}
/*
* In order to work around the underlying issue of TIMOB-2392, we must
* use KrollWrapper as a JS wrapper instead of converting it to a proxy
*/
KrollWrapper * result = [[KrollWrapper alloc] init];
[result setBridge:self];
[result setJsobject:(TiObjectRef)resultRef];
[result protectJsobject];
return [result autorelease];
}
-(NSString*)pathToModuleClassName:(NSString*)path
{
//TODO: switch to use ApplicationMods
NSArray *tokens = [path componentsSeparatedByString:@"."];
NSMutableString *modulename = [NSMutableString string];
for (NSString *token in tokens)
{
[modulename appendFormat:@"%@%@",[[token substringToIndex:1] uppercaseString],[token substringFromIndex:1]];
}
[modulename appendString:@"Module"];
return modulename;
}
- (TiModule *)loadTopLevelNativeModule:(TiModule *)module withPath:(NSString *)path withContext:(KrollContext *)kroll
{
// does it have JS? No, then nothing else to do...
if (![module isJSModule]) {
return module;
}
NSData* data = [module moduleJS];
if (data == nil) {
// Uh oh, no actual data. Let's just punt and return the native module as-is
return module;
}
NSString* contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
KrollWrapper* wrapper = (id) [self loadJavascriptText:contents fromFile:path withContext:kroll];
// For right now, we need to mix any compiled JS on top of a compiled module, so that both components
// are accessible. We store the exports object and then put references to its properties on the toplevel
// object.
TiContextRef jsContext = [[self krollContext] context];
TiObjectRef jsObject = [wrapper jsobject];
KrollObject* moduleObject = [module krollObjectForContext:[self krollContext]];
[moduleObject noteObject:jsObject forTiString:kTiStringExportsKey context:jsContext];
TiPropertyNameArrayRef properties = TiObjectCopyPropertyNames(jsContext, jsObject);
size_t count = TiPropertyNameArrayGetCount(properties);
for (size_t i=0; i < count; i++) {
// Mixin the property onto the module JS object if it's not already there
TiStringRef propertyName = TiPropertyNameArrayGetNameAtIndex(properties, i);
if (!TiObjectHasProperty(jsContext, [moduleObject jsobject], propertyName)) {
TiValueRef property = TiObjectGetProperty(jsContext, jsObject, propertyName, NULL);
TiObjectSetProperty([[self krollContext] context], [moduleObject jsobject], propertyName, property, kTiPropertyAttributeReadOnly, NULL);
}
}
TiPropertyNameArrayRelease(properties);
return module;
}
- (TiModule *)loadCoreModule:(NSString *)path withContext:(KrollContext *)kroll
{
// make sure path doesn't begin with ., .., or /
// Can't be a "core" module then
if ([path hasPrefix:@"/"] || [path hasPrefix:@"."]) {
return nil;
}
// moduleId then is the first path component
// try to load up the native module's class...
NSString *moduleID = [[path pathComponents] objectAtIndex:0];
NSString *moduleClassName = [self pathToModuleClassName:moduleID];
Class moduleClass = NSClassFromString(moduleClassName);
// If no such module exists, bail out!
if (moduleClass == nil) {
return nil;
}
// If there is a JS file that collides with the given path,
// warn the user of the collision, but prefer the native/core module
NSURL *jsPath = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@.js", [[NSURL fileURLWithPath:[TiHost resourcePath] isDirectory:YES] path], path]];
if ([[NSFileManager defaultManager] fileExistsAtPath:[jsPath absoluteString]]) {
NSLog(@"[WARN] The requested path '%@' has a collison betweeb a native Ti%@um API/module and a JS file.", path, @"tani");
NSLog(@"[WARN] The native Ti%@um API/module will be loaded in preference.", @"tani");
NSLog(@"[WARN] If you intended to address the JS file, please require the path using a prefixed string such as require('./%@') or require('/%@') instead.", path, path);
}
// Ok, we have a native module, make sure instantiate and cache it
TiModule *module = [modules objectForKey:moduleID];
if (module == nil) {
module = [[moduleClass alloc] _initWithPageContext:self];
[module setHost:host];
[module _setName:moduleClassName];
[modules setObject:module forKey:moduleID];
[module autorelease];
}
// Are they just trying to load the top-level module?
NSRange separatorLocation = [path rangeOfString:@"/"];
if (separatorLocation.location == NSNotFound) {
// Indicates toplevel module
return [self loadTopLevelNativeModule:module withPath:path withContext:kroll];
}
// check rest of path
NSString* assetPath = [path substringFromIndex: separatorLocation.location + 1];
// Treat require('module.id/module.id') == require('module.id')
if ([assetPath isEqualToString:moduleID]) {
return [self loadTopLevelNativeModule:module withPath:path withContext:kroll];
}
// not top-level module!
// Try to load the file as module asset!
NSString* filepath = [assetPath stringByAppendingString:@".js"];
NSData* data = [module loadModuleAsset:filepath];
// does it exist in module?
if (data == nil) {
// nope, return nil so we can try to fall back to resource in user's app
return nil;
}
NSString* contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// This is an asset inside the native module. Load it like a "normal" common js file
return [self loadJavascriptText:contents fromFile:filepath withContext:kroll];
}
- (NSString *)loadFile:(NSString *)path
{
NSURL *url_ = [NSURL URLWithString:path relativeToURL:[[self host] baseURL]];
NSData *data = [TiUtils loadAppResource:url_];
if (data == nil) {
data = [NSData dataWithContentsOfURL:url_];
}
if (data != nil) {
[self setCurrentURL:[NSURL URLWithString:[path stringByDeletingLastPathComponent] relativeToURL:[[self host] baseURL]]];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
return nil;
}
- (TiModule *)loadJavascriptObject:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
// FIXME Move this up the stack to where we check for file existence?
// Now that we have the full path, we can check and see if the module was loaded,
// and return it if available.
if (modules != nil) {
TiModule *module = [modules objectForKey:filename];
if (module != nil) {
return module;
}
}
// We could cheat and just do "module.exports = %data%", but that wouldn't validate that the passed in content was JSON
// and may open a security hole.
// TODO It'd be good to try and handle things more gracefully if the JSON is "bad"/malformed
// Take JSON and turn into JS program that assigns module.exports to the parsed JSON
// 1. trim leading and trailing newlines and whitespace from JSON file
data = [data stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
// 2. Escape single quotes
data = [data stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];
// 3. assign module.exports as JSON.parse call on the JSON
data = [@"module.exports = JSON.parse('" stringByAppendingString:data];
// 4. Replace newlines with "' +\n'"
data = [data stringByReplacingOccurrencesOfString:@"\n" withString:@"' +\n'"];
// 5. close the JSON string and end the JSON.parse call
data = [data stringByAppendingString:@"');"];
return [self loadJavascriptText:data fromFile:filename withContext:kroll];
}
- (TiModule *)loadJavascriptText:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
// FIXME Move this up the stack to where we check for file existence?
// Now that we have the full path, we can check and see if the module was loaded,
// and return it if available.
if (modules != nil) {
TiModule *module = [modules objectForKey:filename];
if (module != nil) {
return module;
}
}
NSURL *url_ = [TiHost resourceBasedURL:filename baseURL:NULL];
#ifndef USE_JSCORE_FRAMEWORK
const char *urlCString = [[url_ absoluteString] UTF8String];
if ([[self host] debugMode]) {
TiDebuggerBeginScript([self krollContext], urlCString);
}
#endif
KrollWrapper *wrapper = [self loadCommonJSModule:data withSourceURL:url_];
#ifndef USE_JSCORE_FRAMEWORK
if ([[self host] debugMode]) {
TiDebuggerEndScript([self krollContext]);
}
#endif
if (![wrapper respondsToSelector:@selector(replaceValue:forKey:notification:)]) {
@throw [NSException exceptionWithName:@"org.appcelerator.kroll"
reason:[NSString stringWithFormat:@"Module \"%@\" failed to leave a valid exports object", filename]
userInfo:nil];
}
// register the module if it's pure JS
TiModule *module = (id)wrapper;
// cache the module by filename