6cbb36eab6a75aa0b2bdf751eade5a6ae6ea76f2
   1#!/bin/sh
   2# Tcl ignores the next line -*- tcl -*- \
   3 if test "z$*" = zversion \
   4 || test "z$*" = z--version; \
   5 then \
   6        echo 'git-gui version @@GITGUI_VERSION@@'; \
   7        exit; \
   8 fi; \
   9 argv0=$0; \
  10 exec wish "$argv0" -- "$@"
  11
  12set appvers {@@GITGUI_VERSION@@}
  13set copyright [string map [list (c) \u00a9] {
  14Copyright (c) 2006-2010 Shawn Pearce, et. al.
  15
  16This program is free software; you can redistribute it and/or modify
  17it under the terms of the GNU General Public License as published by
  18the Free Software Foundation; either version 2 of the License, or
  19(at your option) any later version.
  20
  21This program is distributed in the hope that it will be useful,
  22but WITHOUT ANY WARRANTY; without even the implied warranty of
  23MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  24GNU General Public License for more details.
  25
  26You should have received a copy of the GNU General Public License
  27along with this program; if not, write to the Free Software
  28Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA}]
  29
  30######################################################################
  31##
  32## Tcl/Tk sanity check
  33
  34if {[catch {package require Tcl 8.4} err]
  35 || [catch {package require Tk  8.4} err]
  36} {
  37        catch {wm withdraw .}
  38        tk_messageBox \
  39                -icon error \
  40                -type ok \
  41                -title "git-gui: fatal error" \
  42                -message $err
  43        exit 1
  44}
  45
  46catch {rename send {}} ; # What an evil concept...
  47
  48######################################################################
  49##
  50## locate our library
  51
  52if { [info exists ::env(GIT_GUI_LIB_DIR) ] } {
  53        set oguilib $::env(GIT_GUI_LIB_DIR)
  54} else {
  55        set oguilib {@@GITGUI_LIBDIR@@}
  56}
  57set oguirel {@@GITGUI_RELATIVE@@}
  58if {$oguirel eq {1}} {
  59        set oguilib [file dirname [file normalize $argv0]]
  60        if {[file tail $oguilib] eq {git-core}} {
  61                set oguilib [file dirname $oguilib]
  62        }
  63        set oguilib [file dirname $oguilib]
  64        set oguilib [file join $oguilib share git-gui lib]
  65        set oguimsg [file join $oguilib msgs]
  66} elseif {[string match @@* $oguirel]} {
  67        set oguilib [file join [file dirname [file normalize $argv0]] lib]
  68        set oguimsg [file join [file dirname [file normalize $argv0]] po]
  69} else {
  70        set oguimsg [file join $oguilib msgs]
  71}
  72unset oguirel
  73
  74######################################################################
  75##
  76## enable verbose loading?
  77
  78if {![catch {set _verbose $env(GITGUI_VERBOSE)}]} {
  79        unset _verbose
  80        rename auto_load real__auto_load
  81        proc auto_load {name args} {
  82                puts stderr "auto_load $name"
  83                return [uplevel 1 real__auto_load $name $args]
  84        }
  85        rename source real__source
  86        proc source {name} {
  87                puts stderr "source    $name"
  88                uplevel 1 real__source $name
  89        }
  90        if {[tk windowingsystem] eq "win32"} { console show }
  91}
  92
  93######################################################################
  94##
  95## Internationalization (i18n) through msgcat and gettext. See
  96## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
  97
  98package require msgcat
  99
 100# Check for Windows 7 MUI language pack (missed by msgcat < 1.4.4)
 101if {[tk windowingsystem] eq "win32"
 102        && [package vcompare [package provide msgcat] 1.4.4] < 0
 103} then {
 104        proc _mc_update_locale {} {
 105                set key {HKEY_CURRENT_USER\Control Panel\Desktop}
 106                if {![catch {
 107                        package require registry
 108                        set uilocale [registry get $key "PreferredUILanguages"]
 109                        msgcat::ConvertLocale [string map {- _} [lindex $uilocale 0]]
 110                } uilocale]} {
 111                        if {[string length $uilocale] > 0} {
 112                                msgcat::mclocale $uilocale
 113                        }
 114                }
 115        }
 116        _mc_update_locale
 117}
 118
 119proc _mc_trim {fmt} {
 120        set cmk [string first @@ $fmt]
 121        if {$cmk > 0} {
 122                return [string range $fmt 0 [expr {$cmk - 1}]]
 123        }
 124        return $fmt
 125}
 126
 127proc mc {en_fmt args} {
 128        set fmt [_mc_trim [::msgcat::mc $en_fmt]]
 129        if {[catch {set msg [eval [list format $fmt] $args]} err]} {
 130                set msg [eval [list format [_mc_trim $en_fmt]] $args]
 131        }
 132        return $msg
 133}
 134
 135proc strcat {args} {
 136        return [join $args {}]
 137}
 138
 139::msgcat::mcload $oguimsg
 140unset oguimsg
 141
 142######################################################################
 143##
 144## On Mac, bring the current Wish process window to front
 145
 146if {[tk windowingsystem] eq "aqua"} {
 147        catch {
 148                exec osascript -e [format {
 149                        tell application "System Events"
 150                                set frontmost of processes whose unix id is %d to true
 151                        end tell
 152                } [pid]]
 153        }
 154}
 155
 156######################################################################
 157##
 158## read only globals
 159
 160set _appname {Git Gui}
 161set _gitdir {}
 162set _gitworktree {}
 163set _isbare {}
 164set _gitexec {}
 165set _githtmldir {}
 166set _reponame {}
 167set _iscygwin {}
 168set _search_path {}
 169set _shellpath {@@SHELL_PATH@@}
 170
 171set _trace [lsearch -exact $argv --trace]
 172if {$_trace >= 0} {
 173        set argv [lreplace $argv $_trace $_trace]
 174        set _trace 1
 175        if {[tk windowingsystem] eq "win32"} { console show }
 176} else {
 177        set _trace 0
 178}
 179
 180# variable for the last merged branch (useful for a default when deleting
 181# branches).
 182set _last_merged_branch {}
 183
 184proc shellpath {} {
 185        global _shellpath env
 186        if {[string match @@* $_shellpath]} {
 187                if {[info exists env(SHELL)]} {
 188                        return $env(SHELL)
 189                } else {
 190                        return /bin/sh
 191                }
 192        }
 193        return $_shellpath
 194}
 195
 196proc appname {} {
 197        global _appname
 198        return $_appname
 199}
 200
 201proc gitdir {args} {
 202        global _gitdir
 203        if {$args eq {}} {
 204                return $_gitdir
 205        }
 206        return [eval [list file join $_gitdir] $args]
 207}
 208
 209proc gitexec {args} {
 210        global _gitexec
 211        if {$_gitexec eq {}} {
 212                if {[catch {set _gitexec [git --exec-path]} err]} {
 213                        error "Git not installed?\n\n$err"
 214                }
 215                if {[is_Cygwin]} {
 216                        set _gitexec [exec cygpath \
 217                                --windows \
 218                                --absolute \
 219                                $_gitexec]
 220                } else {
 221                        set _gitexec [file normalize $_gitexec]
 222                }
 223        }
 224        if {$args eq {}} {
 225                return $_gitexec
 226        }
 227        return [eval [list file join $_gitexec] $args]
 228}
 229
 230proc githtmldir {args} {
 231        global _githtmldir
 232        if {$_githtmldir eq {}} {
 233                if {[catch {set _githtmldir [git --html-path]}]} {
 234                        # Git not installed or option not yet supported
 235                        return {}
 236                }
 237                if {[is_Cygwin]} {
 238                        set _githtmldir [exec cygpath \
 239                                --windows \
 240                                --absolute \
 241                                $_githtmldir]
 242                } else {
 243                        set _githtmldir [file normalize $_githtmldir]
 244                }
 245        }
 246        if {$args eq {}} {
 247                return $_githtmldir
 248        }
 249        return [eval [list file join $_githtmldir] $args]
 250}
 251
 252proc reponame {} {
 253        return $::_reponame
 254}
 255
 256proc is_MacOSX {} {
 257        if {[tk windowingsystem] eq {aqua}} {
 258                return 1
 259        }
 260        return 0
 261}
 262
 263proc is_Windows {} {
 264        if {$::tcl_platform(platform) eq {windows}} {
 265                return 1
 266        }
 267        return 0
 268}
 269
 270proc is_Cygwin {} {
 271        global _iscygwin
 272        if {$_iscygwin eq {}} {
 273                if {$::tcl_platform(platform) eq {windows}} {
 274                        if {[catch {set p [exec cygpath --windir]} err]} {
 275                                set _iscygwin 0
 276                        } else {
 277                                set _iscygwin 1
 278                        }
 279                } else {
 280                        set _iscygwin 0
 281                }
 282        }
 283        return $_iscygwin
 284}
 285
 286proc is_enabled {option} {
 287        global enabled_options
 288        if {[catch {set on $enabled_options($option)}]} {return 0}
 289        return $on
 290}
 291
 292proc enable_option {option} {
 293        global enabled_options
 294        set enabled_options($option) 1
 295}
 296
 297proc disable_option {option} {
 298        global enabled_options
 299        set enabled_options($option) 0
 300}
 301
 302######################################################################
 303##
 304## config
 305
 306proc is_many_config {name} {
 307        switch -glob -- $name {
 308        gui.recentrepo -
 309        remote.*.fetch -
 310        remote.*.push
 311                {return 1}
 312        *
 313                {return 0}
 314        }
 315}
 316
 317proc is_config_true {name} {
 318        global repo_config
 319        if {[catch {set v $repo_config($name)}]} {
 320                return 0
 321        }
 322        set v [string tolower $v]
 323        if {$v eq {} || $v eq {true} || $v eq {1} || $v eq {yes} || $v eq {on}} {
 324                return 1
 325        } else {
 326                return 0
 327        }
 328}
 329
 330proc is_config_false {name} {
 331        global repo_config
 332        if {[catch {set v $repo_config($name)}]} {
 333                return 0
 334        }
 335        set v [string tolower $v]
 336        if {$v eq {false} || $v eq {0} || $v eq {no} || $v eq {off}} {
 337                return 1
 338        } else {
 339                return 0
 340        }
 341}
 342
 343proc get_config {name} {
 344        global repo_config
 345        if {[catch {set v $repo_config($name)}]} {
 346                return {}
 347        } else {
 348                return $v
 349        }
 350}
 351
 352proc is_bare {} {
 353        global _isbare
 354        global _gitdir
 355        global _gitworktree
 356
 357        if {$_isbare eq {}} {
 358                if {[catch {
 359                        set _bare [git rev-parse --is-bare-repository]
 360                        switch  -- $_bare {
 361                        true { set _isbare 1 }
 362                        false { set _isbare 0}
 363                        default { throw }
 364                        }
 365                }]} {
 366                        if {[is_config_true core.bare]
 367                                || ($_gitworktree eq {}
 368                                        && [lindex [file split $_gitdir] end] ne {.git})} {
 369                                set _isbare 1
 370                        } else {
 371                                set _isbare 0
 372                        }
 373                }
 374        }
 375        return $_isbare
 376}
 377
 378######################################################################
 379##
 380## handy utils
 381
 382proc _trace_exec {cmd} {
 383        if {!$::_trace} return
 384        set d {}
 385        foreach v $cmd {
 386                if {$d ne {}} {
 387                        append d { }
 388                }
 389                if {[regexp {[ \t\r\n'"$?*]} $v]} {
 390                        set v [sq $v]
 391                }
 392                append d $v
 393        }
 394        puts stderr $d
 395}
 396
 397#'"  fix poor old emacs font-lock mode
 398
 399proc _git_cmd {name} {
 400        global _git_cmd_path
 401
 402        if {[catch {set v $_git_cmd_path($name)}]} {
 403                switch -- $name {
 404                  version   -
 405                --version   -
 406                --exec-path { return [list $::_git $name] }
 407                }
 408
 409                set p [gitexec git-$name$::_search_exe]
 410                if {[file exists $p]} {
 411                        set v [list $p]
 412                } elseif {[is_Windows] && [file exists [gitexec git-$name]]} {
 413                        # Try to determine what sort of magic will make
 414                        # git-$name go and do its thing, because native
 415                        # Tcl on Windows doesn't know it.
 416                        #
 417                        set p [gitexec git-$name]
 418                        set f [open $p r]
 419                        set s [gets $f]
 420                        close $f
 421
 422                        switch -glob -- [lindex $s 0] {
 423                        #!*sh     { set i sh     }
 424                        #!*perl   { set i perl   }
 425                        #!*python { set i python }
 426                        default   { error "git-$name is not supported: $s" }
 427                        }
 428
 429                        upvar #0 _$i interp
 430                        if {![info exists interp]} {
 431                                set interp [_which $i]
 432                        }
 433                        if {$interp eq {}} {
 434                                error "git-$name requires $i (not in PATH)"
 435                        }
 436                        set v [concat [list $interp] [lrange $s 1 end] [list $p]]
 437                } else {
 438                        # Assume it is builtin to git somehow and we
 439                        # aren't actually able to see a file for it.
 440                        #
 441                        set v [list $::_git $name]
 442                }
 443                set _git_cmd_path($name) $v
 444        }
 445        return $v
 446}
 447
 448proc _which {what args} {
 449        global env _search_exe _search_path
 450
 451        if {$_search_path eq {}} {
 452                if {[is_Cygwin] && [regexp {^(/|\.:)} $env(PATH)]} {
 453                        set _search_path [split [exec cygpath \
 454                                --windows \
 455                                --path \
 456                                --absolute \
 457                                $env(PATH)] {;}]
 458                        set _search_exe .exe
 459                } elseif {[is_Windows]} {
 460                        set gitguidir [file dirname [info script]]
 461                        regsub -all ";" $gitguidir "\\;" gitguidir
 462                        set env(PATH) "$gitguidir;$env(PATH)"
 463                        set _search_path [split $env(PATH) {;}]
 464                        set _search_exe .exe
 465                } else {
 466                        set _search_path [split $env(PATH) :]
 467                        set _search_exe {}
 468                }
 469        }
 470
 471        if {[is_Windows] && [lsearch -exact $args -script] >= 0} {
 472                set suffix {}
 473        } else {
 474                set suffix $_search_exe
 475        }
 476
 477        foreach p $_search_path {
 478                set p [file join $p $what$suffix]
 479                if {[file exists $p]} {
 480                        return [file normalize $p]
 481                }
 482        }
 483        return {}
 484}
 485
 486# Test a file for a hashbang to identify executable scripts on Windows.
 487proc is_shellscript {filename} {
 488        if {![file exists $filename]} {return 0}
 489        set f [open $filename r]
 490        fconfigure $f -encoding binary
 491        set magic [read $f 2]
 492        close $f
 493        return [expr {$magic eq "#!"}]
 494}
 495
 496# Run a command connected via pipes on stdout.
 497# This is for use with textconv filters and uses sh -c "..." to allow it to
 498# contain a command with arguments. On windows we must check for shell
 499# scripts specifically otherwise just call the filter command.
 500proc open_cmd_pipe {cmd path} {
 501        global env
 502        if {![file executable [shellpath]]} {
 503                set exe [auto_execok [lindex $cmd 0]]
 504                if {[is_shellscript [lindex $exe 0]]} {
 505                        set run [linsert [auto_execok sh] end -c "$cmd \"\$0\"" $path]
 506                } else {
 507                        set run [concat $exe [lrange $cmd 1 end] $path]
 508                }
 509        } else {
 510                set run [list [shellpath] -c "$cmd \"\$0\"" $path]
 511        }
 512        return [open |$run r]
 513}
 514
 515proc _lappend_nice {cmd_var} {
 516        global _nice
 517        upvar $cmd_var cmd
 518
 519        if {![info exists _nice]} {
 520                set _nice [_which nice]
 521                if {[catch {exec $_nice git version}]} {
 522                        set _nice {}
 523                } elseif {[is_Windows] && [file dirname $_nice] ne [file dirname $::_git]} {
 524                        set _nice {}
 525                }
 526        }
 527        if {$_nice ne {}} {
 528                lappend cmd $_nice
 529        }
 530}
 531
 532proc git {args} {
 533        set opt [list]
 534
 535        while {1} {
 536                switch -- [lindex $args 0] {
 537                --nice {
 538                        _lappend_nice opt
 539                }
 540
 541                default {
 542                        break
 543                }
 544
 545                }
 546
 547                set args [lrange $args 1 end]
 548        }
 549
 550        set cmdp [_git_cmd [lindex $args 0]]
 551        set args [lrange $args 1 end]
 552
 553        _trace_exec [concat $opt $cmdp $args]
 554        set result [eval exec $opt $cmdp $args]
 555        if {$::_trace} {
 556                puts stderr "< $result"
 557        }
 558        return $result
 559}
 560
 561proc _open_stdout_stderr {cmd} {
 562        _trace_exec $cmd
 563        if {[catch {
 564                        set fd [open [concat [list | ] $cmd] r]
 565                } err]} {
 566                if {   [lindex $cmd end] eq {2>@1}
 567                    && $err eq {can not find channel named "1"}
 568                        } {
 569                        # Older versions of Tcl 8.4 don't have this 2>@1 IO
 570                        # redirect operator.  Fallback to |& cat for those.
 571                        # The command was not actually started, so its safe
 572                        # to try to start it a second time.
 573                        #
 574                        set fd [open [concat \
 575                                [list | ] \
 576                                [lrange $cmd 0 end-1] \
 577                                [list |& cat] \
 578                                ] r]
 579                } else {
 580                        error $err
 581                }
 582        }
 583        fconfigure $fd -eofchar {}
 584        return $fd
 585}
 586
 587proc git_read {args} {
 588        set opt [list]
 589
 590        while {1} {
 591                switch -- [lindex $args 0] {
 592                --nice {
 593                        _lappend_nice opt
 594                }
 595
 596                --stderr {
 597                        lappend args 2>@1
 598                }
 599
 600                default {
 601                        break
 602                }
 603
 604                }
 605
 606                set args [lrange $args 1 end]
 607        }
 608
 609        set cmdp [_git_cmd [lindex $args 0]]
 610        set args [lrange $args 1 end]
 611
 612        return [_open_stdout_stderr [concat $opt $cmdp $args]]
 613}
 614
 615proc git_write {args} {
 616        set opt [list]
 617
 618        while {1} {
 619                switch -- [lindex $args 0] {
 620                --nice {
 621                        _lappend_nice opt
 622                }
 623
 624                default {
 625                        break
 626                }
 627
 628                }
 629
 630                set args [lrange $args 1 end]
 631        }
 632
 633        set cmdp [_git_cmd [lindex $args 0]]
 634        set args [lrange $args 1 end]
 635
 636        _trace_exec [concat $opt $cmdp $args]
 637        return [open [concat [list | ] $opt $cmdp $args] w]
 638}
 639
 640proc githook_read {hook_name args} {
 641        set pchook [gitdir hooks $hook_name]
 642        lappend args 2>@1
 643
 644        # On Windows [file executable] might lie so we need to ask
 645        # the shell if the hook is executable.  Yes that's annoying.
 646        #
 647        if {[is_Windows]} {
 648                upvar #0 _sh interp
 649                if {![info exists interp]} {
 650                        set interp [_which sh]
 651                }
 652                if {$interp eq {}} {
 653                        error "hook execution requires sh (not in PATH)"
 654                }
 655
 656                set scr {if test -x "$1";then exec "$@";fi}
 657                set sh_c [list $interp -c $scr $interp $pchook]
 658                return [_open_stdout_stderr [concat $sh_c $args]]
 659        }
 660
 661        if {[file executable $pchook]} {
 662                return [_open_stdout_stderr [concat [list $pchook] $args]]
 663        }
 664
 665        return {}
 666}
 667
 668proc kill_file_process {fd} {
 669        set process [pid $fd]
 670
 671        catch {
 672                if {[is_Windows]} {
 673                        # Use a Cygwin-specific flag to allow killing
 674                        # native Windows processes
 675                        exec kill -f $process
 676                } else {
 677                        exec kill $process
 678                }
 679        }
 680}
 681
 682proc gitattr {path attr default} {
 683        if {[catch {set r [git check-attr $attr -- $path]}]} {
 684                set r unspecified
 685        } else {
 686                set r [join [lrange [split $r :] 2 end] :]
 687                regsub {^ } $r {} r
 688        }
 689        if {$r eq {unspecified}} {
 690                return $default
 691        }
 692        return $r
 693}
 694
 695proc sq {value} {
 696        regsub -all ' $value "'\\''" value
 697        return "'$value'"
 698}
 699
 700proc load_current_branch {} {
 701        global current_branch is_detached
 702
 703        set fd [open [gitdir HEAD] r]
 704        if {[gets $fd ref] < 1} {
 705                set ref {}
 706        }
 707        close $fd
 708
 709        set pfx {ref: refs/heads/}
 710        set len [string length $pfx]
 711        if {[string equal -length $len $pfx $ref]} {
 712                # We're on a branch.  It might not exist.  But
 713                # HEAD looks good enough to be a branch.
 714                #
 715                set current_branch [string range $ref $len end]
 716                set is_detached 0
 717        } else {
 718                # Assume this is a detached head.
 719                #
 720                set current_branch HEAD
 721                set is_detached 1
 722        }
 723}
 724
 725auto_load tk_optionMenu
 726rename tk_optionMenu real__tkOptionMenu
 727proc tk_optionMenu {w varName args} {
 728        set m [eval real__tkOptionMenu $w $varName $args]
 729        $m configure -font font_ui
 730        $w configure -font font_ui
 731        return $m
 732}
 733
 734proc rmsel_tag {text} {
 735        $text tag conf sel \
 736                -background [$text cget -background] \
 737                -foreground [$text cget -foreground] \
 738                -borderwidth 0
 739        $text tag conf in_sel -background lightgray
 740        bind $text <Motion> break
 741        return $text
 742}
 743
 744wm withdraw .
 745set root_exists 0
 746bind . <Visibility> {
 747        bind . <Visibility> {}
 748        set root_exists 1
 749}
 750
 751if {[is_Windows]} {
 752        wm iconbitmap . -default $oguilib/git-gui.ico
 753        set ::tk::AlwaysShowSelection 1
 754        bind . <Control-F2> {console show}
 755
 756        # Spoof an X11 display for SSH
 757        if {![info exists env(DISPLAY)]} {
 758                set env(DISPLAY) :9999
 759        }
 760} else {
 761        catch {
 762                image create photo gitlogo -width 16 -height 16
 763
 764                gitlogo put #33CC33 -to  7  0  9  2
 765                gitlogo put #33CC33 -to  4  2 12  4
 766                gitlogo put #33CC33 -to  7  4  9  6
 767                gitlogo put #CC3333 -to  4  6 12  8
 768                gitlogo put gray26  -to  4  9  6 10
 769                gitlogo put gray26  -to  3 10  6 12
 770                gitlogo put gray26  -to  8  9 13 11
 771                gitlogo put gray26  -to  8 11 10 12
 772                gitlogo put gray26  -to 11 11 13 14
 773                gitlogo put gray26  -to  3 12  5 14
 774                gitlogo put gray26  -to  5 13
 775                gitlogo put gray26  -to 10 13
 776                gitlogo put gray26  -to  4 14 12 15
 777                gitlogo put gray26  -to  5 15 11 16
 778                gitlogo redither
 779
 780                image create photo gitlogo32 -width 32 -height 32
 781                gitlogo32 copy gitlogo -zoom 2 2
 782
 783                wm iconphoto . -default gitlogo gitlogo32
 784        }
 785}
 786
 787######################################################################
 788##
 789## config defaults
 790
 791set cursor_ptr arrow
 792font create font_ui
 793if {[lsearch -exact [font names] TkDefaultFont] != -1} {
 794        eval [linsert [font actual TkDefaultFont] 0 font configure font_ui]
 795        eval [linsert [font actual TkFixedFont] 0 font create font_diff]
 796} else {
 797        font create font_diff -family Courier -size 10
 798        catch {
 799                label .dummy
 800                eval font configure font_ui [font actual [.dummy cget -font]]
 801                destroy .dummy
 802        }
 803}
 804
 805font create font_uiitalic
 806font create font_uibold
 807font create font_diffbold
 808font create font_diffitalic
 809
 810foreach class {Button Checkbutton Entry Label
 811                Labelframe Listbox Message
 812                Radiobutton Spinbox Text} {
 813        option add *$class.font font_ui
 814}
 815if {![is_MacOSX]} {
 816        option add *Menu.font font_ui
 817        option add *Entry.borderWidth 1 startupFile
 818        option add *Entry.relief sunken startupFile
 819        option add *RadioButton.anchor w startupFile
 820}
 821unset class
 822
 823if {[is_Windows] || [is_MacOSX]} {
 824        option add *Menu.tearOff 0
 825}
 826
 827if {[is_MacOSX]} {
 828        set M1B M1
 829        set M1T Cmd
 830} else {
 831        set M1B Control
 832        set M1T Ctrl
 833}
 834
 835proc bind_button3 {w cmd} {
 836        bind $w <Any-Button-3> $cmd
 837        if {[is_MacOSX]} {
 838                # Mac OS X sends Button-2 on right click through three-button mouse,
 839                # or through trackpad right-clicking (two-finger touch + click).
 840                bind $w <Any-Button-2> $cmd
 841                bind $w <Control-Button-1> $cmd
 842        }
 843}
 844
 845proc apply_config {} {
 846        global repo_config font_descs
 847
 848        foreach option $font_descs {
 849                set name [lindex $option 0]
 850                set font [lindex $option 1]
 851                if {[catch {
 852                        set need_weight 1
 853                        foreach {cn cv} $repo_config(gui.$name) {
 854                                if {$cn eq {-weight}} {
 855                                        set need_weight 0
 856                                }
 857                                font configure $font $cn $cv
 858                        }
 859                        if {$need_weight} {
 860                                font configure $font -weight normal
 861                        }
 862                        } err]} {
 863                        error_popup [strcat [mc "Invalid font specified in %s:" "gui.$name"] "\n\n$err"]
 864                }
 865                foreach {cn cv} [font configure $font] {
 866                        font configure ${font}bold $cn $cv
 867                        font configure ${font}italic $cn $cv
 868                }
 869                font configure ${font}bold -weight bold
 870                font configure ${font}italic -slant italic
 871        }
 872
 873        global use_ttk NS
 874        set use_ttk 0
 875        set NS {}
 876        if {$repo_config(gui.usettk)} {
 877                set use_ttk [package vsatisfies [package provide Tk] 8.5]
 878                if {$use_ttk} {
 879                        set NS ttk
 880                        bind [winfo class .] <<ThemeChanged>> [list InitTheme]
 881                        pave_toplevel .
 882                }
 883        }
 884}
 885
 886set default_config(branch.autosetupmerge) true
 887set default_config(merge.tool) {}
 888set default_config(mergetool.keepbackup) true
 889set default_config(merge.diffstat) true
 890set default_config(merge.summary) false
 891set default_config(merge.verbosity) 2
 892set default_config(user.name) {}
 893set default_config(user.email) {}
 894
 895set default_config(gui.encoding) [encoding system]
 896set default_config(gui.matchtrackingbranch) false
 897set default_config(gui.textconv) true
 898set default_config(gui.pruneduringfetch) false
 899set default_config(gui.trustmtime) false
 900set default_config(gui.fastcopyblame) false
 901set default_config(gui.maxrecentrepo) 10
 902set default_config(gui.copyblamethreshold) 40
 903set default_config(gui.blamehistoryctx) 7
 904set default_config(gui.diffcontext) 5
 905set default_config(gui.diffopts) {}
 906set default_config(gui.commitmsgwidth) 75
 907set default_config(gui.newbranchtemplate) {}
 908set default_config(gui.spellingdictionary) {}
 909set default_config(gui.fontui) [font configure font_ui]
 910set default_config(gui.fontdiff) [font configure font_diff]
 911# TODO: this option should be added to the git-config documentation
 912set default_config(gui.maxfilesdisplayed) 5000
 913set default_config(gui.usettk) 1
 914set default_config(gui.warndetachedcommit) 1
 915set font_descs {
 916        {fontui   font_ui   {mc "Main Font"}}
 917        {fontdiff font_diff {mc "Diff/Console Font"}}
 918}
 919set default_config(gui.stageuntracked) ask
 920set default_config(gui.displayuntracked) true
 921
 922######################################################################
 923##
 924## find git
 925
 926set _git  [_which git]
 927if {$_git eq {}} {
 928        catch {wm withdraw .}
 929        tk_messageBox \
 930                -icon error \
 931                -type ok \
 932                -title [mc "git-gui: fatal error"] \
 933                -message [mc "Cannot find git in PATH."]
 934        exit 1
 935}
 936
 937######################################################################
 938##
 939## version check
 940
 941if {[catch {set _git_version [git --version]} err]} {
 942        catch {wm withdraw .}
 943        tk_messageBox \
 944                -icon error \
 945                -type ok \
 946                -title [mc "git-gui: fatal error"] \
 947                -message "Cannot determine Git version:
 948
 949$err
 950
 951[appname] requires Git 1.5.0 or later."
 952        exit 1
 953}
 954if {![regsub {^git version } $_git_version {} _git_version]} {
 955        catch {wm withdraw .}
 956        tk_messageBox \
 957                -icon error \
 958                -type ok \
 959                -title [mc "git-gui: fatal error"] \
 960                -message [strcat [mc "Cannot parse Git version string:"] "\n\n$_git_version"]
 961        exit 1
 962}
 963
 964proc get_trimmed_version {s} {
 965    set r {}
 966    foreach x [split $s -._] {
 967        if {[string is integer -strict $x]} {
 968            lappend r $x
 969        } else {
 970            break
 971        }
 972    }
 973    return [join $r .]
 974}
 975set _real_git_version $_git_version
 976set _git_version [get_trimmed_version $_git_version]
 977
 978if {![regexp {^[1-9]+(\.[0-9]+)+$} $_git_version]} {
 979        catch {wm withdraw .}
 980        if {[tk_messageBox \
 981                -icon warning \
 982                -type yesno \
 983                -default no \
 984                -title "[appname]: warning" \
 985                 -message [mc "Git version cannot be determined.
 986
 987%s claims it is version '%s'.
 988
 989%s requires at least Git 1.5.0 or later.
 990
 991Assume '%s' is version 1.5.0?
 992" $_git $_real_git_version [appname] $_real_git_version]] eq {yes}} {
 993                set _git_version 1.5.0
 994        } else {
 995                exit 1
 996        }
 997}
 998unset _real_git_version
 999
1000proc git-version {args} {
1001        global _git_version
1002
1003        switch [llength $args] {
1004        0 {
1005                return $_git_version
1006        }
1007
1008        2 {
1009                set op [lindex $args 0]
1010                set vr [lindex $args 1]
1011                set cm [package vcompare $_git_version $vr]
1012                return [expr $cm $op 0]
1013        }
1014
1015        4 {
1016                set type [lindex $args 0]
1017                set name [lindex $args 1]
1018                set parm [lindex $args 2]
1019                set body [lindex $args 3]
1020
1021                if {($type ne {proc} && $type ne {method})} {
1022                        error "Invalid arguments to git-version"
1023                }
1024                if {[llength $body] < 2 || [lindex $body end-1] ne {default}} {
1025                        error "Last arm of $type $name must be default"
1026                }
1027
1028                foreach {op vr cb} [lrange $body 0 end-2] {
1029                        if {[git-version $op $vr]} {
1030                                return [uplevel [list $type $name $parm $cb]]
1031                        }
1032                }
1033
1034                return [uplevel [list $type $name $parm [lindex $body end]]]
1035        }
1036
1037        default {
1038                error "git-version >= x"
1039        }
1040
1041        }
1042}
1043
1044if {[git-version < 1.5]} {
1045        catch {wm withdraw .}
1046        tk_messageBox \
1047                -icon error \
1048                -type ok \
1049                -title [mc "git-gui: fatal error"] \
1050                -message "[appname] requires Git 1.5.0 or later.
1051
1052You are using [git-version]:
1053
1054[git --version]"
1055        exit 1
1056}
1057
1058######################################################################
1059##
1060## configure our library
1061
1062set idx [file join $oguilib tclIndex]
1063if {[catch {set fd [open $idx r]} err]} {
1064        catch {wm withdraw .}
1065        tk_messageBox \
1066                -icon error \
1067                -type ok \
1068                -title [mc "git-gui: fatal error"] \
1069                -message $err
1070        exit 1
1071}
1072if {[gets $fd] eq {# Autogenerated by git-gui Makefile}} {
1073        set idx [list]
1074        while {[gets $fd n] >= 0} {
1075                if {$n ne {} && ![string match #* $n]} {
1076                        lappend idx $n
1077                }
1078        }
1079} else {
1080        set idx {}
1081}
1082close $fd
1083
1084if {$idx ne {}} {
1085        set loaded [list]
1086        foreach p $idx {
1087                if {[lsearch -exact $loaded $p] >= 0} continue
1088                source [file join $oguilib $p]
1089                lappend loaded $p
1090        }
1091        unset loaded p
1092} else {
1093        set auto_path [concat [list $oguilib] $auto_path]
1094}
1095unset -nocomplain idx fd
1096
1097######################################################################
1098##
1099## config file parsing
1100
1101git-version proc _parse_config {arr_name args} {
1102        >= 1.5.3 {
1103                upvar $arr_name arr
1104                array unset arr
1105                set buf {}
1106                catch {
1107                        set fd_rc [eval \
1108                                [list git_read config] \
1109                                $args \
1110                                [list --null --list]]
1111                        fconfigure $fd_rc -translation binary
1112                        set buf [read $fd_rc]
1113                        close $fd_rc
1114                }
1115                foreach line [split $buf "\0"] {
1116                        if {[regexp {^([^\n]+)\n(.*)$} $line line name value]} {
1117                                if {[is_many_config $name]} {
1118                                        lappend arr($name) $value
1119                                } else {
1120                                        set arr($name) $value
1121                                }
1122                        } elseif {[regexp {^([^\n]+)$} $line line name]} {
1123                                # no value given, but interpreting them as
1124                                # boolean will be handled as true
1125                                set arr($name) {}
1126                        }
1127                }
1128        }
1129        default {
1130                upvar $arr_name arr
1131                array unset arr
1132                catch {
1133                        set fd_rc [eval [list git_read config --list] $args]
1134                        while {[gets $fd_rc line] >= 0} {
1135                                if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
1136                                        if {[is_many_config $name]} {
1137                                                lappend arr($name) $value
1138                                        } else {
1139                                                set arr($name) $value
1140                                        }
1141                                } elseif {[regexp {^([^=]+)$} $line line name]} {
1142                                        # no value given, but interpreting them as
1143                                        # boolean will be handled as true
1144                                        set arr($name) {}
1145                                }
1146                        }
1147                        close $fd_rc
1148                }
1149        }
1150}
1151
1152proc load_config {include_global} {
1153        global repo_config global_config system_config default_config
1154
1155        if {$include_global} {
1156                _parse_config system_config --system
1157                _parse_config global_config --global
1158        }
1159        _parse_config repo_config
1160
1161        foreach name [array names default_config] {
1162                if {[catch {set v $system_config($name)}]} {
1163                        set system_config($name) $default_config($name)
1164                }
1165        }
1166        foreach name [array names system_config] {
1167                if {[catch {set v $global_config($name)}]} {
1168                        set global_config($name) $system_config($name)
1169                }
1170                if {[catch {set v $repo_config($name)}]} {
1171                        set repo_config($name) $system_config($name)
1172                }
1173        }
1174}
1175
1176######################################################################
1177##
1178## feature option selection
1179
1180if {[regexp {^git-(.+)$} [file tail $argv0] _junk subcommand]} {
1181        unset _junk
1182} else {
1183        set subcommand gui
1184}
1185if {$subcommand eq {gui.sh}} {
1186        set subcommand gui
1187}
1188if {$subcommand eq {gui} && [llength $argv] > 0} {
1189        set subcommand [lindex $argv 0]
1190        set argv [lrange $argv 1 end]
1191}
1192
1193enable_option multicommit
1194enable_option branch
1195enable_option transport
1196disable_option bare
1197
1198switch -- $subcommand {
1199browser -
1200blame {
1201        enable_option bare
1202
1203        disable_option multicommit
1204        disable_option branch
1205        disable_option transport
1206}
1207citool {
1208        enable_option singlecommit
1209        enable_option retcode
1210
1211        disable_option multicommit
1212        disable_option branch
1213        disable_option transport
1214
1215        while {[llength $argv] > 0} {
1216                set a [lindex $argv 0]
1217                switch -- $a {
1218                --amend {
1219                        enable_option initialamend
1220                }
1221                --nocommit {
1222                        enable_option nocommit
1223                        enable_option nocommitmsg
1224                }
1225                --commitmsg {
1226                        disable_option nocommitmsg
1227                }
1228                default {
1229                        break
1230                }
1231                }
1232
1233                set argv [lrange $argv 1 end]
1234        }
1235}
1236}
1237
1238######################################################################
1239##
1240## execution environment
1241
1242set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
1243
1244# Suggest our implementation of askpass, if none is set
1245if {![info exists env(SSH_ASKPASS)]} {
1246        set env(SSH_ASKPASS) [gitexec git-gui--askpass]
1247}
1248
1249######################################################################
1250##
1251## repository setup
1252
1253set picked 0
1254if {[catch {
1255                set _gitdir $env(GIT_DIR)
1256                set _prefix {}
1257                }]
1258        && [catch {
1259                # beware that from the .git dir this sets _gitdir to .
1260                # and _prefix to the empty string
1261                set _gitdir [git rev-parse --git-dir]
1262                set _prefix [git rev-parse --show-prefix]
1263        } err]} {
1264        load_config 1
1265        apply_config
1266        choose_repository::pick
1267        set picked 1
1268}
1269
1270# we expand the _gitdir when it's just a single dot (i.e. when we're being
1271# run from the .git dir itself) lest the routines to find the worktree
1272# get confused
1273if {$_gitdir eq "."} {
1274        set _gitdir [pwd]
1275}
1276
1277if {![file isdirectory $_gitdir] && [is_Cygwin]} {
1278        catch {set _gitdir [exec cygpath --windows $_gitdir]}
1279}
1280if {![file isdirectory $_gitdir]} {
1281        catch {wm withdraw .}
1282        error_popup [strcat [mc "Git directory not found:"] "\n\n$_gitdir"]
1283        exit 1
1284}
1285# _gitdir exists, so try loading the config
1286load_config 0
1287apply_config
1288
1289# v1.7.0 introduced --show-toplevel to return the canonical work-tree
1290if {[package vsatisfies $_git_version 1.7.0-]} {
1291        if { [is_Cygwin] } {
1292                catch {set _gitworktree [exec cygpath --windows [git rev-parse --show-toplevel]]}
1293        } else {
1294                set _gitworktree [git rev-parse --show-toplevel]
1295        }
1296} else {
1297        # try to set work tree from environment, core.worktree or use
1298        # cdup to obtain a relative path to the top of the worktree. If
1299        # run from the top, the ./ prefix ensures normalize expands pwd.
1300        if {[catch { set _gitworktree $env(GIT_WORK_TREE) }]} {
1301                set _gitworktree [get_config core.worktree]
1302                if {$_gitworktree eq ""} {
1303                        set _gitworktree [file normalize ./[git rev-parse --show-cdup]]
1304                }
1305        }
1306}
1307
1308if {$_prefix ne {}} {
1309        if {$_gitworktree eq {}} {
1310                regsub -all {[^/]+/} $_prefix ../ cdup
1311        } else {
1312                set cdup $_gitworktree
1313        }
1314        if {[catch {cd $cdup} err]} {
1315                catch {wm withdraw .}
1316                error_popup [strcat [mc "Cannot move to top of working directory:"] "\n\n$err"]
1317                exit 1
1318        }
1319        set _gitworktree [pwd]
1320        unset cdup
1321} elseif {![is_enabled bare]} {
1322        if {[is_bare]} {
1323                catch {wm withdraw .}
1324                error_popup [strcat [mc "Cannot use bare repository:"] "\n\n$_gitdir"]
1325                exit 1
1326        }
1327        if {$_gitworktree eq {}} {
1328                set _gitworktree [file dirname $_gitdir]
1329        }
1330        if {[catch {cd $_gitworktree} err]} {
1331                catch {wm withdraw .}
1332                error_popup [strcat [mc "No working directory"] " $_gitworktree:\n\n$err"]
1333                exit 1
1334        }
1335        set _gitworktree [pwd]
1336}
1337set _reponame [file split [file normalize $_gitdir]]
1338if {[lindex $_reponame end] eq {.git}} {
1339        set _reponame [lindex $_reponame end-1]
1340} else {
1341        set _reponame [lindex $_reponame end]
1342}
1343
1344set env(GIT_DIR) $_gitdir
1345set env(GIT_WORK_TREE) $_gitworktree
1346
1347######################################################################
1348##
1349## global init
1350
1351set current_diff_path {}
1352set current_diff_side {}
1353set diff_actions [list]
1354
1355set HEAD {}
1356set PARENT {}
1357set MERGE_HEAD [list]
1358set commit_type {}
1359set empty_tree {}
1360set current_branch {}
1361set is_detached 0
1362set current_diff_path {}
1363set is_3way_diff 0
1364set is_submodule_diff 0
1365set is_conflict_diff 0
1366set selected_commit_type new
1367set diff_empty_count 0
1368
1369set nullid "0000000000000000000000000000000000000000"
1370set nullid2 "0000000000000000000000000000000000000001"
1371
1372######################################################################
1373##
1374## task management
1375
1376set rescan_active 0
1377set diff_active 0
1378set last_clicked {}
1379
1380set disable_on_lock [list]
1381set index_lock_type none
1382
1383proc lock_index {type} {
1384        global index_lock_type disable_on_lock
1385
1386        if {$index_lock_type eq {none}} {
1387                set index_lock_type $type
1388                foreach w $disable_on_lock {
1389                        uplevel #0 $w disabled
1390                }
1391                return 1
1392        } elseif {$index_lock_type eq "begin-$type"} {
1393                set index_lock_type $type
1394                return 1
1395        }
1396        return 0
1397}
1398
1399proc unlock_index {} {
1400        global index_lock_type disable_on_lock
1401
1402        set index_lock_type none
1403        foreach w $disable_on_lock {
1404                uplevel #0 $w normal
1405        }
1406}
1407
1408######################################################################
1409##
1410## status
1411
1412proc repository_state {ctvar hdvar mhvar} {
1413        global current_branch
1414        upvar $ctvar ct $hdvar hd $mhvar mh
1415
1416        set mh [list]
1417
1418        load_current_branch
1419        if {[catch {set hd [git rev-parse --verify HEAD]}]} {
1420                set hd {}
1421                set ct initial
1422                return
1423        }
1424
1425        set merge_head [gitdir MERGE_HEAD]
1426        if {[file exists $merge_head]} {
1427                set ct merge
1428                set fd_mh [open $merge_head r]
1429                while {[gets $fd_mh line] >= 0} {
1430                        lappend mh $line
1431                }
1432                close $fd_mh
1433                return
1434        }
1435
1436        set ct normal
1437}
1438
1439proc PARENT {} {
1440        global PARENT empty_tree
1441
1442        set p [lindex $PARENT 0]
1443        if {$p ne {}} {
1444                return $p
1445        }
1446        if {$empty_tree eq {}} {
1447                set empty_tree [git mktree << {}]
1448        }
1449        return $empty_tree
1450}
1451
1452proc force_amend {} {
1453        global selected_commit_type
1454        global HEAD PARENT MERGE_HEAD commit_type
1455
1456        repository_state newType newHEAD newMERGE_HEAD
1457        set HEAD $newHEAD
1458        set PARENT $newHEAD
1459        set MERGE_HEAD $newMERGE_HEAD
1460        set commit_type $newType
1461
1462        set selected_commit_type amend
1463        do_select_commit_type
1464}
1465
1466proc rescan {after {honor_trustmtime 1}} {
1467        global HEAD PARENT MERGE_HEAD commit_type
1468        global ui_index ui_workdir ui_comm
1469        global rescan_active file_states
1470        global repo_config
1471
1472        if {$rescan_active > 0 || ![lock_index read]} return
1473
1474        repository_state newType newHEAD newMERGE_HEAD
1475        if {[string match amend* $commit_type]
1476                && $newType eq {normal}
1477                && $newHEAD eq $HEAD} {
1478        } else {
1479                set HEAD $newHEAD
1480                set PARENT $newHEAD
1481                set MERGE_HEAD $newMERGE_HEAD
1482                set commit_type $newType
1483        }
1484
1485        array unset file_states
1486
1487        if {!$::GITGUI_BCK_exists &&
1488                (![$ui_comm edit modified]
1489                || [string trim [$ui_comm get 0.0 end]] eq {})} {
1490                if {[string match amend* $commit_type]} {
1491                } elseif {[load_message GITGUI_MSG utf-8]} {
1492                } elseif {[run_prepare_commit_msg_hook]} {
1493                } elseif {[load_message MERGE_MSG]} {
1494                } elseif {[load_message SQUASH_MSG]} {
1495                }
1496                $ui_comm edit reset
1497                $ui_comm edit modified false
1498        }
1499
1500        if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
1501                rescan_stage2 {} $after
1502        } else {
1503                set rescan_active 1
1504                ui_status [mc "Refreshing file status..."]
1505                set fd_rf [git_read update-index \
1506                        -q \
1507                        --unmerged \
1508                        --ignore-missing \
1509                        --refresh \
1510                        ]
1511                fconfigure $fd_rf -blocking 0 -translation binary
1512                fileevent $fd_rf readable \
1513                        [list rescan_stage2 $fd_rf $after]
1514        }
1515}
1516
1517if {[is_Cygwin]} {
1518        set is_git_info_exclude {}
1519        proc have_info_exclude {} {
1520                global is_git_info_exclude
1521
1522                if {$is_git_info_exclude eq {}} {
1523                        if {[catch {exec test -f [gitdir info exclude]}]} {
1524                                set is_git_info_exclude 0
1525                        } else {
1526                                set is_git_info_exclude 1
1527                        }
1528                }
1529                return $is_git_info_exclude
1530        }
1531} else {
1532        proc have_info_exclude {} {
1533                return [file readable [gitdir info exclude]]
1534        }
1535}
1536
1537proc rescan_stage2 {fd after} {
1538        global rescan_active buf_rdi buf_rdf buf_rlo
1539
1540        if {$fd ne {}} {
1541                read $fd
1542                if {![eof $fd]} return
1543                close $fd
1544        }
1545
1546        if {[package vsatisfies $::_git_version 1.6.3-]} {
1547                set ls_others [list --exclude-standard]
1548        } else {
1549                set ls_others [list --exclude-per-directory=.gitignore]
1550                if {[have_info_exclude]} {
1551                        lappend ls_others "--exclude-from=[gitdir info exclude]"
1552                }
1553                set user_exclude [get_config core.excludesfile]
1554                if {$user_exclude ne {} && [file readable $user_exclude]} {
1555                        lappend ls_others "--exclude-from=[file normalize $user_exclude]"
1556                }
1557        }
1558
1559        set buf_rdi {}
1560        set buf_rdf {}
1561        set buf_rlo {}
1562
1563        set rescan_active 2
1564        ui_status [mc "Scanning for modified files ..."]
1565        if {[git-version >= "1.7.2"]} {
1566                set fd_di [git_read diff-index --cached --ignore-submodules=dirty -z [PARENT]]
1567        } else {
1568                set fd_di [git_read diff-index --cached -z [PARENT]]
1569        }
1570        set fd_df [git_read diff-files -z]
1571
1572        fconfigure $fd_di -blocking 0 -translation binary -encoding binary
1573        fconfigure $fd_df -blocking 0 -translation binary -encoding binary
1574
1575        fileevent $fd_di readable [list read_diff_index $fd_di $after]
1576        fileevent $fd_df readable [list read_diff_files $fd_df $after]
1577
1578        if {[is_config_true gui.displayuntracked]} {
1579                set fd_lo [eval git_read ls-files --others -z $ls_others]
1580                fconfigure $fd_lo -blocking 0 -translation binary -encoding binary
1581                fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
1582                incr rescan_active
1583        }
1584}
1585
1586proc load_message {file {encoding {}}} {
1587        global ui_comm
1588
1589        set f [gitdir $file]
1590        if {[file isfile $f]} {
1591                if {[catch {set fd [open $f r]}]} {
1592                        return 0
1593                }
1594                fconfigure $fd -eofchar {}
1595                if {$encoding ne {}} {
1596                        fconfigure $fd -encoding $encoding
1597                }
1598                set content [string trim [read $fd]]
1599                close $fd
1600                regsub -all -line {[ \r\t]+$} $content {} content
1601                $ui_comm delete 0.0 end
1602                $ui_comm insert end $content
1603                return 1
1604        }
1605        return 0
1606}
1607
1608proc run_prepare_commit_msg_hook {} {
1609        global pch_error
1610
1611        # prepare-commit-msg requires PREPARE_COMMIT_MSG exist.  From git-gui
1612        # it will be .git/MERGE_MSG (merge), .git/SQUASH_MSG (squash), or an
1613        # empty file but existent file.
1614
1615        set fd_pcm [open [gitdir PREPARE_COMMIT_MSG] a]
1616
1617        if {[file isfile [gitdir MERGE_MSG]]} {
1618                set pcm_source "merge"
1619                set fd_mm [open [gitdir MERGE_MSG] r]
1620                puts -nonewline $fd_pcm [read $fd_mm]
1621                close $fd_mm
1622        } elseif {[file isfile [gitdir SQUASH_MSG]]} {
1623                set pcm_source "squash"
1624                set fd_sm [open [gitdir SQUASH_MSG] r]
1625                puts -nonewline $fd_pcm [read $fd_sm]
1626                close $fd_sm
1627        } else {
1628                set pcm_source ""
1629        }
1630
1631        close $fd_pcm
1632
1633        set fd_ph [githook_read prepare-commit-msg \
1634                        [gitdir PREPARE_COMMIT_MSG] $pcm_source]
1635        if {$fd_ph eq {}} {
1636                catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1637                return 0;
1638        }
1639
1640        ui_status [mc "Calling prepare-commit-msg hook..."]
1641        set pch_error {}
1642
1643        fconfigure $fd_ph -blocking 0 -translation binary -eofchar {}
1644        fileevent $fd_ph readable \
1645                [list prepare_commit_msg_hook_wait $fd_ph]
1646
1647        return 1;
1648}
1649
1650proc prepare_commit_msg_hook_wait {fd_ph} {
1651        global pch_error
1652
1653        append pch_error [read $fd_ph]
1654        fconfigure $fd_ph -blocking 1
1655        if {[eof $fd_ph]} {
1656                if {[catch {close $fd_ph}]} {
1657                        ui_status [mc "Commit declined by prepare-commit-msg hook."]
1658                        hook_failed_popup prepare-commit-msg $pch_error
1659                        catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1660                        exit 1
1661                } else {
1662                        load_message PREPARE_COMMIT_MSG
1663                }
1664                set pch_error {}
1665                catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1666                return
1667        }
1668        fconfigure $fd_ph -blocking 0
1669        catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1670}
1671
1672proc read_diff_index {fd after} {
1673        global buf_rdi
1674
1675        append buf_rdi [read $fd]
1676        set c 0
1677        set n [string length $buf_rdi]
1678        while {$c < $n} {
1679                set z1 [string first "\0" $buf_rdi $c]
1680                if {$z1 == -1} break
1681                incr z1
1682                set z2 [string first "\0" $buf_rdi $z1]
1683                if {$z2 == -1} break
1684
1685                incr c
1686                set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
1687                set p [string range $buf_rdi $z1 [expr {$z2 - 1}]]
1688                merge_state \
1689                        [encoding convertfrom $p] \
1690                        [lindex $i 4]? \
1691                        [list [lindex $i 0] [lindex $i 2]] \
1692                        [list]
1693                set c $z2
1694                incr c
1695        }
1696        if {$c < $n} {
1697                set buf_rdi [string range $buf_rdi $c end]
1698        } else {
1699                set buf_rdi {}
1700        }
1701
1702        rescan_done $fd buf_rdi $after
1703}
1704
1705proc read_diff_files {fd after} {
1706        global buf_rdf
1707
1708        append buf_rdf [read $fd]
1709        set c 0
1710        set n [string length $buf_rdf]
1711        while {$c < $n} {
1712                set z1 [string first "\0" $buf_rdf $c]
1713                if {$z1 == -1} break
1714                incr z1
1715                set z2 [string first "\0" $buf_rdf $z1]
1716                if {$z2 == -1} break
1717
1718                incr c
1719                set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
1720                set p [string range $buf_rdf $z1 [expr {$z2 - 1}]]
1721                merge_state \
1722                        [encoding convertfrom $p] \
1723                        ?[lindex $i 4] \
1724                        [list] \
1725                        [list [lindex $i 0] [lindex $i 2]]
1726                set c $z2
1727                incr c
1728        }
1729        if {$c < $n} {
1730                set buf_rdf [string range $buf_rdf $c end]
1731        } else {
1732                set buf_rdf {}
1733        }
1734
1735        rescan_done $fd buf_rdf $after
1736}
1737
1738proc read_ls_others {fd after} {
1739        global buf_rlo
1740
1741        append buf_rlo [read $fd]
1742        set pck [split $buf_rlo "\0"]
1743        set buf_rlo [lindex $pck end]
1744        foreach p [lrange $pck 0 end-1] {
1745                set p [encoding convertfrom $p]
1746                if {[string index $p end] eq {/}} {
1747                        set p [string range $p 0 end-1]
1748                }
1749                merge_state $p ?O
1750        }
1751        rescan_done $fd buf_rlo $after
1752}
1753
1754proc rescan_done {fd buf after} {
1755        global rescan_active current_diff_path
1756        global file_states repo_config
1757        upvar $buf to_clear
1758
1759        if {![eof $fd]} return
1760        set to_clear {}
1761        close $fd
1762        if {[incr rescan_active -1] > 0} return
1763
1764        prune_selection
1765        unlock_index
1766        display_all_files
1767        if {$current_diff_path ne {}} { reshow_diff $after }
1768        if {$current_diff_path eq {}} { select_first_diff $after }
1769}
1770
1771proc prune_selection {} {
1772        global file_states selected_paths
1773
1774        foreach path [array names selected_paths] {
1775                if {[catch {set still_here $file_states($path)}]} {
1776                        unset selected_paths($path)
1777                }
1778        }
1779}
1780
1781######################################################################
1782##
1783## ui helpers
1784
1785proc mapicon {w state path} {
1786        global all_icons
1787
1788        if {[catch {set r $all_icons($state$w)}]} {
1789                puts "error: no icon for $w state={$state} $path"
1790                return file_plain
1791        }
1792        return $r
1793}
1794
1795proc mapdesc {state path} {
1796        global all_descs
1797
1798        if {[catch {set r $all_descs($state)}]} {
1799                puts "error: no desc for state={$state} $path"
1800                return $state
1801        }
1802        return $r
1803}
1804
1805proc ui_status {msg} {
1806        global main_status
1807        if {[info exists main_status]} {
1808                $main_status show $msg
1809        }
1810}
1811
1812proc ui_ready {{test {}}} {
1813        global main_status
1814        if {[info exists main_status]} {
1815                $main_status show [mc "Ready."] $test
1816        }
1817}
1818
1819proc escape_path {path} {
1820        regsub -all {\\} $path "\\\\" path
1821        regsub -all "\n" $path "\\n" path
1822        return $path
1823}
1824
1825proc short_path {path} {
1826        return [escape_path [lindex [file split $path] end]]
1827}
1828
1829set next_icon_id 0
1830set null_sha1 [string repeat 0 40]
1831
1832proc merge_state {path new_state {head_info {}} {index_info {}}} {
1833        global file_states next_icon_id null_sha1
1834
1835        set s0 [string index $new_state 0]
1836        set s1 [string index $new_state 1]
1837
1838        if {[catch {set info $file_states($path)}]} {
1839                set state __
1840                set icon n[incr next_icon_id]
1841        } else {
1842                set state [lindex $info 0]
1843                set icon [lindex $info 1]
1844                if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1845                if {$index_info eq {}} {set index_info [lindex $info 3]}
1846        }
1847
1848        if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1849        elseif {$s0 eq {_}} {set s0 _}
1850
1851        if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1852        elseif {$s1 eq {_}} {set s1 _}
1853
1854        if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1855                set head_info [list 0 $null_sha1]
1856        } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1857                && $head_info eq {}} {
1858                set head_info $index_info
1859        } elseif {$s0 eq {_} && [string index $state 0] ne {_}} {
1860                set index_info $head_info
1861                set head_info {}
1862        }
1863
1864        set file_states($path) [list $s0$s1 $icon \
1865                $head_info $index_info \
1866                ]
1867        return $state
1868}
1869
1870proc display_file_helper {w path icon_name old_m new_m} {
1871        global file_lists
1872
1873        if {$new_m eq {_}} {
1874                set lno [lsearch -sorted -exact $file_lists($w) $path]
1875                if {$lno >= 0} {
1876                        set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1877                        incr lno
1878                        $w conf -state normal
1879                        $w delete $lno.0 [expr {$lno + 1}].0
1880                        $w conf -state disabled
1881                }
1882        } elseif {$old_m eq {_} && $new_m ne {_}} {
1883                lappend file_lists($w) $path
1884                set file_lists($w) [lsort -unique $file_lists($w)]
1885                set lno [lsearch -sorted -exact $file_lists($w) $path]
1886                incr lno
1887                $w conf -state normal
1888                $w image create $lno.0 \
1889                        -align center -padx 5 -pady 1 \
1890                        -name $icon_name \
1891                        -image [mapicon $w $new_m $path]
1892                $w insert $lno.1 "[escape_path $path]\n"
1893                $w conf -state disabled
1894        } elseif {$old_m ne $new_m} {
1895                $w conf -state normal
1896                $w image conf $icon_name -image [mapicon $w $new_m $path]
1897                $w conf -state disabled
1898        }
1899}
1900
1901proc display_file {path state} {
1902        global file_states selected_paths
1903        global ui_index ui_workdir
1904
1905        set old_m [merge_state $path $state]
1906        set s $file_states($path)
1907        set new_m [lindex $s 0]
1908        set icon_name [lindex $s 1]
1909
1910        set o [string index $old_m 0]
1911        set n [string index $new_m 0]
1912        if {$o eq {U}} {
1913                set o _
1914        }
1915        if {$n eq {U}} {
1916                set n _
1917        }
1918        display_file_helper     $ui_index $path $icon_name $o $n
1919
1920        if {[string index $old_m 0] eq {U}} {
1921                set o U
1922        } else {
1923                set o [string index $old_m 1]
1924        }
1925        if {[string index $new_m 0] eq {U}} {
1926                set n U
1927        } else {
1928                set n [string index $new_m 1]
1929        }
1930        display_file_helper     $ui_workdir $path $icon_name $o $n
1931
1932        if {$new_m eq {__}} {
1933                unset file_states($path)
1934                catch {unset selected_paths($path)}
1935        }
1936}
1937
1938proc display_all_files_helper {w path icon_name m} {
1939        global file_lists
1940
1941        lappend file_lists($w) $path
1942        set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1943        $w image create end \
1944                -align center -padx 5 -pady 1 \
1945                -name $icon_name \
1946                -image [mapicon $w $m $path]
1947        $w insert end "[escape_path $path]\n"
1948}
1949
1950set files_warning 0
1951proc display_all_files {} {
1952        global ui_index ui_workdir
1953        global file_states file_lists
1954        global last_clicked
1955        global files_warning
1956
1957        $ui_index conf -state normal
1958        $ui_workdir conf -state normal
1959
1960        $ui_index delete 0.0 end
1961        $ui_workdir delete 0.0 end
1962        set last_clicked {}
1963
1964        set file_lists($ui_index) [list]
1965        set file_lists($ui_workdir) [list]
1966
1967        set to_display [lsort [array names file_states]]
1968        set display_limit [get_config gui.maxfilesdisplayed]
1969        if {[llength $to_display] > $display_limit} {
1970                if {!$files_warning} {
1971                        # do not repeatedly warn:
1972                        set files_warning 1
1973                        info_popup [mc "Displaying only %s of %s files." \
1974                                $display_limit [llength $to_display]]
1975                }
1976                set to_display [lrange $to_display 0 [expr {$display_limit-1}]]
1977        }
1978        foreach path $to_display {
1979                set s $file_states($path)
1980                set m [lindex $s 0]
1981                set icon_name [lindex $s 1]
1982
1983                set s [string index $m 0]
1984                if {$s ne {U} && $s ne {_}} {
1985                        display_all_files_helper $ui_index $path \
1986                                $icon_name $s
1987                }
1988
1989                if {[string index $m 0] eq {U}} {
1990                        set s U
1991                } else {
1992                        set s [string index $m 1]
1993                }
1994                if {$s ne {_}} {
1995                        display_all_files_helper $ui_workdir $path \
1996                                $icon_name $s
1997                }
1998        }
1999
2000        $ui_index conf -state disabled
2001        $ui_workdir conf -state disabled
2002}
2003
2004######################################################################
2005##
2006## icons
2007
2008set filemask {
2009#define mask_width 14
2010#define mask_height 15
2011static unsigned char mask_bits[] = {
2012   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2013   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2014   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
2015}
2016
2017image create bitmap file_plain -background white -foreground black -data {
2018#define plain_width 14
2019#define plain_height 15
2020static unsigned char plain_bits[] = {
2021   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2022   0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
2023   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2024} -maskdata $filemask
2025
2026image create bitmap file_mod -background white -foreground blue -data {
2027#define mod_width 14
2028#define mod_height 15
2029static unsigned char mod_bits[] = {
2030   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
2031   0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2032   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2033} -maskdata $filemask
2034
2035image create bitmap file_fulltick -background white -foreground "#007000" -data {
2036#define file_fulltick_width 14
2037#define file_fulltick_height 15
2038static unsigned char file_fulltick_bits[] = {
2039   0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
2040   0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
2041   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2042} -maskdata $filemask
2043
2044image create bitmap file_question -background white -foreground black -data {
2045#define file_question_width 14
2046#define file_question_height 15
2047static unsigned char file_question_bits[] = {
2048   0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
2049   0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
2050   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2051} -maskdata $filemask
2052
2053image create bitmap file_removed -background white -foreground red -data {
2054#define file_removed_width 14
2055#define file_removed_height 15
2056static unsigned char file_removed_bits[] = {
2057   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2058   0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
2059   0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
2060} -maskdata $filemask
2061
2062image create bitmap file_merge -background white -foreground blue -data {
2063#define file_merge_width 14
2064#define file_merge_height 15
2065static unsigned char file_merge_bits[] = {
2066   0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
2067   0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2068   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2069} -maskdata $filemask
2070
2071image create bitmap file_statechange -background white -foreground green -data {
2072#define file_statechange_width 14
2073#define file_statechange_height 15
2074static unsigned char file_statechange_bits[] = {
2075   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x62, 0x10,
2076   0x62, 0x10, 0xba, 0x11, 0xba, 0x11, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10,
2077   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2078} -maskdata $filemask
2079
2080set ui_index .vpane.files.index.list
2081set ui_workdir .vpane.files.workdir.list
2082
2083set all_icons(_$ui_index)   file_plain
2084set all_icons(A$ui_index)   file_plain
2085set all_icons(M$ui_index)   file_fulltick
2086set all_icons(D$ui_index)   file_removed
2087set all_icons(U$ui_index)   file_merge
2088set all_icons(T$ui_index)   file_statechange
2089
2090set all_icons(_$ui_workdir) file_plain
2091set all_icons(M$ui_workdir) file_mod
2092set all_icons(D$ui_workdir) file_question
2093set all_icons(U$ui_workdir) file_merge
2094set all_icons(O$ui_workdir) file_plain
2095set all_icons(T$ui_workdir) file_statechange
2096
2097set max_status_desc 0
2098foreach i {
2099                {__ {mc "Unmodified"}}
2100
2101                {_M {mc "Modified, not staged"}}
2102                {M_ {mc "Staged for commit"}}
2103                {MM {mc "Portions staged for commit"}}
2104                {MD {mc "Staged for commit, missing"}}
2105
2106                {_T {mc "File type changed, not staged"}}
2107                {MT {mc "File type changed, old type staged for commit"}}
2108                {AT {mc "File type changed, old type staged for commit"}}
2109                {T_ {mc "File type changed, staged"}}
2110                {TM {mc "File type change staged, modification not staged"}}
2111                {TD {mc "File type change staged, file missing"}}
2112
2113                {_O {mc "Untracked, not staged"}}
2114                {A_ {mc "Staged for commit"}}
2115                {AM {mc "Portions staged for commit"}}
2116                {AD {mc "Staged for commit, missing"}}
2117
2118                {_D {mc "Missing"}}
2119                {D_ {mc "Staged for removal"}}
2120                {DO {mc "Staged for removal, still present"}}
2121
2122                {_U {mc "Requires merge resolution"}}
2123                {U_ {mc "Requires merge resolution"}}
2124                {UU {mc "Requires merge resolution"}}
2125                {UM {mc "Requires merge resolution"}}
2126                {UD {mc "Requires merge resolution"}}
2127                {UT {mc "Requires merge resolution"}}
2128        } {
2129        set text [eval [lindex $i 1]]
2130        if {$max_status_desc < [string length $text]} {
2131                set max_status_desc [string length $text]
2132        }
2133        set all_descs([lindex $i 0]) $text
2134}
2135unset i
2136
2137######################################################################
2138##
2139## util
2140
2141proc scrollbar2many {list mode args} {
2142        foreach w $list {eval $w $mode $args}
2143}
2144
2145proc many2scrollbar {list mode sb top bottom} {
2146        $sb set $top $bottom
2147        foreach w $list {$w $mode moveto $top}
2148}
2149
2150proc incr_font_size {font {amt 1}} {
2151        set sz [font configure $font -size]
2152        incr sz $amt
2153        font configure $font -size $sz
2154        font configure ${font}bold -size $sz
2155        font configure ${font}italic -size $sz
2156}
2157
2158######################################################################
2159##
2160## ui commands
2161
2162set starting_gitk_msg [mc "Starting gitk... please wait..."]
2163
2164proc do_gitk {revs {is_submodule false}} {
2165        global current_diff_path file_states current_diff_side ui_index
2166        global _gitdir _gitworktree
2167
2168        # -- Always start gitk through whatever we were loaded with.  This
2169        #    lets us bypass using shell process on Windows systems.
2170        #
2171        set exe [_which gitk -script]
2172        set cmd [list [info nameofexecutable] $exe]
2173        if {$exe eq {}} {
2174                error_popup [mc "Couldn't find gitk in PATH"]
2175        } else {
2176                global env
2177
2178                set pwd [pwd]
2179
2180                if {!$is_submodule} {
2181                        if {![is_bare]} {
2182                                cd $_gitworktree
2183                        }
2184                } else {
2185                        cd $current_diff_path
2186                        if {$revs eq {--}} {
2187                                set s $file_states($current_diff_path)
2188                                set old_sha1 {}
2189                                set new_sha1 {}
2190                                switch -glob -- [lindex $s 0] {
2191                                M_ { set old_sha1 [lindex [lindex $s 2] 1] }
2192                                _M { set old_sha1 [lindex [lindex $s 3] 1] }
2193                                MM {
2194                                        if {$current_diff_side eq $ui_index} {
2195                                                set old_sha1 [lindex [lindex $s 2] 1]
2196                                                set new_sha1 [lindex [lindex $s 3] 1]
2197                                        } else {
2198                                                set old_sha1 [lindex [lindex $s 3] 1]
2199                                        }
2200                                }
2201                                }
2202                                set revs $old_sha1...$new_sha1
2203                        }
2204                        # GIT_DIR and GIT_WORK_TREE for the submodule are not the ones
2205                        # we've been using for the main repository, so unset them.
2206                        # TODO we could make life easier (start up faster?) for gitk
2207                        # by setting these to the appropriate values to allow gitk
2208                        # to skip the heuristics to find their proper value
2209                        unset env(GIT_DIR)
2210                        unset env(GIT_WORK_TREE)
2211                }
2212                eval exec $cmd $revs "--" "--" &
2213
2214                set env(GIT_DIR) $_gitdir
2215                set env(GIT_WORK_TREE) $_gitworktree
2216                cd $pwd
2217
2218                ui_status $::starting_gitk_msg
2219                after 10000 {
2220                        ui_ready $starting_gitk_msg
2221                }
2222        }
2223}
2224
2225proc do_git_gui {} {
2226        global current_diff_path
2227
2228        # -- Always start git gui through whatever we were loaded with.  This
2229        #    lets us bypass using shell process on Windows systems.
2230        #
2231        set exe [list [_which git]]
2232        if {$exe eq {}} {
2233                error_popup [mc "Couldn't find git gui in PATH"]
2234        } else {
2235                global env
2236                global _gitdir _gitworktree
2237
2238                # see note in do_gitk about unsetting these vars when
2239                # running tools in a submodule
2240                unset env(GIT_DIR)
2241                unset env(GIT_WORK_TREE)
2242
2243                set pwd [pwd]
2244                cd $current_diff_path
2245
2246                eval exec $exe gui &
2247
2248                set env(GIT_DIR) $_gitdir
2249                set env(GIT_WORK_TREE) $_gitworktree
2250                cd $pwd
2251
2252                ui_status $::starting_gitk_msg
2253                after 10000 {
2254                        ui_ready $starting_gitk_msg
2255                }
2256        }
2257}
2258
2259proc do_explore {} {
2260        global _gitworktree
2261        set explorer {}
2262        if {[is_Cygwin] || [is_Windows]} {
2263                set explorer "explorer.exe"
2264        } elseif {[is_MacOSX]} {
2265                set explorer "open"
2266        } else {
2267                # freedesktop.org-conforming system is our best shot
2268                set explorer "xdg-open"
2269        }
2270        eval exec $explorer [list [file nativename $_gitworktree]] &
2271}
2272
2273set is_quitting 0
2274set ret_code    1
2275
2276proc terminate_me {win} {
2277        global ret_code
2278        if {$win ne {.}} return
2279        exit $ret_code
2280}
2281
2282proc do_quit {{rc {1}}} {
2283        global ui_comm is_quitting repo_config commit_type
2284        global GITGUI_BCK_exists GITGUI_BCK_i
2285        global ui_comm_spell
2286        global ret_code use_ttk
2287
2288        if {$is_quitting} return
2289        set is_quitting 1
2290
2291        if {[winfo exists $ui_comm]} {
2292                # -- Stash our current commit buffer.
2293                #
2294                set save [gitdir GITGUI_MSG]
2295                if {$GITGUI_BCK_exists && ![$ui_comm edit modified]} {
2296                        file rename -force [gitdir GITGUI_BCK] $save
2297                        set GITGUI_BCK_exists 0
2298                } else {
2299                        set msg [string trim [$ui_comm get 0.0 end]]
2300                        regsub -all -line {[ \r\t]+$} $msg {} msg
2301                        if {(![string match amend* $commit_type]
2302                                || [$ui_comm edit modified])
2303                                && $msg ne {}} {
2304                                catch {
2305                                        set fd [open $save w]
2306                                        fconfigure $fd -encoding utf-8
2307                                        puts -nonewline $fd $msg
2308                                        close $fd
2309                                }
2310                        } else {
2311                                catch {file delete $save}
2312                        }
2313                }
2314
2315                # -- Cancel our spellchecker if its running.
2316                #
2317                if {[info exists ui_comm_spell]} {
2318                        $ui_comm_spell stop
2319                }
2320
2321                # -- Remove our editor backup, its not needed.
2322                #
2323                after cancel $GITGUI_BCK_i
2324                if {$GITGUI_BCK_exists} {
2325                        catch {file delete [gitdir GITGUI_BCK]}
2326                }
2327
2328                # -- Stash our current window geometry into this repository.
2329                #
2330                set cfg_wmstate [wm state .]
2331                if {[catch {set rc_wmstate $repo_config(gui.wmstate)}]} {
2332                        set rc_wmstate {}
2333                }
2334                if {$cfg_wmstate ne $rc_wmstate} {
2335                        catch {git config gui.wmstate $cfg_wmstate}
2336                }
2337                if {$cfg_wmstate eq {zoomed}} {
2338                        # on Windows wm geometry will lie about window
2339                        # position (but not size) when window is zoomed
2340                        # restore the window before querying wm geometry
2341                        wm state . normal
2342                }
2343                set cfg_geometry [list]
2344                lappend cfg_geometry [wm geometry .]
2345                if {$use_ttk} {
2346                        lappend cfg_geometry [.vpane sashpos 0]
2347                        lappend cfg_geometry [.vpane.files sashpos 0]
2348                } else {
2349                        lappend cfg_geometry [lindex [.vpane sash coord 0] 0]
2350                        lappend cfg_geometry [lindex [.vpane.files sash coord 0] 1]
2351                }
2352                if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
2353                        set rc_geometry {}
2354                }
2355                if {$cfg_geometry ne $rc_geometry} {
2356                        catch {git config gui.geometry $cfg_geometry}
2357                }
2358        }
2359
2360        set ret_code $rc
2361
2362        # Briefly enable send again, working around Tk bug
2363        # http://sourceforge.net/tracker/?func=detail&atid=112997&aid=1821174&group_id=12997
2364        tk appname [appname]
2365
2366        destroy .
2367}
2368
2369proc do_rescan {} {
2370        rescan ui_ready
2371}
2372
2373proc ui_do_rescan {} {
2374        rescan {force_first_diff ui_ready}
2375}
2376
2377proc do_commit {} {
2378        commit_tree
2379}
2380
2381proc next_diff {{after {}}} {
2382        global next_diff_p next_diff_w next_diff_i
2383        show_diff $next_diff_p $next_diff_w {} {} $after
2384}
2385
2386proc find_anchor_pos {lst name} {
2387        set lid [lsearch -sorted -exact $lst $name]
2388
2389        if {$lid == -1} {
2390                set lid 0
2391                foreach lname $lst {
2392                        if {$lname >= $name} break
2393                        incr lid
2394                }
2395        }
2396
2397        return $lid
2398}
2399
2400proc find_file_from {flist idx delta path mmask} {
2401        global file_states
2402
2403        set len [llength $flist]
2404        while {$idx >= 0 && $idx < $len} {
2405                set name [lindex $flist $idx]
2406
2407                if {$name ne $path && [info exists file_states($name)]} {
2408                        set state [lindex $file_states($name) 0]
2409
2410                        if {$mmask eq {} || [regexp $mmask $state]} {
2411                                return $idx
2412                        }
2413                }
2414
2415                incr idx $delta
2416        }
2417
2418        return {}
2419}
2420
2421proc find_next_diff {w path {lno {}} {mmask {}}} {
2422        global next_diff_p next_diff_w next_diff_i
2423        global file_lists ui_index ui_workdir
2424
2425        set flist $file_lists($w)
2426        if {$lno eq {}} {
2427                set lno [find_anchor_pos $flist $path]
2428        } else {
2429                incr lno -1
2430        }
2431
2432        if {$mmask ne {} && ![regexp {(^\^)|(\$$)} $mmask]} {
2433                if {$w eq $ui_index} {
2434                        set mmask "^$mmask"
2435                } else {
2436                        set mmask "$mmask\$"
2437                }
2438        }
2439
2440        set idx [find_file_from $flist $lno 1 $path $mmask]
2441        if {$idx eq {}} {
2442                incr lno -1
2443                set idx [find_file_from $flist $lno -1 $path $mmask]
2444        }
2445
2446        if {$idx ne {}} {
2447                set next_diff_w $w
2448                set next_diff_p [lindex $flist $idx]
2449                set next_diff_i [expr {$idx+1}]
2450                return 1
2451        } else {
2452                return 0
2453        }
2454}
2455
2456proc next_diff_after_action {w path {lno {}} {mmask {}}} {
2457        global current_diff_path
2458
2459        if {$path ne $current_diff_path} {
2460                return {}
2461        } elseif {[find_next_diff $w $path $lno $mmask]} {
2462                return {next_diff;}
2463        } else {
2464                return {reshow_diff;}
2465        }
2466}
2467
2468proc select_first_diff {after} {
2469        global ui_workdir
2470
2471        if {[find_next_diff $ui_workdir {} 1 {^_?U}] ||
2472            [find_next_diff $ui_workdir {} 1 {[^O]$}]} {
2473                next_diff $after
2474        } else {
2475                uplevel #0 $after
2476        }
2477}
2478
2479proc force_first_diff {after} {
2480        global ui_workdir current_diff_path file_states
2481
2482        if {[info exists file_states($current_diff_path)]} {
2483                set state [lindex $file_states($current_diff_path) 0]
2484        } else {
2485                set state {OO}
2486        }
2487
2488        set reselect 0
2489        if {[string first {U} $state] >= 0} {
2490                # Already a conflict, do nothing
2491        } elseif {[find_next_diff $ui_workdir $current_diff_path {} {^_?U}]} {
2492                set reselect 1
2493        } elseif {[string index $state 1] ne {O}} {
2494                # Already a diff & no conflicts, do nothing
2495        } elseif {[find_next_diff $ui_workdir $current_diff_path {} {[^O]$}]} {
2496                set reselect 1
2497        }
2498
2499        if {$reselect} {
2500                next_diff $after
2501        } else {
2502                uplevel #0 $after
2503        }
2504}
2505
2506proc toggle_or_diff {w x y} {
2507        global file_states file_lists current_diff_path ui_index ui_workdir
2508        global last_clicked selected_paths
2509
2510        set pos [split [$w index @$x,$y] .]
2511        set lno [lindex $pos 0]
2512        set col [lindex $pos 1]
2513        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2514        if {$path eq {}} {
2515                set last_clicked {}
2516                return
2517        }
2518
2519        set last_clicked [list $w $lno]
2520        array unset selected_paths
2521        $ui_index tag remove in_sel 0.0 end
2522        $ui_workdir tag remove in_sel 0.0 end
2523
2524        # Determine the state of the file
2525        if {[info exists file_states($path)]} {
2526                set state [lindex $file_states($path) 0]
2527        } else {
2528                set state {__}
2529        }
2530
2531        # Restage the file, or simply show the diff
2532        if {$col == 0 && $y > 1} {
2533                # Conflicts need special handling
2534                if {[string first {U} $state] >= 0} {
2535                        # $w must always be $ui_workdir, but...
2536                        if {$w ne $ui_workdir} { set lno {} }
2537                        merge_stage_workdir $path $lno
2538                        return
2539                }
2540
2541                if {[string index $state 1] eq {O}} {
2542                        set mmask {}
2543                } else {
2544                        set mmask {[^O]}
2545                }
2546
2547                set after [next_diff_after_action $w $path $lno $mmask]
2548
2549                if {$w eq $ui_index} {
2550                        update_indexinfo \
2551                                "Unstaging [short_path $path] from commit" \
2552                                [list $path] \
2553                                [concat $after [list ui_ready]]
2554                } elseif {$w eq $ui_workdir} {
2555                        update_index \
2556                                "Adding [short_path $path]" \
2557                                [list $path] \
2558                                [concat $after [list ui_ready]]
2559                }
2560        } else {
2561                set selected_paths($path) 1
2562                show_diff $path $w $lno
2563        }
2564}
2565
2566proc add_one_to_selection {w x y} {
2567        global file_lists last_clicked selected_paths
2568
2569        set lno [lindex [split [$w index @$x,$y] .] 0]
2570        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2571        if {$path eq {}} {
2572                set last_clicked {}
2573                return
2574        }
2575
2576        if {$last_clicked ne {}
2577                && [lindex $last_clicked 0] ne $w} {
2578                array unset selected_paths
2579                [lindex $last_clicked 0] tag remove in_sel 0.0 end
2580        }
2581
2582        set last_clicked [list $w $lno]
2583        if {[catch {set in_sel $selected_paths($path)}]} {
2584                set in_sel 0
2585        }
2586        if {$in_sel} {
2587                unset selected_paths($path)
2588                $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
2589        } else {
2590                set selected_paths($path) 1
2591                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
2592        }
2593}
2594
2595proc add_range_to_selection {w x y} {
2596        global file_lists last_clicked selected_paths
2597
2598        if {[lindex $last_clicked 0] ne $w} {
2599                toggle_or_diff $w $x $y
2600                return
2601        }
2602
2603        set lno [lindex [split [$w index @$x,$y] .] 0]
2604        set lc [lindex $last_clicked 1]
2605        if {$lc < $lno} {
2606                set begin $lc
2607                set end $lno
2608        } else {
2609                set begin $lno
2610                set end $lc
2611        }
2612
2613        foreach path [lrange $file_lists($w) \
2614                [expr {$begin - 1}] \
2615                [expr {$end - 1}]] {
2616                set selected_paths($path) 1
2617        }
2618        $w tag add in_sel $begin.0 [expr {$end + 1}].0
2619}
2620
2621proc show_more_context {} {
2622        global repo_config
2623        if {$repo_config(gui.diffcontext) < 99} {
2624                incr repo_config(gui.diffcontext)
2625                reshow_diff
2626        }
2627}
2628
2629proc show_less_context {} {
2630        global repo_config
2631        if {$repo_config(gui.diffcontext) > 1} {
2632                incr repo_config(gui.diffcontext) -1
2633                reshow_diff
2634        }
2635}
2636
2637######################################################################
2638##
2639## ui construction
2640
2641set ui_comm {}
2642
2643# -- Menu Bar
2644#
2645menu .mbar -tearoff 0
2646if {[is_MacOSX]} {
2647        # -- Apple Menu (Mac OS X only)
2648        #
2649        .mbar add cascade -label Apple -menu .mbar.apple
2650        menu .mbar.apple
2651}
2652.mbar add cascade -label [mc Repository] -menu .mbar.repository
2653.mbar add cascade -label [mc Edit] -menu .mbar.edit
2654if {[is_enabled branch]} {
2655        .mbar add cascade -label [mc Branch] -menu .mbar.branch
2656}
2657if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2658        .mbar add cascade -label [mc Commit@@noun] -menu .mbar.commit
2659}
2660if {[is_enabled transport]} {
2661        .mbar add cascade -label [mc Merge] -menu .mbar.merge
2662        .mbar add cascade -label [mc Remote] -menu .mbar.remote
2663}
2664if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2665        .mbar add cascade -label [mc Tools] -menu .mbar.tools
2666}
2667
2668# -- Repository Menu
2669#
2670menu .mbar.repository
2671
2672if {![is_bare]} {
2673        .mbar.repository add command \
2674                -label [mc "Explore Working Copy"] \
2675                -command {do_explore}
2676}
2677
2678if {[is_Windows]} {
2679        .mbar.repository add command \
2680                -label [mc "Git Bash"] \
2681                -command {eval exec [auto_execok start] \
2682                                          [list "Git Bash" bash --login -l &]}
2683}
2684
2685if {[is_Windows] || ![is_bare]} {
2686        .mbar.repository add separator
2687}
2688
2689.mbar.repository add command \
2690        -label [mc "Browse Current Branch's Files"] \
2691        -command {browser::new $current_branch}
2692set ui_browse_current [.mbar.repository index last]
2693.mbar.repository add command \
2694        -label [mc "Browse Branch Files..."] \
2695        -command browser_open::dialog
2696.mbar.repository add separator
2697
2698.mbar.repository add command \
2699        -label [mc "Visualize Current Branch's History"] \
2700        -command {do_gitk $current_branch}
2701set ui_visualize_current [.mbar.repository index last]
2702.mbar.repository add command \
2703        -label [mc "Visualize All Branch History"] \
2704        -command {do_gitk --all}
2705.mbar.repository add separator
2706
2707proc current_branch_write {args} {
2708        global current_branch
2709        .mbar.repository entryconf $::ui_browse_current \
2710                -label [mc "Browse %s's Files" $current_branch]
2711        .mbar.repository entryconf $::ui_visualize_current \
2712                -label [mc "Visualize %s's History" $current_branch]
2713}
2714trace add variable current_branch write current_branch_write
2715
2716if {[is_enabled multicommit]} {
2717        .mbar.repository add command -label [mc "Database Statistics"] \
2718                -command do_stats
2719
2720        .mbar.repository add command -label [mc "Compress Database"] \
2721                -command do_gc
2722
2723        .mbar.repository add command -label [mc "Verify Database"] \
2724                -command do_fsck_objects
2725
2726        .mbar.repository add separator
2727
2728        if {[is_Cygwin]} {
2729                .mbar.repository add command \
2730                        -label [mc "Create Desktop Icon"] \
2731                        -command do_cygwin_shortcut
2732        } elseif {[is_Windows]} {
2733                .mbar.repository add command \
2734                        -label [mc "Create Desktop Icon"] \
2735                        -command do_windows_shortcut
2736        } elseif {[is_MacOSX]} {
2737                .mbar.repository add command \
2738                        -label [mc "Create Desktop Icon"] \
2739                        -command do_macosx_app
2740        }
2741}
2742
2743if {[is_MacOSX]} {
2744        proc ::tk::mac::Quit {args} { do_quit }
2745} else {
2746        .mbar.repository add command -label [mc Quit] \
2747                -command do_quit \
2748                -accelerator $M1T-Q
2749}
2750
2751# -- Edit Menu
2752#
2753menu .mbar.edit
2754.mbar.edit add command -label [mc Undo] \
2755        -command {catch {[focus] edit undo}} \
2756        -accelerator $M1T-Z
2757.mbar.edit add command -label [mc Redo] \
2758        -command {catch {[focus] edit redo}} \
2759        -accelerator $M1T-Y
2760.mbar.edit add separator
2761.mbar.edit add command -label [mc Cut] \
2762        -command {catch {tk_textCut [focus]}} \
2763        -accelerator $M1T-X
2764.mbar.edit add command -label [mc Copy] \
2765        -command {catch {tk_textCopy [focus]}} \
2766        -accelerator $M1T-C
2767.mbar.edit add command -label [mc Paste] \
2768        -command {catch {tk_textPaste [focus]; [focus] see insert}} \
2769        -accelerator $M1T-V
2770.mbar.edit add command -label [mc Delete] \
2771        -command {catch {[focus] delete sel.first sel.last}} \
2772        -accelerator Del
2773.mbar.edit add separator
2774.mbar.edit add command -label [mc "Select All"] \
2775        -command {catch {[focus] tag add sel 0.0 end}} \
2776        -accelerator $M1T-A
2777
2778# -- Branch Menu
2779#
2780if {[is_enabled branch]} {
2781        menu .mbar.branch
2782
2783        .mbar.branch add command -label [mc "Create..."] \
2784                -command branch_create::dialog \
2785                -accelerator $M1T-N
2786        lappend disable_on_lock [list .mbar.branch entryconf \
2787                [.mbar.branch index last] -state]
2788
2789        .mbar.branch add command -label [mc "Checkout..."] \
2790                -command branch_checkout::dialog \
2791                -accelerator $M1T-O
2792        lappend disable_on_lock [list .mbar.branch entryconf \
2793                [.mbar.branch index last] -state]
2794
2795        .mbar.branch add command -label [mc "Rename..."] \
2796                -command branch_rename::dialog
2797        lappend disable_on_lock [list .mbar.branch entryconf \
2798                [.mbar.branch index last] -state]
2799
2800        .mbar.branch add command -label [mc "Delete..."] \
2801                -command branch_delete::dialog
2802        lappend disable_on_lock [list .mbar.branch entryconf \
2803                [.mbar.branch index last] -state]
2804
2805        .mbar.branch add command -label [mc "Reset..."] \
2806                -command merge::reset_hard
2807        lappend disable_on_lock [list .mbar.branch entryconf \
2808                [.mbar.branch index last] -state]
2809}
2810
2811# -- Commit Menu
2812#
2813proc commit_btn_caption {} {
2814        if {[is_enabled nocommit]} {
2815                return [mc "Done"]
2816        } else {
2817                return [mc Commit@@verb]
2818        }
2819}
2820
2821if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2822        menu .mbar.commit
2823
2824        if {![is_enabled nocommit]} {
2825                .mbar.commit add radiobutton \
2826                        -label [mc "New Commit"] \
2827                        -command do_select_commit_type \
2828                        -variable selected_commit_type \
2829                        -value new
2830                lappend disable_on_lock \
2831                        [list .mbar.commit entryconf [.mbar.commit index last] -state]
2832
2833                .mbar.commit add radiobutton \
2834                        -label [mc "Amend Last Commit"] \
2835                        -command do_select_commit_type \
2836                        -variable selected_commit_type \
2837                        -value amend
2838                lappend disable_on_lock \
2839                        [list .mbar.commit entryconf [.mbar.commit index last] -state]
2840
2841                .mbar.commit add separator
2842        }
2843
2844        .mbar.commit add command -label [mc Rescan] \
2845                -command ui_do_rescan \
2846                -accelerator F5
2847        lappend disable_on_lock \
2848                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2849
2850        .mbar.commit add command -label [mc "Stage To Commit"] \
2851                -command do_add_selection \
2852                -accelerator $M1T-T
2853        lappend disable_on_lock \
2854                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2855
2856        .mbar.commit add command -label [mc "Stage Changed Files To Commit"] \
2857                -command do_add_all \
2858                -accelerator $M1T-I
2859        lappend disable_on_lock \
2860                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2861
2862        .mbar.commit add command -label [mc "Unstage From Commit"] \
2863                -command do_unstage_selection \
2864                -accelerator $M1T-U
2865        lappend disable_on_lock \
2866                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2867
2868        .mbar.commit add command -label [mc "Revert Changes"] \
2869                -command do_revert_selection \
2870                -accelerator $M1T-J
2871        lappend disable_on_lock \
2872                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2873
2874        .mbar.commit add separator
2875
2876        .mbar.commit add command -label [mc "Show Less Context"] \
2877                -command show_less_context \
2878                -accelerator $M1T-\-
2879
2880        .mbar.commit add command -label [mc "Show More Context"] \
2881                -command show_more_context \
2882                -accelerator $M1T-=
2883
2884        .mbar.commit add separator
2885
2886        if {![is_enabled nocommitmsg]} {
2887                .mbar.commit add command -label [mc "Sign Off"] \
2888                        -command do_signoff \
2889                        -accelerator $M1T-S
2890        }
2891
2892        .mbar.commit add command -label [commit_btn_caption] \
2893                -command do_commit \
2894                -accelerator $M1T-Return
2895        lappend disable_on_lock \
2896                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2897}
2898
2899# -- Merge Menu
2900#
2901if {[is_enabled branch]} {
2902        menu .mbar.merge
2903        .mbar.merge add command -label [mc "Local Merge..."] \
2904                -command merge::dialog \
2905                -accelerator $M1T-M
2906        lappend disable_on_lock \
2907                [list .mbar.merge entryconf [.mbar.merge index last] -state]
2908        .mbar.merge add command -label [mc "Abort Merge..."] \
2909                -command merge::reset_hard
2910        lappend disable_on_lock \
2911                [list .mbar.merge entryconf [.mbar.merge index last] -state]
2912}
2913
2914# -- Transport Menu
2915#
2916if {[is_enabled transport]} {
2917        menu .mbar.remote
2918
2919        .mbar.remote add command \
2920                -label [mc "Add..."] \
2921                -command remote_add::dialog \
2922                -accelerator $M1T-A
2923        .mbar.remote add command \
2924                -label [mc "Push..."] \
2925                -command do_push_anywhere \
2926                -accelerator $M1T-P
2927        .mbar.remote add command \
2928                -label [mc "Delete Branch..."] \
2929                -command remote_branch_delete::dialog
2930}
2931
2932if {[is_MacOSX]} {
2933        proc ::tk::mac::ShowPreferences {} {do_options}
2934} else {
2935        # -- Edit Menu
2936        #
2937        .mbar.edit add separator
2938        .mbar.edit add command -label [mc "Options..."] \
2939                -command do_options
2940}
2941
2942# -- Tools Menu
2943#
2944if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2945        set tools_menubar .mbar.tools
2946        menu $tools_menubar
2947        $tools_menubar add separator
2948        $tools_menubar add command -label [mc "Add..."] -command tools_add::dialog
2949        $tools_menubar add command -label [mc "Remove..."] -command tools_remove::dialog
2950        set tools_tailcnt 3
2951        if {[array names repo_config guitool.*.cmd] ne {}} {
2952                tools_populate_all
2953        }
2954}
2955
2956# -- Help Menu
2957#
2958.mbar add cascade -label [mc Help] -menu .mbar.help
2959menu .mbar.help
2960
2961if {[is_MacOSX]} {
2962        .mbar.apple add command -label [mc "About %s" [appname]] \
2963                -command do_about
2964        .mbar.apple add separator
2965} else {
2966        .mbar.help add command -label [mc "About %s" [appname]] \
2967                -command do_about
2968}
2969. configure -menu .mbar
2970
2971set doc_path [githtmldir]
2972if {$doc_path ne {}} {
2973        set doc_path [file join $doc_path index.html]
2974
2975        if {[is_Cygwin]} {
2976                set doc_path [exec cygpath --mixed $doc_path]
2977        }
2978}
2979
2980if {[file isfile $doc_path]} {
2981        set doc_url "file:$doc_path"
2982} else {
2983        set doc_url {http://www.kernel.org/pub/software/scm/git/docs/}
2984}
2985
2986proc start_browser {url} {
2987        git "web--browse" $url
2988}
2989
2990.mbar.help add command -label [mc "Online Documentation"] \
2991        -command [list start_browser $doc_url]
2992
2993.mbar.help add command -label [mc "Show SSH Key"] \
2994        -command do_ssh_key
2995
2996unset doc_path doc_url
2997
2998# -- Standard bindings
2999#
3000wm protocol . WM_DELETE_WINDOW do_quit
3001bind all <$M1B-Key-q> do_quit
3002bind all <$M1B-Key-Q> do_quit
3003bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
3004bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
3005
3006set subcommand_args {}
3007proc usage {} {
3008        set s "usage: $::argv0 $::subcommand $::subcommand_args"
3009        if {[tk windowingsystem] eq "win32"} {
3010                wm withdraw .
3011                tk_messageBox -icon info -message $s \
3012                        -title [mc "Usage"]
3013        } else {
3014                puts stderr $s
3015        }
3016        exit 1
3017}
3018
3019proc normalize_relpath {path} {
3020        set elements {}
3021        foreach item [file split $path] {
3022                if {$item eq {.}} continue
3023                if {$item eq {..} && [llength $elements] > 0
3024                    && [lindex $elements end] ne {..}} {
3025                        set elements [lrange $elements 0 end-1]
3026                        continue
3027                }
3028                lappend elements $item
3029        }
3030        return [eval file join $elements]
3031}
3032
3033# -- Not a normal commit type invocation?  Do that instead!
3034#
3035switch -- $subcommand {
3036browser -
3037blame {
3038        if {$subcommand eq "blame"} {
3039                set subcommand_args {[--line=<num>] rev? path}
3040        } else {
3041                set subcommand_args {rev? path}
3042        }
3043        if {$argv eq {}} usage
3044        set head {}
3045        set path {}
3046        set jump_spec {}
3047        set is_path 0
3048        foreach a $argv {
3049                set p [file join $_prefix $a]
3050
3051                if {$is_path || [file exists $p]} {
3052                        if {$path ne {}} usage
3053                        set path [normalize_relpath $p]
3054                        break
3055                } elseif {$a eq {--}} {
3056                        if {$path ne {}} {
3057                                if {$head ne {}} usage
3058                                set head $path
3059                                set path {}
3060                        }
3061                        set is_path 1
3062                } elseif {[regexp {^--line=(\d+)$} $a a lnum]} {
3063                        if {$jump_spec ne {} || $head ne {}} usage
3064                        set jump_spec [list $lnum]
3065                } elseif {$head eq {}} {
3066                        if {$head ne {}} usage
3067                        set head $a
3068                        set is_path 1
3069                } else {
3070                        usage
3071                }
3072        }
3073        unset is_path
3074
3075        if {$head ne {} && $path eq {}} {
3076                if {[string index $head 0] eq {/}} {
3077                        set path [normalize_relpath $head]
3078                        set head {}
3079                } else {
3080                        set path [normalize_relpath $_prefix$head]
3081                        set head {}
3082                }
3083        }
3084
3085        if {$head eq {}} {
3086                load_current_branch
3087        } else {
3088                if {[regexp {^[0-9a-f]{1,39}$} $head]} {
3089                        if {[catch {
3090                                        set head [git rev-parse --verify $head]
3091                                } err]} {
3092                                if {[tk windowingsystem] eq "win32"} {
3093                                        tk_messageBox -icon error -title [mc Error] -message $err
3094                                } else {
3095                                        puts stderr $err
3096                                }
3097                                exit 1
3098                        }
3099                }
3100                set current_branch $head
3101        }
3102
3103        wm deiconify .
3104        switch -- $subcommand {
3105        browser {
3106                if {$jump_spec ne {}} usage
3107                if {$head eq {}} {
3108                        if {$path ne {} && [file isdirectory $path]} {
3109                                set head $current_branch
3110                        } else {
3111                                set head $path
3112                                set path {}
3113                        }
3114                }
3115                browser::new $head $path
3116        }
3117        blame   {
3118                if {$head eq {} && ![file exists $path]} {
3119                        catch {wm withdraw .}
3120                        tk_messageBox \
3121                                -icon error \
3122                                -type ok \
3123                                -title [mc "git-gui: fatal error"] \
3124                                -message [mc "fatal: cannot stat path %s: No such file or directory" $path]
3125                        exit 1
3126                }
3127                blame::new $head $path $jump_spec
3128        }
3129        }
3130        return
3131}
3132citool -
3133gui {
3134        if {[llength $argv] != 0} {
3135                usage
3136        }
3137        # fall through to setup UI for commits
3138}
3139default {
3140        set err "usage: $argv0 \[{blame|browser|citool}\]"
3141        if {[tk windowingsystem] eq "win32"} {
3142                wm withdraw .
3143                tk_messageBox -icon error -message $err \
3144                        -title [mc "Usage"]
3145        } else {
3146                puts stderr $err
3147        }
3148        exit 1
3149}
3150}
3151
3152# -- Branch Control
3153#
3154${NS}::frame .branch
3155if {!$use_ttk} {.branch configure -borderwidth 1 -relief sunken}
3156${NS}::label .branch.l1 \
3157        -text [mc "Current Branch:"] \
3158        -anchor w \
3159        -justify left
3160${NS}::label .branch.cb \
3161        -textvariable current_branch \
3162        -anchor w \
3163        -justify left
3164pack .branch.l1 -side left
3165pack .branch.cb -side left -fill x
3166pack .branch -side top -fill x
3167
3168# -- Main Window Layout
3169#
3170${NS}::panedwindow .vpane -orient horizontal
3171${NS}::panedwindow .vpane.files -orient vertical
3172if {$use_ttk} {
3173        .vpane add .vpane.files
3174} else {
3175        .vpane add .vpane.files -sticky nsew -height 100 -width 200
3176}
3177pack .vpane -anchor n -side top -fill both -expand 1
3178
3179# -- Index File List
3180#
3181${NS}::frame .vpane.files.index -height 100 -width 200
3182tlabel .vpane.files.index.title \
3183        -text [mc "Staged Changes (Will Commit)"] \
3184        -background lightgreen -foreground black
3185text $ui_index -background white -foreground black \
3186        -borderwidth 0 \
3187        -width 20 -height 10 \
3188        -wrap none \
3189        -cursor $cursor_ptr \
3190        -xscrollcommand {.vpane.files.index.sx set} \
3191        -yscrollcommand {.vpane.files.index.sy set} \
3192        -state disabled
3193${NS}::scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
3194${NS}::scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
3195pack .vpane.files.index.title -side top -fill x
3196pack .vpane.files.index.sx -side bottom -fill x
3197pack .vpane.files.index.sy -side right -fill y
3198pack $ui_index -side left -fill both -expand 1
3199
3200# -- Working Directory File List
3201#
3202${NS}::frame .vpane.files.workdir -height 100 -width 200
3203tlabel .vpane.files.workdir.title -text [mc "Unstaged Changes"] \
3204        -background lightsalmon -foreground black
3205text $ui_workdir -background white -foreground black \
3206        -borderwidth 0 \
3207        -width 20 -height 10 \
3208        -wrap none \
3209        -cursor $cursor_ptr \
3210        -xscrollcommand {.vpane.files.workdir.sx set} \
3211        -yscrollcommand {.vpane.files.workdir.sy set} \
3212        -state disabled
3213${NS}::scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
3214${NS}::scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
3215pack .vpane.files.workdir.title -side top -fill x
3216pack .vpane.files.workdir.sx -side bottom -fill x
3217pack .vpane.files.workdir.sy -side right -fill y
3218pack $ui_workdir -side left -fill both -expand 1
3219
3220.vpane.files add .vpane.files.workdir
3221.vpane.files add .vpane.files.index
3222if {!$use_ttk} {
3223        .vpane.files paneconfigure .vpane.files.workdir -sticky news
3224        .vpane.files paneconfigure .vpane.files.index -sticky news
3225}
3226
3227foreach i [list $ui_index $ui_workdir] {
3228        rmsel_tag $i
3229        $i tag conf in_diff -background [$i tag cget in_sel -background]
3230}
3231unset i
3232
3233# -- Diff and Commit Area
3234#
3235if {$have_tk85} {
3236        ${NS}::panedwindow .vpane.lower -orient vertical
3237        ${NS}::frame .vpane.lower.commarea
3238        ${NS}::frame .vpane.lower.diff -relief sunken -borderwidth 1 -height 500
3239        .vpane.lower add .vpane.lower.diff
3240        .vpane.lower add .vpane.lower.commarea
3241        .vpane add .vpane.lower
3242        if {$use_ttk} {
3243                .vpane.lower pane .vpane.lower.diff -weight 1
3244                .vpane.lower pane .vpane.lower.commarea -weight 0
3245        } else {
3246                .vpane.lower paneconfigure .vpane.lower.diff -stretch always
3247                .vpane.lower paneconfigure .vpane.lower.commarea -stretch never
3248        }
3249} else {
3250        frame .vpane.lower -height 300 -width 400
3251        frame .vpane.lower.commarea
3252        frame .vpane.lower.diff -relief sunken -borderwidth 1
3253        pack .vpane.lower.diff -fill both -expand 1
3254        pack .vpane.lower.commarea -side bottom -fill x
3255        .vpane add .vpane.lower
3256        .vpane paneconfigure .vpane.lower -sticky nsew
3257}
3258
3259# -- Commit Area Buttons
3260#
3261${NS}::frame .vpane.lower.commarea.buttons
3262${NS}::label .vpane.lower.commarea.buttons.l -text {} \
3263        -anchor w \
3264        -justify left
3265pack .vpane.lower.commarea.buttons.l -side top -fill x
3266pack .vpane.lower.commarea.buttons -side left -fill y
3267
3268${NS}::button .vpane.lower.commarea.buttons.rescan -text [mc Rescan] \
3269        -command ui_do_rescan
3270pack .vpane.lower.commarea.buttons.rescan -side top -fill x
3271lappend disable_on_lock \
3272        {.vpane.lower.commarea.buttons.rescan conf -state}
3273
3274${NS}::button .vpane.lower.commarea.buttons.incall -text [mc "Stage Changed"] \
3275        -command do_add_all
3276pack .vpane.lower.commarea.buttons.incall -side top -fill x
3277lappend disable_on_lock \
3278        {.vpane.lower.commarea.buttons.incall conf -state}
3279
3280if {![is_enabled nocommitmsg]} {
3281        ${NS}::button .vpane.lower.commarea.buttons.signoff -text [mc "Sign Off"] \
3282                -command do_signoff
3283        pack .vpane.lower.commarea.buttons.signoff -side top -fill x
3284}
3285
3286${NS}::button .vpane.lower.commarea.buttons.commit -text [commit_btn_caption] \
3287        -command do_commit
3288pack .vpane.lower.commarea.buttons.commit -side top -fill x
3289lappend disable_on_lock \
3290        {.vpane.lower.commarea.buttons.commit conf -state}
3291
3292if {![is_enabled nocommit]} {
3293        ${NS}::button .vpane.lower.commarea.buttons.push -text [mc Push] \
3294                -command do_push_anywhere
3295        pack .vpane.lower.commarea.buttons.push -side top -fill x
3296}
3297
3298# -- Commit Message Buffer
3299#
3300${NS}::frame .vpane.lower.commarea.buffer
3301${NS}::frame .vpane.lower.commarea.buffer.header
3302set ui_comm .vpane.lower.commarea.buffer.t
3303set ui_coml .vpane.lower.commarea.buffer.header.l
3304
3305if {![is_enabled nocommit]} {
3306        ${NS}::radiobutton .vpane.lower.commarea.buffer.header.new \
3307                -text [mc "New Commit"] \
3308                -command do_select_commit_type \
3309                -variable selected_commit_type \
3310                -value new
3311        lappend disable_on_lock \
3312                [list .vpane.lower.commarea.buffer.header.new conf -state]
3313        ${NS}::radiobutton .vpane.lower.commarea.buffer.header.amend \
3314                -text [mc "Amend Last Commit"] \
3315                -command do_select_commit_type \
3316                -variable selected_commit_type \
3317                -value amend
3318        lappend disable_on_lock \
3319                [list .vpane.lower.commarea.buffer.header.amend conf -state]
3320}
3321
3322${NS}::label $ui_coml \
3323        -anchor w \
3324        -justify left
3325proc trace_commit_type {varname args} {
3326        global ui_coml commit_type
3327        switch -glob -- $commit_type {
3328        initial       {set txt [mc "Initial Commit Message:"]}
3329        amend         {set txt [mc "Amended Commit Message:"]}
3330        amend-initial {set txt [mc "Amended Initial Commit Message:"]}
3331        amend-merge   {set txt [mc "Amended Merge Commit Message:"]}
3332        merge         {set txt [mc "Merge Commit Message:"]}
3333        *             {set txt [mc "Commit Message:"]}
3334        }
3335        $ui_coml conf -text $txt
3336}
3337trace add variable commit_type write trace_commit_type
3338pack $ui_coml -side left -fill x
3339
3340if {![is_enabled nocommit]} {
3341        pack .vpane.lower.commarea.buffer.header.amend -side right
3342        pack .vpane.lower.commarea.buffer.header.new -side right
3343}
3344
3345text $ui_comm -background white -foreground black \
3346        -borderwidth 1 \
3347        -undo true \
3348        -maxundo 20 \
3349        -autoseparators true \
3350        -relief sunken \
3351        -width $repo_config(gui.commitmsgwidth) -height 9 -wrap none \
3352        -font font_diff \
3353        -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
3354${NS}::scrollbar .vpane.lower.commarea.buffer.sby \
3355        -command [list $ui_comm yview]
3356pack .vpane.lower.commarea.buffer.header -side top -fill x
3357pack .vpane.lower.commarea.buffer.sby -side right -fill y
3358pack $ui_comm -side left -fill y
3359pack .vpane.lower.commarea.buffer -side left -fill y
3360
3361# -- Commit Message Buffer Context Menu
3362#
3363set ctxm .vpane.lower.commarea.buffer.ctxm
3364menu $ctxm -tearoff 0
3365$ctxm add command \
3366        -label [mc Cut] \
3367        -command {tk_textCut $ui_comm}
3368$ctxm add command \
3369        -label [mc Copy] \
3370        -command {tk_textCopy $ui_comm}
3371$ctxm add command \
3372        -label [mc Paste] \
3373        -command {tk_textPaste $ui_comm}
3374$ctxm add command \
3375        -label [mc Delete] \
3376        -command {catch {$ui_comm delete sel.first sel.last}}
3377$ctxm add separator
3378$ctxm add command \
3379        -label [mc "Select All"] \
3380        -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
3381$ctxm add command \
3382        -label [mc "Copy All"] \
3383        -command {
3384                $ui_comm tag add sel 0.0 end
3385                tk_textCopy $ui_comm
3386                $ui_comm tag remove sel 0.0 end
3387        }
3388$ctxm add separator
3389$ctxm add command \
3390        -label [mc "Sign Off"] \
3391        -command do_signoff
3392set ui_comm_ctxm $ctxm
3393
3394# -- Diff Header
3395#
3396proc trace_current_diff_path {varname args} {
3397        global current_diff_path diff_actions file_states
3398        if {$current_diff_path eq {}} {
3399                set s {}
3400                set f {}
3401                set p {}
3402                set o disabled
3403        } else {
3404                set p $current_diff_path
3405                set s [mapdesc [lindex $file_states($p) 0] $p]
3406                set f [mc "File:"]
3407                set p [escape_path $p]
3408                set o normal
3409        }
3410
3411        .vpane.lower.diff.header.status configure -text $s
3412        .vpane.lower.diff.header.file configure -text $f
3413        .vpane.lower.diff.header.path configure -text $p
3414        foreach w $diff_actions {
3415                uplevel #0 $w $o
3416        }
3417}
3418trace add variable current_diff_path write trace_current_diff_path
3419
3420gold_frame .vpane.lower.diff.header
3421tlabel .vpane.lower.diff.header.status \
3422        -background gold \
3423        -foreground black \
3424        -width $max_status_desc \
3425        -anchor w \
3426        -justify left
3427tlabel .vpane.lower.diff.header.file \
3428        -background gold \
3429        -foreground black \
3430        -anchor w \
3431        -justify left
3432tlabel .vpane.lower.diff.header.path \
3433        -background gold \
3434        -foreground black \
3435        -anchor w \
3436        -justify left
3437pack .vpane.lower.diff.header.status -side left
3438pack .vpane.lower.diff.header.file -side left
3439pack .vpane.lower.diff.header.path -fill x
3440set ctxm .vpane.lower.diff.header.ctxm
3441menu $ctxm -tearoff 0
3442$ctxm add command \
3443        -label [mc Copy] \
3444        -command {
3445                clipboard clear
3446                clipboard append \
3447                        -format STRING \
3448                        -type STRING \
3449                        -- $current_diff_path
3450        }
3451lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3452bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
3453
3454# -- Diff Body
3455#
3456${NS}::frame .vpane.lower.diff.body
3457set ui_diff .vpane.lower.diff.body.t
3458text $ui_diff -background white -foreground black \
3459        -borderwidth 0 \
3460        -width 80 -height 5 -wrap none \
3461        -font font_diff \
3462        -xscrollcommand {.vpane.lower.diff.body.sbx set} \
3463        -yscrollcommand {.vpane.lower.diff.body.sby set} \
3464        -state disabled
3465catch {$ui_diff configure -tabstyle wordprocessor}
3466${NS}::scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
3467        -command [list $ui_diff xview]
3468${NS}::scrollbar .vpane.lower.diff.body.sby -orient vertical \
3469        -command [list $ui_diff yview]
3470pack .vpane.lower.diff.body.sbx -side bottom -fill x
3471pack .vpane.lower.diff.body.sby -side right -fill y
3472pack $ui_diff -side left -fill both -expand 1
3473pack .vpane.lower.diff.header -side top -fill x
3474pack .vpane.lower.diff.body -side bottom -fill both -expand 1
3475
3476foreach {n c} {0 black 1 red4 2 green4 3 yellow4 4 blue4 5 magenta4 6 cyan4 7 grey60} {
3477        $ui_diff tag configure clr4$n -background $c
3478        $ui_diff tag configure clri4$n -foreground $c
3479        $ui_diff tag configure clr3$n -foreground $c
3480        $ui_diff tag configure clri3$n -background $c
3481}
3482$ui_diff tag configure clr1 -font font_diffbold
3483$ui_diff tag configure clr4 -underline 1
3484
3485$ui_diff tag conf d_info -foreground blue -font font_diffbold
3486
3487$ui_diff tag conf d_cr -elide true
3488$ui_diff tag conf d_@ -font font_diffbold
3489$ui_diff tag conf d_+ -foreground {#00a000}
3490$ui_diff tag conf d_- -foreground red
3491
3492$ui_diff tag conf d_++ -foreground {#00a000}
3493$ui_diff tag conf d_-- -foreground red
3494$ui_diff tag conf d_+s \
3495        -foreground {#00a000} \
3496        -background {#e2effa}
3497$ui_diff tag conf d_-s \
3498        -foreground red \
3499        -background {#e2effa}
3500$ui_diff tag conf d_s+ \
3501        -foreground {#00a000} \
3502        -background ivory1
3503$ui_diff tag conf d_s- \
3504        -foreground red \
3505        -background ivory1
3506
3507$ui_diff tag conf d< \
3508        -foreground orange \
3509        -font font_diffbold
3510$ui_diff tag conf d= \
3511        -foreground orange \
3512        -font font_diffbold
3513$ui_diff tag conf d> \
3514        -foreground orange \
3515        -font font_diffbold
3516
3517$ui_diff tag raise sel
3518
3519# -- Diff Body Context Menu
3520#
3521
3522proc create_common_diff_popup {ctxm} {
3523        $ctxm add command \
3524                -label [mc Refresh] \
3525                -command reshow_diff
3526        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3527        $ctxm add command \
3528                -label [mc Copy] \
3529                -command {tk_textCopy $ui_diff}
3530        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3531        $ctxm add command \
3532                -label [mc "Select All"] \
3533                -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
3534        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3535        $ctxm add command \
3536                -label [mc "Copy All"] \
3537                -command {
3538                        $ui_diff tag add sel 0.0 end
3539                        tk_textCopy $ui_diff
3540                        $ui_diff tag remove sel 0.0 end
3541                }
3542        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3543        $ctxm add separator
3544        $ctxm add command \
3545                -label [mc "Decrease Font Size"] \
3546                -command {incr_font_size font_diff -1}
3547        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3548        $ctxm add command \
3549                -label [mc "Increase Font Size"] \
3550                -command {incr_font_size font_diff 1}
3551        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3552        $ctxm add separator
3553        set emenu $ctxm.enc
3554        menu $emenu
3555        build_encoding_menu $emenu [list force_diff_encoding]
3556        $ctxm add cascade \
3557                -label [mc "Encoding"] \
3558                -menu $emenu
3559        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3560        $ctxm add separator
3561        $ctxm add command -label [mc "Options..."] \
3562                -command do_options
3563}
3564
3565set ctxm .vpane.lower.diff.body.ctxm
3566menu $ctxm -tearoff 0
3567$ctxm add command \
3568        -label [mc "Apply/Reverse Hunk"] \
3569        -command {apply_hunk $cursorX $cursorY}
3570set ui_diff_applyhunk [$ctxm index last]
3571lappend diff_actions [list $ctxm entryconf $ui_diff_applyhunk -state]
3572$ctxm add command \
3573        -label [mc "Apply/Reverse Line"] \
3574        -command {apply_range_or_line $cursorX $cursorY; do_rescan}
3575set ui_diff_applyline [$ctxm index last]
3576lappend diff_actions [list $ctxm entryconf $ui_diff_applyline -state]
3577$ctxm add separator
3578$ctxm add command \
3579        -label [mc "Show Less Context"] \
3580        -command show_less_context
3581lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3582$ctxm add command \
3583        -label [mc "Show More Context"] \
3584        -command show_more_context
3585lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3586$ctxm add separator
3587create_common_diff_popup $ctxm
3588
3589set ctxmmg .vpane.lower.diff.body.ctxmmg
3590menu $ctxmmg -tearoff 0
3591$ctxmmg add command \
3592        -label [mc "Run Merge Tool"] \
3593        -command {merge_resolve_tool}
3594lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3595$ctxmmg add separator
3596$ctxmmg add command \
3597        -label [mc "Use Remote Version"] \
3598        -command {merge_resolve_one 3}
3599lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3600$ctxmmg add command \
3601        -label [mc "Use Local Version"] \
3602        -command {merge_resolve_one 2}
3603lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3604$ctxmmg add command \
3605        -label [mc "Revert To Base"] \
3606        -command {merge_resolve_one 1}
3607lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3608$ctxmmg add separator
3609$ctxmmg add command \
3610        -label [mc "Show Less Context"] \
3611        -command show_less_context
3612lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3613$ctxmmg add command \
3614        -label [mc "Show More Context"] \
3615        -command show_more_context
3616lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3617$ctxmmg add separator
3618create_common_diff_popup $ctxmmg
3619
3620set ctxmsm .vpane.lower.diff.body.ctxmsm
3621menu $ctxmsm -tearoff 0
3622$ctxmsm add command \
3623        -label [mc "Visualize These Changes In The Submodule"] \
3624        -command {do_gitk -- true}
3625lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3626$ctxmsm add command \
3627        -label [mc "Visualize Current Branch History In The Submodule"] \
3628        -command {do_gitk {} true}
3629lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3630$ctxmsm add command \
3631        -label [mc "Visualize All Branch History In The Submodule"] \
3632        -command {do_gitk --all true}
3633lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3634$ctxmsm add separator
3635$ctxmsm add command \
3636        -label [mc "Start git gui In The Submodule"] \
3637        -command {do_git_gui}
3638lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3639$ctxmsm add separator
3640create_common_diff_popup $ctxmsm
3641
3642proc has_textconv {path} {
3643        if {[is_config_false gui.textconv]} {
3644                return 0
3645        }
3646        set filter [gitattr $path diff set]
3647        set textconv [get_config [join [list diff $filter textconv] .]]
3648        if {$filter ne {set} && $textconv ne {}} {
3649                return 1
3650        } else {
3651                return 0
3652        }
3653}
3654
3655proc popup_diff_menu {ctxm ctxmmg ctxmsm x y X Y} {
3656        global current_diff_path file_states
3657        set ::cursorX $x
3658        set ::cursorY $y
3659        if {[info exists file_states($current_diff_path)]} {
3660                set state [lindex $file_states($current_diff_path) 0]
3661        } else {
3662                set state {__}
3663        }
3664        if {[string first {U} $state] >= 0} {
3665                tk_popup $ctxmmg $X $Y
3666        } elseif {$::is_submodule_diff} {
3667                tk_popup $ctxmsm $X $Y
3668        } else {
3669                set has_range [expr {[$::ui_diff tag nextrange sel 0.0] != {}}]
3670                if {$::ui_index eq $::current_diff_side} {
3671                        set l [mc "Unstage Hunk From Commit"]
3672                        if {$has_range} {
3673                                set t [mc "Unstage Lines From Commit"]
3674                        } else {
3675                                set t [mc "Unstage Line From Commit"]
3676                        }
3677                } else {
3678                        set l [mc "Stage Hunk For Commit"]
3679                        if {$has_range} {
3680                                set t [mc "Stage Lines For Commit"]
3681                        } else {
3682                                set t [mc "Stage Line For Commit"]
3683                        }
3684                }
3685                if {$::is_3way_diff
3686                        || $current_diff_path eq {}
3687                        || {__} eq $state
3688                        || {_O} eq $state
3689                        || [string match {?T} $state]
3690                        || [string match {T?} $state]
3691                        || [has_textconv $current_diff_path]} {
3692                        set s disabled
3693                } else {
3694                        set s normal
3695                }
3696                $ctxm entryconf $::ui_diff_applyhunk -state $s -label $l
3697                $ctxm entryconf $::ui_diff_applyline -state $s -label $t
3698                tk_popup $ctxm $X $Y
3699        }
3700}
3701bind_button3 $ui_diff [list popup_diff_menu $ctxm $ctxmmg $ctxmsm %x %y %X %Y]
3702
3703# -- Status Bar
3704#
3705set main_status [::status_bar::new .status]
3706pack .status -anchor w -side bottom -fill x
3707$main_status show [mc "Initializing..."]
3708
3709# -- Load geometry
3710#
3711proc on_ttk_pane_mapped {w pane pos} {
3712        bind $w <Map> {}
3713        after 0 [list after idle [list $w sashpos $pane $pos]]
3714}
3715proc on_tk_pane_mapped {w pane x y} {
3716        bind $w <Map> {}
3717        after 0 [list after idle [list $w sash place $pane $x $y]]
3718}
3719proc on_application_mapped {} {
3720        global repo_config use_ttk
3721        bind . <Map> {}
3722        set gm $repo_config(gui.geometry)
3723        if {$use_ttk} {
3724                bind .vpane <Map> \
3725                    [list on_ttk_pane_mapped %W 0 [lindex $gm 1]]
3726                bind .vpane.files <Map> \
3727                    [list on_ttk_pane_mapped %W 0 [lindex $gm 2]]
3728        } else {
3729                bind .vpane <Map> \
3730                    [list on_tk_pane_mapped %W 0 \
3731                         [lindex $gm 1] \
3732                         [lindex [.vpane sash coord 0] 1]]
3733                bind .vpane.files <Map> \
3734                    [list on_tk_pane_mapped %W 0 \
3735                         [lindex [.vpane.files sash coord 0] 0] \
3736                         [lindex $gm 2]]
3737        }
3738        wm geometry . [lindex $gm 0]
3739}
3740if {[info exists repo_config(gui.geometry)]} {
3741        bind . <Map> [list on_application_mapped]
3742        wm geometry . [lindex $repo_config(gui.geometry) 0]
3743}
3744
3745# -- Load window state
3746#
3747if {[info exists repo_config(gui.wmstate)]} {
3748        catch {wm state . $repo_config(gui.wmstate)}
3749}
3750
3751# -- Key Bindings
3752#
3753bind $ui_comm <$M1B-Key-Return> {do_commit;break}
3754bind $ui_comm <$M1B-Key-t> {do_add_selection;break}
3755bind $ui_comm <$M1B-Key-T> {do_add_selection;break}
3756bind $ui_comm <$M1B-Key-u> {do_unstage_selection;break}
3757bind $ui_comm <$M1B-Key-U> {do_unstage_selection;break}
3758bind $ui_comm <$M1B-Key-j> {do_revert_selection;break}
3759bind $ui_comm <$M1B-Key-J> {do_revert_selection;break}
3760bind $ui_comm <$M1B-Key-i> {do_add_all;break}
3761bind $ui_comm <$M1B-Key-I> {do_add_all;break}
3762bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
3763bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
3764bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
3765bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
3766bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
3767bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
3768bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3769bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3770bind $ui_comm <$M1B-Key-minus> {show_less_context;break}
3771bind $ui_comm <$M1B-Key-KP_Subtract> {show_less_context;break}
3772bind $ui_comm <$M1B-Key-equal> {show_more_context;break}
3773bind $ui_comm <$M1B-Key-plus> {show_more_context;break}
3774bind $ui_comm <$M1B-Key-KP_Add> {show_more_context;break}
3775
3776bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
3777bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
3778bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
3779bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
3780bind $ui_diff <$M1B-Key-v> {break}
3781bind $ui_diff <$M1B-Key-V> {break}
3782bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3783bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3784bind $ui_diff <$M1B-Key-j> {do_revert_selection;break}
3785bind $ui_diff <$M1B-Key-J> {do_revert_selection;break}
3786bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
3787bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
3788bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
3789bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
3790bind $ui_diff <Key-k>         {catch {%W yview scroll -1 units};break}
3791bind $ui_diff <Key-j>         {catch {%W yview scroll  1 units};break}
3792bind $ui_diff <Key-h>         {catch {%W xview scroll -1 units};break}
3793bind $ui_diff <Key-l>         {catch {%W xview scroll  1 units};break}
3794bind $ui_diff <Control-Key-b> {catch {%W yview scroll -1 pages};break}
3795bind $ui_diff <Control-Key-f> {catch {%W yview scroll  1 pages};break}
3796bind $ui_diff <Button-1>   {focus %W}
3797
3798if {[is_enabled branch]} {
3799        bind . <$M1B-Key-n> branch_create::dialog
3800        bind . <$M1B-Key-N> branch_create::dialog
3801        bind . <$M1B-Key-o> branch_checkout::dialog
3802        bind . <$M1B-Key-O> branch_checkout::dialog
3803        bind . <$M1B-Key-m> merge::dialog
3804        bind . <$M1B-Key-M> merge::dialog
3805}
3806if {[is_enabled transport]} {
3807        bind . <$M1B-Key-p> do_push_anywhere
3808        bind . <$M1B-Key-P> do_push_anywhere
3809}
3810
3811bind .   <Key-F5>     ui_do_rescan
3812bind .   <$M1B-Key-r> ui_do_rescan
3813bind .   <$M1B-Key-R> ui_do_rescan
3814bind .   <$M1B-Key-s> do_signoff
3815bind .   <$M1B-Key-S> do_signoff
3816bind .   <$M1B-Key-t> do_add_selection
3817bind .   <$M1B-Key-T> do_add_selection
3818bind .   <$M1B-Key-u> do_unstage_selection
3819bind .   <$M1B-Key-U> do_unstage_selection
3820bind .   <$M1B-Key-j> do_revert_selection
3821bind .   <$M1B-Key-J> do_revert_selection
3822bind .   <$M1B-Key-i> do_add_all
3823bind .   <$M1B-Key-I> do_add_all
3824bind .   <$M1B-Key-minus> {show_less_context;break}
3825bind .   <$M1B-Key-KP_Subtract> {show_less_context;break}
3826bind .   <$M1B-Key-equal> {show_more_context;break}
3827bind .   <$M1B-Key-plus> {show_more_context;break}
3828bind .   <$M1B-Key-KP_Add> {show_more_context;break}
3829bind .   <$M1B-Key-Return> do_commit
3830foreach i [list $ui_index $ui_workdir] {
3831        bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
3832        bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
3833        bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
3834}
3835unset i
3836
3837set file_lists($ui_index) [list]
3838set file_lists($ui_workdir) [list]
3839
3840wm title . "[appname] ([reponame]) [file normalize $_gitworktree]"
3841focus -force $ui_comm
3842
3843# -- Warn the user about environmental problems.  Cygwin's Tcl
3844#    does *not* pass its env array onto any processes it spawns.
3845#    This means that git processes get none of our environment.
3846#
3847if {[is_Cygwin]} {
3848        set ignored_env 0
3849        set suggest_user {}
3850        set msg [mc "Possible environment issues exist.
3851
3852The following environment variables are probably
3853going to be ignored by any Git subprocess run
3854by %s:
3855
3856" [appname]]
3857        foreach name [array names env] {
3858                switch -regexp -- $name {
3859                {^GIT_INDEX_FILE$} -
3860                {^GIT_OBJECT_DIRECTORY$} -
3861                {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
3862                {^GIT_DIFF_OPTS$} -
3863                {^GIT_EXTERNAL_DIFF$} -
3864                {^GIT_PAGER$} -
3865                {^GIT_TRACE$} -
3866                {^GIT_CONFIG$} -
3867                {^GIT_(AUTHOR|COMMITTER)_DATE$} {
3868                        append msg " - $name\n"
3869                        incr ignored_env
3870                }
3871                {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
3872                        append msg " - $name\n"
3873                        incr ignored_env
3874                        set suggest_user $name
3875                }
3876                }
3877        }
3878        if {$ignored_env > 0} {
3879                append msg [mc "
3880This is due to a known issue with the
3881Tcl binary distributed by Cygwin."]
3882
3883                if {$suggest_user ne {}} {
3884                        append msg [mc "
3885
3886A good replacement for %s
3887is placing values for the user.name and
3888user.email settings into your personal
3889~/.gitconfig file.
3890" $suggest_user]
3891                }
3892                warn_popup $msg
3893        }
3894        unset ignored_env msg suggest_user name
3895}
3896
3897# -- Only initialize complex UI if we are going to stay running.
3898#
3899if {[is_enabled transport]} {
3900        load_all_remotes
3901
3902        set n [.mbar.remote index end]
3903        populate_remotes_menu
3904        set n [expr {[.mbar.remote index end] - $n}]
3905        if {$n > 0} {
3906                if {[.mbar.remote type 0] eq "tearoff"} { incr n }
3907                .mbar.remote insert $n separator
3908        }
3909        unset n
3910}
3911
3912if {[winfo exists $ui_comm]} {
3913        set GITGUI_BCK_exists [load_message GITGUI_BCK utf-8]
3914
3915        # -- If both our backup and message files exist use the
3916        #    newer of the two files to initialize the buffer.
3917        #
3918        if {$GITGUI_BCK_exists} {
3919                set m [gitdir GITGUI_MSG]
3920                if {[file isfile $m]} {
3921                        if {[file mtime [gitdir GITGUI_BCK]] > [file mtime $m]} {
3922                                catch {file delete [gitdir GITGUI_MSG]}
3923                        } else {
3924                                $ui_comm delete 0.0 end
3925                                $ui_comm edit reset
3926                                $ui_comm edit modified false
3927                                catch {file delete [gitdir GITGUI_BCK]}
3928                                set GITGUI_BCK_exists 0
3929                        }
3930                }
3931                unset m
3932        }
3933
3934        proc backup_commit_buffer {} {
3935                global ui_comm GITGUI_BCK_exists
3936
3937                set m [$ui_comm edit modified]
3938                if {$m || $GITGUI_BCK_exists} {
3939                        set msg [string trim [$ui_comm get 0.0 end]]
3940                        regsub -all -line {[ \r\t]+$} $msg {} msg
3941
3942                        if {$msg eq {}} {
3943                                if {$GITGUI_BCK_exists} {
3944                                        catch {file delete [gitdir GITGUI_BCK]}
3945                                        set GITGUI_BCK_exists 0
3946                                }
3947                        } elseif {$m} {
3948                                catch {
3949                                        set fd [open [gitdir GITGUI_BCK] w]
3950                                        fconfigure $fd -encoding utf-8
3951                                        puts -nonewline $fd $msg
3952                                        close $fd
3953                                        set GITGUI_BCK_exists 1
3954                                }
3955                        }
3956
3957                        $ui_comm edit modified false
3958                }
3959
3960                set ::GITGUI_BCK_i [after 2000 backup_commit_buffer]
3961        }
3962
3963        backup_commit_buffer
3964
3965        # -- If the user has aspell available we can drive it
3966        #    in pipe mode to spellcheck the commit message.
3967        #
3968        set spell_cmd [list |]
3969        set spell_dict [get_config gui.spellingdictionary]
3970        lappend spell_cmd aspell
3971        if {$spell_dict ne {}} {
3972                lappend spell_cmd --master=$spell_dict
3973        }
3974        lappend spell_cmd --mode=none
3975        lappend spell_cmd --encoding=utf-8
3976        lappend spell_cmd pipe
3977        if {$spell_dict eq {none}
3978         || [catch {set spell_fd [open $spell_cmd r+]} spell_err]} {
3979                bind_button3 $ui_comm [list tk_popup $ui_comm_ctxm %X %Y]
3980        } else {
3981                set ui_comm_spell [spellcheck::init \
3982                        $spell_fd \
3983                        $ui_comm \
3984                        $ui_comm_ctxm \
3985                ]
3986        }
3987        unset -nocomplain spell_cmd spell_fd spell_err spell_dict
3988}
3989
3990lock_index begin-read
3991if {![winfo ismapped .]} {
3992        wm deiconify .
3993}
3994after 1 {
3995        if {[is_enabled initialamend]} {
3996                force_amend
3997        } else {
3998                do_rescan
3999        }
4000
4001        if {[is_enabled nocommitmsg]} {
4002                $ui_comm configure -state disabled -background gray
4003        }
4004}
4005if {[is_enabled multicommit] && ![is_config_false gui.gcwarning]} {
4006        after 1000 hint_gc
4007}
4008if {[is_enabled retcode]} {
4009        bind . <Destroy> {+terminate_me %W}
4010}
4011if {$picked && [is_config_true gui.autoexplore]} {
4012        do_explore
4013}
4014
4015# Local variables:
4016# mode: tcl
4017# indent-tabs-mode: t
4018# tab-width: 4
4019# End: