git-gui.shon commit git-gui: rework handling of diff header (c976bbf)
   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
 881proc get_trimmed_version {s} {
 882    set r {}
 883    foreach x [split $s -._] {
 884        if {[string is integer -strict $x]} {
 885            lappend r $x
 886        } else {
 887            break
 888        }
 889    }
 890    return [join $r .]
 891}
 892set _real_git_version $_git_version
 893set _git_version [get_trimmed_version $_git_version]
 894
 895if {![regexp {^[1-9]+(\.[0-9]+)+$} $_git_version]} {
 896        catch {wm withdraw .}
 897        if {[tk_messageBox \
 898                -icon warning \
 899                -type yesno \
 900                -default no \
 901                -title "[appname]: warning" \
 902                 -message [mc "Git version cannot be determined.
 903
 904%s claims it is version '%s'.
 905
 906%s requires at least Git 1.5.0 or later.
 907
 908Assume '%s' is version 1.5.0?
 909" $_git $_real_git_version [appname] $_real_git_version]] eq {yes}} {
 910                set _git_version 1.5.0
 911        } else {
 912                exit 1
 913        }
 914}
 915unset _real_git_version
 916
 917proc git-version {args} {
 918        global _git_version
 919
 920        switch [llength $args] {
 921        0 {
 922                return $_git_version
 923        }
 924
 925        2 {
 926                set op [lindex $args 0]
 927                set vr [lindex $args 1]
 928                set cm [package vcompare $_git_version $vr]
 929                return [expr $cm $op 0]
 930        }
 931
 932        4 {
 933                set type [lindex $args 0]
 934                set name [lindex $args 1]
 935                set parm [lindex $args 2]
 936                set body [lindex $args 3]
 937
 938                if {($type ne {proc} && $type ne {method})} {
 939                        error "Invalid arguments to git-version"
 940                }
 941                if {[llength $body] < 2 || [lindex $body end-1] ne {default}} {
 942                        error "Last arm of $type $name must be default"
 943                }
 944
 945                foreach {op vr cb} [lrange $body 0 end-2] {
 946                        if {[git-version $op $vr]} {
 947                                return [uplevel [list $type $name $parm $cb]]
 948                        }
 949                }
 950
 951                return [uplevel [list $type $name $parm [lindex $body end]]]
 952        }
 953
 954        default {
 955                error "git-version >= x"
 956        }
 957
 958        }
 959}
 960
 961if {[git-version < 1.5]} {
 962        catch {wm withdraw .}
 963        tk_messageBox \
 964                -icon error \
 965                -type ok \
 966                -title [mc "git-gui: fatal error"] \
 967                -message "[appname] requires Git 1.5.0 or later.
 968
 969You are using [git-version]:
 970
 971[git --version]"
 972        exit 1
 973}
 974
 975######################################################################
 976##
 977## configure our library
 978
 979set idx [file join $oguilib tclIndex]
 980if {[catch {set fd [open $idx r]} err]} {
 981        catch {wm withdraw .}
 982        tk_messageBox \
 983                -icon error \
 984                -type ok \
 985                -title [mc "git-gui: fatal error"] \
 986                -message $err
 987        exit 1
 988}
 989if {[gets $fd] eq {# Autogenerated by git-gui Makefile}} {
 990        set idx [list]
 991        while {[gets $fd n] >= 0} {
 992                if {$n ne {} && ![string match #* $n]} {
 993                        lappend idx $n
 994                }
 995        }
 996} else {
 997        set idx {}
 998}
 999close $fd
1000
1001if {$idx ne {}} {
1002        set loaded [list]
1003        foreach p $idx {
1004                if {[lsearch -exact $loaded $p] >= 0} continue
1005                source [file join $oguilib $p]
1006                lappend loaded $p
1007        }
1008        unset loaded p
1009} else {
1010        set auto_path [concat [list $oguilib] $auto_path]
1011}
1012unset -nocomplain idx fd
1013
1014######################################################################
1015##
1016## config file parsing
1017
1018git-version proc _parse_config {arr_name args} {
1019        >= 1.5.3 {
1020                upvar $arr_name arr
1021                array unset arr
1022                set buf {}
1023                catch {
1024                        set fd_rc [eval \
1025                                [list git_read config] \
1026                                $args \
1027                                [list --null --list]]
1028                        fconfigure $fd_rc -translation binary
1029                        set buf [read $fd_rc]
1030                        close $fd_rc
1031                }
1032                foreach line [split $buf "\0"] {
1033                        if {[regexp {^([^\n]+)\n(.*)$} $line line name value]} {
1034                                if {[is_many_config $name]} {
1035                                        lappend arr($name) $value
1036                                } else {
1037                                        set arr($name) $value
1038                                }
1039                        }
1040                }
1041        }
1042        default {
1043                upvar $arr_name arr
1044                array unset arr
1045                catch {
1046                        set fd_rc [eval [list git_read config --list] $args]
1047                        while {[gets $fd_rc line] >= 0} {
1048                                if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
1049                                        if {[is_many_config $name]} {
1050                                                lappend arr($name) $value
1051                                        } else {
1052                                                set arr($name) $value
1053                                        }
1054                                }
1055                        }
1056                        close $fd_rc
1057                }
1058        }
1059}
1060
1061proc load_config {include_global} {
1062        global repo_config global_config system_config default_config
1063
1064        if {$include_global} {
1065                _parse_config system_config --system
1066                _parse_config global_config --global
1067        }
1068        _parse_config repo_config
1069
1070        foreach name [array names default_config] {
1071                if {[catch {set v $system_config($name)}]} {
1072                        set system_config($name) $default_config($name)
1073                }
1074        }
1075        foreach name [array names system_config] {
1076                if {[catch {set v $global_config($name)}]} {
1077                        set global_config($name) $system_config($name)
1078                }
1079                if {[catch {set v $repo_config($name)}]} {
1080                        set repo_config($name) $system_config($name)
1081                }
1082        }
1083}
1084
1085######################################################################
1086##
1087## feature option selection
1088
1089if {[regexp {^git-(.+)$} [file tail $argv0] _junk subcommand]} {
1090        unset _junk
1091} else {
1092        set subcommand gui
1093}
1094if {$subcommand eq {gui.sh}} {
1095        set subcommand gui
1096}
1097if {$subcommand eq {gui} && [llength $argv] > 0} {
1098        set subcommand [lindex $argv 0]
1099        set argv [lrange $argv 1 end]
1100}
1101
1102enable_option multicommit
1103enable_option branch
1104enable_option transport
1105disable_option bare
1106
1107switch -- $subcommand {
1108browser -
1109blame {
1110        enable_option bare
1111
1112        disable_option multicommit
1113        disable_option branch
1114        disable_option transport
1115}
1116citool {
1117        enable_option singlecommit
1118        enable_option retcode
1119
1120        disable_option multicommit
1121        disable_option branch
1122        disable_option transport
1123
1124        while {[llength $argv] > 0} {
1125                set a [lindex $argv 0]
1126                switch -- $a {
1127                --amend {
1128                        enable_option initialamend
1129                }
1130                --nocommit {
1131                        enable_option nocommit
1132                        enable_option nocommitmsg
1133                }
1134                --commitmsg {
1135                        disable_option nocommitmsg
1136                }
1137                default {
1138                        break
1139                }
1140                }
1141
1142                set argv [lrange $argv 1 end]
1143        }
1144}
1145}
1146
1147######################################################################
1148##
1149## execution environment
1150
1151set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
1152
1153# Suggest our implementation of askpass, if none is set
1154if {![info exists env(SSH_ASKPASS)]} {
1155        set env(SSH_ASKPASS) [gitexec git-gui--askpass]
1156}
1157
1158######################################################################
1159##
1160## repository setup
1161
1162set picked 0
1163if {[catch {
1164                set _gitdir $env(GIT_DIR)
1165                set _prefix {}
1166                }]
1167        && [catch {
1168                # beware that from the .git dir this sets _gitdir to .
1169                # and _prefix to the empty string
1170                set _gitdir [git rev-parse --git-dir]
1171                set _prefix [git rev-parse --show-prefix]
1172        } err]} {
1173        load_config 1
1174        apply_config
1175        choose_repository::pick
1176        set picked 1
1177}
1178
1179# we expand the _gitdir when it's just a single dot (i.e. when we're being
1180# run from the .git dir itself) lest the routines to find the worktree
1181# get confused
1182if {$_gitdir eq "."} {
1183        set _gitdir [pwd]
1184}
1185
1186if {![file isdirectory $_gitdir] && [is_Cygwin]} {
1187        catch {set _gitdir [exec cygpath --windows $_gitdir]}
1188}
1189if {![file isdirectory $_gitdir]} {
1190        catch {wm withdraw .}
1191        error_popup [strcat [mc "Git directory not found:"] "\n\n$_gitdir"]
1192        exit 1
1193}
1194# _gitdir exists, so try loading the config
1195load_config 0
1196apply_config
1197
1198# v1.7.0 introduced --show-toplevel to return the canonical work-tree
1199if {[package vsatisfies $_git_version 1.7.0]} {
1200        set _gitworktree [git rev-parse --show-toplevel]
1201} else {
1202        # try to set work tree from environment, core.worktree or use
1203        # cdup to obtain a relative path to the top of the worktree. If
1204        # run from the top, the ./ prefix ensures normalize expands pwd.
1205        if {[catch { set _gitworktree $env(GIT_WORK_TREE) }]} {
1206                set _gitworktree [get_config core.worktree]
1207                if {$_gitworktree eq ""} {
1208                        set _gitworktree [file normalize ./[git rev-parse --show-cdup]]
1209                }
1210        }
1211}
1212
1213if {$_prefix ne {}} {
1214        if {$_gitworktree eq {}} {
1215                regsub -all {[^/]+/} $_prefix ../ cdup
1216        } else {
1217                set cdup $_gitworktree
1218        }
1219        if {[catch {cd $cdup} err]} {
1220                catch {wm withdraw .}
1221                error_popup [strcat [mc "Cannot move to top of working directory:"] "\n\n$err"]
1222                exit 1
1223        }
1224        set _gitworktree [pwd]
1225        unset cdup
1226} elseif {![is_enabled bare]} {
1227        if {[is_bare]} {
1228                catch {wm withdraw .}
1229                error_popup [strcat [mc "Cannot use bare repository:"] "\n\n$_gitdir"]
1230                exit 1
1231        }
1232        if {$_gitworktree eq {}} {
1233                set _gitworktree [file dirname $_gitdir]
1234        }
1235        if {[catch {cd $_gitworktree} err]} {
1236                catch {wm withdraw .}
1237                error_popup [strcat [mc "No working directory"] " $_gitworktree:\n\n$err"]
1238                exit 1
1239        }
1240        set _gitworktree [pwd]
1241}
1242set _reponame [file split [file normalize $_gitdir]]
1243if {[lindex $_reponame end] eq {.git}} {
1244        set _reponame [lindex $_reponame end-1]
1245} else {
1246        set _reponame [lindex $_reponame end]
1247}
1248
1249set env(GIT_DIR) $_gitdir
1250set env(GIT_WORK_TREE) $_gitworktree
1251
1252######################################################################
1253##
1254## global init
1255
1256set current_diff_path {}
1257set current_diff_side {}
1258set diff_actions [list]
1259
1260set HEAD {}
1261set PARENT {}
1262set MERGE_HEAD [list]
1263set commit_type {}
1264set empty_tree {}
1265set current_branch {}
1266set is_detached 0
1267set current_diff_path {}
1268set is_3way_diff 0
1269set is_submodule_diff 0
1270set is_conflict_diff 0
1271set selected_commit_type new
1272set diff_empty_count 0
1273
1274set nullid "0000000000000000000000000000000000000000"
1275set nullid2 "0000000000000000000000000000000000000001"
1276
1277######################################################################
1278##
1279## task management
1280
1281set rescan_active 0
1282set diff_active 0
1283set last_clicked {}
1284
1285set disable_on_lock [list]
1286set index_lock_type none
1287
1288proc lock_index {type} {
1289        global index_lock_type disable_on_lock
1290
1291        if {$index_lock_type eq {none}} {
1292                set index_lock_type $type
1293                foreach w $disable_on_lock {
1294                        uplevel #0 $w disabled
1295                }
1296                return 1
1297        } elseif {$index_lock_type eq "begin-$type"} {
1298                set index_lock_type $type
1299                return 1
1300        }
1301        return 0
1302}
1303
1304proc unlock_index {} {
1305        global index_lock_type disable_on_lock
1306
1307        set index_lock_type none
1308        foreach w $disable_on_lock {
1309                uplevel #0 $w normal
1310        }
1311}
1312
1313######################################################################
1314##
1315## status
1316
1317proc repository_state {ctvar hdvar mhvar} {
1318        global current_branch
1319        upvar $ctvar ct $hdvar hd $mhvar mh
1320
1321        set mh [list]
1322
1323        load_current_branch
1324        if {[catch {set hd [git rev-parse --verify HEAD]}]} {
1325                set hd {}
1326                set ct initial
1327                return
1328        }
1329
1330        set merge_head [gitdir MERGE_HEAD]
1331        if {[file exists $merge_head]} {
1332                set ct merge
1333                set fd_mh [open $merge_head r]
1334                while {[gets $fd_mh line] >= 0} {
1335                        lappend mh $line
1336                }
1337                close $fd_mh
1338                return
1339        }
1340
1341        set ct normal
1342}
1343
1344proc PARENT {} {
1345        global PARENT empty_tree
1346
1347        set p [lindex $PARENT 0]
1348        if {$p ne {}} {
1349                return $p
1350        }
1351        if {$empty_tree eq {}} {
1352                set empty_tree [git mktree << {}]
1353        }
1354        return $empty_tree
1355}
1356
1357proc force_amend {} {
1358        global selected_commit_type
1359        global HEAD PARENT MERGE_HEAD commit_type
1360
1361        repository_state newType newHEAD newMERGE_HEAD
1362        set HEAD $newHEAD
1363        set PARENT $newHEAD
1364        set MERGE_HEAD $newMERGE_HEAD
1365        set commit_type $newType
1366
1367        set selected_commit_type amend
1368        do_select_commit_type
1369}
1370
1371proc rescan {after {honor_trustmtime 1}} {
1372        global HEAD PARENT MERGE_HEAD commit_type
1373        global ui_index ui_workdir ui_comm
1374        global rescan_active file_states
1375        global repo_config
1376
1377        if {$rescan_active > 0 || ![lock_index read]} return
1378
1379        repository_state newType newHEAD newMERGE_HEAD
1380        if {[string match amend* $commit_type]
1381                && $newType eq {normal}
1382                && $newHEAD eq $HEAD} {
1383        } else {
1384                set HEAD $newHEAD
1385                set PARENT $newHEAD
1386                set MERGE_HEAD $newMERGE_HEAD
1387                set commit_type $newType
1388        }
1389
1390        array unset file_states
1391
1392        if {!$::GITGUI_BCK_exists &&
1393                (![$ui_comm edit modified]
1394                || [string trim [$ui_comm get 0.0 end]] eq {})} {
1395                if {[string match amend* $commit_type]} {
1396                } elseif {[load_message GITGUI_MSG]} {
1397                } elseif {[run_prepare_commit_msg_hook]} {
1398                } elseif {[load_message MERGE_MSG]} {
1399                } elseif {[load_message SQUASH_MSG]} {
1400                }
1401                $ui_comm edit reset
1402                $ui_comm edit modified false
1403        }
1404
1405        if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
1406                rescan_stage2 {} $after
1407        } else {
1408                set rescan_active 1
1409                ui_status [mc "Refreshing file status..."]
1410                set fd_rf [git_read update-index \
1411                        -q \
1412                        --unmerged \
1413                        --ignore-missing \
1414                        --refresh \
1415                        ]
1416                fconfigure $fd_rf -blocking 0 -translation binary
1417                fileevent $fd_rf readable \
1418                        [list rescan_stage2 $fd_rf $after]
1419        }
1420}
1421
1422if {[is_Cygwin]} {
1423        set is_git_info_exclude {}
1424        proc have_info_exclude {} {
1425                global is_git_info_exclude
1426
1427                if {$is_git_info_exclude eq {}} {
1428                        if {[catch {exec test -f [gitdir info exclude]}]} {
1429                                set is_git_info_exclude 0
1430                        } else {
1431                                set is_git_info_exclude 1
1432                        }
1433                }
1434                return $is_git_info_exclude
1435        }
1436} else {
1437        proc have_info_exclude {} {
1438                return [file readable [gitdir info exclude]]
1439        }
1440}
1441
1442proc rescan_stage2 {fd after} {
1443        global rescan_active buf_rdi buf_rdf buf_rlo
1444
1445        if {$fd ne {}} {
1446                read $fd
1447                if {![eof $fd]} return
1448                close $fd
1449        }
1450
1451        if {[package vsatisfies $::_git_version 1.6.3]} {
1452                set ls_others [list --exclude-standard]
1453        } else {
1454                set ls_others [list --exclude-per-directory=.gitignore]
1455                if {[have_info_exclude]} {
1456                        lappend ls_others "--exclude-from=[gitdir info exclude]"
1457                }
1458                set user_exclude [get_config core.excludesfile]
1459                if {$user_exclude ne {} && [file readable $user_exclude]} {
1460                        lappend ls_others "--exclude-from=[file normalize $user_exclude]"
1461                }
1462        }
1463
1464        set buf_rdi {}
1465        set buf_rdf {}
1466        set buf_rlo {}
1467
1468        set rescan_active 3
1469        ui_status [mc "Scanning for modified files ..."]
1470        set fd_di [git_read diff-index --cached -z [PARENT]]
1471        set fd_df [git_read diff-files -z]
1472        set fd_lo [eval git_read ls-files --others -z $ls_others]
1473
1474        fconfigure $fd_di -blocking 0 -translation binary -encoding binary
1475        fconfigure $fd_df -blocking 0 -translation binary -encoding binary
1476        fconfigure $fd_lo -blocking 0 -translation binary -encoding binary
1477        fileevent $fd_di readable [list read_diff_index $fd_di $after]
1478        fileevent $fd_df readable [list read_diff_files $fd_df $after]
1479        fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
1480}
1481
1482proc load_message {file} {
1483        global ui_comm
1484
1485        set f [gitdir $file]
1486        if {[file isfile $f]} {
1487                if {[catch {set fd [open $f r]}]} {
1488                        return 0
1489                }
1490                fconfigure $fd -eofchar {}
1491                set content [string trim [read $fd]]
1492                close $fd
1493                regsub -all -line {[ \r\t]+$} $content {} content
1494                $ui_comm delete 0.0 end
1495                $ui_comm insert end $content
1496                return 1
1497        }
1498        return 0
1499}
1500
1501proc run_prepare_commit_msg_hook {} {
1502        global pch_error
1503
1504        # prepare-commit-msg requires PREPARE_COMMIT_MSG exist.  From git-gui
1505        # it will be .git/MERGE_MSG (merge), .git/SQUASH_MSG (squash), or an
1506        # empty file but existant file.
1507
1508        set fd_pcm [open [gitdir PREPARE_COMMIT_MSG] a]
1509
1510        if {[file isfile [gitdir MERGE_MSG]]} {
1511                set pcm_source "merge"
1512                set fd_mm [open [gitdir MERGE_MSG] r]
1513                puts -nonewline $fd_pcm [read $fd_mm]
1514                close $fd_mm
1515        } elseif {[file isfile [gitdir SQUASH_MSG]]} {
1516                set pcm_source "squash"
1517                set fd_sm [open [gitdir SQUASH_MSG] r]
1518                puts -nonewline $fd_pcm [read $fd_sm]
1519                close $fd_sm
1520        } else {
1521                set pcm_source ""
1522        }
1523
1524        close $fd_pcm
1525
1526        set fd_ph [githook_read prepare-commit-msg \
1527                        [gitdir PREPARE_COMMIT_MSG] $pcm_source]
1528        if {$fd_ph eq {}} {
1529                catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1530                return 0;
1531        }
1532
1533        ui_status [mc "Calling prepare-commit-msg hook..."]
1534        set pch_error {}
1535
1536        fconfigure $fd_ph -blocking 0 -translation binary -eofchar {}
1537        fileevent $fd_ph readable \
1538                [list prepare_commit_msg_hook_wait $fd_ph]
1539
1540        return 1;
1541}
1542
1543proc prepare_commit_msg_hook_wait {fd_ph} {
1544        global pch_error
1545
1546        append pch_error [read $fd_ph]
1547        fconfigure $fd_ph -blocking 1
1548        if {[eof $fd_ph]} {
1549                if {[catch {close $fd_ph}]} {
1550                        ui_status [mc "Commit declined by prepare-commit-msg hook."]
1551                        hook_failed_popup prepare-commit-msg $pch_error
1552                        catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1553                        exit 1
1554                } else {
1555                        load_message PREPARE_COMMIT_MSG
1556                }
1557                set pch_error {}
1558                catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1559                return
1560        }
1561        fconfigure $fd_ph -blocking 0
1562        catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1563}
1564
1565proc read_diff_index {fd after} {
1566        global buf_rdi
1567
1568        append buf_rdi [read $fd]
1569        set c 0
1570        set n [string length $buf_rdi]
1571        while {$c < $n} {
1572                set z1 [string first "\0" $buf_rdi $c]
1573                if {$z1 == -1} break
1574                incr z1
1575                set z2 [string first "\0" $buf_rdi $z1]
1576                if {$z2 == -1} break
1577
1578                incr c
1579                set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
1580                set p [string range $buf_rdi $z1 [expr {$z2 - 1}]]
1581                merge_state \
1582                        [encoding convertfrom $p] \
1583                        [lindex $i 4]? \
1584                        [list [lindex $i 0] [lindex $i 2]] \
1585                        [list]
1586                set c $z2
1587                incr c
1588        }
1589        if {$c < $n} {
1590                set buf_rdi [string range $buf_rdi $c end]
1591        } else {
1592                set buf_rdi {}
1593        }
1594
1595        rescan_done $fd buf_rdi $after
1596}
1597
1598proc read_diff_files {fd after} {
1599        global buf_rdf
1600
1601        append buf_rdf [read $fd]
1602        set c 0
1603        set n [string length $buf_rdf]
1604        while {$c < $n} {
1605                set z1 [string first "\0" $buf_rdf $c]
1606                if {$z1 == -1} break
1607                incr z1
1608                set z2 [string first "\0" $buf_rdf $z1]
1609                if {$z2 == -1} break
1610
1611                incr c
1612                set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
1613                set p [string range $buf_rdf $z1 [expr {$z2 - 1}]]
1614                merge_state \
1615                        [encoding convertfrom $p] \
1616                        ?[lindex $i 4] \
1617                        [list] \
1618                        [list [lindex $i 0] [lindex $i 2]]
1619                set c $z2
1620                incr c
1621        }
1622        if {$c < $n} {
1623                set buf_rdf [string range $buf_rdf $c end]
1624        } else {
1625                set buf_rdf {}
1626        }
1627
1628        rescan_done $fd buf_rdf $after
1629}
1630
1631proc read_ls_others {fd after} {
1632        global buf_rlo
1633
1634        append buf_rlo [read $fd]
1635        set pck [split $buf_rlo "\0"]
1636        set buf_rlo [lindex $pck end]
1637        foreach p [lrange $pck 0 end-1] {
1638                set p [encoding convertfrom $p]
1639                if {[string index $p end] eq {/}} {
1640                        set p [string range $p 0 end-1]
1641                }
1642                merge_state $p ?O
1643        }
1644        rescan_done $fd buf_rlo $after
1645}
1646
1647proc rescan_done {fd buf after} {
1648        global rescan_active current_diff_path
1649        global file_states repo_config
1650        upvar $buf to_clear
1651
1652        if {![eof $fd]} return
1653        set to_clear {}
1654        close $fd
1655        if {[incr rescan_active -1] > 0} return
1656
1657        prune_selection
1658        unlock_index
1659        display_all_files
1660        if {$current_diff_path ne {}} { reshow_diff $after }
1661        if {$current_diff_path eq {}} { select_first_diff $after }
1662}
1663
1664proc prune_selection {} {
1665        global file_states selected_paths
1666
1667        foreach path [array names selected_paths] {
1668                if {[catch {set still_here $file_states($path)}]} {
1669                        unset selected_paths($path)
1670                }
1671        }
1672}
1673
1674######################################################################
1675##
1676## ui helpers
1677
1678proc mapicon {w state path} {
1679        global all_icons
1680
1681        if {[catch {set r $all_icons($state$w)}]} {
1682                puts "error: no icon for $w state={$state} $path"
1683                return file_plain
1684        }
1685        return $r
1686}
1687
1688proc mapdesc {state path} {
1689        global all_descs
1690
1691        if {[catch {set r $all_descs($state)}]} {
1692                puts "error: no desc for state={$state} $path"
1693                return $state
1694        }
1695        return $r
1696}
1697
1698proc ui_status {msg} {
1699        global main_status
1700        if {[info exists main_status]} {
1701                $main_status show $msg
1702        }
1703}
1704
1705proc ui_ready {{test {}}} {
1706        global main_status
1707        if {[info exists main_status]} {
1708                $main_status show [mc "Ready."] $test
1709        }
1710}
1711
1712proc escape_path {path} {
1713        regsub -all {\\} $path "\\\\" path
1714        regsub -all "\n" $path "\\n" path
1715        return $path
1716}
1717
1718proc short_path {path} {
1719        return [escape_path [lindex [file split $path] end]]
1720}
1721
1722set next_icon_id 0
1723set null_sha1 [string repeat 0 40]
1724
1725proc merge_state {path new_state {head_info {}} {index_info {}}} {
1726        global file_states next_icon_id null_sha1
1727
1728        set s0 [string index $new_state 0]
1729        set s1 [string index $new_state 1]
1730
1731        if {[catch {set info $file_states($path)}]} {
1732                set state __
1733                set icon n[incr next_icon_id]
1734        } else {
1735                set state [lindex $info 0]
1736                set icon [lindex $info 1]
1737                if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1738                if {$index_info eq {}} {set index_info [lindex $info 3]}
1739        }
1740
1741        if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1742        elseif {$s0 eq {_}} {set s0 _}
1743
1744        if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1745        elseif {$s1 eq {_}} {set s1 _}
1746
1747        if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1748                set head_info [list 0 $null_sha1]
1749        } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1750                && $head_info eq {}} {
1751                set head_info $index_info
1752        } elseif {$s0 eq {_} && [string index $state 0] ne {_}} {
1753                set index_info $head_info
1754                set head_info {}
1755        }
1756
1757        set file_states($path) [list $s0$s1 $icon \
1758                $head_info $index_info \
1759                ]
1760        return $state
1761}
1762
1763proc display_file_helper {w path icon_name old_m new_m} {
1764        global file_lists
1765
1766        if {$new_m eq {_}} {
1767                set lno [lsearch -sorted -exact $file_lists($w) $path]
1768                if {$lno >= 0} {
1769                        set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1770                        incr lno
1771                        $w conf -state normal
1772                        $w delete $lno.0 [expr {$lno + 1}].0
1773                        $w conf -state disabled
1774                }
1775        } elseif {$old_m eq {_} && $new_m ne {_}} {
1776                lappend file_lists($w) $path
1777                set file_lists($w) [lsort -unique $file_lists($w)]
1778                set lno [lsearch -sorted -exact $file_lists($w) $path]
1779                incr lno
1780                $w conf -state normal
1781                $w image create $lno.0 \
1782                        -align center -padx 5 -pady 1 \
1783                        -name $icon_name \
1784                        -image [mapicon $w $new_m $path]
1785                $w insert $lno.1 "[escape_path $path]\n"
1786                $w conf -state disabled
1787        } elseif {$old_m ne $new_m} {
1788                $w conf -state normal
1789                $w image conf $icon_name -image [mapicon $w $new_m $path]
1790                $w conf -state disabled
1791        }
1792}
1793
1794proc display_file {path state} {
1795        global file_states selected_paths
1796        global ui_index ui_workdir
1797
1798        set old_m [merge_state $path $state]
1799        set s $file_states($path)
1800        set new_m [lindex $s 0]
1801        set icon_name [lindex $s 1]
1802
1803        set o [string index $old_m 0]
1804        set n [string index $new_m 0]
1805        if {$o eq {U}} {
1806                set o _
1807        }
1808        if {$n eq {U}} {
1809                set n _
1810        }
1811        display_file_helper     $ui_index $path $icon_name $o $n
1812
1813        if {[string index $old_m 0] eq {U}} {
1814                set o U
1815        } else {
1816                set o [string index $old_m 1]
1817        }
1818        if {[string index $new_m 0] eq {U}} {
1819                set n U
1820        } else {
1821                set n [string index $new_m 1]
1822        }
1823        display_file_helper     $ui_workdir $path $icon_name $o $n
1824
1825        if {$new_m eq {__}} {
1826                unset file_states($path)
1827                catch {unset selected_paths($path)}
1828        }
1829}
1830
1831proc display_all_files_helper {w path icon_name m} {
1832        global file_lists
1833
1834        lappend file_lists($w) $path
1835        set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1836        $w image create end \
1837                -align center -padx 5 -pady 1 \
1838                -name $icon_name \
1839                -image [mapicon $w $m $path]
1840        $w insert end "[escape_path $path]\n"
1841}
1842
1843set files_warning 0
1844proc display_all_files {} {
1845        global ui_index ui_workdir
1846        global file_states file_lists
1847        global last_clicked
1848        global files_warning
1849
1850        $ui_index conf -state normal
1851        $ui_workdir conf -state normal
1852
1853        $ui_index delete 0.0 end
1854        $ui_workdir delete 0.0 end
1855        set last_clicked {}
1856
1857        set file_lists($ui_index) [list]
1858        set file_lists($ui_workdir) [list]
1859
1860        set to_display [lsort [array names file_states]]
1861        set display_limit [get_config gui.maxfilesdisplayed]
1862        if {[llength $to_display] > $display_limit} {
1863                if {!$files_warning} {
1864                        # do not repeatedly warn:
1865                        set files_warning 1
1866                        info_popup [mc "Displaying only %s of %s files." \
1867                                $display_limit [llength $to_display]]
1868                }
1869                set to_display [lrange $to_display 0 [expr {$display_limit-1}]]
1870        }
1871        foreach path $to_display {
1872                set s $file_states($path)
1873                set m [lindex $s 0]
1874                set icon_name [lindex $s 1]
1875
1876                set s [string index $m 0]
1877                if {$s ne {U} && $s ne {_}} {
1878                        display_all_files_helper $ui_index $path \
1879                                $icon_name $s
1880                }
1881
1882                if {[string index $m 0] eq {U}} {
1883                        set s U
1884                } else {
1885                        set s [string index $m 1]
1886                }
1887                if {$s ne {_}} {
1888                        display_all_files_helper $ui_workdir $path \
1889                                $icon_name $s
1890                }
1891        }
1892
1893        $ui_index conf -state disabled
1894        $ui_workdir conf -state disabled
1895}
1896
1897######################################################################
1898##
1899## icons
1900
1901set filemask {
1902#define mask_width 14
1903#define mask_height 15
1904static unsigned char mask_bits[] = {
1905   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
1906   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
1907   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
1908}
1909
1910image create bitmap file_plain -background white -foreground black -data {
1911#define plain_width 14
1912#define plain_height 15
1913static unsigned char plain_bits[] = {
1914   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
1915   0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
1916   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1917} -maskdata $filemask
1918
1919image create bitmap file_mod -background white -foreground blue -data {
1920#define mod_width 14
1921#define mod_height 15
1922static unsigned char mod_bits[] = {
1923   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
1924   0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
1925   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
1926} -maskdata $filemask
1927
1928image create bitmap file_fulltick -background white -foreground "#007000" -data {
1929#define file_fulltick_width 14
1930#define file_fulltick_height 15
1931static unsigned char file_fulltick_bits[] = {
1932   0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
1933   0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
1934   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1935} -maskdata $filemask
1936
1937image create bitmap file_question -background white -foreground black -data {
1938#define file_question_width 14
1939#define file_question_height 15
1940static unsigned char file_question_bits[] = {
1941   0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
1942   0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
1943   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1944} -maskdata $filemask
1945
1946image create bitmap file_removed -background white -foreground red -data {
1947#define file_removed_width 14
1948#define file_removed_height 15
1949static unsigned char file_removed_bits[] = {
1950   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
1951   0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
1952   0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
1953} -maskdata $filemask
1954
1955image create bitmap file_merge -background white -foreground blue -data {
1956#define file_merge_width 14
1957#define file_merge_height 15
1958static unsigned char file_merge_bits[] = {
1959   0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
1960   0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
1961   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
1962} -maskdata $filemask
1963
1964image create bitmap file_statechange -background white -foreground green -data {
1965#define file_statechange_width 14
1966#define file_statechange_height 15
1967static unsigned char file_statechange_bits[] = {
1968   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x62, 0x10,
1969   0x62, 0x10, 0xba, 0x11, 0xba, 0x11, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10,
1970   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1971} -maskdata $filemask
1972
1973set ui_index .vpane.files.index.list
1974set ui_workdir .vpane.files.workdir.list
1975
1976set all_icons(_$ui_index)   file_plain
1977set all_icons(A$ui_index)   file_plain
1978set all_icons(M$ui_index)   file_fulltick
1979set all_icons(D$ui_index)   file_removed
1980set all_icons(U$ui_index)   file_merge
1981set all_icons(T$ui_index)   file_statechange
1982
1983set all_icons(_$ui_workdir) file_plain
1984set all_icons(M$ui_workdir) file_mod
1985set all_icons(D$ui_workdir) file_question
1986set all_icons(U$ui_workdir) file_merge
1987set all_icons(O$ui_workdir) file_plain
1988set all_icons(T$ui_workdir) file_statechange
1989
1990set max_status_desc 0
1991foreach i {
1992                {__ {mc "Unmodified"}}
1993
1994                {_M {mc "Modified, not staged"}}
1995                {M_ {mc "Staged for commit"}}
1996                {MM {mc "Portions staged for commit"}}
1997                {MD {mc "Staged for commit, missing"}}
1998
1999                {_T {mc "File type changed, not staged"}}
2000                {MT {mc "File type changed, old type staged for commit"}}
2001                {AT {mc "File type changed, old type staged for commit"}}
2002                {T_ {mc "File type changed, staged"}}
2003                {TM {mc "File type change staged, modification not staged"}}
2004                {TD {mc "File type change staged, file missing"}}
2005
2006                {_O {mc "Untracked, not staged"}}
2007                {A_ {mc "Staged for commit"}}
2008                {AM {mc "Portions staged for commit"}}
2009                {AD {mc "Staged for commit, missing"}}
2010
2011                {_D {mc "Missing"}}
2012                {D_ {mc "Staged for removal"}}
2013                {DO {mc "Staged for removal, still present"}}
2014
2015                {_U {mc "Requires merge resolution"}}
2016                {U_ {mc "Requires merge resolution"}}
2017                {UU {mc "Requires merge resolution"}}
2018                {UM {mc "Requires merge resolution"}}
2019                {UD {mc "Requires merge resolution"}}
2020                {UT {mc "Requires merge resolution"}}
2021        } {
2022        set text [eval [lindex $i 1]]
2023        if {$max_status_desc < [string length $text]} {
2024                set max_status_desc [string length $text]
2025        }
2026        set all_descs([lindex $i 0]) $text
2027}
2028unset i
2029
2030######################################################################
2031##
2032## util
2033
2034proc scrollbar2many {list mode args} {
2035        foreach w $list {eval $w $mode $args}
2036}
2037
2038proc many2scrollbar {list mode sb top bottom} {
2039        $sb set $top $bottom
2040        foreach w $list {$w $mode moveto $top}
2041}
2042
2043proc incr_font_size {font {amt 1}} {
2044        set sz [font configure $font -size]
2045        incr sz $amt
2046        font configure $font -size $sz
2047        font configure ${font}bold -size $sz
2048        font configure ${font}italic -size $sz
2049}
2050
2051######################################################################
2052##
2053## ui commands
2054
2055set starting_gitk_msg [mc "Starting gitk... please wait..."]
2056
2057proc do_gitk {revs {is_submodule false}} {
2058        global current_diff_path file_states current_diff_side ui_index
2059        global _gitdir _gitworktree
2060
2061        # -- Always start gitk through whatever we were loaded with.  This
2062        #    lets us bypass using shell process on Windows systems.
2063        #
2064        set exe [_which gitk -script]
2065        set cmd [list [info nameofexecutable] $exe]
2066        if {$exe eq {}} {
2067                error_popup [mc "Couldn't find gitk in PATH"]
2068        } else {
2069                global env
2070
2071                set pwd [pwd]
2072
2073                if {!$is_submodule} {
2074                        if {![is_bare]} {
2075                                cd $_gitworktree
2076                        }
2077                } else {
2078                        cd $current_diff_path
2079                        if {$revs eq {--}} {
2080                                set s $file_states($current_diff_path)
2081                                set old_sha1 {}
2082                                set new_sha1 {}
2083                                switch -glob -- [lindex $s 0] {
2084                                M_ { set old_sha1 [lindex [lindex $s 2] 1] }
2085                                _M { set old_sha1 [lindex [lindex $s 3] 1] }
2086                                MM {
2087                                        if {$current_diff_side eq $ui_index} {
2088                                                set old_sha1 [lindex [lindex $s 2] 1]
2089                                                set new_sha1 [lindex [lindex $s 3] 1]
2090                                        } else {
2091                                                set old_sha1 [lindex [lindex $s 3] 1]
2092                                        }
2093                                }
2094                                }
2095                                set revs $old_sha1...$new_sha1
2096                        }
2097                        # GIT_DIR and GIT_WORK_TREE for the submodule are not the ones
2098                        # we've been using for the main repository, so unset them.
2099                        # TODO we could make life easier (start up faster?) for gitk
2100                        # by setting these to the appropriate values to allow gitk
2101                        # to skip the heuristics to find their proper value
2102                        unset env(GIT_DIR)
2103                        unset env(GIT_WORK_TREE)
2104                }
2105                eval exec $cmd $revs "--" "--" &
2106
2107                set env(GIT_DIR) $_gitdir
2108                set env(GIT_WORK_TREE) $_gitworktree
2109                cd $pwd
2110
2111                ui_status $::starting_gitk_msg
2112                after 10000 {
2113                        ui_ready $starting_gitk_msg
2114                }
2115        }
2116}
2117
2118proc do_git_gui {} {
2119        global current_diff_path
2120
2121        # -- Always start git gui through whatever we were loaded with.  This
2122        #    lets us bypass using shell process on Windows systems.
2123        #
2124        set exe [list [_which git]]
2125        if {$exe eq {}} {
2126                error_popup [mc "Couldn't find git gui in PATH"]
2127        } else {
2128                global env
2129                global _gitdir _gitworktree
2130
2131                # see note in do_gitk about unsetting these vars when
2132                # running tools in a submodule
2133                unset env(GIT_DIR)
2134                unset env(GIT_WORK_TREE)
2135
2136                set pwd [pwd]
2137                cd $current_diff_path
2138
2139                eval exec $exe gui &
2140
2141                set env(GIT_DIR) $_gitdir
2142                set env(GIT_WORK_TREE) $_gitworktree
2143                cd $pwd
2144
2145                ui_status $::starting_gitk_msg
2146                after 10000 {
2147                        ui_ready $starting_gitk_msg
2148                }
2149        }
2150}
2151
2152proc do_explore {} {
2153        global _gitworktree
2154        set explorer {}
2155        if {[is_Cygwin] || [is_Windows]} {
2156                set explorer "explorer.exe"
2157        } elseif {[is_MacOSX]} {
2158                set explorer "open"
2159        } else {
2160                # freedesktop.org-conforming system is our best shot
2161                set explorer "xdg-open"
2162        }
2163        eval exec $explorer [list [file nativename $_gitworktree]] &
2164}
2165
2166set is_quitting 0
2167set ret_code    1
2168
2169proc terminate_me {win} {
2170        global ret_code
2171        if {$win ne {.}} return
2172        exit $ret_code
2173}
2174
2175proc do_quit {{rc {1}}} {
2176        global ui_comm is_quitting repo_config commit_type
2177        global GITGUI_BCK_exists GITGUI_BCK_i
2178        global ui_comm_spell
2179        global ret_code use_ttk
2180
2181        if {$is_quitting} return
2182        set is_quitting 1
2183
2184        if {[winfo exists $ui_comm]} {
2185                # -- Stash our current commit buffer.
2186                #
2187                set save [gitdir GITGUI_MSG]
2188                if {$GITGUI_BCK_exists && ![$ui_comm edit modified]} {
2189                        file rename -force [gitdir GITGUI_BCK] $save
2190                        set GITGUI_BCK_exists 0
2191                } else {
2192                        set msg [string trim [$ui_comm get 0.0 end]]
2193                        regsub -all -line {[ \r\t]+$} $msg {} msg
2194                        if {(![string match amend* $commit_type]
2195                                || [$ui_comm edit modified])
2196                                && $msg ne {}} {
2197                                catch {
2198                                        set fd [open $save w]
2199                                        puts -nonewline $fd $msg
2200                                        close $fd
2201                                }
2202                        } else {
2203                                catch {file delete $save}
2204                        }
2205                }
2206
2207                # -- Cancel our spellchecker if its running.
2208                #
2209                if {[info exists ui_comm_spell]} {
2210                        $ui_comm_spell stop
2211                }
2212
2213                # -- Remove our editor backup, its not needed.
2214                #
2215                after cancel $GITGUI_BCK_i
2216                if {$GITGUI_BCK_exists} {
2217                        catch {file delete [gitdir GITGUI_BCK]}
2218                }
2219
2220                # -- Stash our current window geometry into this repository.
2221                #
2222                set cfg_wmstate [wm state .]
2223                if {[catch {set rc_wmstate $repo_config(gui.wmstate)}]} {
2224                        set rc_wmstate {}
2225                }
2226                if {$cfg_wmstate ne $rc_wmstate} {
2227                        catch {git config gui.wmstate $cfg_wmstate}
2228                }
2229                if {$cfg_wmstate eq {zoomed}} {
2230                        # on Windows wm geometry will lie about window
2231                        # position (but not size) when window is zoomed
2232                        # restore the window before querying wm geometry
2233                        wm state . normal
2234                }
2235                set cfg_geometry [list]
2236                lappend cfg_geometry [wm geometry .]
2237                if {$use_ttk} {
2238                        lappend cfg_geometry [.vpane sashpos 0]
2239                        lappend cfg_geometry [.vpane.files sashpos 0]
2240                } else {
2241                        lappend cfg_geometry [lindex [.vpane sash coord 0] 0]
2242                        lappend cfg_geometry [lindex [.vpane.files sash coord 0] 1]
2243                }
2244                if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
2245                        set rc_geometry {}
2246                }
2247                if {$cfg_geometry ne $rc_geometry} {
2248                        catch {git config gui.geometry $cfg_geometry}
2249                }
2250        }
2251
2252        set ret_code $rc
2253
2254        # Briefly enable send again, working around Tk bug
2255        # http://sourceforge.net/tracker/?func=detail&atid=112997&aid=1821174&group_id=12997
2256        tk appname [appname]
2257
2258        destroy .
2259}
2260
2261proc do_rescan {} {
2262        rescan ui_ready
2263}
2264
2265proc ui_do_rescan {} {
2266        rescan {force_first_diff ui_ready}
2267}
2268
2269proc do_commit {} {
2270        commit_tree
2271}
2272
2273proc next_diff {{after {}}} {
2274        global next_diff_p next_diff_w next_diff_i
2275        show_diff $next_diff_p $next_diff_w {} {} $after
2276}
2277
2278proc find_anchor_pos {lst name} {
2279        set lid [lsearch -sorted -exact $lst $name]
2280
2281        if {$lid == -1} {
2282                set lid 0
2283                foreach lname $lst {
2284                        if {$lname >= $name} break
2285                        incr lid
2286                }
2287        }
2288
2289        return $lid
2290}
2291
2292proc find_file_from {flist idx delta path mmask} {
2293        global file_states
2294
2295        set len [llength $flist]
2296        while {$idx >= 0 && $idx < $len} {
2297                set name [lindex $flist $idx]
2298
2299                if {$name ne $path && [info exists file_states($name)]} {
2300                        set state [lindex $file_states($name) 0]
2301
2302                        if {$mmask eq {} || [regexp $mmask $state]} {
2303                                return $idx
2304                        }
2305                }
2306
2307                incr idx $delta
2308        }
2309
2310        return {}
2311}
2312
2313proc find_next_diff {w path {lno {}} {mmask {}}} {
2314        global next_diff_p next_diff_w next_diff_i
2315        global file_lists ui_index ui_workdir
2316
2317        set flist $file_lists($w)
2318        if {$lno eq {}} {
2319                set lno [find_anchor_pos $flist $path]
2320        } else {
2321                incr lno -1
2322        }
2323
2324        if {$mmask ne {} && ![regexp {(^\^)|(\$$)} $mmask]} {
2325                if {$w eq $ui_index} {
2326                        set mmask "^$mmask"
2327                } else {
2328                        set mmask "$mmask\$"
2329                }
2330        }
2331
2332        set idx [find_file_from $flist $lno 1 $path $mmask]
2333        if {$idx eq {}} {
2334                incr lno -1
2335                set idx [find_file_from $flist $lno -1 $path $mmask]
2336        }
2337
2338        if {$idx ne {}} {
2339                set next_diff_w $w
2340                set next_diff_p [lindex $flist $idx]
2341                set next_diff_i [expr {$idx+1}]
2342                return 1
2343        } else {
2344                return 0
2345        }
2346}
2347
2348proc next_diff_after_action {w path {lno {}} {mmask {}}} {
2349        global current_diff_path
2350
2351        if {$path ne $current_diff_path} {
2352                return {}
2353        } elseif {[find_next_diff $w $path $lno $mmask]} {
2354                return {next_diff;}
2355        } else {
2356                return {reshow_diff;}
2357        }
2358}
2359
2360proc select_first_diff {after} {
2361        global ui_workdir
2362
2363        if {[find_next_diff $ui_workdir {} 1 {^_?U}] ||
2364            [find_next_diff $ui_workdir {} 1 {[^O]$}]} {
2365                next_diff $after
2366        } else {
2367                uplevel #0 $after
2368        }
2369}
2370
2371proc force_first_diff {after} {
2372        global ui_workdir current_diff_path file_states
2373
2374        if {[info exists file_states($current_diff_path)]} {
2375                set state [lindex $file_states($current_diff_path) 0]
2376        } else {
2377                set state {OO}
2378        }
2379
2380        set reselect 0
2381        if {[string first {U} $state] >= 0} {
2382                # Already a conflict, do nothing
2383        } elseif {[find_next_diff $ui_workdir $current_diff_path {} {^_?U}]} {
2384                set reselect 1
2385        } elseif {[string index $state 1] ne {O}} {
2386                # Already a diff & no conflicts, do nothing
2387        } elseif {[find_next_diff $ui_workdir $current_diff_path {} {[^O]$}]} {
2388                set reselect 1
2389        }
2390
2391        if {$reselect} {
2392                next_diff $after
2393        } else {
2394                uplevel #0 $after
2395        }
2396}
2397
2398proc toggle_or_diff {w x y} {
2399        global file_states file_lists current_diff_path ui_index ui_workdir
2400        global last_clicked selected_paths
2401
2402        set pos [split [$w index @$x,$y] .]
2403        set lno [lindex $pos 0]
2404        set col [lindex $pos 1]
2405        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2406        if {$path eq {}} {
2407                set last_clicked {}
2408                return
2409        }
2410
2411        set last_clicked [list $w $lno]
2412        array unset selected_paths
2413        $ui_index tag remove in_sel 0.0 end
2414        $ui_workdir tag remove in_sel 0.0 end
2415
2416        # Determine the state of the file
2417        if {[info exists file_states($path)]} {
2418                set state [lindex $file_states($path) 0]
2419        } else {
2420                set state {__}
2421        }
2422
2423        # Restage the file, or simply show the diff
2424        if {$col == 0 && $y > 1} {
2425                # Conflicts need special handling
2426                if {[string first {U} $state] >= 0} {
2427                        # $w must always be $ui_workdir, but...
2428                        if {$w ne $ui_workdir} { set lno {} }
2429                        merge_stage_workdir $path $lno
2430                        return
2431                }
2432
2433                if {[string index $state 1] eq {O}} {
2434                        set mmask {}
2435                } else {
2436                        set mmask {[^O]}
2437                }
2438
2439                set after [next_diff_after_action $w $path $lno $mmask]
2440
2441                if {$w eq $ui_index} {
2442                        update_indexinfo \
2443                                "Unstaging [short_path $path] from commit" \
2444                                [list $path] \
2445                                [concat $after [list ui_ready]]
2446                } elseif {$w eq $ui_workdir} {
2447                        update_index \
2448                                "Adding [short_path $path]" \
2449                                [list $path] \
2450                                [concat $after [list ui_ready]]
2451                }
2452        } else {
2453                show_diff $path $w $lno
2454        }
2455}
2456
2457proc add_one_to_selection {w x y} {
2458        global file_lists last_clicked selected_paths
2459
2460        set lno [lindex [split [$w index @$x,$y] .] 0]
2461        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2462        if {$path eq {}} {
2463                set last_clicked {}
2464                return
2465        }
2466
2467        if {$last_clicked ne {}
2468                && [lindex $last_clicked 0] ne $w} {
2469                array unset selected_paths
2470                [lindex $last_clicked 0] tag remove in_sel 0.0 end
2471        }
2472
2473        set last_clicked [list $w $lno]
2474        if {[catch {set in_sel $selected_paths($path)}]} {
2475                set in_sel 0
2476        }
2477        if {$in_sel} {
2478                unset selected_paths($path)
2479                $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
2480        } else {
2481                set selected_paths($path) 1
2482                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
2483        }
2484}
2485
2486proc add_range_to_selection {w x y} {
2487        global file_lists last_clicked selected_paths
2488
2489        if {[lindex $last_clicked 0] ne $w} {
2490                toggle_or_diff $w $x $y
2491                return
2492        }
2493
2494        set lno [lindex [split [$w index @$x,$y] .] 0]
2495        set lc [lindex $last_clicked 1]
2496        if {$lc < $lno} {
2497                set begin $lc
2498                set end $lno
2499        } else {
2500                set begin $lno
2501                set end $lc
2502        }
2503
2504        foreach path [lrange $file_lists($w) \
2505                [expr {$begin - 1}] \
2506                [expr {$end - 1}]] {
2507                set selected_paths($path) 1
2508        }
2509        $w tag add in_sel $begin.0 [expr {$end + 1}].0
2510}
2511
2512proc show_more_context {} {
2513        global repo_config
2514        if {$repo_config(gui.diffcontext) < 99} {
2515                incr repo_config(gui.diffcontext)
2516                reshow_diff
2517        }
2518}
2519
2520proc show_less_context {} {
2521        global repo_config
2522        if {$repo_config(gui.diffcontext) > 1} {
2523                incr repo_config(gui.diffcontext) -1
2524                reshow_diff
2525        }
2526}
2527
2528######################################################################
2529##
2530## ui construction
2531
2532set ui_comm {}
2533
2534# -- Menu Bar
2535#
2536menu .mbar -tearoff 0
2537if {[is_MacOSX]} {
2538        # -- Apple Menu (Mac OS X only)
2539        #
2540        .mbar add cascade -label Apple -menu .mbar.apple
2541        menu .mbar.apple
2542}
2543.mbar add cascade -label [mc Repository] -menu .mbar.repository
2544.mbar add cascade -label [mc Edit] -menu .mbar.edit
2545if {[is_enabled branch]} {
2546        .mbar add cascade -label [mc Branch] -menu .mbar.branch
2547}
2548if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2549        .mbar add cascade -label [mc Commit@@noun] -menu .mbar.commit
2550}
2551if {[is_enabled transport]} {
2552        .mbar add cascade -label [mc Merge] -menu .mbar.merge
2553        .mbar add cascade -label [mc Remote] -menu .mbar.remote
2554}
2555if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2556        .mbar add cascade -label [mc Tools] -menu .mbar.tools
2557}
2558
2559# -- Repository Menu
2560#
2561menu .mbar.repository
2562
2563if {![is_bare]} {
2564        .mbar.repository add command \
2565                -label [mc "Explore Working Copy"] \
2566                -command {do_explore}
2567        .mbar.repository add separator
2568}
2569
2570.mbar.repository add command \
2571        -label [mc "Browse Current Branch's Files"] \
2572        -command {browser::new $current_branch}
2573set ui_browse_current [.mbar.repository index last]
2574.mbar.repository add command \
2575        -label [mc "Browse Branch Files..."] \
2576        -command browser_open::dialog
2577.mbar.repository add separator
2578
2579.mbar.repository add command \
2580        -label [mc "Visualize Current Branch's History"] \
2581        -command {do_gitk $current_branch}
2582set ui_visualize_current [.mbar.repository index last]
2583.mbar.repository add command \
2584        -label [mc "Visualize All Branch History"] \
2585        -command {do_gitk --all}
2586.mbar.repository add separator
2587
2588proc current_branch_write {args} {
2589        global current_branch
2590        .mbar.repository entryconf $::ui_browse_current \
2591                -label [mc "Browse %s's Files" $current_branch]
2592        .mbar.repository entryconf $::ui_visualize_current \
2593                -label [mc "Visualize %s's History" $current_branch]
2594}
2595trace add variable current_branch write current_branch_write
2596
2597if {[is_enabled multicommit]} {
2598        .mbar.repository add command -label [mc "Database Statistics"] \
2599                -command do_stats
2600
2601        .mbar.repository add command -label [mc "Compress Database"] \
2602                -command do_gc
2603
2604        .mbar.repository add command -label [mc "Verify Database"] \
2605                -command do_fsck_objects
2606
2607        .mbar.repository add separator
2608
2609        if {[is_Cygwin]} {
2610                .mbar.repository add command \
2611                        -label [mc "Create Desktop Icon"] \
2612                        -command do_cygwin_shortcut
2613        } elseif {[is_Windows]} {
2614                .mbar.repository add command \
2615                        -label [mc "Create Desktop Icon"] \
2616                        -command do_windows_shortcut
2617        } elseif {[is_MacOSX]} {
2618                .mbar.repository add command \
2619                        -label [mc "Create Desktop Icon"] \
2620                        -command do_macosx_app
2621        }
2622}
2623
2624if {[is_MacOSX]} {
2625        proc ::tk::mac::Quit {args} { do_quit }
2626} else {
2627        .mbar.repository add command -label [mc Quit] \
2628                -command do_quit \
2629                -accelerator $M1T-Q
2630}
2631
2632# -- Edit Menu
2633#
2634menu .mbar.edit
2635.mbar.edit add command -label [mc Undo] \
2636        -command {catch {[focus] edit undo}} \
2637        -accelerator $M1T-Z
2638.mbar.edit add command -label [mc Redo] \
2639        -command {catch {[focus] edit redo}} \
2640        -accelerator $M1T-Y
2641.mbar.edit add separator
2642.mbar.edit add command -label [mc Cut] \
2643        -command {catch {tk_textCut [focus]}} \
2644        -accelerator $M1T-X
2645.mbar.edit add command -label [mc Copy] \
2646        -command {catch {tk_textCopy [focus]}} \
2647        -accelerator $M1T-C
2648.mbar.edit add command -label [mc Paste] \
2649        -command {catch {tk_textPaste [focus]; [focus] see insert}} \
2650        -accelerator $M1T-V
2651.mbar.edit add command -label [mc Delete] \
2652        -command {catch {[focus] delete sel.first sel.last}} \
2653        -accelerator Del
2654.mbar.edit add separator
2655.mbar.edit add command -label [mc "Select All"] \
2656        -command {catch {[focus] tag add sel 0.0 end}} \
2657        -accelerator $M1T-A
2658
2659# -- Branch Menu
2660#
2661if {[is_enabled branch]} {
2662        menu .mbar.branch
2663
2664        .mbar.branch add command -label [mc "Create..."] \
2665                -command branch_create::dialog \
2666                -accelerator $M1T-N
2667        lappend disable_on_lock [list .mbar.branch entryconf \
2668                [.mbar.branch index last] -state]
2669
2670        .mbar.branch add command -label [mc "Checkout..."] \
2671                -command branch_checkout::dialog \
2672                -accelerator $M1T-O
2673        lappend disable_on_lock [list .mbar.branch entryconf \
2674                [.mbar.branch index last] -state]
2675
2676        .mbar.branch add command -label [mc "Rename..."] \
2677                -command branch_rename::dialog
2678        lappend disable_on_lock [list .mbar.branch entryconf \
2679                [.mbar.branch index last] -state]
2680
2681        .mbar.branch add command -label [mc "Delete..."] \
2682                -command branch_delete::dialog
2683        lappend disable_on_lock [list .mbar.branch entryconf \
2684                [.mbar.branch index last] -state]
2685
2686        .mbar.branch add command -label [mc "Reset..."] \
2687                -command merge::reset_hard
2688        lappend disable_on_lock [list .mbar.branch entryconf \
2689                [.mbar.branch index last] -state]
2690}
2691
2692# -- Commit Menu
2693#
2694proc commit_btn_caption {} {
2695        if {[is_enabled nocommit]} {
2696                return [mc "Done"]
2697        } else {
2698                return [mc Commit@@verb]
2699        }
2700}
2701
2702if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2703        menu .mbar.commit
2704
2705        if {![is_enabled nocommit]} {
2706                .mbar.commit add radiobutton \
2707                        -label [mc "New Commit"] \
2708                        -command do_select_commit_type \
2709                        -variable selected_commit_type \
2710                        -value new
2711                lappend disable_on_lock \
2712                        [list .mbar.commit entryconf [.mbar.commit index last] -state]
2713
2714                .mbar.commit add radiobutton \
2715                        -label [mc "Amend Last Commit"] \
2716                        -command do_select_commit_type \
2717                        -variable selected_commit_type \
2718                        -value amend
2719                lappend disable_on_lock \
2720                        [list .mbar.commit entryconf [.mbar.commit index last] -state]
2721
2722                .mbar.commit add separator
2723        }
2724
2725        .mbar.commit add command -label [mc Rescan] \
2726                -command ui_do_rescan \
2727                -accelerator F5
2728        lappend disable_on_lock \
2729                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2730
2731        .mbar.commit add command -label [mc "Stage To Commit"] \
2732                -command do_add_selection \
2733                -accelerator $M1T-T
2734        lappend disable_on_lock \
2735                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2736
2737        .mbar.commit add command -label [mc "Stage Changed Files To Commit"] \
2738                -command do_add_all \
2739                -accelerator $M1T-I
2740        lappend disable_on_lock \
2741                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2742
2743        .mbar.commit add command -label [mc "Unstage From Commit"] \
2744                -command do_unstage_selection \
2745                -accelerator $M1T-U
2746        lappend disable_on_lock \
2747                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2748
2749        .mbar.commit add command -label [mc "Revert Changes"] \
2750                -command do_revert_selection \
2751                -accelerator $M1T-J
2752        lappend disable_on_lock \
2753                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2754
2755        .mbar.commit add separator
2756
2757        .mbar.commit add command -label [mc "Show Less Context"] \
2758                -command show_less_context \
2759                -accelerator $M1T-\-
2760
2761        .mbar.commit add command -label [mc "Show More Context"] \
2762                -command show_more_context \
2763                -accelerator $M1T-=
2764
2765        .mbar.commit add separator
2766
2767        if {![is_enabled nocommitmsg]} {
2768                .mbar.commit add command -label [mc "Sign Off"] \
2769                        -command do_signoff \
2770                        -accelerator $M1T-S
2771        }
2772
2773        .mbar.commit add command -label [commit_btn_caption] \
2774                -command do_commit \
2775                -accelerator $M1T-Return
2776        lappend disable_on_lock \
2777                [list .mbar.commit entryconf [.mbar.commit index last] -state]
2778}
2779
2780# -- Merge Menu
2781#
2782if {[is_enabled branch]} {
2783        menu .mbar.merge
2784        .mbar.merge add command -label [mc "Local Merge..."] \
2785                -command merge::dialog \
2786                -accelerator $M1T-M
2787        lappend disable_on_lock \
2788                [list .mbar.merge entryconf [.mbar.merge index last] -state]
2789        .mbar.merge add command -label [mc "Abort Merge..."] \
2790                -command merge::reset_hard
2791        lappend disable_on_lock \
2792                [list .mbar.merge entryconf [.mbar.merge index last] -state]
2793}
2794
2795# -- Transport Menu
2796#
2797if {[is_enabled transport]} {
2798        menu .mbar.remote
2799
2800        .mbar.remote add command \
2801                -label [mc "Add..."] \
2802                -command remote_add::dialog \
2803                -accelerator $M1T-A
2804        .mbar.remote add command \
2805                -label [mc "Push..."] \
2806                -command do_push_anywhere \
2807                -accelerator $M1T-P
2808        .mbar.remote add command \
2809                -label [mc "Delete Branch..."] \
2810                -command remote_branch_delete::dialog
2811}
2812
2813if {[is_MacOSX]} {
2814        proc ::tk::mac::ShowPreferences {} {do_options}
2815} else {
2816        # -- Edit Menu
2817        #
2818        .mbar.edit add separator
2819        .mbar.edit add command -label [mc "Options..."] \
2820                -command do_options
2821}
2822
2823# -- Tools Menu
2824#
2825if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2826        set tools_menubar .mbar.tools
2827        menu $tools_menubar
2828        $tools_menubar add separator
2829        $tools_menubar add command -label [mc "Add..."] -command tools_add::dialog
2830        $tools_menubar add command -label [mc "Remove..."] -command tools_remove::dialog
2831        set tools_tailcnt 3
2832        if {[array names repo_config guitool.*.cmd] ne {}} {
2833                tools_populate_all
2834        }
2835}
2836
2837# -- Help Menu
2838#
2839.mbar add cascade -label [mc Help] -menu .mbar.help
2840menu .mbar.help
2841
2842if {[is_MacOSX]} {
2843        .mbar.apple add command -label [mc "About %s" [appname]] \
2844                -command do_about
2845        .mbar.apple add separator
2846} else {
2847        .mbar.help add command -label [mc "About %s" [appname]] \
2848                -command do_about
2849}
2850. configure -menu .mbar
2851
2852set doc_path [githtmldir]
2853if {$doc_path ne {}} {
2854        set doc_path [file join $doc_path index.html]
2855
2856        if {[is_Cygwin]} {
2857                set doc_path [exec cygpath --mixed $doc_path]
2858        }
2859}
2860
2861if {[file isfile $doc_path]} {
2862        set doc_url "file:$doc_path"
2863} else {
2864        set doc_url {http://www.kernel.org/pub/software/scm/git/docs/}
2865}
2866
2867proc start_browser {url} {
2868        git "web--browse" $url
2869}
2870
2871.mbar.help add command -label [mc "Online Documentation"] \
2872        -command [list start_browser $doc_url]
2873
2874.mbar.help add command -label [mc "Show SSH Key"] \
2875        -command do_ssh_key
2876
2877unset doc_path doc_url
2878
2879# -- Standard bindings
2880#
2881wm protocol . WM_DELETE_WINDOW do_quit
2882bind all <$M1B-Key-q> do_quit
2883bind all <$M1B-Key-Q> do_quit
2884bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
2885bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
2886
2887set subcommand_args {}
2888proc usage {} {
2889        set s "usage: $::argv0 $::subcommand $::subcommand_args"
2890        if {[tk windowingsystem] eq "win32"} {
2891                wm withdraw .
2892                tk_messageBox -icon info -message $s \
2893                        -title [mc "Usage"]
2894        } else {
2895                puts stderr $s
2896        }
2897        exit 1
2898}
2899
2900proc normalize_relpath {path} {
2901        set elements {}
2902        foreach item [file split $path] {
2903                if {$item eq {.}} continue
2904                if {$item eq {..} && [llength $elements] > 0
2905                    && [lindex $elements end] ne {..}} {
2906                        set elements [lrange $elements 0 end-1]
2907                        continue
2908                }
2909                lappend elements $item
2910        }
2911        return [eval file join $elements]
2912}
2913
2914# -- Not a normal commit type invocation?  Do that instead!
2915#
2916switch -- $subcommand {
2917browser -
2918blame {
2919        if {$subcommand eq "blame"} {
2920                set subcommand_args {[--line=<num>] rev? path}
2921        } else {
2922                set subcommand_args {rev? path}
2923        }
2924        if {$argv eq {}} usage
2925        set head {}
2926        set path {}
2927        set jump_spec {}
2928        set is_path 0
2929        foreach a $argv {
2930                if {$is_path || [file exists $_prefix$a]} {
2931                        if {$path ne {}} usage
2932                        set path [normalize_relpath $_prefix$a]
2933                        break
2934                } elseif {$a eq {--}} {
2935                        if {$path ne {}} {
2936                                if {$head ne {}} usage
2937                                set head $path
2938                                set path {}
2939                        }
2940                        set is_path 1
2941                } elseif {[regexp {^--line=(\d+)$} $a a lnum]} {
2942                        if {$jump_spec ne {} || $head ne {}} usage
2943                        set jump_spec [list $lnum]
2944                } elseif {$head eq {}} {
2945                        if {$head ne {}} usage
2946                        set head $a
2947                        set is_path 1
2948                } else {
2949                        usage
2950                }
2951        }
2952        unset is_path
2953
2954        if {$head ne {} && $path eq {}} {
2955                set path [normalize_relpath $_prefix$head]
2956                set head {}
2957        }
2958
2959        if {$head eq {}} {
2960                load_current_branch
2961        } else {
2962                if {[regexp {^[0-9a-f]{1,39}$} $head]} {
2963                        if {[catch {
2964                                        set head [git rev-parse --verify $head]
2965                                } err]} {
2966                                if {[tk windowingsystem] eq "win32"} {
2967                                        tk_messageBox -icon error -title [mc Error] -message $err
2968                                } else {
2969                                        puts stderr $err
2970                                }
2971                                exit 1
2972                        }
2973                }
2974                set current_branch $head
2975        }
2976
2977        wm deiconify .
2978        switch -- $subcommand {
2979        browser {
2980                if {$jump_spec ne {}} usage
2981                if {$head eq {}} {
2982                        if {$path ne {} && [file isdirectory $path]} {
2983                                set head $current_branch
2984                        } else {
2985                                set head $path
2986                                set path {}
2987                        }
2988                }
2989                browser::new $head $path
2990        }
2991        blame   {
2992                if {$head eq {} && ![file exists $path]} {
2993                        catch {wm withdraw .}
2994                        tk_messageBox \
2995                                -icon error \
2996                                -type ok \
2997                                -title [mc "git-gui: fatal error"] \
2998                                -message [mc "fatal: cannot stat path %s: No such file or directory" $path]
2999                        exit 1
3000                }
3001                blame::new $head $path $jump_spec
3002        }
3003        }
3004        return
3005}
3006citool -
3007gui {
3008        if {[llength $argv] != 0} {
3009                usage
3010        }
3011        # fall through to setup UI for commits
3012}
3013default {
3014        set err "usage: $argv0 \[{blame|browser|citool}\]"
3015        if {[tk windowingsystem] eq "win32"} {
3016                wm withdraw .
3017                tk_messageBox -icon error -message $err \
3018                        -title [mc "Usage"]
3019        } else {
3020                puts stderr $err
3021        }
3022        exit 1
3023}
3024}
3025
3026# -- Branch Control
3027#
3028${NS}::frame .branch
3029if {!$use_ttk} {.branch configure -borderwidth 1 -relief sunken}
3030${NS}::label .branch.l1 \
3031        -text [mc "Current Branch:"] \
3032        -anchor w \
3033        -justify left
3034${NS}::label .branch.cb \
3035        -textvariable current_branch \
3036        -anchor w \
3037        -justify left
3038pack .branch.l1 -side left
3039pack .branch.cb -side left -fill x
3040pack .branch -side top -fill x
3041
3042# -- Main Window Layout
3043#
3044${NS}::panedwindow .vpane -orient horizontal
3045${NS}::panedwindow .vpane.files -orient vertical
3046if {$use_ttk} {
3047        .vpane add .vpane.files
3048} else {
3049        .vpane add .vpane.files -sticky nsew -height 100 -width 200
3050}
3051pack .vpane -anchor n -side top -fill both -expand 1
3052
3053# -- Index File List
3054#
3055${NS}::frame .vpane.files.index -height 100 -width 200
3056tlabel .vpane.files.index.title \
3057        -text [mc "Staged Changes (Will Commit)"] \
3058        -background lightgreen -foreground black
3059text $ui_index -background white -foreground black \
3060        -borderwidth 0 \
3061        -width 20 -height 10 \
3062        -wrap none \
3063        -cursor $cursor_ptr \
3064        -xscrollcommand {.vpane.files.index.sx set} \
3065        -yscrollcommand {.vpane.files.index.sy set} \
3066        -state disabled
3067${NS}::scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
3068${NS}::scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
3069pack .vpane.files.index.title -side top -fill x
3070pack .vpane.files.index.sx -side bottom -fill x
3071pack .vpane.files.index.sy -side right -fill y
3072pack $ui_index -side left -fill both -expand 1
3073
3074# -- Working Directory File List
3075#
3076${NS}::frame .vpane.files.workdir -height 100 -width 200
3077tlabel .vpane.files.workdir.title -text [mc "Unstaged Changes"] \
3078        -background lightsalmon -foreground black
3079text $ui_workdir -background white -foreground black \
3080        -borderwidth 0 \
3081        -width 20 -height 10 \
3082        -wrap none \
3083        -cursor $cursor_ptr \
3084        -xscrollcommand {.vpane.files.workdir.sx set} \
3085        -yscrollcommand {.vpane.files.workdir.sy set} \
3086        -state disabled
3087${NS}::scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
3088${NS}::scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
3089pack .vpane.files.workdir.title -side top -fill x
3090pack .vpane.files.workdir.sx -side bottom -fill x
3091pack .vpane.files.workdir.sy -side right -fill y
3092pack $ui_workdir -side left -fill both -expand 1
3093
3094.vpane.files add .vpane.files.workdir
3095.vpane.files add .vpane.files.index
3096if {!$use_ttk} {
3097        .vpane.files paneconfigure .vpane.files.workdir -sticky news
3098        .vpane.files paneconfigure .vpane.files.index -sticky news
3099}
3100
3101foreach i [list $ui_index $ui_workdir] {
3102        rmsel_tag $i
3103        $i tag conf in_diff -background [$i tag cget in_sel -background]
3104}
3105unset i
3106
3107# -- Diff and Commit Area
3108#
3109${NS}::frame .vpane.lower -height 300 -width 400
3110${NS}::frame .vpane.lower.commarea
3111${NS}::frame .vpane.lower.diff -relief sunken -borderwidth 1
3112pack .vpane.lower.diff -fill both -expand 1
3113pack .vpane.lower.commarea -side bottom -fill x
3114.vpane add .vpane.lower
3115if {!$use_ttk} {.vpane paneconfigure .vpane.lower -sticky nsew}
3116
3117# -- Commit Area Buttons
3118#
3119${NS}::frame .vpane.lower.commarea.buttons
3120${NS}::label .vpane.lower.commarea.buttons.l -text {} \
3121        -anchor w \
3122        -justify left
3123pack .vpane.lower.commarea.buttons.l -side top -fill x
3124pack .vpane.lower.commarea.buttons -side left -fill y
3125
3126${NS}::button .vpane.lower.commarea.buttons.rescan -text [mc Rescan] \
3127        -command ui_do_rescan
3128pack .vpane.lower.commarea.buttons.rescan -side top -fill x
3129lappend disable_on_lock \
3130        {.vpane.lower.commarea.buttons.rescan conf -state}
3131
3132${NS}::button .vpane.lower.commarea.buttons.incall -text [mc "Stage Changed"] \
3133        -command do_add_all
3134pack .vpane.lower.commarea.buttons.incall -side top -fill x
3135lappend disable_on_lock \
3136        {.vpane.lower.commarea.buttons.incall conf -state}
3137
3138if {![is_enabled nocommitmsg]} {
3139        ${NS}::button .vpane.lower.commarea.buttons.signoff -text [mc "Sign Off"] \
3140                -command do_signoff
3141        pack .vpane.lower.commarea.buttons.signoff -side top -fill x
3142}
3143
3144${NS}::button .vpane.lower.commarea.buttons.commit -text [commit_btn_caption] \
3145        -command do_commit
3146pack .vpane.lower.commarea.buttons.commit -side top -fill x
3147lappend disable_on_lock \
3148        {.vpane.lower.commarea.buttons.commit conf -state}
3149
3150if {![is_enabled nocommit]} {
3151        ${NS}::button .vpane.lower.commarea.buttons.push -text [mc Push] \
3152                -command do_push_anywhere
3153        pack .vpane.lower.commarea.buttons.push -side top -fill x
3154}
3155
3156# -- Commit Message Buffer
3157#
3158${NS}::frame .vpane.lower.commarea.buffer
3159${NS}::frame .vpane.lower.commarea.buffer.header
3160set ui_comm .vpane.lower.commarea.buffer.t
3161set ui_coml .vpane.lower.commarea.buffer.header.l
3162
3163if {![is_enabled nocommit]} {
3164        ${NS}::radiobutton .vpane.lower.commarea.buffer.header.new \
3165                -text [mc "New Commit"] \
3166                -command do_select_commit_type \
3167                -variable selected_commit_type \
3168                -value new
3169        lappend disable_on_lock \
3170                [list .vpane.lower.commarea.buffer.header.new conf -state]
3171        ${NS}::radiobutton .vpane.lower.commarea.buffer.header.amend \
3172                -text [mc "Amend Last Commit"] \
3173                -command do_select_commit_type \
3174                -variable selected_commit_type \
3175                -value amend
3176        lappend disable_on_lock \
3177                [list .vpane.lower.commarea.buffer.header.amend conf -state]
3178}
3179
3180${NS}::label $ui_coml \
3181        -anchor w \
3182        -justify left
3183proc trace_commit_type {varname args} {
3184        global ui_coml commit_type
3185        switch -glob -- $commit_type {
3186        initial       {set txt [mc "Initial Commit Message:"]}
3187        amend         {set txt [mc "Amended Commit Message:"]}
3188        amend-initial {set txt [mc "Amended Initial Commit Message:"]}
3189        amend-merge   {set txt [mc "Amended Merge Commit Message:"]}
3190        merge         {set txt [mc "Merge Commit Message:"]}
3191        *             {set txt [mc "Commit Message:"]}
3192        }
3193        $ui_coml conf -text $txt
3194}
3195trace add variable commit_type write trace_commit_type
3196pack $ui_coml -side left -fill x
3197
3198if {![is_enabled nocommit]} {
3199        pack .vpane.lower.commarea.buffer.header.amend -side right
3200        pack .vpane.lower.commarea.buffer.header.new -side right
3201}
3202
3203text $ui_comm -background white -foreground black \
3204        -borderwidth 1 \
3205        -undo true \
3206        -maxundo 20 \
3207        -autoseparators true \
3208        -relief sunken \
3209        -width $repo_config(gui.commitmsgwidth) -height 9 -wrap none \
3210        -font font_diff \
3211        -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
3212${NS}::scrollbar .vpane.lower.commarea.buffer.sby \
3213        -command [list $ui_comm yview]
3214pack .vpane.lower.commarea.buffer.header -side top -fill x
3215pack .vpane.lower.commarea.buffer.sby -side right -fill y
3216pack $ui_comm -side left -fill y
3217pack .vpane.lower.commarea.buffer -side left -fill y
3218
3219# -- Commit Message Buffer Context Menu
3220#
3221set ctxm .vpane.lower.commarea.buffer.ctxm
3222menu $ctxm -tearoff 0
3223$ctxm add command \
3224        -label [mc Cut] \
3225        -command {tk_textCut $ui_comm}
3226$ctxm add command \
3227        -label [mc Copy] \
3228        -command {tk_textCopy $ui_comm}
3229$ctxm add command \
3230        -label [mc Paste] \
3231        -command {tk_textPaste $ui_comm}
3232$ctxm add command \
3233        -label [mc Delete] \
3234        -command {catch {$ui_comm delete sel.first sel.last}}
3235$ctxm add separator
3236$ctxm add command \
3237        -label [mc "Select All"] \
3238        -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
3239$ctxm add command \
3240        -label [mc "Copy All"] \
3241        -command {
3242                $ui_comm tag add sel 0.0 end
3243                tk_textCopy $ui_comm
3244                $ui_comm tag remove sel 0.0 end
3245        }
3246$ctxm add separator
3247$ctxm add command \
3248        -label [mc "Sign Off"] \
3249        -command do_signoff
3250set ui_comm_ctxm $ctxm
3251
3252# -- Diff Header
3253#
3254proc trace_current_diff_path {varname args} {
3255        global current_diff_path diff_actions file_states
3256        if {$current_diff_path eq {}} {
3257                set s {}
3258                set f {}
3259                set p {}
3260                set o disabled
3261        } else {
3262                set p $current_diff_path
3263                set s [mapdesc [lindex $file_states($p) 0] $p]
3264                set f [mc "File:"]
3265                set p [escape_path $p]
3266                set o normal
3267        }
3268
3269        .vpane.lower.diff.header.status configure -text $s
3270        .vpane.lower.diff.header.file configure -text $f
3271        .vpane.lower.diff.header.path configure -text $p
3272        foreach w $diff_actions {
3273                uplevel #0 $w $o
3274        }
3275}
3276trace add variable current_diff_path write trace_current_diff_path
3277
3278gold_frame .vpane.lower.diff.header
3279tlabel .vpane.lower.diff.header.status \
3280        -background gold \
3281        -foreground black \
3282        -width $max_status_desc \
3283        -anchor w \
3284        -justify left
3285tlabel .vpane.lower.diff.header.file \
3286        -background gold \
3287        -foreground black \
3288        -anchor w \
3289        -justify left
3290tlabel .vpane.lower.diff.header.path \
3291        -background gold \
3292        -foreground black \
3293        -anchor w \
3294        -justify left
3295pack .vpane.lower.diff.header.status -side left
3296pack .vpane.lower.diff.header.file -side left
3297pack .vpane.lower.diff.header.path -fill x
3298set ctxm .vpane.lower.diff.header.ctxm
3299menu $ctxm -tearoff 0
3300$ctxm add command \
3301        -label [mc Copy] \
3302        -command {
3303                clipboard clear
3304                clipboard append \
3305                        -format STRING \
3306                        -type STRING \
3307                        -- $current_diff_path
3308        }
3309lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3310bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
3311
3312# -- Diff Body
3313#
3314${NS}::frame .vpane.lower.diff.body
3315set ui_diff .vpane.lower.diff.body.t
3316text $ui_diff -background white -foreground black \
3317        -borderwidth 0 \
3318        -width 80 -height 5 -wrap none \
3319        -font font_diff \
3320        -xscrollcommand {.vpane.lower.diff.body.sbx set} \
3321        -yscrollcommand {.vpane.lower.diff.body.sby set} \
3322        -state disabled
3323catch {$ui_diff configure -tabstyle wordprocessor}
3324${NS}::scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
3325        -command [list $ui_diff xview]
3326${NS}::scrollbar .vpane.lower.diff.body.sby -orient vertical \
3327        -command [list $ui_diff yview]
3328pack .vpane.lower.diff.body.sbx -side bottom -fill x
3329pack .vpane.lower.diff.body.sby -side right -fill y
3330pack $ui_diff -side left -fill both -expand 1
3331pack .vpane.lower.diff.header -side top -fill x
3332pack .vpane.lower.diff.body -side bottom -fill both -expand 1
3333
3334foreach {n c} {0 black 1 red4 2 green4 3 yellow4 4 blue4 5 magenta4 6 cyan4 7 grey60} {
3335        $ui_diff tag configure clr4$n -background $c
3336        $ui_diff tag configure clri4$n -foreground $c
3337        $ui_diff tag configure clr3$n -foreground $c
3338        $ui_diff tag configure clri3$n -background $c
3339}
3340$ui_diff tag configure clr1 -font font_diffbold
3341
3342$ui_diff tag conf d_info -foreground blue -font font_diffbold
3343
3344$ui_diff tag conf d_cr -elide true
3345$ui_diff tag conf d_@ -font font_diffbold
3346$ui_diff tag conf d_+ -foreground {#00a000}
3347$ui_diff tag conf d_- -foreground red
3348
3349$ui_diff tag conf d_++ -foreground {#00a000}
3350$ui_diff tag conf d_-- -foreground red
3351$ui_diff tag conf d_+s \
3352        -foreground {#00a000} \
3353        -background {#e2effa}
3354$ui_diff tag conf d_-s \
3355        -foreground red \
3356        -background {#e2effa}
3357$ui_diff tag conf d_s+ \
3358        -foreground {#00a000} \
3359        -background ivory1
3360$ui_diff tag conf d_s- \
3361        -foreground red \
3362        -background ivory1
3363
3364$ui_diff tag conf d< \
3365        -foreground orange \
3366        -font font_diffbold
3367$ui_diff tag conf d= \
3368        -foreground orange \
3369        -font font_diffbold
3370$ui_diff tag conf d> \
3371        -foreground orange \
3372        -font font_diffbold
3373
3374$ui_diff tag raise sel
3375
3376# -- Diff Body Context Menu
3377#
3378
3379proc create_common_diff_popup {ctxm} {
3380        $ctxm add command \
3381                -label [mc Refresh] \
3382                -command reshow_diff
3383        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3384        $ctxm add command \
3385                -label [mc Copy] \
3386                -command {tk_textCopy $ui_diff}
3387        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3388        $ctxm add command \
3389                -label [mc "Select All"] \
3390                -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
3391        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3392        $ctxm add command \
3393                -label [mc "Copy All"] \
3394                -command {
3395                        $ui_diff tag add sel 0.0 end
3396                        tk_textCopy $ui_diff
3397                        $ui_diff tag remove sel 0.0 end
3398                }
3399        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3400        $ctxm add separator
3401        $ctxm add command \
3402                -label [mc "Decrease Font Size"] \
3403                -command {incr_font_size font_diff -1}
3404        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3405        $ctxm add command \
3406                -label [mc "Increase Font Size"] \
3407                -command {incr_font_size font_diff 1}
3408        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3409        $ctxm add separator
3410        set emenu $ctxm.enc
3411        menu $emenu
3412        build_encoding_menu $emenu [list force_diff_encoding]
3413        $ctxm add cascade \
3414                -label [mc "Encoding"] \
3415                -menu $emenu
3416        lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3417        $ctxm add separator
3418        $ctxm add command -label [mc "Options..."] \
3419                -command do_options
3420}
3421
3422set ctxm .vpane.lower.diff.body.ctxm
3423menu $ctxm -tearoff 0
3424$ctxm add command \
3425        -label [mc "Apply/Reverse Hunk"] \
3426        -command {apply_hunk $cursorX $cursorY}
3427set ui_diff_applyhunk [$ctxm index last]
3428lappend diff_actions [list $ctxm entryconf $ui_diff_applyhunk -state]
3429$ctxm add command \
3430        -label [mc "Apply/Reverse Line"] \
3431        -command {apply_range_or_line $cursorX $cursorY; do_rescan}
3432set ui_diff_applyline [$ctxm index last]
3433lappend diff_actions [list $ctxm entryconf $ui_diff_applyline -state]
3434$ctxm add separator
3435$ctxm add command \
3436        -label [mc "Show Less Context"] \
3437        -command show_less_context
3438lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3439$ctxm add command \
3440        -label [mc "Show More Context"] \
3441        -command show_more_context
3442lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3443$ctxm add separator
3444create_common_diff_popup $ctxm
3445
3446set ctxmmg .vpane.lower.diff.body.ctxmmg
3447menu $ctxmmg -tearoff 0
3448$ctxmmg add command \
3449        -label [mc "Run Merge Tool"] \
3450        -command {merge_resolve_tool}
3451lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3452$ctxmmg add separator
3453$ctxmmg add command \
3454        -label [mc "Use Remote Version"] \
3455        -command {merge_resolve_one 3}
3456lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3457$ctxmmg add command \
3458        -label [mc "Use Local Version"] \
3459        -command {merge_resolve_one 2}
3460lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3461$ctxmmg add command \
3462        -label [mc "Revert To Base"] \
3463        -command {merge_resolve_one 1}
3464lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3465$ctxmmg add separator
3466$ctxmmg add command \
3467        -label [mc "Show Less Context"] \
3468        -command show_less_context
3469lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3470$ctxmmg add command \
3471        -label [mc "Show More Context"] \
3472        -command show_more_context
3473lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3474$ctxmmg add separator
3475create_common_diff_popup $ctxmmg
3476
3477set ctxmsm .vpane.lower.diff.body.ctxmsm
3478menu $ctxmsm -tearoff 0
3479$ctxmsm add command \
3480        -label [mc "Visualize These Changes In The Submodule"] \
3481        -command {do_gitk -- true}
3482lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3483$ctxmsm add command \
3484        -label [mc "Visualize Current Branch History In The Submodule"] \
3485        -command {do_gitk {} true}
3486lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3487$ctxmsm add command \
3488        -label [mc "Visualize All Branch History In The Submodule"] \
3489        -command {do_gitk --all true}
3490lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3491$ctxmsm add separator
3492$ctxmsm add command \
3493        -label [mc "Start git gui In The Submodule"] \
3494        -command {do_git_gui}
3495lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3496$ctxmsm add separator
3497create_common_diff_popup $ctxmsm
3498
3499proc has_textconv {path} {
3500        if {[is_config_false gui.textconv]} {
3501                return 0
3502        }
3503        set filter [gitattr $path diff set]
3504        set textconv [get_config [join [list diff $filter textconv] .]]
3505        if {$filter ne {set} && $textconv ne {}} {
3506                return 1
3507        } else {
3508                return 0
3509        }
3510}
3511
3512proc popup_diff_menu {ctxm ctxmmg ctxmsm x y X Y} {
3513        global current_diff_path file_states
3514        set ::cursorX $x
3515        set ::cursorY $y
3516        if {[info exists file_states($current_diff_path)]} {
3517                set state [lindex $file_states($current_diff_path) 0]
3518        } else {
3519                set state {__}
3520        }
3521        if {[string first {U} $state] >= 0} {
3522                tk_popup $ctxmmg $X $Y
3523        } elseif {$::is_submodule_diff} {
3524                tk_popup $ctxmsm $X $Y
3525        } else {
3526                set has_range [expr {[$::ui_diff tag nextrange sel 0.0] != {}}]
3527                if {$::ui_index eq $::current_diff_side} {
3528                        set l [mc "Unstage Hunk From Commit"]
3529                        if {$has_range} {
3530                                set t [mc "Unstage Lines From Commit"]
3531                        } else {
3532                                set t [mc "Unstage Line From Commit"]
3533                        }
3534                } else {
3535                        set l [mc "Stage Hunk For Commit"]
3536                        if {$has_range} {
3537                                set t [mc "Stage Lines For Commit"]
3538                        } else {
3539                                set t [mc "Stage Line For Commit"]
3540                        }
3541                }
3542                if {$::is_3way_diff
3543                        || $current_diff_path eq {}
3544                        || {__} eq $state
3545                        || {_O} eq $state
3546                        || [string match {?T} $state]
3547                        || [string match {T?} $state]
3548                        || [has_textconv $current_diff_path]} {
3549                        set s disabled
3550                } else {
3551                        set s normal
3552                }
3553                $ctxm entryconf $::ui_diff_applyhunk -state $s -label $l
3554                $ctxm entryconf $::ui_diff_applyline -state $s -label $t
3555                tk_popup $ctxm $X $Y
3556        }
3557}
3558bind_button3 $ui_diff [list popup_diff_menu $ctxm $ctxmmg $ctxmsm %x %y %X %Y]
3559
3560# -- Status Bar
3561#
3562set main_status [::status_bar::new .status]
3563pack .status -anchor w -side bottom -fill x
3564$main_status show [mc "Initializing..."]
3565
3566# -- Load geometry
3567#
3568proc on_ttk_pane_mapped {w pane pos} {
3569        bind $w <Map> {}
3570        after 0 [list after idle [list $w sashpos $pane $pos]]
3571}
3572proc on_tk_pane_mapped {w pane x y} {
3573        bind $w <Map> {}
3574        after 0 [list after idle [list $w sash place $pane $x $y]]
3575}
3576proc on_application_mapped {} {
3577        global repo_config use_ttk
3578        bind . <Map> {}
3579        set gm $repo_config(gui.geometry)
3580        if {$use_ttk} {
3581                bind .vpane <Map> \
3582                    [list on_ttk_pane_mapped %W 0 [lindex $gm 1]]
3583                bind .vpane.files <Map> \
3584                    [list on_ttk_pane_mapped %W 0 [lindex $gm 2]]
3585        } else {
3586                bind .vpane <Map> \
3587                    [list on_tk_pane_mapped %W 0 \
3588                         [lindex $gm 1] \
3589                         [lindex [.vpane sash coord 0] 1]]
3590                bind .vpane.files <Map> \
3591                    [list on_tk_pane_mapped %W 0 \
3592                         [lindex [.vpane.files sash coord 0] 0] \
3593                         [lindex $gm 2]]
3594        }
3595        wm geometry . [lindex $gm 0]
3596}
3597if {[info exists repo_config(gui.geometry)]} {
3598        bind . <Map> [list on_application_mapped]
3599        wm geometry . [lindex $repo_config(gui.geometry) 0]
3600}
3601
3602# -- Load window state
3603#
3604if {[info exists repo_config(gui.wmstate)]} {
3605        catch {wm state . $repo_config(gui.wmstate)}
3606}
3607
3608# -- Key Bindings
3609#
3610bind $ui_comm <$M1B-Key-Return> {do_commit;break}
3611bind $ui_comm <$M1B-Key-t> {do_add_selection;break}
3612bind $ui_comm <$M1B-Key-T> {do_add_selection;break}
3613bind $ui_comm <$M1B-Key-u> {do_unstage_selection;break}
3614bind $ui_comm <$M1B-Key-U> {do_unstage_selection;break}
3615bind $ui_comm <$M1B-Key-j> {do_revert_selection;break}
3616bind $ui_comm <$M1B-Key-J> {do_revert_selection;break}
3617bind $ui_comm <$M1B-Key-i> {do_add_all;break}
3618bind $ui_comm <$M1B-Key-I> {do_add_all;break}
3619bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
3620bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
3621bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
3622bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
3623bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
3624bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
3625bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3626bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3627bind $ui_comm <$M1B-Key-minus> {show_less_context;break}
3628bind $ui_comm <$M1B-Key-KP_Subtract> {show_less_context;break}
3629bind $ui_comm <$M1B-Key-equal> {show_more_context;break}
3630bind $ui_comm <$M1B-Key-plus> {show_more_context;break}
3631bind $ui_comm <$M1B-Key-KP_Add> {show_more_context;break}
3632
3633bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
3634bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
3635bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
3636bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
3637bind $ui_diff <$M1B-Key-v> {break}
3638bind $ui_diff <$M1B-Key-V> {break}
3639bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3640bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3641bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
3642bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
3643bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
3644bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
3645bind $ui_diff <Key-k>         {catch {%W yview scroll -1 units};break}
3646bind $ui_diff <Key-j>         {catch {%W yview scroll  1 units};break}
3647bind $ui_diff <Key-h>         {catch {%W xview scroll -1 units};break}
3648bind $ui_diff <Key-l>         {catch {%W xview scroll  1 units};break}
3649bind $ui_diff <Control-Key-b> {catch {%W yview scroll -1 pages};break}
3650bind $ui_diff <Control-Key-f> {catch {%W yview scroll  1 pages};break}
3651bind $ui_diff <Button-1>   {focus %W}
3652
3653if {[is_enabled branch]} {
3654        bind . <$M1B-Key-n> branch_create::dialog
3655        bind . <$M1B-Key-N> branch_create::dialog
3656        bind . <$M1B-Key-o> branch_checkout::dialog
3657        bind . <$M1B-Key-O> branch_checkout::dialog
3658        bind . <$M1B-Key-m> merge::dialog
3659        bind . <$M1B-Key-M> merge::dialog
3660}
3661if {[is_enabled transport]} {
3662        bind . <$M1B-Key-p> do_push_anywhere
3663        bind . <$M1B-Key-P> do_push_anywhere
3664}
3665
3666bind .   <Key-F5>     ui_do_rescan
3667bind .   <$M1B-Key-r> ui_do_rescan
3668bind .   <$M1B-Key-R> ui_do_rescan
3669bind .   <$M1B-Key-s> do_signoff
3670bind .   <$M1B-Key-S> do_signoff
3671bind .   <$M1B-Key-t> do_add_selection
3672bind .   <$M1B-Key-T> do_add_selection
3673bind .   <$M1B-Key-j> do_revert_selection
3674bind .   <$M1B-Key-J> do_revert_selection
3675bind .   <$M1B-Key-i> do_add_all
3676bind .   <$M1B-Key-I> do_add_all
3677bind .   <$M1B-Key-minus> {show_less_context;break}
3678bind .   <$M1B-Key-KP_Subtract> {show_less_context;break}
3679bind .   <$M1B-Key-equal> {show_more_context;break}
3680bind .   <$M1B-Key-plus> {show_more_context;break}
3681bind .   <$M1B-Key-KP_Add> {show_more_context;break}
3682bind .   <$M1B-Key-Return> do_commit
3683foreach i [list $ui_index $ui_workdir] {
3684        bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
3685        bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
3686        bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
3687}
3688unset i
3689
3690set file_lists($ui_index) [list]
3691set file_lists($ui_workdir) [list]
3692
3693wm title . "[appname] ([reponame]) [file normalize $_gitworktree]"
3694focus -force $ui_comm
3695
3696# -- Warn the user about environmental problems.  Cygwin's Tcl
3697#    does *not* pass its env array onto any processes it spawns.
3698#    This means that git processes get none of our environment.
3699#
3700if {[is_Cygwin]} {
3701        set ignored_env 0
3702        set suggest_user {}
3703        set msg [mc "Possible environment issues exist.
3704
3705The following environment variables are probably
3706going to be ignored by any Git subprocess run
3707by %s:
3708
3709" [appname]]
3710        foreach name [array names env] {
3711                switch -regexp -- $name {
3712                {^GIT_INDEX_FILE$} -
3713                {^GIT_OBJECT_DIRECTORY$} -
3714                {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
3715                {^GIT_DIFF_OPTS$} -
3716                {^GIT_EXTERNAL_DIFF$} -
3717                {^GIT_PAGER$} -
3718                {^GIT_TRACE$} -
3719                {^GIT_CONFIG$} -
3720                {^GIT_(AUTHOR|COMMITTER)_DATE$} {
3721                        append msg " - $name\n"
3722                        incr ignored_env
3723                }
3724                {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
3725                        append msg " - $name\n"
3726                        incr ignored_env
3727                        set suggest_user $name
3728                }
3729                }
3730        }
3731        if {$ignored_env > 0} {
3732                append msg [mc "
3733This is due to a known issue with the
3734Tcl binary distributed by Cygwin."]
3735
3736                if {$suggest_user ne {}} {
3737                        append msg [mc "
3738
3739A good replacement for %s
3740is placing values for the user.name and
3741user.email settings into your personal
3742~/.gitconfig file.
3743" $suggest_user]
3744                }
3745                warn_popup $msg
3746        }
3747        unset ignored_env msg suggest_user name
3748}
3749
3750# -- Only initialize complex UI if we are going to stay running.
3751#
3752if {[is_enabled transport]} {
3753        load_all_remotes
3754
3755        set n [.mbar.remote index end]
3756        populate_remotes_menu
3757        set n [expr {[.mbar.remote index end] - $n}]
3758        if {$n > 0} {
3759                if {[.mbar.remote type 0] eq "tearoff"} { incr n }
3760                .mbar.remote insert $n separator
3761        }
3762        unset n
3763}
3764
3765if {[winfo exists $ui_comm]} {
3766        set GITGUI_BCK_exists [load_message GITGUI_BCK]
3767
3768        # -- If both our backup and message files exist use the
3769        #    newer of the two files to initialize the buffer.
3770        #
3771        if {$GITGUI_BCK_exists} {
3772                set m [gitdir GITGUI_MSG]
3773                if {[file isfile $m]} {
3774                        if {[file mtime [gitdir GITGUI_BCK]] > [file mtime $m]} {
3775                                catch {file delete [gitdir GITGUI_MSG]}
3776                        } else {
3777                                $ui_comm delete 0.0 end
3778                                $ui_comm edit reset
3779                                $ui_comm edit modified false
3780                                catch {file delete [gitdir GITGUI_BCK]}
3781                                set GITGUI_BCK_exists 0
3782                        }
3783                }
3784                unset m
3785        }
3786
3787        proc backup_commit_buffer {} {
3788                global ui_comm GITGUI_BCK_exists
3789
3790                set m [$ui_comm edit modified]
3791                if {$m || $GITGUI_BCK_exists} {
3792                        set msg [string trim [$ui_comm get 0.0 end]]
3793                        regsub -all -line {[ \r\t]+$} $msg {} msg
3794
3795                        if {$msg eq {}} {
3796                                if {$GITGUI_BCK_exists} {
3797                                        catch {file delete [gitdir GITGUI_BCK]}
3798                                        set GITGUI_BCK_exists 0
3799                                }
3800                        } elseif {$m} {
3801                                catch {
3802                                        set fd [open [gitdir GITGUI_BCK] w]
3803                                        puts -nonewline $fd $msg
3804                                        close $fd
3805                                        set GITGUI_BCK_exists 1
3806                                }
3807                        }
3808
3809                        $ui_comm edit modified false
3810                }
3811
3812                set ::GITGUI_BCK_i [after 2000 backup_commit_buffer]
3813        }
3814
3815        backup_commit_buffer
3816
3817        # -- If the user has aspell available we can drive it
3818        #    in pipe mode to spellcheck the commit message.
3819        #
3820        set spell_cmd [list |]
3821        set spell_dict [get_config gui.spellingdictionary]
3822        lappend spell_cmd aspell
3823        if {$spell_dict ne {}} {
3824                lappend spell_cmd --master=$spell_dict
3825        }
3826        lappend spell_cmd --mode=none
3827        lappend spell_cmd --encoding=utf-8
3828        lappend spell_cmd pipe
3829        if {$spell_dict eq {none}
3830         || [catch {set spell_fd [open $spell_cmd r+]} spell_err]} {
3831                bind_button3 $ui_comm [list tk_popup $ui_comm_ctxm %X %Y]
3832        } else {
3833                set ui_comm_spell [spellcheck::init \
3834                        $spell_fd \
3835                        $ui_comm \
3836                        $ui_comm_ctxm \
3837                ]
3838        }
3839        unset -nocomplain spell_cmd spell_fd spell_err spell_dict
3840}
3841
3842lock_index begin-read
3843if {![winfo ismapped .]} {
3844        wm deiconify .
3845}
3846after 1 {
3847        if {[is_enabled initialamend]} {
3848                force_amend
3849        } else {
3850                do_rescan
3851        }
3852
3853        if {[is_enabled nocommitmsg]} {
3854                $ui_comm configure -state disabled -background gray
3855        }
3856}
3857if {[is_enabled multicommit]} {
3858        after 1000 hint_gc
3859}
3860if {[is_enabled retcode]} {
3861        bind . <Destroy> {+terminate_me %W}
3862}
3863if {$picked && [is_config_true gui.autoexplore]} {
3864        do_explore
3865}
3866
3867# Local variables:
3868# mode: tcl
3869# indent-tabs-mode: t
3870# tab-width: 4
3871# End: