-
Notifications
You must be signed in to change notification settings - Fork 11
/
TSService.m
695 lines (546 loc) · 29.6 KB
/
TSService.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
//
// TSService.m
// ThisService
//
// Created by Jesper on 2011-07-20.
// Copyright 2011-2012 waffle software. All rights reserved.
// BSD licensed - see license.txt for more information.
//
#import "TSService.h"
#import "IconFamily.h"
#import "TSServiceInputRules.h"
#import "NDAlias.h"
#import "NDAlias+AliasFile.h"
#import "TSServiceTester.h"
#define ThisServiceServiceVersion @"2"
@implementation TSService
+ (NSString *)stringByCleansingString:(NSString *)string fromCharactersNotInSet:(NSCharacterSet *)set {
NSScanner *cleanseScanner = [NSScanner scannerWithString:string];
[cleanseScanner setCharactersToBeSkipped:[set invertedSet]];
NSString *cleansedName = @"";
NSString *cleansedChunk = nil;
while (!([cleanseScanner isAtEnd])) {
[cleanseScanner scanUpToCharactersFromSet:set intoString:NULL];
[cleanseScanner scanCharactersFromSet:set intoString:&cleansedChunk];
cleansedName = [cleansedName stringByAppendingString:cleansedChunk];
cleansedChunk = nil;
}
return cleansedName;
}
+ (NSString *)camelCize:(NSString *)name {
NSString *orig = name;
NSArray *comps = [orig componentsSeparatedByString:@" "];
NSMutableString *cc = [[comps objectAtIndex:0] mutableCopy];
if ([comps count] > 1) {
int i = 1;
for (i = 1; i < [comps count]; i++) [cc appendString:[[comps objectAtIndex:i] capitalizedString]];
}
return [cc autorelease];
}
+ (NSString *)cleanseName:(NSString *)name {
static NSCharacterSet *cleansingSet = nil;
if (cleansingSet == nil) {
NSMutableCharacterSet *mcs = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[mcs addCharactersInString:@" "];
cleansingSet = [mcs copy];
[mcs release];
}
return [self camelCize:[self stringByCleansingString:name fromCharactersNotInSet:cleansingSet]];
}
- (NSTimeInterval)effectiveTimeout {
return timeoutInSeconds ? [timeoutInSeconds doubleValue] : 30;
}
+ (NSString *)sanitizeName:(NSString *)name {
static NSCharacterSet *sanitizedSet = nil;
if (sanitizedSet == nil) {
sanitizedSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "] retain];
}
return [self camelCize:[self stringByCleansingString:name fromCharactersNotInSet:sanitizedSet]];
}
- (BOOL)supportsInput {
return (serviceType == TSServiceInputOnlyType || serviceType == TSServiceFilterType);
}
- (BOOL)supportsOutput {
return (serviceType == TSServiceOutputOnlyType || serviceType == TSServiceFilterType);
}
- (id)initWithServiceName:(NSString *)serviceName_
serviceFileName:(NSString *)serviceFileName_
executableName:(NSString *)executableName_
infoPlistDictionary:(NSDictionary *)infoPlistDictionary_
serviceIcon:(IconFamily *)serviceIcon_
serviceType:(TSServiceType)serviceType_
scriptReferenceType:(TSServiceScriptReferenceType)scriptReferenceType_
allInputRules:(NSArray *)allInputRules_
timeoutInSeconds:(NSNumber *)timeoutInSeconds_
serviceFileWrapper:(NSFileWrapper *)serviceFileWrapper_
pathToScriptInFileWrapper:(NSString *)pathToScriptInFileWrapper_
pathToScriptOutsideService:(NSString *)pathToScriptOutsideService_
existingServiceURL:(NSURL *)existingServiceURL_ {
self = [super init];
if (self != nil) {
serviceName = [serviceName_ retain];
serviceFileName = [serviceFileName_ retain];
executableName = [executableName_ retain];
infoPlistDictionary = [infoPlistDictionary_ retain];
serviceIcon = [serviceIcon_ retain];
serviceType = serviceType_;
scriptReferenceType = scriptReferenceType_;
allInputRules = [allInputRules_ retain];
timeoutInSeconds = [timeoutInSeconds_ retain];
serviceFileWrapper = [serviceFileWrapper_ retain];
pathToScriptInFileWrapper = [pathToScriptInFileWrapper_ retain];
pathToScriptOutsideService = [pathToScriptOutsideService_ retain];
existingServiceURL = [existingServiceURL_ retain];
}
return self;
}
+ (TSService *)serviceAtURL:(NSURL *)serviceURL {
if (![serviceURL isFileURL]) return nil;
NSString *path = [serviceURL path];
if (![[path pathExtension] isEqualToString:@"service"]) return nil;
NSFileManager *fm = [NSFileManager defaultManager];
NSString *contentsPath = [path stringByAppendingPathComponent:@"Contents"];
BOOL isDir;
if (![fm fileExistsAtPath:contentsPath isDirectory:&isDir] || !isDir) return nil;
NSString *infoPlistPath = [contentsPath stringByAppendingPathComponent:@"Info.plist"];
if (![fm fileExistsAtPath:infoPlistPath isDirectory:&isDir] || isDir) return nil;
NSString *macOSFolderPath = [contentsPath stringByAppendingPathComponent:@"MacOS"];
if (![fm fileExistsAtPath:macOSFolderPath isDirectory:&isDir] || !isDir) return nil;
NSString *resourcesFolderPath = [contentsPath stringByAppendingPathComponent:@"Resources"];
if (![fm fileExistsAtPath:resourcesFolderPath isDirectory:&isDir] || !isDir) return nil;
NSFileWrapper *serviceFileWrapper = [[[NSFileWrapper alloc] initWithPath:path] autorelease];
if (!serviceFileWrapper || ![serviceFileWrapper isDirectory]) return nil;
NSFileWrapper *contentsFileWrapper = (NSFileWrapper *)[[serviceFileWrapper fileWrappers] objectForKey:@"Contents"];
if (!contentsFileWrapper || ![contentsFileWrapper isKindOfClass:[NSFileWrapper class]] || ![contentsFileWrapper isDirectory]) return nil;
NSFileWrapper *macOSFileWrapper = (NSFileWrapper *)[[contentsFileWrapper fileWrappers] objectForKey:@"MacOS"];
if (!macOSFileWrapper || ![macOSFileWrapper isKindOfClass:[NSFileWrapper class]] || ![macOSFileWrapper isDirectory]) return nil;
NSFileWrapper *resourcesFileWrapper = (NSFileWrapper *)[[contentsFileWrapper fileWrappers] objectForKey:@"Resources"];
if (!resourcesFileWrapper || ![resourcesFileWrapper isKindOfClass:[NSFileWrapper class]] || ![resourcesFileWrapper isDirectory]) return nil;
NSFileWrapper *infoPlistFileWrapper = (NSFileWrapper *)[[contentsFileWrapper fileWrappers] objectForKey:@"Info.plist"];
if (!infoPlistFileWrapper || ![infoPlistFileWrapper isKindOfClass:[NSFileWrapper class]] || ![infoPlistFileWrapper isRegularFile]) return nil;
NSString *deserializeError = nil;
id plist = [NSPropertyListSerialization propertyListFromData:[infoPlistFileWrapper regularFileContents] mutabilityOption:NSPropertyListMutableContainersAndLeaves format:NULL errorDescription:&deserializeError];
if (deserializeError != nil) {
[deserializeError release];
return nil;
}
if (!plist || ![plist isKindOfClass:[NSMutableDictionary class]]) {
return nil;
}
NSMutableDictionary *infoPlist = (NSMutableDictionary *)plist;
NSArray *acceptableServiceVersions = [NSArray arrayWithObjects:@"1", @"2", nil];
NSString *serviceVersion = [infoPlist objectForKey:@"ThisServiceServiceVersion"];
if (!serviceVersion || ![serviceVersion isKindOfClass:[NSString class]]) return nil;
if (![acceptableServiceVersions containsObject:serviceVersion]) return nil;
NSArray *services = [infoPlist objectForKey:@"NSServices"];
if (!services || ![services isKindOfClass:[NSArray class]] || [services count] != 1) return nil;
NSMutableDictionary *firstService = [services objectAtIndex:0];
if (!firstService || ![firstService isKindOfClass:[NSMutableDictionary class]]) return nil;
NSArray *mustExistHaveStringsAndNotBeEmpty = [NSArray arrayWithObjects:@"NSMessage", @"NSPortName", @"NSUserData", nil];
NSCharacterSet *white = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSString *mustExistKey in mustExistHaveStringsAndNotBeEmpty) {
id object = [firstService objectForKey:mustExistKey];
if (!object) return nil;
if (![object isKindOfClass:[NSString class]]) return nil;
NSString *str = object;
if ([[str stringByTrimmingCharactersInSet:white] length] == 0) return nil;
}
NSDictionary *menuItemDict = [firstService objectForKey:@"NSMenuItem"];
if (!menuItemDict || ![menuItemDict isKindOfClass:[NSDictionary class]]) return nil;
NSString *menuItemDefault = [menuItemDict objectForKey:@"default"];
if (!menuItemDefault || ![menuItemDefault isKindOfClass:[NSString class]] || [[menuItemDefault stringByTrimmingCharactersInSet:white] length] == 0) return nil;
NSString *serviceName = menuItemDefault;
NSString *singleRecognizedType = @"NSStringPboardType";
NSArray *sendTypes = [firstService objectForKey:@"NSSendTypes"];
NSArray *returnTypes = [firstService objectForKey:@"NSReturnTypes"];
// if (!sendTypes && !returnTypes) return nil;
BOOL acceptsInput = NO;
BOOL producesOutput = NO;
for (id typesArrayObj in [NSArray arrayWithObjects:(sendTypes == nil ? [NSNull null] : sendTypes), (returnTypes == nil ? [NSNull null] : returnTypes), nil]) {
if ([typesArrayObj isEqual:[NSNull null]]) continue;
if (![typesArrayObj isKindOfClass:[NSArray class]]) return nil;
NSArray *typesArray = (NSArray *)typesArrayObj;
if ([typesArray count] != 1) return nil;
id singleTypeObj = [typesArray objectAtIndex:0];
if (![singleTypeObj isKindOfClass:[NSString class]]) return nil;
NSString *singleType = singleTypeObj;
if (![singleType isEqualToString:singleRecognizedType]) return nil;
if (typesArray == sendTypes) {
acceptsInput = YES;
}
if (typesArray == returnTypes) {
producesOutput = YES;
}
}
TSServiceType serviceType = (producesOutput ? (acceptsInput ? TSServiceFilterType : TSServiceOutputOnlyType) : (acceptsInput ? TSServiceInputOnlyType : TSServiceNoInputOutputType));
NSString *origExec = [infoPlist objectForKey:@"CFBundleExecutable"];
if (!origExec || ![origExec isKindOfClass:[NSString class]]) return nil;
NSFileWrapper *origExecWrapper = [[macOSFileWrapper fileWrappers] objectForKey:origExec];
if (!origExecWrapper || ![origExecWrapper isKindOfClass:[NSFileWrapper class]] || ![origExecWrapper isRegularFile]) return nil;
[macOSFileWrapper removeFileWrapper:origExecWrapper];
[macOSFileWrapper addRegularFileWithContents:[NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ServiceSkeleton" ofType:nil]] preferredFilename:origExec];
NSString *refType = [infoPlist objectForKey:@"ServiceSkeletonReferenceType"];
if (refType != nil && [refType isEqualToString:@"ref"]) {
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:[[[path stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:origExec]];
[task setArguments:[NSArray arrayWithObject:@"-THISSERVICE_PRINT_SCRIPT_URL_AND_QUIT"]];
NSPipe *pstdout;
pstdout = [NSPipe pipe];
[task setStandardOutput:pstdout];
NSFileHandle *fileout;
fileout = [pstdout fileHandleForReading];
[task launch];
[task waitUntilExit];
NSData *readdata;
readdata = [fileout readDataToEndOfFile];
[task terminate];
[task release];
NSString *urlstr;
urlstr = [[[[NSString alloc] initWithData:readdata encoding:NSUTF8StringEncoding] autorelease] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// NSLog(@"urlstr: %@", urlstr);
NSURL *url = [NSURL URLWithString:urlstr];
NSString *pathToScript = [url path];
// NSLog(@"path to script: %@", pathToScript);
if (![pathToScript hasSuffix:[[path stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"Resources"]]) {
[resourcesFileWrapper removeFileWrapper:[[resourcesFileWrapper fileWrappers] objectForKey:@"Alias Reference"]];
[resourcesFileWrapper addFileWrapper:[[[NSFileWrapper alloc] initWithPath:pathToScript] autorelease]];
[infoPlist setObject:@"copy" forKey:@"ServiceSkeletonReferenceType"];
[infoPlist removeObjectForKey:@"ServiceSkeletonOriginalScriptPath"];
}
}
// BOOL nulledKeys = NO;
if ([firstService objectForKey:@"NSKeyEquivalent"] != nil) {
[firstService removeObjectForKey:@"NSKeyEquivalent"];
// nulledKeys = YES;
}
id timeout = [infoPlist objectForKey:@"NSTimeout"];
NSNumber *timeoutNumberInSeconds = nil;
if ([timeout isKindOfClass:[NSString class]]) { // yes, this is a string
NSString *timeoutAsString = timeout;
NSInteger timeoutInMilliseconds = [timeoutAsString doubleValue];
timeoutNumberInSeconds = [NSNumber numberWithDouble:timeoutInMilliseconds/1000.0];
}
[plist setObject:ThisServiceServiceVersion forKey:@"ThisServiceServiceVersion"];
NSString *serializeError = nil;
NSData *updatedPlist = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:&serializeError];
if (serializeError != nil) {
[serializeError release];
return nil;
}
[contentsFileWrapper removeFileWrapper:infoPlistFileWrapper];
[contentsFileWrapper addRegularFileWithContents:updatedPlist preferredFilename:@"Info.plist"];
NSString *serviceFileName = [[path lastPathComponent] stringByDeletingPathExtension];
return [[[self alloc] initWithServiceName:serviceName
serviceFileName:serviceFileName
executableName:origExec
infoPlistDictionary:plist
serviceIcon:nil
serviceType:serviceType
scriptReferenceType:TSServiceScriptCopied
allInputRules:nil
timeoutInSeconds:timeoutNumberInSeconds
serviceFileWrapper:serviceFileWrapper
pathToScriptInFileWrapper:nil
pathToScriptOutsideService:nil
existingServiceURL:serviceURL] autorelease];
}
- (NSString *)serviceName {
return serviceName;
}
- (BOOL)renameService:(NSString *)newServiceName {
if ([newServiceName isEqualToString:serviceName]) return YES;
NSFileWrapper *contentsFileWrapper = [[serviceFileWrapper fileWrappers] objectForKey:@"Contents"];
NSFileWrapper *infoPlistFileWrapper = [[contentsFileWrapper fileWrappers] objectForKey:@"Info.plist"];
NSData *infoPlistData = [infoPlistFileWrapper regularFileContents];
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSMutableDictionary *fullInfoPlist = [NSPropertyListSerialization propertyListFromData:infoPlistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDescription];
if (errorDescription) {
[errorDescription release];
return NO;
}
[serviceName release];
serviceName = [newServiceName copy];
NSString *cl = [TSService cleanseName:newServiceName];
NSString *san = [TSService sanitizeName:newServiceName];
[serviceFileName release];
serviceFileName = [[cl stringByAppendingPathExtension:@"service"] retain];
NSString *newExec = [NSString stringWithFormat:@"%@ThisService", san];
[fullInfoPlist setObject:san forKey:@"ServiceSkeletonSuitableExecutableName"];
NSString *origExec = [[fullInfoPlist objectForKey:@"CFBundleExecutable"] retain];
[fullInfoPlist setObject:newExec forKey:@"CFBundleExecutable"];
[fullInfoPlist setObject:[NSString stringWithFormat:@"net.wafflesoftware.ThisService.generated-service.%@", cl] forKey:@"CFBundleIdentifier"];
[fullInfoPlist setObject:[NSString stringWithFormat:@"ThisServiceGeneratedService%@", cl] forKey:@"ServiceSkeletonPortName"];
[infoPlistDictionary release];
infoPlistDictionary = [fullInfoPlist retain];
NSData *infoPlistDataAgain = [NSPropertyListSerialization
dataFromPropertyList:fullInfoPlist
format:format
errorDescription:&errorDescription];
NSFileWrapper *binFW = [[contentsFileWrapper fileWrappers] objectForKey:@"MacOS"];
NSFileWrapper *execFW = [[binFW fileWrappers] objectForKey:origExec];
[origExec release];
NSFileWrapper *execNewFW = [[NSFileWrapper alloc] initRegularFileWithContents:[execFW regularFileContents]];
[execNewFW setIcon:[execFW icon]];
[execNewFW setFileAttributes:[execFW fileAttributes]];
[execNewFW setFilename:newExec];
[execNewFW setPreferredFilename:newExec];
[binFW removeFileWrapper:execFW];
[binFW addFileWrapper:[execNewFW autorelease]];
[contentsFileWrapper removeFileWrapper:infoPlistFileWrapper];
[contentsFileWrapper addRegularFileWithContents:infoPlistDataAgain preferredFilename:@"Info.plist"];
return YES;
}
+ (TSService *)serviceWithServiceName:(NSString *)serviceName
serviceType:(TSServiceType)serviceType
scriptReferenceType:(TSServiceScriptReferenceType)scriptReferenceType
inputRules:(NSArray *)allInputRules
timeoutInSeconds:(NSNumber *)timeoutInSeconds
scriptPath:(NSString *)pathToScript
serviceIcon:(IconFamily *)iconFamily
applicationIDs:(NSSet *)applicationIDs {
NSString *scriptName = [pathToScript lastPathComponent];
NSString *cleansedName = [self cleanseName:serviceName];
NSString *sanitaryName = [self sanitizeName:serviceName];
// NSLog(@"cleansedName: %@; sanitaryName: %@", cleansedName, sanitaryName);
NSFileWrapper *scriptfw = [[NSFileWrapper alloc] initRegularFileWithContents:[NSData dataWithContentsOfFile:pathToScript]];
NSString *executableName = [NSString stringWithFormat:@"%@ThisService", sanitaryName];
NSMutableDictionary *service = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjectsAndKeys:
serviceName, @"default", nil], @"NSMenuItem",
@"doServiceWork", @"NSMessage",
@"ServiceSkeletonMagic", @"NSPortName",
@"", @"NSServiceDescription",
scriptName, @"NSUserData",
nil];
id rulesObj = nil;
if ([allInputRules count] == 1) {
NSMutableDictionary *ctxDict = [[[allInputRules objectAtIndex:0] infoPlistRequiredContextDictionary] mutableCopy];
if ([applicationIDs count] > 0) {
[ctxDict setObject:[applicationIDs allObjects] forKey:@"NSApplicationIdentifier"];
}
rulesObj = [ctxDict autorelease];
} else if ([allInputRules count] > 1) {
NSMutableArray *manyRules = [NSMutableArray array];
for (TSServiceInputRules *rules in allInputRules) {
NSMutableDictionary *ctxDict = [[[rules infoPlistRequiredContextDictionary] mutableCopy] autorelease];
if ([applicationIDs count] > 0) {
[ctxDict setObject:[applicationIDs allObjects] forKey:@"NSApplicationIdentifier"];
}
[manyRules addObject:ctxDict];
}
rulesObj = manyRules;
}
if (rulesObj) {
[service setObject:rulesObj forKey:@"NSRequiredContext"];
} else {
id ctxObj = [NSArray array];
if ([applicationIDs count] > 0) {
ctxObj = [NSDictionary dictionaryWithObject:[applicationIDs allObjects] forKey:@"NSApplicationIdentifier"];
}
[service setObject:ctxObj forKey:@"NSRequiredContext"];
}
if (serviceType == TSServiceInputOnlyType || serviceType == TSServiceFilterType) {
[service setObject:[NSArray arrayWithObject:@"NSStringPboardType"]
forKey:@"NSSendTypes"];
}
if (serviceType == TSServiceOutputOnlyType || serviceType == TSServiceFilterType) {
[service setObject:[NSArray arrayWithObject:@"NSStringPboardType"]
forKey:@"NSReturnTypes"];
}
if (timeoutInSeconds) {
NSTimeInterval ti = [timeoutInSeconds integerValue] * 1000;
if (ti >= 1) {
[service setObject:[NSString stringWithFormat:@"%llu", (unsigned long long)ti] forKey:@"NSTimeout"];
} else {
timeoutInSeconds = nil;
}
}
BOOL isRefService = scriptReferenceType == TSServiceScriptReferenced;
NSString *refType = (isRefService ? @"ref" : @"copy");
NSMutableDictionary *infoplist = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"English", @"CFBundleDevelopmentRegion",
executableName, @"CFBundleExecutable",
// serviceName, @"CFBundleDisplayName", doesn't actually do anything
[NSString stringWithFormat:@"net.wafflesoftware.ThisService.generated-service.%@", cleansedName], @"CFBundleIdentifier",
[NSString stringWithFormat:@"ThisServiceGeneratedService%@", cleansedName], @"ServiceSkeletonPortName",
sanitaryName, @"ServiceSkeletonSuitableExecutableName",
refType, @"ServiceSkeletonReferenceType",
ThisServiceServiceVersion, @"ThisServiceServiceVersion",
@"6.0", @"CFBundleInfoDictionaryVersion",
@"APPL", @"CFBundlePackageType",
@"", @"CFBundleSignature",
@"1.0", @"CFBundleVersion",
@"1", @"NSBGOnly",
@"NSApplication", @"NSPrincipalClass",
[NSArray arrayWithObject:service], @"NSServices",
nil];
if (isRefService)
[infoplist setObject:pathToScript forKey:@"ServiceSkeletonOriginalScriptPath"];
BOOL hasIcon = (iconFamily != nil);
NSString *iconFileName = nil;
if (hasIcon) {
iconFileName = [[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"icns"];
[infoplist setObject:iconFileName forKey:@"CFBundleIconFile"];
}
NSString *failure = nil;
NSFileWrapper *infoplistfw = [[NSFileWrapper alloc] initRegularFileWithContents:
[NSPropertyListSerialization dataFromPropertyList:infoplist format:NSPropertyListXMLFormat_v1_0 errorDescription:&failure]];
if (failure) [failure release];
NSFileWrapper *serviceSkeletonfw = [[NSFileWrapper alloc] initRegularFileWithContents:[NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ServiceSkeleton" ofType:nil]]];
NSFileWrapper *macosfw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:[NSDictionary dictionaryWithObject:[serviceSkeletonfw autorelease] forKey:executableName]];
NSFileWrapper *resourcefw = nil;
NSString *pathToScriptInFileWrapper = nil;
if (isRefService) {
resourcefw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:[NSDictionary dictionary]];
} else {
resourcefw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:[NSDictionary dictionaryWithObject:scriptfw forKey:scriptName]];
pathToScriptInFileWrapper = [[@"Contents" stringByAppendingPathComponent:@"Resources"] stringByAppendingPathComponent:scriptName];
}
[scriptfw release];
NSDictionary *contentsFileWrappers = [NSDictionary dictionaryWithObjectsAndKeys:
infoplistfw, @"Info.plist",
resourcefw, @"Resources",
macosfw, @"MacOS",
nil];
[infoplistfw release];
[resourcefw release];
[macosfw release];
if (hasIcon) {
NSData *icns = [iconFamily data];
[resourcefw addRegularFileWithContents:icns preferredFilename:iconFileName];
}
NSFileWrapper *contentsfw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:contentsFileWrappers];
NSFileWrapper *fw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:[NSDictionary dictionaryWithObject:[contentsfw autorelease] forKey:@"Contents"]];
NSString *serviceFileName = [cleansedName stringByAppendingPathExtension:@"service"];
return [[[self alloc] initWithServiceName:serviceName
serviceFileName:serviceFileName
executableName:executableName
infoPlistDictionary:infoplist
serviceIcon:iconFamily
serviceType:serviceType
scriptReferenceType:scriptReferenceType
allInputRules:allInputRules
timeoutInSeconds:timeoutInSeconds
serviceFileWrapper:[fw autorelease]
pathToScriptInFileWrapper:pathToScriptInFileWrapper
pathToScriptOutsideService:pathToScript
existingServiceURL:nil] autorelease];
}
-(NSURL *)existingServiceURL {
return existingServiceURL;
}
- (void)writeReferenceAliasForServiceAtURL:(NSURL *)serviceURL {
if (scriptReferenceType != TSServiceScriptReferenced) return;
NSString *pathToService = [serviceURL path];
NSString *pathToScript = pathToScriptOutsideService;
NSString *pathToAlias = [[[pathToService stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"Resources"] stringByAppendingPathComponent:@"Alias Reference"];
NDAlias *alias = [NDAlias aliasWithURL:[NSURL fileURLWithPath:pathToScript]];
[alias writeToFile:pathToAlias];
}
- (NSString *)pathToScriptOutsideService {
return pathToScriptOutsideService;
}
- (BOOL)freshenScriptInFileWrapperWrittenAtURL:(NSURL *)serviceURL {
if (!pathToScriptInFileWrapper) return YES; // reference script is always fresh
if (!pathToScriptOutsideService) return YES;
NSString *pathToService = [serviceURL path];
NSString *pathToScriptDestination = [pathToService stringByAppendingPathComponent:pathToScriptInFileWrapper];
NSString *pathToScriptOrigin = pathToScriptOutsideService;
NSFileManager *fm = [NSFileManager defaultManager];
NSError *copyingError = nil;
if (![pathToScriptDestination hasPrefix:pathToService]) {
NSLog(@"destination script is not in service bundle, wtf? dest: %@, service: %@", pathToScriptDestination, pathToService);
return NO;
}
[fm removeItemAtPath:pathToScriptDestination error:NULL];
if (![fm copyItemAtPath:pathToScriptOrigin toPath:pathToScriptDestination error:©ingError]) {
NSLog(@"Could not freshen script! %@", copyingError);
return NO;
}
NSArray *pathComponents = [pathToScriptInFileWrapper componentsSeparatedByString:@"/"];
NSFileWrapper *currentFileWrapper = serviceFileWrapper;
NSFileWrapper *prevFileWrapper = nil;
for (NSString *pathComponent in pathComponents) {
NSFileWrapper *subWrapper = [[currentFileWrapper fileWrappers] objectForKey:pathComponent];
prevFileWrapper = currentFileWrapper;
currentFileWrapper = subWrapper;
}
NSLog(@"prev file wrapper %@", prevFileWrapper);
NSLog(@"current file wrapper %@", currentFileWrapper);
NSString *preferredFilename = [currentFileWrapper preferredFilename];
[prevFileWrapper removeFileWrapper:currentFileWrapper];
[prevFileWrapper addRegularFileWithContents:[NSData dataWithContentsOfFile:pathToScriptOrigin] preferredFilename:preferredFilename];
return YES;
}
- (void)installServiceAfterFileWrapperWrittenAtURL:(NSURL *)serviceURL {
NSString *pathToService = [serviceURL path];
NSDictionary *fileAttributesToSet = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0775] forKey:NSFilePosixPermissions];
NSString *pathToExecutable = [[[pathToService stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:executableName];
[[NSFileManager defaultManager] setAttributes:fileAttributesToSet ofItemAtPath:pathToExecutable error:NULL];
NSTask *quicklyOpen = [[NSTask alloc] init];
[quicklyOpen setLaunchPath:[[[pathToService stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:executableName]];
[quicklyOpen setArguments:[NSArray arrayWithObject:@"-THISSERVICE_REGISTER_SERVICE"]];
[quicklyOpen launch];
[quicklyOpen waitUntilExit]; // it'll exit on its own
// [quicklyOpen terminate];
[quicklyOpen release];
}
- (TSServiceTester *)testRunServiceAfterFileWrapperWrittenAtURL:(NSURL *)serviceURL {
NSString *pathToService = [serviceURL path];
NSDictionary *fileAttributesToSet = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0775] forKey:NSFilePosixPermissions];
NSString *pathToExecutable = [[[pathToService stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:executableName];
[[NSFileManager defaultManager] setAttributes:fileAttributesToSet ofItemAtPath:pathToExecutable error:NULL];
NSString *launchPath =[[[pathToService stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:executableName];
TSServiceTester *tester = [[TSServiceTester alloc] initWithServiceLaunchPath:launchPath service:self testServiceURL:serviceURL];
return [tester autorelease];
}
- (NSString *)serviceFileName {
return serviceFileName;
}
- (NSFileWrapper *)upgradedServiceFileWrapper {
return serviceFileWrapper;
}
- (void) dealloc
{
[serviceName release];
[serviceFileName release];
[executableName release];
[infoPlistDictionary release];
[serviceIcon release];
[allInputRules release];
[serviceFileWrapper release];
[pathToScriptInFileWrapper release];
[pathToScriptOutsideService release];
[super dealloc];
}
// key is NSString * (local file name), value is TSService *.
+ (NSDictionary *)allServicesInUserBoundary {
@try {
NSString *pathToServicesFolder = [@"~/Library/Services" stringByExpandingTildeInPath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *folderenum = [fm contentsOfDirectoryAtPath:pathToServicesFolder error:NULL];
NSMutableDictionary *d = [NSMutableDictionary dictionary];
for (NSString *filename in folderenum) {
if (![[filename pathExtension] isEqualToString:@"service"]) continue;
NSString *fullPath = [pathToServicesFolder stringByAppendingPathComponent:filename];
BOOL isDir;
if (![fm fileExistsAtPath:fullPath isDirectory:&isDir] || !isDir) continue;
// NSLog(@"found service %@", fullPath);
TSService *service = [TSService serviceAtURL:[NSURL fileURLWithPath:fullPath]];
if (!service) {
// NSLog(@" - not eligible");
continue;
} else {
// NSLog(@" + eligible");
}
[d setObject:service forKey:filename];
}
return [[d copy] autorelease];
}
@catch (NSException *exception) {
NSLog(@"encountered error finding out services in user boundary: %@", exception);
return [NSDictionary dictionary];
}
}
@end