Source

Murky / Source / RepoController_Actions.m

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
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
//
//  RepoController_Actions.m
//  Murky
//
//  Copyright 2008-2009 Jens Alfke. All rights reserved.
//

#import "RepoController.h"
#import "FileViewer.h"
#import "HgRepository.h"
#import "HgDir.h"
#import "HgUncommittedRevision.h"
#import "HgOperation.h"
#import "HgTempDir.h"
#import "HgConfigFile.h"
#import "URLFormatter.h"
#import "Terminal.h"
#import "CompareTool.h"

#define kPrefRevertWithoutBackup @"RevertWithoutBackup"


@implementation RepoController (Actions)


#pragma mark -
#pragma mark UTILITIES:


- (BOOL) anySelectedFilesHaveStatus: (HgStatus)status
{
    for( HgFile *file in self.selectedFiles )
        if( file.status == status )
            return YES;
    return NO;
}


- (BOOL) anySelectedFilesUncommitted
{
    for( HgFile *file in self.selectedFiles )
        if( file.isUncommitted )
            return YES;
    return NO;
}


- (BOOL) getSelectedRevisionsOld: (HgRevision**)outOld andNew: (HgRevision**)outNew
{
    HgFile *file = self.selectedFile;
    if( ! file )
        return NO;
    *outNew = self.selectedRevision;
    if( ! *outNew )
        return NO;
    *outOld = (*outNew).parent;
    return YES;
    /*
    NSArray *revisions = file.revisions;
    NSUInteger nRevisions = revisions.count;
    if( nRevisions < 2 )
        return NO;
    *outNew = [revisions lastObject];
    
    NSArray *sel;
    if( file == self.actuallySelectedFile )
        sel = [_revisions selectedObjects];
    else
        sel = nil;
    
    switch( sel.count ) {
        case 0:
            // No selection: diff current modifications against base:
            *outOld = [revisions objectAtIndex: nRevisions-2];
            return (*outNew).isUncommitted;
        case 1: {
            // One selection: diff it against previous
            *outNew = [sel objectAtIndex: 0];
            NSUInteger selIndex = [revisions indexOfObject: *outNew];
            if( selIndex==0 || selIndex==NSNotFound )
                return NO;
            *outOld = [revisions objectAtIndex: selIndex-1];
            return YES;
        }
        case 2:
            // Two selections: diff them:
            *outOld = [sel objectAtIndex: 0];
            *outNew = [sel objectAtIndex: 1];
            if( (*outOld).localNumber > (*outNew).localNumber ) {
                HgRevision *temp = *outOld;
                *outOld = *outNew;
                *outNew = temp;
            }
            return YES;
        default:
            return NO;
    }
     */
}


#pragma mark -
#pragma mark ACTIONS:


- (IBAction) toggleShowsOnlyUncleanFiles: (id)sender
{
    _hideShowUnmodifiedToolbarItem.selectedSegment = self.showsOnlyUncleanFiles = !self.showsOnlyUncleanFiles;
}

- (IBAction) viewModeSelectorChanged: (id)sender
{
    self.showsOnlyUncleanFiles = _hideShowUnmodifiedToolbarItem.selectedSegment;
}


- (IBAction) chooseRevisionFromPopUp: (id)sender
{
    HgRevision *rev = ((NSPopUpButton*)sender).selectedItem.representedObject;
    Log(@"Pop-up selected revision %@",rev);
    //[_revisions setSelectedObjects: [NSArray arrayWithObject: rev]];
}


- (IBAction) revealInFinder: (id) sender
{
    NSURL* fileURL = [NSURL fileURLWithPath: self.repository.absolutePath];
    NSWorkspace* ws = [NSWorkspace sharedWorkspace];
    [ws openURL:fileURL];   //use openURL instead of selectFile to support PathFinder. WD-rpw May 1, 2009
}

// escapePath method derived from quotePath function in project ShellHere created by John Daniel on 3/22/09,
// Copyright Etresoft 2009 (www.etresoft.org). All rights reserved.
- (NSString*) escapePath: (NSString*) path
{
    NSScanner *scanner = [NSScanner scannerWithString: path];
    
    // Don't skip whitespace.
    [scanner setCharactersToBeSkipped: [NSCharacterSet illegalCharacterSet]];
    
    // Character set with path-unfriendly characters (punctuation, symbols, white space).
    NSMutableCharacterSet *punctuation = [NSMutableCharacterSet punctuationCharacterSet];
    [punctuation formUnionWithCharacterSet: [NSCharacterSet symbolCharacterSet]];
    [punctuation formUnionWithCharacterSet: [NSCharacterSet whitespaceCharacterSet]];
    
    // Remove characters that should not (/) or need not (-_.,:+) be replaced.
    [punctuation removeCharactersInString: @"/-_.,:+"];
    
    NSMutableString *escapedPath = [NSMutableString string];
    NSString *good, *bad;
    
    while( ! [scanner isAtEnd] ) {
        // Scan all the good characters.
        if( [scanner scanUpToCharactersFromSet: punctuation intoString: &good] )
            [escapedPath appendString: good];
        
        // Scan all the bad characters that come next and escape them.
        if( [scanner scanCharactersFromSet: punctuation intoString: &bad] )
            for( NSUInteger i = 0; i < [bad length]; ++i )
                [escapedPath appendFormat: @"\\%C", [bad characterAtIndex: i]];
    }
    
    return escapedPath;
}

