From fd3ff51dc624be5ce645ce25eb72d03e5a359416 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 5 Dec 2014 00:01:44 +0100 Subject: Add stub for SPTableContentFilterController And with that we are back to a build that should not spam your Console upon launch. (Sorry for the future merge conflict) :) --- Source/SPTableContentFilterController.h | 10 ++++++++++ Source/SPTableContentFilterController.m | 5 +++++ 2 files changed, 15 insertions(+) create mode 100644 Source/SPTableContentFilterController.h create mode 100644 Source/SPTableContentFilterController.m (limited to 'Source') diff --git a/Source/SPTableContentFilterController.h b/Source/SPTableContentFilterController.h new file mode 100644 index 00000000..15880416 --- /dev/null +++ b/Source/SPTableContentFilterController.h @@ -0,0 +1,10 @@ +// This class is a dummy. +// It is only present because DBView.xib already references it, but the +// code itself is still in another branch. This stub is used to avoid a warning +// from the Nib loader, saying 'this class was not found and replaced with a NSObject'. + +#import + +@interface SPTableContentFilterController : NSObject + +@end diff --git a/Source/SPTableContentFilterController.m b/Source/SPTableContentFilterController.m new file mode 100644 index 00000000..39c0f722 --- /dev/null +++ b/Source/SPTableContentFilterController.m @@ -0,0 +1,5 @@ +#import "SPTableContentFilterController.h" + +@implementation SPTableContentFilterController + +@end -- cgit v1.2.3 From 00d1e5aee581ff413ded538a470ade2073bb6a43 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 02:38:16 +0100 Subject: Changed a few typedef enums to Apples new method --- Source/SPConstants.h | 41 +++++++++++++++++++---------------------- Source/SPConstants.m | 10 ---------- 2 files changed, 19 insertions(+), 32 deletions(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 6c9f4a68..fd7afe40 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -46,23 +46,21 @@ typedef enum { } SPViewMode; // Query modes -enum { +typedef NS_ENUM(NSUInteger, SPQueryMode) { SPInterfaceQueryMode = 0, SPCustomQueryQueryMode = 1, SPImportExportQueryMode = 2 }; -typedef NSUInteger SPQueryMode; // Connection types -enum { +typedef NS_ENUM(NSUInteger, SPConnectionType) { SPTCPIPConnection = 0, SPSocketConnection = 1, SPSSHTunnelConnection = 2 -}; -typedef NSUInteger SPConnectionType; +}; // Export type constants -enum { +typedef NS_ENUM(NSUInteger, SPExportType) { SPSQLExport = 0, SPCSVExport = 1, SPXMLExport = 2, @@ -71,29 +69,25 @@ enum { SPHTMLExport = 5, SPExcelExport = 6 }; -typedef NSUInteger SPExportType; // Export source constants -enum { +typedef NS_ENUM(NSUInteger, SPExportSource) { SPFilteredExport = 0, SPQueryExport = 1, SPTableExport = 2 }; -typedef NSUInteger SPExportSource; // SQL export INSERT statment divider constants -enum { +typedef NS_ENUM(NSUInteger , SPSQLExportInsertDivider) { SPSQLInsertEveryNDataBytes = 0, SPSQLInsertEveryNRows = 1 }; -typedef NSUInteger SPSQLExportInsertDivider; // XML export formats -enum { +typedef NS_ENUM(NSUInteger, SPXMLExportFormat) { SPXMLExportMySQLFormat = 0, SPXMLExportPlainFormat = 1 }; -typedef NSUInteger SPXMLExportFormat; // Table row count query usage levels typedef enum { @@ -214,6 +208,7 @@ typedef enum // Export file handle creation typedef enum { + SPExportFileHandleInvalid = -1, SPExportFileHandleCreated = 0, SPExportFileHandleFailed = 1, SPExportFileHandleExists = 2 @@ -595,15 +590,17 @@ extern NSString *SPBundleShellVariableAllFunctions; extern NSString *SPBundleShellVariableAllViews; extern NSString *SPBundleShellVariableAllTables; -extern const NSInteger SPBundleRedirectActionNone; -extern const NSInteger SPBundleRedirectActionReplaceSection; -extern const NSInteger SPBundleRedirectActionReplaceContent; -extern const NSInteger SPBundleRedirectActionInsertAsText; -extern const NSInteger SPBundleRedirectActionInsertAsSnippet; -extern const NSInteger SPBundleRedirectActionShowAsHTML; -extern const NSInteger SPBundleRedirectActionShowAsTextTooltip; -extern const NSInteger SPBundleRedirectActionShowAsHTMLTooltip; -extern const NSInteger SPBundleRedirectActionLastCode; +typedef NS_ENUM(NSInteger, SPBundleRedirectAction) { + SPBundleRedirectActionNone = 200, + SPBundleRedirectActionReplaceSection = 201, + SPBundleRedirectActionReplaceContent = 202, + SPBundleRedirectActionInsertAsText = 203, + SPBundleRedirectActionInsertAsSnippet = 204, + SPBundleRedirectActionShowAsHTML = 205, + SPBundleRedirectActionShowAsTextTooltip = 207, + SPBundleRedirectActionShowAsHTMLTooltip = 208, + SPBundleRedirectActionLastCode = 208 +}; // URL scheme extern NSString *SPURLSchemeQueryInputPathHeader; diff --git a/Source/SPConstants.m b/Source/SPConstants.m index eb11ac11..e7b92884 100644 --- a/Source/SPConstants.m +++ b/Source/SPConstants.m @@ -412,16 +412,6 @@ NSString *SPBundleShellVariableSelectedText = @"SP_SELECTED_TEXT NSString *SPBundleShellVariableSelectedTextRange = @"SP_SELECTED_TEXT_RANGE"; NSString *SPBundleShellVariableUsedQueryForTable = @"SP_USED_QUERY_FOR_TABLE"; -const NSInteger SPBundleRedirectActionNone = 200; -const NSInteger SPBundleRedirectActionReplaceSection = 201; -const NSInteger SPBundleRedirectActionReplaceContent = 202; -const NSInteger SPBundleRedirectActionInsertAsText = 203; -const NSInteger SPBundleRedirectActionInsertAsSnippet = 204; -const NSInteger SPBundleRedirectActionShowAsHTML = 205; -const NSInteger SPBundleRedirectActionShowAsTextTooltip = 207; -const NSInteger SPBundleRedirectActionShowAsHTMLTooltip = 208; -const NSInteger SPBundleRedirectActionLastCode = 208; - // URL scheme NSString *SPURLSchemeQueryInputPathHeader = @"/tmp/SP_QUERY_"; NSString *SPURLSchemeQueryResultPathHeader = @"/tmp/SP_QUERY_RESULT_"; -- cgit v1.2.3 From 33fd38501be11213968536a0c540cee7061e42a9 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 02:45:23 +0100 Subject: Mark issue for s.o. to look at --- Source/SPTableContentDelegate.m | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'Source') diff --git a/Source/SPTableContentDelegate.m b/Source/SPTableContentDelegate.m index f6b933f7..2f78a120 100644 --- a/Source/SPTableContentDelegate.m +++ b/Source/SPTableContentDelegate.m @@ -367,10 +367,11 @@ else { tmp = [tableContentView draggedRowsAsTabString]; } - + +#warning code inside "if" is unreachable if (!tmp && [tmp length]) { - [pboard declareTypes:[NSArray arrayWithObjects: NSTabularTextPboardType, NSStringPboardType, nil] owner:nil]; + [pboard declareTypes:@[NSTabularTextPboardType, NSStringPboardType] owner:nil]; [pboard setString:tmp forType:NSStringPboardType]; [pboard setString:tmp forType:NSTabularTextPboardType]; -- cgit v1.2.3 From 4ad26db45b46d8267fcb5203571b81bc8949b853 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 03:01:19 +0100 Subject: Reformatting code for modern ObjC Replaced all [NSNumber numberWithBool:YES/NO] with the @YES/@NO literals. Also replaced some TRUE/FALSE with their YES/NO counterparts. --- Source/MGTemplateEngine.m | 12 ++++----- Source/MGTemplateStandardMarkers.m | 4 +-- Source/SPBundleEditorController.m | 6 ++--- Source/SPContentFilterManager.m | 6 ++--- Source/SPCustomQuery.m | 2 +- Source/SPDataImport.m | 12 ++++----- Source/SPDataStorage.m | 2 +- Source/SPDatabaseDocument.m | 52 +++++++++++++++++++------------------- Source/SPExportController.m | 30 +++++++++++----------- Source/SPExportInitializer.m | 6 ++--- Source/SPFieldMapperController.m | 8 +++--- Source/SPNavigatorController.m | 2 +- Source/SPPreferencesUpgrade.m | 2 +- Source/SPQueryController.m | 8 +++--- Source/SPQueryFavoriteManager.m | 4 +-- Source/SPSSHTunnel.m | 2 +- Source/SPTableContent.m | 2 +- Source/SPTableData.m | 49 +++++++++++++++++------------------ Source/SPTableStructure.m | 4 +-- Source/SPTableStructureLoading.m | 2 +- Source/SPTablesList.m | 28 ++++++++++---------- Source/SPUserManager.m | 8 +++--- Source/SPWindowManagement.m | 12 ++++----- 23 files changed, 130 insertions(+), 133 deletions(-) (limited to 'Source') diff --git a/Source/MGTemplateEngine.m b/Source/MGTemplateEngine.m index a6e15c2a..941a7e1b 100644 --- a/Source/MGTemplateEngine.m +++ b/Source/MGTemplateEngine.m @@ -408,12 +408,12 @@ nil], GLOBAL_ENGINE_DELIMITERS, nil] forKey:GLOBAL_ENGINE_GROUP]; - [_globals setObject:[NSNumber numberWithBool:YES] forKey:@"true"]; - [_globals setObject:[NSNumber numberWithBool:NO] forKey:@"false"]; - [_globals setObject:[NSNumber numberWithBool:YES] forKey:@"YES"]; - [_globals setObject:[NSNumber numberWithBool:NO] forKey:@"NO"]; - [_globals setObject:[NSNumber numberWithBool:YES] forKey:@"yes"]; - [_globals setObject:[NSNumber numberWithBool:NO] forKey:@"no"]; + [_globals setObject:@YES forKey:@"true"]; + [_globals setObject:@NO forKey:@"false"]; + [_globals setObject:@YES forKey:@"YES"]; + [_globals setObject:@NO forKey:@"NO"]; + [_globals setObject:@YES forKey:@"yes"]; + [_globals setObject:@NO forKey:@"no"]; _outputDisabledCount = 0; [templateContents release]; templateContents = [templateString retain]; diff --git a/Source/MGTemplateStandardMarkers.m b/Source/MGTemplateStandardMarkers.m index 3421abe3..db765aef 100644 --- a/Source/MGTemplateStandardMarkers.m +++ b/Source/MGTemplateStandardMarkers.m @@ -231,7 +231,7 @@ // Disable output for this block. *blockStarted = YES; NSMutableDictionary *stackFrame = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], FOR_STACK_DISABLED_OUTPUT, + @YES, FOR_STACK_DISABLED_OUTPUT, [NSValue valueWithRange:markerRange], STACK_START_MARKER_RANGE, [NSValue valueWithRange:*nextRange], STACK_START_REMAINING_RANGE, nil]; @@ -426,7 +426,7 @@ } // Note that we've now seen the else marker. - [frame setObject:[NSNumber numberWithBool:YES] forKey:IF_ELSE_SEEN]; + [frame setObject:@YES forKey:IF_ELSE_SEEN]; } } diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index 8ae9ceac..4aaa7cad 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -951,7 +951,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; if([[saveDict description] isEqualToString:[cmdData description]]) return YES; if([cmdData objectForKey:SPBundleFileIsDefaultBundleKey]) - [saveDict setObject:[NSNumber numberWithBool:YES] forKey:SPBundleFileDefaultBundleWasModifiedKey]; + [saveDict setObject:@YES forKey:SPBundleFileDefaultBundleWasModifiedKey]; } if (cmdData) [cmdData release]; } @@ -1357,9 +1357,9 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; //abort editing [control abortEditing]; [[NSApp mainWindow] makeFirstResponder:commandsOutlineView]; - return TRUE; + return YES; } else{ - return FALSE; + return NO; } } diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index 1322aa4a..9fe255ef 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -679,10 +679,10 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; [contentFilterNameTextField setStringValue: [[contentFilters objectAtIndex:[contentFilterTableView selectedRow]] objectForKey:@"MenuLabel"]]; - return TRUE; + return YES; } - return FALSE; + return NO; } /** @@ -931,7 +931,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; [spfdata setObject:[NSNumber numberWithInteger:1] forKey:@"version"]; [spfdata setObject:@"content filters" forKey:@"format"]; - [spfdata setObject:[NSNumber numberWithBool:NO] forKey:@"encrypted"]; + [spfdata setObject:@NO forKey:@"encrypted"]; NSIndexSet *indexes = [contentFilterTableView selectedRowIndexes]; diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 083de5c3..acfe7eac 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -3918,7 +3918,7 @@ // Preserve the focus [[tableDocumentInstance parentWindow] makeFirstResponder:customQueryView]; - return TRUE; + return YES; } } diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index 26c56348..ed17a506 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -662,7 +662,7 @@ [tablesListInstance updateTables:self]; // Re-query the structure of all databases in the background - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; // Import finished Growl notification [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Import Finished" @@ -1178,7 +1178,7 @@ [tablesListInstance performSelectorOnMainThread:@selector(updateTables:) withObject:self waitUntilDone:YES]; // Re-query the structure of all databases in the background - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; // Select the new table [tablesListInstance selectItemWithName:selectedTableTarget]; @@ -1215,7 +1215,7 @@ nil, nil, NSLocalizedString(@"Could not parse file as CSV", @"Error when we can't parse/split file as CSV") ); - return FALSE; + return YES; } // Sanity check the first row of the CSV to prevent hang loops caused by wrong line ending entry @@ -1228,7 +1228,7 @@ nil, nil, NSLocalizedString(@"The CSV was read as containing more than 512 columns, more than the maximum columns permitted for speed reasons by Sequel Pro.\n\nThis usually happens due to errors reading the CSV; please double-check the CSV to be imported and the line endings and escape characters at the bottom of the CSV selection dialog.", @"Error when CSV appears to have too many columns to import, probably due to line ending mismatch") ); - return FALSE; + return NO; } fieldMappingImportArrayIsPreview = dataIsPreviewData; @@ -1262,7 +1262,7 @@ // If the mapping was cancelled, abort the import if (fieldMapperSheetStatus == SPFieldMapperCancelled) { if (fieldMapperController) [fieldMapperController release]; - return FALSE; + return NO; } // Get mapping settings and preset some global variables @@ -1290,7 +1290,7 @@ { if(fieldMapperController) [fieldMapperController release]; NSBeep(); - return FALSE; + return NO; } // Store target table definitions diff --git a/Source/SPDataStorage.m b/Source/SPDataStorage.m index ed50c7fc..30be0644 100644 --- a/Source/SPDataStorage.m +++ b/Source/SPDataStorage.m @@ -391,7 +391,7 @@ static inline NSMutableArray* SPDataStorageGetEditedRow(NSPointerArray* rowStore if (columnIndex >= numberOfColumns) { [NSException raise:NSRangeException format:@"Invalid column set as unloaded; requested column index (%llu) beyond bounds (%llu)", (unsigned long long)columnIndex, (unsigned long long)numberOfColumns]; } - unloadedColumns[columnIndex] = true; + unloadedColumns[columnIndex] = YES; } #pragma mark - Basic information diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 654f06cd..4f09b3a8 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -552,10 +552,10 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; notificationName:@"Connected"]; // Init Custom Query editor with the stored queries in a spf file if given. - [spfDocData setObject:[NSNumber numberWithBool:NO] forKey:@"save_editor_content"]; + [spfDocData setObject:@NO forKey:@"save_editor_content"]; if (spfSession != nil && [spfSession objectForKey:@"queries"]) { - [spfDocData setObject:[NSNumber numberWithBool:YES] forKey:@"save_editor_content"]; + [spfDocData setObject:@YES forKey:@"save_editor_content"]; if ([[spfSession objectForKey:@"queries"] isKindOfClass:[NSData class]]) { NSString *q = [[NSString alloc] initWithData:[[spfSession objectForKey:@"queries"] decompress] encoding:NSUTF8StringEncoding]; [self initQueryEditorWithString:q]; @@ -1012,7 +1012,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [self _addDatabase]; // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:databaseStructureRetrieval selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:databaseStructureRetrieval selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } else { // Reset chooseDatabaseButton @@ -3072,7 +3072,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } } - [fileManager createDirectoryAtPath:fileName withIntermediateDirectories:TRUE attributes:nil error:&error]; + [fileManager createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:&error]; if(error != nil) { NSAlert *errorAlert = [NSAlert alertWithError:error]; @@ -3080,7 +3080,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; return; } - [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Contents", fileName] withIntermediateDirectories:TRUE attributes:nil error:&error]; + [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Contents", fileName] withIntermediateDirectories:YES attributes:nil error:&error]; if(error != nil) { NSAlert *errorAlert = [NSAlert alertWithError:error]; @@ -3142,12 +3142,12 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // save it as temporary spf file inside the bundle with save panel options spfDocData_temp [doc saveDocumentWithFilePath:filePath inBackground:NO onlyPreferences:NO contextInfo:[NSDictionary dictionaryWithDictionary:spfDocData_temp]]; [doc setIsSavedInBundle:YES]; - [tabData setObject:[NSNumber numberWithBool:NO] forKey:@"isAbsolutePath"]; + [tabData setObject:@NO forKey:@"isAbsolutePath"]; [tabData setObject:newName forKey:@"path"]; } else { // save it to the original location and take the file's spfDocData [doc saveDocumentWithFilePath:[[doc fileURL] path] inBackground:YES onlyPreferences:NO contextInfo:nil]; - [tabData setObject:[NSNumber numberWithBool:YES] forKey:@"isAbsolutePath"]; + [tabData setObject:@YES forKey:@"isAbsolutePath"]; [tabData setObject:[[doc fileURL] path] forKey:@"path"]; } [tabs addObject:tabData]; @@ -3219,7 +3219,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionAutoConnect state]==NSOnState) ? YES : NO ] forKey:@"auto_connect"]; [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionSavePassword state]==NSOnState) ? YES : NO ] forKey:@"save_password"]; [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionIncludeData state]==NSOnState) ? YES : NO ] forKey:@"include_session"]; - [spfDocData_temp setObject:[NSNumber numberWithBool:NO] forKey:@"save_editor_content"]; + [spfDocData_temp setObject:@NO forKey:@"save_editor_content"]; if([[[[customQueryInstance valueForKeyPath:@"textView"] textStorage] string] length]) [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionIncludeQuery state]==NSOnState) ? YES : NO ] forKey:@"save_editor_content"]; @@ -3334,23 +3334,23 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Set up the document details to store NSMutableDictionary *stateDetailsToSave = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], @"connection", - [NSNumber numberWithBool:YES], @"history", + @YES, @"connection", + @YES, @"history", nil]; // Include session data like selected table, view etc. ? if ([[spfDocData_temp objectForKey:@"include_session"] boolValue]) - [stateDetailsToSave setObject:[NSNumber numberWithBool:YES] forKey:@"session"]; + [stateDetailsToSave setObject:@YES forKey:@"session"]; // Include the query editor contents if asked to if ([[spfDocData_temp objectForKey:@"save_editor_content"] boolValue]) { - [stateDetailsToSave setObject:[NSNumber numberWithBool:YES] forKey:@"query"]; - [stateDetailsToSave setObject:[NSNumber numberWithBool:YES] forKey:@"enablecompression"]; + [stateDetailsToSave setObject:@YES forKey:@"query"]; + [stateDetailsToSave setObject:@YES forKey:@"enablecompression"]; } // Add passwords if asked to if ([[spfDocData_temp objectForKey:@"save_password"] boolValue]) - [stateDetailsToSave setObject:[NSNumber numberWithBool:YES] forKey:@"password"]; + [stateDetailsToSave setObject:@YES forKey:@"password"]; // Retrieve details and add to the appropriate dictionaries NSMutableDictionary *stateDetails = [NSMutableDictionary dictionaryWithDictionary:[self stateIncludingDetails:stateDetailsToSave]]; @@ -3444,16 +3444,16 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Get the current state NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], @"connection", - [NSNumber numberWithBool:YES], @"history", - [NSNumber numberWithBool:YES], @"session", - [NSNumber numberWithBool:YES], @"query", - [NSNumber numberWithBool:YES], @"password", + @YES, @"connection", + @YES, @"history", + @YES, @"session", + @YES, @"query", + @YES, @"password", nil]; NSMutableDictionary *currentState = [NSMutableDictionary dictionaryWithDictionary:[self stateIncludingDetails:allStateDetails]]; // Ensure it's set to autoconnect, and clear the table - [currentState setObject:[NSNumber numberWithBool:YES] forKey:@"auto_connect"]; + [currentState setObject:@YES forKey:@"auto_connect"]; NSMutableDictionary *sessionDict = [NSMutableDictionary dictionaryWithDictionary:[currentState objectForKey:@"session"]]; [sessionDict removeObjectForKey:@"table"]; [currentState setObject:sessionDict forKey:@"session"]; @@ -4917,16 +4917,16 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [data setObject:[spf objectForKey:SPContentFilters] forKey:SPContentFilters]; // Ensure the encryption status is stored in the spfDocData store for future saves - [spfDocData setObject:[NSNumber numberWithBool:NO] forKey:@"encrypted"]; + [spfDocData setObject:@NO forKey:@"encrypted"]; if (encryptpw != nil) { - [spfDocData setObject:[NSNumber numberWithBool:YES] forKey:@"encrypted"]; + [spfDocData setObject:@YES forKey:@"encrypted"]; [spfDocData setObject:encryptpw forKey:@"e_string"]; } encryptpw = nil; // If session data is available, ensure it is marked for save if ([data objectForKey:@"session"]) { - [spfDocData setObject:[NSNumber numberWithBool:YES] forKey:@"include_session"]; + [spfDocData setObject:@YES forKey:@"include_session"]; } if (![self isSaveInBundle]) { @@ -4935,11 +4935,11 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [spfDocData setObject:[NSNumber numberWithBool:([[data objectForKey:@"connection"] objectForKey:@"password"]) ? YES : NO] forKey:@"save_password"]; - [spfDocData setObject:[NSNumber numberWithBool:NO] forKey:@"auto_connect"]; + [spfDocData setObject:@NO forKey:@"auto_connect"]; if([spf objectForKey:@"auto_connect"] && [[spf valueForKey:@"auto_connect"] boolValue]) { - [spfDocData setObject:[NSNumber numberWithBool:YES] forKey:@"auto_connect"]; - [data setObject:[NSNumber numberWithBool:YES] forKey:@"auto_connect"]; + [spfDocData setObject:@YES forKey:@"auto_connect"]; + [data setObject:@YES forKey:@"auto_connect"]; } // Set the state dictionary, triggering an autoconnect if appropriate diff --git a/Source/SPExportController.m b/Source/SPExportController.m index 3fb07267..4a97ae00 100644 --- a/Source/SPExportController.m +++ b/Source/SPExportController.m @@ -191,9 +191,9 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; // Disable all tables for (NSMutableArray *table in tables) { - [table replaceObjectAtIndex:1 withObject:[NSNumber numberWithBool:NO]]; - [table replaceObjectAtIndex:2 withObject:[NSNumber numberWithBool:NO]]; - [table replaceObjectAtIndex:3 withObject:[NSNumber numberWithBool:NO]]; + [table replaceObjectAtIndex:1 withObject:@NO]; + [table replaceObjectAtIndex:2 withObject:@NO]; + [table replaceObjectAtIndex:3 withObject:@NO]; } // Select the supplied tables @@ -202,9 +202,9 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; for (NSString *exportTable in exportTables) { if ([exportTable isEqualToString:[table objectAtIndex:0]]) { - [table replaceObjectAtIndex:1 withObject:[NSNumber numberWithBool:YES]]; - [table replaceObjectAtIndex:2 withObject:[NSNumber numberWithBool:YES]]; - [table replaceObjectAtIndex:3 withObject:[NSNumber numberWithBool:YES]]; + [table replaceObjectAtIndex:1 withObject:@YES]; + [table replaceObjectAtIndex:2 withObject:@YES]; + [table replaceObjectAtIndex:3 withObject:@YES]; } } } @@ -436,9 +436,9 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; for (id itemName in tablesAndViews) { [tables addObject:[NSMutableArray arrayWithObjects: itemName, - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], + @YES, + @YES, + @YES, [NSNumber numberWithInt:SPTableTypeTable], nil]]; } @@ -451,9 +451,9 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; { [tables addObject:[NSMutableArray arrayWithObjects: procName, - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], + @YES, + @YES, + @YES, [NSNumber numberWithInt:SPTableTypeProc], nil]]; } @@ -464,9 +464,9 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; { [tables addObject:[NSMutableArray arrayWithObjects: funcName, - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], - [NSNumber numberWithBool:YES], + @YES, + @YES, + @YES, [NSNumber numberWithInt:SPTableTypeFunc], nil]]; } diff --git a/Source/SPExportInitializer.m b/Source/SPExportInitializer.m index bb59dd60..9c626a53 100644 --- a/Source/SPExportInitializer.m +++ b/Source/SPExportInitializer.m @@ -126,15 +126,15 @@ // Check the overall export settings if ([[table objectAtIndex:1] boolValue] && (![exportSQLIncludeStructureCheck state])) { - [table replaceObjectAtIndex:1 withObject:[NSNumber numberWithBool:NO]]; + [table replaceObjectAtIndex:1 withObject:@NO]; } if ([[table objectAtIndex:2] boolValue] && (![exportSQLIncludeContentCheck state])) { - [table replaceObjectAtIndex:2 withObject:[NSNumber numberWithBool:NO]]; + [table replaceObjectAtIndex:2 withObject:@NO]; } if ([[table objectAtIndex:3] boolValue] && (![exportSQLIncludeDropSyntaxCheck state])) { - [table replaceObjectAtIndex:3 withObject:[NSNumber numberWithBool:NO]]; + [table replaceObjectAtIndex:3 withObject:@NO]; } [exportTables addObject:table]; diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index 397c017f..aaa6c0bc 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -1120,7 +1120,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; - (IBAction)addGlobalValue:(id)sender { [fieldMappingGlobalValues addObject:@""]; - [fieldMappingGlobalValuesSQLMarked addObject:[NSNumber numberWithBool:NO]]; + [fieldMappingGlobalValuesSQLMarked addObject:@NO]; [globalValuesTableView reloadData]; [globalValuesTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fieldMappingGlobalValues count]-1-numberOfImportColumns] byExtendingSelection:NO]; [globalValuesTableView editColumn:1 row:[fieldMappingGlobalValues count]-1-numberOfImportColumns withEvent:nil select:YES]; @@ -1432,7 +1432,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; } // Sort the matrix according distance - NSSortDescriptor *sortByDistance = [[[NSSortDescriptor alloc] initWithKey:@"dist" ascending:TRUE] autorelease]; + NSSortDescriptor *sortByDistance = [[[NSSortDescriptor alloc] initWithKey:@"dist" ascending:YES] autorelease]; [distMatrix sortUsingDescriptors:[NSArray arrayWithObjects:sortByDistance, nil]]; NSMutableArray *matchedFile = [NSMutableArray array]; @@ -2091,10 +2091,10 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // Preserve the focus [[fieldMapperTableView window] makeFirstResponder:fieldMapperTableView]; - return TRUE; + return YES; } - return FALSE; + return NO; } diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index 1a7e52fd..67070472 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -611,7 +611,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if (![[doc getConnection] isConnected]) return; - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[doc databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[doc databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } - (IBAction)outlineViewAction:(id)sender diff --git a/Source/SPPreferencesUpgrade.m b/Source/SPPreferencesUpgrade.m index d4a9ca84..6151f675 100644 --- a/Source/SPPreferencesUpgrade.m +++ b/Source/SPPreferencesUpgrade.m @@ -76,7 +76,7 @@ void SPApplyRevisionChanges(void) } // Inform SPAppController to check installed default Bundles for available updates - [prefs setObject:[NSNumber numberWithBool:YES] forKey:@"doBundleUpdate"]; + [prefs setObject:@YES forKey:@"doBundleUpdate"]; // For versions prior to r336 (0.9.4), where column widths have been saved, walk through them and remove // any table widths set to 15 or less (fix for mangled columns caused by Issue #140) diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m index 718a5ff3..3e33b533 100644 --- a/Source/SPQueryController.m +++ b/Source/SPQueryController.m @@ -458,7 +458,7 @@ static SPQueryController *sharedQueryController = nil; [progressIndicator startAnimation:self]; // Don't allow clearing the console while filtering its content - [self _allowFilterClearOrSave:[NSNumber numberWithBool:NO]]; + [self _allowFilterClearOrSave:@NO]; [messagesFilteredSet removeAllObjects]; @@ -470,7 +470,7 @@ static SPQueryController *sharedQueryController = nil; [consoleTableView reloadData]; [consoleTableView scrollRowToVisible:([messagesVisibleSet count] - 1)]; - [self _allowFilterClearOrSave:[NSNumber numberWithBool:YES]]; + [self _allowFilterClearOrSave:@YES]; [saveConsoleButton setTitle:NSLocalizedString(@"Save As...", @"save as button title")]; @@ -502,7 +502,7 @@ static SPQueryController *sharedQueryController = nil; [consoleTableView scrollRowToVisible:([messagesVisibleSet count] - 1)]; if ([messagesVisibleSet count] > 0) { - [self _allowFilterClearOrSave:[NSNumber numberWithBool:YES]]; + [self _allowFilterClearOrSave:@YES]; } [saveConsoleButton setTitle:NSLocalizedString(@"Save View As...", @"save view as button title")]; @@ -623,7 +623,7 @@ static SPQueryController *sharedQueryController = nil; && [self _messageMatchesCurrentFilters:[consoleMessage message]]) { [messagesFilteredSet addObject:[messagesFullSet lastObject]]; - [self performSelectorOnMainThread:@selector(_allowFilterClearOrSave:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO]; + [self performSelectorOnMainThread:@selector(_allowFilterClearOrSave:) withObject:@YES waitUntilDone:NO]; } // Reload the table and scroll to the new message if it's visible (for speed) diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index 97f7790b..a7147646 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -422,7 +422,7 @@ // Identify the tab completion index NSRange snippetNumberRange = [queryString rangeOfRegex:snipRegex options:RKLNoOptions inRange:matchedRange capture:1L error:NULL]; NSInteger snippetNumber = [[queryString substringWithRange:snippetNumberRange] integerValue]; - [snippetNumbers setObject:[NSNumber numberWithBool:YES] forKey:[NSNumber numberWithInteger:snippetNumber]]; + [snippetNumbers setObject:@YES forKey:[NSNumber numberWithInteger:snippetNumber]]; rangeStart = matchedRange.location + matchedRange.length; } @@ -919,7 +919,7 @@ [spfdata setObject:[NSNumber numberWithInteger:1] forKey:@"version"]; [spfdata setObject:@"query favorites" forKey:@"format"]; - [spfdata setObject:[NSNumber numberWithBool:NO] forKey:@"encrypted"]; + [spfdata setObject:@NO forKey:@"encrypted"]; NSIndexSet *indexes = [favoritesTableView selectedRowIndexes]; diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index ff220318..20f1aa43 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -116,7 +116,7 @@ delegate = theDelegate; stateChangeSelector = theStateChangeSelector; - return true; + return YES; } /* diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 892fe30f..9e190cb2 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -3851,7 +3851,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper NSUInteger indexCount = [selectedRowIndexes getIndexes:indexBuffer maxCount:[selectedRowIndexes count] inIndexRange:NULL]; NSMutableDictionary *selectedRowLookupTable = [NSMutableDictionary dictionaryWithCapacity:indexCount]; - NSNumber *trueNumber = [NSNumber numberWithBool:YES]; + NSNumber *trueNumber = @YES; for (NSUInteger i = 0; i < indexCount; i++) { // For single-column primary keys, use the cell value as a dictionary key for fast lookups diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 5158d4be..00de39da 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -390,7 +390,7 @@ // The table information fetch may have already unlocked the data lock. pthread_mutex_trylock(&dataProcessingLock); pthread_mutex_unlock(&dataProcessingLock); - return FALSE; + return NO; } [columns addObjectsFromArray:[tableData objectForKey:@"columns"]]; @@ -408,7 +408,7 @@ pthread_mutex_unlock(&dataProcessingLock); - return TRUE; + return YES; } /** @@ -431,7 +431,7 @@ [columnNames removeAllObjects]; [constraints removeAllObjects]; pthread_mutex_unlock(&dataProcessingLock); - return FALSE; + return NO; } [columns addObjectsFromArray:[viewData objectForKey:@"columns"]]; @@ -448,7 +448,7 @@ pthread_mutex_unlock(&dataProcessingLock); - return TRUE; + return YES; } /** @@ -915,9 +915,9 @@ // If there's a null column, use the details from it if ([resultRow objectForKey:@"Null"]) { if ([[[resultRow objectForKey:@"Null"] uppercaseString] isEqualToString:@"NO"]) { - [tableColumn setValue:[NSNumber numberWithBool:NO] forKey:@"null"]; + [tableColumn setValue:@NO forKey:@"null"]; } else { - [tableColumn setValue:[NSNumber numberWithBool:YES] forKey:@"null"]; + [tableColumn setValue:@YES forKey:@"null"]; } } @@ -957,7 +957,7 @@ // Catch unselected tables and return false if (![tableListInstance tableName]) { pthread_mutex_unlock(&dataProcessingLock); - return FALSE; + return NO; } // Ensure queries are run as UTF8 @@ -1004,7 +1004,7 @@ if (changeEncoding) [mySQLConnection restoreStoredEncoding]; } pthread_mutex_unlock(&dataProcessingLock); - return FALSE; + return NO; } // Retrieve the status as a dictionary and set as the cache @@ -1022,7 +1022,7 @@ [status setDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"Error", @"Engine", [NSString stringWithFormat:NSLocalizedString(@"An error occurred retrieving table information. MySQL said: %@", @"MySQL table info retrieval error message"), [status objectForKey:@"Comment"]], @"Comment", [tableListInstance tableName], @"Name", nil]]; if (changeEncoding) [mySQLConnection restoreStoredEncoding]; pthread_mutex_unlock(&dataProcessingLock); - return FALSE; + return NO; } // Add a note for whether the row count is accurate or not - only for MyISAM @@ -1058,7 +1058,7 @@ pthread_mutex_unlock(&dataProcessingLock); - return TRUE; + return YES; } /** @@ -1267,16 +1267,13 @@ [detailString release]; - NSNumber *boolYES = [NSNumber numberWithBool:YES]; - NSNumber *boolNO = [NSNumber numberWithBool:NO]; - // Set up some column defaults for all columns - [fieldDetails setValue:boolYES forKey:@"null"]; - [fieldDetails setValue:boolNO forKey:@"unsigned"]; - [fieldDetails setValue:boolNO forKey:@"binary"]; - [fieldDetails setValue:boolNO forKey:@"zerofill"]; - [fieldDetails setValue:boolNO forKey:@"autoincrement"]; - [fieldDetails setValue:boolNO forKey:@"onupdatetimestamp"]; + [fieldDetails setValue:@YES forKey:@"null"]; + [fieldDetails setValue:@NO forKey:@"unsigned"]; + [fieldDetails setValue:@NO forKey:@"binary"]; + [fieldDetails setValue:@NO forKey:@"zerofill"]; + [fieldDetails setValue:@NO forKey:@"autoincrement"]; + [fieldDetails setValue:@NO forKey:@"onupdatetimestamp"]; [fieldDetails setValue:@"" forKey:@"comment"]; [fieldDetails setValue:[NSMutableString string] forKey:@"unparsed"]; @@ -1288,15 +1285,15 @@ // Whether numeric fields are unsigned if ([detailString isEqualToString:@"UNSIGNED"]) { - [fieldDetails setValue:boolYES forKey:@"unsigned"]; + [fieldDetails setValue:@YES forKey:@"unsigned"]; // Whether numeric fields are zerofill } else if ([detailString isEqualToString:@"ZEROFILL"]) { - [fieldDetails setValue:boolYES forKey:@"zerofill"]; + [fieldDetails setValue:@YES forKey:@"zerofill"]; // Whether text types are binary } else if ([detailString isEqualToString:@"BINARY"]) { - [fieldDetails setValue:boolYES forKey:@"binary"]; + [fieldDetails setValue:@YES forKey:@"binary"]; // Whether text types have a different encoding to the table } else if ([detailString isEqualToString:@"CHARSET"] && (definitionPartsIndex + 1 < partsArrayLength)) { @@ -1321,16 +1318,16 @@ // Whether fields are NOT NULL } else if ([detailString isEqualToString:@"NOT"] && (definitionPartsIndex + 1 < partsArrayLength) && [[NSArrayObjectAtIndex(definitionParts, definitionPartsIndex+1) uppercaseString] isEqualToString:@"NULL"]) { - [fieldDetails setValue:boolNO forKey:@"null"]; + [fieldDetails setValue:@NO forKey:@"null"]; definitionPartsIndex++; // Whether fields are NULL } else if ([detailString isEqualToString:@"NULL"]) { - [fieldDetails setValue:boolYES forKey:@"null"]; + [fieldDetails setValue:@YES forKey:@"null"]; // Whether fields should auto-increment } else if ([detailString isEqualToString:@"AUTO_INCREMENT"]) { - [fieldDetails setValue:boolYES forKey:@"autoincrement"]; + [fieldDetails setValue:@YES forKey:@"autoincrement"]; tableHasAutoIncrementField = YES; // Field defaults @@ -1347,7 +1344,7 @@ } else if ([detailString isEqualToString:@"ON"] && (definitionPartsIndex + 2 < partsArrayLength) && [[NSArrayObjectAtIndex(definitionParts, definitionPartsIndex+1) uppercaseString] isEqualToString:@"UPDATE"] && [[NSArrayObjectAtIndex(definitionParts, definitionPartsIndex+2) uppercaseString] isEqualToString:@"CURRENT_TIMESTAMP"]) { - [fieldDetails setValue:boolYES forKey:@"onupdatetimestamp"]; + [fieldDetails setValue:@YES forKey:@"onupdatetimestamp"]; definitionPartsIndex += 2; // Column comments diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 05bf1186..310af941 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -964,7 +964,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [tableDocumentInstance setContentRequiresReload:YES]; // Query the structure of all databases in the background - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", selectedTable, @"affectedItem", [NSNumber numberWithInteger:[tablesListInstance tableType]], @"affectedItemType", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", selectedTable, @"affectedItem", [NSNumber numberWithInteger:[tablesListInstance tableType]], @"affectedItemType", nil]]; return YES; } @@ -1059,7 +1059,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; // on the main thread ensures the timer fires on the main thread. if (![errorDictionary objectForKey:@"delayed"]) { NSMutableDictionary *delayedErrorDictionary = [NSMutableDictionary dictionaryWithDictionary:errorDictionary]; - [delayedErrorDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"delayed"]; + [delayedErrorDictionary setObject:@YES forKey:@"delayed"]; [self performSelector:@selector(showErrorSheetWith:) withObject:delayedErrorDictionary afterDelay:0.3]; return; } diff --git a/Source/SPTableStructureLoading.m b/Source/SPTableStructureLoading.m index 9e9edd5c..a2a90f40 100644 --- a/Source/SPTableStructureLoading.m +++ b/Source/SPTableStructureLoading.m @@ -290,7 +290,7 @@ [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; [self loadTable:selectedTable]; } diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index fdabd3af..458389c2 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -360,7 +360,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:nil]; else // User press refresh button ergo force update - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", [NSNumber numberWithBool:YES], @"cancelQuerying", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", @YES, @"cancelQuerying", nil]]; } /** @@ -705,16 +705,16 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; { // Get the state of the document NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], @"connection", - [NSNumber numberWithBool:YES], @"history", - [NSNumber numberWithBool:YES], @"session", - [NSNumber numberWithBool:YES], @"query", - [NSNumber numberWithBool:YES], @"password", + @YES, @"connection", + @YES, @"history", + @YES, @"session", + @YES, @"query", + @YES, @"password", nil]; NSMutableDictionary *documentState = [NSMutableDictionary dictionaryWithDictionary:[tableDocumentInstance stateIncludingDetails:allStateDetails]]; // Ensure it's set to autoconnect - [documentState setObject:[NSNumber numberWithBool:YES] forKey:@"auto_connect"]; + [documentState setObject:@YES forKey:@"auto_connect"]; // Set the connection on the new tab [[[NSApp delegate] frontDocument] setState:documentState]; @@ -1621,7 +1621,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; #endif // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } #ifndef SP_CODA @@ -1637,7 +1637,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; // When enter/return is used, save the row. if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(insertNewline:)] ) { [[control window] makeFirstResponder:control]; - return TRUE; + return YES; // When the escape key is used, abort the rename. } else if ( [[control window] methodForSelector:command] == [[control window] methodForSelector:@selector(cancelOperation:)] || @@ -1646,9 +1646,9 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [control abortEditing]; [[NSApp mainWindow] makeFirstResponder:tablesListView]; - return TRUE; + return YES; } else{ - return FALSE; + return NO; } } #endif @@ -2279,7 +2279,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } #ifndef SP_CODA /* operations performed on whole tables */ @@ -2430,7 +2430,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } else { // Error while creating new table @@ -2637,7 +2637,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [tableDocumentInstance loadTable:selectedTableName ofType:selectedTableType]; // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; } } } diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m index 3ac9e5de..917c73ae 100644 --- a/Source/SPUserManager.m +++ b/Source/SPUserManager.m @@ -183,7 +183,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; [privKey replaceOccurrencesOfString:@" " withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, [privKey length])]; [privKey appendString:@"_priv"]; - [[self privsSupportedByServer] setValue:[NSNumber numberWithBool:YES] forKey:privKey]; + [[self privsSupportedByServer] setValue:@YES forKey:privKey]; } } // If that fails, base privilege support on the mysql.users columns @@ -200,7 +200,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; if ([privColumnToGrantMap objectForKey:privKey]) privKey = [privColumnToGrantMap objectForKey:privKey]; - [[self privsSupportedByServer] setValue:[NSNumber numberWithBool:YES] forKey:[privKey lowercaseString]]; + [[self privsSupportedByServer] setValue:@YES forKey:[privKey lowercaseString]]; } } @@ -580,7 +580,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; // Perform the change in a try/catch check to avoid exceptions for unhandled privs NS_DURING - [selectedUser setValue:[NSNumber numberWithBool:YES] forKey:key]; + [selectedUser setValue:@YES forKey:key]; NS_HANDLER NS_ENDHANDLER } @@ -600,7 +600,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; // Perform the change in a try/catch check to avoid exceptions for unhandled privs NS_DURING - [selectedUser setValue:[NSNumber numberWithBool:NO] forKey:key]; + [selectedUser setValue:@NO forKey:key]; NS_HANDLER NS_ENDHANDLER } diff --git a/Source/SPWindowManagement.m b/Source/SPWindowManagement.m index 000bbe3f..022ad7fa 100644 --- a/Source/SPWindowManagement.m +++ b/Source/SPWindowManagement.m @@ -117,17 +117,17 @@ // Get the state of the previously-frontmost document NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], @"connection", - [NSNumber numberWithBool:YES], @"history", - [NSNumber numberWithBool:YES], @"session", - [NSNumber numberWithBool:YES], @"query", - [NSNumber numberWithBool:YES], @"password", + @YES, @"connection", + @YES, @"history", + @YES, @"session", + @YES, @"query", + @YES, @"password", nil]; NSMutableDictionary *frontState = [NSMutableDictionary dictionaryWithDictionary:[theFrontDocument stateIncludingDetails:allStateDetails]]; // Ensure it's set to autoconnect - [frontState setObject:[NSNumber numberWithBool:YES] forKey:@"auto_connect"]; + [frontState setObject:@YES forKey:@"auto_connect"]; // Set the connection on the new tab [[self frontDocument] setState:frontState]; -- cgit v1.2.3 From 3cf0254e55d558565775e6cb20d36ea7e54beca1 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 03:12:41 +0100 Subject: Replace boxed integers in code with @ literals --- Source/GeneratePreviewForURL.m | 2 +- Source/MGTemplateStandardMarkers.m | 2 +- Source/SPAppController.m | 12 ++++++------ Source/SPConnectionController.m | 4 ++-- Source/SPContentFilterManager.m | 2 +- Source/SPCustomQuery.m | 14 +++++++------- Source/SPDatabaseDocument.m | 18 +++++++++--------- Source/SPFieldMapperController.m | 10 +++++----- Source/SPNavigatorController.m | 20 ++++++++++---------- Source/SPPreferencesUpgrade.m | 8 ++++---- Source/SPPrintController.m | 2 +- Source/SPQueryFavoriteManager.m | 2 +- Source/SPTableContent.m | 14 +++++++------- Source/SPTableData.m | 4 ++-- Source/SPTableInfo.m | 4 ++-- Source/SPTableStructure.m | 4 ++-- Source/SPTableStructureDelegate.m | 6 +++--- Source/SPTableStructureLoading.m | 2 +- 18 files changed, 65 insertions(+), 65 deletions(-) (limited to 'Source') diff --git a/Source/GeneratePreviewForURL.m b/Source/GeneratePreviewForURL.m index 2e0fc0cb..034d7bd1 100644 --- a/Source/GeneratePreviewForURL.m +++ b/Source/GeneratePreviewForURL.m @@ -488,7 +488,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, imgProps = [[NSMutableDictionary alloc] initWithCapacity:2]; [props setObject:[NSNumber numberWithInteger:previewHeight] forKey:(NSString *)kQLPreviewPropertyHeightKey]; - [props setObject:[NSNumber numberWithInt:600] forKey:(NSString *)kQLPreviewPropertyWidthKey]; + [props setObject:@600 forKey:(NSString *) kQLPreviewPropertyWidthKey]; if(image) { [imgProps setObject:@"image/tiff" forKey:(NSString *)kQLPreviewPropertyMIMETypeKey]; diff --git a/Source/MGTemplateStandardMarkers.m b/Source/MGTemplateStandardMarkers.m index db765aef..543d16a7 100644 --- a/Source/MGTemplateStandardMarkers.m +++ b/Source/MGTemplateStandardMarkers.m @@ -522,7 +522,7 @@ } else { // New cycle. Create and output appropriately. cycle = [NSMutableDictionary dictionaryWithCapacity:2]; - [cycle setObject:[NSNumber numberWithInteger:0] forKey:CYCLE_INDEX]; + [cycle setObject:@0 forKey:CYCLE_INDEX]; [cycle setObject:args forKey:CYCLE_VALUES]; [cycles setObject:cycle forKey:rangeKey]; return [args objectAtIndex:0]; diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 44f3513d..ba9c6cab 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -1243,12 +1243,12 @@ SPDatabaseDocument* frontMostDoc = [self frontDocument]; if(frontMostDoc) { if([runningActivitiesArray count] || [[frontMostDoc runningActivities] count]) - [frontMostDoc performSelector:@selector(setActivityPaneHidden:) withObject:[NSNumber numberWithInteger:0] afterDelay:1.0]; + [frontMostDoc performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:frontMostDoc selector:@selector(setActivityPaneHidden:) - object:[NSNumber numberWithInteger:0]]; - [frontMostDoc setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + object:@0]; + [frontMostDoc setActivityPaneHidden:@1]; } } @@ -1268,12 +1268,12 @@ SPDatabaseDocument* frontMostDoc = [self frontDocument]; if(frontMostDoc) { if([runningActivitiesArray count] || [[frontMostDoc runningActivities] count]) - [frontMostDoc performSelector:@selector(setActivityPaneHidden:) withObject:[NSNumber numberWithInteger:0] afterDelay:1.0]; + [frontMostDoc performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:frontMostDoc selector:@selector(setActivityPaneHidden:) - object:[NSNumber numberWithInteger:0]]; - [frontMostDoc setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + object:@0]; + [frontMostDoc setActivityPaneHidden:@1]; } } } diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index a91f6929..905975dc 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -781,11 +781,11 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, NSArray *objects = [NSArray arrayWithObjects: NSLocalizedString(@"New Favorite", @"new favorite name"), - [NSNumber numberWithInteger:0], + @0, @"", @"", @"", - [NSNumber numberWithInteger:-1], + @(-1), @"", [NSNumber numberWithInt:NSOffState], [NSNumber numberWithInt:NSOffState], diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index 9fe255ef..c08e84b9 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -929,7 +929,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; NSMutableArray *filterData = [NSMutableArray array]; - [spfdata setObject:[NSNumber numberWithInteger:1] forKey:@"version"]; + [spfdata setObject:@1 forKey:@"version"]; [spfdata setObject:@"content filters" forKey:@"format"]; [spfdata setObject:@NO forKey:@"encrypted"]; diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index acfe7eac..ba053dbf 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -1808,7 +1808,7 @@ NSDictionary *columnDefinition = [NSDictionary dictionaryWithDictionary:[cqColumnDefinition objectAtIndex:[[[[customQueryView tableColumns] objectAtIndex:columnIndex] identifier] integerValue]]]; if(!columnDefinition) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-2], @"", nil]; + return [NSArray arrayWithObjects:@(-2), @"", nil]; // Resolve the original table name for current column if AS was used NSString *tableForColumn = [columnDefinition objectForKey:@"org_table"]; @@ -1819,13 +1819,13 @@ // No table/database name found indicates that the field's column contains data from more than one table as for UNION // or the field data are not bound to any table as in SELECT 1 or if column database is unset if(!tableForColumn || ![tableForColumn length] || !dbForColumn || ![dbForColumn length]) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; // if table and database name are given check if field can be identified unambiguously // first without blob data NSString *fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:NO]; if(!fieldIDQueryStr) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; [tableDocumentInstance startTaskWithDescription:NSLocalizedString(@"Checking field data for editing...", @"checking field data for editing task description")]; @@ -1837,7 +1837,7 @@ if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } NSArray *tempRow = [tempResult getRowAsArray]; @@ -1847,7 +1847,7 @@ fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:YES]; if(!fieldIDQueryStr) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } tempResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@.%@ %@", @@ -1857,14 +1857,14 @@ if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } tempRow = [tempResult getRowAsArray]; if([tempRow count] && [[tempRow objectAtIndex:0] integerValue] < 1) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } } diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 4f09b3a8..a377a8ec 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -330,7 +330,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [tableTabView setTabViewType:NSNoTabsNoBorder]; // Hide the activity list - [self setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + [self setActivityPaneHidden:@1]; // Load additional nibs, keeping track of the top-level objects to allow correct release NSArray *connectionDialogTopLevelObjects = nil; @@ -3114,7 +3114,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [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:[NSNumber numberWithInteger:1] forKey:@"version"]; + [info setObject:@1 forKey:@"version"]; [info setObject:@"connection bundle" forKey:@"format"]; // Loop through all windows @@ -3323,7 +3323,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; NSMutableDictionary *spfData = [NSMutableDictionary dictionary]; // Add basic details - [spfStructure setObject:[NSNumber numberWithInteger:1] forKey:@"version"]; + [spfStructure setObject:@1 forKey:@"version"]; [spfStructure setObject:@"connection" forKey:@"format"]; [spfStructure setObject:@"mysql" forKey:@"rdbms_type"]; if([self mySQLVersion]) @@ -5592,12 +5592,12 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:SPActivitiesUpdateNotification object:self]; if([runningActivitiesArray count] || [[[NSApp delegate] runningActivities] count]) - [self performSelector:@selector(setActivityPaneHidden:) withObject:[NSNumber numberWithInteger:0] afterDelay:1.0]; + [self performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setActivityPaneHidden:) - object:[NSNumber numberWithInteger:0]]; - [self setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + object:@0]; + [self setActivityPaneHidden:@1]; } } @@ -5613,12 +5613,12 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } if([runningActivitiesArray count] || [[[NSApp delegate] runningActivities] count]) - [self performSelector:@selector(setActivityPaneHidden:) withObject:[NSNumber numberWithInteger:0] afterDelay:1.0]; + [self performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setActivityPaneHidden:) - object:[NSNumber numberWithInteger:0]]; - [self setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + object:@0]; + [self setActivityPaneHidden:@1]; } [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:SPActivitiesUpdateNotification object:self]; diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index aaa6c0bc..52b799d0 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -83,11 +83,11 @@ static NSUInteger SPSourceColumnTypeInteger = 1; fieldMappingGlobalValuesSQLMarked = [[NSMutableArray alloc] init]; fieldMappingArray = nil; - lastDisabledCSVFieldcolumn = [NSNumber numberWithInteger:0]; + lastDisabledCSVFieldcolumn = @0; - doImport = [NSNumber numberWithInteger:0]; - doNotImport = [NSNumber numberWithInteger:1]; - isEqual = [NSNumber numberWithInteger:2]; + doImport = @0; + doNotImport = @1; + isEqual = @2; doImportString = @"―"; doNotImportString = @" "; isEqualString = @"="; @@ -1936,7 +1936,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // If anObject contains $1 etc. enable SQL checkbox if([anObject isMatchedByRegex:@"(? 3) { NSString *field_id = [NSString stringWithFormat:@"%@%@%@", table_id,SPUniqueSchemaDelimiter,[a objectAtIndex:3]]; diff --git a/Source/SPPreferencesUpgrade.m b/Source/SPPreferencesUpgrade.m index 6151f675..a412088c 100644 --- a/Source/SPPreferencesUpgrade.m +++ b/Source/SPPreferencesUpgrade.m @@ -214,17 +214,17 @@ void SPApplyRevisionChanges(void) if ([[favorite objectForKey:@"host"] isEqualToString:@"localhost"] || ([favorite objectForKey:@"socket"] && [(NSString *)[favorite objectForKey:@"socket"] length])) { - [favorite setObject:[NSNumber numberWithInteger:1] forKey:@"type"]; + [favorite setObject:@1 forKey:@"type"]; // If SSH details are set, set to tunnel connection } else if ([favorite objectForKey:@"useSSH"] && [[favorite objectForKey:@"useSSH"] integerValue]) { - [favorite setObject:[NSNumber numberWithInteger:2] forKey:@"type"]; + [favorite setObject:@2 forKey:@"type"]; // Default to TCP/IP } else { - [favorite setObject:[NSNumber numberWithInteger:0] forKey:@"type"]; + [favorite setObject:@0 forKey:@"type"]; } // Remove SSH tunnel flag - no longer required @@ -311,7 +311,7 @@ void SPApplyRevisionChanges(void) NSNumber *newMappedValue = [encodingMap valueForKey:[prefs objectForKey:SPOldDefaultEncodingKey]]; - if (newMappedValue == nil) newMappedValue = [NSNumber numberWithInt:0]; + if (newMappedValue == nil) newMappedValue = @0; [prefs setObject:newMappedValue forKey:@"DefaultEncodingTag"]; } diff --git a/Source/SPPrintController.m b/Source/SPPrintController.m index 0b8d78c9..70f5662b 100644 --- a/Source/SPPrintController.m +++ b/Source/SPPrintController.m @@ -251,7 +251,7 @@ [printData setObject:indexes forKey:@"indexes"]; [printData setObject:indexColumns forKey:@"indexColumns"]; - if ([indexes count]) [printData setObject:[NSNumber numberWithInteger:1] forKey:@"hasIndexes"]; + if ([indexes count]) [printData setObject:@1 forKey:@"hasIndexes"]; [rows release]; [indexes release]; diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index a7147646..9f96d98a 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -917,7 +917,7 @@ NSMutableArray *favoriteData = [NSMutableArray array]; - [spfdata setObject:[NSNumber numberWithInteger:1] forKey:@"version"]; + [spfdata setObject:@1 forKey:@"version"]; [spfdata setObject:@"query favorites" forKey:@"format"]; [spfdata setObject:@NO forKey:@"encrypted"]; diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 9e190cb2..ae49c772 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -3333,7 +3333,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper NSDictionary *columnDefinition = [NSDictionary dictionaryWithDictionary:[cqColumnDefinition objectAtIndex:[[[[tableContentView tableColumns] objectAtIndex:columnIndex] identifier] integerValue]]]; if(!columnDefinition) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-2], @"", nil]; + return [NSArray arrayWithObjects:@(-2), @"", nil]; // Resolve the original table name for current column if AS was used NSString *tableForColumn = [columnDefinition objectForKey:@"org_table"]; @@ -3344,13 +3344,13 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // No table/database name found indicates that the field's column contains data from more than one table as for UNION // or the field data are not bound to any table as in SELECT 1 or if column database is unset if(!tableForColumn || ![tableForColumn length] || !dbForColumn || ![dbForColumn length]) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; // if table and database name are given check if field can be identified unambiguously // first without blob data NSString *fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:NO]; if(!fieldIDQueryStr) - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; [tableDocumentInstance startTaskWithDescription:NSLocalizedString(@"Checking field data for editing...", @"checking field data for editing task description")]; @@ -3362,7 +3362,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } NSArray *tempRow = [tempResult getRowAsArray]; @@ -3372,7 +3372,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:YES]; if(!fieldIDQueryStr) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } tempResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@.%@ %@", @@ -3382,14 +3382,14 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } tempRow = [tempResult getRowAsArray]; if([tempRow count] && [[tempRow objectAtIndex:0] integerValue] < 1) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], @"", nil]; + return [NSArray arrayWithObjects:@(-1), @"", nil]; } } diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 00de39da..9d875555 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -743,7 +743,7 @@ [primaryKeyFields addObject:primaryFieldName]; for (NSMutableDictionary *theTableColumn in tableColumns) { if ([[theTableColumn objectForKey:@"name"] isEqualToString:primaryFieldName]) { - [theTableColumn setObject:[NSNumber numberWithInteger:1] forKey:@"isprimarykey"]; + [theTableColumn setObject:@1 forKey:@"isprimarykey"]; break; } } @@ -761,7 +761,7 @@ NSString *uniqueFieldName = [[SPSQLParser stringWithString:quotedUniqueKey] unquotedString]; for (NSMutableDictionary *theTableColumn in tableColumns) { if ([[theTableColumn objectForKey:@"name"] isEqualToString:uniqueFieldName]) { - [theTableColumn setObject:[NSNumber numberWithInteger:1] forKey:@"unique"]; + [theTableColumn setObject:@1 forKey:@"unique"]; break; } } diff --git a/Source/SPTableInfo.m b/Source/SPTableInfo.m index 38d06b3e..4bed0226 100644 --- a/Source/SPTableInfo.m +++ b/Source/SPTableInfo.m @@ -388,11 +388,11 @@ if (rowIndex > 0) return NO; if (![tableInfoScrollView isHidden]) { - [tableDocumentInstance setActivityPaneHidden:[NSNumber numberWithInteger:0]]; + [tableDocumentInstance setActivityPaneHidden:@0]; [[NSApp mainWindow] makeFirstResponder:activitiesTable]; } else { - [tableDocumentInstance setActivityPaneHidden:[NSNumber numberWithInteger:1]]; + [tableDocumentInstance setActivityPaneHidden:@1]; [[NSApp mainWindow] makeFirstResponder:infoTable]; } diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 310af941..1b922683 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -253,12 +253,12 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; BOOL allowNull = [[[tableDataInstance statusValueForKey:@"Engine"] uppercaseString] isEqualToString:@"CSV"] ? NO : [prefs boolForKey:SPNewFieldsAllowNulls]; [tableFields insertObject:[NSMutableDictionary - dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", allowNull ? @"1" : @"0", @"", [prefs stringForKey:SPNullValue], @"None", @"", [NSNumber numberWithInt:0], [NSNumber numberWithInt:0], nil] + dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", allowNull ? @"1" : @"0", @"", [prefs stringForKey:SPNullValue], @"None", @"", @0, @0, nil] forKeys:[NSArray arrayWithObjects:@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation", nil]] atIndex:insertIndex]; #else [tableFields insertObject:[NSMutableDictionary - dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", @"1", @"", @"NULL", @"None", @"", [NSNumber numberWithInt:0], [NSNumber numberWithInt:0], nil] + dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", @"1", @"", @"NULL", @"None", @"", @0, @0, nil] forKeys:[NSArray arrayWithObjects:@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation", nil]] atIndex:insertIndex]; #endif diff --git a/Source/SPTableStructureDelegate.m b/Source/SPTableStructureDelegate.m index aebb0f18..4d2f580c 100644 --- a/Source/SPTableStructureDelegate.m +++ b/Source/SPTableStructureDelegate.m @@ -145,14 +145,14 @@ // Reset collation if encoding was changed if ([[aTableColumn identifier] isEqualToString:@"encoding"]) { if ([[currentRow objectForKey:@"encoding"] integerValue] != [anObject integerValue]) { - [currentRow setObject:[NSNumber numberWithInteger:0] forKey:@"collation"]; + [currentRow setObject:@0 forKey:@"collation"]; [tableSourceView reloadData]; } } // Reset collation if BINARY was set changed, as enabling BINARY sets collation to *_bin else if ([[aTableColumn identifier] isEqualToString:@"binary"]) { if ([[currentRow objectForKey:@"binary"] integerValue] != [anObject integerValue]) { - [currentRow setObject:[NSNumber numberWithInteger:0] forKey:@"collation"]; + [currentRow setObject:@0 forKey:@"collation"]; [tableSourceView reloadData]; } @@ -164,7 +164,7 @@ isCurrentExtraAutoIncrement = [[[anObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString] isEqualToString:@"AUTO_INCREMENT"]; if (isCurrentExtraAutoIncrement) { - [currentRow setObject:[NSNumber numberWithInteger:0] forKey:@"null"]; + [currentRow setObject:@0 forKey:@"null"]; // Asks the user to add an index to query if AUTO_INCREMENT is set and field isn't indexed if ((![currentRow objectForKey:@"Key"] || [[currentRow objectForKey:@"Key"] isEqualToString:@""])) { diff --git a/Source/SPTableStructureLoading.m b/Source/SPTableStructureLoading.m index a2a90f40..4c4e8c37 100644 --- a/Source/SPTableStructureLoading.m +++ b/Source/SPTableStructureLoading.m @@ -212,7 +212,7 @@ // Set BINARY if collation ends with _bin for convenience if ([[col objectForKey:@"COLLATION_NAME"] hasSuffix:@"_bin"]) { - [theField setObject:[NSNumber numberWithInt:1] forKey:@"binary"]; + [theField setObject:@1 forKey:@"binary"]; } break; -- cgit v1.2.3 From 994057ae2a82dc110a385ced4239ce49cc0601f8 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 17:20:18 +0100 Subject: Add cast for [NSApp delegate] * (Also changed some outdated URLs) * Replaced [NSApplication sharedApplication] with NSApp --- Source/SPAppController.m | 12 ++++----- Source/SPBundleCommandRunner.m | 7 ++--- Source/SPBundleEditorController.m | 5 ++-- Source/SPBundleHTMLOutputController.m | 14 +++++----- Source/SPChooseMenuItemDialog.m | 2 +- Source/SPConnectionController.m | 8 +++--- Source/SPConnectionControllerDelegate.m | 2 +- Source/SPConstants.h | 2 ++ Source/SPConstants.m | 2 +- Source/SPContentFilterManager.m | 3 ++- Source/SPCopyTable.m | 12 ++++----- Source/SPCustomQuery.m | 6 ++--- Source/SPDatabaseDocument.m | 46 ++++++++++++++++----------------- Source/SPDatabaseViewController.m | 4 +-- Source/SPDocumentController.m | 2 +- Source/SPExportFilenameUtilities.m | 2 +- Source/SPNavigatorController.m | 12 ++++----- Source/SPProcessListController.m | 4 +-- Source/SPQueryDocumentsController.m | 5 ++-- Source/SPQueryFavoriteManager.m | 3 ++- Source/SPServerVariablesController.m | 2 +- Source/SPTableContentDelegate.m | 4 +-- Source/SPTableInfo.m | 3 ++- Source/SPTablesList.m | 6 ++--- Source/SPTextView.m | 6 ++--- Source/SPTextViewAdditions.m | 14 +++++----- Source/SPUserManager.m | 8 +++--- Source/SPWindowControllerDelegate.m | 6 ++--- Source/Sequel-Pro.pch | 2 +- 29 files changed, 106 insertions(+), 98 deletions(-) (limited to 'Source') diff --git a/Source/SPAppController.m b/Source/SPAppController.m index ba9c6cab..8aabce60 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -440,8 +440,8 @@ [spfsDocData setObject:[NSNumber numberWithBool:[[spfs objectForKey:@"save_editor_content"] boolValue]] forKey:@"save_editor_content"]; // Set global session properties - [[NSApp delegate] setSpfSessionDocData:spfsDocData]; - [[NSApp delegate] setSessionURL:[NSURL fileURLWithPath:filePath]]; + [SPAppDelegate setSpfSessionDocData:spfsDocData]; + [SPAppDelegate setSessionURL:[NSURL fileURLWithPath:filePath]]; // Loop through each defined window in reversed order to reconstruct the last active window for (NSDictionary *window in [[[spfs objectForKey:@"windows"] reverseObjectEnumerator] allObjects]) @@ -993,7 +993,7 @@ { NSInteger idx = [sender tag] - 1000000; NSString *infoPath = nil; - NSArray *scopeBundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeGeneral]; + NSArray *scopeBundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeGeneral]; if(idx >=0 && idx < (NSInteger)[scopeBundleItems count]) { infoPath = [[scopeBundleItems objectAtIndex:idx] objectForKey:SPBundleInternPathToFileKey]; } else { @@ -1137,7 +1137,7 @@ [c setWindowUUID:[cmdData objectForKey:SPBundleFileUUIDKey]]; [c setDocUUID:uuid]; [c displayHTMLContent:output withOptions:nil]; - [[NSApp delegate] addHTMLOutputController:c]; + [SPAppDelegate addHTMLOutputController:c]; } } } @@ -1830,8 +1830,8 @@ BOOL bundleOtherThanGeneralFound = NO; for(NSString* scope in scopes) { - NSArray *scopeBundleCategories = [[NSApp delegate] bundleCategoriesForScope:scope]; - NSArray *scopeBundleItems = [[NSApp delegate] bundleItemsForScope:scope]; + NSArray *scopeBundleCategories = [SPAppDelegate bundleCategoriesForScope:scope]; + NSArray *scopeBundleItems = [SPAppDelegate bundleItemsForScope:scope]; if(![scopeBundleItems count]) { k++; diff --git a/Source/SPBundleCommandRunner.m b/Source/SPBundleCommandRunner.m index 2842ce4e..b8e22b93 100644 --- a/Source/SPBundleCommandRunner.m +++ b/Source/SPBundleCommandRunner.m @@ -30,6 +30,7 @@ #import "SPBundleCommandRunner.h" #import "SPDatabaseDocument.h" +#import "SPAppController.h" // Defined to suppress warnings @interface NSObject (SPBundleMethods) @@ -91,11 +92,11 @@ [fm removeItemAtPath:scriptFilePath error:nil]; [fm removeItemAtPath:stdoutFilePath error:nil]; - if([[NSApp delegate] lastBundleBlobFilesDirectory] != nil) - [fm removeItemAtPath:[[NSApp delegate] lastBundleBlobFilesDirectory] error:nil]; + if([SPAppDelegate lastBundleBlobFilesDirectory] != nil) + [fm removeItemAtPath:[SPAppDelegate lastBundleBlobFilesDirectory] error:nil]; if([shellEnvironment objectForKey:SPBundleShellVariableBlobFileDirectory]) - [[NSApp delegate] setLastBundleBlobFilesDirectory:[shellEnvironment objectForKey:SPBundleShellVariableBlobFileDirectory]]; + [SPAppDelegate setLastBundleBlobFilesDirectory:[shellEnvironment objectForKey:SPBundleShellVariableBlobFileDirectory]]; // Parse first line for magic header #! ; if found save the script content and run the command after #! with that file. // This allows to write perl, ruby, osascript scripts natively. diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index 4aaa7cad..aa400b05 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -34,6 +34,7 @@ #import "SPOutlineView.h" #import "SPBundleCommandTextView.h" #import "SPSplitView.h" +#import "SPAppController.h" static NSString *SPSaveBundleAction = @"SPSaveBundle"; @@ -880,7 +881,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [[self window] performClose:self]; } - [[NSApp delegate] reloadBundles:self]; + [SPAppDelegate reloadBundles:self]; } @@ -1083,7 +1084,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [undeleteTableView reloadData]; [[NSUserDefaults standardUserDefaults] setObject:stillUndeletedBundles forKey:SPBundleDeletedDefaultBundlesKey]; [[NSUserDefaults standardUserDefaults] synchronize]; - [[NSApp delegate] reloadBundles:nil]; + [SPAppDelegate reloadBundles:nil]; [self reloadBundles:self]; } diff --git a/Source/SPBundleHTMLOutputController.m b/Source/SPBundleHTMLOutputController.m index da82d768..ed1142a2 100644 --- a/Source/SPBundleHTMLOutputController.m +++ b/Source/SPBundleHTMLOutputController.m @@ -260,7 +260,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; [c displayHTMLContent:[NSString stringWithFormat:@"
%@
", [sourceCode HTMLEscapeString]] withOptions:nil]; - [[NSApp delegate] addHTMLOutputController:c]; + [SPAppDelegate addHTMLOutputController:c]; } - (void)saveDocument @@ -294,7 +294,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; windowUUID = @""; docUUID = @""; - [[NSApp delegate] removeHTMLOutputController:self]; + [SPAppDelegate removeHTMLOutputController:self]; [self release]; } @@ -332,7 +332,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; if(request != nil) { SPBundleHTMLOutputController *c = [[SPBundleHTMLOutputController alloc] init]; [c displayURLString:[[request URL] absoluteString] withOptions:nil]; - [[NSApp delegate] addHTMLOutputController:c]; + [SPAppDelegate addHTMLOutputController:c]; return [c webView]; } return nil; @@ -351,7 +351,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; // sequelpro:// handler if([[[request URL] scheme] isEqualToString:@"sequelpro"] && navigationType == WebNavigationTypeLinkClicked) { - [[NSApp delegate] handleEventWithURL:[request URL]]; + [SPAppDelegate handleEventWithURL:[request URL]]; [listener ignore]; } // sp-reveal-file://a_file_path reveals the file in Finder @@ -571,7 +571,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; */ - (NSString *)getShellEnvironmentForName:(NSString*)keyName { - return [[[NSApp delegate] shellEnvironmentForDocument:nil] objectForKey:keyName]; + return [[SPAppDelegate shellEnvironmentForDocument:nil] objectForKey:keyName]; } /** @@ -691,7 +691,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; output = [SPBundleCommandRunner runBashCommand:command withEnvironment:nil atCurrentDirectoryPath:nil error:&err]; else { NSMutableDictionary *theEnv = [NSMutableDictionary dictionary]; - [theEnv addEntriesFromDictionary:[[NSApp delegate] shellEnvironmentForDocument:nil]]; + [theEnv addEntriesFromDictionary:[SPAppDelegate shellEnvironmentForDocument:nil]]; [theEnv setObject:uuid forKey:SPBundleShellVariableProcessID]; [theEnv setObject:[NSString stringWithFormat:@"%@%@", SPURLSchemeQueryInputPathHeader, uuid] forKey:SPBundleShellVariableQueryFile]; [theEnv setObject:[NSString stringWithFormat:@"%@%@", SPURLSchemeQueryResultPathHeader, uuid] forKey:SPBundleShellVariableQueryResultFile]; @@ -701,7 +701,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; output = [SPBundleCommandRunner runBashCommand:command withEnvironment:theEnv atCurrentDirectoryPath:nil - callerInstance:[NSApp delegate] + callerInstance:SPAppDelegate contextInfo:[NSDictionary dictionaryWithObjectsAndKeys: @"JavaScript", @"name", NSLocalizedString(@"General", @"general menu item label"), @"scope", diff --git a/Source/SPChooseMenuItemDialog.m b/Source/SPChooseMenuItemDialog.m index 4b1dafb5..60b9ced3 100644 --- a/Source/SPChooseMenuItemDialog.m +++ b/Source/SPChooseMenuItemDialog.m @@ -148,7 +148,7 @@ clickCount:1 pressure:0.0f]; - [[NSApplication sharedApplication] sendEvent:theEvent]; + [NSApp sendEvent:theEvent]; while ([dialog waitForChoice] && [[[NSApp keyWindow] firstResponder] isKindOfClass:[SPChooseMenuItemDialogTextView class]]) { diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 905975dc..e98cc426 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -836,7 +836,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self _sortFavorites]; [self _selectNode:node]; - [[[[NSApp delegate] preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; + [[[SPAppDelegate preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; favoriteNameFieldWasAutogenerated = YES; @@ -979,7 +979,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self _reloadFavoritesViewData]; [self _selectNode:node]; - [[(SPPreferenceController *)[[NSApp delegate] preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; + [[(SPPreferenceController *)[SPAppDelegate preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; } } @@ -1354,7 +1354,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self _selectNode:newNode]; // Update the favorites popup button in the preferences - [[[[NSApp delegate] preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; + [[[SPAppDelegate preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; // Otherwise, if editing the favourite, update it } else { @@ -1677,7 +1677,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [connectionResizeContainer setHidden:NO]; [connectionInstructionsTextField setStringValue:NSLocalizedString(@"Enter connection details below, or choose a favorite", @"enter connection details label")]; - [[(SPPreferenceController *)[[NSApp delegate] preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; + [[(SPPreferenceController *)[SPAppDelegate preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; } /** diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index acd9f1d7..4384ae32 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -424,7 +424,7 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; [[NSNotificationCenter defaultCenter] postNotificationName:SPConnectionFavoritesChangedNotification object:self]; - [[[[NSApp delegate] preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; + [[[SPAppDelegate preferenceController] generalPreferencePane] updateDefaultFavoritePopup]; // Update the selection to account for rearranged faourites NSMutableIndexSet *restoredSelection = [NSMutableIndexSet indexSet]; diff --git a/Source/SPConstants.h b/Source/SPConstants.h index fd7afe40..322219ae 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -607,3 +607,5 @@ extern NSString *SPURLSchemeQueryInputPathHeader; extern NSString *SPURLSchemeQueryResultPathHeader; extern NSString *SPURLSchemeQueryResultStatusPathHeader; extern NSString *SPURLSchemeQueryResultMetaPathHeader; + +#define SPAppDelegate ((SPAppController *)[NSApp delegate]) diff --git a/Source/SPConstants.m b/Source/SPConstants.m index e7b92884..23d8c378 100644 --- a/Source/SPConstants.m +++ b/Source/SPConstants.m @@ -233,7 +233,7 @@ NSString *SPSSHEnableMuxingPreference = @"SSHMultiplexingEnabled"; // URLs NSString *SPDonationsURL = @"http://www.sequelpro.com/donate/"; NSString *SPMySQLSearchURL = @"http://dev.mysql.com/doc/refman/%@/%@/%@.html"; -NSString *SPDevURL = @"http://code.google.com/p/sequel-pro/"; +NSString *SPDevURL = @"https://github.com/sequelpro/sequelpro"; // Toolbar constants diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index c08e84b9..ea7c49b1 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -37,6 +37,7 @@ #import "SPTableContent.h" #import "SPConnectionController.h" #import "SPSplitView.h" +#import "SPAppController.h" static NSString *SPExportFilterAction = @"SPExportFilter"; @@ -404,7 +405,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; [cf release]; // Inform all opened documents to update the query favorites list - for(id doc in [[NSApp delegate] orderedDocuments]) + for(id doc in [SPAppDelegate orderedDocuments]) if([[doc valueForKeyPath:@"tableContentInstance"] respondsToSelector:@selector(setCompareTypes:)]) [[doc valueForKeyPath:@"tableContentInstance"] setCompareTypes:nil]; #endif diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m index 8eb33525..7796ca11 100644 --- a/Source/SPCopyTable.m +++ b/Source/SPCopyTable.m @@ -885,7 +885,7 @@ static const NSInteger kBlobAsImageFile = 4; if(![[self delegate] isKindOfClass:[SPCustomQuery class]] && ![[self delegate] isKindOfClass:[SPTableContent class]]) return menu; - [[NSApp delegate] reloadBundles:self]; + [SPAppDelegate reloadBundles:self]; // Remove 'Bundles' sub menu and separator NSMenuItem *bItem = [menu itemWithTag:10000000]; @@ -895,8 +895,8 @@ static const NSInteger kBlobAsImageFile = 4; [menu removeItem:bItem]; } - NSArray *bundleCategories = [[NSApp delegate] bundleCategoriesForScope:SPBundleScopeDataTable]; - NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeDataTable]; + NSArray *bundleCategories = [SPAppDelegate bundleCategoriesForScope:SPBundleScopeDataTable]; + NSArray *bundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeDataTable]; // Add 'Bundles' sub menu if(bundleItems && [bundleItems count]) { @@ -1246,7 +1246,7 @@ static const NSInteger kBlobAsImageFile = 4; #ifndef SP_CODA /* executeBundleItemForDataTable: */ NSInteger idx = [sender tag] - 1000000; NSString *infoPath = nil; - NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeDataTable]; + NSArray *bundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeDataTable]; if(idx >=0 && idx < (NSInteger)[bundleItems count]) { infoPath = [[bundleItems objectAtIndex:idx] objectForKey:SPBundleInternPathToFileKey]; } else { @@ -1432,7 +1432,7 @@ static const NSInteger kBlobAsImageFile = 4; NSString *output = [SPBundleCommandRunner runBashCommand:cmd withEnvironment:env atCurrentDirectoryPath:nil - callerInstance:[[NSApp delegate] frontDocument] + callerInstance:[SPAppDelegate frontDocument] contextInfo:[NSDictionary dictionaryWithObjectsAndKeys: ([cmdData objectForKey:SPBundleFileNameKey])?:@"-", @"name", NSLocalizedString(@"Data Table", @"data table menu item label"), @"scope", @@ -1509,7 +1509,7 @@ static const NSInteger kBlobAsImageFile = 4; SPBundleHTMLOutputController *bundleController = [[SPBundleHTMLOutputController alloc] init]; [bundleController setWindowUUID:[cmdData objectForKey:SPBundleFileUUIDKey]]; [bundleController displayHTMLContent:output withOptions:nil]; - [[NSApp delegate] addHTMLOutputController:bundleController]; + [SPAppDelegate addHTMLOutputController:bundleController]; } } } diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index ba053dbf..9de7391d 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -2541,7 +2541,7 @@ if ([aNotification object] != customQueryView) return; #ifndef SP_CODA /* triggered commands */ - NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged]; + NSArray *triggeredCommands = [SPAppDelegate bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged]; for(NSString* cmdPath in triggeredCommands) { NSArray *data = [cmdPath componentsSeparatedByString:@"|"]; NSMenuItem *aMenuItem = [[[NSMenuItem alloc] init] autorelease]; @@ -2565,7 +2565,7 @@ } if(!stopTrigger) { if([[data objectAtIndex:1] isEqualToString:SPBundleScopeGeneral]) { - [[[NSApp delegate] onMainThread] executeBundleItemForApp:aMenuItem]; + [[SPAppDelegate onMainThread] executeBundleItemForApp:aMenuItem]; } else if([[data objectAtIndex:1] isEqualToString:SPBundleScopeDataTable]) { if([[[[[NSApp mainWindow] firstResponder] class] description] isEqualToString:@"SPCopyTable"]) @@ -3894,7 +3894,7 @@ arrowEvent = [NSEvent keyEventWithType:NSKeyDown location:NSMakePoint(0,0) modifierFlags:0 timestamp:0 windowNumber:[[tableDocumentInstance parentWindow] windowNumber] context:[NSGraphicsContext currentContext] characters:nil charactersIgnoringModifiers:nil isARepeat:NO keyCode:0x7D]; else arrowEvent = [NSEvent keyEventWithType:NSKeyDown location:NSMakePoint(0,0) modifierFlags:0 timestamp:0 windowNumber:[[tableDocumentInstance parentWindow] windowNumber] context:[NSGraphicsContext currentContext] characters:nil charactersIgnoringModifiers:nil isARepeat:NO keyCode:0x7E]; - [[NSApplication sharedApplication] postEvent:arrowEvent atStart:NO]; + [NSApp postEvent:arrowEvent atStart:NO]; return YES; } diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index a377a8ec..7ab802da 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -2526,8 +2526,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; - (IBAction)openCurrentConnectionInNewWindow:(id)sender { - [[NSApp delegate] newWindow:self]; - SPDatabaseDocument *newTableDocument = [[NSApp delegate] frontDocument]; + [SPAppDelegate newWindow:self]; + SPDatabaseDocument *newTableDocument = [SPAppDelegate frontDocument]; [newTableDocument setStateFromConnectionFile:[[self fileURL] path]]; } @@ -2921,7 +2921,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; else if (sender == nil || [sender tag] == 1020 || [sender tag] == 1021) { // Save As Session - if ([sender tag] == 1020 && [[NSApp delegate] sessionURL]) { + if ([sender tag] == 1020 && [SPAppDelegate sessionURL]) { [self saveConnectionPanelDidEnd:panel returnCode:1 contextInfo:@"saveAsSession"]; return; } @@ -2935,7 +2935,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [panel setAllowedFileTypes:[NSArray arrayWithObjects:SPBundleFileExtension, nil]]; - NSDictionary *spfSessionData = [[NSApp delegate] spfSessionDocData]; + NSDictionary *spfSessionData = [SPAppDelegate spfSessionDocData]; // Restore accessory view settings if possible if ([spfSessionData objectForKey:@"save_password"]) { @@ -2967,8 +2967,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [panel setAccessoryView:saveConnectionAccessory]; // Set file name - if ([[NSApp delegate] sessionURL]) - filename = [[[[NSApp delegate] sessionURL] absoluteString] lastPathComponent]; + if ([SPAppDelegate sessionURL]) + filename = [[[SPAppDelegate sessionURL] absoluteString] lastPathComponent]; else filename = [NSString stringWithFormat:NSLocalizedString(@"Session",@"Initial filename for 'Save session' file")]; @@ -3055,8 +3055,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // 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 == @"saveAsSession" && [[NSApp delegate] sessionURL]) - fileName = [[[NSApp delegate] sessionURL] path]; + if(contextInfo == @"saveAsSession" && [SPAppDelegate sessionURL]) + fileName = [[SPAppDelegate sessionURL] path]; if(!fileName || ![fileName length]) return; @@ -3094,7 +3094,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // retrieve save panel data for passing them to each doc NSMutableDictionary *spfDocData_temp = [NSMutableDictionary dictionary]; if(contextInfo == @"saveAsSession") { - [spfDocData_temp addEntriesFromDictionary:[[NSApp delegate] spfSessionDocData]]; + [spfDocData_temp addEntriesFromDictionary:[SPAppDelegate spfSessionDocData]]; } else { [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionEncrypt state]==NSOnState) ? YES : NO ] forKey:@"encrypted"]; if([[spfDocData_temp objectForKey:@"encrypted"] boolValue]) @@ -3105,7 +3105,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [spfDocData_temp setObject:[NSNumber numberWithBool:([saveConnectionIncludeQuery state]==NSOnState) ? YES : NO ] forKey:@"save_editor_content"]; // Save the session's accessory view settings - [[NSApp delegate] setSpfSessionDocData:spfDocData_temp]; + [SPAppDelegate setSpfSessionDocData:spfDocData_temp]; } @@ -3118,7 +3118,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [info setObject:@"connection bundle" forKey:@"format"]; // Loop through all windows - for(NSWindow *window in [[NSApp delegate] orderedDatabaseConnectionWindows]) { + for(NSWindow *window in [SPAppDelegate orderedDatabaseConnectionWindows]) { // First window is always the currently key window @@ -3192,7 +3192,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; return; } - [[NSApp delegate] setSessionURL:fileName]; + [SPAppDelegate setSessionURL:fileName]; // Register spfs bundle in Recent Files [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:fileName]]; @@ -3459,7 +3459,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [currentState setObject:sessionDict forKey:@"session"]; // Set the connection on the new tab - [[[NSApp delegate] frontDocument] setState:currentState]; + [[SPAppDelegate frontDocument] setState:currentState]; } /** @@ -4807,11 +4807,11 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Ask for a password if SPF file passwords were encrypted, via a sheet if ([spf objectForKey:@"encrypted"] && [[spf valueForKey:@"encrypted"] boolValue]) { - if([self isSaveInBundle] && [[[NSApp delegate] spfSessionDocData] objectForKey:@"e_string"]) { - encryptpw = [[[NSApp delegate] spfSessionDocData] objectForKey:@"e_string"]; + if([self isSaveInBundle] && [[SPAppDelegate spfSessionDocData] objectForKey:@"e_string"]) { + encryptpw = [[SPAppDelegate spfSessionDocData] objectForKey:@"e_string"]; } else { [inputTextWindowHeader setStringValue:NSLocalizedString(@"Connection file is encrypted", @"Connection file is encrypted")]; - [inputTextWindowMessage setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Please enter the password for ‘%@’:", @"Please enter the password"), ([self isSaveInBundle]) ? [[[[NSApp delegate] sessionURL] absoluteString] lastPathComponent] : [path lastPathComponent]]]; + [inputTextWindowMessage setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Please enter the password for ‘%@’:", @"Please enter the password"), ([self isSaveInBundle]) ? [[[SPAppDelegate sessionURL] absoluteString] lastPathComponent] : [path lastPathComponent]]]; [inputTextWindowSecureTextField setStringValue:@""]; [inputTextWindowSecureTextField selectText:nil]; @@ -4843,9 +4843,9 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; encryptpw = [inputTextWindowSecureTextField stringValue]; if ([self isSaveInBundle]) { NSMutableDictionary *spfSessionData = [NSMutableDictionary dictionary]; - [spfSessionData addEntriesFromDictionary:[[NSApp delegate] spfSessionDocData]]; + [spfSessionData addEntriesFromDictionary:[SPAppDelegate spfSessionDocData]]; [spfSessionData setObject:encryptpw forKey:@"e_string"]; - [[NSApp delegate] setSpfSessionDocData:spfSessionData]; + [SPAppDelegate setSpfSessionDocData:spfSessionData]; } } else { [self closeAndDisconnect]; @@ -5379,7 +5379,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; return; } if(doSyntaxHighlighting) { - [result appendFormat:@"%@
", [[NSApp delegate] doSQLSyntaxHighlightForString:[syntaxString createViewSyntaxPrettifier] cssLike:doSyntaxHighlightingViaCSS]]; + [result appendFormat:@"%@
", [SPAppDelegate doSQLSyntaxHighlightForString:[syntaxString createViewSyntaxPrettifier] cssLike:doSyntaxHighlightingViaCSS]]; } else { [result appendFormat:@"%@\n", [syntaxString createViewSyntaxPrettifier]]; } @@ -5591,7 +5591,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [runningActivitiesArray addObject:commandDict]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:SPActivitiesUpdateNotification object:self]; - if([runningActivitiesArray count] || [[[NSApp delegate] runningActivities] count]) + if([runningActivitiesArray count] || [[SPAppDelegate runningActivities] count]) [self performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:self @@ -5612,7 +5612,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } } - if([runningActivitiesArray count] || [[[NSApp delegate] runningActivities] count]) + if([runningActivitiesArray count] || [[SPAppDelegate runningActivities] count]) [self performSelector:@selector(setActivityPaneHidden:) withObject:@0 afterDelay:1.0]; else { [NSObject cancelPreviousPerformRequestsWithTarget:self @@ -6198,7 +6198,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #ifndef SP_CODA - (void)_processDatabaseChangedBundleTriggerActions { - NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionDatabaseChanged]; + NSArray *triggeredCommands = [SPAppDelegate bundleCommandsForTrigger:SPBundleTriggerActionDatabaseChanged]; for (NSString* cmdPath in triggeredCommands) { @@ -6229,7 +6229,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } if(!stopTrigger) { if([[data objectAtIndex:1] isEqualToString:SPBundleScopeGeneral]) { - [[[NSApp delegate] onMainThread] executeBundleItemForApp:aMenuItem]; + [[SPAppDelegate onMainThread] executeBundleItemForApp:aMenuItem]; } else if([[data objectAtIndex:1] isEqualToString:SPBundleScopeDataTable]) { if ([[[[[NSApp mainWindow] firstResponder] class] description] isEqualToString:@"SPCopyTable"]) { diff --git a/Source/SPDatabaseViewController.m b/Source/SPDatabaseViewController.m index c1823661..9b0ded39 100644 --- a/Source/SPDatabaseViewController.m +++ b/Source/SPDatabaseViewController.m @@ -589,7 +589,7 @@ [self endTask]; #ifndef SP_CODA /* triggered commands */ - NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableChanged]; + NSArray *triggeredCommands = [SPAppDelegate bundleCommandsForTrigger:SPBundleTriggerActionTableChanged]; for(NSString* cmdPath in triggeredCommands) { @@ -615,7 +615,7 @@ } if(!stopTrigger) { if([[data objectAtIndex:1] isEqualToString:SPBundleScopeGeneral]) { - [[[NSApp delegate] onMainThread] executeBundleItemForApp:aMenuItem]; + [[SPAppDelegate onMainThread] executeBundleItemForApp:aMenuItem]; } else if([[data objectAtIndex:1] isEqualToString:SPBundleScopeDataTable]) { if([[[[[NSApp mainWindow] firstResponder] class] description] isEqualToString:@"SPCopyTable"]) diff --git a/Source/SPDocumentController.m b/Source/SPDocumentController.m index 391d41a6..a5d81554 100644 --- a/Source/SPDocumentController.m +++ b/Source/SPDocumentController.m @@ -40,7 +40,7 @@ /** * Add a dummy implementation of readFromData:ofType:error:, which appears to * be called by the OS in certain situations despite non-document use. - * (See http://code.google.com/p/sequel-pro/issues/detail?id=1411 ) + * (See issue #1411 ) */ - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError { diff --git a/Source/SPExportFilenameUtilities.m b/Source/SPExportFilenameUtilities.m index 71422b28..b0070f31 100644 --- a/Source/SPExportFilenameUtilities.m +++ b/Source/SPExportFilenameUtilities.m @@ -242,7 +242,7 @@ isARepeat:NO keyCode:0x24]; - [[NSApplication sharedApplication] postEvent:tokenizingEvent atStart:NO]; + [NSApp postEvent:tokenizingEvent atStart:NO]; // Update the filename preview [self updateDisplayedExportFilename]; diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index 379cdc18..e2319141 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -312,8 +312,8 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte // Detect if more than one connection windows with the connectionID are open. // If so, don't remove it. - if ([[NSApp delegate] frontDocument]) { - for(id doc in [[NSApp delegate] orderedDocuments]) { + if ([SPAppDelegate frontDocument]) { + for(id doc in [SPAppDelegate orderedDocuments]) { if([[doc connectionID] isEqualToString:connectionID]) docCounter++; if(docCounter > 1) break; @@ -322,7 +322,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if(docCounter > 1) return; - if(schemaData && [schemaData objectForKey:connectionID] && [[NSApp delegate] frontDocument] && [[[NSApp delegate] orderedDocuments] count]) + if(schemaData && [schemaData objectForKey:connectionID] && [SPAppDelegate frontDocument] && [[SPAppDelegate orderedDocuments] count]) [self saveSelectedItems]; if(schemaDataFiltered) @@ -374,7 +374,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte NSArray *pathArray = [[[parentKeys objectAtIndex:0] description] componentsSeparatedByString:SPUniqueSchemaDelimiter]; if([pathArray count] > 1) { - SPDatabaseDocument *doc = [[NSApp delegate] frontDocument]; + SPDatabaseDocument *doc = [SPAppDelegate frontDocument]; if([doc isWorking]) { [SPTooltip showWithObject:NSLocalizedString(@"Active connection window is busy. Please wait and try again.", @"active connection window is busy. please wait and try again. tooltip") atLocation:pos @@ -590,7 +590,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte { // Reset everything for current active doc connection - SPDatabaseDocument *doc = [[NSApp delegate] frontDocument]; + SPDatabaseDocument *doc = [SPAppDelegate frontDocument]; if(!doc) return; NSString *connectionID = [doc connectionID]; if(!connectionID || [connectionID length] < 2) return; @@ -750,7 +750,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte [searchField setStringValue:@""]; } - SPDatabaseDocument *doc = [[NSApp delegate] frontDocument]; + SPDatabaseDocument *doc = [SPAppDelegate frontDocument]; if (doc) { NSMutableString *key = [NSMutableString string]; [key setString:[doc connectionID]]; diff --git a/Source/SPProcessListController.m b/Source/SPProcessListController.m index 956b0d9b..c77e82d2 100644 --- a/Source/SPProcessListController.m +++ b/Source/SPProcessListController.m @@ -85,7 +85,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; - (void)awakeFromNib { - [[self window] setTitle:[NSString stringWithFormat:NSLocalizedString(@"Server Processes on %@", @"server processes window title (var = hostname)"),[[(SPAppController*)[NSApp delegate] frontDocument] name]]]; + [[self window] setTitle:[NSString stringWithFormat:NSLocalizedString(@"Server Processes on %@", @"server processes window title (var = hostname)"),[[SPAppDelegate frontDocument] name]]]; [self setWindowFrameAutosaveName:@"ProcessList"]; @@ -238,7 +238,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; [panel beginSheetModalForWindow:[self window] completionHandler:^(NSInteger returnCode) { if (returnCode == NSOKButton) { if ([processesFiltered count] > 0) { - NSMutableString *processesString = [NSMutableString stringWithFormat:@"# MySQL server proceese for %@\n\n", [[[NSApp delegate] frontDocument] host]]; + NSMutableString *processesString = [NSMutableString stringWithFormat:@"# MySQL server proceese for %@\n\n", [[SPAppDelegate frontDocument] host]]; for (NSDictionary *process in processesFiltered) { diff --git a/Source/SPQueryDocumentsController.m b/Source/SPQueryDocumentsController.m index ba1bc2b1..e42a734b 100644 --- a/Source/SPQueryDocumentsController.m +++ b/Source/SPQueryDocumentsController.m @@ -30,6 +30,7 @@ #import "SPQueryDocumentsController.h" #import "SPCustomQuery.h" +#import "SPAppController.h" @implementation SPQueryController (SPQueryDocumentsController) @@ -122,7 +123,7 @@ #ifndef SP_CODA // Check for multiple instance of the same document. // Remove it if only one instance was registerd. - NSArray *allDocs = [[NSApp delegate] orderedDocuments]; + NSArray *allDocs = [SPAppDelegate orderedDocuments]; NSMutableArray *allURLs = [NSMutableArray array]; for (id doc in allDocs) @@ -202,7 +203,7 @@ } // Inform all opened documents to update the history list - for (id doc in [[NSApp delegate] orderedDocuments]) + for (id doc in [SPAppDelegate orderedDocuments]) { if([[doc valueForKeyPath:@"customQueryInstance"] respondsToSelector:@selector(historyItemsHaveBeenUpdated:)]) { [[doc valueForKeyPath:@"customQueryInstance"] performSelectorOnMainThread:@selector(historyItemsHaveBeenUpdated:) withObject:self waitUntilDone:NO]; diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index 9f96d98a..c73501b8 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -38,6 +38,7 @@ #import "RegexKitLite.h" #import "SPTextView.h" #import "SPSplitView.h" +#import "SPAppController.h" #define SP_MULTIPLE_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[multiple selection]", @"[multiple selection]") #define SP_NO_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[no selection]", @"[no selection]") @@ -477,7 +478,7 @@ [prefs setObject:[self queryFavoritesForFileURL:nil] forKey:SPQueryFavorites]; // Inform all opened documents to update the query favorites list - for(id doc in [[NSApp delegate] orderedDocuments]) + for(id doc in [SPAppDelegate orderedDocuments]) if([[doc valueForKeyPath:@"customQueryInstance"] respondsToSelector:@selector(queryFavoritesHaveBeenUpdated:)]) [[doc valueForKeyPath:@"customQueryInstance"] queryFavoritesHaveBeenUpdated:self]; } diff --git a/Source/SPServerVariablesController.m b/Source/SPServerVariablesController.m index a2e1e059..80c9f558 100644 --- a/Source/SPServerVariablesController.m +++ b/Source/SPServerVariablesController.m @@ -136,7 +136,7 @@ [panel beginSheetModalForWindow:[self window] completionHandler:^(NSInteger returnCode) { if (returnCode == NSOKButton) { if ([variablesFiltered count] > 0) { - NSMutableString *variablesString = [NSMutableString stringWithFormat:@"# MySQL server variables for %@\n\n", [[(SPAppController*)[NSApp delegate] frontDocument] host]]; + NSMutableString *variablesString = [NSMutableString stringWithFormat:@"# MySQL server variables for %@\n\n", [[SPAppDelegate frontDocument] host]]; for (NSDictionary *variable in variablesFiltered) { diff --git a/Source/SPTableContentDelegate.m b/Source/SPTableContentDelegate.m index 2f78a120..0a624efc 100644 --- a/Source/SPTableContentDelegate.m +++ b/Source/SPTableContentDelegate.m @@ -118,7 +118,7 @@ [self updateCountText]; #ifndef SP_CODA /* triggered commands */ - NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged]; + NSArray *triggeredCommands = [SPAppDelegate bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged]; for (NSString *cmdPath in triggeredCommands) { @@ -150,7 +150,7 @@ if (!stopTrigger) { if ([[data objectAtIndex:1] isEqualToString:SPBundleScopeGeneral]) { - [[[NSApp delegate] onMainThread] executeBundleItemForApp:aMenuItem]; + [[SPAppDelegate onMainThread] executeBundleItemForApp:aMenuItem]; } else if ([[data objectAtIndex:1] isEqualToString:SPBundleScopeDataTable]) { if ([[[[[NSApp mainWindow] firstResponder] class] description] isEqualToString:@"SPCopyTable"]) { diff --git a/Source/SPTableInfo.m b/Source/SPTableInfo.m index 4bed0226..76a11a5c 100644 --- a/Source/SPTableInfo.m +++ b/Source/SPTableInfo.m @@ -35,6 +35,7 @@ #import "SPTableData.h" #import "SPActivityTextFieldCell.h" #import "SPTableTextFieldCell.h" +#import "SPAppController.h" @interface SPTableInfo (PrivateAPI) @@ -111,7 +112,7 @@ [acts removeAllObjects]; [acts addObject:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"ACTIVITIES", @"header for activities pane"), @"name", nil]]; [acts addObjectsFromArray:[tableDocumentInstance runningActivities]]; - [acts addObjectsFromArray:[[NSApp delegate] runningActivities]]; + [acts addObjectsFromArray:[SPAppDelegate runningActivities]]; _activitiesWillBeUpdated = YES; diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 458389c2..8d455b58 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -717,13 +717,13 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [documentState setObject:@YES forKey:@"auto_connect"]; // Set the connection on the new tab - [[[NSApp delegate] frontDocument] setState:documentState]; + [[SPAppDelegate frontDocument] setState:documentState]; } - (IBAction)openTableInNewWindow:(id)sender { //create new window - [(SPAppController *)[NSApp delegate] newWindow:self]; + [SPAppDelegate newWindow:self]; [self _duplicateConnectionToFrontTab]; } @@ -2653,7 +2653,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; // check if the name really changed if ([oldTableName isEqualToString:newTableName]) return; - // check if only the case changed - then we have to do two renames, see http://code.google.com/p/sequel-pro/issues/detail?id=484 + // check if only the case changed - then we have to do two renames, see issue #484 if ([[oldTableName lowercaseString] isEqualToString:[newTableName lowercaseString]]) { // first try finding an unused temporary name diff --git a/Source/SPTextView.m b/Source/SPTextView.m index abe89c5b..523a7ade 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -3125,7 +3125,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS } #ifndef SP_CODA - [[NSApp delegate] reloadBundles:self]; + [SPAppDelegate reloadBundles:self]; // Remove 'Bundles' sub menu and separator NSMenuItem *bItem = [menu itemWithTag:10000000]; @@ -3135,8 +3135,8 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS [menu removeItem:bItem]; } - NSArray *bundleCategories = [[NSApp delegate] bundleCategoriesForScope:SPBundleScopeInputField]; - NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeInputField]; + NSArray *bundleCategories = [SPAppDelegate bundleCategoriesForScope:SPBundleScopeInputField]; + NSArray *bundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeInputField]; // Add 'Bundles' sub menu for custom query editor only so far if bundles with scope 'editor' were found if(customQueryInstance && bundleItems && [bundleItems count]) { diff --git a/Source/SPTextViewAdditions.m b/Source/SPTextViewAdditions.m index 17998fa6..7272de1d 100644 --- a/Source/SPTextViewAdditions.m +++ b/Source/SPTextViewAdditions.m @@ -511,7 +511,7 @@ NSInteger idx = [sender tag] - 1000000; NSString *infoPath = nil; - NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeInputField]; + NSArray *bundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeInputField]; if(idx >=0 && idx < (NSInteger)[bundleItems count]) { infoPath = [[bundleItems objectAtIndex:idx] objectForKey:SPBundleInternPathToFileKey]; } else { @@ -661,7 +661,7 @@ NSString *output = [SPBundleCommandRunner runBashCommand:cmd withEnvironment:env atCurrentDirectoryPath:nil - callerInstance:[(SPAppController*)[NSApp delegate] frontDocument] + callerInstance:[SPAppDelegate frontDocument] contextInfo:[NSDictionary dictionaryWithObjectsAndKeys: ([cmdData objectForKey:SPBundleFileNameKey])?:@"-", @"name", NSLocalizedString(@"Input Field", @"input field menu item label"), @"scope", @@ -736,7 +736,7 @@ SPBundleHTMLOutputController *c = [[SPBundleHTMLOutputController alloc] init]; [c setWindowUUID:[cmdData objectForKey:SPBundleFileUUIDKey]]; [c displayHTMLContent:output withOptions:nil]; - [[NSApp delegate] addHTMLOutputController:c]; + [SPAppDelegate addHTMLOutputController:c]; } } @@ -800,12 +800,12 @@ [menu removeItem:bItem]; } - if ([[[(SPWindowController *)[[[NSApp delegate] frontDocumentWindow] delegate] selectedTableDocument] connectionID] isEqualToString:@"_"]) return menu; + if ([[[(SPWindowController *)[[SPAppDelegate frontDocumentWindow] delegate] selectedTableDocument] connectionID] isEqualToString:@"_"]) return menu; - [[NSApp delegate] reloadBundles:self]; + [SPAppDelegate reloadBundles:self]; - NSArray *bundleCategories = [[NSApp delegate] bundleCategoriesForScope:SPBundleScopeInputField]; - NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeInputField]; + NSArray *bundleCategories = [SPAppDelegate bundleCategoriesForScope:SPBundleScopeInputField]; + NSArray *bundleItems = [SPAppDelegate bundleItemsForScope:SPBundleScopeInputField]; // Add 'Bundles' sub menu if(bundleItems && [bundleItems count]) { diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m index 917c73ae..3fdcaa63 100644 --- a/Source/SPUserManager.m +++ b/Source/SPUserManager.m @@ -281,7 +281,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; [[self managedObjectContext] save:&error]; if (error != nil) { - [[NSApplication sharedApplication] presentError:error]; + [NSApp presentError:error]; } [parentResults release]; @@ -443,7 +443,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]]; if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error]) { - [[NSApplication sharedApplication] presentError:error]; + [NSApp presentError:error]; } return persistentStoreCoordinator; @@ -1261,7 +1261,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; NSArray *array = [moc executeFetchRequest:request error:&error]; if (error != nil) { - [[NSApplication sharedApplication] presentError:error]; + [NSApp presentError:error]; } return array; @@ -1297,7 +1297,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; NSArray *array = [moc executeFetchRequest:request error:&error]; if (error != nil) { - [[NSApplication sharedApplication] presentError:error]; + [NSApp presentError:error]; } return array; diff --git a/Source/SPWindowControllerDelegate.m b/Source/SPWindowControllerDelegate.m index d8637ac4..47959f1b 100644 --- a/Source/SPWindowControllerDelegate.m +++ b/Source/SPWindowControllerDelegate.m @@ -68,9 +68,9 @@ } // Remove global session data if the last window of a session will be closed - if ([[NSApp delegate] sessionURL] && [[[NSApp delegate] orderedDatabaseConnectionWindows] count] == 1) { - [[NSApp delegate] setSessionURL:nil]; - [[NSApp delegate] setSpfSessionDocData:nil]; + if ([SPAppDelegate sessionURL] && [[SPAppDelegate orderedDatabaseConnectionWindows] count] == 1) { + [SPAppDelegate setSessionURL:nil]; + [SPAppDelegate setSpfSessionDocData:nil]; } return YES; diff --git a/Source/Sequel-Pro.pch b/Source/Sequel-Pro.pch index 080e20ec..f3b2fd16 100644 --- a/Source/Sequel-Pro.pch +++ b/Source/Sequel-Pro.pch @@ -25,7 +25,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // -// More info at +// More info at #ifdef __OBJC__ #import -- cgit v1.2.3 From 876dde21d97897ad4ee98aa0d6b11898282982ce Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 18:02:01 +0100 Subject: Change [NSArray arrayWithObject:] to @[] literal Note: [NSArray arrayWithObjects:...,nil] is left unchanged as that could possibly cause a NPE if converted to @[] --- Source/GeneratePreviewForURL.m | 2 +- Source/MGTemplateEngine.m | 2 +- Source/SPAppController.m | 8 ++++---- Source/SPBundleEditorController.m | 6 +++--- Source/SPConnectionControllerDelegate.m | 2 +- Source/SPConnectionControllerInitializer.m | 2 +- Source/SPContentFilterManager.m | 6 +++--- Source/SPCustomQuery.m | 14 +++++++------- Source/SPDatabaseData.m | 2 +- Source/SPDatabaseDocument.m | 8 ++++---- Source/SPEditorPreferencePane.m | 6 +++--- Source/SPExportControllerDelegate.m | 2 +- Source/SPFavoritesController.m | 2 +- Source/SPFieldEditorController.m | 3 +-- Source/SPNavigatorController.m | 2 +- Source/SPPrintAccessory.m | 2 +- Source/SPQueryController.m | 2 +- Source/SPQueryDocumentsController.m | 8 ++++---- Source/SPQueryFavoriteManager.m | 8 ++++---- Source/SPServerVariablesController.m | 2 +- Source/SPTableData.m | 2 +- Source/SPTableStructureDelegate.m | 4 ++-- Source/SPTableStructureLoading.m | 4 ++-- Source/SPTextView.m | 20 ++++++++++---------- Source/SPUserManager.m | 2 +- 25 files changed, 60 insertions(+), 61 deletions(-) (limited to 'Source') diff --git a/Source/GeneratePreviewForURL.m b/Source/GeneratePreviewForURL.m index 034d7bd1..ebbadd5a 100644 --- a/Source/GeneratePreviewForURL.m +++ b/Source/GeneratePreviewForURL.m @@ -474,7 +474,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, // just in case if(!iconImages || [iconImages count] < 1) - iconImages = [NSArray arrayWithObject:[NSImage imageNamed:NSImageNameStopProgressTemplate]]; + iconImages = @[[NSImage imageNamed:NSImageNameStopProgressTemplate]]; #warning Shouldn't that be "> 1"? if([iconImages count] > 0) diff --git a/Source/MGTemplateEngine.m b/Source/MGTemplateEngine.m index 941a7e1b..4a5d3192 100644 --- a/Source/MGTemplateEngine.m +++ b/Source/MGTemplateEngine.m @@ -542,7 +542,7 @@ [frame setObject:endMarkers forKey:BLOCK_END_NAMES_KEY]; NSArray *arguments = [matchInfo objectForKey:MARKER_ARGUMENTS_KEY]; if (!arguments) { - arguments = [NSArray array]; + arguments = @[]; } [frame setObject:arguments forKey:BLOCK_ARGUMENTS_KEY]; [frame setObject:[matchInfo objectForKey:MARKER_RANGE_KEY] forKey:BLOCK_START_MARKER_RANGE_KEY]; diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 8aabce60..56da49cf 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -738,7 +738,7 @@ if([pathComponents count] > 2) parameter = [pathComponents subarrayWithRange:NSMakeRange(2, [pathComponents count]-2)]; else - parameter = [NSArray array]; + parameter = @[]; NSFileManager *fm = [NSFileManager defaultManager]; @@ -1533,7 +1533,7 @@ if([[NSUserDefaults standardUserDefaults] objectForKey:SPBundleDeletedDefaultBundlesKey]) deletedDefaultBundles = [[[NSUserDefaults standardUserDefaults] objectForKey:SPBundleDeletedDefaultBundlesKey] retain]; else - deletedDefaultBundles = [[NSArray array] retain]; + deletedDefaultBundles = [@[] retain]; NSMutableString *infoAboutUpdatedDefaultBundles = [NSMutableString string]; BOOL doBundleUpdate = ([[NSUserDefaults standardUserDefaults] objectForKey:@"doBundleUpdate"]) ? YES : NO; @@ -1775,7 +1775,7 @@ // Sort items for menus NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SPBundleInternLabelKey ascending:YES] autorelease]; for(NSString* scope in [bundleItems allKeys]) { - [[bundleItems objectForKey:scope] sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; + [[bundleItems objectForKey:scope] sortUsingDescriptors:@[sortDescriptor]]; [[bundleCategories objectForKey:scope] sortUsingSelector:@selector(compare:)]; } } @@ -1949,7 +1949,7 @@ // Sort if more than one found if([assignedKeyEquivalents count] > 1) { NSSortDescriptor *aSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease]; - NSArray *sorted = [assignedKeyEquivalents sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]; + NSArray *sorted = [assignedKeyEquivalents sortedArrayUsingDescriptors:@[aSortDescriptor]]; [assignedKeyEquivalents setArray:sorted]; } } diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index aa400b05..4de339de 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -741,8 +741,8 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; - (IBAction)saveBundle:(id)sender { NSSavePanel *panel = [NSSavePanel savePanel]; - - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPUserBundleFileExtension]]; + + [panel setAllowedFileTypes:@[SPUserBundleFileExtension]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:NO]; @@ -1536,7 +1536,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; // Write data to the pasteboard NSArray *fileList = [NSArray arrayWithObjects:draggedFilePath, nil]; // NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard]; - [pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil]; + [pboard declareTypes:@[NSFilenamesPboardType] owner:nil]; [pboard setPropertyList:fileList forType:NSFilenamesPboardType]; // Start the drag operation diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index 4384ae32..a28a27b7 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -312,7 +312,7 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; return NO; } - [pboard declareTypes:[NSArray arrayWithObject:SPFavoritesPasteboardDragType] owner:self]; + [pboard declareTypes:@[SPFavoritesPasteboardDragType] owner:self]; BOOL result = [pboard setData:[NSData data] forType:SPFavoritesPasteboardDragType]; diff --git a/Source/SPConnectionControllerInitializer.m b/Source/SPConnectionControllerInitializer.m index 5ef4f3a4..5254e36d 100644 --- a/Source/SPConnectionControllerInitializer.m +++ b/Source/SPConnectionControllerInitializer.m @@ -320,7 +320,7 @@ static NSString *SPConnectionViewNibName = @"ConnectionView"; [favoritesOutlineView setDoubleAction:@selector(nodeDoubleClicked:)]; // Register drag types for the favorites outline view - [favoritesOutlineView registerForDraggedTypes:[NSArray arrayWithObject:SPFavoritesPasteboardDragType]]; + [favoritesOutlineView registerForDraggedTypes:@[SPFavoritesPasteboardDragType]]; [favoritesOutlineView setDraggingSourceOperationMask:NSDragOperationMove forLocal:YES]; } diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index ea7c49b1..d6fed676 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -143,7 +143,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; [contentFilterTextView setString:@""]; // Register drag types - [contentFilterTableView registerForDraggedTypes:[NSArray arrayWithObject:SPContentFilterPasteboardDragType]]; + [contentFilterTableView registerForDraggedTypes:@[SPContentFilterPasteboardDragType]]; [contentFilterArrayController setContent:contentFilters]; [contentFilterTableView reloadData]; @@ -333,7 +333,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; #ifndef SP_CODA NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionDefault]]; + [panel setAllowedFileTypes:@[SPFileExtensionDefault]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:NO]; @@ -556,7 +556,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rows toPasteboard:(NSPasteboard*)pboard { - NSArray *pboardTypes = [NSArray arrayWithObject:SPContentFilterPasteboardDragType]; + NSArray *pboardTypes = @[SPContentFilterPasteboardDragType]; NSUInteger originalRow = [rows firstIndex]; if(originalRow < 1) return NO; diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 9de7391d..21ce6970 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -197,7 +197,7 @@ NSBeep(); return; } - queries = [NSArray arrayWithObject:[SPSQLParser normaliseQueryForExecution:query]]; + queries = @[[SPSQLParser normaliseQueryForExecution:query]]; // Otherwise, run the selected text. } else { @@ -470,7 +470,7 @@ #ifndef SP_CODA NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionSQL]]; + [panel setAllowedFileTypes:@[SPFileExtensionSQL]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:YES]; @@ -504,7 +504,7 @@ { NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; + [pb declareTypes:@[NSStringPboardType] owner:nil]; [pb setString:[self buildHistoryString] forType:NSStringPboardType]; } @@ -2038,7 +2038,7 @@ if ([prefs boolForKey:SPReloadAfterEditingRow]) { reloadingExistingResult = YES; [self storeCurrentResultViewForRestoration]; - [self performQueries:[NSArray arrayWithObject:lastExecutedQuery] withCallback:NULL]; + [self performQueries:@[lastExecutedQuery] withCallback:NULL]; } else { #endif // otherwise, just update the data in the data storage @@ -2264,7 +2264,7 @@ sortColumn = tableColumn; else sortColumn = nil; - [self performQueries:[NSArray arrayWithObject:queryString] withCallback:@selector(tableSortCallback)]; + [self performQueries:@[queryString] withCallback:@selector(tableSortCallback)]; } - (void)tableSortCallback @@ -3392,7 +3392,7 @@ for (NSDictionary *favorite in [[SPQueryController sharedQueryController] favoritesForFileURL:[tableDocumentInstance fileURL]]) { if (![favorite isKindOfClass:[NSDictionary class]] || ![favorite objectForKey:@"name"]) continue; NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - [paraStyle setTabStops:[NSArray array]]; + [paraStyle setTabStops:@[]]; [paraStyle addTabStop:[[[NSTextTab alloc] initWithType:NSRightTabStopType location:190.0f] autorelease]]; NSDictionary *attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:paraStyle, [NSFont systemFontOfSize:11], nil] forKeys:[NSArray arrayWithObjects:NSParagraphStyleAttributeName, NSFontAttributeName, nil]]; NSAttributedString *titleString = [[[NSAttributedString alloc] @@ -3418,7 +3418,7 @@ for (NSDictionary *favorite in [prefs objectForKey:SPQueryFavorites]) { if (![favorite isKindOfClass:[NSDictionary class]] || ![favorite objectForKey:@"name"]) continue; NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - [paraStyle setTabStops:[NSArray array]]; + [paraStyle setTabStops:@[]]; [paraStyle addTabStop:[[[NSTextTab alloc] initWithType:NSRightTabStopType location:190.0f] autorelease]]; NSDictionary *attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:paraStyle, [NSFont systemFontOfSize:11], nil] forKeys:[NSArray arrayWithObjects:NSParagraphStyleAttributeName, NSFontAttributeName, nil]]; NSAttributedString *titleString = [[[NSAttributedString alloc] diff --git a/Source/SPDatabaseData.m b/Source/SPDatabaseData.m index 9d5b47e7..1bd9a8f9 100644 --- a/Source/SPDatabaseData.m +++ b/Source/SPDatabaseData.m @@ -428,7 +428,7 @@ NSInteger _sortStorageEngineEntry(NSDictionary *itemOne, NSDictionary *itemTwo, { SPMySQLResult *result = [connection queryString:query]; - if ([connection queryErrored]) return [NSArray array]; + if ([connection queryErrored]) return @[]; [result setReturnDataAsStrings:YES]; diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 7ab802da..88ab58ed 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -1841,7 +1841,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // show syntax(es) in sheet if (sender == self) { NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:self]; + [pb declareTypes:@[NSStringPboardType] owner:self]; [pb setString:createSyntax forType:NSStringPboardType]; // Table syntax copied Growl notification @@ -2330,7 +2330,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; { NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionSQL]]; + [panel setAllowedFileTypes:@[SPFileExtensionSQL]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:YES]; @@ -2361,7 +2361,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Copy to the clipboard NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:self]; + [pb declareTypes:@[NSStringPboardType] owner:self]; [pb setString:createSyntax forType:NSStringPboardType]; // Table syntax copied Growl notification @@ -5264,7 +5264,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; NSString *query = [NSString stringWithContentsOfFile:queryFileName encoding:NSUTF8StringEncoding error:&inError]; [fm removeItemAtPath:queryFileName error:nil]; if(inError == nil && query && [query length]) { - [customQueryInstance performQueries:[NSArray arrayWithObject:query] withCallback:NULL]; + [customQueryInstance performQueries:@[query] withCallback:NULL]; } } return; diff --git a/Source/SPEditorPreferencePane.m b/Source/SPEditorPreferencePane.m index 93e5c42b..e5250e1d 100644 --- a/Source/SPEditorPreferencePane.m +++ b/Source/SPEditorPreferencePane.m @@ -131,7 +131,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; { NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPColorThemeFileExtension]]; + [panel setAllowedFileTypes:@[SPColorThemeFileExtension]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:NO]; @@ -770,7 +770,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; if ([fm fileExistsAtPath:themePath isDirectory:nil]) { NSArray *allItemsRaw = [fm contentsOfDirectoryAtPath:themePath error:NULL]; - if(!allItemsRaw) return [NSArray array]; + if(!allItemsRaw) return @[]; // Filter out all themes NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF ENDSWITH %@", [NSString stringWithFormat:@".%@", SPColorThemeFileExtension]]; @@ -791,7 +791,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; return (NSArray *)allItems; } - return [NSArray array]; + return @[]; } - (void)_saveColorThemeAtPath:(NSString *)path diff --git a/Source/SPExportControllerDelegate.m b/Source/SPExportControllerDelegate.m index aca7791f..43b1804f 100644 --- a/Source/SPExportControllerDelegate.m +++ b/Source/SPExportControllerDelegate.m @@ -155,7 +155,7 @@ // Check whether the group of items make up a token groupToken = [self tokenObjectForString:[[processedTokens subarrayWithRange:NSMakeRange(k, 1 + i - k)] componentsJoinedByString:@""]]; if ([groupToken isKindOfClass:[SPExportFileNameTokenObject class]]) { - [processedTokens replaceObjectsInRange:NSMakeRange(k, 1 + i - k) withObjectsFromArray:[NSArray arrayWithObject:groupToken]]; + [processedTokens replaceObjectsInRange:NSMakeRange(k, 1 + i - k) withObjectsFromArray:@[groupToken]]; i = k + 1; break; } diff --git a/Source/SPFavoritesController.m b/Source/SPFavoritesController.m index d5564428..07d74ee0 100644 --- a/Source/SPFavoritesController.m +++ b/Source/SPFavoritesController.m @@ -237,7 +237,7 @@ static SPFavoritesController *sharedFavoritesController = nil; favoritesData = [[NSMutableDictionary alloc] initWithContentsOfFile:favoritesFile]; } else { - NSMutableDictionary *newFavorites = [NSMutableDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Favorites", @"favorites label"), SPFavoritesGroupNameKey, [NSArray array], SPFavoriteChildrenKey, nil] forKey:SPFavoritesRootKey]; + NSMutableDictionary *newFavorites = [NSMutableDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Favorites", @"favorites label"), SPFavoritesGroupNameKey, @[], SPFavoriteChildrenKey, nil] forKey:SPFavoritesRootKey]; error = nil; NSString *errorString = nil; diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index 9c2de5fc..2d8e9529 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -895,8 +895,7 @@ id ql = [NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel]; [[ql delegate] setDelegate:self]; - [ql setURLs:[NSArray arrayWithObject: - [NSURL fileURLWithPath:tmpFileName]] currentIndex:0 preservingDisplayState:YES]; + [ql setURLs:@[[NSURL fileURLWithPath:tmpFileName]] currentIndex:0 preservingDisplayState:YES]; // TODO: No interaction with iChat and iPhoto due to .scriptSuite warning: // unknown image format diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index e2319141..5db53418 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -467,7 +467,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte [allSchemaKeys setObject:a forKey:connectionName]; } else { [schemaData setObject:[NSDictionary dictionary] forKey:[NSString stringWithFormat:@"%@&DEL&no data loaded yet", connectionName]]; - [allSchemaKeys setObject:[NSArray array] forKey:connectionName]; + [allSchemaKeys setObject:@[] forKey:connectionName]; } [updatingConnections removeObject:connectionName]; diff --git a/Source/SPPrintAccessory.m b/Source/SPPrintAccessory.m index aab04630..043d04a1 100644 --- a/Source/SPPrintAccessory.m +++ b/Source/SPPrintAccessory.m @@ -49,7 +49,7 @@ - (NSArray *)localizedSummaryItems { - return [NSArray arrayWithObject:[NSDictionary dictionary]]; + return @[@{}]; } - (NSSet *)keyPathsForValuesAffectingPreview diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m index 3e33b533..0b1e59b6 100644 --- a/Source/SPQueryController.m +++ b/Source/SPQueryController.m @@ -226,7 +226,7 @@ static SPQueryController *sharedQueryController = nil; #ifndef SP_CODA NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionSQL]]; + [panel setAllowedFileTypes:@[SPFileExtensionSQL]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:YES]; diff --git a/Source/SPQueryDocumentsController.m b/Source/SPQueryDocumentsController.m index e42a734b..e4689c41 100644 --- a/Source/SPQueryDocumentsController.m +++ b/Source/SPQueryDocumentsController.m @@ -312,7 +312,7 @@ } #endif - return [NSArray array]; + return @[]; } /** @@ -355,7 +355,7 @@ - (NSArray *)queryFavoritesForFileURL:(NSURL *)fileURL andTabTrigger:(NSString *)tabTrigger includeGlobals:(BOOL)includeGlobals { - if (![tabTrigger length]) return [NSArray array]; + if (![tabTrigger length]) return @[]; NSMutableArray *result = [[NSMutableArray alloc] init]; @@ -390,7 +390,7 @@ */ - (NSArray*)functionList { - return (completionFunctionList != nil && [completionFunctionList count]) ? completionFunctionList : [NSArray array]; + return (completionFunctionList != nil && [completionFunctionList count]) ? completionFunctionList : @[]; } /** @@ -398,7 +398,7 @@ */ - (NSArray*)keywordList { - return (completionKeywordList != nil && [completionKeywordList count]) ? completionKeywordList : [NSArray array]; + return (completionKeywordList != nil && [completionKeywordList count]) ? completionKeywordList : @[]; } /** diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index c73501b8..38758a45 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -124,7 +124,7 @@ [self _initWithNoSelection]; // Register drag types - [favoritesTableView registerForDraggedTypes:[NSArray arrayWithObject:SPFavoritesPasteboardDragType]]; + [favoritesTableView registerForDraggedTypes:@[SPFavoritesPasteboardDragType]]; [favoritesArrayController setContent:favorites]; [favoritesTableView reloadData]; @@ -310,7 +310,7 @@ #ifndef SP_CODA NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionSQL]]; + [panel setAllowedFileTypes:@[SPFileExtensionSQL]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:YES]; @@ -335,7 +335,7 @@ #ifndef SP_CODA NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionDefault]]; + [panel setAllowedFileTypes:@[SPFileExtensionDefault]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:NO]; @@ -677,7 +677,7 @@ - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rows toPasteboard:(NSPasteboard*)pboard { - NSArray *pboardTypes = [NSArray arrayWithObject:SPFavoritesPasteboardDragType]; + NSArray *pboardTypes = @[SPFavoritesPasteboardDragType]; NSInteger originalRow = [rows firstIndex]; if(originalRow < 1) return NO; diff --git a/Source/SPServerVariablesController.m b/Source/SPServerVariablesController.m index 80c9f558..43da2068 100644 --- a/Source/SPServerVariablesController.m +++ b/Source/SPServerVariablesController.m @@ -126,7 +126,7 @@ { NSSavePanel *panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes:[NSArray arrayWithObject:@"cnf"]]; + [panel setAllowedFileTypes:@[@"cnf"]]; [panel setExtensionHidden:NO]; [panel setAllowsOtherFileTypes:YES]; diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 9d875555..4ee09fd9 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -165,7 +165,7 @@ [self updateTriggersForCurrentTable]; } else { - return [NSArray array]; + return @[]; } } diff --git a/Source/SPTableStructureDelegate.m b/Source/SPTableStructureDelegate.m index 4d2f580c..c027d339 100644 --- a/Source/SPTableStructureDelegate.m +++ b/Source/SPTableStructureDelegate.m @@ -74,7 +74,7 @@ else { // If the structure has loaded (not still loading!) and the table encoding // is set, use the appropriate collations. - collations = ([tableDocumentInstance structureLoaded] && [tableDataInstance tableEncoding] != nil) ? [databaseDataInstance getDatabaseCollationsForEncoding:[tableDataInstance tableEncoding]] : [NSArray array]; + collations = ([tableDocumentInstance structureLoaded] && [tableDataInstance tableEncoding] != nil) ? [databaseDataInstance getDatabaseCollationsForEncoding:[tableDataInstance tableEncoding]] : @[]; } [[tableColumn dataCell] removeAllItems]; @@ -254,7 +254,7 @@ if (![self saveRowOnDeselect]) return NO; if ([rows count] == 1) { - [pboard declareTypes:[NSArray arrayWithObject:SPDefaultPasteboardDragType] owner:nil]; + [pboard declareTypes:@[SPDefaultPasteboardDragType] owner:nil]; [pboard setString:[[NSNumber numberWithInteger:[rows firstIndex]] stringValue] forType:SPDefaultPasteboardDragType]; return YES; diff --git a/Source/SPTableStructureLoading.m b/Source/SPTableStructureLoading.m index 4c4e8c37..5366d49e 100644 --- a/Source/SPTableStructureLoading.m +++ b/Source/SPTableStructureLoading.m @@ -335,8 +335,8 @@ if (!selectedTable) { [tableSourceView reloadData]; // Empty indexesController's fields and indices explicitly before reloading - [indexesController setFields:[NSArray array]]; - [indexesController setIndexes:[NSArray array]]; + [indexesController setFields:@[]]; + [indexesController setIndexes:@[]]; [indexesTableView reloadData]; return; diff --git a/Source/SPTextView.m b/Source/SPTextView.m index 523a7ade..17c61faf 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -381,7 +381,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; NSMutableArray *sortedDbs = [NSMutableArray array]; - [sortedDbs addObjectsFromArray:[allDbs sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]]; + [sortedDbs addObjectsFromArray:[allDbs sortedArrayUsingDescriptors:@[desc]]]; NSString *currentDb = nil; NSString *currentTable = nil; @@ -478,7 +478,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS [sortedTables addObject:aTableName_id]; } else { [possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:[[db componentsSeparatedByString:SPUniqueSchemaDelimiter] lastObject], @"display", @"database-small", @"image", @"", @"isRef", nil]]; - [sortedTables addObjectsFromArray:[allTables sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]]; + [sortedTables addObjectsFromArray:[allTables sortedArrayUsingDescriptors:@[desc]]]; if([sortedTables count] > 1 && [sortedTables containsObject:[NSString stringWithFormat:@"%@%@%@", db, SPUniqueSchemaDelimiter, currentTable]]) { [sortedTables removeObject:[NSString stringWithFormat:@"%@%@%@", db, SPUniqueSchemaDelimiter, currentTable]]; [sortedTables insertObject:[NSString stringWithFormat:@"%@%@%@", db, SPUniqueSchemaDelimiter, currentTable] atIndex:0]; @@ -508,7 +508,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS break; } if(!breakFlag) { - NSArray *sortedFields = [allFields sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]; + NSArray *sortedFields = [allFields sortedArrayUsingDescriptors:@[desc]]; for(id field in sortedFields) { if(![field hasPrefix:@" "]) { NSString *fieldpath = [field substringFromIndex:[field rangeOfString:SPUniqueSchemaDelimiter].location]; @@ -1127,7 +1127,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS if (rtf) { - [pb declareTypes:[NSArray arrayWithObject:NSRTFPboardType] owner:self]; + [pb declareTypes:@[NSRTFPboardType] owner:self]; [pb setData:rtf forType:NSRTFPboardType]; } } @@ -1414,7 +1414,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS // if(currentDb != nil && dbs != nil && [dbs count] && [dbs objectForKey:currentDb]) { // NSArray *allTables = [[dbs objectForKey:currentDb] allKeys]; // NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; - // NSArray *sortedTables = [allTables sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]; + // NSArray *sortedTables = [allTables sortedArrayUsingDescriptors:@[desc]]; // [desc release]; // for(id table in sortedTables) { // NSDictionary * theTable = [[dbs objectForKey:currentDb] objectForKey:table]; @@ -1431,7 +1431,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS // } else { arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allTableAndViewNames]]; if(arr == nil) { - arr = [NSArray array]; + arr = @[]; } for(id w in arr) [possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:w, @"display", @"table-small-square", @"image", @"", @"isRef", nil]]; @@ -1440,13 +1440,13 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS else if([kind isEqualToString:@"$SP_ASLIST_ALL_DATABASES"]) { arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allDatabaseNames]]; if(arr == nil) { - arr = [NSArray array]; + arr = @[]; } for(id w in arr) [possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:w, @"display", @"database-small", @"image", @"", @"isRef", nil]]; arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allSystemDatabaseNames]]; if(arr == nil) { - arr = [NSArray array]; + arr = @[]; } for(id w in arr) [possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:w, @"display", @"database-small", @"image", @"", @"isRef", nil]]; @@ -1466,7 +1466,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS NSDictionary * theTable = [[dbs objectForKey:currentDb] objectForKey:currentTable]; NSArray *allFields = [theTable allKeys]; NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; - NSArray *sortedFields = [allFields sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]; + NSArray *sortedFields = [allFields sortedArrayUsingDescriptors:@[desc]]; [desc release]; for(id field in sortedFields) { if(![field hasPrefix:@" "]) { @@ -1499,7 +1499,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS } else { arr = [NSArray arrayWithArray:[[tableDocumentInstance valueForKeyPath:@"tableDataInstance"] valueForKey:@"columnNames"]]; if(arr == nil) { - arr = [NSArray array]; + arr = @[]; } for(id w in arr) [possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:w, @"display", @"field-small-square", @"image", @"", @"isRef", nil]]; diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m index 3fdcaa63..abfac606 100644 --- a/Source/SPUserManager.m +++ b/Source/SPUserManager.m @@ -135,7 +135,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; treeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES]; - [self setTreeSortDescriptors:[NSArray arrayWithObject:treeSortDescriptor]]; + [self setTreeSortDescriptors:@[treeSortDescriptor]]; [super windowDidLoad]; } -- cgit v1.2.3 From 3b251b8e3d4dc9a694ef76562b388ab07da54785 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 19:48:41 +0100 Subject: Replace some NSDictionaries with literals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [NSDictionary dictionary] → @{} * [NSDictionary dictionaryWithObject:forKey:] can safely be replaced. object==nil would have already thrown a NPE in the past. * Also replaced some (hopefully safe) NSArray initializers (ie. their objects should always exist). --- Source/GeneratePreviewForURL.m | 2 +- Source/MGTemplateEngine.m | 7 +- Source/MGTemplateStandardFilters.m | 5 +- Source/MGTemplateStandardMarkers.m | 22 +-- Source/SPActivityTextFieldCell.m | 2 +- Source/SPAppController.m | 35 ++--- Source/SPBundleCommandRunner.m | 2 +- Source/SPBundleCommandTextView.m | 2 +- Source/SPBundleEditorController.m | 241 ++++++++++++++++---------------- Source/SPConnectionController.m | 22 +-- Source/SPContentFilterManager.m | 16 +-- Source/SPCopyTable.m | 8 +- Source/SPCustomQuery.m | 34 ++--- Source/SPDataImport.m | 4 +- Source/SPDatabaseData.m | 18 +-- Source/SPDatabaseDocument.m | 94 ++++++------- Source/SPEditorPreferencePane.m | 12 +- Source/SPExtendedTableInfo.m | 2 +- Source/SPFavoritesController.m | 2 +- Source/SPFavoritesExporter.m | 2 +- Source/SPFavoritesImporter.m | 6 +- Source/SPFieldEditorController.m | 2 +- Source/SPFieldMapperController.m | 7 +- Source/SPGrowlController.m | 2 +- Source/SPNarrowDownCompletion.m | 6 +- Source/SPNavigatorController.m | 18 +-- Source/SPPreferenceControllerDelegate.m | 54 +++---- Source/SPPreferencesUpgrade.m | 80 +++++------ Source/SPProcessListController.m | 2 +- Source/SPQueryController.m | 2 +- Source/SPQueryControllerInitializer.m | 2 +- Source/SPQueryFavoriteManager.m | 50 ++++--- Source/SPSQLExporter.m | 2 +- Source/SPServerVariablesController.m | 2 +- Source/SPTableContent.m | 18 +-- Source/SPTableData.m | 2 +- Source/SPTableInfo.m | 4 +- Source/SPTableRelations.m | 2 +- Source/SPTableStructure.m | 15 +- Source/SPTableStructureLoading.m | 4 +- Source/SPTablesList.m | 34 ++--- Source/SPTextAndLinkCell.m | 2 +- Source/SPTextView.m | 2 +- Source/SPTooltip.m | 2 +- Source/SPWindowManagement.m | 14 +- 45 files changed, 419 insertions(+), 447 deletions(-) (limited to 'Source') diff --git a/Source/GeneratePreviewForURL.m b/Source/GeneratePreviewForURL.m index ebbadd5a..1062f11d 100644 --- a/Source/GeneratePreviewForURL.m +++ b/Source/GeneratePreviewForURL.m @@ -495,7 +495,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, [imgProps setObject:image forKey:(NSString *)kQLPreviewPropertyAttachmentDataKey]; } - [props setObject:[NSDictionary dictionaryWithObject:imgProps forKey:@"icon.tiff"] forKey:(NSString *)kQLPreviewPropertyAttachmentsKey]; + [props setObject:@{@"icon.tiff" : imgProps} forKey:(NSString *) kQLPreviewPropertyAttachmentsKey]; [props setObject:@"UTF-8" forKey:(NSString *)kQLPreviewPropertyTextEncodingNameKey]; [props setObject:[NSNumber numberWithInt:NSUTF8StringEncoding] forKey:(NSString *)kQLPreviewPropertyStringEncodingKey]; [props setObject:@"text/html" forKey:(NSString *)kQLPreviewPropertyMIMETypeKey]; diff --git a/Source/MGTemplateEngine.m b/Source/MGTemplateEngine.m index 4a5d3192..4fe7620b 100644 --- a/Source/MGTemplateEngine.m +++ b/Source/MGTemplateEngine.m @@ -189,10 +189,9 @@ SEL selector = @selector(templateEngine:encounteredError:isContinuing:); if ([(NSObject *)delegate respondsToSelector:selector]) { - NSError *error = [NSError errorWithDomain:TEMPLATE_ENGINE_ERROR_DOMAIN - code:code - userInfo:[NSDictionary dictionaryWithObject:errStr - forKey:NSLocalizedDescriptionKey]]; + NSError *error = [NSError errorWithDomain:TEMPLATE_ENGINE_ERROR_DOMAIN + code:code + userInfo:@{NSLocalizedDescriptionKey : errStr}]; [(NSObject *)delegate templateEngine:self encounteredError:error isContinuing:continuing]; diff --git a/Source/MGTemplateStandardFilters.m b/Source/MGTemplateStandardFilters.m index 3acc155e..f06ae752 100644 --- a/Source/MGTemplateStandardFilters.m +++ b/Source/MGTemplateStandardFilters.m @@ -16,10 +16,7 @@ - (NSArray *)filters { - return [NSArray arrayWithObjects: - UPPERCASE, LOWERCASE, CAPITALIZED, - DATE_FORMAT, COLOR_FORMAT, - nil]; + return @[UPPERCASE, LOWERCASE, CAPITALIZED, DATE_FORMAT, COLOR_FORMAT]; } - (NSObject *)filterInvoked:(NSString *)filter withArguments:(NSArray *)args onValue:(NSObject *)value diff --git a/Source/MGTemplateStandardMarkers.m b/Source/MGTemplateStandardMarkers.m index 543d16a7..5edcb00c 100644 --- a/Source/MGTemplateStandardMarkers.m +++ b/Source/MGTemplateStandardMarkers.m @@ -107,29 +107,20 @@ - (NSArray *)markers { - return [NSArray arrayWithObjects: - FOR_START, FOR_END, - SECTION_START, SECTION_END, - IF_START, ELSE, IF_END, - NOW, - COMMENT_START, COMMENT_END, - LOAD, - CYCLE, - SET, - nil]; + return @[FOR_START, FOR_END, SECTION_START, SECTION_END, IF_START, ELSE, IF_END, NOW, COMMENT_START, COMMENT_END, LOAD, CYCLE, SET]; } - (NSArray *)endMarkersForMarker:(NSString *)marker { if ([marker isEqualToString:FOR_START]) { - return [NSArray arrayWithObjects:FOR_END, nil]; + return @[FOR_END]; } else if ([marker isEqualToString:SECTION_START]) { - return [NSArray arrayWithObjects:SECTION_END, nil]; + return @[SECTION_END]; } else if ([marker isEqualToString:IF_START]) { - return [NSArray arrayWithObjects:IF_END, ELSE, nil]; + return @[IF_END, ELSE]; } else if ([marker isEqualToString:COMMENT_START]) { - return [NSArray arrayWithObjects:COMMENT_END, nil]; + return @[COMMENT_END]; } return nil; } @@ -531,8 +522,7 @@ } else if ([marker isEqualToString:SET]) { if (args && [args count] == 2 && *outputEnabled) { // Set variable arg1 to value arg2. - NSDictionary *newVar = [NSDictionary dictionaryWithObject:[args objectAtIndex:1] - forKey:[args objectAtIndex:0]]; + NSDictionary *newVar = @{[args objectAtIndex:0] : [args objectAtIndex:1]}; if (newVar) { *newVariables = newVar; } diff --git a/Source/SPActivityTextFieldCell.m b/Source/SPActivityTextFieldCell.m index 52b85bdd..5eb2deda 100644 --- a/Source/SPActivityTextFieldCell.m +++ b/Source/SPActivityTextFieldCell.m @@ -206,7 +206,7 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) /** * Allow hit tracking for cancel functionality */ -- (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView +- (NSCellHitResult)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView { return NSCellHitContentArea | NSCellHitTrackableArea; } diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 56da49cf..3f9db630 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -1821,10 +1821,12 @@ // For each scope add a submenu but not for the last one (should be General always) [menu addItem:[NSMenuItem separatorItem]]; [menu setAutoenablesItems:YES]; - NSArray *scopes = [NSArray arrayWithObjects:SPBundleScopeInputField, SPBundleScopeDataTable, SPBundleScopeGeneral, nil]; - NSArray *scopeTitles = [NSArray arrayWithObjects:NSLocalizedString(@"Input Field", @"input field menu item label"), - NSLocalizedString(@"Data Table", @"data table menu item label"), - NSLocalizedString(@"General", @"general menu item label"),nil]; + NSArray *scopes = @[SPBundleScopeInputField, SPBundleScopeDataTable, SPBundleScopeGeneral]; + NSArray *scopeTitles = @[ + NSLocalizedString(@"Input Field", @"input field menu item label"), + NSLocalizedString(@"Data Table", @"data table menu item label"), + NSLocalizedString(@"General", @"general menu item label") + ]; NSUInteger k = 0; BOOL bundleOtherThanGeneralFound = NO; @@ -2023,19 +2025,18 @@ */ - (NSMutableDictionary*)anonymizePreferencesForFeedbackReport:(NSMutableDictionary *)preferences { - [preferences removeObjectsForKeys: - [NSArray arrayWithObjects: - @"ContentFilters", - @"favorites", - @"lastSqlFileName", - @"NSNavLastRootDirectory", - @"openPath", - @"queryFavorites", - @"queryHistory", - @"tableColumnWidths", - @"savePath", - @"NSRecentDocumentRecords", - nil]]; + [preferences removeObjectsForKeys:@[ + @"ContentFilters", + @"favorites", + @"lastSqlFileName", + @"NSNavLastRootDirectory", + @"openPath", + @"queryFavorites", + @"queryHistory", + @"tableColumnWidths", + @"savePath", + @"NSRecentDocumentRecords" + ]]; return preferences; } diff --git a/Source/SPBundleCommandRunner.m b/Source/SPBundleCommandRunner.m index b8e22b93..45184618 100644 --- a/Source/SPBundleCommandRunner.m +++ b/Source/SPBundleCommandRunner.m @@ -219,7 +219,7 @@ // register command pid = [bashTask processIdentifier]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:pid], @"pid", - (contextInfo)?:[NSDictionary dictionary], @"contextInfo", + (contextInfo)?: @{}, @"contextInfo", @"bashcommand", @"type", [[NSDate date] descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], @"starttime", nil]; diff --git a/Source/SPBundleCommandTextView.m b/Source/SPBundleCommandTextView.m index 4ca63451..9a2d2ba8 100644 --- a/Source/SPBundleCommandTextView.m +++ b/Source/SPBundleCommandTextView.m @@ -377,7 +377,7 @@ NSInteger tabStopWidth = [prefs integerForKey:SPCustomQueryEditorTabStopWidth]; if(tabStopWidth < 1) tabStopWidth = 1; - float tabWidth = NSSizeToCGSize([@" " sizeWithAttributes:[NSDictionary dictionaryWithObject:tvFont forKey:NSFontAttributeName]]).width; + float tabWidth = NSSizeToCGSize([@" " sizeWithAttributes:@{NSFontAttributeName : tvFont}]).width; tabWidth = (float)tabStopWidth * tabWidth; NSInteger numberOfTabs = 256/tabStopWidth; diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index 4de339de..cb4ccf88 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -130,17 +130,17 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; triggerGeneralPopUpMenu = [[NSMenu alloc] initWithTitle:@""]; withBlobDataTablePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; - inputGeneralScopeArray = [[NSArray arrayWithObjects:SPBundleInputSourceNone, nil] retain]; - inputInputFieldScopeArray = [[NSArray arrayWithObjects:SPBundleInputSourceNone, SPBundleInputSourceSelectedText, SPBundleInputSourceEntireContent, nil] retain]; - inputDataTableScopeArray = [[NSArray arrayWithObjects:SPBundleInputSourceNone, SPBundleInputSourceSelectedTableRowsAsTab, SPBundleInputSourceSelectedTableRowsAsCsv, SPBundleInputSourceSelectedTableRowsAsSqlInsert, SPBundleInputSourceTableRowsAsTab, SPBundleInputSourceTableRowsAsCsv, SPBundleInputSourceTableRowsAsSqlInsert, nil] retain]; - outputInputFieldScopeArray = [[NSArray arrayWithObjects:SPBundleOutputActionNone, SPBundleOutputActionInsertAsText, SPBundleOutputActionInsertAsSnippet, SPBundleOutputActionReplaceSelection, SPBundleOutputActionReplaceContent, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML, nil] retain]; - outputGeneralScopeArray = [[NSArray arrayWithObjects:SPBundleOutputActionNone, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML, nil] retain]; - outputDataTableScopeArray = [[NSArray arrayWithObjects:SPBundleOutputActionNone, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML, nil] retain]; - inputFallbackInputFieldScopeArray = [[NSArray arrayWithObjects:SPBundleInputSourceNone, SPBundleInputSourceCurrentWord, SPBundleInputSourceCurrentLine, SPBundleInputSourceCurrentQuery, SPBundleInputSourceEntireContent, nil] retain]; - triggerInputFieldArray = [[NSArray arrayWithObjects:SPBundleTriggerActionNone, nil] retain]; - triggerDataTableArray = [[NSArray arrayWithObjects:SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged, SPBundleTriggerActionTableRowChanged, nil] retain]; - triggerGeneralArray = [[NSArray arrayWithObjects:SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged, nil] retain]; - withBlobDataTableArray = [[NSArray arrayWithObjects:SPBundleInputSourceBlobHandlingExclude, SPBundleInputSourceBlobHandlingInclude, SPBundleInputSourceBlobHandlingImageFileReference, SPBundleInputSourceBlobHandlingFileReference, nil] retain]; + inputGeneralScopeArray = [@[SPBundleInputSourceNone] retain]; + inputInputFieldScopeArray = [@[SPBundleInputSourceNone, SPBundleInputSourceSelectedText, SPBundleInputSourceEntireContent] retain]; + inputDataTableScopeArray = [@[SPBundleInputSourceNone, SPBundleInputSourceSelectedTableRowsAsTab, SPBundleInputSourceSelectedTableRowsAsCsv, SPBundleInputSourceSelectedTableRowsAsSqlInsert, SPBundleInputSourceTableRowsAsTab, SPBundleInputSourceTableRowsAsCsv, SPBundleInputSourceTableRowsAsSqlInsert] retain]; + outputInputFieldScopeArray = [@[SPBundleOutputActionNone, SPBundleOutputActionInsertAsText, SPBundleOutputActionInsertAsSnippet, SPBundleOutputActionReplaceSelection, SPBundleOutputActionReplaceContent, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML] retain]; + outputGeneralScopeArray = [@[SPBundleOutputActionNone, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML] retain]; + outputDataTableScopeArray = [@[SPBundleOutputActionNone, SPBundleOutputActionShowAsTextTooltip, SPBundleOutputActionShowAsHTMLTooltip, SPBundleOutputActionShowAsHTML] retain]; + inputFallbackInputFieldScopeArray = [@[SPBundleInputSourceNone, SPBundleInputSourceCurrentWord, SPBundleInputSourceCurrentLine, SPBundleInputSourceCurrentQuery, SPBundleInputSourceEntireContent] retain]; + triggerInputFieldArray = [@[SPBundleTriggerActionNone] retain]; + triggerDataTableArray = [@[SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged, SPBundleTriggerActionTableRowChanged] retain]; + triggerGeneralArray = [@[SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged] retain]; + withBlobDataTableArray = [@[SPBundleInputSourceBlobHandlingExclude, SPBundleInputSourceBlobHandlingInclude, SPBundleInputSourceBlobHandlingImageFileReference, SPBundleInputSourceBlobHandlingFileReference] retain]; NSMutableArray *allPopupScopeItems = [NSMutableArray array]; [allPopupScopeItems addObjectsFromArray:inputGeneralScopeArray]; @@ -155,65 +155,65 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [allPopupScopeItems addObjectsFromArray:triggerGeneralArray]; [allPopupScopeItems addObjectsFromArray:withBlobDataTableArray]; - NSDictionary *menuItemTitles = [NSDictionary dictionaryWithObjects: - [NSArray arrayWithObjects: - NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Input source dropdown: 'None' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Input source dropdown: 'None' item"), - NSLocalizedString(@"Selected Text", @"Bundle Editor : Scope=Field : Input source dropdown: 'selected text' item"), - NSLocalizedString(@"Entire Content", @"Bundle Editor : Scope=Field : Input source dropdown: 'entire content' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'none' item"), - NSLocalizedString(@"Selected Rows (TSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as tab-separated' item"), - NSLocalizedString(@"Selected Rows (CSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as comma-separated' item"), - NSLocalizedString(@"Selected Rows (SQL)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as SQL' item"), - NSLocalizedString(@"Table Content (TSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as tab-separated' item"), - NSLocalizedString(@"Table Content (CSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as comma-separated' item"), - NSLocalizedString(@"Table Content (SQL)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as SQL' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Output dropdown : 'none' item"), - NSLocalizedString(@"Insert as Text", @"Bundle Editor : Scope=Field : Output dropdown : 'insert as text' item"), - NSLocalizedString(@"Insert as Snippet", @"Bundle Editor : Scope=Field : Output dropdown : 'insert as snippet' item"), - NSLocalizedString(@"Replace Selection", @"Bundle Editor : Scope=Field : Output dropdown : 'replace selection' item"), - NSLocalizedString(@"Replace Entire Content", @"Bundle Editor : Scope=Field : Output dropdown : 'replace entire content' item"), - NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=Field : Output dropdown : 'show as text tooltip' item"), - NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=Field : Output dropdown : 'show as html tooltip' item"), - NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=Field : Output dropdown : 'show as html' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Output dropdown : 'none' item"), - NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=General : Output dropdown : 'show as text tooltip' item"), - NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=General : Output dropdown : 'show as html tooltip' item"), - NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=General : Output dropdown : 'show as html' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'none' item"), - NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as text tooltip' item"), - NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as html tooltip' item"), - NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as html' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Fallback Input source dropdown : 'none' item"), - NSLocalizedString(@"Current Word", @"Bundle Editor : Fallback Input source dropdown : 'current word' item"), - NSLocalizedString(@"Current Line", @"Bundle Editor : Fallback Input source dropdown : 'current line' item"), - NSLocalizedString(@"Current Query", @"Bundle Editor : Fallback Input source dropdown : 'current query' item"), - NSLocalizedString(@"Entire Content", @"Bundle Editor : Fallback Input source dropdown : 'entire content' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Trigger dropdown : 'none' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'none' item"), - NSLocalizedString(@"Database changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'database changed' item"), - NSLocalizedString(@"Table changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'table changed' item"), - NSLocalizedString(@"Table Row changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'table row changed' item"), - - NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Trigger dropdown : 'none' item"), - NSLocalizedString(@"Database changed", @"Bundle Editor : Scope=General : Trigger dropdown : 'database changed' item"), - NSLocalizedString(@"Table changed", @"Bundle Editor : Scope=General : Trigger dropdown : 'table changed' item"), - - NSLocalizedString(@"exclude BLOB", @"Bundle Editor : BLOB dropdown : 'exclude BLOB' item"), - NSLocalizedString(@"include BLOB", @"Bundle Editor : BLOB dropdown : 'include BLOB' item"), - NSLocalizedString(@"save BLOB as image file", @"Bundle Editor : BLOB dropdown : 'save BLOB as image file' item"), - NSLocalizedString(@"save BLOB as dat file", @"Bundle Editor : BLOB dropdown : 'save BLOB as dat file' item"), - - nil] - forKeys:allPopupScopeItems]; + NSDictionary *menuItemTitles = @{ + allPopupScopeItems : @[ + NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Input source dropdown: 'None' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Input source dropdown: 'None' item"), + NSLocalizedString(@"Selected Text", @"Bundle Editor : Scope=Field : Input source dropdown: 'selected text' item"), + NSLocalizedString(@"Entire Content", @"Bundle Editor : Scope=Field : Input source dropdown: 'entire content' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'none' item"), + NSLocalizedString(@"Selected Rows (TSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as tab-separated' item"), + NSLocalizedString(@"Selected Rows (CSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as comma-separated' item"), + NSLocalizedString(@"Selected Rows (SQL)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'selected rows as SQL' item"), + NSLocalizedString(@"Table Content (TSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as tab-separated' item"), + NSLocalizedString(@"Table Content (CSV)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as comma-separated' item"), + NSLocalizedString(@"Table Content (SQL)", @"Bundle Editor : Scope=Data-Table : Input source dropdown: 'table content as SQL' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Output dropdown : 'none' item"), + NSLocalizedString(@"Insert as Text", @"Bundle Editor : Scope=Field : Output dropdown : 'insert as text' item"), + NSLocalizedString(@"Insert as Snippet", @"Bundle Editor : Scope=Field : Output dropdown : 'insert as snippet' item"), + NSLocalizedString(@"Replace Selection", @"Bundle Editor : Scope=Field : Output dropdown : 'replace selection' item"), + NSLocalizedString(@"Replace Entire Content", @"Bundle Editor : Scope=Field : Output dropdown : 'replace entire content' item"), + NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=Field : Output dropdown : 'show as text tooltip' item"), + NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=Field : Output dropdown : 'show as html tooltip' item"), + NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=Field : Output dropdown : 'show as html' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Output dropdown : 'none' item"), + NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=General : Output dropdown : 'show as text tooltip' item"), + NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=General : Output dropdown : 'show as html tooltip' item"), + NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=General : Output dropdown : 'show as html' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'none' item"), + NSLocalizedString(@"Show as Text Tooltip", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as text tooltip' item"), + NSLocalizedString(@"Show as HTML Tooltip", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as html tooltip' item"), + NSLocalizedString(@"Show as HTML", @"Bundle Editor : Scope=Data-Table : Output dropdown : 'show as html' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Fallback Input source dropdown : 'none' item"), + NSLocalizedString(@"Current Word", @"Bundle Editor : Fallback Input source dropdown : 'current word' item"), + NSLocalizedString(@"Current Line", @"Bundle Editor : Fallback Input source dropdown : 'current line' item"), + NSLocalizedString(@"Current Query", @"Bundle Editor : Fallback Input source dropdown : 'current query' item"), + NSLocalizedString(@"Entire Content", @"Bundle Editor : Fallback Input source dropdown : 'entire content' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Trigger dropdown : 'none' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'none' item"), + NSLocalizedString(@"Database changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'database changed' item"), + NSLocalizedString(@"Table changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'table changed' item"), + NSLocalizedString(@"Table Row changed", @"Bundle Editor : Scope=Data-Table : Trigger dropdown : 'table row changed' item"), + + NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Trigger dropdown : 'none' item"), + NSLocalizedString(@"Database changed", @"Bundle Editor : Scope=General : Trigger dropdown : 'database changed' item"), + NSLocalizedString(@"Table changed", @"Bundle Editor : Scope=General : Trigger dropdown : 'table changed' item"), + + NSLocalizedString(@"exclude BLOB", @"Bundle Editor : BLOB dropdown : 'exclude BLOB' item"), + NSLocalizedString(@"include BLOB", @"Bundle Editor : BLOB dropdown : 'include BLOB' item"), + NSLocalizedString(@"save BLOB as image file", @"Bundle Editor : BLOB dropdown : 'save BLOB as image file' item"), + NSLocalizedString(@"save BLOB as dat file", @"Bundle Editor : BLOB dropdown : 'save BLOB as dat file' item"), + + ] + }; NSMenuItem *anItem; for(NSString* title in inputGeneralScopeArray) { @@ -294,52 +294,51 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [commandBundleTreeController setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]]; - shellVariableSuggestions = [[NSArray arrayWithObjects: - SPBundleShellVariableAllDatabases, - SPBundleShellVariableAllFunctions, - SPBundleShellVariableAllProcedures, - SPBundleShellVariableAllTables, - SPBundleShellVariableAllViews, - SPBundleShellVariableAppResourcesDirectory, - SPBundleShellVariableBlobFileDirectory, - SPBundleShellVariableExitInsertAsSnippet, - SPBundleShellVariableExitInsertAsText, - SPBundleShellVariableExitNone, - SPBundleShellVariableExitReplaceContent, - SPBundleShellVariableExitReplaceSelection, - SPBundleShellVariableExitShowAsHTML, - SPBundleShellVariableExitShowAsHTMLTooltip, - SPBundleShellVariableExitShowAsTextTooltip, - SPBundleShellVariableInputFilePath, - SPBundleShellVariableInputTableMetaData, - SPBundleShellVariableBundlePath, - SPBundleShellVariableBundleScope, - SPBundleShellVariableCurrentEditedColumnName, - SPBundleShellVariableCurrentEditedTable, - SPBundleShellVariableCurrentHost, - SPBundleShellVariableCurrentLine, - SPBundleShellVariableCurrentPort, - SPBundleShellVariableCurrentQuery, - SPBundleShellVariableCurrentUser, - SPBundleShellVariableCurrentWord, - SPBundleShellVariableDataTableSource, - SPBundleShellVariableDatabaseEncoding, - SPBundleShellVariableIconFile, - SPBundleShellVariableProcessID, - SPBundleShellVariableQueryFile, - SPBundleShellVariableQueryResultFile, - SPBundleShellVariableQueryResultMetaFile, - SPBundleShellVariableQueryResultStatusFile, - SPBundleShellVariableRDBMSType, - SPBundleShellVariableRDBMSVersion, - SPBundleShellVariableSelectedDatabase, - SPBundleShellVariableSelectedRowIndices, - SPBundleShellVariableSelectedTable, - SPBundleShellVariableSelectedTables, - SPBundleShellVariableSelectedText, - SPBundleShellVariableSelectedTextRange, - SPBundleShellVariableUsedQueryForTable, - nil + shellVariableSuggestions = [@[ + SPBundleShellVariableAllDatabases, + SPBundleShellVariableAllFunctions, + SPBundleShellVariableAllProcedures, + SPBundleShellVariableAllTables, + SPBundleShellVariableAllViews, + SPBundleShellVariableAppResourcesDirectory, + SPBundleShellVariableBlobFileDirectory, + SPBundleShellVariableExitInsertAsSnippet, + SPBundleShellVariableExitInsertAsText, + SPBundleShellVariableExitNone, + SPBundleShellVariableExitReplaceContent, + SPBundleShellVariableExitReplaceSelection, + SPBundleShellVariableExitShowAsHTML, + SPBundleShellVariableExitShowAsHTMLTooltip, + SPBundleShellVariableExitShowAsTextTooltip, + SPBundleShellVariableInputFilePath, + SPBundleShellVariableInputTableMetaData, + SPBundleShellVariableBundlePath, + SPBundleShellVariableBundleScope, + SPBundleShellVariableCurrentEditedColumnName, + SPBundleShellVariableCurrentEditedTable, + SPBundleShellVariableCurrentHost, + SPBundleShellVariableCurrentLine, + SPBundleShellVariableCurrentPort, + SPBundleShellVariableCurrentQuery, + SPBundleShellVariableCurrentUser, + SPBundleShellVariableCurrentWord, + SPBundleShellVariableDataTableSource, + SPBundleShellVariableDatabaseEncoding, + SPBundleShellVariableIconFile, + SPBundleShellVariableProcessID, + SPBundleShellVariableQueryFile, + SPBundleShellVariableQueryResultFile, + SPBundleShellVariableQueryResultMetaFile, + SPBundleShellVariableQueryResultStatusFile, + SPBundleShellVariableRDBMSType, + SPBundleShellVariableRDBMSVersion, + SPBundleShellVariableSelectedDatabase, + SPBundleShellVariableSelectedRowIndices, + SPBundleShellVariableSelectedTable, + SPBundleShellVariableSelectedTables, + SPBundleShellVariableSelectedText, + SPBundleShellVariableSelectedTextRange, + SPBundleShellVariableUsedQueryForTable ] retain]; if([[NSUserDefaults standardUserDefaults] objectForKey:SPBundleDeletedDefaultBundlesKey]) { @@ -348,7 +347,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [self _initTree]; -} +}; #pragma mark - @@ -675,7 +674,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; if(category == nil) category = @""; bundle = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:NSLocalizedString(@"New Bundle",@"Bundle Editor : Default name for new bundle in the list on the left"), NSLocalizedString(@"New Name",@"Bundle Editor : Default name for a new bundle in the menu"), @"", scope, category, newUUID, nil] - forKeys:[NSArray arrayWithObjects:kBundleNameKey, SPBundleFileNameKey, SPBundleFileCommandKey, SPBundleFileScopeKey, SPBundleFileCategoryKey, SPBundleFileUUIDKey, nil]]; + forKeys:@[kBundleNameKey, SPBundleFileNameKey, SPBundleFileCommandKey, SPBundleFileScopeKey, SPBundleFileCategoryKey, SPBundleFileUUIDKey]]; } if(![touchedBundleArray containsObject:[bundle objectForKey:kBundleNameKey]]) @@ -929,9 +928,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [saveDict setObject:[[saveDict objectForKey:SPBundleFileContactKey] rot13] forKey:SPBundleFileContactKey]; // Remove unnecessary keys - [saveDict removeObjectsForKeys:[NSArray arrayWithObjects: - kBundleNameKey, - nil]]; + [saveDict removeObjectsForKeys:@[kBundleNameKey]]; if(!isNewBundle) { @@ -1493,7 +1490,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; /** * Allow for drag-n-drop out of the application as a copy */ -- (NSUInteger)draggingSourceOperationMaskForLocal:(BOOL)isLocal +- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal { return NSDragOperationMove; } diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index e98cc426..e9d9272c 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -779,7 +779,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, { NSNumber *favoriteID = [self _createNewFavoriteID]; - NSArray *objects = [NSArray arrayWithObjects: + NSArray *objects = @[ NSLocalizedString(@"New Favorite", @"new favorite name"), @0, @"", @@ -787,20 +787,20 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, @"", @(-1), @"", - [NSNumber numberWithInt:NSOffState], - [NSNumber numberWithInt:NSOffState], - [NSNumber numberWithInt:NSOffState], - [NSNumber numberWithInt:NSOffState], + @(NSOffState), + @(NSOffState), + @(NSOffState), + @(NSOffState), @"", @"", @"", - [NSNumber numberWithInt:NSOffState], + @(NSOffState), @"", @"", - favoriteID, - nil]; + favoriteID + ]; - NSArray *keys = [NSArray arrayWithObjects: + NSArray *keys = @[ SPFavoriteNameKey, SPFavoriteTypeKey, SPFavoriteHostKey, @@ -818,8 +818,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, SPFavoriteSSHKeyLocationEnabledKey, SPFavoriteSSHKeyLocationKey, SPFavoriteSSHPortKey, - SPFavoriteIDKey, - nil]; + SPFavoriteIDKey + ]; // Create default favorite NSMutableDictionary *favorite = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys]; diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index d6fed676..e35fd672 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -89,12 +89,12 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; [contentFilterSplitView setMaxSize:245.f ofSubviewAtIndex:0]; // Add global group row to contentFilters - [contentFilters addObject:[NSDictionary dictionaryWithObjectsAndKeys: - NSLocalizedString(@"Global",@"Content Filter Manager : Filter Entry List: 'Global' Header"), @"MenuLabel", - @"", @"headerOfFileURL", - @"", @"Clause", - @"", @"ConjunctionLabel", - nil]]; + [contentFilters addObject:@{ + @"MenuLabel" : NSLocalizedString(@"Global", @"Content Filter Manager : Filter Entry List: 'Global' Header"), + @"headerOfFileURL" : @"", + @"Clause" : @"", + @"ConjunctionLabel" : @"" + }]; #ifndef SP_CODA /* prefs access */ // Build data source for global content filter (as mutable copy! otherwise each @@ -240,10 +240,10 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; // Duplicate a selected filter if sender == self if(sender == self) - filter = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:NSLocalizedString(@"%@ Copy",@"Content Filter Manager : Initial name of copied filter"),[contentFilterNameTextField stringValue]], [contentFilterTextView string], nil] forKeys:[NSArray arrayWithObjects:@"MenuLabel", @"Clause", nil]]; + filter = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:NSLocalizedString(@"%@ Copy",@"Content Filter Manager : Initial name of copied filter"),[contentFilterNameTextField stringValue]], [contentFilterTextView string], nil] forKeys:@[@"MenuLabel", @"Clause"]]; // Add a new filter else - filter = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:NSLocalizedString(@"New Filter",@"Content Filter Manager : Initial name for new filter"), @"", @"", nil] forKeys:[NSArray arrayWithObjects:@"MenuLabel", @"Clause", @"ConjunctionLabel", nil]]; + filter = [NSMutableDictionary dictionaryWithObjects:@[NSLocalizedString(@"New Filter",@"Content Filter Manager : Initial name for new filter"), @"", @""] forKeys:@[@"MenuLabel", @"Clause", @"ConjunctionLabel"]]; // If a favourite is currently selected, add the new favourite next to it if([contentFilterTableView numberOfSelectedRows] > 0) { diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m index 7796ca11..3efc132a 100644 --- a/Source/SPCopyTable.m +++ b/Source/SPCopyTable.m @@ -108,7 +108,7 @@ static const NSInteger kBlobAsImageFile = 4; if (tmp != nil){ NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObjects: NSStringPboardType, nil] owner:nil]; + [pb declareTypes:@[NSStringPboardType] owner:nil]; [pb setString:tmp forType:NSStringPboardType]; } @@ -119,7 +119,7 @@ static const NSInteger kBlobAsImageFile = 4; if (tmp != nil) { NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObjects:NSTabularTextPboardType, NSStringPboardType, nil] owner:nil]; + [pb declareTypes:@[NSTabularTextPboardType, NSStringPboardType] owner:nil]; [pb setString:tmp forType:NSStringPboardType]; [pb setString:tmp forType:NSTabularTextPboardType]; @@ -781,7 +781,7 @@ static const NSInteger kBlobAsImageFile = 4; NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]; #endif NSUInteger columnIndex = (NSUInteger)[[columnDefinition objectForKey:@"datacolumnindex"] integerValue]; - NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]; + NSDictionary *stringAttributes = @{NSFontAttributeName : tableFont}; Class spmysqlGeometryData = [SPMySQLGeometryData class]; // Check the number of rows available to check, sampling every n rows @@ -870,7 +870,7 @@ static const NSInteger kBlobAsImageFile = 4; maxCellWidth += columnBaseWidth; // If the header width is wider than this expanded width, use it instead - cellWidth = [[columnDefinition objectForKey:@"name"] sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont labelFontOfSize:[NSFont smallSystemFontSize]] forKey:NSFontAttributeName]].width; + cellWidth = [[columnDefinition objectForKey:@"name"] sizeWithAttributes:@{NSFontAttributeName : [NSFont labelFontOfSize:[NSFont smallSystemFontSize]]}].width; if (cellWidth + 10 > maxCellWidth) maxCellWidth = cellWidth + 10; return maxCellWidth; diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 21ce6970..94d1b355 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -1664,7 +1664,7 @@ #else NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]; #endif - [customQueryView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height]; + [customQueryView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:@{NSFontAttributeName : tableFont}]).height]; // If there are no table columns to add, return if (!cqColumnDefinition || ![cqColumnDefinition count]) return; @@ -1808,7 +1808,7 @@ NSDictionary *columnDefinition = [NSDictionary dictionaryWithDictionary:[cqColumnDefinition objectAtIndex:[[[[customQueryView tableColumns] objectAtIndex:columnIndex] identifier] integerValue]]]; if(!columnDefinition) - return [NSArray arrayWithObjects:@(-2), @"", nil]; + return @[@(-2), @""]; // Resolve the original table name for current column if AS was used NSString *tableForColumn = [columnDefinition objectForKey:@"org_table"]; @@ -1819,13 +1819,13 @@ // No table/database name found indicates that the field's column contains data from more than one table as for UNION // or the field data are not bound to any table as in SELECT 1 or if column database is unset if(!tableForColumn || ![tableForColumn length] || !dbForColumn || ![dbForColumn length]) - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; // if table and database name are given check if field can be identified unambiguously // first without blob data NSString *fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:NO]; if(!fieldIDQueryStr) - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; [tableDocumentInstance startTaskWithDescription:NSLocalizedString(@"Checking field data for editing...", @"checking field data for editing task description")]; @@ -1837,7 +1837,7 @@ if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } NSArray *tempRow = [tempResult getRowAsArray]; @@ -1847,7 +1847,7 @@ fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:YES]; if(!fieldIDQueryStr) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } tempResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@.%@ %@", @@ -1857,14 +1857,14 @@ if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } tempRow = [tempResult getRowAsArray]; if([tempRow count] && [[tempRow objectAtIndex:0] integerValue] < 1) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } } @@ -2290,9 +2290,7 @@ NSString *tmp = [customQueryView draggedRowsAsTabString]; if ( nil != tmp ) { - [pboard declareTypes:[NSArray arrayWithObjects: NSTabularTextPboardType, - NSStringPboardType, nil] - owner:nil]; + [pboard declareTypes:@[NSTabularTextPboardType, NSStringPboardType] owner:nil]; [pboard setString:tmp forType:NSStringPboardType]; [pboard setString:tmp forType:NSTabularTextPboardType]; return YES; @@ -3394,7 +3392,7 @@ NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; [paraStyle setTabStops:@[]]; [paraStyle addTabStop:[[[NSTextTab alloc] initWithType:NSRightTabStopType location:190.0f] autorelease]]; - NSDictionary *attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:paraStyle, [NSFont systemFontOfSize:11], nil] forKeys:[NSArray arrayWithObjects:NSParagraphStyleAttributeName, NSFontAttributeName, nil]]; + NSDictionary *attributes = @{NSParagraphStyleAttributeName : paraStyle, NSFontAttributeName : [NSFont systemFontOfSize:11]}; NSAttributedString *titleString = [[[NSAttributedString alloc] initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@⇥", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"] attributes:attributes] autorelease]; @@ -3420,7 +3418,7 @@ NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; [paraStyle setTabStops:@[]]; [paraStyle addTabStop:[[[NSTextTab alloc] initWithType:NSRightTabStopType location:190.0f] autorelease]]; - NSDictionary *attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:paraStyle, [NSFont systemFontOfSize:11], nil] forKeys:[NSArray arrayWithObjects:NSParagraphStyleAttributeName, NSFontAttributeName, nil]]; + NSDictionary *attributes = @{NSParagraphStyleAttributeName : paraStyle, NSFontAttributeName : [NSFont systemFontOfSize:11]}; NSAttributedString *titleString = [[[NSAttributedString alloc] initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@⇥", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"] attributes:attributes] autorelease]; @@ -3540,11 +3538,7 @@ // Result Table Font preference changed else if ([keyPath isEqualToString:SPGlobalResultTableFont]) { NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]]; -#ifndef SP_CODA - [customQueryView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height]; -#else - [customQueryView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height]; -#endif + [customQueryView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:@{NSFontAttributeName : tableFont}]).height]; [customQueryView setFont:tableFont]; [customQueryView reloadData]; } @@ -3596,13 +3590,13 @@ if([saveQueryFavoriteGlobal state] == NSOnState) { [favorites addObject:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[queryFavoriteNameTextField stringValue], queryToBeAddded, nil] - forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]]]; + forKeys:@[@"name", @"query"]]]; [prefs setObject:favorites forKey:SPQueryFavorites]; } else { [[SPQueryController sharedQueryController] addFavorite:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[queryFavoriteNameTextField stringValue], [[queryToBeAddded mutableCopy] autorelease], nil] - forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]] forFileURL:[tableDocumentInstance fileURL]]; + forKeys:@[@"name", @"query"]] forFileURL:[tableDocumentInstance fileURL]]; } [saveQueryFavoriteGlobal setState:NSOffState]; diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index ed17a506..b0355b05 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -662,7 +662,7 @@ [tablesListInstance updateTables:self]; // Re-query the structure of all databases in the background - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; // Import finished Growl notification [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Import Finished" @@ -1178,7 +1178,7 @@ [tablesListInstance performSelectorOnMainThread:@selector(updateTables:) withObject:self waitUntilDone:YES]; // Re-query the structure of all databases in the background - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; // Select the new table [tablesListInstance selectItemWithName:selectedTableTarget]; diff --git a/Source/SPDatabaseData.m b/Source/SPDatabaseData.m index 1bd9a8f9..58ffa2d2 100644 --- a/Source/SPDatabaseData.m +++ b/Source/SPDatabaseData.m @@ -167,7 +167,7 @@ NSInteger _sortStorageEngineEntry(NSDictionary *itemOne, NSDictionary *itemTwo, NSString *charSet = [NSString stringWithCString:c->name encoding:NSUTF8StringEncoding]; if ([charSet isEqualToString:characterSetEncoding]) { - [characterSetCollations addObject:[NSDictionary dictionaryWithObject:[NSString stringWithCString:c->collation encoding:NSUTF8StringEncoding] forKey:@"COLLATION_NAME"]]; + [characterSetCollations addObject:@{@"COLLATION_NAME" : [NSString stringWithCString:c->collation encoding:NSUTF8StringEncoding]}]; } ++c; @@ -191,36 +191,36 @@ NSInteger _sortStorageEngineEntry(NSDictionary *itemOne, NSDictionary *itemTwo, { if ([storageEngines count] == 0) { if ([serverSupport isMySQL3] || [serverSupport isMySQL4]) { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"MyISAM" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"MyISAM"}]; // Check if InnoDB support is enabled NSString *result = [self _getSingleVariableValue:@"have_innodb"]; if(result && [result isEqualToString:@"YES"]) - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"InnoDB" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"InnoDB"}]; // Before MySQL 4.1 the MEMORY engine was known as HEAP and the ISAM engine was included if ([serverSupport supportsPre41StorageEngines]) { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"HEAP" forKey:@"Engine"]]; - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"ISAM" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"HEAP"}]; + [storageEngines addObject:@{@"Engine" : @"ISAM"}]; } else { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"MEMORY" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"MEMORY"}]; } // BLACKHOLE storage engine was added in MySQL 4.1.11 if ([serverSupport supportsBlackholeStorageEngine]) { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"BLACKHOLE" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"BLACKHOLE"}]; } // ARCHIVE storage engine was added in MySQL 4.1.3 if ([serverSupport supportsArchiveStorageEngine]) { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"ARCHIVE" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"ARCHIVE"}]; } // CSV storage engine was added in MySQL 4.1.4 if ([serverSupport supportsCSVStorageEngine]) { - [storageEngines addObject:[NSDictionary dictionaryWithObject:@"CSV" forKey:@"Engine"]]; + [storageEngines addObject:@{@"Engine" : @"CSV"}]; } } // The table information_schema.engines didn't exist until MySQL 5.1.5 diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 88ab58ed..c62b42e4 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -1012,8 +1012,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [self _addDatabase]; // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:databaseStructureRetrieval selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; - } + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:databaseStructureRetrieval selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; + } else { // Reset chooseDatabaseButton if ([[self database] length]) { @@ -1631,30 +1631,30 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; */ - (NSNumber *)encodingTagFromMySQLEncoding:(NSString *)mysqlEncoding { - NSDictionary *translationMap = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithInt:SPEncodingUCS2], @"ucs2", - [NSNumber numberWithInt:SPEncodingUTF8], @"utf8", - [NSNumber numberWithInt:SPEncodingUTF8viaLatin1], @"utf8-", - [NSNumber numberWithInt:SPEncodingASCII], @"ascii", - [NSNumber numberWithInt:SPEncodingLatin1], @"latin1", - [NSNumber numberWithInt:SPEncodingMacRoman], @"macroman", - [NSNumber numberWithInt:SPEncodingCP1250Latin2], @"cp1250", - [NSNumber numberWithInt:SPEncodingISOLatin2], @"latin2", - [NSNumber numberWithInt:SPEncodingCP1256Arabic], @"cp1256", - [NSNumber numberWithInt:SPEncodingGreek], @"greek", - [NSNumber numberWithInt:SPEncodingHebrew], @"hebrew", - [NSNumber numberWithInt:SPEncodingLatin5Turkish], @"latin5", - [NSNumber numberWithInt:SPEncodingCP1257WinBaltic], @"cp1257", - [NSNumber numberWithInt:SPEncodingCP1251WinCyrillic], @"cp1251", - [NSNumber numberWithInt:SPEncodingBig5Chinese], @"big5", - [NSNumber numberWithInt:SPEncodingShiftJISJapanese], @"sjis", - [NSNumber numberWithInt:SPEncodingEUCJPJapanese], @"ujis", - [NSNumber numberWithInt:SPEncodingEUCKRKorean], @"euckr", - nil]; + NSDictionary *translationMap = @{ + @"ucs2" : @(SPEncodingUCS2), + @"utf8" : @(SPEncodingUTF8), + @"utf8-" : @(SPEncodingUTF8viaLatin1), + @"ascii" : @(SPEncodingASCII), + @"latin1" : @(SPEncodingLatin1), + @"macroman" : @(SPEncodingMacRoman), + @"cp1250" : @(SPEncodingCP1250Latin2), + @"latin2" : @(SPEncodingISOLatin2), + @"cp1256" : @(SPEncodingCP1256Arabic), + @"greek" : @(SPEncodingGreek), + @"hebrew" : @(SPEncodingHebrew), + @"latin5" : @(SPEncodingLatin5Turkish), + @"cp1257" : @(SPEncodingCP1257WinBaltic), + @"cp1251" : @(SPEncodingCP1251WinCyrillic), + @"big5" : @(SPEncodingBig5Chinese), + @"sjis" : @(SPEncodingShiftJISJapanese), + @"ujis" : @(SPEncodingEUCJPJapanese), + @"euckr" : @(SPEncodingEUCKRKorean) + }; NSNumber *encodingTag = [translationMap valueForKey:mysqlEncoding]; if (!encodingTag) - return [NSNumber numberWithInt:SPEncodingAutodetect]; + return @(SPEncodingAutodetect); return encodingTag; } @@ -2843,7 +2843,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [panel setAccessoryView:[SPEncodingPopupAccessory encodingAccessory:[prefs integerForKey:SPLastSQLFileEncoding] includeDefaultEntry:NO encodingPopUp:&encodingPopUp]]; - [panel setAllowedFileTypes:[NSArray arrayWithObjects:SPFileExtensionSQL, nil]]; + [panel setAllowedFileTypes:@[SPFileExtensionSQL]]; if (![prefs stringForKey:@"lastSqlFileName"]) { [prefs setObject:@"" forKey:@"lastSqlFileName"]; @@ -2880,7 +2880,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } // Save current session (open connection windows as SPF file) - [panel setAllowedFileTypes:[NSArray arrayWithObjects:SPFileExtensionDefault, nil]]; + [panel setAllowedFileTypes:@[SPFileExtensionDefault]]; //Restore accessory view settings if possible if ([spfDocData objectForKey:@"save_password"]) { @@ -2933,7 +2933,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; return; } - [panel setAllowedFileTypes:[NSArray arrayWithObjects:SPBundleFileExtension, nil]]; + [panel setAllowedFileTypes:@[SPBundleFileExtension]]; NSDictionary *spfSessionData = [SPAppDelegate spfSessionDocData]; @@ -3357,7 +3357,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [spfStructure setObject:[stateDetails objectForKey:SPQueryFavorites] forKey:SPQueryFavorites]; [spfStructure setObject:[stateDetails objectForKey:SPQueryHistory] forKey:SPQueryHistory]; [spfStructure setObject:[stateDetails objectForKey:SPContentFilters] forKey:SPContentFilters]; - [stateDetails removeObjectsForKeys:[NSArray arrayWithObjects:SPQueryFavorites, SPQueryHistory, SPContentFilters, nil]]; + [stateDetails removeObjectsForKeys:@[SPQueryFavorites, SPQueryHistory, SPContentFilters]]; [spfData addEntriesFromDictionary:stateDetails]; // Determine whether to use encryption when adding the data @@ -3443,13 +3443,13 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [[parentWindow windowController] addNewConnection:self]; // Get the current state - NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - @YES, @"connection", - @YES, @"history", - @YES, @"session", - @YES, @"query", - @YES, @"password", - nil]; + NSDictionary *allStateDetails = @{ + @"connection" : @YES, + @"history" : @YES, + @"session" : @YES, + @"query" : @YES, + @"password" : @YES + }; NSMutableDictionary *currentState = [NSMutableDictionary dictionaryWithDictionary:[self stateIncludingDetails:allStateDetails]]; // Ensure it's set to autoconnect, and clear the table @@ -3589,7 +3589,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } if (action == @selector(importFromClipboard:)){ - return [self database] && [[NSPasteboard generalPasteboard] availableTypeFromArray:[NSArray arrayWithObjects:NSStringPboardType, nil]]; + return [self database] && [[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSStringPboardType]]; } // Change "Save Query/Queries" menu item title dynamically @@ -4046,7 +4046,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; */ - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar { - return [NSArray arrayWithObjects: + return @[ SPMainToolbarDatabaseSelection, SPMainToolbarHistoryNavigation, SPMainToolbarShowConsole, @@ -4061,8 +4061,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarSpaceItemIdentifier, - NSToolbarSeparatorItemIdentifier, - nil]; + NSToolbarSeparatorItemIdentifier + ]; } /** @@ -4070,7 +4070,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; */ - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar { - return [NSArray arrayWithObjects: + return @[ SPMainToolbarDatabaseSelection, SPMainToolbarTableStructure, SPMainToolbarTableContent, @@ -4081,8 +4081,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; NSToolbarFlexibleSpaceItemIdentifier, SPMainToolbarHistoryNavigation, SPMainToolbarUserManager, - SPMainToolbarShowConsole, - nil]; + SPMainToolbarShowConsole + ]; } /** @@ -4090,14 +4090,14 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; */ - (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar { - return [NSArray arrayWithObjects: + return @[ SPMainToolbarTableStructure, SPMainToolbarTableContent, SPMainToolbarCustomQuery, SPMainToolbarTableInfo, SPMainToolbarTableRelations, - SPMainToolbarTableTriggers, - nil]; + SPMainToolbarTableTriggers + ]; } @@ -5643,7 +5643,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; - (NSDictionary*)shellVariables { - if(!_isConnected) return [NSDictionary dictionary]; + if(!_isConnected) return @{}; NSMutableDictionary *env = [NSMutableDictionary dictionary]; @@ -5865,9 +5865,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; { NSPasteboard *pb = [NSPasteboard generalPasteboard]; - [pb declareTypes:[NSArray arrayWithObjects: NSTabularTextPboardType, - NSStringPboardType, nil] - owner:nil]; + [pb declareTypes:@[NSTabularTextPboardType, NSStringPboardType] owner:nil]; [pb setString:tmp forType:NSStringPboardType]; [pb setString:tmp forType:NSTabularTextPboardType]; diff --git a/Source/SPEditorPreferencePane.m b/Source/SPEditorPreferencePane.m index e5250e1d..d5127e65 100644 --- a/Source/SPEditorPreferencePane.m +++ b/Source/SPEditorPreferencePane.m @@ -66,7 +66,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; editThemeListItems = [[NSArray arrayWithArray:[self _getAvailableThemes]] retain]; editorColors = - [[NSArray arrayWithObjects: + [@[ SPCustomQueryEditorTextColor, SPCustomQueryEditorBackgroundColor, SPCustomQueryEditorCaretColor, @@ -77,11 +77,11 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; SPCustomQueryEditorBacktickColor, SPCustomQueryEditorVariableColor, SPCustomQueryEditorHighlightQueryColor, - SPCustomQueryEditorSelectionColor, - nil] retain]; + SPCustomQueryEditorSelectionColor + ] retain]; editorNameForColors = - [[NSArray arrayWithObjects: + [@[ NSLocalizedString(@"Text", @"text label for color table (Prefs > Editor)"), NSLocalizedString(@"Background", @"background label for color table (Prefs > Editor)"), NSLocalizedString(@"Caret", @"caret label for color table (Prefs > Editor)"), @@ -92,8 +92,8 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; NSLocalizedString(@"Backtick Quote", @"backtick quote label for color table (Prefs > Editor)"), NSLocalizedString(@"Variable", @"variable label for color table (Prefs > Editor)"), NSLocalizedString(@"Query Background", @"query background label for color table (Prefs > Editor)"), - NSLocalizedString(@"Selection", @"selection label for color table (Prefs > Editor)"), - nil] retain]; + NSLocalizedString(@"Selection", @"selection label for color table (Prefs > Editor)") + ] retain]; } return self; diff --git a/Source/SPExtendedTableInfo.m b/Source/SPExtendedTableInfo.m index 501b7c09..2e9eb9e2 100644 --- a/Source/SPExtendedTableInfo.m +++ b/Source/SPExtendedTableInfo.m @@ -490,7 +490,7 @@ static NSString *SPMySQLCommentField = @"Comment"; } NSError *error = nil; - NSArray *HTMLExcludes = [NSArray arrayWithObjects:@"doctype", @"html", @"head", @"body", @"xml", nil]; + NSArray *HTMLExcludes = @[@"doctype", @"html", @"head", @"body", @"xml"]; NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, HTMLExcludes, NSExcludedElementsDocumentAttribute, nil]; diff --git a/Source/SPFavoritesController.m b/Source/SPFavoritesController.m index 07d74ee0..76f376e8 100644 --- a/Source/SPFavoritesController.m +++ b/Source/SPFavoritesController.m @@ -377,7 +377,7 @@ static SPFavoritesController *sharedFavoritesController = nil; // from the current favourites tree and convert it to a dictionary representation // to create the plist data. This is done before file changes as it can sometimes // be terminated during shutdown. - NSDictionary *dictionary = [NSDictionary dictionaryWithObject:data forKey:SPFavoritesRootKey]; + NSDictionary *dictionary = @{SPFavoritesRootKey : data}; NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:dictionary format:NSPropertyListXMLFormat_v1_0 diff --git a/Source/SPFavoritesExporter.m b/Source/SPFavoritesExporter.m index d9342fa8..a8b78a86 100644 --- a/Source/SPFavoritesExporter.m +++ b/Source/SPFavoritesExporter.m @@ -77,7 +77,7 @@ [favorites addObject:[node dictionaryRepresentation]]; } - NSDictionary *dictionary = [NSDictionary dictionaryWithObject:favorites forKey:SPFavoritesDataRootKey]; + NSDictionary *dictionary = @{SPFavoritesDataRootKey : favorites}; [favorites release]; diff --git a/Source/SPFavoritesImporter.m b/Source/SPFavoritesImporter.m index 8dc1d94f..f80d6cff 100644 --- a/Source/SPFavoritesImporter.m +++ b/Source/SPFavoritesImporter.m @@ -127,9 +127,9 @@ static NSString *SPOldPreferenceFileFavoritesKey = @"favorites"; */ - (void)_informDelegateOfErrorCode:(NSUInteger)code description:(NSString *)description { - NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain - code:code - userInfo:[NSDictionary dictionaryWithObject:description forKey:NSLocalizedDescriptionKey]]; + NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain + code:code + userInfo:@{NSLocalizedDescriptionKey : description}]; [self _informDelegateOfImportCompletion:error]; } diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index 2d8e9529..9048cfe9 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -143,7 +143,7 @@ } } - qlTypes = [[NSDictionary dictionaryWithObject:qlTypesItems forKey:SPQuickLookTypes] retain]; + qlTypes = [@{SPQuickLookTypes : qlTypesItems} retain]; [qlTypesItems release]; #endif diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index 52b799d0..a79c8a40 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -162,7 +162,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; } - [defaultFieldTypesForComboBox setArray:[NSArray arrayWithObjects: + [defaultFieldTypesForComboBox setArray:@[ @"VARCHAR(255)", @"CHAR(63)", @"TEXT", @@ -172,9 +172,8 @@ static NSUInteger SPSourceColumnTypeInteger = 1; @"DATE", @"DATETIME", @"TIME", - @"TIMESTAMP", - nil - ]]; + @"TIMESTAMP" + ]]; [importFieldNamesHeaderSwitch setState:importFieldNamesHeader]; diff --git a/Source/SPGrowlController.m b/Source/SPGrowlController.m index e9fd3f77..f363208c 100644 --- a/Source/SPGrowlController.m +++ b/Source/SPGrowlController.m @@ -98,7 +98,7 @@ static SPGrowlController *sharedGrowlController = nil; [notificationDictionary setObject:description forKey:@"description"]; [notificationDictionary setObject:document forKey:@"document"]; [notificationDictionary setObject:name forKey:@"name"]; - [notificationDictionary setObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInteger:[document hash]] forKey:@"notificationDocumentHash"] forKey:@"clickContext"]; + [notificationDictionary setObject:@{@"notificationDocumentHash" : @([document hash])} forKey:@"clickContext"]; [self performSelector:@selector(notifyWithObject:) withObject:notificationDictionary afterDelay:0.1]; } diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m index 77ea9fbe..1b0128ca 100644 --- a/Source/SPNarrowDownCompletion.m +++ b/Source/SPNarrowDownCompletion.m @@ -294,7 +294,7 @@ for(NSUInteger i=0; imaxWindowWidth) ? maxWindowWidth : w; } else { maxWindowWidth = 220; @@ -712,7 +712,7 @@ closeMe = YES; return; } else { - [newFiltered addObject:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"No item found", @"no item found message"), @"display", @"", @"noCompletion", nil]]; + [newFiltered addObject:@{@"display" : NSLocalizedString(@"No item found", @"no item found message"), @"noCompletion" : @""}]; } } } @@ -725,7 +725,7 @@ // if fetching db structure add dummy row for displaying that info on top of the list if(isQueryingDatabaseStructure) - [newFiltered insertObject:[NSDictionary dictionaryWithObjectsAndKeys:@"dummy", @"display", @"", @"noCompletion", nil] atIndex:0]; + [newFiltered insertObject:@{@"display" : @"dummy", @"noCompletion" : @""} atIndex:0]; NSPoint old = NSMakePoint([self frame].origin.x, [self frame].origin.y + [self frame].size.height); diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index 5db53418..07feee86 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -155,7 +155,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte [schemaStatusSplitView setMinSize:16.f ofSubviewAtIndex:1]; [self setWindowFrameAutosaveName:@"SPNavigator"]; - [outlineSchema2 registerForDraggedTypes:[NSArray arrayWithObjects:SPNavigatorTableDataPasteboardDragType, SPNavigatorPasteboardDragType, NSStringPboardType, nil]]; + [outlineSchema2 registerForDraggedTypes:@[SPNavigatorTableDataPasteboardDragType, SPNavigatorPasteboardDragType, NSStringPboardType]]; [outlineSchema2 setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES]; [outlineSchema2 setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO]; @@ -466,7 +466,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if(a) [allSchemaKeys setObject:a forKey:connectionName]; } else { - [schemaData setObject:[NSDictionary dictionary] forKey:[NSString stringWithFormat:@"%@&DEL&no data loaded yet", connectionName]]; + [schemaData setObject:@{} forKey:[NSString stringWithFormat:@"%@&DEL&no data loaded yet", connectionName]]; [allSchemaKeys setObject:@[] forKey:connectionName]; } @@ -547,12 +547,12 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte } } - if([result count] < 1 ) return [NSArray arrayWithObjects:@0, @"", nil]; + if([result count] < 1 ) return @[@0, @""]; if([result count] == 1) { NSArray *split = [[result objectAtIndex:0] componentsSeparatedByString:SPUniqueSchemaDelimiter]; if([split count] == 2 ) return [NSArray arrayWithObjects:@1, [split lastObject], nil]; if([split count] == 3 ) return [NSArray arrayWithObjects:@2, [split lastObject], nil]; - return [NSArray arrayWithObjects:@0, @"", nil]; + return @[@0, @""]; } // case if field is equal to a table or db name NSMutableArray *arr = [NSMutableArray array]; @@ -560,14 +560,14 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if([[item componentsSeparatedByString:SPUniqueSchemaDelimiter] count] < 4) [arr addObject:item]; } - if([arr count] < 1 ) [NSArray arrayWithObjects:@0, @"", nil]; + if([arr count] < 1 ) @[@0, @""]; if([arr count] == 1) { NSArray *split = [[arr objectAtIndex:0] componentsSeparatedByString:SPUniqueSchemaDelimiter]; if([split count] == 2 ) [NSArray arrayWithObjects:@1, [split lastObject], nil]; if([split count] == 3 ) [NSArray arrayWithObjects:@2, [split lastObject], nil]; - return [NSArray arrayWithObjects:@0, @"", nil]; + return @[@0, @""]; } - return [NSArray arrayWithObjects:@0, @"", nil]; + return @[@0, @""]; } #ifndef SP_CODA @@ -611,7 +611,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if (![[doc getConnection] isConnected]) return; - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[doc databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[doc databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; } - (IBAction)outlineViewAction:(id)sender @@ -1113,7 +1113,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard { // Provide data for our custom type, and simple NSStrings. - [pboard declareTypes:[NSArray arrayWithObjects:SPNavigatorTableDataPasteboardDragType, SPNavigatorPasteboardDragType, NSStringPboardType, nil] owner:self]; + [pboard declareTypes:@[SPNavigatorTableDataPasteboardDragType, SPNavigatorPasteboardDragType, NSStringPboardType] owner:self]; // Collect the actual schema paths without leading connection ID NSMutableArray *draggedItems = [NSMutableArray array]; diff --git a/Source/SPPreferenceControllerDelegate.m b/Source/SPPreferenceControllerDelegate.m index ca08f2f0..ce05de6c 100644 --- a/Source/SPPreferenceControllerDelegate.m +++ b/Source/SPPreferenceControllerDelegate.m @@ -91,41 +91,41 @@ - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar { - return [NSArray arrayWithObjects: - SPPreferenceToolbarGeneral, - SPPreferenceToolbarTables, - SPPreferenceToolbarNotifications, - SPPreferenceToolbarEditor, - SPPreferenceToolbarShortcuts, - SPPreferenceToolbarAutoUpdate, - SPPreferenceToolbarNetwork, - nil]; + return @[ + SPPreferenceToolbarGeneral, + SPPreferenceToolbarTables, + SPPreferenceToolbarNotifications, + SPPreferenceToolbarEditor, + SPPreferenceToolbarShortcuts, + SPPreferenceToolbarAutoUpdate, + SPPreferenceToolbarNetwork + ]; } - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar { - return [NSArray arrayWithObjects: - SPPreferenceToolbarGeneral, - SPPreferenceToolbarTables, - SPPreferenceToolbarNotifications, - SPPreferenceToolbarEditor, - SPPreferenceToolbarShortcuts, - SPPreferenceToolbarAutoUpdate, - SPPreferenceToolbarNetwork, - nil]; + return @[ + SPPreferenceToolbarGeneral, + SPPreferenceToolbarTables, + SPPreferenceToolbarNotifications, + SPPreferenceToolbarEditor, + SPPreferenceToolbarShortcuts, + SPPreferenceToolbarAutoUpdate, + SPPreferenceToolbarNetwork + ]; } - (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar { - return [NSArray arrayWithObjects: - SPPreferenceToolbarGeneral, - SPPreferenceToolbarTables, - SPPreferenceToolbarNotifications, - SPPreferenceToolbarEditor, - SPPreferenceToolbarShortcuts, - SPPreferenceToolbarAutoUpdate, - SPPreferenceToolbarNetwork, - nil]; + return @[ + SPPreferenceToolbarGeneral, + SPPreferenceToolbarTables, + SPPreferenceToolbarNotifications, + SPPreferenceToolbarEditor, + SPPreferenceToolbarShortcuts, + SPPreferenceToolbarAutoUpdate, + SPPreferenceToolbarNetwork + ]; } @end diff --git a/Source/SPPreferencesUpgrade.m b/Source/SPPreferencesUpgrade.m index a412088c..d88dc4c8 100644 --- a/Source/SPPreferencesUpgrade.m +++ b/Source/SPPreferencesUpgrade.m @@ -130,22 +130,22 @@ void SPApplyRevisionChanges(void) if (recordedVersionNumber < 561) { NSEnumerator *keyEnumerator; NSString *oldKey, *newKey; - NSDictionary *keysToUpgrade = [NSDictionary dictionaryWithObjectsAndKeys: - @"encoding", SPDefaultEncoding, - @"useMonospacedFonts", SPUseMonospacedFonts, - @"reloadAfterAdding", SPReloadAfterAddingRow, - @"reloadAfterEditing", SPReloadAfterEditingRow, - @"reloadAfterRemoving", SPReloadAfterRemovingRow, - @"dontShowBlob", SPLoadBlobsAsNeeded, - @"fetchRowCount", @"FetchCorrectRowCount", - @"limitRows", SPLimitResults, - @"limitRowsValue", SPLimitResultsValue, - @"nullValue", SPNullValue, - @"showError", SPShowNoAffectedRowsError, - @"connectionTimeout", SPConnectionTimeoutValue, - @"keepAliveInterval", SPKeepAliveInterval, - @"lastFavoriteIndex", SPLastFavoriteID, - nil]; + NSDictionary *keysToUpgrade = @{ + SPDefaultEncoding : @"encoding", + SPUseMonospacedFonts : @"useMonospacedFonts", + SPReloadAfterAddingRow : @"reloadAfterAdding", + SPReloadAfterEditingRow : @"reloadAfterEditing", + SPReloadAfterRemovingRow : @"reloadAfterRemoving", + SPLoadBlobsAsNeeded : @"dontShowBlob", + @"FetchCorrectRowCount" : @"fetchRowCount", + SPLimitResults : @"limitRows", + SPLimitResultsValue : @"limitRowsValue", + SPNullValue : @"nullValue", + SPShowNoAffectedRowsError : @"showError", + SPConnectionTimeoutValue : @"connectionTimeout", + SPKeepAliveInterval : @"keepAliveInterval", + SPLastFavoriteID : @"lastFavoriteIndex" + }; keyEnumerator = [keysToUpgrade keyEnumerator]; @@ -255,7 +255,7 @@ void SPApplyRevisionChanges(void) if (([favorite isKindOfClass:[NSDictionary class]]) && ([favorite objectForKey:@"name"]) && ([favorite objectForKey:@"query"])) { NSMutableString *favoriteName = [NSMutableString stringWithString:[favorite objectForKey:@"name"]]; [favoriteName replaceOccurrencesOfString:@"\n" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [favoriteName length])]; - [queryFavoritesArray replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithString:favoriteName], [favorite objectForKey:@"query"], nil] forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]]]; + [queryFavoritesArray replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithString:favoriteName], [favorite objectForKey:@"query"], nil] forKeys:@[@"name", @"query"]]]; continue; } @@ -268,7 +268,7 @@ void SPApplyRevisionChanges(void) [favoriteName appendString:@"..."]; } - [queryFavoritesArray replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithString:favoriteName], favorite, nil] forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]]]; + [queryFavoritesArray replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithString:favoriteName], favorite, nil] forKeys:@[@"name", @"query"]]]; } [prefs setObject:queryFavoritesArray forKey:SPQueryFavorites]; @@ -287,27 +287,27 @@ void SPApplyRevisionChanges(void) // For versions prior to 2325 (<0.9.9), convert the old encoding pref string into the new localizable constant if (recordedVersionNumber < 2325 && [prefs objectForKey:SPOldDefaultEncodingKey] && [[prefs objectForKey:SPOldDefaultEncodingKey] isKindOfClass:[NSString class]]) { - NSDictionary *encodingMap = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithInt:SPEncodingAutodetect], @"Autodetect", - [NSNumber numberWithInt:SPEncodingUCS2], @"UCS-2 Unicode (ucs2)", - [NSNumber numberWithInt:SPEncodingUTF8], @"UTF-8 Unicode (utf8)", - [NSNumber numberWithInt:SPEncodingUTF8viaLatin1], @"UTF-8 Unicode via Latin 1", - [NSNumber numberWithInt:SPEncodingASCII], @"US ASCII (ascii)", - [NSNumber numberWithInt:SPEncodingLatin1], @"ISO Latin 1 (latin1)", - [NSNumber numberWithInt:SPEncodingMacRoman], @"Mac Roman (macroman)", - [NSNumber numberWithInt:SPEncodingCP1250Latin2], @"Windows Latin 2 (cp1250)", - [NSNumber numberWithInt:SPEncodingISOLatin2], @"ISO Latin 2 (latin2)", - [NSNumber numberWithInt:SPEncodingCP1256Arabic], @"Windows Arabic (cp1256)", - [NSNumber numberWithInt:SPEncodingGreek], @"ISO Greek (greek)", - [NSNumber numberWithInt:SPEncodingHebrew], @"ISO Hebrew (hebrew)", - [NSNumber numberWithInt:SPEncodingLatin5Turkish], @"ISO Turkish (latin5)", - [NSNumber numberWithInt:SPEncodingCP1257WinBaltic], @"Windows Baltic (cp1257)", - [NSNumber numberWithInt:SPEncodingCP1251WinCyrillic], @"Windows Cyrillic (cp1251)", - [NSNumber numberWithInt:SPEncodingBig5Chinese], @"Big5 Traditional Chinese (big5)", - [NSNumber numberWithInt:SPEncodingShiftJISJapanese], @"Shift-JIS Japanese (sjis)", - [NSNumber numberWithInt:SPEncodingEUCJPJapanese], @"EUC-JP Japanese (ujis)", - [NSNumber numberWithInt:SPEncodingEUCKRKorean], @"EUC-KR Korean (euckr)", - nil]; + NSDictionary *encodingMap = @{ + @"Autodetect" : @(SPEncodingAutodetect), + @"UCS-2 Unicode (ucs2)" : @(SPEncodingUCS2), + @"UTF-8 Unicode (utf8)" : @(SPEncodingUTF8), + @"UTF-8 Unicode via Latin 1" : @(SPEncodingUTF8viaLatin1), + @"US ASCII (ascii)" : @(SPEncodingASCII), + @"ISO Latin 1 (latin1)" : @(SPEncodingLatin1), + @"Mac Roman (macroman)" : @(SPEncodingMacRoman), + @"Windows Latin 2 (cp1250)" : @(SPEncodingCP1250Latin2), + @"ISO Latin 2 (latin2)" : @(SPEncodingISOLatin2), + @"Windows Arabic (cp1256)" : @(SPEncodingCP1256Arabic), + @"ISO Greek (greek)" : @(SPEncodingGreek), + @"ISO Hebrew (hebrew)" : @(SPEncodingHebrew), + @"ISO Turkish (latin5)" : @(SPEncodingLatin5Turkish), + @"Windows Baltic (cp1257)" : @(SPEncodingCP1257WinBaltic), + @"Windows Cyrillic (cp1251)" : @(SPEncodingCP1251WinCyrillic), + @"Big5 Traditional Chinese (big5)" : @(SPEncodingBig5Chinese), + @"Shift-JIS Japanese (sjis)" : @(SPEncodingShiftJISJapanese), + @"EUC-JP Japanese (ujis)" : @(SPEncodingEUCJPJapanese), + @"EUC-KR Korean (euckr)" : @(SPEncodingEUCKRKorean) + }; NSNumber *newMappedValue = [encodingMap valueForKey:[prefs objectForKey:SPOldDefaultEncodingKey]]; @@ -394,7 +394,7 @@ void SPMigrateConnectionFavoritesData(void) [prefs removeObjectForKey:@"LastFavoriteIndex"]; } - NSDictionary *newFavorites = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Favorites", @"favorites label"), SPFavoritesGroupNameKey, favorites, SPFavoriteChildrenKey, nil] forKey:SPFavoritesRootKey]; + NSDictionary *newFavorites = @{SPFavoritesRootKey : [NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Favorites", @"favorites label"), SPFavoritesGroupNameKey, favorites, SPFavoriteChildrenKey, nil]}; error = nil; NSString *errorString = nil; diff --git a/Source/SPProcessListController.m b/Source/SPProcessListController.m index c77e82d2..f24a7891 100644 --- a/Source/SPProcessListController.m +++ b/Source/SPProcessListController.m @@ -167,7 +167,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard]; // Copy the string to the pasteboard - [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil]; + [pasteBoard declareTypes:@[NSStringPboardType] owner:nil]; [pasteBoard setString:string forType:NSStringPboardType]; } } diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m index 0b1e59b6..c08aec3e 100644 --- a/Source/SPQueryController.m +++ b/Source/SPQueryController.m @@ -199,7 +199,7 @@ static SPQueryController *sharedQueryController = nil; NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard]; // Copy the string to the pasteboard - [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil]; + [pasteBoard declareTypes:@[NSStringPboardType] owner:nil]; [pasteBoard setString:string forType:NSStringPboardType]; } #endif diff --git a/Source/SPQueryControllerInitializer.m b/Source/SPQueryControllerInitializer.m index 8890a607..fc03d107 100644 --- a/Source/SPQueryControllerInitializer.m +++ b/Source/SPQueryControllerInitializer.m @@ -136,7 +136,7 @@ static NSString *SPCompletionTokensSnippetsKey = @"function_argument_snippets"; } } - return errorDescription ? [NSError errorWithDomain:NSCocoaErrorDomain code:1 userInfo:[NSDictionary dictionaryWithObject:errorDescription forKey:NSLocalizedDescriptionKey]] : nil; + return errorDescription ? [NSError errorWithDomain:NSCocoaErrorDomain code:1 userInfo:@{NSLocalizedDescriptionKey : errorDescription}] : nil; } @end diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index 38758a45..649d4b5a 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -43,8 +43,6 @@ #define SP_MULTIPLE_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[multiple selection]", @"[multiple selection]") #define SP_NO_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[no selection]", @"[no selection]") -#define SP_Int(x) [NSNumber numberWithInteger:x] - @interface SPQueryFavoriteManager () - (void)_initWithNoSelection; @@ -86,11 +84,11 @@ - (void)awakeFromNib { #ifndef SP_CODA - [favorites addObject:[NSDictionary dictionaryWithObjectsAndKeys: - @"Global", @"name", - @"", @"headerOfFileURL", - @"", @"query", - nil]]; + [favorites addObject:@{ + @"name" : @"Global", + @"headerOfFileURL" : @"", + @"query" : @"" + }]; // Set up the split view [favoritesSplitView setMinSize:152.f ofSubviewAtIndex:0]; @@ -206,7 +204,7 @@ favorite = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[[favoriteNameTextField stringValue] stringByAppendingFormat:@" Copy"], [favoriteQueryTextView string], nil] forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]]; // Add a new favorite else - favorite = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"New Favorite", @"", nil] forKeys:[NSArray arrayWithObjects:@"name", @"query", nil]]; + favorite = [NSMutableDictionary dictionaryWithObjects:@[@"New Favorite", @""] forKeys:@[@"name", @"query"]]; // If a favourite is currently selected, add the new favourite next to it if ([favoritesTableView numberOfSelectedRows] > 0) { @@ -380,24 +378,24 @@ { // Look up the sender's tag to determine the placeholder to insert. // Note that tag values alter behaviour slightly - see below. - NSDictionary *lookupTable = [NSDictionary dictionaryWithObjectsAndKeys: - NSLocalizedString(@"default_value", @"Query snippet default value placeholder"), SP_Int(100), - NSLocalizedString(@"$(shell_command)", @"Query snippet shell command syntax and placeholder"), SP_Int(101), - @"$1", SP_Int(501), - @"¦a¦b¦", SP_Int(102), - @"¦¦a¦b¦¦", SP_Int(103), - @"¦", SP_Int(104), - @"$SP_SELECTED_TABLE", SP_Int(105), - @"$SP_SELECTED_TABLES", SP_Int(106), - @"$SP_SELECTED_DATABASE", SP_Int(107), - @"¦$SP_ASLIST_ALL_FIELDS¦", SP_Int(108), - @"¦¦$SP_ASLIST_ALL_FIELDS¦¦", SP_Int(109), - @"¦$SP_ASLIST_ALL_TABLES¦", SP_Int(110), - @"¦¦$SP_ASLIST_ALL_TABLES¦¦", SP_Int(111), - @"¦$SP_ASLIST_ALL_DATABASES¦", SP_Int(112), - @"¦¦$SP_ASLIST_ALL_DATABASES¦¦", SP_Int(113), - nil]; - NSString *placeholder = [lookupTable objectForKey:SP_Int([[sender selectedItem] tag])]; + NSDictionary *lookupTable = @{ + @100 : NSLocalizedString(@"default_value", @"Query snippet default value placeholder"), + @101 : NSLocalizedString(@"$(shell_command)", @"Query snippet shell command syntax and placeholder"), + @501 : @"$1", + @102 : @"¦a¦b¦", + @103 : @"¦¦a¦b¦¦", + @104 : @"¦", + @105 : @"$SP_SELECTED_TABLE", + @106 : @"$SP_SELECTED_TABLES", + @107 : @"$SP_SELECTED_DATABASE", + @108 : @"¦$SP_ASLIST_ALL_FIELDS¦", + @109 : @"¦¦$SP_ASLIST_ALL_FIELDS¦¦", + @110 : @"¦$SP_ASLIST_ALL_TABLES¦", + @111 : @"¦¦$SP_ASLIST_ALL_TABLES¦¦", + @112 : @"¦$SP_ASLIST_ALL_DATABASES¦", + @113 : @"¦¦$SP_ASLIST_ALL_DATABASES¦¦" + }; + NSString *placeholder = [lookupTable objectForKey:[NSNumber numberWithInteger:[[sender selectedItem] tag]]]; if (!placeholder) [NSException raise:NSInternalInconsistencyException format:@"Inserted placeholder (%lld) not found", (long long)[[sender selectedItem] tag]]; // Iterate through the current snippets, to get the lowest unused tab counter, and diff --git a/Source/SPSQLExporter.m b/Source/SPSQLExporter.m index 649e4ac3..9fd57e6d 100644 --- a/Source/SPSQLExporter.m +++ b/Source/SPSQLExporter.m @@ -614,7 +614,7 @@ } // Export procedures and functions - for (NSString *procedureType in [NSArray arrayWithObjects:@"PROCEDURE", @"FUNCTION", nil]) + for (NSString *procedureType in @[@"PROCEDURE", @"FUNCTION"]) { // Check for cancellation flag if ([self isCancelled]) { diff --git a/Source/SPServerVariablesController.m b/Source/SPServerVariablesController.m index 43da2068..090970fb 100644 --- a/Source/SPServerVariablesController.m +++ b/Source/SPServerVariablesController.m @@ -370,7 +370,7 @@ NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard]; // Copy the string to the pasteboard - [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil]; + [pasteBoard declareTypes:@[NSStringPboardType] owner:nil]; [pasteBoard setString:string forType:NSStringPboardType]; } } diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index ae49c772..67825671 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -568,7 +568,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper #else NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]; #endif - [tableContentView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height]; + [tableContentView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:@{NSFontAttributeName : tableFont}]).height]; // Add the new columns to the table and filterTable for ( i = 0 ; i < (NSInteger)[dataColumns count] ; i++ ) { @@ -3333,7 +3333,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper NSDictionary *columnDefinition = [NSDictionary dictionaryWithDictionary:[cqColumnDefinition objectAtIndex:[[[[tableContentView tableColumns] objectAtIndex:columnIndex] identifier] integerValue]]]; if(!columnDefinition) - return [NSArray arrayWithObjects:@(-2), @"", nil]; + return @[@(-2), @""]; // Resolve the original table name for current column if AS was used NSString *tableForColumn = [columnDefinition objectForKey:@"org_table"]; @@ -3344,13 +3344,13 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // No table/database name found indicates that the field's column contains data from more than one table as for UNION // or the field data are not bound to any table as in SELECT 1 or if column database is unset if(!tableForColumn || ![tableForColumn length] || !dbForColumn || ![dbForColumn length]) - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; // if table and database name are given check if field can be identified unambiguously // first without blob data NSString *fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:NO]; if(!fieldIDQueryStr) - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; [tableDocumentInstance startTaskWithDescription:NSLocalizedString(@"Checking field data for editing...", @"checking field data for editing task description")]; @@ -3362,7 +3362,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } NSArray *tempRow = [tempResult getRowAsArray]; @@ -3372,7 +3372,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper fieldIDQueryStr = [self argumentForRow:rowIndex ofTable:tableForColumn andDatabase:[columnDefinition objectForKey:@"db"] includeBlobs:YES]; if(!fieldIDQueryStr) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } tempResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@.%@ %@", @@ -3382,14 +3382,14 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper if ([mySQLConnection queryErrored]) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } tempRow = [tempResult getRowAsArray]; if([tempRow count] && [[tempRow objectAtIndex:0] integerValue] < 1) { [tableDocumentInstance endTask]; - return [NSArray arrayWithObjects:@(-1), @"", nil]; + return @[@(-1), @""]; } } @@ -4252,7 +4252,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper else if ([keyPath isEqualToString:SPGlobalResultTableFont]) { NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]]; - [tableContentView setRowHeight:2.0f + NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height]; + [tableContentView setRowHeight:2.0f + NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:@{NSFontAttributeName : tableFont}]).height]; [tableContentView setFont:tableFont]; [tableContentView reloadData]; } diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 4ee09fd9..0e340f49 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -1170,7 +1170,7 @@ */ - (NSDictionary *) parseFieldDefinitionStringParts:(NSArray *)definitionParts { - if (![definitionParts count]) return [NSDictionary dictionary]; + if (![definitionParts count]) return @{}; SPSQLParser *detailParser; SPSQLParser *fieldParser = [[SPSQLParser alloc] init]; diff --git a/Source/SPTableInfo.m b/Source/SPTableInfo.m index 76a11a5c..4b16bdc0 100644 --- a/Source/SPTableInfo.m +++ b/Source/SPTableInfo.m @@ -78,7 +78,7 @@ object:nil]; // Add activities header - [activities addObject:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"ACTIVITIES", @"header for activities pane"), @"name", nil]]; + [activities addObject:@{@"name" : NSLocalizedString(@"ACTIVITIES", @"header for activities pane")}]; [activitiesTable reloadData]; // Add Information header @@ -110,7 +110,7 @@ NSMutableArray *acts = [NSMutableArray array]; [acts removeAllObjects]; - [acts addObject:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"ACTIVITIES", @"header for activities pane"), @"name", nil]]; + [acts addObject:@{@"name" : NSLocalizedString(@"ACTIVITIES", @"header for activities pane")}]; [acts addObjectsFromArray:[tableDocumentInstance runningActivities]]; [acts addObjectsFromArray:[SPAppDelegate runningActivities]]; diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index f2188a3b..f82dd3e7 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -163,7 +163,7 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; [thatTable backtickQuotedString], [thatColumn backtickQuotedString]]]; - NSArray *onActions = [NSArray arrayWithObjects:@"RESTRICT", @"CASCADE", @"SET NULL", @"NO ACTION", nil]; + NSArray *onActions = @[@"RESTRICT", @"CASCADE", @"SET NULL", @"NO ACTION"]; // If required add ON DELETE if ([onDeletePopUpButton selectedTag] >= 0) { diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 1b922683..9013fb05 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -116,12 +116,11 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [indexesTableView setFont:useMonospacedFont ? [NSFont fontWithName:SPDefaultMonospacedFontName size:monospacedFontSize] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; #endif - extraFieldSuggestions = [[NSArray arrayWithObjects: - @"None", - @"auto_increment", - @"on update CURRENT_TIMESTAMP", - @"SERIAL DEFAULT VALUE", - nil + extraFieldSuggestions = [@[ + @"None", + @"auto_increment", + @"on update CURRENT_TIMESTAMP", + @"SERIAL DEFAULT VALUE" ] retain]; // Note that changing the contents or ordering of this array will affect the implementation of @@ -254,7 +253,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [tableFields insertObject:[NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", allowNull ? @"1" : @"0", @"", [prefs stringForKey:SPNullValue], @"None", @"", @0, @0, nil] - forKeys:[NSArray arrayWithObjects:@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation", nil]] + forKeys:@[@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation"]] atIndex:insertIndex]; #else [tableFields insertObject:[NSMutableDictionary @@ -1208,7 +1207,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [indexesController setConnection:mySQLConnection]; // Set up tableView - [tableSourceView registerForDraggedTypes:[NSArray arrayWithObjects:SPDefaultPasteboardDragType, nil]]; + [tableSourceView registerForDraggedTypes:@[SPDefaultPasteboardDragType]]; } /** diff --git a/Source/SPTableStructureLoading.m b/Source/SPTableStructureLoading.m index 5366d49e..a15d31cd 100644 --- a/Source/SPTableStructureLoading.m +++ b/Source/SPTableStructureLoading.m @@ -288,9 +288,9 @@ // Query the structure of all databases in the background (mainly for completion) [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" - target:[tableDocumentInstance databaseStructureRetrieval] + target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + object:@{@"forceUpdate" : @YES}]; [self loadTable:selectedTable]; } diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 8d455b58..952d4868 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -168,7 +168,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; object:tableDocumentInstance]; #ifndef SP_CODA - [tablesListView registerForDraggedTypes:[NSArray arrayWithObjects:SPNavigatorTableDataPasteboardDragType, nil]]; + [tablesListView registerForDraggedTypes:@[SPNavigatorTableDataPasteboardDragType]]; #endif //create the charset helper @@ -360,7 +360,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:nil]; else // User press refresh button ergo force update - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", @YES, @"cancelQuerying", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES, @"cancelQuerying" : @YES}]; } /** @@ -704,13 +704,13 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; - (void)_duplicateConnectionToFrontTab { // Get the state of the document - NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - @YES, @"connection", - @YES, @"history", - @YES, @"session", - @YES, @"query", - @YES, @"password", - nil]; + NSDictionary *allStateDetails = @{ + @"connection" : @YES, + @"history" : @YES, + @"session" : @YES, + @"query" : @YES, + @"password" : @YES + }; NSMutableDictionary *documentState = [NSMutableDictionary dictionaryWithDictionary:[tableDocumentInstance stateIncludingDetails:allStateDetails]]; // Ensure it's set to autoconnect @@ -1621,7 +1621,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; #endif // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; } #ifndef SP_CODA @@ -2276,10 +2276,10 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; #endif // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" - target:[tableDocumentInstance databaseStructureRetrieval] - selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" + target:[tableDocumentInstance databaseStructureRetrieval] + selector:@selector(queryDbStructureWithUserInfo:) + object:@{@"forceUpdate" : @YES}]; } #ifndef SP_CODA /* operations performed on whole tables */ @@ -2428,9 +2428,9 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; // Query the structure of all databases in the background (mainly for completion) [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" - target:[tableDocumentInstance databaseStructureRetrieval] + target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) - object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + object:@{@"forceUpdate" : @YES}]; } else { // Error while creating new table @@ -2637,7 +2637,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [tableDocumentInstance loadTable:selectedTableName ofType:selectedTableType]; // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", nil]]; + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; } } } diff --git a/Source/SPTextAndLinkCell.m b/Source/SPTextAndLinkCell.m index a4d118ed..059ad6ec 100644 --- a/Source/SPTextAndLinkCell.m +++ b/Source/SPTextAndLinkCell.m @@ -176,7 +176,7 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) /** * Allow hit tracking for link functionality */ -- (NSUInteger) hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView +- (NSCellHitResult) hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView { // Fast case for no link - make entire cell editable click area diff --git a/Source/SPTextView.m b/Source/SPTextView.m index 17c61faf..4ed92f94 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -2907,7 +2907,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS #endif if(tabStopWidth < 1) tabStopWidth = 1; - float tabWidth = NSSizeToCGSize([@" " sizeWithAttributes:[NSDictionary dictionaryWithObject:tvFont forKey:NSFontAttributeName]]).width; + float tabWidth = NSSizeToCGSize([@" " sizeWithAttributes:@{NSFontAttributeName : tvFont}]).width; tabWidth = (float)tabStopWidth * tabWidth; NSInteger numberOfTabs = 256/tabStopWidth; diff --git a/Source/SPTooltip.m b/Source/SPTooltip.m index 276b5ebd..33564d81 100644 --- a/Source/SPTooltip.m +++ b/Source/SPTooltip.m @@ -96,7 +96,7 @@ static CGFloat slow_in_out (CGFloat t) + (void)showWithObject:(id)content atLocation:(NSPoint)point { - [self showWithObject:content atLocation:point ofType:@"text" displayOptions:[NSDictionary dictionary]]; + [self showWithObject:content atLocation:point ofType:@"text" displayOptions:@{}]; } + (void)showWithObject:(id)content atLocation:(NSPoint)point ofType:(NSString *)type diff --git a/Source/SPWindowManagement.m b/Source/SPWindowManagement.m index 022ad7fa..c30a2826 100644 --- a/Source/SPWindowManagement.m +++ b/Source/SPWindowManagement.m @@ -116,13 +116,13 @@ [[[self frontDocumentWindow] windowController] addNewConnection:self]; // Get the state of the previously-frontmost document - NSDictionary *allStateDetails = [NSDictionary dictionaryWithObjectsAndKeys: - @YES, @"connection", - @YES, @"history", - @YES, @"session", - @YES, @"query", - @YES, @"password", - nil]; + NSDictionary *allStateDetails = @{ + @"connection" : @YES, + @"history" : @YES, + @"session" : @YES, + @"query" : @YES, + @"password" : @YES + }; NSMutableDictionary *frontState = [NSMutableDictionary dictionaryWithDictionary:[theFrontDocument stateIncludingDetails:allStateDetails]]; -- cgit v1.2.3 From 28a705f74854d5c34d0e952c0747a512c19fadc2 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 20:24:58 +0100 Subject: Fix issue #2040 Changing the query favorties/history would cause an UI inconsitency when the list was filtered before. --- Source/SPCustomQuery.m | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'Source') diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 94d1b355..216cafa8 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -3363,6 +3363,9 @@ if(numberOfHistoryItems>0) for(id historyMenuItem in [[SPQueryController sharedQueryController] historyMenuItemsForFileURL:[tableDocumentInstance fileURL]]) [historyMenu addItem:historyMenuItem]; + + // Reapply the filter + [self filterQueryHistory:nil]; } /** @@ -3431,6 +3434,9 @@ [menu addItem:item]; [item release]; } + + // Reapply the filter + [self filterQueryFavorites:nil]; } #endif -- cgit v1.2.3 From d5dd8b1eb5b8bfaa040ddc52d603231e4828cec7 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 20:42:45 +0100 Subject: Attempt 1 to fix building on 10.7 --- Source/SPActivityTextFieldCell.m | 5 +++++ Source/SPTextAndLinkCell.m | 5 +++++ 2 files changed, 10 insertions(+) (limited to 'Source') diff --git a/Source/SPActivityTextFieldCell.m b/Source/SPActivityTextFieldCell.m index 5eb2deda..c088c9cb 100644 --- a/Source/SPActivityTextFieldCell.m +++ b/Source/SPActivityTextFieldCell.m @@ -33,6 +33,11 @@ #define FAVORITE_NAME_FONT_SIZE 12.0f +#ifndef NS_OPTIONS +// This type is available since 10.5 but only got a "name" in 10.8 +typedef NSUInteger NSCellHitResult; +#endif + @interface SPActivityTextFieldCell (PrivateAPI) - (NSAttributedString *)constructSubStringAttributedString; diff --git a/Source/SPTextAndLinkCell.m b/Source/SPTextAndLinkCell.m index 059ad6ec..86d8ca9d 100644 --- a/Source/SPTextAndLinkCell.m +++ b/Source/SPTextAndLinkCell.m @@ -42,6 +42,11 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) return NSMakeRect(inRect.origin.x + inRect.size.width - 15, inRect.origin.y - 1, 12, inRect.size.height); } +#ifndef NS_OPTIONS +// This type is available since 10.5 but only got a "name" in 10.8 +typedef NSUInteger NSCellHitResult; +#endif + #pragma mark - #pragma mark Setup and teardown -- cgit v1.2.3 From c573bf18ff0ce2a350bec687f2d7cc5ba5a69865 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 13 Dec 2014 21:00:30 +0100 Subject: Attempt 2 to fix building on 10.7, 10.8 --- Source/DMLocalizedNibBundle.m | 5 ----- Source/SPActivityTextFieldCell.m | 5 ----- Source/SPConstants.h | 16 ++++++++++++++++ Source/SPTableContent.m | 4 ---- Source/SPTextAndLinkCell.m | 4 ---- 5 files changed, 16 insertions(+), 18 deletions(-) (limited to 'Source') diff --git a/Source/DMLocalizedNibBundle.m b/Source/DMLocalizedNibBundle.m index 90fc4264..5dc94f9f 100644 --- a/Source/DMLocalizedNibBundle.m +++ b/Source/DMLocalizedNibBundle.m @@ -12,11 +12,6 @@ #import #import -//Backwards compatibility -#ifndef __MAC_10_8 -#define __MAC_10_8 1080 -#endif - @interface NSBundle (DMLocalizedNibBundle) #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_8 - (BOOL)deliciousLocalizingLoadNibNamed:(NSString *)fileName owner:(id)owner topLevelObjects:(NSArray **)topLevelObjects; diff --git a/Source/SPActivityTextFieldCell.m b/Source/SPActivityTextFieldCell.m index c088c9cb..5eb2deda 100644 --- a/Source/SPActivityTextFieldCell.m +++ b/Source/SPActivityTextFieldCell.m @@ -33,11 +33,6 @@ #define FAVORITE_NAME_FONT_SIZE 12.0f -#ifndef NS_OPTIONS -// This type is available since 10.5 but only got a "name" in 10.8 -typedef NSUInteger NSCellHitResult; -#endif - @interface SPActivityTextFieldCell (PrivateAPI) - (NSAttributedString *)constructSubStringAttributedString; diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 322219ae..f630dd49 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -609,3 +609,19 @@ extern NSString *SPURLSchemeQueryResultStatusPathHeader; extern NSString *SPURLSchemeQueryResultMetaPathHeader; #define SPAppDelegate ((SPAppController *)[NSApp delegate]) + +//Backwards compatibility +#ifndef __MAC_10_7 +#define __MAC_10_7 1070 +#endif +#ifndef __MAC_10_8 +#define __MAC_10_8 1080 +#endif +#ifndef __MAC_10_10 +#define __MAC_10_10 101000 +#endif + +// This enum is available since 10.5 but only got a "name" in 10.10 +#if __MAC_OS_X_VERSION_MAX_ALLOWED < __MAC_10_10 +typedef NSUInteger NSCellHitResult; +#endif diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 67825671..d904ab73 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -70,10 +70,6 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOperator"; #endif -#ifndef __MAC_10_7 -#define __MAC_10_7 1070 -#endif - @interface SPTableContent (SPTableContentDataSource_Private_API) - (id)_contentValueForTableColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex asPreview:(BOOL)asPreview; diff --git a/Source/SPTextAndLinkCell.m b/Source/SPTextAndLinkCell.m index 86d8ca9d..89521e54 100644 --- a/Source/SPTextAndLinkCell.m +++ b/Source/SPTextAndLinkCell.m @@ -42,10 +42,6 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) return NSMakeRect(inRect.origin.x + inRect.size.width - 15, inRect.origin.y - 1, 12, inRect.size.height); } -#ifndef NS_OPTIONS -// This type is available since 10.5 but only got a "name" in 10.8 -typedef NSUInteger NSCellHitResult; -#endif #pragma mark - #pragma mark Setup and teardown -- cgit v1.2.3 From 915b4fb171afec486a386b7098f6ccfe59058f4f Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 14 Dec 2014 17:19:50 +0100 Subject: Fix crash on export with "overwrite existing files" This should fix #2010. A required object was not retained long enough. --- Source/SPExportFileUtilities.m | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPExportFileUtilities.m b/Source/SPExportFileUtilities.m index aafea54d..778deb3e 100644 --- a/Source/SPExportFileUtilities.m +++ b/Source/SPExportFileUtilities.m @@ -31,10 +31,11 @@ #import "SPExportFileUtilities.h" #import "SPExportInitializer.h" #import "SPExporter.h" -#import "SPAlertSheets.h" #import "SPExportFile.h" #import "SPDatabaseDocument.h" #import "SPCustomQuery.h" +#import "SPTableContent.h" +#import "SPTableContentDelegate.h" #import @@ -53,7 +54,7 @@ SPExportErrorChoice; @end -@implementation SPExportController (SPExportFileUtilities) +@implementation SPExportController (SPExportFileUtilitiesPrivateAPI) /** * Writes the CSV file header to the supplied export file. @@ -115,7 +116,7 @@ SPExportErrorChoice; if ([exportXMLFormatPopUpButton indexOfSelectedItem] == SPXMLExportMySQLFormat) { - NSString *tag = @""; + NSString *tag; if (exportSource == SPTableExport) { tag = [NSString stringWithFormat:@"\n\n\n", [tableDocumentInstance database]]; @@ -141,6 +142,11 @@ SPExportErrorChoice; */ - (void)errorCreatingExportFileHandles:(NSArray *)files { + // We don't know where "files" came from, but we know 2 things: + // - NSAlert will NOT retain it as contextInfo + // - This method continues execution after [alert beginSheet:...], thus even if files was retained before, it could be released before the alert ends + [files retain]; + // Get the number of files that already exist as well as couldn't be created because of other reasons NSUInteger filesAlreadyExisting = 0; NSUInteger parentFoldersMissing = 0; @@ -270,6 +276,7 @@ SPExportErrorChoice; [exportProgressWindow orderOut:self]; [alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:files]; + [alert autorelease]; } /** -- cgit v1.2.3 From ef5193bc6b897f1040f252789d7c4b635abcb11b Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 14 Dec 2014 21:26:09 +0100 Subject: Fix an exception when opening Bundle Editor Caused by an earlier commit of mine. --- Source/SPBundleEditorController.m | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index cb4ccf88..197ceee6 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -155,8 +155,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [allPopupScopeItems addObjectsFromArray:triggerGeneralArray]; [allPopupScopeItems addObjectsFromArray:withBlobDataTableArray]; - NSDictionary *menuItemTitles = @{ - allPopupScopeItems : @[ + NSDictionary *menuItemTitles = [NSDictionary dictionaryWithObjects:@[ NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Input source dropdown: 'None' item"), NSLocalizedString(@"None", @"Bundle Editor : Scope=Field : Input source dropdown: 'None' item"), @@ -212,8 +211,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; NSLocalizedString(@"save BLOB as image file", @"Bundle Editor : BLOB dropdown : 'save BLOB as image file' item"), NSLocalizedString(@"save BLOB as dat file", @"Bundle Editor : BLOB dropdown : 'save BLOB as dat file' item"), - ] - }; + ] forKeys:allPopupScopeItems]; NSMenuItem *anItem; for(NSString* title in inputGeneralScopeArray) { @@ -2112,6 +2110,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [triggerInputFieldPopUpMenu release]; [triggerDataTablePopUpMenu release]; [triggerGeneralPopUpMenu release]; + [withBlobDataTablePopUpMenu release]; [inputNonePopUpMenu release]; [inputGeneralScopeArray release]; -- cgit v1.2.3 From ca6b8681a49d51b5dfafbb2647119ada070df8da Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 14 Dec 2014 22:37:12 +0100 Subject: Roll some duplicate code into a loop (so the compiler can unroll it again) --- Source/SPBundleEditorController.m | 92 ++++++++++++++------------------------- 1 file changed, 33 insertions(+), 59 deletions(-) (limited to 'Source') diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index 197ceee6..ac227cf4 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -120,7 +120,6 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; inputGeneralScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; inputInputFieldScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; inputDataTableScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; - inputNonePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; outputGeneralScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; outputInputFieldScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; outputDataTableScopePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; @@ -129,6 +128,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; triggerDataTablePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; triggerGeneralPopUpMenu = [[NSMenu alloc] initWithTitle:@""]; withBlobDataTablePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; + inputNonePopUpMenu = [[NSMenu alloc] initWithTitle:@""]; inputGeneralScopeArray = [@[SPBundleInputSourceNone] retain]; inputInputFieldScopeArray = [@[SPBundleInputSourceNone, SPBundleInputSourceSelectedText, SPBundleInputSourceEntireContent] retain]; @@ -141,6 +141,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; triggerDataTableArray = [@[SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged, SPBundleTriggerActionTableRowChanged] retain]; triggerGeneralArray = [@[SPBundleTriggerActionNone, SPBundleTriggerActionDatabaseChanged, SPBundleTriggerActionTableChanged] retain]; withBlobDataTableArray = [@[SPBundleInputSourceBlobHandlingExclude, SPBundleInputSourceBlobHandlingInclude, SPBundleInputSourceBlobHandlingImageFileReference, SPBundleInputSourceBlobHandlingFileReference] retain]; + NSArray *inputNoneArray = @[SPBundleInputSourceNone]; //we only need that once to construct the menu NSMutableArray *allPopupScopeItems = [NSMutableArray array]; [allPopupScopeItems addObjectsFromArray:inputGeneralScopeArray]; @@ -154,6 +155,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [allPopupScopeItems addObjectsFromArray:triggerDataTableArray]; [allPopupScopeItems addObjectsFromArray:triggerGeneralArray]; [allPopupScopeItems addObjectsFromArray:withBlobDataTableArray]; + [allPopupScopeItems addObjectsFromArray:inputNoneArray]; NSDictionary *menuItemTitles = [NSDictionary dictionaryWithObjects:@[ NSLocalizedString(@"None", @"Bundle Editor : Scope=General : Input source dropdown: 'None' item"), @@ -211,68 +213,40 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; NSLocalizedString(@"save BLOB as image file", @"Bundle Editor : BLOB dropdown : 'save BLOB as image file' item"), NSLocalizedString(@"save BLOB as dat file", @"Bundle Editor : BLOB dropdown : 'save BLOB as dat file' item"), + NSLocalizedString(@"None", @"Bundle Editor : Scope=? : ? dropdown: 'None' item") ] forKeys:allPopupScopeItems]; - NSMenuItem *anItem; - for(NSString* title in inputGeneralScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(inputPopupButtonChanged:) keyEquivalent:@""]; - [inputGeneralScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in inputInputFieldScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(inputPopupButtonChanged:) keyEquivalent:@""]; - [inputInputFieldScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in inputDataTableScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(inputPopupButtonChanged:) keyEquivalent:@""]; - [inputDataTableScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in outputGeneralScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(outputPopupButtonChanged:) keyEquivalent:@""]; - [outputGeneralScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in outputInputFieldScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(outputPopupButtonChanged:) keyEquivalent:@""]; - [outputInputFieldScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in outputDataTableScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(outputPopupButtonChanged:) keyEquivalent:@""]; - [outputDataTableScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in inputFallbackInputFieldScopeArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(inputFallbackPopupButtonChanged:) keyEquivalent:@""]; - [inputFallbackInputFieldScopePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in triggerInputFieldArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(triggerButtonChanged:) keyEquivalent:@""]; - [triggerInputFieldPopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in triggerDataTableArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(triggerButtonChanged:) keyEquivalent:@""]; - [triggerDataTablePopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in triggerGeneralArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(triggerButtonChanged:) keyEquivalent:@""]; - [triggerGeneralPopUpMenu addItem:anItem]; - [anItem release]; - } - for(NSString* title in withBlobDataTableArray) { - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:@selector(withBlobButtonChanged:) keyEquivalent:@""]; - [withBlobDataTablePopUpMenu addItem:anItem]; - [anItem release]; + struct _menuItemMap { + NSArray *items; + NSMenu *menu; + SEL action; + }; + + struct _menuItemMap menus[] = { + {inputGeneralScopeArray, inputGeneralScopePopUpMenu, @selector(inputPopupButtonChanged:)}, + {inputInputFieldScopeArray, inputInputFieldScopePopUpMenu, @selector(inputPopupButtonChanged:)}, + {inputDataTableScopeArray, inputDataTableScopePopUpMenu, @selector(inputPopupButtonChanged:)}, + {outputGeneralScopeArray, outputGeneralScopePopUpMenu, @selector(outputPopupButtonChanged:)}, + {outputInputFieldScopeArray, outputInputFieldScopePopUpMenu, @selector(outputPopupButtonChanged:)}, + {outputDataTableScopeArray, outputDataTableScopePopUpMenu, @selector(outputPopupButtonChanged:)}, + {inputFallbackInputFieldScopeArray, inputFallbackInputFieldScopePopUpMenu, @selector(inputFallbackPopupButtonChanged:)}, + {triggerInputFieldArray, triggerInputFieldPopUpMenu, @selector(triggerButtonChanged:)}, + {triggerDataTableArray, triggerDataTablePopUpMenu, @selector(triggerButtonChanged:)}, + {triggerGeneralArray, triggerGeneralPopUpMenu, @selector(triggerButtonChanged:)}, + {withBlobDataTableArray, withBlobDataTablePopUpMenu, @selector(withBlobButtonChanged:)}, + {inputNoneArray, inputNonePopUpMenu, NULL} + }; + + for(unsigned int i=0;i<(sizeof(menus)/sizeof(struct _menuItemMap));i++) { + struct _menuItemMap *menu = &menus[i]; + for(NSString* title in menu->items) { + NSMenuItem *anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:title] action:menu->action keyEquivalent:@""]; + [menu->menu addItem:anItem]; + [anItem release]; + } } - anItem = [[NSMenuItem alloc] initWithTitle:[menuItemTitles objectForKey:SPBundleInputSourceNone] action:nil keyEquivalent:@""]; - [inputNonePopUpMenu addItem:anItem]; - [anItem release]; + NSMenuItem *anItem; [inputGeneralScopePopUpMenu compatibleRemoveAllItems]; anItem = [[NSMenuItem alloc] initWithTitle:SP_BUNDLEEDITOR_SCOPE_GENERAL_STRING action:@selector(scopeButtonChanged:) keyEquivalent:@""]; [anItem setTag:kGeneralScopeArrayIndex]; -- cgit v1.2.3 From f90b5d98b485aac53c793a6c2d4df5418d6cb14d Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 19 Dec 2014 17:05:15 +0100 Subject: Add code for utf8mb4 encoding --- Source/SPConstants.h | 3 ++- Source/SPDatabaseDocument.m | 38 ++++++++++++++++++++------------------ 2 files changed, 22 insertions(+), 19 deletions(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index f630dd49..60787559 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -177,7 +177,8 @@ typedef enum SPEncodingBig5Chinese = 150, SPEncodingShiftJISJapanese = 160, SPEncodingEUCJPJapanese = 170, - SPEncodingEUCKRKorean = 180 + SPEncodingEUCKRKorean = 180, + SPEncodingUTF8MB4 = 190 } SPEncodingTypes; // Table index type menu tags diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index c62b42e4..9f5ce128 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -1649,7 +1649,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; @"big5" : @(SPEncodingBig5Chinese), @"sjis" : @(SPEncodingShiftJISJapanese), @"ujis" : @(SPEncodingEUCJPJapanese), - @"euckr" : @(SPEncodingEUCKRKorean) + @"euckr" : @(SPEncodingEUCKRKorean), + @"utf8mb4" : @(SPEncodingUTF8MB4) }; NSNumber *encodingTag = [translationMap valueForKey:mysqlEncoding]; @@ -1665,24 +1666,25 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; - (NSString *)mysqlEncodingFromEncodingTag:(NSNumber *)encodingTag { NSDictionary *translationMap = [NSDictionary dictionaryWithObjectsAndKeys: - @"ucs2", [NSString stringWithFormat:@"%i", SPEncodingUCS2], - @"utf8", [NSString stringWithFormat:@"%i", SPEncodingUTF8], - @"utf8-", [NSString stringWithFormat:@"%i", SPEncodingUTF8viaLatin1], - @"ascii", [NSString stringWithFormat:@"%i", SPEncodingASCII], - @"latin1", [NSString stringWithFormat:@"%i", SPEncodingLatin1], + @"ucs2", [NSString stringWithFormat:@"%i", SPEncodingUCS2], + @"utf8", [NSString stringWithFormat:@"%i", SPEncodingUTF8], + @"utf8-", [NSString stringWithFormat:@"%i", SPEncodingUTF8viaLatin1], + @"ascii", [NSString stringWithFormat:@"%i", SPEncodingASCII], + @"latin1", [NSString stringWithFormat:@"%i", SPEncodingLatin1], @"macroman", [NSString stringWithFormat:@"%i", SPEncodingMacRoman], - @"cp1250", [NSString stringWithFormat:@"%i", SPEncodingCP1250Latin2], - @"latin2", [NSString stringWithFormat:@"%i", SPEncodingISOLatin2], - @"cp1256", [NSString stringWithFormat:@"%i", SPEncodingCP1256Arabic], - @"greek", [NSString stringWithFormat:@"%i", SPEncodingGreek], - @"hebrew", [NSString stringWithFormat:@"%i", SPEncodingHebrew], - @"latin5", [NSString stringWithFormat:@"%i", SPEncodingLatin5Turkish], - @"cp1257", [NSString stringWithFormat:@"%i", SPEncodingCP1257WinBaltic], - @"cp1251", [NSString stringWithFormat:@"%i", SPEncodingCP1251WinCyrillic], - @"big5", [NSString stringWithFormat:@"%i", SPEncodingBig5Chinese], - @"sjis", [NSString stringWithFormat:@"%i", SPEncodingShiftJISJapanese], - @"ujis", [NSString stringWithFormat:@"%i", SPEncodingEUCJPJapanese], - @"euckr", [NSString stringWithFormat:@"%i", SPEncodingEUCKRKorean], + @"cp1250", [NSString stringWithFormat:@"%i", SPEncodingCP1250Latin2], + @"latin2", [NSString stringWithFormat:@"%i", SPEncodingISOLatin2], + @"cp1256", [NSString stringWithFormat:@"%i", SPEncodingCP1256Arabic], + @"greek", [NSString stringWithFormat:@"%i", SPEncodingGreek], + @"hebrew", [NSString stringWithFormat:@"%i", SPEncodingHebrew], + @"latin5", [NSString stringWithFormat:@"%i", SPEncodingLatin5Turkish], + @"cp1257", [NSString stringWithFormat:@"%i", SPEncodingCP1257WinBaltic], + @"cp1251", [NSString stringWithFormat:@"%i", SPEncodingCP1251WinCyrillic], + @"big5", [NSString stringWithFormat:@"%i", SPEncodingBig5Chinese], + @"sjis", [NSString stringWithFormat:@"%i", SPEncodingShiftJISJapanese], + @"ujis", [NSString stringWithFormat:@"%i", SPEncodingEUCJPJapanese], + @"euckr", [NSString stringWithFormat:@"%i", SPEncodingEUCKRKorean], + @"utf8mb4", [NSString stringWithFormat:@"%i", SPEncodingUTF8MB4], nil]; NSString *mysqlEncoding = [translationMap valueForKey:[NSString stringWithFormat:@"%i", [encodingTag intValue]]]; -- cgit v1.2.3 From 21ced682547ef855ac6d83a00ad7fda1b8225af3 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 23 Dec 2014 13:14:06 +0100 Subject: Fix two threading issues * A call of setString: from background thread which could cause a "deleted thread with uncommitted CATransaction" warning * SPFieldMapperController was allocated from a background thread with an own autoreleasepool, while it contains UI objects. This could cause a crash when the autoreleasepool was drained and the field mapper forcefully released, while other UI objects still had it retained. --- Source/SPDataImport.m | 54 +++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 25 deletions(-) (limited to 'Source') diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index b0355b05..5859b75d 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -754,7 +754,7 @@ if ([csvFileHandle compressionFormat] == SPBzip2Compression) useIndeterminate = YES; // Reset progress interface - [errorsView setString:@""]; + [[errorsView onMainThread] setString:@""]; [[singleProgressTitle onMainThread] setStringValue:NSLocalizedString(@"Importing CSV", @"text showing that the application is importing CSV")]; [[singleProgressText onMainThread] setStringValue:NSLocalizedString(@"Reading...", @"text showing that app is reading dump")]; [[singleProgressBar onMainThread] setIndeterminate:YES]; @@ -1240,29 +1240,33 @@ fieldMapperSheetStatus = SPFieldMapperInProgress; fieldMappingArrayHasGlobalVariables = NO; - // Init the field mapper controller - fieldMapperController = [(SPFieldMapperController *)[SPFieldMapperController alloc] initWithDelegate:self]; - [fieldMapperController setConnection:mySQLConnection]; - [fieldMapperController setSourcePath:filename]; - [fieldMapperController setImportDataArray:fieldMappingImportArray hasHeader:[importFieldNamesSwitch state] isPreview:fieldMappingImportArrayIsPreview]; - - // Show field mapper sheet and set the focus to it - [[NSApp onMainThread] beginSheet:[fieldMapperController window] - modalForWindow:[tableDocumentInstance parentWindow] - modalDelegate:self - didEndSelector:@selector(fieldMapperDidEndSheet:returnCode:contextInfo:) - contextInfo:nil]; - - [[[fieldMapperController window] onMainThread] makeKeyWindow]; + //the field mapper is an UI object and must not be caught in the background thread's autoreleasepool + dispatch_async(dispatch_get_main_queue(), ^{ + // Init the field mapper controller + fieldMapperController = [[SPFieldMapperController alloc] initWithDelegate:self]; + [fieldMapperController setConnection:mySQLConnection]; + [fieldMapperController setSourcePath:filename]; + [fieldMapperController setImportDataArray:fieldMappingImportArray hasHeader:[importFieldNamesSwitch state] isPreview:fieldMappingImportArrayIsPreview]; + + // Show field mapper sheet and set the focus to it + [NSApp beginSheet:[fieldMapperController window] + modalForWindow:[tableDocumentInstance parentWindow] + modalDelegate:self + didEndSelector:@selector(fieldMapperDidEndSheet:returnCode:contextInfo:) + contextInfo:nil]; + + [[fieldMapperController window] makeKeyWindow]; + }); // Wait for field mapper sheet while (fieldMapperSheetStatus == SPFieldMapperInProgress) usleep(100000); + + BOOL success = NO; // If the mapping was cancelled, abort the import if (fieldMapperSheetStatus == SPFieldMapperCancelled) { - if (fieldMapperController) [fieldMapperController release]; - return NO; + goto cleanup; } // Get mapping settings and preset some global variables @@ -1288,9 +1292,8 @@ || ![selectedTableTarget length] || ![csvImportHeaderString length]) { - if(fieldMapperController) [fieldMapperController release]; NSBeep(); - return NO; + goto cleanup; } // Store target table definitions @@ -1312,13 +1315,14 @@ [importFieldNamesSwitch setState:[fieldMapperController importFieldNamesHeader]]; [prefs setBool:[importFieldNamesSwitch state] forKey:SPCSVImportFirstLineIsHeader]; + success = YES; + +cleanup: + dispatch_async(dispatch_get_main_queue(), ^{ + if(fieldMapperController) [fieldMapperController release], fieldMapperController = nil; + }); - if(fieldMapperController) [fieldMapperController release]; - - if(fieldMapperSheetStatus == SPFieldMapperCompleted) - return YES; - else - return NO; + return success; } /** -- cgit v1.2.3 From 03d11e5d82a7c2a0c5db624020632a7d10b5a13a Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 23 Dec 2014 15:05:58 +0100 Subject: Add some more stub code (as the nib loader on 10.10 is even whinier) --- Source/SPTableContent.h | 3 +++ Source/SPTableContentFilterController.h | 13 ++++++++++++- Source/SPTableRelations.h | 1 + 3 files changed, 16 insertions(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPTableContent.h b/Source/SPTableContent.h index fdb434e8..15266d4e 100644 --- a/Source/SPTableContent.h +++ b/Source/SPTableContent.h @@ -48,6 +48,7 @@ #ifndef SP_CODA @class SPSplitView; #endif +@class SPTableContentFilterController; #import "SPDatabaseContentViewDelegate.h" @@ -116,6 +117,8 @@ // Temporary to avoid nib conflicts during WIP IBOutlet SPSplitView *contentSplitView; + + IBOutlet SPTableContentFilterController *filterControllerInstance; #endif SPMySQLConnection *mySQLConnection; diff --git a/Source/SPTableContentFilterController.h b/Source/SPTableContentFilterController.h index 15880416..542f4bad 100644 --- a/Source/SPTableContentFilterController.h +++ b/Source/SPTableContentFilterController.h @@ -5,6 +5,17 @@ #import -@interface SPTableContentFilterController : NSObject +@class SPSplitView; +@class SPTableData; +@class SPDatabaseDocument; +@class SPTablesList; + +@interface SPTableContentFilterController : NSObject { + IBOutlet SPSplitView *contentSplitView; + IBOutlet NSRuleEditor *filterRuleEditor; + IBOutlet SPTableData *tableDataInstance; + IBOutlet SPDatabaseDocument *tableDocumentInstance; + IBOutlet SPTablesList *tablesListInstance; +} @end diff --git a/Source/SPTableRelations.h b/Source/SPTableRelations.h index e1620007..4bb998c9 100644 --- a/Source/SPTableRelations.h +++ b/Source/SPTableRelations.h @@ -39,6 +39,7 @@ IBOutlet SPDatabaseDocument *tableDocumentInstance; IBOutlet SPTablesList *tablesListInstance; IBOutlet SPTableData *tableDataInstance; + IBOutlet SPTableView *tableList; IBOutlet NSButton *addRelationButton; IBOutlet NSButton *removeRelationButton; -- cgit v1.2.3 From c7362cc8c6d3c02d8e9b5f5a31735bb3fbbf0b02 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 26 Dec 2014 20:37:39 +0100 Subject: ************** IMPORTANT: SEE BELOW ************** MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This change should fix the "slow CSV import dialog" issue on 10.10 (details below). To accomplish that, some major changes had to be made to the CSV import code. PLEASE VERIFY THE CORRECTNESS OF THE NEXT FEW CSV IMPORTS YOU DO! * Renamed some variables for better search visibility * Changed some instances where NSNumbers were being compared using "==" instead of "isEqual…" (does not work with object literals!) * The CSV import dialog would recreate the popup menus on *every* call to "tableView:objectValueFor…". However Instruments suggests that [NSMenu removeAllItems] and [NSMenu addItemsWithTitles:] are **really** expensive, esp. when called multiple times per second (e.g. when scrolling in the table view). This commit moves the popup menu setup into its own method and only calls it when the data actually changes. * The 'destination table column' was for some reason a NSPopupButtonCell which only ever had one item and sometimes got changed to a NSTextFieldCell in code. I didn't see any need to keep the popup cell and replaced it with a simple text cell. --- Source/SPFieldMapperController.h | 9 +- Source/SPFieldMapperController.m | 234 +++++++++++++++++++++------------------ 2 files changed, 131 insertions(+), 112 deletions(-) (limited to 'Source') diff --git a/Source/SPFieldMapperController.h b/Source/SPFieldMapperController.h index a12adcb8..76b65c49 100644 --- a/Source/SPFieldMapperController.h +++ b/Source/SPFieldMapperController.h @@ -33,7 +33,7 @@ @class SPTablesList; @class SPMySQLConnection; -@interface SPFieldMapperController : NSWindowController +@interface SPFieldMapperController : NSWindowController { IBOutlet SPTableView *fieldMapperTableView; IBOutlet NSScrollView *fieldMapperTableScrollView; @@ -110,9 +110,9 @@ NSMutableArray *fieldMappingTableDefaultValues; NSMutableArray *defaultFieldTypesForComboBox; - NSNumber *doImport; - NSNumber *doNotImport; - NSNumber *isEqual; + NSNumber *doImportKey; + NSNumber *doNotImportKey; + NSNumber *isEqualKey; NSString *doImportString; NSString *doNotImportString; NSString *isEqualString; @@ -135,6 +135,7 @@ NSUInteger windowMinHeigth; NSInteger numberOfImportColumns; NSInteger fieldMappingCurrentRow; + NSInteger firstDefaultItemOffset; BOOL fieldMappingImportArrayIsPreview; BOOL importFieldNamesHeader; diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index a79c8a40..2fcf4c9e 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -53,6 +53,10 @@ static NSString *SPTableViewSqlColumnID = @"sql"; static NSUInteger SPSourceColumnTypeText = 0; static NSUInteger SPSourceColumnTypeInteger = 1; +@interface SPFieldMapperController (Private) +- (void)_setupFieldMappingPopUpMenus; +@end + @implementation SPFieldMapperController @synthesize sourcePath; @@ -85,9 +89,9 @@ static NSUInteger SPSourceColumnTypeInteger = 1; lastDisabledCSVFieldcolumn = @0; - doImport = @0; - doNotImport = @1; - isEqual = @2; + doImportKey = @0; + doNotImportKey = @1; + isEqualKey = @2; doImportString = @"―"; doNotImportString = @" "; isEqualString = @"="; @@ -215,20 +219,20 @@ static NSUInteger SPSourceColumnTypeInteger = 1; - (void)dealloc { - if (mySQLConnection) [mySQLConnection release]; - if (sourcePath) [sourcePath release]; - if (fieldMappingTableColumnNames) [fieldMappingTableColumnNames release]; - if (defaultFieldTypesForComboBox) [defaultFieldTypesForComboBox release]; - if (fieldMappingTableTypes) [fieldMappingTableTypes release]; - if (fieldMappingArray) [fieldMappingArray release]; - if (fieldMappingButtonOptions) [fieldMappingButtonOptions release]; - if (fieldMappingOperatorOptions) [fieldMappingOperatorOptions release]; - if (fieldMappingOperatorArray) [fieldMappingOperatorArray release]; - if (fieldMappingGlobalValues) [fieldMappingGlobalValues release]; - if (fieldMappingGlobalValuesSQLMarked) [fieldMappingGlobalValuesSQLMarked release]; - if (fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release]; - if (primaryKeyFields) [primaryKeyFields release]; - if (toBeEditedRowIndexes) [toBeEditedRowIndexes release]; + if (mySQLConnection) [mySQLConnection release], mySQLConnection = nil; + if (sourcePath) [sourcePath release], sourcePath = nil; + if (fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil; + if (defaultFieldTypesForComboBox) [defaultFieldTypesForComboBox release], defaultFieldTypesForComboBox = nil; + if (fieldMappingTableTypes) [fieldMappingTableTypes release], fieldMappingTableTypes = nil; + if (fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil; + if (fieldMappingButtonOptions) [fieldMappingButtonOptions release], fieldMappingButtonOptions = nil; + if (fieldMappingOperatorOptions) [fieldMappingOperatorOptions release], fieldMappingOperatorOptions = nil; + if (fieldMappingOperatorArray) [fieldMappingOperatorArray release], fieldMappingOperatorArray = nil; + if (fieldMappingGlobalValues) [fieldMappingGlobalValues release], fieldMappingGlobalValues = nil; + if (fieldMappingGlobalValuesSQLMarked) [fieldMappingGlobalValuesSQLMarked release], fieldMappingGlobalValuesSQLMarked = nil; + if (fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil; + if (primaryKeyFields) [primaryKeyFields release], primaryKeyFields = nil; + if (toBeEditedRowIndexes) [toBeEditedRowIndexes release], toBeEditedRowIndexes = nil; [super dealloc]; } @@ -309,7 +313,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; { NSInteger i = 0; for(id item in fieldMappingArray) { - if([item intValue] >= numberOfImportColumns && NSArrayObjectAtIndex(fieldMappingOperatorArray, i) != doNotImport) + if([item intValue] >= numberOfImportColumns && ![doNotImportKey isEqualToNumber:NSArrayObjectAtIndex(fieldMappingOperatorArray, i)]) return YES; i++; } @@ -455,7 +459,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; for(columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) { // Skip fields which aren't marked as imported - if ([fieldMappingOperatorArray objectAtIndex:columnIndex] != doImport) { + if (![doImportKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:columnIndex]]) { continue; } @@ -610,16 +614,16 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [self updateFieldMappingButtonCell]; [self updateFieldMappingOperatorOptions]; - // Set all operators to doNotImport + // Set all operators to doNotImportKey [fieldMappingOperatorArray removeAllObjects]; for(i=0; i < [fieldMappingTableColumnNames count]; i++) - [fieldMappingOperatorArray addObject:doNotImport]; + [fieldMappingOperatorArray addObject:doNotImportKey]; // Set the first n operators to doImport if([fieldMappingImportArray count]) { NSUInteger possibleImports = ([NSArrayObjectAtIndex(fieldMappingImportArray, 0) count] > [fieldMappingTableColumnNames count]) ? [fieldMappingTableColumnNames count] : [NSArrayObjectAtIndex(fieldMappingImportArray, 0) count]; for(i=0; i < possibleImports; i++) - [fieldMappingOperatorArray replaceObjectAtIndex:i withObject:doImport]; + [fieldMappingOperatorArray replaceObjectAtIndex:i withObject:doImportKey]; } // Disable Import button if no fields are available @@ -638,6 +642,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [self updateFieldNameAlignment]; + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; } @@ -686,12 +691,12 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [advancedBox setHidden:YES]; } - // If operator is set to = for UPDATE method replace it by doNotImport + // If operator is set to = for UPDATE method replace it by doNotImportKey if(![[importMethodPopup titleOfSelectedItem] isEqualToString:@"UPDATE"]) { [advancedButton setEnabled:YES]; for(i=0; i<[fieldMappingTableColumnNames count]; i++) { - if([fieldMappingOperatorArray objectAtIndex:i] == isEqual) { - [fieldMappingOperatorArray replaceObjectAtIndex:i withObject:doNotImport]; + if([isEqualKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:i]]) { + [fieldMappingOperatorArray replaceObjectAtIndex:i withObject:doNotImportKey]; } } } else { @@ -701,6 +706,8 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [self validateImportButton]; [self updateFieldMappingOperatorOptions]; + + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; } @@ -715,23 +722,23 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if(possibleImports < 1) return; - // Set all operators to doNotImport + // Set all operators to doNotImportKey [fieldMappingOperatorArray removeAllObjects]; for(i=0; i < [fieldMappingTableColumnNames count]; i++) - [fieldMappingOperatorArray addObject:doNotImport]; + [fieldMappingOperatorArray addObject:doNotImportKey]; switch([[alignByPopup selectedItem] tag]) { case 0: // file order for(j=0; j=0; j--) { [fieldMappingArray replaceObjectAtIndex:possibleImports-j withObject:[NSNumber numberWithInteger:j]]; - [fieldMappingOperatorArray replaceObjectAtIndex:possibleImports-j withObject:doImport]; + [fieldMappingOperatorArray replaceObjectAtIndex:possibleImports - j withObject:doImportKey]; } break; case 2: // try to align header and table target field names via Levenshtein distance @@ -914,11 +921,12 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [self updateFieldMappingButtonCell]; [self updateFieldMappingOperatorOptions]; - // Set all operators to doNotImport + // Set all operators to doNotImportKey [fieldMappingOperatorArray removeAllObjects]; for (i=0; i < [fieldMappingTableColumnNames count]; i++) - [fieldMappingOperatorArray addObject:doImport]; + [fieldMappingOperatorArray addObject:doImportKey]; + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; [self validateImportButton]; } @@ -929,7 +937,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; - (IBAction)addNewColumn:(id)sender { - [fieldMappingOperatorArray addObject:doNotImport]; + [fieldMappingOperatorArray addObject:doNotImportKey]; [fieldMappingTableColumnNames addObject:NSLocalizedString(@"New Column Name", @"new column name placeholder string")]; [fieldMappingTableTypes addObject:@"VARCHAR(255)"]; [fieldMappingTableDefaultValues addObject:@""]; @@ -939,6 +947,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [fieldMappingArray addObject:[NSNumber numberWithInteger:newIndex]]; [toBeEditedRowIndexes addIndex:newIndex]; + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; [fieldMapperTableView editColumn:2 row:newIndex withEvent:nil select:YES]; @@ -977,6 +986,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; currentIndex = [toBeEditedRowIndexes indexGreaterThanIndex:currentIndex]; } + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; } @@ -1175,9 +1185,9 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [fieldMappingArray replaceObjectAtIndex:[fieldMapperTableView selectedRow] withObject:[NSNumber numberWithInteger:[globalValuesTableView selectedRow]+numberOfImportColumns]]; - // Set corresponding operator to doImport if not set to isEqual - if([fieldMappingOperatorArray objectAtIndex:[fieldMapperTableView selectedRow]] != isEqual) - [fieldMappingOperatorArray replaceObjectAtIndex:[fieldMapperTableView selectedRow] withObject:doImport]; + // Set corresponding operator to doImport if not set to isEqualKey + if(![isEqualKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:[fieldMapperTableView selectedRow]]]) + [fieldMappingOperatorArray replaceObjectAtIndex:[fieldMapperTableView selectedRow] withObject:doImportKey]; [fieldMapperTableView reloadData]; @@ -1444,7 +1454,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // Set best match [fieldMappingArray replaceObjectAtIndex:match.location withObject:[NSNumber numberWithInteger:match.length]]; - [fieldMappingOperatorArray replaceObjectAtIndex:match.location withObject:doImport]; + [fieldMappingOperatorArray replaceObjectAtIndex:match.location withObject:doImportKey]; // Remember matched pair [matchedTable addObject:[m objectForKey:@"table"]]; @@ -1508,6 +1518,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [fieldMappingButtonOptions addObject:[NSString stringWithFormat:@"%li. %@", (long)i+1, NSArrayObjectAtIndex(fieldMappingGlobalValues, i)]]; } + [self _setupFieldMappingPopUpMenus]; [fieldMapperTableView reloadData]; } @@ -1562,7 +1573,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; return; } for (NSUInteger i = 0; i < [fieldMappingTableColumnNames count]; i++) { - if (![[fieldMappingTableColumnNames objectAtIndex:i] length] && [fieldMappingOperatorArray objectAtIndex:i] == doImport) { + if (![[fieldMappingTableColumnNames objectAtIndex:i] length] && [doImportKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:i]]) { [importButton setEnabled:NO]; return; } @@ -1578,7 +1589,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if ([[self selectedImportMethod] isEqualToString:@"UPDATE"]) { enableImportButton = NO; for(id op in fieldMappingOperatorArray) { - if(op == isEqual) { + if([isEqualKey isEqualToNumber:op]) { enableImportButton = YES; break; } @@ -1654,9 +1665,9 @@ static NSUInteger SPSourceColumnTypeInteger = 1; && [fieldMappingOperatorArray count] && [fieldMappingTableColumnNames count]) { NSUInteger i; - NSNumber *globalValue = doImport; - if([fieldMappingOperatorArray objectAtIndex:0] == doImport) - globalValue = doNotImport; + NSNumber *globalValue = doImportKey; + if([doImportKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:0]]) + globalValue = doNotImportKey; [fieldMappingOperatorArray removeAllObjects]; for(i=0; i < [fieldMappingTableColumnNames count]; i++) [fieldMappingOperatorArray addObject:globalValue]; @@ -1671,7 +1682,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if(aTableView == fieldMapperTableView) { - if ([fieldMappingOperatorArray objectAtIndex:rowIndex] == doNotImport) return [NSString stringWithFormat:@"DEFAULT: %@", [fieldMappingTableDefaultValues objectAtIndex:rowIndex]]; + if ([doNotImportKey isEqual:[fieldMappingOperatorArray objectAtIndex:rowIndex]]) return [NSString stringWithFormat:@"DEFAULT: %@", [fieldMappingTableDefaultValues objectAtIndex:rowIndex]]; if([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID] && [importFieldNamesHeaderSwitch state] == NSOnState) { @@ -1695,11 +1706,11 @@ static NSUInteger SPSourceColumnTypeInteger = 1; } else if([[aTableColumn identifier] isEqualToString:SPTableViewOperatorColumnID]) { - if([aCell objectValue] == doImport) + if([doImportKey isEqual:[aCell objectValue]]) return NSLocalizedString(@"Import field", @"import field operator tooltip"); - else if([aCell objectValue] == doNotImport) + else if([doNotImportKey isEqual:[aCell objectValue]]) return NSLocalizedString(@"Ignore field", @"ignore field label"); - else if([aCell objectValue] == isEqual) + else if([isEqualKey isEqual:[aCell objectValue]]) return NSLocalizedString(@"Do UPDATE where field contents match", @"do update operator tooltip"); else return @""; @@ -1715,32 +1726,64 @@ static NSUInteger SPSourceColumnTypeInteger = 1; return @""; } +- (void)menuNeedsUpdate:(NSMenu *)aMenu +{ + // Note: matching aMenu with "==" will most likely not work, as NSTableView copies it. + // This technique is based on: http://www.corbinstreehouse.com/blog/2005/07/dynamically-populating-an-nspopupbuttoncell-in-an-nstableview/ + + NSInteger rowIndex = [fieldMapperTableView selectedRow]; + if(rowIndex < 0) + return; + + NSInteger rowIndexInMenu = firstDefaultItemOffset + rowIndex; + for (NSInteger i = firstDefaultItemOffset; i < [aMenu numberOfItems]; i++) { + [[aMenu itemAtIndex:i] setHidden:(i != rowIndexInMenu)]; + } +} + +- (void)_setupFieldMappingPopUpMenus +{ + NSPopUpButtonCell *c = [[fieldMapperTableView tableColumnWithIdentifier:SPTableViewImportValueColumnID] dataCell]; + NSMenu *m = [c menu]; + [m setAutoenablesItems:NO]; + [c removeAllItems]; + [c addItemsWithTitles:fieldMappingButtonOptions]; + + [m addItem:[NSMenuItem separatorItem]]; + + [c addItemWithTitle:NSLocalizedString(@"Ignore Field", @"ignore field label")]; + [c addItemWithTitle:NSLocalizedString(@"Ignore all Fields", @"ignore all fields menu item")]; + [c addItemWithTitle:NSLocalizedString(@"Import all Fields", @"import all fields menu item")]; + if([[self selectedImportMethod] isEqualToString:@"UPDATE"]) + [c addItemWithTitle:NSLocalizedString(@"Match Field", @"match field menu item")]; + + [m addItem:[NSMenuItem separatorItem]]; + + NSMenuItem *menuItem = [m addItemWithTitle:NSLocalizedString(@"Add Value or Expression…", @"add global value or expression menu item") action:@selector(addGlobalSourceVariable:) keyEquivalent:@"g"]; + [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; + + //create all menu items for the "DEFAULT" rows. We will use menuNeedsUpdate: to hide all items that are not needed. + //This works because NSTableView will copy the menu before showing it, so menuNeedsUpdate: will work on a disposable copy + //while the full menu is never shown (but it's items are displayed in the table view) + firstDefaultItemOffset = [m numberOfItems]; + for (id item in fieldMappingTableDefaultValues) { + NSString *label = [NSString stringWithFormat:NSLocalizedString(@"Default: %@",@"import : csv field mapping : field default value"), item]; + NSMenuItem *defaultItem = [m addItemWithTitle:label action:NULL keyEquivalent:@""]; + [defaultItem setEnabled:NO]; + } + + NSPopUpButtonCell *optsCell = [[fieldMapperTableView tableColumnWithIdentifier:SPTableViewOperatorColumnID] dataCell]; + [optsCell removeAllItems]; + [optsCell addItemsWithTitles:fieldMappingOperatorOptions]; +} + - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex { if(aTableView == fieldMapperTableView) { if ([[aTableColumn identifier] isEqualToString:SPTableViewTargetFieldColumnID]) { - if([toBeEditedRowIndexes containsIndex:rowIndex]) { - NSTextFieldCell *b = [[[NSTextFieldCell alloc] initTextCell:[fieldMappingTableColumnNames objectAtIndex:rowIndex]] autorelease]; - [b setEditable:YES]; - [b setFont:[NSFont systemFontOfSize:12]]; - [aTableColumn setDataCell:b]; - return b; - } - if(newTableMode) { - NSTextFieldCell *b = [[[NSTextFieldCell alloc] initTextCell:[fieldMappingTableColumnNames objectAtIndex:rowIndex]] autorelease]; - [b setEditable:YES]; - [b setFont:[NSFont systemFontOfSize:12]]; - [aTableColumn setDataCell:b]; - return b; - } else { - if ([[aTableColumn dataCell] isKindOfClass:[NSPopUpButtonCell class]]) { - [(NSPopUpButton *)[aTableColumn dataCell] removeAllItems]; - [(NSPopUpButtonCell *)[aTableColumn dataCell] addItemWithTitle:[fieldMappingTableColumnNames objectAtIndex:rowIndex]]; - } - return [fieldMappingTableColumnNames objectAtIndex:rowIndex]; - } + return [fieldMappingTableColumnNames objectAtIndex:rowIndex]; } else if ([[aTableColumn identifier] isEqualToString:SPTableViewTypeColumnID]) { @@ -1765,45 +1808,20 @@ static NSUInteger SPSourceColumnTypeInteger = 1; else if ([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID]) { - // Check if all global value was deleted, if so set assigned field as doNotImport + // Check if all global value was deleted, if so set assigned field as doNotImportKey if([[fieldMappingArray objectAtIndex:rowIndex] unsignedIntegerValue] >= [fieldMappingButtonOptions count]) { - [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doNotImport]; + [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doNotImportKey]; } - if ([[aTableColumn dataCell] isKindOfClass:[NSPopUpButtonCell class]]) { - - NSPopUpButtonCell *c = [aTableColumn dataCell]; - NSMenu *m = [c menu]; - [m setAutoenablesItems:NO]; - [c removeAllItems]; - [c addItemsWithTitles:fieldMappingButtonOptions]; - [m addItem:[NSMenuItem separatorItem]]; - [c addItemWithTitle:NSLocalizedString(@"Ignore Field", @"ignore field label")]; - [c addItemWithTitle:NSLocalizedString(@"Ignore all Fields", @"ignore all fields menu item")]; - [c addItemWithTitle:NSLocalizedString(@"Import all Fields", @"import all fields menu item")]; - if([[self selectedImportMethod] isEqualToString:@"UPDATE"]) - [c addItemWithTitle:NSLocalizedString(@"Match Field", @"match field menu item")]; - [m addItem:[NSMenuItem separatorItem]]; - NSMenuItem *menuItem = [m addItemWithTitle:NSLocalizedString(@"Add Value or Expression…", @"add global value or expression menu item") action:@selector(addGlobalSourceVariable:) keyEquivalent:@"g"]; - [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; - [c addItemWithTitle:[NSString stringWithFormat:@"DEFAULT: %@", [fieldMappingTableDefaultValues objectAtIndex:rowIndex]]]; - [[m itemAtIndex:[c numberOfItems]-1] setEnabled:NO]; - - // If user doesn't want to import it show its DEFAULT value if not - // UPDATE was chosen otherwise hide it. - if([fieldMappingOperatorArray objectAtIndex:rowIndex] != doNotImport) - return [fieldMappingArray objectAtIndex:rowIndex]; - else if(![[self selectedImportMethod] isEqualToString:@"UPDATE"]) - return [NSNumber numberWithInteger:[c numberOfItems]-1]; - - } + // If user doesn't want to import it show its DEFAULT value if not + // UPDATE was chosen otherwise hide it. + if(![doNotImportKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:rowIndex]]) + return [fieldMappingArray objectAtIndex:rowIndex]; + else if(![[self selectedImportMethod] isEqualToString:@"UPDATE"]) + return [NSNumber numberWithInteger:firstDefaultItemOffset+rowIndex]; } else if ([[aTableColumn identifier] isEqualToString:SPTableViewOperatorColumnID]) { - if ([[aTableColumn dataCell] isKindOfClass:[NSPopUpButtonCell class]]) { - [(NSPopUpButtonCell *)[aTableColumn dataCell] removeAllItems]; - [(NSPopUpButtonCell *)[aTableColumn dataCell] addItemsWithTitles:fieldMappingOperatorOptions]; - } return [fieldMappingOperatorArray objectAtIndex:rowIndex]; } } @@ -1845,16 +1863,16 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if(aTableView == fieldMapperTableView) { if ([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID]) { if([anObject integerValue] > (NSInteger)[fieldMappingButtonOptions count]) { - // Ignore field - set operator to doNotImport + // Ignore field - set operator to doNotImportKey if([anObject integerValue] == (NSInteger)[fieldMappingButtonOptions count]+1) { lastDisabledCSVFieldcolumn = [fieldMappingArray objectAtIndex:rowIndex]; - [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doNotImport]; + [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doNotImportKey]; [aTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; } - // Ignore all field - set all operator to doNotImport + // Ignore all field - set all operator to doNotImportKey else if([anObject integerValue] == (NSInteger)[fieldMappingButtonOptions count]+2) { NSUInteger i; - NSNumber *globalValue = doNotImport; + NSNumber *globalValue = doNotImportKey; [fieldMappingOperatorArray removeAllObjects]; for(i=0; i < [fieldMappingTableColumnNames count]; i++) [fieldMappingOperatorArray addObject:globalValue]; @@ -1863,14 +1881,14 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // Import all field - set all operator to doImport else if([anObject integerValue] == (NSInteger)[fieldMappingButtonOptions count]+3) { NSUInteger i; - NSNumber *globalValue = doImport; + NSNumber *globalValue = doImportKey; [fieldMappingOperatorArray removeAllObjects]; for(i=0; i < [fieldMappingTableColumnNames count]; i++) [fieldMappingOperatorArray addObject:globalValue]; [aTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; } else if([[self selectedImportMethod] isEqualToString:@"UPDATE"] && [anObject integerValue] == (NSInteger)[fieldMappingButtonOptions count]+4) { - [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:isEqual]; + [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:isEqualKey]; [aTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; } // Add global value @@ -1890,8 +1908,8 @@ static NSUInteger SPSourceColumnTypeInteger = 1; [fieldMappingArray replaceObjectAtIndex:rowIndex withObject:anObject]; // If user _changed_ the csv file column set the operator to doImport if not set to = - if([(NSNumber*)anObject integerValue] > -1 && NSArrayObjectAtIndex(fieldMappingOperatorArray, rowIndex) != isEqual) - [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doImport]; + if([(NSNumber*)anObject integerValue] > -1 && ![isEqualKey isEqualToNumber:NSArrayObjectAtIndex(fieldMappingOperatorArray, rowIndex)]) + [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:doImportKey]; [self validateImportButton]; @@ -1918,11 +1936,11 @@ static NSUInteger SPSourceColumnTypeInteger = 1; } else if ([[aTableColumn identifier] isEqualToString:SPTableViewOperatorColumnID]) { - if([fieldMappingOperatorArray objectAtIndex:rowIndex] == doNotImport) { + if([doNotImportKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:rowIndex]]) { [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:anObject]; [fieldMappingArray replaceObjectAtIndex:rowIndex withObject:lastDisabledCSVFieldcolumn]; } else { - if(anObject == doNotImport) lastDisabledCSVFieldcolumn = [fieldMappingArray objectAtIndex:rowIndex]; + if([doNotImportKey isEqual:anObject]) lastDisabledCSVFieldcolumn = [fieldMappingArray objectAtIndex:rowIndex]; [fieldMappingOperatorArray replaceObjectAtIndex:rowIndex withObject:anObject]; } [self validateImportButton]; -- cgit v1.2.3 From 19226617658f7452d8f02a68c52556aca6810c36 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 26 Dec 2014 22:54:24 +0100 Subject: Fix two minor CSV import dialog issues * Tooltips were somewhat broken for non-imported fields (issue exists in 1.0.2) * Newly added expressions would cause the field to switch to "do not import" instead of the added expression --- Source/SPFieldMapperController.m | 46 +++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 22 deletions(-) (limited to 'Source') diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index 2fcf4c9e..418a255f 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -1189,13 +1189,15 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if(![isEqualKey isEqualToNumber:[fieldMappingOperatorArray objectAtIndex:[fieldMapperTableView selectedRow]]]) [fieldMappingOperatorArray replaceObjectAtIndex:[fieldMapperTableView selectedRow] withObject:doImportKey]; - [fieldMapperTableView reloadData]; - // Set alignment popup to "custom order" [alignByPopup selectItemWithTag:3]; } + // This must happen before orderOut:nil as that might cause the tableview to redraw which would in turn invalidate + // a newly added globalValue when updateFieldMappingButtonCell has not been run before. + [self updateFieldMappingButtonCell]; + [NSApp endSheet:globalValuesSheet returnCode:[sender tag]]; } @@ -1378,7 +1380,6 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if (sheet == globalValuesSheet) { addGlobalSheetIsOpen = NO; - [self updateFieldMappingButtonCell]; } } @@ -1682,27 +1683,29 @@ static NSUInteger SPSourceColumnTypeInteger = 1; if(aTableView == fieldMapperTableView) { - if ([doNotImportKey isEqual:[fieldMappingOperatorArray objectAtIndex:rowIndex]]) return [NSString stringWithFormat:@"DEFAULT: %@", [fieldMappingTableDefaultValues objectAtIndex:rowIndex]]; + if([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID]) { - if([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID] && [importFieldNamesHeaderSwitch state] == NSOnState) { + if ([doNotImportKey isEqual:[fieldMappingOperatorArray objectAtIndex:rowIndex]]) return [NSString stringWithFormat:@"DEFAULT: %@", [fieldMappingTableDefaultValues objectAtIndex:rowIndex]]; - if([NSArrayObjectAtIndex(fieldMappingArray, rowIndex) unsignedIntegerValue]>=[NSArrayObjectAtIndex(fieldMappingImportArray, 0) count]) - return [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"User-defined value", @"user-defined value"), NSArrayObjectAtIndex(fieldMappingGlobalValues, [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue])]; + if([importFieldNamesHeaderSwitch state] == NSOnState) { + if([NSArrayObjectAtIndex(fieldMappingArray, rowIndex) unsignedIntegerValue]>=[NSArrayObjectAtIndex(fieldMappingImportArray, 0) count]) + return [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"User-defined value", @"user-defined value"), NSArrayObjectAtIndex(fieldMappingGlobalValues, [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue])]; - if(fieldMappingCurrentRow) - return [NSString stringWithFormat:@"%@: %@", - [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, 0), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description], - [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, fieldMappingCurrentRow), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description]]; - else - return [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, 0), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description]; + if(fieldMappingCurrentRow) + return [NSString stringWithFormat:@"%@: %@", + [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, 0), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description], + [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, fieldMappingCurrentRow), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description]]; + else + return [NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, 0), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]) description]; - } + } + else if([importFieldNamesHeaderSwitch state] == NSOffState) { + if([NSArrayObjectAtIndex(fieldMappingArray, rowIndex) unsignedIntegerValue]>=[NSArrayObjectAtIndex(fieldMappingImportArray, 0) count]) + return NSArrayObjectAtIndex(fieldMappingGlobalValues, [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]); + else + return NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, fieldMappingCurrentRow), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]); - else if([[aTableColumn identifier] isEqualToString:SPTableViewImportValueColumnID] && [importFieldNamesHeaderSwitch state] == NSOffState) { - if([NSArrayObjectAtIndex(fieldMappingArray, rowIndex) unsignedIntegerValue]>=[NSArrayObjectAtIndex(fieldMappingImportArray, 0) count]) - return NSArrayObjectAtIndex(fieldMappingGlobalValues, [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]); - else - return NSArrayObjectAtIndex(NSArrayObjectAtIndex(fieldMappingImportArray, fieldMappingCurrentRow), [NSArrayObjectAtIndex(fieldMappingArray, rowIndex) integerValue]); + } } else if([[aTableColumn identifier] isEqualToString:SPTableViewOperatorColumnID]) { @@ -1712,12 +1715,11 @@ static NSUInteger SPSourceColumnTypeInteger = 1; return NSLocalizedString(@"Ignore field", @"ignore field label"); else if([isEqualKey isEqual:[aCell objectValue]]) return NSLocalizedString(@"Do UPDATE where field contents match", @"do update operator tooltip"); - else - return @""; } - else if([[aTableColumn identifier] isEqualToString:SPTableViewTargetFieldColumnID]) + else if([[aTableColumn identifier] isEqualToString:SPTableViewTargetFieldColumnID]) { return [fieldMappingTableColumnNames objectAtIndex:rowIndex]; + } } else if(aTableView == globalValuesTableView) { if ([[aTableColumn identifier] isEqualToString:SPTableViewGlobalValueColumnID]) -- cgit v1.2.3 From ae8a9465306eaee5bb1478b74057e1bdf540b1db Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 30 Dec 2014 02:29:26 +0100 Subject: =?UTF-8?q?+[NSThread=20detachNewThreadWithName:=E2=80=A6]=20chang?= =?UTF-8?q?es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The method never did the one extra thing it should do, because… see comment in the code. Let's see how this works out :) --- Source/SPThreadAdditions.m | 60 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPThreadAdditions.m b/Source/SPThreadAdditions.m index c1f0a52b..74476888 100644 --- a/Source/SPThreadAdditions.m +++ b/Source/SPThreadAdditions.m @@ -29,17 +29,69 @@ // More info at #import "SPThreadAdditions.h" +#import + +//this is a "private" class only needed by the +detachNewThreadWithName:… method below. +@interface SPNamedThread : NSObject { + @private + NSString *name; + id object; + SEL selector; +} +- (id)initWithTarget:(id)aObject selector:(SEL)aSelector name:(NSString *)aName; +- (void)run:(id)argument; +@end @implementation NSThread (SPThreadAdditions) + (void)detachNewThreadWithName:(NSString *)aName target:(id)aTarget selector:(SEL)aSelector object:(id)anArgument { - NSThread *newThread = [[NSThread alloc] initWithTarget:aTarget selector:aSelector object:anArgument]; - if (aName) { - [newThread setName:aName]; - } + // -[NSThread setName:] has two limitations when it comes to visibility in Xcode: + // a) Xcode only updates the thread name in UI once (on the first time the thread is shown in the debugger). + // b) Internally this method calls + // int pthread_setname_np(const char*); + // which, as can be seen, does not allow to specify a thread id. Therefore it is skipped if . + // Unfortunately this (and not the property of the NSThread) seems to be the actual name shown in Xcode. + // The consequence is, we can only set a thread's name from within the thread, so let's add a proxy object to do that. + SPNamedThread *namedThread = [[SPNamedThread alloc] initWithTarget:aTarget selector:aSelector name:aName]; + + NSThread *newThread = [[NSThread alloc] initWithTarget:namedThread selector:@selector(run:) object:anArgument]; [newThread start]; [newThread autorelease]; + [namedThread autorelease]; +} + +@end + +#pragma mark - + +@implementation SPNamedThread + +- (id)initWithTarget:(id)aObject selector:(SEL)aSelector name:(NSString *)aName +{ + if(self = [super init]) { + name = [aName copy]; + object = [aObject retain]; + selector = aSelector; + } + return self; +} + +- (void)run:(id)argument +{ + [[NSThread currentThread] setName:name]; + + void (*msgsend)(id, SEL, id) = (void (*)(id, SEL, id)) objc_msgSend; //hint for the compiler + + msgsend(object,selector,argument); +} + +- (void)dealloc +{ + [object release], object = nil; + selector = NULL; + [name release], name = nil; + [super dealloc]; } @end -- cgit v1.2.3 From 2d8fd9c8eff0afca2cab9b8bbb791a0cdf1c583a Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 30 Dec 2014 02:30:30 +0100 Subject: Fix a minor case of "bg thread updating UI" --- Source/SPCustomQuery.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 216cafa8..8b201776 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -916,7 +916,7 @@ return; } - [customQueryView reloadData]; + [[customQueryView onMainThread] reloadData]; // Restore the result view origin if appropriate if (!NSEqualRects(selectionViewportToRestore, NSZeroRect)) { -- cgit v1.2.3 From f12b95bb7b3dda011dea4bb3e0edff1428a38209 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 31 Dec 2014 03:00:10 +0100 Subject: Remove some duplicate code by adding abstraction --- Source/SPEditorPreferencePane.m | 8 ++++++++ Source/SPPreferenceController.h | 2 -- Source/SPPreferenceController.m | 39 ++++----------------------------------- Source/SPPreferencePane.h | 2 +- Source/SPPreferencePane.m | 5 +++++ Source/SPPreferencePaneProtocol.h | 5 +++++ Source/SPTablesPreferencePane.m | 5 +++++ 7 files changed, 28 insertions(+), 38 deletions(-) (limited to 'Source') diff --git a/Source/SPEditorPreferencePane.m b/Source/SPEditorPreferencePane.m index d5127e65..08a833c2 100644 --- a/Source/SPEditorPreferencePane.m +++ b/Source/SPEditorPreferencePane.m @@ -732,6 +732,14 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; return NO; } +- (void)preferencePaneWillBeShown +{ + [self updateColorSchemeSelectionMenu]; + [self updateDisplayColorThemeName]; + + [self updateDisplayedEditorFontName]; +} + #pragma mark - #pragma mark Private API diff --git a/Source/SPPreferenceController.h b/Source/SPPreferenceController.h index a001b60c..c34f8542 100644 --- a/Source/SPPreferenceController.h +++ b/Source/SPPreferenceController.h @@ -84,8 +84,6 @@ // Toolbar item IBAction methods - (IBAction)displayPreferencePane:(id)sender; -- (IBAction)displayTablePreferences:(id)sender; -- (IBAction)displayEditorPreferences:(id)sender; - (void)changeFont:(id)sender; diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m index 3a67ae80..d28dfcb9 100644 --- a/Source/SPPreferenceController.m +++ b/Source/SPPreferenceController.m @@ -105,40 +105,9 @@ [toolbar setSelectedItemIdentifier:[preferencePane preferencePaneIdentifier]]; - [self _resizeWindowForContentView:[preferencePane preferencePaneView]]; -} - -/** - * Displays the table preferences pane. - */ -- (IBAction)displayTablePreferences:(id)sender -{ - [[self window] setMinSize:NSMakeSize(0, 0)]; - [[self window] setShowsResizeIndicator:[tablesPreferencePane preferencePaneAllowsResizing]]; - - [toolbar setSelectedItemIdentifier:[tablesPreferencePane preferencePaneIdentifier]]; - - [(SPTablesPreferencePane *)tablesPreferencePane updateDisplayedTableFontName]; - - [self _resizeWindowForContentView:[tablesPreferencePane preferencePaneView]]; -} - -/** - * Displays the editor preferences pane. - */ -- (IBAction)displayEditorPreferences:(id)sender -{ - [(SPEditorPreferencePane *)editorPreferencePane updateColorSchemeSelectionMenu]; - [(SPEditorPreferencePane *)editorPreferencePane updateDisplayColorThemeName]; + [preferencePane preferencePaneWillBeShown]; - [[self window] setMinSize:NSMakeSize(0, 0)]; - [[self window] setShowsResizeIndicator:[editorPreferencePane preferencePaneAllowsResizing]]; - - [toolbar setSelectedItemIdentifier:[editorPreferencePane preferencePaneIdentifier]]; - - [(SPEditorPreferencePane *)editorPreferencePane updateDisplayedEditorFontName]; - - [self _resizeWindowForContentView:[editorPreferencePane preferencePaneView]]; + [self _resizeWindowForContentView:[preferencePane preferencePaneView]]; } #pragma mark - @@ -198,7 +167,7 @@ [tablesItem setLabel:[tablesPreferencePane preferencePaneName]]; [tablesItem setImage:[tablesPreferencePane preferencePaneIcon]]; [tablesItem setTarget:self]; - [tablesItem setAction:@selector(displayTablePreferences:)]; + [tablesItem setAction:@selector(displayPreferencePane:)]; // Notification preferences notificationsItem = [[NSToolbarItem alloc] initWithItemIdentifier:[notificationsPreferencePane preferencePaneIdentifier]]; @@ -214,7 +183,7 @@ [editorItem setLabel:[editorPreferencePane preferencePaneName]]; [editorItem setImage:[editorPreferencePane preferencePaneIcon]]; [editorItem setTarget:self]; - [editorItem setAction:@selector(displayEditorPreferences:)]; + [editorItem setAction:@selector(displayPreferencePane:)]; // AutoUpdate preferences autoUpdateItem = [[NSToolbarItem alloc] initWithItemIdentifier:[autoUpdatePreferencePane preferencePaneIdentifier]]; diff --git a/Source/SPPreferencePane.h b/Source/SPPreferencePane.h index 39d239c8..19e0436b 100644 --- a/Source/SPPreferencePane.h +++ b/Source/SPPreferencePane.h @@ -42,5 +42,5 @@ { NSUserDefaults *prefs; } - +- (void)preferencePaneWillBeShown; @end diff --git a/Source/SPPreferencePane.m b/Source/SPPreferencePane.m index a1b85ed7..39a870c7 100644 --- a/Source/SPPreferencePane.m +++ b/Source/SPPreferencePane.m @@ -47,4 +47,9 @@ return self; } +- (void)preferencePaneWillBeShown +{ + // Default: do nothing. Override in subclass. +} + @end diff --git a/Source/SPPreferencePaneProtocol.h b/Source/SPPreferencePaneProtocol.h index a9d67598..e00e12ec 100644 --- a/Source/SPPreferencePaneProtocol.h +++ b/Source/SPPreferencePaneProtocol.h @@ -79,4 +79,9 @@ */ - (BOOL)preferencePaneAllowsResizing; +/** + * Called shortly before the preference pane will be made visible + */ +- (void)preferencePaneWillBeShown; + @end diff --git a/Source/SPTablesPreferencePane.m b/Source/SPTablesPreferencePane.m index 5c55af94..f89849ec 100644 --- a/Source/SPTablesPreferencePane.m +++ b/Source/SPTablesPreferencePane.m @@ -93,4 +93,9 @@ return NO; } +- (void)preferencePaneWillBeShown +{ + [self updateDisplayedTableFontName]; +} + @end -- cgit v1.2.3 From 918324e27b6b4753307fa6a8166b3d7227f97b35 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 31 Dec 2014 05:36:48 +0100 Subject: Change how Growl status is displayed in prefs The current status of Growl/Notification center will now be shown as a label beneath the "Enable notifications" checkbox. --- Source/SPNotificationsPreferencePane.h | 3 ++ Source/SPNotificationsPreferencePane.m | 81 ++++++++++++++++++++++++++++++---- 2 files changed, 75 insertions(+), 9 deletions(-) (limited to 'Source') diff --git a/Source/SPNotificationsPreferencePane.h b/Source/SPNotificationsPreferencePane.h index e9650928..cf0f4c42 100644 --- a/Source/SPNotificationsPreferencePane.h +++ b/Source/SPNotificationsPreferencePane.h @@ -38,5 +38,8 @@ * Notifications preference pane controller. */ @interface SPNotificationsPreferencePane : SPPreferencePane +{ + IBOutlet NSTextField *growlStatusLabel; +} @end diff --git a/Source/SPNotificationsPreferencePane.m b/Source/SPNotificationsPreferencePane.m index dcd713e2..3c64a1ff 100644 --- a/Source/SPNotificationsPreferencePane.m +++ b/Source/SPNotificationsPreferencePane.m @@ -29,23 +29,66 @@ // More info at #import "SPNotificationsPreferencePane.h" +#import +#import "SPGrowlController.h" + +static NSString *_runningApplicationsKeyPath = @"runningApplications"; @implementation SPNotificationsPreferencePane +- (instancetype)init +{ + self = [super init]; + if (self) { + // this notification is posted by the GrowlApplicationBridge right after + // it would have called -[delegate growlIsReady], so we'll just use this + // as a shortcut. + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(growlLaunchedNotifcation:) + name:GROWL_IS_READY + object:nil]; + // we need to initialize the GrowlApplicationBridge for the notification to actually work + [SPGrowlController sharedGrowlController]; + // Growl doesn't tell use when it exits (even though they DO monitor it). + // This code replicates what it does internally. + [[NSWorkspace sharedWorkspace] addObserver:self + forKeyPath:_runningApplicationsKeyPath + options:NSKeyValueObservingOptionNew + context:nil]; + // TODO: we are only really interested in this notification while we are visible. + } + return self; +} + +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + //check if growl has exited + if(object == [NSWorkspace sharedWorkspace] && [keyPath isEqualToString:_runningApplicationsKeyPath]){ + [self updateGrowlStatusLabel]; + } +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [[NSWorkspace sharedWorkspace] removeObserver:self forKeyPath:_runningApplicationsKeyPath]; + [super dealloc]; +} + +- (void)growlLaunchedNotifcation:(NSNotification *)notification +{ + [self updateGrowlStatusLabel]; +} + +- (void)preferencePaneWillBeShown +{ + [self updateGrowlStatusLabel]; +} + #pragma mark - #pragma mark Bindings -/** - * Displays an informational message regarding Growl notifications if enabled. - */ - (void)setGrowlEnabled:(BOOL)value { - if (value) { - NSBeginInformationalAlertSheet(NSLocalizedString(@"Growl notification preferences", "Growl notification preferences alert title"), - nil, nil, nil, [[self view] window], self, nil, nil, nil, - NSLocalizedString(@"All Growl notifications are enabled by default. To change which notifications are displayed, go to the Growl Preference Pane in the System Preferences and choose what notifications Growl should display from Sequel Pro.", @"Growl notification preferences alert message")); - } - [prefs setBool:value forKey:SPGrowlEnabled]; } @@ -57,6 +100,26 @@ return [prefs boolForKey:SPGrowlEnabled]; } +- (void)updateGrowlStatusLabel +{ + NSString *text; + if([GrowlApplicationBridge isGrowlRunning]) { + text = NSLocalizedString(@"Growl will be used for sending notifications.\nAdvanced settings can be configured via Growl.",@"Preferences : Notifications : growl status text : growl installed and running"); + } + else { + text = @""; + + if(NSClassFromString(@"NSUserNotificationCenter")) { //this is what growl does + //10.8+ + text = NSLocalizedString(@"Notification Center will be used for sending notifications. ",@"Preferences : Notifications : growl status text : growl not installed, Apple's Notificiation Center is used instead. (KEEP the SPACE at the end)"); + } + //else case would be embedded growl ("Mist", 10.6 - 10.7), but telling that would IMHO be more confusing for the user. + + text = [text stringByAppendingString:NSLocalizedString(@"Install Growl for advanced control over notifications.",@"Preferences : Notifications : growl status text : additional hint when embedded Growl ('Mist') or Notification Center is used.")]; + } + [growlStatusLabel setStringValue:text]; +} + #pragma mark - #pragma mark Preference pane protocol methods -- cgit v1.2.3 From ee588049b5a7f755d788b983dc8cabce24453641 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 2 Jan 2015 16:08:19 +0100 Subject: =?UTF-8?q?*=20Fix=20broken=20import=20on=2010.6=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (Import would not work on a new installation where a certain preference key has not yet been set) * Also attached the gear menu in table structure view to the table header view, so the columns to show can now be selected by right-clicking on the table header (like in Activity Monitor) --- Source/SPDataImport.m | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index 5859b75d..f1208a54 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -288,7 +288,12 @@ [openPanel setNameFieldStringValue:[lastFilename lastPathComponent]]; } - [openPanel setDirectoryURL:[NSURL URLWithString:[prefs objectForKey:@"openPath"]]]; + NSString *openPath; + if((openPath = [prefs objectForKey:@"openPath"])) { + // Doc says calling +[NSURL URLWithString:] with nil is fine, + // but at least on 10.6 this will cause an exception + [openPanel setDirectoryURL:[NSURL URLWithString:openPath]]; + } [openPanel beginSheetModalForWindow:[tableDocumentInstance parentWindow] completionHandler:^(NSInteger returnCode) { // Ensure text inputs are completed, preventing dead character entry -- cgit v1.2.3 From 30ffc7c4d6158e1210b2463dddb62e627ca410db Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 2 Jan 2015 16:17:22 +0100 Subject: Some internal addtions for mysql event support (Also deduplicated some code) --- Source/SPConstants.h | 3 ++- Source/SPServerSupport.h | 8 ++++++++ Source/SPServerSupport.m | 5 +++++ Source/SPTablesList.h | 1 + Source/SPTablesList.m | 41 ++++++++++++++++------------------------- 5 files changed, 32 insertions(+), 26 deletions(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 60787559..415fd4da 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -103,7 +103,8 @@ typedef enum SPTableTypeTable = 0, SPTableTypeView = 1, SPTableTypeProc = 2, - SPTableTypeFunc = 3 + SPTableTypeFunc = 3, + SPTableTypeEvent = 4 } SPTableType; // History views diff --git a/Source/SPServerSupport.h b/Source/SPServerSupport.h index 55b8a6ad..e8b8a613 100644 --- a/Source/SPServerSupport.h +++ b/Source/SPServerSupport.h @@ -85,6 +85,9 @@ // Indexes BOOL supportsIndexKeyBlockSize; + + // Events + BOOL supportsEvents; // Data types BOOL supportsFractionalSeconds; @@ -229,6 +232,11 @@ */ @property (readonly) BOOL supportsTriggers; +/** +* @property supportsEvents Indicates if the server supports scheduled events +*/ +@property (readonly) BOOL supportsEvents; + /** * @property supportsIndexKeyBlockSize Indicates if the server supports specifying an index's key block size */ diff --git a/Source/SPServerSupport.m b/Source/SPServerSupport.m index 991a9fd3..bf74a61e 100644 --- a/Source/SPServerSupport.m +++ b/Source/SPServerSupport.m @@ -69,6 +69,7 @@ @synthesize supportsArchiveStorageEngine; @synthesize supportsCSVStorageEngine; @synthesize supportsTriggers; +@synthesize supportsEvents; @synthesize supportsIndexKeyBlockSize; @synthesize supportsQuotingEngineTypeInCreateSyntax; @synthesize supportsFractionalSeconds; @@ -185,6 +186,9 @@ // Support for triggers wasn't added until MySQL 5.0.2 supportsTriggers = [self isEqualToOrGreaterThanMajorVersion:5 minor:0 release:2]; + + // Support for events wasn't added until MySQL 5.1.6 + supportsEvents = [self isEqualToOrGreaterThanMajorVersion:5 minor:1 release:6]; // Support for specifying an index's key block size wasn't added until MySQL 5.1.10 supportsIndexKeyBlockSize = [self isEqualToOrGreaterThanMajorVersion:5 minor:1 release:10]; @@ -280,6 +284,7 @@ supportsArchiveStorageEngine = NO; supportsCSVStorageEngine = NO; supportsTriggers = NO; + supportsEvents = NO; supportsIndexKeyBlockSize = NO; supportsQuotingEngineTypeInCreateSyntax = NO; supportsFractionalSeconds = NO; diff --git a/Source/SPTablesList.h b/Source/SPTablesList.h index a8d9ab91..198f327f 100644 --- a/Source/SPTablesList.h +++ b/Source/SPTablesList.h @@ -180,6 +180,7 @@ - (NSArray *)allViewNames; - (NSArray *)allFunctionNames; - (NSArray *)allProcedureNames; +- (NSArray *)allEventNames; - (NSArray *)allDatabaseNames; - (NSArray *)allSystemDatabaseNames; - (NSString *)selectedDatabase; diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 952d4868..3efc45ef 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -91,6 +91,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; #endif - (void)_renameTableOfType:(SPTableType)tableType from:(NSString *)oldTableName to:(NSString *)newTableName; - (void)_duplicateConnectionToFrontTab; +- (NSMutableArray *)_allSchemaObjectsOfType:(SPTableType)type; @end @implementation SPTablesList @@ -1286,47 +1287,37 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; - (NSArray *)allTableNames { - NSMutableArray *returnArray = [NSMutableArray array]; - NSInteger i; - NSInteger cnt = [[self tables] count]; - for(i=0; i Date: Sat, 3 Jan 2015 01:08:03 +0100 Subject: Fix minor UI issue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When cancelling a connection, because SSH is asking for a password, the "SSH connecting…" message in the upper right window corner would not be reset. --- Source/SPConnectionController.m | 1 + 1 file changed, 1 insertion(+) (limited to 'Source') diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index e9d9272c..82c29510 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -1615,6 +1615,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [progressIndicator display]; [progressIndicatorText setHidden:YES]; [progressIndicatorText display]; + [dbDocument setTitlebarStatus:@""]; // If not testing a connection, Update the password fields, restoring passwords that may have // been bulleted out during connection -- cgit v1.2.3 From 2735e15bf5d4b3a976435ebb29ca9073de0e5071 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 4 Jan 2015 03:57:26 +0100 Subject: Formalize [x release], x = nil; convention Take this commit as a proposal to formalize our existing "[x release], x = nil;" convention by introducing a macro for it. Feel free to revert this commit if you see issues with the approch or implementation. --- Source/DMLocalizedNib.m | 2 +- Source/GeneratePreviewForURL.m | 32 +++++----- Source/NoodleLineNumberView.m | 2 +- Source/SPActivityTextFieldCell.m | 6 +- Source/SPAppController.m | 12 ++-- Source/SPBundleCommandRunner.m | 2 +- Source/SPBundleEditorController.m | 18 +++--- Source/SPCSVExporter.m | 16 ++--- Source/SPCSVParser.m | 4 +- Source/SPConnectionController.m | 38 ++++++------ Source/SPConnectionHandler.m | 12 ++-- Source/SPConsoleMessage.m | 8 +-- Source/SPConstants.h | 7 +++ Source/SPConstants.m | 4 ++ Source/SPCopyTable.m | 10 ++-- Source/SPCustomQuery.m | 14 ++--- Source/SPDataCellFormatter.m | 2 +- Source/SPDataImport.m | 16 ++--- Source/SPDataStorage.m | 8 +-- Source/SPDatabaseData.m | 20 +++---- Source/SPDatabaseDocument.m | 111 +++++++++++++++++------------------ Source/SPDatabaseStructure.m | 6 +- Source/SPDatabaseViewController.m | 2 +- Source/SPDotExporter.m | 12 ++-- Source/SPEditorPreferencePane.m | 16 ++--- Source/SPExportController.m | 12 ++-- Source/SPExportFile.m | 2 +- Source/SPExportInitializer.m | 2 +- Source/SPExporter.m | 6 +- Source/SPExtendedTableInfo.m | 2 +- Source/SPFavoriteNode.m | 2 +- Source/SPFavoritesController.m | 6 +- Source/SPFieldEditorController.m | 2 +- Source/SPFieldMapperController.m | 32 +++++----- Source/SPGeneralPreferencePane.m | 2 +- Source/SPGotoDatabaseController.m | 4 +- Source/SPGroupNode.m | 2 +- Source/SPGrowlController.m | 4 +- Source/SPIndexesController.m | 14 ++--- Source/SPNarrowDownCompletion.m | 2 +- Source/SPNavigatorController.m | 1 - Source/SPPreferenceController.m | 2 +- Source/SPProcessListController.m | 10 ++-- Source/SPQueryController.m | 20 +++---- Source/SPSQLExporter.m | 12 ++-- Source/SPSQLParser.m | 2 +- Source/SPSSHTunnel.m | 20 +++---- Source/SPServerVariablesController.m | 6 +- Source/SPSplitView.m | 16 ++--- Source/SPTableContent.m | 22 +++---- Source/SPTableContentDelegate.m | 2 +- Source/SPTableData.m | 6 +- Source/SPTableFieldValidation.m | 2 +- Source/SPTableRelations.m | 4 +- Source/SPTableStructure.m | 2 +- Source/SPTableStructureLoading.m | 4 +- Source/SPTableTriggers.m | 4 +- Source/SPTablesList.m | 8 +-- Source/SPThreadAdditions.m | 4 +- Source/SPUserManager.m | 28 +++++---- Source/SPXMLExporter.m | 6 +- 61 files changed, 333 insertions(+), 322 deletions(-) (limited to 'Source') diff --git a/Source/DMLocalizedNib.m b/Source/DMLocalizedNib.m index 56f6a810..4a03247a 100644 --- a/Source/DMLocalizedNib.m +++ b/Source/DMLocalizedNib.m @@ -154,7 +154,7 @@ static NSMutableDictionary *deliciousNibNames = nil; { if (deliciousNibNames) { [deliciousNibNames removeObjectForKey:[NSValue valueWithPointer:self]]; - if (![deliciousNibNames count]) [deliciousNibNames release], deliciousNibNames = nil; + if (![deliciousNibNames count]) SPClear(deliciousNibNames); } [self deliciousDealloc]; } diff --git a/Source/GeneratePreviewForURL.m b/Source/GeneratePreviewForURL.m index 1062f11d..ef20b852 100644 --- a/Source/GeneratePreviewForURL.m +++ b/Source/GeneratePreviewForURL.m @@ -78,8 +78,8 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&convError] retain]; if(!spf || readError != nil || [convError length] || !(format == NSPropertyListXMLFormat_v1_0 || format == NSPropertyListBinaryFormat_v1_0)) { - if(spf) [spf release], spf = nil; - if(pool) [pool release], pool = nil; + if(spf) SPClear(spf); + if(pool) SPClear(pool); return noErr; } @@ -89,8 +89,8 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (template == nil || ![template length] || templateReadError != nil) { - if(spf) [spf release], spf = nil; - if(pool) [pool release], pool = nil; + if(spf) SPClear(spf); + if(pool) SPClear(pool); return noErr; } @@ -146,8 +146,8 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (template == nil || ![template length] || templateReadError != nil) { - if(spf) [spf release], spf = nil; - if(pool) [pool release], pool = nil; + if(spf) SPClear(spf); + if(pool) SPClear(pool); return noErr; } // compose the html @@ -162,8 +162,8 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (template == nil || ![template length] || templateReadError != nil) { - if(spf) [spf release], spf = nil; - if(pool) [pool release], pool = nil; + if(spf) SPClear(spf); + if(pool) SPClear(pool); return noErr; } // compose the html @@ -182,7 +182,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (template == nil || ![template length] || templateReadError != nil) { - if(pool) [pool release], pool = nil; + if(pool) SPClear(pool); return noErr; } @@ -190,7 +190,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (windowTemplate == nil || ![windowTemplate length] || templateReadError != nil) { - if(pool) [pool release], pool = nil; + if(pool) SPClear(pool); return noErr; } @@ -205,8 +205,8 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&convError] retain]; if(!spf || readError != nil || [convError length] || !(format == NSPropertyListXMLFormat_v1_0 || format == NSPropertyListBinaryFormat_v1_0)) { - if(spf) [spf release], spf = nil; - if(pool) [pool release], pool = nil; + if(spf) SPClear(spf); + if(pool) SPClear(pool); return noErr; } @@ -323,7 +323,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, encoding:NSUTF8StringEncoding error:&templateReadError]; if (template == nil || ![template length] || templateReadError != nil) { - if(pool) [pool release], pool = nil; + if(pool) SPClear(pool); return noErr; } @@ -418,10 +418,10 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, [sqlHTML appendFormat:@"%@", tokenColor, [[sqlText substringWithRange:tokenRange] HTMLEscapeString]]; if (QLPreviewRequestIsCancelled(preview)) { - if(sqlHTML) [sqlHTML release], sqlHTML = nil; + if(sqlHTML) SPClear(sqlHTML); if(truncatedString) [truncatedString release], sqlHTML = nil; if(sqlText) [sqlText release], sqlHTML = nil; - if(pool) [pool release], pool = nil; + if(pool) SPClear(pool); [loopPool release]; return noErr; } @@ -457,7 +457,7 @@ OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, } else { // No file attributes were read, bail for safety reasons - if(pool) [pool release], pool = nil; + if(pool) SPClear(pool); return noErr; } diff --git a/Source/NoodleLineNumberView.m b/Source/NoodleLineNumberView.m index 1d58bbed..24b76be1 100644 --- a/Source/NoodleLineNumberView.m +++ b/Source/NoodleLineNumberView.m @@ -497,7 +497,7 @@ typedef NSRange (*RangeOfLineIMP)(id object, SEL selector, NSRange range); - (void)invalidateLineIndices { - if (lineIndices) [lineIndices release], lineIndices = nil; + if (lineIndices) SPClear(lineIndices); } diff --git a/Source/SPActivityTextFieldCell.m b/Source/SPActivityTextFieldCell.m index 5eb2deda..b82fa995 100644 --- a/Source/SPActivityTextFieldCell.m +++ b/Source/SPActivityTextFieldCell.m @@ -324,9 +324,9 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) */ - (void)dealloc { - if(activityName) [activityName release], activityName = nil; - if(activityInfo) [activityInfo release], activityInfo = nil; - if(contextInfo) [contextInfo release], contextInfo = nil; + if(activityName) SPClear(activityName); + if(activityInfo) SPClear(activityInfo); + if(contextInfo) SPClear(contextInfo); if(cancelButton) [cancelButton release]; [super dealloc]; diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 3f9db630..87cf9f24 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -1355,7 +1355,7 @@ */ - (void)setSessionURL:(NSString *)urlString { - if(_sessionURL) [_sessionURL release], _sessionURL = nil; + if(_sessionURL) SPClear(_sessionURL); if(urlString) _sessionURL = [[NSURL fileURLWithPath:urlString] retain]; } @@ -2240,13 +2240,13 @@ if (installedBundleUUIDs) [installedBundleUUIDs release]; if (runningActivitiesArray) [runningActivitiesArray release]; - [prefsController release], prefsController = nil; + SPClear(prefsController); - if (aboutController) [aboutController release], aboutController = nil; - if (bundleEditorController) [bundleEditorController release], bundleEditorController = nil; + if (aboutController) SPClear(aboutController); + if (bundleEditorController) SPClear(bundleEditorController); - if (_sessionURL) [_sessionURL release], _sessionURL = nil; - if (_spfSessionDocData) [_spfSessionDocData release], _spfSessionDocData = nil; + if (_sessionURL) SPClear(_sessionURL); + if (_spfSessionDocData) SPClear(_spfSessionDocData); [super dealloc]; } diff --git a/Source/SPBundleCommandRunner.m b/Source/SPBundleCommandRunner.m index 45184618..08fad6f1 100644 --- a/Source/SPBundleCommandRunner.m +++ b/Source/SPBundleCommandRunner.m @@ -297,7 +297,7 @@ // Read STDOUT saved to file if([fm fileExistsAtPath:stdoutFilePath isDirectory:nil]) { NSString *stdoutContent = [NSString stringWithContentsOfFile:stdoutFilePath encoding:NSUTF8StringEncoding error:nil]; - if(bashTask) [bashTask release], bashTask = nil; + if(bashTask) SPClear(bashTask); [fm removeItemAtPath:stdoutFilePath error:nil]; if(stdoutContent != nil) { if (status == 0) { diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index ac227cf4..69652bf1 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -1093,7 +1093,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [draggedFilePath release]; draggedFilePath = nil; } - if(oldBundleName) [oldBundleName release], oldBundleName = nil; + if(oldBundleName) SPClear(oldBundleName); } #pragma mark - @@ -1234,13 +1234,13 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; // Remember selected bundle name to reset the name if the user cancelled // the editing of the bundle name - if(oldBundleName) [oldBundleName release], oldBundleName = nil; + if(oldBundleName) SPClear(oldBundleName); if(![[self _currentSelectedObject] objectForKey:kChildrenKey]) { oldBundleName = [[[self _currentSelectedObject] objectForKey:kBundleNameKey] retain]; [self _enableBundleDataInput:YES bundleEnabled:![[[self _currentSelectedObject] objectForKey:@"disabled"] boolValue]]; } else { [self _enableBundleDataInput:NO bundleEnabled:NO]; - if(oldBundleName) [oldBundleName release], oldBundleName = nil; + if(oldBundleName) SPClear(oldBundleName); } // Remember the selected bundle name in touchedBundleArray to save only those @@ -1386,7 +1386,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [commandBundleTreeController rearrangeObjects]; [commandsOutlineView reloadData]; - if(oldBundleName) [oldBundleName release], oldBundleName = nil; + if(oldBundleName) SPClear(oldBundleName); oldBundleName = [[[self _currentSelectedObject] objectForKey:kBundleNameKey] retain]; if(oldBundleName != nil && ![touchedBundleArray containsObject:oldBundleName]) [touchedBundleArray addObject:oldBundleName]; @@ -2102,11 +2102,11 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; [shellVariableSuggestions release]; [deletedDefaultBundles release]; - if (touchedBundleArray) [touchedBundleArray release], touchedBundleArray = nil; - if (commandBundleTree) [commandBundleTree release], commandBundleTree = nil; - if (sortDescriptor) [sortDescriptor release], sortDescriptor = nil; - if (bundlePath) [bundlePath release], bundlePath = nil; - if (esUndoManager) [esUndoManager release], esUndoManager = nil; + if (touchedBundleArray) SPClear(touchedBundleArray); + if (commandBundleTree) SPClear(commandBundleTree); + if (sortDescriptor) SPClear(sortDescriptor); + if (bundlePath) SPClear(bundlePath); + if (esUndoManager) SPClear(esUndoManager); [super dealloc]; } diff --git a/Source/SPCSVExporter.m b/Source/SPCSVExporter.m index dd244410..5fb6f664 100644 --- a/Source/SPCSVExporter.m +++ b/Source/SPCSVExporter.m @@ -415,15 +415,15 @@ - (void)dealloc { - if (csvDataArray) [csvDataArray release], csvDataArray = nil; - if (csvTableName) [csvTableName release], csvTableName = nil; + if (csvDataArray) SPClear(csvDataArray); + if (csvTableName) SPClear(csvTableName); - [csvFieldSeparatorString release], csvFieldSeparatorString = nil; - [csvEnclosingCharacterString release], csvEnclosingCharacterString = nil; - [csvEscapeString release], csvEscapeString = nil; - [csvLineEndingString release], csvLineEndingString = nil; - [csvNULLString release], csvNULLString = nil; - [csvTableData release], csvTableData = nil; + SPClear(csvFieldSeparatorString); + SPClear(csvEnclosingCharacterString); + SPClear(csvEscapeString); + SPClear(csvLineEndingString); + SPClear(csvNULLString); + SPClear(csvTableData); [super dealloc]; } diff --git a/Source/SPCSVParser.m b/Source/SPCSVParser.m index 09d8c989..88a2fbb5 100644 --- a/Source/SPCSVParser.m +++ b/Source/SPCSVParser.m @@ -469,7 +469,7 @@ */ - (void) setNullReplacementString:(NSString *)nullString { - if (nullReplacementString) [nullReplacementString release], nullReplacementString = nil; + if (nullReplacementString) SPClear(nullReplacementString); if (nullString) nullReplacementString = [[NSString alloc] initWithString:nullString]; } @@ -576,7 +576,7 @@ { NSMutableString *charactersToSkip; - if (skipCharacterSet) [skipCharacterSet release], skipCharacterSet = nil; + if (skipCharacterSet) SPClear(skipCharacterSet); charactersToSkip = [[NSMutableString alloc] init]; if (![fieldEndString isEqualToString:@" "] && ![fieldQuoteString isEqualToString:@" "] && ![escapeString isEqualToString:@" "] && ![lineEndString isEqualToString:@" "]) diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 82c29510..651d3538 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -256,8 +256,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [[sshPasswordField undoManager] removeAllActionsWithTarget:sshPasswordField]; } else { - [connectionKeychainItemName release], connectionKeychainItemName = nil; - [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil; + SPClear(connectionKeychainItemName); + SPClear(connectionKeychainItemAccount); } } @@ -267,8 +267,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [[sshSSHPasswordField undoManager] removeAllActionsWithTarget:sshSSHPasswordField]; } else { - [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil; - [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil; + SPClear(connectionSSHKeychainItemName); + SPClear(connectionSSHKeychainItemAccount); } } #endif @@ -608,11 +608,11 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, #ifndef SP_CODA // Clear the keychain referral items as appropriate - if (connectionKeychainID) [connectionKeychainID release], connectionKeychainID = nil; - if (connectionKeychainItemName) [connectionKeychainItemName release], connectionKeychainItemName = nil; - if (connectionKeychainItemAccount) [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil; - if (connectionSSHKeychainItemName) [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil; - if (connectionSSHKeychainItemAccount) [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil; + if (connectionKeychainID) SPClear(connectionKeychainID); + if (connectionKeychainItemName) SPClear(connectionKeychainItemName); + if (connectionKeychainItemAccount) SPClear(connectionKeychainItemAccount); + if (connectionSSHKeychainItemName) SPClear(connectionSSHKeychainItemName); + if (connectionSSHKeychainItemAccount) SPClear(connectionSSHKeychainItemAccount); SPTreeNode *node = [self selectedFavoriteNode]; if ([node isGroup]) node = nil; @@ -621,7 +621,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, NSDictionary *fav = [[node representedObject] nodeFavorite]; // Keep a copy of the favorite as it currently stands - if (currentFavorite) [currentFavorite release], currentFavorite = nil; + if (currentFavorite) SPClear(currentFavorite); currentFavorite = [fav copy]; [connectionResizeContainer setHidden:NO]; @@ -669,8 +669,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, if (![[self password] length]) { [self setPassword:nil]; - [connectionKeychainItemName release], connectionKeychainItemName = nil; - [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil; + SPClear(connectionKeychainItemName); + SPClear(connectionKeychainItemAccount); } // Store the selected favorite ID for use with the document on connection @@ -684,8 +684,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, if (![[self sshPassword] length]) { [self setSshPassword:nil]; - [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil; - [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil; + SPClear(connectionSSHKeychainItemName); + SPClear(connectionSSHKeychainItemAccount); } [prefs setInteger:[[fav objectForKey:SPFavoriteIDKey] integerValue] forKey:SPLastFavoriteID]; @@ -1365,7 +1365,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self _stopEditingConnection]; - if (currentFavorite) [currentFavorite release], currentFavorite = nil; + if (currentFavorite) SPClear(currentFavorite); currentFavorite = [theFavorite copy]; [self _sortFavorites]; @@ -1888,9 +1888,9 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [prefs release]; #ifndef SP_CODA - [folderImage release], folderImage = nil; - [quickConnectItem release], quickConnectItem = nil; - [quickConnectCell release], quickConnectCell = nil; + SPClear(folderImage); + SPClear(quickConnectItem); + SPClear(quickConnectCell); #endif for (id retainedObject in nibObjectsToRelease) [retainedObject release]; @@ -1904,7 +1904,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, if (connectionSSHKeychainItemAccount) [connectionSSHKeychainItemAccount release]; #ifndef SP_CODA - if (currentFavorite) [currentFavorite release], currentFavorite = nil; + if (currentFavorite) SPClear(currentFavorite); #endif [super dealloc]; diff --git a/Source/SPConnectionHandler.m b/Source/SPConnectionHandler.m index 12b868f5..bac0c680 100644 --- a/Source/SPConnectionHandler.m +++ b/Source/SPConnectionHandler.m @@ -208,9 +208,9 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; // Tidy up isConnecting = NO; - if (sshTunnel) [sshTunnel disconnect], [sshTunnel release], sshTunnel = nil; + if (sshTunnel) [sshTunnel disconnect], SPClear(sshTunnel); - [mySQLConnection release], mySQLConnection = nil; + SPClear(mySQLConnection); #ifndef SP_CODA if (!cancellingConnection) [self _restoreConnectionInterface]; #endif @@ -229,9 +229,9 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; // Tidy up isConnecting = NO; - if (sshTunnel) [sshTunnel release], sshTunnel = nil; + if (sshTunnel) SPClear(sshTunnel); - [mySQLConnection release], mySQLConnection = nil; + SPClear(mySQLConnection); [self _restoreConnectionInterface]; if (isTestingConnection) { [self _showConnectionTestResult:NSLocalizedString(@"Invalid database", @"Invalid database very short status message")]; @@ -352,7 +352,7 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; #endif // Release the tunnel if set - will now be retained by the connection - if (sshTunnel) [sshTunnel release], sshTunnel = nil; + if (sshTunnel) SPClear(sshTunnel); // Pass the connection to the document and clean up the interface [self addConnectionToDocument]; @@ -436,7 +436,7 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; // Release as appropriate if (sshTunnel) { - [sshTunnel disconnect], [sshTunnel release], sshTunnel = nil; + [sshTunnel disconnect], SPClear(sshTunnel); // If the SSH tunnel connection failed because the port it was trying to bind to was already in use take note // of it so we can give the user the option of connecting via standard connection and use the existing tunnel. diff --git a/Source/SPConsoleMessage.m b/Source/SPConsoleMessage.m index 6ada323a..eb7573f9 100644 --- a/Source/SPConsoleMessage.m +++ b/Source/SPConsoleMessage.m @@ -65,10 +65,10 @@ - (void)dealloc { - [message release], message = nil; - [messageDate release], messageDate = nil; - [messageDatabase release], messageDatabase = nil; - [messageConnection release], messageConnection = nil; + SPClear(message); + SPClear(messageDate); + SPClear(messageDatabase); + SPClear(messageConnection); [super dealloc]; } diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 415fd4da..f0350f07 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -612,6 +612,13 @@ extern NSString *SPURLSchemeQueryResultMetaPathHeader; #define SPAppDelegate ((SPAppController *)[NSApp delegate]) +// Provides a standard method for our "[x release], x = nil;" convention. +// Yes, this could have been done with a preprocessor macro alone, however +// a function works more nicely in the debugger and in production code +// the optimizer will most likely remove all overhead by inlining anyway :) +void _SPClear(id *addr); +#define SPClear(x) _SPClear(&x) + //Backwards compatibility #ifndef __MAC_10_7 #define __MAC_10_7 1070 diff --git a/Source/SPConstants.m b/Source/SPConstants.m index 23d8c378..292acb3c 100644 --- a/Source/SPConstants.m +++ b/Source/SPConstants.m @@ -417,3 +417,7 @@ NSString *SPURLSchemeQueryInputPathHeader = @"/tmp/SP_QUERY_"; NSString *SPURLSchemeQueryResultPathHeader = @"/tmp/SP_QUERY_RESULT_"; NSString *SPURLSchemeQueryResultStatusPathHeader = @"/tmp/SP_QUERY_RESULT_STATUS_"; NSString *SPURLSchemeQueryResultMetaPathHeader = @"/tmp/SP_QUERY_META_"; + +void inline _SPClear(id *addr) { + [*addr release], *addr = nil; +} diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m index 3efc132a..7aaae1a6 100644 --- a/Source/SPCopyTable.m +++ b/Source/SPCopyTable.m @@ -219,7 +219,7 @@ static const NSInteger kBlobAsImageFile = 4; if (image) { NSData *d = [[NSData alloc] initWithData:[image TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:1]]; [d writeToFile:fp atomically:NO]; - if(d) [d release], d = nil; + if(d) SPClear(d); [image release]; } else { NSString *noData = @""; @@ -242,7 +242,7 @@ static const NSInteger kBlobAsImageFile = 4; } else { [result appendFormat:@"%@\t", [cellData wktString]]; } - if(v) [v release], v = nil; + if(v) SPClear(v); } else { [result appendFormat:@"%@\t", [cellData wktString]]; } @@ -358,7 +358,7 @@ static const NSInteger kBlobAsImageFile = 4; if (image) { NSData *d = [[NSData alloc] initWithData:[image TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:1]]; [d writeToFile:fp atomically:NO]; - if(d) [d release], d = nil; + if(d) SPClear(d); [image release]; } else { NSString *noData = @""; @@ -381,7 +381,7 @@ static const NSInteger kBlobAsImageFile = 4; } else { [result appendFormat:@"\"%@\",", [cellData wktString]]; } - if(v) [v release], v = nil; + if(v) SPClear(v); } else { [result appendFormat:@"\"%@\",", [cellData wktString]]; } @@ -698,7 +698,7 @@ static const NSInteger kBlobAsImageFile = 4; tableInstance = anInstance; tableStorage = theTableStorage; - if (columnDefinitions) [columnDefinitions release], columnDefinitions = nil; + if (columnDefinitions) SPClear(columnDefinitions); columnDefinitions = [[NSArray alloc] initWithArray:columnDefs]; } diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 8b201776..2114d766 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -141,7 +141,7 @@ // Re-init sort order isDesc = NO; sortColumn = nil; - if(sortField) [sortField release], sortField = nil; + if(sortField) SPClear(sortField); // Retrieve the custom query string and split it into separate SQL queries queryParser = [[SPSQLParser alloc] initWithString:[textView string]]; @@ -185,7 +185,7 @@ // Re-init sort order isDesc = NO; sortColumn = nil; - if(sortField) [sortField release], sortField = nil; + if(sortField) SPClear(sortField); // If the current selection is a single caret position, run the current query. if (selectedRange.length == 0) { @@ -628,7 +628,7 @@ // Remove all the columns if not reloading the table if(!reloadingExistingResult) { - if (cqColumnDefinition) [cqColumnDefinition release], cqColumnDefinition = nil; + if (cqColumnDefinition) SPClear(cqColumnDefinition); [[self onMainThread] updateTableView]; } @@ -1736,7 +1736,7 @@ */ - (void)setResultSelectedRowIndexesToRestore:(NSIndexSet *)theIndexSet { - if (selectionIndexToRestore) [selectionIndexToRestore release], selectionIndexToRestore = nil; + if (selectionIndexToRestore) SPClear(selectionIndexToRestore); if (theIndexSet) selectionIndexToRestore = [[NSIndexSet alloc] initWithIndexSet:theIndexSet]; } @@ -2273,7 +2273,7 @@ if ([mySQLConnection queryErrored]) { sortColumn = nil; - if(sortField) [sortField release], sortField = nil; + if(sortField) SPClear(sortField); return; } @@ -2449,7 +2449,7 @@ // Open the editing sheet if required if ([customQueryView shouldUseFieldEditorForRow:rowIndex column:[[aTableColumn identifier] integerValue] checkWithLock:NULL]) { - if (fieldEditor) [fieldEditor release], fieldEditor = nil; + if (fieldEditor) SPClear(fieldEditor); fieldEditor = [[SPFieldEditorController alloc] init]; // Remember edited row for reselecting and setting the scroll view after reload @@ -4042,7 +4042,7 @@ [resultData release]; [favoritesManager release]; - if(fieldEditor) [fieldEditor release], fieldEditor = nil; + if(fieldEditor) SPClear(fieldEditor); #ifndef SP_CODA if (helpHTMLTemplate) [helpHTMLTemplate release]; diff --git a/Source/SPDataCellFormatter.m b/Source/SPDataCellFormatter.m index 2cd3b8c8..6c6cd913 100644 --- a/Source/SPDataCellFormatter.m +++ b/Source/SPDataCellFormatter.m @@ -140,7 +140,7 @@ - (void)dealloc { - if (fieldType) [fieldType release], fieldType = nil; + if (fieldType) SPClear(fieldType); [super dealloc]; } diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index f1208a54..be3935c4 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -1324,7 +1324,7 @@ cleanup: dispatch_async(dispatch_get_main_queue(), ^{ - if(fieldMapperController) [fieldMapperController release], fieldMapperController = nil; + if(fieldMapperController) SPClear(fieldMapperController); }); return success; @@ -1715,13 +1715,13 @@ cleanup: */ - (void)_resetFieldMappingGlobals { - if (csvImportTailString) [csvImportTailString release], csvImportTailString = nil; - if (csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil; - if (fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil; - if (fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil; - if (fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil; - if (fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil; - if (fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil; + if (csvImportTailString) SPClear(csvImportTailString); + if (csvImportHeaderString) SPClear(csvImportHeaderString); + if (fieldMappingArray) SPClear(fieldMappingArray); + if (fieldMappingGlobalValueArray) SPClear(fieldMappingGlobalValueArray); + if (fieldMappingTableColumnNames) SPClear(fieldMappingTableColumnNames); + if (fieldMappingTableDefaultValues) SPClear(fieldMappingTableDefaultValues); + if (fieldMapperOperator) SPClear(fieldMapperOperator); } #pragma mark - diff --git a/Source/SPDataStorage.m b/Source/SPDataStorage.m index 30be0644..3db04159 100644 --- a/Source/SPDataStorage.m +++ b/Source/SPDataStorage.m @@ -58,7 +58,7 @@ static inline NSMutableArray* SPDataStorageGetEditedRow(NSPointerArray* rowStore { NSUInteger i; editedRowCount = 0; - [editedRows release], editedRows = nil; + SPClear(editedRows); if (unloadedColumns) free(unloadedColumns), unloadedColumns = NULL; if (dataStorage) { @@ -68,7 +68,7 @@ static inline NSMutableArray* SPDataStorageGetEditedRow(NSPointerArray* rowStore [newDataStorage replaceExistingResultStore:dataStorage]; } - [dataStorage release], dataStorage = nil; + SPClear(dataStorage); } dataStorage = [newDataStorage retain]; @@ -449,8 +449,8 @@ static inline NSMutableArray* SPDataStorageGetEditedRow(NSPointerArray* rowStore } - (void) dealloc { - [dataStorage release], dataStorage = nil; - [editedRows release], editedRows = nil; + SPClear(dataStorage); + SPClear(editedRows); if (unloadedColumns) free(unloadedColumns), unloadedColumns = NULL; [super dealloc]; diff --git a/Source/SPDatabaseData.m b/Source/SPDatabaseData.m index 58ffa2d2..4856505d 100644 --- a/Source/SPDatabaseData.m +++ b/Source/SPDatabaseData.m @@ -82,11 +82,11 @@ NSInteger _sortStorageEngineEntry(NSDictionary *itemOne, NSDictionary *itemTwo, */ - (void)resetAllData { - if (characterSetEncoding != nil) [characterSetEncoding release], characterSetEncoding = nil; - if (defaultCollation != nil) [defaultCollation release], defaultCollation = nil; - if (defaultCharacterSetEncoding != nil) [defaultCharacterSetEncoding release], defaultCharacterSetEncoding = nil; - if (serverDefaultCharacterSetEncoding) [serverDefaultCharacterSetEncoding release], serverDefaultCharacterSetEncoding = nil; - if (serverDefaultCollation) [serverDefaultCollation release], serverDefaultCollation = nil; + if (characterSetEncoding != nil) SPClear(characterSetEncoding); + if (defaultCollation != nil) SPClear(defaultCollation); + if (defaultCharacterSetEncoding != nil) SPClear(defaultCharacterSetEncoding); + if (serverDefaultCharacterSetEncoding) SPClear(serverDefaultCharacterSetEncoding); + if (serverDefaultCollation) SPClear(serverDefaultCollation); [collations removeAllObjects]; [characterSetCollations removeAllObjects]; @@ -489,11 +489,11 @@ NSInteger _sortStorageEngineEntry(NSDictionary *itemOne, NSDictionary *itemTwo, { [self resetAllData]; - [collations release], collations = nil; - [characterSetCollations release], characterSetCollations = nil; - [storageEngines release], storageEngines = nil; - [characterSetEncodings release], characterSetEncodings = nil; - [cachedCollationsByEncoding release], cachedCollationsByEncoding = nil; + SPClear(collations); + SPClear(characterSetCollations); + SPClear(storageEngines); + SPClear(characterSetEncodings); + SPClear(cachedCollationsByEncoding); [super dealloc]; } diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 9f5ce128..6940abfb 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -473,7 +473,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Update the selected database if appropriate if ([connectionController database] && ![[connectionController database] isEqualToString:@""]) { - if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil; + if (selectedDatabase) SPClear(selectedDatabase); selectedDatabase = [[NSString alloc] initWithString:[connectionController database]]; #ifndef SP_CODA /* [spHistoryControllerInstance updateHistoryEntries] */ [spHistoryControllerInstance updateHistoryEntries]; @@ -665,8 +665,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [[chooseDatabaseButton menu] addItem:[NSMenuItem separatorItem]]; #endif - if (allDatabases) [allDatabases release]; - if (allSystemDatabases) [allSystemDatabases release]; + if (allDatabases) SPClear(allDatabases); + if (allSystemDatabases) SPClear(allSystemDatabases); NSArray *theDatabaseList = [mySQLConnection databases]; @@ -1056,7 +1056,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #ifndef SP_CODA // Close error status sheet for OPTIMIZE, CHECK, REPAIR etc. else if ([contextInfo isEqualToString:@"statusError"]) { - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); } #endif } @@ -1096,7 +1096,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; if(![dbName isNSNull]) { if(![dbName isEqualToString:selectedDatabase]) { - if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil; + if (selectedDatabase) SPClear(selectedDatabase); selectedDatabase = [[NSString alloc] initWithString:dbName]; [chooseDatabaseButton selectItemWithTitle:selectedDatabase]; #ifndef SP_CODA /* [self updateWindowTitle:self] */ @@ -1104,7 +1104,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #endif } } else { - if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil; + if (selectedDatabase) SPClear(selectedDatabase); [chooseDatabaseButton selectItemAtIndex:0]; #ifndef SP_CODA /* [self updateWindowTitle:self] */ [self updateWindowTitle:self]; @@ -1313,8 +1313,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // If the window has been fully faded in, clean up the timer. if (alphaValue == 1.0) { - [taskDrawTimer invalidate], [taskDrawTimer release], taskDrawTimer = nil; - [taskFadeInStartDate release], taskFadeInStartDate = nil; + [taskDrawTimer invalidate], SPClear(taskDrawTimer); + SPClear(taskFadeInStartDate); } #endif } @@ -1424,8 +1424,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #ifndef SP_CODA // Cancel the draw timer if it exists if (taskDrawTimer) { - [taskDrawTimer invalidate], [taskDrawTimer release], taskDrawTimer = nil; - [taskFadeInStartDate release], taskFadeInStartDate = nil; + [taskDrawTimer invalidate], SPClear(taskDrawTimer); + SPClear(taskFadeInStartDate); } // Hide the task interface and reset to indeterminate @@ -1712,7 +1712,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; NSString *mysqlEncoding = [databaseDataInstance getDatabaseDefaultCharacterSet]; - [selectedDatabaseEncoding release], selectedDatabaseEncoding = nil; + SPClear(selectedDatabaseEncoding); // Fallback or older version? -> set encoding to mysql default encoding latin1 if ( !mysqlEncoding ) { @@ -1953,7 +1953,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo:NULL]; } else { message = NSLocalizedString(@"MySQL said:",@"mysql said message"); - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:message]; @@ -2030,7 +2030,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo:NULL]; } else { message = NSLocalizedString(@"MySQL said:",@"mysql said message"); - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:message]; @@ -2107,7 +2107,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo:NULL]; } else { message = NSLocalizedString(@"MySQL said:",@"mysql said message"); - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:message]; @@ -2183,7 +2183,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo:NULL]; } else { message = NSLocalizedString(@"MySQL said:",@"mysql said message"); - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:message]; @@ -2259,7 +2259,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo:NULL]; } else { message = NSLocalizedString(@"MySQL said:",@"mysql said message"); - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:message]; @@ -2315,7 +2315,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; didEndSelector:NULL contextInfo:NULL]; } else { - if (statusValues) [statusValues release], statusValues = nil; + if (statusValues) SPClear(statusValues); statusValues = [resultStatuses retain]; NSAlert *alert = [[NSAlert new] autorelease]; [alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Checksums of %@",@"Checksums of %@ message"), what]]; @@ -2487,7 +2487,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [userManagerInstance beginSheetModalForWindow:parentWindow completionHandler:^(){ - [userManagerInstance release], userManagerInstance = nil; + SPClear(userManagerInstance); }]; } @@ -3044,7 +3044,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [self saveDocumentWithFilePath:fileName inBackground:NO onlyPreferences:NO contextInfo:nil]; // Manually loaded nibs don't have their top-level objects released automatically - do that here. - [saveConnectionAccessory release]; + SPClear(saveConnectionAccessory); if(contextInfo == @"saveSPFfileAndClose") [self closeAndDisconnect]; @@ -4357,7 +4357,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; */ - (void)setFileURL:(NSURL *)theURL { - if (spfFileURL) [spfFileURL release], spfFileURL = nil; + if (spfFileURL) SPClear(spfFileURL); spfFileURL = [theURL retain]; if ([parentWindowController selectedTableDocument] == self) { if (spfFileURL && [spfFileURL isFileURL]) @@ -5016,8 +5016,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [self updateWindowTitle:self]; // dealloc spfSession data - [spfSession release]; - spfSession = nil; + SPClear(spfSession); // End the task [self endTask]; @@ -6064,7 +6063,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // that's why we can run this on main thread [databaseStructureRetrieval queryDbStructureWithUserInfo:nil]; - if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil; + if (selectedDatabase) SPClear(selectedDatabase); [self setDatabases:self]; @@ -6134,7 +6133,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #ifndef SP_CODA /* chooseDatabaseButton selectItemWithTitle: */ [[chooseDatabaseButton onMainThread] selectItemWithTitle:targetDatabaseName]; #endif - if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil; + if (selectedDatabase) SPClear(selectedDatabase); selectedDatabase = [[NSString alloc] initWithString:targetDatabaseName]; [databaseDataInstance resetAllData]; @@ -6280,59 +6279,59 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; #ifndef SP_CODA /* release nib objects */ for (id retainedObject in nibObjectsToRelease) [retainedObject release]; - [nibObjectsToRelease release]; + SPClear(nibObjectsToRelease); #endif // Tell listeners that this database document is being closed - fixes retain cycles and allows cleanup [[NSNotificationCenter defaultCenter] postNotificationName:SPDocumentWillCloseNotification object:self]; - [databaseStructureRetrieval release]; + SPClear(databaseStructureRetrieval); - [allDatabases release]; - [allSystemDatabases release]; - [gotoDatabaseController release]; + SPClear(allDatabases); + SPClear(allSystemDatabases); + SPClear(gotoDatabaseController); #ifndef SP_CODA /* dealloc ivars */ - [undoManager release]; - [printWebView release]; + SPClear(undoManager); + SPClear(printWebView); #endif - [selectedDatabaseEncoding release]; + SPClear(selectedDatabaseEncoding); #ifndef SP_CODA [taskProgressWindow close]; #endif - if (selectedTableName) [selectedTableName release]; - if (connectionController) [connectionController release]; + if (selectedTableName) SPClear(selectedTableName); + if (connectionController) SPClear(connectionController); #ifndef SP_CODA /* dealloc ivars */ - if (processListController) [processListController release]; - if (serverVariablesController) [serverVariablesController release]; + if (processListController) SPClear(processListController); + if (serverVariablesController) SPClear(serverVariablesController); #endif - if (mySQLConnection) [mySQLConnection release], mySQLConnection = nil; - if (selectedDatabase) [selectedDatabase release]; - if (mySQLVersion) [mySQLVersion release]; + if (mySQLConnection) SPClear(mySQLConnection); + if (selectedDatabase) SPClear(selectedDatabase); + if (mySQLVersion) SPClear(mySQLVersion); #ifndef SP_CODA - if (taskDrawTimer) [taskDrawTimer invalidate], [taskDrawTimer release]; - if (taskFadeInStartDate) [taskFadeInStartDate release]; + if (taskDrawTimer) [taskDrawTimer invalidate], SPClear(taskDrawTimer); + if (taskFadeInStartDate) SPClear(taskFadeInStartDate); #endif - if (queryEditorInitString) [queryEditorInitString release]; + if (queryEditorInitString) SPClear(queryEditorInitString); #ifndef SP_CODA - if (sqlFileURL) [sqlFileURL release]; - if (spfFileURL) [spfFileURL release]; - if (spfPreferences) [spfPreferences release]; - if (spfSession) [spfSession release]; - if (spfDocData) [spfDocData release]; + if (sqlFileURL) SPClear(sqlFileURL); + if (spfFileURL) SPClear(spfFileURL); + if (spfPreferences) SPClear(spfPreferences); + if (spfSession) SPClear(spfSession); + if (spfDocData) SPClear(spfDocData); #endif - if (keyChainID) [keyChainID release]; + if (keyChainID) SPClear(keyChainID); #ifndef SP_CODA - if (mainToolbar) [mainToolbar release]; + if (mainToolbar) SPClear(mainToolbar); #endif - if (titleAccessoryView) [titleAccessoryView release]; + if (titleAccessoryView) SPClear(titleAccessoryView); #ifndef SP_CODA - if (taskProgressWindow) [taskProgressWindow release]; + if (taskProgressWindow) SPClear(taskProgressWindow); #endif - if (serverSupport) [serverSupport release]; + if (serverSupport) SPClear(serverSupport); #ifndef SP_CODA /* dealloc ivars */ - if (processID) [processID release]; - if (runningActivitiesArray) [runningActivitiesArray release]; + if (processID) SPClear(processID); + if (runningActivitiesArray) SPClear(runningActivitiesArray); #endif #ifdef SP_CODA @@ -6340,8 +6339,8 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; if (customQueryInstance) [customQueryInstance release]; #endif - if (alterDatabaseCharsetHelper) [alterDatabaseCharsetHelper release]; - if (addDatabaseCharsetHelper) [addDatabaseCharsetHelper release]; + if (alterDatabaseCharsetHelper) SPClear(alterDatabaseCharsetHelper); + if (addDatabaseCharsetHelper) SPClear(addDatabaseCharsetHelper); [super dealloc]; } diff --git a/Source/SPDatabaseStructure.m b/Source/SPDatabaseStructure.m index 70d0aee5..b34522c5 100644 --- a/Source/SPDatabaseStructure.m +++ b/Source/SPDatabaseStructure.m @@ -573,9 +573,9 @@ pthread_mutex_destroy(&dataLock); pthread_mutex_destroy(&connectionCheckLock); - if (mySQLConnection) [mySQLConnection release], mySQLConnection = nil; - if (structure) [structure release], structure = nil; - if (allKeysofDbStructure) [allKeysofDbStructure release], allKeysofDbStructure = nil; + if (mySQLConnection) SPClear(mySQLConnection); + if (structure) SPClear(structure); + if (allKeysofDbStructure) SPClear(allKeysofDbStructure); [super dealloc]; } diff --git a/Source/SPDatabaseViewController.m b/Source/SPDatabaseViewController.m index 9b0ded39..c43761d3 100644 --- a/Source/SPDatabaseViewController.m +++ b/Source/SPDatabaseViewController.m @@ -332,7 +332,7 @@ if (!aTable) { // Update the selected table name and type - if (selectedTableName) [selectedTableName release], selectedTableName = nil; + if (selectedTableName) SPClear(selectedTableName); selectedTableType = SPTableTypeNone; diff --git a/Source/SPDotExporter.m b/Source/SPDotExporter.m index 249851ea..5f1dbd42 100644 --- a/Source/SPDotExporter.m +++ b/Source/SPDotExporter.m @@ -231,12 +231,12 @@ { delegate = nil; - [dotExportTables release], dotExportTables = nil; - [dotExportCurrentTable release], dotExportCurrentTable = nil; - [dotTableData release], dotTableData = nil; - [dotDatabaseHost release], dotDatabaseHost = nil; - [dotDatabaseName release], dotDatabaseName = nil; - [dotDatabaseVersion release], dotDatabaseVersion = nil; + SPClear(dotExportTables); + SPClear(dotExportCurrentTable); + SPClear(dotTableData); + SPClear(dotDatabaseHost); + SPClear(dotDatabaseName); + SPClear(dotDatabaseVersion); [super dealloc]; } diff --git a/Source/SPEditorPreferencePane.m b/Source/SPEditorPreferencePane.m index 08a833c2..7eaecf47 100644 --- a/Source/SPEditorPreferencePane.m +++ b/Source/SPEditorPreferencePane.m @@ -209,7 +209,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; if (![fm fileExistsAtPath:selectedPath isDirectory:nil]) { if ([fm copyItemAtPath:[NSString stringWithFormat:@"%@/%@.%@", themePath, [editThemeListItems objectAtIndex:[editThemeListTable selectedRow]], SPColorThemeFileExtension] toPath:selectedPath error:nil]) { - if (editThemeListItems) [editThemeListItems release], editThemeListItems = nil; + if (editThemeListItems) SPClear(editThemeListItems); editThemeListItems = [[NSArray arrayWithArray:[self _getAvailableThemes]] retain]; @@ -243,7 +243,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; [prefs setObject:SPCustomColorSchemeName forKey:SPCustomQueryEditorThemeName]; } - if (editThemeListItems) [editThemeListItems release], editThemeListItems = nil; + if (editThemeListItems) SPClear(editThemeListItems); editThemeListItems = [[NSArray arrayWithArray:[self _getAvailableThemes]] retain]; @@ -313,7 +313,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; { [[NSColorPanel sharedColorPanel] close]; - if (editThemeListItems) [editThemeListItems release], editThemeListItems = nil; + if (editThemeListItems) SPClear(editThemeListItems); editThemeListItems = [[NSArray arrayWithArray:[self _getAvailableThemes]] retain]; @@ -595,7 +595,7 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; } // Reload everything needed - if (editThemeListItems) [editThemeListItems release], editThemeListItems = nil; + if (editThemeListItems) SPClear(editThemeListItems); editThemeListItems = [[NSArray arrayWithArray:[self _getAvailableThemes]] retain]; [editThemeListTable reloadData]; @@ -1029,10 +1029,10 @@ static NSString *SPCustomColorSchemeNameLC = @"user-defined"; */ - (void)dealloc { - if (themePath) [themePath release], themePath = nil; - if (editThemeListItems) [editThemeListItems release], editThemeListItems = nil; - if (editorColors) [editorColors release], editorColors = nil; - if (editorNameForColors) [editorNameForColors release], editorNameForColors = nil; + if (themePath) SPClear(themePath); + if (editThemeListItems) SPClear(editThemeListItems); + if (editorColors) SPClear(editorColors); + if (editorNameForColors) SPClear(editorNameForColors); [super dealloc]; } diff --git a/Source/SPExportController.m b/Source/SPExportController.m index 4a97ae00..752e8521 100644 --- a/Source/SPExportController.m +++ b/Source/SPExportController.m @@ -1039,13 +1039,13 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; - (void)dealloc { - [tables release], tables = nil; - [exporters release], exporters = nil; - [exportFiles release], exportFiles = nil; - [operationQueue release], operationQueue = nil; - [exportFilename release], exportFilename = nil; + SPClear(tables); + SPClear(exporters); + SPClear(exportFiles); + SPClear(operationQueue); + SPClear(exportFilename); - if (previousConnectionEncoding) [previousConnectionEncoding release], previousConnectionEncoding = nil; + if (previousConnectionEncoding) SPClear(previousConnectionEncoding); [super dealloc]; } diff --git a/Source/SPExportFile.m b/Source/SPExportFile.m index c33aa076..132e1028 100644 --- a/Source/SPExportFile.m +++ b/Source/SPExportFile.m @@ -226,7 +226,7 @@ - (void)dealloc { - if (exportFileHandle) [exportFileHandle release], exportFileHandle = nil; + if (exportFileHandle) SPClear(exportFileHandle); [super dealloc]; } diff --git a/Source/SPExportInitializer.m b/Source/SPExportInitializer.m index 9c626a53..26cdd0dc 100644 --- a/Source/SPExportInitializer.m +++ b/Source/SPExportInitializer.m @@ -99,7 +99,7 @@ NSArray *dataArray = nil; // Get rid of the cached connection encoding - if (previousConnectionEncoding) [previousConnectionEncoding release], previousConnectionEncoding = nil; + if (previousConnectionEncoding) SPClear(previousConnectionEncoding); createCustomFilename = ([[exportCustomFilenameTokenField stringValue] length] > 0); diff --git a/Source/SPExporter.m b/Source/SPExporter.m index 7ec577b6..195d900d 100644 --- a/Source/SPExporter.m +++ b/Source/SPExporter.m @@ -103,9 +103,9 @@ */ - (void)dealloc { - if (exportData) [exportData release], exportData = nil; - if (connection) [connection release], connection = nil; - if (exportOutputFile) [exportOutputFile release], exportOutputFile = nil; + if (exportData) SPClear(exportData); + if (connection) SPClear(connection); + if (exportOutputFile) SPClear(exportOutputFile); [super dealloc]; } diff --git a/Source/SPExtendedTableInfo.m b/Source/SPExtendedTableInfo.m index 2e9eb9e2..3d27b821 100644 --- a/Source/SPExtendedTableInfo.m +++ b/Source/SPExtendedTableInfo.m @@ -720,7 +720,7 @@ static NSString *SPMySQLCommentField = @"Comment"; { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [connection release], connection = nil; + SPClear(connection); [super dealloc]; } diff --git a/Source/SPFavoriteNode.m b/Source/SPFavoriteNode.m index aabb01c5..b2b99c64 100644 --- a/Source/SPFavoriteNode.m +++ b/Source/SPFavoriteNode.m @@ -103,7 +103,7 @@ static NSString *SPFavoriteNodeKey = @"SPFavoriteNode"; - (void)dealloc { - if (nodeFavorite) [nodeFavorite release], nodeFavorite = nil; + if (nodeFavorite) SPClear(nodeFavorite); [super dealloc]; } diff --git a/Source/SPFavoritesController.m b/Source/SPFavoritesController.m index 76f376e8..ce6e5427 100644 --- a/Source/SPFavoritesController.m +++ b/Source/SPFavoritesController.m @@ -218,7 +218,7 @@ static SPFavoritesController *sharedFavoritesController = nil; NSError *error = nil; NSFileManager *fileManager = [NSFileManager defaultManager]; - if (favoritesData) [favoritesData release], favoritesData = nil; + if (favoritesData) SPClear(favoritesData); NSString *dataPath = [fileManager applicationSupportDirectoryForSubDirectory:SPDataSupportFolder error:&error]; @@ -468,8 +468,8 @@ static SPFavoritesController *sharedFavoritesController = nil; - (void)dealloc { - if (favoritesTree) [favoritesTree release], favoritesTree = nil; - if (favoritesData) [favoritesData release], favoritesData = nil; + if (favoritesTree) SPClear(favoritesTree); + if (favoritesData) SPClear(favoritesData); pthread_mutex_destroy(&writeLock); pthread_mutex_destroy(&favoritesLock); diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index 9048cfe9..c223faf4 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -477,7 +477,7 @@ [usedSheet makeFirstResponder:image == nil || _isGeometry ? editTextView : editImage]; } - if (stringValue) [stringValue release], stringValue = nil; + if (stringValue) SPClear(stringValue); editSheetWillBeInitialized = NO; diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m index 418a255f..9bef9d03 100644 --- a/Source/SPFieldMapperController.m +++ b/Source/SPFieldMapperController.m @@ -219,20 +219,20 @@ static NSUInteger SPSourceColumnTypeInteger = 1; - (void)dealloc { - if (mySQLConnection) [mySQLConnection release], mySQLConnection = nil; - if (sourcePath) [sourcePath release], sourcePath = nil; - if (fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil; - if (defaultFieldTypesForComboBox) [defaultFieldTypesForComboBox release], defaultFieldTypesForComboBox = nil; - if (fieldMappingTableTypes) [fieldMappingTableTypes release], fieldMappingTableTypes = nil; - if (fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil; - if (fieldMappingButtonOptions) [fieldMappingButtonOptions release], fieldMappingButtonOptions = nil; - if (fieldMappingOperatorOptions) [fieldMappingOperatorOptions release], fieldMappingOperatorOptions = nil; - if (fieldMappingOperatorArray) [fieldMappingOperatorArray release], fieldMappingOperatorArray = nil; - if (fieldMappingGlobalValues) [fieldMappingGlobalValues release], fieldMappingGlobalValues = nil; - if (fieldMappingGlobalValuesSQLMarked) [fieldMappingGlobalValuesSQLMarked release], fieldMappingGlobalValuesSQLMarked = nil; - if (fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil; - if (primaryKeyFields) [primaryKeyFields release], primaryKeyFields = nil; - if (toBeEditedRowIndexes) [toBeEditedRowIndexes release], toBeEditedRowIndexes = nil; + if (mySQLConnection) SPClear(mySQLConnection); + if (sourcePath) SPClear(sourcePath); + if (fieldMappingTableColumnNames) SPClear(fieldMappingTableColumnNames); + if (defaultFieldTypesForComboBox) SPClear(defaultFieldTypesForComboBox); + if (fieldMappingTableTypes) SPClear(fieldMappingTableTypes); + if (fieldMappingArray) SPClear(fieldMappingArray); + if (fieldMappingButtonOptions) SPClear(fieldMappingButtonOptions); + if (fieldMappingOperatorOptions) SPClear(fieldMappingOperatorOptions); + if (fieldMappingOperatorArray) SPClear(fieldMappingOperatorArray); + if (fieldMappingGlobalValues) SPClear(fieldMappingGlobalValues); + if (fieldMappingGlobalValuesSQLMarked) SPClear(fieldMappingGlobalValuesSQLMarked); + if (fieldMappingTableDefaultValues) SPClear(fieldMappingTableDefaultValues); + if (primaryKeyFields) SPClear(primaryKeyFields); + if (toBeEditedRowIndexes) SPClear(toBeEditedRowIndexes); [super dealloc]; } @@ -605,7 +605,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // Update the table view fieldMappingCurrentRow = 0; - if (fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil; + if (fieldMappingArray) SPClear(fieldMappingArray); [self setupFieldMappingArray]; [rowDownButton setEnabled:NO]; [rowUpButton setEnabled:([fieldMappingImportArray count] > 1)]; @@ -912,7 +912,7 @@ static NSUInteger SPSourceColumnTypeInteger = 1; // Update the table view fieldMappingCurrentRow = 0; - if (fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil; + if (fieldMappingArray) SPClear(fieldMappingArray); [self setupFieldMappingArray]; [rowDownButton setEnabled:NO]; [rowUpButton setEnabled:([fieldMappingImportArray count] > 1)]; diff --git a/Source/SPGeneralPreferencePane.m b/Source/SPGeneralPreferencePane.m index 7879b9f0..a1c024e7 100644 --- a/Source/SPGeneralPreferencePane.m +++ b/Source/SPGeneralPreferencePane.m @@ -208,7 +208,7 @@ static NSString *SPDatabaseImage = @"database-small"; - (void)dealloc { - [folderImage release], folderImage = nil; + SPClear(folderImage); [super dealloc]; } diff --git a/Source/SPGotoDatabaseController.m b/Source/SPGotoDatabaseController.m index 3f9a4730..5e8a4fb2 100644 --- a/Source/SPGotoDatabaseController.m +++ b/Source/SPGotoDatabaseController.m @@ -265,8 +265,8 @@ - (void)dealloc { - [unfilteredList release], unfilteredList = nil; - [filteredList release], filteredList = nil; + SPClear(unfilteredList); + SPClear(filteredList); [super dealloc]; } diff --git a/Source/SPGroupNode.m b/Source/SPGroupNode.m index debc0b84..4d90c0c1 100644 --- a/Source/SPGroupNode.m +++ b/Source/SPGroupNode.m @@ -108,7 +108,7 @@ static NSString *SPGroupNodeIsExpandedKey = @"SPGroupNodeIsExpanded"; - (void)dealloc { - if (nodeName) [nodeName release], nodeName = nil; + if (nodeName) SPClear(nodeName); [super dealloc]; } diff --git a/Source/SPGrowlController.m b/Source/SPGrowlController.m index f363208c..be659041 100644 --- a/Source/SPGrowlController.m +++ b/Source/SPGrowlController.m @@ -143,7 +143,7 @@ static SPGrowlController *sharedGrowlController = nil; postNotification = YES; } - [timingNotificationName release], timingNotificationName = nil; + SPClear(timingNotificationName); } // Post notification only if preference is set and visibility has been confirmed @@ -192,7 +192,7 @@ static SPGrowlController *sharedGrowlController = nil; - (void)setVisibilityForNotificationName:(NSString *)name { if (timingNotificationName) { - [timingNotificationName release], timingNotificationName = nil; + SPClear(timingNotificationName); } timingNotificationName = [[NSString alloc] initWithString:name]; diff --git a/Source/SPIndexesController.m b/Source/SPIndexesController.m index 7236a977..5cca12f9 100644 --- a/Source/SPIndexesController.m +++ b/Source/SPIndexesController.m @@ -219,7 +219,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; // If no initial field has been selected yet - all fields are indexed - add the first field. if (!initialField) initialField = [fields objectAtIndex:0]; - if (indexedFieldNames) [indexedFieldNames release], indexedFieldNames = nil; + if (indexedFieldNames) SPClear(indexedFieldNames); // Reset the indexed columns [indexedFields removeAllObjects]; @@ -1081,14 +1081,14 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; - (void)dealloc { - [table release], table = nil; - [indexes release], indexes = nil; - [fields release], fields = nil; + SPClear(table); + SPClear(indexes); + SPClear(fields); - [supportsLength release], supportsLength = nil; - [requiresLength release], requiresLength = nil; + SPClear(supportsLength); + SPClear(requiresLength); - if (indexedFields) [indexedFields release], indexedFields = nil; + if (indexedFields) SPClear(indexedFields); #ifndef SP_CODA [prefs removeObserver:self forKeyPath:SPDisplayTableViewVerticalGridlines]; diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m index 1b0128ca..cb1ba20b 100644 --- a/Source/SPNarrowDownCompletion.m +++ b/Source/SPNarrowDownCompletion.m @@ -206,7 +206,7 @@ [stateTimer invalidate]; [stateTimer release]; stateTimer = nil; - if(syncArrowImages) [syncArrowImages release], syncArrowImages = nil; + if(syncArrowImages) SPClear(syncArrowImages); [self performSelectorOnMainThread:@selector(reInvokeCompletion) withObject:nil waitUntilDone:YES]; closeMe = YES; return; diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index 07feee86..e4bdd1ec 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -560,7 +560,6 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte if([[item componentsSeparatedByString:SPUniqueSchemaDelimiter] count] < 4) [arr addObject:item]; } - if([arr count] < 1 ) @[@0, @""]; if([arr count] == 1) { NSArray *split = [[arr objectAtIndex:0] componentsSeparatedByString:SPUniqueSchemaDelimiter]; if([split count] == 2 ) [NSArray arrayWithObjects:@1, [split lastObject], nil]; diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m index d28dfcb9..ae407312 100644 --- a/Source/SPPreferenceController.m +++ b/Source/SPPreferenceController.m @@ -232,7 +232,7 @@ - (void)dealloc { - [preferencePanes release], preferencePanes = nil; + SPClear(preferencePanes); [super dealloc]; } diff --git a/Source/SPProcessListController.m b/Source/SPProcessListController.m index f24a7891..5f8a422e 100644 --- a/Source/SPProcessListController.m +++ b/Source/SPProcessListController.m @@ -500,7 +500,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; { // If the filtered array is allocated and it's not a reference to the processes array get rid of it if ((processesFiltered) && (processesFiltered != processes)) { - [processesFiltered release], processesFiltered = nil; + SPClear(processesFiltered); } // Kill the auto refresh timer if running @@ -554,7 +554,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; // If the auto refresh timer is running, kill it if (autoRefreshTimer && [autoRefreshTimer isValid]) { [autoRefreshTimer invalidate]; - [autoRefreshTimer release], autoRefreshTimer = nil; + SPClear(autoRefreshTimer); } } @@ -710,7 +710,7 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; // If the filtered array is allocated and its not a reference to the processes array, // relase it to prevent memory leaks upon the next allocation. if ((processesFiltered) && (processesFiltered != processes)) { - [processesFiltered release], processesFiltered = nil; + SPClear(processesFiltered); } processesFiltered = [[NSMutableArray alloc] init]; @@ -763,9 +763,9 @@ static NSString *SPTableViewIDColumnIdentifier = @"Id"; processListThreadRunning = NO; - [processes release], processes = nil; + SPClear(processes); - if (autoRefreshTimer) [autoRefreshTimer release], autoRefreshTimer = nil; + if (autoRefreshTimer) SPClear(autoRefreshTimer); [super dealloc]; } diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m index c08aec3e..4aba3a14 100644 --- a/Source/SPQueryController.m +++ b/Source/SPQueryController.m @@ -645,20 +645,20 @@ static SPQueryController *sharedQueryController = nil; [NSObject cancelPreviousPerformRequestsWithTarget:self]; #ifndef SP_CODA - [dateFormatter release], dateFormatter = nil; + SPClear(dateFormatter); - [messagesFullSet release], messagesFullSet = nil; - [messagesFilteredSet release], messagesFilteredSet = nil; - [activeFilterString release], activeFilterString = nil; + SPClear(messagesFullSet); + SPClear(messagesFilteredSet); + SPClear(activeFilterString); - [favoritesContainer release], favoritesContainer = nil; - [historyContainer release], historyContainer = nil; - [contentFilterContainer release], contentFilterContainer = nil; + SPClear(favoritesContainer); + SPClear(historyContainer); + SPClear(contentFilterContainer); #endif - if (completionKeywordList) [completionKeywordList release], completionKeywordList = nil; - if (completionFunctionList) [completionFunctionList release], completionFunctionList = nil; - if (functionArgumentSnippets) [functionArgumentSnippets release], functionArgumentSnippets = nil; + if (completionKeywordList) SPClear(completionKeywordList); + if (completionFunctionList) SPClear(completionFunctionList); + if (functionArgumentSnippets) SPClear(functionArgumentSnippets); #ifndef SP_CODA pthread_mutex_destroy(&consoleLock); diff --git a/Source/SPSQLExporter.m b/Source/SPSQLExporter.m index 9fd57e6d..f9dde93c 100644 --- a/Source/SPSQLExporter.m +++ b/Source/SPSQLExporter.m @@ -910,12 +910,12 @@ - (void)dealloc { - [sqlExportTables release], sqlExportTables = nil; - [sqlDatabaseHost release], sqlDatabaseHost = nil; - [sqlDatabaseName release], sqlDatabaseName = nil; - [sqlExportCurrentTable release], sqlExportCurrentTable = nil; - [sqlDatabaseVersion release], sqlDatabaseVersion = nil; - [sqlExportErrors release], sqlExportErrors = nil; + SPClear(sqlExportTables); + SPClear(sqlDatabaseHost); + SPClear(sqlDatabaseName); + SPClear(sqlExportCurrentTable); + SPClear(sqlDatabaseVersion); + SPClear(sqlExportErrors); [super dealloc]; } diff --git a/Source/SPSQLParser.m b/Source/SPSQLParser.m index d9162a66..a7a3ee98 100644 --- a/Source/SPSQLParser.m +++ b/Source/SPSQLParser.m @@ -1021,7 +1021,7 @@ TO_BUFFER_STATE to_scan_string (const char *); } - (void) setString:(NSString *)aString { [string setString:aString]; - if (delimiter) [delimiter release], delimiter = nil; + if (delimiter) SPClear(delimiter); delimiterLengthMinusOne = 0; lastMatchIsDelimiter = NO; [self _clearCharCache]; diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index 20f1aa43..c9a214ab 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -126,8 +126,8 @@ { // As this object is not a NSWindowController, use manual top-level nib item management - if (sshQuestionDialog) [sshQuestionDialog release], sshQuestionDialog = nil; - if (sshPasswordDialog) [sshPasswordDialog release], sshPasswordDialog = nil; + if (sshQuestionDialog) SPClear(sshQuestionDialog); + if (sshPasswordDialog) SPClear(sshPasswordDialog); parentWindow = theWindow; if (![NSBundle loadNibNamed:@"SSHQuestionDialog" owner:self]) { @@ -167,7 +167,7 @@ */ - (BOOL)setPasswordKeychainName:(NSString *)theName account:(NSString *)theAccount { - if (password) [password release], password = nil; + if (password) SPClear(password); passwordInKeychain = YES; keychainName = [[NSString alloc] initWithString:theName]; @@ -420,8 +420,8 @@ [task waitUntilExit]; // On tunnel close, clean up, ready for re-use if the delegate reconnects. - [task release], task = nil; - [standardError release], standardError = nil; + SPClear(task); + SPClear(standardError); [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSFileHandleDataAvailableNotification" object:nil]; @@ -438,8 +438,8 @@ // Run the run loop for a short time to ensure all task/pipe callbacks are dealt with [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; - [taskEnvironment release], taskEnvironment = nil; - [taskArguments release], taskArguments = nil; + SPClear(taskEnvironment); + SPClear(taskArguments); [pool release]; } @@ -647,7 +647,7 @@ NSString *thePassword = nil; if (requestedPassphrase) { thePassword = [NSString stringWithString:requestedPassphrase]; - [requestedPassphrase release], requestedPassphrase = nil; + SPClear(requestedPassphrase); } // Unlock the lock again @@ -747,8 +747,8 @@ if (identityFilePath) [identityFilePath release]; // As this object is not a NSWindowController, use manual top-level nib item management - if (sshQuestionDialog) [sshQuestionDialog release], sshQuestionDialog = nil; - if (sshPasswordDialog) [sshPasswordDialog release], sshPasswordDialog = nil; + if (sshQuestionDialog) SPClear(sshQuestionDialog); + if (sshPasswordDialog) SPClear(sshPasswordDialog); [super dealloc]; } diff --git a/Source/SPServerVariablesController.m b/Source/SPServerVariablesController.m index 090970fb..dade0687 100644 --- a/Source/SPServerVariablesController.m +++ b/Source/SPServerVariablesController.m @@ -115,7 +115,7 @@ // If the filtered array is allocated and it's not a reference to the processes array get rid of it if ((variablesFiltered) && (variablesFiltered != variables)) { - [variablesFiltered release], variablesFiltered = nil; + SPClear(variablesFiltered); } } @@ -292,7 +292,7 @@ // If the filtered array is allocated and its not a reference to the variables array // relase it to prevent memory leaks upon the next allocation. if ((variablesFiltered) && (variablesFiltered != variables)) { - [variablesFiltered release], variablesFiltered = nil; + SPClear(variablesFiltered); } variablesFiltered = [[NSMutableArray alloc] init]; @@ -381,7 +381,7 @@ { [prefs removeObserver:self forKeyPath:SPUseMonospacedFonts]; - [variables release], variables = nil; + SPClear(variables); [super dealloc]; } diff --git a/Source/SPSplitView.m b/Source/SPSplitView.m index 9d5b59d8..599432cf 100644 --- a/Source/SPSplitView.m +++ b/Source/SPSplitView.m @@ -108,8 +108,8 @@ [viewMinimumSizes release]; [viewMaximumSizes release]; - if (animationTimer) [animationTimer invalidate], [animationTimer release], animationTimer = nil; - if (animationRetainCycleBypassObject) [animationRetainCycleBypassObject release], animationRetainCycleBypassObject = nil; + if (animationTimer) [animationTimer invalidate], SPClear(animationTimer); + if (animationRetainCycleBypassObject) SPClear(animationRetainCycleBypassObject); [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; @@ -233,8 +233,8 @@ // Otherwise, start an animation. } else { - if (animationTimer) [animationTimer invalidate], [animationTimer release], animationTimer = nil; - if (animationRetainCycleBypassObject) [animationRetainCycleBypassObject release], animationRetainCycleBypassObject = nil; + if (animationTimer) [animationTimer invalidate], SPClear(animationTimer); + if (animationRetainCycleBypassObject) SPClear(animationRetainCycleBypassObject); animationStartTime = [NSDate monotonicTimeInterval]; // Determine the animation length, in seconds, starting with a quarter of a second @@ -853,8 +853,8 @@ // If the animation has reached the end, ensure completion tasks are run if (animationProgress == 1) { - if (animationTimer) [animationTimer invalidate], [animationTimer release], animationTimer = nil; - if (animationRetainCycleBypassObject) [animationRetainCycleBypassObject release], animationRetainCycleBypassObject = nil; + if (animationTimer) [animationTimer invalidate], SPClear(animationTimer); + if (animationRetainCycleBypassObject) SPClear(animationRetainCycleBypassObject); // If uncollapsing, restore the original view and remove the helper if (!collapsibleSubviewCollapsed) { @@ -1132,12 +1132,12 @@ [[wrappedView window] makeFirstResponder:firstResponderToRestore]; } - [wrappedView release], wrappedView = nil; + SPClear(wrappedView); } - (void)dealloc { - if (wrappedView) [wrappedView release], wrappedView = nil; + if (wrappedView) SPClear(wrappedView); [super dealloc]; } diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index d904ab73..b0d0f03c 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -407,7 +407,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper #endif // Reset table key store for use in argumentForRow: - if (keys) [keys release], keys = nil; + if (keys) SPClear(keys); // Reset data column store [dataColumns removeAllObjects]; @@ -425,7 +425,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // Otherwise store the newly selected table name and reset the data } else { - if (selectedTable) [selectedTable release], selectedTable = nil; + if (selectedTable) SPClear(selectedTable); if (newTableName) selectedTable = [[NSString alloc] initWithString:newTableName]; previousTableRowsCount = 0; contentPage = 1; @@ -1509,7 +1509,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // If a string was supplied, use a custom query from that URL scheme else if([sender isKindOfClass:[NSString class]] && [(NSString *)sender length]) { - if(schemeFilter) [schemeFilter release], schemeFilter = nil; + if(schemeFilter) SPClear(schemeFilter); schemeFilter = [sender retain]; activeFilter = 2; } @@ -3942,7 +3942,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper */ - (void) setSortColumnNameToRestore:(NSString *)theSortColumnName isAscending:(BOOL)isAscending { - if (sortColumnToRestore) [sortColumnToRestore release], sortColumnToRestore = nil; + if (sortColumnToRestore) SPClear(sortColumnToRestore); if (theSortColumnName) { sortColumnToRestore = [[NSString alloc] initWithString:theSortColumnName]; @@ -3963,7 +3963,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper */ - (void) setSelectionToRestore:(NSDictionary *)theSelection { - if (selectionToRestore) [selectionToRestore release], selectionToRestore = nil; + if (selectionToRestore) SPClear(selectionToRestore); if (theSelection) selectionToRestore = [theSelection copy]; } @@ -3981,11 +3981,11 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper */ - (void) setFiltersToRestore:(NSDictionary *)filterSettings { - if (filterFieldToRestore) [filterFieldToRestore release], filterFieldToRestore = nil; - if (filterComparisonToRestore) [filterComparisonToRestore release], filterComparisonToRestore = nil; - if (filterValueToRestore) [filterValueToRestore release], filterValueToRestore = nil; - if (firstBetweenValueToRestore) [firstBetweenValueToRestore release], firstBetweenValueToRestore = nil; - if (secondBetweenValueToRestore) [secondBetweenValueToRestore release], secondBetweenValueToRestore = nil; + if (filterFieldToRestore) SPClear(filterFieldToRestore); + if (filterComparisonToRestore) SPClear(filterComparisonToRestore); + if (filterValueToRestore) SPClear(filterValueToRestore); + if (firstBetweenValueToRestore) SPClear(firstBetweenValueToRestore); + if (secondBetweenValueToRestore) SPClear(secondBetweenValueToRestore); if (filterSettings) { if ([filterSettings objectForKey:@"filterField"]) @@ -4311,7 +4311,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper [NSObject cancelPreviousPerformRequestsWithTarget:self]; [NSObject cancelPreviousPerformRequestsWithTarget:tableContentView]; - if(fieldEditor) [fieldEditor release], fieldEditor = nil; + if(fieldEditor) SPClear(fieldEditor); [self clearTableLoadTimer]; [tableLoadingCondition release]; diff --git a/Source/SPTableContentDelegate.m b/Source/SPTableContentDelegate.m index 0a624efc..b73282ec 100644 --- a/Source/SPTableContentDelegate.m +++ b/Source/SPTableContentDelegate.m @@ -295,7 +295,7 @@ fieldEncoding = [columnDefinition objectForKey:@"charset_name"]; } - if (fieldEditor) [fieldEditor release], fieldEditor = nil; + if (fieldEditor) SPClear(fieldEditor); fieldEditor = [[SPFieldEditorController alloc] init]; diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 0e340f49..86243956 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -520,7 +520,7 @@ // connection reconnect dialog to appear and the user chose to close the connection. if (!syntaxResult) return nil; - if (tableCreateSyntax != nil) [tableCreateSyntax release], tableCreateSyntax = nil; + if (tableCreateSyntax != nil) SPClear(tableCreateSyntax); // A NULL value indicates that the user does not have permission to view the syntax if ([[syntaxResult objectAtIndex:1] isNSNull]) { @@ -864,7 +864,7 @@ } // Retrieve the table syntax string - if (tableCreateSyntax) [tableCreateSyntax release], tableCreateSyntax = nil; + if (tableCreateSyntax) SPClear(tableCreateSyntax); NSString *syntaxString = [[theResult getRowAsArray] objectAtIndex:1]; // A NULL value indicates that the user does not have permission to view the syntax @@ -1086,7 +1086,7 @@ nil, nil, [NSApp mainWindow], self, nil, nil, [NSString stringWithFormat:NSLocalizedString(@"An error occurred while retrieving the trigger information for table '%@'. Please try again.\n\nMySQL said: %@", @"error retrieving table information informative message"), [tableListInstance tableName], [mySQLConnection lastErrorMessage]]); - if (triggers) [triggers release], triggers = nil; + if (triggers) SPClear(triggers); if (changeEncoding) [mySQLConnection restoreStoredEncoding]; } diff --git a/Source/SPTableFieldValidation.m b/Source/SPTableFieldValidation.m index e3c7f706..97c55a93 100644 --- a/Source/SPTableFieldValidation.m +++ b/Source/SPTableFieldValidation.m @@ -136,7 +136,7 @@ - (void)dealloc { - [fieldTypes release], fieldTypes = nil; + SPClear(fieldTypes); [super dealloc]; } diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index f82dd3e7..2374ea81 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -666,8 +666,8 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; [[NSNotificationCenter defaultCenter] removeObserver:self]; [[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:SPUseMonospacedFonts]; - [relationData release], relationData = nil; - [takenConstraintNames release], takenConstraintNames = nil; + SPClear(relationData); + SPClear(takenConstraintNames); [super dealloc]; } diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 9013fb05..77e5c77b 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -1479,7 +1479,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [typeSuggestions release]; [extraFieldSuggestions release]; - [fieldValidation release], fieldValidation = nil; + SPClear(fieldValidation); if (defaultValues) [defaultValues release]; if (selectedTable) [selectedTable release]; diff --git a/Source/SPTableStructureLoading.m b/Source/SPTableStructureLoading.m index a15d31cd..1950c32e 100644 --- a/Source/SPTableStructureLoading.m +++ b/Source/SPTableStructureLoading.m @@ -312,7 +312,7 @@ ![tableDocumentInstance isWorking]; // Update the selected table name - if (selectedTable) [selectedTable release], selectedTable = nil; + if (selectedTable) SPClear(selectedTable); if (newTableName) selectedTable = [[NSString alloc] initWithString:newTableName]; [indexesController setTable:selectedTable]; @@ -348,7 +348,7 @@ [indexesController setFields:tableFields]; [indexesController setIndexes:[tableDetails objectForKey:@"tableIndexes"]]; - if (defaultValues) [defaultValues release], defaultValues = nil; + if (defaultValues) SPClear(defaultValues); newDefaultValues = [NSMutableDictionary dictionaryWithCapacity:[tableFields count]]; diff --git a/Source/SPTableTriggers.m b/Source/SPTableTriggers.m index 1ab39825..179e509e 100644 --- a/Source/SPTableTriggers.m +++ b/Source/SPTableTriggers.m @@ -632,8 +632,8 @@ static const NSString *SPTriggerSQLMode = @"TriggerSQLMode"; - (void)dealloc { - [triggerData release], triggerData = nil; - [editedTrigger release], editedTrigger = nil; + SPClear(triggerData); + SPClear(editedTrigger); [[NSNotificationCenter defaultCenter] removeObserver:self]; [prefs removeObserver:self forKeyPath:SPUseMonospacedFonts]; diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 3efc45ef..147aec52 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -1314,7 +1314,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; - (NSMutableArray *)_allSchemaObjectsOfType:(SPTableType)type { NSMutableArray *returnArray = [NSMutableArray array]; - NSUInteger i; + NSInteger i; NSInteger cnt = [[self tables] count]; for(i=0; i 1) { [tablesListView deselectAll:self]; - if (selectedTableName) [selectedTableName release], selectedTableName = nil; + if (selectedTableName) SPClear(selectedTableName); } #ifndef SP_CODA diff --git a/Source/SPThreadAdditions.m b/Source/SPThreadAdditions.m index 74476888..f61b6289 100644 --- a/Source/SPThreadAdditions.m +++ b/Source/SPThreadAdditions.m @@ -88,9 +88,9 @@ - (void)dealloc { - [object release], object = nil; + SPClear(object); selector = NULL; - [name release], name = nil; + SPClear(name); [super dealloc]; } diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m index abfac606..bf78ab6f 100644 --- a/Source/SPUserManager.m +++ b/Source/SPUserManager.m @@ -848,7 +848,7 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; - (void)_clearData { [managedObjectContext reset]; - [managedObjectContext release], managedObjectContext = nil; + SPClear(managedObjectContext); } /** @@ -1458,18 +1458,20 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - - [managedObjectContext release]; - [persistentStoreCoordinator release]; - [managedObjectModel release]; - [privColumnToGrantMap release]; - [connection release]; - [privsSupportedByServer release]; - [schemas release]; - [availablePrivs release]; - [grantedSchemaPrivs release]; - [treeSortDescriptor release]; - [serverSupport release]; + + + SPClear(managedObjectContext); + SPClear(persistentStoreCoordinator); + SPClear(managedObjectModel); + SPClear(privColumnToGrantMap); + SPClear(connection); + SPClear(privsSupportedByServer); + SPClear(schemas); + SPClear(availablePrivs); + SPClear(grantedSchemaPrivs); + SPClear(treeSortDescriptor); + SPClear(treeSortDescriptors); + SPClear(serverSupport); [super dealloc]; } diff --git a/Source/SPXMLExporter.m b/Source/SPXMLExporter.m index 5aefd80b..dd4e9223 100644 --- a/Source/SPXMLExporter.m +++ b/Source/SPXMLExporter.m @@ -358,9 +358,9 @@ - (void)dealloc { - if (xmlDataArray) [xmlDataArray release], xmlDataArray = nil; - if (xmlTableName) [xmlTableName release], xmlTableName = nil; - if (xmlNULLString) [xmlNULLString release], xmlNULLString = nil; + if (xmlDataArray) SPClear(xmlDataArray); + if (xmlTableName) SPClear(xmlTableName); + if (xmlNULLString) SPClear(xmlNULLString); [super dealloc]; } -- cgit v1.2.3 From 5b55d8c4d24b0c24a5dc74a49cfd70448146d582 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 4 Jan 2015 21:10:26 +0100 Subject: Replace some "magic numbers" with constants --- Source/SPConstants.h | 8 ++++++++ Source/SPDatabaseDocument.m | 12 ++++++------ Source/SPWindowController.m | 4 ++-- 3 files changed, 16 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index f0350f07..a2df5bde 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -148,6 +148,14 @@ typedef enum { SPMainMenuSequelPro = 0, SPMainMenuFile = 1, + SPMainMenuFileSaveConnection = 1004, + SPMainMenuFileSaveConnectionAs = 1005, + SPMainMenuFileSaveQuery = 1006, + SPMainMenuFileSaveQueryAs = 1008, + SPMainMenuFileSaveSession = 1020, + SPMainMenuFileSaveSessionAs = 1021, + SPMainMenuFileClose = 1003, + SPMainMenuFileCloseTab = 1103, SPMainMenuEdit = 2, SPMainMenuView = 3, SPMainMenuDatabase = 4, diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 6940abfb..ab8eafc6 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -2831,10 +2831,10 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [panel setCanSelectHiddenExtension:YES]; // Save Query... - if (sender != nil && ([sender tag] == 1006 || [sender tag] == 1008)) { + if (sender != nil && ([sender tag] == SPMainMenuFileSaveQuery || [sender tag] == SPMainMenuFileSaveQueryAs)) { // If Save was invoked, check whether the file was previously opened, and if so save without the panel - if ([sender tag] == 1006 && [[[self sqlFileURL] path] length]) { + if ([sender tag] == SPMainMenuFileSaveQuery && [[[self sqlFileURL] path] length]) { NSError *error = nil; NSString *content = [NSString stringWithString:[[[customQueryInstance valueForKeyPath:@"textView"] textStorage] string]]; [content writeToURL:sqlFileURL atomically:YES encoding:sqlFileEncoding error:&error]; @@ -2865,11 +2865,11 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // Save As… or Save } - else if (sender == nil || [sender tag] == 1005 || [sender tag] == 1004) { + else if (sender == nil || [sender tag] == SPMainMenuFileSaveConnection || [sender tag] == SPMainMenuFileSaveConnectionAs) { // If Save was invoked check for fileURL and Untitled docs and save the spf file without save panel // otherwise ask for file name - if (sender != nil && [sender tag] == 1004 && [[[self fileURL] path] length] && ![self isUntitled]) { + if (sender != nil && [sender tag] == SPMainMenuFileSaveConnection && [[[self fileURL] path] length] && ![self isUntitled]) { [self saveDocumentWithFilePath:nil inBackground:YES onlyPreferences:NO contextInfo:nil]; return; } @@ -2920,10 +2920,10 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; contextInfo = sender == nil ? @"saveSPFfileAndClose" : @"saveSPFfile"; } // Save Session or Save Session As... - else if (sender == nil || [sender tag] == 1020 || [sender tag] == 1021) + else if (sender == nil || [sender tag] == SPMainMenuFileSaveSession || [sender tag] == SPMainMenuFileSaveSessionAs) { // Save As Session - if ([sender tag] == 1020 && [SPAppDelegate sessionURL]) { + if ([sender tag] == SPMainMenuFileSaveSession && [SPAppDelegate sessionURL]) { [self saveConnectionPanelDidEnd:panel returnCode:1 contextInfo:@"saveAsSession"]; return; } diff --git a/Source/SPWindowController.m b/Source/SPWindowController.m index f90b423d..6edbb684 100644 --- a/Source/SPWindowController.m +++ b/Source/SPWindowController.m @@ -83,8 +83,8 @@ enum { [self _setUpTabBar]; // Retrieve references to the 'Close Window' and 'Close Tab' menus. These are updated as window focus changes. - closeWindowMenuItem = [[[[NSApp mainMenu] itemWithTag:SPMainMenuFile] submenu] itemWithTag:1003]; - closeTabMenuItem = [[[[NSApp mainMenu] itemWithTag:SPMainMenuFile] submenu] itemWithTag:1103]; + closeWindowMenuItem = [[[[NSApp mainMenu] itemWithTag:SPMainMenuFile] submenu] itemWithTag:SPMainMenuFileClose]; + closeTabMenuItem = [[[[NSApp mainMenu] itemWithTag:SPMainMenuFile] submenu] itemWithTag:SPMainMenuFileCloseTab]; // Register for drag start and stop notifications - used to show/hide tab bars [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabDragStarted:) name:PSMTabDragDidBeginNotification object:nil]; -- cgit v1.2.3 From e201531daa71ee1a2e2a0f927c619947126c9d3d Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 4 Jan 2015 21:15:43 +0100 Subject: Addition to commit 2735e15b --- Source/SPActivityTextFieldCell.m | 2 +- Source/SPAppController.m | 16 +++++----- Source/SPBundleCommandTextView.m | 4 +-- Source/SPBundleEditorController.m | 56 +++++++++++++++++------------------ Source/SPBundleHTMLOutputController.m | 2 +- Source/SPCSVParser.m | 22 +++++++------- Source/SPChooseMenuItemDialog.m | 2 +- Source/SPColorSelectorView.m | 2 +- Source/SPConnectionController.m | 21 +++++++------ Source/SPContentFilterManager.m | 2 +- Source/SPCopyTable.m | 4 +-- Source/SPCustomQuery.m | 31 +++++++++---------- Source/SPDataImport.m | 25 ++++++++-------- Source/SPDatabaseDocument.m | 3 +- Source/SPDatabaseStructure.m | 5 ++-- Source/SPFieldEditorController.m | 14 ++++----- Source/SPFileHandle.m | 4 +-- Source/SPHistoryController.m | 4 +-- Source/SPNarrowDownCompletion.m | 29 ++++++++---------- Source/SPNavigatorController.m | 28 +++++++++--------- Source/SPPrintController.m | 2 +- Source/SPQueryFavoriteManager.m | 2 +- Source/SPSQLParser.m | 7 ++--- Source/SPSSHTunnel.m | 29 +++++++++--------- Source/SPSplitView.m | 4 +-- Source/SPTableContent.m | 51 +++++++++++++++---------------- Source/SPTableData.m | 29 ++++++++---------- Source/SPTableInfo.m | 4 +-- Source/SPTableStructure.m | 14 ++++----- Source/SPTablesList.m | 18 +++++------ Source/SPTextAndLinkCell.m | 2 +- Source/SPTextView.m | 22 +++++++------- Source/SPTooltip.m | 6 ++-- Source/SPUserManager.m | 4 +-- Source/SPWindowController.m | 2 +- 35 files changed, 223 insertions(+), 249 deletions(-) (limited to 'Source') diff --git a/Source/SPActivityTextFieldCell.m b/Source/SPActivityTextFieldCell.m index b82fa995..b09454bb 100644 --- a/Source/SPActivityTextFieldCell.m +++ b/Source/SPActivityTextFieldCell.m @@ -327,7 +327,7 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) if(activityName) SPClear(activityName); if(activityInfo) SPClear(activityInfo); if(contextInfo) SPClear(contextInfo); - if(cancelButton) [cancelButton release]; + if(cancelButton) SPClear(cancelButton); [super dealloc]; } diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 87cf9f24..0840978d 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -2231,14 +2231,14 @@ { [[NSNotificationCenter defaultCenter] removeObserver:self]; - if (bundleItems) [bundleItems release]; - if (bundleUsedScopes) [bundleUsedScopes release]; - if (bundleHTMLOutputController) [bundleHTMLOutputController release]; - if (bundleCategories) [bundleCategories release]; - if (bundleTriggers) [bundleTriggers release]; - if (bundleKeyEquivalents) [bundleKeyEquivalents release]; - if (installedBundleUUIDs) [installedBundleUUIDs release]; - if (runningActivitiesArray) [runningActivitiesArray release]; + if (bundleItems) SPClear(bundleItems); + if (bundleUsedScopes) SPClear(bundleUsedScopes); + if (bundleHTMLOutputController) SPClear(bundleHTMLOutputController); + if (bundleCategories) SPClear(bundleCategories); + if (bundleTriggers) SPClear(bundleTriggers); + if (bundleKeyEquivalents) SPClear(bundleKeyEquivalents); + if (installedBundleUUIDs) SPClear(installedBundleUUIDs); + if (runningActivitiesArray) SPClear(runningActivitiesArray); SPClear(prefsController); diff --git a/Source/SPBundleCommandTextView.m b/Source/SPBundleCommandTextView.m index 9a2d2ba8..f8d4e53f 100644 --- a/Source/SPBundleCommandTextView.m +++ b/Source/SPBundleCommandTextView.m @@ -40,8 +40,8 @@ { [[NSNotificationCenter defaultCenter] removeObserver:self]; [prefs removeObserver:self forKeyPath:SPCustomQueryEditorTabStopWidth]; - [prefs release]; - [lineNumberView release]; + SPClear(prefs); + SPClear(lineNumberView); [super dealloc]; } diff --git a/Source/SPBundleEditorController.m b/Source/SPBundleEditorController.m index 69652bf1..01aca387 100644 --- a/Source/SPBundleEditorController.m +++ b/Source/SPBundleEditorController.m @@ -1090,8 +1090,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; // Remove temporary drag file if any if(draggedFilePath) { [[NSFileManager defaultManager] removeItemAtPath:draggedFilePath error:nil]; - [draggedFilePath release]; - draggedFilePath = nil; + SPClear(draggedFilePath); } if(oldBundleName) SPClear(oldBundleName); } @@ -1478,8 +1477,7 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; // Remove old temporary drag file if any if(draggedFilePath) { [[NSFileManager defaultManager] removeItemAtPath:draggedFilePath error:nil]; - [draggedFilePath release]; - draggedFilePath = nil; + SPClear(draggedFilePath); } NSImage *dragImage; @@ -2074,33 +2072,33 @@ static NSString *SPSaveBundleAction = @"SPSaveBundle"; - (void)dealloc { - [inputGeneralScopePopUpMenu release]; - [inputInputFieldScopePopUpMenu release]; - [inputDataTableScopePopUpMenu release]; - [outputGeneralScopePopUpMenu release]; - [outputInputFieldScopePopUpMenu release]; - [outputDataTableScopePopUpMenu release]; - [inputFallbackInputFieldScopePopUpMenu release]; - [triggerInputFieldPopUpMenu release]; - [triggerDataTablePopUpMenu release]; - [triggerGeneralPopUpMenu release]; - [withBlobDataTablePopUpMenu release]; - [inputNonePopUpMenu release]; + SPClear(inputGeneralScopePopUpMenu); + SPClear(inputInputFieldScopePopUpMenu); + SPClear(inputDataTableScopePopUpMenu); + SPClear(outputGeneralScopePopUpMenu); + SPClear(outputInputFieldScopePopUpMenu); + SPClear(outputDataTableScopePopUpMenu); + SPClear(inputFallbackInputFieldScopePopUpMenu); + SPClear(triggerInputFieldPopUpMenu); + SPClear(triggerDataTablePopUpMenu); + SPClear(triggerGeneralPopUpMenu); + SPClear(withBlobDataTablePopUpMenu); + SPClear(inputNonePopUpMenu); - [inputGeneralScopeArray release]; - [inputInputFieldScopeArray release]; - [inputDataTableScopeArray release]; - [outputGeneralScopeArray release]; - [outputInputFieldScopeArray release]; - [outputDataTableScopeArray release]; - [inputFallbackInputFieldScopeArray release]; - [triggerInputFieldArray release]; - [triggerDataTableArray release]; - [triggerGeneralArray release]; - [withBlobDataTableArray release]; + SPClear(inputGeneralScopeArray); + SPClear(inputInputFieldScopeArray); + SPClear(inputDataTableScopeArray); + SPClear(outputGeneralScopeArray); + SPClear(outputInputFieldScopeArray); + SPClear(outputDataTableScopeArray); + SPClear(inputFallbackInputFieldScopeArray); + SPClear(triggerInputFieldArray); + SPClear(triggerDataTableArray); + SPClear(triggerGeneralArray); + SPClear(withBlobDataTableArray); - [shellVariableSuggestions release]; - [deletedDefaultBundles release]; + SPClear(shellVariableSuggestions); + SPClear(deletedDefaultBundles); if (touchedBundleArray) SPClear(touchedBundleArray); if (commandBundleTree) SPClear(commandBundleTree); diff --git a/Source/SPBundleHTMLOutputController.m b/Source/SPBundleHTMLOutputController.m index ed1142a2..16a2f9da 100644 --- a/Source/SPBundleHTMLOutputController.m +++ b/Source/SPBundleHTMLOutputController.m @@ -126,7 +126,7 @@ static NSString *SPSaveDocumentAction = @"SPSaveDocument"; - (void)dealloc { - if(webPreferences) [webPreferences release]; + if(webPreferences) SPClear(webPreferences); [super dealloc]; } diff --git a/Source/SPCSVParser.m b/Source/SPCSVParser.m index 88a2fbb5..819c34b7 100644 --- a/Source/SPCSVParser.m +++ b/Source/SPCSVParser.m @@ -650,17 +650,17 @@ return self; } - (void) dealloc { - [csvString release]; - [fieldEndString release]; - [lineEndString release]; - [fieldQuoteString release]; - [escapeString release]; - [escapedFieldEndString release]; - [escapedLineEndString release]; - [escapedFieldQuoteString release]; - [escapedEscapeString release]; - if (nullReplacementString) [nullReplacementString release]; - if (skipCharacterSet) [skipCharacterSet release]; + SPClear(csvString); + SPClear(fieldEndString); + SPClear(lineEndString); + SPClear(fieldQuoteString); + SPClear(escapeString); + SPClear(escapedFieldEndString); + SPClear(escapedLineEndString); + SPClear(escapedFieldQuoteString); + SPClear(escapedEscapeString); + if (nullReplacementString) SPClear(nullReplacementString); + if (skipCharacterSet) SPClear(skipCharacterSet); [super dealloc]; } diff --git a/Source/SPChooseMenuItemDialog.m b/Source/SPChooseMenuItemDialog.m index 60b9ced3..8b7bf650 100644 --- a/Source/SPChooseMenuItemDialog.m +++ b/Source/SPChooseMenuItemDialog.m @@ -174,7 +174,7 @@ - (void)dealloc { - [dummyTextView release]; + SPClear(dummyTextView); [super dealloc]; } diff --git a/Source/SPColorSelectorView.m b/Source/SPColorSelectorView.m index 15b18596..f2eade86 100644 --- a/Source/SPColorSelectorView.m +++ b/Source/SPColorSelectorView.m @@ -424,7 +424,7 @@ enum trackingAreaIDs // ------------------------------------------------------------------------------- - (void)dealloc { - [trackingAreas release]; + SPClear(trackingAreas); [super dealloc]; } diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 651d3538..79a15a19 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -317,8 +317,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, // Cancel the SSH tunnel if present if (sshTunnel) { [sshTunnel disconnect]; - [sshTunnel release]; - sshTunnel = nil; + SPClear(sshTunnel); } #ifndef SP_CODA @@ -1848,7 +1847,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, mySQLConnection = nil; } - if (sshTunnel) [sshTunnel setConnectionStateChangeSelector:nil delegate:nil], [sshTunnel disconnect], [sshTunnel release]; + if (sshTunnel) [sshTunnel setConnectionStateChangeSelector:nil delegate:nil], SPClear(sshTunnel); } #pragma mark - @@ -1883,9 +1882,9 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, #endif #ifndef SP_CODA - [keychain release]; + SPClear(keychain); #endif - [prefs release]; + SPClear(prefs); #ifndef SP_CODA SPClear(folderImage); @@ -1895,13 +1894,13 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, for (id retainedObject in nibObjectsToRelease) [retainedObject release]; - [nibObjectsToRelease release]; + SPClear(nibObjectsToRelease); - if (connectionKeychainID) [connectionKeychainID release]; - if (connectionKeychainItemName) [connectionKeychainItemName release]; - if (connectionKeychainItemAccount) [connectionKeychainItemAccount release]; - if (connectionSSHKeychainItemName) [connectionSSHKeychainItemName release]; - if (connectionSSHKeychainItemAccount) [connectionSSHKeychainItemAccount release]; + if (connectionKeychainID) SPClear(connectionKeychainID); + if (connectionKeychainItemName) SPClear(connectionKeychainItemName); + if (connectionKeychainItemAccount) SPClear(connectionKeychainItemAccount); + if (connectionSSHKeychainItemName) SPClear(connectionSSHKeychainItemName); + if (connectionSSHKeychainItemAccount) SPClear(connectionSSHKeychainItemAccount); #ifndef SP_CODA if (currentFavorite) SPClear(currentFavorite); diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m index e35fd672..a8e747e2 100644 --- a/Source/SPContentFilterManager.m +++ b/Source/SPContentFilterManager.m @@ -975,7 +975,7 @@ static NSString *SPExportFilterAction = @"SPExportFilter"; - (void)dealloc { - [contentFilters release]; + SPClear(contentFilters); [super dealloc]; } diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m index 7aaae1a6..7f25d05f 100644 --- a/Source/SPCopyTable.m +++ b/Source/SPCopyTable.m @@ -1539,9 +1539,9 @@ static const NSInteger kBlobAsImageFile = 4; - (void)dealloc { - if (columnDefinitions) [columnDefinitions release]; + if (columnDefinitions) SPClear(columnDefinitions); #ifndef SP_CODA - [prefs release]; + SPClear(prefs); #endif [super dealloc]; diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 2114d766..8b3897fe 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -1465,8 +1465,7 @@ { if (queryLoadTimer) { [queryLoadTimer invalidate]; - [queryLoadTimer release]; - queryLoadTimer = nil; + SPClear(queryLoadTimer); } } @@ -2153,8 +2152,7 @@ // this is the same as saying (isDesc && !invert) || (!isDesc && invert) if (isDesc != invert) { - [sortField release]; - sortField = nil; + SPClear(sortField); } else { isDesc = !isDesc; } @@ -3681,8 +3679,7 @@ } if(fieldEditor) { - [fieldEditor release]; - fieldEditor = nil; + SPClear(fieldEditor); } // Preserve focus and restore selection indexes if appropriate @@ -4036,22 +4033,22 @@ [NSObject cancelPreviousPerformRequestsWithTarget:customQueryView]; [self clearQueryLoadTimer]; - [resultLoadingCondition release]; - [usedQuery release]; - [lastExecutedQuery release]; - [resultData release]; - [favoritesManager release]; + SPClear(resultLoadingCondition); + SPClear(usedQuery); + SPClear(lastExecutedQuery); + SPClear(resultData); + SPClear(favoritesManager); if(fieldEditor) SPClear(fieldEditor); #ifndef SP_CODA - if (helpHTMLTemplate) [helpHTMLTemplate release]; + if (helpHTMLTemplate) SPClear(helpHTMLTemplate); #endif - if (mySQLversion) [mySQLversion release]; - if (sortField) [sortField release]; - if (cqColumnDefinition) [cqColumnDefinition release]; - if (selectionIndexToRestore) [selectionIndexToRestore release]; - if (currentQueryRanges) [currentQueryRanges release]; + if (mySQLversion) SPClear(mySQLversion); + if (sortField) SPClear(sortField); + if (cqColumnDefinition) SPClear(cqColumnDefinition); + if (selectionIndexToRestore) SPClear(selectionIndexToRestore); + if (currentQueryRanges) SPClear(currentQueryRanges); [super dealloc]; } diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m index be3935c4..30ef3bf4 100644 --- a/Source/SPDataImport.m +++ b/Source/SPDataImport.m @@ -312,7 +312,7 @@ // Reset progress cancelled from any previous runs progressCancelled = NO; - if (lastFilename) [lastFilename release]; lastFilename = nil; + if (lastFilename) SPClear(lastFilename); lastFilename = [[NSString stringWithString:[[openPanel URL] path]] retain]; @@ -1728,21 +1728,20 @@ cleanup: - (void)dealloc { - if (fieldMappingImportArray) [fieldMappingImportArray release]; - if (geometryFields) [geometryFields release]; - if (geometryFieldsMapIndex) [geometryFieldsMapIndex release]; - if (bitFields) [bitFields release]; - if (nullableNumericFields) [nullableNumericFields release]; - if (bitFieldsMapIndex) [bitFieldsMapIndex release]; - if (nullableNumericFieldsMapIndex) [nullableNumericFieldsMapIndex release]; - - if (lastFilename) [lastFilename release]; - if (prefs) [prefs release]; - if(selectedTableTarget) [selectedTableTarget release]; + if (fieldMappingImportArray) SPClear(fieldMappingImportArray); + if (geometryFields) SPClear(geometryFields); + if (geometryFieldsMapIndex) SPClear(geometryFieldsMapIndex); + if (bitFields) SPClear(bitFields); + if (nullableNumericFields) SPClear(nullableNumericFields); + if (bitFieldsMapIndex) SPClear(bitFieldsMapIndex); + if (nullableNumericFieldsMapIndex) SPClear(nullableNumericFieldsMapIndex); + if (lastFilename) SPClear(lastFilename); + if (prefs) SPClear(prefs); + if (selectedTableTarget) SPClear(selectedTableTarget); for (id retainedObject in nibObjectsToRelease) [retainedObject release]; - [nibObjectsToRelease release]; + SPClear(nibObjectsToRelease); [super dealloc]; } diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index ab8eafc6..a0a6bf1c 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -569,8 +569,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; if (queryEditorInitString && [queryEditorInitString length]) { [self viewQuery:self]; [customQueryInstance doPerformLoadQueryService:queryEditorInitString]; - [queryEditorInitString release]; - queryEditorInitString = nil; + SPClear(queryEditorInitString); } if (spfSession != nil) { diff --git a/Source/SPDatabaseStructure.m b/Source/SPDatabaseStructure.m index b34522c5..2eab3562 100644 --- a/Source/SPDatabaseStructure.m +++ b/Source/SPDatabaseStructure.m @@ -567,7 +567,7 @@ [[NSNotificationCenter defaultCenter] removeObserver:self]; [self destroy:nil]; - [structureRetrievalThreads release]; + SPClear(structureRetrievalThreads); pthread_mutex_destroy(&threadManagementLock); pthread_mutex_destroy(&dataLock); @@ -630,8 +630,7 @@ } pthread_mutex_unlock(&threadManagementLock); - [mySQLConnection release]; - mySQLConnection = nil; + SPClear(mySQLConnection); } // Create a copy of the supplied connection diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index c223faf4..4f34a998 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -169,14 +169,14 @@ } #endif - if ( sheetEditData ) [sheetEditData release]; + if ( sheetEditData ) SPClear(sheetEditData); #ifndef SP_CODA - if ( qlTypes ) [qlTypes release]; + if ( qlTypes ) SPClear(qlTypes); #endif - if ( tmpFileName ) [tmpFileName release]; - if ( tmpDirPath ) [tmpDirPath release]; - if ( esUndoManager ) [esUndoManager release]; - if ( contextInfo ) [contextInfo release]; + if ( tmpFileName ) SPClear(tmpFileName); + if ( tmpDirPath ) SPClear(tmpDirPath); + if ( esUndoManager ) SPClear(esUndoManager); + if ( contextInfo ) SPClear(contextInfo); [super dealloc]; } @@ -1078,8 +1078,6 @@ image = [[[NSImage alloc] initWithPasteboard:[NSPasteboard generalPasteboard]] autorelease]; if (image) { - if (nil != sheetEditData) [sheetEditData release]; - [editImage setImage:image]; if( sheetEditData ) [sheetEditData release]; diff --git a/Source/SPFileHandle.m b/Source/SPFileHandle.m index 58350443..62204252 100644 --- a/Source/SPFileHandle.m +++ b/Source/SPFileHandle.m @@ -467,10 +467,10 @@ { [self closeFile]; - if (processingThread) [processingThread release]; + if (processingThread) SPClear(processingThread); free(wrappedFilePath); - [buffer release]; + SPClear(buffer); pthread_mutex_destroy(&bufferLock); diff --git a/Source/SPHistoryController.m b/Source/SPHistoryController.m index af39323c..aa504bc2 100644 --- a/Source/SPHistoryController.m +++ b/Source/SPHistoryController.m @@ -71,8 +71,8 @@ - (void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [tableContentStates release]; - [history release]; + SPClear(tableContentStates); + SPClear(history); [super dealloc]; } diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m index cb1ba20b..d5391644 100644 --- a/Source/SPNarrowDownCompletion.m +++ b/Source/SPNarrowDownCompletion.m @@ -159,18 +159,16 @@ [NSObject cancelPreviousPerformRequestsWithTarget:self]; if(stateTimer != nil) { [stateTimer invalidate]; - [stateTimer release]; - stateTimer = nil; + SPClear(stateTimer); } - if (staticPrefix) [staticPrefix release]; - [mutablePrefix release]; - [textualInputCharacters release]; - [originalFilterString release]; - if(syncArrowImages) [syncArrowImages release]; - if(suggestions) [suggestions release]; - - if (filtered) [filtered release]; - if (databaseStructureRetrieval) [databaseStructureRetrieval release]; + SPClear(mutablePrefix); + SPClear(textualInputCharacters); + SPClear(originalFilterString); + if (staticPrefix) SPClear(staticPrefix); + if (syncArrowImages) SPClear(syncArrowImages); + if (suggestions) SPClear(suggestions); + if (filtered) SPClear(filtered); + if (databaseStructureRetrieval) SPClear(databaseStructureRetrieval); [super dealloc]; } @@ -181,8 +179,7 @@ // Invalidate the timer now to prevent retain cycles preventing deallocation if (stateTimer != nil) { [stateTimer invalidate]; - [stateTimer release]; - stateTimer = nil; + SPClear(stateTimer); } closeMe = YES; @@ -204,8 +201,7 @@ isQueryingDatabaseStructure = NO; if(stateTimer) { [stateTimer invalidate]; - [stateTimer release]; - stateTimer = nil; + SPClear(stateTimer); if(syncArrowImages) SPClear(syncArrowImages); [self performSelectorOnMainThread:@selector(reInvokeCompletion) withObject:nil waitUntilDone:YES]; closeMe = YES; @@ -222,8 +218,7 @@ { if(stateTimer) { [stateTimer invalidate]; - [stateTimer release]; - stateTimer = nil; + SPClear(stateTimer); } [theView setCompletionIsOpen:NO]; [self close]; diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m index e4bdd1ec..3f194b24 100644 --- a/Source/SPNavigatorController.m +++ b/Source/SPNavigatorController.m @@ -109,21 +109,21 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - if(schemaDataFiltered) [schemaDataFiltered release]; - if(allSchemaKeys) [allSchemaKeys release]; - if(schemaData) [schemaData release]; - if(infoArray) [infoArray release]; - if(updatingConnections) [updatingConnections release]; - if(expandStatus2) [expandStatus2 release]; - if(cachedSortedKeys) [cachedSortedKeys release]; + if(schemaDataFiltered) SPClear(schemaDataFiltered); + if(allSchemaKeys) SPClear(allSchemaKeys); + if(schemaData) SPClear(schemaData); + if(infoArray) SPClear(infoArray); + if(updatingConnections) SPClear(updatingConnections); + if(expandStatus2) SPClear(expandStatus2); + if(cachedSortedKeys) SPClear(cachedSortedKeys); #ifndef SP_CODA /* dealloc ivars */ - [connectionIcon release]; - [databaseIcon release]; - [tableIcon release]; - [viewIcon release]; - [procedureIcon release]; - [functionIcon release]; - [fieldIcon release]; + SPClear(connectionIcon); + SPClear(databaseIcon); + SPClear(tableIcon); + SPClear(viewIcon); + SPClear(procedureIcon); + SPClear(functionIcon); + SPClear(fieldIcon); #endif [super dealloc]; diff --git a/Source/SPPrintController.m b/Source/SPPrintController.m index 70f5662b..d0feec68 100644 --- a/Source/SPPrintController.m +++ b/Source/SPPrintController.m @@ -193,7 +193,7 @@ { [[printWebView mainFrame] loadHTMLString:HTMLString baseURL:nil]; - if (printThread) [printThread release]; + if (printThread) SPClear(printThread); } /** diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index 649d4b5a..6522b884 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -971,7 +971,7 @@ - (void)dealloc { - [favorites release]; + SPClear(favorites); [super dealloc]; } diff --git a/Source/SPSQLParser.m b/Source/SPSQLParser.m index a7a3ee98..d9bec2eb 100644 --- a/Source/SPSQLParser.m +++ b/Source/SPSQLParser.m @@ -790,8 +790,7 @@ TO_BUFFER_STATE to_scan_string (const char *); // Drop back to standard non-delimiter mode if the delimiter has ended if ([delimiter isEqualToString:[NSString stringWithFormat:@"%C", character]]) { - if (delimiter) [delimiter release]; - delimiter = nil; + if (delimiter) SPClear(delimiter); delimiterLengthMinusOne = 0; } @@ -1039,8 +1038,8 @@ TO_BUFFER_STATE to_scan_string (const char *); [self _clearCharCache]; } - (void) dealloc { - [string release]; - if (delimiter) [delimiter release]; + SPClear(string); + if (delimiter) SPClear(delimiter); if (charCacheEnd != -1) free(stringCharCache); [super dealloc]; } diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index c9a214ab..1c217986 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -711,8 +711,7 @@ SPKeychain *keychain = [[SPKeychain alloc] init]; [keychain addPassword:thePassword forName:@"SSH" account:currentKeyName withLabel:[NSString stringWithFormat:@"SSH: %@", currentKeyName]]; [keychain release]; - [currentKeyName release]; - currentKeyName = nil; + SPClear(currentKeyName); } } @@ -729,22 +728,22 @@ [[NSNotificationCenter defaultCenter] removeObserver:self]; if (connectionState != SPMySQLProxyIdle) [self disconnect]; [NSObject cancelPreviousPerformRequestsWithTarget:self]; - [sshHost release]; - [sshLogin release]; - [remoteHost release]; - [tunnelConnectionName release]; - [tunnelConnectionVerifyHash release]; + SPClear(sshHost); + SPClear(sshLogin); + SPClear(remoteHost); + SPClear(tunnelConnectionName); + SPClear(tunnelConnectionVerifyHash); [tunnelConnection invalidate]; - [tunnelConnection release]; - [debugMessages release]; - [debugMessagesLock release]; + SPClear(tunnelConnection); + SPClear(debugMessages); + SPClear(debugMessagesLock); [answerAvailableLock tryLock]; [answerAvailableLock unlock]; - [answerAvailableLock release]; - if (password) [password release]; - if (keychainName) [keychainName release]; - if (keychainAccount) [keychainAccount release]; - if (identityFilePath) [identityFilePath release]; + SPClear(answerAvailableLock); + if (password) SPClear(password); + if (keychainName) SPClear(keychainName); + if (keychainAccount) SPClear(keychainAccount); + if (identityFilePath) SPClear(identityFilePath); // As this object is not a NSWindowController, use manual top-level nib item management if (sshQuestionDialog) SPClear(sshQuestionDialog); diff --git a/Source/SPSplitView.m b/Source/SPSplitView.m index 599432cf..ed87f3c0 100644 --- a/Source/SPSplitView.m +++ b/Source/SPSplitView.m @@ -105,8 +105,8 @@ - (void)dealloc { - [viewMinimumSizes release]; - [viewMaximumSizes release]; + SPClear(viewMinimumSizes); + SPClear(viewMaximumSizes); if (animationTimer) [animationTimer invalidate], SPClear(animationTimer); if (animationRetainCycleBypassObject) SPClear(animationRetainCycleBypassObject); diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index b0d0f03c..9295c858 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -462,7 +462,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper #endif // Reset sort column - if (sortCol) [sortCol release]; sortCol = nil; + if (sortCol) SPClear(sortCol); isDesc = NO; // Empty and disable filter options @@ -697,8 +697,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // Otherwise, clear sorting } else { if (sortCol) { - [sortCol release]; - sortCol = nil; + SPClear(sortCol); } isDesc = NO; } @@ -1372,8 +1371,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper { if (tableLoadTimer) { [tableLoadTimer invalidate]; - [tableLoadTimer release]; - tableLoadTimer = nil; + SPClear(tableLoadTimer); } } @@ -1678,8 +1676,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper // this is the same as saying (isDesc && !invert) || (!isDesc && invert) if (isDesc != invert) { - [sortCol release]; - sortCol = nil; + SPClear(sortCol); } else { isDesc = !isDesc; @@ -3494,8 +3491,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper } if(fieldEditor) { - [fieldEditor release]; - fieldEditor = nil; + SPClear(fieldEditor); } [[tableContentView window] makeFirstResponder:tableContentView]; @@ -4314,34 +4310,35 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper if(fieldEditor) SPClear(fieldEditor); [self clearTableLoadTimer]; - [tableLoadingCondition release]; - [tableValues release]; + SPClear(tableLoadingCondition); + SPClear(tableValues); pthread_mutex_destroy(&tableValuesLock); - [dataColumns release]; - [oldRow release]; + SPClear(dataColumns); + SPClear(oldRow); #ifndef SP_CODA for (id retainedObject in nibObjectsToRelease) [retainedObject release]; - [nibObjectsToRelease release]; - [paginationPopover release]; + SPClear(nibObjectsToRelease); + SPClear(paginationPopover); - [filterTableData release]; - if (lastEditedFilterTableValue) [lastEditedFilterTableValue release]; - if (filterTableDefaultOperator) [filterTableDefaultOperator release]; + SPClear(filterTableData); + if (lastEditedFilterTableValue) SPClear(lastEditedFilterTableValue); + if (filterTableDefaultOperator) SPClear(filterTableDefaultOperator); #endif - if (selectedTable) [selectedTable release]; - if (contentFilters) [contentFilters release]; - if (numberOfDefaultFilters) [numberOfDefaultFilters release]; - if (keys) [keys release]; - if (sortCol) [sortCol release]; - [usedQuery release]; - if (sortColumnToRestore) [sortColumnToRestore release]; - if (selectionToRestore) [selectionToRestore release]; + if (selectedTable) SPClear(selectedTable); + if (contentFilters) SPClear(contentFilters); + if (numberOfDefaultFilters) SPClear(numberOfDefaultFilters); + if (keys) SPClear(keys); + if (sortCol) SPClear(sortCol); + SPClear(usedQuery); + if (sortColumnToRestore) SPClear(sortColumnToRestore); + if (selectionToRestore) SPClear(selectionToRestore); + if (cqColumnDefinition) SPClear(cqColumnDefinition); + if (filterFieldToRestore) filterFieldToRestore = nil; if (filterComparisonToRestore) filterComparisonToRestore = nil; if (filterValueToRestore) filterValueToRestore = nil; if (firstBetweenValueToRestore) firstBetweenValueToRestore = nil; if (secondBetweenValueToRestore) secondBetweenValueToRestore = nil; - if (cqColumnDefinition) [cqColumnDefinition release]; [super dealloc]; } diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 86243956..320a0b66 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -329,18 +329,15 @@ [status removeAllObjects]; if (triggers != nil) { - [triggers release]; - triggers = nil; + SPClear(triggers); } if (tableEncoding != nil) { - [tableEncoding release]; - tableEncoding = nil; + SPClear(tableEncoding); } if (tableCreateSyntax != nil) { - [tableCreateSyntax release]; - tableCreateSyntax = nil; + SPClear(tableCreateSyntax); } } @@ -1395,16 +1392,16 @@ */ - (void)dealloc { - [columns release]; - [columnNames release]; - [constraints release]; - [status release]; - [primaryKeyColumns release]; - - if (triggers) [triggers release]; - if (tableEncoding) [tableEncoding release]; - if (tableCreateSyntax) [tableCreateSyntax release]; - if (mySQLConnection) [mySQLConnection release]; + SPClear(columns); + SPClear(columnNames); + SPClear(constraints); + SPClear(status); + SPClear(primaryKeyColumns); + + if (triggers) SPClear(triggers); + if (tableEncoding) SPClear(tableEncoding); + if (tableCreateSyntax) SPClear(tableCreateSyntax); + if (mySQLConnection) SPClear(mySQLConnection); pthread_mutex_destroy(&dataProcessingLock); diff --git a/Source/SPTableInfo.m b/Source/SPTableInfo.m index 4b16bdc0..e1ce3e4d 100644 --- a/Source/SPTableInfo.m +++ b/Source/SPTableInfo.m @@ -470,8 +470,8 @@ { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [info release]; - [activities release]; + SPClear(info); + SPClear(activities); [super dealloc]; } diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 77e5c77b..32739eb3 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -1473,16 +1473,16 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; [prefs removeObserver:indexesController forKeyPath:SPUseMonospacedFonts]; #endif - [tableFields release]; - [oldRow release]; - [enumFields release]; - [typeSuggestions release]; - [extraFieldSuggestions release]; + SPClear(tableFields); + SPClear(oldRow); + SPClear(enumFields); + SPClear(typeSuggestions); + SPClear(extraFieldSuggestions); SPClear(fieldValidation); - if (defaultValues) [defaultValues release]; - if (selectedTable) [selectedTable release]; + if (defaultValues) SPClear(defaultValues); + if (selectedTable) SPClear(selectedTable); [super dealloc]; } diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 147aec52..aa0d6ea2 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -328,8 +328,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; selectedTableType = (SPTableType)[[tableTypes objectAtIndex:itemToReselect] integerValue]; } else { - if (selectedTableName) [selectedTableName release]; - selectedTableName = nil; + if (selectedTableName) SPClear(selectedTableName); selectedTableType = SPTableTypeNone; } @@ -860,8 +859,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; NSIndexSet *indexes = [tablesListView selectedRowIndexes]; #endif // Update the selected table name and type - if (selectedTableName) [selectedTableName release]; - selectedTableName = nil; + if (selectedTableName) SPClear(selectedTableName); #ifndef SP_CODA /* ui manipulation */ @@ -2729,15 +2727,15 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [tables release]; - [tableTypes release]; + SPClear(tables); + SPClear(tableTypes); #ifndef SP_CODA - if (isTableListFiltered && filteredTables) [filteredTables release]; - if (isTableListFiltered && filteredTableTypes) [filteredTableTypes release]; + if (isTableListFiltered && filteredTables) SPClear(filteredTables); + if (isTableListFiltered && filteredTableTypes) SPClear(filteredTableTypes); #endif - if (selectedTableName) [selectedTableName release]; + if (selectedTableName) SPClear(selectedTableName); - if (addTableCharsetHelper) [addTableCharsetHelper release]; + if (addTableCharsetHelper) SPClear(addTableCharsetHelper); [super dealloc]; } diff --git a/Source/SPTextAndLinkCell.m b/Source/SPTextAndLinkCell.m index 89521e54..2aefbff5 100644 --- a/Source/SPTextAndLinkCell.m +++ b/Source/SPTextAndLinkCell.m @@ -70,7 +70,7 @@ static inline NSRect SPTextLinkRectFromCellRect(NSRect inRect) */ - (void) dealloc { - if (linkButton) [linkButton release]; + if (linkButton) SPClear(linkButton); [super dealloc]; } diff --git a/Source/SPTextView.m b/Source/SPTextView.m index 4ed92f94..70fcefc5 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -3687,18 +3687,18 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS if (completionIsOpen) [completionPopup close], completionIsOpen = NO; #ifndef SP_CODA - [prefs release]; + SPClear(prefs); #endif - [lineNumberView release]; - if(queryHiliteColor) [queryHiliteColor release]; - if(queryEditorBackgroundColor) [queryEditorBackgroundColor release]; - if(commentColor) [commentColor release]; - if(quoteColor) [quoteColor release]; - if(keywordColor) [keywordColor release]; - if(backtickColor) [backtickColor release]; - if(numericColor) [numericColor release]; - if(variableColor) [variableColor release]; - if(otherTextColor) [otherTextColor release]; + SPClear(lineNumberView); + if(queryHiliteColor) SPClear(queryHiliteColor); + if(queryEditorBackgroundColor) SPClear(queryEditorBackgroundColor); + if(commentColor) SPClear(commentColor); + if(quoteColor) SPClear(quoteColor); + if(keywordColor) SPClear(keywordColor); + if(backtickColor) SPClear(backtickColor); + if(numericColor) SPClear(numericColor); + if(variableColor) SPClear(variableColor); + if(otherTextColor) SPClear(otherTextColor); [super dealloc]; } diff --git a/Source/SPTooltip.m b/Source/SPTooltip.m index 33564d81..0a7597f5 100644 --- a/Source/SPTooltip.m +++ b/Source/SPTooltip.m @@ -241,9 +241,9 @@ static CGFloat slow_in_out (CGFloat t) - (void)dealloc { [NSObject cancelPreviousPerformRequestsWithTarget:self]; - [didOpenAtDate release]; - [webView release]; - [webPreferences release]; + SPClear(didOpenAtDate); + SPClear(webView); + SPClear(webPreferences); [super dealloc]; } diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m index bf78ab6f..e3f611c3 100644 --- a/Source/SPUserManager.m +++ b/Source/SPUserManager.m @@ -555,12 +555,12 @@ static NSString * const SPTableViewNameColumnID = @"NameColumn"; didEndSelector:NULL contextInfo:nil]; - [errorsString release]; + SPClear(errorsString); return; } - [errorsString release]; + SPClear(errorsString); // Otherwise, close the sheet [NSApp endSheet:[self window] returnCode:0]; diff --git a/Source/SPWindowController.m b/Source/SPWindowController.m index 6edbb684..0666f1a7 100644 --- a/Source/SPWindowController.m +++ b/Source/SPWindowController.m @@ -537,7 +537,7 @@ enum { // Tear down the animations on the tab bar to stop redraws [tabBar destroyAnimations]; - [managedDatabaseConnections release]; + SPClear(managedDatabaseConnections); [super dealloc]; } -- cgit v1.2.3 From 4ffde6a4867ae005405f586947cf943097c212c1 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 6 Jan 2015 22:18:39 +0100 Subject: Minor internal changes --- Source/SPCopyTable.h | 6 +++--- Source/SPCopyTable.m | 19 +++++++++---------- Source/SPGeneralPreferencePane.m | 6 ++++++ Source/SPPreferenceController.m | 2 -- Source/SPPreferenceControllerDelegate.h | 2 +- Source/SPTextView.m | 2 +- 6 files changed, 20 insertions(+), 17 deletions(-) (limited to 'Source') diff --git a/Source/SPCopyTable.h b/Source/SPCopyTable.h index 02bc2fb4..e397e030 100644 --- a/Source/SPCopyTable.h +++ b/Source/SPCopyTable.h @@ -40,7 +40,7 @@ extern NSInteger SPEditMenuCopy; extern NSInteger SPEditMenuCopyWithColumns; -extern NSInteger SPEditCopyAsSQL; +extern NSInteger SPEditMenuCopyAsSQL; /*! @class copyTable @@ -52,7 +52,7 @@ extern NSInteger SPEditCopyAsSQL; */ @interface SPCopyTable : SPTableView { - SPTableContent* tableInstance; // the table content view instance + SPTableContent* tableInstance; // the table content view instance id mySQLConnection; // current MySQL connection NSArray* columnDefinitions; // array of NSDictionary containing info about columns NSString* selectedTable; // the name of the current selected table @@ -94,7 +94,7 @@ extern NSInteger SPEditCopyAsSQL; @param isLocal who cares @result Always calls for a copy type drag operation */ -- (NSUInteger)draggingSourceOperationMaskForLocal:(BOOL)isLocal; +- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal; #ifndef SP_CODA /* method decls */ /*! diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m index 7f25d05f..2b5554b5 100644 --- a/Source/SPCopyTable.m +++ b/Source/SPCopyTable.m @@ -56,7 +56,7 @@ NSInteger SPEditMenuCopy = 2001; NSInteger SPEditMenuCopyWithColumns = 2002; -NSInteger SPEditCopyAsSQL = 2003; +NSInteger SPEditMenuCopyAsSQL = 2003; static const NSInteger kBlobExclude = 1; static const NSInteger kBlobInclude = 2; @@ -102,7 +102,7 @@ static const NSInteger kBlobAsImageFile = 4; #ifndef SP_CODA /* copy table rows */ NSString *tmp = nil; - if ([sender tag] == SPEditCopyAsSQL) { + if ([sender tag] == SPEditMenuCopyAsSQL) { tmp = [self rowsAsSqlInsertsOnlySelectedRows:YES]; if (tmp != nil){ @@ -607,7 +607,7 @@ static const NSInteger kBlobAsImageFile = 4; /** * Allow for drag-n-drop out of the application as a copy */ -- (NSUInteger) draggingSourceOperationMaskForLocal:(BOOL)isLocal +- (NSDragOperation) draggingSourceOperationMaskForLocal:(BOOL)isLocal { return NSDragOperationCopy; } @@ -991,7 +991,7 @@ static const NSInteger kBlobAsImageFile = 4; } // Don't validate anything other than the copy commands - if (menuItemTag != SPEditMenuCopy && menuItemTag != SPEditMenuCopyWithColumns && menuItemTag != SPEditCopyAsSQL) { + if (menuItemTag != SPEditMenuCopy && menuItemTag != SPEditMenuCopyWithColumns && menuItemTag != SPEditMenuCopyAsSQL) { return YES; } @@ -1006,7 +1006,7 @@ static const NSInteger kBlobAsImageFile = 4; } // Enable the Copy as SQL commands if rows are selected and column definitions are available - if (menuItemTag == SPEditCopyAsSQL) { + if (menuItemTag == SPEditMenuCopyAsSQL) { return (columnDefinitions != nil && [self numberOfSelectedRows] > 0); } #endif @@ -1189,15 +1189,14 @@ static const NSInteger kBlobAsImageFile = 4; */ - (BOOL)shouldUseFieldEditorForRow:(NSUInteger)rowIndex column:(NSUInteger)colIndex checkWithLock:(pthread_mutex_t *)dataLock { - // Retrieve the column definition - NSDictionary *columnDefinition = [[(id )[self delegate] dataColumnDefinitions] objectAtIndex:colIndex]; - - NSString *columnType = [columnDefinition objectForKey:@"typegrouping"]; - // Return YES if the multiple line editing button is enabled - triggers sheet editing on all cells. #ifndef SP_CODA if ([prefs boolForKey:SPEditInSheetEnabled]) return YES; #endif + + // Retrieve the column definition + NSDictionary *columnDefinition = [[(id )[self delegate] dataColumnDefinitions] objectAtIndex:colIndex]; + NSString *columnType = [columnDefinition objectForKey:@"typegrouping"]; // If the column is a BLOB or TEXT column, and not an enum, trigger sheet editing BOOL isBlob = ([columnType isEqualToString:@"textdata"] || [columnType isEqualToString:@"blobdata"]); diff --git a/Source/SPGeneralPreferencePane.m b/Source/SPGeneralPreferencePane.m index a1c024e7..8f4f5c5b 100644 --- a/Source/SPGeneralPreferencePane.m +++ b/Source/SPGeneralPreferencePane.m @@ -204,6 +204,12 @@ static NSString *SPDatabaseImage = @"database-small"; return NO; } +- (void)preferencePaneWillBeShown +{ + [self updateDefaultFavoritePopup]; +} + + #pragma mark - - (void)dealloc diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m index ae407312..36954bc8 100644 --- a/Source/SPPreferenceController.m +++ b/Source/SPPreferenceController.m @@ -68,8 +68,6 @@ { [self _setupToolbar]; - [(SPGeneralPreferencePane *)generalPreferencePane updateDefaultFavoritePopup]; - preferencePanes = [[NSArray alloc] initWithObjects: generalPreferencePane, tablesPreferencePane, diff --git a/Source/SPPreferenceControllerDelegate.h b/Source/SPPreferenceControllerDelegate.h index 2fcdfb24..bcfcb271 100644 --- a/Source/SPPreferenceControllerDelegate.h +++ b/Source/SPPreferenceControllerDelegate.h @@ -37,6 +37,6 @@ * * Preference controller delegate category. */ -@interface SPPreferenceController (SPPreferenceControllerDelegate) +@interface SPPreferenceController (SPPreferenceControllerDelegate) @end diff --git a/Source/SPTextView.m b/Source/SPTextView.m index 70fcefc5..c3ebf394 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -3225,7 +3225,7 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS // Disable "Copy with Column Names" and "Copy as SQL INSERT" // in the main menu if ( [menuItem tag] == SPEditMenuCopyWithColumns - || [menuItem tag] == SPEditCopyAsSQL ) { + || [menuItem tag] == SPEditMenuCopyAsSQL) { return NO; } -- cgit v1.2.3 From 56949ac737a3838f3276d0e558fd0dac7632aae5 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 6 Jan 2015 23:14:21 +0100 Subject: Change some code formatting --- Source/SPDatabaseDocument.m | 25 ++++++---- Source/SPExportController.m | 71 +++++++++++++++------------- Source/SPTablesList.m | 110 ++++++++++++++++++++++---------------------- 3 files changed, 108 insertions(+), 98 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index a0a6bf1c..269e62d4 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -5312,9 +5312,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; } NSInteger itemType = SPTableTypeNone; - NSString *itemTypeStr = @"TABLE"; NSUInteger i; - NSInteger queryCol = 1; // Loop through the unfiltered tables/views to find the desired item for (i = 0; i < [availableItems count]; i++) { @@ -5327,19 +5325,26 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // If no match found, continue if (itemType == SPTableTypeNone) continue; + NSString *itemTypeStr; + NSInteger queryCol; + switch(itemType) { case SPTableTypeTable: case SPTableTypeView: - itemTypeStr = @"TABLE"; - break; + itemTypeStr = @"TABLE"; + queryCol = 1; + break; case SPTableTypeProc: - itemTypeStr = @"PROCEDURE"; - queryCol = 2; - break; + itemTypeStr = @"PROCEDURE"; + queryCol = 2; + break; case SPTableTypeFunc: - itemTypeStr = @"FUNCTION"; - queryCol = 2; - break; + itemTypeStr = @"FUNCTION"; + queryCol = 2; + break; + default: + NSLog(@"%s: Unhandled SPTableType=%ld for item=%@ (skipping)", __func__, itemType, item); + continue; } // Ensure that queries are made in UTF8 diff --git a/Source/SPExportController.m b/Source/SPExportController.m index 752e8521..f650bab9 100644 --- a/Source/SPExportController.m +++ b/Source/SPExportController.m @@ -431,45 +431,50 @@ static const NSString *SPSQLExportDropEnabled = @"SQLExportDropEnabled"; [tables removeAllObjects]; // For all modes, retrieve table and view names - NSArray *tablesAndViews = [tablesListInstance allTableAndViewNames]; - - for (id itemName in tablesAndViews) { - [tables addObject:[NSMutableArray arrayWithObjects: - itemName, - @YES, - @YES, - @YES, - [NSNumber numberWithInt:SPTableTypeTable], - nil]]; - } + { + NSArray *tablesAndViews = [tablesListInstance allTableAndViewNames]; + + for (id itemName in tablesAndViews) { + [tables addObject:[NSMutableArray arrayWithObjects: + itemName, + @YES, + @YES, + @YES, + [NSNumber numberWithInt:SPTableTypeTable], + nil]]; + } + } // The purpose of this extra { } is to limit visibility and thus catch copy&paste errors // For SQL only, add procedures and functions if (exportType == SPSQLExport) { - NSArray *procedures = [tablesListInstance allProcedureNames]; - - for (id procName in procedures) + // Procedures { - [tables addObject:[NSMutableArray arrayWithObjects: - procName, - @YES, - @YES, - @YES, - [NSNumber numberWithInt:SPTableTypeProc], - nil]]; + NSArray *procedures = [tablesListInstance allProcedureNames]; + + for (id procName in procedures) { + [tables addObject:[NSMutableArray arrayWithObjects: + procName, + @YES, + @YES, + @YES, + [NSNumber numberWithInt:SPTableTypeProc], + nil]]; + } } - - NSArray *functions = [tablesListInstance allFunctionNames]; - - for (id funcName in functions) + // Functions { - [tables addObject:[NSMutableArray arrayWithObjects: - funcName, - @YES, - @YES, - @YES, - [NSNumber numberWithInt:SPTableTypeFunc], - nil]]; - } + NSArray *functions = [tablesListInstance allFunctionNames]; + + for (id funcName in functions) { + [tables addObject:[NSMutableArray arrayWithObjects: + funcName, + @YES, + @YES, + @YES, + [NSNumber numberWithInt:SPTableTypeFunc], + nil]]; + } + } } if (sender) { diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index aa0d6ea2..1ae2e83f 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -273,13 +273,12 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; [tables addObject:NSLocalizedString(@"PROCS & FUNCS",@"header for procs & funcs list")]; [tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeNone]]; - for (NSArray *eachRow in theResult) { - [tables addObject:NSArrayObjectAtIndex(eachRow, 3)]; - if ([NSArrayObjectAtIndex(eachRow, 4) isEqualToString:@"PROCEDURE"]) { - [tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeProc]]; - } else { - [tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeFunc]]; - } + for (NSArray *eachRow in theResult) { + [tables addObject:NSArrayObjectAtIndex(eachRow, 3)]; + if ([NSArrayObjectAtIndex(eachRow, 4) isEqualToString:@"PROCEDURE"]) { + [tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeProc]]; + } else { + [tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeFunc]]; } } } @@ -885,31 +884,31 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; switch (lastType) { case SPTableTypeTable: - [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")]; - [truncateTableButton setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")]; - [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")]; - [truncateTableContextMenuItem setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")]; - [truncateTableButton setHidden:NO]; - [truncateTableContextMenuItem setHidden:NO]; - break; + [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")]; + [truncateTableButton setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")]; + [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")]; + [truncateTableContextMenuItem setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")]; + [truncateTableButton setHidden:NO]; + [truncateTableContextMenuItem setHidden:NO]; + break; case SPTableTypeView: - [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")]; - [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")]; - [truncateTableButton setHidden:YES]; - [truncateTableContextMenuItem setHidden:YES]; - break; + [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")]; + [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")]; + [truncateTableButton setHidden:YES]; + [truncateTableContextMenuItem setHidden:YES]; + break; case SPTableTypeProc: - [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")]; - [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")]; - [truncateTableButton setHidden:YES]; - [truncateTableContextMenuItem setHidden:YES]; - break; + [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")]; + [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")]; + [truncateTableButton setHidden:YES]; + [truncateTableContextMenuItem setHidden:YES]; + break; case SPTableTypeFunc: - [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")]; - [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")]; - [truncateTableButton setHidden:YES]; - [truncateTableContextMenuItem setHidden:YES]; - break; + [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")]; + [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")]; + [truncateTableButton setHidden:YES]; + [truncateTableContextMenuItem setHidden:YES]; + break; } } else { @@ -1274,10 +1273,11 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; - (NSArray *)allTableAndViewNames { NSMutableArray *returnArray = [NSMutableArray array]; - NSInteger i; + NSUInteger i; NSInteger cnt = [[self tables] count]; for(i=0; i Date: Tue, 6 Jan 2015 23:20:59 +0100 Subject: Addition to previous commit. Attention: Depening on your diff tool (Kaleidoscope and Tower are pretty bad, AppCode works well) this change might look big, but all I did was remove two levels of else { } by using return; instead. --- Source/SPTablesList.m | 245 +++++++++++++++++++++++++------------------------- 1 file changed, 123 insertions(+), 122 deletions(-) (limited to 'Source') diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 1ae2e83f..e2165029 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -2495,140 +2495,141 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, [NSString stringWithFormat:NSLocalizedString(@"Couldn't get create syntax.\nMySQL said: %@", @"message of panel when table information cannot be retrieved"), [mySQLConnection lastErrorMessage]]); - } else { - //insert new table name in create syntax and create new table - NSScanner *scanner; - NSString *scanString; - - if(tblType == SPTableTypeView){ - scanner = [[NSScanner alloc] initWithString:[[queryResult getRowAsDictionary] objectForKey:@"Create View"]]; - [scanner scanUpToString:@"AS" intoString:nil]; - [scanner scanUpToString:@"" intoString:&scanString]; - [scanner release]; - [mySQLConnection queryString:[NSString stringWithFormat:@"CREATE VIEW %@ %@", [[copyTableNameField stringValue] backtickQuotedString], scanString]]; - } - else if(tblType == SPTableTypeTable){ - scanner = [[NSScanner alloc] initWithString:[[queryResult getRowAsDictionary] objectForKey:@"Create Table"]]; - [scanner scanUpToString:@"(" intoString:nil]; - [scanner scanUpToString:@"" intoString:&scanString]; - [scanner release]; - - // If there are any InnoDB referencial constraints we need to strip out the names as they must be unique. - // MySQL will generate the new names based on the new table name. - scanString = [scanString stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"CONSTRAINT `[^`]+` "] withString:@""]; - - // If we're not copying the tables content as well then we need to strip out any AUTO_INCREMENT presets. - if (!copyTableContent) { - scanString = [scanString stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"AUTO_INCREMENT=[0-9]+ "] withString:@""]; - } - - [mySQLConnection queryString:[NSString stringWithFormat:@"CREATE TABLE %@ %@", [[copyTableNameField stringValue] backtickQuotedString], scanString]]; + return; + } + + //insert new table name in create syntax and create new table + NSScanner *scanner; + NSString *scanString; + + if(tblType == SPTableTypeView){ + scanner = [[NSScanner alloc] initWithString:[[queryResult getRowAsDictionary] objectForKey:@"Create View"]]; + [scanner scanUpToString:@"AS" intoString:nil]; + [scanner scanUpToString:@"" intoString:&scanString]; + [scanner release]; + [mySQLConnection queryString:[NSString stringWithFormat:@"CREATE VIEW %@ %@", [[copyTableNameField stringValue] backtickQuotedString], scanString]]; + } + else if(tblType == SPTableTypeTable){ + scanner = [[NSScanner alloc] initWithString:[[queryResult getRowAsDictionary] objectForKey:@"Create Table"]]; + [scanner scanUpToString:@"(" intoString:nil]; + [scanner scanUpToString:@"" intoString:&scanString]; + [scanner release]; + + // If there are any InnoDB referencial constraints we need to strip out the names as they must be unique. + // MySQL will generate the new names based on the new table name. + scanString = [scanString stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"CONSTRAINT `[^`]+` "] withString:@""]; + + // If we're not copying the tables content as well then we need to strip out any AUTO_INCREMENT presets. + if (!copyTableContent) { + scanString = [scanString stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"AUTO_INCREMENT=[0-9]+ "] withString:@""]; } - else if(tblType == SPTableTypeFunc || tblType == SPTableTypeProc) - { - // get the create syntax - SPMySQLResult *theResult; - - if(selectedTableType == SPTableTypeProc) - theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW CREATE PROCEDURE %@", [selectedTableName backtickQuotedString]]]; - else if([self tableType] == SPTableTypeFunc) - theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW CREATE FUNCTION %@", [selectedTableName backtickQuotedString]]]; - else - return; - - // Check for errors, only displaying if the connection hasn't been terminated - if ([mySQLConnection queryErrored]) { - if ([mySQLConnection isConnected]) { - SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, - [NSString stringWithFormat:NSLocalizedString(@"An error occured while retrieving the create syntax for '%@'.\nMySQL said: %@", @"message of panel when create syntax cannot be retrieved"), selectedTableName, [mySQLConnection lastErrorMessage]]); - } - return; - } - [theResult setReturnDataAsStrings:YES]; - NSString *tableSyntax = [[theResult getRowAsArray] objectAtIndex:2]; - - // replace the old name by the new one and drop the old one - [mySQLConnection queryString:[tableSyntax stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"(?<=%@ )(`[^`]+?`)", [tableType uppercaseString]] withString:[[copyTableNameField stringValue] backtickQuotedString]]]; + [mySQLConnection queryString:[NSString stringWithFormat:@"CREATE TABLE %@ %@", [[copyTableNameField stringValue] backtickQuotedString], scanString]]; + } + else if(tblType == SPTableTypeFunc || tblType == SPTableTypeProc) + { + // get the create syntax + SPMySQLResult *theResult; + + if(selectedTableType == SPTableTypeProc) + theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW CREATE PROCEDURE %@", [selectedTableName backtickQuotedString]]]; + else if([self tableType] == SPTableTypeFunc) + theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW CREATE FUNCTION %@", [selectedTableName backtickQuotedString]]]; + else + return; - if ([mySQLConnection queryErrored]) { + // Check for errors, only displaying if the connection hasn't been terminated + if ([mySQLConnection queryErrored]) { + if ([mySQLConnection isConnected]) { SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, - [NSString stringWithFormat:NSLocalizedString(@"Couldn't duplicate '%@'.\nMySQL said: %@", @"message of panel when an item cannot be renamed"), [copyTableNameField stringValue], [mySQLConnection lastErrorMessage]]); + [NSString stringWithFormat:NSLocalizedString(@"An error occured while retrieving the create syntax for '%@'.\nMySQL said: %@", @"message of panel when create syntax cannot be retrieved"), selectedTableName, [mySQLConnection lastErrorMessage]]); } - + return; } - if ([mySQLConnection queryErrored]) { - //error while creating new table + [theResult setReturnDataAsStrings:YES]; + NSString *tableSyntax = [[theResult getRowAsArray] objectAtIndex:2]; + + // replace the old name by the new one and drop the old one + [mySQLConnection queryString:[tableSyntax stringByReplacingOccurrencesOfRegex:[NSString stringWithFormat:@"(?<=%@ )(`[^`]+?`)", [tableType uppercaseString]] withString:[[copyTableNameField stringValue] backtickQuotedString]]]; + + if ([mySQLConnection queryErrored]) { SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, - [NSString stringWithFormat:NSLocalizedString(@"Couldn't create '%@'.\nMySQL said: %@", @"message of panel when table cannot be created"), [copyTableNameField stringValue], [mySQLConnection lastErrorMessage]]); - } else { - - if (copyTableContent) { - //copy table content - [mySQLConnection queryString:[NSString stringWithFormat: - @"INSERT INTO %@ SELECT * FROM %@", - [[copyTableNameField stringValue] backtickQuotedString], - [selectedTableName backtickQuotedString] - ]]; - - if ([mySQLConnection queryErrored]) { - SPBeginAlertSheet( - NSLocalizedString(@"Warning", @"warning"), - NSLocalizedString(@"OK", @"OK button"), - nil, - nil, - [tableDocumentInstance parentWindow], - self, - nil, - nil, - NSLocalizedString(@"There have been errors while copying table content. Please control the new table.", @"message of panel when table content cannot be copied") - ); - } - } - - // Insert the new item into the tables list and select it. - NSInteger addItemAtIndex = NSNotFound; - for (NSUInteger i = 0; i < [tables count]; i++) { - NSInteger theTableType = [[tableTypes objectAtIndex:i] integerValue]; - if (theTableType == SPTableTypeNone) continue; - if ((theTableType == SPTableTypeView || theTableType == SPTableTypeTable) - && (tblType == SPTableTypeProc || tblType == SPTableTypeFunc)) { - continue; - } - if ((theTableType == SPTableTypeProc || theTableType == SPTableTypeFunc) - && (tblType == SPTableTypeView || tblType == SPTableTypeTable)) { - addItemAtIndex = i - 1; - break; - } - if ([[copyTableNameField stringValue] localizedCompare:[tables objectAtIndex:i]] == NSOrderedAscending) { - addItemAtIndex = i; - break; - } - } - if (addItemAtIndex == NSNotFound) { - [tables addObject:[copyTableNameField stringValue]]; - [tableTypes addObject:[NSNumber numberWithInteger:tblType]]; - } else { - [tables insertObject:[copyTableNameField stringValue] atIndex:addItemAtIndex]; - [tableTypes insertObject:[NSNumber numberWithInteger:tblType] atIndex:addItemAtIndex]; - } + [NSString stringWithFormat:NSLocalizedString(@"Couldn't duplicate '%@'.\nMySQL said: %@", @"message of panel when an item cannot be renamed"), [copyTableNameField stringValue], [mySQLConnection lastErrorMessage]]); + } - // Set the selected table name and type, and use updateFilter to update the filter list and selection - if (selectedTableName) [selectedTableName release]; - - selectedTableName = [[NSString alloc] initWithString:[copyTableNameField stringValue]]; - selectedTableType = tblType; - - [self updateFilter:self]; - - [tablesListView scrollRowToVisible:[tablesListView selectedRow]]; - [tableDocumentInstance loadTable:selectedTableName ofType:selectedTableType]; + } - // Query the structure of all databases in the background (mainly for completion) - [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; + if ([mySQLConnection queryErrored]) { + //error while creating new table + SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, + [NSString stringWithFormat:NSLocalizedString(@"Couldn't create '%@'.\nMySQL said: %@", @"message of panel when table cannot be created"), [copyTableNameField stringValue], [mySQLConnection lastErrorMessage]]); + return; + } + + if (copyTableContent) { + //copy table content + [mySQLConnection queryString:[NSString stringWithFormat: + @"INSERT INTO %@ SELECT * FROM %@", + [[copyTableNameField stringValue] backtickQuotedString], + [selectedTableName backtickQuotedString] + ]]; + + if ([mySQLConnection queryErrored]) { + SPBeginAlertSheet( + NSLocalizedString(@"Warning", @"warning"), + NSLocalizedString(@"OK", @"OK button"), + nil, + nil, + [tableDocumentInstance parentWindow], + self, + nil, + nil, + NSLocalizedString(@"There have been errors while copying table content. Please control the new table.", @"message of panel when table content cannot be copied") + ); } } + + // Insert the new item into the tables list and select it. + NSInteger addItemAtIndex = NSNotFound; + for (NSUInteger i = 0; i < [tables count]; i++) { + NSInteger theTableType = [[tableTypes objectAtIndex:i] integerValue]; + if (theTableType == SPTableTypeNone) continue; + if ((theTableType == SPTableTypeView || theTableType == SPTableTypeTable) + && (tblType == SPTableTypeProc || tblType == SPTableTypeFunc)) { + continue; + } + if ((theTableType == SPTableTypeProc || theTableType == SPTableTypeFunc) + && (tblType == SPTableTypeView || tblType == SPTableTypeTable)) { + addItemAtIndex = i - 1; + break; + } + if ([[copyTableNameField stringValue] localizedCompare:[tables objectAtIndex:i]] == NSOrderedAscending) { + addItemAtIndex = i; + break; + } + } + if (addItemAtIndex == NSNotFound) { + [tables addObject:[copyTableNameField stringValue]]; + [tableTypes addObject:[NSNumber numberWithInteger:tblType]]; + } else { + [tables insertObject:[copyTableNameField stringValue] atIndex:addItemAtIndex]; + [tableTypes insertObject:[NSNumber numberWithInteger:tblType] atIndex:addItemAtIndex]; + } + + // Set the selected table name and type, and use updateFilter to update the filter list and selection + if (selectedTableName) [selectedTableName release]; + + selectedTableName = [[NSString alloc] initWithString:[copyTableNameField stringValue]]; + selectedTableType = tblType; + + [self updateFilter:self]; + + [tablesListView scrollRowToVisible:[tablesListView selectedRow]]; + [tableDocumentInstance loadTable:selectedTableName ofType:selectedTableType]; + + // Query the structure of all databases in the background (mainly for completion) + [NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES}]; } #endif -- cgit v1.2.3 From 69b519cb18762cd1b1596d50346f24e233cb8e29 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 7 Jan 2015 00:07:36 +0100 Subject: Fix some warnings --- Source/SPPreferenceController.h | 1 - Source/SPPreferenceController.m | 10 ++++++++-- Source/SPPreferenceControllerDelegate.m | 8 ++++---- 3 files changed, 12 insertions(+), 7 deletions(-) (limited to 'Source') diff --git a/Source/SPPreferenceController.h b/Source/SPPreferenceController.h index c34f8542..3434663e 100644 --- a/Source/SPPreferenceController.h +++ b/Source/SPPreferenceController.h @@ -61,7 +61,6 @@ NSToolbarItem *generalItem; NSToolbarItem *notificationsItem; NSToolbarItem *tablesItem; - NSToolbarItem *favoritesItem; NSToolbarItem *autoUpdateItem; NSToolbarItem *networkItem; NSToolbarItem *editorItem; diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m index 36954bc8..fad1d95b 100644 --- a/Source/SPPreferenceController.m +++ b/Source/SPPreferenceController.m @@ -128,14 +128,14 @@ [prefs setObject:[NSArchiver archivedDataWithRootObject:font] forKey:SPGlobalResultTableFont]; - [(SPTablesPreferencePane *)tablesPreferencePane updateDisplayedTableFontName]; + [tablesPreferencePane updateDisplayedTableFontName]; break; case SPPrefFontChangeTargetEditor: font = [[NSFontPanel sharedFontPanel] panelConvertFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorFont]]]; [prefs setObject:[NSArchiver archivedDataWithRootObject:font] forKey:SPCustomQueryEditorFont]; - [(SPEditorPreferencePane *)editorPreferencePane updateDisplayedEditorFontName]; + [editorPreferencePane updateDisplayedEditorFontName]; break; } } @@ -231,6 +231,12 @@ - (void)dealloc { SPClear(preferencePanes); + SPClear(generalItem); + SPClear(tablesItem); + SPClear(notificationsItem); + SPClear(editorItem); + SPClear(autoUpdateItem); + SPClear(networkItem); [super dealloc]; } diff --git a/Source/SPPreferenceControllerDelegate.m b/Source/SPPreferenceControllerDelegate.m index ce05de6c..6a16de0f 100644 --- a/Source/SPPreferenceControllerDelegate.m +++ b/Source/SPPreferenceControllerDelegate.m @@ -62,7 +62,7 @@ #pragma mark - #pragma mark Toolbar delegate methods -- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag +- (NSToolbarItem *)toolbar:(NSToolbar *)aToolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag { if ([itemIdentifier isEqualToString:SPPreferenceToolbarGeneral]) { return generalItem; @@ -89,7 +89,7 @@ return [[[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier] autorelease]; } -- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar +- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)aToolbar { return @[ SPPreferenceToolbarGeneral, @@ -102,7 +102,7 @@ ]; } -- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar +- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)aToolbar { return @[ SPPreferenceToolbarGeneral, @@ -115,7 +115,7 @@ ]; } -- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar +- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)aToolbar { return @[ SPPreferenceToolbarGeneral, -- cgit v1.2.3 From dcfe99612cadd055599acd2070d4d9ac49633a95 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 9 Jan 2015 22:07:25 +0100 Subject: Unescape escaped mirrored snippets in query fav. fixes #2049 --- Source/SPTextView.m | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) (limited to 'Source') diff --git a/Source/SPTextView.m b/Source/SPTextView.m index c3ebf394..f50ed939 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -1934,20 +1934,22 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS } // unescape escaped snippets and re-adjust successive snippet locations : \${1:a} → ${1:a} - NSString *ure = @"(?s)\\\\\\$\\{(1?\\d):(.{0}|.*?[^\\\\])\\}"; - while([snip isMatchedByRegex:ure]) { - NSRange escapeRange = [snip rangeOfRegex:ure capture:0L]; - [snip replaceCharactersInRange:escapeRange withString:[snip substringWithRange:NSMakeRange(escapeRange.location+1,escapeRange.length-1)]]; - NSInteger loc = escapeRange.location + targetRange.location; - [snip flushCachedRegexData]; - for(i=0; i<=snippetControlMax; i++) - if(snippetControlArray[i][0] > -1 && snippetControlArray[i][0] > loc) - snippetControlArray[i][0]--; - // Adjust mirrored snippets - if(mirroredCounter > -1) - for(i=0; i<=mirroredCounter; i++) - if(snippetMirroredControlArray[i][0] > -1 && snippetMirroredControlArray[i][1] > loc) - snippetMirroredControlArray[i][1]--; + // unescape escaped mirrored snippets and re-adjust successive snippet locations : \$1 → $1 + for (NSString *regex in @[@"(?s)\\\\\\$\\{(1?\\d):(.{0}|.*?[^\\\\])\\}",@"(?s)\\\\\\$(1?\\d)(?=\\D)"]) { + while([snip isMatchedByRegex:regex]) { + NSRange escapeRange = [snip rangeOfRegex:regex capture:0L]; + [snip replaceCharactersInRange:escapeRange withString:[snip substringWithRange:NSMakeRange(escapeRange.location+1,escapeRange.length-1)]]; + NSInteger loc = escapeRange.location + targetRange.location; + [snip flushCachedRegexData]; + for(i=0; i<=snippetControlMax; i++) + if(snippetControlArray[i][0] > -1 && snippetControlArray[i][0] > loc) + snippetControlArray[i][0]--; + // Adjust mirrored snippets + if(mirroredCounter > -1) + for(i=0; i<=mirroredCounter; i++) + if(snippetMirroredControlArray[i][0] > -1 && snippetMirroredControlArray[i][1] > loc) + snippetMirroredControlArray[i][1]--; + } } // Insert favorite query by selecting the tab trigger if any -- cgit v1.2.3 From 4fafe928e01b6dbf1674eebddd8b9816a9ebcdd1 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 10 Jan 2015 08:42:27 +0100 Subject: Somehow a "}" got dropped in 56949ac7 --- Source/SPTablesList.m | 1 + 1 file changed, 1 insertion(+) (limited to 'Source') diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index e2165029..76f6d1ce 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -282,6 +282,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; } } } + } #endif // Restore encoding if appropriate -- cgit v1.2.3 From d5ffcf83d78e5dc2c6185c13ecce5456b613a655 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 10 Jan 2015 14:51:20 +0100 Subject: Fix a compiler warning --- Source/SPAppController.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPAppController.m b/Source/SPAppController.m index 0840978d..0d60437b 100644 --- a/Source/SPAppController.m +++ b/Source/SPAppController.m @@ -670,10 +670,10 @@ } // Update Bundle Editor if it was already initialized - for (id win in [NSApp windows]) + for (NSWindow *win in [NSApp windows]) { - if ([[[[win delegate] class] description] isEqualToString:@"SPBundleEditorController"]) { - [[win delegate] reloadBundles:nil]; + if ([[win delegate] class] == [SPBundleEditorController class]) { + [((SPBundleEditorController *)[win delegate]) reloadBundles:nil]; break; } } -- cgit v1.2.3 From f2bb1116a22dcbd680a61637532108d0c8497b99 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 11 Jan 2015 15:24:10 +0100 Subject: Fix an issue where a KV Observer was not removed on dealloc resulting in KVO messaging a Zombie and crashing --- Source/SPDatabaseDocument.m | 1 + 1 file changed, 1 insertion(+) (limited to 'Source') diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 269e62d4..a14a6f03 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -6264,6 +6264,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [prefs removeObserver:tableSourceInstance forKeyPath:SPUseMonospacedFonts]; [prefs removeObserver:[SPQueryController sharedQueryController] forKeyPath:SPUseMonospacedFonts]; [prefs removeObserver:tableContentInstance forKeyPath:SPGlobalResultTableFont]; + [prefs removeObserver:tableContentInstance forKeyPath:SPDisplayBinaryDataAsHex]; [prefs removeObserver:[SPQueryController sharedQueryController] forKeyPath:SPConsoleEnableLogging]; [prefs removeObserver:self forKeyPath:SPConsoleEnableLogging]; -- cgit v1.2.3 From 4e3fc71b8f5c4a1cc53e2ebf6dee1ad9ccfbaf34 Mon Sep 17 00:00:00 2001 From: Christoph Neukirch Date: Tue, 13 Jan 2015 19:57:30 +0100 Subject: Fix an issue with ssh -L forwarding (: is the correct separator) --- Source/SPSSHTunnel.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index 1c217986..3b58d331 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -373,10 +373,10 @@ [taskArguments addObject:sshHost]; } if (useHostFallback) { - [taskArguments addObject:[NSString stringWithFormat:@"-L %ld/127.0.0.1/%ld", (long)localPort, (long)remotePort]]; - [taskArguments addObject:[NSString stringWithFormat:@"-L %ld/%@/%ld", (long)localPortFallback, remoteHost, (long)remotePort]]; + [taskArguments addObject:[NSString stringWithFormat:@"-L %ld:127.0.0.1:%ld", (long)localPort, (long)remotePort]]; + [taskArguments addObject:[NSString stringWithFormat:@"-L %ld:%@:%ld", (long)localPortFallback, remoteHost, (long)remotePort]]; } else { - [taskArguments addObject:[NSString stringWithFormat:@"-L %ld/%@/%ld", (long)localPort, remoteHost, (long)remotePort]]; + [taskArguments addObject:[NSString stringWithFormat:@"-L %ld:%@:%ld", (long)localPort, remoteHost, (long)remotePort]]; } [task setArguments:taskArguments]; -- cgit v1.2.3 From e9b8c389a1e2341ff069de8de4305163dfef48b5 Mon Sep 17 00:00:00 2001 From: Max Lohrmann Date: Tue, 13 Jan 2015 21:46:54 +0100 Subject: Change the way the NSOpenPanel is handled when selecting an SSH key to address #2042 --- Source/SPConnectionController.m | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'Source') diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 79a15a19..7cde1e4e 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -371,8 +371,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, #ifndef SP_CODA NSString *directoryPath = nil; NSString *filePath = nil; - keySelectionPanel = [NSOpenPanel openPanel]; - [keySelectionPanel setShowsHiddenFiles:[prefs boolForKey:SPHiddenKeyFileVisibilityKey]]; + NSView *accessoryView = nil; // If the button was toggled off, ensure editing is ended if ([sender state] == NSOffState) { @@ -395,7 +394,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, directoryPath = [sshKeyLocation stringByDeletingLastPathComponent]; } - [keySelectionPanel setAccessoryView:sshKeyLocationHelp]; + accessoryView = sshKeyLocationHelp; } // SSL key file location: else if (sender == standardSSLKeyFileButton || sender == socketSSLKeyFileButton || sender == sslOverSSHKeyFileButton) { @@ -404,7 +403,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, return; } - [keySelectionPanel setAccessoryView:sslKeyFileLocationHelp]; + accessoryView = sslKeyFileLocationHelp; } // SSL certificate file location: else if (sender == standardSSLCertificateButton || sender == socketSSLCertificateButton || sender == sslOverSSHCertificateButton) { @@ -413,7 +412,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, return; } - [keySelectionPanel setAccessoryView:sslCertificateLocationHelp]; + accessoryView = sslCertificateLocationHelp; } // SSL CA certificate file location: else if (sender == standardSSLCACertButton || sender == socketSSLCACertButton || sender == sslOverSSHCACertButton) { @@ -422,12 +421,21 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, return; } - [keySelectionPanel setAccessoryView:sslCACertLocationHelp]; + accessoryView = sslCACertLocationHelp; } + + keySelectionPanel = [[NSOpenPanel openPanel] retain]; // retain/release needed on OS X ≤ 10.6 according to Apple doc + [keySelectionPanel setShowsHiddenFiles:[prefs boolForKey:SPHiddenKeyFileVisibilityKey]]; + [keySelectionPanel setAccessoryView:accessoryView]; [keySelectionPanel beginSheetModalForWindow:[dbDocument parentWindow] completionHandler:^(NSInteger returnCode) { NSString *abbreviatedFileName = [[[keySelectionPanel URL] path] stringByAbbreviatingWithTildeInPath]; + + //delay the release so it won't happen while this block is still executing. + dispatch_async(dispatch_get_current_queue(), ^{ + SPClear(keySelectionPanel); + }); // SSH key file selection if (sender == sshSSHKeyButton) { -- cgit v1.2.3 From cf2559d98a00699462bc32f3e19753a9ca547a9c Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 27 Jan 2015 01:55:18 +0100 Subject: Move some duplicate code into it's own file --- Source/SPEditorTokens.l | 55 +------------------------------ Source/SPParserUtils.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ Source/SPParserUtils.h | 41 +++++++++++++++++++++++ Source/SPSQLTokenizer.l | 59 ++------------------------------- 4 files changed, 132 insertions(+), 110 deletions(-) create mode 100644 Source/SPParserUtils.c create mode 100644 Source/SPParserUtils.h (limited to 'Source') diff --git a/Source/SPEditorTokens.l b/Source/SPEditorTokens.l index c10dbd60..a40105a1 100644 --- a/Source/SPEditorTokens.l +++ b/Source/SPEditorTokens.l @@ -43,8 +43,8 @@ */ #import "SPEditorTokens.h" +#include "SPParserUtils.h" -size_t utf8strlen(const char * _s); size_t yyuoffset, yyuleng; //keep track of the current utf-8 character (not byte) offset and token length @@ -126,59 +126,6 @@ keywords (X(OR|509|A)|S(MALLINT|SL|H(OW({s}(E(NGINE(S)?|RRORS)|M(ASTER|UTEX)|BIN } %% -#define ONEMASK ((size_t)(-1) / 0xFF) -// adapted from http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html -size_t utf8strlen(const char * _s) -{ - const char * s; - size_t count = 0; - size_t u; - unsigned char b; - - /* Handle any initial misaligned bytes. */ - for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) { - b = *s; - - /* Exit if we hit a zero byte. */ - if (b == '\0') - goto done; - - /* Is this byte NOT the first byte of a character? */ - count += (b >> 7) & ((~b) >> 6); - } - - /* Handle complete blocks. */ - for (; ; s += sizeof(size_t)) { - /* Prefetch 256 bytes ahead. */ - __builtin_prefetch(&s[256], 0, 0); - - /* Grab 4 or 8 bytes of UTF-8 data. */ - u = *(size_t *)(s); - - /* Exit the loop if there are any zero bytes. */ - if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80)) - break; - - /* Count bytes which are NOT the first byte of a character. */ - u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6); - count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8); - } - - /* Take care of any left-over bytes. */ - for (; ; s++) { - b = *s; - - /* Exit if we hit a zero byte. */ - if (b == '\0') - break; - - /* Is this byte NOT the first byte of a character? */ - count += (b >> 7) & ((~b) >> 6); - } - -done: - return ((s - _s) - count); -} /* un-optimized keywords: ACCESSIBLE diff --git a/Source/SPParserUtils.c b/Source/SPParserUtils.c new file mode 100644 index 00000000..b3b48945 --- /dev/null +++ b/Source/SPParserUtils.c @@ -0,0 +1,87 @@ +// +// SPParserUtils.c +// sequel-pro +// +// Created by Max Lohrmann on 27.01.15. +// Relocated from existing files. Previous copyright applies. +// +// 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 + +#include "SPParserUtils.h" +#include + +#define ONEMASK ((size_t)(-1) / 0xFF) + +// adapted from http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html +size_t utf8strlen(const char * _s) +{ + const char * s; + size_t count = 0; + size_t u; + unsigned char b; + + /* Handle any initial misaligned bytes. */ + for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) { + b = *s; + + /* Exit if we hit a zero byte. */ + if (b == '\0') + goto done; + + /* Is this byte NOT the first byte of a character? */ + count += (b >> 7) & ((~b) >> 6); + } + + /* Handle complete blocks. */ + for (; ; s += sizeof(size_t)) { + /* Prefetch 256 bytes ahead. */ + __builtin_prefetch(&s[256], 0, 0); + + /* Grab 4 or 8 bytes of UTF-8 data. */ + u = *(size_t *)(s); + + /* Exit the loop if there are any zero bytes. */ + if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80)) + break; + + /* Count bytes which are NOT the first byte of a character. */ + u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6); + count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8); + } + + /* Take care of any left-over bytes. */ + for (; ; s++) { + b = *s; + + /* Exit if we hit a zero byte. */ + if (b == '\0') + break; + + /* Is this byte NOT the first byte of a character? */ + count += (b >> 7) & ((~b) >> 6); + } + +done: + return ((s - _s) - count); +} diff --git a/Source/SPParserUtils.h b/Source/SPParserUtils.h new file mode 100644 index 00000000..487131e0 --- /dev/null +++ b/Source/SPParserUtils.h @@ -0,0 +1,41 @@ +// +// SPParserUtils.h +// sequel-pro +// +// Created by Max Lohrmann on 27.01.15. +// Relocated from existing files. Previous copyright applies. +// +// 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 + +#ifndef __SPParserUtils__ +#define __SPParserUtils__ + +#include + +/** + * Return number of characters (NOT bytes) in a given UTF-8 encoded C string. + */ +size_t utf8strlen(const char * _s); + +#endif /* defined(__SPParserUtils__) */ diff --git a/Source/SPSQLTokenizer.l b/Source/SPSQLTokenizer.l index 24dac938..b9170edb 100644 --- a/Source/SPSQLTokenizer.l +++ b/Source/SPSQLTokenizer.l @@ -31,12 +31,12 @@ // More info at #import "SPSQLTokenizer.h" +#include "SPParserUtils.h" -int utf8strlenfortoken(const char * _s); -int yyuoffset, yyuleng; +size_t yyuoffset, yyuleng; //keep track of the current utf-8 character (not byte) offset and token length -#define YY_USER_ACTION { yyuoffset += yyuleng; yyuleng = utf8strlenfortoken(yytext); } +#define YY_USER_ACTION { yyuoffset += yyuleng; yyuleng = utf8strlen(yytext); } //ignore the output of unmatched characters #define ECHO {} %} @@ -90,56 +90,3 @@ compend {s}"end" return 0; } %% -#define ONEMASK ((size_t)(-1) / 0xFF) -// adapted from http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html -int utf8strlenfortoken(const char * _s) -{ - const char * s; - size_t count = 0; - size_t u; - unsigned char b; - - /* Handle any initial misaligned bytes. */ - for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) { - b = *s; - - /* Exit if we hit a zero byte. */ - if (b == '\0') - goto done; - - /* Is this byte NOT the first byte of a character? */ - count += (b >> 7) & ((~b) >> 6); - } - - /* Handle complete blocks. */ - for (; ; s += sizeof(size_t)) { - /* Prefetch 256 bytes ahead. */ - __builtin_prefetch(&s[256], 0, 0); - - /* Grab 4 or 8 bytes of UTF-8 data. */ - u = *(size_t *)(s); - - /* Exit the loop if there are any zero bytes. */ - if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80)) - break; - - /* Count bytes which are NOT the first byte of a character. */ - u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6); - count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8); - } - - /* Take care of any left-over bytes. */ - for (; ; s++) { - b = *s; - - /* Exit if we hit a zero byte. */ - if (b == '\0') - break; - - /* Is this byte NOT the first byte of a character? */ - count += (b >> 7) & ((~b) >> 6); - } - -done: - return (int)((s - _s) - count); -} -- cgit v1.2.3 From 2ab2ddf5356117d16d1b0e9f78f9c74b6fdb2dc1 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 28 Jan 2015 22:42:47 +0100 Subject: Fix syntax highlighting for emoji et al. #2044 Voodoo magic provided by @Bibiko ;) --- Source/SPParserUtils.c | 45 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 7 deletions(-) (limited to 'Source') diff --git a/Source/SPParserUtils.c b/Source/SPParserUtils.c index b3b48945..69929cee 100644 --- a/Source/SPParserUtils.c +++ b/Source/SPParserUtils.c @@ -31,18 +31,36 @@ #include "SPParserUtils.h" #include +#define SIZET (sizeof(size_t)) +#define SIZET1 (SIZET - 1) +#define SBYTE (SIZET1 * 8) + #define ONEMASK ((size_t)(-1) / 0xFF) +#define ONEMASK8 (ONEMASK * 0x80) +#define FMASK ((size_t)(-1)*(ONEMASK*0xf)-1) // adapted from http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html size_t utf8strlen(const char * _s) { + + /* Due to [NSString length] behaviour for chars > 0xFFFF {length = 2} + "correct" the variable 'count' by subtraction the number + of occurrences of the start byte 0xF0 (4-byte UTF-8 char). + Here we assume that only up to 4-byte UTF-8 chars + are allowed [latest UTF-8 specification]. + + Marked in the source code by "CORRECT". + */ + const char * s; - size_t count = 0; - size_t u; + long count = 0; + size_t u = 0; + size_t u1 = 0; unsigned char b; + /* Handle any initial misaligned bytes. */ - for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) { + for (s = _s; (uintptr_t)(s) & SIZET1; s++) { b = *s; /* Exit if we hit a zero byte. */ @@ -51,10 +69,13 @@ size_t utf8strlen(const char * _s) /* Is this byte NOT the first byte of a character? */ count += (b >> 7) & ((~b) >> 6); + + /* CORRECT */ + count -= (b & 0xf0) == 0xf0; } /* Handle complete blocks. */ - for (; ; s += sizeof(size_t)) { + for (; ; s += SIZET) { /* Prefetch 256 bytes ahead. */ __builtin_prefetch(&s[256], 0, 0); @@ -62,12 +83,19 @@ size_t utf8strlen(const char * _s) u = *(size_t *)(s); /* Exit the loop if there are any zero bytes. */ - if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80)) + if ((u - ONEMASK) & (~u) & ONEMASK8) break; + /* CORRECT */ + u1 = u & FMASK; + u1 = (u1 >> 7) & (u1 >> 6) & (u1 >> 5) & (u1 >> 4); + if (u1) count -= (u1 * ONEMASK) >> SBYTE; + /* Count bytes which are NOT the first byte of a character. */ - u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6); - count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8); + u = ((u & ONEMASK8) >> 7) & ((~u) >> 6); + + count += (u * ONEMASK) >> SBYTE; + } /* Take care of any left-over bytes. */ @@ -80,6 +108,9 @@ size_t utf8strlen(const char * _s) /* Is this byte NOT the first byte of a character? */ count += (b >> 7) & ((~b) >> 6); + + /* CORRECT */ + count -= (b & 0xf0) == 0xf0; } done: -- cgit v1.2.3 From f2fc88bd1875d0dd6642c064c3528d0b5aeab09a Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 1 Feb 2015 18:20:19 +0100 Subject: Simplify catchall lexer rule --- Source/SPEditorTokens.l | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'Source') diff --git a/Source/SPEditorTokens.l b/Source/SPEditorTokens.l index a40105a1..8a7c317b 100644 --- a/Source/SPEditorTokens.l +++ b/Source/SPEditorTokens.l @@ -61,7 +61,6 @@ numeric ([+-]?(([0-9]+\.[0-9]+)|([0-9]*\.[0-9]+)|([0-9]+))(e[+-]?[0-9]+)?) ops "+"|"-"|"*"|"/" word [a-z_\.0-9À-゚@] variable @{1,2}[a-z_\.0-9À-゚$]+ -nonword [^a-z_0-9À-゚#\n\t\r] keyworda (G(R(OUP{s}BY|ANT(S)?)|E(NERAL|T_FORMAT|OMETRY(COLLECTION)?)|LOBAL)|B(Y(TE)?|TREE|I(GINT|N(LOG|ARY)|T)|O(TH|OL(EAN)?)|E(GIN|TWEEN|FORE)|LOB|ACKUP{s}TABLE)|H(IGH_PRIORITY|O(ST(S)?|UR(_(MI(NUTE|CROSECOND)|SECOND))?)|ELP|A(SH|NDLER|VING))|C(R(OSS|EATE)|H(ECK(SUM)?|A(R(SET|ACTER)?|NGE(D)?|IN))|IPHER|O(M(M(IT(TED)?|ENT)|P(RESSED|LETION|ACT))|N(S(TRAINT(_(SCHEMA|NAME|CATALOG))?|ISTENT)|NECTION|CURRENT|T(RIBUTORS|INUE|AINS)|DITION|VERT)|DE|L(UMN(S|_(NAME|FORMAT))?|LATE)|ALESCE{s}PARTITION)|U(R(RENT_(TIME(STAMP)?|DATE|USER)|SOR(_NAME)?)|BE)|L(IENT|OSE|ASS_ORIGIN)|A(S(CADE(D)?|E)|CHE{s}INDEX|TALOG_NAME|LL))|I(GNORE(_SERVER_IDS)?|MPORT{s}TABLESPACE|S(SUER|OLATION)?|N(S(TALL({s}PLUGIN)?|E(RT(_METHOD)?|NSITIVE))|N(O(BASE|DB)|ER)|T(1|2|8|3|O({s}(DUMP|OUT)FILE)?|4|E(RVAL|GER))?|ITIAL_SIZE|OUT|DEX(ES)?|VOKER|FILE)?|TERATE|O_THREAD|DENTIFIED|F)|D(ROP|YNAMIC|I(RECTORY|S(CARD{s}TABLESPACE|TINCT(ROW)?|K|ABLE{s}KEYS)|V)|O(UBLE)?|U(MPFILE|PLICATE|AL)|E(S(C(RIBE)?|_KEY_FILE)|C(IMAL|LARE)?|TERMINISTIC|F(INER|AULT)|L(ETE|AY(_KEY_WRITE|ED))|ALLOCATE)|A(Y(_(MI(NUTE|CROSECOND)|SECOND|HOUR))?|T(E(TIME)?|A(BASE(S)?|FILE)?)))|JOIN|E(RRORS|X(TEN(T_SIZE|DED)|I(STS|T)|P(LAIN|ANSION)|ECUTE)|SCAPE(D{s}BY)?|N(GINE(S)?|CLOSED{s}BY|D(S)?|UM|ABLE{s}KEYS)|VE(RY|NT)|LSE(IF)?|ACH)|K(ILL({s}(CONNECTION|QUERY))?|EY(S|_BLOCK_SIZE)?)|F(R(OM|AC_SECOND)|I(RST|XED|LE)|O(R(CE|EIGN)?|UND)|U(NCTION|LL(TEXT)?)|ETCH|L(OAT(8|4)?|USH)|A(ST|LSE))|A(G(GREGATE|AINST)|S(C(II)?|ENSITIVE)?|N(Y|D|ALYZE)|C(CESSIBLE|TION)|T|DD|UT(HORS|O(_INCREMENT|EXTEND_SIZE))|VG(_ROW_LENGTH)?|FTER|L(GORITHM|TER|L))) keywordl (R(TREE|IGHT|O(UTINE|W(S|_FORMAT)?|LL(BACK|UP))|E(GEXP|MOVE{s}PARTITIONING|BUILD{s}PARTITION|S(T(RICT|ORE{s}TABLE)|IGNAL|UME|ET)|NAME|COVER|TURN(S)?|ORGANIZE{s}PARTITION|D(O(_BUFFER_SIZE|FILE)|UNDANT)|P(EAT(ABLE)?|L(ICATION|ACE)|AIR)|VOKE|QUIRE|FERENCES|L(OAD|EASE|AY_(THREAD|LOG_(POS|FILE)))|A(D(S|_(ONLY|WRITE))?|L))|LIKE|ANGE)|M(YSQL_ERRNO|I(GRATE|N(_ROWS|UTE(_(MICROSECOND|SECOND))?)|CROSECOND|DDLEINT)|O(NTH|D(IF(Y|IES)|E)?)|U(TEX|LTI(PO(INT|LYGON)|LINESTRING))|E(RGE|MORY|SSAGE_TEXT|DIUM(BLOB|TEXT|INT)?)|A(X(_(ROWS|SIZE|CONNECTIONS_PER_HOUR|U(SER_CONNECTIONS|PDATES_PER_HOUR)|QUERIES_PER_HOUR)|VALUE)|STER(_(S(SL(_(C(IPHER|ERT|A(PATH)?)|VERIFY_SERVER_CERT|KEY))?|ERVER_ID)|H(OST|EARTBEAT_PERIOD)|CONNECT_RETRY|USER|P(ORT|ASSWORD)|LOG_(POS|FILE)))?|TCH))|N(CHAR|O(NE|_W(RITE_TO_BINLOG|AIT)|T|DEGROUP)?|DB(CLUSTER)?|U(MERIC|LL)|E(XT|W)|VARCHAR|A(ME(S)?|T(IONAL|URAL)))|O(R(DER{s}BY)?|N(({s}DUPLICATE{s}KEY{s}UPDATE)?|E(_SHOT)?|LINE)?|UT(ER|FILE)?|P(TI(MIZE|ON(S|ALLY)?)|EN)|FF(SET|LINE)|WNER|LD_PASSWORD)|P(R(I(MARY|VILEGES)|OCE(SS|DURE{s}(ANALYSE)?)|E(SERVE|CISION|PARE|V))|HASE|O(RT|INT|LYGON)|URGE|A(R(SER|TI(TION(S|ING)?|AL))|SSWORD|CK_KEYS))|QU(ICK|ERY|ARTER)|L(I(MIT|ST|NE(S(TRING)?|AR)|KE)|O(G(S|FILE({s}GROUP))|NG(BLOB|TEXT)?|C(K(S)?|AL(TIME(STAMP)?)?)|OP|W_PRIORITY|AD{s}(DATA|INDEX{s}INTO{s}CACHE|XML))|E(SS|VEL|FT|A(DING|VE(S)?))|A(ST|NGUAGE))) keywords (X(OR|509|A)|S(MALLINT|SL|H(OW({s}(E(NGINE(S)?|RRORS)|M(ASTER|UTEX)|BINLOG|GRANTS|INNODB|P(RIVILEGES|ROFILE(S)?|ROCEDURE{s}CODE)|SLAVE{s}(HOSTS|STATUS)|TRIGGERS|VARIABLES|WARNINGS|(FULL{s})?PROCESSLIST|FIELDS|PLUGIN(S)?|STORAGE{s}ENGINES|TABLE{s}TYPES|CO(LUMNS|LLATION)|BINLOG{s}EVENTS))?|UTDOWN|ARE)|NAPSHOT|CHE(MA(S|_NAME)?|DULE(R)?)|T(R(ING|AIGHT_JOIN)|O(RAGE|P)|A(RT(S|ING{s}BY)?|TUS))|I(GN(ED|AL)|MPLE)|O(ME|NAME|CKET|UNDS)|U(B(CLASS_ORIGIN|JECT|PARTITION(S)?)|SPEND|PER)|P(ECIFIC|ATIAL)|E(R(IAL(IZABLE)?|VER)|SSION|NSITIVE|C(OND(_MICROSECOND)?|URITY)|T({s}(PASSWORD|NAMES|ONE_SHOT))?|PARATOR|LECT)|QL(STATE|_(MAX_JOIN_SIZE|B(IG_(RESULT|SELECTS|TABLES)|UFFER_RESULT)|S(MALL_RESULT|ELECT_LIMIT|LAVE_SKIP_COUNTER|AFE_UPDATES)|NO_CACHE|CA(CHE|LC_FOUND_ROWS)|T(SI_(M(INUTE|ONTH)|SECOND|HOUR|YEAR|DAY|QUARTER|FRAC_SECOND|WEEK)|HREAD)|QUOTE_SHOW_CREATE|WARNINGS|LO(G_(BIN|OFF|UPDATE)|W_PRIORITY_UPDATES)|AUTO_IS_NULL)|EXCEPTION|WARNING)?|L(OW|AVE)|AVEPOINT)|YEAR(_MONTH)?|T(R(IGGER(S)?|U(NCATE|E)|A(NSACTION|ILING))|H(EN|AN)|YPE|I(ME(STAMP(DIFF|ADD)?)?|NY(BLOB|TEXT|INT))|O|E(RMINATED{s}BY|XT|MP(TABLE|ORARY))|ABLE(S(PACE)?|_NAME)?)|ZEROFILL|U(S(ING|E(R(_RESOURCES)?|_FRM)?|AGE)|N(SIGNED|COMMITTED|TIL|I(NSTALL({s}PLUGIN)?|CODE|ON|QUE)|D(O(_BUFFER_SIZE|FILE)?|EFINED)|KNOWN|LOCK)|TC_(TIME(STAMP)?|DATE)|P(GRADE|DATE))|V(IEW|A(R(BINARY|YING|CHAR(ACTER)?|IABLES)|LUE(S)?))|W(R(ITE|APPER)|H(ILE|E(RE|N))|ITH({s}PARSER)?|ORK|EEK|A(RNINGS|IT))) @@ -115,7 +114,7 @@ keywords (X(OR|509|A)|S(MALLINT|SL|H(OW({s}(E(NGINE(S)?|RRORS)|M(ASTER|UTEX)|BIN {word}+ { return SPT_WORD; } /* return any word */ -{nonword} { return SPT_OTHER; } /* return anything else */ +. { return SPT_OTHER; } /* return anything else */ -- cgit v1.2.3 From c25bb060a197deecc79dac86e24df8246a87db71 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 1 Feb 2015 18:36:22 +0100 Subject: Update lexer to reflect that backticks can actually escape themselves (won't cause visible changes) --- Source/SPEditorTokens.l | 2 +- Source/SPSQLTokenizer.l | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'Source') diff --git a/Source/SPEditorTokens.l b/Source/SPEditorTokens.l index 8a7c317b..e2d3099a 100644 --- a/Source/SPEditorTokens.l +++ b/Source/SPEditorTokens.l @@ -80,7 +80,7 @@ keywords (X(OR|509|A)|S(MALLINT|SL|H(OW({s}(E(NGINE(S)?|RRORS)|M(ASTER|UTEX)|BIN \"([^"\\]|\\(.|[\n\r]))*\"? { return SPT_DOUBLE_QUOTED_TEXT; } /* double quoted strings */ '([^'\\]|\\(.|[\n\r]))*'? { return SPT_SINGLE_QUOTED_TEXT; } /* single quoted strings */ -`[^`]*`? { return SPT_BACKTICK_QUOTED_TEXT; } /* backtick quoted string */ +`(``|[^`])*`? { return SPT_BACKTICK_QUOTED_TEXT; } /* backtick quoted string */ "/*" { BEGIN(comment); return SPT_COMMENT; } /* beginning of a c style comment */ [^*]* { return SPT_COMMENT; } /* anything except * in a c cmnt */ diff --git a/Source/SPSQLTokenizer.l b/Source/SPSQLTokenizer.l index b9170edb..f33d373d 100644 --- a/Source/SPSQLTokenizer.l +++ b/Source/SPSQLTokenizer.l @@ -63,7 +63,7 @@ compend {s}"end" \"([^"\\]|\\(.|[\n\r]))*\"? { ; } '([^'\\]|\\(.|[\n\r]))*'? { ; } -`[^`]*`? { ; } +`(``|[^`])*`? { ; } "/*" { BEGIN(comment); } [^*]* { ; } -- cgit v1.2.3 From 60a5d64518f09af80059e2e293849ff6b0d6be75 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 1 Feb 2015 20:19:52 +0100 Subject: Change lexer definition of high bytes. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit flex does not(*) support UTF-8, therefore alpha [a-z_\.À-゚] has always been interpreted by flex as alpha [a-z_\.\xC3\x80-\xEF\xBE\x9F] I assume this is not what was indetend and the only reason it worked, is because C3 (195),BE (190) and 9F (159) are already covered by 80-EF (128-239). Incidentally this range would also cover the whole Unicode BMP in UTF8. This change should make it more obvious. (*) There were some patches in 2012 and 2014 but they don't seem to have been merged. --- Source/SPEditorTokens.l | 6 +++--- Source/SPSQLTokenizer.l | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPEditorTokens.l b/Source/SPEditorTokens.l index e2d3099a..2ac99be8 100644 --- a/Source/SPEditorTokens.l +++ b/Source/SPEditorTokens.l @@ -56,11 +56,11 @@ size_t yyuoffset, yyuleng; %option case-insensitive s [ \t\n\r]+ -alpha [a-z_\.À-゚] +alpha [a-z_\.\x80-\xEF] numeric ([+-]?(([0-9]+\.[0-9]+)|([0-9]*\.[0-9]+)|([0-9]+))(e[+-]?[0-9]+)?) ops "+"|"-"|"*"|"/" -word [a-z_\.0-9À-゚@] -variable @{1,2}[a-z_\.0-9À-゚$]+ +word [a-z_\.0-9\x80-\xEF@] +variable @{1,2}[a-z_\.0-9\x80-\xEF$]+ keyworda (G(R(OUP{s}BY|ANT(S)?)|E(NERAL|T_FORMAT|OMETRY(COLLECTION)?)|LOBAL)|B(Y(TE)?|TREE|I(GINT|N(LOG|ARY)|T)|O(TH|OL(EAN)?)|E(GIN|TWEEN|FORE)|LOB|ACKUP{s}TABLE)|H(IGH_PRIORITY|O(ST(S)?|UR(_(MI(NUTE|CROSECOND)|SECOND))?)|ELP|A(SH|NDLER|VING))|C(R(OSS|EATE)|H(ECK(SUM)?|A(R(SET|ACTER)?|NGE(D)?|IN))|IPHER|O(M(M(IT(TED)?|ENT)|P(RESSED|LETION|ACT))|N(S(TRAINT(_(SCHEMA|NAME|CATALOG))?|ISTENT)|NECTION|CURRENT|T(RIBUTORS|INUE|AINS)|DITION|VERT)|DE|L(UMN(S|_(NAME|FORMAT))?|LATE)|ALESCE{s}PARTITION)|U(R(RENT_(TIME(STAMP)?|DATE|USER)|SOR(_NAME)?)|BE)|L(IENT|OSE|ASS_ORIGIN)|A(S(CADE(D)?|E)|CHE{s}INDEX|TALOG_NAME|LL))|I(GNORE(_SERVER_IDS)?|MPORT{s}TABLESPACE|S(SUER|OLATION)?|N(S(TALL({s}PLUGIN)?|E(RT(_METHOD)?|NSITIVE))|N(O(BASE|DB)|ER)|T(1|2|8|3|O({s}(DUMP|OUT)FILE)?|4|E(RVAL|GER))?|ITIAL_SIZE|OUT|DEX(ES)?|VOKER|FILE)?|TERATE|O_THREAD|DENTIFIED|F)|D(ROP|YNAMIC|I(RECTORY|S(CARD{s}TABLESPACE|TINCT(ROW)?|K|ABLE{s}KEYS)|V)|O(UBLE)?|U(MPFILE|PLICATE|AL)|E(S(C(RIBE)?|_KEY_FILE)|C(IMAL|LARE)?|TERMINISTIC|F(INER|AULT)|L(ETE|AY(_KEY_WRITE|ED))|ALLOCATE)|A(Y(_(MI(NUTE|CROSECOND)|SECOND|HOUR))?|T(E(TIME)?|A(BASE(S)?|FILE)?)))|JOIN|E(RRORS|X(TEN(T_SIZE|DED)|I(STS|T)|P(LAIN|ANSION)|ECUTE)|SCAPE(D{s}BY)?|N(GINE(S)?|CLOSED{s}BY|D(S)?|UM|ABLE{s}KEYS)|VE(RY|NT)|LSE(IF)?|ACH)|K(ILL({s}(CONNECTION|QUERY))?|EY(S|_BLOCK_SIZE)?)|F(R(OM|AC_SECOND)|I(RST|XED|LE)|O(R(CE|EIGN)?|UND)|U(NCTION|LL(TEXT)?)|ETCH|L(OAT(8|4)?|USH)|A(ST|LSE))|A(G(GREGATE|AINST)|S(C(II)?|ENSITIVE)?|N(Y|D|ALYZE)|C(CESSIBLE|TION)|T|DD|UT(HORS|O(_INCREMENT|EXTEND_SIZE))|VG(_ROW_LENGTH)?|FTER|L(GORITHM|TER|L))) keywordl (R(TREE|IGHT|O(UTINE|W(S|_FORMAT)?|LL(BACK|UP))|E(GEXP|MOVE{s}PARTITIONING|BUILD{s}PARTITION|S(T(RICT|ORE{s}TABLE)|IGNAL|UME|ET)|NAME|COVER|TURN(S)?|ORGANIZE{s}PARTITION|D(O(_BUFFER_SIZE|FILE)|UNDANT)|P(EAT(ABLE)?|L(ICATION|ACE)|AIR)|VOKE|QUIRE|FERENCES|L(OAD|EASE|AY_(THREAD|LOG_(POS|FILE)))|A(D(S|_(ONLY|WRITE))?|L))|LIKE|ANGE)|M(YSQL_ERRNO|I(GRATE|N(_ROWS|UTE(_(MICROSECOND|SECOND))?)|CROSECOND|DDLEINT)|O(NTH|D(IF(Y|IES)|E)?)|U(TEX|LTI(PO(INT|LYGON)|LINESTRING))|E(RGE|MORY|SSAGE_TEXT|DIUM(BLOB|TEXT|INT)?)|A(X(_(ROWS|SIZE|CONNECTIONS_PER_HOUR|U(SER_CONNECTIONS|PDATES_PER_HOUR)|QUERIES_PER_HOUR)|VALUE)|STER(_(S(SL(_(C(IPHER|ERT|A(PATH)?)|VERIFY_SERVER_CERT|KEY))?|ERVER_ID)|H(OST|EARTBEAT_PERIOD)|CONNECT_RETRY|USER|P(ORT|ASSWORD)|LOG_(POS|FILE)))?|TCH))|N(CHAR|O(NE|_W(RITE_TO_BINLOG|AIT)|T|DEGROUP)?|DB(CLUSTER)?|U(MERIC|LL)|E(XT|W)|VARCHAR|A(ME(S)?|T(IONAL|URAL)))|O(R(DER{s}BY)?|N(({s}DUPLICATE{s}KEY{s}UPDATE)?|E(_SHOT)?|LINE)?|UT(ER|FILE)?|P(TI(MIZE|ON(S|ALLY)?)|EN)|FF(SET|LINE)|WNER|LD_PASSWORD)|P(R(I(MARY|VILEGES)|OCE(SS|DURE{s}(ANALYSE)?)|E(SERVE|CISION|PARE|V))|HASE|O(RT|INT|LYGON)|URGE|A(R(SER|TI(TION(S|ING)?|AL))|SSWORD|CK_KEYS))|QU(ICK|ERY|ARTER)|L(I(MIT|ST|NE(S(TRING)?|AR)|KE)|O(G(S|FILE({s}GROUP))|NG(BLOB|TEXT)?|C(K(S)?|AL(TIME(STAMP)?)?)|OP|W_PRIORITY|AD{s}(DATA|INDEX{s}INTO{s}CACHE|XML))|E(SS|VEL|FT|A(DING|VE(S)?))|A(ST|NGUAGE))) keywords (X(OR|509|A)|S(MALLINT|SL|H(OW({s}(E(NGINE(S)?|RRORS)|M(ASTER|UTEX)|BINLOG|GRANTS|INNODB|P(RIVILEGES|ROFILE(S)?|ROCEDURE{s}CODE)|SLAVE{s}(HOSTS|STATUS)|TRIGGERS|VARIABLES|WARNINGS|(FULL{s})?PROCESSLIST|FIELDS|PLUGIN(S)?|STORAGE{s}ENGINES|TABLE{s}TYPES|CO(LUMNS|LLATION)|BINLOG{s}EVENTS))?|UTDOWN|ARE)|NAPSHOT|CHE(MA(S|_NAME)?|DULE(R)?)|T(R(ING|AIGHT_JOIN)|O(RAGE|P)|A(RT(S|ING{s}BY)?|TUS))|I(GN(ED|AL)|MPLE)|O(ME|NAME|CKET|UNDS)|U(B(CLASS_ORIGIN|JECT|PARTITION(S)?)|SPEND|PER)|P(ECIFIC|ATIAL)|E(R(IAL(IZABLE)?|VER)|SSION|NSITIVE|C(OND(_MICROSECOND)?|URITY)|T({s}(PASSWORD|NAMES|ONE_SHOT))?|PARATOR|LECT)|QL(STATE|_(MAX_JOIN_SIZE|B(IG_(RESULT|SELECTS|TABLES)|UFFER_RESULT)|S(MALL_RESULT|ELECT_LIMIT|LAVE_SKIP_COUNTER|AFE_UPDATES)|NO_CACHE|CA(CHE|LC_FOUND_ROWS)|T(SI_(M(INUTE|ONTH)|SECOND|HOUR|YEAR|DAY|QUARTER|FRAC_SECOND|WEEK)|HREAD)|QUOTE_SHOW_CREATE|WARNINGS|LO(G_(BIN|OFF|UPDATE)|W_PRIORITY_UPDATES)|AUTO_IS_NULL)|EXCEPTION|WARNING)?|L(OW|AVE)|AVEPOINT)|YEAR(_MONTH)?|T(R(IGGER(S)?|U(NCATE|E)|A(NSACTION|ILING))|H(EN|AN)|YPE|I(ME(STAMP(DIFF|ADD)?)?|NY(BLOB|TEXT|INT))|O|E(RMINATED{s}BY|XT|MP(TABLE|ORARY))|ABLE(S(PACE)?|_NAME)?)|ZEROFILL|U(S(ING|E(R(_RESOURCES)?|_FRM)?|AGE)|N(SIGNED|COMMITTED|TIL|I(NSTALL({s}PLUGIN)?|CODE|ON|QUE)|D(O(_BUFFER_SIZE|FILE)?|EFINED)|KNOWN|LOCK)|TC_(TIME(STAMP)?|DATE)|P(GRADE|DATE))|V(IEW|A(R(BINARY|YING|CHAR(ACTER)?|IABLES)|LUE(S)?))|W(R(ITE|APPER)|H(ILE|E(RE|N))|ITH({s}PARSER)?|ORK|EEK|A(RNINGS|IT))) diff --git a/Source/SPSQLTokenizer.l b/Source/SPSQLTokenizer.l index f33d373d..5b08f312 100644 --- a/Source/SPSQLTokenizer.l +++ b/Source/SPSQLTokenizer.l @@ -50,7 +50,7 @@ size_t yyuoffset, yyuleng; s [ \t\n\r] dkey "delimiter" scol ";" -dval [!-゚] +dval [!-\x7E\x80-\xEF] compstart "begin"{s} compend {s}"end" %x comment -- cgit v1.2.3 From 24fcf917473862ddabc2095447f3ec5c4e9081fd Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 1 Feb 2015 20:51:54 +0100 Subject: Rename utf8 and utf8mb4 * To reduce confusion (and create some, for those people not yet aware of the difference) I have renamed the utf8s to "UTF-8 Unicode BMP" resp. "UTF-8 Full Unicode" according to their supported character range. * Also *both* utf8 variants will now be at the top of the list when creating new tables/databases --- Source/SPCharsetCollationHelper.m | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'Source') diff --git a/Source/SPCharsetCollationHelper.m b/Source/SPCharsetCollationHelper.m index 14b0a987..378fb7cf 100644 --- a/Source/SPCharsetCollationHelper.m +++ b/Source/SPCharsetCollationHelper.m @@ -133,6 +133,8 @@ if (([encodings count] > 0) && [serverSupport supportsPost41CharacterSetHandling]) { + NSUInteger utf8encounters = 0; + for (NSDictionary *encoding in encodings) { NSString *charsetId = [encoding objectForKey:@"CHARACTER_SET_NAME"]; @@ -146,12 +148,9 @@ if(selectedCharset && [charsetId isEqualToString:selectedCharset]) selectedRef = menuItem; - // If the UTF8 entry has been encountered, promote it to the top of the list - if (promoteUTF8 && [charsetId isEqualToString:@"utf8"]) { - [[charsetButton menu] insertItem:[menuItem autorelease] atIndex:0]; - //only add a separator if there actually are more items other than utf8 (might not be true for mysql forks) - if([encodings count] > 1) - [[charsetButton menu] insertItem:[NSMenuItem separatorItem] atIndex:1]; + // If an UTF8 entry has been encountered, promote it to the top of the list + if (promoteUTF8 && [charsetId hasPrefix:@"utf8"]) { + [[charsetButton menu] insertItem:[menuItem autorelease] atIndex:(utf8encounters++)]; } else { [[charsetButton menu] addItem:[menuItem autorelease]]; @@ -159,6 +158,10 @@ } + //only add a separator if there actually are more items other than utf8 (might not be true for mysql forks) + if(utf8encounters && [encodings count] > utf8encounters) + [[charsetButton menu] insertItem:[NSMenuItem separatorItem] atIndex:utf8encounters]; + [charsetButton setEnabled:YES]; } -- cgit v1.2.3 From 19a1c9f81ec1ae6f5518babfb974ad7f01407b16 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 3 Feb 2015 23:01:42 +0100 Subject: Fix some minor compiler warnings --- Source/SPExportController+SharedPrivateAPI.h | 35 ++++++++++++++++++++++++++++ Source/SPExportController.m | 1 + Source/SPExportFileUtilities.m | 4 +--- Source/SPExportFilenameUtilities.m | 6 +++++ Source/SPExportInitializer.m | 6 +++++ Source/SPTablesList.m | 2 +- 6 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 Source/SPExportController+SharedPrivateAPI.h (limited to 'Source') diff --git a/Source/SPExportController+SharedPrivateAPI.h b/Source/SPExportController+SharedPrivateAPI.h new file mode 100644 index 00000000..067c4645 --- /dev/null +++ b/Source/SPExportController+SharedPrivateAPI.h @@ -0,0 +1,35 @@ +// +// SPExportController+SharedPrivateAPI.h +// sequel-pro +// +// Created by Max Lohrmann on 03.02.15. +// Copyright (c) 2015 Max Lohrmann. 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 + +#import "SPExportController.h" + +@interface SPExportController (SharedPrivateAPI) +- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; +@end diff --git a/Source/SPExportController.m b/Source/SPExportController.m index f650bab9..c13e4fc6 100644 --- a/Source/SPExportController.m +++ b/Source/SPExportController.m @@ -41,6 +41,7 @@ #import "SPDatabaseDocument.h" #import "SPThreadAdditions.h" #import "SPCustomQuery.h" +#import "SPExportController+SharedPrivateAPI.h" #import diff --git a/Source/SPExportFileUtilities.m b/Source/SPExportFileUtilities.m index 778deb3e..0cecad91 100644 --- a/Source/SPExportFileUtilities.m +++ b/Source/SPExportFileUtilities.m @@ -36,6 +36,7 @@ #import "SPCustomQuery.h" #import "SPTableContent.h" #import "SPTableContentDelegate.h" +#import "SPExportController+SharedPrivateAPI.h" #import @@ -48,10 +49,7 @@ typedef enum SPExportErrorChoice; @interface SPExportController (SPExportFileUtilitiesPrivateAPI) - - (void)_reopenExportSheet; -- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; - @end @implementation SPExportController (SPExportFileUtilitiesPrivateAPI) diff --git a/Source/SPExportFilenameUtilities.m b/Source/SPExportFilenameUtilities.m index b0070f31..df9d3a69 100644 --- a/Source/SPExportFilenameUtilities.m +++ b/Source/SPExportFilenameUtilities.m @@ -298,6 +298,12 @@ case SPDotExport: extension = @"dot"; break; + case SPPDFExport: + case SPHTMLExport: + case SPExcelExport: + default: + [NSException raise:NSInvalidArgumentException format:@"unsupported exportType=%lu",exportType]; + return nil; } if ([exportOutputCompressionFormatPopupButton indexOfSelectedItem] != SPNoCompression) { diff --git a/Source/SPExportInitializer.m b/Source/SPExportInitializer.m index 26cdd0dc..7794d1e4 100644 --- a/Source/SPExportInitializer.m +++ b/Source/SPExportInitializer.m @@ -168,6 +168,12 @@ case SPDotExport: exportTypeLabel = @"Dot"; break; + case SPPDFExport: + case SPHTMLExport: + case SPExcelExport: + default: + [NSException raise:NSInvalidArgumentException format:@"unsupported exportType=%lu",exportType]; + return; } // Begin the export based on the source diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m index 76f6d1ce..74523da3 100644 --- a/Source/SPTablesList.m +++ b/Source/SPTablesList.m @@ -1275,7 +1275,7 @@ static NSString *SPDuplicateTable = @"SPDuplicateTable"; { NSMutableArray *returnArray = [NSMutableArray array]; NSUInteger i; - NSInteger cnt = [[self tables] count]; + NSUInteger cnt = [[self tables] count]; for(i=0; i Date: Sun, 8 Feb 2015 04:40:59 +0100 Subject: Fix one case of "SSH input fields cut off" When the last selected favorite was "Quick Connect" with SSH, on the next launch SSH would be re-selected, but the fields other than SSH Host would be cut off. This was caused by a race condition between our window setup code and Cocoas window restoration code. Solved by disabling window restoration for now (didn't really work for us anyway). --- Source/SPWindowController.m | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'Source') diff --git a/Source/SPWindowController.m b/Source/SPWindowController.m index 0666f1a7..58afeb16 100644 --- a/Source/SPWindowController.m +++ b/Source/SPWindowController.m @@ -90,6 +90,12 @@ enum { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabDragStarted:) name:PSMTabDragDidBeginNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabDragStopped:) name:PSMTabDragDidEndNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_updateLineHidingViewState) name:SPWindowToolbarDidToggleNotification object:nil]; + + // Because we are a document-based app we automatically adopt window restoration on 10.7+. + // However that causes a race condition with our own window setup code. + // Remove this when we actually support restoration. + if([[self window] respondsToSelector:@selector(setRestorable:)]) + [[self window] setRestorable:NO]; } #pragma mark - -- cgit v1.2.3 From fa28b26e418f6f5c2f47ec78f9b7ef4910155b96 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 14 Feb 2015 21:45:08 +0100 Subject: Move some duplicate code into a new class (This also affects PSMSequelProTabStyle, but see the comment there why it is left unchanged) --- Source/SPFavoritesOutlineView.h | 5 ++- Source/SPFavoritesOutlineView.m | 7 ++- Source/SPOSInfo.h | 50 ++++++++++++++++++++++ Source/SPOSInfo.m | 94 +++++++++++++++++++++++++++++++++++++++++ Source/SPSSHTunnel.m | 6 +-- Source/SPWindowController.h | 2 +- Source/SPWindowController.m | 7 +-- 7 files changed, 156 insertions(+), 15 deletions(-) create mode 100644 Source/SPOSInfo.h create mode 100644 Source/SPOSInfo.m (limited to 'Source') diff --git a/Source/SPFavoritesOutlineView.h b/Source/SPFavoritesOutlineView.h index 8a671f3c..2c3d475c 100644 --- a/Source/SPFavoritesOutlineView.h +++ b/Source/SPFavoritesOutlineView.h @@ -28,10 +28,11 @@ // // More info at +#import "SPOSInfo.h" + @interface SPFavoritesOutlineView : NSOutlineView { - SInt32 systemVersion; - + BOOL isOSVersionAtLeast10_7_0; BOOL justGainedFocus; } diff --git a/Source/SPFavoritesOutlineView.m b/Source/SPFavoritesOutlineView.m index 01eb7b04..2e111925 100644 --- a/Source/SPFavoritesOutlineView.m +++ b/Source/SPFavoritesOutlineView.m @@ -39,8 +39,7 @@ static NSUInteger SPFavoritesOutlineViewUnindent = 6; - (void)awakeFromNib { - systemVersion = 0; - Gestalt(gestaltSystemVersion, &systemVersion); + isOSVersionAtLeast10_7_0 = [SPOSInfo isOSVersionAtLeastMajor:10 minor:7 patch:0]; } - (BOOL)acceptsFirstResponder @@ -129,7 +128,7 @@ static NSUInteger SPFavoritesOutlineViewUnindent = 6; NSRect superFrame = [super frameOfCellAtColumn:columnIndex row:rowIndex]; // On system versions lower than Lion, don't alter padding - if (systemVersion < 0x1070) { + if (!isOSVersionAtLeast10_7_0) { return superFrame; } @@ -159,7 +158,7 @@ static NSUInteger SPFavoritesOutlineViewUnindent = 6; } // On versions of Lion or above, amend the padding appropriately - if (systemVersion >= 0x1070) { + if (isOSVersionAtLeast10_7_0) { return NSMakeRect(superFrame.origin.x + SPFavoritesOutlineViewUnindent, superFrame.origin.y, superFrame.size.width, superFrame.size.height); } diff --git a/Source/SPOSInfo.h b/Source/SPOSInfo.h new file mode 100644 index 00000000..8b5bb65b --- /dev/null +++ b/Source/SPOSInfo.h @@ -0,0 +1,50 @@ +// +// SPOSInfo.h +// sequel-pro +// +// Created by Max Lohrmann on 14.02.15. +// Copyright (c) 2015 Max Lohrmann. 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 + +#import + +typedef struct { + NSInteger major; + NSInteger minor; + NSInteger patch; +} SPOSVersion; + +/** + * Compare two OS versions similar to strcmp() + * @param left One operand + * @param right The other operand + * @return A negative value if left < right, 0 is both are equal, a postive value if left > right + */ +int SPOSVersionCompare(SPOSVersion left, SPOSVersion right); + +@interface SPOSInfo : NSObject ++ (SPOSVersion)osVersion; ++ (BOOL)isOSVersionAtLeastMajor:(NSInteger)major minor:(NSInteger)minor patch:(NSInteger)patch; +@end diff --git a/Source/SPOSInfo.m b/Source/SPOSInfo.m new file mode 100644 index 00000000..5608e4cf --- /dev/null +++ b/Source/SPOSInfo.m @@ -0,0 +1,94 @@ +// +// SPOSInfo.m +// sequel-pro +// +// Created by Max Lohrmann on 14.02.15. +// Copyright (c) 2015 Max Lohrmann. 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 + +#import "SPOSInfo.h" + +#if __MAC_OS_X_VERSION_MAX_ALLOWED < __MAC_10_10 +// This code is available since 10.8 but public only since 10.10 +typedef struct { + NSInteger major; + NSInteger minor; + NSInteger patch; +} NSOperatingSystemVersion; + +@interface NSProcessInfo () +- (NSOperatingSystemVersion)operatingSystemVersion; +- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version; +@end + +#endif + +int SPOSVersionCompare(SPOSVersion left, SPOSVersion right) +{ + if(left.major != right.major) return (left.major < right.major)? -1 : 1; + if(left.minor != right.minor) return (left.minor < right.minor)? -1 : 1; + if(left.patch != right.patch) return (left.patch < right.patch)? -1 : 1; + return 0; +} + +@implementation SPOSInfo + ++ (SPOSVersion)osVersion +{ + NSProcessInfo *procInfo = [NSProcessInfo processInfo]; + if([procInfo respondsToSelector:@selector(operatingSystemVersion)]) { + NSOperatingSystemVersion nsVer = [procInfo operatingSystemVersion]; + //structs cannot be casted per C standard + SPOSVersion spVer = {nsVer.majorVersion,nsVer.minorVersion,nsVer.patchVersion}; + return spVer; + } + else { + SInt32 versionMajor = 0; + SInt32 versionMinor = 0; + SInt32 versionPatch = 0; + Gestalt(gestaltSystemVersionMajor, &versionMajor); + Gestalt(gestaltSystemVersionMinor, &versionMinor); + Gestalt(gestaltSystemVersionBugFix, &versionPatch); + + SPOSVersion spVer = {versionMajor,versionMinor,versionPatch}; + return spVer; + } +} + ++ (BOOL)isOSVersionAtLeastMajor:(NSInteger)major minor:(NSInteger)minor patch:(NSInteger)patch +{ + NSProcessInfo *procInfo = [NSProcessInfo processInfo]; + if([procInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)]) { + NSOperatingSystemVersion nsVer = {major,minor,patch}; + return [procInfo isOperatingSystemAtLeastVersion:nsVer]; + } + else { + SPOSVersion runningVersion = [self osVersion]; + SPOSVersion referenceVersion = {major, minor, patch}; + return (SPOSVersionCompare(runningVersion, referenceVersion) >= 0); + } +} + +@end diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index 3b58d331..e09d0ce2 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -35,6 +35,7 @@ #import "SPKeychain.h" #import "SPAlertSheets.h" #import "SPThreadAdditions.h" +#import "SPOSInfo.h" #import #import @@ -55,8 +56,7 @@ if (!theHost || !targetPort || !targetHost) return nil; if ((self = [super init])) { - SInt32 systemVersion = 0; - Gestalt(gestaltSystemVersion, &systemVersion); + BOOL isOSVersionAtLeast10_7_0 = [SPOSInfo isOSVersionAtLeastMajor:10 minor:7 patch:0]; // Store the connection settings as appropriate sshHost = [[NSString alloc] initWithString:theHost]; @@ -74,7 +74,7 @@ // Enable connection muxing on 10.7+, but only if a preference is enabled; this is because // muxing causes connection instability for a large number of users (see Issue #1457) - connectionMuxingEnabled = (systemVersion >= 0x1070) && [[NSUserDefaults standardUserDefaults] boolForKey:SPSSHEnableMuxingPreference]; + connectionMuxingEnabled = isOSVersionAtLeast10_7_0 && [[NSUserDefaults standardUserDefaults] boolForKey:SPSSHEnableMuxingPreference]; // Set up a connection for use by the tunnel process tunnelConnectionName = [[NSString alloc] initWithFormat:@"SequelPro-%lu", (unsigned long)[[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]] hash]]; diff --git a/Source/SPWindowController.h b/Source/SPWindowController.h index 8697e738..c99a2ff2 100644 --- a/Source/SPWindowController.h +++ b/Source/SPWindowController.h @@ -37,7 +37,7 @@ IBOutlet NSTabView *tabView; NSClipView *titleBarLineHidingView; - SInt32 systemVersion; + BOOL isOSVersionAtLeast10_7_0; NSMenuItem *closeWindowMenuItem; NSMenuItem *closeTabMenuItem; diff --git a/Source/SPWindowController.m b/Source/SPWindowController.m index 58afeb16..db94f5ce 100644 --- a/Source/SPWindowController.m +++ b/Source/SPWindowController.m @@ -63,11 +63,8 @@ enum { - (void)awakeFromNib { - systemVersion = 0; selectedTableDocument = nil; - Gestalt(gestaltSystemVersion, &systemVersion); - [[self window] setCollectionBehavior:[[self window] collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary]; // Add a line to the window to hide the line below the title bar when the toolbar is collapsed @@ -517,10 +514,10 @@ enum { { // Set the background colour to match the titlebar window state if ((([[self window] isMainWindow] || [[[self window] attachedSheet] isMainWindow]) && [NSApp isActive])) { - [titleBarLineHidingView setBackgroundColor:[NSColor colorWithCalibratedWhite:(systemVersion >= 0x1070) ? 0.66f : 0.63f alpha:1.0]]; + [titleBarLineHidingView setBackgroundColor:[NSColor colorWithCalibratedWhite:(isOSVersionAtLeast10_7_0) ? 0.66f : 0.63f alpha:1.0]]; } else { - [titleBarLineHidingView setBackgroundColor:[NSColor colorWithCalibratedWhite:(systemVersion >= 0x1070) ? 0.87f : 0.84f alpha:1.0]]; + [titleBarLineHidingView setBackgroundColor:[NSColor colorWithCalibratedWhite:(isOSVersionAtLeast10_7_0) ? 0.87f : 0.84f alpha:1.0]]; } // If the window is fullscreen or the toolbar is showing, hide the view; otherwise show it -- cgit v1.2.3 From 085b381858dcd3cda5c0b00527d3b7a77641345a Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 14 Feb 2015 23:05:52 +0100 Subject: Change look of the favorite color picker on 10.9+ --- Source/SPColorSelectorView.h | 2 + Source/SPColorSelectorView.m | 141 ++++++++++++++++++++++--------------------- 2 files changed, 75 insertions(+), 68 deletions(-) (limited to 'Source') diff --git a/Source/SPColorSelectorView.h b/Source/SPColorSelectorView.h index b3d9325e..925034a3 100644 --- a/Source/SPColorSelectorView.h +++ b/Source/SPColorSelectorView.h @@ -57,6 +57,8 @@ IBOutlet id delegate; NSArray *colorList; + + BOOL isOSAtLeast10_9_0; } @property (nonatomic,readwrite,assign) NSInteger selectedTag; diff --git a/Source/SPColorSelectorView.m b/Source/SPColorSelectorView.m index f2eade86..ba577170 100644 --- a/Source/SPColorSelectorView.m +++ b/Source/SPColorSelectorView.m @@ -41,10 +41,13 @@ // More info at #import "SPColorSelectorView.h" +#import "SPOSInfo.h" @interface SPColorSelectorView (Private) - (void)setupTrackingAreas; +- (void)_drawDotBevelStyleWithGradient:(NSGradient *)gradient insideRect:(NSRect)colorSquareRect; +- (void)_drawDotFlatStyleWithColor:(NSColor *)color insideRect:(NSRect)colorSquareRect; @end @@ -86,6 +89,8 @@ enum trackingAreaIDs //set ourselves as observer of selectedTag (need to mark view dirty) [self addObserver:self forKeyPath:@"selectedTag" options:0 context:nil]; + + isOSAtLeast10_9_0 = [SPOSInfo isOSVersionAtLeastMajor:10 minor:9 patch:0]; } return self; @@ -126,9 +131,9 @@ enum trackingAreaIDs - (NSRect)rectForColorViewAtIndex:(NSInteger)index { CGFloat baseY = 2.0; - CGFloat baseX = 2.0; + CGFloat baseX = 3.0; - CGFloat marginR = 5.0; + CGFloat marginR = 7.0; CGFloat width = 16.0; CGFloat height = 16.0; @@ -138,46 +143,20 @@ enum trackingAreaIDs switch (index) { case kTrackingAreaNone: - returnRect = NSMakeRect(baseX, baseY, width, height); - break; - case kTrackingArea0: - returnRect = NSMakeRect(baseX + 1 * (width + marginR), baseY, width, height); - break; - case kTrackingArea1: - returnRect = NSMakeRect(baseX + 2 * (width + marginR), baseY, width, height); - break; - case kTrackingArea2: - returnRect = NSMakeRect(baseX + 3 * (width + marginR), baseY, width, height); - break; - case kTrackingArea3: - returnRect = NSMakeRect(baseX + 4 * (width + marginR), baseY, width, height); - break; - case kTrackingArea4: - returnRect = NSMakeRect(baseX + 5 * (width + marginR), baseY, width, height); - break; - case kTrackingArea5: - returnRect = NSMakeRect(baseX + 6 * (width + marginR), baseY, width, height); - break; - case kTrackingArea6: - returnRect = NSMakeRect(baseX + 7 * (width + marginR), baseY, width, height); + returnRect = NSMakeRect(baseX + (index + 1) * (width + marginR), baseY, width, height); break; } return returnRect; } -// ------------------------------------------------------------------------------- -// Returns the color gradient corresponding to the tag. These colours were -// chosen to appear similar to those in Aperture 3. -// ------------------------------------------------------------------------------- - - (NSGradient *)gradientForTag:(NSInteger)colorTag { NSGradient *gradient = nil; @@ -289,53 +268,79 @@ enum trackingAreaIDs [left setLineWidth:3.0]; [left setLineCapStyle:NSButtLineCapStyle]; - [left moveToPoint:NSMakePoint(colorSquareRect.origin.x + 4.0, colorSquareRect.origin.y + 4.0)]; + [left moveToPoint:NSMakePoint(colorSquareRect.origin.x + 4.0, colorSquareRect.origin.y + 4.0)]; [left lineToPoint:NSMakePoint(colorSquareRect.origin.x + 12.0, colorSquareRect.origin.y + 12.0)]; - [left moveToPoint:NSMakePoint(colorSquareRect.origin.x + 12.0, colorSquareRect.origin.y + 4.0)]; - [left lineToPoint:NSMakePoint(colorSquareRect.origin.x + 4.0, colorSquareRect.origin.y + 12.0)]; + [left moveToPoint:NSMakePoint(colorSquareRect.origin.x + 12.0, colorSquareRect.origin.y + 4.0)]; + [left lineToPoint:NSMakePoint(colorSquareRect.origin.x + 4.0, colorSquareRect.origin.y + 12.0)]; [left stroke]; } else { - // draw the gradient dot - NSGradient *gradient = [self gradientForTag:index]; - NSRect dotRect = NSInsetRect(colorSquareRect, 2.0, 2.0); - NSBezierPath *circlePath = [NSBezierPath bezierPathWithOvalInRect:dotRect]; - [gradient drawInBezierPath:circlePath angle:-90.0]; - - // draw a highlight - - // top edge outline - gradient = [[NSGradient alloc] initWithColorsAndLocations: - [NSColor colorWithCalibratedWhite:1.0 alpha:0.18], 0.0, - [NSColor colorWithCalibratedWhite:1.0 alpha:0.0], 0.6, nil]; - circlePath = [NSBezierPath bezierPathWithOvalInRect:NSInsetRect(dotRect, 1.0, 1.0)]; - [circlePath appendBezierPath:[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(dotRect.origin.x+1.0, dotRect.origin.y-2.0, dotRect.size.width-2.0, dotRect.size.height)]]; - [circlePath setWindingRule:NSEvenOddWindingRule]; - [gradient drawInBezierPath:circlePath angle:-90.0]; - [gradient release]; - - // top center gloss - gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.18] - endingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.0]]; - [gradient drawFromCenter:NSMakePoint(NSMidX(dotRect), NSMaxY(dotRect) - 2.0) - radius:0.0 - toCenter:NSMakePoint(NSMidX(dotRect), NSMaxY(dotRect) - 2.0) - radius:4.0 - options:0]; - [gradient release]; - - // draw a dark outline - circlePath = [NSBezierPath bezierPathWithOvalInRect:dotRect]; - gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.12] - endingColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.46]]; - [circlePath appendBezierPath:[NSBezierPath bezierPathWithOvalInRect:NSInsetRect(dotRect, 1.0, 1.0)]]; - [circlePath setWindingRule:NSEvenOddWindingRule]; - [gradient drawInBezierPath:circlePath angle:-90.0]; - [gradient release]; + if(!isOSAtLeast10_9_0) { + NSGradient *gradient = [self gradientForTag:index]; + [self _drawDotBevelStyleWithGradient:gradient insideRect:colorSquareRect]; + } + else { + NSColor *baseColor = (NSColor *)[colorList objectAtIndex:index]; + [self _drawDotFlatStyleWithColor:baseColor insideRect:colorSquareRect]; + } } } } +- (void)_drawDotBevelStyleWithGradient:(NSGradient *)gradient insideRect:(NSRect)colorSquareRect +{ + // draw the gradient dot + NSRect dotRect = NSInsetRect(colorSquareRect, 2.0, 2.0); + NSBezierPath *circlePath = [NSBezierPath bezierPathWithOvalInRect:dotRect]; + [gradient drawInBezierPath:circlePath angle:-90.0]; + + // draw a highlight + + // top edge outline + NSGradient *grad = [[NSGradient alloc] initWithColorsAndLocations: + [NSColor colorWithCalibratedWhite:1.0 alpha:0.18], 0.0, + [NSColor colorWithCalibratedWhite:1.0 alpha:0.0], 0.6, nil]; + circlePath = [NSBezierPath bezierPathWithOvalInRect:NSInsetRect(dotRect, 1.0, 1.0)]; + [circlePath appendBezierPath:[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(dotRect.origin.x+1.0, dotRect.origin.y-2.0, dotRect.size.width-2.0, dotRect.size.height)]]; + [circlePath setWindingRule:NSEvenOddWindingRule]; + [grad drawInBezierPath:circlePath angle:-90.0]; + [grad release]; + + // top center gloss + NSGradient *grad2 = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.18] + endingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.0]]; + [grad2 drawFromCenter:NSMakePoint(NSMidX(dotRect), NSMaxY(dotRect) - 2.0) + radius:0.0 + toCenter:NSMakePoint(NSMidX(dotRect), NSMaxY(dotRect) - 2.0) + radius:4.0 + options:0]; + [grad2 release]; + + // draw a dark outline + circlePath = [NSBezierPath bezierPathWithOvalInRect:dotRect]; + NSGradient *grad3 = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.12] + endingColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.46]]; + [circlePath appendBezierPath:[NSBezierPath bezierPathWithOvalInRect:NSInsetRect(dotRect, 1.0, 1.0)]]; + [circlePath setWindingRule:NSEvenOddWindingRule]; + [grad3 drawInBezierPath:circlePath angle:-90.0]; + [grad3 release]; +} + +- (void)_drawDotFlatStyleWithColor:(NSColor *)color insideRect:(NSRect)colorSquareRect +{ + CGFloat h,s,b,a; + [color getHue:&h saturation:&s brightness:&b alpha:&a]; + + NSRect dotRect = NSInsetRect(colorSquareRect, 2.0, 2.0); + NSBezierPath *circlePath = [NSBezierPath bezierPathWithOvalInRect:dotRect]; + [[NSColor colorWithCalibratedHue:h saturation:s*1.21 brightness:b*1.1 alpha:a] set]; + [circlePath fill]; + + [[color shadowWithLevel:0.15f] set]; + [circlePath setLineWidth:1.0f]; + [circlePath stroke]; +} + #pragma mark - #pragma mark Mouse Handling -- cgit v1.2.3 From baa1593d4bd84b2eebc41821d5ff2b70013371bf Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 15 Feb 2015 02:59:14 +0100 Subject: Add basic color highlighting in favorites list --- Source/SPConnectionControllerDelegate.m | 8 ++++++ Source/SPFavoriteTextFieldCell.h | 2 ++ Source/SPFavoriteTextFieldCell.m | 45 +++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) (limited to 'Source') diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index a28a27b7..8cef86e9 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -32,6 +32,7 @@ #ifndef SP_CODA #import "SPFavoritesController.h" #import "SPTableTextFieldCell.h" +#import "SPFavoriteTextFieldCell.h" #import "SPPreferenceController.h" #import "SPGeneralPreferencePane.h" #import "SPAppController.h" @@ -39,6 +40,7 @@ #import "SPGroupNode.h" #import "SPTreeNode.h" #import "SPFavoritesOutlineView.h" +#import "SPFavoriteColorSupport.h" #endif #ifndef SP_CODA @@ -171,6 +173,12 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; } else { [(SPTableTextFieldCell *)cell setImage:[NSImage imageNamed:SPDatabaseImage]]; + NSColor *bgColor = nil; + NSNumber *colorIndexObj = [[[node representedObject] nodeFavorite] objectForKey:SPFavoriteColorIndexKey]; + if(colorIndexObj != nil) { + bgColor = [[SPFavoriteColorSupport sharedInstance] colorForIndex:[colorIndexObj integerValue]]; + } + [(SPFavoriteTextFieldCell *)cell setLabelColor:bgColor]; } } diff --git a/Source/SPFavoriteTextFieldCell.h b/Source/SPFavoriteTextFieldCell.h index afc32bcb..931d767d 100644 --- a/Source/SPFavoriteTextFieldCell.h +++ b/Source/SPFavoriteTextFieldCell.h @@ -38,4 +38,6 @@ - (BOOL)drawsDividerUnderCell; - (void)setDrawsDividerUnderCell:(BOOL)drawsDivider; +@property(copy)NSColor *labelColor; + @end diff --git a/Source/SPFavoriteTextFieldCell.m b/Source/SPFavoriteTextFieldCell.m index 41511c8c..c5ec9150 100644 --- a/Source/SPFavoriteTextFieldCell.m +++ b/Source/SPFavoriteTextFieldCell.m @@ -29,6 +29,9 @@ // More info at #import "SPFavoriteTextFieldCell.h" +#import "SPOSInfo.h" + +extern BOOL isOSAtLeast10_10_0(void); @implementation SPFavoriteTextFieldCell @@ -46,6 +49,7 @@ SPFavoriteTextFieldCell *cell = (SPFavoriteTextFieldCell *)[super copyWithZone:zone]; cell->drawsDividerUnderCell = drawsDividerUnderCell; + cell->labelColor = nil; //TODO copying the color sometimes causes a drawing bug return cell; } @@ -68,8 +72,37 @@ drawsDividerUnderCell = drawsDivider; } +@synthesize labelColor; + #pragma mark - +- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView +{ + if([self labelColor]) { + CGFloat round = (cellFrame.size.height/2); + NSBezierPath *bg = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:round yRadius:round]; + + if(isOSAtLeast10_10_0()) { + CGFloat h,s,b,a; + [[self labelColor] getHue:&h saturation:&s brightness:&b alpha:&a]; + + [[NSColor colorWithCalibratedHue:h saturation:s*1.21 brightness:b*1.1 alpha:a] set]; + [bg fill]; + } + else { + NSGradient * gradient = [[NSGradient alloc] initWithColorsAndLocations: + [[self labelColor] highlightWithLevel:0.33], 0.0, + [self labelColor], 0.5, + [[self labelColor] shadowWithLevel:0.15], 1.0, nil]; + [gradient drawInBezierPath:bg angle:90.0]; + [gradient release]; + } + } + + [super drawWithFrame:cellFrame inView:controlView]; +} + + /** * Draws the actual cell, with a divider if appropriate. */ @@ -110,4 +143,16 @@ } } +- (void)dealloc +{ + [self setLabelColor:nil]; + + [super dealloc]; +} + @end + +BOOL isOSAtLeast10_10_0() { + const BOOL value = [SPOSInfo isOSVersionAtLeastMajor:10 minor:10 patch:0]; + return value; +} -- cgit v1.2.3 From 3fce6977d519fa80a96fcfa7baa476a3675a70da Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 15 Feb 2015 03:08:31 +0100 Subject: Fix compile error on older SDKs --- Source/SPOSInfo.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPOSInfo.m b/Source/SPOSInfo.m index 5608e4cf..8d91c067 100644 --- a/Source/SPOSInfo.m +++ b/Source/SPOSInfo.m @@ -33,9 +33,9 @@ #if __MAC_OS_X_VERSION_MAX_ALLOWED < __MAC_10_10 // This code is available since 10.8 but public only since 10.10 typedef struct { - NSInteger major; - NSInteger minor; - NSInteger patch; + NSInteger majorVersion; + NSInteger minorVersion; + NSInteger patchVersion; } NSOperatingSystemVersion; @interface NSProcessInfo () -- cgit v1.2.3 From 3d18994b788dc9563bba804e2eec56cd035bae09 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 15 Feb 2015 03:15:28 +0100 Subject: Fix compiler compatibility issue with older Xcode versions --- Source/SPFavoriteTextFieldCell.h | 1 + Source/SPFavoriteTextFieldCell.m | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'Source') diff --git a/Source/SPFavoriteTextFieldCell.h b/Source/SPFavoriteTextFieldCell.h index 931d767d..0e900636 100644 --- a/Source/SPFavoriteTextFieldCell.h +++ b/Source/SPFavoriteTextFieldCell.h @@ -33,6 +33,7 @@ @interface SPFavoriteTextFieldCell : ImageAndTextCell { BOOL drawsDividerUnderCell; + NSColor *labelColor; } - (BOOL)drawsDividerUnderCell; diff --git a/Source/SPFavoriteTextFieldCell.m b/Source/SPFavoriteTextFieldCell.m index c5ec9150..00c05da1 100644 --- a/Source/SPFavoriteTextFieldCell.m +++ b/Source/SPFavoriteTextFieldCell.m @@ -78,22 +78,22 @@ extern BOOL isOSAtLeast10_10_0(void); - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { - if([self labelColor]) { + if(labelColor) { CGFloat round = (cellFrame.size.height/2); NSBezierPath *bg = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:round yRadius:round]; if(isOSAtLeast10_10_0()) { CGFloat h,s,b,a; - [[self labelColor] getHue:&h saturation:&s brightness:&b alpha:&a]; + [labelColor getHue:&h saturation:&s brightness:&b alpha:&a]; [[NSColor colorWithCalibratedHue:h saturation:s*1.21 brightness:b*1.1 alpha:a] set]; [bg fill]; } else { NSGradient * gradient = [[NSGradient alloc] initWithColorsAndLocations: - [[self labelColor] highlightWithLevel:0.33], 0.0, - [self labelColor], 0.5, - [[self labelColor] shadowWithLevel:0.15], 1.0, nil]; + [labelColor highlightWithLevel:0.33], 0.0, + labelColor, 0.5, + [labelColor shadowWithLevel:0.15], 1.0, nil]; [gradient drawInBezierPath:bg angle:90.0]; [gradient release]; } -- cgit v1.2.3 From 2fda43e6a54c0c7532d80b9f3f86987ceb772342 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 15 Feb 2015 22:05:37 +0100 Subject: Refined the look of $(see last commit) on systems < 10.10 a bit --- Source/SPFavoriteTextFieldCell.m | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'Source') diff --git a/Source/SPFavoriteTextFieldCell.m b/Source/SPFavoriteTextFieldCell.m index 00c05da1..cf9f6a05 100644 --- a/Source/SPFavoriteTextFieldCell.m +++ b/Source/SPFavoriteTextFieldCell.m @@ -90,12 +90,54 @@ extern BOOL isOSAtLeast10_10_0(void); [bg fill]; } else { + // Draw main background gradient NSGradient * gradient = [[NSGradient alloc] initWithColorsAndLocations: [labelColor highlightWithLevel:0.33], 0.0, labelColor, 0.5, [labelColor shadowWithLevel:0.15], 1.0, nil]; [gradient drawInBezierPath:bg angle:90.0]; [gradient release]; + + //replace the shadow color of the highlighted item (the default is dark blue) + if([self isHighlighted]) { + NSMutableAttributedString *mas = [[self attributedStringValue] mutableCopy]; + NSShadow *strShadow = [mas attribute:NSShadowAttributeName atIndex:0 effectiveRange:NULL]; + if(strShadow) { + [strShadow setShadowColor:[labelColor shadowWithLevel:0.4]]; + [self setAttributedStringValue:mas]; + } + [mas release]; + } + + // Add a little border at the top half (technically this is an inner shadow) + CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort]; + + NSShadow* shadow = [[NSShadow alloc] init]; + [shadow setShadowColor:labelColor]; + [shadow setShadowOffset: NSMakeSize(0.1, -1.2)]; + [shadow setShadowBlurRadius: 1]; + + [NSGraphicsContext saveGraphicsState]; + NSRectClip([bg bounds]); + CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL); + + CGContextSetAlpha(context, [[shadow shadowColor] alphaComponent]); + CGContextBeginTransparencyLayer(context, NULL); + { + [shadow set]; + + CGContextSetBlendMode(context, kCGBlendModeSourceOut); + CGContextBeginTransparencyLayer(context, NULL); + + [[shadow shadowColor] setFill]; + [bg fill]; + + CGContextEndTransparencyLayer(context); + } + CGContextEndTransparencyLayer(context); + [NSGraphicsContext restoreGraphicsState]; + + [shadow release]; } } -- cgit v1.2.3 From 5f3c003919903c597b2d6aeb7fcc064b0d6d9ef3 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 19 Feb 2015 18:11:59 +0100 Subject: Fix a bug that could cause items in the favorite list to be color-labeled when they don't have a label assigned --- Source/SPConnectionControllerDelegate.m | 19 +++++++++++-------- Source/SPFavoriteTextFieldCell.m | 2 +- 2 files changed, 12 insertions(+), 9 deletions(-) (limited to 'Source') diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index 8cef86e9..f0813292 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -147,38 +147,41 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item { - SPTreeNode *node = (SPTreeNode *)item; + SPTreeNode *node = (SPTreeNode *)item; + SPFavoriteTextFieldCell *favoriteCell = (SPFavoriteTextFieldCell *)cell; // Draw entries with the small system font by default - [(SPTableTextFieldCell *)cell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; + [cell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; // Set an image as appropriate; the quick connect image for that entry, no image for other // top-level items, the folder image for group nodes, or the database image for other nodes. if (![[node parentNode] parentNode]) { if (node == quickConnectItem) { if ([outlineView rowForItem:item] == [outlineView selectedRow]) { - [(SPTableTextFieldCell *)cell setImage:[NSImage imageNamed:SPQuickConnectImageWhite]]; + [favoriteCell setImage:[NSImage imageNamed:SPQuickConnectImageWhite]]; } else { - [(SPTableTextFieldCell *)cell setImage:[NSImage imageNamed:SPQuickConnectImage]]; + [favoriteCell setImage:[NSImage imageNamed:SPQuickConnectImage]]; } } else { - [(SPTableTextFieldCell *)cell setImage:nil]; + [favoriteCell setImage:nil]; } + [favoriteCell setLabelColor:nil]; } else { if ([node isGroup]) { - [(SPTableTextFieldCell *)cell setImage:folderImage]; + [favoriteCell setImage:folderImage]; + [favoriteCell setLabelColor:nil]; } else { - [(SPTableTextFieldCell *)cell setImage:[NSImage imageNamed:SPDatabaseImage]]; + [favoriteCell setImage:[NSImage imageNamed:SPDatabaseImage]]; NSColor *bgColor = nil; NSNumber *colorIndexObj = [[[node representedObject] nodeFavorite] objectForKey:SPFavoriteColorIndexKey]; if(colorIndexObj != nil) { bgColor = [[SPFavoriteColorSupport sharedInstance] colorForIndex:[colorIndexObj integerValue]]; } - [(SPFavoriteTextFieldCell *)cell setLabelColor:bgColor]; + [favoriteCell setLabelColor:bgColor]; } } diff --git a/Source/SPFavoriteTextFieldCell.m b/Source/SPFavoriteTextFieldCell.m index cf9f6a05..5eb6c103 100644 --- a/Source/SPFavoriteTextFieldCell.m +++ b/Source/SPFavoriteTextFieldCell.m @@ -49,7 +49,7 @@ extern BOOL isOSAtLeast10_10_0(void); SPFavoriteTextFieldCell *cell = (SPFavoriteTextFieldCell *)[super copyWithZone:zone]; cell->drawsDividerUnderCell = drawsDividerUnderCell; - cell->labelColor = nil; //TODO copying the color sometimes causes a drawing bug + cell->labelColor = [labelColor copyWithZone:zone]; return cell; } -- cgit v1.2.3 From 89fb7e74a72b44a59d15117d4a6a2a9913bee591 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 3 Mar 2015 21:08:20 +0100 Subject: Fix an issue with connection color and cloned connections The red (first) connection color would not be duplicated to another tab, when choosing "Open Table in New X" from the context menu (issue reported by Kyle via e-mail). --- Source/SPDatabaseDocument.m | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index a14a6f03..7f531f60 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -4441,9 +4441,9 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; { BOOL returnConnection = [[detailsToReturn objectForKey:@"connection"] boolValue]; BOOL includePasswords = [[detailsToReturn objectForKey:@"password"] boolValue]; - BOOL returnSession = [[detailsToReturn objectForKey:@"session"] boolValue]; - BOOL returnHistory = [[detailsToReturn objectForKey:@"history"] boolValue]; - BOOL returnQuery = [[detailsToReturn objectForKey:@"query"] boolValue]; + BOOL returnSession = [[detailsToReturn objectForKey:@"session"] boolValue]; + BOOL returnHistory = [[detailsToReturn objectForKey:@"history"] boolValue]; + BOOL returnQuery = [[detailsToReturn objectForKey:@"query"] boolValue]; if (!returnConnection && !returnSession && !returnHistory && !returnQuery) return nil; NSMutableDictionary *stateDetails = [NSMutableDictionary dictionary]; @@ -4482,7 +4482,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [connection setObject:[self name] forKey:@"name"]; [connection setObject:[self host] forKey:@"host"]; [connection setObject:[self user] forKey:@"user"]; - if([connectionController colorIndex]) + if([connectionController colorIndex] >= 0) [connection setObject:[NSNumber numberWithInteger:[connectionController colorIndex]] forKey:SPFavoriteColorIndexKey]; if([connectionController port] && [[connectionController port] length]) [connection setObject:[NSNumber numberWithInteger:[[connectionController port] integerValue]] forKey:@"port"]; -- cgit v1.2.3 From 96b765ffbcb6c7fda058fbe8028b2e128007134a Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 7 Mar 2015 20:48:55 +0100 Subject: Added an internal algorithm for fuzzy string matching * This works similar to a regex matching "abc" as /a.*b.*c/ (ie. all characters of $needle need to be contained in $haystack in the correct order but not neccesarily consecutive). Additionaly some unicode equivalencies are handled. * Changed a tiny helper function from ObjC to plain C --- Source/SPStringAdditions.h | 19 +++++++++ Source/SPStringAdditions.m | 101 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 109 insertions(+), 11 deletions(-) (limited to 'Source') diff --git a/Source/SPStringAdditions.h b/Source/SPStringAdditions.h index 3296326f..c6871e2a 100644 --- a/Source/SPStringAdditions.h +++ b/Source/SPStringAdditions.h @@ -81,4 +81,23 @@ static inline id NSMutableAttributedStringAttributeAtIndex(NSMutableAttributedSt - (CGFloat)levenshteinDistanceWithWord:(NSString *)stringB; +/** + * Checks if the string other is contained in self on a per-character basis. + * In regex-speak that would mean "abc" is matched as /a.*b.*c/ (not anchored). + * This is a SEARCH function, NOT a MATCHING function! + * Namely the following options will be applied when matching: + * NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch|NSDiacriticInsensitiveSearch + * Additionaly this method might match even when it should not. + * + * @param other String to match against self + * @param submatches Pass the pointer to a variable that will be set to an NSArray * + * of NSNumber *s of NSRanges. This will only be the case if + * the method also returns YES. The variable will not be modified + * otherwise. + * Pass NULL if you don't care for the ranges. + * The object will be set to autorelase. + * @return YES if self contains all characters from other in the order given in other + * @warning This method is NOT thread-safe (probably), NOT constant-time and DOES NOT check binary equivalence + */ +- (BOOL)nonConsecutivelySearchString:(NSString *)other matchingRanges:(NSArray **)submatches; @end diff --git a/Source/SPStringAdditions.m b/Source/SPStringAdditions.m index 29b4144d..0c623af7 100644 --- a/Source/SPStringAdditions.m +++ b/Source/SPStringAdditions.m @@ -31,11 +31,7 @@ #import "SPStringAdditions.h" #import "RegexKitLite.h" -@interface NSString (PrivateAPI) - -- (NSInteger)_smallestOf:(NSInteger)a andOf:(NSInteger)b andOf:(NSInteger)c; - -@end +static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c); @implementation NSString (SPStringAdditions) @@ -426,9 +422,9 @@ cost = ([stringA characterAtIndex:i - 1] == [stringB characterAtIndex:j - 1]) ? 0 : 1; d[j * n + i] = - [self _smallestOf:d[(j - 1) * n + i] + 1 - andOf:d[j * n + i - 1] + 1 - andOf:d[(j - 1) * n + i -1] + cost]; + _smallestOf(d[(j - 1) * n + i] + 1, + d[j * n + i - 1] + 1, + d[(j - 1) * n + i -1] + cost); } distance = d[n * m - 1]; @@ -468,10 +464,95 @@ } } +- (BOOL)nonConsecutivelySearchString:(NSString *)other matchingRanges:(NSArray **)submatches +{ + NSStringCompareOptions opts = NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch|NSWidthInsensitiveSearch; + BOOL recordMatches = (submatches != NULL); //for readability + NSRange selfRange = NSMakeRange(0, [self length]); + + //shortcut: * a longer string can never be contained in a shorter one. + // * nil can never match in a string. + // * an empty other can never match if self is non-empty + if(([other length] > [self length]) || (!other) || ([self length] && ![other length])) + return NO; + + //handle the simple case via the default algorithm + if ([self compare:other options:opts] == NSOrderedSame) { + if(recordMatches) { + *submatches = [NSArray arrayWithObject:[NSValue valueWithRange:selfRange]]; + } + return YES; + } + + // for now let's save the overhead of NSArray and NSValues + NSRange *tmpMatchStore = recordMatches? calloc([other length], sizeof(NSRange)) : NULL; + __block NSUInteger matchCount = 0; + __block NSRange searchRange = selfRange; + + //this looks a bit silly but is basically Apples approach to handling multibyte charsets + void (^it)(NSString *,NSRange,NSRange,BOOL *) = ^(NSString *substring,NSRange substringRange,NSRange enclosingRange,BOOL *stop) { + //look for the current character of other in the remaining part of self + NSRange found = [self rangeOfString:substring options:opts range:searchRange]; + if(found.location == NSNotFound) { + matchCount = 0; //reset match count to "no match" + *stop = YES; + return; + } + if(recordMatches) + tmpMatchStore[matchCount] = found; + matchCount++; + //move the next search past the current match + searchRange.location = found.location + found.length; + searchRange.length = [self length] - searchRange.location; + }; + + [other enumerateSubstringsInRange:NSMakeRange(0, [other length]) + options:NSStringEnumerationByComposedCharacterSequences + usingBlock:it]; + + if(matchCount && recordMatches) { + //we want to re-combine sub-matches that are actually consecutive + + //This algorithm uses a simple look-behind for merges: + // Object 1 checks if it continues object 0. If so, 1 and 0 will merge + // and be placed in the slot of 0 (slot 1 is now invalid). + // Then object 2 checks if it continues object 0. If it does not, it is + // placed in slot 1. + // Object 3 then checks if it continues object 1 and so on... + NSUInteger mergeTarget = 0; + for (NSUInteger i = 1; i < matchCount; i++ ) { + NSRange prev = tmpMatchStore[mergeTarget]; + NSRange this = tmpMatchStore[i]; + //if the previous match ends right before this match begins we can merge them + if(prev.location + prev.length == this.location) { + NSRange mergedRange = NSMakeRange(prev.location, prev.length+this.length); + tmpMatchStore[mergeTarget] = mergedRange; + } + //otherwise we have to move on to the next and make ourselves the new base + else { + if(++mergeTarget != i) + tmpMatchStore[mergeTarget] = this; + } + } + + NSMutableArray *combinedArray = [NSMutableArray arrayWithCapacity:mergeTarget+1]; + for (NSUInteger j = 0; j <= mergeTarget; j++) { + [combinedArray addObject:[NSValue valueWithRange:tmpMatchStore[j]]]; + } + + *submatches = combinedArray; + } + + free(tmpMatchStore); // free(NULL) is safe as per OS X man page + return (matchCount > 0); +} + +@end + /** * Returns the minimum of a, b and c. */ -- (NSInteger)_smallestOf:(NSInteger)a andOf:(NSInteger)b andOf:(NSInteger)c +static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c) { NSInteger min = a; @@ -481,5 +562,3 @@ return min; } - -@end -- cgit v1.2.3 From a9f5656e9649cf67bae7c6362bb5366f9dde3b44 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 7 Mar 2015 22:20:41 +0100 Subject: Fuzzy search for "Go to database" --- Source/SPGotoDatabaseController.m | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPGotoDatabaseController.m b/Source/SPGotoDatabaseController.m index 5e8a4fb2..23b43ee2 100644 --- a/Source/SPGotoDatabaseController.m +++ b/Source/SPGotoDatabaseController.m @@ -185,21 +185,27 @@ nil]; for (NSString *db in unfilteredList) { - // Let's just assume it is in the users interest (most of the time) for searches to be CI. - NSRange match = [db rangeOfString:filter options:NSCaseInsensitiveSearch]; - - if (match.location == NSNotFound) continue; - + + NSArray *matches = nil; + BOOL hasMatch = [db nonConsecutivelySearchString:filter matchingRanges:&matches]; + + if(!hasMatch) continue; + // Should we check for exact match AND have not yet found one? if (exactMatch && !*exactMatch) { - if (match.location == 0 && match.length == [db length]) { - *exactMatch = YES; + if([matches count] == 1) { + NSRange match = [(NSValue *)[matches objectAtIndex:0] rangeValue]; + if (match.location == 0 && match.length == [db length]) { + *exactMatch = YES; + } } } NSMutableAttributedString *attrMatch = [[NSMutableAttributedString alloc] initWithString:db]; - [attrMatch setAttributes:attrs range:match]; + for (NSValue *matchValue in matches) { + [attrMatch setAttributes:attrs range:[matchValue rangeValue]]; + } [filteredList addObject:[attrMatch autorelease]]; } -- cgit v1.2.3 From b15c7fb2d407ec8751a2579a7a68bbd8a037ccfe Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Mar 2015 23:49:40 +0100 Subject: xibLocalizationPostprocessor changes * Can now also reverse the key replacement: Pass in an original IB strings file and a translated strings file in the DMLocalizedNib format and it will generate a translated IB strings file --- Source/xibLocalizationPostprocessor.m | 74 +++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/xibLocalizationPostprocessor.m b/Source/xibLocalizationPostprocessor.m index ad2e152d..8efa545a 100644 --- a/Source/xibLocalizationPostprocessor.m +++ b/Source/xibLocalizationPostprocessor.m @@ -5,20 +5,37 @@ #import +NSDictionary *load_kv_pairs(NSString *input); int main(int argc, const char *argv[]) { NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init]; { - if (argc != 3) { - fprintf(stderr, "Usage: %s inputfile outputfile\n", argv[0]); + if (argc != 3 && argc != 4) { + fprintf(stderr, "Usage: xibLocalizationPostprocessor inputfile outputfile (Replace IB keys with their English string value)\n"); + fprintf(stderr, " xibLocalizationPostprocessor transfile inputfile outputfile (Reverse mode: Change English keys back to IB keys in translation)\n"); exit (-1); } + + NSUInteger inputFileIndex = 1; + NSDictionary *translatedStrings = nil; + if(argc == 4) { + NSError *error = nil; + NSStringEncoding usedEncoding; + NSString *translatedFile = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[1]] usedEncoding:&usedEncoding error:&error]; + if (error) { + fprintf(stderr, "Error reading transfile %s: %s\n", argv[1], error.localizedDescription.UTF8String); + exit (-1); + } + translatedStrings = load_kv_pairs(translatedFile); + + inputFileIndex++; + } NSError *error = nil; NSStringEncoding usedEncoding; - NSString *rawXIBStrings = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[1]] usedEncoding:&usedEncoding error:&error]; + NSString *rawXIBStrings = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[inputFileIndex]] usedEncoding:&usedEncoding error:&error]; if (error) { - fprintf(stderr, "Error reading %s: %s\n", argv[1], error.localizedDescription.UTF8String); + fprintf(stderr, "Error reading inputfile %s: %s\n", argv[inputFileIndex], error.localizedDescription.UTF8String); exit (-1); } @@ -44,9 +61,20 @@ int main(int argc, const char *argv[]) [outputStrings appendString:lastComment]; [outputStrings appendString:@"\n"]; } - NSString *stringNeedingLocalization = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = " + NSString *stringNeedingLocalization = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = " stringNeedingLocalization = [stringNeedingLocalization substringToIndex:stringNeedingLocalization.length - 2]; // chop off trailing: "; - [outputStrings appendFormat:@"\"%@\" = \"%@\";\n\n", stringNeedingLocalization, stringNeedingLocalization]; + if(translatedStrings) { + NSString *translation = [translatedStrings objectForKey:stringNeedingLocalization]; + if(!translation) { + fprintf(stderr, "Warning: key \"%s\" not found in transfile.\n",[stringNeedingLocalization UTF8String]); + translation = stringNeedingLocalization; //fallback to untranslated + } + [outputStrings appendFormat:@"%@\" = \"%@\";\n\n", [line substringToIndex:quoteEqualsQuoteRange.location], translation]; + } + else { + [outputStrings appendFormat:@"\"%@\" = \"%@\";\n\n", stringNeedingLocalization, stringNeedingLocalization]; + } + continue; } } @@ -54,9 +82,39 @@ int main(int argc, const char *argv[]) NSLog(@"Warning: skipped garbage input line %lu, contents: \"%@\"", (unsigned long)lineCount, line); } - if (outputStrings.length && ![outputStrings writeToFile:[NSString stringWithUTF8String:argv[2]] atomically:NO encoding:usedEncoding error:&error]) { - fprintf(stderr, "Error writing %s: %s\n", argv[2], error.localizedDescription.UTF8String); + if (outputStrings.length && ![outputStrings writeToFile:[NSString stringWithUTF8String:argv[inputFileIndex+1]] atomically:NO encoding:usedEncoding error:&error]) { + fprintf(stderr, "Error writing %s: %s\n", argv[inputFileIndex+1], error.localizedDescription.UTF8String); exit (-1); } } [autoreleasePool release]; } + +NSDictionary *load_kv_pairs(NSString *input) +{ + NSDictionary *result = [NSMutableDictionary dictionary]; + __block NSUInteger lineCount = 0; + [input enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { + lineCount++; + + if (line.length == 0 || [line hasPrefix:@"/*"]) { + return; + } + + if ([line hasPrefix:@"\""] && [line hasSuffix:@"\";"]) { // eg: "136.title" = "Quit Library"; + + NSRange quoteEqualsQuoteRange = [line rangeOfString:@"\" = \""]; + if (quoteEqualsQuoteRange.length && NSMaxRange(quoteEqualsQuoteRange) < line.length - 1) { + NSRange keyRange = NSMakeRange(1,quoteEqualsQuoteRange.location - 1); //the first " is always at pos. 0 (we checked that above) + NSString *key = [line substringWithRange:keyRange]; + NSString *value = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = " + value = [value substringToIndex:[value length] - 2]; // chop off trailing: "; + [result setValue:value forKey:key]; + return; + } + } + + NSLog(@"Warning: skipped garbage trans line %lu, contents: \"%@\"", (unsigned long)lineCount, line); + + }]; + return result; +} -- cgit v1.2.3 From 784876380b871b6d85978a705e2477e7b7d2d984 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 9 Mar 2015 00:00:43 +0100 Subject: Minimal refactoring Replaced some (range.location + range.length) with NSMaxRange(range) --- Source/SPCustomQuery.m | 2 +- Source/SPDataStorage.m | 6 +++--- Source/SPNarrowDownCompletion.m | 2 +- Source/SPQueryFavoriteManager.m | 4 ++-- Source/SPStringAdditions.m | 10 +++++----- Source/SPTableData.m | 2 +- Source/SPTableStructure.m | 2 +- Source/SPTextView.m | 4 ++-- Source/SPTextViewAdditions.m | 10 +++++----- 9 files changed, 21 insertions(+), 21 deletions(-) (limited to 'Source') diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 8b3897fe..70ff07ff 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -3152,7 +3152,7 @@ aRange = NSMakeRange(0,0); NSInteger safeCnt = 0; // safety counter - not more than 200 loops allowed while(1){ - aRange = [desc rangeOfRegex:@"\\s((https?|ftp|file)://.*?html)" options:RKLNoOptions inRange:NSMakeRange(aRange.location+aRange.length, [desc length]-aRange.location-aRange.length) capture:1 error:&err1]; + aRange = [desc rangeOfRegex:@"\\s((https?|ftp|file)://.*?html)" options:RKLNoOptions inRange:NSMakeRange(NSMaxRange(aRange), [desc length]-aRange.location-aRange.length) capture:1 error:&err1]; if(aRange.location != NSNotFound) { aUrl = [desc substringWithRange:aRange]; [desc replaceCharactersInRange:aRange withString:[NSString stringWithFormat:@"%@", aUrl, aUrl]]; diff --git a/Source/SPDataStorage.m b/Source/SPDataStorage.m index 3db04159..dd5e87a5 100644 --- a/Source/SPDataStorage.m +++ b/Source/SPDataStorage.m @@ -357,12 +357,12 @@ static inline NSMutableArray* SPDataStorageGetEditedRow(NSPointerArray* rowStore { // Throw an exception if the range is out of bounds - if (rangeToRemove.location + rangeToRemove.length > SPMySQLResultStoreGetRowCount(dataStorage)) { - [NSException raise:NSRangeException format:@"Requested storage index (%llu) beyond bounds (%llu)", (unsigned long long)(rangeToRemove.location + rangeToRemove.length), SPMySQLResultStoreGetRowCount(dataStorage)]; + if (NSMaxRange(rangeToRemove) > SPMySQLResultStoreGetRowCount(dataStorage)) { + [NSException raise:NSRangeException format:@"Requested storage index (%llu) beyond bounds (%llu)", (unsigned long long)(NSMaxRange(rangeToRemove)), SPMySQLResultStoreGetRowCount(dataStorage)]; } // Remove the rows from the edited list and underlying storage - NSUInteger i = MIN(editedRowCount, rangeToRemove.location + rangeToRemove.length); + NSUInteger i = MIN(editedRowCount, NSMaxRange(rangeToRemove)); while (--i >= rangeToRemove.location) { editedRowCount--; [editedRows removePointerAtIndex:i]; diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m index d5391644..b9dba0e4 100644 --- a/Source/SPNarrowDownCompletion.m +++ b/Source/SPNarrowDownCompletion.m @@ -1025,7 +1025,7 @@ if (scanPosition + attributeResultRange.length == currentLength) break; // A match was found - retrieve the location - NSUInteger matchStart = attributeResultRange.location+attributeResultRange.length; + NSUInteger matchStart = NSMaxRange(attributeResultRange); if ([[theView textStorage] attribute:kSPAutoCompletePlaceholderName atIndex:matchStart longestEffectiveRange:&attributeResultRange inRange:NSMakeRange(matchStart, currentLength - matchStart)]) { [theView shouldChangeTextInRange:attributeResultRange replacementString:@""]; [[theView textStorage] deleteCharactersInRange:attributeResultRange]; diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m index 6522b884..a715bd93 100644 --- a/Source/SPQueryFavoriteManager.m +++ b/Source/SPQueryFavoriteManager.m @@ -413,7 +413,7 @@ // Check whether the selection range lies within the snippet if (selRange.location != NSNotFound && selRange.location > matchedRange.location + 1 - && selRange.location + selRange.length < matchedRange.location + matchedRange.length) + && NSMaxRange(selRange) < NSMaxRange(matchedRange)) { selectionInsideSnippet = YES; } @@ -423,7 +423,7 @@ NSInteger snippetNumber = [[queryString substringWithRange:snippetNumberRange] integerValue]; [snippetNumbers setObject:@YES forKey:[NSNumber numberWithInteger:snippetNumber]]; - rangeStart = matchedRange.location + matchedRange.length; + rangeStart = NSMaxRange(matchedRange); } // If the selection is not inside a snippet, wrap it inside the snippet syntax. diff --git a/Source/SPStringAdditions.m b/Source/SPStringAdditions.m index 0c623af7..0254dc36 100644 --- a/Source/SPStringAdditions.m +++ b/Source/SPStringAdditions.m @@ -322,7 +322,7 @@ static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c); NSMutableArray *lineRangesArray = [NSMutableArray array]; // Check that the range supplied is valid - if not return an empty array. - if (aRange.location == NSNotFound || aRange.location + aRange.length > [self length]) { + if (aRange.location == NSNotFound || NSMaxRange(aRange) > [self length]) { return lineRangesArray; } @@ -332,9 +332,9 @@ static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c); [lineRangesArray addObject:NSStringFromRange(currentLineRange)]; // Loop through until the line end matches or surpasses the end of the specified range - while (currentLineRange.location + currentLineRange.length < aRange.location + aRange.length) + while (NSMaxRange(currentLineRange) < NSMaxRange(aRange)) { - currentLineRange = [self lineRangeForRange:NSMakeRange(currentLineRange.location + currentLineRange.length, 0)]; + currentLineRange = [self lineRangeForRange:NSMakeRange(NSMaxRange(currentLineRange), 0)]; [lineRangesArray addObject:NSStringFromRange(currentLineRange)]; } @@ -502,7 +502,7 @@ static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c); tmpMatchStore[matchCount] = found; matchCount++; //move the next search past the current match - searchRange.location = found.location + found.length; + searchRange.location = NSMaxRange(found); searchRange.length = [self length] - searchRange.location; }; @@ -524,7 +524,7 @@ static NSInteger _smallestOf(NSInteger a, NSInteger b, NSInteger c); NSRange prev = tmpMatchStore[mergeTarget]; NSRange this = tmpMatchStore[i]; //if the previous match ends right before this match begins we can merge them - if(prev.location + prev.length == this.location) { + if(NSMaxRange(prev) == this.location) { NSRange mergedRange = NSMakeRange(prev.location, prev.length+this.length); tmpMatchStore[mergeTarget] = mergedRange; } diff --git a/Source/SPTableData.m b/Source/SPTableData.m index 320a0b66..bdd1f1db 100644 --- a/Source/SPTableData.m +++ b/Source/SPTableData.m @@ -780,7 +780,7 @@ charsetDefinitionRange = [createTableParser rangeOfString:@"CHARACTER SET=" options:NSCaseInsensitiveSearch]; } if (charsetDefinitionRange.location != NSNotFound) { - stringStart = charsetDefinitionRange.location + charsetDefinitionRange.length; + stringStart = NSMaxRange(charsetDefinitionRange); for (i = stringStart; i < [createTableParser length]; i++) { if ([createTableParser characterAtIndex:i] == ' ') break; } diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m index 32739eb3..992ecdcf 100644 --- a/Source/SPTableStructure.m +++ b/Source/SPTableStructure.m @@ -912,7 +912,7 @@ static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey"; // UNSIGNED keyword. NSRange range = [queryString rangeOfString:[NSString stringWithFormat:@"%@ %@", [[theRow objectForKey:@"name"] backtickQuotedString], theRowType] options:NSLiteralSearch]; - NSInteger insertionIndex = (range.location + range.length); + NSInteger insertionIndex = NSMaxRange(range); // If the field definition's data type includes the length then we must take this into // account when inserting the UNSIGNED keyword. Add 2 to the index to accommodate the diff --git a/Source/SPTextView.m b/Source/SPTextView.m index f50ed939..12d6ed13 100644 --- a/Source/SPTextView.m +++ b/Source/SPTextView.m @@ -772,8 +772,8 @@ static inline NSPoint SPPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NS backtickMode+=1; leftBacktick = YES; } - if([[self string] length] > parseRange.location+parseRange.length) { - if([[self string] characterAtIndex:parseRange.location+parseRange.length] == '`') { + if([[self string] length] > NSMaxRange(parseRange)) { + if([[self string] characterAtIndex:NSMaxRange(parseRange)] == '`') { backtickMode+=2; parseRange.length++; // adjust parse string for right ` rightBacktick = YES; diff --git a/Source/SPTextViewAdditions.m b/Source/SPTextViewAdditions.m index 7272de1d..56103a53 100644 --- a/Source/SPTextViewAdditions.m +++ b/Source/SPTextViewAdditions.m @@ -247,7 +247,7 @@ // if no selection place the caret at the end of the current word { NSRange newRange = [self getRangeForCurrentWord]; - [self setSelectedRange:NSMakeRange(newRange.location + newRange.length, 0)]; + [self setSelectedRange:NSMakeRange(NSMaxRange(newRange), 0)]; } } @@ -269,7 +269,7 @@ // if no selection place the caret at the end of the current word { NSRange newRange = [self getRangeForCurrentWord]; - [self setSelectedRange:NSMakeRange(newRange.location + newRange.length, 0)]; + [self setSelectedRange:NSMakeRange(NSMaxRange(newRange), 0)]; } } @@ -291,7 +291,7 @@ // if no selection place the caret at the end of the current word { NSRange newRange = [self getRangeForCurrentWord]; - [self setSelectedRange:NSMakeRange(newRange.location + newRange.length, 0)]; + [self setSelectedRange:NSMakeRange(NSMaxRange(newRange), 0)]; } } @@ -312,7 +312,7 @@ // if no selection place the caret at the end of the current word { NSRange newRange = [self getRangeForCurrentWord]; - [self setSelectedRange:NSMakeRange(newRange.location + newRange.length, 0)]; + [self setSelectedRange:NSMakeRange(NSMaxRange(newRange), 0)]; } } @@ -335,7 +335,7 @@ // if no selection place the caret at the end of the current word { NSRange newRange = [self getRangeForCurrentWord]; - [self setSelectedRange:NSMakeRange(newRange.location + newRange.length, 0)]; + [self setSelectedRange:NSMakeRange(NSMaxRange(newRange), 0)]; } } -- cgit v1.2.3 From 8b1ff9c9b8a996ff0c6321e58709c25f0c5763c1 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 9 Mar 2015 21:28:28 +0100 Subject: Update nightly build script for temporary translation workaround, improve xibLocalizationPostprocessor robustness --- Source/xibLocalizationPostprocessor.m | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'Source') diff --git a/Source/xibLocalizationPostprocessor.m b/Source/xibLocalizationPostprocessor.m index 8efa545a..1806d6b2 100644 --- a/Source/xibLocalizationPostprocessor.m +++ b/Source/xibLocalizationPostprocessor.m @@ -92,29 +92,31 @@ int main(int argc, const char *argv[]) NSDictionary *load_kv_pairs(NSString *input) { NSDictionary *result = [NSMutableDictionary dictionary]; - __block NSUInteger lineCount = 0; - [input enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { + + NSUInteger lineCount = 0; + //don't try [NSString enumerateLines...] here. It supports some obscure Unicode line breaks! + for (NSString *line in [input componentsSeparatedByString:@"\n"]) { lineCount++; if (line.length == 0 || [line hasPrefix:@"/*"]) { - return; + continue; } if ([line hasPrefix:@"\""] && [line hasSuffix:@"\";"]) { // eg: "136.title" = "Quit Library"; NSRange quoteEqualsQuoteRange = [line rangeOfString:@"\" = \""]; - if (quoteEqualsQuoteRange.length && NSMaxRange(quoteEqualsQuoteRange) < line.length - 1) { + if (quoteEqualsQuoteRange.location != NSNotFound && quoteEqualsQuoteRange.length && NSMaxRange(quoteEqualsQuoteRange) < line.length - 1) { NSRange keyRange = NSMakeRange(1,quoteEqualsQuoteRange.location - 1); //the first " is always at pos. 0 (we checked that above) NSString *key = [line substringWithRange:keyRange]; NSString *value = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = " value = [value substringToIndex:[value length] - 2]; // chop off trailing: "; [result setValue:value forKey:key]; - return; + continue; } } NSLog(@"Warning: skipped garbage trans line %lu, contents: \"%@\"", (unsigned long)lineCount, line); - - }]; + } + return result; } -- cgit v1.2.3 From 8cc66aa348870e6cdf086500515848b07ea5aa06 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 12 Mar 2015 02:17:31 +0100 Subject: Fix Sequel Pro forgetting database charset when renaming or copying a database (#2082) (While we're at it, also removed some duplicate CREATE DATABASE code) --- Source/SPDatabaseAction.h | 27 +++++++++++++++++++++++ Source/SPDatabaseAction.m | 45 ++++++++++++++++++++++++++++++++++++++ Source/SPDatabaseCopy.h | 16 ++++---------- Source/SPDatabaseCopy.m | 34 ++++++++++------------------- Source/SPDatabaseDocument.h | 2 ++ Source/SPDatabaseDocument.m | 38 +++++++++++++++++--------------- Source/SPDatabaseRename.h | 8 +++---- Source/SPDatabaseRename.m | 53 ++++++++++++++++----------------------------- 8 files changed, 132 insertions(+), 91 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseAction.h b/Source/SPDatabaseAction.h index 00de9065..52af621f 100644 --- a/Source/SPDatabaseAction.h +++ b/Source/SPDatabaseAction.h @@ -31,6 +31,14 @@ @class SPTablesList; @class SPMySQLConnection; +@interface SPCreateDatabaseInfo : NSObject + +@property (readwrite,retain) NSString *databaseName; +@property (readwrite,retain) NSString *defaultEncoding; +@property (readwrite,retain) NSString *defaultCollation; + +@end + @interface SPDatabaseAction : NSObject { NSWindow *messageWindow; @@ -53,4 +61,23 @@ */ @property (readwrite, assign) SPTablesList *tablesList; +/** + * This method creates a new database. + * + * @param dbInfo database name/charset/collation (charset, collation may be nil) + * @return success + * @see createDatabase:withEncoding:collation: + */ +- (BOOL)createDatabase:(SPCreateDatabaseInfo *)dbInfo; + +/** + * This method creates a new database. + * + * @param database name of the new database to be created + * @param encoding charset of the new database (can be nil to skip) + * @param collation sorting collation of the new database (can be nil. Will be ignored if encoding == nil) + * @return YES on success, otherwise NO + */ +- (BOOL)createDatabase:(NSString *)database withEncoding:(NSString *)encoding collation:(NSString *)collation; + @end diff --git a/Source/SPDatabaseAction.m b/Source/SPDatabaseAction.m index 998aff95..f5ed8b60 100644 --- a/Source/SPDatabaseAction.m +++ b/Source/SPDatabaseAction.m @@ -30,10 +30,55 @@ #import "SPDatabaseAction.h" +#import + +@implementation SPCreateDatabaseInfo + +@synthesize databaseName; +@synthesize defaultEncoding; +@synthesize defaultCollation; + +- (void)dealloc +{ + [self setDatabaseName:nil]; + [self setDefaultEncoding:nil]; + [self setDefaultCollation:nil]; + [super dealloc]; +} + +@end + +#pragma mark - + @implementation SPDatabaseAction @synthesize connection; @synthesize messageWindow; @synthesize tablesList; +- (BOOL)createDatabase:(SPCreateDatabaseInfo *)dbInfo +{ + return [self createDatabase:[dbInfo databaseName] + withEncoding:[dbInfo defaultEncoding] + collation:[dbInfo defaultCollation]]; +} + +- (BOOL)createDatabase:(NSString *)database withEncoding:(NSString *)encoding collation:(NSString *)collation +{ + NSParameterAssert(database != nil && [database length] > 0); + + NSMutableString *query = [NSMutableString stringWithFormat:@"CREATE DATABASE %@", [database backtickQuotedString]]; + + if([encoding length]) { // [nil length] == 0 + [query appendFormat:@" DEFAULT CHARACTER SET = %@",[encoding backtickQuotedString]]; + if([collation length]) { + [query appendFormat:@" DEFAULT COLLATE = %@",[collation backtickQuotedString]]; + } + } + + [connection queryString:query]; + + return ![connection queryErrored]; +} + @end diff --git a/Source/SPDatabaseCopy.h b/Source/SPDatabaseCopy.h index 081378e2..3adf7fa0 100644 --- a/Source/SPDatabaseCopy.h +++ b/Source/SPDatabaseCopy.h @@ -38,18 +38,10 @@ /** * This method clones an existing database. * - * @param NSString sourceDatabaseName the name of the source database - * @param NSString targetDatabaseName the name of the target database - * @result BOOL success + * @param sourceDatabase information tuple about source database + * @param targetDatabaseName the name of the target database + * @result success */ -- (BOOL)copyDatabaseFrom:(NSString *)sourceDatabaseName to:(NSString *)targetDatabaseName withContent:(BOOL)copyWithContent; - -/** - * This method creates a new database. - * - * @param NSString newDatabaseName name of the new database to be created - * @return BOOL YES on success, otherwise NO - */ -- (BOOL)createDatabase:(NSString *)newDatabaseName; +- (BOOL)copyDatabaseFrom:(SPCreateDatabaseInfo *)sourceDatabase to:(NSString *)targetDatabaseName withContent:(BOOL)copyWithContent; @end diff --git a/Source/SPDatabaseCopy.m b/Source/SPDatabaseCopy.m index 5ea0a2d5..94a5e896 100644 --- a/Source/SPDatabaseCopy.m +++ b/Source/SPDatabaseCopy.m @@ -35,46 +35,34 @@ @implementation SPDatabaseCopy -- (BOOL)copyDatabaseFrom:(NSString *)sourceDatabaseName to:(NSString *)targetDatabaseName withContent:(BOOL)copyWithContent +- (BOOL)copyDatabaseFrom:(SPCreateDatabaseInfo *)sourceDatabase to:(NSString *)targetDatabaseName withContent:(BOOL)copyWithContent { NSArray *tables = nil; // Check whether the source database exists and the target database doesn't. - BOOL sourceExists = [[connection databases] containsObject:sourceDatabaseName]; + BOOL sourceExists = [[connection databases] containsObject:[sourceDatabase databaseName]]; BOOL targetExists = [[connection databases] containsObject:targetDatabaseName]; - if (sourceExists && !targetExists) { - - // Retrieve the list of tables/views/funcs/triggers from the source database - tables = [connection tablesFromDatabase:sourceDatabaseName]; - } - else { + if (!sourceExists || targetExists) return NO; - } - + + // Retrieve the list of tables/views/funcs/triggers from the source database + tables = [connection tablesFromDatabase:[sourceDatabase databaseName]]; + // Abort if database creation failed - if (![self createDatabase:targetDatabaseName]) return NO; + if (![self createDatabase:targetDatabaseName + withEncoding:[sourceDatabase defaultEncoding] + collation:[sourceDatabase defaultCollation]]) return NO; SPTableCopy *dbActionTableCopy = [[SPTableCopy alloc] init]; [dbActionTableCopy setConnection:connection]; - BOOL success = [dbActionTableCopy copyTables:tables from:sourceDatabaseName to:targetDatabaseName withContent:copyWithContent]; + BOOL success = [dbActionTableCopy copyTables:tables from:[sourceDatabase databaseName] to:targetDatabaseName withContent:copyWithContent]; [dbActionTableCopy release]; return success; } -- (BOOL)createDatabase:(NSString *)newDatabaseName -{ - NSString *createStatement = [NSString stringWithFormat:@"CREATE DATABASE %@", [newDatabaseName backtickQuotedString]]; - - [connection queryString:createStatement]; - - if ([connection queryErrored]) return NO; - - return YES; -} - @end diff --git a/Source/SPDatabaseDocument.h b/Source/SPDatabaseDocument.h index 0cd485b9..23b22d4a 100644 --- a/Source/SPDatabaseDocument.h +++ b/Source/SPDatabaseDocument.h @@ -56,6 +56,7 @@ @class SPMySQLConnection; @class SPCharsetCollationHelper; @class SPGotoDatabaseController; +@class SPCreateDatabaseInfo; #import "SPDatabaseContentViewDelegate.h" #import "SPConnectionControllerDelegateProtocol.h" @@ -451,6 +452,7 @@ #endif - (NSArray *)allTableNames; - (SPTablesList *)tablesListInstance; +- (SPCreateDatabaseInfo *)createDatabaseInfo; #ifndef SP_CODA /* method decls */ // Notification center methods diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 7f531f60..506e78f6 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -2769,6 +2769,17 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; return tablesListInstance; } +- (SPCreateDatabaseInfo *)createDatabaseInfo +{ + SPCreateDatabaseInfo *dbInfo = [[SPCreateDatabaseInfo alloc] init]; + + [dbInfo setDatabaseName:[self database]]; + [dbInfo setDefaultEncoding:[databaseDataInstance getDatabaseDefaultCharacterSet]]; + [dbInfo setDefaultCollation:[databaseDataInstance getDatabaseDefaultCollation]]; + + return [dbInfo autorelease]; +} + #pragma mark - #pragma mark Notification center methods @@ -5903,7 +5914,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; BOOL copyWithContent = [copyDatabaseDataButton state] == NSOnState; - if ([dbActionCopy copyDatabaseFrom:[self database] to:[databaseCopyNameField stringValue] withContent:copyWithContent]) { + if ([dbActionCopy copyDatabaseFrom:[self createDatabaseInfo] to:[databaseCopyNameField stringValue] withContent:copyWithContent]) { [self selectDatabase:[databaseCopyNameField stringValue] item:nil]; } else { @@ -5934,7 +5945,7 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [dbActionRename setConnection:[self getConnection]]; [dbActionRename setMessageWindow:parentWindow]; - if ([dbActionRename renameDatabaseFrom:[self database] to:newDatabaseName]) { + if ([dbActionRename renameDatabaseFrom:[self createDatabaseInfo] to:newDatabaseName]) { [self setDatabases:self]; [self selectDatabase:newDatabaseName item:nil]; } @@ -5974,25 +5985,16 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; // As we're amending identifiers, ensure UTF8 if (![[mySQLConnection encoding] isEqualToString:@"utf8"]) [mySQLConnection setEncoding:@"utf8"]; - NSString *createStatement = [NSString stringWithFormat:@"CREATE DATABASE %@", [[databaseNameField stringValue] backtickQuotedString]]; - - // If there is an encoding selected other than the default we must specify it in CREATE DATABASE statement - NSString *encodingName = [addDatabaseCharsetHelper selectedCharset]; - if (encodingName) - createStatement = [NSString stringWithFormat:@"%@ DEFAULT CHARACTER SET %@", createStatement, [encodingName backtickQuotedString]]; + SPDatabaseAction *dbAction = [[SPDatabaseAction alloc] init]; + [dbAction setConnection:mySQLConnection]; + BOOL res = [dbAction createDatabase:[databaseNameField stringValue] + withEncoding:[addDatabaseCharsetHelper selectedCharset] + collation:[addDatabaseCharsetHelper selectedCollation]]; + [dbAction release]; - // If there is a collation selected other than the default we must specify it in the CREATE DATABASE statement - NSString *collationName = [addDatabaseCharsetHelper selectedCollation]; - if (collationName) - createStatement = [NSString stringWithFormat:@"%@ DEFAULT COLLATE %@", createStatement, [collationName backtickQuotedString]]; - - // Create the database - [mySQLConnection queryString:createStatement]; - - if ([mySQLConnection queryErrored]) { + if (!res) { // An error occurred SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, parentWindow, self, nil, nil, [NSString stringWithFormat:NSLocalizedString(@"Couldn't create database.\nMySQL said: %@", @"message of panel when creation of db failed"), [mySQLConnection lastErrorMessage]]); - return; } diff --git a/Source/SPDatabaseRename.h b/Source/SPDatabaseRename.h index 2f9cb4db..becf460e 100644 --- a/Source/SPDatabaseRename.h +++ b/Source/SPDatabaseRename.h @@ -38,10 +38,10 @@ /** * This method renames an existing database. * - * @param NSString sourceDatabaseName the name of the source database - * @param NSString targetDatabaseName the name of the target database - * @result BOOL success + * @param sourceDatabase information tuple about the source database + * @param targetDatabase the name of the target database + * @result success */ -- (BOOL)renameDatabaseFrom:(NSString *)sourceDatabase to:(NSString *)targetDatabase; +- (BOOL)renameDatabaseFrom:(SPCreateDatabaseInfo *)sourceDatabase to:(NSString *)targetDatabase; @end diff --git a/Source/SPDatabaseRename.m b/Source/SPDatabaseRename.m index b07f513d..04f71182 100644 --- a/Source/SPDatabaseRename.m +++ b/Source/SPDatabaseRename.m @@ -37,7 +37,6 @@ @interface SPDatabaseRename () -- (BOOL)_createDatabase:(NSString *)database; - (BOOL)_dropDatabase:(NSString *)database; - (void)_moveTables:(NSArray *)tables fromDatabase:(NSString *)sourceDatabase toDatabase:(NSString *)targetDatabase; @@ -47,52 +46,38 @@ @implementation SPDatabaseRename -- (BOOL)renameDatabaseFrom:(NSString *)sourceDatabase to:(NSString *)targetDatabase +- (BOOL)renameDatabaseFrom:(SPCreateDatabaseInfo *)sourceDatabase to:(NSString *)targetDatabase { - NSArray *tables = nil; - NSArray *views = nil; - // Check, whether the source database exists and the target database doesn't - BOOL sourceExists = [[connection databases] containsObject:sourceDatabase]; + BOOL sourceExists = [[connection databases] containsObject:[sourceDatabase databaseName]]; BOOL targetExists = [[connection databases] containsObject:targetDatabase]; - if (sourceExists && !targetExists) { - tables = [tablesList allTableNames]; - views = [tablesList allViewNames]; - } - else { - return NO; - } - - BOOL success = [self _createDatabase:targetDatabase]; + if (!sourceExists || targetExists) return NO; + + NSArray *tables = [tablesList allTableNames]; + NSArray *views = [tablesList allViewNames]; - [self _moveTables:tables fromDatabase:sourceDatabase toDatabase:targetDatabase]; + BOOL success = [self createDatabase:targetDatabase + withEncoding:[sourceDatabase defaultEncoding] + collation:[sourceDatabase defaultCollation]]; - tables = [connection tablesFromDatabase:sourceDatabase]; - + [self _moveTables:tables fromDatabase:[sourceDatabase databaseName] toDatabase:targetDatabase]; + +#warning Section disabled because it might destroy data (views, functions, events, ...) +/* + tables = [connection tablesFromDatabase:[sourceDatabase databaseName]]; + if ([tables count] == 0) { - [self _dropDatabase:sourceDatabase]; - } - + [self _dropDatabase:[sourceDatabase databaseName]]; + } +*/ + return success; } #pragma mark - #pragma mark Private API -/** - * This method creates a new database. - * - * @param NSString newDatabaseName name of the new database to be created - * @return BOOL YES on success, otherwise NO - */ -- (BOOL)_createDatabase:(NSString *)database -{ - [connection queryString:[NSString stringWithFormat:@"CREATE DATABASE %@", [database backtickQuotedString]]]; - - return ![connection queryErrored]; -} - /** * This method drops a database. * -- cgit v1.2.3 From 6af24620e1126fe08e573ebf4dce93444ac140cb Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 12 Mar 2015 02:21:19 +0100 Subject: Missed a special case in the previous commit --- Source/SPDatabaseAction.h | 2 +- Source/SPDatabaseAction.m | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseAction.h b/Source/SPDatabaseAction.h index 52af621f..137a8737 100644 --- a/Source/SPDatabaseAction.h +++ b/Source/SPDatabaseAction.h @@ -75,7 +75,7 @@ * * @param database name of the new database to be created * @param encoding charset of the new database (can be nil to skip) - * @param collation sorting collation of the new database (can be nil. Will be ignored if encoding == nil) + * @param collation sorting collation of the new database (can be nil) * @return YES on success, otherwise NO */ - (BOOL)createDatabase:(NSString *)database withEncoding:(NSString *)encoding collation:(NSString *)collation; diff --git a/Source/SPDatabaseAction.m b/Source/SPDatabaseAction.m index f5ed8b60..c7f5dbf9 100644 --- a/Source/SPDatabaseAction.m +++ b/Source/SPDatabaseAction.m @@ -71,9 +71,9 @@ if([encoding length]) { // [nil length] == 0 [query appendFormat:@" DEFAULT CHARACTER SET = %@",[encoding backtickQuotedString]]; - if([collation length]) { - [query appendFormat:@" DEFAULT COLLATE = %@",[collation backtickQuotedString]]; - } + } + if([collation length]) { + [query appendFormat:@" DEFAULT COLLATE = %@",[collation backtickQuotedString]]; } [connection queryString:query]; -- cgit v1.2.3 From f86e21e8296a5c368fb547b93ff0390dec0f5785 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 12 Mar 2015 02:28:28 +0100 Subject: =?UTF-8?q?Well,=20and=20then=20there=20was=20backwards=20compatib?= =?UTF-8?q?ility=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Source/SPDatabaseAction.h | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'Source') diff --git a/Source/SPDatabaseAction.h b/Source/SPDatabaseAction.h index 137a8737..7ca8d402 100644 --- a/Source/SPDatabaseAction.h +++ b/Source/SPDatabaseAction.h @@ -32,6 +32,11 @@ @class SPMySQLConnection; @interface SPCreateDatabaseInfo : NSObject +{ + NSString *databaseName; + NSString *defaultEncoding; + NSString *defaultCollation; +} @property (readwrite,retain) NSString *databaseName; @property (readwrite,retain) NSString *defaultEncoding; -- cgit v1.2.3 From 0dc8d023f39c1bd03f51e62d90b6be7693955e53 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 16 Mar 2015 21:48:15 +0100 Subject: Updated OCMock framework and added a unit test --- Source/SPConstants.h | 3 +++ Source/SPDatabaseAction.m | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index a2df5bde..728d213a 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -642,3 +642,6 @@ void _SPClear(id *addr); #if __MAC_OS_X_VERSION_MAX_ALLOWED < __MAC_10_10 typedef NSUInteger NSCellHitResult; #endif + +// Stolen from Stack Overflow: http://stackoverflow.com/questions/969130 +#define SPLog(fmt, ...) NSLog((@"%s:%d: " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) diff --git a/Source/SPDatabaseAction.m b/Source/SPDatabaseAction.m index c7f5dbf9..413e2378 100644 --- a/Source/SPDatabaseAction.m +++ b/Source/SPDatabaseAction.m @@ -65,7 +65,10 @@ - (BOOL)createDatabase:(NSString *)database withEncoding:(NSString *)encoding collation:(NSString *)collation { - NSParameterAssert(database != nil && [database length] > 0); + if(![database length]) { + SPLog(@"'database' should not be nil or empty!"); + return NO; + } NSMutableString *query = [NSMutableString stringWithFormat:@"CREATE DATABASE %@", [database backtickQuotedString]]; -- cgit v1.2.3 From 9f2e5a6b0fafeec8f94dfa00414b0016b12194ba Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 17 Mar 2015 01:37:41 +0100 Subject: Allow selection of SSH client binary in prefs Hey, I was against this, but if you want it... - just don't blame me for what might happen :shipit: --- Source/SPConstants.h | 1 + Source/SPConstants.m | 1 + Source/SPNetworkPreferencePane.h | 14 +++++++-- Source/SPNetworkPreferencePane.m | 66 ++++++++++++++++++++++++++++++++++++++++ Source/SPSSHTunnel.m | 34 +++++++++++++++++---- 5 files changed, 108 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 728d213a..38e05cc5 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -428,6 +428,7 @@ extern NSString *SPHiddenKeyFileVisibilityKey; extern NSString *SPSelectionDetailTypeIndexed; extern NSString *SPSelectionDetailTypePrimaryKeyed; extern NSString *SPSSHEnableMuxingPreference; +extern NSString *SPSSHClientPath; // URLs extern NSString *SPDonationsURL; diff --git a/Source/SPConstants.m b/Source/SPConstants.m index 292acb3c..fad42bc6 100644 --- a/Source/SPConstants.m +++ b/Source/SPConstants.m @@ -229,6 +229,7 @@ NSString *SPHiddenKeyFileVisibilityKey = @"KeySelectionHiddenFilesVisi NSString *SPSelectionDetailTypeIndexed = @"SelectionDetailTypeNSIndexSet"; NSString *SPSelectionDetailTypePrimaryKeyed = @"SelectionDetailTypePrimaryKeyedDetails"; NSString *SPSSHEnableMuxingPreference = @"SSHMultiplexingEnabled"; +NSString *SPSSHClientPath = @"SSHClientPath"; // URLs NSString *SPDonationsURL = @"http://www.sequelpro.com/donate/"; diff --git a/Source/SPNetworkPreferencePane.h b/Source/SPNetworkPreferencePane.h index dc99b3e2..37408c32 100644 --- a/Source/SPNetworkPreferencePane.h +++ b/Source/SPNetworkPreferencePane.h @@ -37,6 +37,16 @@ * * Network preference pane controller. */ -@interface SPNetworkPreferencePane : SPPreferencePane - +@interface SPNetworkPreferencePane : SPPreferencePane +{ + IBOutlet NSView *sshClientPickerView; + IBOutlet NSTextField *sshClientPath; + IBOutlet NSView *hiddenFileView; + +@private + NSAlert *_currentAlert; + NSOpenPanel *_currentFilePanel; +} +- (IBAction)pickSSHClientViaFileBrowser:(id)sender; +- (IBAction)pickSSHClient:(id)sender; @end diff --git a/Source/SPNetworkPreferencePane.m b/Source/SPNetworkPreferencePane.m index d3e2f52f..376ba39f 100644 --- a/Source/SPNetworkPreferencePane.m +++ b/Source/SPNetworkPreferencePane.m @@ -30,6 +30,10 @@ #import "SPNetworkPreferencePane.h" +@interface SPNetworkPreferencePane (Private) +- (void)updateHiddenFiles; +@end + @implementation SPNetworkPreferencePane #pragma mark - @@ -65,4 +69,66 @@ return NO; } +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ + if([SPHiddenKeyFileVisibilityKey isEqualTo:keyPath]) { + [self updateHiddenFiles]; + } +} + +- (void)updateHiddenFiles +{ + [_currentFilePanel setShowsHiddenFiles:[prefs boolForKey:SPHiddenKeyFileVisibilityKey]]; +} + +- (IBAction)pickSSHClientViaFileBrowser:(id)sender +{ + _currentFilePanel = [NSOpenPanel openPanel]; + [_currentFilePanel setCanChooseFiles:YES]; + [_currentFilePanel setCanChooseDirectories:NO]; + [_currentFilePanel setAllowsMultipleSelection:NO]; + [_currentFilePanel setAccessoryView:hiddenFileView]; + [self updateHiddenFiles]; + + [prefs addObserver:self + forKeyPath:SPHiddenKeyFileVisibilityKey + options:NSKeyValueObservingOptionNew + context:NULL]; + + [_currentFilePanel beginSheetModalForWindow:[_currentAlert window] completionHandler:^(NSInteger result) { + if(result == NSFileHandlingPanelOKButton) [sshClientPath setStringValue:[[_currentFilePanel URL] path]]; + + [prefs removeObserver:self forKeyPath:SPHiddenKeyFileVisibilityKey]; + + _currentFilePanel = nil; + }]; +} + +- (IBAction)pickSSHClient:(id)sender +{ + //take value from user defaults + NSString *oldPath = [prefs stringForKey:SPSSHClientPath]; + if([oldPath length]) [sshClientPath setStringValue:oldPath]; + + // set up dialog + _currentAlert = [[NSAlert alloc] init]; //needs to be ivar so we can attach the OpenPanel later + [_currentAlert setAccessoryView:sshClientPickerView]; + [_currentAlert setAlertStyle:NSWarningAlertStyle]; + [_currentAlert setMessageText:NSLocalizedString(@"Unsupported configuration!",@"Preferences : Network : Custom SSH client : warning dialog title")]; + [_currentAlert setInformativeText:NSLocalizedString(@"Sequel Pro only supports and is tested with the default OpenSSH client versions included with Mac OS X. Using different clients might cause connection issues, security risks or not work at all.\n\nPlease be aware, that we cannot provide support for such configurations.",@"Preferences : Network : Custom SSH client : warning dialog message")]; + [_currentAlert addButtonWithTitle:NSLocalizedString(@"OK",@"Preferences : Network : Custom SSH client : warning dialog : accept button")]; + [_currentAlert addButtonWithTitle:NSLocalizedString(@"Cancel",@"Preferences : Network : Custom SSH client : warning dialog : cancel button")]; + + if([_currentAlert runModal] == NSAlertFirstButtonReturn) { + //store new value to user defaults + NSString *newPath = [sshClientPath stringValue]; + if(![newPath length]) + [prefs removeObjectForKey:SPSSHClientPath]; + else + [prefs setObject:newPath forKey:SPSSHClientPath]; + } + + SPClear(_currentAlert); +} + @end diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index e09d0ce2..8e9ffb13 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -309,7 +309,20 @@ // Set up the NSTask task = [[NSTask alloc] init]; - [task setLaunchPath: @"/usr/bin/ssh"]; + NSString *launchPath = @"/usr/bin/ssh"; + NSString *userSSHPath = [[NSUserDefaults standardUserDefaults] stringForKey:SPSSHClientPath]; + + if([userSSHPath length]) { + launchPath = userSSHPath; + // And I'm sure we will get issue reports about it anyway! + [debugMessagesLock lock]; + [debugMessages addObject:@"################################################################"]; + [debugMessages addObject:[NSString stringWithFormat:@"# %@",NSLocalizedString(@"Custom SSH binary enabled. Disable in Preferences to rule out incompatibilities!", @"SSH connection : debug header with user-defined ssh binary")]]; + [debugMessages addObject:@"################################################################"]; + [debugMessagesLock unlock]; + } + + [task setLaunchPath:launchPath]; // Prepare to set up the arguments for the task taskArguments = [[NSMutableArray alloc] init]; @@ -413,11 +426,20 @@ object:[standardError fileHandleForReading]]; [[standardError fileHandleForReading] waitForDataInBackgroundAndNotify]; - // Launch and run the tunnel - [task launch]; - - // Listen for output - [task waitUntilExit]; + @try { + // Launch and run the tunnel + [task launch]; //throws for invalid paths, missing +x permission + + // Listen for output + [task waitUntilExit]; + } + @catch (NSException *e) { + connectionState = SPMySQLProxyLaunchFailed; + // Log the exception. Could be improved by showing a dedicated alert instead + [debugMessagesLock lock]; + [debugMessages addObject:[NSString stringWithFormat:@"%@: %@\n", [e name], [e reason]]]; + [debugMessagesLock unlock]; + } // On tunnel close, clean up, ready for re-use if the delegate reconnects. SPClear(task); -- cgit v1.2.3 From 1b6248d6a256ad774d092151227fdd5f40247c02 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 21 Mar 2015 02:25:59 +0100 Subject: Add code for using custom SSL cipher list in SP --- Source/SPConnectionHandler.m | 10 ++++++++++ Source/SPConstants.h | 1 + Source/SPConstants.m | 1 + 3 files changed, 12 insertions(+) (limited to 'Source') diff --git a/Source/SPConnectionHandler.m b/Source/SPConnectionHandler.m index bac0c680..80e9c3f5 100644 --- a/Source/SPConnectionHandler.m +++ b/Source/SPConnectionHandler.m @@ -145,6 +145,16 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; if ([self sslCACertFileLocationEnabled]) { [mySQLConnection setSslCACertificatePath:[self sslCACertFileLocation]]; } + + NSString *userSSLCipherList = [prefs stringForKey:SPSSLCipherListKey]; + if(userSSLCipherList) { + //strip out disabled ciphers (e.g. in "foo:bar:--:baz") + NSRange markerPos = [userSSLCipherList rangeOfRegex:@":?--"]; + if(markerPos.location != NSNotFound) { + userSSLCipherList = [userSSLCipherList substringToIndex:markerPos.location]; + } + [mySQLConnection setSslCipherList:userSSLCipherList]; + } } // Connection delegate must be set before actual connection attempt is made diff --git a/Source/SPConstants.h b/Source/SPConstants.h index 38e05cc5..f81b3fd0 100644 --- a/Source/SPConstants.h +++ b/Source/SPConstants.h @@ -429,6 +429,7 @@ extern NSString *SPSelectionDetailTypeIndexed; extern NSString *SPSelectionDetailTypePrimaryKeyed; extern NSString *SPSSHEnableMuxingPreference; extern NSString *SPSSHClientPath; +extern NSString *SPSSLCipherListKey; // URLs extern NSString *SPDonationsURL; diff --git a/Source/SPConstants.m b/Source/SPConstants.m index fad42bc6..d9729980 100644 --- a/Source/SPConstants.m +++ b/Source/SPConstants.m @@ -230,6 +230,7 @@ NSString *SPSelectionDetailTypeIndexed = @"SelectionDetailTypeNSIndexS NSString *SPSelectionDetailTypePrimaryKeyed = @"SelectionDetailTypePrimaryKeyedDetails"; NSString *SPSSHEnableMuxingPreference = @"SSHMultiplexingEnabled"; NSString *SPSSHClientPath = @"SSHClientPath"; +NSString *SPSSLCipherListKey = @"SSLCipherList"; // URLs NSString *SPDonationsURL = @"http://www.sequelpro.com/donate/"; -- cgit v1.2.3 From ea39be538d4726b583e67748d6e3e7ffb0ce9026 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 21 Mar 2015 03:05:33 +0100 Subject: Add UI for custom SSL cipher lists See Preferences > Network. Note: If you play around with that too much and libmysql can no longer connect, don't hope for a meaningful error. It will rather be something like "protocol version mismatch". --- Source/SPNetworkPreferencePane.h | 5 +- Source/SPNetworkPreferencePane.m | 195 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 199 insertions(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPNetworkPreferencePane.h b/Source/SPNetworkPreferencePane.h index 37408c32..d980f175 100644 --- a/Source/SPNetworkPreferencePane.h +++ b/Source/SPNetworkPreferencePane.h @@ -37,16 +37,19 @@ * * Network preference pane controller. */ -@interface SPNetworkPreferencePane : SPPreferencePane +@interface SPNetworkPreferencePane : SPPreferencePane { IBOutlet NSView *sshClientPickerView; IBOutlet NSTextField *sshClientPath; IBOutlet NSView *hiddenFileView; + IBOutlet NSTableView *sslCipherView; @private NSAlert *_currentAlert; NSOpenPanel *_currentFilePanel; + NSMutableArray *sslCiphers; } - (IBAction)pickSSHClientViaFileBrowser:(id)sender; - (IBAction)pickSSHClient:(id)sender; +- (IBAction)resetCipherList:(id)sender; @end diff --git a/Source/SPNetworkPreferencePane.m b/Source/SPNetworkPreferencePane.m index 376ba39f..4f13c433 100644 --- a/Source/SPNetworkPreferencePane.m +++ b/Source/SPNetworkPreferencePane.m @@ -30,12 +30,33 @@ #import "SPNetworkPreferencePane.h" +static NSString *SPSSLCipherListMarkerItem = @"--"; +static NSString *SPSSLCipherPboardTypeName = @"SSLCipherPboardType"; + @interface SPNetworkPreferencePane (Private) - (void)updateHiddenFiles; +- (void)loadSSLCiphers; +- (void)storeSSLCiphers; ++ (NSArray *)defaultSSLCipherList; @end @implementation SPNetworkPreferencePane +- (instancetype)init +{ + self = [super init]; + if (self) { + sslCiphers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)dealloc +{ + SPClear(sslCiphers); + [super dealloc]; +} + #pragma mark - #pragma mark Preference pane protocol methods @@ -69,6 +90,16 @@ return NO; } +- (void)preferencePaneWillBeShown +{ + [self loadSSLCiphers]; + if(![[sslCipherView registeredDraggedTypes] containsObject:SPSSLCipherPboardTypeName]) + [sslCipherView registerForDraggedTypes:@[SPSSLCipherPboardTypeName]]; +} + +#pragma mark - +#pragma mark Custom SSH client methods + - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([SPHiddenKeyFileVisibilityKey isEqualTo:keyPath]) { @@ -131,4 +162,168 @@ SPClear(_currentAlert); } +#pragma mark - +#pragma mark SSL cipher list methods + +- (void)loadSSLCiphers +{ + NSArray *supportedCiphers = [SPNetworkPreferencePane defaultSSLCipherList]; + [sslCiphers removeAllObjects]; + + NSString *userCipherString = [prefs stringForKey:SPSSLCipherListKey]; + if(userCipherString) { + //expand user list + NSArray *userCipherList = [userCipherString componentsSeparatedByString:@":"]; + + //compare the users list to the valid list and only copy over valid items + for (NSString *userCipher in userCipherList) { + if (![supportedCiphers containsObject:userCipher] || [sslCiphers containsObject:userCipher]) { + SPLog(@"Unknown ssl cipher in users' list: %@",userCipher); + continue; + } + [sslCiphers addObject:userCipher]; + } + + //now we do the reverse and add valid ciphers that are not yet in the users list. + //We'll just assume the ones not in the users' list are newer and therefore better and add + //them at the top + NSUInteger shift = 0; + for (NSString *validCipher in supportedCiphers) { + if(![sslCiphers containsObject:validCipher]) { + [sslCiphers insertObject:validCipher atIndex:shift++]; + } + } + } + else { + //no user prefs configured, so we'll just go with the defaults + [sslCiphers addObjectsFromArray:supportedCiphers]; + } + + //reload UI + [sslCipherView deselectAll:nil]; + [sslCipherView reloadData]; +} + +- (void)storeSSLCiphers +{ + NSString *flattedList = [sslCiphers componentsJoinedByString:@":"]; + [prefs setObject:flattedList forKey:SPSSLCipherListKey]; +} + +- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView +{ + return [sslCiphers count]; +} + +- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex +{ + NSString *value = [sslCiphers objectAtIndex:rowIndex]; + if ([value isEqualTo:SPSSLCipherListMarkerItem]) { + return NSLocalizedString(@"Disabled Cipher Suites", @"Preferences : Network : SSL Chiper suites : List seperator"); + } + return value; +} + +- (BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row +{ + return ([[sslCiphers objectAtIndex:row] isEqualTo:SPSSLCipherListMarkerItem]); +} + +- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row +{ + return ![self tableView:tableView isGroupRow:row]; +} + +- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id )info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation +{ + if(row < 0) return NO; //why is that even a signed int when all "indexes" are unsigned!? + + NSPasteboard *pboard = [info draggingPasteboard]; + NSArray *draggedItems = [NSKeyedUnarchiver unarchiveObjectWithData:[pboard dataForType:SPSSLCipherPboardTypeName]]; + + NSUInteger nextInsert = row; + for (NSString *item in draggedItems) { + NSUInteger oldPos = [sslCiphers indexOfObject:item]; + [sslCiphers removeObjectAtIndex:oldPos]; + + if(oldPos < (NSUInteger)row) { + // readjust position because we removed an object further up in the list, shifting all following indexes down by 1 + nextInsert--; + } + + [sslCiphers insertObject:item atIndex:nextInsert++]; + } + + NSMutableIndexSet *newSelection = [NSMutableIndexSet indexSet]; + for (NSString *item in draggedItems) { + [newSelection addIndex:[sslCiphers indexOfObject:item]]; + } + + [self storeSSLCiphers]; + [sslCipherView selectRowIndexes:newSelection byExtendingSelection:NO]; + + return YES; +} + +- (NSDragOperation)tableView:(NSTableView *)aTableView validateDrop:(id )info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation +{ + //cannot drop something on another item in the list, only between them + return (operation == NSTableViewDropOn)? NSDragOperationNone : NSDragOperationMove; +} + +- (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard +{ + //the marker cannot be actively reordered + if ([rowIndexes containsIndex:[sslCiphers indexOfObject:SPSSLCipherListMarkerItem]]) + return NO; + + //put the names of the items on the pasteboard. easier to work with than indexes... + NSMutableArray *items = [NSMutableArray arrayWithCapacity:[rowIndexes count]]; + [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { + [items addObject:[sslCiphers objectAtIndex:idx]]; + }]; + + NSData *arch = [NSKeyedArchiver archivedDataWithRootObject:items]; + [pboard declareTypes:@[SPSSLCipherPboardTypeName] owner:self]; + [pboard setData:arch forType:SPSSLCipherPboardTypeName]; + return YES; +} + +- (IBAction)resetCipherList:(id)sender +{ + //remove the user pref and reset the GUI + [prefs removeObjectForKey:SPSSLCipherListKey]; + [self loadSSLCiphers]; +} + ++ (NSArray *)defaultSSLCipherList +{ + //this is the default list as hardcoded in SPMySQLConnection.m + //Sadly there is no way to make MySQL give us the list of runtime-supported ciphers. + return @[@"DHE-RSA-AES256-SHA", + @"AES256-SHA", + @"DHE-RSA-AES128-SHA", + @"AES128-SHA", + @"AES256-RMD", + @"AES128-RMD", + @"DES-CBC3-RMD", + @"DHE-RSA-AES256-RMD", + @"DHE-RSA-AES128-RMD", + @"DHE-RSA-DES-CBC3-RMD", + @"RC4-SHA", + @"RC4-MD5", + @"DES-CBC3-SHA", + @"DES-CBC-SHA", + @"EDH-RSA-DES-CBC3-SHA", + @"EDH-RSA-DES-CBC-SHA", + SPSSLCipherListMarkerItem, //marker. disabled items below here + @"EDH-DSS-DES-CBC-SHA", + @"EDH-DSS-DES-CBC3-SHA", + @"DHE-DSS-AES128-SHA", + @"DHE-DSS-AES256-SHA", + @"DHE-DSS-DES-CBC3-RMD", + @"DHE-DSS-AES128-RMD", + @"DHE-DSS-AES256-RMD"]; +} + @end -- cgit v1.2.3 From 9fd78af55a55a8a5a976a6b6f31839439cc28241 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 24 Mar 2015 21:15:03 +0100 Subject: Disable editing columns in "Display in Hex" mode This is a workaround for a potential data loss/corruption bug until we really fix this (see #1876) --- Source/SPTableContentDelegate.m | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'Source') diff --git a/Source/SPTableContentDelegate.m b/Source/SPTableContentDelegate.m index b73282ec..19bbc4b3 100644 --- a/Source/SPTableContentDelegate.m +++ b/Source/SPTableContentDelegate.m @@ -261,11 +261,12 @@ [tableContentView reloadData]; } + // Retrieve the column definition + NSDictionary *columnDefinition = [cqColumnDefinition objectAtIndex:[[tableColumn identifier] integerValue]]; + // Open the editing sheet if required if ([tableContentView shouldUseFieldEditorForRow:rowIndex column:[[tableColumn identifier] integerValue] checkWithLock:NULL]) { - // Retrieve the column definition - NSDictionary *columnDefinition = [cqColumnDefinition objectAtIndex:[[tableColumn identifier] integerValue]]; BOOL isBlob = [tableDataInstance columnIsBlobOrText:[[tableColumn headerCell] stringValue]]; // A table is per definition editable @@ -318,6 +319,7 @@ if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { [fieldEditor setTextMaxLength:[[self tableView:tableContentView objectValueForTableColumn:tableColumn row:rowIndex] length]]; + isFieldEditable = NO; } NSInteger editedColumn = 0; @@ -345,6 +347,13 @@ return NO; } + // TODO: Fix editing of "Display as Hex" columns and remove this (also see above) + if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { + NSBeep(); + [SPTooltip showWithObject:NSLocalizedString(@"Disable \"Display Binary Data as Hex\" in the View menu to edit this field.",@"Temporary : Tooltip shown when trying to edit a binary field in table content view while it is displayed using HEX conversion")]; + return NO; + } + return YES; } -- cgit v1.2.3 From 34383efe75a6f655522c9cb6385b3cb97cd99e3c Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Mar 2015 20:22:29 +0100 Subject: Fix an issue with certain tooltips being placed on the wrong screen in certain multi screen configurations This did affect users with a vertical multi monitor setup using the classical (single Space) multi monitor mode. --- Source/SPTooltip.m | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'Source') diff --git a/Source/SPTooltip.m b/Source/SPTooltip.m index 0a7597f5..478945ed 100644 --- a/Source/SPTooltip.m +++ b/Source/SPTooltip.m @@ -320,8 +320,11 @@ static CGFloat slow_in_out (CGFloat t) NSScreen* candidate; for(candidate in [NSScreen screens]) { - if(NSMinX([candidate frame]) < pos.x && NSMinX([candidate frame]) > NSMinX(screenFrame)) - screenFrame = [candidate frame]; + NSRect cf = [candidate frame]; + if(NSPointInRect(pos,cf)) { + screenFrame = cf; + break; + } } // is contentView a webView calculate actual rendered size via JavaScript -- cgit v1.2.3 From 01dd6402ee530e5d9fff1916507ea287893f0960 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 2 Apr 2015 17:51:00 +0200 Subject: Some code reformatting --- Source/SPTableContentDataSource.m | 199 +++++++++++++++++++------------------- 1 file changed, 97 insertions(+), 102 deletions(-) (limited to 'Source') diff --git a/Source/SPTableContentDataSource.m b/Source/SPTableContentDataSource.m index c7af81be..21422865 100644 --- a/Source/SPTableContentDataSource.m +++ b/Source/SPTableContentDataSource.m @@ -54,96 +54,92 @@ if (tableView == filterTableView) { return filterTableIsSwapped ? [filterTableData count] : [[[filterTableData objectForKey:@"0"] objectForKey:SPTableContentFilterKey] count]; } - else #endif - if (tableView == tableContentView) { - return tableRowsCount; - } + if (tableView == tableContentView) { + return tableRowsCount; + } return 0; } - (id)tableView:(SPCopyTable *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex { + NSUInteger columnIndex = [[tableColumn identifier] integerValue]; #ifndef SP_CODA if (tableView == filterTableView) { - if (filterTableIsSwapped) - + if (filterTableIsSwapped) { // First column shows the field names - if ([[tableColumn identifier] integerValue] == 0) { + if (columnIndex == 0) { return [[[NSTableHeaderCell alloc] initTextCell:[[filterTableData objectForKey:[NSNumber numberWithInteger:rowIndex]] objectForKey:@"name"]] autorelease]; } - else { - return NSArrayObjectAtIndex([[filterTableData objectForKey:[NSNumber numberWithInteger:rowIndex]] objectForKey:SPTableContentFilterKey], [[tableColumn identifier] integerValue] - 1); - } - else { - return NSArrayObjectAtIndex([[filterTableData objectForKey:[tableColumn identifier]] objectForKey:SPTableContentFilterKey], rowIndex); + + return NSArrayObjectAtIndex([[filterTableData objectForKey:[NSNumber numberWithInteger:rowIndex]] objectForKey:SPTableContentFilterKey], columnIndex - 1); } + + return NSArrayObjectAtIndex([[filterTableData objectForKey:[tableColumn identifier]] objectForKey:SPTableContentFilterKey], rowIndex); } - else #endif - if (tableView == tableContentView) { - - id value = nil; - NSUInteger columnIndex = [[tableColumn identifier] integerValue]; + if (tableView == tableContentView) { + + id value = nil; + + // While the table is being loaded, additional validation is required - data + // locks must be used to avoid crashes, and indexes higher than the available + // rows or columns may be requested. Return "..." to indicate loading in these + // cases. + if (isWorking) { + pthread_mutex_lock(&tableValuesLock); - // While the table is being loaded, additional validation is required - data - // locks must be used to avoid crashes, and indexes higher than the available - // rows or columns may be requested. Return "..." to indicate loading in these - // cases. - if (isWorking) { - pthread_mutex_lock(&tableValuesLock); - - if (rowIndex < (NSInteger)tableRowsCount && columnIndex < [tableValues columnCount]) { - value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:YES]; - } - - pthread_mutex_unlock(&tableValuesLock); - - if (!value) return @"..."; - } - else { - if ([tableView editedColumn] == (NSInteger)columnIndex && [tableView editedRow] == rowIndex) { - value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:NO]; - } - else { - value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:YES]; - } + if (rowIndex < (NSInteger)tableRowsCount && columnIndex < [tableValues columnCount]) { + value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:YES]; } - - NSDictionary *columnDefinition = [[(id )[tableContentView delegate] dataColumnDefinitions] objectAtIndex:columnIndex]; - - NSString *columnType = [columnDefinition objectForKey:@"typegrouping"]; - if ([value isKindOfClass:[SPMySQLGeometryData class]]) { - return [value wktString]; - } + pthread_mutex_unlock(&tableValuesLock); - if ([value isNSNull]) { - return [prefs objectForKey:SPNullValue]; + if (!value) return @"..."; + } + else { + if ([tableView editedColumn] == (NSInteger)columnIndex && [tableView editedRow] == rowIndex) { + value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:NO]; } - - if ([value isKindOfClass:[NSData class]]) { + else { + value = [self _contentValueForTableColumn:columnIndex row:rowIndex asPreview:YES]; + } + } - if ([columnType isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { - return [NSString stringWithFormat:@"0x%@", [value dataToHexString]]; - } + NSDictionary *columnDefinition = [[(id )[tableContentView delegate] dataColumnDefinitions] objectAtIndex:columnIndex]; - pthread_mutex_t *fieldEditorCheckLock = NULL; - if (isWorking) { - fieldEditorCheckLock = &tableValuesLock; - } + NSString *columnType = [columnDefinition objectForKey:@"typegrouping"]; + + if ([value isKindOfClass:[SPMySQLGeometryData class]]) { + return [value wktString]; + } + + if ([value isNSNull]) { + return [prefs objectForKey:SPNullValue]; + } + + if ([value isKindOfClass:[NSData class]]) { - // Always retrieve the short string representation, truncating the value where necessary - return [value shortStringRepresentationUsingEncoding:[mySQLConnection stringEncoding]]; + if ([columnType isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { + return [NSString stringWithFormat:@"0x%@", [value dataToHexString]]; } - - if ([value isSPNotLoaded]) { - return NSLocalizedString(@"(not loaded)", @"value shown for hidden blob and text fields"); + + pthread_mutex_t *fieldEditorCheckLock = NULL; + if (isWorking) { + fieldEditorCheckLock = &tableValuesLock; } - - return value; + + // Always retrieve the short string representation, truncating the value where necessary + return [value shortStringRepresentationUsingEncoding:[mySQLConnection stringEncoding]]; + } + + if ([value isSPNotLoaded]) { + return NSLocalizedString(@"(not loaded)", @"value shown for hidden blob and text fields"); } + + return value; + } return nil; } @@ -163,49 +159,48 @@ return; } - else #endif - if (tableView == tableContentView) { - - // If the current cell should have been edited in a sheet, do nothing - field closing will have already - // updated the field. - if ([tableContentView shouldUseFieldEditorForRow:rowIndex column:[[tableColumn identifier] integerValue] checkWithLock:NULL]) { - return; - } - - // If table data comes from a view, save back to the view - if ([tablesListInstance tableType] == SPTableTypeView) { - [self saveViewCellValue:object forTableColumn:tableColumn row:rowIndex]; - return; - } - - // Catch editing events in the row and if the row isn't currently being edited, - // start an edit. This allows edits including enum changes to save correctly. - if (isEditingRow && [tableContentView selectedRow] != currentlyEditingRow) { - [self saveRowOnDeselect]; - } + if (tableView == tableContentView) { + + // If the current cell should have been edited in a sheet, do nothing - field closing will have already + // updated the field. + if ([tableContentView shouldUseFieldEditorForRow:rowIndex column:[[tableColumn identifier] integerValue] checkWithLock:NULL]) { + return; + } + + // If table data comes from a view, save back to the view + if ([tablesListInstance tableType] == SPTableTypeView) { + [self saveViewCellValue:object forTableColumn:tableColumn row:rowIndex]; + return; + } + + // Catch editing events in the row and if the row isn't currently being edited, + // start an edit. This allows edits including enum changes to save correctly. + if (isEditingRow && [tableContentView selectedRow] != currentlyEditingRow) { + [self saveRowOnDeselect]; + } + + if (!isEditingRow) { + [oldRow setArray:[tableValues rowContentsAtIndex:rowIndex]]; - if (!isEditingRow) { - [oldRow setArray:[tableValues rowContentsAtIndex:rowIndex]]; - - isEditingRow = YES; - currentlyEditingRow = rowIndex; + isEditingRow = YES; + currentlyEditingRow = rowIndex; + } + + NSDictionary *column = NSArrayObjectAtIndex(dataColumns, [[tableColumn identifier] integerValue]); + + if (object) { + // Restore NULLs if necessary + if ([object isEqualToString:[prefs objectForKey:SPNullValue]] && [[column objectForKey:@"null"] boolValue]) { + object = [NSNull null]; } - NSDictionary *column = NSArrayObjectAtIndex(dataColumns, [[tableColumn identifier] integerValue]); - - if (object) { - // Restore NULLs if necessary - if ([object isEqualToString:[prefs objectForKey:SPNullValue]] && [[column objectForKey:@"null"] boolValue]) { - object = [NSNull null]; - } - - [tableValues replaceObjectInRow:rowIndex column:[[tableColumn identifier] integerValue] withObject:object]; - } - else { - [tableValues replaceObjectInRow:rowIndex column:[[tableColumn identifier] integerValue] withObject:@""]; - } + [tableValues replaceObjectInRow:rowIndex column:[[tableColumn identifier] integerValue] withObject:object]; + } + else { + [tableValues replaceObjectInRow:rowIndex column:[[tableColumn identifier] integerValue] withObject:@""]; } + } } @end -- cgit v1.2.3 From bdf196ac60472fa7eccbd094ee1b5a505f550f4d Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 2 Apr 2015 23:33:38 +0200 Subject: Remove a hack to support QuickLook on 10.5 We don't need that anymore since 10.5 support is gone. Sequel Pro now explicitly links Quartz and doesn't try to guess QuickLook support at runtime. --- Source/QLPreviewPanel.h | 119 ----------------------------------- Source/SPFieldEditorController.h | 21 ++++++- Source/SPFieldEditorController.m | 133 +++++++++------------------------------ Source/SPTableContent.m | 1 - 4 files changed, 49 insertions(+), 225 deletions(-) delete mode 100644 Source/QLPreviewPanel.h (limited to 'Source') diff --git a/Source/QLPreviewPanel.h b/Source/QLPreviewPanel.h deleted file mode 100644 index 7c342ed9..00000000 --- a/Source/QLPreviewPanel.h +++ /dev/null @@ -1,119 +0,0 @@ -// -// QLPreviewPanel.h -// sequel-pro -// -// Created by Stuart Connolly (stuconnolly.com) on June 15, 2009. -// Copyright (c) 2009 Stuart Connolly. 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 - -// As the QuickLook framework is private we have to make -// these methods public to avoid warnings while compiling -@interface QLPreviewPanel : NSPanel - -+ (id)sharedPreviewPanel; -+ (id)_previewPanel; -+ (BOOL)isSharedPreviewPanelLoaded; -- (id)initWithContentRect:(NSRect)fp8 styleMask:(NSUInteger)fp24 backing:(NSUInteger)fp28 defer:(BOOL)fp32; -- (id)initWithCoder:(id)fp8; -- (void)dealloc; -- (BOOL)isOpaque; -- (BOOL)canBecomeKeyWindow; -- (BOOL)canBecomeMainWindow; -- (BOOL)shouldIgnorePanelFrameChanges; -- (BOOL)isOpen; -- (void)setFrame:(NSRect)fp8 display:(BOOL)fp24 animate:(BOOL)fp28; -- (id)_subEffectsForWindow:(id)fp8 itemFrame:(NSRect)fp12 transitionWindow:(id *)fp28; -- (id)_scaleEffectForItemFrame:(NSRect)fp8 transitionWindow:(id *)fp24; -- (void)_invertCurrentEffect; -- (struct _NSRect)_currentItemFrame; -- (void)setAutosizesAndCenters:(BOOL)fp8; -- (BOOL)autosizesAndCenters; -- (void)makeKeyAndOrderFront:(id)fp8; -- (void)makeKeyAndOrderFrontWithEffect:(NSInteger)fp8; -- (void)makeKeyAndGoFullscreenWithEffect:(NSInteger)fp8; -- (void)makeKeyAndOrderFrontWithEffect:(NSInteger)fp8 canClose:(BOOL)fp12; -- (void)_makeKeyAndOrderFrontWithEffect:(NSInteger)fp8 canClose:(BOOL)fp12 willOpen:(BOOL)fp16 toFullscreen:(BOOL)fp20; -- (NSInteger)openingEffect; -- (void)closePanel; -- (void)close; -- (void)closeWithEffect:(NSInteger)fp8; -- (void)closeWithEffect:(NSInteger)fp8 canReopen:(BOOL)fp12; -- (void)_closeWithEffect:(NSInteger)fp8 canReopen:(BOOL)fp12; -- (void)windowEffectDidTerminate:(id)fp8; -- (void)_close:(id)fp8; -- (void)sendEvent:(id)fp8; -- (void)selectNextItem; -- (void)selectPreviousItem; -- (void)setURLs:(id)fp8 currentIndex:(NSUInteger)fp12 preservingDisplayState:(BOOL)fp16; -- (void)setURLs:(id)fp8 preservingDisplayState:(BOOL)fp12; -- (void)setURLs:(id)fp8; -- (id)URLs; -- (NSUInteger)indexOfCurrentURL; -- (void)setIndexOfCurrentURL:(NSUInteger)fp8; -- (void)setDelegate:(id)fp8; -- (id)sharedPreviewView; -- (void)setSharedPreviewView:(id)fp8; -- (void)setCyclesSelection:(BOOL)fp8; -- (BOOL)cyclesSelection; -- (void)setShowsAddToiPhotoButton:(BOOL)fp8; -- (BOOL)showsAddToiPhotoButton; -- (void)setShowsiChatTheaterButton:(BOOL)fp8; -- (BOOL)showsiChatTheaterButton; -- (void)setShowsFullscreenButton:(BOOL)fp8; -- (BOOL)showsFullscreenButton; -- (void)setShowsIndexSheetButton:(BOOL)fp8; -- (BOOL)showsIndexSheetButton; -- (void)setAutostarts:(BOOL)fp8; -- (BOOL)autostarts; -- (void)setPlaysDuringPanelAnimation:(BOOL)fp8; -- (BOOL)playsDuringPanelAnimation; -- (void)setDeferredLoading:(BOOL)fp8; -- (BOOL)deferredLoading; -- (void)setEnableDragNDrop:(BOOL)fp8; -- (BOOL)enableDragNDrop; -- (void)start:(id)fp8; -- (void)stop:(id)fp8; -- (void)setShowsIndexSheet:(BOOL)fp8; -- (BOOL)showsIndexSheet; -- (void)setShareWithiChat:(BOOL)fp8; -- (BOOL)shareWithiChat; -- (void)setPlaysSlideShow:(BOOL)fp8; -- (BOOL)playsSlideShow; -- (void)setIsFullscreen:(BOOL)fp8; -- (BOOL)isFullscreen; -- (void)setMandatoryClient:(id)fp8; -- (id)mandatoryClient; -- (void)setForcedContentTypeUTI:(id)fp8; -- (id)forcedContentTypeUTI; -- (void)setDocumentURLs:(id)fp8; -- (void)setDocumentURLs:(id)fp8 preservingDisplayState:(BOOL)fp12; -- (void)setDocumentURLs:(id)fp8 itemFrame:(struct _NSRect)fp12; -- (void)setURLs:(id)fp8 itemFrame:(struct _NSRect)fp12; -- (void)setAutoSizeAndCenterOnScreen:(BOOL)fp8; -- (void)setShowsAddToiPhoto:(BOOL)fp8; -- (void)setShowsiChatTheater:(BOOL)fp8; -- (void)setShowsFullscreen:(BOOL)fp8; - -@end diff --git a/Source/SPFieldEditorController.h b/Source/SPFieldEditorController.h index b56c6d1c..fbf04c49 100644 --- a/Source/SPFieldEditorController.h +++ b/Source/SPFieldEditorController.h @@ -28,6 +28,21 @@ // // More info at +#ifndef SP_CODA + +#import // QuickLookUI + +//This is an informal protocol +@protocol _QLPreviewPanelController + +- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel; +- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel; +- (void)endPreviewPanelControl:(QLPreviewPanel *)panel; + +@end + +#endif + @class SPWindow; /** @@ -38,7 +53,11 @@ * This class offers a sheet for editing different kind of data such as text, blobs (including images) as * editSheet and bit fields as bitSheet. */ -@interface SPFieldEditorController : NSWindowController +@interface SPFieldEditorController : NSWindowController { IBOutlet id editSheetProgressBar; IBOutlet id editSheetSegmentControl; diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index 4f34a998..52242406 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -29,9 +29,6 @@ // More info at #import "SPFieldEditorController.h" -#ifndef SP_CODA -#import "QLPreviewPanel.h" -#endif #import "RegexKitLite.h" #import "SPTooltip.h" #import "SPGeometryDataView.h" @@ -164,8 +161,8 @@ #ifndef SP_CODA // On Mac OSX 10.6 QuickLook runs non-modal thus order out the panel // if still visible - if ([[NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel] isVisible]) { - [[NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel] orderOut:nil]; + if ([[QLPreviewPanel sharedPreviewPanel] isVisible]) { + [[QLPreviewPanel sharedPreviewPanel] orderOut:nil]; } #endif @@ -882,89 +879,34 @@ - (void)invokeQuickLookOfType:(NSString *)type treatAsText:(BOOL)isText { #ifndef SP_CODA - // Load QL via private framework (SDK 10.5) - if([[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/QuickLookUI.framework"] load]) { - - [editSheetProgressBar startAnimation:self]; - - [self createTemporaryQuickLookFileOfType:type treatAsText:isText]; - - counter++; - - // Init QuickLook - id ql = [NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel]; - - [[ql delegate] setDelegate:self]; - [ql setURLs:@[[NSURL fileURLWithPath:tmpFileName]] currentIndex:0 preservingDisplayState:YES]; - - // TODO: No interaction with iChat and iPhoto due to .scriptSuite warning: - // unknown image format - [ql setShowsAddToiPhotoButton:NO]; - [ql setShowsiChatTheaterButton:NO]; - // Since we are inside of editSheet we have to avoid full-screen zooming - // otherwise QuickLook hangs - [ql setShowsFullscreenButton:NO]; - [ql setEnableDragNDrop:NO]; - // Order out QuickLook with animation effect according to self:previewPanel:frameForURL: - [ql makeKeyAndOrderFrontWithEffect:2]; // 1 = fade in - - // quickLookCloseMarker == 1 break the modal session - quickLookCloseMarker = 0; - - [editSheetProgressBar stopAnimation:self]; - - // Run QuickLook in its own modal seesion for event handling - NSModalSession session = [NSApp beginModalSessionForWindow:ql]; - for (;;) { - // Conditions for closing QuickLook - if ([NSApp runModalSession:session] != NSRunContinuesResponse - || quickLookCloseMarker == 1 - || ![ql isVisible]) - break; - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode - beforeDate:[NSDate distantFuture]]; - - } - [NSApp endModalSession:session]; - - // set ql's delegate to nil for dealloc - [[ql windowController] setDelegate:nil]; - - } - // Load QL via framework (SDK 10.5 but SP runs on 10.6) - // TODO: This is an hack in order to be able to support QuickLook on Mac OS X 10.5 and 10.6 - // as long as SP will be compiled against SDK 10.5. - // If SP will be compiled against SDK 10.6 we can use the standard way by using - // the QuickLookUI which is part of the Quartz.framework. See Developer example "QuickLookDownloader" + // See Developer example "QuickLookDownloader" // file:///Developer/Documentation/DocSets/com.apple.adc.documentation.AppleSnowLeopard.CoreReference.docset/Contents/Resources/Documents/samplecode/QuickLookDownloader/index.html#//apple_ref/doc/uid/DTS40009082 - else if([[NSBundle bundleWithPath:@"/System/Library/Frameworks/Quartz.framework/Frameworks/QuickLookUI.framework"] load]) { - [editSheetProgressBar startAnimation:self]; + [editSheetProgressBar startAnimation:self]; - [self createTemporaryQuickLookFileOfType:type treatAsText:isText]; + [self createTemporaryQuickLookFileOfType:type treatAsText:isText]; - counter++; + counter++; - // TODO: If QL is visible reload it - but how? - // Up to now QL will close and the user has to redo it. - if([[NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel] isVisible]) { - [[NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel] orderOut:nil]; - } + // TODO: If QL is visible reload it - but how? + // Up to now QL will close and the user has to redo it. + if([[QLPreviewPanel sharedPreviewPanel] isVisible]) { + [[QLPreviewPanel sharedPreviewPanel] orderOut:nil]; + } - [[NSClassFromString(@"QLPreviewPanel") sharedPreviewPanel] makeKeyAndOrderFront:nil]; + [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; - [editSheetProgressBar stopAnimation:self]; + [editSheetProgressBar stopAnimation:self]; - } else { - [SPTooltip showWithObject:[NSString stringWithFormat:@"QuickLook is not available on that platform."]]; - } #endif } +#pragma mark - QLPreviewPanelController methods + /** * QuickLook delegate for SDK 10.6. Set the Quicklook delegate to self and suppress setShowsAddToiPhotoButton since the format is unknow. */ -- (void)beginPreviewPanelControl:(id)panel +- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel { #ifndef SP_CODA @@ -972,15 +914,13 @@ [panel setDelegate:self]; [panel setDataSource:self]; - // Due to the unknown image format disable image sharing - [panel setShowsAddToiPhotoButton:NO]; #endif } /** * QuickLook delegate for SDK 10.6 - not in usage. */ -- (void)endPreviewPanelControl:(id)panel +- (void)endPreviewPanelControl:(QLPreviewPanel *)panel { // This document loses its responsisibility on the preview panel // Until the next call to -beginPreviewPanelControl: it must not @@ -990,22 +930,19 @@ /** * QuickLook delegate for SDK 10.6 */ -- (BOOL)acceptsPreviewPanelControl:(id)panel; +- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel; { return YES; } -// QuickLook delegates for SDK 10.6 -// - (BOOL)previewPanel:(QLPreviewPanel *)panel handleEvent:(NSEvent *)event -// { -// } +#pragma mark - QLPreviewPanelDataSource methods /** * QuickLook delegate for SDK 10.6. * * @return It always returns 1. */ -- (NSInteger)numberOfPreviewItemsInPreviewPanel:(id)panel +- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel { return 1; } @@ -1015,7 +952,7 @@ * * @return It returns as NSURL the temporarily created file. */ -- (id)previewPanel:(id)panel previewItemAtIndex:(NSInteger)anIndex +- (id)previewPanel:(QLPreviewPanel *)panel previewItemAtIndex:(NSInteger)anIndex { if(tmpFileName) return [NSURL fileURLWithPath:tmpFileName]; @@ -1023,33 +960,19 @@ return nil; } -/** - * QuickLook delegate for SDK 10.5. - * - * @return It returns the frame of the application's middle. If an empty frame is returned then the panel will fade in/out instead. - */ -- (NSRect)previewPanel:(NSPanel*)panel frameForURL:(NSURL*)URL -{ - - // Close modal session defined in invokeQuickLookOfType: - // if user closes the QuickLook view - quickLookCloseMarker = 1; +#pragma mark - QLPreviewPanelDelegate methods - // Return the App's middle point - NSRect mwf = [[NSApp mainWindow] frame]; - return NSMakeRect( - mwf.origin.x+mwf.size.width/2, - mwf.origin.y+mwf.size.height/2, - 5, 5); - -} +// QuickLook delegates for SDK 10.6 +// - (BOOL)previewPanel:(QLPreviewPanel *)panel handleEvent:(NSEvent *)event +// { +// } /** * QuickLook delegate for SDK 10.6. * * @return It returns the frame of the application's middle. If an empty frame is returned then the panel will fade in/out instead. */ -- (NSRect)previewPanel:(id)panel sourceFrameOnScreenForPreviewItem:(id)item +- (NSRect)previewPanel:(QLPreviewPanel *)panel sourceFrameOnScreenForPreviewItem:(id)item { // Return the App's middle point NSRect mwf = [[NSApp mainWindow] frame]; @@ -1065,6 +988,8 @@ // return [NSImage imageNamed:@"database"]; // } +#pragma mark - + /** * Called by (SPImageView) if an image was pasted into the editSheet */ diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 9295c858..45add266 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -43,7 +43,6 @@ #import "SPQueryDocumentsController.h" #import "SPTextAndLinkCell.h" #ifndef SP_CODA -#import "QLPreviewPanel.h" #import "SPSplitView.h" #endif #import "SPFieldEditorController.h" -- cgit v1.2.3 From 9aa296a3e93b0b98a1018ba4d7aa8920d85b2a81 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 2 Apr 2015 23:34:45 +0200 Subject: Converted some setters to equivalent @propertys --- Source/SPFieldEditorController.h | 30 ++++++++++++++++++++++----- Source/SPFieldEditorController.m | 44 ++++------------------------------------ 2 files changed, 29 insertions(+), 45 deletions(-) (limited to 'Source') diff --git a/Source/SPFieldEditorController.h b/Source/SPFieldEditorController.h index fbf04c49..ec36c9d2 100644 --- a/Source/SPFieldEditorController.h +++ b/Source/SPFieldEditorController.h @@ -195,6 +195,31 @@ @property(readwrite, retain) NSDictionary *editedFieldInfo; +//don't blame me for nonatomic,assign. That's how the previous setters worked :) + +/** + * The maximum text length of the underlying table field for input validation. + */ +@property(nonatomic,assign) unsigned long long textMaxLength; + +/** + * The field type of the underlying table field for input validation. + * The field type will be used for dispatching which sheet will be shown. + * If type == BIT the bitSheet will be used otherwise the editSheet. + */ +@property(nonatomic,assign) NSString *fieldType; + +/** + * The field encoding of the underlying table field for displaying it to the user. + */ +@property(nonatomic,assign) NSString *fieldEncoding; + +/** + * Whether underlying table field allows NULL for several validations. + * If allowNULL is YES NULL value is allowed for the underlying table field. + */ +@property(nonatomic,assign) BOOL allowNULL; + - (IBAction)closeEditSheet:(id)sender; - (IBAction)openEditSheet:(id)sender; - (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; @@ -215,11 +240,6 @@ isObjectBlob:(BOOL)isFieldBlob isEditable:(BOOL)isEditable withWindow:(NSWindow *)theWindow sender:(id)sender contextInfo:(NSDictionary*)theContextInfo; -- (void)setTextMaxLength:(NSUInteger)length; -- (void)setFieldType:(NSString*)aType; -- (void)setFieldEncoding:(NSString*)aEncoding; -- (void)setAllowNULL:(BOOL)allowNULL; - - (void)processPasteImageData; - (void)processUpdatedImageData:(NSData *)data; diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index 52242406..c1908a19 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -49,6 +49,10 @@ @implementation SPFieldEditorController @synthesize editedFieldInfo; +@synthesize textMaxLength = maxTextLength; +@synthesize fieldType; +@synthesize fieldEncoding; +@synthesize allowNULL = _allowNULL; /** * Initialise an instance of SPFieldEditorController using the XIB “FieldEditorSheet.xib”. Init the available Quciklook format by reading @@ -482,46 +486,6 @@ } } -/** - * Set the maximum text length of the underlying table field for input validation. - * - * @param length The maximum text length - */ -- (void)setTextMaxLength:(NSUInteger)length -{ - maxTextLength = length; -} - -/** - * Set the field type of the underlying table field for input validation. - * - * @param aType The field type which will be used for dispatching which sheet will be shown. If type == BIT the bitSheet will be used otherwise the editSheet. - */ -- (void)setFieldType:(NSString*)aType -{ - fieldType = aType; -} - -/** - * Set the field encoding of the underlying table field for displaying it to the user. - * - * @param aEncoding encoding - */ -- (void)setFieldEncoding:(NSString*)aEncoding -{ - fieldEncoding = aEncoding; -} - -/** - * Set if underlying table field allows NULL for several validations. - * - * @param allowNULL If allowNULL is YES NULL value is allowed for the underlying table field - */ -- (void)setAllowNULL:(BOOL)allowNULL -{ - _allowNULL = allowNULL; -} - /** * Segement controller for text/image/hex buttons in editSheet */ -- cgit v1.2.3 From 0382e135e30c1e441225717fc5eed3520108d3ca Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 2 Apr 2015 23:55:17 +0200 Subject: Replaced some magic numbers with an enum --- Source/SPFieldEditorController.m | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) (limited to 'Source') diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m index c1908a19..c791dfc5 100644 --- a/Source/SPFieldEditorController.m +++ b/Source/SPFieldEditorController.m @@ -40,6 +40,12 @@ #import +typedef enum { + TextSegment = 0, + ImageSegment, + HexSegment +} FieldEditorSegment; + @interface SPFieldEditorController (SPFieldEditorControllerDelegate) - (void)processFieldEditorResult:(id)data contextInfo:(NSDictionary*)contextInfo; @@ -344,7 +350,7 @@ [editSheetQuickLookButton setHidden:((!_isBlob && !isBinary) || _isGeometry)]; [editSheetSegmentControl setHidden:(!_isBlob && !isBinary && !_isGeometry)]; - [editSheetSegmentControl setEnabled:YES forSegment:1]; + [editSheetSegmentControl setEnabled:YES forSegment:ImageSegment]; // Set window's min size since no segment and quicklook buttons are hidden if (_isBlob || isBinary || _isGeometry) { @@ -399,7 +405,7 @@ [editImage setHidden:YES]; [editTextView setHidden:YES]; [editTextScrollView setHidden:YES]; - [editSheetSegmentControl setSelectedSegment:2]; + [editSheetSegmentControl setSelectedSegment:HexSegment]; } else if ([sheetEditData isKindOfClass:[SPMySQLGeometryData class]]) { SPGeometryDataView *v = [[[SPGeometryDataView alloc] initWithCoordinates:[sheetEditData coordinates] targetDimension:2000.0f] autorelease]; @@ -411,8 +417,8 @@ [hexTextView setString:@""]; [hexTextView setHidden:YES]; [hexTextScrollView setHidden:YES]; - [editSheetSegmentControl setEnabled:NO forSegment:2]; - [editSheetSegmentControl setSelectedSegment:0]; + [editSheetSegmentControl setEnabled:NO forSegment:HexSegment]; + [editSheetSegmentControl setSelectedSegment:TextSegment]; [editTextView setHidden:NO]; [editTextScrollView setHidden:NO]; } @@ -426,7 +432,7 @@ [editImage setHidden:YES]; [editTextView setHidden:NO]; [editTextScrollView setHidden:NO]; - [editSheetSegmentControl setSelectedSegment:0]; + [editSheetSegmentControl setSelectedSegment:TextSegment]; } if (image) { @@ -437,7 +443,7 @@ if(!_isGeometry) { [editTextView setHidden:YES]; [editTextScrollView setHidden:YES]; - [editSheetSegmentControl setSelectedSegment:1]; + [editSheetSegmentControl setSelectedSegment:ImageSegment]; } } else { @@ -453,13 +459,13 @@ [hexTextScrollView setHidden:YES]; } else { - [editSheetSegmentControl setEnabled:NO forSegment:1]; + [editSheetSegmentControl setEnabled:NO forSegment:ImageSegment]; } [editImage setHidden:YES]; [editTextView setHidden:NO]; [editTextScrollView setHidden:NO]; - [editSheetSegmentControl setSelectedSegment:0]; + [editSheetSegmentControl setSelectedSegment:TextSegment]; } // Locate the caret in editTextView @@ -491,8 +497,8 @@ */ - (IBAction)segmentControllerChanged:(id)sender { - switch([sender selectedSegment]){ - case 0: // text + switch((FieldEditorSegment)[sender selectedSegment]){ + case TextSegment: [editTextView setHidden:NO]; [editTextScrollView setHidden:NO]; [editImage setHidden:YES]; @@ -503,7 +509,7 @@ [[NSApp mainWindow] makeFirstResponder:editTextView]; #endif break; - case 1: // image + case ImageSegment: [editTextView setHidden:YES]; [editTextScrollView setHidden:YES]; [editImage setHidden:NO]; @@ -511,7 +517,7 @@ [hexTextScrollView setHidden:YES]; [usedSheet makeFirstResponder:editImage]; break; - case 2: // hex - load on demand + case HexSegment: [usedSheet makeFirstResponder:hexTextView]; if([[hexTextView string] isEqualToString:@""]) { [editSheetProgressBar startAnimation:self]; @@ -551,7 +557,7 @@ { NSSavePanel *panel = [NSSavePanel savePanel]; - if ([editSheetSegmentControl selectedSegment] == 1 && [sheetEditData isKindOfClass:[SPMySQLGeometryData class]]) { + if ([editSheetSegmentControl selectedSegment] == ImageSegment && [sheetEditData isKindOfClass:[SPMySQLGeometryData class]]) { [panel setAllowedFileTypes:@[@"pdf"]]; [panel setAllowsOtherFileTypes:NO]; } @@ -679,7 +685,7 @@ // If the image cell now contains a valid image, select the image view if (image) { - [editSheetSegmentControl setSelectedSegment:1]; + [editSheetSegmentControl setSelectedSegment:ImageSegment]; [hexTextView setHidden:YES]; [hexTextScrollView setHidden:YES]; [editImage setHidden:NO]; @@ -688,7 +694,7 @@ // Otherwise deselect the image view } else { - [editSheetSegmentControl setSelectedSegment:0]; + [editSheetSegmentControl setSelectedSegment:TextSegment]; [hexTextView setHidden:YES]; [hexTextScrollView setHidden:YES]; [editImage setHidden:YES]; @@ -722,7 +728,7 @@ } else if ( [sheetEditData isKindOfClass:[SPMySQLGeometryData class]] ) { - if ( [editSheetSegmentControl selectedSegment] == 0 || editImage == nil ) { + if ( [editSheetSegmentControl selectedSegment] == TextSegment || editImage == nil ) { [[editTextView string] writeToURL:fileURL atomically:YES -- cgit v1.2.3 From f03de6f42b1ea00875f9d57accbee2537604ee39 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 5 Apr 2015 20:01:17 +0200 Subject: Fix a threading issue when adding tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (Also the localizations should now work again on 10.10 🎉) --- Source/SPDatabaseViewController.m | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseViewController.m b/Source/SPDatabaseViewController.m index c43761d3..ea2186cc 100644 --- a/Source/SPDatabaseViewController.m +++ b/Source/SPDatabaseViewController.m @@ -116,16 +116,17 @@ #pragma mark - #pragma mark Tab view control and delegate methods +//WARNING: Might be called from code in background threads - (IBAction)viewStructure:(id)sender { // Cancel the selection if currently editing a view and unable to save if (![self couldCommitCurrentViewActions]) { - [mainToolbar setSelectedItemIdentifier:*SPViewModeToMainToolbarMap[[prefs integerForKey:SPLastViewMode]]]; + [[mainToolbar onMainThread] setSelectedItemIdentifier:*SPViewModeToMainToolbarMap[[prefs integerForKey:SPLastViewMode]]]; return; } - [tableTabView selectTabViewItemAtIndex:0]; - [mainToolbar setSelectedItemIdentifier:SPMainToolbarTableStructure]; + [[tableTabView onMainThread] selectTabViewItemAtIndex:0]; + [[mainToolbar onMainThread] setSelectedItemIdentifier:SPMainToolbarTableStructure]; [spHistoryControllerInstance updateHistoryEntries]; [prefs setInteger:SPStructureViewMode forKey:SPLastViewMode]; -- cgit v1.2.3 From 8631b5a61843aa52662946093e8391ead3de5689 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 6 Apr 2015 01:10:51 +0200 Subject: Remove DMLocalizedNib runtime localization No longer needed, see #1998. I'm feeling a bit sentimental now. --- Source/DMLocalizedNib.m | 162 ----------------------- Source/DMLocalizedNibBundle.m | 295 ------------------------------------------ 2 files changed, 457 deletions(-) delete mode 100644 Source/DMLocalizedNib.m delete mode 100644 Source/DMLocalizedNibBundle.m (limited to 'Source') diff --git a/Source/DMLocalizedNib.m b/Source/DMLocalizedNib.m deleted file mode 100644 index 4a03247a..00000000 --- a/Source/DMLocalizedNib.m +++ /dev/null @@ -1,162 +0,0 @@ -// -// DMLocalizedNib.h -// sequel-pro -// -// Created by Rowan Beentje on July 4, 2010. -// Copyright (c) 2010 Rowan Beentje. 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 - -#import -#import - -@interface NSNib (DMLocalizedNib) -- (id)deliciousInitWithNibNamed:(NSString *)nibName bundle:(NSBundle *)bundle; -- (id)deliciousInitWithContentsOfURL:(NSURL *)nibFileURL; -- (BOOL)deliciousInstantiateNibWithOwner:(id)owner topLevelObjects:(NSArray **)topLevelObjects; -- (void)setDeliciousNibName:(NSString *)nibName; -- (NSString *)deliciousNibName; -- (void)deliciousDealloc; -@end - -// Private methods from DMLocalizedNib used here -@interface NSBundle () -+ (void)_localizeStringsInObject:(id)object table:(NSString *)table; -@end - -static NSMutableDictionary *deliciousNibNames = nil; - -@implementation NSNib (DMLocalizedNib) - -#pragma mark NSObject - -/** - * On NSNib class load, swizzle in our overrides of the basic methods. - */ -+ (void)load; -{ - NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init]; - if (self == [NSNib class]) { - method_exchangeImplementations(class_getInstanceMethod(self, @selector(initWithNibNamed:bundle:)), class_getInstanceMethod(self, @selector(deliciousInitWithNibNamed:bundle:))); - method_exchangeImplementations(class_getInstanceMethod(self, @selector(initWithContentsOfURL:)), class_getInstanceMethod(self, @selector(deliciousInitWithContentsOfURL:))); - method_exchangeImplementations(class_getInstanceMethod(self, @selector(instantiateNibWithOwner:topLevelObjects:)), class_getInstanceMethod(self, @selector(deliciousInstantiateNibWithOwner:topLevelObjects:))); - method_exchangeImplementations(class_getInstanceMethod(self, @selector(dealloc)), class_getInstanceMethod(self, @selector(deliciousDealloc))); - } - [autoreleasePool release]; -} - - -#pragma mark API - -/** - * An init method swizzled with the original method, storing the base - * name passed into the init method for later reuse. - */ -- (id)deliciousInitWithNibNamed:(NSString *)nibName bundle:(NSBundle *)bundle -{ - - // Instantiate the nib using the original (swizzled) call - id nib = [self deliciousInitWithNibNamed:nibName bundle:bundle]; - if (nib) { - [self setDeliciousNibName:nibName]; - } - - return nib; -} - -/** - * An init method swizzled with the original method, extracting and - * storing the base name of the nib for later reuse. - */ -- (id)deliciousInitWithContentsOfURL:(NSURL *)nibFileURL -{ - - // Instantiate the nib using the original (swizzled) call - id nib = [self deliciousInitWithContentsOfURL:nibFileURL]; - if (nib) { - - // Extract the filename from the URL - NSArray *urlParts = [[nibFileURL path] componentsSeparatedByString:@"/"]; - NSString *nibName = [urlParts lastObject]; - [self setDeliciousNibName:nibName]; - } - - return nib; -} - -/** - * An instatiation method swizzled with the original method. Instantiates - * as before, and then if it can find a .strings file in a preferred language - * to localize the instantiated objects with, does so. - */ -- (BOOL)deliciousInstantiateNibWithOwner:(id)owner topLevelObjects:(NSArray **)topLevelObjects -{ - if ([self deliciousInstantiateNibWithOwner:owner topLevelObjects:topLevelObjects]) { - - // Look for a localised strings table file based on the original nib name, - // translating only if one was found and it wasn't English - NSString *localizedStringsTablePath = [[NSBundle mainBundle] pathForResource:[self deliciousNibName] ofType:@"strings"]; - if (localizedStringsTablePath && ![[[localizedStringsTablePath stringByDeletingLastPathComponent] lastPathComponent] isEqualToString:@"English.lproj"]) { - [NSBundle _localizeStringsInObject:*topLevelObjects table:[self deliciousNibName]]; - } - - return YES; - } - - return NO; -} - -/** - * Store the nib name that was used when setting up the nib, which will - * also be used to look up the .strings file name - */ -- (void)setDeliciousNibName:(NSString *)nibName -{ - if (!deliciousNibNames) { - deliciousNibNames = [[NSMutableDictionary alloc] init]; - } - [deliciousNibNames setObject:nibName forKey:[NSValue valueWithPointer:self]]; -} - -/** - * Retrieve the nib name to look up the matching .strings file name - */ -- (NSString *)deliciousNibName -{ - return [deliciousNibNames objectForKey:[NSValue valueWithPointer:self]]; -} - -/** - * Swizzled deallocate to release custom stores. - */ -- (void)deliciousDealloc -{ - if (deliciousNibNames) { - [deliciousNibNames removeObjectForKey:[NSValue valueWithPointer:self]]; - if (![deliciousNibNames count]) SPClear(deliciousNibNames); - } - [self deliciousDealloc]; -} - -@end diff --git a/Source/DMLocalizedNibBundle.m b/Source/DMLocalizedNibBundle.m deleted file mode 100644 index 5dc94f9f..00000000 --- a/Source/DMLocalizedNibBundle.m +++ /dev/null @@ -1,295 +0,0 @@ -// DMLocalizedNibBundle.m -// -// Created by William Jon Shipley on 2/13/05. -// Copyright (c) 2005-2009 Golden % Braeburn, LLC. All rights reserved except as below: -// -// This code is provided as-is, with no warranties or anything. You may use it in your projects as you wish, -// but you must leave this comment block (credits and copyright) intact. That's the only restriction -// -- Golden % Braeburn otherwise grants you a fully-paid, worldwide, transferrable license to use this -// code as you see fit, including but not limited to making derivative works. - -#import -#import -#import - -@interface NSBundle (DMLocalizedNibBundle) -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_8 -- (BOOL)deliciousLocalizingLoadNibNamed:(NSString *)fileName owner:(id)owner topLevelObjects:(NSArray **)topLevelObjects; -#endif -+ (BOOL)deliciousLocalizingLoadNibFile:(NSString *)fileName externalNameTable:(NSDictionary *)context withZone:(NSZone *)zone; -@end - -@interface NSBundle (DMLocalizedNibBundle_Private_API) -+ (void)_localizeStringsInObject:(id)object table:(NSString *)table; -+ (NSString *)_localizedStringForString:(NSString *)string table:(NSString *)table; -// localize particular attributes in objects -+ (void)_localizeTitleOfObject:(id)object table:(NSString *)table; -+ (void)_localizeAlternateTitleOfObject:(id)object table:(NSString *)table; -+ (void)_localizeStringValueOfObject:(id)object table:(NSString *)table; -+ (void)_localizePlaceholderStringOfObject:(id)object table:(NSString *)table; -+ (void)_localizeToolTipOfObject:(id)object table:(NSString *)table; -+ (void)_localizeLabelOfObject:(id)object table:(NSString *)table; -@end - -static NSMutableArray *deliciousBindingKeys = nil; - -@implementation NSBundle (DMLocalizedNibBundle) - -#pragma mark NSObject - -+ (void)load -{ - NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init]; - if (self == [NSBundle class]) { - Method oldM,newM; -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_8 - oldM = class_getInstanceMethod(self, @selector(loadNibNamed:owner:topLevelObjects:)); - newM = class_getInstanceMethod(self, @selector(deliciousLocalizingLoadNibNamed:owner:topLevelObjects:)); - method_exchangeImplementations(oldM, newM); -#endif - oldM = class_getClassMethod(self, @selector(loadNibFile:externalNameTable:withZone:)); - newM = class_getClassMethod(self, @selector(deliciousLocalizingLoadNibFile:externalNameTable:withZone:)); - method_exchangeImplementations(oldM, newM); - deliciousBindingKeys = [[NSMutableArray alloc] initWithObjects: - NSMultipleValuesPlaceholderBindingOption, - NSNoSelectionPlaceholderBindingOption, - NSNotApplicablePlaceholderBindingOption, - NSNullPlaceholderBindingOption, - nil]; - } - [autoreleasePool release]; -} - -#pragma mark API - -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_8 -- (BOOL)deliciousLocalizingLoadNibNamed:(NSString *)fileName owner:(id)owner topLevelObjects:(NSArray **)topLevelObjects -{ - fileName = [self pathForResource:fileName ofType:@"nib"]; - NSString *localizedStringsTableName = [[fileName lastPathComponent] stringByDeletingPathExtension]; - NSString *localizedStringsTablePath = [[NSBundle mainBundle] pathForResource:localizedStringsTableName ofType:@"strings"]; - if (localizedStringsTablePath && ![[[localizedStringsTablePath stringByDeletingLastPathComponent] lastPathComponent] isEqualToString:@"English.lproj"]) { - - NSNib *nib = [[NSNib alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName]]; - BOOL success = [nib instantiateWithOwner:owner topLevelObjects:topLevelObjects]; - NSMutableArray *topLevelObjectsArray = [NSMutableArray arrayWithArray:*topLevelObjects]; - [[self class] _localizeStringsInObject:topLevelObjectsArray table:localizedStringsTableName]; - - [nib release]; - return success; - - } else { - return [self deliciousLocalizingLoadNibNamed:localizedStringsTableName owner:owner topLevelObjects:topLevelObjects]; - } -} -#endif - -+ (BOOL)deliciousLocalizingLoadNibFile:(NSString *)fileName externalNameTable:(NSDictionary *)context withZone:(NSZone *)zone -{ - NSString *localizedStringsTableName = [[fileName lastPathComponent] stringByDeletingPathExtension]; - NSString *localizedStringsTablePath = [[NSBundle mainBundle] pathForResource:localizedStringsTableName ofType:@"strings"]; - if (localizedStringsTablePath && ![[[localizedStringsTablePath stringByDeletingLastPathComponent] lastPathComponent] isEqualToString:@"English.lproj"]) { - - NSNib *nib = [[NSNib alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName]]; - NSMutableArray *topLevelObjectsArray = [context objectForKey:NSNibTopLevelObjects]; - if (!topLevelObjectsArray) { - topLevelObjectsArray = [NSMutableArray array]; - context = [NSMutableDictionary dictionaryWithDictionary:context]; - [(NSMutableDictionary *)context setObject:topLevelObjectsArray forKey:NSNibTopLevelObjects]; - } - BOOL success = [nib instantiateNibWithExternalNameTable:context]; - [self _localizeStringsInObject:topLevelObjectsArray table:localizedStringsTableName]; - - [nib release]; - return success; - - } else { - return [self deliciousLocalizingLoadNibFile:fileName externalNameTable:context withZone:zone]; - } -} - -@end - -#pragma mark Private API - -@implementation NSBundle (DMLocalizedNibBundle_Private_API) - -+ (void)_localizeStringsInObject:(id)object table:(NSString *)table -{ - if ([object isKindOfClass:[NSArray class]]) { - NSArray *array = object; - - for (id nibItem in array) - [self _localizeStringsInObject:nibItem table:table]; - - } else if ([object isKindOfClass:[NSCell class]]) { - NSCell *cell = object; - - if ([cell isKindOfClass:[NSActionCell class]]) { - NSActionCell *actionCell = (NSActionCell *)cell; - - if ([actionCell isKindOfClass:[NSButtonCell class]]) { - NSButtonCell *buttonCell = (NSButtonCell *)actionCell; - if ([buttonCell imagePosition] != NSImageOnly) { - [self _localizeTitleOfObject:buttonCell table:table]; - [self _localizeStringValueOfObject:buttonCell table:table]; - [self _localizeAlternateTitleOfObject:buttonCell table:table]; - } - - } else if ([actionCell isKindOfClass:[NSTextFieldCell class]]) { - NSTextFieldCell *textFieldCell = (NSTextFieldCell *)actionCell; - // Following line is redundant with other code, localizes twice. - // [self _localizeTitleOfObject:textFieldCell table:table]; - [self _localizeStringValueOfObject:textFieldCell table:table]; - [self _localizePlaceholderStringOfObject:textFieldCell table:table]; - - } else if ([actionCell type] == NSTextCellType) { - [self _localizeTitleOfObject:actionCell table:table]; - [self _localizeStringValueOfObject:actionCell table:table]; - } - } - - } else if ([object isKindOfClass:[NSMenu class]]) { - NSMenu *menu = object; - [self _localizeTitleOfObject:menu table:table]; - - [self _localizeStringsInObject:[menu itemArray] table:table]; - - } else if ([object isKindOfClass:[NSMenuItem class]]) { - NSMenuItem *menuItem = object; - [self _localizeTitleOfObject:menuItem table:table]; - [self _localizeToolTipOfObject:menuItem table:table]; - - [self _localizeStringsInObject:[menuItem submenu] table:table]; - - } else if ([object isKindOfClass:[NSView class]]) { - NSView *view = object; - [self _localizeToolTipOfObject:view table:table]; - - if ([view isKindOfClass:[NSBox class]]) { - NSBox *box = (NSBox *)view; - [self _localizeTitleOfObject:box table:table]; - - } else if ([view isKindOfClass:[NSControl class]]) { - NSControl *control = (NSControl *)view; - - if ([view isKindOfClass:[NSButton class]]) { - NSButton *button = (NSButton *)control; - - if ([button isKindOfClass:[NSPopUpButton class]]) { - NSPopUpButton *popUpButton = (NSPopUpButton *)button; - NSMenu *menu = [popUpButton menu]; - - [self _localizeStringsInObject:[menu itemArray] table:table]; - } else - [self _localizeStringsInObject:[button cell] table:table]; - - - } else if ([view isKindOfClass:[NSMatrix class]]) { - NSMatrix *matrix = (NSMatrix *)control; - - NSArray *cells = [matrix cells]; - [self _localizeStringsInObject:cells table:table]; - - for (NSCell *cell in cells) { - - NSString *localizedCellToolTip = [self _localizedStringForString:[matrix toolTipForCell:cell] table:table]; - if (localizedCellToolTip) - [matrix setToolTip:localizedCellToolTip forCell:cell]; - } - - } else if ([view isKindOfClass:[NSSegmentedControl class]]) { - NSSegmentedControl *segmentedControl = (NSSegmentedControl *)control; - - NSInteger segmentIndex, segmentCount = [segmentedControl segmentCount]; - for (segmentIndex = 0; segmentIndex < segmentCount; segmentIndex++) { - NSString *localizedSegmentLabel = [self _localizedStringForString:[segmentedControl labelForSegment:segmentIndex] table:table]; - if (localizedSegmentLabel) - [segmentedControl setLabel:localizedSegmentLabel forSegment:segmentIndex]; - NSString *localizedSegmentTooltip = [self _localizedStringForString:[[segmentedControl cell] toolTipForSegment:segmentIndex] table:table]; - if (localizedSegmentTooltip) - [[segmentedControl cell] setToolTip:localizedSegmentTooltip forSegment:segmentIndex]; - - [self _localizeStringsInObject:[segmentedControl menuForSegment:segmentIndex] table:table]; - } - - } else if ([view isKindOfClass:[NSTableView class]]) { - for (NSTableColumn *column in [(NSTableView*)view tableColumns]) { - [self _localizeStringValueOfObject:[column headerCell] table:table]; - NSString *localizedHeaderTip = [self _localizedStringForString:[column headerToolTip] table:table]; - if (localizedHeaderTip) [column setHeaderToolTip:localizedHeaderTip]; - } - - } else if ([view isKindOfClass:[NSTextField class]]) { - NSDictionary *vb; - if ((vb = [view infoForBinding:@"value"])) { - NSMutableDictionary *lvb = [NSMutableDictionary dictionaryWithDictionary:[vb objectForKey:NSOptionsKey]]; - for (NSString *bindingKey in deliciousBindingKeys) { - if ([lvb objectForKey:bindingKey] == [NSNull null]) continue; - NSString *localizedBindingString = [self _localizedStringForString:[lvb objectForKey:bindingKey] table:table]; - if (localizedBindingString) - [lvb setObject:localizedBindingString forKey:bindingKey]; - } - [view bind:@"value" toObject:[vb objectForKey:NSObservedObjectKey] withKeyPath:[vb objectForKey:NSObservedKeyPathKey] options:lvb]; - } - [self _localizeStringsInObject:[control cell] table:table]; - - } else - [self _localizeStringsInObject:[control cell] table:table]; - - } else if ([view isKindOfClass:[NSTabView class]]) { - NSTabView *tabView = (NSTabView *)view; - for (NSTabViewItem *tabViewItem in [tabView tabViewItems]) { - [self _localizeLabelOfObject:tabViewItem table:table]; - if ([tabViewItem respondsToSelector:@selector(toolTip)]) // 10.6+ - [self _localizeToolTipOfObject:tabViewItem table:table]; - [self _localizeStringsInObject:[tabViewItem view] table:table]; - } - - } - - [self _localizeStringsInObject:[view subviews] table:table]; - - } else if ([object isKindOfClass:[NSWindow class]]) { - NSWindow *window = object; - [self _localizeTitleOfObject:window table:table]; - - [self _localizeStringsInObject:[window contentView] table:table]; - - } -} - -+ (NSString *)_localizedStringForString:(NSString *)string table:(NSString *)table -{ - if (![string length]) - return nil; - - static NSString *defaultValue = @"I AM THE DEFAULT VALUE"; - NSString *localizedString = [[NSBundle mainBundle] localizedStringForKey:string value:defaultValue table:table]; - if (localizedString != defaultValue) { - return localizedString; - } else { -#ifdef BETA_BUILD - NSLog(@" not going to localize string %@", string); -#endif - return nil; - } -} - - -#define DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(blahName, capitalizedBlahName) \ -+ (void)_localize ##capitalizedBlahName ##OfObject:(id)object table:(NSString *)table; \ -{ \ - NSString *localizedBlah = [self _localizedStringForString:[object blahName] table:table]; \ - if (localizedBlah) \ - [object set ##capitalizedBlahName:localizedBlah]; \ -} - -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(title, Title) -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(alternateTitle, AlternateTitle) -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(stringValue, StringValue) -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(placeholderString, PlaceholderString) -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(toolTip, ToolTip) -DM_DEFINE_LOCALIZE_BLAH_OF_OBJECT(label, Label) - -@end -- cgit v1.2.3 From 8eadd956e7b28695a3204ed2ba695a771a2b8da4 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 6 Apr 2015 18:23:11 +0200 Subject: Add support for FULLTEXT indexes in InnoDB tables Fixes #1917 --- Source/SPIndexesController.h | 3 ++- Source/SPIndexesController.m | 16 +++++++++------- Source/SPServerSupport.h | 6 ++++++ Source/SPServerSupport.m | 3 +++ 4 files changed, 20 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPIndexesController.h b/Source/SPIndexesController.h index 6ee59226..82bc0a03 100644 --- a/Source/SPIndexesController.h +++ b/Source/SPIndexesController.h @@ -74,7 +74,8 @@ #endif BOOL _mainNibLoaded; - BOOL isMyISAMTale; + BOOL isMyISAMTable; + BOOL isInnoDBTable; NSString *table; NSMutableArray *fields, *indexes, *indexedFields; diff --git a/Source/SPIndexesController.m b/Source/SPIndexesController.m index 5cca12f9..93466c27 100644 --- a/Source/SPIndexesController.m +++ b/Source/SPIndexesController.m @@ -166,7 +166,8 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; // Check whether a save of the current field row is required. if (![tableStructure saveRowOnDeselect]) return; - isMyISAMTale = [[[tableData statusValues] objectForKey:@"Engine"] isEqualToString:@"MyISAM"]; + isMyISAMTable = [[[tableData statusValues] objectForKey:@"Engine"] isEqualToString:@"MyISAM"]; + isInnoDBTable = [[[tableData statusValues] objectForKey:@"Engine"] isEqualToString:@"InnoDB"]; // Reset visibility of the primary key item [[[indexTypePopUpButton menu] itemWithTag:SPPrimaryKeyMenuTag] setHidden:NO]; @@ -236,7 +237,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; #ifndef SP_CODA // MyISAM and InnoDB tables only support BTREE storage types so disable the storage type popup button // as it's the default anyway. - [indexStorageTypePopUpButton setEnabled:(!(isMyISAMTale || [[[tableData statusValues] objectForKey:@"Engine"] isEqualToString:@"InnoDB"]))]; + [indexStorageTypePopUpButton setEnabled:(!(isMyISAMTable || isInnoDBTable))]; // The ability to specify an index's key block size was added in MySQL 5.1.10 so disable the textfield // if it's not supported. @@ -328,10 +329,8 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; } #ifndef SP_CODA - NSString *engine = [[tableData statusValues] objectForKey:@"Engine"]; - // Specifiying an index storage type (i.e. HASH or BTREE) is not permitted with SPATIAL indexes - [indexStorageTypePopUpButton setEnabled:(indexType != SPSpatialMenuTag) && !(isMyISAMTale || [engine isEqualToString:@"InnoDB"])]; + [indexStorageTypePopUpButton setEnabled:(indexType != SPSpatialMenuTag) && !(isMyISAMTable || isInnoDBTable)]; #endif } @@ -768,8 +767,8 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; [indexTypePopUpButton removeItemAtIndex:[indexTypePopUpButton indexOfItemWithTag:SPFullTextMenuTag]]; } - // FULLTEXT and SPATIAL index types are only available using the MyISAM engine - if (isMyISAMTale) { + // SPATIAL index types are only available using the MyISAM engine + if (isMyISAMTable) { if ([[dbDocument serverSupport] supportsSpatialExtensions]) { NSMenuItem *spatialMenuItem = [[[NSMenuItem alloc] init] autorelease]; @@ -778,7 +777,10 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize"; [[indexTypePopUpButton menu] addItem:spatialMenuItem]; } + } + // FULLTEXT only works with MyISAM and (InnoDB since 5.6.4) + if(isMyISAMTable || (isInnoDBTable && [[dbDocument serverSupport] supportsFulltextOnInnoDB])) { NSMenuItem *fullTextMenuItem = [[[NSMenuItem alloc] init] autorelease]; [fullTextMenuItem setTitle:NSLocalizedString(@"FULLTEXT", @"full text index menu item title")]; diff --git a/Source/SPServerSupport.h b/Source/SPServerSupport.h index e8b8a613..8052ed90 100644 --- a/Source/SPServerSupport.h +++ b/Source/SPServerSupport.h @@ -85,6 +85,7 @@ // Indexes BOOL supportsIndexKeyBlockSize; + BOOL supportsFulltextOnInnoDB; // Events BOOL supportsEvents; @@ -253,6 +254,11 @@ */ @property (readonly) BOOL supportsFractionalSeconds; +/** + * @property supportsFulltextOnInnoDB Indicates whether the server supports FULLTEXT indexes with the InnoDb engine. + */ +@property (readonly) BOOL supportsFulltextOnInnoDB; + - (id)initWithMajorVersion:(NSInteger)majorVersion minor:(NSInteger)minorVersion release:(NSInteger)releaseVersion; - (void)evaluate; diff --git a/Source/SPServerSupport.m b/Source/SPServerSupport.m index bf74a61e..5537e476 100644 --- a/Source/SPServerSupport.m +++ b/Source/SPServerSupport.m @@ -76,6 +76,7 @@ @synthesize serverMajorVersion; @synthesize serverMinorVersion; @synthesize serverReleaseVersion; +@synthesize supportsFulltextOnInnoDB; #pragma mark - #pragma mark Initialisation @@ -198,6 +199,7 @@ // Fractional second support wasn't added until MySQL 5.6.4 supportsFractionalSeconds = [self isEqualToOrGreaterThanMajorVersion:5 minor:6 release:4]; + supportsFulltextOnInnoDB = supportsFractionalSeconds; //introduced in 5.6.4 too } /** @@ -288,6 +290,7 @@ supportsIndexKeyBlockSize = NO; supportsQuotingEngineTypeInCreateSyntax = NO; supportsFractionalSeconds = NO; + supportsFulltextOnInnoDB = NO; } /** -- cgit v1.2.3 From 7a60951df49c129a7e24ec302d976d32dbe9af79 Mon Sep 17 00:00:00 2001 From: George Gardiner Date: Mon, 13 Apr 2015 09:11:51 +0100 Subject: Fixed a typo --- Source/SPSQLExporter.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPSQLExporter.m b/Source/SPSQLExporter.m index f9dde93c..079ea8b9 100644 --- a/Source/SPSQLExporter.m +++ b/Source/SPSQLExporter.m @@ -729,7 +729,7 @@ // A NULL result indicates a permission problem if ([createProcedure isNSNull]) { - NSString *errorString = [NSString stringWithFormat:NSLocalizedString(@"Could not export the %@ '%@' because of a permisions error.\n", @"Procedure/function export permission error"), procedureType, procedureName]; + NSString *errorString = [NSString stringWithFormat:NSLocalizedString(@"Could not export the %@ '%@' because of a permissions error.\n", @"Procedure/function export permission error"), procedureType, procedureName]; [errors appendString:errorString]; if ([self sqlOutputIncludeErrors]) { [[self exportOutputFile] writeData:[[NSString stringWithFormat:@"# Error: %@\n", errorString] dataUsingEncoding:NSUTF8StringEncoding]]; -- cgit v1.2.3 From 9537631e044312f6639c14b0dc5ba158ca3d3ff8 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 13 Apr 2015 16:27:15 +0200 Subject: Fix a previous commit not catching all cases. --- Source/SPTableContentDelegate.m | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPTableContentDelegate.m b/Source/SPTableContentDelegate.m index 19bbc4b3..4d7bbb04 100644 --- a/Source/SPTableContentDelegate.m +++ b/Source/SPTableContentDelegate.m @@ -263,7 +263,14 @@ // Retrieve the column definition NSDictionary *columnDefinition = [cqColumnDefinition objectAtIndex:[[tableColumn identifier] integerValue]]; - + + // TODO: Fix editing of "Display as Hex" columns and remove this (also see above) + if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { + NSBeep(); + [SPTooltip showWithObject:NSLocalizedString(@"Disable \"Display Binary Data as Hex\" in the View menu to edit this field.",@"Temporary : Tooltip shown when trying to edit a binary field in table content view while it is displayed using HEX conversion")]; + return NO; + } + // Open the editing sheet if required if ([tableContentView shouldUseFieldEditorForRow:rowIndex column:[[tableColumn identifier] integerValue] checkWithLock:NULL]) { @@ -347,13 +354,6 @@ return NO; } - // TODO: Fix editing of "Display as Hex" columns and remove this (also see above) - if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"binary"] && [prefs boolForKey:SPDisplayBinaryDataAsHex]) { - NSBeep(); - [SPTooltip showWithObject:NSLocalizedString(@"Disable \"Display Binary Data as Hex\" in the View menu to edit this field.",@"Temporary : Tooltip shown when trying to edit a binary field in table content view while it is displayed using HEX conversion")]; - return NO; - } - return YES; } -- cgit v1.2.3 From 9a5cb83cdf913e616a0f96f4f720dc3187d650ce Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 13 Apr 2015 17:04:21 +0200 Subject: Dim the database name in relations view if foreign database == local database. --- Source/SPTableRelations.m | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index 2374ea81..5734a96d 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -376,7 +376,13 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex { - return [[relationData objectAtIndex:rowIndex] objectForKey:[tableColumn identifier]]; + id data = [[relationData objectAtIndex:rowIndex] objectForKey:[tableColumn identifier]]; + //dim the database name if it matches the current database + if([[tableColumn identifier] isEqualToString:SPRelationFKDatabaseKey] && [[tableDocumentInstance database] isEqual:data]) { + NSDictionary *textAttributes = @{NSForegroundColorAttributeName: [NSColor lightGrayColor]}; + data = [[[NSAttributedString alloc] initWithString:(NSString *)data attributes:textAttributes] autorelease]; + } + return data; } #pragma mark - -- cgit v1.2.3 From 028f1ff9ac1e22db9abec6ea3838079a08aa471e Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 16 Apr 2015 00:24:53 +0200 Subject: Restore detailed error messages for FK errors in MySQL 5.5+ --- Source/SPServerSupport.h | 16 ++++++++++++++++ Source/SPServerSupport.m | 24 ++++++++++++++++++++++++ Source/SPTableRelations.m | 24 ++++++++++++++---------- 3 files changed, 54 insertions(+), 10 deletions(-) (limited to 'Source') diff --git a/Source/SPServerSupport.h b/Source/SPServerSupport.h index 8052ed90..e4551643 100644 --- a/Source/SPServerSupport.h +++ b/Source/SPServerSupport.h @@ -28,6 +28,11 @@ // // More info at +typedef struct { + NSString *queryString; + NSUInteger columnIndex; +} SPInnoDBStatusQueryFormat; + /** * @class SPServerSupport SPServerSupport.h * @@ -79,6 +84,7 @@ BOOL supportsArchiveStorageEngine; BOOL supportsCSVStorageEngine; BOOL supportsQuotingEngineTypeInCreateSyntax; + BOOL supportsShowEngine; // Triggers BOOL supportsTriggers; @@ -259,9 +265,19 @@ */ @property (readonly) BOOL supportsFulltextOnInnoDB; +/** + * @property supportsShowEngine Indicates whether the server supports the "SHOW ENGINE x {LOGS|STATUS}" query. + */ +@property (readonly) BOOL supportsShowEngine; + - (id)initWithMajorVersion:(NSInteger)majorVersion minor:(NSInteger)minorVersion release:(NSInteger)releaseVersion; - (void)evaluate; - (BOOL)isEqualToOrGreaterThanMajorVersion:(NSInteger)majorVersion minor:(NSInteger)minorVersion release:(NSInteger)releaseVersion; +/** + * @return The correct query to get the InnoDB engine status. queryString is nil for unsupported versions. + * The columnIndex tells the index of the column (starting with 0) in which the status text is returned. + */ +- (SPInnoDBStatusQueryFormat)innoDBStatusQuery; @end diff --git a/Source/SPServerSupport.m b/Source/SPServerSupport.m index 5537e476..489acc04 100644 --- a/Source/SPServerSupport.m +++ b/Source/SPServerSupport.m @@ -77,6 +77,7 @@ @synthesize serverMinorVersion; @synthesize serverReleaseVersion; @synthesize supportsFulltextOnInnoDB; +@synthesize supportsShowEngine; #pragma mark - #pragma mark Initialisation @@ -200,6 +201,28 @@ // Fractional second support wasn't added until MySQL 5.6.4 supportsFractionalSeconds = [self isEqualToOrGreaterThanMajorVersion:5 minor:6 release:4]; supportsFulltextOnInnoDB = supportsFractionalSeconds; //introduced in 5.6.4 too + + // The SHOW ENGINE query wasn't added until MySQL 4.1.2 + supportsShowEngine = [self isEqualToOrGreaterThanMajorVersion:4 minor:1 release:2]; +} + +- (SPInnoDBStatusQueryFormat)innoDBStatusQuery +{ + SPInnoDBStatusQueryFormat tuple = {nil,0}; + + //if we have SHOW ENGINE go with that + if(supportsShowEngine) { + tuple.queryString = @"SHOW ENGINE INNODB STATUS"; + tuple.columnIndex = 2; + } + //up to mysql 5.5 we could also use the old SHOW INNODB STATUS + if([self isEqualToOrGreaterThanMajorVersion:3 minor:23 release:52] && + ![self isEqualToOrGreaterThanMajorVersion:5 minor:5 release:0]) { + tuple.queryString = @"SHOW INNODB STATUS"; + tuple.columnIndex = 0; + } + + return tuple; } /** @@ -291,6 +314,7 @@ supportsQuotingEngineTypeInCreateSyntax = NO; supportsFractionalSeconds = NO; supportsFulltextOnInnoDB = NO; + supportsShowEngine = NO; } /** diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index 5734a96d..43156eae 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -35,6 +35,7 @@ #import "SPTableView.h" #import "SPAlertSheets.h" #import "RegexKitLite.h" +#import "SPServerSupport.h" #import @@ -192,16 +193,19 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; // most common are 121 (name probably in use) and 150 (types don't exactly match). // Retrieve the InnoDB status and extract the most recent error for more helpful text. if ([connection lastErrorID] == 1005) { - NSString *statusText = [connection getFirstFieldFromQuery:@"SHOW INNODB STATUS"]; - NSString *detailErrorString = [statusText stringByMatching:@"latest foreign key error\\s+-----*\\s+[0-9: ]*(.*?)\\s+-----" options:(RKLCaseless | RKLDotAll) inRange:NSMakeRange(0, [statusText length]) capture:1L error:NULL]; - if (detailErrorString) { - errorText = [NSString stringWithFormat:NSLocalizedString(@"%@\n\nDetail: %@", @"Add relation error detail intro"), errorText, [detailErrorString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]]; - } - - // Detect name duplication if appropriate - if ([errorText isMatchedByRegex:@"errno: 121"] && [errorText isMatchedByRegex:@"already exists"]) { - [takenConstraintNames addObject:[[constraintName stringValue] lowercaseString]]; - [self controlTextDidChange:[NSNotification notificationWithName:@"dummy" object:constraintName]]; + SPInnoDBStatusQueryFormat status = [[tableDocumentInstance serverSupport] innoDBStatusQuery]; + if(status.queryString) { + NSString *statusText = [[[connection queryString:status.queryString] getRowAsArray] objectAtIndex:status.columnIndex]; + NSString *detailErrorString = [statusText stringByMatching:@"latest foreign key error\\s+-----*\\s+[0-9: ]*(.*?)\\s+-----" options:(RKLCaseless | RKLDotAll) inRange:NSMakeRange(0, [statusText length]) capture:1L error:NULL]; + if (detailErrorString) { + errorText = [NSString stringWithFormat:NSLocalizedString(@"%@\n\nDetail: %@", @"Add relation error detail intro"), errorText, [detailErrorString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]]; + } + + // Detect name duplication if appropriate + if ([errorText isMatchedByRegex:@"errno: 121"] && [errorText isMatchedByRegex:@"already exists"]) { + [takenConstraintNames addObject:[[constraintName stringValue] lowercaseString]]; + [self controlTextDidChange:[NSNotification notificationWithName:@"dummy" object:constraintName]]; + } } } -- cgit v1.2.3 From 734d3a90187734b7d7d4678229644573ccdbf7bb Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 16 Apr 2015 02:45:16 +0200 Subject: Change the visual appearance of the FK creation error dialog a bit --- Source/SPTableRelations.h | 5 ++++- Source/SPTableRelations.m | 27 ++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) (limited to 'Source') diff --git a/Source/SPTableRelations.h b/Source/SPTableRelations.h index 4bb998c9..1ab7f1b7 100644 --- a/Source/SPTableRelations.h +++ b/Source/SPTableRelations.h @@ -58,7 +58,10 @@ IBOutlet NSButton *confirmAddRelationButton; IBOutlet NSProgressIndicator *dataProgressIndicator; IBOutlet NSTextField *progressStatusTextField; - + + IBOutlet NSView *detailErrorView; + IBOutlet NSTextView *detailErrorText; + SPMySQLConnection *connection; NSUserDefaults *prefs; diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index 43156eae..0caf78b6 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -53,7 +53,6 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; - (void)_refreshRelationDataForcingCacheRefresh:(BOOL)clearAllCaches; - (void)_updateAvailableTableColumns; -- (void)_reopenRelationSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; @end @@ -188,6 +187,12 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; // Retrieve the last connection error message. NSString *errorText = [connection lastErrorMessage]; + + NSAlert *alert = [[[NSAlert alloc] init] autorelease]; + + [alert setMessageText:NSLocalizedString(@"Error creating relation", @"error creating relation message")]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", @"OK button")]; + [alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"The specified relation could not be created.\n\nMySQL said: %@", @"error creating relation informative message"), errorText]]; // An error ID of 1005 indicates a foreign key error. These are thrown for many reasons, but the two // most common are 121 (name probably in use) and 150 (types don't exactly match). @@ -198,7 +203,8 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; NSString *statusText = [[[connection queryString:status.queryString] getRowAsArray] objectAtIndex:status.columnIndex]; NSString *detailErrorString = [statusText stringByMatching:@"latest foreign key error\\s+-----*\\s+[0-9: ]*(.*?)\\s+-----" options:(RKLCaseless | RKLDotAll) inRange:NSMakeRange(0, [statusText length]) capture:1L error:NULL]; if (detailErrorString) { - errorText = [NSString stringWithFormat:NSLocalizedString(@"%@\n\nDetail: %@", @"Add relation error detail intro"), errorText, [detailErrorString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]]; + [alert setAccessoryView:detailErrorView]; + [detailErrorText setString:[detailErrorString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]]; } // Detect name duplication if appropriate @@ -209,11 +215,10 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; } } - SPBeginAlertSheet(NSLocalizedString(@"Error creating relation", @"error creating relation message"), - NSLocalizedString(@"OK", @"OK button"), - nil, nil, [NSApp mainWindow], self, @selector(_reopenRelationSheet:returnCode:contextInfo:), nil, - [NSString stringWithFormat:NSLocalizedString(@"The specified relation was unable to be created.\n\nMySQL said: %@", @"error creating relation informative message"), errorText]); - } + [[alert onMainThread] beginSheetModalForWindow:[tableDocumentInstance parentWindow] completionHandler:^(NSModalResponse returnCode) { + [self performSelector:@selector(openRelationSheet:) withObject:self afterDelay:0.0]; + }]; + } else { [self _refreshRelationDataForcingCacheRefresh:YES]; } @@ -661,14 +666,6 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; [columnInfo release]; } -/** - * Reopen the add relation sheet, usually after an error message, with the previous content. - */ -- (void)_reopenRelationSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo -{ - [self performSelector:@selector(openRelationSheet:) withObject:self afterDelay:0.0]; -} - #pragma mark - - (void)dealloc -- cgit v1.2.3 From 55951d00cde44cfc654a2a6cb97e941eca2eb70f Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 16 Apr 2015 03:06:42 +0200 Subject: =?UTF-8?q?Silly=20me,=20tried=20to=20use=20a=20method=20that=20wa?= =?UTF-8?q?s=20newer=20than=2010.6=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Source/SPTableRelations.m | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'Source') diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m index 0caf78b6..134aa2fb 100644 --- a/Source/SPTableRelations.m +++ b/Source/SPTableRelations.m @@ -53,6 +53,7 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; - (void)_refreshRelationDataForcingCacheRefresh:(BOOL)clearAllCaches; - (void)_updateAvailableTableColumns; +- (void)addAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; @end @@ -215,15 +216,18 @@ static NSString *SPRelationOnDeleteKey = @"on_delete"; } } - [[alert onMainThread] beginSheetModalForWindow:[tableDocumentInstance parentWindow] completionHandler:^(NSModalResponse returnCode) { - [self performSelector:@selector(openRelationSheet:) withObject:self afterDelay:0.0]; - }]; + [[alert onMainThread] beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(addAlertDidEnd:returnCode:contextInfo:) contextInfo:NULL]; } else { [self _refreshRelationDataForcingCacheRefresh:YES]; } } +- (void)addAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo +{ + [self performSelector:@selector(openRelationSheet:) withObject:self afterDelay:0.0]; +} + /** * Updates the available columns when the user selects a table. */ -- cgit v1.2.3 From 75738e17389d9d66713fdde60cfd59774c934557 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 22 Apr 2015 22:30:57 +0200 Subject: Fixed two case of background thread interacting with UI aka "deleted uncommited CA transaction" --- Source/SPDatabaseDocument.m | 5 +++-- Source/SPHistoryController.m | 2 +- Source/SPTableContent.m | 6 +++++- 3 files changed, 9 insertions(+), 4 deletions(-) (limited to 'Source') diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m index 506e78f6..0b4abdb9 100644 --- a/Source/SPDatabaseDocument.m +++ b/Source/SPDatabaseDocument.m @@ -4577,8 +4577,9 @@ static NSString *SPAlterDatabaseAction = @"SPAlterDatabase"; [sessionState setObject:[NSNumber numberWithBool:[tableContentInstance sortColumnIsAscending]] forKey:@"contentSortColIsAsc"]; [sessionState setObject:[NSNumber numberWithInteger:[tableContentInstance pageNumber]] forKey:@"contentPageNumber"]; [sessionState setObject:NSStringFromRect([tableContentInstance viewport]) forKey:@"contentViewport"]; - if ([tableContentInstance filterSettings]) - [sessionState setObject:[tableContentInstance filterSettings] forKey:@"contentFilter"]; + NSDictionary *filterSettings = [tableContentInstance filterSettings]; + if (filterSettings) + [sessionState setObject:filterSettings forKey:@"contentFilter"]; NSDictionary *contentSelectedRows = [tableContentInstance selectionDetailsAllowingIndexSelection:YES]; if (contentSelectedRows) { diff --git a/Source/SPHistoryController.m b/Source/SPHistoryController.m index aa504bc2..87cc4eab 100644 --- a/Source/SPHistoryController.m +++ b/Source/SPHistoryController.m @@ -276,7 +276,7 @@ NSUInteger contentPageNumber = [tableContentInstance pageNumber]; NSDictionary *contentSelectedRows = [tableContentInstance selectionDetailsAllowingIndexSelection:YES]; NSRect contentViewport = [tableContentInstance viewport]; - NSDictionary *contentFilter = [tableContentInstance filterSettings]; + NSDictionary *contentFilter = [[tableContentInstance onMainThread] filterSettings]; NSData *filterTableData = [tableContentInstance filterTableData]; if (!theDatabase) return; diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 45add266..7b60d152 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -811,7 +811,7 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper [self fieldListForQuery], [selectedTable backtickQuotedString]]; // Add a filter string if appropriate - filterString = [self tableFilterString]; + filterString = [[self onMainThread] tableFilterString]; if (filterString) { [queryString appendFormat:@" WHERE %@", filterString]; @@ -1071,6 +1071,8 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper * Returns the query string for the current filter settings, * ready to be dropped into a WHERE clause, or nil if no filtering * is active. + * + * @warning Uses UI. ONLY call from main thread! */ - (NSString *)tableFilterString { @@ -3912,6 +3914,8 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper /** * Provide a getter for the current filter details + * + * @warning Uses UI. MUST call from main thread! */ - (NSDictionary *) filterSettings { -- cgit v1.2.3 From 5ef3f0df72d89ad85680a02048c27e2460e2c685 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 22 Apr 2015 22:41:58 +0200 Subject: Move some complex logic into its own class so it will easier to write some unit tests and refactor some of the code. --- Source/SPTableContent.m | 167 +++----------------------------- Source/SPTableFilterParser.h | 61 ++++++++++++ Source/SPTableFilterParser.m | 225 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 297 insertions(+), 156 deletions(-) create mode 100644 Source/SPTableFilterParser.h create mode 100644 Source/SPTableFilterParser.m (limited to 'Source') diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m index 7b60d152..308c101b 100644 --- a/Source/SPTableContent.m +++ b/Source/SPTableContent.m @@ -61,6 +61,7 @@ #endif #import "SPCustomQuery.h" #import "SPThreadAdditions.h" +#import "SPTableFilterParser.h" #import #import @@ -1104,8 +1105,6 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper BOOL caseSensitive = (([[[NSApp onMainThread] currentEvent] modifierFlags] & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask)) > 0); - NSString *filterString; - if(contentFilters == nil) { NSLog(@"Fatal error while retrieving content filters. No filters found."); NSBeep(); @@ -1133,160 +1132,16 @@ static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOper return nil; } - - NSUInteger numberOfArguments = [[filter objectForKey:@"NumberOfArguments"] integerValue]; - - BOOL suppressLeadingTablePlaceholder = NO; - if([filter objectForKey:@"SuppressLeadingFieldPlaceholder"]) - suppressLeadingTablePlaceholder = YES; - - // argument if Filter requires only one argument - NSMutableString *argument = [[NSMutableString alloc] initWithString:[argumentField stringValue]]; - - // If the filter field is empty and the selected filter does not require - // only one argument, then no filtering is required - return nil. - if (![argument length] && numberOfArguments == 1) { - [argument release]; - return nil; - } - - // arguments if Filter requires two arguments - NSMutableString *firstBetweenArgument = [[NSMutableString alloc] initWithString:[firstBetweenField stringValue]]; - NSMutableString *secondBetweenArgument = [[NSMutableString alloc] initWithString:[secondBetweenField stringValue]]; - - // If filter requires two arguments and either of the argument fields are empty - // return nil. - if (numberOfArguments == 2) { - if (([firstBetweenArgument length] == 0) || ([secondBetweenArgument length] == 0)) { - [argument release]; - [firstBetweenArgument release]; - [secondBetweenArgument release]; - return nil; - } - } - - // Retrieve actual WHERE clause - NSMutableString *clause = [[NSMutableString alloc] init]; - [clause setString:[filter objectForKey:@"Clause"]]; - - [clause replaceOccurrencesOfRegex:@"(? 0) - [clause replaceOccurrencesOfRegex:@"%" withString:@"%%"]; - [clause flushCachedRegexData]; - - // Replace placeholder ${} by %@ - NSRange matchedRange; - NSString *re = @"(? 2) { - NSLog(@"Filter with more than 2 arguments is not yet supported."); - NSBeep(); - } - } - } else { - if (numberOfArguments == 2) { - filterString = [NSString stringWithFormat:@"%@ %@", - [[fieldField titleOfSelectedItem] backtickQuotedString], - [NSString stringWithFormat:clause, - [self escapeFilterArgument:firstBetweenArgument againstClause:clause], - [self escapeFilterArgument:secondBetweenArgument againstClause:clause]]]; - } else if (numberOfArguments == 1) { - filterString = [NSString stringWithFormat:@"%@ %@", - [[fieldField titleOfSelectedItem] backtickQuotedString], - [NSString stringWithFormat:clause, [self escapeFilterArgument:argument againstClause:clause]]]; - } else { - filterString = [NSString stringWithFormat:@"%@ %@", - [[fieldField titleOfSelectedItem] backtickQuotedString], clause]; - if(numberOfArguments > 2) { - NSLog(@"Filter with more than 2 arguments is not yet supported."); - NSBeep(); - } - } - } - - [argument release]; - [firstBetweenArgument release]; - [secondBetweenArgument release]; - [clause release]; - - // Return the filter string - return filterString; -} - -/** - * Escape argument by looking for used quoting strings in a clause. Attempt to - * be smart - use a single escape for most clauses, doubling up for LIKE clauses. - * Also attempt to not escape what look like common escape sequences - \n, \r, \t. - * - * @param argument The to be used filter argument which should be be escaped - * - * @param clause The entire WHERE filter clause - * - */ -- (NSString *)escapeFilterArgument:(NSString *)argument againstClause:(NSString *)clause -{ - BOOL clauseIsLike = [clause isMatchedByRegex:@"(?i)\\blike\\b.*?%(?!@)"]; - NSString *recognizedEscapeSequences, *escapeSequence, *regexTerm; - NSMutableString *arg = [argument mutableCopy]; - - // Determine the character set not to escape slashes before, and the escape depth - if (clauseIsLike) { - recognizedEscapeSequences = @"nrt_%"; - escapeSequence = @"\\\\\\\\\\\\\\\\"; - } else { - recognizedEscapeSequences = @"nrt"; - escapeSequence = @"\\\\\\\\"; - } - regexTerm = [NSString stringWithFormat:@"(\\\\)(?![%@])", recognizedEscapeSequences]; - - // Escape slashes appropriately - [arg replaceOccurrencesOfRegex:regexTerm withString:escapeSequence]; - [arg flushCachedRegexData]; - - // Get quote sign for escaping - this should work for 99% of all cases - NSString *quoteSign = [clause stringByMatching:@"([\"'])[^\\1]*?%@[^\\1]*?\\1" capture:1L]; - - // Escape argument - if(quoteSign != nil && [quoteSign length] == 1) { - [arg replaceOccurrencesOfRegex:[NSString stringWithFormat:@"(%@)", quoteSign] withString:@"\\\\$1"]; - [arg flushCachedRegexData]; - } - - return [arg autorelease]; + + SPTableFilterParser *parser = [[[SPTableFilterParser alloc] initWithFilterClause:[filter objectForKey:@"Clause"] numberOfArguments:[[filter objectForKey:@"NumberOfArguments"] integerValue]] autorelease]; + [parser setArgument:[argumentField stringValue]]; + [parser setFirstBetweenArgument:[firstBetweenField stringValue]]; + [parser setSecondBetweenArgument:[secondBetweenField stringValue]]; + [parser setSuppressLeadingTablePlaceholder:(!![filter objectForKey:@"SuppressLeadingFieldPlaceholder"])]; + [parser setCaseSensitive:caseSensitive]; + [parser setCurrentField:[fieldField titleOfSelectedItem]]; + + return [parser filterString]; } /** diff --git a/Source/SPTableFilterParser.h b/Source/SPTableFilterParser.h new file mode 100644 index 00000000..069c802c --- /dev/null +++ b/Source/SPTableFilterParser.h @@ -0,0 +1,61 @@ +// +// SPTableFilterParser.h +// sequel-pro +// +// Created by Max Lohrmann on 22.04.15. +// Relocated from existing files. Previous copyright applies. +// +// 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 + +#import + +@interface SPTableFilterParser : NSObject +{ + NSString *_clause; + NSUInteger numberOfArguments; + + NSString *_currentField; + NSString *_argument; + NSString *_firstBetweenArgument; + NSString *_secondsBetweenArgument; + + BOOL caseSensitive; + BOOL suppressLeadingTablePlaceholder; +} + +- (id)initWithFilterClause:(NSString *)filter numberOfArguments:(NSUInteger)numArgs; + +@property(readonly) NSString *clause; +@property(readonly) NSUInteger numberOfArguments; + +@property BOOL suppressLeadingTablePlaceholder; +@property BOOL caseSensitive; +@property(copy) NSString *currentField; +@property(copy) NSString *argument; +@property(copy) NSString *firstBetweenArgument; +@property(copy) NSString *secondBetweenArgument; + +- (NSString *)filterString; + +@end diff --git a/Source/SPTableFilterParser.m b/Source/SPTableFilterParser.m new file mode 100644 index 00000000..96ba8368 --- /dev/null +++ b/Source/SPTableFilterParser.m @@ -0,0 +1,225 @@ +// +// SPTableFilterParser.m +// sequel-pro +// +// Created by Max Lohrmann on 22.04.15. +// Relocated from existing files. Previous copyright applies. +// +// 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 + +#import "SPTableFilterParser.h" +#import "RegexKitLite.h" + +@interface SPTableFilterParser (Private) ++ (NSString *)escapeFilterArgument:(NSString *)argument againstClause:(NSString *)clause; +@end + +@implementation SPTableFilterParser + +@synthesize suppressLeadingTablePlaceholder = suppressLeadingTablePlaceholder; +@synthesize caseSensitive = caseSensitive; +@synthesize currentField = _currentField; +@synthesize argument = _argument; +@synthesize firstBetweenArgument = _firstBetweenArgument; +@synthesize secondBetweenArgument = _secondBetweenArgument; +@synthesize numberOfArguments = numberOfArguments; +@synthesize clause = _clause; + +- (id)initWithFilterClause:(NSString *)filter numberOfArguments:(NSUInteger)numArgs +{ + self = [super init]; + if (self) { + numberOfArguments = numArgs; + _clause = [filter copy]; + } + return self; +} + +- (void)dealloc +{ + SPClear(_clause); + + [self setCurrentField:nil]; + [self setArgument:nil]; + [self setFirstBetweenArgument:nil]; + [self setSecondBetweenArgument:nil]; + + [super dealloc]; +} + +- (NSString *)filterString +{ + NSString *filterString; + + // argument if Filter requires only one argument + NSMutableString *argument = [[NSMutableString alloc] initWithString:_argument]; + + // If the filter field is empty and the selected filter does not require + // only one argument, then no filtering is required - return nil. + if (![argument length] && numberOfArguments == 1) { + [argument release]; + return nil; + } + + // arguments if Filter requires two arguments + NSMutableString *firstBetweenArgument = [[NSMutableString alloc] initWithString:_firstBetweenArgument]; + NSMutableString *secondBetweenArgument = [[NSMutableString alloc] initWithString:_secondBetweenArgument]; + + // If filter requires two arguments and either of the argument fields are empty + // return nil. + if (numberOfArguments == 2) { + if (([firstBetweenArgument length] == 0) || ([secondBetweenArgument length] == 0)) { + [argument release]; + [firstBetweenArgument release]; + [secondBetweenArgument release]; + return nil; + } + } + + // Retrieve actual WHERE clause + NSMutableString *clause = [[NSMutableString alloc] init]; + [clause setString:_clause]; + + [clause replaceOccurrencesOfRegex:@"(? 0) + [clause replaceOccurrencesOfRegex:@"%" withString:@"%%"]; + [clause flushCachedRegexData]; + + // Replace placeholder ${} by %@ + NSRange matchedRange; + NSString *re = @"(? 2) { + SPLog(@"Filter with more than 2 arguments is not yet supported."); + NSBeep(); + } + } + } else { + if (numberOfArguments == 2) { + filterString = [NSString stringWithFormat:@"%@ %@", + [_currentField backtickQuotedString], + [NSString stringWithFormat:clause, + [[self class] escapeFilterArgument:firstBetweenArgument againstClause:clause], + [[self class] escapeFilterArgument:secondBetweenArgument againstClause:clause]]]; + } else if (numberOfArguments == 1) { + filterString = [NSString stringWithFormat:@"%@ %@", + [_currentField backtickQuotedString], + [NSString stringWithFormat:clause, [[self class] escapeFilterArgument:argument againstClause:clause]]]; + } else { + filterString = [NSString stringWithFormat:@"%@ %@", + [_currentField backtickQuotedString], clause]; + if(numberOfArguments > 2) { + SPLog(@"Filter with more than 2 arguments is not yet supported."); + NSBeep(); + } + } + } + + [argument release]; + [firstBetweenArgument release]; + [secondBetweenArgument release]; + [clause release]; + + // Return the filter string + return filterString; +} + +/** + * Escape argument by looking for used quoting strings in a clause. Attempt to + * be smart - use a single escape for most clauses, doubling up for LIKE clauses. + * Also attempt to not escape what look like common escape sequences - \n, \r, \t. + * + * @param argument The to be used filter argument which should be be escaped + * + * @param clause The entire WHERE filter clause + * + */ ++ (NSString *)escapeFilterArgument:(NSString *)argument againstClause:(NSString *)clause +{ + BOOL clauseIsLike = [clause isMatchedByRegex:@"(?i)\\blike\\b.*?%(?!@)"]; + NSString *recognizedEscapeSequences, *escapeSequence, *regexTerm; + NSMutableString *arg = [argument mutableCopy]; + + // Determine the character set not to escape slashes before, and the escape depth + if (clauseIsLike) { + recognizedEscapeSequences = @"nrt_%"; + escapeSequence = @"\\\\\\\\\\\\\\\\"; + } else { + recognizedEscapeSequences = @"nrt"; + escapeSequence = @"\\\\\\\\"; + } + regexTerm = [NSString stringWithFormat:@"(\\\\)(?![%@])", recognizedEscapeSequences]; + + // Escape slashes appropriately + [arg replaceOccurrencesOfRegex:regexTerm withString:escapeSequence]; + [arg flushCachedRegexData]; + + // Get quote sign for escaping - this should work for 99% of all cases + NSString *quoteSign = [clause stringByMatching:@"([\"'])[^\\1]*?%@[^\\1]*?\\1" capture:1L]; + + // Escape argument + if(quoteSign != nil && [quoteSign length] == 1) { + [arg replaceOccurrencesOfRegex:[NSString stringWithFormat:@"(%@)", quoteSign] withString:@"\\\\$1"]; + [arg flushCachedRegexData]; + } + + return [arg autorelease]; +} + + +@end -- cgit v1.2.3 From d828290bdc4229db1beb7e8e2f9df0b8f0a35a72 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 23 Apr 2015 21:34:15 +0200 Subject: Added some basic unit tests for SPTableFilterParser --- Source/SPTableFilterParser.m | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'Source') diff --git a/Source/SPTableFilterParser.m b/Source/SPTableFilterParser.m index 96ba8368..f7c9ed62 100644 --- a/Source/SPTableFilterParser.m +++ b/Source/SPTableFilterParser.m @@ -50,8 +50,10 @@ { self = [super init]; if (self) { - numberOfArguments = numArgs; - _clause = [filter copy]; + numberOfArguments = numArgs; + _clause = [filter copy]; + caseSensitive = NO; + suppressLeadingTablePlaceholder = NO; } return self; } @@ -73,7 +75,7 @@ NSString *filterString; // argument if Filter requires only one argument - NSMutableString *argument = [[NSMutableString alloc] initWithString:_argument]; + NSMutableString *argument = [[NSMutableString alloc] initWithString:(_argument? _argument : @"")]; // If the filter field is empty and the selected filter does not require // only one argument, then no filtering is required - return nil. @@ -83,8 +85,8 @@ } // arguments if Filter requires two arguments - NSMutableString *firstBetweenArgument = [[NSMutableString alloc] initWithString:_firstBetweenArgument]; - NSMutableString *secondBetweenArgument = [[NSMutableString alloc] initWithString:_secondBetweenArgument]; + NSMutableString *firstBetweenArgument = [[NSMutableString alloc] initWithString:(_firstBetweenArgument? _firstBetweenArgument : @"")]; + NSMutableString *secondBetweenArgument = [[NSMutableString alloc] initWithString:(_secondBetweenArgument? _secondBetweenArgument : @"")]; // If filter requires two arguments and either of the argument fields are empty // return nil. -- cgit v1.2.3 From ace145be795f25dfa42080e459a63cc0c885a9fa Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 28 Apr 2015 20:53:26 +0200 Subject: Choosing a custom SSH binary via file picker no longer resolves softlinks --- Source/SPNetworkPreferencePane.m | 1 + 1 file changed, 1 insertion(+) (limited to 'Source') diff --git a/Source/SPNetworkPreferencePane.m b/Source/SPNetworkPreferencePane.m index 4f13c433..c734f07b 100644 --- a/Source/SPNetworkPreferencePane.m +++ b/Source/SPNetworkPreferencePane.m @@ -119,6 +119,7 @@ static NSString *SPSSLCipherPboardTypeName = @"SSLCipherPboardType"; [_currentFilePanel setCanChooseDirectories:NO]; [_currentFilePanel setAllowsMultipleSelection:NO]; [_currentFilePanel setAccessoryView:hiddenFileView]; + [_currentFilePanel setResolvesAliases:NO]; [self updateHiddenFiles]; [prefs addObserver:self -- cgit v1.2.3 From 80a2088f43bd3a901fb20d714318d4b5d3dc60a9 Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 1 May 2015 02:08:48 +0200 Subject: Significantly reduce risk of a race condition in a certain setup (see #2107) * Replaced a run loop sleep with a thread sleep as it was on a background thread where a) a regular sleep is fine, b) the run loop sleep did not seem to have any effect * While we are at it, cut done some duplicate code * Removed a redundant if() --- Source/SPConnectionHandler.m | 10 +++++--- Source/SPSSHTunnel.m | 56 +++++++++++++++++++++----------------------- 2 files changed, 34 insertions(+), 32 deletions(-) (limited to 'Source') diff --git a/Source/SPConnectionHandler.m b/Source/SPConnectionHandler.m index 80e9c3f5..c216142f 100644 --- a/Source/SPConnectionHandler.m +++ b/Source/SPConnectionHandler.m @@ -174,8 +174,12 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; if (![mySQLConnection isConnected]) { if (sshTunnel && !cancellingConnection) { - // If an SSH tunnel is running, temporarily block to allow the tunnel to register changes in state - [[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]]; + // This is a race condition we cannot fix "properly": + // For meaningful error handling we need to also consider the debug output from the SSH connection. + // The SSH debug output might be sligthly delayed though (flush, delegates, ...) or + // there might not even by any output at all (when it is purely a libmysql issue). + // TL;DR: No guaranteed events we could wait for, just trying our luck. + [NSThread sleepForTimeInterval:0.1]; // 100ms // If the state is connection refused, attempt the MySQL connection again with the host using the hostfield value. if ([sshTunnel state] == SPMySQLProxyForwardingFailed) { @@ -184,7 +188,7 @@ static NSString *SPLocalhostAddress = @"127.0.0.1"; [mySQLConnection connect]; if (![mySQLConnection isConnected]) { - [[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]]; + [NSThread sleepForTimeInterval:0.1]; //100ms } } } diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m index 8e9ffb13..d2c999c4 100644 --- a/Source/SPSSHTunnel.m +++ b/Source/SPSSHTunnel.m @@ -40,6 +40,8 @@ #import #import +static unsigned short getRandomPort(); + @implementation SPSSHTunnel @synthesize passwordPromptCancelled; @@ -264,36 +266,10 @@ // If no local port has yet been chosen, choose one if (!localPort) { - int tempSocket; - struct sockaddr_in tempSocketAddress; - size_t addressLength = sizeof(tempSocketAddress); - if((tempSocket = socket(AF_INET, SOCK_STREAM, 0)) > 0) { - memset(&tempSocketAddress, 0, sizeof(tempSocketAddress)); - tempSocketAddress.sin_family = AF_INET; - tempSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY); - tempSocketAddress.sin_port = 0; - if (bind(tempSocket, (struct sockaddr *)&tempSocketAddress, (socklen_t)addressLength) >= 0) { - if (getsockname(tempSocket, (struct sockaddr *)&tempSocketAddress, (uint32_t *)&addressLength) >= 0) { - localPort = ntohs(tempSocketAddress.sin_port); - } - } - close(tempSocket); - } + localPort = getRandomPort(); if (useHostFallback) { - if((tempSocket = socket(AF_INET, SOCK_STREAM, 0)) > 0) { - memset(&tempSocketAddress, 0, sizeof(tempSocketAddress)); - tempSocketAddress.sin_family = AF_INET; - tempSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY); - tempSocketAddress.sin_port = 0; - if (bind(tempSocket, (struct sockaddr *)&tempSocketAddress, (socklen_t)addressLength) >= 0) { - if (getsockname(tempSocket, (struct sockaddr *)&tempSocketAddress, (uint32_t *)&addressLength) >= 0) { - localPortFallback = ntohs(tempSocketAddress.sin_port); - } - } - close(tempSocket); - } - + localPortFallback = getRandomPort(); } // Abort if no local free port could be allocated @@ -748,7 +724,7 @@ { delegate = nil; [[NSNotificationCenter defaultCenter] removeObserver:self]; - if (connectionState != SPMySQLProxyIdle) [self disconnect]; + [self disconnect]; [NSObject cancelPreviousPerformRequestsWithTarget:self]; SPClear(sshHost); SPClear(sshLogin); @@ -775,3 +751,25 @@ } @end + +#pragma mark - + +unsigned short getRandomPort() { + int port = 0; + int tempSocket; + struct sockaddr_in tempSocketAddress; + size_t addressLength = sizeof(tempSocketAddress); + if((tempSocket = socket(AF_INET, SOCK_STREAM, 0)) > 0) { + memset(&tempSocketAddress, 0, sizeof(tempSocketAddress)); + tempSocketAddress.sin_family = AF_INET; + tempSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY); + tempSocketAddress.sin_port = 0; + if (bind(tempSocket, (struct sockaddr *)&tempSocketAddress, (socklen_t)addressLength) >= 0) { + if (getsockname(tempSocket, (struct sockaddr *)&tempSocketAddress, (uint32_t *)&addressLength) >= 0) { + port = ntohs(tempSocketAddress.sin_port); + } + } + close(tempSocket); + } + return port; +} -- cgit v1.2.3 From 7b579c9ddc7c161cfd4ed99e07bf83ccd72a83ee Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 2 May 2015 00:47:50 +0200 Subject: Fix a typo that caused build failures with older Xcode versions --- Source/SPTableFilterParser.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Source') diff --git a/Source/SPTableFilterParser.h b/Source/SPTableFilterParser.h index 069c802c..828b4b4a 100644 --- a/Source/SPTableFilterParser.h +++ b/Source/SPTableFilterParser.h @@ -38,7 +38,7 @@ NSString *_currentField; NSString *_argument; NSString *_firstBetweenArgument; - NSString *_secondsBetweenArgument; + NSString *_secondBetweenArgument; BOOL caseSensitive; BOOL suppressLeadingTablePlaceholder; -- cgit v1.2.3 From 4d82718f43d92f2ef2193dc603a4486f85fb1582 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 7 May 2015 16:30:51 +0200 Subject: * Copying text from the query console without having a database selected could cause an exception (fixes #2111) * Text copied from the query console could have an invalid format in some setups --- Source/SPQueryController.m | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'Source') diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m index 4aba3a14..c57621d8 100644 --- a/Source/SPQueryController.m +++ b/Source/SPQueryController.m @@ -171,20 +171,23 @@ static SPQueryController *sharedQueryController = nil; if (i < [messagesVisibleSet count]) { SPConsoleMessage *message = NSArrayObjectAtIndex(messagesVisibleSet, i); - if (includeTimestamps || includeConnections) [string appendString:@"/* "]; + if (includeTimestamps || includeConnections || includeDatabases) [string appendString:@"/* "]; - if (includeTimestamps) { - [string appendString:[dateFormatter stringFromDate:[message messageDate]]]; + NSDate *date = [message messageDate]; + if (includeTimestamps && date) { + [string appendString:[dateFormatter stringFromDate:date]]; [string appendString:@" "]; } - if (includeConnections) { - [string appendString:[message messageConnection]]; + NSString *connection = [message messageConnection]; + if (includeConnections && connection) { + [string appendString:connection]; [string appendString:@" "]; } - if (includeDatabases) { - [string appendString:[message messageDatabase]]; + NSString *database = [message messageDatabase]; + if (includeDatabases && database) { + [string appendString:database]; [string appendString:@" "]; } -- cgit v1.2.3 From 7dbcadc2c0523dc3c3bcc0a8cd7ceea9f44fc655 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 9 May 2015 23:27:05 +0200 Subject: Fix a possible crash caused by a use-after-free in some rare cases when closing a connection tab. --- Source/NoodleLineNumberView.m | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'Source') diff --git a/Source/NoodleLineNumberView.m b/Source/NoodleLineNumberView.m index 24b76be1..8b678434 100644 --- a/Source/NoodleLineNumberView.m +++ b/Source/NoodleLineNumberView.m @@ -59,6 +59,7 @@ typedef NSRange (*RangeOfLineIMP)(id object, SEL selector, NSRange range); - (void)invalidateLineIndices; - (void)calculateLines; - (void)updateGutterThicknessConstants; +- (void)setRuleThicknessNumber:(NSNumber *)aNum; @end @@ -112,6 +113,7 @@ typedef NSRange (*RangeOfLineIMP)(id object, SEL selector, NSRange range); - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; + [NSObject cancelPreviousPerformRequestsWithTarget:self]; if (lineIndices) [lineIndices release]; if (textAttributes) [textAttributes release]; @@ -566,17 +568,23 @@ typedef NSRange (*RangeOfLineIMP)(id object, SEL selector, NSRange range); currentRuleThickness = newThickness; // Not a good idea to resize the view during calculations (which can happen during - // display). Do a delayed perform (using NSInvocation since arg is a float). - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(setRuleThickness:)]]; - [invocation setSelector:@selector(setRuleThickness:)]; - [invocation setTarget:self]; - [invocation setArgument:&newThickness atIndex:2]; - - [invocation performSelector:@selector(invoke) withObject:nil afterDelay:0.0]; + // display). Do a delayed perform. + [self performSelector:@selector(setRuleThicknessNumber:) withObject:[NSNumber numberWithFloat:newThickness] afterDelay:0.0]; } } } +- (void)setRuleThicknessNumber:(NSNumber *)aNum +{ + // We want to do a delayed perform, but setRuleThickness: does take a CGFloat + // and not an object. In the past we used NSInvocation to work around that, + // however that has one major issue: >>This class does not retain the arguments + // for the contained invocation by default.<< (NSInvocation doc). + // A perform with delay 0.0 is queued with the run loop, so a dealloc can very + // well happen before that! + [self setRuleThickness:[aNum floatValue]]; +} + - (void)updateGutterThicknessConstants { maxWidthOfGlyph1 = ceilf(MAX(DEFAULT_THICKNESS, maxWidthOfGlyph + RULER_MARGIN2)); -- cgit v1.2.3 From 0f11cb74639d17a2fe512ed81d67ccf33601b605 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 10 May 2015 01:24:34 +0200 Subject: * Fix an exception that would occur if a user tried to export favorites when no favorites are selected * Select "Quick Connect" after deleting a favorite --- Source/SPConnectionController.m | 20 +++++++++++++------- Source/SPConnectionControllerDelegate.m | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) (limited to 'Source') diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 7cde1e4e..25049d44 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -1039,10 +1039,17 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, */ - (IBAction)exportFavorites:(id)sender { - NSSavePanel *savePanel = [NSSavePanel savePanel]; + // additional empty selection check + if(![[self selectedFavoriteNodes] count]) return; - NSString *fileName = [[self selectedFavoriteNodes] count] > 1 ? SPExportFavoritesFilename : [[[self selectedFavorite] objectForKey:SPFavoriteNameKey] stringByAppendingPathExtension:@"plist"]; + NSSavePanel *savePanel = [NSSavePanel savePanel]; + // suggest the name of the favorite or a default name for multiple selection + NSString *fileName = ([[self selectedFavoriteNodes] count] == 1)? [[[self selectedFavorite] objectForKey:SPFavoriteNameKey] stringByAppendingPathExtension:@"plist"] : nil; + // This if() is so we can also catch nil due to favorite corruption (NSSavePanel will @throw if nil is passed in) + if(!fileName) + fileName = SPExportFavoritesFilename; + [savePanel setAccessoryView:exportPanelAccessoryView]; [savePanel setNameFieldStringValue:fileName]; @@ -1652,7 +1659,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, { [favoritesOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[favoritesOutlineView rowForItem:node]] byExtendingSelection:NO]; [self _scrollToSelectedNode]; - } +} /** * Scroll to the currently selected node. @@ -1663,7 +1670,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, if ([favoritesOutlineView selectedRow] == -1) return; [favoritesOutlineView scrollRowToVisible:[favoritesOutlineView selectedRow]]; - } +} /** * Removes the supplied tree node. @@ -1678,9 +1685,8 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self _reloadFavoritesViewData]; - // Clear the selection and update the interface to match - [favoritesOutlineView selectRowIndexes:nil byExtendingSelection:NO]; - [self updateFavoriteSelection:self]; + // Select Quick Connect item to prevent empty selection + [self _selectNode:quickConnectItem]; [connectionResizeContainer setHidden:NO]; [connectionInstructionsTextField setStringValue:NSLocalizedString(@"Enter connection details below, or choose a favorite", @"enter connection details label")]; diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index f0813292..f2a57e53 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -656,7 +656,7 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; // Favorites export if (action == @selector(exportFavorites:)) { - if ([[favoritesRoot allChildLeafs] count] == 0) { + if ([[favoritesRoot allChildLeafs] count] == 0 || selectedRows == 0) { return NO; } else if (selectedRows == 1) { -- cgit v1.2.3 From 11b8718ddfd44dc5786ac745f90fa390aaf57a06 Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 11 May 2015 02:04:06 +0200 Subject: * Fully enable export of favorite groups * Favorites can now be imported, sorted even if "Quick Connect" is selected * Favorite files containing groups will now be imported correctly * If a favorite and the group containing said favorite are exported, the favorite will no longer be included twice --- Source/SPConnectionController.m | 5 +++-- Source/SPConnectionControllerDelegate.m | 12 +++++----- Source/SPFavoriteNode.h | 3 ++- Source/SPFavoriteNode.m | 8 ++++++- Source/SPFavoritesController.m | 40 ++++++++++++++++++++++++++++----- Source/SPFavoritesExporter.m | 5 ++++- Source/SPGroupNode.h | 5 ++++- Source/SPGroupNode.m | 15 +++++++++++++ Source/SPNamedNode.h | 37 ++++++++++++++++++++++++++++++ Source/SPTreeNode.h | 1 + Source/SPTreeNode.m | 36 ++++++++++++++++++++++++++--- 11 files changed, 147 insertions(+), 20 deletions(-) create mode 100644 Source/SPNamedNode.h (limited to 'Source') diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index 25049d44..d7fce6fb 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -51,6 +51,7 @@ #import "SPFavoritesImporter.h" #import "SPThreadAdditions.h" #import "SPFavoriteColorSupport.h" +#import "SPNamedNode.h" #import @@ -738,7 +739,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, { SPTreeNode *node = [self selectedFavoriteNode]; - return (![node isGroup]) ? [[node representedObject] nodeFavorite] : nil; + return (![node isGroup]) ? [(SPFavoriteNode *)[node representedObject] nodeFavorite] : nil; } /** @@ -1045,7 +1046,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, NSSavePanel *savePanel = [NSSavePanel savePanel]; // suggest the name of the favorite or a default name for multiple selection - NSString *fileName = ([[self selectedFavoriteNodes] count] == 1)? [[[self selectedFavorite] objectForKey:SPFavoriteNameKey] stringByAppendingPathExtension:@"plist"] : nil; + NSString *fileName = ([[self selectedFavoriteNodes] count] == 1)? [[(id)[[self selectedFavoriteNode] representedObject] nodeName] stringByAppendingPathExtension:@"plist"] : nil; // This if() is so we can also catch nil due to favorite corruption (NSSavePanel will @throw if nil is passed in) if(!fileName) fileName = SPExportFavoritesFilename; diff --git a/Source/SPConnectionControllerDelegate.m b/Source/SPConnectionControllerDelegate.m index f2a57e53..99af9e35 100644 --- a/Source/SPConnectionControllerDelegate.m +++ b/Source/SPConnectionControllerDelegate.m @@ -617,8 +617,6 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; SPTreeNode *node = [self selectedFavoriteNode]; NSInteger selectedRows = [favoritesOutlineView numberOfSelectedRows]; - - if (node == quickConnectItem) return NO; if ((action == @selector(sortFavorites:)) || (action == @selector(reverseSortFavorites:))) { @@ -634,7 +632,14 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; if (action == @selector(reverseSortFavorites:)) { [menuItem setState:reverseFavoritesSort]; } + + return YES; } + + // import does not depend on a selection + if(action == @selector(importFavorites:)) return YES; + + if (node == quickConnectItem) return NO; // Remove/rename the selected node if (action == @selector(removeNode:) || action == @selector(renameNode:)) { @@ -659,9 +664,6 @@ static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf"; if ([[favoritesRoot allChildLeafs] count] == 0 || selectedRows == 0) { return NO; } - else if (selectedRows == 1) { - return (![[self selectedFavoriteNode] isGroup]); - } else if (selectedRows > 1) { [menuItem setTitle:NSLocalizedString(@"Export Selected...", @"export selected favorites menu item")]; } diff --git a/Source/SPFavoriteNode.h b/Source/SPFavoriteNode.h index a26c9a3b..6a132767 100644 --- a/Source/SPFavoriteNode.h +++ b/Source/SPFavoriteNode.h @@ -28,6 +28,7 @@ // // More info at +#import "SPNamedNode.h" /** * @class SPFavoriteNode SPFavoriteNode.h * @@ -35,7 +36,7 @@ * * Tree node the represents a connection favorite. */ -@interface SPFavoriteNode : NSObject +@interface SPFavoriteNode : NSObject { NSMutableDictionary *nodeFavorite; } diff --git a/Source/SPFavoriteNode.m b/Source/SPFavoriteNode.m index b2b99c64..b51980f7 100644 --- a/Source/SPFavoriteNode.m +++ b/Source/SPFavoriteNode.m @@ -81,6 +81,7 @@ static NSString *SPFavoriteNodeKey = @"SPFavoriteNode"; - (id)initWithCoder:(NSCoder *)coder { +#warning This is not a valid initializer. [self setNodeFavorite:[coder decodeObjectForKey:SPFavoriteNodeKey]]; return self; @@ -96,7 +97,12 @@ static NSString *SPFavoriteNodeKey = @"SPFavoriteNode"; - (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p ('%@')>", [self className], self, [[self nodeFavorite] objectForKey:SPFavoriteNameKey]]; + return [NSString stringWithFormat:@"<%@: %p ('%@')>", [self className], self, [self nodeName]]; +} + +- (NSString *)nodeName +{ + return [[self nodeFavorite] objectForKey:SPFavoriteNameKey]; } #pragma mark - diff --git a/Source/SPFavoritesController.m b/Source/SPFavoritesController.m index ce6e5427..625b46cc 100644 --- a/Source/SPFavoritesController.m +++ b/Source/SPFavoritesController.m @@ -45,7 +45,7 @@ static SPFavoritesController *sharedFavoritesController = nil; - (void)_addNode:(SPTreeNode *)node asChildOfNode:(SPTreeNode *)parent; - (SPTreeNode *)_constructBranchForNodeData:(NSDictionary *)nodeData; - +- (SPTreeNode *)_addFavoriteNodeWithData:(NSMutableDictionary *)data asChildOfNode:(SPTreeNode *)parent; @end @implementation SPFavoritesController @@ -164,6 +164,7 @@ static SPFavoritesController *sharedFavoritesController = nil; [self _addNode:node asChildOfNode:parent]; + [self saveFavorites]; [[NSNotificationCenter defaultCenter] postNotificationName:SPConnectionFavoritesChangedNotification object:self]; return node; @@ -179,11 +180,40 @@ static SPFavoritesController *sharedFavoritesController = nil; */ - (SPTreeNode *)addFavoriteNodeWithData:(NSMutableDictionary *)data asChildOfNode:(SPTreeNode *)parent { - SPTreeNode *node = [SPTreeNode treeNodeWithRepresentedObject:[SPFavoriteNode favoriteNodeWithDictionary:data]]; - + SPTreeNode *node = [self _addFavoriteNodeWithData:data asChildOfNode:parent]; + + [self saveFavorites]; + [[NSNotificationCenter defaultCenter] postNotificationName:SPConnectionFavoritesChangedNotification object:self]; + + return node; +} + +/** + * Inner recursive variant of the method above + */ +- (SPTreeNode *)_addFavoriteNodeWithData:(NSMutableDictionary *)data asChildOfNode:(SPTreeNode *)parent +{ + id object; + NSArray *childs = nil; + //if it has "Children" it must be a group node, otherwise assume favorite node + if ([data objectForKey:SPFavoriteChildrenKey]) { + object = [SPGroupNode groupNodeWithDictionary:data]; + childs = [data objectForKey:SPFavoriteChildrenKey]; + } + else { + object = [SPFavoriteNode favoriteNodeWithDictionary:data]; + } + + SPTreeNode *node = [SPTreeNode treeNodeWithRepresentedObject:object]; + [self _addNode:node asChildOfNode:parent]; - [[NSNotificationCenter defaultCenter] postNotificationName:SPConnectionFavoritesChangedNotification object:self]; + //also add the children + if(childs) { + for (NSMutableDictionary *childData in childs) { + [self _addFavoriteNodeWithData:childData asChildOfNode:node]; + } + } return node; } @@ -460,8 +490,6 @@ static SPFavoritesController *sharedFavoritesController = nil; else { [[[[favoritesTree mutableChildNodes] objectAtIndex:0] mutableChildNodes] addObject:node]; } - - [self saveFavorites]; } #pragma mark - diff --git a/Source/SPFavoritesExporter.m b/Source/SPFavoritesExporter.m index a8b78a86..d37ce07d 100644 --- a/Source/SPFavoritesExporter.m +++ b/Source/SPFavoritesExporter.m @@ -74,7 +74,10 @@ // Get a dictionary representation of all favorites for (SPTreeNode *node in [self exportFavorites]) { - [favorites addObject:[node dictionaryRepresentation]]; + // The selection could contain a group as well as items in that group. + // So we skip those items, as their group will already export them. + if(![node isDescendantOfNodes:[self exportFavorites]]) + [favorites addObject:[node dictionaryRepresentation]]; } NSDictionary *dictionary = @{SPFavoritesDataRootKey : favorites}; diff --git a/Source/SPGroupNode.h b/Source/SPGroupNode.h index a6583dc1..d12f7465 100644 --- a/Source/SPGroupNode.h +++ b/Source/SPGroupNode.h @@ -28,6 +28,7 @@ // // More info at +#import "SPNamedNode.h" /** * @class SPGroupNode SPGroupNode.h * @@ -35,7 +36,7 @@ * * Tree node that represents a group. */ -@interface SPGroupNode : NSObject +@interface SPGroupNode : NSObject { BOOL nodeIsExpanded; @@ -53,7 +54,9 @@ @property (readwrite, assign) BOOL nodeIsExpanded; - (id)initWithName:(NSString *)name; +- (id)initWithDictionary:(NSDictionary *)dict; + (SPGroupNode *)groupNodeWithName:(NSString *)name; ++ (SPGroupNode *)groupNodeWithDictionary:(NSDictionary *)dict; @end diff --git a/Source/SPGroupNode.m b/Source/SPGroupNode.m index 4d90c0c1..e1a0dfb3 100644 --- a/Source/SPGroupNode.m +++ b/Source/SPGroupNode.m @@ -61,11 +61,25 @@ static NSString *SPGroupNodeIsExpandedKey = @"SPGroupNodeIsExpanded"; return self; } +- (id)initWithDictionary:(NSDictionary *)dict +{ + if ((self = [self initWithName:[dict objectForKey:SPFavoritesGroupNameKey]])) { + [self setNodeIsExpanded:[(NSNumber *)[dict objectForKey:SPFavoritesGroupIsExpandedKey] boolValue]]; + } + + return self; +} + + (SPGroupNode *)groupNodeWithName:(NSString *)name { return [[[self alloc] initWithName:name] autorelease]; } ++ (SPGroupNode *)groupNodeWithDictionary:(NSDictionary *)dict +{ + return [[[self alloc] initWithDictionary:dict] autorelease]; +} + #pragma mark - #pragma mark Copying protocol methods @@ -84,6 +98,7 @@ static NSString *SPGroupNodeIsExpandedKey = @"SPGroupNodeIsExpanded"; - (id)initWithCoder:(NSCoder *)coder { +#warning This is not a valid initializer. [self setNodeName:[coder decodeObjectForKey:SPGroupNodeNameKey]]; [self setNodeIsExpanded:[[coder decodeObjectForKey:SPGroupNodeIsExpandedKey] boolValue]]; diff --git a/Source/SPNamedNode.h b/Source/SPNamedNode.h new file mode 100644 index 00000000..2ce99fdf --- /dev/null +++ b/Source/SPNamedNode.h @@ -0,0 +1,37 @@ +// +// SPNamedNode.h +// sequel-pro +// +// Created by Max Lohrmann on 11.05.15. +// Copyright (c) 2015 Max Lohrmann. 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 + +#import + +@protocol SPNamedNode + +- (NSString *)nodeName; + +@end diff --git a/Source/SPTreeNode.h b/Source/SPTreeNode.h index abbb179c..aa2edbdc 100644 --- a/Source/SPTreeNode.h +++ b/Source/SPTreeNode.h @@ -55,6 +55,7 @@ - (SPTreeNode *)parentFromArray:(NSArray *)array; - (BOOL)isDescendantOfOrOneOfNodes:(NSArray *)nodes; +- (BOOL)isDescendantOfNodes:(NSArray *)nodes; - (NSDictionary *)dictionaryRepresentation; diff --git a/Source/SPTreeNode.m b/Source/SPTreeNode.m index 13c86f27..22cfb1da 100644 --- a/Source/SPTreeNode.m +++ b/Source/SPTreeNode.m @@ -50,7 +50,7 @@ static NSString *SPTreeNodeIsGroupKey = @"SPTreeNodeIsGroup"; - (id)initWithRepresentedObject:(id)object { if ((self = [super initWithRepresentedObject:object])) { - [self setIsGroup:NO]; + [self setIsGroup:[object isKindOfClass:[SPGroupNode class]]]; } return self; @@ -197,11 +197,12 @@ static NSString *SPTreeNodeIsGroupKey = @"SPTreeNodeIsGroup"; /** * Returns YES if self is contained anywhere inside the children or children of - * sub-nodes of the nodes contained inside the supplied array. + * sub-nodes of the nodes contained inside the supplied array or is itself a + * member of the array. * * @param nodes The array of nodes to search * - * @return A BOOL indicating whether or not it's a descendent + * @return A BOOL indicating whether or not it's a descendent or array member */ - (BOOL)isDescendantOfOrOneOfNodes:(NSArray *)nodes { @@ -220,6 +221,34 @@ static NSString *SPTreeNodeIsGroupKey = @"SPTreeNodeIsGroup"; return NO; } +/** + * Returns YES if self is contained anywhere inside the children or children of + * sub-nodes of the nodes contained inside the supplied array, but NOT the given + * array itself. + * This means, if self is a member of nodes but not a child of any + * other node in nodes it will still return NO. + * + * @param nodes The array of nodes to search + * + * @return A BOOL indicating whether or not it's a descendent + */ +- (BOOL)isDescendantOfNodes:(NSArray *)nodes +{ + for (SPTreeNode *node in nodes) + { + if (node == self) continue; + + // Check all the sub-nodes + if ([node isGroup]) { + if ([self isDescendantOfOrOneOfNodes:[node childNodes]]) { + return YES; + } + } + } + + return NO; +} + /** * Constructs a dictionary representation of the favorite. * @@ -265,6 +294,7 @@ static NSString *SPTreeNodeIsGroupKey = @"SPTreeNodeIsGroup"; - (id)initWithCoder:(NSCoder *)coder { +#warning This is not a valid initializer. [self setIsGroup:[[coder decodeObjectForKey:SPTreeNodeIsGroupKey] boolValue]]; return self; -- cgit v1.2.3 From dfcbabf42c877ba6b5d626d02095d34559e5fee2 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 14 May 2015 20:13:06 +0200 Subject: Fix a data corruption issue in custom query editor (fixes #2113) ... which occurred if ALL of the following conditions were met: * A cell of a custom query result was being edited * At the same time another process removed said row * The custom query was rerun without canceling or finishing the edit first (also added a NSBeep() for a certain tooltip error message) --- Source/SPCustomQuery.m | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'Source') diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m index 70ff07ff..a6e14b34 100644 --- a/Source/SPCustomQuery.m +++ b/Source/SPCustomQuery.m @@ -563,6 +563,9 @@ { NSString *taskString; + //ensure there is no pending edit, which could be messed up (#2113) + [[tableDocumentInstance parentWindow] endEditingFor:nil]; + if ([queries count] > 1) { taskString = [NSString stringWithFormat:NSLocalizedString(@"Running query %i of %lu...", @"Running multiple queries string"), 1, (unsigned long)[queries count]]; } @@ -3822,27 +3825,31 @@ pos.y -= 20; switch(numberOfPossibleUpdateRows) { case -1: - [SPTooltip showWithObject:kCellEditorErrorNoMultiTabDb - atLocation:pos - ofType:@"text"]; - shouldBeginEditing = NO; + NSBeep(); + [SPTooltip showWithObject:kCellEditorErrorNoMultiTabDb + atLocation:pos + ofType:@"text"]; + shouldBeginEditing = NO; break; + case 0: - [SPTooltip showWithObject:[NSString stringWithFormat:kCellEditorErrorNoMatch, [columnDefinition objectForKey:@"org_table"]] - atLocation:pos - ofType:@"text"]; - shouldBeginEditing = NO; + NSBeep(); + [SPTooltip showWithObject:[NSString stringWithFormat:kCellEditorErrorNoMatch, [columnDefinition objectForKey:@"org_table"]] + atLocation:pos + ofType:@"text"]; + shouldBeginEditing = NO; break; case 1: - shouldBeginEditing = YES; + shouldBeginEditing = YES; break; default: - [SPTooltip showWithObject:[NSString stringWithFormat:kCellEditorErrorTooManyMatches, (long)numberOfPossibleUpdateRows] - atLocation:pos - ofType:@"text"]; - shouldBeginEditing = NO; + NSBeep(); + [SPTooltip showWithObject:[NSString stringWithFormat:kCellEditorErrorTooManyMatches, (long)numberOfPossibleUpdateRows] + atLocation:pos + ofType:@"text"]; + shouldBeginEditing = NO; } isFieldEditable = shouldBeginEditing; -- cgit v1.2.3 From 0f0c43eb74408b6a65a42e2c6fd46f4142ef8e3f Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 15 May 2015 00:07:41 +0200 Subject: * Fix some spacing issues for localization * Removed some leftover elements in Prefs from the old favorites UI --- Source/SPConnectionController.m | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'Source') diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m index d7fce6fb..dcdaec93 100644 --- a/Source/SPConnectionController.m +++ b/Source/SPConnectionController.m @@ -1545,7 +1545,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, */ - (void)_favoriteTypeDidChange - { +{ NSDictionary *favorite = [self selectedFavorite]; // If either socket or host is localhost, clear. @@ -1560,7 +1560,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [self setName:favoriteName]; } } - } +} /** * Convenience method for reloading the outline view, expanding the root item and scrolling to the selected item. @@ -1768,7 +1768,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, } return favoriteNode; - } +} #endif /** @@ -1780,7 +1780,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, NSString *result = [subject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; return [result stringByReplacingOccurrencesOfString:@"\n" withString:@""]; - } +} #ifndef SP_CODA /** @@ -1803,7 +1803,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, } return aName; - } +} /** @@ -1816,7 +1816,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, // If not connecting, hide the connection status text to reflect changes if (!isConnecting) { [progressIndicatorText setHidden:YES]; - } + } if (isEditingConnection) return; @@ -1833,13 +1833,13 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, // Show the area to allow saving the changes [self setIsEditingConnection:YES]; [favoritesOutlineView setNeedsDisplayInRect:[favoritesOutlineView rectOfRow:[favoritesOutlineView selectedRow]]]; - } +} /** * If editing is active, mark editing as complete, triggering UI updates to match. */ - (void)_stopEditingConnection - { +{ if (!isEditingConnection) return; [self setIsEditingConnection:NO]; @@ -1847,7 +1847,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, [editButtonsView setHidden:YES]; [progressIndicatorText setHidden:YES]; [(NSView *)favoritesOutlineView display]; - } +} #endif - (void)_documentWillClose:(NSNotification *)notification @@ -1863,7 +1863,7 @@ static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, } if (sshTunnel) [sshTunnel setConnectionStateChangeSelector:nil delegate:nil], SPClear(sshTunnel); - } +} #pragma mark - -- cgit v1.2.3