aboutsummaryrefslogtreecommitdiffstats
path: root/Source
diff options
context:
space:
mode:
authorsqlprodev <sqlprodev@northofthree.com>2011-04-11 20:29:49 +0000
committersqlprodev <sqlprodev@northofthree.com>2011-04-11 20:29:49 +0000
commit0ce916eb0583ec6b062786f91bee0133906671ce (patch)
tree68a5767ded966f4eadf53ba9ce85bcaf6d31b951 /Source
parent2621e79c75a0119a54c669b263caa82183bd19c8 (diff)
downloadsequelpro-0ce916eb0583ec6b062786f91bee0133906671ce.tar.gz
sequelpro-0ce916eb0583ec6b062786f91bee0133906671ce.tar.bz2
sequelpro-0ce916eb0583ec6b062786f91bee0133906671ce.zip
initial commit of SP_REFACTOR ifdefs, the start of a long quest to separate UI code from functional code
Diffstat (limited to 'Source')
-rw-r--r--Source/SPConnectionController.h36
-rw-r--r--Source/SPConnectionController.m82
-rw-r--r--Source/SPContentFilterManager.h8
-rw-r--r--Source/SPContentFilterManager.m16
-rw-r--r--Source/SPCopyTable.h9
-rw-r--r--Source/SPCopyTable.m71
-rw-r--r--Source/SPCustomQuery.h22
-rw-r--r--Source/SPCustomQuery.m164
-rw-r--r--Source/SPDatabaseDocument.h78
-rw-r--r--Source/SPDatabaseDocument.m215
-rw-r--r--Source/SPDatabaseViewController.h4
-rw-r--r--Source/SPDatabaseViewController.m43
-rw-r--r--Source/SPFieldEditorController.h6
-rw-r--r--Source/SPFieldEditorController.m77
-rw-r--r--Source/SPFieldMapperController.h8
-rw-r--r--Source/SPFieldMapperController.m72
-rw-r--r--Source/SPIndexesController.h2
-rw-r--r--Source/SPIndexesController.m28
-rw-r--r--Source/SPNarrowDownCompletion.h8
-rw-r--r--Source/SPNarrowDownCompletion.m14
-rw-r--r--Source/SPNavigatorController.h11
-rw-r--r--Source/SPNavigatorController.m18
-rw-r--r--Source/SPQueryController.h2
-rw-r--r--Source/SPQueryController.m54
-rw-r--r--Source/SPQueryFavoriteManager.h8
-rw-r--r--Source/SPQueryFavoriteManager.m20
-rw-r--r--Source/SPSQLParser.m2
-rw-r--r--Source/SPServerSupport.m2
-rw-r--r--Source/SPStringAdditions.h2
-rw-r--r--Source/SPStringAdditions.m2
-rw-r--r--Source/SPTableContent.h18
-rw-r--r--Source/SPTableContent.m484
-rw-r--r--Source/SPTableData.h12
-rw-r--r--Source/SPTableData.m13
-rw-r--r--Source/SPTableStructure.h23
-rw-r--r--Source/SPTableStructure.m143
-rw-r--r--Source/SPTableStructureDelegate.m16
-rw-r--r--Source/SPTableView.m19
-rw-r--r--Source/SPTablesList.h39
-rw-r--r--Source/SPTablesList.m139
-rw-r--r--Source/SPTextView.h18
-rw-r--r--Source/SPTextView.m152
-rw-r--r--Source/SPTextViewAdditions.h2
-rw-r--r--Source/SPTextViewAdditions.m11
44 files changed, 1847 insertions, 326 deletions
diff --git a/Source/SPConnectionController.h b/Source/SPConnectionController.h
index b68aad93..bded0b66 100644
--- a/Source/SPConnectionController.h
+++ b/Source/SPConnectionController.h
@@ -24,11 +24,19 @@
// More info at <http://code.google.com/p/sequel-pro/>
#import <MCPKit/MCPKit.h>
-
#import "SPConnectionControllerDelegateProtocol.h"
+
+#ifndef SP_REFACTOR /* headers */
#import "SPFavoritesOutlineView.h"
+#endif
+
+@class SPDatabaseDocument, SPSSHTunnel
+#ifndef SP_REFACTOR /* class decl */
+, SPKeychain, BWAnchoredButtonBar, SPFavoriteNode
+#endif
+;
-@class SPDatabaseDocument, SPKeychain, SPSSHTunnel, BWAnchoredButtonBar, SPFavoriteNode;
+#ifndef SP_REFACTOR /* class decl */
@interface NSObject (BWAnchoredButtonBar)
@@ -41,24 +49,30 @@
- (BOOL)isFlipped;
@end
+#endif
@interface SPConnectionController : NSObject
{
id <SPConnectionControllerDelegateProtocol, NSObject> delegate;
SPDatabaseDocument *tableDocument;
+#ifndef SP_REFACTOR /* ivars */
NSView *databaseConnectionSuperview;
NSSplitView *databaseConnectionView;
SPKeychain *keychain;
NSUserDefaults *prefs;
NSMutableArray *favorites;
+#endif
SPSSHTunnel *sshTunnel;
MCPConnection *mySQLConnection;
+#ifndef SP_REFACTOR /* ivars */
BOOL automaticFavoriteSelection;
+#endif
BOOL cancellingConnection;
BOOL isConnecting;
-
+#ifndef SP_REFACTOR /* ivars */
NSInteger previousType;
+#endif
NSInteger type;
NSString *name;
NSString *host;
@@ -80,10 +94,13 @@
int sshKeyLocationEnabled;
NSString *sshKeyLocation;
NSString *sshPort;
+#ifndef SP_REFACTOR /* ivars */
@private NSString *favoritesPBoardType;
+#endif
NSString *connectionKeychainID;
NSString *connectionKeychainItemName;
+#ifndef SP_REFACTOR /* ivars */
NSString *connectionKeychainItemAccount;
NSString *connectionSSHKeychainItemName;
NSString *connectionSSHKeychainItemAccount;
@@ -132,14 +149,17 @@
IBOutlet NSMenuItem *favoritesSortByMenuItem;
BOOL reverseFavoritesSort;
+#endif
+
BOOL mySQLConnectionCancelled;
-
+#ifndef SP_REFACTOR /* ivars */
SPFavoritesSortItem previousSortItem, currentSortItem;
SPFavoriteNode *favoritesRoot;
+#endif
}
-@property (readwrite, assign) id <SPConnectionControllerDelegateProtocol> delegate;
+@property (readwrite, assign) id <SPConnectionControllerDelegateProtocol, NSObject> delegate;
@property (readwrite, assign) NSInteger type;
@property (readwrite, retain) NSString *name;
@property (readwrite, retain) NSString *host;
@@ -161,19 +181,24 @@
@property (readwrite, assign) int sshKeyLocationEnabled;
@property (readwrite, retain) NSString *sshKeyLocation;
@property (readwrite, retain) NSString *sshPort;
+#ifndef SP_REFACTOR /* ivars */
@property (readwrite, retain) NSString *connectionKeychainItemName;
@property (readwrite, retain) NSString *connectionKeychainItemAccount;
@property (readwrite, retain) NSString *connectionSSHKeychainItemName;
@property (readwrite, retain) NSString *connectionSSHKeychainItemAccount;
+#endif
@property (readonly, assign) BOOL isConnecting;
+#ifndef SP_REFACTOR /* ivars */
@property (readonly, assign) NSString *favoritesPBoardType;
+#endif
- (id)initWithDocument:(SPDatabaseDocument *)theTableDocument;
// Connection processes
- (IBAction)initiateConnection:(id)sender;
+#ifndef SP_REFACTOR /* method decls */
- (IBAction)cancelMySQLConnection:(id)sender;
- (void)initiateSSHTunnelConnection;
- (void)sshTunnelCallback:(SPSSHTunnel *)theTunnel;
@@ -202,4 +227,5 @@
- (void)scrollViewFrameChanged:(NSNotification *)aNotification;
+#endif
@end
diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m
index e557b655..239681d0 100644
--- a/Source/SPConnectionController.m
+++ b/Source/SPConnectionController.m
@@ -25,24 +25,32 @@
#import "SPConnectionController.h"
#import "SPDatabaseDocument.h"
+
+#ifndef SP_REFACTOR /* headers */
#import "SPAppController.h"
#import "SPPreferenceController.h"
#import "ImageAndTextCell.h"
#import "RegexKitLite.h"
+#endif
#import "SPAlertSheets.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPKeychain.h"
+#import "SPFavoritesPreferencePane.h"
+#endif
#import "SPSSHTunnel.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPFavoriteNode.h"
#import "SPTableTextFieldCell.h"
#import "SPGeneralPreferencePane.h"
#import "SPDatabaseViewController.h"
-#import "SPPreferenceController.h"
-#import "SPFavoritesPreferencePane.h"
+#endif
@interface SPConnectionController (PrivateAPI)
+#ifndef SP_REFACTOR /* @interface */
- (void)_sortFavorites;
- (void)_buildFavoritesTree;
+#endif
- (void)_restoreConnectionInterface;
- (void)_mySQLConnectionEstablished;
- (void)_initiateMySQLConnectionInBackground;
@@ -74,13 +82,17 @@
@synthesize sshKeyLocation;
@synthesize sshPort;
+#ifndef SP_REFACTOR /* ivars */
@synthesize connectionKeychainItemName;
@synthesize connectionKeychainItemAccount;
@synthesize connectionSSHKeychainItemName;
@synthesize connectionSSHKeychainItemAccount;
+#endif
@synthesize isConnecting;
+#ifndef SP_REFACTOR /* ivars */
@synthesize favoritesPBoardType;
+#endif
#pragma mark -
@@ -92,18 +104,23 @@
{
if ((self = [super init])) {
tableDocument = theTableDocument;
+#ifndef SP_REFACTOR /* ivars */
databaseConnectionSuperview = [tableDocument databaseView];
databaseConnectionView = [tableDocument valueForKey:@"contentViewSplitter"];
+#endif
connectionKeychainID = nil;
connectionKeychainItemName = nil;
+#ifndef SP_REFACTOR /* ivars */
connectionKeychainItemAccount = nil;
connectionSSHKeychainItemName = nil;
connectionSSHKeychainItemAccount = nil;
+#endif
mySQLConnection = nil;
sshTunnel = nil;
cancellingConnection = NO;
isConnecting = NO;
mySQLConnectionCancelled = NO;
+#ifndef SP_REFACTOR /* ui init */
favoritesPBoardType = @"FavoritesPBoardType";
// Load the connection nib, keeping references to the top-level objects for later release
@@ -161,6 +178,7 @@
previousType = SPTCPIPConnection;
[self resizeTabViewToConnectionType:SPTCPIPConnection animating:NO];
}
+#endif
}
return self;
@@ -168,8 +186,11 @@
- (void) dealloc
{
+#ifndef SP_REFACTOR /* remove prefs observer */
[prefs removeObserver:self forKeyPath:SPFavorites];
+#endif
[[NSNotificationCenter defaultCenter] removeObserver:self];
+#ifndef SP_REFACTOR /* dealloc ivars */
[keychain release];
[prefs release];
@@ -177,14 +198,16 @@
[nibObjectsToRelease release];
if (favorites) [favorites release];
+#endif
if (mySQLConnection) [mySQLConnection release];
if (sshTunnel) [sshTunnel setConnectionStateChangeSelector:nil delegate:nil], [sshTunnel disconnect], [sshTunnel release];
if (connectionKeychainID) [connectionKeychainID release];
if (connectionKeychainItemName) [connectionKeychainItemName release];
+#ifndef SP_REFACTOR /* dealloc ivars */
if (connectionKeychainItemAccount) [connectionKeychainItemAccount release];
if (connectionSSHKeychainItemName) [connectionSSHKeychainItemName release];
if (connectionSSHKeychainItemAccount) [connectionSSHKeychainItemAccount release];
-
+#endif
[super dealloc];
}
@@ -199,6 +222,7 @@
*/
- (IBAction)initiateConnection:(id)sender
{
+#ifndef SP_REFACTOR /* validate connection details */
// Ensure that host is not empty if this is a TCP/IP or SSH connection
if (([self type] == SPTCPIPConnection || [self type] == SPSSHTunnelConnection) && ![[self host] length]) {
SPBeginAlertSheet(NSLocalizedString(@"Insufficient connection details", @"insufficient details message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocument parentWindow], self, nil, nil, NSLocalizedString(@"Insufficient details provided to establish a connection. Please enter at least the hostname.", @"insufficient details informative message"));
@@ -304,11 +328,12 @@
[self performSelector:@selector(initiateSSHTunnelConnection) withObject:nil afterDelay:0.0];
return;
}
-
+#endif
// ...or start the MySQL connection process directly
[self performSelector:@selector(initiateMySQLConnection) withObject:nil afterDelay:0.0];
}
+#ifndef SP_REFACTOR /* cancelMySQLConnection: */
/**
* Cancels (or rather marks) the current connection is to be cancelled once established.
*
@@ -325,7 +350,9 @@
mySQLConnectionCancelled = YES;
}
+#endif
+#ifndef SP_REFACTOR /* initiateSSHTunnelConnection */
/*
* Initiate the SSH connection process.
* This should only be called as part of initiateConnection:, and will indirectly
@@ -362,6 +389,7 @@
// itself as an argument - retain count should be one at this point.
[sshTunnel connect];
}
+#endif
/*
* Cancel connection.
@@ -379,6 +407,7 @@
sshTunnel = nil;
}
+#ifndef SP_REFACTOR /* sshTunnelCallback: */
/*
* A callback function for the SSH Tunnel setup process - will be called on a connection
* state change, allowing connection to fail or proceed as appropriate. If successful,
@@ -413,11 +442,14 @@
}
}
+#endif
+
/*
* Set up the MySQL connection, either through a successful tunnel or directly in the background.
*/
- (void)initiateMySQLConnection
{
+#ifndef SP_REFACTOR /* ui manipulation */
if (sshTunnel)
[progressIndicatorText setStringValue:NSLocalizedString(@"MySQL connecting...", @"MySQL connecting very short status message")];
else
@@ -429,7 +461,7 @@
[connectButton setAction:@selector(cancelMySQLConnection:)];
[connectButton setEnabled:YES];
[connectButton display];
-
+#endif
[NSThread detachNewThreadSelector:@selector(_initiateMySQLConnectionInBackground) toTarget:self withObject:nil];
}
@@ -441,6 +473,7 @@
{
BOOL isSSHTunnelBindError = NO;
+#ifndef SP_REFACTOR /* ui manipulation */
// Clean up the interface
[progressIndicator stopAnimation:self];
[progressIndicator display];
@@ -450,6 +483,7 @@
[addToFavoritesButton display];
[connectButton setEnabled:YES];
[tableDocument clearStatusIcon];
+#endif
// Release as appropriate
if (sshTunnel) {
@@ -462,7 +496,9 @@
}
}
+#ifndef SP_REFACTOR /* [errorDetailText setString:errorDetail] */
if (errorDetail) [errorDetailText setString:errorDetail];
+#endif
// Inform the delegate that the connection attempt failed
if (delegate && [delegate respondsToSelector:@selector(connectionControllerConnectAttemptFailed:)]) {
@@ -471,8 +507,8 @@
// Only display the connection error message if there is a window visible and the connection attempt
// wasn't cancelled even though it failed.
- if ([[tableDocument parentWindow] isVisible] && (!mySQLConnectionCancelled)) {
- SPBeginAlertSheet(theTitle, NSLocalizedString(@"OK", @"OK button"), (errorDetail) ? NSLocalizedString(@"Show Detail", @"Show detail button") : nil, (isSSHTunnelBindError) ? NSLocalizedString(@"Use Standard Connection", @"use standard connection button") : nil, [tableDocument parentWindow], self, @selector(connectionFailureSheetDidEnd:returnCode:contextInfo:), @"connect", theErrorMessage);
+ if ([[NSApp keyWindow] isVisible] && (!mySQLConnectionCancelled)) {
+ SPBeginAlertSheet(theTitle, NSLocalizedString(@"OK", @"OK button"), (errorDetail) ? NSLocalizedString(@"Show Detail", @"Show detail button") : nil, (isSSHTunnelBindError) ? NSLocalizedString(@"Use Standard Connection", @"use standard connection button") : nil, [NSApp keyWindow], self, @selector(connectionFailureSheetDidEnd:returnCode:contextInfo:), @"connect", theErrorMessage);
}
}
@@ -481,6 +517,7 @@
*/
- (void)connectionFailureSheetDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
+#ifndef SP_REFACTOR /* connectionFailureSheetDidEnd: */
// Restore the passwords from keychain for editing if appropriate
if (connectionKeychainItemName) {
[self setPassword:[keychain getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount]];
@@ -513,6 +550,7 @@
// Initiate the connection after half a second to give the connection view a chance to resize
[self performSelector:@selector(initiateConnection:) withObject:self afterDelay:0.5];
}
+#endif
}
/**
@@ -521,6 +559,7 @@
*/
- (void)addConnectionToDocument
{
+#ifndef SP_REFACTOR /* ui manipulation */
// Hide the connection view and restore the main view
[connectionView removeFromSuperviewWithoutNeedingDisplay];
[databaseConnectionView setHidden:NO];
@@ -528,7 +567,8 @@
// Restore the toolbar icons
NSArray *toolbarItems = [[[tableDocument parentWindow] toolbar] items];
- for (NSUInteger i = 0; i < [toolbarItems count]; i++) [[toolbarItems objectAtIndex:i] setEnabled:YES];
+ for (NSInteger i = 0; i < (NSInteger)[toolbarItems count]; i++) [[toolbarItems objectAtIndex:i] setEnabled:YES];
+#endif
// Set keychain id for saving SPF files
if (connectionKeychainID) [tableDocument setKeychainID:connectionKeychainID];
@@ -538,6 +578,8 @@
[tableDocument setConnection:mySQLConnection];
}
+#ifndef SP_REFACTOR /* connection favorites and ssh key handling */
+
#pragma mark -
#pragma mark Interface interaction
@@ -1241,6 +1283,7 @@
// Revert the connect button back to its original selector
[connectButton setAction:@selector(initiateConnection:)];
}
+#endif
/**
* Called on the main thread once the MySQL connection is established on the background thread. Either the
@@ -1266,31 +1309,38 @@
return;
}
+#ifndef SP_REFACTOR /* ui manipulation */
[progressIndicatorText setStringValue:NSLocalizedString(@"Connected", @"connection established message")];
[progressIndicatorText display];
+#endif
// Stop the current tab's progress indicator
[tableDocument setIsProcessing:NO];
+#ifndef SP_REFACTOR /* ui manipulation */
// Successful connection!
[connectButton setEnabled:NO];
[connectButton display];
[progressIndicator stopAnimation:self];
[progressIndicatorText setHidden:YES];
[addToFavoritesButton setHidden:NO];
+#endif
// If SSL was enabled, check it was established correctly
if (useSSL && ([self type] == SPTCPIPConnection || [self type] == SPSocketConnection)) {
if (![mySQLConnection isConnectedViaSSL]) {
- SPBeginAlertSheet(NSLocalizedString(@"SSL connection not established", @"SSL requested but not used title"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocument parentWindow], nil, nil, nil, NSLocalizedString(@"You requested that the connection should be established using SSL, but MySQL made the connection without SSL.\n\nThis may be because the server does not support SSL connections, or has SSL disabled; or insufficient details were supplied to establish an SSL connection.\n\nThis connection is not encrypted.", @"SSL connection requested but not established error detail"));
+ SPBeginAlertSheet(NSLocalizedString(@"SSL connection not established", @"SSL requested but not used title"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], nil, nil, nil, NSLocalizedString(@"You requested that the connection should be established using SSL, but MySQL made the connection without SSL.\n\nThis may be because the server does not support SSL connections, or has SSL disabled; or insufficient details were supplied to establish an SSL connection.\n\nThis connection is not encrypted.", @"SSL connection requested but not established error detail"));
} else {
+#ifndef SP_REFACTOR /* [tableDocument setStatusIconToImageWithName:@"titlebarlock"] */
[tableDocument setStatusIconToImageWithName:@"titlebarlock"];
+#endif
}
}
-
+#ifndef SP_REFACTOR /* ui manipulation */
// Re-enable favorites table view
[favoritesTable setEnabled:YES];
[favoritesTable display];
+#endif
// Release the tunnel if set - will now be retained by the connection
if (sshTunnel) [sshTunnel release], sshTunnel = nil;
@@ -1340,7 +1390,7 @@
// Connection delegate must be set before actual connection attempt is made
[mySQLConnection setDelegate:tableDocument];
-
+#ifndef SP_REFACTOR /* set mysql connection settings from prefs */
// Set whether or not we should enable delegate logging according to the prefs
[mySQLConnection setDelegateQueryLogging:[prefs boolForKey:SPConsoleEnableLogging]];
@@ -1348,6 +1398,7 @@
[mySQLConnection setConnectionTimeout:[[prefs objectForKey:SPConnectionTimeoutValue] integerValue]];
[mySQLConnection setUseKeepAlive:[[prefs objectForKey:SPUseKeepAlive] boolValue]];
[mySQLConnection setKeepAliveInterval:[[prefs objectForKey:SPKeepAliveInterval] doubleValue]];
+#endif
// Connect
[mySQLConnection connect];
@@ -1385,8 +1436,10 @@
errorMessage = [NSString stringWithFormat:NSLocalizedString(@"Unable to connect via the socket, or the request timed out.\n\nDouble-check that the socket path is correct and that you have the necessary privileges, and that the server is running.\n\nMySQL said: %@", @"message of panel when connection to host failed"), [mySQLConnection getLastErrorMessage]];
[[self onMainThread] failConnectionWithTitle:NSLocalizedString(@"Socket connection failed!", @"socket connection failed title") errorMessage:errorMessage detail:nil];
} else {
+#ifndef SP_REFACTOR /* error message requiring prefs access */
errorMessage = [NSString stringWithFormat:NSLocalizedString(@"Unable to connect to host %@, or the request timed out.\n\nBe sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently %ld seconds).\n\nMySQL said: %@", @"message of panel when connection to host failed"), [self host], (long)[[prefs objectForKey:SPConnectionTimeoutValue] integerValue], [mySQLConnection getLastErrorMessage]];
[[self onMainThread] failConnectionWithTitle:NSLocalizedString(@"Connection failed!", @"connection failed title") errorMessage:errorMessage detail:nil];
+#endif
}
// Tidy up
@@ -1395,7 +1448,9 @@
if (sshTunnel) [sshTunnel release], sshTunnel = nil;
[mySQLConnection release], mySQLConnection = nil;
+#ifndef SP_REFACTOR /* ui manipulation */
[self _restoreConnectionInterface];
+#endif
[pool release];
return;
@@ -1412,7 +1467,9 @@
if (sshTunnel) [sshTunnel release], sshTunnel = nil;
[mySQLConnection release], mySQLConnection = nil;
+#ifndef SP_REFACTOR /* ui manipulation */
[self _restoreConnectionInterface];
+#endif
[pool release];
return;
@@ -1427,6 +1484,8 @@
@end
+#ifndef SP_REFACTOR /* SPFlippedView */
+
#pragma mark -
#pragma mark NSView subclass - flipped view for simpler drawing
@@ -1441,3 +1500,4 @@
}
@end
+#endif
diff --git a/Source/SPContentFilterManager.h b/Source/SPContentFilterManager.h
index ec2c1ef6..ec23afe6 100644
--- a/Source/SPContentFilterManager.h
+++ b/Source/SPContentFilterManager.h
@@ -31,9 +31,15 @@
@end
-@interface SPContentFilterManager : NSWindowController
+#ifndef SP_REFACTOR /* ivars */
+@interface SPContentFilterManager : NSWindowController
+#else
+@interface SPContentFilterManager : NSWindowController <NSOpenSavePanelDelegate>
+#endif
{
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
SPDatabaseDocument *tableDocumentInstance;
NSURL *delegatesFileURL;
diff --git a/Source/SPContentFilterManager.m b/Source/SPContentFilterManager.m
index 97c0b5d6..7b24d6e1 100644
--- a/Source/SPContentFilterManager.m
+++ b/Source/SPContentFilterManager.m
@@ -29,7 +29,9 @@
#import "SPQueryController.h"
#import "SPTableContent.h"
#import "SPConnectionController.h"
+#ifndef SP_REFACTOR /* headers */
#import <BWToolkitFramework/BWToolkitFramework.h>
+#endif
#define SP_MULTIPLE_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[multiple selection]", @"[multiple selection]")
#define SP_NO_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[no selection]", @"[no selection]")
@@ -45,7 +47,9 @@
{
if ((self = [super initWithWindowNibName:@"ContentFilterManager"])) {
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
+#endif
contentFilters = [[NSMutableArray alloc] init];
@@ -84,6 +88,7 @@
@"", @"ConjunctionLabel",
nil]];
+#ifndef SP_REFACTOR /* prefs access */
// Build data source for global content filter (as mutable copy! otherwise each
// change will be stored in the prefs at once)
if([[prefs objectForKey:SPContentFilters] objectForKey:filterType]) {
@@ -94,6 +99,7 @@
[contentFilters addObject:f];
}
}
+#endif
// Build doc-based filters
[contentFilters addObject:[NSDictionary dictionaryWithObjectsAndKeys:
@@ -135,8 +141,10 @@
// Set column header
[[[contentFilterTableView tableColumnWithIdentifier:@"MenuLabel"] headerCell] setStringValue:[NSString stringWithFormat:NSLocalizedString(@"‘%@’ Fields Content Filters", @"table column header. Read: 'Showing all content filters for fields of type %@' (ContentFilterManager)"), filterType]];
+#ifndef SP_REFACTOR /* split view delegate */
// Set the button delegate
[splitViewButtonBar setSplitViewDelegate:self];
+#endif
}
#pragma mark -
@@ -359,6 +367,7 @@
[[SPQueryController sharedQueryController] replaceContentFilterByArray:
[self contentFilterForFileURL:delegatesFileURL] ofType:filterType forFileURL:delegatesFileURL];
+#ifndef SP_REFACTOR
// Update global preferences' list
id cf = [[prefs objectForKey:SPContentFilters] mutableCopy];
[cf setObject:[self contentFilterForFileURL:nil] forKey:filterType];
@@ -370,6 +379,7 @@
if([[doc valueForKeyPath:@"tableContentInstance"] respondsToSelector:@selector(setCompareTypes:)])
[[doc valueForKeyPath:@"tableContentInstance"] setCompareTypes:nil];
+#endif
}
@@ -833,7 +843,7 @@
mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&convError] retain];
if(!spf || readError != nil || [convError length] || !(format == NSPropertyListXMLFormat_v1_0 || format == NSPropertyListBinaryFormat_v1_0)) {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:SP_FILE_PARSER_ERROR_TITLE_STRING]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:SP_FILE_PARSER_ERROR_TITLE_STRING]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
@@ -861,7 +871,7 @@
[contentFilterTableView reloadData];
[spf release];
} else {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:SP_FILE_PARSER_ERROR_TITLE_STRING]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:SP_FILE_PARSER_ERROR_TITLE_STRING]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
@@ -913,7 +923,7 @@
errorDescription:&err];
if(err != nil) {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Error while converting content filter data", @"Content filters could not be converted to plist upon export - message title (ContentFilterManager)")]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:NSLocalizedString(@"Error while converting content filter data", @"Content filters could not be converted to plist upon export - message title (ContentFilterManager)")]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
diff --git a/Source/SPCopyTable.h b/Source/SPCopyTable.h
index 4723dbc9..b7b5f77d 100644
--- a/Source/SPCopyTable.h
+++ b/Source/SPCopyTable.h
@@ -28,6 +28,7 @@
#define SP_MAX_CELL_WIDTH 400
@class SPDataStorage;
+@class SPTableContent;
/*!
@class copyTable
@@ -39,13 +40,15 @@
*/
@interface SPCopyTable : SPTableView
{
- id 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
SPDataStorage* tableStorage; // the underlying storage array holding the table data
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSRange fieldEditorSelectedRange;
NSString *copyBlobFileDirectory;
@@ -84,6 +87,7 @@
*/
- (NSUInteger)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
+#ifndef SP_REFACTOR /* method decls */
/*!
@method rowsAsTabStringWithHeaders:onlySelectedRows:
@abstract getter of the selected rows or all of the table for copy
@@ -105,6 +109,7 @@
@result The above described string, or nil if nothing selected
*/
- (NSString *)rowsAsCsvStringWithHeaders:(BOOL)withHeaders onlySelectedRows:(BOOL)onlySelected blobHandling:(NSInteger)withBlobHandling;
+#endif
/*
* Generate a string in form of INSERT INTO <table> VALUES () of
@@ -172,6 +177,8 @@
- (void)selectTableRows:(NSArray*)rowIndices;
+- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command;
+
@end
extern NSInteger MENU_EDIT_COPY;
diff --git a/Source/SPCopyTable.m b/Source/SPCopyTable.m
index b44ba920..f297ff76 100644
--- a/Source/SPCopyTable.m
+++ b/Source/SPCopyTable.m
@@ -23,7 +23,9 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#import <MCPKit/MCPKit.h>
+#ifndef SP_REFACTOR /* headers */
#import "MCPGeometryData.h"
+#endif
#import "SPCopyTable.h"
#import "SPTableContent.h"
@@ -67,8 +69,8 @@ NSInteger kBlobAsImageFile = 4;
return ([[self delegate] isKindOfClass:[SPCustomQuery class]]
|| ([[self delegate] isKindOfClass:[SPTableContent class]]
- && [[self delegate] valueForKeyPath:@"tablesListInstance"]
- && [[[self delegate] valueForKeyPath:@"tablesListInstance"] tableType] == SPTableTypeView));
+ && [(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"]
+ && [(SPTablesList*)([(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"]) tableType] == SPTableTypeView));
}
@@ -90,6 +92,7 @@ NSInteger kBlobAsImageFile = 4;
*/
- (void) copy:(id)sender
{
+#ifndef SP_REFACTOR /* copy table rows */
NSString *tmp = nil;
if([sender tag] == MENU_EDIT_COPY_AS_SQL) {
@@ -119,12 +122,14 @@ NSInteger kBlobAsImageFile = 4;
[pb setString:tmp forType:NSTabularTextPboardType];
}
}
+#endif
}
/**
* Get selected rows a string of newline separated lines of tab separated fields
* the value in each field is from the objects description method
*/
+#ifndef SP_REFACTOR /* get rows as string */
- (NSString *) rowsAsTabStringWithHeaders:(BOOL)withHeaders onlySelectedRows:(BOOL)onlySelected blobHandling:(NSInteger)withBlobHandling
{
if (onlySelected && [self numberOfSelectedRows] == 0) return nil;
@@ -397,6 +402,7 @@ NSInteger kBlobAsImageFile = 4;
return result;
}
+#endif
/*
* Return selected rows as SQL INSERT INTO `foo` VALUES (baz) string.
@@ -478,7 +484,7 @@ NSInteger kBlobAsImageFile = 4;
if ([cellData isSPNotLoaded] && [[self delegate] isKindOfClass:spTableContentClass]) {
// Abort if no table name given, not table content, or if there are no indices on this table
- if (!selectedTable || ![[self delegate] isKindOfClass:spTableContentClass] || ![[tableInstance argumentForRow:rowIndex] length]) {
+ if (!selectedTable || ![[self delegate] isKindOfClass:spTableContentClass] || ![(NSString*)[tableInstance argumentForRow:rowIndex] length]) {
NSBeep();
free(columnMappings);
free(columnTypes);
@@ -612,7 +618,11 @@ NSInteger kBlobAsImageFile = 4;
// Loop through the rows, adding their descriptive contents
NSUInteger rowIndex = [selectedRows firstIndex];
+#ifndef SP_REFACTOR
NSString *nullString = [prefs objectForKey:SPNullValue];
+#else
+ NSString *nullString = @"NULL";
+#endif
Class nsDataClass = [NSData class];
Class mcpGeometryData = [MCPGeometryData class];
NSStringEncoding connectionEncoding = [mySQLConnection stringEncoding];
@@ -753,7 +763,11 @@ NSInteger kBlobAsImageFile = 4;
NSUInteger cellWidth, maxCellWidth, i;
NSRange linebreakRange;
double rowStep;
+#ifndef SP_REFACTOR /* patch */
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]];
+#else
+ NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
+#endif
NSUInteger columnIndex = [[columnDefinition objectForKey:@"datacolumnindex"] unsignedIntegerValue];
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName];
Class mcpGeometryData = [MCPGeometryData class];
@@ -782,7 +796,11 @@ NSInteger kBlobAsImageFile = 4;
// Replace NULLs with their placeholder string
else if ([contentString isNSNull]) {
+#ifndef SP_REFACTOR /* patch */
contentString = [prefs objectForKey:SPNullValue];
+#else
+ contentString = @"NULL";
+#endif
// Same for cells for which loading has been deferred - likely blobs
} else if ([contentString isSPNotLoaded]) {
@@ -836,6 +854,7 @@ NSInteger kBlobAsImageFile = 4;
{
NSMenu *menu = [self menu];
+#ifndef SP_REFACTOR /* menuForEvent: */
if(![[self delegate] isKindOfClass:[SPCustomQuery class]] && ![[self delegate] isKindOfClass:[SPTableContent class]]) return menu;
@@ -903,7 +922,7 @@ NSInteger kBlobAsImageFile = 4;
[bundleSubMenuItem release];
}
-
+#endif
return menu;
}
@@ -914,7 +933,11 @@ NSInteger kBlobAsImageFile = 4;
if(!rowIndices || ![rowIndices count]) return;
NSMutableIndexSet *selection = [NSMutableIndexSet indexSet];
+#ifndef SP_REFACTOR
NSInteger rows = [[self delegate] numberOfRowsInTableView:self];
+#else
+ NSInteger rows = [(id<NSTableViewDataSource>)[self delegate] numberOfRowsInTableView:self];
+#endif
NSInteger i;
if(rows > 0) {
for(NSString* idx in rowIndices) {
@@ -934,6 +957,7 @@ NSInteger kBlobAsImageFile = 4;
*/
- (BOOL) validateMenuItem:(NSMenuItem*)anItem
{
+#ifndef SP_REFACTOR /* validateMenuItem: */
NSInteger menuItemTag = [anItem tag];
if ([anItem action] == @selector(performFindPanelAction:)) {
@@ -959,7 +983,7 @@ NSInteger kBlobAsImageFile = 4;
if (menuItemTag == MENU_EDIT_COPY_AS_SQL) {
return (columnDefinitions != nil && [self numberOfSelectedRows] > 0);
}
-
+#endif
return NO;
}
@@ -984,7 +1008,7 @@ NSInteger kBlobAsImageFile = 4;
// Save the current line if it's the last field in the table
if ( [self numberOfColumns] - 1 == column ) {
if([[self delegate] respondsToSelector:@selector(saveRowToTable)])
- [[self delegate] saveRowToTable];
+ [(SPTableContent*)[self delegate] saveRowToTable];
[[self window] makeFirstResponder:self];
} else {
// Select the next field for editing
@@ -1002,7 +1026,7 @@ NSInteger kBlobAsImageFile = 4;
// Save the current line if it's the last field in the table
if ( column < 1 ) {
if([[self delegate] respondsToSelector:@selector(saveRowToTable)])
- [[self delegate] saveRowToTable];
+ [(SPTableContent*)([self delegate]) saveRowToTable];
[[self window] makeFirstResponder:self];
} else {
// Select the previous field for editing
@@ -1021,7 +1045,7 @@ NSInteger kBlobAsImageFile = 4;
[[control window] makeFirstResponder:control];
if([[self delegate] isKindOfClass:[SPTableContent class]] && ![self isCellEditingMode] && [[self delegate] respondsToSelector:@selector(saveRowToTable)])
- [[self delegate] saveRowToTable];
+ [(SPTableContent*)[self delegate] saveRowToTable];
return YES;
}
@@ -1035,14 +1059,22 @@ NSInteger kBlobAsImageFile = 4;
return NO;
NSInteger newRow = row+1;
+#ifndef SP_REFACTOR
if (newRow>=[[self delegate] numberOfRowsInTableView:self]) return YES; //check if we're already at the end of the list
+#else
+ if (newRow>=[(id<NSTableViewDataSource>)[self delegate] numberOfRowsInTableView:self]) return YES; //check if we're already at the end of the list
+#endif
[[control window] makeFirstResponder:control];
if([[self delegate] isKindOfClass:[SPTableContent class]] && ![self isCellEditingMode] && [[self delegate] respondsToSelector:@selector(saveRowToTable)])
- [[self delegate] saveRowToTable];
+ [(SPTableContent*)([self delegate]) saveRowToTable];
+#ifndef SP_REFACTOR
if (newRow>=[[self delegate] numberOfRowsInTableView:self]) return YES; //check again. saveRowToTable could reload the table and change the number of rows
- if (tableStorage && column >= (NSInteger)[tableStorage columnCount]) return YES; //the column count could change too
+#else
+ if (newRow>=[(id<NSTableViewDataSource>)[self delegate] numberOfRowsInTableView:self]) return YES; //check again. saveRowToTable could reload the table and change the number of rows
+#endif
+ if (tableStorage && (NSUInteger)column>=[tableStorage columnCount]) return YES; //the column count could change too
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
[self editColumn:column row:newRow withEvent:nil select:YES];
@@ -1062,10 +1094,14 @@ NSInteger kBlobAsImageFile = 4;
[[control window] makeFirstResponder:control];
if([[self delegate] isKindOfClass:[SPTableContent class]] && ![self isCellEditingMode] && [[self delegate] respondsToSelector:@selector(saveRowToTable)])
- [[self delegate] saveRowToTable];
+ [(SPTableContent*)([self delegate]) saveRowToTable];
+#ifndef SP_REFACTOR
if (newRow>=[[self delegate] numberOfRowsInTableView:self]) return YES; // saveRowToTable could reload the table and change the number of rows
- if (tableStorage && column >= (NSInteger)[tableStorage columnCount]) return YES; //the column count could change too
+#else
+ if (newRow>=[(id<NSTableViewDataSource>)[self delegate] numberOfRowsInTableView:self]) return YES; // saveRowToTable could reload the table and change the number of rows
+#endif
+ if (tableStorage && (NSUInteger)column>=[tableStorage columnCount]) return YES; //the column count could change too
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
[self editColumn:column row:newRow withEvent:nil select:YES];
@@ -1089,7 +1125,7 @@ NSInteger kBlobAsImageFile = 4;
// Check if ESCAPE is hit and use it to cancel row editing if supported
if ([theEvent keyCode] == 53 && [[self delegate] respondsToSelector:@selector(cancelRowEditing)])
{
- if ([[self delegate] cancelRowEditing]) return;
+ if ([[self delegate] performSelector:@selector(cancelRowEditing)]) return;
}
else if ([theEvent keyCode] == 48 && ([[self delegate] isKindOfClass:[SPCustomQuery class]]
@@ -1104,7 +1140,7 @@ NSInteger kBlobAsImageFile = 4;
- (void)performFindPanelAction:(id)sender
{
if([sender tag] == 1 && [[self delegate] isKindOfClass:[SPTableContent class]]) {
- [[self delegate] showFilterTable:self];
+ [(SPTableContent*)[self delegate] showFilterTable:self];
}
}
@@ -1113,6 +1149,7 @@ NSInteger kBlobAsImageFile = 4;
- (IBAction)executeBundleItemForDataTable:(id)sender
{
+#ifndef SP_REFACTOR /* executeBundleItemForDataTable: */
NSInteger idx = [sender tag] - 1000000;
NSString *infoPath = nil;
NSArray *bundleItems = [[NSApp delegate] bundleItemsForScope:SPBundleScopeDataTable];
@@ -1389,7 +1426,7 @@ NSInteger kBlobAsImageFile = 4;
if (cmdData) [cmdData release];
}
-
+#endif
}
#pragma mark -
@@ -1397,7 +1434,9 @@ NSInteger kBlobAsImageFile = 4;
- (void) awakeFromNib
{
columnDefinitions = nil;
+#ifndef SP_REFACTOR
prefs = [[NSUserDefaults standardUserDefaults] retain];
+#endif
if ([NSTableView instancesRespondToSelector:@selector(awakeFromNib)])
[super awakeFromNib];
@@ -1407,7 +1446,9 @@ NSInteger kBlobAsImageFile = 4;
- (void) dealloc
{
if (columnDefinitions) [columnDefinitions release];
+#ifndef SP_REFACTOR
[prefs release];
+#endif
[super dealloc];
}
diff --git a/Source/SPCustomQuery.h b/Source/SPCustomQuery.h
index 68969a01..fde7068e 100644
--- a/Source/SPCustomQuery.h
+++ b/Source/SPCustomQuery.h
@@ -46,9 +46,17 @@
#define SP_HISTORY_SAVE_MENUITEM_TAG 300001
#define SP_HISTORY_CLEAR_MENUITEM_TAG 300002
+#ifndef SP_REFACTOR
@class SPCopyTable, SPQueryFavoriteManager, SPDataStorage, BWSplitView, SPFieldEditorController;
+#else
+@class SPCopyTable, SPQueryFavoriteManager, SPDataStorage, NSSplitView, SPFieldEditorController;
+#endif
+#ifndef SP_REFACTOR
@interface SPCustomQuery : NSObject
+#else
+@interface SPCustomQuery : NSObject <NSTableViewDataSource, NSWindowDelegate, NSTableViewDelegate>
+#endif
{
IBOutlet id tableDocumentInstance;
IBOutlet id tablesListInstance;
@@ -101,21 +109,29 @@
IBOutlet NSMenuItem *previousHistoryMenuItem;
IBOutlet NSMenuItem *nextHistoryMenuItem;
+#ifndef SP_REFACTOR
IBOutlet NSWindow *helpWebViewWindow;
IBOutlet WebView *helpWebView;
IBOutlet NSSearchField *helpSearchField;
IBOutlet NSSearchFieldCell *helpSearchFieldCell;
IBOutlet NSSegmentedControl *helpNavigator;
IBOutlet NSSegmentedControl *helpTargetSelector;
+#endif
IBOutlet NSButton *queryInfoButton;
+#ifndef SP_REFACTOR
IBOutlet BWSplitView *queryInfoPaneSplitView;
+#else
+ IBOutlet NSSplitView *queryInfoPaneSplitView;
+#endif
SPFieldEditorController *fieldEditor;
SPQueryFavoriteManager *favoritesManager;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
MCPConnection *mySQLConnection;
NSString *usedQuery;
@@ -129,9 +145,11 @@
NSUInteger queryStartPosition;
+#ifndef SP_REFACTOR
NSUInteger helpTarget;
WebHistory *helpHistory;
NSString *helpHTMLTemplate;
+#endif
SPDataStorage *resultData;
pthread_mutex_t resultDataLock;
@@ -181,6 +199,7 @@
- (IBAction)chooseQueryHistory:(id)sender;
- (IBAction)closeSheet:(id)sender;
- (IBAction)gearMenuItemSelected:(id)sender;
+#ifndef SP_REFACTOR
- (IBAction)showHelpForCurrentWord:(id)sender;
- (IBAction)showHelpForSearchString:(id)sender;
- (IBAction)helpSegmentDispatcher:(id)sender;
@@ -190,6 +209,7 @@
- (IBAction)helpSelectHelpTargetMySQL:(id)sender;
- (IBAction)helpSelectHelpTargetPage:(id)sender;
- (IBAction)helpSelectHelpTargetWeb:(id)sender;
+#endif
- (IBAction)filterQueryFavorites:(id)sender;
- (IBAction)filterQueryHistory:(id)sender;
- (IBAction)saveQueryHistory:(id)sender;
@@ -226,6 +246,7 @@
- (void) clearResultViewDetailsToRestore;
- (void) autosizeColumns;
+#ifndef SP_REFACTOR
// MySQL Help
- (void)showAutoHelpForCurrentWord:(id)sender;
- (NSString *)getHTMLformattedMySQLHelpFor:(NSString *)searchString calledByAutoHelp:(BOOL)autoHelp;
@@ -233,6 +254,7 @@
- (void)helpTargetValidation;
- (void)openMySQLonlineDocumentationWithString:(NSString *)searchString;
- (NSWindow *)helpWebViewWindow;
+#endif
- (void)setMySQLversion:(NSString *)theVersion;
// Task interaction
diff --git a/Source/SPCustomQuery.m b/Source/SPCustomQuery.m
index 2c9e890e..732ed5db 100644
--- a/Source/SPCustomQuery.m
+++ b/Source/SPCustomQuery.m
@@ -25,7 +25,9 @@
#import "SPCustomQuery.h"
#import "SPSQLParser.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPGrowlController.h"
+#endif
#import "SPDataCellFormatter.h"
#import "SPDatabaseDocument.h"
#import "SPTablesList.h"
@@ -43,7 +45,9 @@
#import "SPAppController.h"
#import "SPBundleHTMLOutputController.h"
+#ifndef SP_REFACTOR /* headers */
#import <BWToolkitFramework/BWToolkitFramework.h>
+#endif
@implementation SPCustomQuery
@@ -212,7 +216,9 @@
return;
}
+#ifndef SP_REFACTOR /* ui manip for query favorites */
if ([tableDocumentInstance isUntitled]) [saveQueryFavoriteGlobal setState:NSOnState];
+#endif
[NSApp beginSheet:queryFavoritesSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
@@ -230,7 +236,9 @@
return;
}
+#ifndef SP_REFACTOR /* ui manip for query favorites */
if ([tableDocumentInstance isUntitled]) [saveQueryFavoriteGlobal setState:NSOnState];
+#endif
[NSApp beginSheet:queryFavoritesSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
@@ -240,7 +248,9 @@
else if ([queryFavoritesButton indexOfSelectedItem] == 3) {
// init query favorites controller
+#ifndef SP_REFACTOR
[prefs synchronize];
+#endif
if(favoritesManager) [favoritesManager release];
favoritesManager = [[SPQueryFavoriteManager alloc] initWithDelegate:self];
@@ -253,7 +263,11 @@
}
else if ([queryFavoritesButton indexOfSelectedItem] > 5) {
// Choose favorite
+#ifndef SP_REFACTOR
BOOL replaceContent = [prefs boolForKey:SPQueryFavoriteReplacesContent];
+#else
+ BOOL replaceContent = YES;
+#endif
if([[NSApp currentEvent] modifierFlags] & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask))
replaceContent = !replaceContent;
@@ -274,12 +288,18 @@
- (IBAction)chooseQueryHistory:(id)sender
{
+#ifndef SP_REFACTOR
[prefs synchronize];
+#endif
// Choose history item
if ([queryHistoryButton indexOfSelectedItem] > 6) {
+#ifndef SP_REFACTOR
BOOL replaceContent = [prefs boolForKey:SPQueryHistoryReplacesContent];
+#else
+ BOOL replaceContent = YES;
+#endif
[textView breakUndoCoalescing];
if([[NSApp currentEvent] modifierFlags] & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask))
replaceContent = !replaceContent;
@@ -382,8 +402,10 @@
// "Indent new lines" toggle
if (sender == autoindentMenuItem) {
BOOL enableAutoindent = !([autoindentMenuItem state] == NSOffState);
+#ifndef SP_REFACTOR /* prefs access */
[prefs setBool:enableAutoindent forKey:SPCustomQueryAutoIndent];
[prefs synchronize];
+#endif
[autoindentMenuItem setState:enableAutoindent?NSOnState:NSOffState];
[textView setAutoindent:enableAutoindent];
}
@@ -391,12 +413,15 @@
// "Auto-pair characters" toggle
if (sender == autopairMenuItem) {
BOOL enableAutopair = !([autopairMenuItem state] == NSOffState);
+#ifndef SP_REFACTOR /* prefs access */
[prefs setBool:enableAutopair forKey:SPCustomQueryAutoPairCharacters];
[prefs synchronize];
+#endif
[autopairMenuItem setState:enableAutopair?NSOnState:NSOffState];
[textView setAutopair:enableAutopair];
}
+#ifndef SP_REFACTOR /* prefs access */
// "Auto-help" toggle
if (sender == autohelpMenuItem) {
BOOL enableAutohelp = !([autohelpMenuItem state] == NSOffState);
@@ -405,12 +430,15 @@
[autohelpMenuItem setState:enableAutohelp?NSOnState:NSOffState];
[textView setAutohelp:enableAutohelp];
}
+#endif
// "Auto-uppercase keywords" toggle
if (sender == autouppercaseKeywordsMenuItem) {
BOOL enableAutouppercaseKeywords = !([autouppercaseKeywordsMenuItem state] == NSOffState);
+#ifndef SP_REFACTOR /* prefs access */
[prefs setBool:enableAutouppercaseKeywords forKey:SPCustomQueryAutoUppercaseKeywords];
[prefs synchronize];
+#endif
[autouppercaseKeywordsMenuItem setState:enableAutouppercaseKeywords?NSOnState:NSOffState];
[textView setAutouppercaseKeywords:enableAutouppercaseKeywords];
}
@@ -418,6 +446,7 @@
- (IBAction)saveQueryHistory:(id)sender
{
+#ifndef SP_REFACTOR
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setRequiredFileType:SPFileExtensionSQL];
@@ -432,6 +461,7 @@
[encodingPopUp setEnabled:YES];
[panel beginSheetForDirectory:nil file:@"history" modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:) contextInfo:@"saveHistory"];
+#endif
}
- (IBAction)copyQueryHistory:(id)sender
@@ -450,10 +480,14 @@
NSString *infoString;
+#ifndef SP_REFACTOR /* if ([tableDocumentInstance isUntitled]) */
if ([tableDocumentInstance isUntitled])
+#endif
infoString = NSLocalizedString(@"Are you sure you want to clear the global history list? This action cannot be undone.", @"clear global history list informative message");
+#ifndef SP_REFACTOR /* if ([tableDocumentInstance isUntitled]) */
else
infoString = [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to clear the history list for “%@”? This action cannot be undone.", @"clear history list for “%@” informative message"), [tableDocumentInstance displayName]];
+#endif
NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Clear History?", @"clear history message")
defaultButton:NSLocalizedString(@"Clear", @"clear button")
@@ -545,13 +579,17 @@
// BOOL queriesSeparatedByDelimiter = NO;
NSCharacterSet *whitespaceAndNewlineSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
+#ifndef SP_REFACTOR /* [tableDocumentInstance setQueryMode:] */
[tableDocumentInstance setQueryMode:SPCustomQueryQueryMode];
+#endif
// Notify listeners that a query has started
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryWillBePerformed" object:tableDocumentInstance];
+#ifndef SP_REFACTOR /* growl */
// Start the notification timer to allow notifications to be shown even if frontmost for long queries
[[SPGrowlController sharedGrowlController] setVisibilityForNotificationName:@"Query Finished"];
+#endif
// Reset the current table view as necessary to avoid redraw and reload issues.
// Restore the view position to the top left to be within the results for all datasets.
@@ -804,7 +842,9 @@
// Restore automatic query retries
[mySQLConnection setAllowQueryRetries:YES];
+#ifndef SP_REFACTOR /* [tableDocumentInstance setQueryMode:] */
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
+#endif
// If no results were returned, redraw the empty table and post notifications before returning.
if ( !resultDataCount ) {
@@ -813,11 +853,13 @@
// Notify any listeners that the query has completed
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
+#ifndef SP_REFACTOR /* growl */
// Perform the Growl notification for query completion
[[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText string]]
document:tableDocumentInstance
notificationName:@"Query Finished"];
+#endif
// Set up the callback if present
if ([taskArguments objectForKey:@"callback"]) {
@@ -844,11 +886,13 @@
//query finished
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
+#ifndef SP_REFACTOR /* growl */
// Query finished Growl notification
[[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText string]]
document:tableDocumentInstance
notificationName:@"Query Finished"];
+#endif
// Set up the callback if present
if ([taskArguments objectForKey:@"callback"]) {
@@ -1112,7 +1156,7 @@
}
/*
- * Add or remove "⁄* *⁄" for each line in the current query
+ * Add or remove "‚ÅÑ* *‚ÅÑ" for each line in the current query
* a given selection
*/
- (void)commentOutCurrentQueryTakingSelection:(BOOL)takeSelection
@@ -1165,8 +1209,8 @@
/*
* Add or remove "-- " for each line in the current query or selection,
- * if the selection is in-line wrap selection into ⁄* block comments and
- * place the caret after ⁄* to allow to enter !xxxxxx e.g.
+ * if the selection is in-line wrap selection into ‚ÅÑ* block comments and
+ * place the caret after ‚ÅÑ* to allow to enter !xxxxxx e.g.
*/
- (void)commentOut
{
@@ -1297,6 +1341,7 @@
[errorText setString:NSLocalizedString(@"There were no errors.", @"text shown when query was successfull")];
}
+#ifndef SP_REFACTOR /* show/hide errror view */
// Show or hide the error area if necessary
if ([errorsString length] && [queryInfoPaneSplitView collapsibleSubviewCollapsed]) {
[queryInfoButton setState:NSOnState];
@@ -1305,6 +1350,7 @@
[queryInfoButton setState:NSOffState];
[self toggleQueryInfoPaneCollapse:queryInfoButton];
}
+#endif
}
#pragma mark -
@@ -1429,16 +1475,25 @@
// Set up the interface
[customQueryView setVerticalMotionCanBeginDrag:NO];
+#ifndef SP_REFACTOR
[autoindentMenuItem setState:([prefs boolForKey:SPCustomQueryAutoIndent]?NSOnState:NSOffState)];
[autopairMenuItem setState:([prefs boolForKey:SPCustomQueryAutoPairCharacters]?NSOnState:NSOffState)];
[autohelpMenuItem setState:([prefs boolForKey:SPCustomQueryUpdateAutoHelp]?NSOnState:NSOffState)];
[autouppercaseKeywordsMenuItem setState:([prefs boolForKey:SPCustomQueryAutoUppercaseKeywords]?NSOnState:NSOffState)];
+#else
+ [autoindentMenuItem setState:(YES?NSOnState:NSOffState)];
+ [autopairMenuItem setState:(YES?NSOnState:NSOffState)];
+ [autohelpMenuItem setState:(YES?NSOnState:NSOffState)];
+ [autouppercaseKeywordsMenuItem setState:(YES?NSOnState:NSOffState)];
+#endif
if ( [[SPQueryController sharedQueryController] historyForFileURL:[tableDocumentInstance fileURL]] )
[self performSelectorOnMainThread:@selector(historyItemsHaveBeenUpdated:) withObject:self waitUntilDone:YES];
// Populate query favorites
+#ifndef SP_REFACTOR
[self queryFavoritesHaveBeenUpdated:nil];
+#endif
// Disable runSelectionMenuItem in the gear menu
[runSelectionMenuItem setEnabled:NO];
@@ -1487,7 +1542,11 @@
}
// Update font size on the table
+#ifndef SP_REFACTOR
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]];
+#else
+ NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
+#endif
[customQueryView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{ǞṶḹÜ∑zgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
// If there are no table columns to add, return
@@ -1523,8 +1582,9 @@
[[dataCell formatter] setFieldType:[columnDefinition objectForKey:@"type"]];
[theCol setDataCell:dataCell];
[[theCol headerCell] setStringValue:[columnDefinition objectForKey:@"name"]];
- [theCol setHeaderToolTip:[NSString stringWithFormat:@"%@ – %@%@", [columnDefinition objectForKey:@"name"], [columnDefinition objectForKey:@"type"], ([columnDefinition objectForKey:@"char_length"]) ? [NSString stringWithFormat:@"(%@)", [columnDefinition objectForKey:@"char_length"]] : @""]];
+ [theCol setHeaderToolTip:[NSString stringWithFormat:@"%@ – %@%@", [columnDefinition objectForKey:@"name"], [columnDefinition objectForKey:@"type"], ([columnDefinition objectForKey:@"char_length"]) ? [NSString stringWithFormat:@"(%@)", [columnDefinition objectForKey:@"char_length"]] : @""]];
+#ifndef SP_REFACTOR
// Set the width of this column to saved value if exists and maps to a real column
if ([columnDefinition objectForKey:@"org_name"] && [(NSString *)[columnDefinition objectForKey:@"org_name"] length]) {
NSNumber *colWidth = [[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [columnDefinition objectForKey:@"db"], [tableDocumentInstance host]]] objectForKey:[columnDefinition objectForKey:@"org_table"]] objectForKey:[columnDefinition objectForKey:@"org_name"]];
@@ -1532,6 +1592,7 @@
[theCol setWidth:[colWidth floatValue]];
}
}
+#endif
[customQueryView addTableColumn:theCol];
[theCol release];
@@ -1619,8 +1680,10 @@
[customQueryView setDelegate:nil];
for (NSDictionary *columnDefinition in cqColumnDefinition) {
+#ifndef SP_REFACTOR
// Skip columns with saved widths
if ([[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]]] objectForKey:[tablesListInstance tableName]] objectForKey:[columnDefinition objectForKey:@"name"]]) continue;
+#endif
// Otherwise set the column width
NSTableColumn *aTableColumn = [customQueryView tableColumnWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
@@ -1888,7 +1951,11 @@
return [theValue shortStringRepresentationUsingEncoding:[mySQLConnection stringEncoding]];
if ([theValue isNSNull])
+#ifndef SP_REFACTOR
return [prefs objectForKey:SPNullValue];
+#else
+ return @"NULL";
+#endif
if ([theValue isKindOfClass:[MCPGeometryData class]])
return [theValue wktString];
@@ -1943,7 +2010,13 @@
} else {
if ( [[anObject description] isEqualToString:@"CURRENT_TIMESTAMP"] ) {
newObject = @"CURRENT_TIMESTAMP";
- } else if([anObject isEqualToString:[prefs stringForKey:SPNullValue]]) {
+ } else if([anObject isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs stringForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]) {
newObject = @"NULL";
} else if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"geometry"]) {
newObject = [(NSString*)anObject getGeomFromTextString];
@@ -1970,26 +2043,32 @@
return;
}
- // This shouldn't happen – for safety reasons
+ // This shouldn't happen – for safety reasons
if ( ![mySQLConnection affectedRows] ) {
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPShowNoAffectedRowsError] ) {
SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
NSLocalizedString(@"The row was not written to the MySQL database. You probably haven't changed anything.\nReload the table to be sure that the row exists and use a primary key for your table.\n(This error can be turned off in the preferences.)", @"message of panel when no rows have been affected after writing to the db"));
} else {
NSBeep();
}
+#endif
return;
}
// On success reload table data by executing the last query if reloading is enabled
+#ifndef SP_REFACTOR
if ([prefs boolForKey:SPReloadAfterEditingRow]) {
reloadingExistingResult = YES;
[self storeCurrentResultViewForRestoration];
[self performQueries:[NSArray arrayWithObject:lastExecutedQuery] withCallback:NULL];
} else {
+#endif
// otherwise, just update the data in the data storage
SPDataStorageReplaceObjectAtRowAndColumn(resultData, rowIndex, [[aTableColumn identifier] intValue], anObject);
+#ifndef SP_REFACTOR
}
+#endif
} else {
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"Updating field content failed. Couldn't identify field origin unambiguously (%ld match%@). It's very likely that while editing this field of table `%@` was changed.", @"message of panel when error while updating field to db after enabling it"),
@@ -2362,7 +2441,11 @@
id originalData = [resultData cellDataAtRow:rowIndex column:[[aTableColumn identifier] integerValue]];
if ([originalData isNSNull])
+#ifndef SP_REFACTOR
originalData = [NSString stringWithString:[prefs objectForKey:SPNullValue]];
+#else
+ originalData = [NSString stringWithString:@"NULL"];
+#endif
[fieldEditor editWithObject:originalData
fieldName:[columnDefinition objectForKey:@"name"]
@@ -2407,6 +2490,7 @@
// Check our notification object is our table content view
if ([aNotification object] != customQueryView) return;
+#ifndef SP_REFACTOR /* triggered commands */
NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged];
for(NSString* cmdPath in triggeredCommands) {
NSArray *data = [cmdPath componentsSeparatedByString:@"|"];
@@ -2443,7 +2527,7 @@
}
}
}
-
+#endif
}
/**
@@ -2468,11 +2552,15 @@
NSString *col = [columnDefinition objectForKey:@"org_name"];
// Retrieve or instantiate the tableColumnWidths object
+#ifndef SP_REFACTOR
if ([prefs objectForKey:SPTableColumnWidths] != nil) {
tableColumnWidths = [NSMutableDictionary dictionaryWithDictionary:[prefs objectForKey:SPTableColumnWidths]];
} else {
+#endif
tableColumnWidths = [NSMutableDictionary dictionary];
+#ifndef SP_REFACTOR
}
+#endif
// Edit or create database object
if ([tableColumnWidths objectForKey:host_db] == nil) {
@@ -2490,7 +2578,9 @@
// Save the column size
[[[tableColumnWidths objectForKey:host_db] objectForKey:table] setObject:[NSNumber numberWithDouble:[(NSTableColumn *)[[aNotification userInfo] objectForKey:@"NSTableColumn"] width]] forKey:col];
+#ifndef SP_REFACTOR
[prefs setObject:tableColumnWidths forKey:SPTableColumnWidths];
+#endif
}
/**
@@ -2505,6 +2595,7 @@
NSUInteger targetWidth = [customQueryView autodetectWidthForColumnDefinition:columnDefinition maxRows:500];
// Clear any saved widths for the column
+#ifndef SP_REFACTOR
NSString *dbKey = [NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]];
NSString *tableKey = [tablesListInstance tableName];
NSMutableDictionary *savedWidths = [NSMutableDictionary dictionaryWithDictionary:[prefs objectForKey:SPTableColumnWidths]];
@@ -2524,6 +2615,7 @@
}
[prefs setObject:[NSDictionary dictionaryWithDictionary:savedWidths] forKey:SPTableColumnWidths];
}
+#endif
// Return the width, while the delegate is empty to prevent column resize notifications
[customQueryView setDelegate:nil];
@@ -2671,6 +2763,8 @@
#pragma mark -
#pragma mark SplitView delegate methods
+#ifndef SP_REFACTOR /* splitview delegate methods */
+
/*
* Tells the splitView that it can collapse views
*/
@@ -2705,6 +2799,8 @@
return (splitView == queryInfoPaneSplitView ? NSZeroRect : proposedEffectiveRect);
}
+#endif
+
#pragma mark -
#pragma mark MySQL Help
@@ -2718,6 +2814,7 @@
}
+#ifndef SP_REFACTOR
/*
* Return the Help window.
*/
@@ -2912,6 +3009,7 @@
helpTarget = [helpTargetSelector selectedSegment];
[self helpTargetValidation];
}
+#endif
- (IBAction)showCompletionList:(id)sender
{
@@ -2928,6 +3026,8 @@
break;
}
}
+
+#ifndef SP_REFACTOR
/*
* Show the data for "HELP 'currentWord' invoked by autohelp"
*/
@@ -3047,7 +3147,7 @@
aRange = [desc rangeOfRegex:@"\\[HELP ([^ ]*?)\\]" options:RKLNoOptions inRange:NSMakeRange(aRange.location+aRange.length+53, [desc length]-53-aRange.location-aRange.length) capture:1 error:&err1];
if(aRange.location != NSNotFound) {
aUrl = [[desc substringWithRange:aRange] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
- [desc replaceCharactersInRange:aRange withString:[NSString stringWithFormat:@"<a title='%@ “%@”' href='%@' class='internallink'>%@</a>", NSLocalizedString(@"Show MySQL help for", @"show mysql help for"), aUrl, aUrl, aUrl]];
+ [desc replaceCharactersInRange:aRange withString:[NSString stringWithFormat:@"<a title='%@ “%@”' href='%@' class='internallink'>%@</a>", NSLocalizedString(@"Show MySQL help for", @"show mysql help for"), aUrl, aUrl, aUrl]];
}
else
break;
@@ -3062,7 +3162,7 @@
// aRange = [desc rangeOfRegex:@"(?<!\\w)([A-Z_]{2,}( [A-Z_]{2,})?)" options:RKLNoOptions inRange:NSMakeRange(aRange.location+aRange.length, [desc length]-aRange.location-aRange.length) capture:1 error:&err1];
// if(aRange.location != NSNotFound) {
// aUrl = [desc substringWithRange:aRange];
- // [desc replaceCharactersInRange:aRange withString:[NSString stringWithFormat:@"<a title='%@ “%@”' href='%@' class='internallink'>%@</a>", NSLocalizedString(@"Show MySQL help for", @"show mysql help for"), aUrl, aUrl, aUrl]];
+ // [desc replaceCharactersInRange:aRange withString:[NSString stringWithFormat:@"<a title='%@ “%@”' href='%@' class='internallink'>%@</a>", NSLocalizedString(@"Show MySQL help for", @"show mysql help for"), aUrl, aUrl, aUrl]];
// }
// else
// break;
@@ -3086,16 +3186,16 @@
if (r) [theResult dataSeek:0];
// check if HELP 'contents' is called
if(![searchString isEqualToString:SP_HELP_TOC_SEARCH_STRING])
- [theHelp appendFormat:@"<br><i>%@ “%@”</i><br>", NSLocalizedString(@"Help topics for", @"help topics for"), searchString];
+ [theHelp appendFormat:@"<br><i>%@ “%@”</i><br>", NSLocalizedString(@"Help topics for", @"help topics for"), searchString];
else
- [theHelp appendFormat:@"<br><b>%@:</b><br>", NSLocalizedString(@"MySQL Help – Categories", @"mysql help categories"), searchString];
+ [theHelp appendFormat:@"<br><b>%@:</b><br>", NSLocalizedString(@"MySQL Help – Categories", @"mysql help categories"), searchString];
// iterate through all found rows and print them as HTML ul/li list
[theHelp appendString:@"<ul>"];
for ( i = 0 ; i < r ; i++ ) {
NSArray *anArray = [theResult fetchRowAsArray];
NSString *topic = [anArray objectAtIndex:[anArray count]-2];
- [theHelp appendFormat:@"<li><a title='%@ “%@”' href='%@' class='internallink'>%@</a></li>",
+ [theHelp appendFormat:@"<li><a title='%@ “%@”' href='%@' class='internallink'>%@</a></li>",
NSLocalizedString(@"Show MySQL help for", @"show mysql help for"), topic, topic, topic];
}
[theHelp appendString:@"</ul>"];
@@ -3236,6 +3336,8 @@
return YES;
}
+#endif
+
#pragma mark -
#pragma mark Query favorites manager delegate methods
@@ -3275,7 +3377,7 @@
[[[[tableDocumentInstance fileURL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] lastPathComponent]
action:NULL keyEquivalent:@""];
[headerMenuItem setTag:SP_FAVORITE_HEADER_MENUITEM_TAG];
- [headerMenuItem setToolTip:[NSString stringWithFormat:@"‘%@’ based favorites",
+ [headerMenuItem setToolTip:[NSString stringWithFormat:@"‘%@’ based favorites",
[[[[tableDocumentInstance fileURL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] lastPathComponent]]];
[headerMenuItem setIndentationLevel:0];
[menu addItem:headerMenuItem];
@@ -3287,7 +3389,7 @@
[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]
- initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@⇥", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"]
+ initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@‚á•", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"]
attributes:attributes] autorelease];
NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
[item setToolTip:[NSString stringWithString:[favorite objectForKey:@"query"]]];
@@ -3304,6 +3406,7 @@
[headerMenuItem setIndentationLevel:0];
[menu addItem:headerMenuItem];
[headerMenuItem release];
+#ifndef SP_REFACTOR
for (NSDictionary *favorite in [prefs objectForKey:SPQueryFavorites]) {
if (![favorite isKindOfClass:[NSDictionary class]] || ![favorite objectForKey:@"name"]) continue;
NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
@@ -3311,7 +3414,7 @@
[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]
- initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@⇥", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"]
+ initWithString:([favorite objectForKey:@"tabtrigger"] && [(NSString*)[favorite objectForKey:@"tabtrigger"] length]) ? [NSString stringWithFormat:@"%@\t%@‚á•", [favorite objectForKey:@"name"], [favorite objectForKey:@"tabtrigger"]] : [favorite objectForKey:@"name"]
attributes:attributes] autorelease];
NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
[item setToolTip:[NSString stringWithString:[favorite objectForKey:@"query"]]];
@@ -3320,6 +3423,7 @@
[menu addItem:item];
[item release];
}
+#endif
}
#pragma mark -
@@ -3332,9 +3436,11 @@
{
isWorking = YES;
+#ifndef SP_REFACTOR /* check selected view */
// Only proceed if this view is selected.
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarCustomQuery])
return;
+#endif
tableRowsSelectable = NO;
[runSelectionButton setEnabled:NO];
@@ -3350,9 +3456,11 @@
{
isWorking = NO;
+#ifndef SP_REFACTOR /* check active tab */
// Only proceed if this view is selected.
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarCustomQuery])
return;
+#endif
if (selectionButtonCanBeEnabled) {
[runSelectionButton setEnabled:YES];
@@ -3408,7 +3516,7 @@
// Result Table Font preference changed
else if ([keyPath isEqualToString:SPGlobalResultTableFont]) {
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]];
- [customQueryView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{ǞṶḹÜ∑zgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
+ [customQueryView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{«û·π∂·∏π√ú‚àëzgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
[customQueryView setFont:tableFont];
[customQueryView reloadData];
}
@@ -3435,6 +3543,7 @@
if ([contextInfo isEqualToString:@"addAllToNewQueryFavorite"] || [contextInfo isEqualToString:@"addSelectionToNewQueryFavorite"]) {
if (returnCode == NSOKButton) {
+#ifndef SP_REFACTOR
// Add the new query favorite directly the user's preferences here instead of asking the manager to do it
// as it may not have been fully initialized yet.
@@ -3472,6 +3581,7 @@
[saveQueryFavoriteGlobal setState:NSOffState];
[self queryFavoritesHaveBeenUpdated:nil];
+#endif
}
}
@@ -3485,8 +3595,10 @@
if (returnCode == NSOKButton) {
NSError *error = nil;
+#ifndef SP_REFACTOR
[prefs setInteger:[[encodingPopUp selectedItem] tag] forKey:SPLastSQLFileEncoding];
[prefs synchronize];
+#endif
[[self buildHistoryString] writeToFile:[panel filename]
atomically:YES
@@ -3524,13 +3636,17 @@
}
// Control Clear History menu item title according to isUntitled
else if ( [menuItem tag] == SP_HISTORY_CLEAR_MENUITEM_TAG ) {
+#ifndef SP_REFACTOR /* if ( [tableDocumentInstance isUntitled] ) */
if ( [tableDocumentInstance isUntitled] ) {
+#endif
[menuItem setTitle:NSLocalizedString(@"Clear Global History", @"clear global history menu item title")];
[menuItem setToolTip:NSLocalizedString(@"Clear the global history list", @"clear the global history list tooltip message")];
+#ifndef SP_REFACTOR /* if ( [tableDocumentInstance isUntitled] ) */
} else {
- [menuItem setTitle:[NSString stringWithFormat:NSLocalizedString(@"Clear History for “%@”", @"clear history for “%@” menu title"), [tableDocumentInstance displayName]]];
+ [menuItem setTitle:[NSString stringWithFormat:NSLocalizedString(@"Clear History for “%@”", @"clear history for “%@” menu title"), [tableDocumentInstance displayName]]];
[menuItem setToolTip:NSLocalizedString(@"Clear the document-based history list", @"clear the document-based history list tooltip message")];
}
+#endif
}
// Check for History items
else if ( [menuItem tag] >= SP_HISTORY_COPY_MENUITEM_TAG && [menuItem tag] <= SP_HISTORY_CLEAR_MENUITEM_TAG ) {
@@ -3601,6 +3717,7 @@
selectionIndexToRestore = nil;
selectionViewportToRestore = NSZeroRect;
+#ifndef SP_REFACTOR
// init helpHTMLTemplate
NSError *error;
@@ -3611,13 +3728,14 @@
// an error occurred while reading
if (helpHTMLTemplate == nil) {
- NSLog(@"%@", [NSString stringWithFormat:@"Error reading “%@.html”!<br>%@", SPHTMLHelpTemplate, [error localizedFailureReason]]);
+ NSLog(@"%@", [NSString stringWithFormat:@"Error reading “%@.html”!<br>%@", SPHTMLHelpTemplate, [error localizedFailureReason]]);
NSBeep();
}
// init search history
[helpWebView setMaintainsBackForwardList:YES];
[[helpWebView backForwardList] setCapacity:20];
+#endif
// init tableView's data source
resultDataCount = 0;
@@ -3629,7 +3747,9 @@
queryLoadTimer = nil;
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
+#endif
kCellEditorErrorNoMatch = NSLocalizedString(@"Field is not editable. No matching record found.\nReload data, check encoding, or try to add\na primary key field or more fields\nin your SELECT statement for table '%@'\nto identify field origin unambiguously.", @"Custom Query result editing error - could not identify original row");
kCellEditorErrorNoMultiTabDb = NSLocalizedString(@"Field is not editable. Field has no or multiple table or database origin(s).",@"field is not editable due to no table/database");
@@ -3834,8 +3954,10 @@
[queryFavoritesSaveAsMenuItem setTag:SP_SAVE_SELECTION_FAVORTITE_MENUITEM_TAG];
[queryFavoritesSaveAllMenuItem setTag:SP_SAVE_ALL_FAVORTITE_MENUITEM_TAG];
+#ifndef SP_REFACTOR
// Set the structure and index view's vertical gridlines if required
[customQueryView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
+#endif
// Add observers for document task activity
[[NSNotificationCenter defaultCenter] addObserver:self
@@ -3847,7 +3969,9 @@
name:SPDocumentTaskEndNotification
object:tableDocumentInstance];
+#ifndef SP_REFACTOR
[prefs addObserver:self forKeyPath:SPGlobalResultTableFont options:NSKeyValueObservingOptionNew context:NULL];
+#endif
// Collapse the query information pane
if ([queryInfoPaneSplitView collapsibleSubview]) {
@@ -3870,7 +3994,9 @@
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
+#ifndef SP_REFACTOR
[prefs removeObserver:self forKeyPath:SPGlobalResultTableFont];
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:customQueryView];
[self clearQueryLoadTimer];
@@ -3880,7 +4006,9 @@
if(fieldEditor) [fieldEditor release], fieldEditor = nil;
+#ifndef SP_REFACTOR
if (helpHTMLTemplate) [helpHTMLTemplate release];
+#endif
if (mySQLversion) [mySQLversion release];
if (sortField) [sortField release];
if (cqColumnDefinition) [cqColumnDefinition release];
diff --git a/Source/SPDatabaseDocument.h b/Source/SPDatabaseDocument.h
index 485b224b..2586efad 100644
--- a/Source/SPDatabaseDocument.h
+++ b/Source/SPDatabaseDocument.h
@@ -26,14 +26,15 @@
// More info at <http://code.google.com/p/sequel-pro/>
#import <MCPKit/MCPKit.h>
+#ifndef SP_REFACTOR /* headers */
#import <WebKit/WebKit.h>
+#endif
-@class SPConnectionController,
- SPProcessListController,
- SPServerVariablesController,
- SPUserManager,
- SPWindowController,
- SPServerSupport;
+@class SPConnectionController,
+#ifndef SP_REFACTOR /* class forward decls */
+SPProcessListController, SPServerVariablesController, SPUserManager, SPWindowController,
+#endif
+SPTablesList, SPTableStructure, SPTableContent, SPTableData, SPServerSupport;
#import "SPConnectionControllerDelegateProtocol.h"
@@ -42,15 +43,19 @@
*/
@interface SPDatabaseDocument : NSObject <SPConnectionControllerDelegateProtocol>
{
+#ifdef SP_REFACTOR /* patch */
+ id delegate;
+#endif
+
// IBOutlets
- IBOutlet id tablesListInstance;
- IBOutlet id tableSourceInstance;
- IBOutlet id tableContentInstance;
+ SPTablesList* tablesListInstance;
+ SPTableStructure* tableSourceInstance;
+ SPTableContent* tableContentInstance;
IBOutlet id tableRelationsInstance;
IBOutlet id tableTriggersInstance;
IBOutlet id customQueryInstance;
IBOutlet id tableDumpInstance;
- IBOutlet id tableDataInstance;
+ SPTableData* tableDataInstance;
IBOutlet id extendedTableInfoInstance;
IBOutlet id databaseDataInstance;
IBOutlet id spHistoryControllerInstance;
@@ -60,7 +65,9 @@
IBOutlet id statusTableView;
IBOutlet id statusTableCopyChecksum;
+#ifndef SP_REFACTOR /* ivars */
SPUserManager *userManagerInstance;
+#endif
SPServerSupport *serverSupport;
IBOutlet NSSearchField *listFilterField;
@@ -137,13 +144,15 @@
// Controllers
SPConnectionController *connectionController;
+#ifndef SP_REFACTOR /* ivars */
SPProcessListController *processListController;
SPServerVariablesController *serverVariablesController;
-
+#endif
MCPConnection *mySQLConnection;
+#ifndef SP_REFACTOR /* ivars */
NSInteger currentTabIndex;
-
+#endif
NSString *selectedTableName;
SPTableType selectedTableType;
@@ -154,14 +163,18 @@
NSString *selectedDatabase;
NSString *mySQLVersion;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
NSMutableArray *nibObjectsToRelease;
+#endif
NSMenu *selectEncodingMenu;
BOOL _supportsEncoding;
BOOL _isConnected;
NSInteger _isWorkingLevel;
+#ifndef SP_REFACTOR /* ivars */
BOOL _mainNibLoaded;
+#endif
BOOL databaseListIsSelectable;
NSInteger _queryMode;
BOOL _isSavedInBundle;
@@ -182,7 +195,9 @@
NSToolbar *mainToolbar;
NSToolbarItem *chooseDatabaseToolbarItem;
+#ifndef SP_REFACTOR /* ivars */
WebView *printWebView;
+#endif
NSMutableArray *allDatabases;
NSMutableArray *allSystemDatabases;
@@ -198,6 +213,7 @@
NSString *keyChainID;
+#ifndef SP_REFACTOR /* ivars */
NSThread *printThread;
id statusValues;
@@ -208,30 +224,47 @@
SPWindowController *parentWindowController;
NSWindow *parentWindow;
NSTabViewItem *parentTabViewItem;
+#endif
BOOL isProcessing;
+#ifndef SP_REFACTOR /* ivars */
NSString *processID;
+#endif
}
+#ifdef SP_REFACTOR /* ivars */
+@property (readwrite, assign) id delegate;
+@property (readonly) NSMutableArray* allDatabases;
+#endif
+
+#ifndef SP_REFACTOR /* ivars */
@property (readwrite, assign) SPWindowController *parentWindowController;
@property (readwrite, assign) NSTabViewItem *parentTabViewItem;
+#endif
@property (readwrite, assign) BOOL isProcessing;
+#ifndef SP_REFACTOR /* ivars */
@property (readwrite, retain) NSString *processID;
+#endif
@property (readonly) SPServerSupport *serverSupport;
+#ifndef SP_REFACTOR /* method decls */
- (BOOL)isUntitled;
- (BOOL)couldCommitCurrentViewActions;
- (void)initQueryEditorWithString:(NSString *)query;
// Connection callback and methods
+#endif
- (void)setConnection:(MCPConnection *)theConnection;
- (MCPConnection *)getConnection;
- (void)setKeychainID:(NSString *)theID;
// Database methods
- (IBAction)setDatabases:(id)sender;
+#ifndef SP_REFACTOR /* method decls */
- (IBAction)chooseDatabase:(id)sender;
+#endif
- (void)selectDatabase:(NSString *)aDatabase item:(NSString *)anItem;
+#ifndef SP_REFACTOR /* method decls */
- (IBAction)addDatabase:(id)sender;
- (IBAction)removeDatabase:(id)sender;
- (IBAction)refreshTables:(id)sender;
@@ -241,6 +274,7 @@
- (IBAction)showServerVariables:(id)sender;
- (IBAction)showServerProcesses:(id)sender;
- (IBAction)openCurrentConnectionInNewWindow:(id)sender;
+#endif
- (NSArray *)allDatabaseNames;
- (NSArray *)allSystemDatabaseNames;
- (NSDictionary *)getDbStructure;
@@ -269,6 +303,7 @@
- (void)updateEncodingMenuWithSelectedEncoding:(NSNumber *)encodingTag;
- (NSNumber *)encodingTagFromMySQLEncoding:(NSString *)mysqlEncoding;
- (NSString *)mysqlEncodingFromEncodingTag:(NSNumber *)encodingTag;
+#ifndef SP_REFACTOR /* method decls */
// Table methods
- (IBAction)showCreateTableSyntax:(id)sender;
@@ -296,7 +331,9 @@
- (void)flushPrivileges:(id)sender;
- (void)closeConnection;
- (NSWindow *)getCreateTableSyntaxWindow;
+#endif
- (void)refreshCurrentDatabase;
+#ifndef SP_REFACTOR /* method decls */
- (void)saveConnectionPanelDidEnd:(NSSavePanel *)panel returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
- (IBAction)validateSaveConnectionAccessory:(id)sender;
- (BOOL)saveDocumentWithFilePath:(NSString *)fileName inBackground:(BOOL)saveInBackground onlyPreferences:(BOOL)saveOnlyPreferences contextInfo:(NSDictionary*)contextInfo;
@@ -312,6 +349,7 @@
- (void)showConsole:(id)sender;
- (IBAction)showNavigator:(id)sender;
- (IBAction)toggleNavigator:(id)sender;
+#endif
// Accessor methods
- (NSString *)host;
@@ -326,6 +364,7 @@
- (BOOL)isSaveInBundle;
- (NSURL *)fileURL;
- (NSString *)displayName;
+#ifndef SP_REFACTOR /* method decls */
// Notification center methods
- (void)willPerformQuery:(NSNotification *)notification;
@@ -361,8 +400,11 @@
- (void)didBecomeActiveTabInWindow;
- (void)tabDidBecomeKey;
- (void)tabDidResize;
+#endif
+
- (void)setIsProcessing:(BOOL)value;
- (BOOL)isProcessing;
+#ifndef SP_REFACTOR /* method decls */
- (void)setParentWindow:(NSWindow *)aWindow;
- (NSWindow *)parentWindow;
@@ -379,5 +421,17 @@
- (BOOL)setState:(NSDictionary *)stateDetails;
- (void)setStateFromConnectionFile:(NSString *)path;
- (void)restoreSession;
+#endif
+
+#ifdef SP_REFACTOR /* method decls */
+- (SPConnectionController*)createConnectionController;
+- (void)connect;
+- (NSArray*)allTableNames;
+- (SPTablesList*)tablesListInstance;
+- (SPTableData*)tableDataInstance;
+- (void)setTableSourceInstance:(SPTableStructure*)source;
+- (void)setTableContentInstance:(SPTableContent*)content;
+- (void)setTableDataInstance:(SPTableData*)data;
+#endif
@end
diff --git a/Source/SPDatabaseDocument.m b/Source/SPDatabaseDocument.m
index 0d3a4fcd..c19e4e0d 100644
--- a/Source/SPDatabaseDocument.m
+++ b/Source/SPDatabaseDocument.m
@@ -26,8 +26,13 @@
// More info at <http://code.google.com/p/sequel-pro/>
#import "SPDatabaseDocument.h"
+#import "SPConnectionController.h"
+
#import "SPTablesList.h"
#import "SPTableStructure.h"
+#ifndef SP_REFACTOR /* headers */
+#import "SPFileHandle.h"
+#import "SPKeychain.h"
#import "SPTableContent.h"
#import "SPCustomQuery.h"
#import "SPDataImport.h"
@@ -35,14 +40,15 @@
#import "SPGrowlController.h"
#import "SPExportController.h"
#import "SPQueryController.h"
+#import "SPWindowController.h"
+#endif
#import "SPNavigatorController.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPSQLParser.h"
#import "SPTableData.h"
#import "SPDatabaseData.h"
#import "SPAppController.h"
#import "SPExtendedTableInfo.h"
-#import "SPConnectionController.h"
-#import "SPKeychain.h"
#import "SPHistoryController.h"
#import "SPPreferenceController.h"
#import "SPUserManager.h"
@@ -55,38 +61,57 @@
#import "SPDatabaseCopy.h"
#import "SPTableCopy.h"
#import "SPDatabaseRename.h"
+#endif
#import "SPServerSupport.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPTooltip.h"
+#endif
#import "SPDatabaseViewController.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPBundleHTMLOutputController.h"
#import "SPConnectionDelegate.h"
-#import "SPWindowController.h"
-#import "SPFileHandle.h"
-#import "SPFavoritesPreferencePane.h"
+#endif
+
+#ifdef SP_REFACTOR /* headers */
+#import "SPAlertSheets.h"
+#endif
@interface SPDatabaseDocument (PrivateAPI)
+#ifndef SP_REFACTOR /* method decls */
- (void)_addDatabase;
- (void)_copyDatabase;
- (void)_renameDatabase;
- (void)_removeDatabase;
+#endif
- (void)_selectDatabaseAndItem:(NSDictionary *)selectionDetails;
@end
@implementation SPDatabaseDocument
+#ifndef SP_REFACTOR /* ivars */
@synthesize parentWindowController;
@synthesize parentTabViewItem;
+#endif
@synthesize isProcessing;
@synthesize serverSupport;
+#ifndef SP_REFACTOR /* ivars */
@synthesize processID;
+#endif
+
+#ifdef SP_REFACTOR /* ivars */
+@synthesize allDatabases;
+@synthesize delegate;
+#endif
- (id)init
{
if ((self = [super init])) {
+#ifndef SP_REFACTOR /* init ivars */
_mainNibLoaded = NO;
+#endif
_isConnected = NO;
_isWorkingLevel = 0;
_isSavedInBundle = NO;
@@ -110,14 +135,18 @@
mySQLVersion = nil;
allDatabases = nil;
allSystemDatabases = nil;
+#ifndef SP_REFACTOR /* init ivars */
mainToolbar = nil;
parentWindow = nil;
+#endif
isProcessing = NO;
+#ifndef SP_REFACTOR /* init ivars */
printWebView = [[WebView alloc] init];
[printWebView setFrameLoadDelegate:self];
prefs = [NSUserDefaults standardUserDefaults];
+#endif
queryEditorInitString = nil;
spfFileURL = nil;
@@ -139,6 +168,7 @@
taskCancellationCallbackSelector = NULL;
keyChainID = nil;
+#ifndef SP_REFACTOR /* init ivars */
statusValues = nil;
printThread = nil;
nibObjectsToRelease = [[NSMutableArray alloc] init];
@@ -150,11 +180,47 @@
[nibLoader instantiateNibWithOwner:self topLevelObjects:&dbViewTopLevelObjects];
[nibLoader release];
[nibObjectsToRelease addObjectsFromArray:dbViewTopLevelObjects];
+#endif
}
return self;
}
+#ifdef SP_REFACTOR /* glue */
+- (SPConnectionController*)createConnectionController
+{
+ // Set up the connection controller
+ connectionController = [[SPConnectionController alloc] initWithDocument:self];
+
+ // Set the connection controller's delegate
+ [connectionController setDelegate:self];
+ return connectionController;
+}
+
+- (void)setTableSourceInstance:(SPTableStructure*)source
+{
+ tableSourceInstance = source;
+}
+
+- (void)setTableContentInstance:(SPTableContent*)content
+{
+ tableContentInstance = content;
+}
+
+- (void)setTableDataInstance:(SPTableData*)data
+{
+ tableDataInstance = data;
+}
+
+- (SPTableData*)tableDataInstance
+{
+ return tableDataInstance;
+}
+
+#endif
+
+#ifndef SP_REFACTOR /* awakeFromNib */
+
- (void)awakeFromNib
{
if (_mainNibLoaded) return;
@@ -256,7 +322,9 @@
[contentViewSplitter setDelegate:self];
}
+#endif
+#ifndef SP_REFACTOR /* password sheet and history navigation */
/**
* Set the return code for entering the encryption passowrd sheet
*/
@@ -291,6 +359,7 @@
break;
}
}
+#endif
#pragma mark -
#pragma mark Connection callback and methods
@@ -305,12 +374,14 @@
serverSupport = [[SPServerSupport alloc] initWithMajorVersion:[mySQLConnection serverMajorVersion]
minor:[mySQLConnection serverMinorVersion]
release:[mySQLConnection serverReleaseVersion]];
-
+
+#ifndef SP_REFACTOR
// Set the fileURL and init the preferences (query favs, filters, and history) if available for that URL
[self setFileURL:[[SPQueryController sharedQueryController] registerDocumentWithFileURL:[self fileURL] andContextInfo:spfPreferences]];
// ...but hide the icon while the document is temporary
if ([self isUntitled]) [[parentWindow standardWindowButton:NSWindowDocumentIconButton] setImage:nil];
+#endif
// Get the mysql version
mySQLVersion = [[NSString alloc] initWithString:[mySQLConnection serverVersionString]];
@@ -319,7 +390,9 @@
if ([connectionController database] && ![[connectionController database] isEqualToString:@""]) {
if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
selectedDatabase = [[NSString alloc] initWithString:[connectionController database]];
+#ifndef SP_REFACTOR /* [spHistoryControllerInstance updateHistoryEntries] */
[spHistoryControllerInstance updateHistoryEntries];
+#endif
}
// Ensure the connection encoding is set to utf8 for database/table name retrieval
@@ -332,19 +405,28 @@
[databaseDataInstance setConnection:mySQLConnection];
+#ifndef SP_REFACTOR /* setServerSupport: */
// Pass the support class to the data instance
[databaseDataInstance setServerSupport:serverSupport];
-
+#endif
+
+#ifdef SP_REFACTOR /* glue */
+ tablesListInstance = [[SPTablesList alloc] init];
+ [tablesListInstance setDatabaseDocument:self];
+#endif
+
// Set the connection on the tables list instance - this updates the table list while the connection
// is still UTF8
[tablesListInstance setConnection:mySQLConnection];
+#ifndef SP_REFACTOR /* set connection encoding from prefs */
// Set the connection encoding if necessary
NSNumber *encodingType = [prefs objectForKey:SPDefaultEncoding];
if ([encodingType intValue] != SPEncodingAutodetect) {
[self setConnectionEncoding:[self mysqlEncodingFromEncodingTag:encodingType] reloadingViews:NO];
}
+#endif
// For each of the main controllers, assign the current connection
[tableSourceInstance setConnection:mySQLConnection];
@@ -357,6 +439,7 @@
[tableDataInstance setConnection:mySQLConnection];
[extendedTableInfoInstance setConnection:mySQLConnection];
+#ifndef SP_REFACTOR /* update custom query editor */
// Set the custom query editor's MySQL version
[customQueryInstance setMySQLversion:mySQLVersion];
@@ -436,6 +519,11 @@
}
(void)[self databaseEncoding];
+#endif
+#ifdef SP_REFACTOR /* glue */
+ if ( delegate && [delegate respondsToSelector:@selector(databaseDocumentDidConnect:)] )
+ [delegate performSelector:@selector(databaseDocumentDidConnect:) withObject:self];
+#endif
}
/**
@@ -464,6 +552,8 @@
*/
- (IBAction)setDatabases:(id)sender;
{
+#ifndef SP_REFACTOR /* ui manipulation */
+
if (!chooseDatabaseButton) return;
[chooseDatabaseButton removeAllItems];
@@ -473,6 +563,7 @@
[[chooseDatabaseButton menu] addItemWithTitle:NSLocalizedString(@"Add Database...", @"menu item to add db") action:@selector(addDatabase:) keyEquivalent:@""];
[[chooseDatabaseButton menu] addItemWithTitle:NSLocalizedString(@"Refresh Databases", @"menu item to refresh databases") action:@selector(setDatabases:) keyEquivalent:@""];
[[chooseDatabaseButton menu] addItem:[NSMenuItem separatorItem]];
+#endif
MCPResult *queryResult = [mySQLConnection listDBs];
@@ -499,6 +590,7 @@
}
}
+#ifndef SP_REFACTOR /* ui manipulation */
// Add system databases
for (NSString *db in allSystemDatabases)
{
@@ -517,8 +609,11 @@
}
(![self database]) ? [chooseDatabaseButton selectItemAtIndex:0] : [chooseDatabaseButton selectItemWithTitle:[self database]];
+#endif
}
+#ifndef SP_REFACTOR /* chooseDatabase: */
+
/**
* Selects the database choosen by the user, using a child task if necessary,
* and displaying errors in an alert sheet on failure.
@@ -543,12 +638,14 @@
// Select the database
[self selectDatabase:[chooseDatabaseButton titleOfSelectedItem] item:[self table]];
}
+#endif
/**
* Select the specified database and, optionally, table.
*/
- (void)selectDatabase:(NSString *)aDatabase item:(NSString *)anItem
{
+#ifndef SP_REFACTOR /* update navigator controller */
// Do not update the navigator since nothing is changed
[[SPNavigatorController sharedNavigatorController] setIgnoreUpdate:NO];
@@ -562,6 +659,7 @@
}
[[SPNavigatorController sharedNavigatorController] selectPath:schemaPath];
}
+#endif
// Start a task
[self startTaskWithDescription:[NSString stringWithFormat:NSLocalizedString(@"Loading database '%@'...", @"Loading database task string"), [chooseDatabaseButton titleOfSelectedItem]]];
@@ -577,6 +675,7 @@
}
}
+#ifndef SP_REFACTOR /* operations on whole databases */
/**
* opens the add-db sheet and creates the new db
*/
@@ -731,6 +830,7 @@
[processListController displayProcessListWindow];
}
+#endif
/**
* Returns an array of all available database names
@@ -748,6 +848,7 @@
return allSystemDatabases;
}
+#ifndef SP_REFACTOR /* sheetDidEnd: */
/**
* Alert sheet method. Invoked when an alert sheet is dismissed.
*
@@ -820,6 +921,7 @@
nil, nil, parentWindow, self, nil, nil,
[error objectAtIndex:1]);
}
+#endif
/**
* Reset the current selected database name
@@ -844,12 +946,16 @@
if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
selectedDatabase = [[NSString alloc] initWithString:dbName];
[chooseDatabaseButton selectItemWithTitle:selectedDatabase];
+#ifndef SP_REFACTOR /* [self updateWindowTitle:self] */
[self updateWindowTitle:self];
+#endif
}
} else {
if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
[chooseDatabaseButton selectItemAtIndex:0];
+#ifndef SP_REFACTOR /* [self updateWindowTitle:self] */
[self updateWindowTitle:self];
+#endif
}
}
@@ -857,10 +963,12 @@
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:self];
}
+#ifndef SP_REFACTOR /* navigatorSchemaPathExistsForDatabase: */
- (BOOL)navigatorSchemaPathExistsForDatabase:(NSString*)dbname
{
return [[SPNavigatorController sharedNavigatorController] schemaPathExistsForConnection:[self connectionID] andDatabase:dbname];
}
+#endif
- (NSDictionary*)getDbStructure
{
@@ -872,6 +980,8 @@
return [[SPNavigatorController sharedNavigatorController] allSchemaKeysForConnection:[self connectionID]];
}
+#ifndef SP_REFACTOR /* console and navigator methods */
+
#pragma mark -
#pragma mark Console methods
@@ -952,6 +1062,7 @@
[[[SPNavigatorController sharedNavigatorController] window] makeKeyAndOrderFront:self];
}
}
+#endif
#pragma mark -
#pragma mark Task progress and notification methods
@@ -1227,7 +1338,7 @@
- (void) centerTaskWindow
{
NSPoint newBottomLeftPoint;
- NSRect mainWindowRect = [parentWindow frame];
+ NSRect mainWindowRect = [[NSApp keyWindow] frame];
NSRect taskWindowRect = [taskProgressWindow frame];
newBottomLeftPoint.x = roundf(mainWindowRect.origin.x + mainWindowRect.size.width/2 - taskWindowRect.size.width/2);
@@ -1426,6 +1537,7 @@
#pragma mark -
#pragma mark Table Methods
+#ifndef SP_REFACTOR /* whole table operations */
/**
* Copies if sender == self or displays or the CREATE TABLE syntax of the selected table(s) to the user .
@@ -2188,6 +2300,8 @@
[newTableDocument setStateFromConnectionFile:[[self fileURL] path]];
}
+#endif
+
/**
* Ask the connection controller to initiate connection, if it hasn't
* already. Used to support automatic connections on window open,
@@ -2203,13 +2317,16 @@
[mySQLConnection disconnect];
_isConnected = NO;
+#ifndef SP_REFACTOR /* growl */
// Disconnected Growl notification
[[SPGrowlController sharedGrowlController] notifyWithTitle:@"Disconnected"
description:[NSString stringWithFormat:NSLocalizedString(@"Disconnected from %@",@"description for disconnected growl notification"), [parentTabViewItem label]]
document:self
notificationName:@"Disconnected"];
+#endif
}
+#ifndef SP_REFACTOR /* observeValueForKeyPath: */
/**
* This method is called as part of Key Value Observing which is used to watch for prefernce changes which effect the interface.
*/
@@ -2219,6 +2336,7 @@
[mySQLConnection setDelegateQueryLogging:[[change objectForKey:NSKeyValueChangeNewKey] boolValue]];
}
}
+#endif
/**
* Is current document Untitled?
@@ -2235,7 +2353,7 @@
*/
- (BOOL)couldCommitCurrentViewActions
{
- [parentWindow endEditingFor:nil];
+ [[NSApp keyWindow] endEditingFor:nil];
switch ([tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]]) {
// Table structure view
@@ -2340,8 +2458,10 @@
tabTitle = [NSMutableString string];
+#ifndef SP_REFACTOR /* Add the MySQL version to the window title */
// Add the MySQL version to the window title if enabled in prefs
if ([prefs boolForKey:SPDisplayServerVersionInWindowTitle]) [tabTitle appendFormat:@"(MySQL %@)\n", [self mySQLVersion]];
+#endif
[tabTitle appendString:[self name]];
if ([self database]) {
@@ -2421,6 +2541,7 @@
[queryProgressBar stopAnimation:self];
}
+#ifndef SP_REFACTOR /* applicationWillTerminate: */
/**
* Invoked when the application will terminate
*/
@@ -3882,6 +4003,7 @@
[parentWindow setRepresentedURL:nil];
}
}
+#endif
/**
* Retrieve the NSURL for the .spf file for this connection instance (if any)
@@ -3891,6 +4013,7 @@
return [[spfFileURL copy] autorelease];
}
+#ifndef SP_REFACTOR /* writeSafelyToURL: */
/**
* Invoked if user chose "Save" from 'Do you want save changes you made...' sheet
* which is called automatically if [self isDocumentEdited] == YES and user wanted to close an Untitled doc.
@@ -3917,6 +4040,7 @@
|| [[[[SPQueryController sharedQueryController] contentFilterForFileURL:[self fileURL]] objectForKey:@"string"] count])
);
}
+#endif
/**
* The window title for this document.
@@ -3930,7 +4054,7 @@
}
return [[[self fileURL] path] lastPathComponent];
}
-
+#ifndef SP_REFACTOR /* state saving and setting */
#pragma mark -
#pragma mark State saving and setting
@@ -4552,6 +4676,7 @@
[self endTask];
[taskPool drain];
}
+#endif
#pragma mark -
#pragma mark Connection controller delegate methods
@@ -4561,12 +4686,14 @@
*/
- (void)connectionControllerInitiatingConnection:(id)controller
{
+#ifndef SP_REFACTOR /* ui manipulation */
// Update the window title to indicate that we are trying to establish a connection
[parentTabViewItem setLabel:NSLocalizedString(@"Connecting…", @"window title string indicating that sp is connecting")];
if ([parentWindowController selectedTableDocument] == self) {
[parentWindow setTitle:NSLocalizedString(@"Connecting…", @"window title string indicating that sp is connecting")];
}
+#endif
}
/**
@@ -4574,10 +4701,15 @@
*/
- (void)connectionControllerConnectAttemptFailed:(id)controller
{
+#ifndef SP_REFACTOR /* updateWindowTitle: */
// Reset the window title
[self updateWindowTitle:self];
+#endif
}
+
+#ifndef SP_REFACTOR /* scheme scripting methods */
+
#pragma mark -
#pragma mark Scheme scripting methods
@@ -5183,6 +5315,7 @@
return (NSDictionary*)env;
}
+#endif
#pragma mark -
#pragma mark Text field delegate methods
@@ -5211,6 +5344,7 @@
#pragma mark -
#pragma mark General sheet delegate methods
+#ifndef SP_REFACTOR /* window:willPositionSheet:usingRect: */
- (NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect {
@@ -5234,10 +5368,11 @@
rect.origin.y -= [[parentWindowController valueForKey:@"tabBar"] frame].size.height - 1;
return rect;
}
+#endif
#pragma mark -
#pragma mark SplitView delegate methods
-
+#ifndef SP_REFACTOR /* SplitView delegate methods */
/**
* tells the splitView that it can collapse views
*/
@@ -5365,6 +5500,9 @@
_isSavedInBundle = savedInBundle;
}
+#endif
+
+
#pragma mark -
/**
@@ -5372,7 +5510,7 @@
*/
- (void)dealloc
{
-
+#ifndef SP_REFACTOR /* Unregister observers */
// Unregister observers
[prefs removeObserver:self forKeyPath:SPDisplayTableViewVerticalGridlines];
[prefs removeObserver:tableSourceInstance forKeyPath:SPDisplayTableViewVerticalGridlines];
@@ -5388,23 +5526,30 @@
if (processListController) [prefs removeObserver:processListController forKeyPath:SPDisplayTableViewVerticalGridlines];
if (serverVariablesController) [prefs removeObserver:serverVariablesController forKeyPath:SPDisplayTableViewVerticalGridlines];
+#endif
[[NSNotificationCenter defaultCenter] removeObserver:self];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
+#ifndef SP_REFACTOR /* release nib objects */
for (id retainedObject in nibObjectsToRelease) [retainedObject release];
[nibObjectsToRelease release];
+#endif
[allDatabases release];
[allSystemDatabases release];
+#ifndef SP_REFACTOR /* dealloc ivars */
[printWebView release];
+#endif
[taskProgressWindow close];
if (selectedTableName) [selectedTableName release];
if (connectionController) [connectionController release];
+#ifndef SP_REFACTOR /* dealloc ivars */
if (processListController) [processListController release];
if (serverVariablesController) [serverVariablesController release];
+#endif
if (mySQLConnection) [mySQLConnection release];
if (selectedDatabase) [selectedDatabase release];
if (mySQLVersion) [mySQLVersion release];
@@ -5420,16 +5565,30 @@
if (titleAccessoryView) [titleAccessoryView release];
if (taskProgressWindow) [taskProgressWindow release];
if (serverSupport) [serverSupport release];
+#ifndef SP_REFACTOR /* dealloc ivars */
if (processID) [processID release];
+#endif
if (runningActivitiesArray) [runningActivitiesArray release];
[super dealloc];
}
+- (NSArray*)allTableNames
+{
+ return [tablesListInstance allTableNames];
+}
+
+- (SPTablesList*)tablesListInstance
+{
+ return tablesListInstance;
+}
+
@end
@implementation SPDatabaseDocument (PrivateAPI)
+#ifndef SP_REFACTOR /* whole database operations */
+
- (void)_copyDatabase
{
if ([[databaseCopyNameField stringValue] isEqualToString:@""]) {
@@ -5579,6 +5738,8 @@
[self updateWindowTitle:self];
}
+#endif
+
/**
* Select the specified database and, optionally, table.
*/
@@ -5586,6 +5747,7 @@
{
NSAutoreleasePool *taskPool = [[NSAutoreleasePool alloc] init];
NSString *targetDatabaseName = [selectionDetails objectForKey:@"database"];
+#ifndef SP_REFACTOR /* update history controller */
NSString *targetItemName = [selectionDetails objectForKey:@"item"];
// Save existing scroll position and details, and ensure no duplicate entries are created as table list changes
@@ -5594,12 +5756,17 @@
[spHistoryControllerInstance updateHistoryEntries];
[spHistoryControllerInstance setModifyingState:YES];
}
+#endif
if (![targetDatabaseName isEqualToString:selectedDatabase]) {
// Attempt to select the specified database, and abort on failure
+#ifndef SP_REFACTOR /* patch */
if ([chooseDatabaseButton indexOfItemWithTitle:targetDatabaseName] == NSNotFound
|| ![mySQLConnection selectDB:targetDatabaseName])
+#else
+ if ( ![mySQLConnection selectDB:targetDatabaseName] )
+#endif
{
// End the task first to ensure the database dropdown can be reselected
@@ -5610,28 +5777,37 @@
// Update the database list
[[self onMainThread] setDatabases:self];
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, parentWindow, self, nil, nil, [NSString stringWithFormat:NSLocalizedString(@"Unable to select database %@.\nPlease check you have the necessary privileges to view the database, and that the database still exists.", @"message of panel when connection to db failed after selecting from popupbutton"), targetDatabaseName]);
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil, [NSString stringWithFormat:NSLocalizedString(@"Unable to select database %@.\nPlease check you have the necessary privileges to view the database, and that the database still exists.", @"message of panel when connection to db failed after selecting from popupbutton"), targetDatabaseName]);
}
[taskPool drain];
return;
}
+#ifndef SP_REFACTOR /* chooseDatabaseButton selectItemWithTitle: */
[[chooseDatabaseButton onMainThread] selectItemWithTitle:targetDatabaseName];
+#endif
if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
+#ifndef SP_REFACTOR /* patch */
selectedDatabase = [[NSString alloc] initWithString:[chooseDatabaseButton titleOfSelectedItem]];
+#else
+ selectedDatabase = [[NSString alloc] initWithString:targetDatabaseName];
+#endif
+#ifndef SP_REFACTOR /* clear SPTablesList selection */
// If the item has changed, clear the item selection for cleaner loading
if (![targetItemName isEqualToString:[self table]]) {
[[tablesListInstance onMainThread] setTableListSelectability:YES];
[[[tablesListInstance valueForKey:@"tablesListView"] onMainThread] deselectAll:self];
[[tablesListInstance onMainThread] setTableListSelectability:NO];
}
+#endif
// Set the connection of SPTablesList and TablesDump to reload tables in db
[tablesListInstance setConnection:mySQLConnection];
[tableDumpInstance setConnection:mySQLConnection];
+#ifndef SP_REFACTOR /* update history controller and ui manip */
// Update the window title
[self updateWindowTitle:self];
@@ -5647,8 +5823,10 @@
[[parentWindow onMainThread] makeFirstResponder:listFilterField];
else
[[parentWindow onMainThread] makeFirstResponder:[tablesListInstance valueForKeyPath:@"tablesListView"]];
+#endif
}
+#ifndef SP_REFACTOR /* update selected table in SPTablesList */
// If a the table has changed, update the selection
if (![targetItemName isEqualToString:[self table]]) {
if (targetItemName) {
@@ -5659,8 +5837,9 @@
[[tablesListInstance onMainThread] setTableListSelectability:NO];
}
}
-
+#endif
[self endTask];
+#ifndef SP_REFACTOR /* triggered commands */
NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionDatabaseChanged];
for(NSString* cmdPath in triggeredCommands) {
@@ -5698,8 +5877,14 @@
}
}
}
+#endif
- [taskPool drain];
+#ifdef SP_REFACTOR /* glue */
+ if ( delegate && [delegate respondsToSelector:@selector(databaseDidChange:)] )
+ [delegate performSelectorOnMainThread:@selector(databaseDidChange:) withObject:self waitUntilDone:NO];
+#endif
+ [taskPool drain];
}
+
@end
diff --git a/Source/SPDatabaseViewController.h b/Source/SPDatabaseViewController.h
index 682d6f74..f84d81cd 100644
--- a/Source/SPDatabaseViewController.h
+++ b/Source/SPDatabaseViewController.h
@@ -35,6 +35,7 @@
- (BOOL)contentLoaded;
- (BOOL)statusLoaded;
+#ifndef SP_REFACTOR /* method decls */
// Tab view control
- (IBAction)viewStructure:(id)sender;
- (IBAction)viewContent:(id)sender;
@@ -42,6 +43,7 @@
- (IBAction)viewStatus:(id)sender;
- (IBAction)viewRelations:(id)sender;
- (IBAction)viewTriggers:(id)sender;
+#endif
- (void)setStructureRequiresReload:(BOOL)reload;
- (void)setContentRequiresReload:(BOOL)reload;
- (void)setStatusRequiresReload:(BOOL)reload;
@@ -49,6 +51,8 @@
// Table control
- (void)loadTable:(NSString *)aTable ofType:(NSInteger)aTableType;
+#ifndef SP_REFACTOR /* method decls */
- (NSView *)databaseView;
+#endif
@end
diff --git a/Source/SPDatabaseViewController.m b/Source/SPDatabaseViewController.m
index 3b6cfc1f..7affec1d 100644
--- a/Source/SPDatabaseViewController.m
+++ b/Source/SPDatabaseViewController.m
@@ -32,6 +32,9 @@
#import "SPTableData.h"
#import "SPTablesList.h"
#import "SPTableTriggers.h"
+#ifdef SP_REFACTOR /* headers */
+#import "SPTableStructure.h"
+#endif
@interface SPDatabaseDocument (SPDatabaseViewControllerPrivateAPI)
@@ -46,6 +49,7 @@
#pragma mark -
#pragma mark Getters
+#ifndef SP_REFACTOR /* getters */
/**
* Returns the master database view, containing the tables list and views for
* table setup and contents.
@@ -54,6 +58,7 @@
{
return parentView;
}
+#endif
/**
* Returns the name of the currently selected table/view/procedure/function.
@@ -95,6 +100,7 @@
return statusLoaded;
}
+#ifndef SP_REFACTOR /* toolbar ibactions */
#pragma mark -
#pragma mark Tab view control and delegate methods
@@ -204,6 +210,7 @@
[prefs setInteger:SPTriggersViewMode forKey:SPLastViewMode];
}
+#endif
/**
* Mark the structure tab for refresh when it's next switched to,
@@ -224,7 +231,11 @@
*/
- (void)setContentRequiresReload:(BOOL)reload
{
- if (reload && selectedTableName && [tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]] == SPTableViewContent) {
+ if (reload && selectedTableName
+#ifndef SP_REFACTOR /* check which tab is selected */
+ && [tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]] == SPTableViewContent
+#endif
+ ) {
[tableContentInstance loadTable:selectedTableName];
} else {
contentLoaded = !reload;
@@ -237,14 +248,18 @@
*/
- (void)setStatusRequiresReload:(BOOL)reload
{
- if (reload && selectedTableName && [tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]] == SPTableViewStatus) {
+ if (reload && selectedTableName
+#ifndef SP_REFACTOR /* check which tab is selected */
+ && [tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]] == SPTableViewStatus
+#endif
+ ) {
[[extendedTableInfoInstance onMainThread] loadTable:selectedTableName];
} else {
statusLoaded = !reload;
}
}
-
+#ifndef SP_REFACTOR /* !!! respond to tab change */
/**
* Triggers a task to update the newly selected tab view, ensuring
* the data is fully loaded and up-to-date.
@@ -258,6 +273,7 @@
[self _loadTabTask:tabViewItem];
}
}
+#endif
#pragma mark -
#pragma mark Table control
@@ -286,18 +302,22 @@
[[tablesListInstance onMainThread] setSelectionState:nil];
[tableSourceInstance loadTable:nil];
[tableContentInstance loadTable:nil];
+#ifndef SP_REFACTOR /* [extendedTableInfoInstance loadTable:] */
[[extendedTableInfoInstance onMainThread] loadTable:nil];
[[tableTriggersInstance onMainThread] resetInterface];
+#endif
structureLoaded = NO;
contentLoaded = NO;
statusLoaded = NO;
triggersLoaded = NO;
+#ifndef SP_REFACTOR
// Update the window title
[self updateWindowTitle:self];
// Add a history entry
[spHistoryControllerInstance updateHistoryEntries];
+#endif
// Notify listeners of the table change
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:SPTableChangedNotification object:self];
@@ -370,6 +390,7 @@
contentLoaded = YES;
}
break;
+#ifndef SP_REFACTOR /* case SPTableViewStatus: case SPTableViewTriggers: */
case SPTableViewStatus:
if (!statusLoaded) {
[[extendedTableInfoInstance onMainThread] loadTable:selectedTableName];
@@ -382,6 +403,7 @@
triggersLoaded = YES;
}
break;
+#endif
}
[self endTask];
@@ -397,8 +419,10 @@
NSAutoreleasePool *loadPool = [[NSAutoreleasePool alloc] init];
NSString *tableEncoding = nil;
+#ifndef SP_REFACTOR /* Update the window title */
// Update the window title
[self updateWindowTitle:self];
+#endif
// Reset table information caches and mark that all loaded views require their data reloading
[tableDataInstance resetAllData];
@@ -440,23 +464,30 @@
// Notify listeners of the table change now that the state is fully set up.
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:SPTableChangedNotification object:self];
+#ifndef SP_REFACTOR /* [spHistoryControllerInstance restoreViewStates] */
// Restore view states as appropriate
[spHistoryControllerInstance restoreViewStates];
+#endif
// Load the currently selected view if looking at a table or view
if (tableEncoding && (selectedTableType == SPTableTypeView || selectedTableType == SPTableTypeTable))
{
+#ifndef SP_REFACTOR /* load everything in Coda */
NSInteger selectedTabViewIndex = [tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]];
switch (selectedTabViewIndex) {
case SPTableViewStructure:
+#endif
[tableSourceInstance loadTable:selectedTableName];
structureLoaded = YES;
+#ifndef SP_REFACTOR /* load everything in Coda */
break;
case SPTableViewContent:
+#endif
[tableContentInstance loadTable:selectedTableName];
contentLoaded = YES;
+#ifndef SP_REFACTOR /* load everything in Coda */
break;
case SPTableViewStatus:
[[extendedTableInfoInstance onMainThread] loadTable:selectedTableName];
@@ -467,6 +498,7 @@
triggersLoaded = YES;
break;
}
+#endif
}
// Clear any views which haven't been loaded as they weren't visible. Note
@@ -477,6 +509,7 @@
if (!statusLoaded) [[extendedTableInfoInstance onMainThread] loadTable:nil];
if (!triggersLoaded) [[tableTriggersInstance onMainThread] resetInterface];
+#ifndef SP_REFACTOR /* show Create Table syntax */
// Update the "Show Create Syntax" window if it's already opened
// according to the selected table/view/proc/func
if([[[self onMainThread] getCreateTableSyntaxWindow] isVisible])
@@ -484,10 +517,11 @@
// Add a history entry
[spHistoryControllerInstance updateHistoryEntries];
-
+#endif
// Empty the loading pool and exit the thread
[self endTask];
+#ifndef SP_REFACTOR /* triggered commands */
NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableChanged];
for(NSString* cmdPath in triggeredCommands) {
NSArray *data = [cmdPath componentsSeparatedByString:@"|"];
@@ -524,6 +558,7 @@
}
}
}
+#endif
[loadPool drain];
diff --git a/Source/SPFieldEditorController.h b/Source/SPFieldEditorController.h
index 1f3b6ea8..96d3501f 100644
--- a/Source/SPFieldEditorController.h
+++ b/Source/SPFieldEditorController.h
@@ -32,7 +32,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.
*/
+#ifndef SP_REFACTOR
@interface SPFieldEditorController : NSWindowController
+#else
+@interface SPFieldEditorController : NSWindowController <NSComboBoxDataSource>
+#endif
{
IBOutlet id editSheetProgressBar;
IBOutlet id editSheetSegmentControl;
@@ -155,7 +159,9 @@
BOOL wasCutPaste;
BOOL selectionChanged;
+#ifndef SP_REFACTOR
NSUserDefaults *prefs;
+#endif
NSDictionary *qlTypes;
diff --git a/Source/SPFieldEditorController.m b/Source/SPFieldEditorController.m
index 73fafe39..83a0c9d7 100644
--- a/Source/SPFieldEditorController.m
+++ b/Source/SPFieldEditorController.m
@@ -31,6 +31,8 @@
#import "SPGeometryDataView.h"
#import "SPCopyTable.h"
#include <objc/objc-runtime.h>
+#import "SPCustomQuery.h"
+#import "SPTableContent.h"
@interface SPFieldEditorController (SPFieldEditorControllerDelegate)
@@ -63,8 +65,9 @@
callerInstance = nil;
doGroupDueToChars = NO;
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
-
+#endif
// Used for max text length recognition if last typed char is a non-space char
editTextViewWasChanged = NO;
@@ -110,6 +113,7 @@
[qlTypesItems addObject:type];
}
}
+#ifndef SP_REFACTOR
// Load user-defined QL types
if([prefs objectForKey:SPQuickLookTypes]) {
for(id type in [prefs objectForKey:SPQuickLookTypes]) {
@@ -122,6 +126,7 @@
[qlTypesItems addObject:type];
}
}
+#endif
qlTypes = [[NSDictionary dictionaryWithObject:qlTypesItems forKey:SPQuickLookTypes] retain];
[qlTypesItems release];
@@ -209,7 +214,13 @@
[bitSheetNULLButton setEnabled:_allowNULL];
// Check for NULL
- if([sheetEditData isEqualToString:[prefs objectForKey:SPNullValue]]) {
+ if([sheetEditData isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]) {
[bitSheetNULLButton setState:NSOnState];
[self setToNull:bitSheetNULLButton];
} else {
@@ -239,14 +250,28 @@
usedSheet = editSheet;
// If required, use monospaced fonts
+#ifndef SP_REFACTOR
if (![prefs objectForKey:SPFieldEditorSheetFont]) {
- [editTextView setFont:([prefs boolForKey:SPUseMonospacedFonts]) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+#endif
+ [editTextView setFont:
+#ifndef SP_REFACTOR
+ ([prefs boolForKey:SPUseMonospacedFonts]) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] :
+#endif
+ [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+#ifndef SP_REFACTOR
}
else {
[editTextView setFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:@"FieldEditorSheetFont"]]];
}
+#endif
- [editTextView setContinuousSpellCheckingEnabled:[prefs boolForKey:SPBlobTextEditorSpellCheckingEnabled]];
+ [editTextView setContinuousSpellCheckingEnabled:
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPBlobTextEditorSpellCheckingEnabled]
+#else
+ NO
+#endif
+ ];
[hexTextView setFont:[NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]]];
@@ -381,7 +406,13 @@
[callerInstance setFieldEditorSelectedRange:NSMakeRange(0,0)];
// If the string content is NULL select NULL for convenience
- if([stringValue isEqualToString:[prefs objectForKey:SPNullValue]])
+ if([stringValue isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ])
[editTextView setSelectedRange:NSMakeRange(0,[[editTextView string] length])];
// Set focus
@@ -532,8 +563,10 @@
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
+#ifndef SP_REFACTOR
// Remember spell cheecker status
[prefs setBool:[editTextView isContinuousSpellCheckingEnabled] forKey:SPBlobTextEditorSpellCheckingEnabled];
+#endif
}
/**
@@ -550,8 +583,14 @@
// - for max text length (except for NULL value string) select the part which won't be saved
// and suppress closing the sheet
if(sender == editSheetOkButton) {
- if (maxTextLength > 0 && [[editTextView textStorage] length] > maxTextLength && ![[[editTextView textStorage] string] isEqualToString:[prefs objectForKey:SPNullValue]]) {
- [editTextView setSelectedRange:NSMakeRange((NSUInteger)maxTextLength, [[editTextView textStorage] length] - (NSUInteger)maxTextLength)];
+ if (maxTextLength > 0 && [[editTextView textStorage] length] > maxTextLength && ![[[editTextView textStorage] string] isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]) {
+ [editTextView setSelectedRange:NSMakeRange(maxTextLength, [[editTextView textStorage] length] - maxTextLength)];
[editTextView scrollRangeToVisible:NSMakeRange([editTextView selectedRange].location,0)];
[SPTooltip showWithObject:[NSString stringWithFormat:NSLocalizedString(@"Text is too long. Maximum text length is set to %llu.", @"Text is too long. Maximum text length is set to %llu."), maxTextLength]];
return;
@@ -580,7 +619,15 @@
if(callerInstance) {
id returnData = ( editSheetReturnCode && _isEditable ) ? (_isGeometry) ? [editTextView string] : sheetEditData : nil;
+
+#ifdef SP_REFACTOR /* patch */
+ if ( [callerInstance isKindOfClass:[SPCustomQuery class]] )
+ [(SPCustomQuery*)callerInstance processFieldEditorResult:returnData contextInfo:contextInfo];
+ else if ( [callerInstance isKindOfClass:[SPTableContent class]] )
+ [(SPTableContent*)callerInstance processFieldEditorResult:returnData contextInfo:contextInfo];
+#else
[callerInstance processFieldEditorResult:returnData contextInfo:contextInfo];
+#endif
}
}
@@ -1062,7 +1109,13 @@
[sheetEditData release];
}
- NSString *nullString = [prefs objectForKey:SPNullValue];
+ NSString *nullString =
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ;
sheetEditData = [[NSString stringWithString:nullString] retain];
[bitSheetIntegerTextField setStringValue:nullString];
[bitSheetHexTextField setStringValue:nullString];
@@ -1263,7 +1316,13 @@
{
if(textView == editTextView && (maxTextLength > 0)
- && ![ [[[editTextView textStorage] string] stringByAppendingString:replacementString] isEqualToString:[prefs objectForKey:SPNullValue]]) {
+ && ![ [[[editTextView textStorage] string] stringByAppendingString:replacementString] isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]) {
NSInteger newLength;
diff --git a/Source/SPFieldMapperController.h b/Source/SPFieldMapperController.h
index 69e9fac4..38f7cfd7 100644
--- a/Source/SPFieldMapperController.h
+++ b/Source/SPFieldMapperController.h
@@ -26,7 +26,11 @@
@class SPTextView, SPTableView, SPTablesList;
-@interface SPFieldMapperController : NSWindowController
+#ifndef SP_REFACTOR
+@interface SPFieldMapperController : NSWindowController
+#else
+@interface SPFieldMapperController : NSWindowController <NSTokenFieldCellDelegate>
+#endif
{
IBOutlet SPTableView *fieldMapperTableView;
IBOutlet id fieldMapperTableScrollView;
@@ -131,7 +135,9 @@
NSString *sourcePath;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSInteger heightOffset;
NSUInteger windowMinWidth;
diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m
index f6633172..d42916a1 100644
--- a/Source/SPFieldMapperController.m
+++ b/Source/SPFieldMapperController.m
@@ -4,7 +4,7 @@
// SPFieldMapperController.m
// sequel-pro
//
-// Created by Hans-Jörg Bibiko on February 01, 2010
+// Created by Hans-Jörg Bibiko on February 01, 2010
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -82,23 +82,26 @@ static NSString *SPTableViewSqlColumnID = @"sql";
doImport = [NSNumber numberWithInteger:0];
doNotImport = [NSNumber numberWithInteger:1];
isEqual = [NSNumber numberWithInteger:2];
- doImportString = @"―";
+ doImportString = @"―";
doNotImportString = @" ";
isEqualString = @"=";
newTableMode = NO;
addGlobalSheetIsOpen = NO;
toBeEditedRowIndexes = [[NSMutableIndexSet alloc] init];
+#ifndef SP_REFACTOR /* init ivars */
prefs = [NSUserDefaults standardUserDefaults];
+#endif
tablesListInstance = [theDelegate valueForKeyPath:@"tablesListInstance"];
databaseDataInstance = [tablesListInstance valueForKeyPath:@"databaseDataInstance"];
+#ifndef SP_REFACTOR /* init ivars */
if(![prefs objectForKey:SPLastImportIntoNewTableType])
[prefs setObject:@"Default" forKey:SPLastImportIntoNewTableType];
if(![prefs objectForKey:SPLastImportIntoNewTableEncoding])
[prefs setObject:@"Default" forKey:SPLastImportIntoNewTableEncoding];
-
+#endif
}
return self;
@@ -253,8 +256,8 @@ static NSString *SPTableViewSqlColumnID = @"sql";
NSInteger i;
for(i=0; i<numberOfImportColumns; i++) {
- [fieldMappingGlobalValues addObject:@"…"];
- [fieldMappingGlobalValuesSQLMarked addObject:@"…"];
+ [fieldMappingGlobalValues addObject:@"…"];
+ [fieldMappingGlobalValuesSQLMarked addObject:@"…"];
}
}
@@ -387,8 +390,10 @@ static NSString *SPTableViewSqlColumnID = @"sql";
{
// Only save selection if the user selected 'OK'
if ([sender tag]) {
+#ifndef SP_REFACTOR
[prefs setObject:[newTableInfoEnginePopup titleOfSelectedItem] forKey:SPLastImportIntoNewTableType];
[prefs setObject:[newTableInfoEncodingPopup titleOfSelectedItem] forKey:SPLastImportIntoNewTableEncoding];
+#endif
}
[NSApp endSheet:[sender window] returnCode:[sender tag]];
@@ -453,13 +458,15 @@ static NSString *SPTableViewSqlColumnID = @"sql";
}
[createString appendString:@")"];
+#ifndef SP_REFACTOR
if(![[prefs objectForKey:SPLastImportIntoNewTableType] isEqualToString:@"Default"])
[createString appendFormat:@" ENGINE=%@", [prefs objectForKey:SPLastImportIntoNewTableType]];
if(![[prefs objectForKey:SPLastImportIntoNewTableEncoding] isEqualToString:@"Default"]) {
NSString *encodingName = [[prefs objectForKey:SPLastImportIntoNewTableEncoding] stringByMatching:@"\\((.*)\\)" capture:1L];
if (!encodingName) encodingName = @"utf8";
- [createString appendFormat:[NSString stringWithFormat:@" DEFAULT CHARACTER SET %@", [encodingName backtickQuotedString]]];
+ [createString appendString:[NSString stringWithFormat:@" DEFAULT CHARACTER SET %@", [encodingName backtickQuotedString]]];
}
+#endif
[mySQLConnection queryString:createString];
@@ -551,7 +558,7 @@ static NSString *SPTableViewSqlColumnID = @"sql";
if([column objectForKey:@"length"])
[type appendFormat:@"(%@)", [column objectForKey:@"length"]];
if([column objectForKey:@"values"])
- [type appendFormat:@"(%@)", [[column objectForKey:@"values"] componentsJoinedByString:@"¦"]];
+ [type appendFormat:@"(%@)", [[column objectForKey:@"values"] componentsJoinedByString:@"¦"]];
if([column objectForKey:@"isprimarykey"]) {
[type appendFormat:@",%@",@"PRIMARY"];
@@ -728,9 +735,11 @@ static NSString *SPTableViewSqlColumnID = @"sql";
}
[fieldMapperTableView reloadData];
+#ifndef SP_REFACTOR
// Remember last field alignment if not "custom order"
if([[alignByPopup selectedItem] tag] != 3)
[prefs setInteger:[[alignByPopup selectedItem] tag] forKey:SPCSVFieldImportMappingAlignment];
+#endif
}
/*
@@ -834,8 +843,8 @@ static NSString *SPTableViewSqlColumnID = @"sql";
columnCounter = 0;
for(id col in row) {
if(col && col != [NSNull null]) {
- if([col isKindOfClass:[NSString class]] && maxLengthOfSourceColumns[columnCounter] < (NSInteger)[col length]) {
- maxLengthOfSourceColumns[columnCounter] = [col length];
+ if([col isKindOfClass:[NSString class]] && maxLengthOfSourceColumns[columnCounter] < (NSInteger)[(NSString*)col length]) {
+ maxLengthOfSourceColumns[columnCounter] = [(NSString*)col length];
}
if(typeOfSourceColumns[columnCounter] == 1) {
if(![[[NSNumber numberWithLongLong:[col longLongValue]] stringValue] isEqualToString:col])
@@ -1034,7 +1043,9 @@ static NSString *SPTableViewSqlColumnID = @"sql";
[newTableInfoEnginePopup addItemWithTitle:[engine objectForKey:@"Engine"]];
}
+#ifndef SP_REFACTOR
[newTableInfoEnginePopup selectItemWithTitle:[prefs objectForKey:SPLastImportIntoNewTableType]];
+#endif
// Populate the table encoding popup button with a default menu item
[newTableInfoEncodingPopup removeAllItems];
@@ -1065,7 +1076,9 @@ static NSString *SPTableViewSqlColumnID = @"sql";
[newTableInfoEncodingPopup insertItemWithTitle:utf8MenuItemTitle atIndex:2];
}
+#ifndef SP_REFACTOR
[newTableInfoEncodingPopup selectItemWithTitle:[prefs objectForKey:SPLastImportIntoNewTableEncoding]];
+#endif
}
[NSApp beginSheet:newTableInfoWindow
@@ -1092,10 +1105,12 @@ static NSString *SPTableViewSqlColumnID = @"sql";
while([insertPullDownButton numberOfItems] > (([[self selectedImportMethod] isEqualToString:@"UPDATE"]) ? 6 : 5))
[insertPullDownButton removeItemAtIndex:[insertPullDownButton numberOfItems]-1];
+#ifndef SP_REFACTOR
// Add recent global value menu
if([prefs objectForKey:SPGlobalValueHistory] && [[prefs objectForKey:SPGlobalValueHistory] isKindOfClass:[NSArray class]] && [[prefs objectForKey:SPGlobalValueHistory] count])
for(id item in [prefs objectForKey:SPGlobalValueHistory])
[recentGlobalValueMenu addItemWithTitle:item action:@selector(insertRecentGlobalValue:) keyEquivalent:@""];
+#endif
// Add column placeholder
NSInteger i = 0;
@@ -1103,11 +1118,17 @@ static NSString *SPTableViewSqlColumnID = @"sql";
for(id item in [fieldMappingImportArray objectAtIndex:0]) {
i++;
if ([item isNSNull]) {
- [insertPullDownButton addItemWithTitle:[NSString stringWithFormat:@"%i. <%@>", i, [prefs objectForKey:SPNullValue]]];
+ [insertPullDownButton addItemWithTitle:[NSString stringWithFormat:@"%i. <%@>", i,
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]];
} else if ([item isSPNotLoaded]) {
[insertPullDownButton addItemWithTitle:[NSString stringWithFormat:@"%i. <%@>", i, @"DEFAULT"]];
} else {
- if([item length] > 20)
+ if([(NSString*)item length] > 20)
[insertPullDownButton addItemWithTitle:[NSString stringWithFormat:@"%i. %@…", i, [item substringToIndex:20]]];
else
[insertPullDownButton addItemWithTitle:[NSString stringWithFormat:@"%i. %@", i, item]];
@@ -1309,6 +1330,7 @@ static NSString *SPTableViewSqlColumnID = @"sql";
- (void)resizeWindowByHeightDelta:(NSInteger)delta
{
+#ifndef SP_REFACTOR /* resizeWindowByHeightDelta: */
NSUInteger tableMask = [fieldMapperTableScrollView autoresizingMask];
NSUInteger headerSwitchMask = [importFieldNamesHeaderSwitch autoresizingMask];
NSUInteger alignPopupMask = [alignByPopup autoresizingMask];
@@ -1362,7 +1384,7 @@ static NSString *SPTableViewSqlColumnID = @"sql";
[advancedUpdateView setAutoresizingMask:updateViewMask];
[advancedInsertView setAutoresizingMask:insertViewMask];
[advancedBox setAutoresizingMask:NSViewNotSizable|NSViewWidthSizable|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin];
-
+#endif
}
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
@@ -1495,7 +1517,13 @@ static NSString *SPTableViewSqlColumnID = @"sql";
[fieldMappingButtonOptions setArray:[fieldMappingImportArray objectAtIndex:fieldMappingCurrentRow]];
for (i = 0; i < [fieldMappingButtonOptions count]; i++) {
if ([[fieldMappingButtonOptions objectAtIndex:i] isNSNull])
- [fieldMappingButtonOptions replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%i. <%@>", i+1, [prefs objectForKey:SPNullValue]]];
+ [fieldMappingButtonOptions replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%i. <%@>", i+1,
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]];
else if ([[fieldMappingButtonOptions objectAtIndex:i] isSPNotLoaded])
[fieldMappingButtonOptions replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%i. <%@>", i+1, @"DEFAULT"]];
else
@@ -1506,7 +1534,13 @@ static NSString *SPTableViewSqlColumnID = @"sql";
if((NSInteger)[fieldMappingGlobalValues count]>numberOfImportColumns)
for( ; i < [fieldMappingGlobalValues count]; i++) {
if ([NSArrayObjectAtIndex(fieldMappingGlobalValues, i) isNSNull])
- [fieldMappingButtonOptions addObject:[NSString stringWithFormat:@"%i. <%@>", i+1, [prefs objectForKey:SPNullValue]]];
+ [fieldMappingButtonOptions addObject:[NSString stringWithFormat:@"%i. <%@>", i+1,
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ]];
else
[fieldMappingButtonOptions addObject:[NSString stringWithFormat:@"%i. %@", i+1, NSArrayObjectAtIndex(fieldMappingGlobalValues, i)]];
}
@@ -1535,11 +1569,13 @@ static NSString *SPTableViewSqlColumnID = @"sql";
NSInteger alignment = 0;
+#ifndef SP_REFACTOR
if([prefs integerForKey:SPCSVFieldImportMappingAlignment]
&& [prefs integerForKey:SPCSVFieldImportMappingAlignment] >= 0
&& [prefs integerForKey:SPCSVFieldImportMappingAlignment] < 4) {
alignment = [prefs integerForKey:SPCSVFieldImportMappingAlignment];
}
+#endif
// Set matching names only if csv file has an header
if(importFieldNamesHeader && alignment == 2)
@@ -1642,7 +1678,9 @@ static NSString *SPTableViewSqlColumnID = @"sql";
- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
+#ifndef SP_REFACTOR
[aCell setFont:([prefs boolForKey:SPUseMonospacedFonts]) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+#endif
}
- (void)tableView:(NSTableView*)aTableView didClickTableColumn:(NSTableColumn *)aTableColumn
@@ -1785,7 +1823,7 @@ static NSString *SPTableViewSqlColumnID = @"sql";
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"];
+ 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];
@@ -1940,15 +1978,19 @@ static NSString *SPTableViewSqlColumnID = @"sql";
// Store anObject as recent global value if it's new
NSMutableArray *recents = [NSMutableArray array];
+#ifndef SP_REFACTOR
if([prefs objectForKey:SPGlobalValueHistory] && [[prefs objectForKey:SPGlobalValueHistory] isKindOfClass:[NSArray class]] && [[prefs objectForKey:SPGlobalValueHistory] count])
[recents setArray:[prefs objectForKey:SPGlobalValueHistory]];
+#endif
if([recents containsObject:anObject])
[recents removeObject:anObject];
[recents insertObject:anObject atIndex:0];
while([recents count] > 20)
[recents removeObjectAtIndex:[recents count]-1];
+#ifndef SP_REFACTOR
if([recents count])
[prefs setObject:recents forKey:SPGlobalValueHistory];
+#endif
// Re-init recent menu
[recentGlobalValueMenu compatibleRemoveAllItems];
diff --git a/Source/SPIndexesController.h b/Source/SPIndexesController.h
index 02dade6c..c56ff4eb 100644
--- a/Source/SPIndexesController.h
+++ b/Source/SPIndexesController.h
@@ -62,7 +62,9 @@
NSMutableArray *fields, *indexes, *indexedFields, *supportsLength, *requiresLength;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
MCPConnection *connection;
diff --git a/Source/SPIndexesController.m b/Source/SPIndexesController.m
index 12aa58e1..21320897 100644
--- a/Source/SPIndexesController.m
+++ b/Source/SPIndexesController.m
@@ -28,9 +28,11 @@
#import "SPServerSupport.h"
#import "SPTableContent.h"
#import "SPTableData.h"
-#import "SPTablesList.h"
#import <MCPKit/MCPKit.h>
+#import "SPDatabaseDocument.h"
+#import "SPTablesList.h"
#import "SPDatabaseViewController.h"
+#import "SPTableStructure.h"
// Constants
static const NSString *SPNewIndexIndexName = @"IndexName";
@@ -70,7 +72,9 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
indexes = [[NSMutableArray alloc] init];
indexedFields = [[NSMutableArray alloc] init];
+#ifndef SP_REFACTOR /* init ivars */
prefs = [NSUserDefaults standardUserDefaults];
+#endif
showAdvancedView = NO;
@@ -97,11 +101,15 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
*/
- (void)awakeFromNib
{
+#ifndef SP_REFACTOR /* patch */
// Set the index tables view's vertical gridlines if required
[indexesTableView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
// Set the strutcture and index view's font
BOOL useMonospacedFont = [prefs boolForKey:SPUseMonospacedFonts];
+#else
+ BOOL useMonospacedFont = NO;
+#endif
for (NSTableColumn *indexColumn in [indexesTableView tableColumns])
{
@@ -113,7 +121,9 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[[fieldColumn dataCell] setFont:(useMonospacedFont) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
}
+#ifndef SP_REFACTOR /* patch */
[prefs addObserver:self forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
+#endif
}
#pragma mark -
@@ -225,7 +235,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
// Begin the sheet
[NSApp beginSheet:[self window]
- modalForWindow:[dbDocument parentWindow]
+ modalForWindow:[NSApp keyWindow]
modalDelegate:self
didEndSelector:@selector(addIndexSheetDidEnd:returnCode:contextInfo:)
contextInfo:nil];
@@ -283,7 +293,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[[buttons objectAtIndex:0] setKeyEquivalentModifierMask:NSCommandKeyMask];
[[buttons objectAtIndex:1] setKeyEquivalent:@"\r"];
- [alert beginSheetModalForWindow:[dbDocument parentWindow] modalDelegate:self didEndSelector:@selector(removeIndexSheetDidEnd:returnCode:contextInfo:) contextInfo:(hasForeignKey) ? @"removeIndexAndForeignKey" : @"removeIndex"];
+ [alert beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(removeIndexSheetDidEnd:returnCode:contextInfo:) contextInfo:(hasForeignKey) ? @"removeIndexAndForeignKey" : @"removeIndex"];
}
/**
@@ -785,7 +795,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
// Check for errors, but only if the query wasn't cancelled
if ([connection queryErrored] && ![connection queryCancelled]) {
- SPBeginAlertSheet(NSLocalizedString(@"Unable to add index", @"add index error message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [dbDocument parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Unable to add index", @"add index error message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to add the index.\n\nMySQL said: %@", @"add index error informative message"), [connection getLastErrorMessage]]);
}
else {
@@ -846,7 +856,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[errorDictionary setObject:NSLocalizedString(@"Unable to delete relation", @"error deleting relation message") forKey:@"title"];
[errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to delete the relation '%@'.\n\nMySQL said: %@", @"error deleting relation informative message"), constraintName, [connection getLastErrorMessage]] forKey:@"message"];
- [[tableStructure onMainThread] showErrorSheetWith:errorDictionary];
+ [(SPTableStructure*)[tableStructure onMainThread] showErrorSheetWith:errorDictionary];
}
}
@@ -865,7 +875,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[errorDictionary setObject:NSLocalizedString(@"Unable to delete index", @"error deleting index message") forKey:@"title"];
[errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to delete the index.\n\nMySQL said: %@", @"error deleting index informative message"), [connection getLastErrorMessage]] forKey:@"message"];
- [[tableStructure onMainThread] showErrorSheetWith:errorDictionary];
+ [(SPTableStructure*)[tableStructure onMainThread] showErrorSheetWith:errorDictionary];
}
else {
[tableData resetAllData];
@@ -895,7 +905,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
NSUInteger advancedViewMask = [indexAdvancedOptionsView autoresizingMask];
NSUInteger typeLabelMask = [indexTypeLabel autoresizingMask];
NSUInteger nameLabelMask = [indexNameLabel autoresizingMask];
- NSUInteger buttonBarMask = [anchoredButtonBar autoresizingMask];
+ NSUInteger buttonBarMask = [(NSView*)anchoredButtonBar autoresizingMask];
NSRect frame = [[self window] frame];
@@ -914,7 +924,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[indexAdvancedOptionsView setAutoresizingMask:NSViewNotSizable | NSViewMinYMargin];
[indexTypeLabel setAutoresizingMask:NSViewNotSizable | NSViewMinYMargin];
[indexNameLabel setAutoresizingMask:NSViewNotSizable | NSViewMinYMargin];
- [anchoredButtonBar setAutoresizingMask:NSViewNotSizable | NSViewMinYMargin];
+ [(NSView*)anchoredButtonBar setAutoresizingMask:NSViewNotSizable | NSViewMinYMargin];
NSInteger newMinHeight = (windowMinHeigth - heightOffset + delta < windowMinHeigth) ? windowMinHeigth : windowMinHeigth - heightOffset + delta;
@@ -938,7 +948,7 @@ static const NSString *SPNewIndexKeyBlockSize = @"IndexKeyBlockSize";
[indexAdvancedOptionsView setAutoresizingMask:advancedViewMask];
[indexTypeLabel setAutoresizingMask:typeLabelMask];
[indexNameLabel setAutoresizingMask:nameLabelMask];
- [anchoredButtonBar setAutoresizingMask:buttonBarMask];
+ [(NSView*)anchoredButtonBar setAutoresizingMask:buttonBarMask];
}
#pragma mark -
diff --git a/Source/SPNarrowDownCompletion.h b/Source/SPNarrowDownCompletion.h
index 08393d4d..44118380 100644
--- a/Source/SPNarrowDownCompletion.h
+++ b/Source/SPNarrowDownCompletion.h
@@ -26,7 +26,11 @@
//
// More info at <http://code.google.com/p/sequel-pro/>
-@interface SPNarrowDownCompletion : NSWindow
+#ifndef SP_REFACTOR
+@interface SPNarrowDownCompletion : NSWindow
+#else
+@interface SPNarrowDownCompletion : NSWindow <NSTableViewDelegate, NSTableViewDataSource, NSTokenFieldCellDelegate>
+#endif
{
NSArray* suggestions;
NSMutableString* mutablePrefix;
@@ -70,7 +74,9 @@
NSMutableCharacterSet* textualInputCharacters;
+#ifndef SP_REFACTOR
NSUserDefaults *prefs;
+#endif
}
- (id)initWithItems:(NSArray*)someSuggestions alreadyTyped:(NSString*)aUserString staticPrefix:(NSString*)aStaticPrefix
diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m
index b1101704..04627e2d 100644
--- a/Source/SPNarrowDownCompletion.m
+++ b/Source/SPNarrowDownCompletion.m
@@ -92,7 +92,7 @@
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
}
[self scrollRowToVisible:row];
- [[self delegate] insertAutocompletePlaceholder];
+ [(SPNarrowDownCompletion*)[self delegate] insertAutocompletePlaceholder];
return YES;
}
}
@@ -124,9 +124,15 @@
staticPrefix = nil;
suggestions = nil;
autocompletePlaceholderWasInserted = NO;
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
+#endif
+#ifndef SP_REFACTOR
tableFont = [NSUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] dataForKey:SPCustomQueryEditorFont]];
+#else
+ tableFont = [NSFont userFixedPitchFontOfSize:10.0];
+#endif
[self setupInterface];
syncArrowImages = [[NSArray alloc] initWithObjects:
@@ -270,7 +276,7 @@
if(!dictMode) {
NSUInteger maxLength = 0;
for(id w in someSuggestions) {
- NSUInteger len = [[w objectForKey:@"display"] length];
+ NSUInteger len = [(NSString*)[w objectForKey:@"display"] length];
if(len>maxLength) maxLength = len;
}
NSMutableString *dummy = [NSMutableString string];
@@ -1054,12 +1060,14 @@
if(backtickMode && !triggerMode)
[theView performSelector:@selector(moveRight:)];
// If it's a function or procedure append () and if a argument list can be retieved insert them as snippets
+#ifndef SP_REFACTOR
else if([prefs boolForKey:SPCustomQueryFunctionCompletionInsertsArguments] && ([[[filtered objectAtIndex:[theTableView selectedRow]] objectForKey:@"image"] hasPrefix:@"func"] || [[[filtered objectAtIndex:[theTableView selectedRow]] objectForKey:@"image"] hasPrefix:@"proc"]) && ![aString hasSuffix:@")"]) {
NSString *functionArgumentSnippet = [NSString stringWithFormat:@"(%@)", [[SPQueryController sharedQueryController] argumentSnippetForFunction:aString]];
[theView insertAsSnippet:functionArgumentSnippet atRange:[theView selectedRange]];
if([functionArgumentSnippet length] == 2)
[theView performSelector:@selector(moveLeft:)];
}
+#endif
}
- (void)completeAndInsertSnippet
@@ -1079,7 +1087,7 @@
NSString* candidateMatch = [selectedItem objectForKey:@"match"] ?: [selectedItem objectForKey:@"display"];
if([selectedItem objectForKey:@"isRef"]
&& ([[NSApp currentEvent] modifierFlags] & (NSShiftKeyMask))
- && [[selectedItem objectForKey:@"path"] length] && theAliasName == nil) {
+ && [(NSString*)[selectedItem objectForKey:@"path"] length] && theAliasName == nil) {
NSString *path = [[[selectedItem objectForKey:@"path"] componentsSeparatedByString:SPUniqueSchemaDelimiter] componentsJoinedByPeriodAndBacktickQuotedAndIgnoreFirst];
// Check if path's db name is the current selected db name
diff --git a/Source/SPNavigatorController.h b/Source/SPNavigatorController.h
index cdac2706..20b3a796 100644
--- a/Source/SPNavigatorController.h
+++ b/Source/SPNavigatorController.h
@@ -26,6 +26,7 @@
@interface SPNavigatorController : NSWindowController
{
+#ifndef SP_REFACTOR /* ivars */
IBOutlet id outlineSchema2;
IBOutlet id navigatorWindow;
IBOutlet id infoTable;
@@ -36,7 +37,7 @@
IBOutlet id schema12SplitView;
NSUserDefaults *prefs;
-
+#endif
NSMutableDictionary *schemaData;
NSMutableDictionary *schemaDataFiltered;
NSMutableDictionary *allSchemaKeys;
@@ -44,7 +45,7 @@
NSMutableArray *updatingConnections;
NSMutableDictionary *expandStatus2;
NSMutableDictionary *cachedSortedKeys;
-
+#ifndef SP_REFACTOR /* ivars */
NSString *selectedKey2;
NSRect selectionViewPort2;
BOOL ignoreUpdate;
@@ -60,11 +61,12 @@
NSImage *fieldIcon;
Class NSDictionaryClass;
-
+#endif
}
+ (SPNavigatorController *)sharedNavigatorController;
+#ifndef SP_REFACTOR /* method decls */
- (IBAction)outlineViewAction:(id)sender;
- (IBAction)reloadAllStructures:(id)sender;
- (IBAction)filterTree:(id)sender;
@@ -74,11 +76,13 @@
- (NSString*)tableInfoLabelForIndex:(NSInteger)index ofType:(NSInteger)type;
- (void)updateNavigator:(NSNotification *)aNotification;
+#endif
- (NSDictionary *)dbStructureForConnection:(NSString*)connectionID;
- (NSArray *)allSchemaKeysForConnection:(NSString*)connectionID;
- (NSArray *)getUniqueDbIdentifierFor:(NSString*)term andConnection:(NSString*)connectionID ignoreFields:(BOOL)ignoreFields;
+#ifndef SP_REFACTOR /* method decls */
- (BOOL)isUpdatingConnection:(NSString*)connectionID;
- (BOOL)isUpdating;
@@ -91,5 +95,6 @@
- (BOOL)schemaPathExistsForConnection:(NSString*)connectionID andDatabase:(NSString*)dbname;
- (void)removeDatabase:(NSString*)db_id forConnectionID:(NSString*)connectionID;
+#endif
@end
diff --git a/Source/SPNavigatorController.m b/Source/SPNavigatorController.m
index 36dddf39..be24948b 100644
--- a/Source/SPNavigatorController.m
+++ b/Source/SPNavigatorController.m
@@ -23,6 +23,7 @@
// More info at <http://code.google.com/p/sequel-pro/>
#import "SPNavigatorController.h"
+#ifndef SP_REFACTOR /* headers */
#import "RegexKitLite.h"
#import "SPNavigatorOutlineView.h"
#import "ImageAndTextCell.h"
@@ -34,18 +35,23 @@
#import "SPDatabaseViewController.h"
#import <objc/message.h>
+#endif
static SPNavigatorController *sharedNavigatorController = nil;
+#ifndef SP_REFACTOR /* pasteboard types */
#define DragFromNavigatorPboardType @"SPDragFromNavigatorPboardType"
#define DragTableDataFromNavigatorPboardType @"SPDragTableDataFromNavigatorPboardType"
+#endif
@implementation SPNavigatorController
+#ifndef SP_REFACTOR /* unused sort func */
static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* context)
{
return (NSComparisonResult)objc_msgSend(s1, @selector(localizedCompare:), s2);
}
+#endif
/**
@@ -80,13 +86,14 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
cachedSortedKeys = [[NSMutableDictionary alloc] init];
infoArray = [[NSMutableArray alloc] init];
updatingConnections = [[NSMutableArray alloc] init];
+#ifndef SP_REFACTOR
selectedKey2 = @"";
ignoreUpdate = NO;
isFiltered = NO;
isFiltering = NO;
[syncButton setState:NSOffState];
NSDictionaryClass = [NSDictionary class];
-
+#endif
}
return self;
@@ -103,6 +110,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
if(updatingConnections) [updatingConnections release];
if(expandStatus2) [expandStatus2 release];
if(cachedSortedKeys) [cachedSortedKeys release];
+#ifndef SP_REFACTOR /* dealloc ivars */
[connectionIcon release];
[databaseIcon release];
[tableIcon release];
@@ -110,6 +118,10 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
[procedureIcon release];
[functionIcon release];
[fieldIcon release];
+#endif
+#ifdef SP_REFACTOR /* patch */
+ [super dealloc];
+#endif
}
/**
* The following base protocol methods are implemented to ensure the singleton status of this class.
@@ -125,6 +137,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
- (void)release { }
+#ifndef SP_REFACTOR
/**
* Set the window's auto save name and initialise display
*/
@@ -487,6 +500,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
[[schemaData objectForKey:connectionID] removeObjectForKey:db_id];
[outlineSchema2 reloadData];
}
+#endif
- (NSDictionary *)dbStructureForConnection:(NSString*)connectionID
{
@@ -550,6 +564,7 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
return [NSArray arrayWithObjects:[NSNumber numberWithInt:0], @"", nil];
}
+#ifndef SP_REFACTOR
- (BOOL)isUpdatingConnection:(NSString*)connectionID
{
@@ -1253,4 +1268,5 @@ static NSComparisonResult compareStrings(NSString *s1, NSString *s2, void* conte
}
return @"";
}
+#endif
@end
diff --git a/Source/SPQueryController.h b/Source/SPQueryController.h
index 6f1d835d..c80da762 100644
--- a/Source/SPQueryController.h
+++ b/Source/SPQueryController.h
@@ -53,7 +53,9 @@
NSArray *completionFunctionList;
NSDictionary *functionArgumentSnippets;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSDateFormatter *dateFormatter;
pthread_mutex_t consoleLock;
diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m
index 346be3d6..e7a8cfc2 100644
--- a/Source/SPQueryController.m
+++ b/Source/SPQueryController.m
@@ -32,7 +32,6 @@
#define MESSAGE_TRUNCATE_CHARACTER_LENGTH 256
// Table view column identifier constants
-static NSString *SPTableViewMessageColumnID = @"message";
static NSString *SPTableViewDateColumnID = @"messageDate";
static NSString *SPTableViewConnectionColumnID = @"messageConnection";
@@ -158,20 +157,41 @@ static SPQueryController *sharedQueryController = nil;
*/
- (void)awakeFromNib
{
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
+#endif
[self setWindowFrameAutosaveName:@"QueryConsole"];
// Show/hide table columns
- [[consoleTableView tableColumnWithIdentifier:SPTableViewDateColumnID] setHidden:![prefs boolForKey:SPConsoleShowTimestamps]];
- [[consoleTableView tableColumnWithIdentifier:SPTableViewConnectionColumnID] setHidden:![prefs boolForKey:SPConsoleShowConnections]];
-
+ [[consoleTableView tableColumnWithIdentifier:SPTableViewDateColumnID] setHidden:
+#ifndef SP_REFACTOR
+ ![prefs boolForKey:SPConsoleShowTimestamps]
+#else
+ YES
+#endif
+ ];
+ [[consoleTableView tableColumnWithIdentifier:SPTableViewConnectionColumnID] setHidden:
+#ifndef SP_REFACTOR
+ ![prefs boolForKey:SPConsoleShowConnections]
+#else
+ YES
+#endif
+ ];
+
+#ifndef SP_REFACTOR
showSelectStatementsAreDisabled = ![prefs boolForKey:SPConsoleShowSelectsAndShows];
showHelpStatementsAreDisabled = ![prefs boolForKey:SPConsoleShowHelps];
+#else
+ showSelectStatementsAreDisabled = YES;
+ showHelpStatementsAreDisabled = YES;
+#endif
[self _updateFilterState];
+#ifndef SP_REFACTOR
[loggingDisabledTextField setStringValue:([prefs boolForKey:SPConsoleEnableLogging]) ? @"" : NSLocalizedString(@"Query logging is currently disabled", @"query logging disabled label")];
+#endif
// Setup data formatter
dateFormatter = [[NSDateFormatter alloc] init];
@@ -181,11 +201,17 @@ static SPQueryController *sharedQueryController = nil;
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
+#ifndef SP_REFACTOR
// Set the process table view's vertical gridlines if required
[consoleTableView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
+#endif
// Set the strutcture and index view's font
+#ifndef SP_REFACTOR
BOOL useMonospacedFont = [prefs boolForKey:SPUseMonospacedFonts];
+#else
+ BOOL useMonospacedFont = YES;
+#endif
for (NSTableColumn *column in [consoleTableView tableColumns])
{
@@ -540,16 +566,20 @@ static SPQueryController *sharedQueryController = nil;
// Set the global history coming from the Prefs as default if available
if(![historyContainer objectForKey:[new absoluteString]]) {
+#ifndef SP_REFACTOR
if([prefs objectForKey:SPQueryHistory]) {
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObjectsFromArray:[prefs objectForKey:SPQueryHistory]];
[historyContainer setObject:arr forKey:[new absoluteString]];
[arr release];
} else {
+#endif
NSMutableArray *arr = [[NSMutableArray alloc] init];
[historyContainer setObject:[NSMutableArray array] forKey:[new absoluteString]];
[arr release];
+#ifndef SP_REFACTOR
}
+#endif
}
// Set the doc-based content filters
@@ -652,9 +682,11 @@ static SPQueryController *sharedQueryController = nil;
[[doc valueForKeyPath:@"customQueryInstance"] performSelectorOnMainThread:@selector(historyItemsHaveBeenUpdated:) withObject:self waitUntilDone:NO];
+#ifndef SP_REFACTOR
// User did choose to clear the global history list
if(![fileURL isFileURL] && ![historyArray count])
[prefs setObject:historyArray forKey:SPQueryHistory];
+#endif
}
- (void)addFavorite:(NSDictionary *)favorite forFileURL:(NSURL *)fileURL
@@ -665,7 +697,11 @@ static SPQueryController *sharedQueryController = nil;
- (void)addHistory:(NSString *)history forFileURL:(NSURL *)fileURL
{
- NSInteger maxHistoryItems = [[prefs objectForKey:SPCustomQueryMaxHistoryItems] integerValue];
+#ifndef SP_REFACTOR
+ NSUInteger maxHistoryItems = [[prefs objectForKey:SPCustomQueryMaxHistoryItems] integerValue];
+#else
+ NSUInteger maxHistoryItems = 20;
+#endif
// Save each history item due to its document source
if([historyContainer objectForKey:[fileURL absoluteString]]) {
@@ -675,7 +711,7 @@ static SPQueryController *sharedQueryController = nil;
[uniquifier addItemsWithTitles:[historyContainer objectForKey:[fileURL absoluteString]]];
[uniquifier insertItemWithTitle:history atIndex:0];
- while ( [uniquifier numberOfItems] > maxHistoryItems )
+ while ( (NSUInteger)[uniquifier numberOfItems] > maxHistoryItems )
[uniquifier removeItemAtIndex:[uniquifier numberOfItems]-1];
[self replaceHistoryByArray:[uniquifier itemTitles] forFileURL:fileURL];
@@ -685,17 +721,19 @@ static SPQueryController *sharedQueryController = nil;
// Save history items coming from each Untitled document in the global Preferences successively
// regardingless of the source document.
if(![fileURL isFileURL]) {
+#ifndef SP_REFACTOR
// Remove all duplicates by using a NSPopUpButton
NSPopUpButton *uniquifier = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(0,0,0,0) pullsDown:YES];
[uniquifier addItemsWithTitles:[prefs objectForKey:SPQueryHistory]];
[uniquifier insertItemWithTitle:history atIndex:0];
- while ( [uniquifier numberOfItems] > maxHistoryItems )
+ while ( (NSUInteger)[uniquifier numberOfItems] > maxHistoryItems )
[uniquifier removeItemAtIndex:[uniquifier numberOfItems]-1];
[prefs setObject:[uniquifier itemTitles] forKey:SPQueryHistory];
[uniquifier release];
+#endif
}
}
@@ -773,6 +811,7 @@ static SPQueryController *sharedQueryController = nil;
[result addObject:fav];
}
+#ifndef SP_REFACTOR
if(includeGlobals && [prefs objectForKey:SPQueryFavorites]) {
for(id fav in [prefs objectForKey:SPQueryFavorites]) {
if([fav objectForKey:@"tabtrigger"] && [[fav objectForKey:@"tabtrigger"] isEqualToString:tabTrigger]) {
@@ -781,6 +820,7 @@ static SPQueryController *sharedQueryController = nil;
}
}
}
+#endif
return [result autorelease];
}
diff --git a/Source/SPQueryFavoriteManager.h b/Source/SPQueryFavoriteManager.h
index 6698ae61..0ebdc837 100644
--- a/Source/SPQueryFavoriteManager.h
+++ b/Source/SPQueryFavoriteManager.h
@@ -31,9 +31,15 @@
@end
-@interface SPQueryFavoriteManager : NSWindowController
+#ifndef SP_REFACTOR
+@interface SPQueryFavoriteManager : NSWindowController
+#else
+@interface SPQueryFavoriteManager : NSWindowController <NSOpenSavePanelDelegate>
+#endif
{
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSURL *delegatesFileURL;
SPDatabaseDocument *tableDocumentInstance;
diff --git a/Source/SPQueryFavoriteManager.m b/Source/SPQueryFavoriteManager.m
index 9316c5ec..7fe5797f 100644
--- a/Source/SPQueryFavoriteManager.m
+++ b/Source/SPQueryFavoriteManager.m
@@ -30,7 +30,9 @@
#import "SPConnectionController.h"
#import "RegexKitLite.h"
#import "SPTextView.h"
+#ifndef SP_REFACTOR
#import <BWToolkitFramework/BWAnchoredButtonBar.h>
+#endif
#define SP_MULTIPLE_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[multiple selection]", @"[multiple selection]")
#define SP_NO_SELECTION_PLACEHOLDER_STRING NSLocalizedString(@"[no selection]", @"[no selection]")
@@ -50,7 +52,9 @@
{
if ((self = [super initWithWindowNibName:@"QueryFavoriteManager"])) {
+#ifndef SP_REFACTOR
prefs = [NSUserDefaults standardUserDefaults];
+#endif
favorites = [[NSMutableArray alloc] init];
@@ -95,12 +99,14 @@
@"", @"query",
nil]];
+#ifndef SP_REFACTOR
// Build data source for global queryFavorites (as mutable copy! otherwise each
// change will be stored in the prefs at once)
if([prefs objectForKey:SPQueryFavorites]) {
for(id fav in [prefs objectForKey:SPQueryFavorites])
[favorites addObject:[[fav mutableCopy] autorelease]];
}
+#endif
[favorites addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[[[delegatesFileURL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] lastPathComponent], @"name",
@@ -131,8 +137,10 @@
// Set Remove button state
[removeButton setEnabled:([favoritesTableView numberOfSelectedRows] > 0)];
+#ifndef SP_REFACTOR /* split view delegate */
// Set the button bar delegate
[splitViewButtonBar setSplitViewDelegate:self];
+#endif
}
#pragma mark -
@@ -297,7 +305,9 @@
[panel setCanSelectHiddenExtension:YES];
[panel setCanCreateDirectories:YES];
+#ifndef SP_REFACTOR
[panel setAccessoryView:[SPEncodingPopupAccessory encodingAccessory:[prefs integerForKey:SPLastSQLFileEncoding] includeDefaultEntry:NO encodingPopUp:&encodingPopUp]];
+#endif
[encodingPopUp setEnabled:YES];
@@ -379,8 +389,10 @@
[[SPQueryController sharedQueryController] replaceFavoritesByArray:
[self queryFavoritesForFileURL:delegatesFileURL] forFileURL:delegatesFileURL];
+#ifndef SP_REFACTOR
// Update global preferences' list
[prefs setObject:[self queryFavoritesForFileURL:nil] forKey:SPQueryFavorites];
+#endif
// Inform all opened documents to update the query favorites list
for(id doc in [[NSApp delegate] orderedDocuments])
@@ -756,7 +768,7 @@
mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&convError] retain];
if(!spf || readError != nil || [convError length] || !(format == NSPropertyListXMLFormat_v1_0 || format == NSPropertyListBinaryFormat_v1_0)) {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Error while reading data file", @"error while reading data file")]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:NSLocalizedString(@"Error while reading data file", @"error while reading data file")]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
@@ -784,7 +796,7 @@
[favoritesTableView reloadData];
[spf release];
} else {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Error while reading data file", @"error while reading data file")]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:NSLocalizedString(@"Error while reading data file", @"error while reading data file")]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
@@ -810,8 +822,10 @@
if (returnCode == NSOKButton) {
NSError *error = nil;
+#ifndef SP_REFACTOR
[prefs setInteger:[[encodingPopUp selectedItem] tag] forKey:SPLastSQLFileEncoding];
[prefs synchronize];
+#endif
[[favoriteQueryTextView string] writeToFile:[panel filename] atomically:YES encoding:[[encodingPopUp selectedItem] tag] error:&error];
@@ -846,7 +860,7 @@
errorDescription:&err];
if(err != nil) {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Error while converting query favorite data", @"error while converting query favorite data")]
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithString:NSLocalizedString(@"Error while converting query favorite data", @"error while converting query favorite data")]
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
diff --git a/Source/SPSQLParser.m b/Source/SPSQLParser.m
index 458d4e25..6da67396 100644
--- a/Source/SPSQLParser.m
+++ b/Source/SPSQLParser.m
@@ -780,7 +780,7 @@ TO_BUFFER_STATE to_scan_string (const char *);
if (delimiter) [delimiter release];
delimiter = [[NSString alloc] initWithString:[delimiterCommandParts objectAtIndex:2]];
delimiterLengthMinusOne = [delimiter length] - 1;
- parsedToPosition = currentStringIndex + [[delimiterCommandParts objectAtIndex:1] length];
+ parsedToPosition = currentStringIndex + [(NSString*)[delimiterCommandParts objectAtIndex:1] length];
// Drop back to standard non-delimiter mode if the delimiter has ended
if ([delimiter isEqualToString:[NSString stringWithFormat:@"%C", character]]) {
diff --git a/Source/SPServerSupport.m b/Source/SPServerSupport.m
index 1aebc0d4..15c3555f 100644
--- a/Source/SPServerSupport.m
+++ b/Source/SPServerSupport.m
@@ -214,7 +214,7 @@
NSString *varName = [NSString stringWithUTF8String:ivar_getName(vars[j])];
if ([varName hasPrefix:@"supports"]) {
- [description appendFormat:@"\t%@ = %@\n", varName, ((BOOL)object_getIvar(self, vars[j])) ? @"YES" : @"NO"];
+ [description appendFormat:@"\t%@ = %@\n", varName, (object_getIvar(self, vars[j])) ? @"YES" : @"NO"];
}
}
diff --git a/Source/SPStringAdditions.h b/Source/SPStringAdditions.h
index 72967780..a45fbe0b 100644
--- a/Source/SPStringAdditions.h
+++ b/Source/SPStringAdditions.h
@@ -77,7 +77,9 @@ static inline id NSMutableAttributedStringAttributeAtIndex (NSMutableAttributedS
- (CGFloat)levenshteinDistanceWithWord:(NSString *)stringB;
+#ifndef SP_REFACTOR /* run self as bash commands */
- (NSString *)runBashCommandWithEnvironment:(NSDictionary*)shellEnvironment atCurrentDirectoryPath:(NSString*)path callerInstance:(id)caller contextInfo:(NSDictionary*)contextInfo error:(NSError**)theError;
- (NSString *)runBashCommandWithEnvironment:(NSDictionary*)shellEnvironment atCurrentDirectoryPath:(NSString*)path error:(NSError**)theError;
+#endif
@end
diff --git a/Source/SPStringAdditions.m b/Source/SPStringAdditions.m
index 79546f9a..31dbbfc6 100644
--- a/Source/SPStringAdditions.m
+++ b/Source/SPStringAdditions.m
@@ -452,6 +452,7 @@
}
+#ifndef SP_REFACTOR /* run self as bash commands */
/**
* Run self as BASH command(s) and return the result.
* This task can be interrupted by pressing ⌘.
@@ -739,6 +740,7 @@
{
return [self runBashCommandWithEnvironment:shellEnvironment atCurrentDirectoryPath:path callerInstance:nil contextInfo:nil error:theError];
}
+#endif
/**
* Returns the minimum of a, b and c.
diff --git a/Source/SPTableContent.h b/Source/SPTableContent.h
index 6c0f2ab7..8ad30614 100644
--- a/Source/SPTableContent.h
+++ b/Source/SPTableContent.h
@@ -29,11 +29,17 @@
@class SPDatabaseDocument, SPCopyTable, SPTextAndLinkCell, SPHistoryController, SPTableInfo, SPDataStorage, SPTextView, SPFieldEditorController;
-@interface SPTableContent : NSObject
+@class SPTableData, SPDatabaseDocument, SPTablesList;
+
+#ifndef SP_REFACTOR
+@interface SPTableContent : NSObject
+#else
+@interface SPTableContent : NSObject <NSTableViewDelegate, NSTableViewDataSource>
+#endif
{
IBOutlet SPDatabaseDocument *tableDocumentInstance;
IBOutlet id tablesListInstance;
- IBOutlet id tableDataInstance;
+ IBOutlet SPTableData* tableDataInstance;
IBOutlet id tableSourceInstance;
IBOutlet SPTableInfo *tableInfoInstance;
@@ -92,7 +98,9 @@
NSNumber *sortCol;
BOOL isEditingRow, isEditingNewRow, isSavingRow, isDesc, setLimit;
BOOL isFiltered, isLimited, isInterruptedLoad, maxNumRowsIsEstimate;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSInteger currentlyEditingRow, maxNumRows;
NSMutableDictionary *contentFilters;
@@ -241,4 +249,10 @@
- (void)updateFilterTableClause:(id)currentValue;
- (NSString*)escapeFilterTableDefaultOperator:(NSString*)anOperator;
+#ifdef SP_REFACTOR /* glue */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)doc;
+- (void)setTableListInstance:(SPTablesList*)list;
+- (void)setConnection:(MCPConnection *)theConnection;
+#endif
+
@end
diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m
index 9cf2e72f..a5f7d373 100644
--- a/Source/SPTableContent.m
+++ b/Source/SPTableContent.m
@@ -49,6 +49,7 @@
#import "SPDatabaseViewController.h"
#import "SPAppController.h"
#import "SPBundleHTMLOutputController.h"
+#import "SPCustomQuery.h"
@interface SPTableContent (Private)
- (BOOL)cancelRowEditing;
@@ -108,7 +109,9 @@
isLimited = NO;
isInterruptedLoad = NO;
+#ifndef SP_REFACTOR /* init ivars */
prefs = [NSUserDefaults standardUserDefaults];
+#endif
usedQuery = [[NSString alloc] initWithString:@""];
@@ -157,8 +160,10 @@
if (_mainNibLoaded) return;
_mainNibLoaded = YES;
+#ifndef SP_REFACTOR /* ui manipulation */
// Set the table content view's vertical gridlines if required
[tableContentView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
+#endif
// Load the pagination view, keeping references to the top-level objects for later release
NSArray *paginationViewTopLevelObjects = nil;
@@ -186,7 +191,11 @@
[filterTableDistinctMenuItem setState:(filterTableDistinct) ? NSOnState : NSOffState];
[filterTableNegateCheckbox setState:(filterTableNegate) ? NSOnState : NSOffState];
[filterTableLiveSearchCheckbox setState:NSOffState];
+#ifndef SP_REFACTOR /* patch */
filterTableDefaultOperator = [[self escapeFilterTableDefaultOperator:[prefs objectForKey:SPFilterTableDefaultOperator]] retain];
+#else
+ filterTableDefaultOperator = [[self escapeFilterTableDefaultOperator:nil] retain];
+#endif
// Add observers for document task activity
[[NSNotificationCenter defaultCenter] addObserver:self
@@ -252,7 +261,7 @@
// Scroll the viewport to the saved location
selectionViewportToRestore.size = [tableContentView visibleRect].size;
- [[tableContentView onMainThread] scrollRectToVisible:selectionViewportToRestore];
+ [(SPCopyTable*)[tableContentView onMainThread] scrollRectToVisible:selectionViewportToRestore];
}
// Restore selection indexes if appropriate
@@ -285,11 +294,19 @@
{
NSString *newTableName;
NSInteger i;
- NSNumber *colWidth, *sortColumnNumberToRestore = nil;
+ NSNumber
+#ifndef SP_REFACTOR
+ *colWidth,
+#endif
+ *sortColumnNumberToRestore = nil;
NSArray *columnNames;
NSDictionary *columnDefinition;
NSTableColumn *theCol, *filterCol;
- BOOL enableInteraction = ![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent] || ![tableDocumentInstance isWorking];
+ BOOL enableInteraction =
+#ifndef SP_REFACTOR /* checking toolbar state */
+ ![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent] ||
+#endif
+ ![tableDocumentInstance isWorking];
if (!tableDetails) {
@@ -442,8 +459,16 @@
}
}
+#ifndef SP_REFACTOR /* patch */
NSString *nullValue = [prefs objectForKey:SPNullValue];
+#else
+ NSString* nullValue = @"NULL";
+#endif
+#ifndef SP_REFACTOR /* get font from prefs */
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]];
+#else
+ NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
+#endif
[tableContentView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{ǞṶḹÜ∑zgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
// Add the new columns to the table and filterTable
@@ -453,7 +478,7 @@
// Set up the column
theCol = [[NSTableColumn alloc] initWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
[[theCol headerCell] setStringValue:[columnDefinition objectForKey:@"name"]];
- [theCol setHeaderToolTip:[NSString stringWithFormat:@"%@ – %@%@%@%@",
+ [theCol setHeaderToolTip:[NSString stringWithFormat:@"%@ – %@%@%@%@",
[columnDefinition objectForKey:@"name"],
[columnDefinition objectForKey:@"type"],
([columnDefinition objectForKey:@"length"]) ? [NSString stringWithFormat:@"(%@)", [columnDefinition objectForKey:@"length"]] : @"",
@@ -530,11 +555,13 @@
// Assign the data cell
[theCol setDataCell:dataCell];
+#ifndef SP_REFACTOR /* prefs access */
// Set the width of this column to saved value if exists
colWidth = [[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]]] objectForKey:[tablesListInstance tableName]] objectForKey:[columnDefinition objectForKey:@"name"]];
if ( colWidth ) {
[theCol setWidth:[colWidth floatValue]];
}
+#endif
// Set the column to be reselected for sorting if appropriate
if (sortColumnToRestore && [sortColumnToRestore isEqualToString:[columnDefinition objectForKey:@"name"]])
@@ -572,7 +599,7 @@
}
// Store the current first responder so filter field doesn't steal focus
- id currentFirstResponder = [[tableDocumentInstance parentWindow] firstResponder];
+ id currentFirstResponder = [[NSApp keyWindow] firstResponder];
// Enable and initialize filter fields (with tags for position of menu item and field position)
[fieldField setEnabled:YES];
@@ -610,10 +637,13 @@
}
// Restore page number if limiting is set
- if ([prefs boolForKey:SPLimitResults]) contentPage = pageToRestore;
+#ifndef SP_REFACTOR /* patch */
+ if ([prefs boolForKey:SPLimitResults])
+#endif
+ contentPage = pageToRestore;
// Restore first responder
- [[tableDocumentInstance parentWindow] makeFirstResponder:currentFirstResponder];
+ [[NSApp keyWindow] makeFirstResponder:currentFirstResponder];
// Set the state of the table buttons
[addButton setEnabled:(enableInteraction && [tablesListInstance tableType] == SPTableTypeTable)];
@@ -688,14 +718,23 @@
if (isDesc) [queryString appendString:@" DESC"];
}
+#ifndef SP_REFACTOR /* patch */
// Check to see if a limit needs to be applied
- if ([prefs boolForKey:SPLimitResults]) {
-
+ if ([prefs boolForKey:SPLimitResults])
+#else
+ if ( YES )
+#endif
+ {
// Ensure the page supplied is within the appropriate limits
if (contentPage <= 0)
contentPage = 1;
+#ifndef SP_REFACTOR /* patch */
else if (contentPage > 1 && (NSInteger)(contentPage - 1) * [prefs integerForKey:SPLimitResultsValue] >= maxNumRows)
- contentPage = ceilf((CGFloat)maxNumRows / [prefs floatForKey:SPLimitResultsValue]);
+ contentPage = ceil((CGFloat)maxNumRows / [prefs floatForKey:SPLimitResultsValue]);
+#else
+ else if (contentPage > 1 && (contentPage - 1) * 1000 >= maxNumRows)
+ contentPage = ceil((CGFloat)maxNumRows / 1000);
+#endif
// If the result set is from a late page, take a copy of the string to allow resetting limit
// if no results are found
@@ -704,11 +743,22 @@
}
// Append the limit settings
- [queryString appendFormat:@" LIMIT %ld,%ld", (long)((contentPage-1)*[prefs integerForKey:SPLimitResultsValue]), (long)[prefs integerForKey:SPLimitResultsValue]];
+ [queryString appendFormat:@" LIMIT %ld,%ld", (long)((contentPage-1)*
+#ifndef SP_REFACTOR /* patch */
+ [prefs integerForKey:SPLimitResultsValue]), (long)[prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000), (long)1000
+#endif
+ ];
// Update the approximate count of the rows to load
+#ifndef SP_REFACTOR /* patch */
rowsToLoad = rowsToLoad - (contentPage-1)*[prefs integerForKey:SPLimitResultsValue];
if (rowsToLoad > [prefs integerForKey:SPLimitResultsValue]) rowsToLoad = [prefs integerForKey:SPLimitResultsValue];
+#else
+ rowsToLoad = rowsToLoad - (contentPage-1)*1000;
+ if (rowsToLoad > 1000) rowsToLoad = 1000;
+#endif
}
// If within a task, allow this query to be cancelled
@@ -736,14 +786,30 @@
if (streamingResult) [streamingResult release];
// If the result is empty, and a late page is selected, reset the page
- if (!fullTableReloadRequired && [prefs boolForKey:SPLimitResults] && queryStringBeforeLimit && !tableRowsCount && ![mySQLConnection queryCancelled]) {
+ if (!fullTableReloadRequired
+#ifndef SP_REFACTOR
+ && [prefs boolForKey:SPLimitResults]
+#endif
+ && queryStringBeforeLimit && !tableRowsCount && ![mySQLConnection queryCancelled]) {
contentPage = 1;
previousTableRowsCount = tableRowsCount;
- queryString = [NSMutableString stringWithFormat:@"%@ LIMIT 0,%ld", queryStringBeforeLimit, (long)[prefs integerForKey:SPLimitResultsValue]];
+ queryString = [NSMutableString stringWithFormat:@"%@ LIMIT 0,%ld", queryStringBeforeLimit,
+#ifndef SP_REFACTOR
+ (long)[prefs integerForKey:SPLimitResultsValue]
+#else
+ (long)1000
+#endif
+ ];
[self setUsedQuery:queryString];
streamingResult = [[mySQLConnection streamingQueryString:queryString] retain];
if (streamingResult) {
- [self processResultIntoDataStorage:streamingResult approximateRowCount:[prefs integerForKey:SPLimitResultsValue]];
+ [self processResultIntoDataStorage:streamingResult approximateRowCount:
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ ];
[streamingResult release];
}
}
@@ -756,9 +822,17 @@
// End cancellation ability
[tableDocumentInstance disableTaskCancellation];
- if ([prefs boolForKey:SPLimitResults]
- && (contentPage > 1
- || (NSInteger)tableRowsCount == [prefs integerForKey:SPLimitResultsValue]))
+ if (
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPLimitResults] &&
+#endif
+ (contentPage > 1 || (NSInteger)tableRowsCount ==
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ ))
{
isLimited = YES;
} else {
@@ -785,15 +859,15 @@
if ([mySQLConnection queryErrored] && ![mySQLConnection queryCancelled]) {
if(activeFilter == 0) {
if(filterString)
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"The table data couldn't be loaded presumably due to used filter clause. \n\nMySQL said: %@", @"message of panel when loading of table failed and presumably due to used filter argument"), [mySQLConnection getLastErrorMessage]]);
else
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"The table data couldn't be loaded.\n\nMySQL said: %@", @"message of panel when loading of table failed"), [mySQLConnection getLastErrorMessage]]);
}
// Filter task came from filter table
else if(activeFilter == 1){
- [filterTableWindow setTitle:[NSString stringWithFormat:@"%@ – %@", NSLocalizedString(@"Filter", @"filter label"), NSLocalizedString(@"WHERE clause not valid", @"WHERE clause not valid")]];
+ [filterTableWindow setTitle:[NSString stringWithFormat:@"%@ – %@", NSLocalizedString(@"Filter", @"filter label"), NSLocalizedString(@"WHERE clause not valid", @"WHERE clause not valid")]];
}
} else {
// Trigger a full reload if required
@@ -822,8 +896,14 @@
NSAutoreleasePool *dataLoadingPool;
NSProgressIndicator *dataLoadingIndicator = [tableDocumentInstance valueForKey:@"queryProgressBar"];
- BOOL prefsLoadBlobsAsNeeded = [prefs boolForKey:SPLoadBlobsAsNeeded];
-
+ BOOL prefsLoadBlobsAsNeeded =
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPLoadBlobsAsNeeded]
+#else
+ NO
+#endif
+ ;
+
// Build up an array of which columns are blobs for faster iteration
for ( i = 0; i < dataColumnsCount ; i++ ) {
columnBlobStatuses[i] = [tableDataInstance columnIsBlobOrText:[NSArrayObjectAtIndex(dataColumns, i) objectForKey:@"name"]];
@@ -918,7 +998,7 @@
}
// If the clause has the placeholder $BINARY that placeholder will be replaced
- // by BINARY if the user pressed ⇧ while invoking 'Filter' otherwise it will
+ // by BINARY if the user pressed ‚áß while invoking 'Filter' otherwise it will
// replaced by @"".
BOOL caseSensitive = (([[[NSApp onMainThread] currentEvent] modifierFlags]
& (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask)) > 0);
@@ -933,21 +1013,21 @@
// Current selected filter type
if(![contentFilters objectForKey:compareType]) {
- NSLog(@"Error while retrieving filters. Filter type “%@” unknown.", compareType);
+ NSLog(@"Error while retrieving filters. Filter type “%@” unknown.", compareType);
NSBeep();
return nil;
}
NSDictionary *filter = [[contentFilters objectForKey:compareType] objectAtIndex:[[compareField selectedItem] tag]];
if(![filter objectForKey:@"NumberOfArguments"]) {
- NSLog(@"Error while retrieving filter clause. No “Clause” or/and “NumberOfArguments” key found.");
+ NSLog(@"Error while retrieving filter clause. No “Clause” or/and “NumberOfArguments” key found.");
NSBeep();
return nil;
}
if(![filter objectForKey:@"Clause"] || ![(NSString *)[filter objectForKey:@"Clause"] length]) {
- SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
NSLocalizedString(@"Content Filter clause is empty.", @"content filter clause is empty tooltip."));
return nil;
@@ -1011,7 +1091,7 @@
// Check number of placeholders and given 'NumberOfArguments'
if([clause replaceOccurrencesOfString:@"%@" withString:@"%@" options:NSLiteralSearch range:NSMakeRange(0, [clause length])] != numberOfArguments) {
- NSLog(@"Error while setting filter string. “NumberOfArguments” differs from the number of arguments specified in “Clause”.");
+ NSLog(@"Error while setting filter string. “NumberOfArguments” differs from the number of arguments specified in “Clause”.");
NSBeep();
[argument release];
[firstBetweenArgument release];
@@ -1129,7 +1209,13 @@
// If a limit is active, display a string suggesting a limit is active
} else if (!isFiltered && isLimited) {
- NSUInteger limitStart = (contentPage-1)*[prefs integerForKey:SPLimitResultsValue] + 1;
+ NSUInteger limitStart = (contentPage-1)*
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ + 1;
[countString appendFormat:NSLocalizedString(@"Rows %@ - %@ of %@%@ from table", @"text showing how many rows are in the limited result"), [numberFormatter stringFromNumber:[NSNumber numberWithUnsignedInteger:limitStart]], [numberFormatter stringFromNumber:[NSNumber numberWithUnsignedInteger:(limitStart+tableRowsCount-1)]], maxNumRowsIsEstimate?@"~":@"", maxRowsString];
// If just a filter is active, show a count and an indication a filter is active
@@ -1141,7 +1227,13 @@
// If both a filter and limit is active, display full string
} else {
- NSUInteger limitStart = (contentPage-1)*[prefs integerForKey:SPLimitResultsValue] + 1;
+ NSUInteger limitStart = (contentPage-1)*
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ + 1;
[countString appendFormat:NSLocalizedString(@"Rows %@ - %@ from filtered matches", @"text showing how many rows are in the limited filter match"), [numberFormatter stringFromNumber:[NSNumber numberWithUnsignedInteger:limitStart]], [numberFormatter stringFromNumber:[NSNumber numberWithUnsignedInteger:(limitStart+tableRowsCount-1)]]];
}
@@ -1308,10 +1400,26 @@
[self setPaginationViewVisibility:FALSE];
// Select the correct pagination value
- if (![prefs boolForKey:SPLimitResults] || [paginationPageField integerValue] <= 0)
+ if (
+#ifndef SP_REFACTOR
+ ![prefs boolForKey:SPLimitResults] ||
+#endif
+ [paginationPageField integerValue] <= 0)
contentPage = 1;
- else if (([paginationPageField integerValue] - 1) * [prefs integerForKey:SPLimitResultsValue] >= maxNumRows)
- contentPage = ceilf((CGFloat)maxNumRows / [prefs floatForKey:SPLimitResultsValue]);
+ else if (([paginationPageField integerValue] - 1) *
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ >= maxNumRows)
+ contentPage = ceil((CGFloat)maxNumRows /
+#ifndef SP_REFACTOR
+ [prefs floatForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ );
else
contentPage = [paginationPageField integerValue];
@@ -1357,13 +1465,13 @@
- (IBAction)toggleFilterField:(id)sender
{
- // Check if user called "Edit Filter…"
+ // Check if user called "Edit Filter…"
if([[compareField selectedItem] tag] == (NSInteger)[[contentFilters objectForKey:compareType] count]) {
[self openContentFilterManager];
return;
}
- // Remember last selection for "Edit filter…"
+ // Remember last selection for "Edit filter…"
lastSelectedContentFilterIndex = [[compareField selectedItem] tag];
NSDictionary *filter = [[contentFilters objectForKey:compareType] objectAtIndex:lastSelectedContentFilterIndex];
@@ -1433,7 +1541,13 @@
[paginationPageField setIntegerValue:(contentPage - 1)];
[self filterTable:sender];
} else if (sender == paginationNextButton) {
- if ((NSInteger)contentPage * [prefs integerForKey:SPLimitResultsValue] >= maxNumRows) return;
+ if ((NSInteger)contentPage *
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ >= maxNumRows) return;
[paginationPageField setIntegerValue:(contentPage + 1)];
[self filterTable:sender];
}
@@ -1461,19 +1575,19 @@
paginationViewFrame.size.height = paginationViewHeight;
[paginationButton setState:NSOnState];
[paginationButton setImage:[NSImage imageNamed:@"button_action"]];
- [[tableDocumentInstance parentWindow] makeFirstResponder:paginationPageField];
+ [[paginationPageField window] makeFirstResponder:paginationPageField];
} else {
if (paginationViewFrame.size.height == 0) return;
paginationViewFrame.size.height = 0;
[paginationButton setState:NSOffState];
[paginationButton setImage:[NSImage imageNamed:@"button_pagination"]];
- if ([[tableDocumentInstance parentWindow] firstResponder] == paginationPageField
- || ([[[tableDocumentInstance parentWindow] firstResponder] respondsToSelector:@selector(superview)]
- && [(id)[[tableDocumentInstance parentWindow] firstResponder] superview]
- && [[(id)[[tableDocumentInstance parentWindow] firstResponder] superview] respondsToSelector:@selector(superview)]
- && [[(id)[[tableDocumentInstance parentWindow] firstResponder] superview] superview] == paginationPageField))
+ if ([[paginationPageField window] firstResponder] == paginationPageField
+ || ([[[paginationPageField window] firstResponder] respondsToSelector:@selector(superview)]
+ && [(id)[[paginationPageField window] firstResponder] superview]
+ && [[(id)[[paginationPageField window] firstResponder] superview] respondsToSelector:@selector(superview)]
+ && [[(id)[[paginationPageField window] firstResponder] superview] superview] == paginationPageField))
{
- [[tableDocumentInstance parentWindow] makeFirstResponder:nil];
+ [[paginationPageField window] makeFirstResponder:nil];
}
}
@@ -1486,7 +1600,13 @@
*/
- (void) updatePaginationState
{
- NSUInteger maxPage = ceilf((CGFloat)maxNumRows / [prefs floatForKey:SPLimitResultsValue]);
+ NSUInteger maxPage = ceil((CGFloat)maxNumRows /
+#ifndef SP_REFACTOR
+ [prefs floatForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ );
if (isFiltered && !isLimited) {
maxPage = contentPage;
}
@@ -1496,13 +1616,21 @@
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
// Set up the previous page button
- if ([prefs boolForKey:SPLimitResults] && contentPage > 1)
+ if (
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPLimitResults] &&
+#endif
+ contentPage > 1)
[paginationPreviousButton setEnabled:enabledMode];
else
[paginationPreviousButton setEnabled:NO];
// Set up the next page button
- if ([prefs boolForKey:SPLimitResults] && contentPage < maxPage)
+ if (
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPLimitResults] &&
+#endif
+ contentPage < maxPage)
[paginationNextButton setEnabled:enabledMode];
else
[paginationNextButton setEnabled:NO];
@@ -1660,13 +1788,14 @@
if ( [tableContentView numberOfSelectedRows] < 1 )
return;
if ( [tableContentView numberOfSelectedRows] > 1 ) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil, NSLocalizedString(@"You can only copy single rows.", @"message of panel when trying to copy multiple rows"));
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil, NSLocalizedString(@"You can only copy single rows.", @"message of panel when trying to copy multiple rows"));
return;
}
//copy row
tempRow = [tableValues rowContentsAtIndex:[tableContentView selectedRow]];
+#ifndef SP_REFACTOR
//if we don't show blobs, read data for this duplicate column from db
if ([prefs boolForKey:SPLoadBlobsAsNeeded]) {
// Abort if there are no indices on this table - argumentForRow will display an error.
@@ -1677,6 +1806,7 @@
queryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@", [selectedTable backtickQuotedString], [self argumentForRow:[tableContentView selectedRow]]]];
dbDataRow = [queryResult fetchRowAsArray];
}
+#endif
//set autoincrement fields to NULL
queryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW COLUMNS FROM %@", [selectedTable backtickQuotedString]]];
@@ -1686,7 +1816,13 @@
row = [queryResult fetchRowAsDictionary];
if ( [[row objectForKey:@"Extra"] isEqualToString:@"auto_increment"] ) {
[tempRow replaceObjectAtIndex:i withObject:[NSNull null]];
- } else if ( [tableDataInstance columnIsBlobOrText:[row objectForKey:@"Field"]] && [prefs boolForKey:SPLoadBlobsAsNeeded] && dbDataRow) {
+ } else if ( [tableDataInstance columnIsBlobOrText:[row objectForKey:@"Field"]] &&
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPLoadBlobsAsNeeded]
+#else
+ NO
+#endif
+ && dbDataRow) {
[tempRow replaceObjectAtIndex:i withObject:[dbDataRow objectAtIndex:i]];
}
}
@@ -1715,7 +1851,7 @@
// return;
// cancel editing (maybe this is not the ideal method -- see xcode docs for that method)
- [[tableDocumentInstance parentWindow] endEditingFor:nil];
+ [[NSApp keyWindow] endEditingFor:nil];
if (![tableContentView numberOfSelectedRows])
@@ -1748,7 +1884,9 @@
// If table has PRIMARY KEY ask for resetting the auto increment after deletion if given
if(![[tableDataInstance statusValueForKey:@"Auto_increment"] isKindOfClass:[NSNull class]]) {
[alert setShowsSuppressionButton:YES];
+#ifndef SP_REFACTOR
[[alert suppressionButton] setState:([prefs boolForKey:SPResetAutoIncrementAfterDeletionOfAllRows]) ? NSOnState : NSOffState];
+#endif
[[[alert suppressionButton] cell] setControlSize:NSSmallControlSize];
[[[alert suppressionButton] cell] setFont:[NSFont systemFontOfSize:11]];
[[alert suppressionButton] setTitle:NSLocalizedString(@"Reset AUTO_INCREMENT after deletion?", @"reset auto_increment after deletion of all rows message")];
@@ -1766,7 +1904,7 @@
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the selected %ld rows from this table? This action cannot be undone.", @"delete rows informative message"), (long)[tableContentView numberOfSelectedRows]]];
}
- [alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(removeRowSheetDidEnd:returnCode:contextInfo:) contextInfo:contextInfo];
+ [alert beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(removeRowSheetDidEnd:returnCode:contextInfo:) contextInfo:contextInfo];
}
/**
@@ -1778,13 +1916,18 @@
NSString *wherePart;
NSInteger i, errors;
BOOL consoleUpdateStatus;
- BOOL reloadAfterRemovingRow = [prefs boolForKey:SPReloadAfterRemovingRow];
-
+ BOOL reloadAfterRemovingRow =
+#ifndef SP_REFACTOR
+ [prefs boolForKey:SPReloadAfterRemovingRow]
+#else
+ NO
+#endif
+ ;
// Order out current sheet to suppress overlapping of sheets
[[alert window] orderOut:nil];
- if ([contextInfo isEqualToString:@"removeallrows"]) {
- if (returnCode == NSAlertDefaultReturn) {
+ if ( [(NSString*)contextInfo isEqualToString:@"removeallrows"] ) {
+ if ( returnCode == NSAlertDefaultReturn ) {
// Check if the user is currently editing a row, and revert to ensure a somewhat
// consistent state if deletion fails.
@@ -1800,9 +1943,13 @@
// Reset auto increment if suppression button was ticked
if([[alert suppressionButton] state] == NSOnState) {
[tableSourceInstance setAutoIncrementTo:@"1"];
+#ifndef SP_REFACTOR
[prefs setBool:YES forKey:SPResetAutoIncrementAfterDeletionOfAllRows];
+#endif
} else {
+#ifndef SP_REFACTOR
[prefs setBool:NO forKey:SPResetAutoIncrementAfterDeletionOfAllRows];
+#endif
}
[self reloadTable:self];
@@ -1816,9 +1963,8 @@
afterDelay:0.3];
}
}
- }
- else if ([contextInfo isEqualToString:@"removerow"]) {
- if (returnCode == NSAlertDefaultReturn) {
+ } else if ( [(NSString*)contextInfo isEqualToString:@"removerow"] ) {
+ if ( returnCode == NSAlertDefaultReturn ) {
[selectedRows addIndexes:[tableContentView selectedRowIndexes]];
//check if the user is currently editing a row
@@ -2343,6 +2489,7 @@
}
}
+#ifndef SP_REFACTOR /* content filters */
// Load global user-defined content filters
if([prefs objectForKey:SPContentFilters]
&& [contentFilters objectForKey:compareType]
@@ -2350,6 +2497,7 @@
{
[[contentFilters objectForKey:compareType] addObjectsFromArray:[[prefs objectForKey:SPContentFilters] objectForKey:compareType]];
}
+#endif
// Load doc-based user-defined content filters
if([[SPQueryController sharedQueryController] contentFilterForFileURL:[tableDocumentInstance fileURL]]) {
@@ -2373,7 +2521,7 @@
[tip setString:[[filter objectForKey:@"Clause"] stringByReplacingOccurrencesOfRegex:@"(?<!\\\\)(\\$\\{.*?\\})" withString:@"[arg]"]];
if([tip isMatchedByRegex:@"(?<!\\\\)\\$BINARY"]) {
[tip replaceOccurrencesOfRegex:@"(?<!\\\\)\\$BINARY" withString:@""];
- [tip appendString:NSLocalizedString(@"\n\nPress ⇧ for binary search (case-sensitive).", @"\n\npress shift for binary search tooltip message")];
+ [tip appendString:NSLocalizedString(@"\n\nPress ‚áß for binary search (case-sensitive).", @"\n\npress shift for binary search tooltip message")];
}
[tip flushCachedRegexData];
[tip replaceOccurrencesOfRegex:@"(?<!\\\\)\\$CURRENT_FIELD" withString:[[fieldField titleOfSelectedItem] backtickQuotedString]];
@@ -2391,8 +2539,8 @@
}
[menu addItem:[NSMenuItem separatorItem]];
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Edit Filters…", @"edit filter") action:NULL keyEquivalent:@""];
- [item setToolTip:NSLocalizedString(@"Edit user-defined Filters…", @"edit user-defined filter")];
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Edit Filters…", @"edit filter") action:NULL keyEquivalent:@""];
+ [item setToolTip:NSLocalizedString(@"Edit user-defined Filters…", @"edit user-defined filter")];
[item setTag:i];
[menu addItem:item];
[item release];
@@ -2417,13 +2565,15 @@
[compareField selectItemWithTag:lastSelectedContentFilterIndex];
// init query favorites controller
+#ifndef SP_REFACTOR
[prefs synchronize];
+#endif
if(contentFilterManager) [contentFilterManager release];
contentFilterManager = [[SPContentFilterManager alloc] initWithDelegate:self forFilterType:compareType];
// Open query favorite manager
[NSApp beginSheet:[contentFilterManager window]
- modalForWindow:[tableDocumentInstance parentWindow]
+ modalForWindow:[NSApp keyWindow]
modalDelegate:contentFilterManager
didEndSelector:nil
contextInfo:nil];
@@ -2546,12 +2696,14 @@
// If no rows have been changed, show error if appropriate.
if ( ![mySQLConnection affectedRows] && ![mySQLConnection queryErrored] ) {
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPShowNoAffectedRowsError] ) {
- SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
NSLocalizedString(@"The row was not written to the MySQL database. You probably haven't changed anything.\nReload the table to be sure that the row exists and use a primary key for your table.\n(This error can be turned off in the preferences.)", @"message of panel when no rows have been affected after writing to the db"));
} else {
NSBeep();
}
+#endif
// If creating a new row, remove the row; otherwise revert the row contents
if (isEditingNewRow) {
@@ -2574,30 +2726,35 @@
// New row created successfully
if ( isEditingNewRow ) {
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPReloadAfterAddingRow] ) {
- [[tableDocumentInstance parentWindow] endEditingFor:nil];
+ [[NSApp keyWindow] endEditingFor:nil];
previousTableRowsCount = tableRowsCount;
[self loadTableValues];
} else {
-
+#endif
// Set the insertId for fields with auto_increment
for ( i = 0; i < [dataColumns count] ; i++ ) {
if ([[NSArrayObjectAtIndex(dataColumns, i) objectForKey:@"autoincrement"] integerValue]) {
[tableValues replaceObjectInRow:currentlyEditingRow column:i withObject:[[NSNumber numberWithUnsignedLongLong:[mySQLConnection insertId]] description]];
}
}
+#ifndef SP_REFACTOR
}
+#endif
isEditingNewRow = NO;
// Existing row edited successfully
} else {
// Reload table if set to - otherwise no action required.
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPReloadAfterEditingRow] ) {
- [[tableDocumentInstance parentWindow] endEditingFor:nil];
+ [[NSApp keyWindow] endEditingFor:nil];
previousTableRowsCount = tableRowsCount;
[self loadTableValues];
}
+#endif
}
currentlyEditingRow = -1;
@@ -2605,7 +2762,7 @@
// Report errors which have occurred
} else {
- SPBeginAlertSheet(NSLocalizedString(@"Couldn't write row", @"Couldn't write row error"), NSLocalizedString(@"Edit row", @"Edit row button"), NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [tableDocumentInstance parentWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Couldn't write row", @"Couldn't write row error"), NSLocalizedString(@"Edit row", @"Edit row button"), NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [NSApp keyWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
[NSString stringWithFormat:NSLocalizedString(@"MySQL said:\n\n%@", @"message of panel when error while adding row to db"), [mySQLConnection getLastErrorMessage]]);
return NO;
}
@@ -2622,7 +2779,7 @@
// Edit row selected - reselect the row, and start editing.
if ( returnCode == NSAlertDefaultReturn ) {
[tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:currentlyEditingRow] byExtendingSelection:NO];
- [tableContentView performSelector:@selector(keyDown:) withObject:[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:0x24] afterDelay:0.0];
+ [tableContentView performSelector:@selector(keyDown:) withObject:[NSEvent keyEventWithType:NSKeyDown location:NSMakePoint(0,0) modifierFlags:0 timestamp:0 windowNumber:[[tableContentView window] windowNumber] context:[NSGraphicsContext currentContext] characters:nil charactersIgnoringModifiers:nil isARepeat:NO keyCode:0x24] afterDelay:0.0];
// Discard changes selected
} else {
@@ -2647,9 +2804,9 @@
// Save any edits which have been made but not saved to the table yet;
// but not for any NSSearchFields which could cause a crash for undo, redo.
- if([[[tableDocumentInstance parentWindow] firstResponder] respondsToSelector:@selector(delegate)]
- && ![[(id)[[tableDocumentInstance parentWindow] firstResponder] delegate] isKindOfClass:[NSSearchField class]])
- [[tableDocumentInstance parentWindow] endEditingFor:nil];
+ if([[[tableContentView window] firstResponder] respondsToSelector:@selector(delegate)]
+ && ![[(id)[[tableContentView window] firstResponder] delegate] isKindOfClass:[NSSearchField class]])
+ [[tableContentView window] endEditingFor:nil];
// If no rows are currently being edited, or a save is in progress, return success at once.
if (!isEditingRow || isSavingRow) return YES;
@@ -2674,7 +2831,7 @@
- (BOOL)cancelRowEditing
{
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableContentView];
+ [[tableContentView window] makeFirstResponder:tableContentView];
if (!isEditingRow) return NO;
if (isEditingNewRow) {
@@ -2688,7 +2845,7 @@
isEditingRow = NO;
currentlyEditingRow = -1;
[tableContentView reloadData];
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableContentView];
+ [[tableContentView window] makeFirstResponder:tableContentView];
return YES;
}
@@ -2747,13 +2904,15 @@
// When the option to not show blob or text options is set, we have a problem - we don't have
// the right values to use in the WHERE statement. Throw an error if this is the case.
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPLoadBlobsAsNeeded] && [self tableContainsBlobOrTextColumns] ) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
NSLocalizedString(@"You can't hide blob and text fields when working with tables without index.", @"message of panel when trying to edit tables without index and with hidden blob/text fields"));
[keys removeAllObjects];
[tableContentView deselectAll:self];
return @"";
}
+#endif
}
// Walk through the keys list constructing the argument list
@@ -2775,7 +2934,7 @@
[argument appendFormat:@"%@ IS NULL", [NSArrayObjectAtIndex(keys, i) backtickQuotedString]];
}
else if ([tempValue isSPNotLoaded]) {
- NSLog(@"Exceptional case: SPNotLoaded object found for method “argumentForRow:”!");
+ NSLog(@"Exceptional case: SPNotLoaded object found for method “argumentForRow:”!");
return @"";
}
else {
@@ -2826,6 +2985,7 @@
*/
- (NSString *)fieldListForQuery
{
+#ifndef SP_REFACTOR
if (([prefs boolForKey:SPLoadBlobsAsNeeded]) && [dataColumns count]) {
NSMutableArray *fields = [NSMutableArray arrayWithCapacity:[dataColumns count]];
@@ -2844,11 +3004,9 @@
return (tableHasBlobs) ? [fields componentsJoinedByString:@", "] : @"*";
}
- else {
-
+#endif
return @"*";
- }
}
/**
@@ -2953,12 +3111,18 @@
if(filterTableDefaultOperator) [filterTableDefaultOperator release];
NSString *newOperator = [filterTableSetDefaultOperatorValue stringValue];
filterTableDefaultOperator = [[self escapeFilterTableDefaultOperator:newOperator] retain];
+#ifndef SP_REFACTOR
[prefs setObject:newOperator forKey:SPFilterTableDefaultOperator];
+#endif
if(![newOperator isMatchedByRegex:@"(?i)like\\s+['\"]%@%['\"]\\s*"]) {
+#ifndef SP_REFACTOR
if(![prefs objectForKey:SPFilterTableDefaultOperatorLastItems])
[prefs setObject:[NSMutableArray array] forKey:SPFilterTableDefaultOperatorLastItems];
+#endif
NSMutableArray *lastItems = [NSMutableArray array];
+#ifndef SP_REFACTOR
[lastItems setArray:[prefs objectForKey:SPFilterTableDefaultOperatorLastItems]];
+#endif
if([lastItems containsObject:newOperator])
[lastItems removeObject:newOperator];
if([lastItems count] > 0)
@@ -2969,7 +3133,9 @@
if([lastItems count] > 15)
while([lastItems count] > 15)
[filterTableSetDefaultOperatorValue removeItemAtIndex:[lastItems count]-1];
+#ifndef SP_REFACTOR
[prefs setObject:lastItems forKey:SPFilterTableDefaultOperatorLastItems];
+#endif
}
[self updateFilterTableClause:nil];
}
@@ -2984,7 +3150,7 @@
{
// error := first object is the title , second the message, only one button OK
SPBeginAlertSheet([error objectAtIndex:0], NSLocalizedString(@"OK", @"OK button"),
- nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ nil, nil, [NSApp keyWindow], self, nil, nil,
[error objectAtIndex:1]);
}
@@ -3010,8 +3176,13 @@
}
if ([data isKindOfClass:[NSString class]]
- && [data isEqualToString:[prefs objectForKey:SPNullValue]]
- && [[NSArrayObjectAtIndex(dataColumns, column) objectForKey:@"null"] boolValue])
+ && [data isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ] && [[NSArrayObjectAtIndex(dataColumns, column) objectForKey:@"null"] boolValue])
{
data = [[NSNull null] retain];
}
@@ -3032,7 +3203,7 @@
fieldEditor = nil;
}
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableContentView];
+ [[tableContentView window] makeFirstResponder:tableContentView];
if(row > -1 && editedColumn > -1)
[tableContentView editColumn:editedColumn row:row withEvent:nil select:YES];
@@ -3075,13 +3246,15 @@
[filterTableWhereClause setContinuousSpellCheckingEnabled:NO];
[filterTableWhereClause setAutoindent:NO];
[filterTableWhereClause setAutoindentIgnoresEnter:NO];
+#ifndef SP_REFACTOR
[filterTableWhereClause setAutopair:[prefs boolForKey:SPCustomQueryAutoPairCharacters]];
[filterTableWhereClause setAutohelp:NO];
[filterTableWhereClause setAutouppercaseKeywords:[prefs boolForKey:SPCustomQueryAutoUppercaseKeywords]];
+#endif
[filterTableWhereClause setCompletionWasReinvokedAutomatically:NO];
[filterTableWhereClause insertText:@""];
[filterTableWhereClause didChangeText];
- [[tableDocumentInstance parentWindow] makeFirstResponder:filterTableView];
+ [[filterTableView window] makeFirstResponder:filterTableView];
}
/**
@@ -3121,6 +3294,7 @@
[filterTableWindow makeFirstResponder:filterTableView];
// Load history
+#ifndef SP_REFACTOR
if([prefs objectForKey:SPFilterTableDefaultOperatorLastItems]) {
NSMutableArray *lastItems = [NSMutableArray array];
NSString *defaultItem = @"LIKE '%@%'";
@@ -3133,6 +3307,7 @@
}
[filterTableSetDefaultOperatorValue setStringValue:[prefs objectForKey:SPFilterTableDefaultOperator]];
+#endif
[NSApp beginSheet:filterTableSetDefaultOperatorSheet
modalForWindow:filterTableWindow
@@ -3395,7 +3570,9 @@
[tableDataInstance setStatusValue:[NSString stringWithFormat:@"%ld", (long)maxNumRows] forKey:@"Rows"];
[tableDataInstance setStatusValue:@"y" forKey:@"RowsCountAccurate"];
[[tableInfoInstance onMainThread] tableChanged:nil];
+#ifndef SP_REFACTOR
[[[tableDocumentInstance valueForKey:@"extendedTableInfoInstance"] onMainThread] loadTable:selectedTable];
+#endif
// Otherwise, if the table status value is accurate, use it
} else if ([[tableDataInstance statusValueForKey:@"RowsCountAccurate"] boolValue]) {
@@ -3404,10 +3581,23 @@
checkStatusCount = YES;
// Choose whether to display an estimate, or to fetch the correct row count, based on prefs
- } else if ([[prefs objectForKey:SPTableRowCountQueryLevel] integerValue] == SPRowCountFetchAlways
+ } else if (
+#ifndef SP_REFACTOR
+ [[prefs objectForKey:SPTableRowCountQueryLevel] integerValue] == SPRowCountFetchAlways
|| ([[prefs objectForKey:SPTableRowCountQueryLevel] integerValue] == SPRowCountFetchIfCheap
- && [tableDataInstance statusValueForKey:@"Data_length"]
- && [[prefs objectForKey:SPTableRowCountCheapSizeBoundary] integerValue] > [[tableDataInstance statusValueForKey:@"Data_length"] integerValue]))
+ &&
+#endif
+ [tableDataInstance statusValueForKey:@"Data_length"]
+ &&
+#ifndef SP_REFACTOR
+ [[prefs objectForKey:SPTableRowCountCheapSizeBoundary] integerValue]
+#else
+ 5242880
+#endif
+ > [[tableDataInstance statusValueForKey:@"Data_length"] integerValue])
+#ifndef SP_REFACTOR
+ )
+#endif
{
maxNumRows = [self fetchNumberOfRows];
maxNumRowsIsEstimate = NO;
@@ -3426,17 +3616,39 @@
// Check whether the estimated count requires updating, ie if the retrieved count exceeds it
if (checkStatusCount) {
NSInteger foundMaxRows;
- if ([prefs boolForKey:SPLimitResults]) {
- foundMaxRows = ((contentPage - 1) * [prefs integerForKey:SPLimitResultsValue]) + tableRowsCount;
+#ifndef SP_REFACTOR
+ if ([prefs boolForKey:SPLimitResults])
+#else
+ if ( YES )
+#endif
+ {
+ foundMaxRows = ((contentPage - 1) *
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ ) + tableRowsCount;
if (foundMaxRows > maxNumRows) {
- if ((NSInteger)tableRowsCount == [prefs integerForKey:SPLimitResultsValue]) {
+#ifndef SP_REFACTOR
+ if ((NSInteger)tableRowsCount == [prefs integerForKey:SPLimitResultsValue])
+#else
+ if (tableRowsCount == 1000)
+#endif
+ {
maxNumRows = foundMaxRows + 1;
maxNumRowsIsEstimate = YES;
} else {
maxNumRows = foundMaxRows;
maxNumRowsIsEstimate = NO;
}
- } else if (!isInterruptedLoad && !isFiltered && (NSInteger)tableRowsCount < [prefs integerForKey:SPLimitResultsValue]) {
+ } else if (!isInterruptedLoad && !isFiltered && (NSInteger)tableRowsCount <
+#ifndef SP_REFACTOR
+ [prefs integerForKey:SPLimitResultsValue]
+#else
+ 1000
+#endif
+ ) {
maxNumRows = foundMaxRows;
maxNumRowsIsEstimate = NO;
}
@@ -3470,8 +3682,10 @@
[tableContentView setDelegate:nil];
for (NSDictionary *columnDefinition in dataColumns) {
+#ifndef SP_REFACTOR
// Skip columns with saved widths
if ([[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]]] objectForKey:[tablesListInstance tableName]] objectForKey:[columnDefinition objectForKey:@"name"]]) continue;
+#endif
// Otherwise set the column width
NSTableColumn *aTableColumn = [tableContentView tableColumnWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
@@ -3480,6 +3694,7 @@
}
[tableContentView setDelegate:self];
}
+#ifndef SP_REFACTOR
#pragma mark -
#pragma mark TableView delegate methods
@@ -3565,6 +3780,7 @@
return nil;
}
+#endif
- (NSInteger)numberOfRowsInTableView:(SPCopyTable *)aTableView
{
@@ -3620,7 +3836,11 @@
return [theValue wktString];
if ([theValue isNSNull])
+#ifndef SP_REFACTOR
return [prefs objectForKey:SPNullValue];
+#else
+ return @"NULL";
+#endif
if ([theValue isKindOfClass:[NSData class]])
return [theValue shortStringRepresentationUsingEncoding:[mySQLConnection stringEncoding]];
@@ -3758,7 +3978,11 @@
} else {
if ( [[anObject description] isEqualToString:@"CURRENT_TIMESTAMP"] ) {
newObject = @"CURRENT_TIMESTAMP";
+#ifndef SP_REFACTOR
} else if([anObject isEqualToString:[prefs stringForKey:SPNullValue]]) {
+#else
+ } else if([anObject isEqualToString:@"NULL"]) {
+#endif
newObject = @"NULL";
} else if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"geometry"]) {
newObject = [(NSString*)anObject getGeomFromTextString];
@@ -3780,7 +4004,7 @@
// Check for errors while UPDATE
if ([mySQLConnection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), NSLocalizedString(@"Cancel", @"cancel button"), nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), NSLocalizedString(@"Cancel", @"cancel button"), nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"Couldn't write field.\nMySQL said: %@", @"message of panel when error while updating field to db"), [mySQLConnection getLastErrorMessage]]);
[tableDocumentInstance endTask];
@@ -3789,21 +4013,23 @@
}
- // This shouldn't happen – for safety reasons
+ // This shouldn't happen – for safety reasons
if ( ![mySQLConnection affectedRows] ) {
+#ifndef SP_REFACTOR
if ( [prefs boolForKey:SPShowNoAffectedRowsError] ) {
- SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Warning", @"warning"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
NSLocalizedString(@"The row was not written to the MySQL database. You probably haven't changed anything.\nReload the table to be sure that the row exists and use a primary key for your table.\n(This error can be turned off in the preferences.)", @"message of panel when no rows have been affected after writing to the db"));
} else {
NSBeep();
}
+#endif
[tableDocumentInstance endTask];
[[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
return;
}
} else {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"Updating field content failed. Couldn't identify field origin unambiguously (%ld match%@). It's very likely that while editing this field the table `%@` was changed by an other user.", @"message of panel when error while updating field to db after enabling it"),
(long)numberOfPossibleUpdateRows, (numberOfPossibleUpdateRows>1)?@"es":@"", tableForColumn]);
@@ -3850,7 +4076,13 @@
if (anObject) {
// Restore NULLs if necessary
- if ([anObject isEqualToString:[prefs objectForKey:SPNullValue]] && [[column objectForKey:@"null"] boolValue])
+ if ([anObject isEqualToString:
+#ifndef SP_REFACTOR
+ [prefs objectForKey:SPNullValue]
+#else
+ @"NULL"
+#endif
+ ] && [[column objectForKey:@"null"] boolValue])
anObject = [NSNull null];
[tableValues replaceObjectInRow:rowIndex column:[[aTableColumn identifier] integerValue] withObject:anObject];
@@ -3934,7 +4166,7 @@
[self loadTableValues];
if ([mySQLConnection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"Couldn't sort table. MySQL said: %@", @"message of panel when sorting of table failed"), [mySQLConnection getLastErrorMessage]]);
[tableDocumentInstance endTask];
[sortPool drain];
@@ -3979,6 +4211,7 @@
[self updateCountText];
+#ifndef SP_REFACTOR /* triggered commands */
NSArray *triggeredCommands = [[NSApp delegate] bundleCommandsForTrigger:SPBundleTriggerActionTableRowChanged];
for(NSString* cmdPath in triggeredCommands) {
NSArray *data = [cmdPath componentsSeparatedByString:@"|"];
@@ -4015,7 +4248,7 @@
}
}
}
-
+#endif
}
/**
@@ -4036,11 +4269,15 @@
NSString *table = [tablesListInstance tableName];
// get tableColumnWidths object
+#ifndef SP_REFACTOR
if ( [prefs objectForKey:SPTableColumnWidths] != nil ) {
tableColumnWidths = [NSMutableDictionary dictionaryWithDictionary:[prefs objectForKey:SPTableColumnWidths]];
} else {
+#endif
tableColumnWidths = [NSMutableDictionary dictionary];
+#ifndef SP_REFACTOR
}
+#endif
// get database object
if ( [tableColumnWidths objectForKey:database] == nil ) {
[tableColumnWidths setObject:[NSMutableDictionary dictionary] forKey:database];
@@ -4057,7 +4294,9 @@
}
// save column size
[[[tableColumnWidths objectForKey:database] objectForKey:table] setObject:[NSNumber numberWithDouble:[(NSTableColumn *)[[aNotification userInfo] objectForKey:@"NSTableColumn"] width]] forKey:[[[[aNotification userInfo] objectForKey:@"NSTableColumn"] headerCell] stringValue]];
+#ifndef SP_REFACTOR
[prefs setObject:tableColumnWidths forKey:SPTableColumnWidths];
+#endif
}
/**
@@ -4089,7 +4328,7 @@
MCPResult *tempResult = [mySQLConnection queryString:query];
if (![tempResult numOfRows]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
NSLocalizedString(@"Couldn't load the row. Reload the table to be sure that the row exists and use a primary key for your table.", @"message of panel when loading of row failed"));
return NO;
}
@@ -4150,8 +4389,11 @@
id cellValue = [tableValues cellDataAtRow:rowIndex column:[[aTableColumn identifier] integerValue]];
if ([cellValue isNSNull])
+#ifndef SP_REFACTOR
cellValue = [NSString stringWithString:[prefs objectForKey:SPNullValue]];
-
+#else
+ cellValue = [NSString stringWithString:@"NULL"];
+#endif
NSInteger editedColumn = 0;
for(NSTableColumn* col in [tableContentView tableColumns]) {
if([[col identifier] isEqualToNumber:[aTableColumn identifier]]) break;
@@ -4163,7 +4405,7 @@
usingEncoding:[mySQLConnection stringEncoding]
isObjectBlob:isBlob
isEditable:isFieldEditable
- withWindow:[tableDocumentInstance parentWindow]
+ withWindow:[NSApp keyWindow]
sender:self
contextInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:rowIndex], @"row",
@@ -4189,7 +4431,7 @@
if (aTableView == tableContentView) {
NSString *tmp;
- // By holding ⌘, ⇧, or/and ⌥ copies selected rows as SQL INSERTS
+ // By holding ‚åò, ‚áß, or/and ‚å• copies selected rows as SQL INSERTS
// otherwise \t delimited lines
if([[NSApp currentEvent] modifierFlags] & (NSCommandKeyMask|NSShiftKeyMask|NSAlternateKeyMask))
tmp = [tableContentView rowsAsSqlInsertsOnlySelectedRows:YES];
@@ -4238,6 +4480,7 @@
// Get the column width
NSUInteger targetWidth = [tableContentView autodetectWidthForColumnDefinition:columnDefinition maxRows:500];
+#ifndef SP_REFACTOR
// Clear any saved widths for the column
NSString *dbKey = [NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]];
NSString *tableKey = [tablesListInstance tableName];
@@ -4258,6 +4501,7 @@
}
[prefs setObject:[NSDictionary dictionaryWithDictionary:savedWidths] forKey:SPTableColumnWidths];
}
+#endif
// Return the width, while the delegate is empty to prevent column resize notifications
[tableContentView setDelegate:nil];
@@ -4265,6 +4509,7 @@
return targetWidth;
}
+#ifndef SP_REFACTOR /* SplitView delegate methods */
#pragma mark -
#pragma mark SplitView delegate methods
@@ -4310,6 +4555,7 @@
[leftView setFrame:leftFrame];
[rightView setFrame:rightFrame];
}
+#endif
#pragma mark -
@@ -4322,9 +4568,11 @@
{
isWorking = YES;
+#ifndef SP_REFACTOR /* Only proceed if this view is selected */
// Only proceed if this view is selected.
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent])
return;
+#endif
[addButton setEnabled:NO];
[removeButton setEnabled:NO];
@@ -4344,9 +4592,11 @@
{
isWorking = NO;
+#ifndef SP_REFACTOR /* Only proceed if this view is selected */
// Only proceed if this view is selected.
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent])
return;
+#endif
if ( ![[[tableDataInstance statusValues] objectForKey:@"Rows"] isNSNull] && selectedTable && [selectedTable length] && [tableDataInstance tableEncoding]) {
[addButton setEnabled:([tablesListInstance tableType] == SPTableTypeTable)];
@@ -4401,7 +4651,7 @@
if([tableContentView isCellEditingMode]) {
NSArray *editStatus = [self fieldEditStatusForRow:row andColumn:[NSArrayObjectAtIndex([tableContentView tableColumns], column) identifier]];
NSInteger numberOfPossibleUpdateRows = [[editStatus objectAtIndex:0] integerValue];
- NSPoint pos = [[tableDocumentInstance parentWindow] convertBaseToScreen:[tableContentView convertPoint:[tableContentView frameOfCellAtColumn:column row:row].origin toView:nil]];
+ NSPoint pos = [[NSApp keyWindow] convertBaseToScreen:[tableContentView convertPoint:[tableContentView frameOfCellAtColumn:column row:row].origin toView:nil]];
pos.y -= 20;
switch(numberOfPossibleUpdateRows) {
case -1:
@@ -4460,7 +4710,11 @@
{
// Check firstly if SPCopyTable can handle command
+#ifndef SP_REFACTOR
if([control control:control textView:textView doCommandBySelector:(SEL)command])
+#else
+ if([(id<NSControlTextEditingDelegate>)control control:control textView:textView doCommandBySelector:(SEL)command])
+#endif
return YES;
// Trap the escape key
@@ -4482,6 +4736,7 @@
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
+#ifndef SP_REFACTOR /* observe pref changes */
// Display table veiew vertical gridlines preference changed
if ([keyPath isEqualToString:SPDisplayTableViewVerticalGridlines]) {
[tableContentView setGridStyleMask:([[change objectForKey:NSKeyValueChangeNewKey] boolValue]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
@@ -4489,10 +4744,11 @@
// Table font preference changed
else if ([keyPath isEqualToString:SPGlobalResultTableFont]) {
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]];
- [tableContentView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{ǞṶḹÜ∑zgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
+ [tableContentView setRowHeight:2.0f+NSSizeToCGSize([[NSString stringWithString:@"{«û·π∂·∏π√ú‚àëzgyf"] sizeWithAttributes:[NSDictionary dictionaryWithObject:tableFont forKey:NSFontAttributeName]]).height];
[tableContentView setFont:tableFont];
[tableContentView reloadData];
}
+#endif
}
/**
@@ -4547,7 +4803,7 @@
BOOL lookInAllFields = NO;
- NSString *re1 = @"^\\s*(<[=>]?|>=?|!?=|≠|≤|≥)\\s*(.*?)\\s*$";
+ NSString *re1 = @"^\\s*(<[=>]?|>=?|!?=|≠|≤|≥)\\s*(.*?)\\s*$";
NSString *re2 = @"^\\s*(.*)\\s+(.*?)\\s*$";
NSInteger editedRow = [filterTableView editedRow];
@@ -4593,9 +4849,9 @@
if([filterCell length]) {
// Recode special operators
- filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*≠" withString:@"!="];
- filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*≤" withString:@"<="];
- filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*≥" withString:@">="];
+ filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*≠" withString:@"!="];
+ filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*≤" withString:@"<="];
+ filterCell = [filterCell stringByReplacingOccurrencesOfRegex:@"^\\s*‚â•" withString:@">="];
if(numberOfValues)
[clause appendString:(lookInAllFields) ? @" OR " : @" AND "];
@@ -4690,13 +4946,13 @@
NSUInteger numOfArgs = [[filter objectForKey:@"NumberOfArguments"] integerValue];
switch(numOfArgs) {
case 2:
- [[tableDocumentInstance parentWindow] makeFirstResponder:firstBetweenField];
+ [[firstBetweenField window] makeFirstResponder:firstBetweenField];
break;
case 1:
- [[tableDocumentInstance parentWindow] makeFirstResponder:argumentField];
+ [[argumentField window] makeFirstResponder:argumentField];
break;
default:
- [[tableDocumentInstance parentWindow] makeFirstResponder:compareField];
+ [[compareField window] makeFirstResponder:compareField];
}
}
}
@@ -4711,6 +4967,18 @@
return [tableContentView fieldEditorSelectedRange];
}
+#ifdef SP_REFACTOR /* glue */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)doc
+{
+ tableDocumentInstance = doc;
+}
+
+- (void)setTableListInstance:(SPTablesList*)list
+{
+ tablesListInstance = list;
+}
+#endif
+
#pragma mark -
/**
diff --git a/Source/SPTableData.h b/Source/SPTableData.h
index 1c3fa8f0..b4042527 100644
--- a/Source/SPTableData.h
+++ b/Source/SPTableData.h
@@ -25,10 +25,13 @@
#import <MCPKit/MCPKit.h>
+@class SPDatabaseDocument;
+@class SPTablesList;
+
@interface SPTableData : NSObject
{
- IBOutlet id tableDocumentInstance;
- IBOutlet id tableListInstance;
+ IBOutlet SPDatabaseDocument* tableDocumentInstance;
+ IBOutlet SPTablesList* tableListInstance;
NSMutableArray *columns;
NSMutableArray *columnNames;
@@ -74,4 +77,9 @@
- (NSDictionary *) parseFieldDefinitionStringParts:(NSArray *)definitionParts;
- (NSArray *) primaryKeyColumnNames;
+#ifdef SP_REFACTOR /* glue */
+- (void)setTableDocumentInstance:(SPDatabaseDocument*)doc;
+- (void)setTableListInstance:(SPTablesList*)list;
+#endif
+
@end
diff --git a/Source/SPTableData.m b/Source/SPTableData.m
index b69ce816..de253e57 100644
--- a/Source/SPTableData.m
+++ b/Source/SPTableData.m
@@ -1374,4 +1374,17 @@
pthread_mutex_unlock(&dataProcessingLock);
}
+#ifdef SP_REFACTOR /* glue */
+
+- (void)setTableDocumentInstance:(SPDatabaseDocument*)doc
+{
+ tableDocumentInstance = doc;
+}
+
+- (void)setTableListInstance:(SPTablesList*)list
+{
+ tableListInstance = list;
+}
+#endif
+
@end \ No newline at end of file
diff --git a/Source/SPTableStructure.h b/Source/SPTableStructure.h
index a08ddd15..02313094 100644
--- a/Source/SPTableStructure.h
+++ b/Source/SPTableStructure.h
@@ -25,17 +25,19 @@
#import <MCPKit/MCPKit.h>
-@class SPDatabaseDocument, SPTableFieldValidation;
+@class SPDatabaseDocument, SPTableFieldValidation, SPTableData, SPDatabaseData, SPTablesList, SPIndexesController;
@interface SPTableStructure : NSObject
{
- IBOutlet id tablesListInstance;
- IBOutlet id tableDataInstance;
- IBOutlet SPDatabaseDocument *tableDocumentInstance;
+ IBOutlet SPTablesList* tablesListInstance;
+ IBOutlet SPTableData* tableDataInstance;
+ IBOutlet SPDatabaseDocument* tableDocumentInstance;
+#ifndef SP_REFACTOR /* ivars */
IBOutlet id tableInfoInstance;
IBOutlet id extendedTableInfoInstance;
- IBOutlet id indexesController;
- IBOutlet id databaseDataInstance;
+#endif
+ IBOutlet SPIndexesController* indexesController;
+ IBOutlet SPDatabaseData* databaseDataInstance;
IBOutlet id keySheet;
IBOutlet id resetAutoIncrementSheet;
@@ -70,7 +72,9 @@
NSMutableDictionary *oldRow, *enumFields;
NSDictionary *defaultValues;
NSInteger currentlyEditingRow;
+#ifndef SP_REFACTOR /* ivars */
NSUserDefaults *prefs;
+#endif
NSArray *collations;
NSArray *typeSuggestions;
NSArray *extraFieldSuggestions;
@@ -85,6 +89,13 @@
- (IBAction)reloadTable:(id)sender;
- (void)setTableDetails:(NSDictionary *)tableDetails;
+#ifdef SP_REFACTOR /* method decls */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)doc;
+- (void)setTableListInstance:(SPTablesList*)list;
+- (void)setTableDataInstance:(SPTableData*)data;
+#endif
+- (void)showErrorSheetWith:(NSDictionary *)errorDictionary;
+
// Edit methods
- (IBAction)addField:(id)sender;
- (IBAction)copyField:(id)sender;
diff --git a/Source/SPTableStructure.m b/Source/SPTableStructure.m
index aab62af8..a616951c 100644
--- a/Source/SPTableStructure.m
+++ b/Source/SPTableStructure.m
@@ -68,7 +68,9 @@
fieldValidation = [[SPTableFieldValidation alloc] init];
+#ifndef SP_REFACTOR /* patch */
prefs = [NSUserDefaults standardUserDefaults];
+#endif
}
return self;
@@ -79,12 +81,15 @@
*/
- (void)awakeFromNib
{
+#ifndef SP_REFACTOR /* ui manipulation */
// Set the structure and index view's vertical gridlines if required
[tableSourceView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
-
+#endif
+#ifndef SP_REFACTOR /* set font from prefs */
// Set the strutcture and index view's font
[tableSourceView setFont:([prefs boolForKey:SPUseMonospacedFonts]) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
[indexesTableView setFont:([prefs boolForKey:SPUseMonospacedFonts]) ? [NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+#endif
extraFieldSuggestions = [[NSArray arrayWithObjects:
@"None",
@@ -159,12 +164,15 @@
name:SPDocumentTaskEndNotification
object:tableDocumentInstance];
+#ifndef SP_REFACTOR /* add prefs observer */
[prefs addObserver:indexesController forKeyPath:SPUseMonospacedFonts options:NSKeyValueObservingOptionNew context:NULL];
+#endif
// Init the view column submenu according to saved hidden status;
// menu items are identified by their tag number which represents the initial column index
for (NSMenuItem *item in [viewColumnsMenu itemArray]) [item setState:NSOnState]; // Set all items to NSOnState
-
+
+#ifndef SP_REFACTOR /* patch */
for (NSTableColumn *col in [tableSourceView tableColumns])
{
if ([col isHidden]) {
@@ -178,6 +186,21 @@
[[viewColumnsMenu itemWithTag:12] setState:NSOffState];
}
}
+#else
+ for (NSTableColumn *col in [tableSourceView tableColumns])
+ {
+ if ([col isHidden]) {
+ if ([[col identifier] isEqualToString:@"Key"])
+ [[viewColumnsMenu itemAtIndex:[viewColumnsMenu indexOfItemWithTag:7]] setState:NSOffState];
+ else if ([[col identifier] isEqualToString:@"encoding"])
+ [[viewColumnsMenu itemAtIndex:[viewColumnsMenu indexOfItemWithTag:10]] setState:NSOffState];
+ else if ([[col identifier] isEqualToString:@"collation"])
+ [[viewColumnsMenu itemAtIndex:[viewColumnsMenu indexOfItemWithTag:11]] setState:NSOffState];
+ else if ([[col identifier] isEqualToString:@"comment"])
+ [[viewColumnsMenu itemAtIndex:[viewColumnsMenu indexOfItemWithTag:12]] setState:NSOffState];
+ }
+ }
+#endif
[tableSourceView reloadData];
}
@@ -314,7 +337,11 @@
if(![theField objectForKey:@"default"])
[theField setObject:@"" forKey:@"default"];
else if([[theField objectForKey:@"default"] isKindOfClass:[NSNull class]])
+#ifndef SP_REFACTOR /* patch */
[theField setObject:[prefs stringForKey:SPNullValue] forKey:@"default"];
+#else
+ [theField setObject:@"NULL" forKey:@"default"];
+#endif
// Init Extra field
[theField setObject:@"None" forKey:@"Extra"];
@@ -373,7 +400,12 @@
{
NSString *newTableName = [tableDetails objectForKey:@"name"];
NSMutableDictionary *newDefaultValues;
- BOOL enableInteraction = ![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableStructure] || ![tableDocumentInstance isWorking];
+
+ BOOL enableInteraction =
+#ifndef SP_REFACTOR /* patch */
+ ![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableStructure] ||
+#endif
+ ![tableDocumentInstance isWorking];
// Update the selected table name
if (selectedTable) [selectedTable release], selectedTable = nil;
@@ -445,10 +477,17 @@
NSInteger insertIndex = ([tableSourceView numberOfSelectedRows] == 0 ? [tableSourceView numberOfRows] : [tableSourceView selectedRow] + 1);
+#ifndef SP_REFACTOR
[tableFields insertObject:[NSMutableDictionary
dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", ([prefs boolForKey:SPNewFieldsAllowNulls]) ? @"1" : @"0", @"", [prefs stringForKey:SPNullValue], @"None", @"", [NSNumber numberWithInt:0], [NSNumber numberWithInt: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]
+ forKeys:[NSArray arrayWithObjects:@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation", nil]]
+ atIndex:insertIndex];
+#endif
[tableSourceView reloadData];
[tableSourceView selectRowIndexes:[NSIndexSet indexSetWithIndex:insertIndex] byExtendingSelection:NO];
@@ -477,7 +516,7 @@
alternateButton:nil
otherButton:nil
informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while fetching the optimized field type.\n\nMySQL said:%@",@"an error occurred while fetching the optimized field type.\n\nMySQL said:%@"), [mySQLConnection getLastErrorMessage]]]
- beginSheetModalForWindow:[tableDocumentInstance parentWindow]
+ beginSheetModalForWindow:[NSApp keyWindow]
modalDelegate:self
didEndSelector:NULL
contextInfo:NULL];
@@ -500,7 +539,7 @@
alternateButton:nil
otherButton:nil
informativeTextWithFormat:type]
- beginSheetModalForWindow:[tableDocumentInstance parentWindow]
+ beginSheetModalForWindow:[NSApp keyWindow]
modalDelegate:self
didEndSelector:NULL
contextInfo:NULL];
@@ -603,7 +642,7 @@
[alert setAlertStyle:NSCriticalAlertStyle];
- [alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:@"cannotremovefield"];
+ [alert beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:@"cannotremovefield"];
}
@@ -641,7 +680,7 @@
[[buttons objectAtIndex:0] setKeyEquivalentModifierMask:NSCommandKeyMask];
[[buttons objectAtIndex:1] setKeyEquivalent:@"\r"];
- [alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(removeFieldSheetDidEnd:returnCode:contextInfo:) contextInfo:(hasForeignKey) ? @"removeFieldAndForeignKey" : @"removeField"];
+ [alert beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(removeFieldSheetDidEnd:returnCode:contextInfo:) contextInfo:(hasForeignKey) ? @"removeFieldAndForeignKey" : @"removeField"];
}
/**
@@ -658,7 +697,7 @@
// Begin the sheet
[NSApp beginSheet:resetAutoIncrementSheet
- modalForWindow:[tableDocumentInstance parentWindow]
+ modalForWindow:[NSApp keyWindow]
modalDelegate:self
didEndSelector:@selector(resetAutoincrementSheetDidEnd:returnCode:contextInfo:)
contextInfo:nil];
@@ -727,7 +766,7 @@
autoIncrementIndex = nil;
[tableSourceView reloadData];
currentlyEditingRow = -1;
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableSourceView];
+ [[NSApp keyWindow] makeFirstResponder:tableSourceView];
return YES;
}
@@ -769,8 +808,10 @@
if (valueAsString == nil || ![valueAsString length]) {
// reload data and bail
[tableDataInstance resetAllData];
+#ifndef SP_REFACTOR
[extendedTableInfoInstance loadTable:selTable];
[tableInfoInstance tableChanged:nil];
+#endif
return;
}
@@ -793,10 +834,14 @@
[tableDataInstance resetStatusData];
if([[tableDocumentInstance valueForKeyPath:@"tableTabView"] indexOfTabViewItem:[[tableDocumentInstance valueForKeyPath:@"tableTabView"] selectedTabViewItem]] == 3) {
[tableDataInstance resetAllData];
+#ifndef SP_REFACTOR
[extendedTableInfoInstance loadTable:selTable];
+#endif
}
+#ifndef SP_REFACTOR
[tableInfoInstance tableChanged:nil];
+#endif
}
/**
@@ -808,14 +853,18 @@
NSMutableArray *tempResult = [NSMutableArray arrayWithCapacity:numOfRows];
NSMutableDictionary *tempRow;
NSArray *keys;
- NSUInteger i;
+ NSInteger i;
+#ifndef SP_REFACTOR /* patch */
id prefsNullValue = [prefs objectForKey:SPNullValue];
+#else
+ id prefsNullValue = @"NULL";
+#endif
// Ensure table information is returned as strings to avoid problems with some server versions
[theResult setReturnDataAsStrings:YES];
if (numOfRows) [theResult dataSeek:0];
- for ( i = 0 ; i < numOfRows ; i++ ) {
+ for ( i = 0 ; i < (NSInteger)numOfRows ; i++ ) {
tempRow = [NSMutableDictionary dictionaryWithDictionary:[theResult fetchRowAsDictionary]];
// Replace NSNull instances with the NULL string from preferences
@@ -852,9 +901,9 @@
// Save any edits which have been made but not saved to the table yet;
// but not for any NSSearchFields which could cause a crash for undo, redo.
- id currentFirstResponder = [[tableDocumentInstance parentWindow] firstResponder];
+ id currentFirstResponder = [[NSApp keyWindow] firstResponder];
if (currentFirstResponder && [currentFirstResponder isKindOfClass:[NSView class]] && [(NSView *)currentFirstResponder isDescendantOf:tableSourceView]) {
- [[tableDocumentInstance parentWindow] endEditingFor:nil];
+ [[NSApp keyWindow] endEditingFor:nil];
}
// If no rows are currently being edited, or a save is already in progress, return success at once.
@@ -862,7 +911,11 @@
isSavingRow = YES;
// Save any edits which have been made but not saved to the table yet.
+#ifndef SP_REFACTOR /* patch */
[[tableDocumentInstance parentWindow] endEditingFor:nil];
+#else
+ [[tableSourceView window] endEditingFor:nil];
+#endif
// Attempt to save the row, and return YES if the save succeeded.
if ([self addRowToDB]) {
@@ -880,7 +933,7 @@
* returns YES if row written to db, otherwies NO
* returns YES if no row is beeing edited and nothing has to be written to db
*/
-- (BOOL)addRowToDB;
+- (BOOL)addRowToDB
{
if ((!isEditingRow) || (currentlyEditingRow == -1)) return YES;
@@ -931,7 +984,12 @@
[queryString appendString:@"\n NULL"];
}
// If a NULL value has been specified, and NULL is allowed, specify DEFAULT NULL
- if ([[theRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]]) {
+#ifndef SP_REFACTOR /* patch */
+ if ([[theRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]])
+#else
+ if ([[theRow objectForKey:@"default"] isEqualToString:@"NULL"])
+#endif
+ {
if ([[theRow objectForKey:@"null"] integerValue] == 1) {
[queryString appendString:@"\n DEFAULT NULL "];
}
@@ -1003,7 +1061,12 @@
if (![theRowExtra isEqualToString:@"AUTO_INCREMENT"]) {
// If a NULL value has been specified, and NULL is allowed, specify DEFAULT NULL
- if ([[theRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]]) {
+#ifndef SP_REFACTOR /* patch */
+ if ([[theRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]])
+#else
+ if ([[theRow objectForKey:@"default"] isEqualToString:@"NULL"])
+#endif
+ {
if ([[theRow objectForKey:@"null"] integerValue] == 1) {
[queryString appendString:@"\n DEFAULT NULL"];
}
@@ -1122,7 +1185,7 @@
if([mySQLConnection getLastErrorID] == 1146) { // If the current table doesn't exist anymore
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"),
NSLocalizedString(@"OK", @"OK button"),
- nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to alter table '%@'.\n\nMySQL said: %@", @"error while trying to alter table message"),
selectedTable, [mySQLConnection getLastErrorMessage]]);
@@ -1145,14 +1208,14 @@
if (isEditingNewRow) {
SPBeginAlertSheet(NSLocalizedString(@"Error adding field", @"error adding field message"),
NSLocalizedString(@"Edit row", @"Edit row button"),
- NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [tableDocumentInstance parentWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
+ NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [NSApp keyWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when trying to add the field '%@' via\n\n%@\n\nMySQL said: %@", @"error adding field informative message"),
[theRow objectForKey:@"name"], queryString, [mySQLConnection getLastErrorMessage]]);
}
else {
SPBeginAlertSheet(NSLocalizedString(@"Error changing field", @"error changing field message"),
NSLocalizedString(@"Edit row", @"Edit row button"),
- NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [tableDocumentInstance parentWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
+ NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [NSApp keyWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), nil,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when trying to change the field '%@' via\n\n%@\n\nMySQL said: %@", @"error changing field informative message"),
[theRow objectForKey:@"name"], queryString, [mySQLConnection getLastErrorMessage]]);
}
@@ -1161,6 +1224,24 @@
}
}
+#ifdef SP_REFACTOR /* glue */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)doc
+{
+ tableDocumentInstance = doc;
+}
+
+- (void)setTableListInstance:(SPTablesList*)list
+{
+ tablesListInstance = list;
+}
+
+- (void)setTableDataInstance:(SPTableData*)data
+{
+ tableDataInstance = data;
+}
+
+#endif
+
/**
* A method to show an error sheet after a short delay, so that it can
* be called from within an endSheet selector. This should be called on
@@ -1179,7 +1260,7 @@
// Display the error sheet
SPBeginAlertSheet([errorDictionary objectForKey:@"title"], NSLocalizedString(@"OK", @"OK button"),
- nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ nil, nil, [NSApp keyWindow], self, nil, nil,
[errorDictionary objectForKey:@"message"]);
}
@@ -1261,7 +1342,7 @@
// Problem: reentering edit mode for first cell doesn't function
[tableSourceView selectRowIndexes:[NSIndexSet indexSetWithIndex:currentlyEditingRow] byExtendingSelection:NO];
- [tableSourceView performSelector:@selector(keyDown:) withObject:[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:0x24] afterDelay:0.0];
+ [tableSourceView performSelector:@selector(keyDown:) withObject:[NSEvent keyEventWithType:NSKeyDown location:NSMakePoint(0,0) modifierFlags:0 timestamp:0 windowNumber:[[NSApp keyWindow] windowNumber] context:[NSGraphicsContext currentContext] characters:nil charactersIgnoringModifiers:nil isARepeat:NO keyCode:0x24] afterDelay:0.0];
}
// Discard changes and cancel editing
@@ -1280,6 +1361,7 @@
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
+#ifndef SP_REFACTOR /* observe prefs change */
// Display table veiew vertical gridlines preference changed
if ([keyPath isEqualToString:SPDisplayTableViewVerticalGridlines]) {
[tableSourceView setGridStyleMask:([[change objectForKey:NSKeyValueChangeNewKey] boolValue]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
@@ -1295,6 +1377,7 @@
[tableSourceView reloadData];
[indexesTableView reloadData];
}
+#endif
}
#pragma mark -
@@ -1320,9 +1403,17 @@
- (NSString *)defaultValueForField:(NSString *)field
{
if ( ![defaultValues objectForKey:field] ) {
+#ifndef SP_REFACTOR /* patch */
return [prefs objectForKey:SPNullValue];
+#else
+ return @"NULL";
+#endif
} else if ( [[defaultValues objectForKey:field] isMemberOfClass:[NSNull class]] ) {
+#ifndef SP_REFACTOR /* patch */
return [prefs objectForKey:SPNullValue];
+#else
+ return @"NULL";
+#endif
} else {
return [defaultValues objectForKey:field];
}
@@ -1371,7 +1462,11 @@
NSMutableArray *tempResult = [NSMutableArray array];
NSMutableArray *tempResult2 = [NSMutableArray array];
+#ifndef SP_REFACTOR /* patch */
NSString *nullValue = [prefs stringForKey:SPNullValue];
+#else
+ NSString *nullValue = @"NULL";
+#endif
CFStringRef escapedNullValue = CFXMLCreateStringByEscapingEntities(NULL, ((CFStringRef)nullValue), NULL);
MCPResult *structureQueryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SHOW COLUMNS FROM %@", [selectedTable backtickQuotedString]]];
@@ -1441,8 +1536,10 @@
*/
- (void)startDocumentTaskForTab:(NSNotification *)aNotification
{
+#ifndef SP_REFACTOR /* check toolbar mode */
// Only proceed if this view is selected.
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableStructure]) return;
+#endif
[tableSourceView setEnabled:NO];
[addFieldButton setEnabled:NO];
@@ -1462,8 +1559,10 @@
*/
- (void)endDocumentTaskForTab:(NSNotification *)aNotification
{
+#ifndef SP_REFACTOR /* check toolbar mode */
// Only re-enable elements if the current tab is the structure view
if (![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableStructure]) return;
+#endif
BOOL editingEnabled = ([tablesListInstance tableType] == SPTableTypeTable);
@@ -1551,7 +1650,7 @@
[tableDocumentInstance endTask];
// Preserve focus on table for keyboard navigation
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableSourceView];
+ [[NSApp keyWindow] makeFirstResponder:tableSourceView];
[pool drain];
}
diff --git a/Source/SPTableStructureDelegate.m b/Source/SPTableStructureDelegate.m
index 0cabda4c..9c8f341c 100644
--- a/Source/SPTableStructureDelegate.m
+++ b/Source/SPTableStructureDelegate.m
@@ -129,7 +129,7 @@
[chooseKeyButton selectItemWithTag:SPPrimaryKeyMenuTag];
[NSApp beginSheet:keySheet
- modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self
+ modalForWindow:[NSApp keyWindow] modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:@"autoincrementindex" ];
}
@@ -150,7 +150,11 @@
else if([[aTableColumn identifier] isEqualToString:@"null"]) {
if([[currentRow objectForKey:@"null"] integerValue] != [anObject integerValue]) {
if([anObject integerValue] == 0) {
+#ifndef SP_REFACTOR /* patch */
if([[currentRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]])
+#else
+ if([[currentRow objectForKey:@"default"] isEqualToString:@"NULL"])
+#endif
[currentRow setObject:@"" forKey:@"default"];
}
[tableSourceView reloadData];
@@ -309,7 +313,11 @@
// Add the default value, skip it for auto_increment
if([originalRow objectForKey:@"Extra"] && ![[originalRow objectForKey:@"Extra"] isEqualToString:@"auto_increment"]) {
+#ifndef SP_REFACTOR /* patch */
if ([[originalRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]]) {
+#else
+ if ([[originalRow objectForKey:@"default"] isEqualToString:@"NULL"]) {
+#endif
if ([[originalRow objectForKey:@"null"] integerValue] == 1) {
[queryString appendString:(isTimestampType) ? @" NULL DEFAULT NULL" : @" DEFAULT NULL"];
}
@@ -344,7 +352,7 @@
[mySQLConnection queryString:queryString];
if ([mySQLConnection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error moving field", @"error moving field message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ SPBeginAlertSheet(NSLocalizedString(@"Error moving field", @"error moving field message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [NSApp keyWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to move the field.\n\nMySQL said: %@", @"error moving field informative message"), [mySQLConnection getLastErrorMessage]]);
}
else {
@@ -467,7 +475,7 @@
[[control window] makeFirstResponder:control];
[self addRowToDB];
[tableSourceView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
- [[tableDocumentInstance parentWindow] makeFirstResponder:tableSourceView];
+ [[NSApp keyWindow] makeFirstResponder:tableSourceView];
return YES;
}
@@ -541,6 +549,7 @@
#pragma mark -
#pragma mark Split view delegate methods
+#ifndef SP_REFACTOR /* Split view delegate methods */
- (BOOL)splitView:(NSSplitView *)sender canCollapseSubview:(NSView *)subview
{
@@ -576,6 +585,7 @@
}
}
}
+#endif
#pragma mark -
#pragma mark Combo box delegate methods
diff --git a/Source/SPTableView.m b/Source/SPTableView.m
index 5e279dbc..d678fef3 100644
--- a/Source/SPTableView.m
+++ b/Source/SPTableView.m
@@ -44,6 +44,7 @@
*/
- (NSMenu *)menuForEvent:(NSEvent *)event
{
+#ifndef SP_REFACTOR /* menuForEvent: */
// Try to retrieve a reference to the table document (assuming this is frontmost tab)
SPDatabaseDocument *parentTableDocument = nil;
@@ -67,24 +68,24 @@
// Check for SPTablesList if right-click on header, then suppress context menu
if ([[[[self delegate] class] description] isEqualToString:@"SPTablesList"]) {
- if ([NSArrayObjectAtIndex([[self delegate] valueForKeyPath:@"tableTypes"], row) integerValue] == -1)
+ if ([NSArrayObjectAtIndex([(NSObject*)[self delegate] valueForKeyPath:@"tableTypes"], row) integerValue] == -1)
return nil;
}
if ([[[[self delegate] class] description] isEqualToString:@"SPQueryFavoriteManager"]) {
- if ([NSArrayObjectAtIndex([[self delegate] valueForKeyPath:SPFavorites], row) objectForKey:@"headerOfFileURL"])
+ if ([NSArrayObjectAtIndex([(NSObject*)[self delegate] valueForKeyPath:SPFavorites], row) objectForKey:@"headerOfFileURL"])
return nil;
}
if ([[[[self delegate] class] description] isEqualToString:@"SPContentFilterManager"]) {
- if ([NSArrayObjectAtIndex([[self delegate] valueForKeyPath:@"contentFilters"], row) objectForKey:@"headerOfFileURL"])
+ if ([NSArrayObjectAtIndex([(NSObject*)[self delegate] valueForKeyPath:@"contentFilters"], row) objectForKey:@"headerOfFileURL"])
return nil;
}
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
[[self window] makeFirstResponder:self];
}
-
+#endif
return [self menu];
}
@@ -112,17 +113,17 @@
if ([self numberOfSelectedRows] == 1 && ([theEvent keyCode] == 36 || [theEvent keyCode] == 76)) {
if ([[[[self delegate] class] description] isEqualToString:@"SPFieldMapperController"]) {
- if ([[self delegate] isGlobalValueSheetOpen]) {
- [[self delegate] closeGlobalValuesSheet:nil];
+ if ([(SPFieldMapperController*)[self delegate] isGlobalValueSheetOpen]) {
+ [(SPFieldMapperController*)[self delegate] closeGlobalValuesSheet:nil];
return;
}
// ENTER or RETURN closes the SPFieldMapperController sheet
// by sending an object with the tag 1 if no table cell is edited
- if ([[self delegate] canBeClosed]) {
+ if ([(SPFieldMapperController*)[self delegate] canBeClosed]) {
NSButton *b = [[[NSButton alloc] init] autorelease];
[b setTag:1];
- [[self delegate] closeSheet:b];
+ [(SPFieldMapperController*)[self delegate] closeSheet:b];
return;
}
@@ -149,7 +150,7 @@
// Check if ESCAPE is hit and use it to cancel row editing if supported
else if ([theEvent keyCode] == 53 && [[self delegate] respondsToSelector:@selector(cancelRowEditing)]) {
- if ([[self delegate] cancelRowEditing]) return;
+ if ([[self delegate] performSelector:@selector(cancelRowEditing)]) return;
}
// If the Tab key is used, but tab editing is disabled, change focus rather than entering edit mode.
diff --git a/Source/SPTablesList.h b/Source/SPTablesList.h
index 42f49f60..914295a5 100644
--- a/Source/SPTablesList.h
+++ b/Source/SPTablesList.h
@@ -26,6 +26,7 @@
#import <MCPKit/MCPKit.h>
@class SPHistoryController, SPTableView;
+@class SPDatabaseDocument;
@interface NSObject (NSSplitView)
@@ -38,7 +39,8 @@
@interface SPTablesList : NSObject
{
- IBOutlet id tableDocumentInstance;
+ SPDatabaseDocument* tableDocumentInstance;
+#ifndef SP_REFACTOR /* ivars */
IBOutlet id tableSourceInstance;
IBOutlet id tableContentInstance;
IBOutlet id customQueryInstance;
@@ -79,9 +81,11 @@
IBOutlet NSMenuItem *separatorTableMenuItem;
IBOutlet NSMenuItem *showCreateSyntaxMenuItem;
IBOutlet NSMenuItem *separatorTableMenuItem2;
+#endif
MCPConnection *mySQLConnection;
+#ifndef SP_REFACTOR /* ivars */
// Table list context menu items
IBOutlet NSMenuItem *removeTableContextMenuItem;
IBOutlet NSMenuItem *duplicateTableContextMenuItem;
@@ -91,25 +95,34 @@
IBOutlet NSMenuItem *separatorTableContextMenuItem;
IBOutlet NSMenuItem *showCreateSyntaxContextMenuItem;
IBOutlet NSMenuItem *separatorTableContextMenuItem2;
+#endif
NSMutableArray *tables;
+#ifndef SP_REFACTOR /* ivars */
NSMutableArray *filteredTables;
+#endif
NSMutableArray *tableTypes;
+#ifndef SP_REFACTOR /* ivars */
NSMutableArray *filteredTableTypes;
- SPTableType selectedTableType;
+#endif
+ NSInteger selectedTableType;
NSString *selectedTableName;
+#ifndef SP_REFACTOR /* ivars */
BOOL isTableListFiltered;
BOOL tableListIsSelectable;
+#endif
BOOL tableListContainsViews;
-
+#ifndef SP_REFACTOR /* ivars */
BOOL alertSheetOpened;
NSFont *smallSystemFont;
-
+#endif
}
// IBAction methods
- (IBAction)updateTables:(id)sender;
+
+#ifndef SP_REFACTOR /* method decls */
- (IBAction)addTable:(id)sender;
- (IBAction)closeSheet:(id)sender;
- (IBAction)removeTable:(id)sender;
@@ -118,13 +131,11 @@
- (IBAction)truncateTable:(id)sender;
- (IBAction)openTableInNewTab:(id)sender;
- (IBAction)togglePaneCollapse:(id)sender;
-
-// Alert sheet callbacks
-- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo;
-
+#endif
// Additional methods
- (void)setConnection:(MCPConnection *)theConnection;
- (void)setSelectionState:(NSDictionary *)selectionDetails;
+#ifndef SP_REFACTOR /* method decls */
- (void)selectTableAtIndex:(NSNumber *)row;
- (void)makeTableListFilterHaveFocus;
@@ -132,6 +143,7 @@
- (NSArray *)selectedTableNames;
- (NSArray *)selectedTableItems;
- (NSArray *)selectedTableTypes;
+#endif
- (NSString *)tableName;
- (SPTableType)tableType;
- (NSArray *)tables;
@@ -147,12 +159,9 @@
// Setters
- (BOOL)selectItemWithName:(NSString *)theName;
+#ifndef SP_REFACTOR /* method decls */
- (BOOL)selectItemsWithNames:(NSArray *)theNames;
-// Data validation
-- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType;
-- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType ignoringSelectedTable:(BOOL)ignoreSelectedTable;
-
// Table list filter interaction
- (void) showFilter;
- (void) hideFilter;
@@ -163,5 +172,11 @@
- (void) startDocumentTaskForTab:(NSNotification *)aNotification;
- (void) endDocumentTaskForTab:(NSNotification *)aNotification;
- (void) setTableListSelectability:(BOOL)isSelectable;
+#endif
+- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType;
+- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType ignoringSelectedTable:(BOOL)ignoreSelectedTable;
+#ifdef SP_REFACTOR /* method decls */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)val;
+#endif
@end
diff --git a/Source/SPTablesList.m b/Source/SPTablesList.m
index fa358b23..c7f3bc1f 100644
--- a/Source/SPTablesList.m
+++ b/Source/SPTablesList.m
@@ -24,11 +24,18 @@
// More info at <http://code.google.com/p/sequel-pro/>
#import "SPTablesList.h"
+#ifndef SP_REFACTOR /* headers */
+#import "SPConnectionController.h"
+#endif
#import "SPDatabaseDocument.h"
-#import "SPDatabaseViewController.h"
#import "SPTableStructure.h"
+#import "SPDatabaseViewController.h"
+
+#ifndef SP_REFACTOR /* headers */
#import "SPTableContent.h"
+#endif
#import "SPTableData.h"
+#ifndef SP_REFACTOR /* headers */
#import "SPTableInfo.h"
#import "SPDataImport.h"
#import "SPTableView.h"
@@ -51,6 +58,7 @@
- (void)renameTableOfType:(SPTableType)tableType from:(NSString *)oldTableName to:(NSString *)newTableName;
@end
+#endif
@implementation SPTablesList
@@ -67,10 +75,13 @@
NSUInteger i;
NSString *previousSelectedTable = nil;
NSString *previousFilterString = nil;
+#ifndef SP_REFACTOR /* table list filtering */
BOOL previousTableListIsSelectable = tableListIsSelectable;
+#endif
BOOL changeEncoding = ![[mySQLConnection encoding] isEqualToString:@"utf8"];
if (selectedTableName) previousSelectedTable = [[NSString alloc] initWithString:selectedTableName];
+#ifndef SP_REFACTOR /* table list filtering */
if (isTableListFiltered) {
previousFilterString = [[NSString alloc] initWithString:[listFilterField stringValue]];
if (filteredTables) [filteredTables release];
@@ -85,6 +96,7 @@
tableListIsSelectable = YES;
[[tablesListView onMainThread] deselectAll:self];
tableListIsSelectable = previousTableListIsSelectable;
+#endif
[tables removeAllObjects];
[tableTypes removeAllObjects];
@@ -132,6 +144,7 @@
// Reorder the tables in alphabetical order
[tables sortArrayUsingSelector:@selector(localizedCompare:) withPairedMutableArrays:tableTypes, nil];
+#ifndef SP_REFACTOR /* table procedures and functions */
/* Grab the procedures and functions
*
* Using information_schema gives us more info (for information window perhaps?) but breaks
@@ -171,7 +184,7 @@
}
}
}
- /*
+#endif /*
BOOL addedPFHeader = FALSE;
NSString *pQuery = [NSString stringWithFormat:@"SHOW PROCEDURE STATUS WHERE db = '%@'",[tableDocumentInstance database]];
theResult = [mySQLConnection queryString:pQuery];
@@ -240,7 +253,9 @@
[tableTypes insertObject:[NSNumber numberWithInteger:SPTableTypeNone] atIndex:0];
+#ifndef SP_REFACTOR /* ui manipulation */
[[tablesListView onMainThread] reloadData];
+#endif
// if the previous selected table still exists, select it
// but not if the update was called from SPTableData since it calls that method
@@ -248,9 +263,11 @@
// or if the table name contains characters which are not supported by the current set encoding
if ( ![sender isKindOfClass:[SPTableData class]] && previousSelectedTable != nil && [tables indexOfObject:previousSelectedTable] < [tables count]) {
NSInteger itemToReselect = [tables indexOfObject:previousSelectedTable];
+#ifndef SP_REFACTOR /* ui manipulation */
tableListIsSelectable = YES;
[[tablesListView onMainThread] selectRowIndexes:[NSIndexSet indexSetWithIndex:itemToReselect] byExtendingSelection:NO];
tableListIsSelectable = previousTableListIsSelectable;
+#endif
if (selectedTableName) [selectedTableName release];
selectedTableName = [[NSString alloc] initWithString:[tables objectAtIndex:itemToReselect]];
selectedTableType = (SPTableType)[[tableTypes objectAtIndex:itemToReselect] integerValue];
@@ -261,6 +278,7 @@
selectedTableType = SPTableTypeNone;
}
+#ifndef SP_REFACTOR /* table list filtering */
// Determine whether or not to preserve the existing filter, and whether to
// show or hide the list filter based on the number of tables
if ([tables count] > 20) {
@@ -277,6 +295,7 @@
if ([tableDocumentInstance database]) {
[[[listFilterField cell] onMainThread] setPlaceholderString:NSLocalizedString(@"Filter", @"filter label")];
}
+#endif
if (previousSelectedTable) [previousSelectedTable release];
if (previousFilterString) [previousFilterString release];
@@ -289,6 +308,7 @@
// User press refresh button ergo force update
[NSThread detachNewThreadSelector:@selector(queryDbStructureWithUserInfo:) toTarget:mySQLConnection withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", [NSNumber numberWithBool:YES], @"cancelQuerying", nil]];
}
+#ifndef SP_REFACTOR /* whole table operations */
/**
* Adds a new table to the tables-array (no changes in mysql-db)
@@ -658,6 +678,8 @@
#pragma mark -
#pragma mark Additional methods
+#endif
+
/**
* Sets the connection (received from SPDatabaseDocument) and makes things that have to be done only once
*/
@@ -667,6 +689,8 @@
[self updateTables:self];
}
+#ifndef SP_REFACTOR /* ui validation */
+
/**
* Performs interface validation for various controls.
*/
@@ -702,6 +726,7 @@
[copyTableButton performClick:object];
}
}
+#endif
/**
* Updates application state to match the current selection, including
@@ -715,17 +740,23 @@
{
// First handle empty or multiple selections
if (!selectionDetails || ![selectionDetails objectForKey:@"name"]) {
+#ifndef SP_REFACTOR /* ui manipulation */
NSIndexSet *indexes = [tablesListView selectedRowIndexes];
-
+#endif
// Update the selected table name and type
if (selectedTableName) [selectedTableName release];
+#ifndef SP_REFACTOR /* ui manipulation */
if ([indexes count]) {
selectedTableName = [[NSString alloc] initWithString:@""];
}
else {
+#endif
selectedTableName = nil;
+#ifndef SP_REFACTOR /* ui manipulation */
}
+#endif
+#ifndef SP_REFACTOR /* ui manipulation */
// Set gear menu items Remove/Duplicate table/view according to the table types
// if at least one item is selected
@@ -826,6 +857,7 @@
[[tableSubMenu itemAtIndex:10] setHidden:NO];
return;
+#endif
}
// If a new selection has been provided, store variables and update the interface to match
@@ -837,6 +869,7 @@
selectedTableName = [[NSString alloc] initWithString:selectedItemName];
selectedTableType = selectedItemType;
+#ifndef SP_REFACTOR /* ui manipulation */
// Remove the "current selection" item for filtered lists if appropriate
if (isTableListFiltered && [tablesListView selectedRow] < (NSInteger)[filteredTables count] - 2 && [filteredTables count] > 2
&& [[filteredTableTypes objectAtIndex:[filteredTableTypes count]-2] integerValue] == SPTableTypeNone
@@ -1007,8 +1040,11 @@
[showCreateSyntaxContextMenuItem setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create Function Syntax...", @"show create func syntax menu item")];
}
+#endif
}
+#ifndef SP_REFACTOR /* getters */
+
#pragma mark -
#pragma mark Getter methods
@@ -1055,6 +1091,7 @@
}
return selTables;
}
+#endif
/**
* Returns the currently selected table or nil if no table or mulitple tables are selected
@@ -1203,6 +1240,7 @@
// If no match found, return failure
if (itemIndex == NSNotFound) return NO;
+#ifndef SP_REFACTOR /* table list filtering */
if (!isTableListFiltered) {
[tablesListView selectRowIndexes:[NSIndexSet indexSetWithIndex:itemIndex] byExtendingSelection:NO];
} else {
@@ -1211,19 +1249,26 @@
[tablesListView selectRowIndexes:[NSIndexSet indexSetWithIndex:filteredIndex] byExtendingSelection:NO];
} else {
[tablesListView deselectAll:nil];
+#endif
if (selectedTableName) [selectedTableName release];
selectedTableName = [[NSString alloc] initWithString:[tables objectAtIndex:itemIndex]];
- selectedTableType = (SPTableType)[[tableTypes objectAtIndex:itemIndex] integerValue];
+ selectedTableType = [[tableTypes objectAtIndex:itemIndex] integerValue];
+#ifndef SP_REFACTOR /* table list filtering */
[self updateFilter:self];
+#endif
[tableDocumentInstance loadTable:selectedTableName ofType:selectedTableType];
+#ifndef SP_REFACTOR /* table list filtering */
}
}
[[tablesListView onMainThread] scrollRowToVisible:[tablesListView selectedRow]];
+#endif
return YES;
}
+#ifndef SP_REFACTOR /* tableView datasource/delegate */
+
/**
* Try to select items using the provided names in theNames; returns YES if at least
* one item could be seleceted, otherwise NO.
@@ -1361,6 +1406,9 @@
return ![tableDocumentInstance isWorking];
}
+
+#ifndef SP_REFACTOR
+
/**
* Renames a table (in tables-array and mysql-db).
*/
@@ -1420,6 +1468,7 @@
// Query the structure of all databases in the background (mainly for completion)
[NSThread detachNewThreadSelector:@selector(queryDbStructureWithUserInfo:) toTarget:mySQLConnection withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]];
}
+#endif
#pragma mark -
#pragma mark TableView delegate methods
@@ -1849,6 +1898,7 @@
{
return (splitView == tableListSplitView ? NSZeroRect : proposedEffectiveRect);
}
+#endif
#pragma mark -
@@ -1861,21 +1911,28 @@
{
if ((self = [super init])) {
tables = [[NSMutableArray alloc] init];
+#ifndef SP_REFACTOR
filteredTables = tables;
+#endif
tableTypes = [[NSMutableArray alloc] init];
+#ifndef SP_REFACTOR
filteredTableTypes = tableTypes;
isTableListFiltered = NO;
tableListIsSelectable = YES;
+#endif
tableListContainsViews = NO;
selectedTableType = SPTableTypeNone;
selectedTableName = nil;
[tables addObject:NSLocalizedString(@"TABLES",@"header for table list")];
+#ifndef SP_REFACTOR /* font */
smallSystemFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
+#endif
}
return self;
}
+#ifndef SP_REFACTOR /* awakeFromNib */
/**
* Standard awakeFromNib method for interface loading.
*/
@@ -1922,6 +1979,7 @@
[tablesListView registerForDraggedTypes:[NSArray arrayWithObjects:@"SPDragTableDataFromNavigatorPboardType", nil]];
}
+#endif
/**
* Standard dealloc method.
@@ -1932,13 +1990,24 @@
[tables release];
[tableTypes release];
+#ifndef SP_REFACTOR
if (isTableListFiltered && filteredTables) [filteredTables release];
if (isTableListFiltered && filteredTableTypes) [filteredTableTypes release];
+#endif
if (selectedTableName) [selectedTableName release];
[super dealloc];
}
+
+#ifdef SP_REFACTOR /* glue */
+- (void)setDatabaseDocument:(SPDatabaseDocument*)val
+{
+ tableDocumentInstance = val;
+}
+#endif
+
+#ifndef SP_REFACTOR /* operations performed on whole tables */
@end
@implementation SPTablesList (PrivateAPI)
@@ -2445,5 +2514,67 @@
[NSException raise:@"Object of unknown type" format:NSLocalizedString(@"An error occured while renaming. '%@' is of an unknown type.", @"rename error - don't know what type the renamed thing is"), oldTableName];
}
+#endif
+
+/**
+ * Check tableName for length and if the tableName doesn't match
+ * against current database table/view names (case-insensitive).
+ */
+- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType
+{
+ return [self isTableNameValid:tableName forType:tableType ignoringSelectedTable:NO];
+}
+
+/**
+ * Check tableName for length and if the tableName doesn't match
+ * against current database table/view names (case-insensitive).
+ */
+- (BOOL)isTableNameValid:(NSString *)tableName forType:(SPTableType)tableType ignoringSelectedTable:(BOOL)ignoreSelectedTable
+{
+ BOOL isValid = YES;
+
+ // delete trailing whitespaces since 'foo ' or ' ' are not valid table names
+ NSString *fieldStr = [tableName stringByMatching:@"(.*?)\\s*$" capture:1];
+ NSString *lowercaseFieldStr = [fieldStr lowercaseString];
+
+ // If table name has trailing whitespaces return 'no valid'
+ if([fieldStr length] != [tableName length]) return NO;
+
+ // empty table names are invalid
+ if([fieldStr length] == 0) return NO;
+
+
+ NSArray *similarTables;
+ switch (tableType) {
+ case SPTableTypeView:
+ case SPTableTypeTable:
+ similarTables = [self allTableAndViewNames];
+ break;
+ case SPTableTypeProc:
+ similarTables = [self allProcedureNames];
+ break;
+ case SPTableTypeFunc:
+ similarTables = [self allFunctionNames];
+ break;
+ default:
+ // if some other table type is given, just return yes
+ // better a mysql error than not being able to change something at all
+ return YES;
+ }
+
+ for(id table in similarTables) {
+ //compare case insensitive here
+ if([lowercaseFieldStr isEqualToString:[table lowercaseString]]) {
+ if (ignoreSelectedTable) {
+ // if table is the selectedTable, ignore it
+ // we must compare CASE SENSITIVE here!
+ if ([table isEqualToString:selectedTableName]) continue;
+ }
+ isValid = NO;
+ break;
+ }
+ }
+ return isValid;
+}
@end
diff --git a/Source/SPTextView.h b/Source/SPTextView.h
index 3954c941..bc4a3eb8 100644
--- a/Source/SPTextView.h
+++ b/Source/SPTextView.h
@@ -32,7 +32,11 @@
@class SPNarrowDownCompletion, SPDatabaseDocument, SPTablesList, SPCustomQuery;
-@interface SPTextView : NSTextView
+#ifndef SP_REFACTOR
+@interface SPTextView : NSTextView
+#else
+@interface SPTextView : NSTextView <NSTextStorageDelegate>
+#endif
{
IBOutlet SPDatabaseDocument *tableDocumentInstance;
IBOutlet SPTablesList *tablesListInstance;
@@ -43,18 +47,24 @@
BOOL autoindentIgnoresEnter;
BOOL autouppercaseKeywordsEnabled;
BOOL delBackwardsWasPressed;
+#ifndef SP_REFACTOR
BOOL autohelpEnabled;
+#endif
NoodleLineNumberView *lineNumberView;
BOOL startListeningToBoundChanges;
BOOL textBufferSizeIncreased;
+#ifndef SP_REFACTOR
NSString *showMySQLHelpFor;
+#endif
IBOutlet NSScrollView *scrollView;
SPNarrowDownCompletion *completionPopup;
+#ifndef SP_REFACTOR
NSUserDefaults *prefs;
+#endif
MCPConnection *mySQLConnection;
NSInteger mySQLmajorVersion;
@@ -102,7 +112,9 @@
@property(assign) BOOL completionIsOpen;
@property(assign) BOOL completionWasReinvokedAutomatically;
+#ifndef SP_REFACTOR
- (IBAction)showMySQLHelpForCurrentWord:(id)sender;
+#endif
- (BOOL) isNextCharMarkedBy:(id)attribute withValue:(id)aValue;
- (BOOL) areAdjacentCharsLinked;
@@ -119,12 +131,16 @@
- (BOOL) autopair;
- (void) setAutouppercaseKeywords:(BOOL)enableAutouppercaseKeywords;
- (BOOL) autouppercaseKeywords;
+#ifndef SP_REFACTOR
- (void) setAutohelp:(BOOL)enableAutohelp;
- (BOOL) autohelp;
+#endif
- (void) setTabStops;
- (void) selectLineNumber:(NSUInteger)lineNumber ignoreLeadingNewLines:(BOOL)ignLeadingNewLines;
- (NSUInteger) getLineNumberForCharacterIndex:(NSUInteger)anIndex;
+#ifndef SP_REFACTOR
- (void) autoHelp;
+#endif
- (void) doSyntaxHighlighting;
- (NSBezierPath*)roundedBezierPathAroundRange:(NSRange)aRange;
- (void) setConnection:(MCPConnection *)theConnection withVersion:(NSInteger)majorVersion;
diff --git a/Source/SPTextView.m b/Source/SPTextView.m
index 4fef6ee3..5e04ff2b 100644
--- a/Source/SPTextView.m
+++ b/Source/SPTextView.m
@@ -112,9 +112,10 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
- (void) awakeFromNib
{
-
+#ifndef SP_REFACTOR
prefs = [[NSUserDefaults standardUserDefaults] retain];
[self setFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorFont]]];
+#endif
// Set self as delegate for the textView's textStorage to enable syntax highlighting,
[[self textStorage] setDelegate:self];
@@ -124,7 +125,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
autopairEnabled = YES;
autoindentIgnoresEnter = NO;
autouppercaseKeywordsEnabled = NO;
+#ifndef SP_REFACTOR
autohelpEnabled = NO;
+#endif
delBackwardsWasPressed = NO;
startListeningToBoundChanges = NO;
textBufferSizeIncreased = NO;
@@ -142,11 +145,20 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[scrollView setRulersVisible:YES];
[self setAllowsDocumentBackgroundColorChange:YES];
[self setContinuousSpellCheckingEnabled:NO];
+#ifndef SP_REFACTOR
[self setAutoindent:[prefs boolForKey:SPCustomQueryAutoIndent]];
+#else
+ [self setAutoindent:YES];
+#endif
[self setAutoindentIgnoresEnter:YES];
+#ifndef SP_REFACTOR
[self setAutopair:[prefs boolForKey:SPCustomQueryAutoPairCharacters]];
[self setAutohelp:[prefs boolForKey:SPCustomQueryUpdateAutoHelp]];
[self setAutouppercaseKeywords:[prefs boolForKey:SPCustomQueryAutoUppercaseKeywords]];
+#else
+ [self setAutopair:YES];
+ [self setAutouppercaseKeywords:YES];
+#endif
[self setCompletionWasReinvokedAutomatically:NO];
// Re-define tab stops for a better editing
@@ -159,6 +171,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[scrollView setPostsBoundsChangedNotifications:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChangeNotification:) name:NSViewBoundsDidChangeNotification object:[scrollView contentView]];
+#ifndef SP_REFACTOR
[self setQueryHiliteColor:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorHighlightQueryColor]]];
[self setQueryEditorBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorBackgroundColor]]];
[self setCommentColor:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorCommentColor]]];
@@ -189,7 +202,22 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[prefs addObserver:self forKeyPath:SPCustomQueryEditorTextColor options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:SPCustomQueryEditorTabStopWidth options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:SPCustomQueryAutoUppercaseKeywords options:NSKeyValueObservingOptionNew context:NULL];
+#else
+ [self setQueryHiliteColor:[NSColor whiteColor]];
+ [self setQueryEditorBackgroundColor:[NSColor whiteColor]];
+ [self setCommentColor:[NSColor darkGrayColor]];
+ [self setQuoteColor:[NSColor blueColor]];
+ [self setKeywordColor:[NSColor redColor]];
+ [self setBacktickColor:[NSColor purpleColor]];
+ [self setNumericColor:[NSColor blueColor]];
+ [self setVariableColor:[NSColor yellowColor]];
+ [self setOtherTextColor:[NSColor blackColor]];
+ [self setTextColor:otherTextColor];
+ [self setInsertionPointColor:[NSColor blackColor]];
+ [self setShouldHiliteQuery:YES];
+ [self setSelectedTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor lightGrayColor], NSBackgroundColorAttributeName, nil]];
+#endif
}
- (void) setConnection:(MCPConnection *)theConnection withVersion:(NSInteger)majorVersion
@@ -203,6 +231,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
+#ifndef SP_REFACTOR
if ([keyPath isEqualToString:SPCustomQueryEditorBackgroundColor]) {
[self setQueryEditorBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]]];
[self setNeedsDisplay:YES];
@@ -255,6 +284,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
} else if ([keyPath isEqualToString:SPCustomQueryAutoUppercaseKeywords]) {
[self setAutouppercaseKeywords:[prefs boolForKey:SPCustomQueryAutoUppercaseKeywords]];
}
+#endif
}
/**
@@ -375,7 +405,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if(!aDbName) {
// Try to suggest only items which are uniquely valid for the parsed string
- NSArray *uniqueSchema = [[SPNavigatorController sharedNavigatorController] getUniqueDbIdentifierFor:[aTableName lowercaseString] andConnection:[[[self delegate] valueForKeyPath:@"tableDocumentInstance"] connectionID] ignoreFields:YES];
+ NSArray *uniqueSchema = [[SPNavigatorController sharedNavigatorController] getUniqueDbIdentifierFor:[aTableName lowercaseString] andConnection:[[(NSObject*)[self delegate] valueForKeyPath:@"tableDocumentInstance"] connectionID] ignoreFields:YES];
NSInteger uniqueSchemaKind = [[uniqueSchema objectAtIndex:0] intValue];
// If no db name but table name check if table name is a valid name in the current selected db
@@ -535,7 +565,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if(completionIsOpen || !self || ![self delegate]) return;
// Cancel autocompletion trigger
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -577,7 +609,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
// Cancel autocompletion trigger
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -770,7 +804,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
}
// Cancel autocompletion trigger again if user typed something in while parsing
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -982,7 +1018,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// If Extended Table Info tab is active delegate the print call to the SPPrintController
// if the user doesn't select anything in self
if([[[[self delegate] class] description] isEqualToString:@"SPExtendedTableInfo"] && ![self selectedRange].length) {
- [[[self delegate] valueForKeyPath:@"tableDocumentInstance"] printDocument:sender];
+ [[(NSObject*)[self delegate] valueForKeyPath:@"tableDocumentInstance"] printDocument:sender];
return;
}
@@ -1020,6 +1056,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.01];
}
+#ifndef SP_REFACTOR
/**
* Search for the current selection or current word in the MySQL Help
*/
@@ -1027,6 +1064,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
[customQueryInstance showHelpForCurrentWord:self];
}
+#endif
/**
* If the textview has a selection, wrap it with the supplied prefix and suffix strings;
@@ -1051,7 +1089,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self setSelectedRange:innerSelectionRange];
// If autopair is enabled mark last autopair character as autopair-linked
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoPairCharacters])
+#endif
[[self textStorage] addAttribute:kAPlinked value:kAPval range:NSMakeRange(NSMaxRange(innerSelectionRange), 1)];
return YES;
@@ -1133,6 +1173,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if (selectedRange.location == NSNotFound || ![self isEditable]) return NO;
NSString *indentString = @"\t";
+#ifndef SP_REFACTOR
if ([prefs boolForKey:SPCustomQuerySoftIndent]) {
NSUInteger numberOfSpaces = [prefs integerForKey:SPCustomQuerySoftIndentWidth];
if(numberOfSpaces < 1) numberOfSpaces = 1;
@@ -1142,6 +1183,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[spaces appendString:@" "];
indentString = [NSString stringWithString:spaces];
}
+#endif
// Indent the currently selected line if the caret is within a single line
if (selectedRange.length == 0) {
@@ -1222,6 +1264,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// Check for soft indention
NSUInteger indentStringLength = 1;
+#ifndef SP_REFACTOR
if ([prefs boolForKey:SPCustomQuerySoftIndent]) {
NSUInteger numberOfSpaces = [prefs integerForKey:SPCustomQuerySoftIndentWidth];
if(numberOfSpaces < 1) numberOfSpaces = 1;
@@ -1234,8 +1277,11 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if(numberOfLeadingWhiteSpaces == NSNotFound) numberOfLeadingWhiteSpaces = 0;
replaceRange = NSMakeRange(currentLineRange.location, numberOfLeadingWhiteSpaces);
} else {
+#endif
replaceRange = NSMakeRange(currentLineRange.location, indentStringLength);
+#ifndef SP_REFACTOR
}
+#endif
// Register the undent for undo
[self shouldChangeTextInRange:replaceRange replacementString:@""];
@@ -1258,6 +1304,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// Check for soft or hard indention
NSString *indentString = @"\t";
NSUInteger indentStringLength = 1;
+#ifndef SP_REFACTOR
if ([prefs boolForKey:SPCustomQuerySoftIndent]) {
indentStringLength = [prefs integerForKey:SPCustomQuerySoftIndentWidth];
if(indentStringLength < 1) indentStringLength = 1;
@@ -1267,6 +1314,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[spaces appendString:@" "];
indentString = [NSString stringWithString:spaces];
}
+#endif
// Check if blockRange starts with SPACE or TAB
// (this also catches the first line of the entire text buffer or
@@ -1321,7 +1369,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
// Cancel auto-completion timer
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -1362,7 +1412,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// }
// }
// } else {
- arr = [NSArray arrayWithArray:[[[self delegate] valueForKeyPath:@"tablesListInstance"] allTableAndViewNames]];
+ arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allTableAndViewNames]];
if(arr == nil) {
arr = [NSArray array];
}
@@ -1371,13 +1421,13 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// }
}
else if([kind isEqualToString:@"$SP_ASLIST_ALL_DATABASES"]) {
- arr = [NSArray arrayWithArray:[[[self delegate] valueForKeyPath:@"tablesListInstance"] allDatabaseNames]];
+ arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allDatabaseNames]];
if(arr == nil) {
arr = [NSArray array];
}
for(id w in arr)
[possibleCompletions addObject:[NSDictionary dictionaryWithObjectsAndKeys:w, @"display", @"database-small", @"image", @"", @"isRef", nil]];
- arr = [NSArray arrayWithArray:[[[self delegate] valueForKeyPath:@"tablesListInstance"] allSystemDatabaseNames]];
+ arr = [NSArray arrayWithArray:[[(NSObject*)[self delegate] valueForKeyPath:@"tablesListInstance"] allSystemDatabaseNames]];
if(arr == nil) {
arr = [NSArray array];
}
@@ -1733,6 +1783,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if (tablesListInstance && [tablesListInstance selectedDatabase])
currentDb = [tablesListInstance selectedDatabase];
+#ifndef SP_REFACTOR
while([theHintString isMatchedByRegex:@"(?<!\\\\)\\$SP_SELECTED_TABLES"]) {
r = [theHintString rangeOfRegex:@"(?<!\\\\)\\$SP_SELECTED_TABLES"];
if(r.length) {
@@ -1744,6 +1795,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
}
[theHintString flushCachedRegexData];
}
+#endif
while([theHintString isMatchedByRegex:@"(?<!\\\\)\\$SP_SELECTED_TABLE"]) {
r = [theHintString rangeOfRegex:@"(?<!\\\\)\\$SP_SELECTED_TABLE"];
@@ -1772,9 +1824,10 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[theHintString replaceOccurrencesOfRegex:@"\\\\(\\$\\(|\\}|\\$SP_)" withString:@"$1"];
[theHintString flushCachedRegexData];
- // If inside the snippet hint $(…) is defined run … as BASH command
- // and replace $(…) by the return string of that command. Please note
- // only one $(…) statement is allowed within one ${…} snippet environment.
+#ifndef SP_REFACTOR
+ // If inside the snippet hint $() is defined run as BASH command
+ // and replace $() by the return string of that command. Please note
+ // only one $() statement is allowed within one ${} snippet environment.
NSRange tagRange = [theHintString rangeOfRegex:@"(?s)(?<!\\\\)\\$\\((.*)\\)"];
if(tagRange.length) {
[theHintString flushCachedRegexData];
@@ -1794,6 +1847,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
}
}
[theHintString flushCachedRegexData];
+#endif
[snip replaceCharactersInRange:snipRange withString:theHintString];
[snip flushCachedRegexData];
@@ -1899,11 +1953,15 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self insertText:snip];
// If autopair is enabled check whether snip begins with ( and ends with ), if so mark ) as pair-linked
- if ([prefs boolForKey:SPCustomQueryAutoPairCharacters]
- && (([snip hasPrefix:@"("] && [snip hasSuffix:@")"])
- || ([snip hasPrefix:@"`"] && [snip hasSuffix:@"`"])
- || ([snip hasPrefix:@"'"] && [snip hasSuffix:@"'"])
- || ([snip hasPrefix:@"\""] && [snip hasSuffix:@"\""])))
+#ifndef SP_REFACTOR
+ if ([prefs boolForKey:SPCustomQueryAutoPairCharacters] &&
+#else
+ if (
+#endif
+ (([snip hasPrefix:@"("] && [snip hasSuffix:@")"])
+ || ([snip hasPrefix:@"`"] && [snip hasSuffix:@"`"])
+ || ([snip hasPrefix:@"'"] && [snip hasSuffix:@"'"])
+ || ([snip hasPrefix:@"\""] && [snip hasSuffix:@"\""])))
{
[[self textStorage] addAttribute:kAPlinked value:kAPval range:NSMakeRange([self selectedRange].location - 1, 1)];
}
@@ -2019,23 +2077,28 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
// Cancel autoHelp timer
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryUpdateAutoHelp])
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(autoHelp)
object:nil];
+#endif
// Cancel auto-completion timer
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
[super mouseDown:theEvent];
+#ifndef SP_REFACTOR
// Start autoHelp timer
if([prefs boolForKey:SPCustomQueryUpdateAutoHelp])
[self performSelector:@selector(autoHelp) withObject:nil afterDelay:[[prefs valueForKey:SPCustomQueryAutoHelpDelay] doubleValue]];
-
+#endif
}
/**
@@ -2043,6 +2106,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
*/
- (void) keyDown:(NSEvent *)theEvent
{
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryUpdateAutoHelp]) {// restart autoHelp timer
[NSObject cancelPreviousPerformRequestsWithTarget:self
@@ -2051,9 +2115,12 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self performSelector:@selector(autoHelp) withObject:nil
afterDelay:[[prefs valueForKey:SPCustomQueryAutoHelpDelay] doubleValue]];
}
+#endif
// Cancel auto-completion timer
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -2081,7 +2148,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self setCompletionWasReinvokedAutomatically:NO];
completionWasRefreshed = NO;
// Cancel autocompletion trigger
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -2156,11 +2225,14 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// Check for TAB as indention for current line, i.e. left of the caret there are only white spaces
// but only if Soft Indent is set
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQuerySoftIndent] && [self isCaretAtIndentPositionIgnoreLineStart:YES]) {
if([self shiftSelectionRight]) return;
}
+#endif
}
+#ifndef SP_REFACTOR
// Note: switch(insertedCharacter) {} does not work instead use charactersIgnoringModifiers
if([charactersIgnMod isEqualToString:@"h"]) // ^H show MySQL Help
if(curFlags==(NSControlKeyMask))
@@ -2168,6 +2240,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self showMySQLHelpForCurrentWord:self];
return;
}
+#endif
if([charactersIgnMod isEqualToString:@"y"]) // ^Y select current query
if(curFlags==(NSControlKeyMask))
{
@@ -2188,14 +2261,20 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if([charactersIgnMod isEqualToString:@"0"]) { // reset font to default
BOOL editableStatus = [self isEditable];
[self setEditable:YES];
+#ifndef SP_REFACTOR
[self setFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorFont]]];
+#endif
[self setEditable:editableStatus];
return;
}
}
// Only process for character autopairing if autopairing is enabled and a single character is being added.
+#ifndef SP_REFACTOR
if ([prefs boolForKey:SPCustomQueryAutoPairCharacters] && characters && [characters length] == 1) {
+#else
+ if (characters && [characters length] == 1) {
+#endif
delBackwardsWasPressed = NO;
@@ -2400,7 +2479,11 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
}
// Remove soft indent if active and left from caret are only white spaces
+#ifndef SP_REFACTOR
else if ([prefs boolForKey:SPCustomQuerySoftIndent] && [self isCaretAtIndentPositionIgnoreLineStart:NO])
+#else
+ else if ([self isCaretAtIndentPositionIgnoreLineStart:NO])
+#endif
{
[self shiftSelectionLeft];
return;
@@ -2422,7 +2505,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// Handle newlines, adding any indentation found on the current line to the new line - ignoring the enter key if appropriate
if (aSelector == @selector(insertNewline:)
+#ifndef SP_REFACTOR
&& [prefs boolForKey:SPCustomQueryAutoIndent]
+#endif
&& (!autoindentIgnoresEnter || [[NSApp currentEvent] keyCode] != 0x4C))
{
NSString *textViewString = [[self textStorage] string];
@@ -2460,6 +2545,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
}
// Remove soft indent if active and left from caret are only white spaces
+#ifndef SP_REFACTOR
if (aSelector == @selector(deleteForward:)
&& ![self selectedRange].length
&& [prefs boolForKey:SPCustomQuerySoftIndent]
@@ -2469,6 +2555,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self shiftSelectionLeft];
return;
}
+#endif
[super doCommandBySelector:aSelector];
}
@@ -2522,6 +2609,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
return autopairEnabled;
}
+#ifndef SP_REFACTOR
/**
* Set whether MySQL Help should be automatically invoked while typing.
*/
@@ -2537,6 +2625,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
return autohelpEnabled;
}
+#endif
/**
* Set whether SQL keywords should be automatically uppercased.
@@ -2562,7 +2651,11 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
- (void)autoHelp
{
+#ifndef SP_REFACTOR
if(![prefs boolForKey:SPCustomQueryUpdateAutoHelp] || ![[self string] length]) return;
+#else
+ if(![[self string] length]) return;
+#endif
// If selection show Help for it
if([self selectedRange].length)
@@ -2784,7 +2877,11 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
- (void) setTabStops
{
+#ifndef SP_REFACTOR
NSFont *tvFont = [self font];
+#else
+ NSFont* tvFont = [NSFont userFixedPitchFontOfSize:10.0];
+#endif
NSInteger i;
NSTextTab *aTab;
NSMutableArray *myArrayOfTabs;
@@ -2793,7 +2890,11 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
BOOL oldEditableStatus = [self isEditable];
[self setEditable:YES];
+#ifndef SP_REFACTOR
NSInteger tabStopWidth = [prefs integerForKey:SPCustomQueryEditorTabStopWidth];
+#else
+ NSInteger tabStopWidth = 4;
+#endif
if(tabStopWidth < 1) tabStopWidth = 1;
float tabWidth = NSSizeToCGSize([[NSString stringWithString:@" "] sizeWithAttributes:[NSDictionary dictionaryWithObject:tvFont forKey:NSFontAttributeName]]).width;
@@ -2960,11 +3061,13 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
*/
- (NSMenu *)menuForEvent:(NSEvent *)event
{
+#ifndef SP_REFACTOR
// Set title of the menu item
if([self selectedRange].length)
showMySQLHelpFor = NSLocalizedString(@"MySQL Help for Selection", @"MySQL Help for Selection");
else
showMySQLHelpFor = NSLocalizedString(@"MySQL Help for Word", @"MySQL Help for Word");
+#endif
// Add the menu items for
// - MySQL Help for Word/Selection
@@ -2973,6 +3076,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// if it doesn't yet exist
NSMenu *menu = [[self class] defaultMenu];
+#ifndef SP_REFACTOR
if ([[[self class] defaultMenu] itemWithTag:SP_CQ_SEARCH_IN_MYSQL_HELP_MENU_ITEM_TAG] == nil)
{
[menu insertItem:[NSMenuItem separatorItem] atIndex:3];
@@ -2984,6 +3088,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
} else {
[[menu itemWithTag:SP_CQ_SEARCH_IN_MYSQL_HELP_MENU_ITEM_TAG] setTitle:showMySQLHelpFor];
}
+#endif
if ([[[self class] defaultMenu] itemWithTag:SP_CQ_COPY_AS_RTF_MENU_ITEM_TAG] == nil)
{
NSMenuItem *copyAsRTFMenuItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Copy as RTF", @"Copy as RTF") action:@selector(copyAsRTF) keyEquivalent:@""];
@@ -3010,6 +3115,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[[menu itemAtIndex:6] setHidden:YES];
}
+#ifndef SP_REFACTOR
[[NSApp delegate] reloadBundles:self];
// Remove 'Bundles' sub menu and separator
@@ -3074,6 +3180,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[bundleSubMenuItem release];
}
+#endif
return menu;
@@ -3147,7 +3254,9 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
if (textStore!=[self textStorage]) return;
// Cancel autocompletion trigger
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryAutoComplete])
+#endif
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doAutoCompletion)
object:nil];
@@ -3155,13 +3264,20 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
NSInteger editedMask = [textStore editedMask];
// Start autohelp only if the user really changed the text (not e.g. for setting a background color)
+#ifndef SP_REFACTOR
if([prefs boolForKey:SPCustomQueryUpdateAutoHelp] && editedMask != 1) {
[self performSelector:@selector(autoHelp) withObject:nil afterDelay:[[prefs valueForKey:SPCustomQueryAutoHelpDelay] doubleValue]];
}
+#endif
// Start autocompletion if enabled
+#ifndef SP_REFACTOR
if([[NSApp keyWindow] firstResponder] == self && [prefs boolForKey:SPCustomQueryAutoComplete] && !completionIsOpen && editedMask != 1 && [textStore changeInLength] == 1)
[self performSelector:@selector(doAutoCompletion) withObject:nil afterDelay:[[prefs valueForKey:SPCustomQueryAutoCompleteDelay] doubleValue]];
+#else
+ if([[NSApp keyWindow] firstResponder] == self && !completionIsOpen && editedMask != 1 && [textStore changeInLength] == 1)
+ [self performSelector:@selector(doAutoCompletion) withObject:nil afterDelay:1.5];
+#endif
// Cancel calling doSyntaxHighlighting for large text
if([[self string] length] > SP_TEXT_SIZE_TRIGGER_FOR_PARTLY_PARSING)
@@ -3488,6 +3604,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
- (void)changeFont:(id)sender
{
+#ifndef SP_REFACTOR
if (prefs && [self font] != nil) {
[prefs setObject:[NSArchiver archivedDataWithRootObject:[self font]] forKey:SPCustomQueryEditorFont];
NSFont *nf = [[NSFontPanel sharedFontPanel] panelConvertFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPCustomQueryEditorFont]]];
@@ -3498,6 +3615,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[self setNeedsDisplay:YES];
[prefs setObject:[NSArchiver archivedDataWithRootObject:nf] forKey:SPCustomQueryEditorFont];
}
+#endif
}
#pragma mark -
@@ -3513,6 +3631,7 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
// Remove observers
[[NSNotificationCenter defaultCenter] removeObserver:self];
+#ifndef SP_REFACTOR
[prefs removeObserver:self forKeyPath:SPCustomQueryEditorFont];
[prefs removeObserver:self forKeyPath:SPCustomQueryEditorBackgroundColor];
[prefs removeObserver:self forKeyPath:SPCustomQueryEditorHighlightQueryColor];
@@ -3526,9 +3645,12 @@ NSInteger _alphabeticSort(id string1, id string2, void *reverse)
[prefs removeObserver:self forKeyPath:SPCustomQueryEditorTextColor];
[prefs removeObserver:self forKeyPath:SPCustomQueryEditorTabStopWidth];
[prefs removeObserver:self forKeyPath:SPCustomQueryAutoUppercaseKeywords];
+#endif
if (completionIsOpen) [completionPopup close], completionIsOpen = NO;
+#ifndef SP_REFACTOR
[prefs release];
+#endif
[lineNumberView release];
if(queryHiliteColor) [queryHiliteColor release];
if(queryEditorBackgroundColor) [queryEditorBackgroundColor release];
diff --git a/Source/SPTextViewAdditions.h b/Source/SPTextViewAdditions.h
index 9553be4d..e95b7041 100644
--- a/Source/SPTextViewAdditions.h
+++ b/Source/SPTextViewAdditions.h
@@ -42,7 +42,9 @@
- (IBAction)moveSelectionLineUp:(id)sender;
- (IBAction)moveSelectionLineDown:(id)sender;
+#ifndef SP_REFACTOR
- (IBAction)executeBundleItemForInputField:(id)sender;
+#endif
- (void)makeTextSizeLarger;
- (void)makeTextSizeSmaller;
diff --git a/Source/SPTextViewAdditions.m b/Source/SPTextViewAdditions.m
index b0e87f3d..74c60987 100644
--- a/Source/SPTextViewAdditions.m
+++ b/Source/SPTextViewAdditions.m
@@ -389,12 +389,17 @@
*/
- (IBAction)insertNULLvalue:(id)sender
{
+#ifndef SP_REFACTOR
id prefs = [NSUserDefaults standardUserDefaults];
- if ([self respondsToSelector:@selector(insertText:)]) {
- if([prefs stringForKey:SPNullValue] && [[prefs stringForKey:SPNullValue] length])
+#endif
+ if([self respondsToSelector:@selector(insertText:)])
+ {
+#ifndef SP_REFACTOR
+ if([prefs objectForKey:SPNullValue] && [(NSString*)[prefs objectForKey:SPNullValue] length])
[self insertText:[prefs objectForKey:SPNullValue]];
else
+#endif
[self insertText:@"NULL"];
}
}
@@ -494,6 +499,7 @@
[self setEditable:editableStatus];
}
+#ifndef SP_REFACTOR
- (IBAction)executeBundleItemForInputField:(id)sender
{
@@ -871,5 +877,6 @@
else if([anEvent deltaZ]<-5.0)
[self makeTextSizeSmaller];
}
+#endif
@end