- (IBAction) openInTerminal: (id) sender
{
    NSURL* fileURL = [NSURL fileURLWithPath: self.repository.absolutePath];
    
    // Terminal
    // Code from John Daniel - ShellHere
    TerminalApplication * terminal = [SBApplication applicationWithBundleIdentifier: @"com.apple.Terminal"];
	BOOL terminalWasRunning = [terminal isRunning];
	
    // Get the Terminal windows.
    SBElementArray * terminalWindows = [terminal windows];
    
    TerminalTab * currentTab = nil;
    
    // If there is only a single window with a single tab, Terminal may 
    // have been just launched. If so, I want to use the new window.
	// (This prevents two windows from being created.)
    if(!terminalWasRunning) {
        for(TerminalWindow * terminalWindow in terminalWindows) {
		    SBElementArray * windowTabs = [terminalWindow tabs];
            for(TerminalTab * tab in windowTabs) {
                currentTab = tab;
            }
        }
    }
	
    // Create a "cd" command.
    NSString * command = [NSString stringWithFormat: @"cd %@;clear;", [self escapePath:[fileURL path]]];
    [terminal doScript: command in: currentTab];
    
    // Activate the Terminal. Hopefully, the new window is already open and
    // is will be brought to the front.
    [terminal activate];
}

- (IBAction) refreshStatus: (id)sender
{
    NSError *error =nil;
    if( ! [_repo updateStatus: &error] )
        [self presentError: error];
}


/** Called when a file is double-clicked */
- (IBAction) openSelectedFile: (id)sender
{
    [self openSelectedFileInWindow: sender];
}


- (IBAction) showRevision: (id)sender
{
    HgFile *file = self.selectedFile;
    if( !(file.isFile || file.isDirectory) || file!=self.actuallySelectedFile ) {
        NSBeep();
        return;
    }
    
    NSString *path = nil;
    if( file.isFile ) {
        NSError *error;
        path = [file.revision getPathToFileContents: file
                                   inTempDir: self.tempDir
                                       error: &error];
        if (!path) {
            [self presentError: error];
            return;
        }
    }
    else if( file.isDirectory ) {
        path = file.absolutePath;
    }
    
    if (![[NSWorkspace sharedWorkspace] openFile: path])
        NSBeep();
}

- (IBAction) openSelectedFileInWindow: (id)sender {
    HgFile *file = self.selectedFile;
    if( !(file.isFile || file.isDirectory) || file!=self.actuallySelectedFile ) {
        NSBeep();
        return;
    }
    FileViewer *viewer = [FileViewer fileViewerWithFile: file];
    [viewer showWindow: sender];
}


#pragma mark -
#pragma mark DIFFS:


- (BOOL) showComparisonFromRevision: (HgRevision*)revOld 
                         toRevision: (HgRevision*)revNew
                             ofFile: (HgFile*)file
                              error: (NSError**)outError
{
    if( ! file.isFile ) {
        //FIX: Can't compare directories yet
        return MYMiscError(outError, @"%@", 
                           NSLocalizedString(@"Can't compare directories yet, sorry!", 
                                             @"Error from Compare command"));
    }
    NSString *pathOld = [revOld getPathToFileContents: file inTempDir: self.tempDir error: outError];
    if( ! pathOld ) return NO;
    NSString *pathNew = [revNew getPathToFileContents: file inTempDir: self.tempDir error: outError];
    if( ! pathNew ) return NO;
    
    CompareTool *tool = [CompareTool toolWithID: @"FileMerge"];  //FIX: Make this a pref
    tool.leftPath = pathOld;
    tool.rightPath = pathNew;
    
    if (file.revision.isUncommitted)
        tool.savePath = file.absolutePath;
    
    HgRevision *revBase = [revOld commonAncestorWith: revNew];
    if (revBase && revBase != revOld && revBase != revNew) {
        NSString *pathBase = [revBase getPathToFileContents: file inTempDir: self.tempDir error: outError];
        tool.basePath = pathBase;
    }
    
    return [tool open: outError];
}


