/
QCMonoPlugIn.m
952 lines (802 loc) · 28.2 KB
/
QCMonoPlugIn.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
//
// QCMonoPlugIn.m
// QCMono
//
// Created by Caleb Cannon on 10/19/10.
// Copyright (c) 2010 Caleb Cannon. All rights reserved.
//
/* It's highly recommended to use CGL macros instead of changing the current context for plug-ins that perform OpenGL rendering */
#import <OpenGL/CGLMacro.h>
#import "QCMonoPlugIn.h"
#import "MonoUtils.h"
NSInteger CompilerCSharp;
#define kQCPlugIn_Name @"QCMono"
#define kQCPlugIn_Description @"This patch executes a script using the Mono IL framework with an arbitrary number of input / output parameters. Currently supported languages are C# and Boo. The Mono framework must be installed on the machine running the composition in order for the patch to work. Each script must declare a \"Script\" class with a public function \"main()\" as an entry point. Class variables beginning with \"input\" and \"output\" will be mapped to input and output ports in the Quartz Composer patch."
// Keys used for saving and loading serialized values
#define kScriptSourceCode @"scriptSourceCode"
#define kMonoImageData @"monoImageData"
#define kSelectedCompilerIndex @"selectedCompilerIndex"
#define kInputPortDescriptions @"inputPortDescriptions"
#define kOutputPortDescriptions @"outputPortDescriptions"
// Keys used by the compiler info dictionary / plist
#define kCompilerCommand @"compileCommand"
#define kCompilerName @"name"
#define kCompilerSyntaxDefinitionFile @"syntaxDefinitionFile"
// Keys used in the port descriptions dictionaries
#define kQCPortType @"QCPortTypeKey"
#define kQCPortKey @"QCPortKey"
#define kQCPortAttributes @"QCPortAttributesKey"
@implementation QCMonoPlugIn
@synthesize selectedCompilerIndex;
@dynamic compilerNames;
@synthesize compilerError, compilerWarning, compilerOK, compiling;
@synthesize scriptSourceCode, monoImageData;
@synthesize consoleText;
@dynamic attributedScriptSourceCode;
+ (NSDictionary*) attributes
{
return [NSDictionary dictionaryWithObjectsAndKeys:kQCPlugIn_Name, QCPlugInAttributeNameKey, kQCPlugIn_Description, QCPlugInAttributeDescriptionKey, nil];
}
+ (NSDictionary*) attributesForPropertyPortWithKey:(NSString*)key
{
return nil;
}
+ (QCPlugInExecutionMode) executionMode
{
return kQCPlugInExecutionModeProcessor;
}
+ (QCPlugInTimeMode) timeMode
{
return kQCPlugInTimeModeNone;
}
- (NSDictionary *)compilerInfo
{
NSString *compilerInfoFilepath = [[NSBundle bundleForClass:[self class]] pathForResource:@"compilers" ofType:@"plist"];
NSArray *compilerInfo = [NSArray arrayWithContentsOfFile:compilerInfoFilepath];
return [compilerInfo objectAtIndex:selectedCompilerIndex];
}
- (NSArray *)compilerNames
{
NSString *compilerInfoFilepath = [[NSBundle bundleForClass:[self class]] pathForResource:@"compilers" ofType:@"plist"];
NSArray *compilerInfo = [NSArray arrayWithContentsOfFile:compilerInfoFilepath];
return [compilerInfo valueForKey:@"name"];
}
- (NSArray *) sortedPropertyPortKeys
{
NSMutableArray *sortedPropertyPortKeys = [NSMutableArray arrayWithCapacity:[inputPortDescriptions count] + [outputPortDescriptions count]];
for (NSDictionary *portDesc in inputPortDescriptions)
[sortedPropertyPortKeys addObject:[portDesc objectForKey:kQCPortKey]];
for (NSDictionary *portDesc in outputPortDescriptions)
[sortedPropertyPortKeys addObject:[portDesc objectForKey:kQCPortKey]];
return sortedPropertyPortKeys;
}
- (id) init
{
if(self = [super init])
{
NSError *error = nil;
scriptSourceCode = [[NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"default" ofType:@"cs"]
encoding:NSASCIIStringEncoding
error:&error] retain];
if (error)
{
// Something went wrong loading the default script ... forget about it
scriptSourceCode = nil;
shouldCompile = NO;
}
selectedCompilerIndex = 0;
}
return self;
}
- (void) finalize
{
[self cleanupMono];
[super finalize];
}
- (void) dealloc
{
[super dealloc];
}
+ (NSArray*) plugInKeys
{
return [NSArray arrayWithObjects:kScriptSourceCode, kMonoImageData, kInputPortDescriptions, kOutputPortDescriptions, kSelectedCompilerIndex, nil];
}
- (id) serializedValueForKey:(NSString*)key;
{
if ([key isEqualToString:kScriptSourceCode])
return self.scriptSourceCode;
else if ([key isEqualToString:kMonoImageData])
return self.monoImageData;
else if ([key isEqualToString:kSelectedCompilerIndex])
return [NSNumber numberWithInt:selectedCompilerIndex];
else if ([key isEqualToString:kInputPortDescriptions])
return inputPortDescriptions;
else if ([key isEqualToString:kOutputPortDescriptions])
return outputPortDescriptions;
else
return [super serializedValueForKey:key];
}
- (void) setSerializedValue:(id)serializedValue forKey:(NSString*)key
{
if ([key isEqualToString:kScriptSourceCode])
self.scriptSourceCode = serializedValue;
else if ([key isEqualToString:kMonoImageData])
{
self.monoImageData = serializedValue;
}
else if ([key isEqualToString:kInputPortDescriptions])
{
[inputPortDescriptions release];
inputPortDescriptions = [serializedValue retain];
[self synchInputPorts];
}
else if ([key isEqualToString:kOutputPortDescriptions])
{
[outputPortDescriptions release];
outputPortDescriptions = [serializedValue retain];
[self synchOutputPorts];
}
else if ([key isEqualToString:kSelectedCompilerIndex])
self.selectedCompilerIndex = [serializedValue intValue];
else
[super setSerializedValue:serializedValue forKey:key];
}
- (QCPlugInViewController*) createViewController
{
/*
Return a new QCPlugInViewController to edit the internal settings of this plug-in instance.
You can return a subclass of QCPlugInViewController if necessary.
*/
return [[QCPlugInViewController alloc] initWithPlugIn:self viewNibName:@"Settings"];
}
#pragma mark -
#pragma mark Accessors
// Start a timer to recompile the script. This prevents the compiler from running every time
// the user types a character.
- (void) startCompileTimer
{
if (!shouldCompile)
{
shouldCompile = YES;
return;
}
if (compileTimer)
[compileTimer invalidate];
const double compileTimeInterval = 3.0;
compileTimer = [NSTimer scheduledTimerWithTimeInterval:compileTimeInterval
target:self
selector:@selector(compileTimerFired)
userInfo:nil
repeats:NO];
}
- (void) compileTimerFired
{
compileTimer = nil;
[self compileAndLoadMonoScript];
}
// Override the accessor so that the source is automatically compiled a short time after updating
- (void) setScriptSourceCode:(NSString *)source
{
[scriptSourceCode release];
scriptSourceCode = [source retain];
[self startCompileTimer];
}
// Override the accessor so that the source is automatically compiled a short time after updating
- (void) setSelectedCompilerIndex:(NSInteger)index
{
selectedCompilerIndex = index;
[self startCompileTimer];
}
// NSTextView bindings are for attributed strings. These are present to
// make binding the NSTextView attributed string to the (ordinary) string
// soruce code possible
- (void) setAttributedScriptSourceCode:(NSAttributedString *)attributedString
{
self.scriptSourceCode = [attributedString string];
}
- (NSAttributedString *)attributedScriptSourceCode
{
if (self.scriptSourceCode)
return [[[NSAttributedString alloc] initWithString:self.scriptSourceCode] autorelease];
return nil;
}
// When a new image is available load it into the mono runtime
- (void) setMonoImageData:(NSData *)data
{
[monoImageData release];
monoImageData = [data retain];
[self loadMonoImageData];
}
#pragma mark -
#pragma mark Mono support
// Prints a message to the console and the 'log' view in the editor
- (void) logMessage:(NSString *)message, ...
{
va_list args;
va_start(args, message);
NSString *str = [[[NSString alloc] initWithFormat:message arguments:args] autorelease];
NSLog(str,nil);
self.consoleText = str;
}
// Load an image into the mono runtime. Initializes the runtime if necessary and cleans up old images
- (BOOL) loadMonoImageData
{
if (self.monoImageData == nil)
return FALSE;
MonoImageOpenStatus status;
// Initialize Mono if no domain can be found
MonoDomain *rootMonoDomain = mono_domain_get();
if (rootMonoDomain == nil)
{
mono_config_parse (nil);
NSString *domainName = [NSString stringWithFormat:@"QC Mono Root Domain %p", self];
rootMonoDomain = mono_jit_init_version([domainName UTF8String], NULL);
}
// The following is almost certainly not done correctly. I have not been able to
// properly free objects allocated in the root domain which tends to cause a crash
// after a few recompiles. Loading objects into a sub domain prevents any crashing
if (monoScriptDomain)
mono_domain_unload(monoScriptDomain);
NSString *domainName = [NSString stringWithFormat:@"QC Mono Application Domain %p", self];
monoScriptDomain = mono_domain_create_appdomain((char *)[domainName UTF8String], 0);
mono_domain_set(monoScriptDomain, 0);
/*
if (monoImage)
{
mono_image_close(monoImage);
monoImage = nil;
monoAssembly = nil;
}
*/
if (monoObjectGCHandle)
{
mono_gchandle_free(monoObjectGCHandle);
monoObjectGCHandle = 0;
}
// Load the image from the NSData we got after compiling the script
BOOL ref_only = NO;
monoImage = mono_image_open_from_data_full((char *)[self.monoImageData bytes], [self.monoImageData length], YES, &status, ref_only);
if (monoImage == nil || status != MONO_IMAGE_OK)
{
[self logMessage:@"Could not load image data. Status: %i", status];
return FALSE;
}
// Load the image assembly
monoAssembly = mono_assembly_load_from_full(monoImage, mono_image_get_name(monoImage), &status, ref_only);
if (monoAssembly == nil)
{
[self logMessage:@"Could not load assembly from image. Status: %i", status];
//mono_image_close(monoImage), monoImage = nil;
return FALSE;
}
//image = mono_assembly_get_image (monoAssembly);
monoScriptClass = mono_class_from_name (monoImage, "", "Script");
if (monoScriptClass == nil)
{
[self logMessage:@"Could not find a Script class. Scripts must contain a class 'Script' with a public method 'main()' as an entry point."];
mono_assembly_close(monoAssembly), monoAssembly = nil;
//mono_image_close(monoImage), monoImage = nil;
return FALSE;
}
// Why a public method would require these flags but the flags themselves are not exposed is beyond me
#define METHOD_ATTRIBUTE_PUBLIC 0x0006
#define METHOD_ATTRIBUTE_STATIC 0x0010
#define M_ATTRS (METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC)
monoInvocationMethod = mono_class_get_method_from_name_flags (monoScriptClass, "main", 0, M_ATTRS);
if (monoInvocationMethod == nil)
{
[self logMessage:@"Could not find a Main method. Scripts must contain a class 'Script' with a public method 'main()' as an entry point."];
mono_assembly_close(monoAssembly);
monoAssembly = nil;
//mono_image_close(monoImage);
monoImage = nil;
return FALSE;
}
// Initialize an object of the script class defined in the assembly
monoScriptObject = mono_object_new(mono_domain_get(), monoScriptClass);
if (monoScriptObject == nil)
{
[self logMessage:@"Unable to create new script object."];
mono_assembly_close(monoAssembly), monoAssembly = nil;
mono_image_close(monoImage), monoImage = nil;
return FALSE;
}
mono_runtime_object_init(monoScriptObject);
monoObjectGCHandle = mono_gchandle_new(monoScriptObject, 1);
mono_domain_set(rootMonoDomain, 0);
[self createInputPortsForScriptFields];
// [[self patch] setNeedsExecution];
[self execute:nil atTime:0.0 withArguments:nil];
return TRUE;
}
- (BOOL) compileAndLoadMonoScript
{
if (self.scriptSourceCode == nil)
return NO;
// Get file paths for the source and executable
const char *sourceFilePrefix = "qc-mono-tmp-";
NSString *sourceFilePath = [[[NSString alloc] initWithCString:tempnam([NSTemporaryDirectory() cStringUsingEncoding:[NSString defaultCStringEncoding]], sourceFilePrefix)] autorelease];
NSString *destFilePath = [sourceFilePath stringByAppendingPathExtension:@"mono.exe"];
NSLog(@"Src: %@", sourceFilePath);
// Write the source to a temporary file
NSError *error = nil;
[self.scriptSourceCode writeToFile:sourceFilePath atomically:NO encoding:[NSString defaultCStringEncoding] error:&error];
if (error)
{
[self logMessage:@"Error writing source: %@", error];
return NO;
}
// Create an execute the compilation task
NSTask *compileTask = [[NSTask alloc] init];
NSString *compileCommand;
NSDictionary *compilerInfo = [self compilerInfo];
compileCommand = [compilerInfo objectForKey:kCompilerCommand];
compileCommand = [compileCommand stringByReplacingOccurrencesOfString:@"%sourcefilepath%" withString:sourceFilePath];
compileCommand = [compileCommand stringByReplacingOccurrencesOfString:@"%destfilepath%" withString:destFilePath];
NSArray *compileArguments = [NSArray arrayWithObjects:
@"-l",
@"-c",
compileCommand,
nil];
[compileTask setLaunchPath:@"/bin/bash"];
[compileTask setArguments:compileArguments];
[compileTask setCurrentDirectoryPath:[@"~" stringByExpandingTildeInPath]];
// Configure a pipe so that NSTask doesn't mess with our output
// Matching the input&output keeps the log where it belongs
NSPipe *pipe = [NSPipe pipe];
[compileTask setStandardOutput:pipe];
[compileTask setStandardInput:[NSPipe pipe]];
[compileTask setStandardError:pipe];
// So that NSTask can use the PATH variables
//[compileTask setEnvironment:[[NSProcessInfo processInfo] environment]];
[compileTask setLaunchPath:@"/bin/bash"];
// Compile the script
self.compilerError = NO;
self.compilerWarning = NO;
self.compilerOK = NO;
self.compiling = TRUE;
[compileTask launch];
[compileTask waitUntilExit];
self.compiling = FALSE;
// Get the compiler log string
NSData *outputData = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSASCIIStringEncoding] autorelease];
// Clean up the string
outputString = [outputString stringByReplacingOccurrencesOfString:sourceFilePath withString:@""];
self.consoleText = outputString;
int compileStatus = [compileTask terminationStatus];
// Load the compiled assembly if compilation was successful and update the compiler status flags
if (compileStatus == 0)
{
if ([outputString length] == 0)
self.compilerOK = YES;
else
self.compilerWarning = YES;
// The accessor will load the assembly data into the Mono interpreter
self.monoImageData = [NSData dataWithContentsOfFile:destFilePath];
}
else
{
self.monoImageData = nil;
self.compilerError = YES;
}
[compileTask release];
return (compileStatus == 0);
}
// Returns TRUE is the port key is present and has the correct type.
// Removes the port and returns FALSE if the port name key is present but has the wrong type
// Returns FALSE if the port key is not present
- (BOOL) validateMonoPortWithType:(NSString *)type key:(NSString *)key fromPorts:(NSArray *)ports
{
// The patch and custom*Ports methods are private methods used to get the current list of input and output ports
for (id port in ports)
{
if ([key isEqualToString:[port key]])
{
if ([type isEqualToString:QCPortTypeIndex] && [[[port class] description] isEqualToString:@"QCIndexPort"])
return YES;
if ([type isEqualToString:QCPortTypeNumber] && [[[port class] description] isEqualToString:@"QCNumberPort"])
return YES;
if ([type isEqualToString:QCPortTypeBoolean] && [[[port class] description] isEqualToString:@"QCBooleanPort"])
return YES;
if ([type isEqualToString:QCPortTypeString] && [[[port class] description] isEqualToString:@"QCStringPort"])
return YES;
if ([type isEqualToString:QCPortTypeStructure] && [[[port class] description] isEqualToString:@"QCStructureDictionaryPort"])
return YES;
else {
[self removeInputPortForKey:key];
return NO;
}
}
}
return NO;
}
// Adds an input port if not present in the current patch input ports array
- (void) addMonoInputPortWithType:(NSString *)type forKey:(NSString *)key withAttributes:(NSDictionary *)attributes
{
NSArray *inputPorts = [[self patch] customInputPorts];
if (![self validateMonoPortWithType:type key:key fromPorts:inputPorts])
{
[self addInputPortWithType:type forKey:key withAttributes:attributes];
}
}
// Adds an input port if not present in the current patch output ports array
- (void) addMonoOutputPortWithType:(NSString *)type forKey:(NSString *)key withAttributes:(NSDictionary *)attributes
{
NSArray *outputPorts = [[self patch] customOutputPorts];
// Add the port if it's not already there
if (![self validateMonoPortWithType:type key:key fromPorts:outputPorts])
[self addOutputPortWithType:type forKey:key withAttributes:attributes];
}
// Creates and removes ports as necessary so that the patch's input and output
// ports match the inputPortDescriptions and outputPortDescriptions arrays
- (void) synchPorts
{
[self synchInputPorts];
[self synchOutputPorts];
}
- (void) synchInputPorts
{
for (NSDictionary *portDescription in inputPortDescriptions)
{
NSString *portType = [portDescription objectForKey:kQCPortType];
NSString *portKey = [portDescription objectForKey:kQCPortKey];
NSDictionary *portAttributes = [portDescription objectForKey:kQCPortAttributes];
[self addMonoInputPortWithType:portType forKey:portKey withAttributes:portAttributes];
}
}
- (void) synchOutputPorts
{
for (NSDictionary *portDescription in outputPortDescriptions)
{
NSString *portType = [portDescription objectForKey:kQCPortType];
NSString *portKey = [portDescription objectForKey:kQCPortKey];
NSDictionary *portAttributes = [portDescription objectForKey:kQCPortAttributes];
[self addMonoOutputPortWithType:portType forKey:portKey withAttributes:portAttributes];
}
}
- (void) createInputPortsForScriptFields
{
if (monoScriptClass == nil || monoScriptObject == nil)
return;
NSMutableArray *newInputPortDescriptions = [NSMutableArray array];
NSMutableArray *newOutputPortDescriptions = [NSMutableArray array];
MonoType *field_type;
int type_type;
MonoObject *field_object;
NSString *fieldName;
id fieldValue;
NSString *portType;
NSMutableDictionary *portAttributes;
void *iter = (void *) 0;
MonoClassField *field;
while ((field = mono_class_get_fields (monoScriptClass, &iter)) != NULL)
{
field_type = mono_field_get_type (field);
fieldName = [NSString stringWithUTF8String:mono_field_get_name(field)];
if ([fieldName length] > 5 && [fieldName hasPrefix:@"input"])
{
char *field_type_name = mono_type_get_name(field_type);
type_type = mono_type_get_type(field_type);
portAttributes = [NSMutableDictionary dictionary];
portType = qcm_get_qcport_type_for_type(type_type);
// TODO: switch to select statement
if (strcmp(field_type_name, "System.Object[]") == 0)
{
fieldValue = nil;
}
else if (strcmp(field_type_name, "System.String[]") == 0)
{
/*
If a default value is specified create a menu for any inputs specified as an array of strings
*/
NSArray *menuItems = qcm_get_string_array_from_field(monoScriptObject, field);
if (menuItems && [menuItems count] > 0)
{
portType = QCPortTypeIndex;
[portAttributes setObject:QCPortTypeIndex forKey:QCPortAttributeTypeKey];
/*
Note: adding a menu at this stage seems to crash QC for some reason.
The line setting the QCPortAttributeMenuItemKey should handle this.
Instead we will use an ordinary index port :( If this is ever corrected
then uncommenting the following line should create the menu items array
*/
//[portAttributes setObject:menuItems forKey:QCPortAttributeMenuItemsKey];
[portAttributes setObject:[NSNumber numberWithInt:0] forKey:QCPortAttributeDefaultValueKey];
[portAttributes setObject:[NSNumber numberWithInt:0] forKey:QCPortAttributeMinimumValueKey];
[portAttributes setObject:[NSNumber numberWithInt:[menuItems count]-1] forKey:QCPortAttributeMaximumValueKey];
}
}
else if (strcmp(field_type_name, "System.Object[]") == 0)
{
portType = QCPortTypeStructure;
[portAttributes setObject:QCPortTypeStructure forKey:QCPortAttributeTypeKey];
}
else
{
field_object = mono_field_get_value_object(mono_domain_get(), field, monoScriptObject);
fieldValue = mono_get_foundation_object_from_object(field_object);
}
[portAttributes setObject:[fieldName substringFromIndex:5] forKey:QCPortAttributeNameKey];
[newInputPortDescriptions addObject:[NSDictionary dictionaryWithObjectsAndKeys:
portType, kQCPortType,
fieldName, kQCPortKey,
portAttributes, kQCPortAttributes,
nil]];
}
else if ([fieldName length] > 6 && [fieldName hasPrefix:@"output"])
{
int type_type = mono_type_get_type(field_type);
portAttributes = [NSMutableDictionary dictionary];
portType = qcm_get_qcport_type_for_type(type_type);
[portAttributes setObject:[fieldName substringFromIndex:6] forKey:QCPortAttributeNameKey];
[newOutputPortDescriptions addObject:[NSDictionary dictionaryWithObjectsAndKeys:
portType, kQCPortType,
fieldName, kQCPortKey,
portAttributes, kQCPortAttributes,
nil]];
}
}
// Remove input ports not present to the inputPorts array
BOOL matchedPort;
for (NSDictionary *portDescription in inputPortDescriptions)
{
matchedPort = FALSE;
for (NSDictionary *newPortDescription in newInputPortDescriptions)
{
if ([[portDescription objectForKey:kQCPortKey] isEqualToString:[newPortDescription objectForKey:kQCPortKey]])
{
if ([[portDescription objectForKey:kQCPortType] isEqualToString:[newPortDescription objectForKey:kQCPortType]])
{
matchedPort = TRUE;
break;
}
}
}
if (!matchedPort)
[self removeInputPortForKey:[portDescription objectForKey:kQCPortKey]];
}
for (NSDictionary *portDescription in outputPortDescriptions)
{
matchedPort = FALSE;
for (NSDictionary *newPortDescription in newOutputPortDescriptions)
{
if ([[portDescription objectForKey:kQCPortKey] isEqualToString:[newPortDescription objectForKey:kQCPortKey]])
{
if ([[portDescription objectForKey:kQCPortType] isEqualToString:[newPortDescription objectForKey:kQCPortType]])
{
matchedPort = TRUE;
break;
}
}
}
if (!matchedPort)
[self removeOutputPortForKey:[portDescription objectForKey:kQCPortKey]];
}
[inputPortDescriptions release];
[outputPortDescriptions release];
inputPortDescriptions = [newInputPortDescriptions retain];
outputPortDescriptions = [newOutputPortDescriptions retain];
[self synchPorts];
}
// Iterate through the current input ports and marshal their current values to the script data members
- (void) updateInputPortValues
{
MonoClassField *field;
MonoType *field_type;
void *field_new_value;
int type_type;
NSString *fieldName;
void *iter = (void *) 0;
while ((field = mono_class_get_fields (monoScriptClass, &iter)) != NULL)
{
field_type = mono_field_get_type (field);
type_type = mono_type_get_type(field_type);
fieldName = [NSString stringWithUTF8String:mono_field_get_name(field)];
field_new_value = nil;
switch (type_type)
{
case MONO_TYPE_END:
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
{
BOOL b = [[self valueForInputKey:fieldName] boolValue];
field_new_value = &b;
break;
}
case MONO_TYPE_CHAR:
{
char c = [[self valueForInputKey:fieldName] charValue];
field_new_value = &c;
break;
}
case MONO_TYPE_I1:
{
char c = [[self valueForInputKey:fieldName] charValue];
field_new_value = &c;
break;
}
case MONO_TYPE_U1:
{
unsigned char c = [[self valueForInputKey:fieldName] unsignedCharValue];
field_new_value = &c;
break;
}
case MONO_TYPE_I2:
{
short s = [[self valueForInputKey:fieldName] shortValue];
field_new_value = &s;
break;
}
case MONO_TYPE_U2:
{
unsigned short s = [[self valueForInputKey:fieldName] unsignedShortValue];
field_new_value = &s;
break;
}
case MONO_TYPE_I4:
{
int i = [[self valueForInputKey:fieldName] intValue];
field_new_value = &i;
break;
}
case MONO_TYPE_U4:
{
unsigned int i = [[self valueForInputKey:fieldName] unsignedIntValue];
field_new_value = &i;
break;
}
case MONO_TYPE_I8:
{
long l = [[self valueForInputKey:fieldName] longValue];
field_new_value = &l;
break;
}
case MONO_TYPE_U8:
{
unsigned long l = [[self valueForInputKey:fieldName] unsignedLongValue];
field_new_value = &l;
break;
}
case MONO_TYPE_R4:
{
float f = [[self valueForInputKey:fieldName] floatValue];
field_new_value = &f;
break;
}
case MONO_TYPE_R8:
{
double d = [[self valueForInputKey:fieldName] doubleValue];
field_new_value = &d;
break;
}
case MONO_TYPE_STRING:
{
const char *input_string = [[self valueForInputKey:fieldName] UTF8String];
if (input_string != nil)
{
field_new_value = mono_string_new(mono_domain_get(), input_string);
mono_field_set_value(monoScriptObject, field, field_new_value);
field_new_value = nil;
}
break;
}
case MONO_TYPE_PTR:
case MONO_TYPE_BYREF:
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_VAR:
case MONO_TYPE_ARRAY:
case MONO_TYPE_GENERICINST:
case MONO_TYPE_TYPEDBYREF:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_FNPTR:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
{
NSDictionary *objectDict = [self valueForInputKey:fieldName];
MonoArray *array = qcm_array_create_from_dictionary(mono_domain_get(), objectDict);
mono_field_set_value(monoScriptObject, field, array);
field_new_value = nil;
break;
}
case MONO_TYPE_MVAR:
case MONO_TYPE_CMOD_REQD:
case MONO_TYPE_CMOD_OPT:
case MONO_TYPE_INTERNAL:
case MONO_TYPE_MODIFIER:
case MONO_TYPE_SENTINEL:
case MONO_TYPE_PINNED:
case MONO_TYPE_ENUM:
default:
break;
}
if (field_new_value != nil)
mono_field_set_value(monoScriptObject, field, field_new_value);
}
}
- (void) updateOutputPortValues
{
MonoType *field_type;
char *field_type_name;
int type_type;
MonoClassField *field;
MonoObject *field_object;
NSString *fieldName;
id fieldValue;
void *iter = (void *) 0;
while ((field = mono_class_get_fields (monoScriptClass, &iter)) != NULL)
{
field_type = mono_field_get_type (field);
type_type = mono_type_get_type(field_type);
fieldName = [NSString stringWithUTF8String:mono_field_get_name(field)];
if ([fieldName length] > 6 && [fieldName hasPrefix:@"output"])
{
field_type_name = mono_type_get_name(field_type);
fieldValue = nil;
field_object = mono_field_get_value_object(mono_domain_get(), field, monoScriptObject);
fieldValue = mono_get_foundation_object_from_object(field_object);
// Assign the foundation value to the output port
[self setValue:fieldValue forOutputKey:fieldName];
}
}
}
- (void) cleanupMono
{
mono_jit_cleanup(mono_domain_get());
}
#pragma mark -
#pragma mark QC plugin execution methods
- (BOOL) startExecution:(id<QCPlugInContext>)context
{
return YES;
}
- (void) enableExecution:(id<QCPlugInContext>)context
{
shouldCompile = YES;
}
- (BOOL) execute:(id<QCPlugInContext>)context atTime:(NSTimeInterval)time withArguments:(NSDictionary*)arguments
{
// Execute the scripts Main method
MonoObject *exc = nil;
if (monoInvocationMethod)
{
[self updateInputPortValues];
mono_runtime_invoke (monoInvocationMethod, monoScriptObject, nil, &exc);
[self updateOutputPortValues];
}
else
return NO;
// If an exception was raised, write the details to standard out and raise an NSException
if (exc != nil)
{
mono_print_unhandled_exception (exc);
NSString *exceptionString = @"Exception raised in Mono invocation method. See console for details";
NSException *exception = [NSException exceptionWithName:@"Unhandled Exception" reason:exceptionString userInfo:nil];
[exception raise];
[self cleanupMono];
return NO;
}
return YES;
}
- (void) disableExecution:(id<QCPlugInContext>)context
{
/*
Called by Quartz Composer when the plug-in instance stops being used by Quartz Composer.
*/
}
- (void) stopExecution:(id<QCPlugInContext>)context
{
/*
Called by Quartz Composer when rendering of the composition stops: perform any required cleanup for the plug-in.
*/
}
#pragma mark -
#pragma mark Misc
// Private method in super class - here to prevent compiler warnings
- (id) patch
{
return [super patch];
}
@end