git-gui.shon commit git-gui: Create new branches from a tag. (101e3ae)
   1#!/bin/sh
   2# Tcl ignores the next line -*- tcl -*- \
   3exec wish "$0" -- "$@"
   4
   5set appvers {@@GITGUI_VERSION@@}
   6set copyright {
   7Copyright © 2006, 2007 Shawn Pearce, Paul Mackerras.
   8
   9This program is free software; you can redistribute it and/or modify
  10it under the terms of the GNU General Public License as published by
  11the Free Software Foundation; either version 2 of the License, or
  12(at your option) any later version.
  13
  14This program is distributed in the hope that it will be useful,
  15but WITHOUT ANY WARRANTY; without even the implied warranty of
  16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17GNU General Public License for more details.
  18
  19You should have received a copy of the GNU General Public License
  20along with this program; if not, write to the Free Software
  21Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA}
  22
  23######################################################################
  24##
  25## read only globals
  26
  27set _appname [lindex [file split $argv0] end]
  28set _gitdir {}
  29set _gitexec {}
  30set _reponame {}
  31set _iscygwin {}
  32
  33proc appname {} {
  34        global _appname
  35        return $_appname
  36}
  37
  38proc gitdir {args} {
  39        global _gitdir
  40        if {$args eq {}} {
  41                return $_gitdir
  42        }
  43        return [eval [concat [list file join $_gitdir] $args]]
  44}
  45
  46proc gitexec {args} {
  47        global _gitexec
  48        if {$_gitexec eq {}} {
  49                if {[catch {set _gitexec [git --exec-path]} err]} {
  50                        error "Git not installed?\n\n$err"
  51                }
  52        }
  53        if {$args eq {}} {
  54                return $_gitexec
  55        }
  56        return [eval [concat [list file join $_gitexec] $args]]
  57}
  58
  59proc reponame {} {
  60        global _reponame
  61        return $_reponame
  62}
  63
  64proc is_MacOSX {} {
  65        global tcl_platform tk_library
  66        if {[tk windowingsystem] eq {aqua}} {
  67                return 1
  68        }
  69        return 0
  70}
  71
  72proc is_Windows {} {
  73        global tcl_platform
  74        if {$tcl_platform(platform) eq {windows}} {
  75                return 1
  76        }
  77        return 0
  78}
  79
  80proc is_Cygwin {} {
  81        global tcl_platform _iscygwin
  82        if {$_iscygwin eq {}} {
  83                if {$tcl_platform(platform) eq {windows}} {
  84                        if {[catch {set p [exec cygpath --windir]} err]} {
  85                                set _iscygwin 0
  86                        } else {
  87                                set _iscygwin 1
  88                        }
  89                } else {
  90                        set _iscygwin 0
  91                }
  92        }
  93        return $_iscygwin
  94}
  95
  96proc is_enabled {option} {
  97        global enabled_options
  98        if {[catch {set on $enabled_options($option)}]} {return 0}
  99        return $on
 100}
 101
 102proc enable_option {option} {
 103        global enabled_options
 104        set enabled_options($option) 1
 105}
 106
 107proc disable_option {option} {
 108        global enabled_options
 109        set enabled_options($option) 0
 110}
 111
 112######################################################################
 113##
 114## config
 115
 116proc is_many_config {name} {
 117        switch -glob -- $name {
 118        remote.*.fetch -
 119        remote.*.push
 120                {return 1}
 121        *
 122                {return 0}
 123        }
 124}
 125
 126proc is_config_true {name} {
 127        global repo_config
 128        if {[catch {set v $repo_config($name)}]} {
 129                return 0
 130        } elseif {$v eq {true} || $v eq {1} || $v eq {yes}} {
 131                return 1
 132        } else {
 133                return 0
 134        }
 135}
 136
 137proc load_config {include_global} {
 138        global repo_config global_config default_config
 139
 140        array unset global_config
 141        if {$include_global} {
 142                catch {
 143                        set fd_rc [open "| git config --global --list" r]
 144                        while {[gets $fd_rc line] >= 0} {
 145                                if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
 146                                        if {[is_many_config $name]} {
 147                                                lappend global_config($name) $value
 148                                        } else {
 149                                                set global_config($name) $value
 150                                        }
 151                                }
 152                        }
 153                        close $fd_rc
 154                }
 155        }
 156
 157        array unset repo_config
 158        catch {
 159                set fd_rc [open "| git config --list" r]
 160                while {[gets $fd_rc line] >= 0} {
 161                        if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
 162                                if {[is_many_config $name]} {
 163                                        lappend repo_config($name) $value
 164                                } else {
 165                                        set repo_config($name) $value
 166                                }
 167                        }
 168                }
 169                close $fd_rc
 170        }
 171
 172        foreach name [array names default_config] {
 173                if {[catch {set v $global_config($name)}]} {
 174                        set global_config($name) $default_config($name)
 175                }
 176                if {[catch {set v $repo_config($name)}]} {
 177                        set repo_config($name) $default_config($name)
 178                }
 179        }
 180}
 181
 182proc save_config {} {
 183        global default_config font_descs
 184        global repo_config global_config
 185        global repo_config_new global_config_new
 186
 187        foreach option $font_descs {
 188                set name [lindex $option 0]
 189                set font [lindex $option 1]
 190                font configure $font \
 191                        -family $global_config_new(gui.$font^^family) \
 192                        -size $global_config_new(gui.$font^^size)
 193                font configure ${font}bold \
 194                        -family $global_config_new(gui.$font^^family) \
 195                        -size $global_config_new(gui.$font^^size)
 196                set global_config_new(gui.$name) [font configure $font]
 197                unset global_config_new(gui.$font^^family)
 198                unset global_config_new(gui.$font^^size)
 199        }
 200
 201        foreach name [array names default_config] {
 202                set value $global_config_new($name)
 203                if {$value ne $global_config($name)} {
 204                        if {$value eq $default_config($name)} {
 205                                catch {git config --global --unset $name}
 206                        } else {
 207                                regsub -all "\[{}\]" $value {"} value
 208                                git config --global $name $value
 209                        }
 210                        set global_config($name) $value
 211                        if {$value eq $repo_config($name)} {
 212                                catch {git config --unset $name}
 213                                set repo_config($name) $value
 214                        }
 215                }
 216        }
 217
 218        foreach name [array names default_config] {
 219                set value $repo_config_new($name)
 220                if {$value ne $repo_config($name)} {
 221                        if {$value eq $global_config($name)} {
 222                                catch {git config --unset $name}
 223                        } else {
 224                                regsub -all "\[{}\]" $value {"} value
 225                                git config $name $value
 226                        }
 227                        set repo_config($name) $value
 228                }
 229        }
 230}
 231
 232######################################################################
 233##
 234## handy utils
 235
 236proc git {args} {
 237        return [eval exec git $args]
 238}
 239
 240proc error_popup {msg} {
 241        set title [appname]
 242        if {[reponame] ne {}} {
 243                append title " ([reponame])"
 244        }
 245        set cmd [list tk_messageBox \
 246                -icon error \
 247                -type ok \
 248                -title "$title: error" \
 249                -message $msg]
 250        if {[winfo ismapped .]} {
 251                lappend cmd -parent .
 252        }
 253        eval $cmd
 254}
 255
 256proc warn_popup {msg} {
 257        set title [appname]
 258        if {[reponame] ne {}} {
 259                append title " ([reponame])"
 260        }
 261        set cmd [list tk_messageBox \
 262                -icon warning \
 263                -type ok \
 264                -title "$title: warning" \
 265                -message $msg]
 266        if {[winfo ismapped .]} {
 267                lappend cmd -parent .
 268        }
 269        eval $cmd
 270}
 271
 272proc info_popup {msg {parent .}} {
 273        set title [appname]
 274        if {[reponame] ne {}} {
 275                append title " ([reponame])"
 276        }
 277        tk_messageBox \
 278                -parent $parent \
 279                -icon info \
 280                -type ok \
 281                -title $title \
 282                -message $msg
 283}
 284
 285proc ask_popup {msg} {
 286        set title [appname]
 287        if {[reponame] ne {}} {
 288                append title " ([reponame])"
 289        }
 290        return [tk_messageBox \
 291                -parent . \
 292                -icon question \
 293                -type yesno \
 294                -title $title \
 295                -message $msg]
 296}
 297
 298######################################################################
 299##
 300## version check
 301
 302set req_maj 1
 303set req_min 5
 304
 305if {[catch {set v [git --version]} err]} {
 306        catch {wm withdraw .}
 307        error_popup "Cannot determine Git version:
 308
 309$err
 310
 311[appname] requires Git $req_maj.$req_min or later."
 312        exit 1
 313}
 314if {[regexp {^git version (\d+)\.(\d+)} $v _junk act_maj act_min]} {
 315        if {$act_maj < $req_maj
 316                || ($act_maj == $req_maj && $act_min < $req_min)} {
 317                catch {wm withdraw .}
 318                error_popup "[appname] requires Git $req_maj.$req_min or later.
 319
 320You are using $v."
 321                exit 1
 322        }
 323} else {
 324        catch {wm withdraw .}
 325        error_popup "Cannot parse Git version string:\n\n$v"
 326        exit 1
 327}
 328unset -nocomplain v _junk act_maj act_min req_maj req_min
 329
 330######################################################################
 331##
 332## repository setup
 333
 334if {   [catch {set _gitdir $env(GIT_DIR)}]
 335        && [catch {set _gitdir [git rev-parse --git-dir]} err]} {
 336        catch {wm withdraw .}
 337        error_popup "Cannot find the git directory:\n\n$err"
 338        exit 1
 339}
 340if {![file isdirectory $_gitdir] && [is_Cygwin]} {
 341        catch {set _gitdir [exec cygpath --unix $_gitdir]}
 342}
 343if {![file isdirectory $_gitdir]} {
 344        catch {wm withdraw .}
 345        error_popup "Git directory not found:\n\n$_gitdir"
 346        exit 1
 347}
 348if {[lindex [file split $_gitdir] end] ne {.git}} {
 349        catch {wm withdraw .}
 350        error_popup "Cannot use funny .git directory:\n\n$_gitdir"
 351        exit 1
 352}
 353if {[catch {cd [file dirname $_gitdir]} err]} {
 354        catch {wm withdraw .}
 355        error_popup "No working directory [file dirname $_gitdir]:\n\n$err"
 356        exit 1
 357}
 358set _reponame [lindex [file split \
 359        [file normalize [file dirname $_gitdir]]] \
 360        end]
 361
 362######################################################################
 363##
 364## task management
 365
 366set rescan_active 0
 367set diff_active 0
 368set last_clicked {}
 369
 370set disable_on_lock [list]
 371set index_lock_type none
 372
 373proc lock_index {type} {
 374        global index_lock_type disable_on_lock
 375
 376        if {$index_lock_type eq {none}} {
 377                set index_lock_type $type
 378                foreach w $disable_on_lock {
 379                        uplevel #0 $w disabled
 380                }
 381                return 1
 382        } elseif {$index_lock_type eq "begin-$type"} {
 383                set index_lock_type $type
 384                return 1
 385        }
 386        return 0
 387}
 388
 389proc unlock_index {} {
 390        global index_lock_type disable_on_lock
 391
 392        set index_lock_type none
 393        foreach w $disable_on_lock {
 394                uplevel #0 $w normal
 395        }
 396}
 397
 398######################################################################
 399##
 400## status
 401
 402proc repository_state {ctvar hdvar mhvar} {
 403        global current_branch
 404        upvar $ctvar ct $hdvar hd $mhvar mh
 405
 406        set mh [list]
 407
 408        if {[catch {set current_branch [git symbolic-ref HEAD]}]} {
 409                set current_branch {}
 410        } else {
 411                regsub ^refs/((heads|tags|remotes)/)? \
 412                        $current_branch \
 413                        {} \
 414                        current_branch
 415        }
 416
 417        if {[catch {set hd [git rev-parse --verify HEAD]}]} {
 418                set hd {}
 419                set ct initial
 420                return
 421        }
 422
 423        set merge_head [gitdir MERGE_HEAD]
 424        if {[file exists $merge_head]} {
 425                set ct merge
 426                set fd_mh [open $merge_head r]
 427                while {[gets $fd_mh line] >= 0} {
 428                        lappend mh $line
 429                }
 430                close $fd_mh
 431                return
 432        }
 433
 434        set ct normal
 435}
 436
 437proc PARENT {} {
 438        global PARENT empty_tree
 439
 440        set p [lindex $PARENT 0]
 441        if {$p ne {}} {
 442                return $p
 443        }
 444        if {$empty_tree eq {}} {
 445                set empty_tree [git mktree << {}]
 446        }
 447        return $empty_tree
 448}
 449
 450proc rescan {after {honor_trustmtime 1}} {
 451        global HEAD PARENT MERGE_HEAD commit_type
 452        global ui_index ui_workdir ui_status_value ui_comm
 453        global rescan_active file_states
 454        global repo_config
 455
 456        if {$rescan_active > 0 || ![lock_index read]} return
 457
 458        repository_state newType newHEAD newMERGE_HEAD
 459        if {[string match amend* $commit_type]
 460                && $newType eq {normal}
 461                && $newHEAD eq $HEAD} {
 462        } else {
 463                set HEAD $newHEAD
 464                set PARENT $newHEAD
 465                set MERGE_HEAD $newMERGE_HEAD
 466                set commit_type $newType
 467        }
 468
 469        array unset file_states
 470
 471        if {![$ui_comm edit modified]
 472                || [string trim [$ui_comm get 0.0 end]] eq {}} {
 473                if {[load_message GITGUI_MSG]} {
 474                } elseif {[load_message MERGE_MSG]} {
 475                } elseif {[load_message SQUASH_MSG]} {
 476                }
 477                $ui_comm edit reset
 478                $ui_comm edit modified false
 479        }
 480
 481        if {[is_enabled branch]} {
 482                load_all_heads
 483                populate_branch_menu
 484        }
 485
 486        if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
 487                rescan_stage2 {} $after
 488        } else {
 489                set rescan_active 1
 490                set ui_status_value {Refreshing file status...}
 491                set cmd [list git update-index]
 492                lappend cmd -q
 493                lappend cmd --unmerged
 494                lappend cmd --ignore-missing
 495                lappend cmd --refresh
 496                set fd_rf [open "| $cmd" r]
 497                fconfigure $fd_rf -blocking 0 -translation binary
 498                fileevent $fd_rf readable \
 499                        [list rescan_stage2 $fd_rf $after]
 500        }
 501}
 502
 503proc rescan_stage2 {fd after} {
 504        global ui_status_value
 505        global rescan_active buf_rdi buf_rdf buf_rlo
 506
 507        if {$fd ne {}} {
 508                read $fd
 509                if {![eof $fd]} return
 510                close $fd
 511        }
 512
 513        set ls_others [list | git ls-files --others -z \
 514                --exclude-per-directory=.gitignore]
 515        set info_exclude [gitdir info exclude]
 516        if {[file readable $info_exclude]} {
 517                lappend ls_others "--exclude-from=$info_exclude"
 518        }
 519
 520        set buf_rdi {}
 521        set buf_rdf {}
 522        set buf_rlo {}
 523
 524        set rescan_active 3
 525        set ui_status_value {Scanning for modified files ...}
 526        set fd_di [open "| git diff-index --cached -z [PARENT]" r]
 527        set fd_df [open "| git diff-files -z" r]
 528        set fd_lo [open $ls_others r]
 529
 530        fconfigure $fd_di -blocking 0 -translation binary -encoding binary
 531        fconfigure $fd_df -blocking 0 -translation binary -encoding binary
 532        fconfigure $fd_lo -blocking 0 -translation binary -encoding binary
 533        fileevent $fd_di readable [list read_diff_index $fd_di $after]
 534        fileevent $fd_df readable [list read_diff_files $fd_df $after]
 535        fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
 536}
 537
 538proc load_message {file} {
 539        global ui_comm
 540
 541        set f [gitdir $file]
 542        if {[file isfile $f]} {
 543                if {[catch {set fd [open $f r]}]} {
 544                        return 0
 545                }
 546                set content [string trim [read $fd]]
 547                close $fd
 548                regsub -all -line {[ \r\t]+$} $content {} content
 549                $ui_comm delete 0.0 end
 550                $ui_comm insert end $content
 551                return 1
 552        }
 553        return 0
 554}
 555
 556proc read_diff_index {fd after} {
 557        global buf_rdi
 558
 559        append buf_rdi [read $fd]
 560        set c 0
 561        set n [string length $buf_rdi]
 562        while {$c < $n} {
 563                set z1 [string first "\0" $buf_rdi $c]
 564                if {$z1 == -1} break
 565                incr z1
 566                set z2 [string first "\0" $buf_rdi $z1]
 567                if {$z2 == -1} break
 568
 569                incr c
 570                set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
 571                set p [string range $buf_rdi $z1 [expr {$z2 - 1}]]
 572                merge_state \
 573                        [encoding convertfrom $p] \
 574                        [lindex $i 4]? \
 575                        [list [lindex $i 0] [lindex $i 2]] \
 576                        [list]
 577                set c $z2
 578                incr c
 579        }
 580        if {$c < $n} {
 581                set buf_rdi [string range $buf_rdi $c end]
 582        } else {
 583                set buf_rdi {}
 584        }
 585
 586        rescan_done $fd buf_rdi $after
 587}
 588
 589proc read_diff_files {fd after} {
 590        global buf_rdf
 591
 592        append buf_rdf [read $fd]
 593        set c 0
 594        set n [string length $buf_rdf]
 595        while {$c < $n} {
 596                set z1 [string first "\0" $buf_rdf $c]
 597                if {$z1 == -1} break
 598                incr z1
 599                set z2 [string first "\0" $buf_rdf $z1]
 600                if {$z2 == -1} break
 601
 602                incr c
 603                set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
 604                set p [string range $buf_rdf $z1 [expr {$z2 - 1}]]
 605                merge_state \
 606                        [encoding convertfrom $p] \
 607                        ?[lindex $i 4] \
 608                        [list] \
 609                        [list [lindex $i 0] [lindex $i 2]]
 610                set c $z2
 611                incr c
 612        }
 613        if {$c < $n} {
 614                set buf_rdf [string range $buf_rdf $c end]
 615        } else {
 616                set buf_rdf {}
 617        }
 618
 619        rescan_done $fd buf_rdf $after
 620}
 621
 622proc read_ls_others {fd after} {
 623        global buf_rlo
 624
 625        append buf_rlo [read $fd]
 626        set pck [split $buf_rlo "\0"]
 627        set buf_rlo [lindex $pck end]
 628        foreach p [lrange $pck 0 end-1] {
 629                merge_state [encoding convertfrom $p] ?O
 630        }
 631        rescan_done $fd buf_rlo $after
 632}
 633
 634proc rescan_done {fd buf after} {
 635        global rescan_active
 636        global file_states repo_config
 637        upvar $buf to_clear
 638
 639        if {![eof $fd]} return
 640        set to_clear {}
 641        close $fd
 642        if {[incr rescan_active -1] > 0} return
 643
 644        prune_selection
 645        unlock_index
 646        display_all_files
 647        reshow_diff
 648        uplevel #0 $after
 649}
 650
 651proc prune_selection {} {
 652        global file_states selected_paths
 653
 654        foreach path [array names selected_paths] {
 655                if {[catch {set still_here $file_states($path)}]} {
 656                        unset selected_paths($path)
 657                }
 658        }
 659}
 660
 661######################################################################
 662##
 663## diff
 664
 665proc clear_diff {} {
 666        global ui_diff current_diff_path current_diff_header
 667        global ui_index ui_workdir
 668
 669        $ui_diff conf -state normal
 670        $ui_diff delete 0.0 end
 671        $ui_diff conf -state disabled
 672
 673        set current_diff_path {}
 674        set current_diff_header {}
 675
 676        $ui_index tag remove in_diff 0.0 end
 677        $ui_workdir tag remove in_diff 0.0 end
 678}
 679
 680proc reshow_diff {} {
 681        global ui_status_value file_states file_lists
 682        global current_diff_path current_diff_side
 683
 684        set p $current_diff_path
 685        if {$p eq {}
 686                || $current_diff_side eq {}
 687                || [catch {set s $file_states($p)}]
 688                || [lsearch -sorted -exact $file_lists($current_diff_side) $p] == -1} {
 689                clear_diff
 690        } else {
 691                show_diff $p $current_diff_side
 692        }
 693}
 694
 695proc handle_empty_diff {} {
 696        global current_diff_path file_states file_lists
 697
 698        set path $current_diff_path
 699        set s $file_states($path)
 700        if {[lindex $s 0] ne {_M}} return
 701
 702        info_popup "No differences detected.
 703
 704[short_path $path] has no changes.
 705
 706The modification date of this file was updated
 707by another application, but the content within
 708the file was not changed.
 709
 710A rescan will be automatically started to find
 711other files which may have the same state."
 712
 713        clear_diff
 714        display_file $path __
 715        rescan {set ui_status_value {Ready.}} 0
 716}
 717
 718proc show_diff {path w {lno {}}} {
 719        global file_states file_lists
 720        global is_3way_diff diff_active repo_config
 721        global ui_diff ui_status_value ui_index ui_workdir
 722        global current_diff_path current_diff_side current_diff_header
 723
 724        if {$diff_active || ![lock_index read]} return
 725
 726        clear_diff
 727        if {$lno == {}} {
 728                set lno [lsearch -sorted -exact $file_lists($w) $path]
 729                if {$lno >= 0} {
 730                        incr lno
 731                }
 732        }
 733        if {$lno >= 1} {
 734                $w tag add in_diff $lno.0 [expr {$lno + 1}].0
 735        }
 736
 737        set s $file_states($path)
 738        set m [lindex $s 0]
 739        set is_3way_diff 0
 740        set diff_active 1
 741        set current_diff_path $path
 742        set current_diff_side $w
 743        set current_diff_header {}
 744        set ui_status_value "Loading diff of [escape_path $path]..."
 745
 746        # - Git won't give us the diff, there's nothing to compare to!
 747        #
 748        if {$m eq {_O}} {
 749                set max_sz [expr {128 * 1024}]
 750                if {[catch {
 751                                set fd [open $path r]
 752                                set content [read $fd $max_sz]
 753                                close $fd
 754                                set sz [file size $path]
 755                        } err ]} {
 756                        set diff_active 0
 757                        unlock_index
 758                        set ui_status_value "Unable to display [escape_path $path]"
 759                        error_popup "Error loading file:\n\n$err"
 760                        return
 761                }
 762                $ui_diff conf -state normal
 763                if {![catch {set type [exec file $path]}]} {
 764                        set n [string length $path]
 765                        if {[string equal -length $n $path $type]} {
 766                                set type [string range $type $n end]
 767                                regsub {^:?\s*} $type {} type
 768                        }
 769                        $ui_diff insert end "* $type\n" d_@
 770                }
 771                if {[string first "\0" $content] != -1} {
 772                        $ui_diff insert end \
 773                                "* Binary file (not showing content)." \
 774                                d_@
 775                } else {
 776                        if {$sz > $max_sz} {
 777                                $ui_diff insert end \
 778"* Untracked file is $sz bytes.
 779* Showing only first $max_sz bytes.
 780" d_@
 781                        }
 782                        $ui_diff insert end $content
 783                        if {$sz > $max_sz} {
 784                                $ui_diff insert end "
 785* Untracked file clipped here by [appname].
 786* To see the entire file, use an external editor.
 787" d_@
 788                        }
 789                }
 790                $ui_diff conf -state disabled
 791                set diff_active 0
 792                unlock_index
 793                set ui_status_value {Ready.}
 794                return
 795        }
 796
 797        set cmd [list | git]
 798        if {$w eq $ui_index} {
 799                lappend cmd diff-index
 800                lappend cmd --cached
 801        } elseif {$w eq $ui_workdir} {
 802                if {[string index $m 0] eq {U}} {
 803                        lappend cmd diff
 804                } else {
 805                        lappend cmd diff-files
 806                }
 807        }
 808
 809        lappend cmd -p
 810        lappend cmd --no-color
 811        if {$repo_config(gui.diffcontext) > 0} {
 812                lappend cmd "-U$repo_config(gui.diffcontext)"
 813        }
 814        if {$w eq $ui_index} {
 815                lappend cmd [PARENT]
 816        }
 817        lappend cmd --
 818        lappend cmd $path
 819
 820        if {[catch {set fd [open $cmd r]} err]} {
 821                set diff_active 0
 822                unlock_index
 823                set ui_status_value "Unable to display [escape_path $path]"
 824                error_popup "Error loading diff:\n\n$err"
 825                return
 826        }
 827
 828        fconfigure $fd \
 829                -blocking 0 \
 830                -encoding binary \
 831                -translation binary
 832        fileevent $fd readable [list read_diff $fd]
 833}
 834
 835proc read_diff {fd} {
 836        global ui_diff ui_status_value diff_active
 837        global is_3way_diff current_diff_header
 838
 839        $ui_diff conf -state normal
 840        while {[gets $fd line] >= 0} {
 841                # -- Cleanup uninteresting diff header lines.
 842                #
 843                if {   [string match {diff --git *}      $line]
 844                        || [string match {diff --cc *}       $line]
 845                        || [string match {diff --combined *} $line]
 846                        || [string match {--- *}             $line]
 847                        || [string match {+++ *}             $line]} {
 848                        append current_diff_header $line "\n"
 849                        continue
 850                }
 851                if {[string match {index *} $line]} continue
 852                if {$line eq {deleted file mode 120000}} {
 853                        set line "deleted symlink"
 854                }
 855
 856                # -- Automatically detect if this is a 3 way diff.
 857                #
 858                if {[string match {@@@ *} $line]} {set is_3way_diff 1}
 859
 860                if {[string match {mode *} $line]
 861                        || [string match {new file *} $line]
 862                        || [string match {deleted file *} $line]
 863                        || [string match {Binary files * and * differ} $line]
 864                        || $line eq {\ No newline at end of file}
 865                        || [regexp {^\* Unmerged path } $line]} {
 866                        set tags {}
 867                } elseif {$is_3way_diff} {
 868                        set op [string range $line 0 1]
 869                        switch -- $op {
 870                        {  } {set tags {}}
 871                        {@@} {set tags d_@}
 872                        { +} {set tags d_s+}
 873                        { -} {set tags d_s-}
 874                        {+ } {set tags d_+s}
 875                        {- } {set tags d_-s}
 876                        {--} {set tags d_--}
 877                        {++} {
 878                                if {[regexp {^\+\+([<>]{7} |={7})} $line _g op]} {
 879                                        set line [string replace $line 0 1 {  }]
 880                                        set tags d$op
 881                                } else {
 882                                        set tags d_++
 883                                }
 884                        }
 885                        default {
 886                                puts "error: Unhandled 3 way diff marker: {$op}"
 887                                set tags {}
 888                        }
 889                        }
 890                } else {
 891                        set op [string index $line 0]
 892                        switch -- $op {
 893                        { } {set tags {}}
 894                        {@} {set tags d_@}
 895                        {-} {set tags d_-}
 896                        {+} {
 897                                if {[regexp {^\+([<>]{7} |={7})} $line _g op]} {
 898                                        set line [string replace $line 0 0 { }]
 899                                        set tags d$op
 900                                } else {
 901                                        set tags d_+
 902                                }
 903                        }
 904                        default {
 905                                puts "error: Unhandled 2 way diff marker: {$op}"
 906                                set tags {}
 907                        }
 908                        }
 909                }
 910                $ui_diff insert end $line $tags
 911                if {[string index $line end] eq "\r"} {
 912                        $ui_diff tag add d_cr {end - 2c}
 913                }
 914                $ui_diff insert end "\n" $tags
 915        }
 916        $ui_diff conf -state disabled
 917
 918        if {[eof $fd]} {
 919                close $fd
 920                set diff_active 0
 921                unlock_index
 922                set ui_status_value {Ready.}
 923
 924                if {[$ui_diff index end] eq {2.0}} {
 925                        handle_empty_diff
 926                }
 927        }
 928}
 929
 930proc apply_hunk {x y} {
 931        global current_diff_path current_diff_header current_diff_side
 932        global ui_diff ui_index file_states
 933
 934        if {$current_diff_path eq {} || $current_diff_header eq {}} return
 935        if {![lock_index apply_hunk]} return
 936
 937        set apply_cmd {git apply --cached --whitespace=nowarn}
 938        set mi [lindex $file_states($current_diff_path) 0]
 939        if {$current_diff_side eq $ui_index} {
 940                set mode unstage
 941                lappend apply_cmd --reverse
 942                if {[string index $mi 0] ne {M}} {
 943                        unlock_index
 944                        return
 945                }
 946        } else {
 947                set mode stage
 948                if {[string index $mi 1] ne {M}} {
 949                        unlock_index
 950                        return
 951                }
 952        }
 953
 954        set s_lno [lindex [split [$ui_diff index @$x,$y] .] 0]
 955        set s_lno [$ui_diff search -backwards -regexp ^@@ $s_lno.0 0.0]
 956        if {$s_lno eq {}} {
 957                unlock_index
 958                return
 959        }
 960
 961        set e_lno [$ui_diff search -forwards -regexp ^@@ "$s_lno + 1 lines" end]
 962        if {$e_lno eq {}} {
 963                set e_lno end
 964        }
 965
 966        if {[catch {
 967                set p [open "| $apply_cmd" w]
 968                fconfigure $p -translation binary -encoding binary
 969                puts -nonewline $p $current_diff_header
 970                puts -nonewline $p [$ui_diff get $s_lno $e_lno]
 971                close $p} err]} {
 972                error_popup "Failed to $mode selected hunk.\n\n$err"
 973                unlock_index
 974                return
 975        }
 976
 977        $ui_diff conf -state normal
 978        $ui_diff delete $s_lno $e_lno
 979        $ui_diff conf -state disabled
 980
 981        if {[$ui_diff get 1.0 end] eq "\n"} {
 982                set o _
 983        } else {
 984                set o ?
 985        }
 986
 987        if {$current_diff_side eq $ui_index} {
 988                set mi ${o}M
 989        } elseif {[string index $mi 0] eq {_}} {
 990                set mi M$o
 991        } else {
 992                set mi ?$o
 993        }
 994        unlock_index
 995        display_file $current_diff_path $mi
 996        if {$o eq {_}} {
 997                clear_diff
 998        }
 999}
1000
1001######################################################################
1002##
1003## commit
1004
1005proc load_last_commit {} {
1006        global HEAD PARENT MERGE_HEAD commit_type ui_comm
1007        global repo_config
1008
1009        if {[llength $PARENT] == 0} {
1010                error_popup {There is nothing to amend.
1011
1012You are about to create the initial commit.
1013There is no commit before this to amend.
1014}
1015                return
1016        }
1017
1018        repository_state curType curHEAD curMERGE_HEAD
1019        if {$curType eq {merge}} {
1020                error_popup {Cannot amend while merging.
1021
1022You are currently in the middle of a merge that
1023has not been fully completed.  You cannot amend
1024the prior commit unless you first abort the
1025current merge activity.
1026}
1027                return
1028        }
1029
1030        set msg {}
1031        set parents [list]
1032        if {[catch {
1033                        set fd [open "| git cat-file commit $curHEAD" r]
1034                        fconfigure $fd -encoding binary -translation lf
1035                        if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
1036                                set enc utf-8
1037                        }
1038                        while {[gets $fd line] > 0} {
1039                                if {[string match {parent *} $line]} {
1040                                        lappend parents [string range $line 7 end]
1041                                } elseif {[string match {encoding *} $line]} {
1042                                        set enc [string tolower [string range $line 9 end]]
1043                                }
1044                        }
1045                        fconfigure $fd -encoding $enc
1046                        set msg [string trim [read $fd]]
1047                        close $fd
1048                } err]} {
1049                error_popup "Error loading commit data for amend:\n\n$err"
1050                return
1051        }
1052
1053        set HEAD $curHEAD
1054        set PARENT $parents
1055        set MERGE_HEAD [list]
1056        switch -- [llength $parents] {
1057        0       {set commit_type amend-initial}
1058        1       {set commit_type amend}
1059        default {set commit_type amend-merge}
1060        }
1061
1062        $ui_comm delete 0.0 end
1063        $ui_comm insert end $msg
1064        $ui_comm edit reset
1065        $ui_comm edit modified false
1066        rescan {set ui_status_value {Ready.}}
1067}
1068
1069proc create_new_commit {} {
1070        global commit_type ui_comm
1071
1072        set commit_type normal
1073        $ui_comm delete 0.0 end
1074        $ui_comm edit reset
1075        $ui_comm edit modified false
1076        rescan {set ui_status_value {Ready.}}
1077}
1078
1079set GIT_COMMITTER_IDENT {}
1080
1081proc committer_ident {} {
1082        global GIT_COMMITTER_IDENT
1083
1084        if {$GIT_COMMITTER_IDENT eq {}} {
1085                if {[catch {set me [git var GIT_COMMITTER_IDENT]} err]} {
1086                        error_popup "Unable to obtain your identity:\n\n$err"
1087                        return {}
1088                }
1089                if {![regexp {^(.*) [0-9]+ [-+0-9]+$} \
1090                        $me me GIT_COMMITTER_IDENT]} {
1091                        error_popup "Invalid GIT_COMMITTER_IDENT:\n\n$me"
1092                        return {}
1093                }
1094        }
1095
1096        return $GIT_COMMITTER_IDENT
1097}
1098
1099proc commit_tree {} {
1100        global HEAD commit_type file_states ui_comm repo_config
1101        global ui_status_value pch_error
1102
1103        if {[committer_ident] eq {}} return
1104        if {![lock_index update]} return
1105
1106        # -- Our in memory state should match the repository.
1107        #
1108        repository_state curType curHEAD curMERGE_HEAD
1109        if {[string match amend* $commit_type]
1110                && $curType eq {normal}
1111                && $curHEAD eq $HEAD} {
1112        } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
1113                info_popup {Last scanned state does not match repository state.
1114
1115Another Git program has modified this repository
1116since the last scan.  A rescan must be performed
1117before another commit can be created.
1118
1119The rescan will be automatically started now.
1120}
1121                unlock_index
1122                rescan {set ui_status_value {Ready.}}
1123                return
1124        }
1125
1126        # -- At least one file should differ in the index.
1127        #
1128        set files_ready 0
1129        foreach path [array names file_states] {
1130                switch -glob -- [lindex $file_states($path) 0] {
1131                _? {continue}
1132                A? -
1133                D? -
1134                M? {set files_ready 1}
1135                U? {
1136                        error_popup "Unmerged files cannot be committed.
1137
1138File [short_path $path] has merge conflicts.
1139You must resolve them and add the file before committing.
1140"
1141                        unlock_index
1142                        return
1143                }
1144                default {
1145                        error_popup "Unknown file state [lindex $s 0] detected.
1146
1147File [short_path $path] cannot be committed by this program.
1148"
1149                }
1150                }
1151        }
1152        if {!$files_ready} {
1153                info_popup {No changes to commit.
1154
1155You must add at least 1 file before you can commit.
1156}
1157                unlock_index
1158                return
1159        }
1160
1161        # -- A message is required.
1162        #
1163        set msg [string trim [$ui_comm get 1.0 end]]
1164        regsub -all -line {[ \t\r]+$} $msg {} msg
1165        if {$msg eq {}} {
1166                error_popup {Please supply a commit message.
1167
1168A good commit message has the following format:
1169
1170- First line: Describe in one sentance what you did.
1171- Second line: Blank
1172- Remaining lines: Describe why this change is good.
1173}
1174                unlock_index
1175                return
1176        }
1177
1178        # -- Run the pre-commit hook.
1179        #
1180        set pchook [gitdir hooks pre-commit]
1181
1182        # On Cygwin [file executable] might lie so we need to ask
1183        # the shell if the hook is executable.  Yes that's annoying.
1184        #
1185        if {[is_Cygwin] && [file isfile $pchook]} {
1186                set pchook [list sh -c [concat \
1187                        "if test -x \"$pchook\";" \
1188                        "then exec \"$pchook\" 2>&1;" \
1189                        "fi"]]
1190        } elseif {[file executable $pchook]} {
1191                set pchook [list $pchook |& cat]
1192        } else {
1193                commit_writetree $curHEAD $msg
1194                return
1195        }
1196
1197        set ui_status_value {Calling pre-commit hook...}
1198        set pch_error {}
1199        set fd_ph [open "| $pchook" r]
1200        fconfigure $fd_ph -blocking 0 -translation binary
1201        fileevent $fd_ph readable \
1202                [list commit_prehook_wait $fd_ph $curHEAD $msg]
1203}
1204
1205proc commit_prehook_wait {fd_ph curHEAD msg} {
1206        global pch_error ui_status_value
1207
1208        append pch_error [read $fd_ph]
1209        fconfigure $fd_ph -blocking 1
1210        if {[eof $fd_ph]} {
1211                if {[catch {close $fd_ph}]} {
1212                        set ui_status_value {Commit declined by pre-commit hook.}
1213                        hook_failed_popup pre-commit $pch_error
1214                        unlock_index
1215                } else {
1216                        commit_writetree $curHEAD $msg
1217                }
1218                set pch_error {}
1219                return
1220        }
1221        fconfigure $fd_ph -blocking 0
1222}
1223
1224proc commit_writetree {curHEAD msg} {
1225        global ui_status_value
1226
1227        set ui_status_value {Committing changes...}
1228        set fd_wt [open "| git write-tree" r]
1229        fileevent $fd_wt readable \
1230                [list commit_committree $fd_wt $curHEAD $msg]
1231}
1232
1233proc commit_committree {fd_wt curHEAD msg} {
1234        global HEAD PARENT MERGE_HEAD commit_type
1235        global all_heads current_branch
1236        global ui_status_value ui_comm selected_commit_type
1237        global file_states selected_paths rescan_active
1238        global repo_config
1239
1240        gets $fd_wt tree_id
1241        if {$tree_id eq {} || [catch {close $fd_wt} err]} {
1242                error_popup "write-tree failed:\n\n$err"
1243                set ui_status_value {Commit failed.}
1244                unlock_index
1245                return
1246        }
1247
1248        # -- Build the message.
1249        #
1250        set msg_p [gitdir COMMIT_EDITMSG]
1251        set msg_wt [open $msg_p w]
1252        if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
1253                set enc utf-8
1254        }
1255        fconfigure $msg_wt -encoding $enc -translation binary
1256        puts -nonewline $msg_wt $msg
1257        close $msg_wt
1258
1259        # -- Create the commit.
1260        #
1261        set cmd [list git commit-tree $tree_id]
1262        set parents [concat $PARENT $MERGE_HEAD]
1263        if {[llength $parents] > 0} {
1264                foreach p $parents {
1265                        lappend cmd -p $p
1266                }
1267        } else {
1268                # git commit-tree writes to stderr during initial commit.
1269                lappend cmd 2>/dev/null
1270        }
1271        lappend cmd <$msg_p
1272        if {[catch {set cmt_id [eval exec $cmd]} err]} {
1273                error_popup "commit-tree failed:\n\n$err"
1274                set ui_status_value {Commit failed.}
1275                unlock_index
1276                return
1277        }
1278
1279        # -- Update the HEAD ref.
1280        #
1281        set reflogm commit
1282        if {$commit_type ne {normal}} {
1283                append reflogm " ($commit_type)"
1284        }
1285        set i [string first "\n" $msg]
1286        if {$i >= 0} {
1287                append reflogm {: } [string range $msg 0 [expr {$i - 1}]]
1288        } else {
1289                append reflogm {: } $msg
1290        }
1291        set cmd [list git update-ref -m $reflogm HEAD $cmt_id $curHEAD]
1292        if {[catch {eval exec $cmd} err]} {
1293                error_popup "update-ref failed:\n\n$err"
1294                set ui_status_value {Commit failed.}
1295                unlock_index
1296                return
1297        }
1298
1299        # -- Make sure our current branch exists.
1300        #
1301        if {$commit_type eq {initial}} {
1302                lappend all_heads $current_branch
1303                set all_heads [lsort -unique $all_heads]
1304                populate_branch_menu
1305        }
1306
1307        # -- Cleanup after ourselves.
1308        #
1309        catch {file delete $msg_p}
1310        catch {file delete [gitdir MERGE_HEAD]}
1311        catch {file delete [gitdir MERGE_MSG]}
1312        catch {file delete [gitdir SQUASH_MSG]}
1313        catch {file delete [gitdir GITGUI_MSG]}
1314
1315        # -- Let rerere do its thing.
1316        #
1317        if {[file isdirectory [gitdir rr-cache]]} {
1318                catch {git rerere}
1319        }
1320
1321        # -- Run the post-commit hook.
1322        #
1323        set pchook [gitdir hooks post-commit]
1324        if {[is_Cygwin] && [file isfile $pchook]} {
1325                set pchook [list sh -c [concat \
1326                        "if test -x \"$pchook\";" \
1327                        "then exec \"$pchook\";" \
1328                        "fi"]]
1329        } elseif {![file executable $pchook]} {
1330                set pchook {}
1331        }
1332        if {$pchook ne {}} {
1333                catch {exec $pchook &}
1334        }
1335
1336        $ui_comm delete 0.0 end
1337        $ui_comm edit reset
1338        $ui_comm edit modified false
1339
1340        if {[is_enabled singlecommit]} do_quit
1341
1342        # -- Update in memory status
1343        #
1344        set selected_commit_type new
1345        set commit_type normal
1346        set HEAD $cmt_id
1347        set PARENT $cmt_id
1348        set MERGE_HEAD [list]
1349
1350        foreach path [array names file_states] {
1351                set s $file_states($path)
1352                set m [lindex $s 0]
1353                switch -glob -- $m {
1354                _O -
1355                _M -
1356                _D {continue}
1357                __ -
1358                A_ -
1359                M_ -
1360                D_ {
1361                        unset file_states($path)
1362                        catch {unset selected_paths($path)}
1363                }
1364                DO {
1365                        set file_states($path) [list _O [lindex $s 1] {} {}]
1366                }
1367                AM -
1368                AD -
1369                MM -
1370                MD {
1371                        set file_states($path) [list \
1372                                _[string index $m 1] \
1373                                [lindex $s 1] \
1374                                [lindex $s 3] \
1375                                {}]
1376                }
1377                }
1378        }
1379
1380        display_all_files
1381        unlock_index
1382        reshow_diff
1383        set ui_status_value \
1384                "Changes committed as [string range $cmt_id 0 7]."
1385}
1386
1387######################################################################
1388##
1389## fetch push
1390
1391proc fetch_from {remote} {
1392        set w [new_console \
1393                "fetch $remote" \
1394                "Fetching new changes from $remote"]
1395        set cmd [list git fetch]
1396        lappend cmd $remote
1397        console_exec $w $cmd console_done
1398}
1399
1400proc push_to {remote} {
1401        set w [new_console \
1402                "push $remote" \
1403                "Pushing changes to $remote"]
1404        set cmd [list git push]
1405        lappend cmd -v
1406        lappend cmd $remote
1407        console_exec $w $cmd console_done
1408}
1409
1410######################################################################
1411##
1412## ui helpers
1413
1414proc mapicon {w state path} {
1415        global all_icons
1416
1417        if {[catch {set r $all_icons($state$w)}]} {
1418                puts "error: no icon for $w state={$state} $path"
1419                return file_plain
1420        }
1421        return $r
1422}
1423
1424proc mapdesc {state path} {
1425        global all_descs
1426
1427        if {[catch {set r $all_descs($state)}]} {
1428                puts "error: no desc for state={$state} $path"
1429                return $state
1430        }
1431        return $r
1432}
1433
1434proc escape_path {path} {
1435        regsub -all {\\} $path "\\\\" path
1436        regsub -all "\n" $path "\\n" path
1437        return $path
1438}
1439
1440proc short_path {path} {
1441        return [escape_path [lindex [file split $path] end]]
1442}
1443
1444set next_icon_id 0
1445set null_sha1 [string repeat 0 40]
1446
1447proc merge_state {path new_state {head_info {}} {index_info {}}} {
1448        global file_states next_icon_id null_sha1
1449
1450        set s0 [string index $new_state 0]
1451        set s1 [string index $new_state 1]
1452
1453        if {[catch {set info $file_states($path)}]} {
1454                set state __
1455                set icon n[incr next_icon_id]
1456        } else {
1457                set state [lindex $info 0]
1458                set icon [lindex $info 1]
1459                if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1460                if {$index_info eq {}} {set index_info [lindex $info 3]}
1461        }
1462
1463        if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1464        elseif {$s0 eq {_}} {set s0 _}
1465
1466        if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1467        elseif {$s1 eq {_}} {set s1 _}
1468
1469        if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1470                set head_info [list 0 $null_sha1]
1471        } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1472                && $head_info eq {}} {
1473                set head_info $index_info
1474        }
1475
1476        set file_states($path) [list $s0$s1 $icon \
1477                $head_info $index_info \
1478                ]
1479        return $state
1480}
1481
1482proc display_file_helper {w path icon_name old_m new_m} {
1483        global file_lists
1484
1485        if {$new_m eq {_}} {
1486                set lno [lsearch -sorted -exact $file_lists($w) $path]
1487                if {$lno >= 0} {
1488                        set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1489                        incr lno
1490                        $w conf -state normal
1491                        $w delete $lno.0 [expr {$lno + 1}].0
1492                        $w conf -state disabled
1493                }
1494        } elseif {$old_m eq {_} && $new_m ne {_}} {
1495                lappend file_lists($w) $path
1496                set file_lists($w) [lsort -unique $file_lists($w)]
1497                set lno [lsearch -sorted -exact $file_lists($w) $path]
1498                incr lno
1499                $w conf -state normal
1500                $w image create $lno.0 \
1501                        -align center -padx 5 -pady 1 \
1502                        -name $icon_name \
1503                        -image [mapicon $w $new_m $path]
1504                $w insert $lno.1 "[escape_path $path]\n"
1505                $w conf -state disabled
1506        } elseif {$old_m ne $new_m} {
1507                $w conf -state normal
1508                $w image conf $icon_name -image [mapicon $w $new_m $path]
1509                $w conf -state disabled
1510        }
1511}
1512
1513proc display_file {path state} {
1514        global file_states selected_paths
1515        global ui_index ui_workdir
1516
1517        set old_m [merge_state $path $state]
1518        set s $file_states($path)
1519        set new_m [lindex $s 0]
1520        set icon_name [lindex $s 1]
1521
1522        set o [string index $old_m 0]
1523        set n [string index $new_m 0]
1524        if {$o eq {U}} {
1525                set o _
1526        }
1527        if {$n eq {U}} {
1528                set n _
1529        }
1530        display_file_helper     $ui_index $path $icon_name $o $n
1531
1532        if {[string index $old_m 0] eq {U}} {
1533                set o U
1534        } else {
1535                set o [string index $old_m 1]
1536        }
1537        if {[string index $new_m 0] eq {U}} {
1538                set n U
1539        } else {
1540                set n [string index $new_m 1]
1541        }
1542        display_file_helper     $ui_workdir $path $icon_name $o $n
1543
1544        if {$new_m eq {__}} {
1545                unset file_states($path)
1546                catch {unset selected_paths($path)}
1547        }
1548}
1549
1550proc display_all_files_helper {w path icon_name m} {
1551        global file_lists
1552
1553        lappend file_lists($w) $path
1554        set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1555        $w image create end \
1556                -align center -padx 5 -pady 1 \
1557                -name $icon_name \
1558                -image [mapicon $w $m $path]
1559        $w insert end "[escape_path $path]\n"
1560}
1561
1562proc display_all_files {} {
1563        global ui_index ui_workdir
1564        global file_states file_lists
1565        global last_clicked
1566
1567        $ui_index conf -state normal
1568        $ui_workdir conf -state normal
1569
1570        $ui_index delete 0.0 end
1571        $ui_workdir delete 0.0 end
1572        set last_clicked {}
1573
1574        set file_lists($ui_index) [list]
1575        set file_lists($ui_workdir) [list]
1576
1577        foreach path [lsort [array names file_states]] {
1578                set s $file_states($path)
1579                set m [lindex $s 0]
1580                set icon_name [lindex $s 1]
1581
1582                set s [string index $m 0]
1583                if {$s ne {U} && $s ne {_}} {
1584                        display_all_files_helper $ui_index $path \
1585                                $icon_name $s
1586                }
1587
1588                if {[string index $m 0] eq {U}} {
1589                        set s U
1590                } else {
1591                        set s [string index $m 1]
1592                }
1593                if {$s ne {_}} {
1594                        display_all_files_helper $ui_workdir $path \
1595                                $icon_name $s
1596                }
1597        }
1598
1599        $ui_index conf -state disabled
1600        $ui_workdir conf -state disabled
1601}
1602
1603proc update_indexinfo {msg pathList after} {
1604        global update_index_cp ui_status_value
1605
1606        if {![lock_index update]} return
1607
1608        set update_index_cp 0
1609        set pathList [lsort $pathList]
1610        set totalCnt [llength $pathList]
1611        set batch [expr {int($totalCnt * .01) + 1}]
1612        if {$batch > 25} {set batch 25}
1613
1614        set ui_status_value [format \
1615                "$msg... %i/%i files (%.2f%%)" \
1616                $update_index_cp \
1617                $totalCnt \
1618                0.0]
1619        set fd [open "| git update-index -z --index-info" w]
1620        fconfigure $fd \
1621                -blocking 0 \
1622                -buffering full \
1623                -buffersize 512 \
1624                -encoding binary \
1625                -translation binary
1626        fileevent $fd writable [list \
1627                write_update_indexinfo \
1628                $fd \
1629                $pathList \
1630                $totalCnt \
1631                $batch \
1632                $msg \
1633                $after \
1634                ]
1635}
1636
1637proc write_update_indexinfo {fd pathList totalCnt batch msg after} {
1638        global update_index_cp ui_status_value
1639        global file_states current_diff_path
1640
1641        if {$update_index_cp >= $totalCnt} {
1642                close $fd
1643                unlock_index
1644                uplevel #0 $after
1645                return
1646        }
1647
1648        for {set i $batch} \
1649                {$update_index_cp < $totalCnt && $i > 0} \
1650                {incr i -1} {
1651                set path [lindex $pathList $update_index_cp]
1652                incr update_index_cp
1653
1654                set s $file_states($path)
1655                switch -glob -- [lindex $s 0] {
1656                A? {set new _O}
1657                M? {set new _M}
1658                D_ {set new _D}
1659                D? {set new _?}
1660                ?? {continue}
1661                }
1662                set info [lindex $s 2]
1663                if {$info eq {}} continue
1664
1665                puts -nonewline $fd "$info\t[encoding convertto $path]\0"
1666                display_file $path $new
1667        }
1668
1669        set ui_status_value [format \
1670                "$msg... %i/%i files (%.2f%%)" \
1671                $update_index_cp \
1672                $totalCnt \
1673                [expr {100.0 * $update_index_cp / $totalCnt}]]
1674}
1675
1676proc update_index {msg pathList after} {
1677        global update_index_cp ui_status_value
1678
1679        if {![lock_index update]} return
1680
1681        set update_index_cp 0
1682        set pathList [lsort $pathList]
1683        set totalCnt [llength $pathList]
1684        set batch [expr {int($totalCnt * .01) + 1}]
1685        if {$batch > 25} {set batch 25}
1686
1687        set ui_status_value [format \
1688                "$msg... %i/%i files (%.2f%%)" \
1689                $update_index_cp \
1690                $totalCnt \
1691                0.0]
1692        set fd [open "| git update-index --add --remove -z --stdin" w]
1693        fconfigure $fd \
1694                -blocking 0 \
1695                -buffering full \
1696                -buffersize 512 \
1697                -encoding binary \
1698                -translation binary
1699        fileevent $fd writable [list \
1700                write_update_index \
1701                $fd \
1702                $pathList \
1703                $totalCnt \
1704                $batch \
1705                $msg \
1706                $after \
1707                ]
1708}
1709
1710proc write_update_index {fd pathList totalCnt batch msg after} {
1711        global update_index_cp ui_status_value
1712        global file_states current_diff_path
1713
1714        if {$update_index_cp >= $totalCnt} {
1715                close $fd
1716                unlock_index
1717                uplevel #0 $after
1718                return
1719        }
1720
1721        for {set i $batch} \
1722                {$update_index_cp < $totalCnt && $i > 0} \
1723                {incr i -1} {
1724                set path [lindex $pathList $update_index_cp]
1725                incr update_index_cp
1726
1727                switch -glob -- [lindex $file_states($path) 0] {
1728                AD {set new __}
1729                ?D {set new D_}
1730                _O -
1731                AM {set new A_}
1732                U? {
1733                        if {[file exists $path]} {
1734                                set new M_
1735                        } else {
1736                                set new D_
1737                        }
1738                }
1739                ?M {set new M_}
1740                ?? {continue}
1741                }
1742                puts -nonewline $fd "[encoding convertto $path]\0"
1743                display_file $path $new
1744        }
1745
1746        set ui_status_value [format \
1747                "$msg... %i/%i files (%.2f%%)" \
1748                $update_index_cp \
1749                $totalCnt \
1750                [expr {100.0 * $update_index_cp / $totalCnt}]]
1751}
1752
1753proc checkout_index {msg pathList after} {
1754        global update_index_cp ui_status_value
1755
1756        if {![lock_index update]} return
1757
1758        set update_index_cp 0
1759        set pathList [lsort $pathList]
1760        set totalCnt [llength $pathList]
1761        set batch [expr {int($totalCnt * .01) + 1}]
1762        if {$batch > 25} {set batch 25}
1763
1764        set ui_status_value [format \
1765                "$msg... %i/%i files (%.2f%%)" \
1766                $update_index_cp \
1767                $totalCnt \
1768                0.0]
1769        set cmd [list git checkout-index]
1770        lappend cmd --index
1771        lappend cmd --quiet
1772        lappend cmd --force
1773        lappend cmd -z
1774        lappend cmd --stdin
1775        set fd [open "| $cmd " w]
1776        fconfigure $fd \
1777                -blocking 0 \
1778                -buffering full \
1779                -buffersize 512 \
1780                -encoding binary \
1781                -translation binary
1782        fileevent $fd writable [list \
1783                write_checkout_index \
1784                $fd \
1785                $pathList \
1786                $totalCnt \
1787                $batch \
1788                $msg \
1789                $after \
1790                ]
1791}
1792
1793proc write_checkout_index {fd pathList totalCnt batch msg after} {
1794        global update_index_cp ui_status_value
1795        global file_states current_diff_path
1796
1797        if {$update_index_cp >= $totalCnt} {
1798                close $fd
1799                unlock_index
1800                uplevel #0 $after
1801                return
1802        }
1803
1804        for {set i $batch} \
1805                {$update_index_cp < $totalCnt && $i > 0} \
1806                {incr i -1} {
1807                set path [lindex $pathList $update_index_cp]
1808                incr update_index_cp
1809                switch -glob -- [lindex $file_states($path) 0] {
1810                U? {continue}
1811                ?M -
1812                ?D {
1813                        puts -nonewline $fd "[encoding convertto $path]\0"
1814                        display_file $path ?_
1815                }
1816                }
1817        }
1818
1819        set ui_status_value [format \
1820                "$msg... %i/%i files (%.2f%%)" \
1821                $update_index_cp \
1822                $totalCnt \
1823                [expr {100.0 * $update_index_cp / $totalCnt}]]
1824}
1825
1826######################################################################
1827##
1828## branch management
1829
1830proc is_tracking_branch {name} {
1831        global tracking_branches
1832
1833        if {![catch {set info $tracking_branches($name)}]} {
1834                return 1
1835        }
1836        foreach t [array names tracking_branches] {
1837                if {[string match {*/\*} $t] && [string match $t $name]} {
1838                        return 1
1839                }
1840        }
1841        return 0
1842}
1843
1844proc load_all_heads {} {
1845        global all_heads
1846
1847        set all_heads [list]
1848        set fd [open "| git for-each-ref --format=%(refname) refs/heads" r]
1849        while {[gets $fd line] > 0} {
1850                if {[is_tracking_branch $line]} continue
1851                if {![regsub ^refs/heads/ $line {} name]} continue
1852                lappend all_heads $name
1853        }
1854        close $fd
1855
1856        set all_heads [lsort $all_heads]
1857}
1858
1859proc populate_branch_menu {} {
1860        global all_heads disable_on_lock
1861
1862        set m .mbar.branch
1863        set last [$m index last]
1864        for {set i 0} {$i <= $last} {incr i} {
1865                if {[$m type $i] eq {separator}} {
1866                        $m delete $i last
1867                        set new_dol [list]
1868                        foreach a $disable_on_lock {
1869                                if {[lindex $a 0] ne $m || [lindex $a 2] < $i} {
1870                                        lappend new_dol $a
1871                                }
1872                        }
1873                        set disable_on_lock $new_dol
1874                        break
1875                }
1876        }
1877
1878        if {$all_heads ne {}} {
1879                $m add separator
1880        }
1881        foreach b $all_heads {
1882                $m add radiobutton \
1883                        -label $b \
1884                        -command [list switch_branch $b] \
1885                        -variable current_branch \
1886                        -value $b \
1887                        -font font_ui
1888                lappend disable_on_lock \
1889                        [list $m entryconf [$m index last] -state]
1890        }
1891}
1892
1893proc all_tracking_branches {} {
1894        global tracking_branches
1895
1896        set all_trackings {}
1897        set cmd {}
1898        foreach name [array names tracking_branches] {
1899                if {[regsub {/\*$} $name {} name]} {
1900                        lappend cmd $name
1901                } else {
1902                        regsub ^refs/(heads|remotes)/ $name {} name
1903                        lappend all_trackings $name
1904                }
1905        }
1906
1907        if {$cmd ne {}} {
1908                set fd [open "| git for-each-ref --format=%(refname) $cmd" r]
1909                while {[gets $fd name] > 0} {
1910                        regsub ^refs/(heads|remotes)/ $name {} name
1911                        lappend all_trackings $name
1912                }
1913                close $fd
1914        }
1915
1916        return [lsort -unique $all_trackings]
1917}
1918
1919proc load_all_tags {} {
1920        set all_tags [list]
1921        set fd [open "| git for-each-ref --format=%(refname) refs/tags" r]
1922        while {[gets $fd line] > 0} {
1923                if {![regsub ^refs/tags/ $line {} name]} continue
1924                lappend all_tags $name
1925        }
1926        close $fd
1927
1928        return [lsort $all_tags]
1929}
1930
1931proc do_create_branch_action {w} {
1932        global all_heads null_sha1 repo_config
1933        global create_branch_checkout create_branch_revtype
1934        global create_branch_head create_branch_trackinghead
1935        global create_branch_name create_branch_revexp
1936        global create_branch_tag
1937
1938        set newbranch $create_branch_name
1939        if {$newbranch eq {}
1940                || $newbranch eq $repo_config(gui.newbranchtemplate)} {
1941                tk_messageBox \
1942                        -icon error \
1943                        -type ok \
1944                        -title [wm title $w] \
1945                        -parent $w \
1946                        -message "Please supply a branch name."
1947                focus $w.desc.name_t
1948                return
1949        }
1950        if {![catch {git show-ref --verify -- "refs/heads/$newbranch"}]} {
1951                tk_messageBox \
1952                        -icon error \
1953                        -type ok \
1954                        -title [wm title $w] \
1955                        -parent $w \
1956                        -message "Branch '$newbranch' already exists."
1957                focus $w.desc.name_t
1958                return
1959        }
1960        if {[catch {git check-ref-format "heads/$newbranch"}]} {
1961                tk_messageBox \
1962                        -icon error \
1963                        -type ok \
1964                        -title [wm title $w] \
1965                        -parent $w \
1966                        -message "We do not like '$newbranch' as a branch name."
1967                focus $w.desc.name_t
1968                return
1969        }
1970
1971        set rev {}
1972        switch -- $create_branch_revtype {
1973        head {set rev $create_branch_head}
1974        tracking {set rev $create_branch_trackinghead}
1975        tag {set rev $create_branch_tag}
1976        expression {set rev $create_branch_revexp}
1977        }
1978        if {[catch {set cmt [git rev-parse --verify "${rev}^0"]}]} {
1979                tk_messageBox \
1980                        -icon error \
1981                        -type ok \
1982                        -title [wm title $w] \
1983                        -parent $w \
1984                        -message "Invalid starting revision: $rev"
1985                return
1986        }
1987        set cmd [list git update-ref]
1988        lappend cmd -m
1989        lappend cmd "branch: Created from $rev"
1990        lappend cmd "refs/heads/$newbranch"
1991        lappend cmd $cmt
1992        lappend cmd $null_sha1
1993        if {[catch {eval exec $cmd} err]} {
1994                tk_messageBox \
1995                        -icon error \
1996                        -type ok \
1997                        -title [wm title $w] \
1998                        -parent $w \
1999                        -message "Failed to create '$newbranch'.\n\n$err"
2000                return
2001        }
2002
2003        lappend all_heads $newbranch
2004        set all_heads [lsort $all_heads]
2005        populate_branch_menu
2006        destroy $w
2007        if {$create_branch_checkout} {
2008                switch_branch $newbranch
2009        }
2010}
2011
2012proc radio_selector {varname value args} {
2013        upvar #0 $varname var
2014        set var $value
2015}
2016
2017trace add variable create_branch_head write \
2018        [list radio_selector create_branch_revtype head]
2019trace add variable create_branch_trackinghead write \
2020        [list radio_selector create_branch_revtype tracking]
2021trace add variable create_branch_tag write \
2022        [list radio_selector create_branch_revtype tag]
2023
2024trace add variable delete_branch_head write \
2025        [list radio_selector delete_branch_checktype head]
2026trace add variable delete_branch_trackinghead write \
2027        [list radio_selector delete_branch_checktype tracking]
2028
2029proc do_create_branch {} {
2030        global all_heads current_branch repo_config
2031        global create_branch_checkout create_branch_revtype
2032        global create_branch_head create_branch_trackinghead
2033        global create_branch_name create_branch_revexp
2034        global create_branch_tag
2035
2036        set w .branch_editor
2037        toplevel $w
2038        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2039
2040        label $w.header -text {Create New Branch} \
2041                -font font_uibold
2042        pack $w.header -side top -fill x
2043
2044        frame $w.buttons
2045        button $w.buttons.create -text Create \
2046                -font font_ui \
2047                -default active \
2048                -command [list do_create_branch_action $w]
2049        pack $w.buttons.create -side right
2050        button $w.buttons.cancel -text {Cancel} \
2051                -font font_ui \
2052                -command [list destroy $w]
2053        pack $w.buttons.cancel -side right -padx 5
2054        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2055
2056        labelframe $w.desc \
2057                -text {Branch Description} \
2058                -font font_ui
2059        label $w.desc.name_l -text {Name:} -font font_ui
2060        entry $w.desc.name_t \
2061                -borderwidth 1 \
2062                -relief sunken \
2063                -width 40 \
2064                -textvariable create_branch_name \
2065                -font font_ui \
2066                -validate key \
2067                -validatecommand {
2068                        if {%d == 1 && [regexp {[~^:?*\[\0- ]} %S]} {return 0}
2069                        return 1
2070                }
2071        grid $w.desc.name_l $w.desc.name_t -sticky we -padx {0 5}
2072        grid columnconfigure $w.desc 1 -weight 1
2073        pack $w.desc -anchor nw -fill x -pady 5 -padx 5
2074
2075        labelframe $w.from \
2076                -text {Starting Revision} \
2077                -font font_ui
2078        radiobutton $w.from.head_r \
2079                -text {Local Branch:} \
2080                -value head \
2081                -variable create_branch_revtype \
2082                -font font_ui
2083        eval tk_optionMenu $w.from.head_m create_branch_head $all_heads
2084        grid $w.from.head_r $w.from.head_m -sticky w
2085        set all_trackings [all_tracking_branches]
2086        if {$all_trackings ne {}} {
2087                set create_branch_trackinghead [lindex $all_trackings 0]
2088                radiobutton $w.from.tracking_r \
2089                        -text {Tracking Branch:} \
2090                        -value tracking \
2091                        -variable create_branch_revtype \
2092                        -font font_ui
2093                eval tk_optionMenu $w.from.tracking_m \
2094                        create_branch_trackinghead \
2095                        $all_trackings
2096                grid $w.from.tracking_r $w.from.tracking_m -sticky w
2097        }
2098        set all_tags [load_all_tags]
2099        if {$all_tags ne {}} {
2100                set create_branch_tag [lindex $all_tags 0]
2101                radiobutton $w.from.tag_r \
2102                        -text {Tag:} \
2103                        -value tag \
2104                        -variable create_branch_revtype \
2105                        -font font_ui
2106                eval tk_optionMenu $w.from.tag_m \
2107                        create_branch_tag \
2108                        $all_tags
2109                grid $w.from.tag_r $w.from.tag_m -sticky w
2110        }
2111        radiobutton $w.from.exp_r \
2112                -text {Revision Expression:} \
2113                -value expression \
2114                -variable create_branch_revtype \
2115                -font font_ui
2116        entry $w.from.exp_t \
2117                -borderwidth 1 \
2118                -relief sunken \
2119                -width 50 \
2120                -textvariable create_branch_revexp \
2121                -font font_ui \
2122                -validate key \
2123                -validatecommand {
2124                        if {%d == 1 && [regexp {\s} %S]} {return 0}
2125                        if {%d == 1 && [string length %S] > 0} {
2126                                set create_branch_revtype expression
2127                        }
2128                        return 1
2129                }
2130        grid $w.from.exp_r $w.from.exp_t -sticky we -padx {0 5}
2131        grid columnconfigure $w.from 1 -weight 1
2132        pack $w.from -anchor nw -fill x -pady 5 -padx 5
2133
2134        labelframe $w.postActions \
2135                -text {Post Creation Actions} \
2136                -font font_ui
2137        checkbutton $w.postActions.checkout \
2138                -text {Checkout after creation} \
2139                -variable create_branch_checkout \
2140                -font font_ui
2141        pack $w.postActions.checkout -anchor nw
2142        pack $w.postActions -anchor nw -fill x -pady 5 -padx 5
2143
2144        set create_branch_checkout 1
2145        set create_branch_head $current_branch
2146        set create_branch_revtype head
2147        set create_branch_name $repo_config(gui.newbranchtemplate)
2148        set create_branch_revexp {}
2149
2150        bind $w <Visibility> "
2151                grab $w
2152                $w.desc.name_t icursor end
2153                focus $w.desc.name_t
2154        "
2155        bind $w <Key-Escape> "destroy $w"
2156        bind $w <Key-Return> "do_create_branch_action $w;break"
2157        wm title $w "[appname] ([reponame]): Create Branch"
2158        tkwait window $w
2159}
2160
2161proc do_delete_branch_action {w} {
2162        global all_heads
2163        global delete_branch_checktype delete_branch_head delete_branch_trackinghead
2164
2165        set check_rev {}
2166        switch -- $delete_branch_checktype {
2167        head {set check_rev $delete_branch_head}
2168        tracking {set check_rev $delete_branch_trackinghead}
2169        always {set check_rev {:none}}
2170        }
2171        if {$check_rev eq {:none}} {
2172                set check_cmt {}
2173        } elseif {[catch {set check_cmt [git rev-parse --verify "${check_rev}^0"]}]} {
2174                tk_messageBox \
2175                        -icon error \
2176                        -type ok \
2177                        -title [wm title $w] \
2178                        -parent $w \
2179                        -message "Invalid check revision: $check_rev"
2180                return
2181        }
2182
2183        set to_delete [list]
2184        set not_merged [list]
2185        foreach i [$w.list.l curselection] {
2186                set b [$w.list.l get $i]
2187                if {[catch {set o [git rev-parse --verify $b]}]} continue
2188                if {$check_cmt ne {}} {
2189                        if {$b eq $check_rev} continue
2190                        if {[catch {set m [git merge-base $o $check_cmt]}]} continue
2191                        if {$o ne $m} {
2192                                lappend not_merged $b
2193                                continue
2194                        }
2195                }
2196                lappend to_delete [list $b $o]
2197        }
2198        if {$not_merged ne {}} {
2199                set msg "The following branches are not completely merged into $check_rev:
2200
2201 - [join $not_merged "\n - "]"
2202                tk_messageBox \
2203                        -icon info \
2204                        -type ok \
2205                        -title [wm title $w] \
2206                        -parent $w \
2207                        -message $msg
2208        }
2209        if {$to_delete eq {}} return
2210        if {$delete_branch_checktype eq {always}} {
2211                set msg {Recovering deleted branches is difficult.
2212
2213Delete the selected branches?}
2214                if {[tk_messageBox \
2215                        -icon warning \
2216                        -type yesno \
2217                        -title [wm title $w] \
2218                        -parent $w \
2219                        -message $msg] ne yes} {
2220                        return
2221                }
2222        }
2223
2224        set failed {}
2225        foreach i $to_delete {
2226                set b [lindex $i 0]
2227                set o [lindex $i 1]
2228                if {[catch {git update-ref -d "refs/heads/$b" $o} err]} {
2229                        append failed " - $b: $err\n"
2230                } else {
2231                        set x [lsearch -sorted -exact $all_heads $b]
2232                        if {$x >= 0} {
2233                                set all_heads [lreplace $all_heads $x $x]
2234                        }
2235                }
2236        }
2237
2238        if {$failed ne {}} {
2239                tk_messageBox \
2240                        -icon error \
2241                        -type ok \
2242                        -title [wm title $w] \
2243                        -parent $w \
2244                        -message "Failed to delete branches:\n$failed"
2245        }
2246
2247        set all_heads [lsort $all_heads]
2248        populate_branch_menu
2249        destroy $w
2250}
2251
2252proc do_delete_branch {} {
2253        global all_heads tracking_branches current_branch
2254        global delete_branch_checktype delete_branch_head delete_branch_trackinghead
2255
2256        set w .branch_editor
2257        toplevel $w
2258        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2259
2260        label $w.header -text {Delete Local Branch} \
2261                -font font_uibold
2262        pack $w.header -side top -fill x
2263
2264        frame $w.buttons
2265        button $w.buttons.create -text Delete \
2266                -font font_ui \
2267                -command [list do_delete_branch_action $w]
2268        pack $w.buttons.create -side right
2269        button $w.buttons.cancel -text {Cancel} \
2270                -font font_ui \
2271                -command [list destroy $w]
2272        pack $w.buttons.cancel -side right -padx 5
2273        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2274
2275        labelframe $w.list \
2276                -text {Local Branches} \
2277                -font font_ui
2278        listbox $w.list.l \
2279                -height 10 \
2280                -width 70 \
2281                -selectmode extended \
2282                -yscrollcommand [list $w.list.sby set] \
2283                -font font_ui
2284        foreach h $all_heads {
2285                if {$h ne $current_branch} {
2286                        $w.list.l insert end $h
2287                }
2288        }
2289        scrollbar $w.list.sby -command [list $w.list.l yview]
2290        pack $w.list.sby -side right -fill y
2291        pack $w.list.l -side left -fill both -expand 1
2292        pack $w.list -fill both -expand 1 -pady 5 -padx 5
2293
2294        labelframe $w.validate \
2295                -text {Delete Only If} \
2296                -font font_ui
2297        radiobutton $w.validate.head_r \
2298                -text {Merged Into Local Branch:} \
2299                -value head \
2300                -variable delete_branch_checktype \
2301                -font font_ui
2302        eval tk_optionMenu $w.validate.head_m delete_branch_head $all_heads
2303        grid $w.validate.head_r $w.validate.head_m -sticky w
2304        set all_trackings [all_tracking_branches]
2305        if {$all_trackings ne {}} {
2306                set delete_branch_trackinghead [lindex $all_trackings 0]
2307                radiobutton $w.validate.tracking_r \
2308                        -text {Merged Into Tracking Branch:} \
2309                        -value tracking \
2310                        -variable delete_branch_checktype \
2311                        -font font_ui
2312                eval tk_optionMenu $w.validate.tracking_m \
2313                        delete_branch_trackinghead \
2314                        $all_trackings
2315                grid $w.validate.tracking_r $w.validate.tracking_m -sticky w
2316        }
2317        radiobutton $w.validate.always_r \
2318                -text {Always (Do not perform merge checks)} \
2319                -value always \
2320                -variable delete_branch_checktype \
2321                -font font_ui
2322        grid $w.validate.always_r -columnspan 2 -sticky w
2323        grid columnconfigure $w.validate 1 -weight 1
2324        pack $w.validate -anchor nw -fill x -pady 5 -padx 5
2325
2326        set delete_branch_head $current_branch
2327        set delete_branch_checktype head
2328
2329        bind $w <Visibility> "grab $w; focus $w"
2330        bind $w <Key-Escape> "destroy $w"
2331        wm title $w "[appname] ([reponame]): Delete Branch"
2332        tkwait window $w
2333}
2334
2335proc switch_branch {new_branch} {
2336        global HEAD commit_type current_branch repo_config
2337
2338        if {![lock_index switch]} return
2339
2340        # -- Our in memory state should match the repository.
2341        #
2342        repository_state curType curHEAD curMERGE_HEAD
2343        if {[string match amend* $commit_type]
2344                && $curType eq {normal}
2345                && $curHEAD eq $HEAD} {
2346        } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
2347                info_popup {Last scanned state does not match repository state.
2348
2349Another Git program has modified this repository
2350since the last scan.  A rescan must be performed
2351before the current branch can be changed.
2352
2353The rescan will be automatically started now.
2354}
2355                unlock_index
2356                rescan {set ui_status_value {Ready.}}
2357                return
2358        }
2359
2360        # -- Don't do a pointless switch.
2361        #
2362        if {$current_branch eq $new_branch} {
2363                unlock_index
2364                return
2365        }
2366
2367        if {$repo_config(gui.trustmtime) eq {true}} {
2368                switch_branch_stage2 {} $new_branch
2369        } else {
2370                set ui_status_value {Refreshing file status...}
2371                set cmd [list git update-index]
2372                lappend cmd -q
2373                lappend cmd --unmerged
2374                lappend cmd --ignore-missing
2375                lappend cmd --refresh
2376                set fd_rf [open "| $cmd" r]
2377                fconfigure $fd_rf -blocking 0 -translation binary
2378                fileevent $fd_rf readable \
2379                        [list switch_branch_stage2 $fd_rf $new_branch]
2380        }
2381}
2382
2383proc switch_branch_stage2 {fd_rf new_branch} {
2384        global ui_status_value HEAD
2385
2386        if {$fd_rf ne {}} {
2387                read $fd_rf
2388                if {![eof $fd_rf]} return
2389                close $fd_rf
2390        }
2391
2392        set ui_status_value "Updating working directory to '$new_branch'..."
2393        set cmd [list git read-tree]
2394        lappend cmd -m
2395        lappend cmd -u
2396        lappend cmd --exclude-per-directory=.gitignore
2397        lappend cmd $HEAD
2398        lappend cmd $new_branch
2399        set fd_rt [open "| $cmd" r]
2400        fconfigure $fd_rt -blocking 0 -translation binary
2401        fileevent $fd_rt readable \
2402                [list switch_branch_readtree_wait $fd_rt $new_branch]
2403}
2404
2405proc switch_branch_readtree_wait {fd_rt new_branch} {
2406        global selected_commit_type commit_type HEAD MERGE_HEAD PARENT
2407        global current_branch
2408        global ui_comm ui_status_value
2409
2410        # -- We never get interesting output on stdout; only stderr.
2411        #
2412        read $fd_rt
2413        fconfigure $fd_rt -blocking 1
2414        if {![eof $fd_rt]} {
2415                fconfigure $fd_rt -blocking 0
2416                return
2417        }
2418
2419        # -- The working directory wasn't in sync with the index and
2420        #    we'd have to overwrite something to make the switch. A
2421        #    merge is required.
2422        #
2423        if {[catch {close $fd_rt} err]} {
2424                regsub {^fatal: } $err {} err
2425                warn_popup "File level merge required.
2426
2427$err
2428
2429Staying on branch '$current_branch'."
2430                set ui_status_value "Aborted checkout of '$new_branch' (file level merging is required)."
2431                unlock_index
2432                return
2433        }
2434
2435        # -- Update the symbolic ref.  Core git doesn't even check for failure
2436        #    here, it Just Works(tm).  If it doesn't we are in some really ugly
2437        #    state that is difficult to recover from within git-gui.
2438        #
2439        if {[catch {git symbolic-ref HEAD "refs/heads/$new_branch"} err]} {
2440                error_popup "Failed to set current branch.
2441
2442This working directory is only partially switched.
2443We successfully updated your files, but failed to
2444update an internal Git file.
2445
2446This should not have occurred.  [appname] will now
2447close and give up.
2448
2449$err"
2450                do_quit
2451                return
2452        }
2453
2454        # -- Update our repository state.  If we were previously in amend mode
2455        #    we need to toss the current buffer and do a full rescan to update
2456        #    our file lists.  If we weren't in amend mode our file lists are
2457        #    accurate and we can avoid the rescan.
2458        #
2459        unlock_index
2460        set selected_commit_type new
2461        if {[string match amend* $commit_type]} {
2462                $ui_comm delete 0.0 end
2463                $ui_comm edit reset
2464                $ui_comm edit modified false
2465                rescan {set ui_status_value "Checked out branch '$current_branch'."}
2466        } else {
2467                repository_state commit_type HEAD MERGE_HEAD
2468                set PARENT $HEAD
2469                set ui_status_value "Checked out branch '$current_branch'."
2470        }
2471}
2472
2473######################################################################
2474##
2475## remote management
2476
2477proc load_all_remotes {} {
2478        global repo_config
2479        global all_remotes tracking_branches
2480
2481        set all_remotes [list]
2482        array unset tracking_branches
2483
2484        set rm_dir [gitdir remotes]
2485        if {[file isdirectory $rm_dir]} {
2486                set all_remotes [glob \
2487                        -types f \
2488                        -tails \
2489                        -nocomplain \
2490                        -directory $rm_dir *]
2491
2492                foreach name $all_remotes {
2493                        catch {
2494                                set fd [open [file join $rm_dir $name] r]
2495                                while {[gets $fd line] >= 0} {
2496                                        if {![regexp {^Pull:[   ]*([^:]+):(.+)$} \
2497                                                $line line src dst]} continue
2498                                        if {![regexp ^refs/ $dst]} {
2499                                                set dst "refs/heads/$dst"
2500                                        }
2501                                        set tracking_branches($dst) [list $name $src]
2502                                }
2503                                close $fd
2504                        }
2505                }
2506        }
2507
2508        foreach line [array names repo_config remote.*.url] {
2509                if {![regexp ^remote\.(.*)\.url\$ $line line name]} continue
2510                lappend all_remotes $name
2511
2512                if {[catch {set fl $repo_config(remote.$name.fetch)}]} {
2513                        set fl {}
2514                }
2515                foreach line $fl {
2516                        if {![regexp {^([^:]+):(.+)$} $line line src dst]} continue
2517                        if {![regexp ^refs/ $dst]} {
2518                                set dst "refs/heads/$dst"
2519                        }
2520                        set tracking_branches($dst) [list $name $src]
2521                }
2522        }
2523
2524        set all_remotes [lsort -unique $all_remotes]
2525}
2526
2527proc populate_fetch_menu {} {
2528        global all_remotes repo_config
2529
2530        set m .mbar.fetch
2531        foreach r $all_remotes {
2532                set enable 0
2533                if {![catch {set a $repo_config(remote.$r.url)}]} {
2534                        if {![catch {set a $repo_config(remote.$r.fetch)}]} {
2535                                set enable 1
2536                        }
2537                } else {
2538                        catch {
2539                                set fd [open [gitdir remotes $r] r]
2540                                while {[gets $fd n] >= 0} {
2541                                        if {[regexp {^Pull:[ \t]*([^:]+):} $n]} {
2542                                                set enable 1
2543                                                break
2544                                        }
2545                                }
2546                                close $fd
2547                        }
2548                }
2549
2550                if {$enable} {
2551                        $m add command \
2552                                -label "Fetch from $r..." \
2553                                -command [list fetch_from $r] \
2554                                -font font_ui
2555                }
2556        }
2557}
2558
2559proc populate_push_menu {} {
2560        global all_remotes repo_config
2561
2562        set m .mbar.push
2563        set fast_count 0
2564        foreach r $all_remotes {
2565                set enable 0
2566                if {![catch {set a $repo_config(remote.$r.url)}]} {
2567                        if {![catch {set a $repo_config(remote.$r.push)}]} {
2568                                set enable 1
2569                        }
2570                } else {
2571                        catch {
2572                                set fd [open [gitdir remotes $r] r]
2573                                while {[gets $fd n] >= 0} {
2574                                        if {[regexp {^Push:[ \t]*([^:]+):} $n]} {
2575                                                set enable 1
2576                                                break
2577                                        }
2578                                }
2579                                close $fd
2580                        }
2581                }
2582
2583                if {$enable} {
2584                        if {!$fast_count} {
2585                                $m add separator
2586                        }
2587                        $m add command \
2588                                -label "Push to $r..." \
2589                                -command [list push_to $r] \
2590                                -font font_ui
2591                        incr fast_count
2592                }
2593        }
2594}
2595
2596proc start_push_anywhere_action {w} {
2597        global push_urltype push_remote push_url push_thin push_tags
2598
2599        set r_url {}
2600        switch -- $push_urltype {
2601        remote {set r_url $push_remote}
2602        url {set r_url $push_url}
2603        }
2604        if {$r_url eq {}} return
2605
2606        set cmd [list git push]
2607        lappend cmd -v
2608        if {$push_thin} {
2609                lappend cmd --thin
2610        }
2611        if {$push_tags} {
2612                lappend cmd --tags
2613        }
2614        lappend cmd $r_url
2615        set cnt 0
2616        foreach i [$w.source.l curselection] {
2617                set b [$w.source.l get $i]
2618                lappend cmd "refs/heads/$b:refs/heads/$b"
2619                incr cnt
2620        }
2621        if {$cnt == 0} {
2622                return
2623        } elseif {$cnt == 1} {
2624                set unit branch
2625        } else {
2626                set unit branches
2627        }
2628
2629        set cons [new_console "push $r_url" "Pushing $cnt $unit to $r_url"]
2630        console_exec $cons $cmd console_done
2631        destroy $w
2632}
2633
2634trace add variable push_remote write \
2635        [list radio_selector push_urltype remote]
2636
2637proc do_push_anywhere {} {
2638        global all_heads all_remotes current_branch
2639        global push_urltype push_remote push_url push_thin push_tags
2640
2641        set w .push_setup
2642        toplevel $w
2643        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2644
2645        label $w.header -text {Push Branches} -font font_uibold
2646        pack $w.header -side top -fill x
2647
2648        frame $w.buttons
2649        button $w.buttons.create -text Push \
2650                -font font_ui \
2651                -command [list start_push_anywhere_action $w]
2652        pack $w.buttons.create -side right
2653        button $w.buttons.cancel -text {Cancel} \
2654                -font font_ui \
2655                -command [list destroy $w]
2656        pack $w.buttons.cancel -side right -padx 5
2657        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2658
2659        labelframe $w.source \
2660                -text {Source Branches} \
2661                -font font_ui
2662        listbox $w.source.l \
2663                -height 10 \
2664                -width 70 \
2665                -selectmode extended \
2666                -yscrollcommand [list $w.source.sby set] \
2667                -font font_ui
2668        foreach h $all_heads {
2669                $w.source.l insert end $h
2670                if {$h eq $current_branch} {
2671                        $w.source.l select set end
2672                }
2673        }
2674        scrollbar $w.source.sby -command [list $w.source.l yview]
2675        pack $w.source.sby -side right -fill y
2676        pack $w.source.l -side left -fill both -expand 1
2677        pack $w.source -fill both -expand 1 -pady 5 -padx 5
2678
2679        labelframe $w.dest \
2680                -text {Destination Repository} \
2681                -font font_ui
2682        if {$all_remotes ne {}} {
2683                radiobutton $w.dest.remote_r \
2684                        -text {Remote:} \
2685                        -value remote \
2686                        -variable push_urltype \
2687                        -font font_ui
2688                eval tk_optionMenu $w.dest.remote_m push_remote $all_remotes
2689                grid $w.dest.remote_r $w.dest.remote_m -sticky w
2690                if {[lsearch -sorted -exact $all_remotes origin] != -1} {
2691                        set push_remote origin
2692                } else {
2693                        set push_remote [lindex $all_remotes 0]
2694                }
2695                set push_urltype remote
2696        } else {
2697                set push_urltype url
2698        }
2699        radiobutton $w.dest.url_r \
2700                -text {Arbitrary URL:} \
2701                -value url \
2702                -variable push_urltype \
2703                -font font_ui
2704        entry $w.dest.url_t \
2705                -borderwidth 1 \
2706                -relief sunken \
2707                -width 50 \
2708                -textvariable push_url \
2709                -font font_ui \
2710                -validate key \
2711                -validatecommand {
2712                        if {%d == 1 && [regexp {\s} %S]} {return 0}
2713                        if {%d == 1 && [string length %S] > 0} {
2714                                set push_urltype url
2715                        }
2716                        return 1
2717                }
2718        grid $w.dest.url_r $w.dest.url_t -sticky we -padx {0 5}
2719        grid columnconfigure $w.dest 1 -weight 1
2720        pack $w.dest -anchor nw -fill x -pady 5 -padx 5
2721
2722        labelframe $w.options \
2723                -text {Transfer Options} \
2724                -font font_ui
2725        checkbutton $w.options.thin \
2726                -text {Use thin pack (for slow network connections)} \
2727                -variable push_thin \
2728                -font font_ui
2729        grid $w.options.thin -columnspan 2 -sticky w
2730        checkbutton $w.options.tags \
2731                -text {Include tags} \
2732                -variable push_tags \
2733                -font font_ui
2734        grid $w.options.tags -columnspan 2 -sticky w
2735        grid columnconfigure $w.options 1 -weight 1
2736        pack $w.options -anchor nw -fill x -pady 5 -padx 5
2737
2738        set push_url {}
2739        set push_thin 0
2740        set push_tags 0
2741
2742        bind $w <Visibility> "grab $w"
2743        bind $w <Key-Escape> "destroy $w"
2744        wm title $w "[appname] ([reponame]): Push"
2745        tkwait window $w
2746}
2747
2748######################################################################
2749##
2750## merge
2751
2752proc can_merge {} {
2753        global HEAD commit_type file_states
2754
2755        if {[string match amend* $commit_type]} {
2756                info_popup {Cannot merge while amending.
2757
2758You must finish amending this commit before
2759starting any type of merge.
2760}
2761                return 0
2762        }
2763
2764        if {[committer_ident] eq {}} {return 0}
2765        if {![lock_index merge]} {return 0}
2766
2767        # -- Our in memory state should match the repository.
2768        #
2769        repository_state curType curHEAD curMERGE_HEAD
2770        if {$commit_type ne $curType || $HEAD ne $curHEAD} {
2771                info_popup {Last scanned state does not match repository state.
2772
2773Another Git program has modified this repository
2774since the last scan.  A rescan must be performed
2775before a merge can be performed.
2776
2777The rescan will be automatically started now.
2778}
2779                unlock_index
2780                rescan {set ui_status_value {Ready.}}
2781                return 0
2782        }
2783
2784        foreach path [array names file_states] {
2785                switch -glob -- [lindex $file_states($path) 0] {
2786                _O {
2787                        continue; # and pray it works!
2788                }
2789                U? {
2790                        error_popup "You are in the middle of a conflicted merge.
2791
2792File [short_path $path] has merge conflicts.
2793
2794You must resolve them, add the file, and commit to
2795complete the current merge.  Only then can you
2796begin another merge.
2797"
2798                        unlock_index
2799                        return 0
2800                }
2801                ?? {
2802                        error_popup "You are in the middle of a change.
2803
2804File [short_path $path] is modified.
2805
2806You should complete the current commit before
2807starting a merge.  Doing so will help you abort
2808a failed merge, should the need arise.
2809"
2810                        unlock_index
2811                        return 0
2812                }
2813                }
2814        }
2815
2816        return 1
2817}
2818
2819proc visualize_local_merge {w} {
2820        set revs {}
2821        foreach i [$w.source.l curselection] {
2822                lappend revs [$w.source.l get $i]
2823        }
2824        if {$revs eq {}} return
2825        lappend revs --not HEAD
2826        do_gitk $revs
2827}
2828
2829proc start_local_merge_action {w} {
2830        global HEAD ui_status_value current_branch
2831
2832        set cmd [list git merge]
2833        set names {}
2834        set revcnt 0
2835        foreach i [$w.source.l curselection] {
2836                set b [$w.source.l get $i]
2837                lappend cmd $b
2838                lappend names $b
2839                incr revcnt
2840        }
2841
2842        if {$revcnt == 0} {
2843                return
2844        } elseif {$revcnt == 1} {
2845                set unit branch
2846        } elseif {$revcnt <= 15} {
2847                set unit branches
2848        } else {
2849                tk_messageBox \
2850                        -icon error \
2851                        -type ok \
2852                        -title [wm title $w] \
2853                        -parent $w \
2854                        -message "Too many branches selected.
2855
2856You have requested to merge $revcnt branches
2857in an octopus merge.  This exceeds Git's
2858internal limit of 15 branches per merge.
2859
2860Please select fewer branches.  To merge more
2861than 15 branches, merge the branches in batches.
2862"
2863                return
2864        }
2865
2866        set msg "Merging $current_branch, [join $names {, }]"
2867        set ui_status_value "$msg..."
2868        set cons [new_console "Merge" $msg]
2869        console_exec $cons $cmd [list finish_merge $revcnt]
2870        bind $w <Destroy> {}
2871        destroy $w
2872}
2873
2874proc finish_merge {revcnt w ok} {
2875        console_done $w $ok
2876        if {$ok} {
2877                set msg {Merge completed successfully.}
2878        } else {
2879                if {$revcnt != 1} {
2880                        info_popup "Octopus merge failed.
2881
2882Your merge of $revcnt branches has failed.
2883
2884There are file-level conflicts between the
2885branches which must be resolved manually.
2886
2887The working directory will now be reset.
2888
2889You can attempt this merge again
2890by merging only one branch at a time." $w
2891
2892                        set fd [open "| git read-tree --reset -u HEAD" r]
2893                        fconfigure $fd -blocking 0 -translation binary
2894                        fileevent $fd readable [list reset_hard_wait $fd]
2895                        set ui_status_value {Aborting... please wait...}
2896                        return
2897                }
2898
2899                set msg {Merge failed.  Conflict resolution is required.}
2900        }
2901        unlock_index
2902        rescan [list set ui_status_value $msg]
2903}
2904
2905proc do_local_merge {} {
2906        global current_branch
2907
2908        if {![can_merge]} return
2909
2910        set w .merge_setup
2911        toplevel $w
2912        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2913
2914        label $w.header \
2915                -text "Merge Into $current_branch" \
2916                -font font_uibold
2917        pack $w.header -side top -fill x
2918
2919        frame $w.buttons
2920        button $w.buttons.visualize -text Visualize \
2921                -font font_ui \
2922                -command [list visualize_local_merge $w]
2923        pack $w.buttons.visualize -side left
2924        button $w.buttons.create -text Merge \
2925                -font font_ui \
2926                -command [list start_local_merge_action $w]
2927        pack $w.buttons.create -side right
2928        button $w.buttons.cancel -text {Cancel} \
2929                -font font_ui \
2930                -command [list destroy $w]
2931        pack $w.buttons.cancel -side right -padx 5
2932        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2933
2934        labelframe $w.source \
2935                -text {Source Branches} \
2936                -font font_ui
2937        listbox $w.source.l \
2938                -height 10 \
2939                -width 70 \
2940                -selectmode extended \
2941                -yscrollcommand [list $w.source.sby set] \
2942                -font font_ui
2943        scrollbar $w.source.sby -command [list $w.source.l yview]
2944        pack $w.source.sby -side right -fill y
2945        pack $w.source.l -side left -fill both -expand 1
2946        pack $w.source -fill both -expand 1 -pady 5 -padx 5
2947
2948        set cmd [list git for-each-ref]
2949        lappend cmd {--format=%(objectname) %(*objectname) %(refname)}
2950        lappend cmd refs/heads
2951        lappend cmd refs/remotes
2952        lappend cmd refs/tags
2953        set fr_fd [open "| $cmd" r]
2954        fconfigure $fr_fd -translation binary
2955        while {[gets $fr_fd line] > 0} {
2956                set line [split $line { }]
2957                set sha1([lindex $line 0]) [lindex $line 2]
2958                set sha1([lindex $line 1]) [lindex $line 2]
2959        }
2960        close $fr_fd
2961
2962        set to_show {}
2963        set fr_fd [open "| git rev-list --all --not HEAD"]
2964        while {[gets $fr_fd line] > 0} {
2965                if {[catch {set ref $sha1($line)}]} continue
2966                regsub ^refs/(heads|remotes|tags)/ $ref {} ref
2967                lappend to_show $ref
2968        }
2969        close $fr_fd
2970
2971        foreach ref [lsort -unique $to_show] {
2972                $w.source.l insert end $ref
2973        }
2974
2975        bind $w <Visibility> "grab $w"
2976        bind $w <Key-Escape> "unlock_index;destroy $w"
2977        bind $w <Destroy> unlock_index
2978        wm title $w "[appname] ([reponame]): Merge"
2979        tkwait window $w
2980}
2981
2982proc do_reset_hard {} {
2983        global HEAD commit_type file_states
2984
2985        if {[string match amend* $commit_type]} {
2986                info_popup {Cannot abort while amending.
2987
2988You must finish amending this commit.
2989}
2990                return
2991        }
2992
2993        if {![lock_index abort]} return
2994
2995        if {[string match *merge* $commit_type]} {
2996                set op merge
2997        } else {
2998                set op commit
2999        }
3000
3001        if {[ask_popup "Abort $op?
3002
3003Aborting the current $op will cause
3004*ALL* uncommitted changes to be lost.
3005
3006Continue with aborting the current $op?"] eq {yes}} {
3007                set fd [open "| git read-tree --reset -u HEAD" r]
3008                fconfigure $fd -blocking 0 -translation binary
3009                fileevent $fd readable [list reset_hard_wait $fd]
3010                set ui_status_value {Aborting... please wait...}
3011        } else {
3012                unlock_index
3013        }
3014}
3015
3016proc reset_hard_wait {fd} {
3017        global ui_comm
3018
3019        read $fd
3020        if {[eof $fd]} {
3021                close $fd
3022                unlock_index
3023
3024                $ui_comm delete 0.0 end
3025                $ui_comm edit modified false
3026
3027                catch {file delete [gitdir MERGE_HEAD]}
3028                catch {file delete [gitdir rr-cache MERGE_RR]}
3029                catch {file delete [gitdir SQUASH_MSG]}
3030                catch {file delete [gitdir MERGE_MSG]}
3031                catch {file delete [gitdir GITGUI_MSG]}
3032
3033                rescan {set ui_status_value {Abort completed.  Ready.}}
3034        }
3035}
3036
3037######################################################################
3038##
3039## browser
3040
3041set next_browser_id 0
3042
3043proc new_browser {commit} {
3044        global next_browser_id cursor_ptr M1B
3045        global browser_commit browser_status browser_stack browser_path browser_busy
3046
3047        set w .browser[incr next_browser_id]
3048        set w_list $w.list.l
3049        set browser_commit($w_list) $commit
3050        set browser_status($w_list) {Starting...}
3051        set browser_stack($w_list) {}
3052        set browser_path($w_list) $browser_commit($w_list):
3053        set browser_busy($w_list) 1
3054
3055        toplevel $w
3056        label $w.path -textvariable browser_path($w_list) \
3057                -anchor w \
3058                -justify left \
3059                -borderwidth 1 \
3060                -relief sunken \
3061                -font font_uibold
3062        pack $w.path -anchor w -side top -fill x
3063
3064        frame $w.list
3065        text $w_list -background white -borderwidth 0 \
3066                -cursor $cursor_ptr \
3067                -state disabled \
3068                -wrap none \
3069                -height 20 \
3070                -width 70 \
3071                -xscrollcommand [list $w.list.sbx set] \
3072                -yscrollcommand [list $w.list.sby set] \
3073                -font font_ui
3074        $w_list tag conf in_sel \
3075                -background [$w_list cget -foreground] \
3076                -foreground [$w_list cget -background]
3077        scrollbar $w.list.sbx -orient h -command [list $w_list xview]
3078        scrollbar $w.list.sby -orient v -command [list $w_list yview]
3079        pack $w.list.sbx -side bottom -fill x
3080        pack $w.list.sby -side right -fill y
3081        pack $w_list -side left -fill both -expand 1
3082        pack $w.list -side top -fill both -expand 1
3083
3084        label $w.status -textvariable browser_status($w_list) \
3085                -anchor w \
3086                -justify left \
3087                -borderwidth 1 \
3088                -relief sunken \
3089                -font font_ui
3090        pack $w.status -anchor w -side bottom -fill x
3091
3092        bind $w_list <Button-1>        "browser_click 0 $w_list @%x,%y;break"
3093        bind $w_list <Double-Button-1> "browser_click 1 $w_list @%x,%y;break"
3094        bind $w_list <$M1B-Up>         "browser_parent $w_list;break"
3095        bind $w_list <$M1B-Left>       "browser_parent $w_list;break"
3096        bind $w_list <Up>              "browser_move -1 $w_list;break"
3097        bind $w_list <Down>            "browser_move 1 $w_list;break"
3098        bind $w_list <$M1B-Right>      "browser_enter $w_list;break"
3099        bind $w_list <Return>          "browser_enter $w_list;break"
3100        bind $w_list <Prior>           "browser_page -1 $w_list;break"
3101        bind $w_list <Next>            "browser_page 1 $w_list;break"
3102        bind $w_list <Left>            break
3103        bind $w_list <Right>           break
3104
3105        bind $w <Visibility> "focus $w"
3106        bind $w <Destroy> "
3107                array unset browser_buffer $w_list
3108                array unset browser_files $w_list
3109                array unset browser_status $w_list
3110                array unset browser_stack $w_list
3111                array unset browser_path $w_list
3112                array unset browser_commit $w_list
3113                array unset browser_busy $w_list
3114        "
3115        wm title $w "[appname] ([reponame]): File Browser"
3116        ls_tree $w_list $browser_commit($w_list) {}
3117}
3118
3119proc browser_move {dir w} {
3120        global browser_files browser_busy
3121
3122        if {$browser_busy($w)} return
3123        set lno [lindex [split [$w index in_sel.first] .] 0]
3124        incr lno $dir
3125        if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3126                $w tag remove in_sel 0.0 end
3127                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3128                $w see $lno.0
3129        }
3130}
3131
3132proc browser_page {dir w} {
3133        global browser_files browser_busy
3134
3135        if {$browser_busy($w)} return
3136        $w yview scroll $dir pages
3137        set lno [expr {int(
3138                  [lindex [$w yview] 0]
3139                * [llength $browser_files($w)]
3140                + 1)}]
3141        if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3142                $w tag remove in_sel 0.0 end
3143                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3144                $w see $lno.0
3145        }
3146}
3147
3148proc browser_parent {w} {
3149        global browser_files browser_status browser_path
3150        global browser_stack browser_busy
3151
3152        if {$browser_busy($w)} return
3153        set info [lindex $browser_files($w) 0]
3154        if {[lindex $info 0] eq {parent}} {
3155                set parent [lindex $browser_stack($w) end-1]
3156                set browser_stack($w) [lrange $browser_stack($w) 0 end-2]
3157                if {$browser_stack($w) eq {}} {
3158                        regsub {:.*$} $browser_path($w) {:} browser_path($w)
3159                } else {
3160                        regsub {/[^/]+$} $browser_path($w) {} browser_path($w)
3161                }
3162                set browser_status($w) "Loading $browser_path($w)..."
3163                ls_tree $w [lindex $parent 0] [lindex $parent 1]
3164        }
3165}
3166
3167proc browser_enter {w} {
3168        global browser_files browser_status browser_path
3169        global browser_commit browser_stack browser_busy
3170
3171        if {$browser_busy($w)} return
3172        set lno [lindex [split [$w index in_sel.first] .] 0]
3173        set info [lindex $browser_files($w) [expr {$lno - 1}]]
3174        if {$info ne {}} {
3175                switch -- [lindex $info 0] {
3176                parent {
3177                        browser_parent $w
3178                }
3179                tree {
3180                        set name [lindex $info 2]
3181                        set escn [escape_path $name]
3182                        set browser_status($w) "Loading $escn..."
3183                        append browser_path($w) $escn
3184                        ls_tree $w [lindex $info 1] $name
3185                }
3186                blob {
3187                        set name [lindex $info 2]
3188                        set p {}
3189                        foreach n $browser_stack($w) {
3190                                append p [lindex $n 1]
3191                        }
3192                        append p $name
3193                        show_blame $browser_commit($w) $p
3194                }
3195                }
3196        }
3197}
3198
3199proc browser_click {was_double_click w pos} {
3200        global browser_files browser_busy
3201
3202        if {$browser_busy($w)} return
3203        set lno [lindex [split [$w index $pos] .] 0]
3204        focus $w
3205
3206        if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3207                $w tag remove in_sel 0.0 end
3208                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3209                if {$was_double_click} {
3210                        browser_enter $w
3211                }
3212        }
3213}
3214
3215proc ls_tree {w tree_id name} {
3216        global browser_buffer browser_files browser_stack browser_busy
3217
3218        set browser_buffer($w) {}
3219        set browser_files($w) {}
3220        set browser_busy($w) 1
3221
3222        $w conf -state normal
3223        $w tag remove in_sel 0.0 end
3224        $w delete 0.0 end
3225        if {$browser_stack($w) ne {}} {
3226                $w image create end \
3227                        -align center -padx 5 -pady 1 \
3228                        -name icon0 \
3229                        -image file_uplevel
3230                $w insert end {[Up To Parent]}
3231                lappend browser_files($w) parent
3232        }
3233        lappend browser_stack($w) [list $tree_id $name]
3234        $w conf -state disabled
3235
3236        set cmd [list git ls-tree -z $tree_id]
3237        set fd [open "| $cmd" r]
3238        fconfigure $fd -blocking 0 -translation binary -encoding binary
3239        fileevent $fd readable [list read_ls_tree $fd $w]
3240}
3241
3242proc read_ls_tree {fd w} {
3243        global browser_buffer browser_files browser_status browser_busy
3244
3245        if {![winfo exists $w]} {
3246                catch {close $fd}
3247                return
3248        }
3249
3250        append browser_buffer($w) [read $fd]
3251        set pck [split $browser_buffer($w) "\0"]
3252        set browser_buffer($w) [lindex $pck end]
3253
3254        set n [llength $browser_files($w)]
3255        $w conf -state normal
3256        foreach p [lrange $pck 0 end-1] {
3257                set info [split $p "\t"]
3258                set path [lindex $info 1]
3259                set info [split [lindex $info 0] { }]
3260                set type [lindex $info 1]
3261                set object [lindex $info 2]
3262
3263                switch -- $type {
3264                blob {
3265                        set image file_mod
3266                }
3267                tree {
3268                        set image file_dir
3269                        append path /
3270                }
3271                default {
3272                        set image file_question
3273                }
3274                }
3275
3276                if {$n > 0} {$w insert end "\n"}
3277                $w image create end \
3278                        -align center -padx 5 -pady 1 \
3279                        -name icon[incr n] \
3280                        -image $image
3281                $w insert end [escape_path $path]
3282                lappend browser_files($w) [list $type $object $path]
3283        }
3284        $w conf -state disabled
3285
3286        if {[eof $fd]} {
3287                close $fd
3288                set browser_status($w) Ready.
3289                set browser_busy($w) 0
3290                array unset browser_buffer $w
3291                if {$n > 0} {
3292                        $w tag add in_sel 1.0 2.0
3293                        focus -force $w
3294                }
3295        }
3296}
3297
3298proc show_blame {commit path} {
3299        global next_browser_id blame_status blame_data
3300
3301        if {[winfo ismapped .]} {
3302                set w .browser[incr next_browser_id]
3303                set tl $w
3304                toplevel $w
3305        } else {
3306                set w {}
3307                set tl .
3308        }
3309        set blame_status($w) {Loading current file content...}
3310
3311        label $w.path -text "$commit:$path" \
3312                -anchor w \
3313                -justify left \
3314                -borderwidth 1 \
3315                -relief sunken \
3316                -font font_uibold
3317        pack $w.path -side top -fill x
3318
3319        frame $w.out
3320        text $w.out.loaded_t \
3321                -background white -borderwidth 0 \
3322                -state disabled \
3323                -wrap none \
3324                -height 40 \
3325                -width 1 \
3326                -font font_diff
3327        $w.out.loaded_t tag conf annotated -background grey
3328
3329        text $w.out.linenumber_t \
3330                -background white -borderwidth 0 \
3331                -state disabled \
3332                -wrap none \
3333                -height 40 \
3334                -width 5 \
3335                -font font_diff
3336        $w.out.linenumber_t tag conf linenumber -justify right
3337
3338        text $w.out.file_t \
3339                -background white -borderwidth 0 \
3340                -state disabled \
3341                -wrap none \
3342                -height 40 \
3343                -width 80 \
3344                -xscrollcommand [list $w.out.sbx set] \
3345                -font font_diff
3346
3347        scrollbar $w.out.sbx -orient h -command [list $w.out.file_t xview]
3348        scrollbar $w.out.sby -orient v \
3349                -command [list scrollbar2many [list \
3350                $w.out.loaded_t \
3351                $w.out.linenumber_t \
3352                $w.out.file_t \
3353                ] yview]
3354        grid \
3355                $w.out.linenumber_t \
3356                $w.out.loaded_t \
3357                $w.out.file_t \
3358                $w.out.sby \
3359                -sticky nsew
3360        grid conf $w.out.sbx -column 2 -sticky we
3361        grid columnconfigure $w.out 2 -weight 1
3362        grid rowconfigure $w.out 0 -weight 1
3363        pack $w.out -fill both -expand 1
3364
3365        label $w.status -textvariable blame_status($w) \
3366                -anchor w \
3367                -justify left \
3368                -borderwidth 1 \
3369                -relief sunken \
3370                -font font_ui
3371        pack $w.status -side bottom -fill x
3372
3373        frame $w.cm
3374        text $w.cm.t \
3375                -background white -borderwidth 0 \
3376                -state disabled \
3377                -wrap none \
3378                -height 10 \
3379                -width 80 \
3380                -xscrollcommand [list $w.cm.sbx set] \
3381                -yscrollcommand [list $w.cm.sby set] \
3382                -font font_diff
3383        scrollbar $w.cm.sbx -orient h -command [list $w.cm.t xview]
3384        scrollbar $w.cm.sby -orient v -command [list $w.cm.t yview]
3385        pack $w.cm.sby -side right -fill y
3386        pack $w.cm.sbx -side bottom -fill x
3387        pack $w.cm.t -expand 1 -fill both
3388        pack $w.cm -side bottom -fill x
3389
3390        menu $w.ctxm -tearoff 0
3391        $w.ctxm add command -label "Copy Commit" \
3392                -font font_ui \
3393                -command "blame_copycommit $w \$cursorW @\$cursorX,\$cursorY"
3394
3395        foreach i [list \
3396                $w.out.loaded_t \
3397                $w.out.linenumber_t \
3398                $w.out.file_t] {
3399                $i tag conf in_sel \
3400                        -background [$i cget -foreground] \
3401                        -foreground [$i cget -background]
3402                $i conf -yscrollcommand \
3403                        [list many2scrollbar [list \
3404                        $w.out.loaded_t \
3405                        $w.out.linenumber_t \
3406                        $w.out.file_t \
3407                        ] yview $w.out.sby]
3408                bind $i <Button-1> "
3409                        blame_click {$w} \\
3410                                $w.cm.t \\
3411                                $w.out.linenumber_t \\
3412                                $w.out.file_t \\
3413                                $i @%x,%y
3414                        focus $i
3415                "
3416                bind_button3 $i "
3417                        set cursorX %x
3418                        set cursorY %y
3419                        set cursorW %W
3420                        tk_popup $w.ctxm %X %Y
3421                "
3422        }
3423
3424        bind $w.cm.t <Button-1> "focus $w.cm.t"
3425        bind $tl <Visibility> "focus $tl"
3426        bind $tl <Destroy> "
3427                array unset blame_status {$w}
3428                array unset blame_data $w,*
3429        "
3430        wm title $tl "[appname] ([reponame]): File Viewer"
3431
3432        set blame_data($w,commit_count) 0
3433        set blame_data($w,commit_list) {}
3434        set blame_data($w,total_lines) 0
3435        set blame_data($w,blame_lines) 0
3436        set blame_data($w,highlight_commit) {}
3437        set blame_data($w,highlight_line) -1
3438
3439        set cmd [list git cat-file blob "$commit:$path"]
3440        set fd [open "| $cmd" r]
3441        fconfigure $fd -blocking 0 -translation lf -encoding binary
3442        fileevent $fd readable [list read_blame_catfile \
3443                $fd $w $commit $path \
3444                $w.cm.t $w.out.loaded_t $w.out.linenumber_t $w.out.file_t]
3445}
3446
3447proc read_blame_catfile {fd w commit path w_cmit w_load w_line w_file} {
3448        global blame_status blame_data
3449
3450        if {![winfo exists $w_file]} {
3451                catch {close $fd}
3452                return
3453        }
3454
3455        set n $blame_data($w,total_lines)
3456        $w_load conf -state normal
3457        $w_line conf -state normal
3458        $w_file conf -state normal
3459        while {[gets $fd line] >= 0} {
3460                regsub "\r\$" $line {} line
3461                incr n
3462                $w_load insert end "\n"
3463                $w_line insert end "$n\n" linenumber
3464                $w_file insert end "$line\n"
3465        }
3466        $w_load conf -state disabled
3467        $w_line conf -state disabled
3468        $w_file conf -state disabled
3469        set blame_data($w,total_lines) $n
3470
3471        if {[eof $fd]} {
3472                close $fd
3473                blame_incremental_status $w
3474                set cmd [list git blame -M -C --incremental]
3475                lappend cmd $commit -- $path
3476                set fd [open "| $cmd" r]
3477                fconfigure $fd -blocking 0 -translation lf -encoding binary
3478                fileevent $fd readable [list read_blame_incremental $fd $w \
3479                        $w_load $w_cmit $w_line $w_file]
3480        }
3481}
3482
3483proc read_blame_incremental {fd w w_load w_cmit w_line w_file} {
3484        global blame_status blame_data
3485
3486        if {![winfo exists $w_file]} {
3487                catch {close $fd}
3488                return
3489        }
3490
3491        while {[gets $fd line] >= 0} {
3492                if {[regexp {^([a-z0-9]{40}) (\d+) (\d+) (\d+)$} $line line \
3493                        cmit original_line final_line line_count]} {
3494                        set blame_data($w,commit) $cmit
3495                        set blame_data($w,original_line) $original_line
3496                        set blame_data($w,final_line) $final_line
3497                        set blame_data($w,line_count) $line_count
3498
3499                        if {[catch {set g $blame_data($w,$cmit,order)}]} {
3500                                $w_line tag conf g$cmit
3501                                $w_file tag conf g$cmit
3502                                $w_line tag raise in_sel
3503                                $w_file tag raise in_sel
3504                                $w_file tag raise sel
3505                                set blame_data($w,$cmit,order) $blame_data($w,commit_count)
3506                                incr blame_data($w,commit_count)
3507                                lappend blame_data($w,commit_list) $cmit
3508                        }
3509                } elseif {[string match {filename *} $line]} {
3510                        set file [string range $line 9 end]
3511                        set n $blame_data($w,line_count)
3512                        set lno $blame_data($w,final_line)
3513                        set cmit $blame_data($w,commit)
3514
3515                        while {$n > 0} {
3516                                if {[catch {set g g$blame_data($w,line$lno,commit)}]} {
3517                                        $w_load tag add annotated $lno.0 "$lno.0 lineend + 1c"
3518                                } else {
3519                                        $w_line tag remove g$g $lno.0 "$lno.0 lineend + 1c"
3520                                        $w_file tag remove g$g $lno.0 "$lno.0 lineend + 1c"
3521                                }
3522
3523                                set blame_data($w,line$lno,commit) $cmit
3524                                set blame_data($w,line$lno,file) $file
3525                                $w_line tag add g$cmit $lno.0 "$lno.0 lineend + 1c"
3526                                $w_file tag add g$cmit $lno.0 "$lno.0 lineend + 1c"
3527
3528                                if {$blame_data($w,highlight_line) == -1} {
3529                                        if {[lindex [$w_file yview] 0] == 0} {
3530                                                $w_file see $lno.0
3531                                                blame_showcommit $w $w_cmit $w_line $w_file $lno
3532                                        }
3533                                } elseif {$blame_data($w,highlight_line) == $lno} {
3534                                        blame_showcommit $w $w_cmit $w_line $w_file $lno
3535                                }
3536
3537                                incr n -1
3538                                incr lno
3539                                incr blame_data($w,blame_lines)
3540                        }
3541
3542                        set hc $blame_data($w,highlight_commit)
3543                        if {$hc ne {}
3544                                && [expr {$blame_data($w,$hc,order) + 1}]
3545                                        == $blame_data($w,$cmit,order)} {
3546                                blame_showcommit $w $w_cmit $w_line $w_file \
3547                                        $blame_data($w,highlight_line)
3548                        }
3549                } elseif {[regexp {^([a-z-]+) (.*)$} $line line header data]} {
3550                        set blame_data($w,$blame_data($w,commit),$header) $data
3551                }
3552        }
3553
3554        if {[eof $fd]} {
3555                close $fd
3556                set blame_status($w) {Annotation complete.}
3557        } else {
3558                blame_incremental_status $w
3559        }
3560}
3561
3562proc blame_incremental_status {w} {
3563        global blame_status blame_data
3564
3565        set blame_status($w) [format \
3566                "Loading annotations... %i of %i lines annotated (%2i%%)" \
3567                $blame_data($w,blame_lines) \
3568                $blame_data($w,total_lines) \
3569                [expr {100 * $blame_data($w,blame_lines)
3570                        / $blame_data($w,total_lines)}]]
3571}
3572
3573proc blame_click {w w_cmit w_line w_file cur_w pos} {
3574        set lno [lindex [split [$cur_w index $pos] .] 0]
3575        if {$lno eq {}} return
3576
3577        $w_line tag remove in_sel 0.0 end
3578        $w_file tag remove in_sel 0.0 end
3579        $w_line tag add in_sel $lno.0 "$lno.0 + 1 line"
3580        $w_file tag add in_sel $lno.0 "$lno.0 + 1 line"
3581
3582        blame_showcommit $w $w_cmit $w_line $w_file $lno
3583}
3584
3585set blame_colors {
3586        #ff4040
3587        #ff40ff
3588        #4040ff
3589}
3590
3591proc blame_showcommit {w w_cmit w_line w_file lno} {
3592        global blame_colors blame_data repo_config
3593
3594        set cmit $blame_data($w,highlight_commit)
3595        if {$cmit ne {}} {
3596                set idx $blame_data($w,$cmit,order)
3597                set i 0
3598                foreach c $blame_colors {
3599                        set h [lindex $blame_data($w,commit_list) [expr {$idx - 1 + $i}]]
3600                        $w_line tag conf g$h -background white
3601                        $w_file tag conf g$h -background white
3602                        incr i
3603                }
3604        }
3605
3606        $w_cmit conf -state normal
3607        $w_cmit delete 0.0 end
3608        if {[catch {set cmit $blame_data($w,line$lno,commit)}]} {
3609                set cmit {}
3610                $w_cmit insert end "Loading annotation..."
3611        } else {
3612                set idx $blame_data($w,$cmit,order)
3613                set i 0
3614                foreach c $blame_colors {
3615                        set h [lindex $blame_data($w,commit_list) [expr {$idx - 1 + $i}]]
3616                        $w_line tag conf g$h -background $c
3617                        $w_file tag conf g$h -background $c
3618                        incr i
3619                }
3620
3621                if {[catch {set msg $blame_data($w,$cmit,message)}]} {
3622                        set msg {}
3623                        catch {
3624                                set fd [open "| git cat-file commit $cmit" r]
3625                                fconfigure $fd -encoding binary -translation lf
3626                                if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
3627                                        set enc utf-8
3628                                }
3629                                while {[gets $fd line] > 0} {
3630                                        if {[string match {encoding *} $line]} {
3631                                                set enc [string tolower [string range $line 9 end]]
3632                                        }
3633                                }
3634                                fconfigure $fd -encoding $enc
3635                                set msg [string trim [read $fd]]
3636                                close $fd
3637                        }
3638                        set blame_data($w,$cmit,message) $msg
3639                }
3640
3641                set author_name {}
3642                set author_email {}
3643                set author_time {}
3644                catch {set author_name $blame_data($w,$cmit,author)}
3645                catch {set author_email $blame_data($w,$cmit,author-mail)}
3646                catch {set author_time [clock format $blame_data($w,$cmit,author-time)]}
3647
3648                set committer_name {}
3649                set committer_email {}
3650                set committer_time {}
3651                catch {set committer_name $blame_data($w,$cmit,committer)}
3652                catch {set committer_email $blame_data($w,$cmit,committer-mail)}
3653                catch {set committer_time [clock format $blame_data($w,$cmit,committer-time)]}
3654
3655                $w_cmit insert end "commit $cmit\n"
3656                $w_cmit insert end "Author: $author_name $author_email $author_time\n"
3657                $w_cmit insert end "Committer: $committer_name $committer_email $committer_time\n"
3658                $w_cmit insert end "Original File: [escape_path $blame_data($w,line$lno,file)]\n"
3659                $w_cmit insert end "\n"
3660                $w_cmit insert end $msg
3661        }
3662        $w_cmit conf -state disabled
3663
3664        set blame_data($w,highlight_line) $lno
3665        set blame_data($w,highlight_commit) $cmit
3666}
3667
3668proc blame_copycommit {w i pos} {
3669        global blame_data
3670        set lno [lindex [split [$i index $pos] .] 0]
3671        if {![catch {set commit $blame_data($w,line$lno,commit)}]} {
3672                clipboard clear
3673                clipboard append \
3674                        -format STRING \
3675                        -type STRING \
3676                        -- $commit
3677        }
3678}
3679
3680######################################################################
3681##
3682## icons
3683
3684set filemask {
3685#define mask_width 14
3686#define mask_height 15
3687static unsigned char mask_bits[] = {
3688   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
3689   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
3690   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
3691}
3692
3693image create bitmap file_plain -background white -foreground black -data {
3694#define plain_width 14
3695#define plain_height 15
3696static unsigned char plain_bits[] = {
3697   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
3698   0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
3699   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3700} -maskdata $filemask
3701
3702image create bitmap file_mod -background white -foreground blue -data {
3703#define mod_width 14
3704#define mod_height 15
3705static unsigned char mod_bits[] = {
3706   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
3707   0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
3708   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
3709} -maskdata $filemask
3710
3711image create bitmap file_fulltick -background white -foreground "#007000" -data {
3712#define file_fulltick_width 14
3713#define file_fulltick_height 15
3714static unsigned char file_fulltick_bits[] = {
3715   0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
3716   0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
3717   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3718} -maskdata $filemask
3719
3720image create bitmap file_parttick -background white -foreground "#005050" -data {
3721#define parttick_width 14
3722#define parttick_height 15
3723static unsigned char parttick_bits[] = {
3724   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
3725   0x7a, 0x14, 0x02, 0x16, 0x02, 0x13, 0x8a, 0x11, 0xda, 0x10, 0x72, 0x10,
3726   0x22, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3727} -maskdata $filemask
3728
3729image create bitmap file_question -background white -foreground black -data {
3730#define file_question_width 14
3731#define file_question_height 15
3732static unsigned char file_question_bits[] = {
3733   0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
3734   0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
3735   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3736} -maskdata $filemask
3737
3738image create bitmap file_removed -background white -foreground red -data {
3739#define file_removed_width 14
3740#define file_removed_height 15
3741static unsigned char file_removed_bits[] = {
3742   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
3743   0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
3744   0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
3745} -maskdata $filemask
3746
3747image create bitmap file_merge -background white -foreground blue -data {
3748#define file_merge_width 14
3749#define file_merge_height 15
3750static unsigned char file_merge_bits[] = {
3751   0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
3752   0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
3753   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
3754} -maskdata $filemask
3755
3756set file_dir_data {
3757#define file_width 18
3758#define file_height 18
3759static unsigned char file_bits[] = {
3760  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x03, 0x00,
3761  0x0c, 0x03, 0x00, 0x04, 0xfe, 0x00, 0x06, 0x80, 0x00, 0xff, 0x9f, 0x00,
3762  0x03, 0x98, 0x00, 0x02, 0x90, 0x00, 0x06, 0xb0, 0x00, 0x04, 0xa0, 0x00,
3763  0x0c, 0xe0, 0x00, 0x08, 0xc0, 0x00, 0xf8, 0xff, 0x00, 0x00, 0x00, 0x00,
3764  0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
3765}
3766image create bitmap file_dir -background white -foreground blue \
3767        -data $file_dir_data -maskdata $file_dir_data
3768unset file_dir_data
3769
3770set file_uplevel_data {
3771#define up_width 15
3772#define up_height 15
3773static unsigned char up_bits[] = {
3774  0x80, 0x00, 0xc0, 0x01, 0xe0, 0x03, 0xf0, 0x07, 0xf8, 0x0f, 0xfc, 0x1f,
3775  0xfe, 0x3f, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01,
3776  0xc0, 0x01, 0xc0, 0x01, 0x00, 0x00};
3777}
3778image create bitmap file_uplevel -background white -foreground red \
3779        -data $file_uplevel_data -maskdata $file_uplevel_data
3780unset file_uplevel_data
3781
3782set ui_index .vpane.files.index.list
3783set ui_workdir .vpane.files.workdir.list
3784
3785set all_icons(_$ui_index)   file_plain
3786set all_icons(A$ui_index)   file_fulltick
3787set all_icons(M$ui_index)   file_fulltick
3788set all_icons(D$ui_index)   file_removed
3789set all_icons(U$ui_index)   file_merge
3790
3791set all_icons(_$ui_workdir) file_plain
3792set all_icons(M$ui_workdir) file_mod
3793set all_icons(D$ui_workdir) file_question
3794set all_icons(U$ui_workdir) file_merge
3795set all_icons(O$ui_workdir) file_plain
3796
3797set max_status_desc 0
3798foreach i {
3799                {__ "Unmodified"}
3800
3801                {_M "Modified, not staged"}
3802                {M_ "Staged for commit"}
3803                {MM "Portions staged for commit"}
3804                {MD "Staged for commit, missing"}
3805
3806                {_O "Untracked, not staged"}
3807                {A_ "Staged for commit"}
3808                {AM "Portions staged for commit"}
3809                {AD "Staged for commit, missing"}
3810
3811                {_D "Missing"}
3812                {D_ "Staged for removal"}
3813                {DO "Staged for removal, still present"}
3814
3815                {U_ "Requires merge resolution"}
3816                {UU "Requires merge resolution"}
3817                {UM "Requires merge resolution"}
3818                {UD "Requires merge resolution"}
3819        } {
3820        if {$max_status_desc < [string length [lindex $i 1]]} {
3821                set max_status_desc [string length [lindex $i 1]]
3822        }
3823        set all_descs([lindex $i 0]) [lindex $i 1]
3824}
3825unset i
3826
3827######################################################################
3828##
3829## util
3830
3831proc bind_button3 {w cmd} {
3832        bind $w <Any-Button-3> $cmd
3833        if {[is_MacOSX]} {
3834                bind $w <Control-Button-1> $cmd
3835        }
3836}
3837
3838proc scrollbar2many {list mode args} {
3839        foreach w $list {eval $w $mode $args}
3840}
3841
3842proc many2scrollbar {list mode sb top bottom} {
3843        $sb set $top $bottom
3844        foreach w $list {$w $mode moveto $top}
3845}
3846
3847proc incr_font_size {font {amt 1}} {
3848        set sz [font configure $font -size]
3849        incr sz $amt
3850        font configure $font -size $sz
3851        font configure ${font}bold -size $sz
3852}
3853
3854proc hook_failed_popup {hook msg} {
3855        set w .hookfail
3856        toplevel $w
3857
3858        frame $w.m
3859        label $w.m.l1 -text "$hook hook failed:" \
3860                -anchor w \
3861                -justify left \
3862                -font font_uibold
3863        text $w.m.t \
3864                -background white -borderwidth 1 \
3865                -relief sunken \
3866                -width 80 -height 10 \
3867                -font font_diff \
3868                -yscrollcommand [list $w.m.sby set]
3869        label $w.m.l2 \
3870                -text {You must correct the above errors before committing.} \
3871                -anchor w \
3872                -justify left \
3873                -font font_uibold
3874        scrollbar $w.m.sby -command [list $w.m.t yview]
3875        pack $w.m.l1 -side top -fill x
3876        pack $w.m.l2 -side bottom -fill x
3877        pack $w.m.sby -side right -fill y
3878        pack $w.m.t -side left -fill both -expand 1
3879        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
3880
3881        $w.m.t insert 1.0 $msg
3882        $w.m.t conf -state disabled
3883
3884        button $w.ok -text OK \
3885                -width 15 \
3886                -font font_ui \
3887                -command "destroy $w"
3888        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
3889
3890        bind $w <Visibility> "grab $w; focus $w"
3891        bind $w <Key-Return> "destroy $w"
3892        wm title $w "[appname] ([reponame]): error"
3893        tkwait window $w
3894}
3895
3896set next_console_id 0
3897
3898proc new_console {short_title long_title} {
3899        global next_console_id console_data
3900        set w .console[incr next_console_id]
3901        set console_data($w) [list $short_title $long_title]
3902        return [console_init $w]
3903}
3904
3905proc console_init {w} {
3906        global console_cr console_data M1B
3907
3908        set console_cr($w) 1.0
3909        toplevel $w
3910        frame $w.m
3911        label $w.m.l1 -text "[lindex $console_data($w) 1]:" \
3912                -anchor w \
3913                -justify left \
3914                -font font_uibold
3915        text $w.m.t \
3916                -background white -borderwidth 1 \
3917                -relief sunken \
3918                -width 80 -height 10 \
3919                -font font_diff \
3920                -state disabled \
3921                -yscrollcommand [list $w.m.sby set]
3922        label $w.m.s -text {Working... please wait...} \
3923                -anchor w \
3924                -justify left \
3925                -font font_uibold
3926        scrollbar $w.m.sby -command [list $w.m.t yview]
3927        pack $w.m.l1 -side top -fill x
3928        pack $w.m.s -side bottom -fill x
3929        pack $w.m.sby -side right -fill y
3930        pack $w.m.t -side left -fill both -expand 1
3931        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
3932
3933        menu $w.ctxm -tearoff 0
3934        $w.ctxm add command -label "Copy" \
3935                -font font_ui \
3936                -command "tk_textCopy $w.m.t"
3937        $w.ctxm add command -label "Select All" \
3938                -font font_ui \
3939                -command "focus $w.m.t;$w.m.t tag add sel 0.0 end"
3940        $w.ctxm add command -label "Copy All" \
3941                -font font_ui \
3942                -command "
3943                        $w.m.t tag add sel 0.0 end
3944                        tk_textCopy $w.m.t
3945                        $w.m.t tag remove sel 0.0 end
3946                "
3947
3948        button $w.ok -text {Close} \
3949                -font font_ui \
3950                -state disabled \
3951                -command "destroy $w"
3952        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
3953
3954        bind_button3 $w.m.t "tk_popup $w.ctxm %X %Y"
3955        bind $w.m.t <$M1B-Key-a> "$w.m.t tag add sel 0.0 end;break"
3956        bind $w.m.t <$M1B-Key-A> "$w.m.t tag add sel 0.0 end;break"
3957        bind $w <Visibility> "focus $w"
3958        wm title $w "[appname] ([reponame]): [lindex $console_data($w) 0]"
3959        return $w
3960}
3961
3962proc console_exec {w cmd after} {
3963        # -- Cygwin's Tcl tosses the enviroment when we exec our child.
3964        #    But most users need that so we have to relogin. :-(
3965        #
3966        if {[is_Cygwin]} {
3967                set cmd [list sh --login -c "cd \"[pwd]\" && [join $cmd { }]"]
3968        }
3969
3970        # -- Tcl won't let us redirect both stdout and stderr to
3971        #    the same pipe.  So pass it through cat...
3972        #
3973        set cmd [concat | $cmd |& cat]
3974
3975        set fd_f [open $cmd r]
3976        fconfigure $fd_f -blocking 0 -translation binary
3977        fileevent $fd_f readable [list console_read $w $fd_f $after]
3978}
3979
3980proc console_read {w fd after} {
3981        global console_cr
3982
3983        set buf [read $fd]
3984        if {$buf ne {}} {
3985                if {![winfo exists $w]} {console_init $w}
3986                $w.m.t conf -state normal
3987                set c 0
3988                set n [string length $buf]
3989                while {$c < $n} {
3990                        set cr [string first "\r" $buf $c]
3991                        set lf [string first "\n" $buf $c]
3992                        if {$cr < 0} {set cr [expr {$n + 1}]}
3993                        if {$lf < 0} {set lf [expr {$n + 1}]}
3994
3995                        if {$lf < $cr} {
3996                                $w.m.t insert end [string range $buf $c $lf]
3997                                set console_cr($w) [$w.m.t index {end -1c}]
3998                                set c $lf
3999                                incr c
4000                        } else {
4001                                $w.m.t delete $console_cr($w) end
4002                                $w.m.t insert end "\n"
4003                                $w.m.t insert end [string range $buf $c $cr]
4004                                set c $cr
4005                                incr c
4006                        }
4007                }
4008                $w.m.t conf -state disabled
4009                $w.m.t see end
4010        }
4011
4012        fconfigure $fd -blocking 1
4013        if {[eof $fd]} {
4014                if {[catch {close $fd}]} {
4015                        set ok 0
4016                } else {
4017                        set ok 1
4018                }
4019                uplevel #0 $after $w $ok
4020                return
4021        }
4022        fconfigure $fd -blocking 0
4023}
4024
4025proc console_chain {cmdlist w {ok 1}} {
4026        if {$ok} {
4027                if {[llength $cmdlist] == 0} {
4028                        console_done $w $ok
4029                        return
4030                }
4031
4032                set cmd [lindex $cmdlist 0]
4033                set cmdlist [lrange $cmdlist 1 end]
4034
4035                if {[lindex $cmd 0] eq {console_exec}} {
4036                        console_exec $w \
4037                                [lindex $cmd 1] \
4038                                [list console_chain $cmdlist]
4039                } else {
4040                        uplevel #0 $cmd $cmdlist $w $ok
4041                }
4042        } else {
4043                console_done $w $ok
4044        }
4045}
4046
4047proc console_done {args} {
4048        global console_cr console_data
4049
4050        switch -- [llength $args] {
4051        2 {
4052                set w [lindex $args 0]
4053                set ok [lindex $args 1]
4054        }
4055        3 {
4056                set w [lindex $args 1]
4057                set ok [lindex $args 2]
4058        }
4059        default {
4060                error "wrong number of args: console_done ?ignored? w ok"
4061        }
4062        }
4063
4064        if {$ok} {
4065                if {[winfo exists $w]} {
4066                        $w.m.s conf -background green -text {Success}
4067                        $w.ok conf -state normal
4068                }
4069        } else {
4070                if {![winfo exists $w]} {
4071                        console_init $w
4072                }
4073                $w.m.s conf -background red -text {Error: Command Failed}
4074                $w.ok conf -state normal
4075        }
4076
4077        array unset console_cr $w
4078        array unset console_data $w
4079}
4080
4081######################################################################
4082##
4083## ui commands
4084
4085set starting_gitk_msg {Starting gitk... please wait...}
4086
4087proc do_gitk {revs} {
4088        global env ui_status_value starting_gitk_msg
4089
4090        # -- Always start gitk through whatever we were loaded with.  This
4091        #    lets us bypass using shell process on Windows systems.
4092        #
4093        set cmd [info nameofexecutable]
4094        lappend cmd [gitexec gitk]
4095        if {$revs ne {}} {
4096                append cmd { }
4097                append cmd $revs
4098        }
4099
4100        if {[catch {eval exec $cmd &} err]} {
4101                error_popup "Failed to start gitk:\n\n$err"
4102        } else {
4103                set ui_status_value $starting_gitk_msg
4104                after 10000 {
4105                        if {$ui_status_value eq $starting_gitk_msg} {
4106                                set ui_status_value {Ready.}
4107                        }
4108                }
4109        }
4110}
4111
4112proc do_stats {} {
4113        set fd [open "| git count-objects -v" r]
4114        while {[gets $fd line] > 0} {
4115                if {[regexp {^([^:]+): (\d+)$} $line _ name value]} {
4116                        set stats($name) $value
4117                }
4118        }
4119        close $fd
4120
4121        set packed_sz 0
4122        foreach p [glob -directory [gitdir objects pack] \
4123                -type f \
4124                -nocomplain -- *] {
4125                incr packed_sz [file size $p]
4126        }
4127        if {$packed_sz > 0} {
4128                set stats(size-pack) [expr {$packed_sz / 1024}]
4129        }
4130
4131        set w .stats_view
4132        toplevel $w
4133        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4134
4135        label $w.header -text {Database Statistics} \
4136                -font font_uibold
4137        pack $w.header -side top -fill x
4138
4139        frame $w.buttons -border 1
4140        button $w.buttons.close -text Close \
4141                -font font_ui \
4142                -command [list destroy $w]
4143        button $w.buttons.gc -text {Compress Database} \
4144                -font font_ui \
4145                -command "destroy $w;do_gc"
4146        pack $w.buttons.close -side right
4147        pack $w.buttons.gc -side left
4148        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4149
4150        frame $w.stat -borderwidth 1 -relief solid
4151        foreach s {
4152                {count           {Number of loose objects}}
4153                {size            {Disk space used by loose objects} { KiB}}
4154                {in-pack         {Number of packed objects}}
4155                {packs           {Number of packs}}
4156                {size-pack       {Disk space used by packed objects} { KiB}}
4157                {prune-packable  {Packed objects waiting for pruning}}
4158                {garbage         {Garbage files}}
4159                } {
4160                set name [lindex $s 0]
4161                set label [lindex $s 1]
4162                if {[catch {set value $stats($name)}]} continue
4163                if {[llength $s] > 2} {
4164                        set value "$value[lindex $s 2]"
4165                }
4166
4167                label $w.stat.l_$name -text "$label:" -anchor w -font font_ui
4168                label $w.stat.v_$name -text $value -anchor w -font font_ui
4169                grid $w.stat.l_$name $w.stat.v_$name -sticky we -padx {0 5}
4170        }
4171        pack $w.stat -pady 10 -padx 10
4172
4173        bind $w <Visibility> "grab $w; focus $w"
4174        bind $w <Key-Escape> [list destroy $w]
4175        bind $w <Key-Return> [list destroy $w]
4176        wm title $w "[appname] ([reponame]): Database Statistics"
4177        tkwait window $w
4178}
4179
4180proc do_gc {} {
4181        set w [new_console {gc} {Compressing the object database}]
4182        console_chain {
4183                {console_exec {git pack-refs --prune}}
4184                {console_exec {git reflog expire --all}}
4185                {console_exec {git repack -a -d -l}}
4186                {console_exec {git rerere gc}}
4187        } $w
4188}
4189
4190proc do_fsck_objects {} {
4191        set w [new_console {fsck-objects} \
4192                {Verifying the object database with fsck-objects}]
4193        set cmd [list git fsck-objects]
4194        lappend cmd --full
4195        lappend cmd --cache
4196        lappend cmd --strict
4197        console_exec $w $cmd console_done
4198}
4199
4200set is_quitting 0
4201
4202proc do_quit {} {
4203        global ui_comm is_quitting repo_config commit_type
4204
4205        if {$is_quitting} return
4206        set is_quitting 1
4207
4208        if {[winfo exists $ui_comm]} {
4209                # -- Stash our current commit buffer.
4210                #
4211                set save [gitdir GITGUI_MSG]
4212                set msg [string trim [$ui_comm get 0.0 end]]
4213                regsub -all -line {[ \r\t]+$} $msg {} msg
4214                if {(![string match amend* $commit_type]
4215                        || [$ui_comm edit modified])
4216                        && $msg ne {}} {
4217                        catch {
4218                                set fd [open $save w]
4219                                puts -nonewline $fd $msg
4220                                close $fd
4221                        }
4222                } else {
4223                        catch {file delete $save}
4224                }
4225
4226                # -- Stash our current window geometry into this repository.
4227                #
4228                set cfg_geometry [list]
4229                lappend cfg_geometry [wm geometry .]
4230                lappend cfg_geometry [lindex [.vpane sash coord 0] 1]
4231                lappend cfg_geometry [lindex [.vpane.files sash coord 0] 0]
4232                if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
4233                        set rc_geometry {}
4234                }
4235                if {$cfg_geometry ne $rc_geometry} {
4236                        catch {git config gui.geometry $cfg_geometry}
4237                }
4238        }
4239
4240        destroy .
4241}
4242
4243proc do_rescan {} {
4244        rescan {set ui_status_value {Ready.}}
4245}
4246
4247proc unstage_helper {txt paths} {
4248        global file_states current_diff_path
4249
4250        if {![lock_index begin-update]} return
4251
4252        set pathList [list]
4253        set after {}
4254        foreach path $paths {
4255                switch -glob -- [lindex $file_states($path) 0] {
4256                A? -
4257                M? -
4258                D? {
4259                        lappend pathList $path
4260                        if {$path eq $current_diff_path} {
4261                                set after {reshow_diff;}
4262                        }
4263                }
4264                }
4265        }
4266        if {$pathList eq {}} {
4267                unlock_index
4268        } else {
4269                update_indexinfo \
4270                        $txt \
4271                        $pathList \
4272                        [concat $after {set ui_status_value {Ready.}}]
4273        }
4274}
4275
4276proc do_unstage_selection {} {
4277        global current_diff_path selected_paths
4278
4279        if {[array size selected_paths] > 0} {
4280                unstage_helper \
4281                        {Unstaging selected files from commit} \
4282                        [array names selected_paths]
4283        } elseif {$current_diff_path ne {}} {
4284                unstage_helper \
4285                        "Unstaging [short_path $current_diff_path] from commit" \
4286                        [list $current_diff_path]
4287        }
4288}
4289
4290proc add_helper {txt paths} {
4291        global file_states current_diff_path
4292
4293        if {![lock_index begin-update]} return
4294
4295        set pathList [list]
4296        set after {}
4297        foreach path $paths {
4298                switch -glob -- [lindex $file_states($path) 0] {
4299                _O -
4300                ?M -
4301                ?D -
4302                U? {
4303                        lappend pathList $path
4304                        if {$path eq $current_diff_path} {
4305                                set after {reshow_diff;}
4306                        }
4307                }
4308                }
4309        }
4310        if {$pathList eq {}} {
4311                unlock_index
4312        } else {
4313                update_index \
4314                        $txt \
4315                        $pathList \
4316                        [concat $after {set ui_status_value {Ready to commit.}}]
4317        }
4318}
4319
4320proc do_add_selection {} {
4321        global current_diff_path selected_paths
4322
4323        if {[array size selected_paths] > 0} {
4324                add_helper \
4325                        {Adding selected files} \
4326                        [array names selected_paths]
4327        } elseif {$current_diff_path ne {}} {
4328                add_helper \
4329                        "Adding [short_path $current_diff_path]" \
4330                        [list $current_diff_path]
4331        }
4332}
4333
4334proc do_add_all {} {
4335        global file_states
4336
4337        set paths [list]
4338        foreach path [array names file_states] {
4339                switch -glob -- [lindex $file_states($path) 0] {
4340                U? {continue}
4341                ?M -
4342                ?D {lappend paths $path}
4343                }
4344        }
4345        add_helper {Adding all changed files} $paths
4346}
4347
4348proc revert_helper {txt paths} {
4349        global file_states current_diff_path
4350
4351        if {![lock_index begin-update]} return
4352
4353        set pathList [list]
4354        set after {}
4355        foreach path $paths {
4356                switch -glob -- [lindex $file_states($path) 0] {
4357                U? {continue}
4358                ?M -
4359                ?D {
4360                        lappend pathList $path
4361                        if {$path eq $current_diff_path} {
4362                                set after {reshow_diff;}
4363                        }
4364                }
4365                }
4366        }
4367
4368        set n [llength $pathList]
4369        if {$n == 0} {
4370                unlock_index
4371                return
4372        } elseif {$n == 1} {
4373                set s "[short_path [lindex $pathList]]"
4374        } else {
4375                set s "these $n files"
4376        }
4377
4378        set reply [tk_dialog \
4379                .confirm_revert \
4380                "[appname] ([reponame])" \
4381                "Revert changes in $s?
4382
4383Any unadded changes will be permanently lost by the revert." \
4384                question \
4385                1 \
4386                {Do Nothing} \
4387                {Revert Changes} \
4388                ]
4389        if {$reply == 1} {
4390                checkout_index \
4391                        $txt \
4392                        $pathList \
4393                        [concat $after {set ui_status_value {Ready.}}]
4394        } else {
4395                unlock_index
4396        }
4397}
4398
4399proc do_revert_selection {} {
4400        global current_diff_path selected_paths
4401
4402        if {[array size selected_paths] > 0} {
4403                revert_helper \
4404                        {Reverting selected files} \
4405                        [array names selected_paths]
4406        } elseif {$current_diff_path ne {}} {
4407                revert_helper \
4408                        "Reverting [short_path $current_diff_path]" \
4409                        [list $current_diff_path]
4410        }
4411}
4412
4413proc do_signoff {} {
4414        global ui_comm
4415
4416        set me [committer_ident]
4417        if {$me eq {}} return
4418
4419        set sob "Signed-off-by: $me"
4420        set last [$ui_comm get {end -1c linestart} {end -1c}]
4421        if {$last ne $sob} {
4422                $ui_comm edit separator
4423                if {$last ne {}
4424                        && ![regexp {^[A-Z][A-Za-z]*-[A-Za-z-]+: *} $last]} {
4425                        $ui_comm insert end "\n"
4426                }
4427                $ui_comm insert end "\n$sob"
4428                $ui_comm edit separator
4429                $ui_comm see end
4430        }
4431}
4432
4433proc do_select_commit_type {} {
4434        global commit_type selected_commit_type
4435
4436        if {$selected_commit_type eq {new}
4437                && [string match amend* $commit_type]} {
4438                create_new_commit
4439        } elseif {$selected_commit_type eq {amend}
4440                && ![string match amend* $commit_type]} {
4441                load_last_commit
4442
4443                # The amend request was rejected...
4444                #
4445                if {![string match amend* $commit_type]} {
4446                        set selected_commit_type new
4447                }
4448        }
4449}
4450
4451proc do_commit {} {
4452        commit_tree
4453}
4454
4455proc do_about {} {
4456        global appvers copyright
4457        global tcl_patchLevel tk_patchLevel
4458
4459        set w .about_dialog
4460        toplevel $w
4461        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4462
4463        label $w.header -text "About [appname]" \
4464                -font font_uibold
4465        pack $w.header -side top -fill x
4466
4467        frame $w.buttons
4468        button $w.buttons.close -text {Close} \
4469                -font font_ui \
4470                -command [list destroy $w]
4471        pack $w.buttons.close -side right
4472        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4473
4474        label $w.desc \
4475                -text "git-gui - a commit creation tool for Git.
4476$copyright" \
4477                -padx 5 -pady 5 \
4478                -justify left \
4479                -anchor w \
4480                -borderwidth 1 \
4481                -relief solid \
4482                -font font_ui
4483        pack $w.desc -side top -fill x -padx 5 -pady 5
4484
4485        set v {}
4486        append v "git-gui version $appvers\n"
4487        append v "[git version]\n"
4488        append v "\n"
4489        if {$tcl_patchLevel eq $tk_patchLevel} {
4490                append v "Tcl/Tk version $tcl_patchLevel"
4491        } else {
4492                append v "Tcl version $tcl_patchLevel"
4493                append v ", Tk version $tk_patchLevel"
4494        }
4495
4496        label $w.vers \
4497                -text $v \
4498                -padx 5 -pady 5 \
4499                -justify left \
4500                -anchor w \
4501                -borderwidth 1 \
4502                -relief solid \
4503                -font font_ui
4504        pack $w.vers -side top -fill x -padx 5 -pady 5
4505
4506        menu $w.ctxm -tearoff 0
4507        $w.ctxm add command \
4508                -label {Copy} \
4509                -font font_ui \
4510                -command "
4511                clipboard clear
4512                clipboard append -format STRING -type STRING -- \[$w.vers cget -text\]
4513        "
4514
4515        bind $w <Visibility> "grab $w; focus $w"
4516        bind $w <Key-Escape> "destroy $w"
4517        bind_button3 $w.vers "tk_popup $w.ctxm %X %Y; grab $w; focus $w"
4518        wm title $w "About [appname]"
4519        tkwait window $w
4520}
4521
4522proc do_options {} {
4523        global repo_config global_config font_descs
4524        global repo_config_new global_config_new
4525
4526        array unset repo_config_new
4527        array unset global_config_new
4528        foreach name [array names repo_config] {
4529                set repo_config_new($name) $repo_config($name)
4530        }
4531        load_config 1
4532        foreach name [array names repo_config] {
4533                switch -- $name {
4534                gui.diffcontext {continue}
4535                }
4536                set repo_config_new($name) $repo_config($name)
4537        }
4538        foreach name [array names global_config] {
4539                set global_config_new($name) $global_config($name)
4540        }
4541
4542        set w .options_editor
4543        toplevel $w
4544        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4545
4546        label $w.header -text "Options" \
4547                -font font_uibold
4548        pack $w.header -side top -fill x
4549
4550        frame $w.buttons
4551        button $w.buttons.restore -text {Restore Defaults} \
4552                -font font_ui \
4553                -command do_restore_defaults
4554        pack $w.buttons.restore -side left
4555        button $w.buttons.save -text Save \
4556                -font font_ui \
4557                -command [list do_save_config $w]
4558        pack $w.buttons.save -side right
4559        button $w.buttons.cancel -text {Cancel} \
4560                -font font_ui \
4561                -command [list destroy $w]
4562        pack $w.buttons.cancel -side right -padx 5
4563        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4564
4565        labelframe $w.repo -text "[reponame] Repository" \
4566                -font font_ui
4567        labelframe $w.global -text {Global (All Repositories)} \
4568                -font font_ui
4569        pack $w.repo -side left -fill both -expand 1 -pady 5 -padx 5
4570        pack $w.global -side right -fill both -expand 1 -pady 5 -padx 5
4571
4572        set optid 0
4573        foreach option {
4574                {t user.name {User Name}}
4575                {t user.email {Email Address}}
4576
4577                {b merge.summary {Summarize Merge Commits}}
4578                {i-1..5 merge.verbosity {Merge Verbosity}}
4579
4580                {b gui.trustmtime  {Trust File Modification Timestamps}}
4581                {i-1..99 gui.diffcontext {Number of Diff Context Lines}}
4582                {t gui.newbranchtemplate {New Branch Name Template}}
4583                } {
4584                set type [lindex $option 0]
4585                set name [lindex $option 1]
4586                set text [lindex $option 2]
4587                incr optid
4588                foreach f {repo global} {
4589                        switch -glob -- $type {
4590                        b {
4591                                checkbutton $w.$f.$optid -text $text \
4592                                        -variable ${f}_config_new($name) \
4593                                        -onvalue true \
4594                                        -offvalue false \
4595                                        -font font_ui
4596                                pack $w.$f.$optid -side top -anchor w
4597                        }
4598                        i-* {
4599                                regexp -- {-(\d+)\.\.(\d+)$} $type _junk min max
4600                                frame $w.$f.$optid
4601                                label $w.$f.$optid.l -text "$text:" -font font_ui
4602                                pack $w.$f.$optid.l -side left -anchor w -fill x
4603                                spinbox $w.$f.$optid.v \
4604                                        -textvariable ${f}_config_new($name) \
4605                                        -from $min \
4606                                        -to $max \
4607                                        -increment 1 \
4608                                        -width [expr {1 + [string length $max]}] \
4609                                        -font font_ui
4610                                bind $w.$f.$optid.v <FocusIn> {%W selection range 0 end}
4611                                pack $w.$f.$optid.v -side right -anchor e -padx 5
4612                                pack $w.$f.$optid -side top -anchor w -fill x
4613                        }
4614                        t {
4615                                frame $w.$f.$optid
4616                                label $w.$f.$optid.l -text "$text:" -font font_ui
4617                                entry $w.$f.$optid.v \
4618                                        -borderwidth 1 \
4619                                        -relief sunken \
4620                                        -width 20 \
4621                                        -textvariable ${f}_config_new($name) \
4622                                        -font font_ui
4623                                pack $w.$f.$optid.l -side left -anchor w
4624                                pack $w.$f.$optid.v -side left -anchor w \
4625                                        -fill x -expand 1 \
4626                                        -padx 5
4627                                pack $w.$f.$optid -side top -anchor w -fill x
4628                        }
4629                        }
4630                }
4631        }
4632
4633        set all_fonts [lsort [font families]]
4634        foreach option $font_descs {
4635                set name [lindex $option 0]
4636                set font [lindex $option 1]
4637                set text [lindex $option 2]
4638
4639                set global_config_new(gui.$font^^family) \
4640                        [font configure $font -family]
4641                set global_config_new(gui.$font^^size) \
4642                        [font configure $font -size]
4643
4644                frame $w.global.$name
4645                label $w.global.$name.l -text "$text:" -font font_ui
4646                pack $w.global.$name.l -side left -anchor w -fill x
4647                eval tk_optionMenu $w.global.$name.family \
4648                        global_config_new(gui.$font^^family) \
4649                        $all_fonts
4650                spinbox $w.global.$name.size \
4651                        -textvariable global_config_new(gui.$font^^size) \
4652                        -from 2 -to 80 -increment 1 \
4653                        -width 3 \
4654                        -font font_ui
4655                bind $w.global.$name.size <FocusIn> {%W selection range 0 end}
4656                pack $w.global.$name.size -side right -anchor e
4657                pack $w.global.$name.family -side right -anchor e
4658                pack $w.global.$name -side top -anchor w -fill x
4659        }
4660
4661        bind $w <Visibility> "grab $w; focus $w"
4662        bind $w <Key-Escape> "destroy $w"
4663        wm title $w "[appname] ([reponame]): Options"
4664        tkwait window $w
4665}
4666
4667proc do_restore_defaults {} {
4668        global font_descs default_config repo_config
4669        global repo_config_new global_config_new
4670
4671        foreach name [array names default_config] {
4672                set repo_config_new($name) $default_config($name)
4673                set global_config_new($name) $default_config($name)
4674        }
4675
4676        foreach option $font_descs {
4677                set name [lindex $option 0]
4678                set repo_config(gui.$name) $default_config(gui.$name)
4679        }
4680        apply_config
4681
4682        foreach option $font_descs {
4683                set name [lindex $option 0]
4684                set font [lindex $option 1]
4685                set global_config_new(gui.$font^^family) \
4686                        [font configure $font -family]
4687                set global_config_new(gui.$font^^size) \
4688                        [font configure $font -size]
4689        }
4690}
4691
4692proc do_save_config {w} {
4693        if {[catch {save_config} err]} {
4694                error_popup "Failed to completely save options:\n\n$err"
4695        }
4696        reshow_diff
4697        destroy $w
4698}
4699
4700proc do_windows_shortcut {} {
4701        global argv0
4702
4703        set fn [tk_getSaveFile \
4704                -parent . \
4705                -title "[appname] ([reponame]): Create Desktop Icon" \
4706                -initialfile "Git [reponame].bat"]
4707        if {$fn != {}} {
4708                if {[catch {
4709                                set fd [open $fn w]
4710                                puts $fd "@ECHO Entering [reponame]"
4711                                puts $fd "@ECHO Starting git-gui... please wait..."
4712                                puts $fd "@SET PATH=[file normalize [gitexec]];%PATH%"
4713                                puts $fd "@SET GIT_DIR=[file normalize [gitdir]]"
4714                                puts -nonewline $fd "@\"[info nameofexecutable]\""
4715                                puts $fd " \"[file normalize $argv0]\""
4716                                close $fd
4717                        } err]} {
4718                        error_popup "Cannot write script:\n\n$err"
4719                }
4720        }
4721}
4722
4723proc do_cygwin_shortcut {} {
4724        global argv0
4725
4726        if {[catch {
4727                set desktop [exec cygpath \
4728                        --windows \
4729                        --absolute \
4730                        --long-name \
4731                        --desktop]
4732                }]} {
4733                        set desktop .
4734        }
4735        set fn [tk_getSaveFile \
4736                -parent . \
4737                -title "[appname] ([reponame]): Create Desktop Icon" \
4738                -initialdir $desktop \
4739                -initialfile "Git [reponame].bat"]
4740        if {$fn != {}} {
4741                if {[catch {
4742                                set fd [open $fn w]
4743                                set sh [exec cygpath \
4744                                        --windows \
4745                                        --absolute \
4746                                        /bin/sh]
4747                                set me [exec cygpath \
4748                                        --unix \
4749                                        --absolute \
4750                                        $argv0]
4751                                set gd [exec cygpath \
4752                                        --unix \
4753                                        --absolute \
4754                                        [gitdir]]
4755                                set gw [exec cygpath \
4756                                        --windows \
4757                                        --absolute \
4758                                        [file dirname [gitdir]]]
4759                                regsub -all ' $me "'\\''" me
4760                                regsub -all ' $gd "'\\''" gd
4761                                puts $fd "@ECHO Entering $gw"
4762                                puts $fd "@ECHO Starting git-gui... please wait..."
4763                                puts -nonewline $fd "@\"$sh\" --login -c \""
4764                                puts -nonewline $fd "GIT_DIR='$gd'"
4765                                puts -nonewline $fd " '$me'"
4766                                puts $fd "&\""
4767                                close $fd
4768                        } err]} {
4769                        error_popup "Cannot write script:\n\n$err"
4770                }
4771        }
4772}
4773
4774proc do_macosx_app {} {
4775        global argv0 env
4776
4777        set fn [tk_getSaveFile \
4778                -parent . \
4779                -title "[appname] ([reponame]): Create Desktop Icon" \
4780                -initialdir [file join $env(HOME) Desktop] \
4781                -initialfile "Git [reponame].app"]
4782        if {$fn != {}} {
4783                if {[catch {
4784                                set Contents [file join $fn Contents]
4785                                set MacOS [file join $Contents MacOS]
4786                                set exe [file join $MacOS git-gui]
4787
4788                                file mkdir $MacOS
4789
4790                                set fd [open [file join $Contents Info.plist] w]
4791                                puts $fd {<?xml version="1.0" encoding="UTF-8"?>
4792<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4793<plist version="1.0">
4794<dict>
4795        <key>CFBundleDevelopmentRegion</key>
4796        <string>English</string>
4797        <key>CFBundleExecutable</key>
4798        <string>git-gui</string>
4799        <key>CFBundleIdentifier</key>
4800        <string>org.spearce.git-gui</string>
4801        <key>CFBundleInfoDictionaryVersion</key>
4802        <string>6.0</string>
4803        <key>CFBundlePackageType</key>
4804        <string>APPL</string>
4805        <key>CFBundleSignature</key>
4806        <string>????</string>
4807        <key>CFBundleVersion</key>
4808        <string>1.0</string>
4809        <key>NSPrincipalClass</key>
4810        <string>NSApplication</string>
4811</dict>
4812</plist>}
4813                                close $fd
4814
4815                                set fd [open $exe w]
4816                                set gd [file normalize [gitdir]]
4817                                set ep [file normalize [gitexec]]
4818                                regsub -all ' $gd "'\\''" gd
4819                                regsub -all ' $ep "'\\''" ep
4820                                puts $fd "#!/bin/sh"
4821                                foreach name [array names env] {
4822                                        if {[string match GIT_* $name]} {
4823                                                regsub -all ' $env($name) "'\\''" v
4824                                                puts $fd "export $name='$v'"
4825                                        }
4826                                }
4827                                puts $fd "export PATH='$ep':\$PATH"
4828                                puts $fd "export GIT_DIR='$gd'"
4829                                puts $fd "exec [file normalize $argv0]"
4830                                close $fd
4831
4832                                file attributes $exe -permissions u+x,g+x,o+x
4833                        } err]} {
4834                        error_popup "Cannot write icon:\n\n$err"
4835                }
4836        }
4837}
4838
4839proc toggle_or_diff {w x y} {
4840        global file_states file_lists current_diff_path ui_index ui_workdir
4841        global last_clicked selected_paths
4842
4843        set pos [split [$w index @$x,$y] .]
4844        set lno [lindex $pos 0]
4845        set col [lindex $pos 1]
4846        set path [lindex $file_lists($w) [expr {$lno - 1}]]
4847        if {$path eq {}} {
4848                set last_clicked {}
4849                return
4850        }
4851
4852        set last_clicked [list $w $lno]
4853        array unset selected_paths
4854        $ui_index tag remove in_sel 0.0 end
4855        $ui_workdir tag remove in_sel 0.0 end
4856
4857        if {$col == 0} {
4858                if {$current_diff_path eq $path} {
4859                        set after {reshow_diff;}
4860                } else {
4861                        set after {}
4862                }
4863                if {$w eq $ui_index} {
4864                        update_indexinfo \
4865                                "Unstaging [short_path $path] from commit" \
4866                                [list $path] \
4867                                [concat $after {set ui_status_value {Ready.}}]
4868                } elseif {$w eq $ui_workdir} {
4869                        update_index \
4870                                "Adding [short_path $path]" \
4871                                [list $path] \
4872                                [concat $after {set ui_status_value {Ready.}}]
4873                }
4874        } else {
4875                show_diff $path $w $lno
4876        }
4877}
4878
4879proc add_one_to_selection {w x y} {
4880        global file_lists last_clicked selected_paths
4881
4882        set lno [lindex [split [$w index @$x,$y] .] 0]
4883        set path [lindex $file_lists($w) [expr {$lno - 1}]]
4884        if {$path eq {}} {
4885                set last_clicked {}
4886                return
4887        }
4888
4889        if {$last_clicked ne {}
4890                && [lindex $last_clicked 0] ne $w} {
4891                array unset selected_paths
4892                [lindex $last_clicked 0] tag remove in_sel 0.0 end
4893        }
4894
4895        set last_clicked [list $w $lno]
4896        if {[catch {set in_sel $selected_paths($path)}]} {
4897                set in_sel 0
4898        }
4899        if {$in_sel} {
4900                unset selected_paths($path)
4901                $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
4902        } else {
4903                set selected_paths($path) 1
4904                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
4905        }
4906}
4907
4908proc add_range_to_selection {w x y} {
4909        global file_lists last_clicked selected_paths
4910
4911        if {[lindex $last_clicked 0] ne $w} {
4912                toggle_or_diff $w $x $y
4913                return
4914        }
4915
4916        set lno [lindex [split [$w index @$x,$y] .] 0]
4917        set lc [lindex $last_clicked 1]
4918        if {$lc < $lno} {
4919                set begin $lc
4920                set end $lno
4921        } else {
4922                set begin $lno
4923                set end $lc
4924        }
4925
4926        foreach path [lrange $file_lists($w) \
4927                [expr {$begin - 1}] \
4928                [expr {$end - 1}]] {
4929                set selected_paths($path) 1
4930        }
4931        $w tag add in_sel $begin.0 [expr {$end + 1}].0
4932}
4933
4934######################################################################
4935##
4936## config defaults
4937
4938set cursor_ptr arrow
4939font create font_diff -family Courier -size 10
4940font create font_ui
4941catch {
4942        label .dummy
4943        eval font configure font_ui [font actual [.dummy cget -font]]
4944        destroy .dummy
4945}
4946
4947font create font_uibold
4948font create font_diffbold
4949
4950if {[is_Windows]} {
4951        set M1B Control
4952        set M1T Ctrl
4953} elseif {[is_MacOSX]} {
4954        set M1B M1
4955        set M1T Cmd
4956} else {
4957        set M1B M1
4958        set M1T M1
4959}
4960
4961proc apply_config {} {
4962        global repo_config font_descs
4963
4964        foreach option $font_descs {
4965                set name [lindex $option 0]
4966                set font [lindex $option 1]
4967                if {[catch {
4968                        foreach {cn cv} $repo_config(gui.$name) {
4969                                font configure $font $cn $cv
4970                        }
4971                        } err]} {
4972                        error_popup "Invalid font specified in gui.$name:\n\n$err"
4973                }
4974                foreach {cn cv} [font configure $font] {
4975                        font configure ${font}bold $cn $cv
4976                }
4977                font configure ${font}bold -weight bold
4978        }
4979}
4980
4981set default_config(merge.summary) false
4982set default_config(merge.verbosity) 2
4983set default_config(user.name) {}
4984set default_config(user.email) {}
4985
4986set default_config(gui.trustmtime) false
4987set default_config(gui.diffcontext) 5
4988set default_config(gui.newbranchtemplate) {}
4989set default_config(gui.fontui) [font configure font_ui]
4990set default_config(gui.fontdiff) [font configure font_diff]
4991set font_descs {
4992        {fontui   font_ui   {Main Font}}
4993        {fontdiff font_diff {Diff/Console Font}}
4994}
4995load_config 0
4996apply_config
4997
4998######################################################################
4999##
5000## feature option selection
5001
5002if {[regexp {^git-(.+)$} [appname] _junk subcommand]} {
5003        unset _junk
5004} else {
5005        set subcommand gui
5006}
5007if {$subcommand eq {gui.sh}} {
5008        set subcommand gui
5009}
5010if {$subcommand eq {gui} && [llength $argv] > 0} {
5011        set subcommand [lindex $argv 0]
5012        set argv [lrange $argv 1 end]
5013}
5014
5015enable_option multicommit
5016enable_option branch
5017enable_option transport
5018
5019switch -- $subcommand {
5020--version -
5021version -
5022blame {
5023        disable_option multicommit
5024        disable_option branch
5025        disable_option transport
5026}
5027citool {
5028        enable_option singlecommit
5029
5030        disable_option multicommit
5031        disable_option branch
5032        disable_option transport
5033}
5034}
5035
5036######################################################################
5037##
5038## ui construction
5039
5040set ui_comm {}
5041
5042# -- Menu Bar
5043#
5044menu .mbar -tearoff 0
5045.mbar add cascade -label Repository -menu .mbar.repository
5046.mbar add cascade -label Edit -menu .mbar.edit
5047if {[is_enabled branch]} {
5048        .mbar add cascade -label Branch -menu .mbar.branch
5049}
5050if {[is_enabled multicommit] || [is_enabled singlecommit]} {
5051        .mbar add cascade -label Commit -menu .mbar.commit
5052}
5053if {[is_enabled transport]} {
5054        .mbar add cascade -label Merge -menu .mbar.merge
5055        .mbar add cascade -label Fetch -menu .mbar.fetch
5056        .mbar add cascade -label Push -menu .mbar.push
5057}
5058. configure -menu .mbar
5059
5060# -- Repository Menu
5061#
5062menu .mbar.repository
5063
5064.mbar.repository add command \
5065        -label {Browse Current Branch} \
5066        -command {new_browser $current_branch} \
5067        -font font_ui
5068trace add variable current_branch write ".mbar.repository entryconf [.mbar.repository index last] -label \"Browse \$current_branch\" ;#"
5069.mbar.repository add separator
5070
5071.mbar.repository add command \
5072        -label {Visualize Current Branch} \
5073        -command {do_gitk $current_branch} \
5074        -font font_ui
5075trace add variable current_branch write ".mbar.repository entryconf [.mbar.repository index last] -label \"Visualize \$current_branch\" ;#"
5076.mbar.repository add command \
5077        -label {Visualize All Branches} \
5078        -command {do_gitk --all} \
5079        -font font_ui
5080.mbar.repository add separator
5081
5082if {[is_enabled multicommit]} {
5083        .mbar.repository add command -label {Database Statistics} \
5084                -command do_stats \
5085                -font font_ui
5086
5087        .mbar.repository add command -label {Compress Database} \
5088                -command do_gc \
5089                -font font_ui
5090
5091        .mbar.repository add command -label {Verify Database} \
5092                -command do_fsck_objects \
5093                -font font_ui
5094
5095        .mbar.repository add separator
5096
5097        if {[is_Cygwin]} {
5098                .mbar.repository add command \
5099                        -label {Create Desktop Icon} \
5100                        -command do_cygwin_shortcut \
5101                        -font font_ui
5102        } elseif {[is_Windows]} {
5103                .mbar.repository add command \
5104                        -label {Create Desktop Icon} \
5105                        -command do_windows_shortcut \
5106                        -font font_ui
5107        } elseif {[is_MacOSX]} {
5108                .mbar.repository add command \
5109                        -label {Create Desktop Icon} \
5110                        -command do_macosx_app \
5111                        -font font_ui
5112        }
5113}
5114
5115.mbar.repository add command -label Quit \
5116        -command do_quit \
5117        -accelerator $M1T-Q \
5118        -font font_ui
5119
5120# -- Edit Menu
5121#
5122menu .mbar.edit
5123.mbar.edit add command -label Undo \
5124        -command {catch {[focus] edit undo}} \
5125        -accelerator $M1T-Z \
5126        -font font_ui
5127.mbar.edit add command -label Redo \
5128        -command {catch {[focus] edit redo}} \
5129        -accelerator $M1T-Y \
5130        -font font_ui
5131.mbar.edit add separator
5132.mbar.edit add command -label Cut \
5133        -command {catch {tk_textCut [focus]}} \
5134        -accelerator $M1T-X \
5135        -font font_ui
5136.mbar.edit add command -label Copy \
5137        -command {catch {tk_textCopy [focus]}} \
5138        -accelerator $M1T-C \
5139        -font font_ui
5140.mbar.edit add command -label Paste \
5141        -command {catch {tk_textPaste [focus]; [focus] see insert}} \
5142        -accelerator $M1T-V \
5143        -font font_ui
5144.mbar.edit add command -label Delete \
5145        -command {catch {[focus] delete sel.first sel.last}} \
5146        -accelerator Del \
5147        -font font_ui
5148.mbar.edit add separator
5149.mbar.edit add command -label {Select All} \
5150        -command {catch {[focus] tag add sel 0.0 end}} \
5151        -accelerator $M1T-A \
5152        -font font_ui
5153
5154# -- Branch Menu
5155#
5156if {[is_enabled branch]} {
5157        menu .mbar.branch
5158
5159        .mbar.branch add command -label {Create...} \
5160                -command do_create_branch \
5161                -accelerator $M1T-N \
5162                -font font_ui
5163        lappend disable_on_lock [list .mbar.branch entryconf \
5164                [.mbar.branch index last] -state]
5165
5166        .mbar.branch add command -label {Delete...} \
5167                -command do_delete_branch \
5168                -font font_ui
5169        lappend disable_on_lock [list .mbar.branch entryconf \
5170                [.mbar.branch index last] -state]
5171}
5172
5173# -- Commit Menu
5174#
5175if {[is_enabled multicommit] || [is_enabled singlecommit]} {
5176        menu .mbar.commit
5177
5178        .mbar.commit add radiobutton \
5179                -label {New Commit} \
5180                -command do_select_commit_type \
5181                -variable selected_commit_type \
5182                -value new \
5183                -font font_ui
5184        lappend disable_on_lock \
5185                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5186
5187        .mbar.commit add radiobutton \
5188                -label {Amend Last Commit} \
5189                -command do_select_commit_type \
5190                -variable selected_commit_type \
5191                -value amend \
5192                -font font_ui
5193        lappend disable_on_lock \
5194                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5195
5196        .mbar.commit add separator
5197
5198        .mbar.commit add command -label Rescan \
5199                -command do_rescan \
5200                -accelerator F5 \
5201                -font font_ui
5202        lappend disable_on_lock \
5203                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5204
5205        .mbar.commit add command -label {Add To Commit} \
5206                -command do_add_selection \
5207                -font font_ui
5208        lappend disable_on_lock \
5209                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5210
5211        .mbar.commit add command -label {Add Existing To Commit} \
5212                -command do_add_all \
5213                -accelerator $M1T-I \
5214                -font font_ui
5215        lappend disable_on_lock \
5216                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5217
5218        .mbar.commit add command -label {Unstage From Commit} \
5219                -command do_unstage_selection \
5220                -font font_ui
5221        lappend disable_on_lock \
5222                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5223
5224        .mbar.commit add command -label {Revert Changes} \
5225                -command do_revert_selection \
5226                -font font_ui
5227        lappend disable_on_lock \
5228                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5229
5230        .mbar.commit add separator
5231
5232        .mbar.commit add command -label {Sign Off} \
5233                -command do_signoff \
5234                -accelerator $M1T-S \
5235                -font font_ui
5236
5237        .mbar.commit add command -label Commit \
5238                -command do_commit \
5239                -accelerator $M1T-Return \
5240                -font font_ui
5241        lappend disable_on_lock \
5242                [list .mbar.commit entryconf [.mbar.commit index last] -state]
5243}
5244
5245if {[is_MacOSX]} {
5246        # -- Apple Menu (Mac OS X only)
5247        #
5248        .mbar add cascade -label Apple -menu .mbar.apple
5249        menu .mbar.apple
5250
5251        .mbar.apple add command -label "About [appname]" \
5252                -command do_about \
5253                -font font_ui
5254        .mbar.apple add command -label "Options..." \
5255                -command do_options \
5256                -font font_ui
5257} else {
5258        # -- Edit Menu
5259        #
5260        .mbar.edit add separator
5261        .mbar.edit add command -label {Options...} \
5262                -command do_options \
5263                -font font_ui
5264
5265        # -- Tools Menu
5266        #
5267        if {[file exists /usr/local/miga/lib/gui-miga]
5268                && [file exists .pvcsrc]} {
5269        proc do_miga {} {
5270                global ui_status_value
5271                if {![lock_index update]} return
5272                set cmd [list sh --login -c "/usr/local/miga/lib/gui-miga \"[pwd]\""]
5273                set miga_fd [open "|$cmd" r]
5274                fconfigure $miga_fd -blocking 0
5275                fileevent $miga_fd readable [list miga_done $miga_fd]
5276                set ui_status_value {Running miga...}
5277        }
5278        proc miga_done {fd} {
5279                read $fd 512
5280                if {[eof $fd]} {
5281                        close $fd
5282                        unlock_index
5283                        rescan [list set ui_status_value {Ready.}]
5284                }
5285        }
5286        .mbar add cascade -label Tools -menu .mbar.tools
5287        menu .mbar.tools
5288        .mbar.tools add command -label "Migrate" \
5289                -command do_miga \
5290                -font font_ui
5291        lappend disable_on_lock \
5292                [list .mbar.tools entryconf [.mbar.tools index last] -state]
5293        }
5294}
5295
5296# -- Help Menu
5297#
5298.mbar add cascade -label Help -menu .mbar.help
5299menu .mbar.help
5300
5301if {![is_MacOSX]} {
5302        .mbar.help add command -label "About [appname]" \
5303                -command do_about \
5304                -font font_ui
5305}
5306
5307set browser {}
5308catch {set browser $repo_config(instaweb.browser)}
5309set doc_path [file dirname [gitexec]]
5310set doc_path [file join $doc_path Documentation index.html]
5311
5312if {[is_Cygwin]} {
5313        set doc_path [exec cygpath --windows $doc_path]
5314}
5315
5316if {$browser eq {}} {
5317        if {[is_MacOSX]} {
5318                set browser open
5319        } elseif {[is_Cygwin]} {
5320                set program_files [file dirname [exec cygpath --windir]]
5321                set program_files [file join $program_files {Program Files}]
5322                set firefox [file join $program_files {Mozilla Firefox} firefox.exe]
5323                set ie [file join $program_files {Internet Explorer} IEXPLORE.EXE]
5324                if {[file exists $firefox]} {
5325                        set browser $firefox
5326                } elseif {[file exists $ie]} {
5327                        set browser $ie
5328                }
5329                unset program_files firefox ie
5330        }
5331}
5332
5333if {[file isfile $doc_path]} {
5334        set doc_url "file:$doc_path"
5335} else {
5336        set doc_url {http://www.kernel.org/pub/software/scm/git/docs/}
5337}
5338
5339if {$browser ne {}} {
5340        .mbar.help add command -label {Online Documentation} \
5341                -command [list exec $browser $doc_url &] \
5342                -font font_ui
5343}
5344unset browser doc_path doc_url
5345
5346# -- Standard bindings
5347#
5348bind .   <Destroy> do_quit
5349bind all <$M1B-Key-q> do_quit
5350bind all <$M1B-Key-Q> do_quit
5351bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
5352bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
5353
5354# -- Not a normal commit type invocation?  Do that instead!
5355#
5356switch -- $subcommand {
5357--version -
5358version {
5359        puts "git-gui version $appvers"
5360        exit
5361}
5362blame {
5363        if {[llength $argv] != 2} {
5364                puts stderr "usage: $argv0 blame commit path"
5365                exit 1
5366        }
5367        set current_branch [lindex $argv 0]
5368        show_blame $current_branch [lindex $argv 1]
5369        return
5370}
5371citool -
5372gui {
5373        if {[llength $argv] != 0} {
5374                puts -nonewline stderr "usage: $argv0"
5375                if {$subcommand ne {gui} && [appname] ne "git-$subcommand"} {
5376                        puts -nonewline stderr " $subcommand"
5377                }
5378                puts stderr {}
5379                exit 1
5380        }
5381        # fall through to setup UI for commits
5382}
5383default {
5384        puts stderr "usage: $argv0 \[{blame|citool}\]"
5385        exit 1
5386}
5387}
5388
5389# -- Branch Control
5390#
5391frame .branch \
5392        -borderwidth 1 \
5393        -relief sunken
5394label .branch.l1 \
5395        -text {Current Branch:} \
5396        -anchor w \
5397        -justify left \
5398        -font font_ui
5399label .branch.cb \
5400        -textvariable current_branch \
5401        -anchor w \
5402        -justify left \
5403        -font font_ui
5404pack .branch.l1 -side left
5405pack .branch.cb -side left -fill x
5406pack .branch -side top -fill x
5407
5408if {[is_enabled branch]} {
5409        menu .mbar.merge
5410        .mbar.merge add command -label {Local Merge...} \
5411                -command do_local_merge \
5412                -font font_ui
5413        lappend disable_on_lock \
5414                [list .mbar.merge entryconf [.mbar.merge index last] -state]
5415        .mbar.merge add command -label {Abort Merge...} \
5416                -command do_reset_hard \
5417                -font font_ui
5418        lappend disable_on_lock \
5419                [list .mbar.merge entryconf [.mbar.merge index last] -state]
5420
5421
5422        menu .mbar.fetch
5423
5424        menu .mbar.push
5425        .mbar.push add command -label {Push...} \
5426                -command do_push_anywhere \
5427                -font font_ui
5428}
5429
5430# -- Main Window Layout
5431#
5432panedwindow .vpane -orient vertical
5433panedwindow .vpane.files -orient horizontal
5434.vpane add .vpane.files -sticky nsew -height 100 -width 200
5435pack .vpane -anchor n -side top -fill both -expand 1
5436
5437# -- Index File List
5438#
5439frame .vpane.files.index -height 100 -width 200
5440label .vpane.files.index.title -text {Changes To Be Committed} \
5441        -background green \
5442        -font font_ui
5443text $ui_index -background white -borderwidth 0 \
5444        -width 20 -height 10 \
5445        -wrap none \
5446        -font font_ui \
5447        -cursor $cursor_ptr \
5448        -xscrollcommand {.vpane.files.index.sx set} \
5449        -yscrollcommand {.vpane.files.index.sy set} \
5450        -state disabled
5451scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
5452scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
5453pack .vpane.files.index.title -side top -fill x
5454pack .vpane.files.index.sx -side bottom -fill x
5455pack .vpane.files.index.sy -side right -fill y
5456pack $ui_index -side left -fill both -expand 1
5457.vpane.files add .vpane.files.index -sticky nsew
5458
5459# -- Working Directory File List
5460#
5461frame .vpane.files.workdir -height 100 -width 200
5462label .vpane.files.workdir.title -text {Changed But Not Updated} \
5463        -background red \
5464        -font font_ui
5465text $ui_workdir -background white -borderwidth 0 \
5466        -width 20 -height 10 \
5467        -wrap none \
5468        -font font_ui \
5469        -cursor $cursor_ptr \
5470        -xscrollcommand {.vpane.files.workdir.sx set} \
5471        -yscrollcommand {.vpane.files.workdir.sy set} \
5472        -state disabled
5473scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
5474scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
5475pack .vpane.files.workdir.title -side top -fill x
5476pack .vpane.files.workdir.sx -side bottom -fill x
5477pack .vpane.files.workdir.sy -side right -fill y
5478pack $ui_workdir -side left -fill both -expand 1
5479.vpane.files add .vpane.files.workdir -sticky nsew
5480
5481foreach i [list $ui_index $ui_workdir] {
5482        $i tag conf in_diff -font font_uibold
5483        $i tag conf in_sel \
5484                -background [$i cget -foreground] \
5485                -foreground [$i cget -background]
5486}
5487unset i
5488
5489# -- Diff and Commit Area
5490#
5491frame .vpane.lower -height 300 -width 400
5492frame .vpane.lower.commarea
5493frame .vpane.lower.diff -relief sunken -borderwidth 1
5494pack .vpane.lower.commarea -side top -fill x
5495pack .vpane.lower.diff -side bottom -fill both -expand 1
5496.vpane add .vpane.lower -sticky nsew
5497
5498# -- Commit Area Buttons
5499#
5500frame .vpane.lower.commarea.buttons
5501label .vpane.lower.commarea.buttons.l -text {} \
5502        -anchor w \
5503        -justify left \
5504        -font font_ui
5505pack .vpane.lower.commarea.buttons.l -side top -fill x
5506pack .vpane.lower.commarea.buttons -side left -fill y
5507
5508button .vpane.lower.commarea.buttons.rescan -text {Rescan} \
5509        -command do_rescan \
5510        -font font_ui
5511pack .vpane.lower.commarea.buttons.rescan -side top -fill x
5512lappend disable_on_lock \
5513        {.vpane.lower.commarea.buttons.rescan conf -state}
5514
5515button .vpane.lower.commarea.buttons.incall -text {Add Existing} \
5516        -command do_add_all \
5517        -font font_ui
5518pack .vpane.lower.commarea.buttons.incall -side top -fill x
5519lappend disable_on_lock \
5520        {.vpane.lower.commarea.buttons.incall conf -state}
5521
5522button .vpane.lower.commarea.buttons.signoff -text {Sign Off} \
5523        -command do_signoff \
5524        -font font_ui
5525pack .vpane.lower.commarea.buttons.signoff -side top -fill x
5526
5527button .vpane.lower.commarea.buttons.commit -text {Commit} \
5528        -command do_commit \
5529        -font font_ui
5530pack .vpane.lower.commarea.buttons.commit -side top -fill x
5531lappend disable_on_lock \
5532        {.vpane.lower.commarea.buttons.commit conf -state}
5533
5534# -- Commit Message Buffer
5535#
5536frame .vpane.lower.commarea.buffer
5537frame .vpane.lower.commarea.buffer.header
5538set ui_comm .vpane.lower.commarea.buffer.t
5539set ui_coml .vpane.lower.commarea.buffer.header.l
5540radiobutton .vpane.lower.commarea.buffer.header.new \
5541        -text {New Commit} \
5542        -command do_select_commit_type \
5543        -variable selected_commit_type \
5544        -value new \
5545        -font font_ui
5546lappend disable_on_lock \
5547        [list .vpane.lower.commarea.buffer.header.new conf -state]
5548radiobutton .vpane.lower.commarea.buffer.header.amend \
5549        -text {Amend Last Commit} \
5550        -command do_select_commit_type \
5551        -variable selected_commit_type \
5552        -value amend \
5553        -font font_ui
5554lappend disable_on_lock \
5555        [list .vpane.lower.commarea.buffer.header.amend conf -state]
5556label $ui_coml \
5557        -anchor w \
5558        -justify left \
5559        -font font_ui
5560proc trace_commit_type {varname args} {
5561        global ui_coml commit_type
5562        switch -glob -- $commit_type {
5563        initial       {set txt {Initial Commit Message:}}
5564        amend         {set txt {Amended Commit Message:}}
5565        amend-initial {set txt {Amended Initial Commit Message:}}
5566        amend-merge   {set txt {Amended Merge Commit Message:}}
5567        merge         {set txt {Merge Commit Message:}}
5568        *             {set txt {Commit Message:}}
5569        }
5570        $ui_coml conf -text $txt
5571}
5572trace add variable commit_type write trace_commit_type
5573pack $ui_coml -side left -fill x
5574pack .vpane.lower.commarea.buffer.header.amend -side right
5575pack .vpane.lower.commarea.buffer.header.new -side right
5576
5577text $ui_comm -background white -borderwidth 1 \
5578        -undo true \
5579        -maxundo 20 \
5580        -autoseparators true \
5581        -relief sunken \
5582        -width 75 -height 9 -wrap none \
5583        -font font_diff \
5584        -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
5585scrollbar .vpane.lower.commarea.buffer.sby \
5586        -command [list $ui_comm yview]
5587pack .vpane.lower.commarea.buffer.header -side top -fill x
5588pack .vpane.lower.commarea.buffer.sby -side right -fill y
5589pack $ui_comm -side left -fill y
5590pack .vpane.lower.commarea.buffer -side left -fill y
5591
5592# -- Commit Message Buffer Context Menu
5593#
5594set ctxm .vpane.lower.commarea.buffer.ctxm
5595menu $ctxm -tearoff 0
5596$ctxm add command \
5597        -label {Cut} \
5598        -font font_ui \
5599        -command {tk_textCut $ui_comm}
5600$ctxm add command \
5601        -label {Copy} \
5602        -font font_ui \
5603        -command {tk_textCopy $ui_comm}
5604$ctxm add command \
5605        -label {Paste} \
5606        -font font_ui \
5607        -command {tk_textPaste $ui_comm}
5608$ctxm add command \
5609        -label {Delete} \
5610        -font font_ui \
5611        -command {$ui_comm delete sel.first sel.last}
5612$ctxm add separator
5613$ctxm add command \
5614        -label {Select All} \
5615        -font font_ui \
5616        -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
5617$ctxm add command \
5618        -label {Copy All} \
5619        -font font_ui \
5620        -command {
5621                $ui_comm tag add sel 0.0 end
5622                tk_textCopy $ui_comm
5623                $ui_comm tag remove sel 0.0 end
5624        }
5625$ctxm add separator
5626$ctxm add command \
5627        -label {Sign Off} \
5628        -font font_ui \
5629        -command do_signoff
5630bind_button3 $ui_comm "tk_popup $ctxm %X %Y"
5631
5632# -- Diff Header
5633#
5634set current_diff_path {}
5635set current_diff_side {}
5636set diff_actions [list]
5637proc trace_current_diff_path {varname args} {
5638        global current_diff_path diff_actions file_states
5639        if {$current_diff_path eq {}} {
5640                set s {}
5641                set f {}
5642                set p {}
5643                set o disabled
5644        } else {
5645                set p $current_diff_path
5646                set s [mapdesc [lindex $file_states($p) 0] $p]
5647                set f {File:}
5648                set p [escape_path $p]
5649                set o normal
5650        }
5651
5652        .vpane.lower.diff.header.status configure -text $s
5653        .vpane.lower.diff.header.file configure -text $f
5654        .vpane.lower.diff.header.path configure -text $p
5655        foreach w $diff_actions {
5656                uplevel #0 $w $o
5657        }
5658}
5659trace add variable current_diff_path write trace_current_diff_path
5660
5661frame .vpane.lower.diff.header -background orange
5662label .vpane.lower.diff.header.status \
5663        -background orange \
5664        -width $max_status_desc \
5665        -anchor w \
5666        -justify left \
5667        -font font_ui
5668label .vpane.lower.diff.header.file \
5669        -background orange \
5670        -anchor w \
5671        -justify left \
5672        -font font_ui
5673label .vpane.lower.diff.header.path \
5674        -background orange \
5675        -anchor w \
5676        -justify left \
5677        -font font_ui
5678pack .vpane.lower.diff.header.status -side left
5679pack .vpane.lower.diff.header.file -side left
5680pack .vpane.lower.diff.header.path -fill x
5681set ctxm .vpane.lower.diff.header.ctxm
5682menu $ctxm -tearoff 0
5683$ctxm add command \
5684        -label {Copy} \
5685        -font font_ui \
5686        -command {
5687                clipboard clear
5688                clipboard append \
5689                        -format STRING \
5690                        -type STRING \
5691                        -- $current_diff_path
5692        }
5693lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5694bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
5695
5696# -- Diff Body
5697#
5698frame .vpane.lower.diff.body
5699set ui_diff .vpane.lower.diff.body.t
5700text $ui_diff -background white -borderwidth 0 \
5701        -width 80 -height 15 -wrap none \
5702        -font font_diff \
5703        -xscrollcommand {.vpane.lower.diff.body.sbx set} \
5704        -yscrollcommand {.vpane.lower.diff.body.sby set} \
5705        -state disabled
5706scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
5707        -command [list $ui_diff xview]
5708scrollbar .vpane.lower.diff.body.sby -orient vertical \
5709        -command [list $ui_diff yview]
5710pack .vpane.lower.diff.body.sbx -side bottom -fill x
5711pack .vpane.lower.diff.body.sby -side right -fill y
5712pack $ui_diff -side left -fill both -expand 1
5713pack .vpane.lower.diff.header -side top -fill x
5714pack .vpane.lower.diff.body -side bottom -fill both -expand 1
5715
5716$ui_diff tag conf d_cr -elide true
5717$ui_diff tag conf d_@ -foreground blue -font font_diffbold
5718$ui_diff tag conf d_+ -foreground {#00a000}
5719$ui_diff tag conf d_- -foreground red
5720
5721$ui_diff tag conf d_++ -foreground {#00a000}
5722$ui_diff tag conf d_-- -foreground red
5723$ui_diff tag conf d_+s \
5724        -foreground {#00a000} \
5725        -background {#e2effa}
5726$ui_diff tag conf d_-s \
5727        -foreground red \
5728        -background {#e2effa}
5729$ui_diff tag conf d_s+ \
5730        -foreground {#00a000} \
5731        -background ivory1
5732$ui_diff tag conf d_s- \
5733        -foreground red \
5734        -background ivory1
5735
5736$ui_diff tag conf d<<<<<<< \
5737        -foreground orange \
5738        -font font_diffbold
5739$ui_diff tag conf d======= \
5740        -foreground orange \
5741        -font font_diffbold
5742$ui_diff tag conf d>>>>>>> \
5743        -foreground orange \
5744        -font font_diffbold
5745
5746$ui_diff tag raise sel
5747
5748# -- Diff Body Context Menu
5749#
5750set ctxm .vpane.lower.diff.body.ctxm
5751menu $ctxm -tearoff 0
5752$ctxm add command \
5753        -label {Refresh} \
5754        -font font_ui \
5755        -command reshow_diff
5756lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5757$ctxm add command \
5758        -label {Copy} \
5759        -font font_ui \
5760        -command {tk_textCopy $ui_diff}
5761lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5762$ctxm add command \
5763        -label {Select All} \
5764        -font font_ui \
5765        -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
5766lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5767$ctxm add command \
5768        -label {Copy All} \
5769        -font font_ui \
5770        -command {
5771                $ui_diff tag add sel 0.0 end
5772                tk_textCopy $ui_diff
5773                $ui_diff tag remove sel 0.0 end
5774        }
5775lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5776$ctxm add separator
5777$ctxm add command \
5778        -label {Apply/Reverse Hunk} \
5779        -font font_ui \
5780        -command {apply_hunk $cursorX $cursorY}
5781set ui_diff_applyhunk [$ctxm index last]
5782lappend diff_actions [list $ctxm entryconf $ui_diff_applyhunk -state]
5783$ctxm add separator
5784$ctxm add command \
5785        -label {Decrease Font Size} \
5786        -font font_ui \
5787        -command {incr_font_size font_diff -1}
5788lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5789$ctxm add command \
5790        -label {Increase Font Size} \
5791        -font font_ui \
5792        -command {incr_font_size font_diff 1}
5793lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5794$ctxm add separator
5795$ctxm add command \
5796        -label {Show Less Context} \
5797        -font font_ui \
5798        -command {if {$repo_config(gui.diffcontext) >= 2} {
5799                incr repo_config(gui.diffcontext) -1
5800                reshow_diff
5801        }}
5802lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5803$ctxm add command \
5804        -label {Show More Context} \
5805        -font font_ui \
5806        -command {
5807                incr repo_config(gui.diffcontext)
5808                reshow_diff
5809        }
5810lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5811$ctxm add separator
5812$ctxm add command -label {Options...} \
5813        -font font_ui \
5814        -command do_options
5815bind_button3 $ui_diff "
5816        set cursorX %x
5817        set cursorY %y
5818        if {\$ui_index eq \$current_diff_side} {
5819                $ctxm entryconf $ui_diff_applyhunk -label {Unstage Hunk From Commit}
5820        } else {
5821                $ctxm entryconf $ui_diff_applyhunk -label {Stage Hunk For Commit}
5822        }
5823        tk_popup $ctxm %X %Y
5824"
5825unset ui_diff_applyhunk
5826
5827# -- Status Bar
5828#
5829set ui_status_value {Initializing...}
5830label .status -textvariable ui_status_value \
5831        -anchor w \
5832        -justify left \
5833        -borderwidth 1 \
5834        -relief sunken \
5835        -font font_ui
5836pack .status -anchor w -side bottom -fill x
5837
5838# -- Load geometry
5839#
5840catch {
5841set gm $repo_config(gui.geometry)
5842wm geometry . [lindex $gm 0]
5843.vpane sash place 0 \
5844        [lindex [.vpane sash coord 0] 0] \
5845        [lindex $gm 1]
5846.vpane.files sash place 0 \
5847        [lindex $gm 2] \
5848        [lindex [.vpane.files sash coord 0] 1]
5849unset gm
5850}
5851
5852# -- Key Bindings
5853#
5854bind $ui_comm <$M1B-Key-Return> {do_commit;break}
5855bind $ui_comm <$M1B-Key-i> {do_add_all;break}
5856bind $ui_comm <$M1B-Key-I> {do_add_all;break}
5857bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
5858bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
5859bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
5860bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
5861bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
5862bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
5863bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
5864bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
5865
5866bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
5867bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
5868bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
5869bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
5870bind $ui_diff <$M1B-Key-v> {break}
5871bind $ui_diff <$M1B-Key-V> {break}
5872bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
5873bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
5874bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
5875bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
5876bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
5877bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
5878bind $ui_diff <Button-1>   {focus %W}
5879
5880if {[is_enabled branch]} {
5881        bind . <$M1B-Key-n> do_create_branch
5882        bind . <$M1B-Key-N> do_create_branch
5883}
5884
5885bind all <Key-F5> do_rescan
5886bind all <$M1B-Key-r> do_rescan
5887bind all <$M1B-Key-R> do_rescan
5888bind .   <$M1B-Key-s> do_signoff
5889bind .   <$M1B-Key-S> do_signoff
5890bind .   <$M1B-Key-i> do_add_all
5891bind .   <$M1B-Key-I> do_add_all
5892bind .   <$M1B-Key-Return> do_commit
5893foreach i [list $ui_index $ui_workdir] {
5894        bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
5895        bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
5896        bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
5897}
5898unset i
5899
5900set file_lists($ui_index) [list]
5901set file_lists($ui_workdir) [list]
5902
5903set HEAD {}
5904set PARENT {}
5905set MERGE_HEAD [list]
5906set commit_type {}
5907set empty_tree {}
5908set current_branch {}
5909set current_diff_path {}
5910set selected_commit_type new
5911
5912wm title . "[appname] ([file normalize [file dirname [gitdir]]])"
5913focus -force $ui_comm
5914
5915# -- Warn the user about environmental problems.  Cygwin's Tcl
5916#    does *not* pass its env array onto any processes it spawns.
5917#    This means that git processes get none of our environment.
5918#
5919if {[is_Cygwin]} {
5920        set ignored_env 0
5921        set suggest_user {}
5922        set msg "Possible environment issues exist.
5923
5924The following environment variables are probably
5925going to be ignored by any Git subprocess run
5926by [appname]:
5927
5928"
5929        foreach name [array names env] {
5930                switch -regexp -- $name {
5931                {^GIT_INDEX_FILE$} -
5932                {^GIT_OBJECT_DIRECTORY$} -
5933                {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
5934                {^GIT_DIFF_OPTS$} -
5935                {^GIT_EXTERNAL_DIFF$} -
5936                {^GIT_PAGER$} -
5937                {^GIT_TRACE$} -
5938                {^GIT_CONFIG$} -
5939                {^GIT_CONFIG_LOCAL$} -
5940                {^GIT_(AUTHOR|COMMITTER)_DATE$} {
5941                        append msg " - $name\n"
5942                        incr ignored_env
5943                }
5944                {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
5945                        append msg " - $name\n"
5946                        incr ignored_env
5947                        set suggest_user $name
5948                }
5949                }
5950        }
5951        if {$ignored_env > 0} {
5952                append msg "
5953This is due to a known issue with the
5954Tcl binary distributed by Cygwin."
5955
5956                if {$suggest_user ne {}} {
5957                        append msg "
5958
5959A good replacement for $suggest_user
5960is placing values for the user.name and
5961user.email settings into your personal
5962~/.gitconfig file.
5963"
5964                }
5965                warn_popup $msg
5966        }
5967        unset ignored_env msg suggest_user name
5968}
5969
5970# -- Only initialize complex UI if we are going to stay running.
5971#
5972if {[is_enabled transport]} {
5973        load_all_remotes
5974        load_all_heads
5975
5976        populate_branch_menu
5977        populate_fetch_menu
5978        populate_push_menu
5979}
5980
5981# -- Only suggest a gc run if we are going to stay running.
5982#
5983if {[is_enabled multicommit]} {
5984        set object_limit 2000
5985        if {[is_Windows]} {set object_limit 200}
5986        regexp {^([0-9]+) objects,} [git count-objects] _junk objects_current
5987        if {$objects_current >= $object_limit} {
5988                if {[ask_popup \
5989                        "This repository currently has $objects_current loose objects.
5990
5991To maintain optimal performance it is strongly
5992recommended that you compress the database
5993when more than $object_limit loose objects exist.
5994
5995Compress the database now?"] eq yes} {
5996                        do_gc
5997                }
5998        }
5999        unset object_limit _junk objects_current
6000}
6001
6002lock_index begin-read
6003after 1 do_rescan