- (BOOL) showComparisonOfFiles: (NSArray*)files error: (NSError**)outError
{
    for( HgFile *file in files ) {
        if( file.isFile ) {
            if( file.status==kModified ) {
                NSArray *revisions = file.revisions;
                NSUInteger n = revisions.count;
                if( ! [self showComparisonFromRevision: [revisions objectAtIndex: n-2]
                                            toRevision: [revisions objectAtIndex: n-1]
                                                ofFile: file
                                                 error: outError] ) {
                    return NO;
                }
            }
        } else {
            if( ! [self showComparisonOfFiles: ((HgDir*)file).files error: outError] )
                return NO;
        }
    }
    return YES;
}


- (IBAction) showDiff: (id)sender
{
    HgRevision *revOld,*revNew;
    if( ! [self getSelectedRevisionsOld: &revOld andNew: &revNew] ) {
        NSBeep();
        return;
    }
    
    HgFile *file = self.selectedFile;
    NSString *filename = [NSString stringWithFormat: NSLocalizedString(@"%@ (%@ vs %@).diff",
                                                                       @"Name of temp file generated by Diff command"), 
                          file.name, revNew.localString,revOld.localString];
    NSError *error = nil;
    NSString *diff = [revNew diffFile: file withRevision: revOld error: &error];
    if( ! diff || ! [self.tempDir openDataInEditor: diff
                                       asFileNamed: filename
                                             error: &error] )
        [self presentError: error];
}


- (IBAction) showComparison: (id)sender
{
    BOOL ok;
    NSError *error = nil;
    NSArray *files = self.selectedFiles;
    if( files.count == 1 && [[files objectAtIndex: 0] isFile] ) {
        HgRevision *revOld,*revNew;
        if( ! [self getSelectedRevisionsOld: &revOld andNew: &revNew] ) {
            NSBeep();
            return;
        }
        ok = [self showComparisonFromRevision: revOld 
                                   toRevision: revNew 
                                       ofFile: [files objectAtIndex: 0]
                                        error: &error];      
    } else {
        // Multiple selection: Compare each against base:
        ok = [self showComparisonOfFiles: files error: &error];
    }
    if( !ok )
        [self presentError: error];
}


#pragma mark -
#pragma mark PROGRESS:


- (void) _startProgressForOperation: (HgOperation*)operation
                            message: (NSString*)message
                     didEndSelector: (SEL)didEndSelector
                            context: (void*)context
{
    Assert(!self.currentOperation);
    self.currentOperation = operation;
    if (![operation start]) {
        [self performSelector: didEndSelector withObject: _progressSheet withObject: (id)context];
        return;
    }
    _progressMessageField.stringValue = message;
    _progressStopButton.title = NSLocalizedString(@"Stop", @"Button in progress sheet");
    NSView *superview = _progressStopButton.superview;
    [_progressStopButton removeFromSuperview];
    _progressStopButton.keyEquivalent = @"\033"; // esc
    [superview addSubview: _progressStopButton];
    
    [NSApp beginSheet: _progressSheet
       modalForWindow: self.window
        modalDelegate: self
       didEndSelector: didEndSelector ?:@selector(_closeProgressSheet)
          contextInfo: context];
    
    [operation addObserver: self 
                forKeyPath: @"isRunning"
                   options: 0
                   context: @selector(_currentOperationStopped)];
}


- (void) _currentOperationStopped {
    [_repo updateStatus: nil];
    _progressStopButton.title = NSLocalizedString(@"Close", @"Button in progress sheet");
    _progressStopButton.keyEquivalent = @"\r";
}


- (IBAction) stopProgress: (id)sender
{
    NSInteger button = NSOKButton;
    if( self.currentOperation.isRunning ) {
        self.currentOperation.stop;
        button = NSCancelButton;
    }
    [NSApp endSheet: _progressSheet returnCode: button];
}

- (void) _closeProgressSheet
{
    [_progressSheet orderOut: self];
    [self.currentOperation removeObserver: self forKeyPath: @"isRunning"];
    self.currentOperation = nil;
}


#pragma mark -
#pragma mark COMMIT / PUSH / PULL:


static BOOL isFileStatus( HgFile *file, void *status ) {
    return [file status] == (HgStatus)status;
}

static BOOL isFileMergeStatus( id file, void *status ) {
    return [file mergeStatus] == (HgMergeStatus)status;
}


- (void) _endCommitWarnSheet: (NSPanel*)sheet resultCode: (NSInteger)result context: (NSArray*)files
{
    [sheet orderOut: self];
    if( result == NSOKButton )
        [NSApp beginSheet: _commitSheet
           modalForWindow: self.window
            modalDelegate: self
           didEndSelector: @selector(_commitSheetDidEnd:returnCode:context:)
              contextInfo: files];
}


