aboutsummaryrefslogtreecommitdiff
path: root/Foundation/GTMNSAppleScript+Handler.m
blob: d3eeffd8497d76facba6252a60f9d870b0f1ede9 (plain)
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
//
//  NSAppleScript+Handler.m
//
//  Copyright 2008 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
// 
//  http://www.apache.org/licenses/LICENSE-2.0
// 
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import <Carbon/Carbon.h>
#import "GTMNSAppleScript+Handler.h"
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMNSAppleEventDescriptor+Handler.h"
#import "GTMFourCharCode.h"
#import "GTMMethodCheck.h"

// Some private methods that we need to call
@interface NSAppleScript (NSPrivate)
+ (ComponentInstance)_defaultScriptingComponent;
- (OSAID) _compiledScriptID;
- (id)_initWithData:(NSData*)data error:(NSDictionary**)error;
@end

@interface NSMethodSignature (NSPrivate)
+ (id)signatureWithObjCTypes:(const char *)fp8;
@end

@implementation NSAppleScript(GTMAppleScriptHandlerAdditions)
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_descriptorWithPositionalHandler:parametersArray:);  // COV_NF_LINE
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_descriptorWithLabeledHandler:labels:parameters:count:);  // COV_NF_LINE
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_registerSelector:forTypes:count:);  // COV_NF_LINE

+ (void)load {
  DescType types[] = { 
    typeScript
  };
  
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  [NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_scriptValue)
                                      forTypes:types
                                         count:sizeof(types)/sizeof(DescType)];
  
  DescType types2[] = { 
    'evnt'  // No type code for this one
  };
  
  [NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_eventValue)
                                      forTypes:types2
                                         count:sizeof(types2)/sizeof(DescType)];
  [pool release];
}

- (OSAID)gtm_realIDAndComponent:(ComponentInstance*)component {
  if (![self isCompiled]) {
    NSDictionary *error;
    if (![self compileAndReturnError:&error]) {
      _GTMDevLog(@"Unable to compile script: %@ %@", self, error);
      return kOSANullScript;
    }
  }
  OSAID genericID = [self _compiledScriptID];
  ComponentInstance genericComponent = [NSAppleScript _defaultScriptingComponent];
  OSAError err = OSAGenericToRealID(genericComponent, &genericID, component);
  if (err) {
    _GTMDevLog(@"Unable to get real id script: %@ %@", self, err); // COV_NF_LINE
    genericID = kOSANullScript; // COV_NF_LINE
  }
  return genericID;
}

- (NSAppleEventDescriptor*)gtm_executePositionalHandler:(NSString*)handler 
                                             parameters:(NSArray*)params 
                                                  error:(NSDictionary**)error {
  NSAppleEventDescriptor *event 
    = [NSAppleEventDescriptor gtm_descriptorWithPositionalHandler:handler 
                                                  parametersArray:params];
  return [self executeAppleEvent:event error:error];
} 

- (NSAppleEventDescriptor*)gtm_executeLabeledHandler:(NSString*)handler
                                              labels:(AEKeyword*)labels
                                          parameters:(id*)params
                                               count:(NSUInteger)count
                                               error:(NSDictionary **)error {
  NSAppleEventDescriptor *event 
    = [NSAppleEventDescriptor gtm_descriptorWithLabeledHandler:handler 
                                                        labels:labels
                                                    parameters:params
                                                         count:count];
  return [self executeAppleEvent:event error:error];
} 

- (NSSet*)gtm_handlers {
  AEDescList names = { typeNull, NULL };
  NSArray *array = nil;
  ComponentInstance component;
  OSAID osaID = [self gtm_realIDAndComponent:&component];
  OSAError err = OSAGetHandlerNames(component, kOSAModeNull, osaID, &names);
  if (!err) {
    NSAppleEventDescriptor *desc 
      = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&names] autorelease];
    array = [desc gtm_objectValue];
  }
  if (err) {
    _GTMDevLog(@"Error getting handlers: %d", err);
  }
  return [NSSet setWithArray:array];
}

- (NSSet*)gtm_properties {
  AEDescList names = { typeNull, NULL };
  NSArray *array = nil;
  ComponentInstance component;
  OSAID osaID = [self gtm_realIDAndComponent:&component];
  OSAError err = OSAGetPropertyNames(component, kOSAModeNull, osaID, &names);
  if (!err) {
    NSAppleEventDescriptor *desc 
      = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&names] autorelease];
    array = [desc gtm_objectValue];
  }
  if (err) {
    _GTMDevLog(@"Error getting properties: %d", err);
  }
  return [NSSet setWithArray:array];
}

