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