- (void) commitChangesToFiles: (NSArray*)files
{
    HgUncommittedRevision* uncommittedRevision = _repo.uncommittedRevision;
    
    // Can't commit if any files are left unmerged:
    NSMutableArray* conflicts = [NSMutableArray array];
    [uncommittedRevision.root addFilesMatching: FunctionPredicate1(isFileMergeStatus,(void*)kConflict) 
                                       toArray: conflicts];
    if (conflicts.count > 0) {
        NSBeginCriticalAlertSheet(NSLocalizedString(@"Some files still have merge conflicts", 
                                                    @"Title of conflicts alert from Commit command"),
                                  NSLocalizedString(@"Cancel", @"Button"), nil, nil,
                                  self.window, self,
                                  NULL, NULL, NULL, 
                                  NSLocalizedString(@"%i file(s) still have unresolved merge conflicts."
                                                    " Please edit them to resolve the conflicting lines,"
                                                    " then use the Mark As Resolved command to tell Mercurial"
                                                    " that they've been resolved.\n"
                                                    "After that, you can commit.",
                                                    @"Body of conflicts alert from Commit command"),
                                  conflicts.count);
        return;
    }
    
    // Check whether any files have unknown ('?') status:
    NSArray *filesToCheck = files ?:[NSArray arrayWithObject: uncommittedRevision.root];
    HgRevision *revision = [filesToCheck.lastObject revision];
    if( filesToCheck.count==0 || ! revision.isUncommitted ) {
        NSBeep();
        return;
    }
    NSMutableArray *unknown = [NSMutableArray array];
    for( HgFile *file in filesToCheck ) {
        [file addFilesMatching: FunctionPredicate1(isFileStatus,(void*)kNotTracked) toArray: unknown];
    }
    
    _commitMessageField.string = uncommittedRevision.formattedDescription ?: @"";
    
    if( unknown.count == 0 ) {
        // No warning sheet
        [self _endCommitWarnSheet: nil resultCode: NSOKButton context: files];
    } else {
        // Helpfully select the "?" files:
        self.selectedRevision = revision;
        self.showsOnlyUncleanFiles = YES;
        [_outline deselectAll: self];
        for( HgFile *file in unknown ) {
            NSInteger row = [revision.uncleanFiles indexOfObjectIdenticalTo: file];
            if (row != NSNotFound) {
                NSIndexSet *indexes = [NSIndexSet indexSetWithIndex:row];
                [_outline selectRowIndexes:indexes byExtendingSelection:YES];
            }
        }
        
        NSBeginCriticalAlertSheet(NSLocalizedString(@"Some files aren't in the repository", 
                                                    @"Title of alert from Commit command"),
                                  NSLocalizedString(@"OK", @"Button"), 
                                  NSLocalizedString(@"Cancel", @"Button"), nil,
                                  self.window, self,
                                  @selector(_endCommitWarnSheet:resultCode:context:),NULL,
                                  files, 
                                  NSLocalizedString(@"%i file(s) you're trying to check in have not yet been added to the repository (status is '?'). These won't be checked in. Proceed anyway?", 
                                                    @"Body of alert from Commit command"),
                                  unknown.count);
    }
}


- (IBAction) commitChanges: (id)sender
{
    [self commitChangesToFiles: _tree.selectedObjects];
}

- (IBAction) commitAllChanges: (id)sender
{
    [self commitChangesToFiles: nil];
}


- (IBAction) endCommitSheet: (id)sender
{
    _repo.uncommittedRevision.formattedDescription = _commitMessageField.string;
    BOOL ok = YES;
    NSButton *button = sender;
    NSInteger returnCode = button.tag;
    if( returnCode == NSOKButton ) {
        NSWindow *sheet = [sender window];
        if( sheet==_commitSheet )
            ok = _commitMessageField.string.length > 0;
        else if( sheet==_pushSheet )
            ok = _pushURLField.objectValue != nil;
    }
    if( ok )
        [NSApp endSheet: button.window returnCode: returnCode];
    else
        NSBeep();
}

- (void) _commitSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode == NSOKButton ) {
        NSArray *files = (NSArray*)context;
        NSError *error = nil;
        if( [_repo.uncommittedRevision commitFiles: files message: _commitMessageField.string error: &error] ) {
            _commitMessageField.string = @"";
            [_repo updateStatus: &error];
            [self _updateInfoView];
        } else {
            [self presentError: error];
        }
    }
}


