-
Notifications
You must be signed in to change notification settings - Fork 17
/
TLMLaunchAgentController.m
437 lines (360 loc) · 16.8 KB
/
TLMLaunchAgentController.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
//
// TLMLaunchAgentController.m
// TeX Live Utility
//
// Created by Adam R. Maxwell on 10/07/10.
/*
This software is Copyright (c) 2010-2016
Adam Maxwell. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
- Neither the name of Adam Maxwell nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "TLMLaunchAgentController.h"
#import "TLMLogServer.h"
#import "TLMTask.h"
#import "TLMAuthorizedOperation.h"
#import "TLMReadWriteOperationQueue.h"
#import "TLMEnvironment.h"
enum {
TLMScheduleMatrixNever = 0,
TLMScheduleMatrixWeekly = 1,
TLMScheduleMatrixDaily = 2
};
@interface TLMLaunchAgentController ()
@property (nonatomic, copy) NSString *propertyListPath;
@end
@implementation TLMLaunchAgentController
@synthesize _scheduleMatrix;
@synthesize _dayField;
@synthesize _datePicker;
@synthesize propertyListPath =_propertyListPath;
#define PLIST_NAME @"com.googlecode.mactlmgr.update_check"
#define UPDATE_CHECK_EXECUTABLE @"texliveupdatecheck"
#define AGENT_INSTALLER_SCRIPT @"agent_installer"
static NSString *__TLMPlistPath(NSSearchPathDomainMask domain)
{
NSString *baseDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, domain, YES) lastObject];
return [[[baseDir stringByAppendingPathComponent:@"LaunchAgents"] stringByAppendingPathComponent:PLIST_NAME] stringByAppendingPathExtension:@"plist"];
}
static NSDictionary * __TLMGetPlist(BOOL *isInstalled, BOOL *allUsers, NSString **outPath)
{
NSString *plistPath;
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMPlistPath(NSLocalDomainMask)]) {
if (isInstalled) *isInstalled = YES;
if (allUsers) *allUsers = YES;
plistPath = __TLMPlistPath(NSLocalDomainMask);
}
else if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMPlistPath(NSUserDomainMask)]) {
if (isInstalled) *isInstalled = YES;
if (allUsers) *allUsers = NO;
plistPath = __TLMPlistPath(NSUserDomainMask);
}
else {
if (isInstalled) *isInstalled = NO;
if (allUsers) *allUsers = NO;
plistPath = [[NSBundle mainBundle] pathForResource:PLIST_NAME ofType:@"plist"];
}
if (outPath) *outPath = plistPath;
return [NSDictionary dictionaryWithContentsOfFile:plistPath];
}
static NSString * __TLMGetTemporaryDirectory()
{
static NSString *tmpDir = nil;
if (nil == tmpDir)
tmpDir = [[NSTemporaryDirectory() stringByAppendingPathComponent:@"TLMLaunchAgentController"] copy];
return tmpDir;
}
+ (void)_removeTemporaryDirectory:(NSNotification *)aNote
{
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMGetTemporaryDirectory() isDirectory:&isDir] && isDir)
[[NSFileManager defaultManager] removeItemAtPath:__TLMGetTemporaryDirectory() error:NULL];
}
+ (void)initialize
{
if (self == [TLMLaunchAgentController class]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_removeTemporaryDirectory:)
name:NSApplicationWillTerminateNotification
object:nil];
}
}
+ (BOOL)_agentInstalled:(NSSearchPathDomainMask *)outDomains;
{
NSSearchPathDomainMask domains = 0;
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMPlistPath(NSLocalDomainMask)]) {
domains |= NSLocalDomainMask;
}
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMPlistPath(NSUserDomainMask)]) {
domains |= NSUserDomainMask;
}
if (outDomains) *outDomains = domains;
return (domains != 0);
}
+ (BOOL)agentInstalled { return [self _agentInstalled:NULL]; }
+ (NSString *)agentInstallerScriptInBundle;
{
return [[NSBundle mainBundle] pathForResource:AGENT_INSTALLER_SCRIPT ofType:@"py"];
}
+ (NSString *)updatecheckerExecutableInBundle;
{
return [[NSBundle mainBundle] pathForAuxiliaryExecutable:UPDATE_CHECK_EXECUTABLE];
}
+ (BOOL)migrateLocalToUserIfNeeded;
{
NSSearchPathDomainMask domains;
BOOL ret = NO;
if ([self _agentInstalled:&domains] && (domains & NSLocalDomainMask)) {
NSMutableArray *options = [NSMutableArray array];
TLMOperation *copyOperation = nil;
// untested with new update checker; I'm almost certain this will never get hit, but just in case...
if ((domains & NSUserDomainMask) == 0) {
// have to copy local to user before removing the local one
NSString *installerScriptPath = [self agentInstallerScriptInBundle];
[options addObject:installerScriptPath];
[options addObject:@"--install"];
[options addObject:@"--plist"];
[options addObject:__TLMPlistPath(NSLocalDomainMask)];
[options addObject:@"--script"];
[options addObject:[self updatecheckerExecutableInBundle]];
copyOperation = [[TLMOperation alloc] initWithCommand:[TLMEnvironment internalPythonInterpreterPath] options:options];
}
// always remove the local agent
[options removeAllObjects];
[options addObject:[[NSBundle mainBundle] pathForResource:@"uninstall_local_agent" ofType:@"sh"]];
TLMAuthorizedOperation *removeOperation = [[TLMAuthorizedOperation alloc] initWithAuthorizedCommand:@"/bin/sh" options:options];
if (copyOperation) {
[removeOperation addDependency:copyOperation];
[[TLMReadWriteOperationQueue defaultQueue] addOperation:copyOperation];
}
[[TLMReadWriteOperationQueue defaultQueue] addOperation:removeOperation];
[copyOperation release];
[removeOperation release];
ret = YES;
}
return ret;
}
static CGFloat __TLMExecutableVersionAtPath(NSString *absolutePath)
{
#if 0
NSString *parent = [absolutePath stringByDeletingLastPathComponent];
NSString *script = [NSString stringWithFormat:@"import sys; sys.path.append(\"%@\"); import update_check as uc; sys.stdout.write(str(uc.VERSION))", parent];
TLMTask *task = [[TLMTask new] autorelease];
[task setLaunchPath:[TLMEnvironment internalPythonInterpreterPath]];
[task setArguments:[NSArray arrayWithObjects:@"-B", @"-c", script, nil]];
[task launch];
[task waitUntilExit];
CGFloat version = 0;
if ([task terminationStatus] == 0) {
version = [[task outputString] floatValue];
}
else {
TLMLog(__func__, @"Failed to get version of script at %@", absolutePath);
}
return version;
#endif
NSURL *scriptURL = [NSURL fileURLWithPath:absolutePath];
NSDictionary *bundleInfo = [(NSDictionary *)CFBundleCopyInfoDictionaryForURL((CFURLRef)scriptURL) autorelease];
// this always needs to be a simple float, although just testing string inequality would be fine
return bundleInfo ? [[bundleInfo objectForKey:(id)kCFBundleVersionKey] floatValue] : -1.0;
}
+ (NSString *)pathOfUpdatedAgentForVenturaStupidity;
{
TLMLog(__func__, @"Checking to see if we need to rewrite the launch agent plist because Ventura sucks.");
BOOL isInstalled, allUsers;
NSString *plistPath;
NSMutableDictionary *plist = [[__TLMGetPlist(&isInstalled, &allUsers, &plistPath) mutableCopy] autorelease];
if (NO == isInstalled) return nil;
// key exists, nothing to do
if ([plist objectForKey:@"AssociatedBundleIdentifiers"]) return nil;
NSArray *identifiers = [NSArray arrayWithObjects:@"com.googlecode.mactlmgr.tlu", @"com.github.amaxwell.tlutility.texliveupdatecheck", nil];
[plist setObject:identifiers forKey:@"AssociatedBundleIdentifiers"];
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMGetTemporaryDirectory()] == NO)
[[NSFileManager defaultManager] createDirectoryAtPath:__TLMGetTemporaryDirectory() withIntermediateDirectories:YES attributes:nil error:NULL];
/* Write to a temporary file, and return the path so the agent installer can handle unload/install/reload,
or else I have to handle that here in Cocoa. No point in reinventing the wheel again.
*/
plistPath = [[__TLMGetTemporaryDirectory() stringByAppendingPathComponent:PLIST_NAME] stringByAppendingPathExtension:@"plist"];
[[NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL] writeToFile:plistPath atomically:NO];
return plistPath;
}
+ (BOOL)scriptNeedsUpdate;
{
BOOL needsUpdate = NO;
if ([self agentInstalled]) {
NSString *internalScript = [self updatecheckerExecutableInBundle];
CGFloat internalVersion = __TLMExecutableVersionAtPath(internalScript);
NSArray *applicationSupportPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportPath = [[applicationSupportPaths lastObject] stringByAppendingPathComponent:@"TeX Live Utility"];
appSupportPath = [appSupportPath stringByAppendingPathComponent:UPDATE_CHECK_EXECUTABLE];
CGFloat version = __TLMExecutableVersionAtPath(appSupportPath);
if (version < internalVersion) {
TLMLog(__func__, @"Update checker v%1.1f at %@ needs to be updated to v%1.1f", version, [appSupportPath stringByAbbreviatingWithTildeInPath], internalVersion);
needsUpdate = YES;
}
}
return needsUpdate;
}
- (id)init { return [self initWithWindowNibName:[self windowNibName]]; }
- (void)dealloc
{
[_scheduleMatrix release];
[_dayField release];
[_datePicker release];
[_propertyListPath release];
[_gregorianCalendar release];
[super dealloc];
}
- (NSString *)windowNibName { return @"LaunchAgentSheet"; }
#define AGENT_DISABLED ((_status & TLMLaunchAgentEnabled) == 0)
#define AGENT_ENABLED ((_status & TLMLaunchAgentEnabled) != 0)
#define CHECK_WEEKLY ((_status & TLMLaunchAgentDaily) == 0)
- (void)_updateUI
{
if (AGENT_DISABLED) {
[_scheduleMatrix selectCellWithTag:TLMScheduleMatrixNever];
[_dayField setEnabled:NO];
[_datePicker setEnabled:NO];
}
else {
[_datePicker setEnabled:YES];
if (CHECK_WEEKLY) {
[_scheduleMatrix selectCellWithTag:TLMScheduleMatrixWeekly];
[_dayField setEnabled:YES];
}
else {
[_scheduleMatrix selectCellWithTag:TLMScheduleMatrixDaily];
[_dayField setEnabled:NO];
}
}
}
- (void)awakeFromNib
{
if (nil == _gregorianCalendar) {
_gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[_gregorianCalendar setTimeZone:[NSTimeZone localTimeZone]];
}
[[_dayField formatter] setTimeZone:[NSTimeZone localTimeZone]];
BOOL isInstalled, allUsers;
NSString *plistPath;
NSDictionary *plist = __TLMGetPlist(&isInstalled, &allUsers, &plistPath);
// user could have disabled with launchctl, but that's not my problem (yet)
if (isInstalled) _status |= TLMLaunchAgentEnabled;
// need to set from a full date, or the day of week ends up being off by one
NSDateComponents *comps = [_gregorianCalendar components:NSWeekdayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
NSDictionary *intervalDict = [plist objectForKey:@"StartCalendarInterval"];
[comps setHour:[[intervalDict objectForKey:@"Hour"] integerValue]];
[comps setMinute:[[intervalDict objectForKey:@"Minute"] integerValue]];
// only shows hour and minute
[_datePicker setDateValue:[_gregorianCalendar dateFromComponents:comps]];
[_dayField setObjectValue:[_gregorianCalendar dateFromComponents:comps]];
if ([[plist objectForKey:@"StartCalendarInterval"] objectForKey:@"Weekday"]) {
// 0 and 7 are Sunday, according to launchd.plist(5)
NSInteger launchdWeekday = [[intervalDict objectForKey:@"Weekday"] integerValue];
// NSDateComponents thinks that 1 is Sunday, in the Gregorian calendar
NSInteger nsdcWeekday = launchdWeekday + 1;
/*
Compute the offset manually, since NSCalendar returns a crap date if NSDateComponents is specified
with year/month/weekday. I could file a bug report with Apple, but it'll either be "works as designed"
or ignored until NSCalendar is deprecated in favor of something else...
*/
NSInteger currentWeekday = [comps weekday];
NSDateComponents *offsetComponents = [[NSDateComponents new] autorelease];
[offsetComponents setWeekday:(nsdcWeekday - currentWeekday)];
NSDate *weekdayDate = [_gregorianCalendar dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
[_dayField setObjectValue:weekdayDate];
_status &= ~TLMLaunchAgentDaily;
}
else {
_status |= TLMLaunchAgentDaily;
}
[_datePicker sizeToFit];
[self setPropertyListPath:plistPath];
[self _updateUI];
}
- (void)_savePropertyList
{
if ([[NSFileManager defaultManager] fileExistsAtPath:__TLMGetTemporaryDirectory()] == NO)
[[NSFileManager defaultManager] createDirectoryAtPath:__TLMGetTemporaryDirectory() withIntermediateDirectories:YES attributes:nil error:NULL];
// write to a temporary file, and then set that as the property list path
NSString *plistPath = [[__TLMGetTemporaryDirectory() stringByAppendingPathComponent:PLIST_NAME] stringByAppendingPathExtension:@"plist"];
NSMutableDictionary *plist = [NSMutableDictionary dictionary];
[plist addEntriesFromDictionary:__TLMGetPlist(NULL, NULL, NULL)];
NSDateComponents *comps = [_gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:[_datePicker dateValue]];
NSMutableDictionary *interval = [NSMutableDictionary dictionary];
[interval setObject:[NSNumber numberWithInteger:[comps hour]] forKey:@"Hour"];
[interval setObject:[NSNumber numberWithInteger:[comps minute]] forKey:@"Minute"];
if (CHECK_WEEKLY) {
comps = [_gregorianCalendar components:NSWeekdayCalendarUnit fromDate:[_dayField objectValue]];
NSInteger launchdWeekday = [comps weekday] - 1;
[interval setObject:[NSNumber numberWithInteger:launchdWeekday] forKey:@"Weekday"];
}
[plist setObject:interval forKey:@"StartCalendarInterval"];
if ([[NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL] writeToFile:plistPath atomically:NO])
[self setPropertyListPath:plistPath];
}
- (IBAction)enableAction:(id)sender;
{
_status |= TLMLaunchAgentChanged;
switch ([[_scheduleMatrix selectedCell] tag]) {
case TLMScheduleMatrixNever:
_status &= ~TLMLaunchAgentEnabled;
break;
case TLMScheduleMatrixWeekly:
_status &= ~TLMLaunchAgentDaily;
_status |= TLMLaunchAgentEnabled;
break;
case TLMScheduleMatrixDaily:
_status |= TLMLaunchAgentDaily;
_status |= TLMLaunchAgentEnabled;
break;
default:
break;
}
if (AGENT_ENABLED)
[self _savePropertyList];
[self _updateUI];
}
- (IBAction)changeDay:(id)sender;
{
_status |= TLMLaunchAgentChanged;
[self _savePropertyList];
}
- (IBAction)changeTime:(id)sender;
{
_status |= TLMLaunchAgentChanged;
[self _savePropertyList];
}
- (IBAction)cancel:(id)sender;
{
[NSApp endSheet:[self window] returnCode:TLMLaunchAgentCancelled];
}
- (IBAction)accept:(id)sender;
{
if ([[self window] makeFirstResponder:nil])
[NSApp endSheet:[self window] returnCode:_status];
else
NSBeep();
}
@end