forked from textmate/commit-window
/
CommitWindowController.m
642 lines (505 loc) · 17.6 KB
/
CommitWindowController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//
// CommitWindowController.m
//
// Created by Chris Thomas on 2/6/05.
// Copyright 2005-2006 Chris Thomas. All rights reserved.
// MIT license.
//
#import "CommitWindowController.h"
#import "CXMenuButton.h"
#import "CWTextView.h"
#import "CXTextWithButtonStripCell.h"
#import "NSString+StatusString.h"
#import "NSTask+CXAdditions.h"
#define kStatusColumnWidthForSingleChar 13
#define kStatusColumnWidthForPadding 13
@interface CommitWindowController (Private)
- (void) populatePreviousSummaryMenu;
- (void) windowDidResize:(NSNotification *)notification;
- (void) summaryScrollViewDidResize:(NSNotification *)notification;
@end
// Forward string comparisons to NSString
@interface NSAttributedString (CommitWindowExtensions)
- (NSComparisonResult)compare:(id)anArgument;
@end
@implementation NSAttributedString (CommitWindowExtensions)
- (NSComparisonResult)compare:(id)aString
{
return [[self string] compare:[aString string]];
}
@end
@implementation CommitWindowController
// Not necessary while CommitWindow is a separate process, but it might be more integrated in the future.
- (void) dealloc
{
// TODO: make sure the nib objects are being released properly
[fDiffCommand release];
[fActionCommands release];
[fFileStatusStrings release];
[super dealloc];
}
// Add a command to the array of commands available for the given status substring
- (void) addAction:(NSString *)name command:(NSArray *)arguments forStatus:(NSString *)statusString
{
NSArray * commandArguments = [NSArray arrayWithObjects:name, arguments, nil];
NSMutableArray * commandsForAction = nil;
if(fActionCommands == nil)
{
fActionCommands = [[NSMutableDictionary alloc] init];
}
else
{
commandsForAction = [fActionCommands objectForKey:statusString];
}
if(commandsForAction == nil)
{
commandsForAction = [NSMutableArray array];
[fActionCommands setObject:commandsForAction forKey:statusString];
}
[commandsForAction addObject:commandArguments];
}
// fFilesController and fFilesStatusStrings should be set up before calling setupUserInterface.
- (void) setupUserInterface
{
CXTextWithButtonStripCell * cell = (CXTextWithButtonStripCell *)[fPathColumn dataCell];
if([cell respondsToSelector:@selector(setLineBreakMode:)])
{
[cell setLineBreakMode:NSLineBreakByTruncatingHead];
}
//
// Set up button strip
//
NSMutableArray * buttonDefinitions = [NSMutableArray array];
// Diff command
if( fDiffCommand != nil )
{
NSMutableDictionary * diffButtonDefinition;
NSMethodSignature * diffMethodSignature = [self methodSignatureForSelector:@selector(doubleClickRowInTable:)];
NSInvocation * diffInvocation = [NSInvocation invocationWithMethodSignature:diffMethodSignature];
// Arguments 0 and 1
[diffInvocation setTarget:self];
[diffInvocation setSelector:@selector(doubleClickRowInTable:)];
// Pretend the table view is the sender
[diffInvocation setArgument:&fTableView atIndex:2];
diffButtonDefinition = [NSMutableDictionary dictionary];
[diffButtonDefinition setObject:@"Diff" forKey:@"title"];
[diffButtonDefinition setObject:diffInvocation forKey:@"invocation"];
[buttonDefinitions addObject:diffButtonDefinition];
}
// Action menu
if(fActionCommands != nil)
{
NSMenu * itemActionMenu;
NSMutableDictionary * actionMenuButtonDefinition;
itemActionMenu = [[NSMenu alloc] initWithTitle:@"Test"];
[itemActionMenu setDelegate:self];
actionMenuButtonDefinition = [NSMutableDictionary dictionaryWithObject:itemActionMenu forKey:@"menu"];
[actionMenuButtonDefinition setObject:@"Modify" forKey:@"title"];
[buttonDefinitions addObject:actionMenuButtonDefinition];
[itemActionMenu release];
}
if( [buttonDefinitions count] > 0 )
{
[cell setButtonDefinitions:buttonDefinitions];
}
//
// Set up summary text view resizing
//
[self windowDidResize:nil];
fPreviousSummaryFrame = [fSummaryScrollView frame];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(summaryScrollViewDidResize:)
name:NSViewFrameDidChangeNotification
object:fSummaryScrollView];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(windowDidResize:)
name:NSWindowDidResizeNotification
object:fWindow];
//
// Add status to each item and choose default commit state
//
if( fFileStatusStrings != nil )
{
NSArray * files = [fFilesController arrangedObjects];
int count = MIN([files count], [fFileStatusStrings count]);
int i;
UInt32 maxCharsToDisplay = 0;
for( i = 0; i < count; i += 1 )
{
NSMutableDictionary * dictionary = [files objectAtIndex:i];
NSString * status = [fFileStatusStrings objectAtIndex:i];
BOOL itemSelectedForCommit;
UInt32 statusLength;
// Set high-water mark
statusLength = [status length];
if( statusLength > maxCharsToDisplay )
{
maxCharsToDisplay = statusLength;
}
[dictionary setObject:status forKey:@"status"];
[dictionary setObject:[status attributedStatusString] forKey:@"attributedStatus"];
// Deselect external commits by default
// and files not added.
// We intentionally do not deselect file conflicts by default
// -- those are most likely to be a problem.
if([status hasPrefix:@"X"]
|| [status hasPrefix:@"?"])
{
itemSelectedForCommit = NO;
}
else
{
itemSelectedForCommit = YES;
}
[dictionary setObject:[NSNumber numberWithBool:itemSelectedForCommit] forKey:@"commit"];
}
// Set status column size
[fStatusColumn setWidth:12 + maxCharsToDisplay * kStatusColumnWidthForSingleChar + (maxCharsToDisplay-1) * kStatusColumnWidthForPadding];
}
//
// Populate previous summary menu
//
[self populatePreviousSummaryMenu];
[fTableView setTarget:self];
[fTableView setDoubleAction:@selector(doubleClickRowInTable:)];
//
// Map the enter key to the OK button
//
[fOKButton setKeyEquivalent:@"\x03"];
[fOKButton setKeyEquivalentModifierMask:0];
//
// Bring the window to absolute front.
// -[NSWindow orderFrontRegardless] doesn't work (maybe because we're an LSUIElement).
//
// Process Manager works, though!
{
ProcessSerialNumber process;
GetCurrentProcess(&process);
SetFrontProcess(&process);
}
[self setWindow:fWindow];
[fWindow setLevel:NSModalPanelWindowLevel];
[fWindow center];
//
// Grow the window to fit as much of the file list onscreen as possible
//
{
NSScreen * screen = [fWindow screen];
NSRect usableRect = [screen visibleFrame];
NSRect windowRect = [fWindow frame];
NSTableView * tableView = [fPathColumn tableView];
float rowHeight = [tableView rowHeight] + [tableView intercellSpacing].height;
int rowCount = [[fFilesController arrangedObjects] count];
float idealVisibleHeight;
float currentVisibleHeight;
float deltaVisibleHeight;
currentVisibleHeight = [[tableView superview] frame].size.height;
idealVisibleHeight = (rowHeight * rowCount) + [[tableView headerView] frame].size.height;
// NSLog(@"current: %g ideal:%g", currentVisibleHeight, idealVisibleHeight );
// Don't bother shrinking the window
if(currentVisibleHeight < idealVisibleHeight)
{
deltaVisibleHeight = (idealVisibleHeight - currentVisibleHeight);
// NSLog( @"old windowRect: %@", NSStringFromRect(windowRect) );
// reasonable margin
usableRect = NSInsetRect( usableRect, 20, 20 );
windowRect = NSIntersectionRect(usableRect, NSInsetRect(windowRect, 0, ceilf(0.5f * -deltaVisibleHeight)));
// NSLog( @"new windowRect: %@", NSStringFromRect(windowRect) );
[fWindow setFrame:windowRect display:NO];
}
}
// center again after resize
[fWindow center];
[fWindow makeKeyAndOrderFront:self];
}
- (void) resetStatusColumnSize
{
//
// Add status to each item and choose default commit state
//
NSArray * files = [fFilesController arrangedObjects];
int count = [files count];
int i;
UInt32 maxCharsToDisplay = 0;
for( i = 0; i < count; i += 1 )
{
NSMutableDictionary * dictionary = [files objectAtIndex:i];
NSString * status = [dictionary objectForKey:@"status"];
UInt32 statusLength;
// Set high-water mark
statusLength = [status length];
if( statusLength > maxCharsToDisplay )
{
maxCharsToDisplay = statusLength;
}
}
// Set status column size
[fStatusColumn setWidth:12 + maxCharsToDisplay * kStatusColumnWidthForSingleChar + (maxCharsToDisplay-1) * kStatusColumnWidthForPadding];
}
#if 0
#pragma mark -
#pragma mark Summary save/restore
#endif
#define kMaxSavedSummariesCount 5
#define kDisplayCharsOfSummaryInMenuItemCount 30
#define kPreviousSummariesKey "prev-summaries"
#define kPreviousSummariesItemTitle "Previous Summaries"
- (void) populatePreviousSummaryMenu
{
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray * summaries = [defaults arrayForKey:@kPreviousSummariesKey];
if( summaries == nil )
{
// No previous summaries, no menu
[fPreviousSummaryPopUp setEnabled:NO];
}
else
{
NSMenu * menu = [[NSMenu alloc] initWithTitle:@kPreviousSummariesItemTitle];
NSMenuItem * item;
int summaryCount = [summaries count];
int index;
// PopUp title
[menu addItemWithTitle:@kPreviousSummariesItemTitle action:@selector(restoreSummary:) keyEquivalent:@""];
// Add items in reverse-chronological order
for(index = (summaryCount - 1); index >= 0; index -= 1)
{
NSString * summary = [summaries objectAtIndex:index];
NSString * itemName;
itemName = summary;
// Limit length of menu item names
if( [itemName length] > kDisplayCharsOfSummaryInMenuItemCount )
{
itemName = [itemName substringToIndex:kDisplayCharsOfSummaryInMenuItemCount];
// append ellipsis
itemName = [itemName stringByAppendingFormat: @"%C", 0x2026];
}
item = [menu addItemWithTitle:itemName action:@selector(restoreSummary:) keyEquivalent:@""];
[item setTarget:self];
[item setRepresentedObject:summary];
}
[fPreviousSummaryPopUp setMenu:menu];
}
}
// To make redo work, we need to add a new undo each time
- (void) restoreTextForUndo:(NSString *)newSummary
{
NSUndoManager * undoManager = [[fCommitMessage window] undoManager];
NSString * oldSummary = [fCommitMessage string];
[undoManager registerUndoWithTarget:self
selector:@selector(restoreTextForUndo:)
object:[[oldSummary copy] autorelease]];
[fCommitMessage setString:newSummary];
}
- (void) restoreSummary:(id)sender
{
NSString * newSummary = [sender representedObject];
[self restoreTextForUndo:newSummary];
}
// Save, in a MRU list, the most recent commit summary
- (void) saveSummary
{
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString * latestSummary = [fCommitMessage string];
// avoid empty string
if( ! [latestSummary isEqualToString:@""] )
{
NSArray * oldSummaries = [defaults arrayForKey:@kPreviousSummariesKey];
NSMutableArray * newSummaries;
if( oldSummaries != nil )
{
unsigned int oldIndex;
newSummaries = [oldSummaries mutableCopy];
// Already in the array? Move it to latest position
oldIndex = [newSummaries indexOfObject:latestSummary];
if( oldIndex != NSNotFound )
{
[newSummaries exchangeObjectAtIndex:oldIndex withObjectAtIndex:[newSummaries count] - 1];
}
else
{
// Add object, remove oldest object
[newSummaries addObject:latestSummary];
if( [newSummaries count] > kMaxSavedSummariesCount )
{
[newSummaries removeObjectAtIndex:0];
}
}
}
else
{
// First time
newSummaries = [NSMutableArray arrayWithObject:latestSummary];
}
[defaults setObject:newSummaries forKey:@kPreviousSummariesKey];
// Write the defaults to disk
[defaults synchronize];
}
}
#if 0
#pragma mark -
#pragma mark File action menu
#endif
- (void) chooseAllItems:(BOOL)chosen
{
NSArray * files = [fFilesController arrangedObjects];
int count = [files count];
int i;
for( i = 0; i < count; i += 1 )
{
NSMutableDictionary * dictionary = [files objectAtIndex:i];
[dictionary setObject:[NSNumber numberWithBool:chosen] forKey:@"commit"];
}
}
- (void) choose:(BOOL)chosen itemsWithStatus:(NSString *)status
{
NSArray * files = [fFilesController arrangedObjects];
int count = [files count];
int i;
for( i = 0; i < count; i += 1 )
{
NSMutableDictionary * dictionary = [files objectAtIndex:i];
if( [[dictionary objectForKey:@"status"] hasPrefix:status] )
{
[dictionary setObject:[NSNumber numberWithBool:chosen] forKey:@"commit"];
}
}
}
- (IBAction) chooseAllFiles:(id)sender
{
[self chooseAllItems:YES];
}
- (IBAction) chooseNoFiles:(id)sender
{
[self chooseAllItems:NO];
}
- (IBAction) revertToStandardChosenState:(id)sender
{
[self chooseAllItems:YES];
[self choose:NO itemsWithStatus:@"X"];
}
#if 0
#pragma mark -
#pragma mark Summary view resize
#endif
- (void) summaryScrollViewDidResize:(NSNotification *)notification
{
// Adjust the size of the lower controls
NSRect currentSummaryFrame = [fSummaryScrollView frame];
NSRect currentLowerControlsFrame = [fLowerControlsView frame];
float deltaV = currentSummaryFrame.size.height - fPreviousSummaryFrame.size.height;
[fLowerControlsView setNeedsDisplayInRect:[fLowerControlsView bounds]];
currentLowerControlsFrame.size.height -= deltaV;
[fLowerControlsView setFrame:currentLowerControlsFrame];
fPreviousSummaryFrame = currentSummaryFrame;
}
- (void) windowDidResize:(NSNotification *)notification
{
// Adjust max allowed summary size to 60% of window size
[fCommitMessage setMaxHeight:[fWindow frame].size.height * 0.60];
}
#if 0
#pragma mark -
#pragma mark Command utilities
#endif
- (NSString *) absolutePathForPath:(NSString *)path
{
if([path hasPrefix:@"/"])
return path;
NSString * absolutePath = nil;
NSString * errorText;
int exitStatus;
NSArray * arguments = [NSArray arrayWithObjects:@"/usr/bin/which", path, nil];
exitStatus = [NSTask executeTaskWithArguments:arguments
input:nil
outputString:&absolutePath
errorString:&errorText];
[self checkExitStatus:exitStatus forCommand:arguments errorText:errorText];
// Trim whitespace
absolutePath = [absolutePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return absolutePath;
}
- (void) checkExitStatus:(int)exitStatus forCommand:(NSArray *)arguments errorText:(NSString *)errorText
{
if( exitStatus != 0 )
{
// This error dialog text sucks for an isolated end user, but allows us to diagnose the problem accurately.
NSRunAlertPanel(errorText, @"Exit status (%d) while executing %@", @"OK", nil, nil, exitStatus, arguments);
[NSException raise:@"ProcessFailed" format:@"Subprocess %@ unsuccessful.", arguments];
}
}
#if 0
#pragma mark -
#pragma mark ButtonStrip action menu delegate
#endif
- (void)chooseActionCommand:(id)sender
{
NSMutableArray * arguments = [[sender representedObject] mutableCopy];
NSString * pathToCommand;
NSMutableDictionary * fileDictionary = [[fFilesController arrangedObjects] objectAtIndex:[fTableView selectedRow]];
NSString * filePath = [[fileDictionary objectForKey:@"path"] stringByStandardizingPath];
NSString * errorText;
NSString * outputStatus;
int exitStatus;
// make sure we have an absolute path
pathToCommand = [self absolutePathForPath:[arguments objectAtIndex:0]];
[arguments replaceObjectAtIndex:0 withObject:pathToCommand];
[arguments addObject:filePath];
exitStatus = [NSTask executeTaskWithArguments:arguments
input:nil
outputString:&outputStatus
errorString:&errorText];
[self checkExitStatus:exitStatus forCommand:arguments errorText:errorText];
//
// Set the file status to the new status
//
NSRange rangeOfStatus;
NSString * newStatus;
rangeOfStatus = [outputStatus rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if( rangeOfStatus.location == NSNotFound)
{
NSRunAlertPanel(@"Cannot understand output from command", @"Command %@ returned '%@'", @"OK", nil, nil, arguments, outputStatus);
[NSException raise:@"CannotUnderstandReturnValue" format:@"Don't understand %@", outputStatus];
}
newStatus = [outputStatus substringToIndex:rangeOfStatus.location];
[fileDictionary setObject:newStatus forKey:@"status"];
[fileDictionary setObject:[newStatus attributedStatusString] forKey:@"attributedStatus"];
[self resetStatusColumnSize];
}
- (void)menuNeedsUpdate:(NSMenu*)menu
{
//
// Remove old items
//
UInt32 itemCount = [menu numberOfItems];
for( UInt32 i = 0; i < itemCount; i += 1 )
{
[menu removeItemAtIndex:0];
}
//
// Find action items usable for the selected row
//
NSArray * keys = [fActionCommands allKeys];
NSString * fileStatus = [[[fFilesController arrangedObjects] objectAtIndex:[fTableView selectedRow]] objectForKey:@"status"];
unsigned int possibleStatusCount = [keys count];
for(unsigned int index = 0; index < possibleStatusCount; index += 1)
{
NSString * possibleStatus = [keys objectAtIndex:index];
if( [fileStatus rangeOfString:possibleStatus].location != NSNotFound )
{
// Add all the commands we find for this status
NSArray * commands = [fActionCommands objectForKey:possibleStatus];
unsigned int commandCount = [commands count];
for(unsigned int arrayOfCommandsIndex = 0; arrayOfCommandsIndex < commandCount; arrayOfCommandsIndex += 1)
{
NSArray * commandArguments = [commands objectAtIndex:arrayOfCommandsIndex];
NSMenuItem * item = [menu addItemWithTitle:[commandArguments objectAtIndex:0]
action:@selector(chooseActionCommand:)
keyEquivalent:@""];
[item setRepresentedObject:[commandArguments objectAtIndex:1]];
[item setTarget:self];
}
}
}
}
@end