- (IBAction) pushPullRevisions: (id)sender
{
    HgTransferOp op = (int)[sender tag];
    NSString *defaultURL, *desc, *buttonTitle;
    switch( op ) {
        case kHgPush: 
            desc = NSLocalizedString(@"Push revisions to repository at URL/file:", 
                                     @"Prompt in Push sheet");
            buttonTitle = NSLocalizedString(@"Push", @"Default button in Push sheet");
            defaultURL = [_repo.configFile valueForKey: @"default-push" inStanza: @"paths"];
            if( ! defaultURL )
                defaultURL = [_repo.configFile valueForKey: @"default" inStanza: @"paths"];
            break;
        case kHgPull: 
            desc = NSLocalizedString(@"Pull revisions from repository at URL/file:", 
                                     @"Prompt in Pull sheet");
            buttonTitle = NSLocalizedString(@"Pull", @"Default button in Pull sheet");
            defaultURL = [_repo.configFile valueForKey: @"default" inStanza: @"paths"];
            break;
        case kHgClone:
            desc = NSLocalizedString(@"Clone repository to URL/file:", 
                                     @"Prompt in Clone sheet");
            buttonTitle = NSLocalizedString(@"Clone", @"Default button in Clone sheet");
            defaultURL = _repo.absolutePath;
            if( [defaultURL hasSuffix: @"/"] )
                defaultURL = [defaultURL substringToIndex: defaultURL.length-1];
            defaultURL = [defaultURL stringByAppendingString: @"_clone"];
            break;
        default:
            Assert(NO,@"Invalid op %i",op);
            return;
    }
    [_pushURLField setStringValue: (defaultURL ?:@"")];
    [_pushURLField removeAllItems];
    [_pushURLField addItemsWithObjectValues: [_repo.configFile URLsForStanza: @"paths"]];
    
    [_pushDescriptionField setObjectValue: desc];
    [_pushButton setTitle: buttonTitle];
    [_pullUpdateCheckbox setHidden: (op==kHgPush)];
    
    [NSApp beginSheet: _pushSheet
       modalForWindow: self.window
        modalDelegate: self
       didEndSelector: @selector(_pushSheetDidEnd:returnCode:context:)
          contextInfo: (void*)(size_t)op];
}

- (IBAction) beginPushSheetFilePicker: (id)sender
{
    [_pushSheet makeFirstResponder: _pushURLField];
    [URLFormatter beginFilePickerFor: _pushURLField];
}

- (void) _pushSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode != NSOKButton )
        return;

    // EW: objectValue may now return either an NSURL or NSString due to my changes.
	// If an NSString is returned, my assumption is that it is a relative path like @"../MySource".
    id some_value = _pushURLField.objectValue;
    NSURL *url;
	
    // Should only be a NSString holding a relative path or a NSURL
    if( [some_value isKindOfClass: [NSString class]] ) {
        NSString* combined_string = [[self.directory stringByAppendingString:some_value] stringByStandardizingPath];
        url = [NSURL fileURLWithPath:combined_string];
	} else {
        url = (NSURL*)some_value;
	}
    if( ! url )
        return;
        
    HgTransferOp xferOp = (HgTransferOp)(size_t)context;
    HgTransferOptions options = 0;
    if( _pullUpdateCheckbox.state )
        options = kHgUpdateAfterwards;
    
    SEL didEnd = NULL;
    if (xferOp==kHgPull)
        didEnd = @selector(_pullDidEnd:result:url:);
    else if( url.isFileURL ) {
        if( xferOp==kHgPush ) 
            didEnd = @selector(_pushDidEnd:result:url:);
        else if( xferOp==kHgClone ) 
            didEnd = @selector(_cloneDidEnd:result:url:);
    }    
    
    static NSString* const kMessage[] = {@"Pulling from <%@>", @"Pushing to <%@>", @"Cloning to <%@>"};
    // NSLocalizedString(@"Pulling from <%@>", @"Progress message during Pull command")
    // NSLocalizedString(@"Pushing to <%@>", @"Progress message during Push command")
    // NSLocalizedString(@"Cloning to <%@>", @"Progress message during Clone command")}
    NSString *msgFormat = [[NSBundle mainBundle] localizedStringForKey: kMessage[xferOp]
                                                                 value: @""
                                                                 table:nil];

    HgOperation *op = [_repo transferRevisions: xferOp
                                       options: options
                               otherRepository: url];
    [self _startProgressForOperation: op
                             message: [NSString stringWithFormat: msgFormat, url.absoluteString]
                      didEndSelector: didEnd
                             context: url];
}

- (void) _pullDidEnd: (NSPanel*)sheet result: (NSInteger)result url: (NSURL*)url
{
    [self _closeProgressSheet];
    // Warn the user if a merge is required:
    if ([_repo canMergeWithRevision: nil]) {
        NSBeginInformationalAlertSheet(
            NSLocalizedString(@"Merging may be required",
                             @"Title of post-pull merge alert"),
            NSLocalizedString(@"Merge Now", @"Default button of post-pull merge alert"), 
            NSLocalizedString(@"Don't Merge", @"Alternate button of post-pull merge alert"), nil,
            self.window,self,
            @selector(_postPullSheetDidEnd:returnCode:), NULL, NULL,
            NSLocalizedString(@"The repository contains multiple head revisions. You will probably need to merge your tip revision to incorporate the pulled changes.\n\n(If you choose not to merge now, you can do it later by using the Merge command.)", 
                             @"Body of post-pull merge alert"));
    }
}

- (void) _postPullSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode {
    [sheet orderOut: self];
    if (returnCode == NSOKButton) {
        [self merge: self];
    }
}

- (void) _pushDidEnd: (NSPanel*)sheet result: (NSInteger)result url: (NSURL*)url
{
    [self _closeProgressSheet];
    // If pushed to a repo open in another window, update that one:
    RepoController *other = [[self class] existingRepoControllerWithDirectory: url.path];
    NSError *error;
    if( other )
        [other.repository updateStatus: &error];
}

- (void) _cloneDidEnd: (NSPanel*)sheet result: (NSInteger)result url: (NSURL*)url
{
    [self _closeProgressSheet];
    // If cloned to a local filesystem, open the new cloned repo:
    NSError *error;
    RepoController *other = [[self class] repoControllerWithDirectory: url.path
                                                                error: &error];
    [other showWindow: self];
}

// if the user pressed the [ENTER] key, do like Version.app does and commit (i.e. simulate pressing "Commit" button)
- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector
{
    if (aTextView != _commitMessageField)
        return NO;
    
    NSEvent *event = [[aTextView window] currentEvent];
    if ([event keyCode] == 76) // enter key pressed
    {
        [[_commitButton target] performSelector:[_commitButton action] withObject:_commitButton];
        return YES;
    }
    return NO;
}

#pragma mark -
#pragma mark ADD / REMOVE / DISCARD:


- (NSArray*) _uncommittedSelectedFiles
{
    if( self.selectedRevision.isUncommitted ) {
        NSArray *files = self.selectedFiles;
        if( files.count > 0 )
            return files;
    }
    NSBeep();
    return nil;
}

- (void) addRemove: (id)sender
{
    NSError *error = nil;
    if (! [_repo.uncommittedRevision addRemoveWithError: &error]) {
        [self presentError: error];
    }
}

- (void) addToRepository: (id)sender
{
    NSArray *files = self._uncommittedSelectedFiles;
    NSError *error = nil;
    if( files && ! [_repo.uncommittedRevision addFiles: files error: &error] ) {
        [self presentError: error];
    }
}


- (void) removeFromRepository: (id)sender
{
    NSArray *files = self._uncommittedSelectedFiles;
    if( files )
        NSBeginCriticalAlertSheet(NSLocalizedString(@"Remove files from repository?",
                                                    @"Title of Remove alert"),
                                  NSLocalizedString(@"Remove", @"Default button of Remove alert"), 
                                  NSLocalizedString(@"Cancel", @"Button"), nil,
                                  self.window,self,
                                  @selector(_removeSheetDidEnd:returnCode:context:), NULL, files,
                                  NSLocalizedString(@"Are you sure you want to remove the selected files from the repository?", 
                                                    @"Body of Remove alert"));
}

- (void) _removeSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode == NSOKButton ) {
        // check if there is any locally modified file
        if ( context ) {
            NSArray *files = (NSArray*) context;
            BOOL modified = NO;
            for( HgFile *file in files ) {
                if ( file.status == kModified ) {
                    modified = YES;
                    break;
                }
            }
            
            if ( ! modified ) {
                NSError *error = nil;
                if( ! [_repo.uncommittedRevision removeFiles: (NSArray*)context trashModified: NO error: &error] ) {
                    [self presentError: error];
                }
            } else {
                NSBeginCriticalAlertSheet(NSLocalizedString(@"Some of the files you are about to remove have local modifications. Do you want to move them to the Trash, or delete them?", @"Trash or Delete files dialog"),
                                          NSLocalizedString(@"Move to Trash", @"Button in remove modified files dialogs"),
                                          NSLocalizedString(@"Cancel", @"Button"),
                                          NSLocalizedString(@"Delete", @"Button"),
                                          self.window,self,
                                          @selector(_removeSheetWithModificationsEnd:returnCode:context:), NULL, files,
                                          NSLocalizedString(@"If you choose to delete them, all the changes will be lost.", 
                                                            @"Body of Trash or Delete files dialog"));
            }
        }
    }
}

- (void) _removeSheetWithModificationsEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode == NSAlertDefaultReturn || returnCode == NSAlertOtherReturn) {
        BOOL trashFiles = returnCode == NSAlertDefaultReturn;
        NSError *error = nil;
        if( ! [_repo.uncommittedRevision removeFiles: (NSArray*)context trashModified: trashFiles error: &error] ) {
            [self presentError: error];
        }
    }
}


