aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorrowanbeentje <rowan@beent.je>2010-08-12 01:15:44 +0000
committerrowanbeentje <rowan@beent.je>2010-08-12 01:15:44 +0000
commite5aa4302f8655a08d7fa7542893db009a6920689 (patch)
tree72a12fcf45eaa76e72a2350576a65a0ace6af08e
parent8b1962153814426bfb7e4ab38056ffa955d7c3f0 (diff)
downloadsequelpro-e5aa4302f8655a08d7fa7542893db009a6920689.tar.gz
sequelpro-e5aa4302f8655a08d7fa7542893db009a6920689.tar.bz2
sequelpro-e5aa4302f8655a08d7fa7542893db009a6920689.zip
Implement column autosizing for the Content View:
- Add automatic column sizing (for columns without saved widths) as part of the value loading process - Rework table updates to be timer based, for time-based and more regular updates. This improves speed and allows tables to update more consistently. This results in overall smoother table loads, faster table loads, and autosizing columns. This partially implements Issues #271 and #272. Column autosizing will likely be tweaked, and this will all also be extended to Custom Query views in a future patch.
-rw-r--r--Source/CMCopyTable.h36
-rw-r--r--Source/CMCopyTable.m95
-rw-r--r--Source/SPTableContent.h7
-rw-r--r--Source/SPTableContent.m183
4 files changed, 294 insertions, 27 deletions
diff --git a/Source/CMCopyTable.h b/Source/CMCopyTable.h
index 6baa2527..948607bc 100644
--- a/Source/CMCopyTable.h
+++ b/Source/CMCopyTable.h
@@ -25,6 +25,8 @@
#import <AppKit/AppKit.h>
#import "SPTableView.h"
+#define SP_MAX_CELL_WIDTH 200
+
@class SPDataStorage;
/*!
@@ -112,6 +114,40 @@
*/
- (void)setTableData:(SPDataStorage *)theTableStorage;
+/*!
+ @method autodetectColumnWidthsForFont:
+ @abstract Autodetect and return column widths based on contents
+ @discussion Support autocalculating column widths for the represented data.
+ This uses the underlying table storage, calculates string widths,
+ and eventually returns an array of table column widths.
+ Suitable for calling on background threads, but ensure that the
+ data storage range in use (currently rows 1-200) won't be altered
+ while this accesses it.
+ @param The font to use when calculating widths
+ @result A dictionary - mapped by column identifier - of the column widths to use
+*/
+- (NSDictionary *) autodetectColumnWidthsForFont:(NSFont *)theFont;
+
+/*!
+ @method autodetectWidthForColumnDefinition:usingFont:maxRows:
+ @abstract Autodetect and return column width based on contents
+ @discussion Support autocalculating column width for the represented data.
+ This uses the underlying table storage, and the supplied column definition,
+ iterating through the data and returning a reasonable column width to
+ display that data.
+ Suitable for calling on background threads, but ensure that the data
+ storage range in use won't be altered while being accessed.
+ @param A column definition for a represented column; the column to use is derived
+ @param The font to use when calculating widths
+ @param The maximum number of rows to process when looking at string lengths
+ @result A reasonable column width to use when displaying data
+*/
+/**
+ * Autodetect the column width for a specified column - derived from the supplied
+ * column definition, using the stored data and the specified font.
+ */
+- (NSUInteger)autodetectWidthForColumnDefinition:(NSDictionary *)columnDefinition usingFont:(NSFont *)theFont maxRows:(NSUInteger)rowsToCheck;
+
@end
extern NSInteger MENU_EDIT_COPY;
diff --git a/Source/CMCopyTable.m b/Source/CMCopyTable.m
index 8ce03586..5eab896d 100644
--- a/Source/CMCopyTable.m
+++ b/Source/CMCopyTable.m
@@ -446,6 +446,101 @@ NSInteger MENU_EDIT_COPY_AS_SQL = 2003;
tableStorage = theTableStorage;
}
+/**
+ * Autodetect column widths for a specified font.
+ */
+- (NSDictionary *) autodetectColumnWidthsForFont:(NSFont *)theFont;
+{
+ NSMutableDictionary *columnWidths = [NSMutableDictionary dictionaryWithCapacity:[columnDefinitions count]];
+ NSUInteger columnWidth;
+
+ for (NSDictionary *columnDefinition in columnDefinitions) {
+ if ([[NSThread currentThread] isCancelled]) return nil;
+
+ columnWidth = [self autodetectWidthForColumnDefinition:columnDefinition usingFont:theFont maxRows:100];
+ [columnWidths setObject:[NSNumber numberWithUnsignedInteger:columnWidth] forKey:[columnDefinition objectForKey:@"datacolumnindex"]];
+ }
+
+ return columnWidths;
+}
+
+/**
+ * Autodetect the column width for a specified column - derived from the supplied
+ * column definition, using the stored data and the specified font.
+ */
+- (NSUInteger)autodetectWidthForColumnDefinition:(NSDictionary *)columnDefinition usingFont:(NSFont *)theFont maxRows:(NSUInteger)rowsToCheck
+{
+ CGFloat columnBaseWidth;
+ id contentString;
+ NSUInteger cellWidth, maxCellWidth, i;
+ NSRange linebreakRange;
+ double rowStep;
+ NSUInteger columnIndex = [[columnDefinition objectForKey:@"datacolumnindex"] unsignedIntegerValue];
+ NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:theFont forKey:NSFontAttributeName];
+
+ // Check the number of rows available to check, sampling every n rows
+ if ([tableStorage count] < rowsToCheck) {
+ rowsToCheck = [tableStorage count];
+ rowStep = 1;
+ } else {
+ rowStep = floor([tableStorage count] / rowsToCheck);
+ }
+
+ // Set a default padding for this column
+ columnBaseWidth = 24;
+
+ // Iterate through the data store rows, checking widths
+ maxCellWidth = 0;
+ for (i = 0; i < rowsToCheck; i += rowStep) {
+
+ // Retrieve the cell's content
+ contentString = [tableStorage cellDataAtRow:i column:columnIndex];
+
+ // Replace NULLs with their placeholder string
+ if ([contentString isNSNull]) {
+ contentString = [prefs objectForKey:SPNullValue];
+
+ } else {
+
+ // Otherwise, ensure the cell is represented as a short string
+ if ([contentString isKindOfClass:[NSData class]]) {
+ contentString = [contentString shortStringRepresentationUsingEncoding:[mySQLConnection encoding]];
+ } else if ([contentString length] > 500) {
+ contentString = [contentString substringToIndex:500];
+ }
+
+ // If any linebreaks are present, use only the visible part of the string
+ linebreakRange = [contentString rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
+ if (linebreakRange.location != NSNotFound) {
+ contentString = [contentString substringToIndex:linebreakRange.location];
+ }
+ }
+
+ // Calculate the width, using it if it's higher than the current stored width
+ cellWidth = [contentString sizeWithAttributes:stringAttributes].width;
+ if (cellWidth > maxCellWidth) maxCellWidth = cellWidth;
+ if (maxCellWidth > SP_MAX_CELL_WIDTH) {
+ maxCellWidth = SP_MAX_CELL_WIDTH;
+ break;
+ }
+ }
+
+ // If the column has a foreign key link, expand the width; and also for enums
+ if ([columnDefinition objectForKey:@"foreignkeyreference"]) {
+ maxCellWidth += 18;
+ } else if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"enum"]) {
+ maxCellWidth += 8;
+ }
+
+ // Add the padding
+ maxCellWidth += columnBaseWidth;
+
+ // If the header width is wider than this expanded width, use it instead
+ cellWidth = [[columnDefinition objectForKey:@"name"] sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont labelFontOfSize:[NSFont smallSystemFontSize]] forKey:NSFontAttributeName]].width;
+ if (cellWidth + 10 > maxCellWidth) maxCellWidth = cellWidth + 10;
+
+ return maxCellWidth;
+}
- (void)keyDown:(NSEvent *)theEvent
{
diff --git a/Source/SPTableContent.h b/Source/SPTableContent.h
index 7b87bc32..1899d6a6 100644
--- a/Source/SPTableContent.h
+++ b/Source/SPTableContent.h
@@ -99,6 +99,9 @@
NSString *filterFieldToRestore, *filterComparisonToRestore, *filterValueToRestore, *firstBetweenValueToRestore, *secondBetweenValueToRestore;
NSInteger paginationViewHeight;
+
+ NSTimer *tableLoadTimer;
+ NSUInteger tableLoadInterfaceUpdateInterval, tableLoadTimerTicksSinceLastUpdate, tableLoadLastRowCount;
}
// Table loading methods and information
@@ -107,6 +110,9 @@
- (void) loadTableValues;
- (NSString *) tableFilterString;
- (void) updateCountText;
+- (void) initTableLoadTimer;
+- (void) clearTableLoadTimer;
+- (void) tableLoadUpdate:(NSTimer *)theTimer;
// Table interface actions
- (IBAction) reloadTable:(id)sender;
@@ -148,6 +154,7 @@
- (NSString *)fieldListForQuery;
- (void)updateNumberOfRows;
- (NSInteger)fetchNumberOfRows;
+- (void)autosizeColumns;
- (BOOL)saveRowOnDeselect;
- (void)sortTableTaskWithColumn:(NSTableColumn *)tableColumn;
diff --git a/Source/SPTableContent.m b/Source/SPTableContent.m
index bf03c66e..26eeb568 100644
--- a/Source/SPTableContent.m
+++ b/Source/SPTableContent.m
@@ -99,6 +99,8 @@
prefs = [NSUserDefaults standardUserDefaults];
usedQuery = [[NSString alloc] initWithString:@""];
+
+ tableLoadTimer = nil;
// Init default filters for Content Browser
contentFilters = nil;
@@ -208,7 +210,10 @@
[tableDataInstance getConstraints], @"constraints",
nil];
[self performSelectorOnMainThread:@selector(setTableDetails:) withObject:tableDetails waitUntilDone:YES];
-
+
+ // Init copyTable with necessary information for copying selected rows as SQL INSERT
+ [tableContentView setTableInstance:self withTableData:tableValues withColumns:dataColumns withTableName:selectedTable withConnection:mySQLConnection];
+
// Trigger a data refresh
[self loadTableValues];
@@ -231,8 +236,6 @@
// Update display if necessary
[[tableContentView onMainThread] setNeedsDisplay:YES];
- // Init copyTable with necessary information for copying selected rows as SQL INSERT
- [tableContentView setTableInstance:self withTableData:tableValues withColumns:dataColumns withTableName:selectedTable withConnection:mySQLConnection];
// Post the notification that the query is finished
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
@@ -689,14 +692,13 @@
NSUInteger dataColumnsCount = [dataColumns count];
BOOL *columnBlobStatuses = malloc(dataColumnsCount * sizeof(BOOL));
+ // Set up the table updates timer
+ [[self onMainThread] initTableLoadTimer];
+
// Set the column count on the data store
[tableValues setColumnCount:dataColumnsCount];
CGFloat relativeTargetRowCount = 100.0/targetRowCount;
- NSUInteger nextTableDisplayBoundary = 50;
- BOOL tableViewRedrawn = NO;
-
- NSUInteger rowsProcessed = 0;
NSAutoreleasePool *dataLoadingPool;
NSProgressIndicator *dataLoadingIndicator = [tableDocumentInstance valueForKey:@"queryProgressBar"];
@@ -711,11 +713,12 @@
dataLoadingPool = [[NSAutoreleasePool alloc] init];
// Loop through the result rows as they become available
+ tableRowsCount = 0;
while (tempRow = [theResult fetchNextRowAsArray]) {
pthread_mutex_lock(&tableValuesLock);
- if (rowsProcessed < previousTableRowsCount) {
- SPDataStorageReplaceRow(tableValues, rowsProcessed, tempRow);
+ if (tableRowsCount < previousTableRowsCount) {
+ SPDataStorageReplaceRow(tableValues, tableRowsCount, tempRow);
} else {
SPDataStorageAddRow(tableValues, tempRow);
}
@@ -724,42 +727,36 @@
if ( prefsLoadBlobsAsNeeded ) {
for ( i = 0 ; i < dataColumnsCount ; i++ ) {
if (columnBlobStatuses[i]) {
- SPDataStorageReplaceObjectAtRowAndColumn(tableValues, rowsProcessed, i, [SPNotLoaded notLoaded]);
+ SPDataStorageReplaceObjectAtRowAndColumn(tableValues, tableRowsCount, i, [SPNotLoaded notLoaded]);
}
}
}
- rowsProcessed++;
+ tableRowsCount++;
pthread_mutex_unlock(&tableValuesLock);
// Update the task interface as necessary
if (!isFiltered) {
- if (rowsProcessed < targetRowCount) {
- [tableDocumentInstance setTaskPercentage:(rowsProcessed*relativeTargetRowCount)];
- } else if (rowsProcessed == targetRowCount) {
+ if (tableRowsCount < targetRowCount) {
+ [tableDocumentInstance setTaskPercentage:(tableRowsCount*relativeTargetRowCount)];
+ } else if (tableRowsCount == targetRowCount) {
[tableDocumentInstance setTaskPercentage:100.0];
[[tableDocumentInstance onMainThread] setTaskProgressToIndeterminateAfterDelay:YES];
}
}
- // Update the table view with new results every now and then
- if (rowsProcessed > nextTableDisplayBoundary) {
- if (rowsProcessed > tableRowsCount) tableRowsCount = rowsProcessed;
- [[tableContentView onMainThread] noteNumberOfRowsChanged];
- if (!tableViewRedrawn) {
- [[tableContentView onMainThread] setNeedsDisplay:YES];
- tableViewRedrawn = YES;
- }
- nextTableDisplayBoundary *= 2;
- }
-
// Drain and reset the autorelease pool every ~1024 rows
- if (!(rowsProcessed % 1024)) {
+ if (!(tableRowsCount % 1024)) {
[dataLoadingPool drain];
dataLoadingPool = [[NSAutoreleasePool alloc] init];
}
}
- tableRowsCount = rowsProcessed;
+
+ // Clean up the interface update timer
+ [[self onMainThread] clearTableLoadTimer];
+
+ // If the final column autoresize wasn't performed, perform it
+ if (tableLoadLastRowCount < 200) [[self onMainThread] autosizeColumns];
// If the reloaded table is shorter than the previous table, remove the extra values from the storage
if (tableRowsCount < [tableValues count]) {
@@ -1015,6 +1012,77 @@
[[countText onMainThread] setStringValue:countString];
}
+/**
+ * Set up the table loading interface update timer.
+ * This should be called on the main thread.
+ */
+- (void) initTableLoadTimer
+{
+ if (tableLoadTimer) [self clearTableLoadTimer];
+ tableLoadInterfaceUpdateInterval = 1;
+ tableLoadLastRowCount = 0;
+ tableLoadTimerTicksSinceLastUpdate = 0;
+
+ tableLoadTimer = [[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(tableLoadUpdate:) userInfo:nil repeats:YES] retain];
+}
+
+/**
+ * Invalidate and release the table loading interface update timer.
+ * This should be called on the main thread.
+ */
+- (void) clearTableLoadTimer
+{
+ if (tableLoadTimer) {
+ [tableLoadTimer invalidate];
+ [tableLoadTimer release];
+ tableLoadTimer = nil;
+ }
+}
+
+/**
+ * Perform table interface updates when loading tables, based on timer
+ * ticks. As data becomes available, the table should be redrawn to
+ * show new rows - quickly at the start of the table, and then slightly
+ * slower after some time to avoid needless updates.
+ */
+- (void) tableLoadUpdate:(NSTimer *)theTimer
+{
+ if (tableLoadTimerTicksSinceLastUpdate < tableLoadInterfaceUpdateInterval) {
+ tableLoadTimerTicksSinceLastUpdate++;
+ return;
+ }
+
+ // Check whether a table update is required, based on whether new rows are
+ // available to display.
+ if (tableRowsCount == tableLoadLastRowCount) {
+ return;
+ }
+
+ // Update the table display
+ [tableContentView noteNumberOfRowsChanged];
+ if (!tableLoadLastRowCount) [tableContentView setNeedsDisplay:YES];
+
+ // Update column widths in two cases: on very first rows displayed, and once
+ // more than 200 rows are present.
+ if (tableLoadInterfaceUpdateInterval || (tableRowsCount >= 200 && tableLoadLastRowCount < 200)) {
+ [self autosizeColumns];
+ }
+
+ tableLoadLastRowCount = tableRowsCount;
+
+ // Determine whether to decrease the update frequency
+ switch (tableLoadInterfaceUpdateInterval) {
+ case 1:
+ tableLoadInterfaceUpdateInterval = 10;
+ break;
+ case 10:
+ tableLoadInterfaceUpdateInterval = 25;
+ break;
+ }
+ tableLoadTimerTicksSinceLastUpdate = 0;
+}
+
+
#pragma mark -
#pragma mark Table interface actions
@@ -2749,6 +2817,27 @@
return [[[[mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@", [selectedTable backtickQuotedString]]] fetchRowAsArray] objectAtIndex:0] integerValue];
}
+/**
+ * Autosize all columns based on their content.
+ * Should be called on the main thread.
+ */
+- (void)autosizeColumns
+{
+ NSDictionary *columnWidths = [tableContentView autodetectColumnWidthsForFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]]];
+ [tableContentView setDelegate:nil];
+ for (NSDictionary *columnDefinition in dataColumns) {
+
+ // Skip columns with saved widths
+ if ([[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]]] objectForKey:[tablesListInstance tableName]] objectForKey:[columnDefinition objectForKey:@"name"]]) continue;
+
+ // Otherwise set the column width
+ NSTableColumn *aTableColumn = [tableContentView tableColumnWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
+ NSUInteger targetWidth = [[columnWidths objectForKey:[columnDefinition objectForKey:@"datacolumnindex"]] unsignedIntegerValue];
+ [aTableColumn setWidth:targetWidth];
+ }
+ [tableContentView setDelegate:self];
+}
+
#pragma mark -
#pragma mark TableView delegate methods
@@ -3157,6 +3246,44 @@
return tableRowsSelectable;
}
+/**
+ * Resize a column when it's double-clicked. (10.6+)
+ */
+- (CGFloat)tableView:(NSTableView *)tableView sizeToFitWidthOfColumn:(NSInteger)columnIndex
+{
+ NSTableColumn *theColumn = [[tableView tableColumns] objectAtIndex:columnIndex];
+ NSDictionary *columnDefinition = [dataColumns objectAtIndex:[[theColumn identifier] integerValue]];
+
+ // Get the column width
+ NSUInteger targetWidth = [tableContentView autodetectWidthForColumnDefinition:columnDefinition usingFont:[NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]] maxRows:500];
+
+ // Clear any saved widths for the column
+ NSString *dbKey = [NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]];
+ NSString *tableKey = [tablesListInstance tableName];
+ NSMutableDictionary *savedWidths = [NSMutableDictionary dictionaryWithDictionary:[prefs objectForKey:SPTableColumnWidths]];
+ NSMutableDictionary *dbDict = [NSMutableDictionary dictionaryWithDictionary:[savedWidths objectForKey:dbKey]];
+ NSMutableDictionary *tableDict = [NSMutableDictionary dictionaryWithDictionary:[dbDict objectForKey:tableKey]];
+ if ([tableDict objectForKey:[columnDefinition objectForKey:@"name"]]) {
+ [tableDict removeObjectForKey:[columnDefinition objectForKey:@"name"]];
+ if ([tableDict count]) {
+ [dbDict setObject:[NSDictionary dictionaryWithDictionary:tableDict] forKey:tableKey];
+ } else {
+ [dbDict removeObjectForKey:tableKey];
+ }
+ if ([dbDict count]) {
+ [savedWidths setObject:[NSDictionary dictionaryWithDictionary:dbDict] forKey:dbKey];
+ } else {
+ [savedWidths removeObjectForKey:dbKey];
+ }
+ [prefs setObject:[NSDictionary dictionaryWithDictionary:savedWidths] forKey:SPTableColumnWidths];
+ }
+
+ // Return the width, while the delegate is empty to prevent column resize notifications
+ [tableContentView setDelegate:nil];
+ [tableContentView performSelector:@selector(setDelegate:) withObject:self afterDelay:0.1];
+ return targetWidth;
+}
+
#pragma mark -
#pragma mark SplitView delegate methods
@@ -3406,7 +3533,9 @@
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
+ [NSObject cancelPreviousPerformRequestsWithTarget:tableContentView];
+ [self clearTableLoadTimer];
[tableValues release];
pthread_mutex_destroy(&tableValuesLock);
[dataColumns release];
id='n1025' href='#n1025'>1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444