- (BOOL)gtm_setValue:(id)value forProperty:(NSString*)property {
  BOOL wasGood = NO;
  NSAppleEventDescriptor *desc = [value gtm_appleEventDescriptor];
  NSAppleEventDescriptor *propertyName = [property gtm_appleEventDescriptor];
  OSAError error = paramErr;
  if (desc && propertyName) {
    OSAID valueID = kOSANullScript;
    ComponentInstance component;
    OSAID scriptID = [self gtm_realIDAndComponent:&component];
    error = OSACoerceFromDesc(component,
                              [desc aeDesc], 
                              kOSAModeNull, 
                              &valueID);
    if (!error) {
      error = OSASetProperty(component, kOSAModeNull, 
                             scriptID, [propertyName aeDesc], valueID); 
      if (!error) {
        wasGood = YES;
      }
    }
  }
  if (!wasGood) {
    _GTMDevLog(@"Unable to setValue:%@ forProperty:%@ from %@ (%d)", 
               value, property, self, error);
  }
  return wasGood;
}

- (id)gtm_valueForProperty:(NSString*)property {
  id value = nil;
  NSAppleEventDescriptor *propertyName = [property gtm_appleEventDescriptor];
  OSAError error = paramErr;
  if (propertyName) {
    ComponentInstance component;
    OSAID scriptID = [self gtm_realIDAndComponent:&component];
    OSAID valueID = kOSANullScript;
    error = OSAGetProperty(component, 
                           kOSAModeNull, 
                           scriptID, 
                           [propertyName aeDesc], 
                           &valueID);
    if (!error) {
      AEDesc aeDesc;
      error = OSACoerceToDesc(component, 
                              valueID, 
                              typeWildCard, 
                              kOSAModeNull, 
                              &aeDesc);
      if (!error) {
        NSAppleEventDescriptor *desc 
        = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&aeDesc] autorelease];
        value = [desc gtm_objectValue];
      }
    }
  }
  if (error) {
    _GTMDevLog(@"Unable to get valueForProperty:%@ from %@ (%d)", 
               property, self, error);
  }
  return value;
}

- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
  ComponentInstance component;
  OSAID osaID = [self gtm_realIDAndComponent:&component];
  AEDesc result = { typeNull, NULL };
  NSAppleEventDescriptor *desc = nil;
  OSAError err = OSACoerceToDesc(component, 
                                 osaID, 
                                 typeScript,
                                 kOSAModeNull,
                                 &result);
  if (!err) {
    desc = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&result] autorelease];
  } else {
    _GTMDevLog(@"Unable to coerce script %d", err);  // COV_NF_LINE
  }
  return desc;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
  NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
  if (!signature) {
    NSMutableString *types = [NSMutableString stringWithString:@"@@:"];
    NSString *selName = NSStringFromSelector(aSelector);
    NSArray *selArray = [selName componentsSeparatedByString:@":"];
    NSUInteger count = [selArray count];
    for (NSUInteger i = 1; i < count; i++) {
      [types appendString:@"@"];
    }
    signature = [NSMethodSignature signatureWithObjCTypes:[types UTF8String]];    
  }
  return signature;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
  SEL sel = [invocation selector];
  NSMutableString *handlerName = [NSStringFromSelector(sel) mutableCopy];
  NSUInteger handlerOrigLength = [handlerName length];
  [handlerName replaceOccurrencesOfString:@":" 
                               withString:@""
                                  options:0
                                    range:NSMakeRange(0,handlerOrigLength)];
  NSUInteger argCount = handlerOrigLength - [handlerName length];
  NSMutableArray *args = [NSMutableArray arrayWithCapacity:argCount];
  for (NSUInteger i = 0; i < argCount; ++i) {
    id arg;
    // +2 to ignore _sel and _cmd
    [invocation getArgument:&arg atIndex:i + 2];
    [args addObject:arg];
  }
  NSDictionary *error = nil;
  NSAppleEventDescriptor *desc = [self gtm_executePositionalHandler:handlerName 
                                                         parameters:args 
                                                              error:&error];  
  if ([[invocation methodSignature] methodReturnLength] > 0) {
    id returnValue = [desc gtm_objectValue];
    [invocation setReturnValue:&returnValue];
  }
}
@end

@implementation NSAppleEventDescriptor(GMAppleEventDescriptorScriptAdditions)

- (NSAppleScript*)gtm_scriptValue {
  NSDictionary *error;
  NSAppleScript *script = [[[NSAppleScript alloc] _initWithData:[self data] 
                                                          error:&error] autorelease];
  if (!script) {
    _GTMDevLog(@"Unable to create script: %@", error);  // COV_NF_LINE
  }
  return script;
}

- (NSString*)gtm_eventValue {
  struct AEEventRecordStruct {
    AEEventClass eventClass;
    AEEventID eventID;
  };
  NSData *data = [self data];
  const struct AEEventRecordStruct *record 
    = (const struct AEEventRecordStruct*)[data bytes];
  NSString *eClass = [GTMFourCharCode stringWithFourCharCode:record->eventClass];
  NSString *eID = [GTMFourCharCode stringWithFourCharCode:record->eventID];
  return [eClass stringByAppendingString:eID];
}
@end