/
SPAppController.m
executable file
·1807 lines (1481 loc) · 72.5 KB
/
SPAppController.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
//
// SPAppController.m
// sequel-pro
//
// Created by Lorenz Textor (lorenz@textor.ch) on May 1, 2002.
// Copyright (c) 2002-2003 Lorenz Textor. All rights reserved.
// Copyright (c) 2012 Sequel Pro Team. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// More info at <https://github.com/sequelpro/sequelpro>
#import "SPKeychain.h"
#import "SPAppController.h"
#import "SPDatabaseDocument.h"
#import "SPPreferenceController.h"
#import "SPAboutController.h"
#import "SPDataImport.h"
#import "SPEncodingPopupAccessory.h"
#import "SPPreferencesUpgrade.h"
#import "SPBundleEditorController.h"
#import "SPTooltip.h"
#import "SPBundleHTMLOutputController.h"
#import "SPChooseMenuItemDialog.h"
#import "SPCustomQuery.h"
#import "SPFavoritesController.h"
#import "SPEditorTokens.h"
#import "SPBundleCommandRunner.h"
#import "SPCopyTable.h"
#import "SPSyntaxParser.h"
#import "SPTextView.h"
#import "SPFunctions.h"
#import "SPBundleManager.h"
#import "MGTemplateEngine.h"
#import "ICUTemplateMatcher.h"
#import "sequel-ace-Swift.h"
@import AppCenter;
@import AppCenterAnalytics;
@import AppCenterCrashes;
static const double SPDelayBeforeCheckingForNewReleases = 10;
@interface SPAppController ()
@property (strong) IBOutlet NSMenu *mainMenu;
- (void)_copyDefaultThemes;
- (void)openConnectionFileAtPath:(NSString *)filePath;
- (void)openSQLFileAtPath:(NSString *)filePath;
- (void)openSessionBundleAtPath:(NSString *)filePath;
- (void)openColorThemeFileAtPath:(NSString *)filePath;
- (void)checkForNewVersionWithDelay:(double)delay andIsFromMenuCheck:(BOOL)isFromMenuCheck;
- (void)removeCheckForUpdatesMenuItem;
- (void)addCheckForUpdatesMenuItem;
- (void)checkForNewVersionFromMenu;
@property (readwrite, strong) NSFileManager *fileManager;
@property (nonatomic, strong, readwrite) TabManager *tabManager;
@end
@implementation SPAppController
@synthesize lastBundleBlobFilesDirectory;
@synthesize fileManager;
@synthesize mainMenu;
@synthesize sshProcessIDs;
#pragma mark -
#pragma mark Initialisation
/**
* Initialise the application's main controller, setting itself as the app delegate.
*/
- (instancetype)init
{
if ((self = [super init])) {
_sessionURL = nil;
aboutController = nil;
lastBundleBlobFilesDirectory = nil;
_spfSessionDocData = [[NSMutableDictionary alloc] init];
runningActivitiesArray = [[NSMutableArray alloc] init];
sshProcessIDs = [[NSMutableArray alloc] init];
fileManager = [NSFileManager defaultManager];
_tabManager = [[TabManager alloc] initWithAppController:self];
//Create runtime directiories
[fileManager createDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] withIntermediateDirectories:true attributes:nil error:nil];
[fileManager createDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@".keys"] withIntermediateDirectories:true attributes:nil error:nil];
//Handle Appearance on macOS 10.14+
if (@available(macOS 10.14, *)) {
//Switch Appearance on Application startup (prevent Appearance blink)
[self switchAppearance];
//Register an observer to switch Appearance at runtime
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}
[NSApp setDelegate:self];
}
return self;
}
/**
* Called even before init so we can register our preference defaults
*/
+ (void)initialize
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *preferenceDefaults = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:SPPreferenceDefaultsFile ofType:@"plist"]];
// Register application defaults
[prefs registerDefaults:preferenceDefaults];
// Upgrade prefs before any other parts of the app pick up on the values
SPApplyRevisionChanges();
}
/**
* Called when default properties had a change at runtime
*/
- (void)defaultsChanged:(NSNotification *)notification {
[self switchAppearance];
}
/**
* Called when need to switch application appearance - on startup and when userDefaults changed
*/
- (void)switchAppearance {
SPMainQSync(^{
if (@available(macOS 10.14, *)) {
NSInteger appearance = [[NSUserDefaults standardUserDefaults] integerForKey:SPAppearance];
if (appearance == 1) {
NSApp.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
} else if (appearance == 2) {
NSApp.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
} else {
NSApp.appearance = nil;
}
}
});
}
/**
* Initialisation stuff upon nib awakening
*/
- (void)awakeFromNib
{
// Register url scheme handle
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(handleEvent:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
// Set up the prefs controller
prefsController = [[SPPreferenceController alloc] init];
// Register SPAppController as services provider
[NSApp setServicesProvider:self];
// Register SPAppController for AppleScript events
[[NSScriptExecutionContext sharedScriptExecutionContext] setTopLevelObject:self];
}
/**
* Initialisation stuff after launch is complete
*/
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
// Send time interval for non-critical logs
// must set before calling AppCenter.start
// 5 mins?
[MSACAnalytics setTransmissionInterval:60*5];
// Use 30 MB for storage for logs
[MSACAppCenter setMaxStorageSize:(30 * 1024 * 1024) completionHandler:nil];
[MSACAppCenter start:@"65535bfb-1763-40fd-896b-a3aaae06227f" withServices:@[[MSACAnalytics class], [MSACCrashes class]]];
#ifdef DEBUG
// default is 5 = MSACLogLevelWarning
[MSACAppCenter setLogLevel:MSACLogLevelDebug];
#endif
if(MSACAppCenter.isEnabled == YES && MSACAppCenter.isConfigured == YES){
SPLog(@"Started MSACAppCenter. sdkVersion: %@. defaultLogLevel: %lu", MSACAppCenter.sdkVersion, (unsigned long) MSACAppCenter.logLevel);
}
else{
SPLog(@"MSACAppCenter FAILED to start.");
}
// this reRequests access to all bookmarks
SecureBookmarkManager *secureBookmarkManager = SecureBookmarkManager.sharedInstance;
// prompt user to recreate secure bookmarks
if(secureBookmarkManager.staleBookmarks.count > 0){
SPLog(@"We have stale bookmarks");
NSMutableString *staleBookmarksString = [[NSMutableString alloc] initWithCapacity:secureBookmarkManager.staleBookmarks.count];
for(NSString* staleFile in secureBookmarkManager.staleBookmarks){
[staleBookmarksString appendFormat:@"%@\n", staleFile.lastPathComponent];
SPLog(@"fileNames adding stale file: %@", staleFile.lastPathComponent);
}
[staleBookmarksString setString:[staleBookmarksString dropSuffixWithSuffix:@"\n"]];
[NSAlert createAccessoryAlertWithTitle:NSLocalizedString(@"App Sandbox Issue", @"App Sandbox Issue") message:[NSString stringWithFormat:NSLocalizedString(@"You have stale secure bookmarks:\n\n%@\n\nWould you like to re-request access now?", @"Would you like to re-request access now?"), staleBookmarksString] accessoryView:_staleBookmarkHelpView primaryButtonTitle:NSLocalizedString(@"Yes", @"Yes")
primaryButtonHandler:^{
SPLog(@"re-request access now");
[self->prefsController showWindow:self];
[self->prefsController displayPreferencePane:self->prefsController->fileItem];
} cancelButtonHandler:^{
SPLog(@"No not now");
}];
}
// init SQLite query history
SQLiteHistoryManager __unused *sqliteHistoryManager = SQLiteHistoryManager.sharedInstance;
NSDictionary *spfDict = nil;
NSArray *args = [[NSProcessInfo processInfo] arguments];
if (args.count == 5) {
if (([[args objectAtIndex:1] isEqualToString:@"--spfData"] && [[args objectAtIndex:3] isEqualToString:@"--dataVersion"] && [[args objectAtIndex:4] isEqualToString:@"1"]) || ([[args objectAtIndex:3] isEqualToString:@"--spfData"] && [[args objectAtIndex:1] isEqualToString:@"--dataVersion"] && [[args objectAtIndex:2] isEqualToString:@"1"])) {
NSData* data = [[args objectAtIndex:2] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
spfDict = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:&error];
if (error) {
spfDict = nil;
}
}
}
executeOnBackgroundThread(^{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// fake the dbViewInfoPanelSplit being open
NSMutableArray *dbViewInfoPanelSplit = [[NSMutableArray alloc] initWithCapacity:2];
[dbViewInfoPanelSplit addObject:@"0.000000, 0.000000, 359.500000, 577.500000, NO, NO"];
[dbViewInfoPanelSplit addObject:@"0.000000, 586.500000, 359.500000, 190.500000, NO, NO"];
[prefs setObject:dbViewInfoPanelSplit forKey:@"NSSplitView Subview Frames DbViewInfoPanelSplit"];
});
[self checkForNewVersionWithDelay:SPDelayBeforeCheckingForNewReleases andIsFromMenuCheck:NO];
// Add menu item to check for updates
[self addCheckForUpdatesMenuItem];
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:SPShowUpdateAvailable options:NSKeyValueObservingOptionNew context:NULL];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(externalApplicationWantsToOpenADatabaseConnection:) name:@"ExternalApplicationWantsToOpenADatabaseConnection" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(duplicateConnectionToTab:) name:SPDocumentDuplicateTabNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switchToPreviousTab:) name:SPWindowSelectPreviousTabNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switchToNextTab:) name:SPWindowSelectNextTabNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveConnectionsToSPF:) name:SPDocumentSaveToSPFNotification object:nil];
[SPBundleManager.shared reloadBundles:self];
[self _copyDefaultThemes];
// If no documents are open, open one
if (![self frontDocument]) {
SPWindowController *newWindowController = [self.tabManager replaceTabServiceWithInitialWindow];
if (spfDict) {
[newWindowController.databaseDocument setState:spfDict];
}
// Set autoconnection if appropriate
if ([[NSUserDefaults standardUserDefaults] boolForKey:SPAutoConnectToDefault] && secureBookmarkManager.staleBookmarks.count == 0) {
[newWindowController.databaseDocument connect];
}
}
}
- (void)addCheckForUpdatesMenuItem {
if (NSBundle.mainBundle.isMASVersion == NO && [[NSUserDefaults standardUserDefaults] boolForKey:SPShowUpdateAvailable] == YES) {
SPLog(@"Adding menu item to check for updates");
NSMenuItem *updates = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Check for Updates...", @"Menu item Check for Updates...") action:@selector(checkForNewVersionFromMenu) keyEquivalent:@""];
[mainMenu insertItem:updates atIndex:1];
}
}
- (void)removeCheckForUpdatesMenuItem {
[mainMenu.itemArray enumerateObjectsUsingBlock:^(NSMenuItem *item2, NSUInteger idx, BOOL * _Nonnull stop) {
if ([item2.title isEqualToString:NSLocalizedString(@"Check for Updates...", @"Menu item Check for Updates...")]) {
SPLog(@"Removing menu item to check for updates");
[mainMenu removeItemAtIndex:idx];
*stop = YES;
}
}];
}
- (void)checkForNewVersionFromMenu{
[self checkForNewVersionWithDelay:0 andIsFromMenuCheck:YES];
}
- (void)checkForNewVersionWithDelay:(double)delay andIsFromMenuCheck:(BOOL)isFromMenuCheck {
SPLog(@"isFromMenuCheck %d", isFromMenuCheck);
if ([[NSUserDefaults standardUserDefaults] boolForKey:SPShowUpdateAvailable] == YES) {
SPLog(@"checking for updates");
executeOnLowPrioQueueAfterADelay(^{
[NSBundle.mainBundle checkForNewVersionWithIsFromMenuCheck:isFromMenuCheck];
}, delay);
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:SPShowUpdateAvailable]) {
if([[change objectForKey:NSKeyValueChangeNewKey] boolValue] == YES){
[self addCheckForUpdatesMenuItem];
}
else if([[change objectForKey:NSKeyValueChangeNewKey] boolValue] == NO){
[self removeCheckForUpdatesMenuItem];
}
}
}
- (void)externalApplicationWantsToOpenADatabaseConnection:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
NSString *MAMP_SPFVersion = [userInfo objectForKey:@"dataVersion"];
if ([MAMP_SPFVersion isEqualToString:@"1"]) {
NSDictionary *spfStructure = [userInfo objectForKey:@"spfData"];
if (spfStructure) {
SPWindowController *windowController = [self.tabManager newWindowForWindow];
[windowController.databaseDocument setState:spfStructure];
}
}
}
- (void)switchToPreviousTab:(NSNotification *)notification {
[self.tabManager switchToPreviousTab];
}
- (void)switchToNextTab:(NSNotification *)notification {
[self.tabManager switchToNextTab];
}
- (void)duplicateConnectionToTab:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
if (userInfo) {
SPWindowController *newWindowController = [self.tabManager newWindowForTab];
[newWindowController.databaseDocument setState:userInfo];
}
}
- (void)saveConnectionsToSPF:(NSNotification *)notification {
NSString *fileName = [notification object];
NSError *error = nil;
NSString *contextInfo = [[notification userInfo] objectForKey:@"contextInfo"];
NSNumber *encrypted = [[notification userInfo] objectForKey:@"encrypted"];
NSString *saveConnectionEncryptString = [[notification userInfo] objectForKey:@"saveConnectionEncryptString"];
NSNumber *auto_connect = [[notification userInfo] objectForKey:@"auto_connect"];
NSNumber *save_password = [[notification userInfo] objectForKey:@"save_password"];
NSNumber *include_session = [[notification userInfo] objectForKey:@"include_session"];
NSNumber *save_editor_content = [[notification userInfo] objectForKey:@"save_editor_content"];
// Sub-folder 'Contents' will contain all untitled connection as single window or tab.
// info.plist will contain the opened structure (windows and tabs for each window). Each connection
// is linked to a saved spf file either in 'Contents' for unTitled ones or already saved spf files.
if ([contextInfo isEqual:@"saveAsSession"] && [self sessionURL]) {
fileName = [[self sessionURL] path];
}
if(!fileName || ![fileName length]) {
return;
}
// If bundle exists remove it
if([fileManager fileExistsAtPath:fileName]) {
[fileManager removeItemAtPath:fileName error:&error];
if(error != nil) {
NSAlert *errorAlert = [NSAlert alertWithError:error];
[errorAlert runModal];
return;
}
}
[fileManager createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:&error];
if (error != nil) {
[[NSAlert alertWithError:error] runModal];
return;
}
[fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Contents", fileName] withIntermediateDirectories:YES attributes:nil error:&error];
if (error != nil) {
[[NSAlert alertWithError:error] runModal];
return;
}
NSMutableDictionary *info = [NSMutableDictionary dictionary];
NSMutableArray *windows = [NSMutableArray array];
// retrieve save panel data for passing them to each doc
NSMutableDictionary *spfDocData_temp = [NSMutableDictionary dictionary];
if ([contextInfo isEqualTo:@"saveAsSession"]) {
[spfDocData_temp addEntriesFromDictionary:[self spfSessionDocData]];
} else {
[spfDocData_temp setObject:encrypted forKey:@"encrypted"];
if ([[spfDocData_temp objectForKey:@"encrypted"] boolValue]) {
[spfDocData_temp setObject:saveConnectionEncryptString forKey:@"e_string"];
}
[spfDocData_temp setObject:auto_connect forKey:@"auto_connect"];
[spfDocData_temp setObject:save_password forKey:@"save_password"];
[spfDocData_temp setObject:include_session forKey:@"include_session"];
[spfDocData_temp setObject:save_editor_content forKey:@"save_editor_content"];
// Save the session's accessory view settings
[self setSpfSessionDocData:spfDocData_temp];
}
[info setObject:[NSNumber numberWithBool:[[spfDocData_temp objectForKey:@"encrypted"] boolValue]] forKey:@"encrypted"];
[info setObject:[NSNumber numberWithBool:[[spfDocData_temp objectForKey:@"auto_connect"] boolValue]] forKey:@"auto_connect"];
[info setObject:[NSNumber numberWithBool:[[spfDocData_temp objectForKey:@"save_password"] boolValue]] forKey:@"save_password"];
[info setObject:[NSNumber numberWithBool:[[spfDocData_temp objectForKey:@"include_session"] boolValue]] forKey:@"include_session"];
[info setObject:[NSNumber numberWithBool:[[spfDocData_temp objectForKey:@"save_editor_content"] boolValue]] forKey:@"save_editor_content"];
[info setObject:@1 forKey:SPFVersionKey];
[info setObject:@"connection bundle" forKey:SPFFormatKey];
// Loop through all windows
for (SPWindowController *windowController in [self.tabManager windowControllers]) {
// First window is always the currently key window
NSMutableDictionary *win = [NSMutableDictionary dictionary];
// Skip not connected docs eg if connection controller is displayed (TODO maybe to be improved)
if (![windowController.databaseDocument mySQLVersion]) continue;
NSMutableDictionary *tabData = [NSMutableDictionary dictionary];
if([windowController.databaseDocument isUntitled]) {
// new bundle file name for untitled docs
NSString *newName = [NSString stringWithFormat:@"%@.%@", [NSString stringWithNewUUID], SPFileExtensionDefault];
// internal bundle path to store the doc
NSString *filePath = [NSString stringWithFormat:@"%@/Contents/%@", fileName, newName];
// save it as temporary spf file inside the bundle with save panel options spfDocData_temp
[windowController.databaseDocument saveDocumentWithFilePath:filePath inBackground:NO onlyPreferences:NO contextInfo:[NSDictionary dictionaryWithDictionary:spfDocData_temp]];
[windowController.databaseDocument setIsSavedInBundle:YES];
[tabData setObject:@NO forKey:@"isAbsolutePath"];
[tabData setObject:newName forKey:@"path"];
} else {
// save it to the original location and take the file's spfDocData
[windowController.databaseDocument saveDocumentWithFilePath:[[windowController.databaseDocument fileURL] path] inBackground:YES onlyPreferences:NO contextInfo:nil];
[tabData setObject:@YES forKey:@"isAbsolutePath"];
[tabData setObject:[[windowController.databaseDocument fileURL] path] forKey:@"path"];
}
[win setObject:NSStringFromRect([[windowController window] frame]) forKey:@"frame"];
[windows addObject:win];
}
[info setObject:windows forKey:@"windows"];
error = nil;
NSData *plist = [NSPropertyListSerialization dataWithPropertyList:info format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if (error) {
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Error while converting session data", @"error while converting session data") message:[error localizedDescription] callback:nil];
return;
}
[plist writeToFile:[NSString stringWithFormat:@"%@/info.plist", fileName] options:NSAtomicWrite error:&error];
if (error != nil){
NSAlert *errorAlert = [NSAlert alertWithError:error];
[errorAlert runModal];
return;
}
[self setSessionURL:fileName];
// Register spfs bundle in Recent Files
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:fileName]];
}
/**
* Menu item validation.
*/
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
SEL action = [menuItem action];
if (action == @selector(newWindow:) || action == @selector(openConnectionSheet:)) {
return YES;
}
if (action == @selector(newTab:)) {
return ([[[self.tabManager activeWindowController] window] attachedSheet] == nil);
}
if (action == @selector(duplicateTab:)) {
return ([[self frontDocument] getConnection] != nil);
}
if (action == @selector(openAboutPanel:) || action == @selector(openPreferences:) || action == @selector(visitWebsite:) || action == @selector(checkForNewVersionFromMenu)) {
return YES;
}
if (self.tabManager.activeWindowController.databaseDocument) {
return [self.tabManager.activeWindowController.databaseDocument validateMenuItem:menuItem];
}
return YES;
}
#pragma mark -
#pragma mark Open methods
/**
* NSOpenPanel delegate to control encoding popup and allowMultipleSelection
*/
- (void)panelSelectionDidChange:(id)sender
{
if ([sender isKindOfClass:[NSOpenPanel class]]) {
if([[[[[sender URL] path] pathExtension] lowercaseString] isEqualToString:SPFileExtensionSQL]) {
[encodingPopUp setEnabled:YES];
} else {
[encodingPopUp setEnabled:NO];
}
}
}
/**
* NSOpenPanel for selecting sql or spf file
*/
- (IBAction)openConnectionSheet:(id)sender
{
// Avoid opening more than NSOpenPanel
if (encodingPopUp) {
NSBeep();
return;
}
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setDelegate:self];
[panel setCanSelectHiddenExtension:YES];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:NO];
[panel setResolvesAliases:YES];
// If no lastSqlFileEncoding in prefs set it to UTF-8
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs integerForKey:SPLastSQLFileEncoding]) {
[prefs setInteger:4 forKey:SPLastSQLFileEncoding];
}
[panel setAccessoryView:[SPEncodingPopupAccessory encodingAccessory:[prefs integerForKey:SPLastSQLFileEncoding]
includeDefaultEntry:NO encodingPopUp:&encodingPopUp]];
// it will enabled if user selects a *.sql file
[encodingPopUp setEnabled:NO];
[panel setAllowedFileTypes:@[SPFileExtensionDefault, SPFileExtensionSQL, SPBundleFileExtension]];
// Check if at least one document exists, if so show a sheet
if ([self.tabManager activeWindowController]) {
[panel beginSheetModalForWindow:[[self.tabManager activeWindowController] window] completionHandler:^(NSInteger returnCode) {
if (returnCode) {
[panel orderOut:self];
NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[[panel URLs] count]];
[[panel URLs] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
[filePaths addObject:[obj path]];
}];
[self application:NSApp openFiles:filePaths];
}
}];
}
else {
NSInteger returnCode = [panel runModal];
if (returnCode) {
NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[[panel URLs] count]];
[[panel URLs] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
[filePaths addObject:[obj path]];
}];
[self application:NSApp openFiles:filePaths];
}
}
encodingPopUp = nil;
}
/**
* Called if user drag and drops files on Sequel Ace's dock item or double-clicked
* at files *.spf or *.sql
*/
- (void)application:(NSApplication *)app openFiles:(NSArray *)filenames
{
for (NSString *filePath in filenames)
{
NSString *fileExt = [[filePath pathExtension] lowercaseString];
// Opens a sql file and insert its content into the Custom Query editor
if ([fileExt isEqualToString:[SPFileExtensionSQL lowercaseString]]) {
[self openSQLFileAtPath:filePath];
break; // open only the first SQL file
}
else if ([fileExt isEqualToString:[SPFileExtensionDefault lowercaseString]]) {
[self openConnectionFileAtPath:filePath];
}
else if ([fileExt isEqualToString:[SPBundleFileExtension lowercaseString]]) {
[self openSessionBundleAtPath:filePath];
}
else if ([fileExt isEqualToString:[SPColorThemeFileExtension lowercaseString]]) {
[self openColorThemeFileAtPath:filePath];
}
else if ([fileExt isEqualToString:[SPUserBundleFileExtension lowercaseString]] || [fileExt isEqualToString:[SPUserBundleFileExtensionV2 lowercaseString]]) {
[SPBundleManager.shared openUserBundleAtPath:filePath];
}
else {
NSBeep();
SPLog(@"Only files with the extensions ‘%@’, ‘%@’, ‘%@’, ‘%@’, ‘%@’ or ‘%@’ are allowed.", SPFileExtensionDefault, SPBundleFileExtension, SPUserBundleFileExtensionV2, SPUserBundleFileExtension, SPColorThemeFileExtension, SPFileExtensionSQL);
}
}
}
- (void)openConnectionFileAtPath:(NSString *)filePath {
SPWindowController *windowController = [self.tabManager newWindowForWindow];
[windowController.databaseDocument setStateFromConnectionFile:filePath];
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:filePath]];
}
- (void)openSQLFileAtPath:(NSString *)filePath
{
// Check size and NSFileType
NSDictionary *attr = [fileManager attributesOfItemAtPath:filePath error:nil];
SPDatabaseDocument *frontDocument = [self frontDocument];
if (attr)
{
NSNumber *filesize = [attr objectForKey:NSFileSize];
NSString *filetype = [attr objectForKey:NSFileType];
if(filetype == NSFileTypeRegular && filesize)
{
// Ask for confirmation if file content is larger than 1MB
if ([filesize unsignedLongValue] > 1000000)
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setAlertStyle:NSAlertStyleWarning];
[alert setMessageText:NSLocalizedString(@"Warning",@"warning")];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Do you really want to load a SQL file with %@ of data into the Query Editor?", @"message of panel asking for confirmation for loading large text into the query editor"), [NSByteCountFormatter stringWithByteSize:[filesize longLongValue]]]];
[alert setHelpAnchor:filePath];
// Order of buttons matters! first button has "firstButtonReturn" return value from runModal
[alert addButtonWithTitle:NSLocalizedString(@"OK", @"OK button")];
[alert addButtonWithTitle:NSLocalizedString(@"Cancel", @"cancel button")];
// Show 'Import' button only if there's a connection available
if ([self frontDocument]) {
[alert addButtonWithTitle:NSLocalizedString(@"Import", @"import button")];
}
NSUInteger returnCode = [alert runModal];
switch (returnCode) {
case NSAlertSecondButtonReturn: // Cancel
return;
case NSAlertThirdButtonReturn: { // Import
[[frontDocument tableDumpInstance] startSQLImportProcessWithFile:filePath];
return;
}
default: // Ok - just proceed
break;
}
}
}
}
// Attempt to open the file into a string.
NSStringEncoding sqlEncoding;
NSString *sqlString = nil;
// If the user came from an openPanel use the chosen encoding
if (encodingPopUp) {
sqlEncoding = [[encodingPopUp selectedItem] tag];
// Otherwise, attempt to autodetect the encoding
}
else {
sqlEncoding = [fileManager detectEncodingforFileAtPath:filePath];
}
NSError *error = nil;
sqlString = [NSString stringWithContentsOfFile:filePath encoding:sqlEncoding error:&error];
if (error != nil) {
NSAlert *errorAlert = [NSAlert alertWithError:error];
[errorAlert runModal];
return;
}
// if encodingPopUp is defined the filename comes from an openPanel and
// the encodingPopUp contains the chosen encoding; otherwise autodetect encoding
if (encodingPopUp) {
[[NSUserDefaults standardUserDefaults] setInteger:[[encodingPopUp selectedItem] tag] forKey:SPLastSQLFileEncoding];
}
// Check if at least one document exists. If not, open one.
if (![self.tabManager activeWindowController]) {
frontDocument = [self.tabManager newWindowForWindow].databaseDocument;
[frontDocument initQueryEditorWithString:sqlString];
}
else {
// Pass query to the Query editor of the current document
[frontDocument doPerformLoadQueryService:sqlString];
}
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:filePath]];
[frontDocument setSqlFileURL:[NSURL fileURLWithPath:filePath]];
[frontDocument setSqlFileEncoding:sqlEncoding];
}
- (void)openSessionBundleAtPath:(NSString *)filePath {
NSError *error = nil;
NSData *pData = [NSData dataWithContentsOfFile:[filePath stringByAppendingPathComponent:@"info.plist"]
options:NSUncachedRead
error:&error];
NSDictionary *spfs = nil;
if (pData && !error) {
spfs = [NSPropertyListSerialization propertyListWithData:pData
options:NSPropertyListImmutable
format:NULL
error:&error];
}
if (!spfs || error) {
NSString *message = [NSString stringWithFormat:NSLocalizedString(@"Connection data file couldn't be read. (%@)", @"error while reading connection data file"), [error localizedDescription]];
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Error while reading connection data file", @"error while reading connection data file") message:message callback:nil];
return;
}
if([spfs objectForKey:@"windows"] && [[spfs objectForKey:@"windows"] isKindOfClass:[NSArray class]]) {
// Retrieve Save Panel accessory view data for remembering them globally
NSMutableDictionary *spfsDocData = [NSMutableDictionary dictionary];
[spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"encrypted"] boolValue]] forKey:@"encrypted"];
[spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"auto_connect"] boolValue]] forKey:@"auto_connect"];
[spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"save_password"] boolValue]] forKey:@"save_password"];
[spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"include_session"] boolValue]] forKey:@"include_session"];
[spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"save_editor_content"] boolValue]] forKey:@"save_editor_content"];
// Set global session properties
[self setSpfSessionDocData:spfsDocData];
[self setSessionURL:filePath];
// Loop through each defined window in reversed order to reconstruct the last active window
for (NSDictionary *window in [[[spfs objectForKey:@"windows"] reverseObjectEnumerator] allObjects]) {
// Create a new window controller, and set up a new connection view within it.
SPWindowController *newWindowController = [self.tabManager newWindowForWindow];
NSWindow *newWindow = [newWindowController window];
// Set the window controller as the window's delegate
[newWindow setDelegate:newWindowController];
usleep(1000);
// Show the window
[newWindowController showWindow:self];
// Loop through all defined tabs for each window
for (NSDictionary *tab in [window objectForKey:@"tabs"])
{
NSString *fileName = nil;
BOOL isBundleFile = NO;
// If isAbsolutePath then take this path directly
// otherwise construct the releative path for the passed spfs file
if ([[tab objectForKey:@"isAbsolutePath"] boolValue]) {
fileName = [tab objectForKey:@"path"];
}
else {
fileName = [NSString stringWithFormat:@"%@/Contents/%@", filePath, [tab objectForKey:@"path"]];
isBundleFile = YES;
}
// Security check if file really exists
if ([fileManager fileExistsAtPath:fileName]) {
// Add new the tab
if(newWindowController) {
if ([[newWindowController window] isMiniaturized]) [[newWindowController window] deminiaturize:self];
[newWindowController.databaseDocument setIsSavedInBundle:isBundleFile];
if (![newWindowController.databaseDocument setStateFromConnectionFile:fileName]) {
break;
}
}
}
else {
SPLog(@"Bundle file “%@” does not exists", fileName);
NSBeep();
}
}
}
}
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:filePath]];
}
- (void)openColorThemeFileAtPath:(NSString *)filePath
{
NSString *themePath = [fileManager applicationSupportDirectoryForSubDirectory:SPThemesSupportFolder error:nil];
if (!themePath) return;
if (![fileManager fileExistsAtPath:themePath isDirectory:nil]) {
if (![fileManager createDirectoryAtPath:themePath withIntermediateDirectories:YES attributes:nil error:nil]) {
NSBeep();
return;
}
}
NSString *newPath = [NSString stringWithFormat:@"%@/%@", themePath, [filePath lastPathComponent]];
if (![fileManager fileExistsAtPath:newPath isDirectory:nil]) {
if (![fileManager moveItemAtPath:filePath toPath:newPath error:nil]) {
NSBeep();
return;
}
}
else {
[NSAlert createWarningAlertWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Error while installing color theme file", @"error while installing color theme file")] message:[NSString stringWithFormat:NSLocalizedString(@"The color theme ‘%@’ already exists.", @"the color theme ‘%@’ already exists."), [filePath lastPathComponent]] callback:nil];
return;
}
}
#pragma mark -
#pragma mark URL scheme handler
/**
* sequelace://” url dispatcher
*
* sequelace://PROCESS_ID@command/parameter1/parameter2/...
* parameters has to be escaped according to RFC 1808 eg %3F for a '?'
*
*/
- (void)handleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSURL *url = [NSURL URLWithString:[[event paramDescriptorForKeyword:keyDirectObject] stringValue]];
if ([[url scheme] isEqualToString:@"sequelace"]) {
[self handleEventWithURL:url];
}
else if([[url scheme] isEqualToString:@"mysql"]) {
[self handleMySQLConnectWithURL:url];
}
else {
NSBeep();
SPLog(@"Error in sequelace URL scheme for URL <%@>",url);
}
}
- (void)handleMySQLConnectWithURL:(NSURL *)url {
if(![[url scheme] isEqualToString:@"mysql"]) {
SPLog(@"unsupported url scheme: %@",url);
return;
}
NSMutableDictionary *details = [NSMutableDictionary dictionary];
NSValue *connect = @NO;
[details setObject:@"SPTCPIPConnection" forKey:@"type"];
if ([url port]) {
[details setObject:[url port] forKey:@"port"];
}
if ([url user]) {
[details setObject:[url user] forKey:@"user"];
}
if ([url password]) {
[details setObject:[url password] forKey:@"password"];
connect = @YES;
}
if ([[url host] length]) {
[details setObject:[url host] forKey:@"host"];
} else {
[details setObject:@"127.0.0.1" forKey:@"host"];
}
NSArray *pc = [url pathComponents];
if ([pc count] > 1) { // first object is "/"
[details setObject:[pc objectAtIndex:1] forKey:@"database"];
}
SPWindowController *windowController = [self.tabManager newWindowForWindow];
[windowController.databaseDocument setState:@{@"connection":details,@"auto_connect": connect} fromFile:NO];
}
- (void)handleEventWithURL:(NSURL*)url
{
NSString *command = [url host];
NSString *passedProcessID = [url user];
NSArray *parameter;
NSArray *pathComponents;
if([[url absoluteString] hasSuffix:@"/"])
pathComponents = [[[url absoluteString] substringToIndex:[[url absoluteString] length]-1] pathComponents];
else
pathComponents = [[url absoluteString] pathComponents];
// remove percent encoding
NSMutableArray *decodedPathComponents = [NSMutableArray arrayWithCapacity:pathComponents.count];
for (NSString *component in pathComponents) {
NSString *decoded;
if(component.isPercentEncoded){
decoded = component.stringByRemovingPercentEncoding;
}
else {
decoded = component;
}
[decodedPathComponents addObject:decoded];
}
pathComponents = decodedPathComponents.copy;
if([pathComponents count] > 2)
parameter = [pathComponents subarrayWithRange:NSMakeRange(2, [pathComponents count]-2)];
else
parameter = @[];
// Handle commands which don't need a connection window
if([command isEqualToString:@"chooseItemFromList"]) {
NSString *statusFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryResultStatusPathHeader stringByExpandingTildeInPath], (passedProcessID && [passedProcessID length]) ? passedProcessID : @""];
NSString *resultFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryResultPathHeader stringByExpandingTildeInPath], (passedProcessID && [passedProcessID length]) ? passedProcessID : @""];
[fileManager removeItemAtPath:statusFileName error:nil];
[fileManager removeItemAtPath:resultFileName error:nil];
NSString *result = @"";
NSString *status = @"0";
if([parameter count]) {
NSInteger idx = [SPChooseMenuItemDialog withItems:parameter atPosition:[NSEvent mouseLocation]];
if(idx > -1) {
result = [parameter objectAtIndex:idx];
}
}
if(![status writeToFile:statusFileName atomically:YES encoding:NSUTF8StringEncoding error:nil]) {
NSBeep();
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"BASH Error", @"bash error") message:NSLocalizedString(@"Status file for sequelace url scheme command couldn't be written!", @"status file for sequelace url scheme command couldn't be written error message") callback:nil];
}
[result writeToFile:resultFileName atomically:YES encoding:NSUTF8StringEncoding error:nil];
return;
}
if([command isEqualToString:@"SyntaxHighlighting"]) {
BOOL isDir;
NSString *anUUID = (passedProcessID && [passedProcessID length]) ? passedProcessID : @"";
NSString *queryFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryInputPathHeader stringByExpandingTildeInPath], anUUID];
NSString *resultFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryResultPathHeader stringByExpandingTildeInPath], anUUID];
NSString *metaFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryResultMetaPathHeader stringByExpandingTildeInPath], anUUID];
NSString *statusFileName = [NSString stringWithFormat:@"%@%@", [SPURLSchemeQueryResultStatusPathHeader stringByExpandingTildeInPath], anUUID];
NSError *inError = nil;
NSString *query = [NSString stringWithContentsOfFile:queryFileName encoding:NSUTF8StringEncoding error:&inError];
NSString *result = @"";
NSString *status = @"0";