- (void) discardChanges: (id)sender
{
    NSArray *files = self._uncommittedSelectedFiles;
    if( files )
        NSBeginCriticalAlertSheet(NSLocalizedString(@"Discard file changes?", 
                                                    @"Title of Discard alert"),
                                  NSLocalizedString(@"Discard", 
                                                    @"Default button of Discard alert"),
                                  NSLocalizedString(@"Cancel", @"Button"), nil,
                                  self.window,self,
                                  @selector(_discardSheetDidEnd:returnCode:context:), NULL, files,
                                  NSLocalizedString(@"Are you sure you want to discard all uncommitted changes to the selected files?", 
                                                    @"Body of Discard alert"));
}

- (void) _discardSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode == NSOKButton ) {
        BOOL backup = ! [[NSUserDefaults standardUserDefaults] boolForKey: kPrefRevertWithoutBackup];
        NSError *error = nil;
        if( ! [_repo.uncommittedRevision revertFiles: (NSArray*)context
                                              backup: backup
                                               error: &error] ) {
            [self presentError: error];
        }
    }
}


#pragma mark -
#pragma mark MERGING:


- (IBAction) merge: (id)sender
{
    NSError *error;
    NSString *output;
    if( [_repo mergeWithRevision: nil output: &output error: &error] ) {
        // Success:
        self.selectedRevision = _repo.uncommittedRevision;
        _repo.uncommittedRevision.formattedDescription =
            NSLocalizedString(@"Merged.",
                              @"Log message that's set when a merge succeeds");
        [self _updateInfoView];
        NSBeginCriticalAlertSheet(
            NSLocalizedString(@"Merged!",
                              @"Title of merge success sheet"),
            NSLocalizedString(@"Commit", @"Default button in merge success sheet"),
            NSLocalizedString(@"Not Now", @"Commit-later button in merge success sheet"),
            nil, 
            self.window,
            self, @selector(mergeConfirmationSheetDidFinish:resultCode:), NULL, NULL,
            @"The revisions were merged, and the result is in your working tree.\n"
            "Don't forget to commit before starting any new work!\n\n"
            "(It would be a good idea to make sure the tree builds and runs first, though.)");
        return;
    }
    
    // Merge failed -- was it because of conflicts?
    NSString *title, *message;
    HgUncommittedRevision* cur = _repo.uncommittedRevision;
    if (cur.root.mergeStatus == kConflict) {
        title = NSLocalizedString(@"Merge Conflicts Remain",
                                  @"Title of merge-conflicts sheet");
        message = NSLocalizedString(@"The merge is unfinished and has not yet been committed!\n\n"
                                    "There were conflicting changes to one or more files. These files are now marked with a conflict status icon in the file list below.\n\n"
                                    "You'll need to hand-edit each conflicting file, then mark it as resolved via the Revisions menu. After that, you can commit the merge.",
                                    @"Body of merge-conflicts sheet");
        _repo.uncommittedRevision.formattedDescription =
            NSLocalizedString(@"Merged, with conflicts resolved by hand.",
                              @"Log message that's set when a merge fails");
        [self _updateInfoView];
    } else {
        // Some other error occurred:
        title = NSLocalizedString(@"Merge Failed!",
                                  @"Title of generic merge error sheet");
        message = NSLocalizedString(@"An error occurred and the merge did not take place.",
                                    @"Body of generic merge error sheet");
    }
    
    NSBeginCriticalAlertSheet(title,
                              nil, nil, nil, self.window, nil, NULL, NULL, NULL,
                              [message stringByAppendingString: @"\n\n____________________\n%@"], 
                              error.localizedRecoverySuggestion, output);
}

- (void) mergeConfirmationSheetDidFinish: (NSPanel*)sheet resultCode: (NSInteger)resultCode {
    [sheet orderOut: self];
    if (resultCode == NSOKButton) {
        // The user might have gone to Xcode and made changes before pressing Commit,
        // so sync up with Mercurial now so that the -commitChanges: method knows the
        // current state.
        [_repo updateStatus: nil];
        [self commitChanges: self];
    }
}

// Redo a merge in a graphical compare/merge tool.
- (IBAction) remergeFiles: (id)sender {
    HgRevision *rev = self.selectedRevision;
    if( !rev.isUncommitted ) {
        NSBeep();
        return;
    }
    BOOL any = NO;
    for (HgFile *file in self.selectedFiles) {
        if (file.isFile && file.mergeStatus == kConflict) {
            any = YES;
            NSError *error;
            if (![self showComparisonFromRevision: rev.parent 
                                       toRevision: rev.parent2 
                                           ofFile: file
                                            error: &error]) {
                [self presentError: error];
                return;
            }
        }
    }
    if (!any)
        NSBeep();
}

