/
JSCocoaController.m
4946 lines (4232 loc) · 171 KB
/
JSCocoaController.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
//
// JSCocoa.m
// JSCocoa
//
// Created by Patrick Geiller on 09/07/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "JSCocoaController.h"
#import "JSCocoaLib.h"
#pragma mark JS objects forward definitions
// Global object
static JSValueRef OSXObject_getProperty(JSContextRef, JSObjectRef, JSStringRef, JSValueRef*);
static void OSXObject_getPropertyNames(JSContextRef, JSObjectRef, JSPropertyNameAccumulatorRef);
// Private JS object callbacks
static void jsCocoaObject_initialize(JSContextRef, JSObjectRef);
static void jsCocoaObject_finalize(JSObjectRef);
static JSValueRef jsCocoaObject_callAsFunction(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef [], JSValueRef*);
//static bool jsCocoaObject_hasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
static JSValueRef jsCocoaObject_getProperty(JSContextRef, JSObjectRef, JSStringRef, JSValueRef*);
static bool jsCocoaObject_setProperty(JSContextRef, JSObjectRef, JSStringRef, JSValueRef, JSValueRef*);
static bool jsCocoaObject_deleteProperty(JSContextRef, JSObjectRef, JSStringRef, JSValueRef*);
static void jsCocoaObject_getPropertyNames(JSContextRef, JSObjectRef, JSPropertyNameAccumulatorRef);
static JSObjectRef jsCocoaObject_callAsConstructor(JSContextRef, JSObjectRef, size_t, const JSValueRef [], JSValueRef*);
static JSValueRef jsCocoaObject_convertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
static bool jsCocoaObject_hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
static JSValueRef jsCocoaInfo_getProperty(JSContextRef, JSObjectRef, JSStringRef, JSValueRef*);
static void jsCocoaInfo_getPropertyNames(JSContextRef, JSObjectRef, JSPropertyNameAccumulatorRef);
// Set on valueOf callback property of objects
#define JSCocoaInternalAttribute kJSPropertyAttributeDontEnum
// These will be destroyed when the last JSCocoa instance dies
static JSClassRef OSXObjectClass = NULL;
static JSClassRef jsCocoaObjectClass = NULL;
static JSClassRef jsCocoaFunctionClass= NULL;
static JSClassRef jsCocoaInfoClass = NULL;
static JSClassRef hashObjectClass = NULL;
// Convenience method to throw a Javascript exception
static void throwException(JSContextRef ctx, JSValueRef* exception, NSString* reason);
// iPhone specifics
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
const JSClassDefinition kJSClassDefinitionEmpty = { 0, 0,
NULL, NULL,
NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
#import "GDataDefines.h"
#import "GDataXMLNode.h"
#endif
// Appended to swizzled method names
#define OriginalMethodPrefix @"original"
//
// JSCocoaController
//
#pragma mark -
#pragma mark JSCocoaController
@interface JSCocoaController (Private)
- (void) callDelegateForException:(JSValueRef)exception;
@end
@implementation JSCocoaController
@synthesize delegate=_delegate, useSafeDealloc, useSplitCall, useJSLint;
// Given a jsFunction, retrieve its closure (jsFunction's pointer address is used as key)
static id closureHash;
// Given a jsFunction, retrieve its selector
static id jsFunctionSelectors;
// Given a jsFunction, retrieve which class it's attached to
static id jsFunctionClasses;
// Given a class, return the parent class implementing JSCocoaHolder method
static id jsClassParents;
// List of all ObjC classes written in Javascript
static id jsClasses;
// Given a class + methodName, retrieve its jsFunction
static id jsFunctionHash;
// Split call cache
static id splitCallCache;
// Shared instance stats
static id sharedInstanceStats = nil;
// Boxed objects
static id boxedObjects;
// Auto call zero arg methods : allow NSWorkspace.sharedWorkspace instead of NSWorkspace.sharedWorkspace()
static BOOL useAutoCall;
// Allow calling obj.method(...) instead of obj.method_(...)
static BOOL callSelectorsMissingTrailingSemicolon;
// Allows setting javascript values on boxed objects (which are collected after nulling all references to them)
static BOOL canSetOnBoxedObjects;
// If true, all exceptions will be sent to NSLog, event if they're caught later on by some Javascript core
static BOOL logAllExceptions;
// Is speaking when throwing exceptions
static BOOL isSpeaking;
// Controller count
static int controllerCount = 0;
// Hash used to quickly check for variadic methods, Original, Super, toString, valueOf ...
NSMutableDictionary* customCallPaths;
BOOL customCallPathsCacheIsClean;
// Javascript functions defined for ObjC classes are stored in this hash
// __globalJSFunctionRepository__[className][propertyName]
//
// Init
//
- (id)initWithGlobalContext:(JSGlobalContextRef)_ctx
{
// NSLog(@"JSCocoa : %x spawning with context %x", self, _ctx);
self = [super init];
controllerCount++;
@synchronized(self)
{
if (!sharedInstanceStats)
{
sharedInstanceStats = [NSMutableDictionary new];
closureHash = [NSMutableDictionary new];
jsFunctionSelectors = [NSMutableDictionary new];
jsFunctionClasses = [NSMutableDictionary new];
jsFunctionHash = [NSMutableDictionary new];
splitCallCache = [NSMutableDictionary new];
jsClassParents = [NSMutableDictionary new];
boxedObjects = [NSMutableDictionary new];
jsClasses = [NSMutableArray new];
customCallPathsCacheIsClean = NO;
customCallPaths = nil;
useAutoCall = YES;
callSelectorsMissingTrailingSemicolon = YES;
canSetOnBoxedObjects= NO;
isSpeaking = YES;
isSpeaking = NO;
logAllExceptions = NO;
}
}
//
// OSX object javascript definition
//
JSClassDefinition OSXObjectDefinition = kJSClassDefinitionEmpty;
OSXObjectDefinition.className = "OSX";
OSXObjectDefinition.getProperty = OSXObject_getProperty;
OSXObjectDefinition.getPropertyNames = OSXObject_getPropertyNames;
if (!OSXObjectClass)
OSXObjectClass = JSClassCreate(&OSXObjectDefinition);
//
// Private object, used for holding references to objects, classes, structs
//
JSClassDefinition jsCocoaObjectDefinition = kJSClassDefinitionEmpty;
jsCocoaObjectDefinition.className = "JSCocoa box";
jsCocoaObjectDefinition.initialize = jsCocoaObject_initialize;
jsCocoaObjectDefinition.finalize = jsCocoaObject_finalize;
// jsCocoaObjectDefinition.hasProperty = jsCocoaObject_hasProperty;
jsCocoaObjectDefinition.getProperty = jsCocoaObject_getProperty;
jsCocoaObjectDefinition.setProperty = jsCocoaObject_setProperty;
jsCocoaObjectDefinition.deleteProperty = jsCocoaObject_deleteProperty;
jsCocoaObjectDefinition.getPropertyNames = jsCocoaObject_getPropertyNames;
// jsCocoaObjectDefinition.callAsFunction = jsCocoaObject_callAsFunction;
jsCocoaObjectDefinition.callAsConstructor = jsCocoaObject_callAsConstructor;
// jsCocoaObjectDefinition.hasInstance = jsCocoaObject_hasInstance;
jsCocoaObjectDefinition.convertToType = jsCocoaObject_convertToType;
if (!jsCocoaObjectClass)
jsCocoaObjectClass = JSClassCreate(&jsCocoaObjectDefinition);
//
// Second kind of private object, used to hold method and function names
// Separated from the object because "typeof NSDate.date" gave "function" instead of object, preventing enumeration in WebKit inspector
//
JSClassDefinition jsCocoaFunctionDefinition = kJSClassDefinitionEmpty;
jsCocoaFunctionDefinition.className = "JSCocoa box";
jsCocoaFunctionDefinition.parentClass = jsCocoaObjectClass;
jsCocoaFunctionDefinition.callAsFunction = jsCocoaObject_callAsFunction;
if (!jsCocoaFunctionClass)
jsCocoaFunctionClass = JSClassCreate(&jsCocoaFunctionDefinition);
//
// Holds __info in objects
//
JSClassDefinition jsCocoaInfoDefinition = kJSClassDefinitionEmpty;
jsCocoaInfoDefinition.className = "Runtime info";
jsCocoaInfoDefinition.getProperty = jsCocoaInfo_getProperty;
jsCocoaInfoDefinition.getPropertyNames = jsCocoaInfo_getPropertyNames;
if (!jsCocoaInfoClass)
jsCocoaInfoClass = JSClassCreate(&jsCocoaInfoDefinition);
//
// Private Hash of derived classes, storing js values
//
JSClassDefinition jsCocoaHashObjectDefinition = kJSClassDefinitionEmpty;
if (!hashObjectClass)
hashObjectClass = JSClassCreate(&jsCocoaHashObjectDefinition);
//
// Start context
//
// Starting from our own context
if (!_ctx)
{
ctx = JSGlobalContextCreate(OSXObjectClass);
}
// Starting from an existing context
else
{
ctx = _ctx;
//JSGlobalContextRetain(ctx);
JSObjectRef o = JSObjectMake(ctx, OSXObjectClass, NULL);
// Set a global var named 'OSX' which will fulfill the usual role of JSCocoa's global object
JSStringRef jsName = JSStringCreateWithUTF8CString("OSX");
JSObjectSetProperty(ctx, JSContextGetGlobalObject(ctx), jsName, o, kJSPropertyAttributeDontDelete, NULL);
JSStringRelease(jsName);
[self accomodateWebKitInspector];
}
#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE
[self loadFrameworkWithName:@"AppKit"];
[self loadFrameworkWithName:@"CoreFoundation"];
[self loadFrameworkWithName:@"Foundation"];
[self loadFrameworkWithName:@"CoreGraphics" inPath:@"/System/Library/Frameworks/ApplicationServices.framework/Frameworks"];
#endif
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
[BurksPool setJSFunctionHash:jsFunctionHash];
#endif
// Create a reference to ourselves, and make it read only, don't enum, don't delete
[self setObject:self withName:@"__jsc__" attributes:kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontEnum|kJSPropertyAttributeDontDelete];
// Load class kit
if (!_ctx)
{
useJSLint = NO;
id lintPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"jslint-jscocoa" ofType:@"js"];
if ([[NSFileManager defaultManager] fileExistsAtPath:lintPath]) [self evalJSFile:lintPath];
id classKitPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"class" ofType:@"js"];
if ([[NSFileManager defaultManager] fileExistsAtPath:classKitPath]) [self evalJSFile:classKitPath];
}
// Add allKeys method to Javascript hash : { a : 1, b : 2, c : 3 }.allKeys() = ['a', 'b', 'c']
// Retrieve Javascript function from class.js
JSStringRef jsName = JSStringCreateWithUTF8CString("allKeysInHash");
JSValueRef fn = JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), jsName, NULL);
JSStringRelease(jsName);
if (fn)
{
// Add it to Object.prototype with dont enum property
JSStringRef scriptJS = JSStringCreateWithUTF8CString("return Object.prototype");
JSObjectRef fn2 = JSObjectMakeFunction(ctx, NULL, 0, NULL, scriptJS, NULL, 1, NULL);
JSValueRef jsValue = JSObjectCallAsFunction(ctx, fn2, NULL, 0, NULL, NULL);
JSObjectRef jsObject = JSValueToObject(ctx, jsValue, NULL);
JSStringRelease(scriptJS);
jsName = JSStringCreateWithUTF8CString("allKeys");
JSObjectSetProperty(ctx, jsObject, jsName, fn, kJSPropertyAttributeDontEnum, NULL);
JSStringRelease(jsName);
}
// Objects can use their own dealloc, normally used up by JSCocoa
// JSCocoa registers 'safeDealloc' in place of 'dealloc' and calls it in the next run loop cycle.
// (If called during dealloc, this would mean executing JS code during JS GC, which is not possible)
// useSafeDealloc will be turned to NO upon JSCocoaController dealloc
useSafeDealloc = YES;
// Yep !
useJSLint = YES;
// ObjJ syntax renders split call moot
useSplitCall = NO;
ownsContext = NO;
[JSCocoa updateCustomCallPaths];
return self;
}
- (id)init
{
id o = [self initWithGlobalContext:nil];
ownsContext = YES;
return o;
}
//
// Dealloc
//
- (void)cleanUp
{
// NSLog(@"JSCocoa : %x dying", self);
[self setUseSafeDealloc:NO];
[self unlinkAllReferences];
JSGarbageCollect(ctx);
controllerCount--;
if (controllerCount == 0)
{
if (OSXObjectClass) {
JSClassRelease(OSXObjectClass);
OSXObjectClass = nil;
}
if (jsCocoaObjectClass) {
JSClassRelease(jsCocoaObjectClass);
jsCocoaObjectClass = nil;
}
if (jsCocoaFunctionClass) {
JSClassRelease(jsCocoaFunctionClass);
jsCocoaFunctionClass = nil;
}
if (jsCocoaInfoClass) {
JSClassRelease(jsCocoaInfoClass);
jsCocoaInfoClass = nil;
}
if (hashObjectClass) {
JSClassRelease(hashObjectClass);
hashObjectClass = nil;
}
// We need to nil these all out, since they are static
// and if we make another JSCocoaController after this- they will
// still be around and that's kinda bad (like crashing bad).
[sharedInstanceStats release];
sharedInstanceStats = nil;
[closureHash release];
closureHash = nil;
[jsFunctionSelectors release];
jsFunctionSelectors = nil;
[jsFunctionClasses release];
jsFunctionClasses = nil;
[jsFunctionHash release];
jsFunctionHash = nil;
[splitCallCache release];
splitCallCache = nil;
[jsClassParents release];
jsClassParents = nil;
[boxedObjects release];
boxedObjects = nil;
[customCallPaths release];
customCallPaths = nil;
// Remove classes : go backwards to remove child classes first
NSInteger c = [jsClasses count]-1;
while (c >= 0)
{
id class = [[jsClasses objectAtIndex:c] pointerValue];
objc_disposeClassPair(class);
c--;
}
[jsClasses release];
jsClasses = nil;
}
if (ownsContext) JSGlobalContextRelease(ctx);
}
- (oneway void)release
{
// Each controller adds itself to its Javascript context, therefore retain count will be two when user last calls release.
// We check for this and clean up references then call GC, which will lower retain count to 1.
// Use 'useSafeDealloc' to make sure we're not reentering this one-time code block when GC calls release.
if ([self retainCount] == 2 && useSafeDealloc)
{
[self setUseSafeDealloc:NO];
[self unlinkAllReferences];
// This will take retain count from 2 to 1, readying this instance for deallocation
[self garbageCollect];
}
[super release];
}
- (void)dealloc
{
[self cleanUp];
[super dealloc];
}
- (void)finalize
{
[self cleanUp];
[super finalize];
}
//
// Shared instance
//
static id JSCocoaSingleton = NULL;
+ (id)sharedController
{
@synchronized(self)
{
if (!JSCocoaSingleton)
{
// 1. alloc
// 2. store pointer
// 3. call init
//
// Why ? if init is calling sharedController, the pointer won't have been set and it will call itself over and over again.
//
JSCocoaSingleton = [self alloc];
// NSLog(@"JSCocoa : allocating shared instance %x", JSCocoaSingleton);
[JSCocoaSingleton init];
}
}
return JSCocoaSingleton;
}
+ (BOOL)hasSharedController
{
return !!JSCocoaSingleton;
}
// Retrieves the __jsc__ variable from a context and unbox it
+ (id)controllerFromContext:(JSContextRef)ctx
{
JSStringRef jsName = JSStringCreateWithUTF8CString("__jsc__");
JSValueRef jsValue = JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), jsName, NULL);
JSStringRelease(jsName);
id jsc = nil;
[JSCocoaFFIArgument unboxJSValueRef:jsValue toObject:&jsc inContext:ctx];
// Commented as it falsely reports failure when controller is cleaning up while being deallocated
// if (!jsc) NSLog(@"controllerFromContext couldn't find found the JSCocoaController in ctx %x", ctx);
return jsc;
}
// Report if we're running a nightly JavascriptCore, with GC
+ (void)hazardReport
{
Dl_info info;
// Get info about a JavascriptCore symbol
dladdr(dlsym(RTLD_DEFAULT, "JSClassCreate"), &info);
BOOL runningFromSystemLibrary = [[NSString stringWithUTF8String:info.dli_fname] hasPrefix:@"/System"];
if (!runningFromSystemLibrary) NSLog(@"***Running a nightly JavascriptCore***");
#if !TARGET_OS_IPHONE
if ([NSGarbageCollector defaultCollector]) NSLog(@"***Running with ObjC Garbage Collection***");
#endif
}
// Report what we're running on
+ (NSString*)runningArchitecture
{
#if defined(__ppc__)
return @"PPC";
// Unsupported
//#elif defined(__ppc64__)
// return @"PPC64";
#elif defined(__i386__)
return @"i386";
#elif defined(__x86_64__)
return @"x86_64";
#elif TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
return @"iPhone";
#elif TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
return @"iPhone Simulator";
#else
return @"unknown architecture";
#endif
}
// Replace the toString function with our own
- (void)accomodateWebKitInspector
{
// The inspector uses Object's toString to extract the class name and print it,
// we replace that class name with valueOf when called for JSCocoa boxes
char* script = "\
var _old_toString = Object.prototype.toString \n\
Object.prototype.toString = function () \n\
{ \n\
var str = _old_toString.call(this) \n\
if (!str.match(/JSCocoa/)) \n\
return str \n\
return '[Object ' + (this.valueOf()) + ']' \n\
} \n\
";
JSStringRef scriptJS = JSStringCreateWithCFString((CFStringRef)[NSString stringWithUTF8String:script]);
JSEvaluateScript(ctx, scriptJS, NULL, NULL, 1, NULL);
JSStringRelease(scriptJS);
}
#pragma mark Script evaluation
//
// Quick eval of strings and functions returning ObjC objects
//
- (id)eval:(NSString*)script { return [self toObject:[self evalJSString:script]]; }
- (id)callFunction:(NSString*)name { return [self toObject:[self callJSFunctionNamed:name withArgumentsArray:nil]]; }
- (id)callFunction:(NSString*)name withArguments:(NSArray*)arguments { return [self toObject:[self callJSFunctionNamed:name withArgumentsArray:arguments]]; }
- (BOOL)hasFunction:(NSString*)name { return [self hasJSFunctionNamed:name]; }
- (BOOL)isSyntaxValid:(NSString*)script { return [self isSyntaxValid:script error:nil]; }
//
// Eval of strings, functions, files, returning JavascriptCore objects
//
#pragma mark Script evaluation returning JavascriptCore objects
//
// Evaluate a file
//
- (BOOL)evalJSFile:(NSString*)path toJSValueRef:(JSValueRef*)returnValue
{
NSError* error;
id script = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
// Skip .DS_Store and directories
if (script == nil) return NSLog(@"evalJSFile could not open %@ (%@) — Check file encoding (should be UTF8) and file build phase (should be in \"Copy Bundle Resources\")", path, error), NO;
//
// Delegate canLoadJSFile
//
if (_delegate && [_delegate respondsToSelector:@selector(JSCocoa:canLoadJSFile:)] && ![_delegate JSCocoa:self canLoadJSFile:path]) return NO;
// Expand macros
script = [self expandJSMacros:script path:path];
//
// Delegate canEvaluateScript, willEvaluateScript
//
if (_delegate)
{
if ([_delegate respondsToSelector:@selector(JSCocoa:canEvaluateScript:)] && ![_delegate JSCocoa:self canEvaluateScript:script]) return NO;
if ([_delegate respondsToSelector:@selector(JSCocoa:willEvaluateScript:)]) script = [_delegate JSCocoa:self willEvaluateScript:script];
}
if (!customCallPathsCacheIsClean) [JSCocoa updateCustomCallPaths];
// Convert script and script URL to js strings
// JSStringRef scriptJS = JSStringCreateWithUTF8CString([script UTF8String]);
// Using CreateWithUTF8 yields wrong results on PPC
JSStringRef scriptJS = JSStringCreateWithCFString((CFStringRef)script);
JSStringRef scriptPath = JSStringCreateWithUTF8CString([path UTF8String]);
// Eval !
JSValueRef exception = NULL;
JSValueRef result = JSEvaluateScript(ctx, scriptJS, NULL, scriptPath, 1, &exception);
if (returnValue) *returnValue = result;
// Release
JSStringRelease(scriptPath);
JSStringRelease(scriptJS);
if (exception)
{
// NSLog(@"JSException - %@", [self formatJSException:exception]);
[self callDelegateForException:exception];
return NO;
}
return YES;
}
//
// Evaluate a file, without caring about return result
//
- (BOOL)evalJSFile:(NSString*)path
{
return [self evalJSFile:path toJSValueRef:nil];
}
//
// Evaluate a string
//
- (JSValueRef)evalJSString:(NSString*)script withScriptPath:(NSString*)path
{
if (!script) return NULL;
// Expand macros
id expandedScript = [self expandJSMacros:script path:path];
if (expandedScript)
script = expandedScript;
//
// Delegate canEvaluateScript, willEvaluateScript
//
if (_delegate)
{
if ([_delegate respondsToSelector:@selector(JSCocoa:canEvaluateScript:)] && ![_delegate JSCocoa:self canEvaluateScript:script]) return NULL;
if ([_delegate respondsToSelector:@selector(JSCocoa:willEvaluateScript:)]) script = [_delegate JSCocoa:self willEvaluateScript:script];
}
if (!script)
return NSLog(@"evalJSString has nothing to eval"), NULL;
if (!customCallPathsCacheIsClean) [JSCocoa updateCustomCallPaths];
JSStringRef scriptJS = JSStringCreateWithCFString((CFStringRef)script);
JSValueRef exception = NULL;
JSStringRef scriptPath = path ? JSStringCreateWithUTF8CString([path UTF8String]) : NULL;
JSValueRef result = JSEvaluateScript(ctx, scriptJS, NULL, scriptPath, 1, &exception);
JSStringRelease(scriptJS);
if (path) JSStringRelease(scriptPath);
if (exception)
{
[self callDelegateForException:exception];
return NULL;
}
return result;
}
// Evaluate a string, no script path
- (JSValueRef)evalJSString:(NSString*)script
{
return [self evalJSString:script withScriptPath:nil];
}
//
// Call a Javascript function by function reference (JSValueRef)
//
- (JSValueRef)callJSFunction:(JSValueRef)function withArguments:(NSArray*)arguments
{
JSObjectRef jsFunction = JSValueToObject(ctx, function, NULL);
// Return if function is not of function type
if (!jsFunction) return NSLog(@"callJSFunction : value is not a function"), NULL;
// Convert arguments
JSValueRef* jsArguments = NULL;
NSUInteger argumentCount = [arguments count];
if (argumentCount)
{
jsArguments = malloc(sizeof(JSValueRef)*argumentCount);
for (int i=0; i<argumentCount; i++)
{
char typeEncoding = _C_ID;
id argument = [arguments objectAtIndex:i];
[JSCocoaFFIArgument toJSValueRef:&jsArguments[i] inContext:ctx typeEncoding:typeEncoding fullTypeEncoding:NULL fromStorage:&argument];
}
}
if (!customCallPathsCacheIsClean) [JSCocoa updateCustomCallPaths];
JSValueRef exception = NULL;
JSValueRef returnValue = JSObjectCallAsFunction(ctx, jsFunction, NULL, argumentCount, jsArguments, &exception);
if (jsArguments) free(jsArguments);
if (exception)
{
// NSLog(@"JSException in callJSFunction : %@", [self formatJSException:exception]);
[self callDelegateForException:exception];
return NULL;
}
return returnValue;
}
//
// Call a Javascript function by name
// Arguments require nil termination : [[JSCocoa sharedController] callJSFunctionNamed:@"myFunction" withArguments:arg1, arg2, nil]
//
- (JSValueRef)callJSFunctionNamed:(NSString*)name withArguments:(id)firstArg, ...
{
// Convert args to array
id arg, arguments = [NSMutableArray array];
if (firstArg) [arguments addObject:firstArg];
if (firstArg)
{
va_list args;
va_start(args, firstArg);
while ((arg = va_arg(args, id)))
[arguments addObject:arg];
va_end(args);
}
// Get global object
JSObjectRef globalObject = JSContextGetGlobalObject(ctx);
JSValueRef exception = NULL;
// Get function as property of global object
JSStringRef jsFunctionName = JSStringCreateWithUTF8CString([name UTF8String]);
JSValueRef jsFunctionValue = JSObjectGetProperty(ctx, globalObject, jsFunctionName, &exception);
JSStringRelease(jsFunctionName);
if (exception)
{
// return NSLog(@"%@", [self formatJSException:exception]), NULL;
[self callDelegateForException:exception];
return NULL;
}
// Return if function is not of function type
JSObjectRef jsFunction = JSValueToObject(ctx, jsFunctionValue, NULL);
if (!jsFunction) return NSLog(@"callJSFunctionNamed : %@ is not a function", name), NULL;
// Call !
return [self callJSFunction:jsFunction withArguments:arguments];
}
//
// Call a Javascript function by name
// Arguments must be in an NSArray : [[JSCocoa sharedController] callJSFunctionNamed:@"myFunction" withArgumentsArray:[NSArray array...]]
//
- (JSValueRef)callJSFunctionNamed:(NSString*)name withArgumentsArray:(NSArray*)arguments
{
JSObjectRef jsFunction = [self JSFunctionNamed:name];
if (!jsFunction) return NSLog(@"callJSFunctionNamed found no function %@", name), NULL;
return [self callJSFunction:jsFunction withArguments:arguments];
}
//
// Get a function by name, check if a function exists by name
//
- (JSObjectRef)JSFunctionNamed:(NSString*)name
{
JSValueRef exception = NULL;
// Get function as property of global object
JSStringRef jsFunctionName = JSStringCreateWithUTF8CString([name UTF8String]);
JSValueRef jsFunctionValue = JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), jsFunctionName, &exception);
JSStringRelease(jsFunctionName);
if (exception)
{
// return NSLog(@"%@", [self formatJSException:exception]), NO;
[self callDelegateForException:exception];
return NO;
}
return JSValueToObject(ctx, jsFunctionValue, NULL);
}
- (BOOL)hasJSFunctionNamed:(NSString*)name
{
return !![self JSFunctionNamed:name];
}
//
// Expand macros
//
- (NSString*)expandJSMacros:(NSString*)script path:(NSString*)path errors:(NSMutableArray*)array
{
// Normal path, with macro expansion for class definitions
// OR
// Lintex path
id functionName = @"expandJSMacros";
// Expand macros
BOOL hasFunction = [self hasJSFunctionNamed:functionName];
if (hasFunction && useJSLint)
{
JSValueRef v = [self callJSFunctionNamed:functionName withArguments:script, array, nil];
id expandedScript = [self unboxJSValueRef:v];
// Bail if expansion failed
if (!expandedScript || ![expandedScript isKindOfClass:[NSString class]])
return NSLog(@"%@ expansion failed on script %@ (%@) ", functionName, script, path), NULL;
script = expandedScript;
}
return script;
}
- (NSString*)expandJSMacros:(NSString*)script path:(NSString*)path
{
return [self expandJSMacros:script path:path errors:nil];
}
//
// Syntax validation
//
- (BOOL)isSyntaxValid:(NSString*)script error:(NSString**)outError
{
id errors = [NSMutableArray array];
script = [self expandJSMacros:script path:nil errors:errors];
JSStringRef scriptJS = JSStringCreateWithUTF8CString([script UTF8String]);
JSValueRef exception = NULL;
BOOL b = JSCheckScriptSyntax(ctx, scriptJS, scriptJS, 1, &exception);
JSStringRelease(scriptJS);
if (exception)
{
NSMutableArray* errorList = [NSMutableArray array];
NSString* str = [self formatJSException:exception];
[errorList addObject:str];
for (id error in errors)
{
[errorList addObject:[error valueForKey:@"error"]];
if ([error valueForKey:@"line"]) [errorList addObject:[error valueForKey:@"line"]];
if ([error valueForKey:@"position"]) [errorList addObject:[error valueForKey:@"position"]];
}
if (outError)
*outError = [errorList componentsJoinedByString:@"\n"];
}
return b;
}
//
// Unbox a JSValueRef
//
- (id)unboxJSValueRef:(JSValueRef)value
{
id object = nil;
[JSCocoaFFIArgument unboxJSValueRef:value toObject:&object inContext:ctx];
return object;
}
//
// Conversion boolean / number / string
//
- (BOOL)toBool:(JSValueRef)value
{
if (!value) return false;
return JSValueToBoolean(ctx, value);
}
- (double)toDouble:(JSValueRef)value
{
if (!value) return 0;
return JSValueToNumber(ctx, value, NULL);
}
- (int)toInt:(JSValueRef)value
{
if (!value) return 0;
return (int)JSValueToNumber(ctx, value, NULL);
}
- (NSString*)toString:(JSValueRef)value
{
if (!value) return nil;
JSStringRef resultStringJS = JSValueToStringCopy(ctx, value, NULL);
NSString* resultString = (NSString*)JSStringCopyCFString(kCFAllocatorDefault, resultStringJS);
JSStringRelease(resultStringJS);
[NSMakeCollectable(resultString) autorelease];
return resultString;
}
- (id)toObject:(JSValueRef)value
{
return [self unboxJSValueRef:value];
}
//
// Add/Remove an ObjC object variable to the global context
//
- (BOOL)setObject:(id)object withName:(id)name attributes:(JSPropertyAttributes)attributes
{
JSObjectRef o = [JSCocoaController boxedJSObject:object inContext:ctx];
// Set
JSValueRef exception = NULL;
JSStringRef jsName = JSStringCreateWithUTF8CString([name UTF8String]);
JSObjectSetProperty(ctx, JSContextGetGlobalObject(ctx), jsName, o, attributes, &exception);
JSStringRelease(jsName);
if (exception)
{
[self callDelegateForException:exception];
return NO;
}
return YES;
}
- (BOOL)setObject:(id)object withName:(id)name
{
return [self setObject:object withName:name attributes:kJSPropertyAttributeNone];
}
- (BOOL)removeObjectWithName:(id)name
{
JSValueRef exception = NULL;
// Delete
JSStringRef jsName = JSStringCreateWithUTF8CString([name UTF8String]);
JSObjectDeleteProperty(ctx, JSContextGetGlobalObject(ctx), jsName, &exception);
JSStringRelease(jsName);
if (exception)
{
[self callDelegateForException:exception];
return NO;
}
return YES;
}
#pragma mark Loading Frameworks
- (BOOL)loadFrameworkWithName:(NSString*)name
{
// Only check /System/Library/Frameworks for now
return [self loadFrameworkWithName:name inPath:@"/System/Library/Frameworks"];
}
//
// Load framework
// even if framework has no bridgeSupport, load it anyway - it could contain ObjC classes
//
- (BOOL)loadFrameworkWithName:(NSString*)name inPath:(NSString*)inPath
{
id path = [NSString stringWithFormat:@"%@/%@.framework/Resources/BridgeSupport/%@.bridgeSupport", inPath, name, name];
// Return YES if already loaded
if ([[BridgeSupportController sharedController] isBridgeSupportLoaded:path]) return YES;
// Load framework
id libPath = [NSString stringWithFormat:@"%@/%@.framework/%@", inPath, name, name];
void* address = dlopen([libPath UTF8String], RTLD_LAZY);
if (!address) return NSLog(@"Could not load framework dylib %@", libPath), NO;
// Try loading .bridgesupport file
if (![[BridgeSupportController sharedController] loadBridgeSupport:path]) return NSLog(@"Could not load framework bridgesupport %@", path), NO;
// Try loading extra dylib (inline functions made callable and compiled to a .dylib)
id extraLibPath = [NSString stringWithFormat:@"%@/%@.framework/Resources/BridgeSupport/%@.dylib", inPath, name, name];
/*address = */dlopen([extraLibPath UTF8String], RTLD_LAZY);
// Don't fail if we didn't load the extra dylib as it is optional
// if (!address) return NSLog(@"Did not load extra framework dylib %@", path), NO;
customCallPathsCacheIsClean = NO;
return YES;
}
+ (void)updateCustomCallPaths
{
if (customCallPaths) [customCallPaths release];
customCallPaths = [NSMutableDictionary new];
[customCallPaths addEntriesFromDictionary:[[BridgeSupportController sharedController] variadicFunctions]];
[customCallPaths addEntriesFromDictionary:[[BridgeSupportController sharedController] variadicSelectors]];
[customCallPaths setObject:@"true" forKey:@"Original"];
[customCallPaths setObject:@"true" forKey:@"Super"];
[customCallPaths setObject:@"true" forKey:@"toString"];
[customCallPaths setObject:@"true" forKey:@"valueOf"];
customCallPathsCacheIsClean = YES;
}
# pragma mark Unsorted methods
+ (void)log:(NSString*)string
{
NSLog(@"%@", string);
}
- (void)log:(NSString*)string
{
NSLog(@"%@", string);
}
- (id)system:(NSString*)string
{
system([string UTF8String]);
return nil;
}
+ (void)logAndSay:(NSString*)string
{
[self log:string];
if (isSpeaking) system([[NSString stringWithFormat:@"say %@ &", string] UTF8String]);
}
+ (JSObjectRef)jsCocoaPrivateObjectInContext:(JSContextRef)ctx
{
JSCocoaPrivateObject* private = [[JSCocoaPrivateObject alloc] init];
#ifdef __OBJC_GC__
// Mark internal object as non collectable
[[NSGarbageCollector defaultCollector] disableCollectorForPointer:private];
#endif
JSObjectRef o = JSObjectMake(ctx, jsCocoaObjectClass, private);
[private release];
return o;
}