forked from amaxwell/tlutility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TLMMainWindowController.m
2202 lines (1876 loc) · 98.2 KB
/
TLMMainWindowController.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
//
// TLMMainWindowController.m
// TeX Live Utility
//
// Created by Adam Maxwell on 12/6/08.
/*
This software is Copyright (c) 2008-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 "TLMMainWindowController.h"
#import "TLMPackage.h"
#import "TLMPackageListDataSource.h"
#import "TLMUpdateListDataSource.h"
#import "TLMInstallDataSource.h"
#import "TLMBackupDataSource.h"
#import "TLMListUpdatesOperation.h"
#import "TLMUpdateOperation.h"
#import "TLMInfraUpdateOperation.h"
#import "TLMPapersizeOperation.h"
#import "TLMAuthorizedOperation.h"
#import "TLMRemoveOperation.h"
#import "TLMInstallOperation.h"
#import "TLMNetInstallOperation.h"
#import "TLMOptionOperation.h"
#import "TLMBackupOperation.h"
#import "TLMBackupListOperation.h"
#import "TLMLoadDatabaseOperation.h"
#import "TLMStatusWindow.h"
#import "TLMInfoController.h"
#import "TLMPreferenceController.h"
#import "TLMLogServer.h"
#import "TLMAppController.h"
#import "TLMPapersizeController.h"
#import "TLMTabView.h"
#import "TLMReadWriteOperationQueue.h"
#import "TLMSizeFormatter.h"
#import "TLMTask.h"
#import "TLMProgressIndicatorCell.h"
#import "TLMAutobackupController.h"
#import "TLMLaunchAgentController.h"
#import "TLMEnvironment.h"
#import "TLMURLFormatter.h"
#import "TLMAddressTextField.h"
#import "TLMDatabase.h"
#import "TLMDatabasePackage.h"
#import "TLMMirrorController.h"
#import "TLMTexdistConfigController.h"
#import "TLMDocumentationController.h"
@interface TLMMainWindowController (Private)
// only declare here if reorganizing the implementation isn't practical
- (void)_refreshCurrentDataSourceIfNeeded;
- (void)_refreshLocalDatabase;
- (void)_displayStatusString:(NSString *)statusString dataSource:(id <TLMListDataSource>)dataSource;
@end
static char _TLMOperationQueueOperationContext;
#define DB_LOAD_STATUS_STRING ([NSString stringWithFormat:@"%@%C", NSLocalizedString(@"Loading Database", @"status message"), TLM_ELLIPSIS])
#define URL_VALIDATE_STATUS_STRING ([NSString stringWithFormat:@"%@%C", NSLocalizedString(@"Validating Server", @"status message"), TLM_ELLIPSIS])
/*
Increment this when/if toolbar configuration changes.
I guess an alternative would be to change the identifier in the nib...
*/
#define TOOLBAR_VERSION ((int)1)
static Class _UserNotificationCenterClass;
static Class _UserNotificationClass;
#ifndef MAC_OS_X_VERSION_10_8
@interface NSUserNotification : NSObject
@property (readwrite, copy) NSString *title;
@end
@interface NSUserNotificationCenter : NSObject
+ (id)defaultUserNotificationCenter;
+ (void)deliverNotification:(NSUserNotification *)note;
@end
#endif
@implementation TLMMainWindowController
@synthesize _progressIndicator;
@synthesize _URLField;
@synthesize _packageListDataSource;
@synthesize _tabView;
@synthesize _updateListDataSource;
@synthesize _installDataSource;
@synthesize infrastructureNeedsUpdate = _infrastructureNeedsUpdate;
@synthesize updatingInfrastructure = _updatingInfrastructure;
@synthesize _backupDataSource;
@synthesize serverURL = _serverURL;
+ (void)initialize
{
_UserNotificationCenterClass = NSClassFromString(@"NSUserNotificationCenter");
_UserNotificationClass = NSClassFromString(@"NSUserNotification");
}
- (id)init
{
return [self initWithWindowNibName:[self windowNibName]];
}
- (id)initWithWindowNibName:(NSString *)windowNibName
{
self = [super initWithWindowNibName:windowNibName];
if (self) {
TLMReadWriteOperationQueue *queue = [TLMReadWriteOperationQueue defaultQueue];
[queue addObserver:self forKeyPath:@"operationCount" options:0 context:&_TLMOperationQueueOperationContext];
_updatingInfrastructure = NO;
_infrastructureNeedsUpdate = NO;
_operationCount = 0;
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"MainWindowToolbarVersion"] != TOOLBAR_VERSION) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NSToolbar Configuration Main window toolbar"];
[[NSUserDefaults standardUserDefaults] setInteger:TOOLBAR_VERSION forKey:@"MainWindowToolbarVersion"];
}
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[TLMReadWriteOperationQueue defaultQueue] removeObserver:self forKeyPath:@"operationCount"];
[_tabView setDelegate:nil];
[_tabView release];
[_URLField release];
[_serverURL release];
[_progressIndicator release];
[_packageListDataSource release];
[_updateListDataSource release];
[_previousInfrastructureVersions release];
[super dealloc];
}
- (void)awakeFromNib
{
[[self window] setTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:(id)kCFBundleNameKey]];
// set delegate before adding tabs, so the datasource gets inserted properly in the responder chain
_currentListDataSource = _updateListDataSource;
[_tabView setDelegate:self];
[_tabView addTabNamed:NSLocalizedString(@"Updates", @"tab title") withView:[[_updateListDataSource tableView] enclosingScrollView]];
[_tabView addTabNamed:NSLocalizedString(@"Packages", @"tab title") withView:[[_packageListDataSource outlineView] enclosingScrollView]];
[_tabView addTabNamed:NSLocalizedString(@"Backups", @"tab title") withView:[[_backupDataSource outlineView] enclosingScrollView]];
if ([[NSUserDefaults standardUserDefaults] boolForKey:TLMEnableNetInstall])
[_tabView addTabNamed:NSLocalizedString(@"Install", @"tab title") withView:[[_installDataSource outlineView] enclosingScrollView]];
// 10.5 release notes say this is enabled by default, but it returns NO
[_progressIndicator setUsesThreadedAnimation:YES];
// set to YES in the nib in hopes that it shows up in the stupid toolbar config sheet
[_progressIndicator setDisplayedWhenStopped:NO];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_startProgressBar:)
name:TLMLogTotalProgressNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_updateProgressBar:)
name:TLMLogDidIncrementProgressNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_stopProgressBar:)
name:TLMLogFinishedProgressNotification
object:nil];
TLMURLFormatter *fmt = [[TLMURLFormatter new] autorelease];
[fmt setReturnsURL:YES];
[_URLField setFormatter:fmt];
// need good initial properties since we can't add to the queue if tlmgr doesn't exist
[_URLField setButtonImage:[NSImage imageNamed:NSImageNameRefreshFreestandingTemplate]];
[_URLField setButtonTarget:self];
[_URLField setButtonAction:@selector(refresh:)];
}
/*
All this crap is to allow the spinner to be visible in the customization palette and
toolbar when modifying the toolbar, and otherwise hidden when it's stopped. I tried
a lot of stuff here, so remember not to screw with this unless it breaks.
1) Setting it always-visible in the nib and sending -[_progressIndicator setDisplayedWhenStopped:NO]
in -awakeFromNib will cause the one in the toolbar and the one in the palette to both be hidden.
2) It has to be sent when the sheet goes away. Any sooner and you won't be able to see it to move
it around in the toolbar.
3) Just returning the @"pig" identifier in toolbarDefaultItemIdentifiers will put the spinner as the
first item in the toolbar, which is not what I want. Therefore, a few of the other items in the
nib also have identifiers set.
*/
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag;
{
if ([itemIdentifier isEqualToString:@"pig"]) {
NSProgressIndicator *pig = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)];
[pig setControlSize:NSSmallControlSize];
[pig setStyle:NSProgressIndicatorSpinningStyle];
[pig setUsesThreadedAnimation:YES];
[pig setDisplayedWhenStopped:YES];
if (flag) [self set_progressIndicator:pig];
NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[item setView:pig];
[pig release];
[item setPaletteLabel:NSLocalizedString(@"Progress", @"toolbar item palette label")];
[item setMaxSize:[pig frame].size];
[item setMinSize:[pig frame].size];
return [item autorelease];
}
return nil;
}
- (void)windowWillBeginSheet:(NSNotification *)notification;
{
if ([[[self window] toolbar] customizationPaletteIsRunning])
[_progressIndicator setDisplayedWhenStopped:YES];
}
- (void)windowDidEndSheet:(NSNotification *)notification;
{
if ([[[self window] toolbar] customizationPaletteIsRunning] == NO)
[_progressIndicator setDisplayedWhenStopped:NO];
}
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar;
{
return [NSArray arrayWithObjects:@"homeButton", @"addressField", @"pig", NSToolbarFlexibleSpaceItemIdentifier, @"searchField", nil];
}
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar;
{
return [NSArray arrayWithObject:@"pig"];
}
- (void)_stopProgressBar:(NSNotification *)aNote
{
// we're done with the progress bar now, so set it to zero to clear it out
[_URLField setProgressValue:0];
[NSApp setApplicationIconImage:nil];
}
- (void)_startProgressBar:(NSNotification *)aNote
{
// we always have an integral number of bytes >> 1, so set a fake value here so it draws immediately
const double initialValue = 1.0;
[_URLField setMinimumProgressValue:0.0];
[_URLField setMaximumProgressValue:([[[aNote userInfo] objectForKey:TLMLogSize] doubleValue] + initialValue)];
[_URLField setProgressValue:initialValue];
}
- (void)_updateProgressBar:(NSNotification *)aNote
{
[_URLField incrementProgressBy:[[[aNote userInfo] objectForKey:TLMLogSize] doubleValue]];
/*
Formerly called -[[self _progressBar] display] here. That was killing performance after I
added progress updates to the infra operation; drawing basically stalled, since the
window had to synchronize too frequently. All this to say...don't do that again.
*/
CGFloat p = [_URLField progressValue] / [_URLField maximumProgressValue];
[NSApp setApplicationIconImage:[TLMProgressIndicatorCell applicationIconBadgedWithProgress:p]];
}
- (void)windowDidLoad
{
[super windowDidLoad];
// checkbox in IB doesn't work?
[[[self window] toolbar] setAutosavesConfiguration:YES];
}
- (void)_goHome
{
if ([[[TLMEnvironment currentEnvironment] defaultServerURL] isMultiplexer])
[self _displayStatusString:URL_VALIDATE_STATUS_STRING dataSource:_currentListDataSource];
// home is based on prefs, not the current URL
_serverURL = [[[TLMEnvironment currentEnvironment] validServerURLFromURL:nil] copy];
if ([[[_currentListDataSource statusWindow] statusString] isEqualToString:URL_VALIDATE_STATUS_STRING])
[self _displayStatusString:nil dataSource:_currentListDataSource];
// !!! end up with a bad environment if this is the multiplexer, and the UI gets out of sync
if (nil == _serverURL)
_serverURL = [[[TLMEnvironment currentEnvironment] defaultServerURL] copy];
if ([_serverURL isMultiplexer]) {
TLMLog(__func__, @"Still have multiplexer URL after setup. This is not good.");
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Unable to find a valid update server", @"alert title")];
[alert setInformativeText:NSLocalizedString(@"Either a network problem exists or the TeX Live version on the server does not match. If this problem persists on further attempts, you may need to try a different repository.", @"alert text")];
[alert beginSheetModalForWindow:[self window]
modalDelegate:nil
didEndSelector:NULL
contextInfo:NULL];
}
[_URLField setStringValue:[[self serverURL] absoluteString]];
// I don't like having this selected and highlighted at launch, for some reason
[[_URLField currentEditor] setSelectedRange:NSMakeRange(0, 0)];
[[self window] makeFirstResponder:nil];
}
- (void)gpgInstallAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)context
{
TLMDatabaseYear year = [[TLMEnvironment currentEnvironment] texliveYear];
if ([[alert suppressionButton] state] == NSOnState)
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:year]
forKey:TLMDisableGPGAlertPreferenceKey];
if (NSAlertFirstButtonReturn == returnCode) {
// tlmgr --repository http://www.preining.info/tlgpg/ install tlgpg
NSURL *gpgURL = [NSURL URLWithString:@"http://www.preining.info/tlgpg/"];
[_URLField setStringValue:[gpgURL absoluteString]];
[self setServerURL:gpgURL];
// I don't like having this selected and highlighted at launch, for some reason
[[_URLField currentEditor] setSelectedRange:NSMakeRange(0, 0)];
[[self window] makeFirstResponder:nil];
TLMInstallOperation *gpgOperation = [[TLMInstallOperation alloc] initWithPackageNames:[NSArray arrayWithObject:@"tlgpg"] location:gpgURL reinstall:YES];
[self _addOperation:gpgOperation selector:@selector(_handleGPGInstallFinishedNotification:) setRefreshingForDataSource:nil];
[gpgOperation release];
}
else {
// set the dirty bit on all datasources
[_updateListDataSource setNeedsUpdate:YES];
[_packageListDataSource setNeedsUpdate:YES];
[_backupDataSource setNeedsUpdate:YES];
[_installDataSource setNeedsUpdate:YES];
// do this after the window loads, so something is visible right away
[self _goHome];
}
}
- (void)showWindow:(id)sender
{
[super showWindow:sender];
[[(TLMAppController *)[NSApp delegate] logWindowController] setDockingDelegate:self];
static BOOL __windowDidShow = NO;
if (__windowDidShow) return;
__windowDidShow = YES;
if ([[NSUserDefaults standardUserDefaults] boolForKey:TLMDisableGPGAlertPreferenceKey])
TLMLog(__func__, @"User has chosen to permanently ignore the GPG install alert");
TLMEnvironment *currentEnv = [TLMEnvironment currentEnvironment];
const TLMDatabaseYear currentYear = [currentEnv texliveYear];
// force the user to disable GPG install warning every year
if (currentYear >= 2016 &&
[[NSUserDefaults standardUserDefaults] integerForKey:TLMDisableGPGAlertPreferenceKey] != currentYear &&
[[TLMDatabase localDatabase] packageNamed:@"tlgpg"] == nil) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Enable security validation of packages?", @"alert title")];
[alert setInformativeText:NSLocalizedString(@"This version of TeX Live allows you to check the digital signature of downloaded packages by installing GnuPG. For better security, you should enable this feature.", @"alert text")];
[alert addButtonWithTitle:NSLocalizedString(@"Enable", @"button title")];
[alert addButtonWithTitle:NSLocalizedString(@"Later", @"button title")];
[alert setShowsSuppressionButton:YES];
[alert beginSheetModalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(gpgInstallAlertDidEnd:returnCode:contextInfo:)
contextInfo:NULL];
}
else {
// set the dirty bit on all datasources
[_updateListDataSource setNeedsUpdate:YES];
[_packageListDataSource setNeedsUpdate:YES];
[_backupDataSource setNeedsUpdate:YES];
[_installDataSource setNeedsUpdate:YES];
// do this after the window loads, so something is visible in the URL field
[self _goHome];
}
// for info window; TL 2011 and later only
[self _refreshLocalDatabase];
// no need to update if we do a migration
if ([TLMLaunchAgentController migrateLocalToUserIfNeeded] == NO && [TLMLaunchAgentController scriptNeedsUpdate]) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Newer update checker is available", @"alert title")];
[alert setInformativeText:NSLocalizedString(@"A newer version of the scheduled update script is available. Would you like to install it now?", @"alert text")];
[alert addButtonWithTitle:NSLocalizedString(@"Yes", @"button title")];
[alert addButtonWithTitle:NSLocalizedString(@"No", @"button title")];
[alert beginSheetModalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(launchAgentScriptUpdateAlertDidEnd:returnCode:contextInfo:)
contextInfo:NULL];
}
}
- (NSString *)windowNibName { return @"MainWindow"; }
- (void)_setOperationCountAsNumber:(NSNumber *)count
{
NSParameterAssert([NSThread isMainThread]);
NSUInteger newCount = [count unsignedIntegerValue];
if (_operationCount != newCount) {
// previous count was zero, so spinner is currently stopped
if (0 == _operationCount) {
[_progressIndicator startAnimation:self];
// change address field to cancel
[_URLField setButtonImage:[NSImage imageNamed:NSImageNameStopProgressFreestandingTemplate]];
[_URLField setButtonTarget:self];
[_URLField setButtonAction:@selector(cancelAllOperations:)];
}
// previous count != 0, so spinner is currently animating
else if (0 == newCount) {
[_progressIndicator stopAnimation:self];
// change address field to refresh
[_URLField setButtonImage:[NSImage imageNamed:NSImageNameRefreshFreestandingTemplate]];
[_URLField setButtonTarget:self];
[_URLField setButtonAction:@selector(refresh:)];
}
// validation depends on this value
_operationCount = newCount;
// can either do this or post a custom event...
[[[self window] toolbar] validateVisibleItems];
}
}
// NB: this will arrive on the queue's thread, at least under some conditions!
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &_TLMOperationQueueOperationContext) {
/*
NSOperationQueue + KVO sucks: calling performSelectorOnMainThread:withObject:waitUntilDone:
with waitUntilDone:YES will cause a deadlock if the main thread is currently in a callout to -[NSOperationQueue operations].
What good is KVO on a non-main thread anyway? That makes it useless for bindings, and KVO is a pain in the ass to use
vs. something like NSNotification. Grrr.
*/
NSNumber *count = [NSNumber numberWithUnsignedInteger:[[TLMReadWriteOperationQueue defaultQueue] operationCount]];
[self performSelectorOnMainThread:@selector(_setOperationCountAsNumber:) withObject:count waitUntilDone:NO];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
// tried validating toolbar items using bindings to queue.operations.@count but the queue sends KVO notifications on its own thread
- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
{
SEL action = [anItem action];
if (@selector(cancelAllOperations:) == action)
return _operationCount > 0;
else if (@selector(updateInfrastructure:) == action)
return [[TLMReadWriteOperationQueue defaultQueue] isWriting] == NO;
else
return YES;
}
- (BOOL)windowShouldClose:(id)sender;
{
BOOL shouldClose = YES;
if ([[TLMReadWriteOperationQueue defaultQueue] isWriting]) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Installation in progress!", @"alert title")];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert setInformativeText:NSLocalizedString(@"If you close the window, the installation process may leave your TeX installation in an unknown state. You can ignore this warning and close the window, or wait until the installation finishes.", @"alert message text")];
[alert addButtonWithTitle:NSLocalizedString(@"Wait", @"button title")];
[alert addButtonWithTitle:NSLocalizedString(@"Ignore", @"button title")];
NSInteger rv = [alert runModal];
if (NSAlertFirstButtonReturn == rv)
shouldClose = NO;
}
return shouldClose;
}
- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
{
if (client == _URLField) {
static TLMMirrorFieldEditor *editor = nil;
if (nil == editor)
editor = [[TLMMirrorFieldEditor alloc] init];
return editor;
}
return nil;
}
// cover method to avoid loading the log controller's window before it's needed
- (NSWindow *)_logWindow
{
TLMLogWindowController *lwc = [(TLMAppController *)[NSApp delegate] logWindowController];
return [lwc isWindowLoaded] ? [[(TLMAppController *)[NSApp delegate] logWindowController] window] : nil;
}
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize;
{
const CGFloat dy = NSHeight([sender frame]) - frameSize.height;
const CGFloat dx = NSWidth([sender frame]) - frameSize.width;
NSWindow *logWindow = [self _logWindow];
if ([logWindow isVisible] && [[[self window] childWindows] containsObject:logWindow]) {
NSPoint logWindowOrigin = [logWindow frame].origin;
switch (_dockedEdge) {
case TLMDockedEdgeBottom:
logWindowOrigin.y += dy;
break;
case TLMDockedEdgeRight:
logWindowOrigin.x -= dx;
default:
break;
}
[logWindow setFrameOrigin:logWindowOrigin];
}
return frameSize;
}
- (void)windowDidResize:(NSNotification *)notification;
{
NSWindow *logWindow = [self _logWindow];
if ([logWindow isVisible] && [[[self window] childWindows] containsObject:logWindow] == NO)
[self dockableWindowGeometryDidChange:logWindow];
}
- (void)windowDidMove:(NSNotification *)notification;
{
NSWindow *logWindow = [self _logWindow];
if ([logWindow isVisible] && [[[self window] childWindows] containsObject:logWindow] == NO)
[self dockableWindowGeometryDidChange:logWindow];
}
- (void)dockableWindowWillClose:(NSWindow *)window;
{
_dockedEdge = TLMDockedEdgeNone;
[[self window] removeChildWindow:window];
TLMLog(__func__, @"Undocking log window");
}
- (void)dockableWindowGeometryDidChange:(NSWindow *)window;
{
// !!! early return on hidden default
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"TLMDisableLogWindowDocking"])
return;
NSRect logWindowFrame = [window frame];
const NSRect mainWindowFrame = [[self window] frame];
const CGFloat tolerance = 10.0;
const CGFloat dx = NSMaxX(mainWindowFrame) - NSMinX(logWindowFrame);
const CGFloat dy = NSMinY(mainWindowFrame) - NSMaxY(logWindowFrame);
/*
Allow docking anytime the log window's midpoint is within the main window's border.
Using the endpoint is fiddly if you're trying to line up the left edge (when docking
on the bottom) or top (when docking on the right), since it keeps undocking if you're
off by a point.
*/
if (ABS(dx) <= tolerance && NSMidY(logWindowFrame) >= NSMinY(mainWindowFrame) && NSMidY(logWindowFrame) <= NSMaxY(mainWindowFrame)) {
// dock on right side of main window
if (TLMDockedEdgeNone == _dockedEdge) {
NSParameterAssert([[[self window] childWindows] containsObject:window] == NO);
// !!! reentrancy: set before changing the frame
_dockedEdge = TLMDockedEdgeRight;
[[self window] addChildWindow:window ordered:NSWindowBelow];
TLMLog(__func__, @"Docking log window on right of main window");
}
// adjust even if already docked, so we get a consistent distance
logWindowFrame.origin.x = NSMaxX(mainWindowFrame) + 1;
[window setFrameOrigin:logWindowFrame.origin];
}
else if (ABS(dy) <= tolerance && NSMidX(logWindowFrame) >= NSMinX(mainWindowFrame) && NSMidX(logWindowFrame) <= NSMaxX(mainWindowFrame)) {
// dock on bottom of main window
if (TLMDockedEdgeNone == _dockedEdge) {
NSParameterAssert([[[self window] childWindows] containsObject:window] == NO);
// !!! reentrancy: set before changing the frame
_dockedEdge = TLMDockedEdgeBottom;
[[self window] addChildWindow:window ordered:NSWindowBelow];
TLMLog(__func__, @"Docking log window below main window");
}
// adjust even if already docked, so we get a consistent distance
logWindowFrame.origin.y = NSMinY(mainWindowFrame) - NSHeight(logWindowFrame) - 1;
[window setFrameOrigin:logWindowFrame.origin];
}
else if (TLMDockedEdgeNone != _dockedEdge) {
NSParameterAssert([[[self window] childWindows] containsObject:window]);
// already a child window, but moving away
_dockedEdge = TLMDockedEdgeNone;
[[self window] removeChildWindow:window];
TLMLog(__func__, @"Undocking log window");
}
}
#pragma mark Interface updates
- (void)setServerURL:(NSURL *)aURL
{
NSParameterAssert(aURL);
[_serverURL autorelease];
_serverURL = [aURL copy];
[_URLField setStringValue:[aURL absoluteString]];
}
- (void)_fixOverlayWindowOrder
{
/*
To avoid showing the overlay window on top of a sheet, call this on a delay
after showing a sheet or status window. NB: changing the window level here
will screw things up; the sheet needs to be at NSNormalWindowLevel.
*/
TLMStatusWindow *statusWindow = [_currentListDataSource statusWindow];
if (statusWindow)
[[[self window] attachedSheet] orderWindow:NSWindowAbove relativeTo:[statusWindow windowNumber]];
}
- (NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect
{
/*
I think this is here in case the overlay window is added while the sheet
is being positioned. The sheet seems to work fine if the overlay window
is up first, and in fact this call causes some flickering when the sheet
is repositioned. Avoid it if we definitely have the overlay now.
*/
if (nil == [_currentListDataSource statusWindow])
[self performSelector:@selector(_fixOverlayWindowOrder) withObject:nil afterDelay:0];
TLMLogServerSync();
return rect;
}
// pass nil for status to clear the view and remove it
- (void)_displayStatusString:(NSString *)statusString dataSource:(id <TLMListDataSource>)dataSource
{
// may currently be a window, so get rid of it
[[dataSource statusWindow] fadeOutAndRemove:YES];
[dataSource setStatusWindow:nil];
if (statusString) {
// status window is one shot
[dataSource setStatusWindow:[TLMStatusWindow windowWithStatusString:statusString frameFromView:_tabView]];
// only display now if this datasource is current
if ([_currentListDataSource isEqual:dataSource]) {
[[self window] addChildWindow:[_currentListDataSource statusWindow] ordered:NSWindowAbove];
[[dataSource statusWindow] fadeIn];
[self performSelector:@selector(_fixOverlayWindowOrder) withObject:nil afterDelay:0];
}
}
}
- (void)_removeDataSourceFromResponderChain:(id)dataSource
{
NSResponder *next = [self nextResponder];
if ([next isEqual:_updateListDataSource] || [next isEqual:_packageListDataSource] || [next isEqual:_backupDataSource] || [next isEqual:_installDataSource])
{
[self setNextResponder:[next nextResponder]];
[next setNextResponder:nil];
}
}
- (void)_insertDataSourceInResponderChain:(id)dataSource
{
NSResponder *next = [self nextResponder];
NSParameterAssert([next isEqual:_updateListDataSource] == NO);
NSParameterAssert([next isEqual:_packageListDataSource] == NO);
NSParameterAssert([next isEqual:_backupDataSource] == NO);
NSParameterAssert([next isEqual:_installDataSource] == NO);
[self setNextResponder:dataSource];
[dataSource setNextResponder:next];
}
- (void)tabView:(TLMTabView *)tabView didSelectViewAtIndex:(NSUInteger)anIndex;
{
// clear the status overlay, if any
[[_currentListDataSource statusWindow] fadeOutAndRemove:NO];
[self _removeDataSourceFromResponderChain:_currentListDataSource];
switch (anIndex) {
case 0:
[self _insertDataSourceInResponderChain:_updateListDataSource];
_currentListDataSource = _updateListDataSource;
[[_currentListDataSource statusWindow] fadeIn];
[self _refreshCurrentDataSourceIfNeeded];
if ([[_updateListDataSource allPackages] count])
[_updateListDataSource search:nil];
break;
case 1:
[self _insertDataSourceInResponderChain:_packageListDataSource];
_currentListDataSource = _packageListDataSource;
[[_currentListDataSource statusWindow] fadeIn];
[self _refreshCurrentDataSourceIfNeeded];
if ([[_packageListDataSource packageNodes] count])
[_packageListDataSource search:nil];
break;
case 2:
[self _insertDataSourceInResponderChain:_backupDataSource];
_currentListDataSource = _backupDataSource;
[[_currentListDataSource statusWindow] fadeIn];
[self _refreshCurrentDataSourceIfNeeded];
if ([[_backupDataSource backupNodes] count])
[_backupDataSource search:nil];
break;
case 3:
[self _insertDataSourceInResponderChain:_installDataSource];
_currentListDataSource = _installDataSource;
[[_currentListDataSource statusWindow] fadeIn];
[self _refreshCurrentDataSourceIfNeeded];
break;
default:
break;
}
}
- (BOOL)control:(NSControl *)control didFailToFormatString:(NSString *)string errorDescription:(NSString *)error
{
if (control == _URLField) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Invalid URL", @"alert title")];
[alert setInformativeText:error];
[alert beginSheetModalForWindow:[self window] modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
}
return NO;
}
- (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)selIndex;
{
if (selIndex) *selIndex = 0;
NSFormatter *fmt = [[control cell] formatter];
NSMutableArray *candidates = [[[(TLMAppController *)[NSApp delegate] mirrorController] mirrorsMatchingSearchString:[textView string]] mutableCopy];
if (fmt) {
NSUInteger idx = [candidates count];
while (idx--) {
id ignored;
if ([fmt getObjectValue:&ignored forString:[candidates objectAtIndex:idx] errorDescription:NULL] == NO)
[candidates removeObjectAtIndex:idx];
}
}
return [candidates autorelease];
}
- (NSRange)control:(NSControl *)control textView:(NSTextView *)textView rangeForUserCompletion:(NSRange)charRange;
{
return NSMakeRange(0, [[textView string] length]);
}
- (BOOL)control:(NSControl *)control textViewShouldAutoComplete:(NSTextView *)textView { return control == _URLField; }
#pragma mark -
#pragma mark Operations
- (void)_runUpdmap
{
[self _displayStatusString:NSLocalizedString(@"Running updmap…", @"") dataSource:_currentListDataSource];
TLMTask *task = [[TLMTask new] autorelease];
[task setLaunchPath:[[TLMEnvironment currentEnvironment] updmapAbsolutePath]];
[task launch];
// so we can check/log messages and clear the status overlay
[task waitUntilExit];
if ([task terminationStatus] == 0) {
if ([[task outputString] length])
TLMLog(__func__, @"%@", [task outputString]);
if ([[task errorString] length])
TLMLog(__func__, @"%@", [task errorString]);
}
else if ([task terminationStatus]) {
TLMLog(__func__, @"updmap had problems:\n%@", [task errorString]);
}
[self _displayStatusString:nil dataSource:_currentListDataSource];
}
- (void)_updmapAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
if ([[alert suppressionButton] state] == NSOnState)
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:TLMDisableUpdmapAlertPreferenceKey];
if (NSAlertFirstButtonReturn == returnCode) {
[[alert window] orderOut:nil];
[self _runUpdmap];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:TLMEnableUserUpdmapPreferenceKey];
}
else {
TLMLog(__func__, @"User declined to run updmap in spite of having the config file; whatever.");
}
}
- (void)_runUpdmapIfNeeded
{
const TLMDatabaseYear texliveYear = [[TLMEnvironment currentEnvironment] texliveYear];
// !!! early return
if (texliveYear < 2012) {
TLMLog(__func__, @"Not doing user updmap.cfg check for old TeX Live versions");
return;
}
TLMTask *task = [[TLMTask new] autorelease];
[task setLaunchPath:[[TLMEnvironment currentEnvironment] kpsewhichAbsolutePath]];
[task setArguments:[NSArray arrayWithObjects:@"-all", @"updmap.cfg", nil]];
[task launch];
[task waitUntilExit];
NSArray *updmapCfgPaths = nil;
if ([task terminationStatus] == 0 && [task outputString]) {
NSString *outputString = [[task outputString] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
updmapCfgPaths = [outputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
else {
TLMLog(__func__, @"%@ %@ returned an error: %@", [task launchPath], [[task arguments] componentsJoinedByString:@" "], [task errorString]);
}
task = [[TLMTask new] autorelease];
[task setLaunchPath:[[TLMEnvironment currentEnvironment] kpsewhichAbsolutePath]];
[task setArguments:[NSArray arrayWithObject:@"-var-value=TEXMFHOME"]];
[task launch];
[task waitUntilExit];
NSArray *texmfHomePaths = nil;
if ([task terminationStatus] == 0 && [task outputString]) {
NSString *outputString = [[task outputString] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
texmfHomePaths = [outputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
else {
TLMLog(__func__, @"%@ %@ returned an error: %@", [task launchPath], [[task arguments] componentsJoinedByString:@" "], [task errorString]);
}
for (NSString *updmapCfgPath in updmapCfgPaths) {
BOOL isSubpathOfHome = NO;
for (NSString *texmfHomePath in texmfHomePaths) {
if ([updmapCfgPath hasPrefix:texmfHomePath]) {
isSubpathOfHome = YES;
break;
}
}
if (NO == isSubpathOfHome) {
TLMLog(__func__, @"%@ is not in %@; ignoring", updmapCfgPath, texmfHomePaths);
}
// now see if any of these files exist (should exist if kpsewhich returns anything)
else if ([[NSFileManager defaultManager] fileExistsAtPath:updmapCfgPath]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
TLMLog(__func__, @"Found local map file %@", updmapCfgPath);
/*
show alert if preference is not enabled && (not previously shown for this TL year || user has not checked box to disable warning)
*/
if ([defaults boolForKey:TLMEnableUserUpdmapPreferenceKey]) {
[self _runUpdmap];
}
else if ([defaults integerForKey:TLMLastUpdmapVersionShownKey] != texliveYear || [defaults boolForKey:TLMDisableUpdmapAlertPreferenceKey] == NO) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Local fonts were found", @"alert title")];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"You appear to have installed fonts in your home directory. Would you like them to be automatically activated in TeX Live %d?", @"alert text, integer format specifier"), texliveYear]];
[alert addButtonWithTitle:NSLocalizedString(@"Yes", @"button title")];
[alert addButtonWithTitle:NSLocalizedString(@"No", @"button title")];
// don't bother showing current state, so user doesn't disable accidentally
[alert setShowsSuppressionButton:YES];
[alert beginSheetModalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(_updmapAlertDidEnd:returnCode:contextInfo:)
contextInfo:NULL];
}
// set this whether we run updmap or not
[defaults setInteger:texliveYear forKey:TLMLastUpdmapVersionShownKey];
// only need to run it once
break;
}
else {
TLMLog(__func__, @"WARNING: updmap returned nonexistent path at %@", updmapCfgPath);
}
}
}
- (BOOL)_checkCommandPathAndWarn:(BOOL)displayWarning
{
NSString *cmdPath = [[TLMEnvironment currentEnvironment] tlmgrAbsolutePath];
BOOL exists = [[NSFileManager defaultManager] isExecutableFileAtPath:cmdPath];
if (NO == exists) {
if (displayWarning) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"TeX installation not found.", @"alert sheet title")];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"The tlmgr tool does not exist at %@. Please set the correct location in preferences or install TeX Live.", @"alert message text"), cmdPath]];
[alert beginSheetModalForWindow:[self window] modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
}
else {
TLMLog(__func__, @"bad path %@, but displayWarning = %d", cmdPath, displayWarning);
}
}
return exists;
}
- (void)_addOperation:(TLMOperation *)op selector:(SEL)sel setRefreshingForDataSource:(id)dataSource
{
// short-circuit the tlmgr path check when installing
if (op && ([_currentListDataSource isEqual:_installDataSource] || [self _checkCommandPathAndWarn:YES])) {
if (NULL != sel)
[[NSNotificationCenter defaultCenter] addObserver:self selector:sel name:TLMOperationFinishedNotification object:op];
[[TLMReadWriteOperationQueue defaultQueue] addOperation:op];
}
else if ([dataSource respondsToSelector:@selector(setRefreshing:)]) {
// operation ending handlers aren't called, so this will never get reset
[dataSource setRefreshing:NO];
}
}
/*
Call before a write operation (update/install), just in case the environment has changed
since the last time updates were listed. This avoids downloading the wrong disaster
recovery script and running it against a different TL version (which the current script
handles correctly, so this is just an extra precaution). Note that changing mirrors
should not be an issue since we always use the last (already validated) mirror. However,
changing the the tlmgr path or TeX Dist in system prefs can cause problems.
Note: also called when manually entering a mirror in the address field, so we can also
get uncached/unvalidated mirrors here.
*/
- (BOOL)_isCorrectDatabaseVersionAtURL:(NSURL *)aURL
{
TLMLog(__func__, @"Checking database version in case preferences have been changed%C", TLM_ELLIPSIS);
// should be cached, unless the user has screwed up (and that's the case we're trying to catch)
TLMDatabase *db = [TLMDatabase databaseForMirrorURL:aURL];
const TLMDatabaseYear year = [[TLMEnvironment currentEnvironment] texliveYear];
if ([db failed] || [db texliveYear] == TLMDatabaseUnknownYear) {
NSAlert *alert = [[NSAlert new] autorelease];
[alert setMessageText:NSLocalizedString(@"Unable to determine repository version", @"alert title")];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"You have TeX Live %lu installed, but the version at %@ cannot be determined.", @"alert text, integer and string format specifiers"), (long)year, [aURL absoluteString]]];
[alert beginSheetModalForWindow:[self window] modalDelegate:nil didEndSelector:NULL contextInfo:NULL];