- (HgMergeStatus) mergeStatusOfSelection {
    HgRevision *rev = self.selectedRevision;
    if( ! rev.isUncommitted )
        return kUnmerged;
    NSArray *files = self.selectedFiles;
    if (files.count == 0)
        return kUnmerged;
    for (HgFile *file in files) {
        switch (file.mergeStatus) {
            case kUnmerged:
                return kUnmerged;
            case kConflict:
                return kConflict;
            case kResolved:
                break;
        }
    }
    return kResolved;
}

- (IBAction) markResolved: (id)sender {
    HgMergeStatus status = self.mergeStatusOfSelection;
    if (status == kUnmerged) {
        NSBeep();
        return;
    }

    NSError *error = nil;
    if( ! [_repo.uncommittedRevision markFiles: self.selectedFiles
                                      resolved: (status != kResolved)
                                         error: &error] ) {
        [self presentError: error];
    }
}


#pragma mark -
#pragma mark UPDATING TO A REVISION:


- (void) _updateTo: (HgRevision*)rev
{
    NSError *error;
    NSString *output;
    if( [_repo updateToRevision: rev output: &output error: &error] ) {
        if( ! output ) output = @"";
        NSBeginInformationalAlertSheet(NSLocalizedString(@"Update Completed", 
                                                         @"Confirmation message after Update"),
                                       nil, nil, nil, self.window, nil, NULL, NULL, NULL,
                                       @"%@", output);
    } else        
        [self presentError: error];
}


- (IBAction) updateToLatest: (id)sender
{
    [self _updateTo: nil];
}


- (IBAction) updateToSelectedRevision: (id)sender
{
    HgRevision *rev = [self selectedRevision];
    if( rev==nil || rev.isUncommitted ) {
        NSBeep();
        return;
    }
    NSBeginCriticalAlertSheet(NSLocalizedString(@"Update to revision?", 
                                                @"Title of Update alert"),
                              NSLocalizedString(@"Update", 
                                                @"Default button of Update alert"),
                              NSLocalizedString(@"Cancel", @"Button"), nil,
                              self.window,self,
                              @selector(_updateSheetDidEnd:returnCode:context:), NULL, rev,
                              NSLocalizedString(@"Are you sure you want to update the source tree to revision %i?", 
                                                @"Body of Update alert"),
                              rev.localNumber);
}

- (void) _updateSheetDidEnd: (NSPanel*)sheet returnCode: (NSInteger)returnCode context: (void*)context
{
    [sheet orderOut: self];
    if( returnCode == NSOKButton )
        [self _updateTo: (HgRevision*)context];
}


- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem
{
    SEL action = [anItem action];
    if( action == @selector(toggleShowsOnlyUncleanFiles:) ) {
        if( [(id)anItem respondsToSelector: @selector(setState:)] )
            [(id)anItem setState: self.showsOnlyUncleanFiles];
        return YES;
    } else if( action==@selector(openSelectedFile:) || action==@selector(showRevision:)
            || action==@selector(openQuickLook:) || action==@selector(openSelectedFileInWindow:)) {
        return self.selectedFile.isFile;
    } else if( action==@selector(showDiff:) ) {
        HgRevision *revOld,*revNew;
        return [self getSelectedRevisionsOld: &revOld andNew: &revNew];
    } else if( action==@selector(addToRepository:) ) {
        return self.selectedRevision.isUncommitted && [self anySelectedFilesHaveStatus: kNotTracked];
    } else if( action==@selector(removeFromRepository:) ) {
        return self.selectedRevision.isUncommitted && self.selectedFiles.count > 0;
    } else if( action==@selector(showComparison:) ) {
        HgRevision *revOld,*revNew;
        return self.selectedFiles.count>1 || [self getSelectedRevisionsOld: &revOld andNew: &revNew];
    } else if( action==@selector(commitChanges:) || action==@selector(discardChanges:) ) {
        return self.selectedRevision.isUncommitted && self.anySelectedFilesUncommitted;
    } else if( action==@selector(commitAllChanges:) ) {
        HgStatus status = _repo.uncommittedRevision.root.status;
        return status==kModified || status==kAdded || status==kDeleted;
    } else if( action == @selector(updateToSelectedRevision:) ) {
        HgRevision *rev = self.selectedRevision;
        return rev!=nil && ! rev.isUncommitted;
    } else if (action == @selector(merge:)) {
        return [_repo canMergeWithRevision: nil];
    } else if (action == @selector(remergeFiles:)) {
        return self.mergeStatusOfSelection == kConflict;
    } else if (action == @selector(markResolved:)) {
        HgMergeStatus status = self.mergeStatusOfSelection;
        NSString *title;
        if (status == kResolved)
            title = @"Mark As Unresolved";
        else
            title = @"Mark As Resolved";
        [(id)anItem setTitle: title];
        return (status != kUnmerged);
    } else
        return YES;
}


@end