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