git-gui.shon commit git-gui: Don't show content of untracked binary files. (464c9ff)
   1#!/bin/sh
   2# Tcl ignores the next line -*- tcl -*- \
   3exec wish "$0" -- "$@"
   4
   5set appvers {@@GIT_VERSION@@}
   6set copyright {
   7Copyright © 2006, 2007 Shawn Pearce, Paul Mackerras.
   8
   9This program is free software; you can redistribute it and/or modify
  10it under the terms of the GNU General Public License as published by
  11the Free Software Foundation; either version 2 of the License, or
  12(at your option) any later version.
  13
  14This program is distributed in the hope that it will be useful,
  15but WITHOUT ANY WARRANTY; without even the implied warranty of
  16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17GNU General Public License for more details.
  18
  19You should have received a copy of the GNU General Public License
  20along with this program; if not, write to the Free Software
  21Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA}
  22
  23######################################################################
  24##
  25## read only globals
  26
  27set _appname [lindex [file split $argv0] end]
  28set _gitdir {}
  29set _reponame {}
  30
  31proc appname {} {
  32        global _appname
  33        return $_appname
  34}
  35
  36proc gitdir {args} {
  37        global _gitdir
  38        if {$args eq {}} {
  39                return $_gitdir
  40        }
  41        return [eval [concat [list file join $_gitdir] $args]]
  42}
  43
  44proc reponame {} {
  45        global _reponame
  46        return $_reponame
  47}
  48
  49######################################################################
  50##
  51## config
  52
  53proc is_many_config {name} {
  54        switch -glob -- $name {
  55        remote.*.fetch -
  56        remote.*.push
  57                {return 1}
  58        *
  59                {return 0}
  60        }
  61}
  62
  63proc load_config {include_global} {
  64        global repo_config global_config default_config
  65
  66        array unset global_config
  67        if {$include_global} {
  68                catch {
  69                        set fd_rc [open "| git repo-config --global --list" r]
  70                        while {[gets $fd_rc line] >= 0} {
  71                                if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
  72                                        if {[is_many_config $name]} {
  73                                                lappend global_config($name) $value
  74                                        } else {
  75                                                set global_config($name) $value
  76                                        }
  77                                }
  78                        }
  79                        close $fd_rc
  80                }
  81        }
  82
  83        array unset repo_config
  84        catch {
  85                set fd_rc [open "| git repo-config --list" r]
  86                while {[gets $fd_rc line] >= 0} {
  87                        if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
  88                                if {[is_many_config $name]} {
  89                                        lappend repo_config($name) $value
  90                                } else {
  91                                        set repo_config($name) $value
  92                                }
  93                        }
  94                }
  95                close $fd_rc
  96        }
  97
  98        foreach name [array names default_config] {
  99                if {[catch {set v $global_config($name)}]} {
 100                        set global_config($name) $default_config($name)
 101                }
 102                if {[catch {set v $repo_config($name)}]} {
 103                        set repo_config($name) $default_config($name)
 104                }
 105        }
 106}
 107
 108proc save_config {} {
 109        global default_config font_descs
 110        global repo_config global_config
 111        global repo_config_new global_config_new
 112
 113        foreach option $font_descs {
 114                set name [lindex $option 0]
 115                set font [lindex $option 1]
 116                font configure $font \
 117                        -family $global_config_new(gui.$font^^family) \
 118                        -size $global_config_new(gui.$font^^size)
 119                font configure ${font}bold \
 120                        -family $global_config_new(gui.$font^^family) \
 121                        -size $global_config_new(gui.$font^^size)
 122                set global_config_new(gui.$name) [font configure $font]
 123                unset global_config_new(gui.$font^^family)
 124                unset global_config_new(gui.$font^^size)
 125        }
 126
 127        foreach name [array names default_config] {
 128                set value $global_config_new($name)
 129                if {$value ne $global_config($name)} {
 130                        if {$value eq $default_config($name)} {
 131                                catch {exec git repo-config --global --unset $name}
 132                        } else {
 133                                regsub -all "\[{}\]" $value {"} value
 134                                exec git repo-config --global $name $value
 135                        }
 136                        set global_config($name) $value
 137                        if {$value eq $repo_config($name)} {
 138                                catch {exec git repo-config --unset $name}
 139                                set repo_config($name) $value
 140                        }
 141                }
 142        }
 143
 144        foreach name [array names default_config] {
 145                set value $repo_config_new($name)
 146                if {$value ne $repo_config($name)} {
 147                        if {$value eq $global_config($name)} {
 148                                catch {exec git repo-config --unset $name}
 149                        } else {
 150                                regsub -all "\[{}\]" $value {"} value
 151                                exec git repo-config $name $value
 152                        }
 153                        set repo_config($name) $value
 154                }
 155        }
 156}
 157
 158proc error_popup {msg} {
 159        set title [appname]
 160        if {[reponame] ne {}} {
 161                append title " ([reponame])"
 162        }
 163        set cmd [list tk_messageBox \
 164                -icon error \
 165                -type ok \
 166                -title "$title: error" \
 167                -message $msg]
 168        if {[winfo ismapped .]} {
 169                lappend cmd -parent .
 170        }
 171        eval $cmd
 172}
 173
 174proc warn_popup {msg} {
 175        set title [appname]
 176        if {[reponame] ne {}} {
 177                append title " ([reponame])"
 178        }
 179        set cmd [list tk_messageBox \
 180                -icon warning \
 181                -type ok \
 182                -title "$title: warning" \
 183                -message $msg]
 184        if {[winfo ismapped .]} {
 185                lappend cmd -parent .
 186        }
 187        eval $cmd
 188}
 189
 190proc info_popup {msg} {
 191        set title [appname]
 192        if {[reponame] ne {}} {
 193                append title " ([reponame])"
 194        }
 195        tk_messageBox \
 196                -parent . \
 197                -icon info \
 198                -type ok \
 199                -title $title \
 200                -message $msg
 201}
 202
 203proc ask_popup {msg} {
 204        set title [appname]
 205        if {[reponame] ne {}} {
 206                append title " ([reponame])"
 207        }
 208        return [tk_messageBox \
 209                -parent . \
 210                -icon question \
 211                -type yesno \
 212                -title $title \
 213                -message $msg]
 214}
 215
 216######################################################################
 217##
 218## repository setup
 219
 220if {   [catch {set _gitdir $env(GIT_DIR)}]
 221        && [catch {set _gitdir [exec git rev-parse --git-dir]} err]} {
 222        catch {wm withdraw .}
 223        error_popup "Cannot find the git directory:\n\n$err"
 224        exit 1
 225}
 226if {![file isdirectory $_gitdir]} {
 227        catch {wm withdraw .}
 228        error_popup "Git directory not found:\n\n$_gitdir"
 229        exit 1
 230}
 231if {[lindex [file split $_gitdir] end] ne {.git}} {
 232        catch {wm withdraw .}
 233        error_popup "Cannot use funny .git directory:\n\n$gitdir"
 234        exit 1
 235}
 236if {[catch {cd [file dirname $_gitdir]} err]} {
 237        catch {wm withdraw .}
 238        error_popup "No working directory [file dirname $_gitdir]:\n\n$err"
 239        exit 1
 240}
 241set _reponame [lindex [file split \
 242        [file normalize [file dirname $_gitdir]]] \
 243        end]
 244
 245set single_commit 0
 246if {[appname] eq {git-citool}} {
 247        set single_commit 1
 248}
 249
 250######################################################################
 251##
 252## task management
 253
 254set rescan_active 0
 255set diff_active 0
 256set last_clicked {}
 257
 258set disable_on_lock [list]
 259set index_lock_type none
 260
 261proc lock_index {type} {
 262        global index_lock_type disable_on_lock
 263
 264        if {$index_lock_type eq {none}} {
 265                set index_lock_type $type
 266                foreach w $disable_on_lock {
 267                        uplevel #0 $w disabled
 268                }
 269                return 1
 270        } elseif {$index_lock_type eq "begin-$type"} {
 271                set index_lock_type $type
 272                return 1
 273        }
 274        return 0
 275}
 276
 277proc unlock_index {} {
 278        global index_lock_type disable_on_lock
 279
 280        set index_lock_type none
 281        foreach w $disable_on_lock {
 282                uplevel #0 $w normal
 283        }
 284}
 285
 286######################################################################
 287##
 288## status
 289
 290proc repository_state {ctvar hdvar mhvar} {
 291        global current_branch
 292        upvar $ctvar ct $hdvar hd $mhvar mh
 293
 294        set mh [list]
 295
 296        if {[catch {set current_branch [exec git symbolic-ref HEAD]}]} {
 297                set current_branch {}
 298        } else {
 299                regsub ^refs/((heads|tags|remotes)/)? \
 300                        $current_branch \
 301                        {} \
 302                        current_branch
 303        }
 304
 305        if {[catch {set hd [exec git rev-parse --verify HEAD]}]} {
 306                set hd {}
 307                set ct initial
 308                return
 309        }
 310
 311        set merge_head [gitdir MERGE_HEAD]
 312        if {[file exists $merge_head]} {
 313                set ct merge
 314                set fd_mh [open $merge_head r]
 315                while {[gets $fd_mh line] >= 0} {
 316                        lappend mh $line
 317                }
 318                close $fd_mh
 319                return
 320        }
 321
 322        set ct normal
 323}
 324
 325proc PARENT {} {
 326        global PARENT empty_tree
 327
 328        set p [lindex $PARENT 0]
 329        if {$p ne {}} {
 330                return $p
 331        }
 332        if {$empty_tree eq {}} {
 333                set empty_tree [exec git mktree << {}]
 334        }
 335        return $empty_tree
 336}
 337
 338proc rescan {after {honor_trustmtime 1}} {
 339        global HEAD PARENT MERGE_HEAD commit_type
 340        global ui_index ui_workdir ui_status_value ui_comm
 341        global rescan_active file_states
 342        global repo_config
 343
 344        if {$rescan_active > 0 || ![lock_index read]} return
 345
 346        repository_state newType newHEAD newMERGE_HEAD
 347        if {[string match amend* $commit_type]
 348                && $newType eq {normal}
 349                && $newHEAD eq $HEAD} {
 350        } else {
 351                set HEAD $newHEAD
 352                set PARENT $newHEAD
 353                set MERGE_HEAD $newMERGE_HEAD
 354                set commit_type $newType
 355        }
 356
 357        array unset file_states
 358
 359        if {![$ui_comm edit modified]
 360                || [string trim [$ui_comm get 0.0 end]] eq {}} {
 361                if {[load_message GITGUI_MSG]} {
 362                } elseif {[load_message MERGE_MSG]} {
 363                } elseif {[load_message SQUASH_MSG]} {
 364                }
 365                $ui_comm edit reset
 366                $ui_comm edit modified false
 367        }
 368
 369        if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
 370                rescan_stage2 {} $after
 371        } else {
 372                set rescan_active 1
 373                set ui_status_value {Refreshing file status...}
 374                set cmd [list git update-index]
 375                lappend cmd -q
 376                lappend cmd --unmerged
 377                lappend cmd --ignore-missing
 378                lappend cmd --refresh
 379                set fd_rf [open "| $cmd" r]
 380                fconfigure $fd_rf -blocking 0 -translation binary
 381                fileevent $fd_rf readable \
 382                        [list rescan_stage2 $fd_rf $after]
 383        }
 384}
 385
 386proc rescan_stage2 {fd after} {
 387        global ui_status_value
 388        global rescan_active buf_rdi buf_rdf buf_rlo
 389
 390        if {$fd ne {}} {
 391                read $fd
 392                if {![eof $fd]} return
 393                close $fd
 394        }
 395
 396        set ls_others [list | git ls-files --others -z \
 397                --exclude-per-directory=.gitignore]
 398        set info_exclude [gitdir info exclude]
 399        if {[file readable $info_exclude]} {
 400                lappend ls_others "--exclude-from=$info_exclude"
 401        }
 402
 403        set buf_rdi {}
 404        set buf_rdf {}
 405        set buf_rlo {}
 406
 407        set rescan_active 3
 408        set ui_status_value {Scanning for modified files ...}
 409        set fd_di [open "| git diff-index --cached -z [PARENT]" r]
 410        set fd_df [open "| git diff-files -z" r]
 411        set fd_lo [open $ls_others r]
 412
 413        fconfigure $fd_di -blocking 0 -translation binary
 414        fconfigure $fd_df -blocking 0 -translation binary
 415        fconfigure $fd_lo -blocking 0 -translation binary
 416        fileevent $fd_di readable [list read_diff_index $fd_di $after]
 417        fileevent $fd_df readable [list read_diff_files $fd_df $after]
 418        fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
 419}
 420
 421proc load_message {file} {
 422        global ui_comm
 423
 424        set f [gitdir $file]
 425        if {[file isfile $f]} {
 426                if {[catch {set fd [open $f r]}]} {
 427                        return 0
 428                }
 429                set content [string trim [read $fd]]
 430                close $fd
 431                $ui_comm delete 0.0 end
 432                $ui_comm insert end $content
 433                return 1
 434        }
 435        return 0
 436}
 437
 438proc read_diff_index {fd after} {
 439        global buf_rdi
 440
 441        append buf_rdi [read $fd]
 442        set c 0
 443        set n [string length $buf_rdi]
 444        while {$c < $n} {
 445                set z1 [string first "\0" $buf_rdi $c]
 446                if {$z1 == -1} break
 447                incr z1
 448                set z2 [string first "\0" $buf_rdi $z1]
 449                if {$z2 == -1} break
 450
 451                incr c
 452                set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
 453                merge_state \
 454                        [string range $buf_rdi $z1 [expr {$z2 - 1}]] \
 455                        [lindex $i 4]? \
 456                        [list [lindex $i 0] [lindex $i 2]] \
 457                        [list]
 458                set c $z2
 459                incr c
 460        }
 461        if {$c < $n} {
 462                set buf_rdi [string range $buf_rdi $c end]
 463        } else {
 464                set buf_rdi {}
 465        }
 466
 467        rescan_done $fd buf_rdi $after
 468}
 469
 470proc read_diff_files {fd after} {
 471        global buf_rdf
 472
 473        append buf_rdf [read $fd]
 474        set c 0
 475        set n [string length $buf_rdf]
 476        while {$c < $n} {
 477                set z1 [string first "\0" $buf_rdf $c]
 478                if {$z1 == -1} break
 479                incr z1
 480                set z2 [string first "\0" $buf_rdf $z1]
 481                if {$z2 == -1} break
 482
 483                incr c
 484                set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
 485                merge_state \
 486                        [string range $buf_rdf $z1 [expr {$z2 - 1}]] \
 487                        ?[lindex $i 4] \
 488                        [list] \
 489                        [list [lindex $i 0] [lindex $i 2]]
 490                set c $z2
 491                incr c
 492        }
 493        if {$c < $n} {
 494                set buf_rdf [string range $buf_rdf $c end]
 495        } else {
 496                set buf_rdf {}
 497        }
 498
 499        rescan_done $fd buf_rdf $after
 500}
 501
 502proc read_ls_others {fd after} {
 503        global buf_rlo
 504
 505        append buf_rlo [read $fd]
 506        set pck [split $buf_rlo "\0"]
 507        set buf_rlo [lindex $pck end]
 508        foreach p [lrange $pck 0 end-1] {
 509                merge_state $p ?O
 510        }
 511        rescan_done $fd buf_rlo $after
 512}
 513
 514proc rescan_done {fd buf after} {
 515        global rescan_active
 516        global file_states repo_config
 517        upvar $buf to_clear
 518
 519        if {![eof $fd]} return
 520        set to_clear {}
 521        close $fd
 522        if {[incr rescan_active -1] > 0} return
 523
 524        prune_selection
 525        unlock_index
 526        display_all_files
 527        reshow_diff
 528        uplevel #0 $after
 529}
 530
 531proc prune_selection {} {
 532        global file_states selected_paths
 533
 534        foreach path [array names selected_paths] {
 535                if {[catch {set still_here $file_states($path)}]} {
 536                        unset selected_paths($path)
 537                }
 538        }
 539}
 540
 541######################################################################
 542##
 543## diff
 544
 545proc clear_diff {} {
 546        global ui_diff current_diff_path ui_index ui_workdir
 547
 548        $ui_diff conf -state normal
 549        $ui_diff delete 0.0 end
 550        $ui_diff conf -state disabled
 551
 552        set current_diff_path {}
 553
 554        $ui_index tag remove in_diff 0.0 end
 555        $ui_workdir tag remove in_diff 0.0 end
 556}
 557
 558proc reshow_diff {} {
 559        global ui_status_value file_states file_lists
 560        global current_diff_path current_diff_side
 561
 562        set p $current_diff_path
 563        if {$p eq {}
 564                || $current_diff_side eq {}
 565                || [catch {set s $file_states($p)}]
 566                || [lsearch -sorted $file_lists($current_diff_side) $p] == -1} {
 567                clear_diff
 568        } else {
 569                show_diff $p $current_diff_side
 570        }
 571}
 572
 573proc handle_empty_diff {} {
 574        global current_diff_path file_states file_lists
 575
 576        set path $current_diff_path
 577        set s $file_states($path)
 578        if {[lindex $s 0] ne {_M}} return
 579
 580        info_popup "No differences detected.
 581
 582[short_path $path] has no changes.
 583
 584The modification date of this file was updated
 585by another application, but the content within
 586the file was not changed.
 587
 588A rescan will be automatically started to find
 589other files which may have the same state."
 590
 591        clear_diff
 592        display_file $path __
 593        rescan {set ui_status_value {Ready.}} 0
 594}
 595
 596proc show_diff {path w {lno {}}} {
 597        global file_states file_lists
 598        global is_3way_diff diff_active repo_config
 599        global ui_diff ui_status_value ui_index ui_workdir
 600        global current_diff_path current_diff_side
 601
 602        if {$diff_active || ![lock_index read]} return
 603
 604        clear_diff
 605        if {$w eq {} || $lno == {}} {
 606                foreach w [array names file_lists] {
 607                        set lno [lsearch -sorted $file_lists($w) $path]
 608                        if {$lno >= 0} {
 609                                incr lno
 610                                break
 611                        }
 612                }
 613        }
 614        if {$w ne {} && $lno >= 1} {
 615                $w tag add in_diff $lno.0 [expr {$lno + 1}].0
 616        }
 617
 618        set s $file_states($path)
 619        set m [lindex $s 0]
 620        set is_3way_diff 0
 621        set diff_active 1
 622        set current_diff_path $path
 623        set current_diff_side $w
 624        set ui_status_value "Loading diff of [escape_path $path]..."
 625
 626        # - Git won't give us the diff, there's nothing to compare to!
 627        #
 628        if {$m eq {_O}} {
 629                if {[catch {
 630                                set fd [open $path r]
 631                                set content [read $fd]
 632                                close $fd
 633                        } err ]} {
 634                        set diff_active 0
 635                        unlock_index
 636                        set ui_status_value "Unable to display [escape_path $path]"
 637                        error_popup "Error loading file:\n\n$err"
 638                        return
 639                }
 640                if {[string first "\0" [string range $content 0 8000]] != -1} {
 641                        set content {* Binary file (not showing content).}
 642                }
 643                $ui_diff conf -state normal
 644                $ui_diff insert end $content
 645                $ui_diff conf -state disabled
 646                set diff_active 0
 647                unlock_index
 648                set ui_status_value {Ready.}
 649                return
 650        }
 651
 652        set cmd [list | git]
 653        if {$w eq $ui_index} {
 654                lappend cmd diff-index
 655                lappend cmd --cached
 656        } elseif {$w eq $ui_workdir} {
 657                if {[string index $m 0] eq {U}} {
 658                        lappend cmd diff
 659                } else {
 660                        lappend cmd diff-files
 661                }
 662        }
 663
 664        lappend cmd -p
 665        lappend cmd --no-color
 666        if {$repo_config(gui.diffcontext) > 0} {
 667                lappend cmd "-U$repo_config(gui.diffcontext)"
 668        }
 669        if {$w eq $ui_index} {
 670                lappend cmd [PARENT]
 671        }
 672        lappend cmd --
 673        lappend cmd $path
 674
 675        if {[catch {set fd [open $cmd r]} err]} {
 676                set diff_active 0
 677                unlock_index
 678                set ui_status_value "Unable to display [escape_path $path]"
 679                error_popup "Error loading diff:\n\n$err"
 680                return
 681        }
 682
 683        fconfigure $fd -blocking 0 -translation auto
 684        fileevent $fd readable [list read_diff $fd]
 685}
 686
 687proc read_diff {fd} {
 688        global ui_diff ui_status_value is_3way_diff diff_active
 689
 690        $ui_diff conf -state normal
 691        while {[gets $fd line] >= 0} {
 692                # -- Cleanup uninteresting diff header lines.
 693                #
 694                if {[string match {diff --git *}      $line]} continue
 695                if {[string match {diff --cc *}       $line]} continue
 696                if {[string match {diff --combined *} $line]} continue
 697                if {[string match {--- *}             $line]} continue
 698                if {[string match {+++ *}             $line]} continue
 699                if {$line eq {deleted file mode 120000}} {
 700                        set line "deleted symlink"
 701                }
 702
 703                # -- Automatically detect if this is a 3 way diff.
 704                #
 705                if {[string match {@@@ *} $line]} {set is_3way_diff 1}
 706
 707                if {[string match {index *} $line]
 708                        || [string match {mode *} $line]
 709                        || [string match {new file *} $line]
 710                        || [string match {deleted file *} $line]
 711                        || $line eq {\ No newline at end of file}
 712                        || [regexp {^\* Unmerged path } $line]} {
 713                        set tags {}
 714                } elseif {$is_3way_diff} {
 715                        set op [string range $line 0 1]
 716                        switch -- $op {
 717                        {  } {set tags {}}
 718                        {@@} {set tags d_@}
 719                        { +} {set tags d_s+}
 720                        { -} {set tags d_s-}
 721                        {+ } {set tags d_+s}
 722                        {- } {set tags d_-s}
 723                        {--} {set tags d_--}
 724                        {++} {
 725                                if {[regexp {^\+\+([<>]{7} |={7})} $line _g op]} {
 726                                        set line [string replace $line 0 1 {  }]
 727                                        set tags d$op
 728                                } else {
 729                                        set tags d_++
 730                                }
 731                        }
 732                        default {
 733                                puts "error: Unhandled 3 way diff marker: {$op}"
 734                                set tags {}
 735                        }
 736                        }
 737                } else {
 738                        set op [string index $line 0]
 739                        switch -- $op {
 740                        { } {set tags {}}
 741                        {@} {set tags d_@}
 742                        {-} {set tags d_-}
 743                        {+} {
 744                                if {[regexp {^\+([<>]{7} |={7})} $line _g op]} {
 745                                        set line [string replace $line 0 0 { }]
 746                                        set tags d$op
 747                                } else {
 748                                        set tags d_+
 749                                }
 750                        }
 751                        default {
 752                                puts "error: Unhandled 2 way diff marker: {$op}"
 753                                set tags {}
 754                        }
 755                        }
 756                }
 757                $ui_diff insert end $line $tags
 758                $ui_diff insert end "\n" $tags
 759        }
 760        $ui_diff conf -state disabled
 761
 762        if {[eof $fd]} {
 763                close $fd
 764                set diff_active 0
 765                unlock_index
 766                set ui_status_value {Ready.}
 767
 768                if {[$ui_diff index end] eq {2.0}} {
 769                        handle_empty_diff
 770                }
 771        }
 772}
 773
 774######################################################################
 775##
 776## commit
 777
 778proc load_last_commit {} {
 779        global HEAD PARENT MERGE_HEAD commit_type ui_comm
 780
 781        if {[llength $PARENT] == 0} {
 782                error_popup {There is nothing to amend.
 783
 784You are about to create the initial commit.
 785There is no commit before this to amend.
 786}
 787                return
 788        }
 789
 790        repository_state curType curHEAD curMERGE_HEAD
 791        if {$curType eq {merge}} {
 792                error_popup {Cannot amend while merging.
 793
 794You are currently in the middle of a merge that
 795has not been fully completed.  You cannot amend
 796the prior commit unless you first abort the
 797current merge activity.
 798}
 799                return
 800        }
 801
 802        set msg {}
 803        set parents [list]
 804        if {[catch {
 805                        set fd [open "| git cat-file commit $curHEAD" r]
 806                        while {[gets $fd line] > 0} {
 807                                if {[string match {parent *} $line]} {
 808                                        lappend parents [string range $line 7 end]
 809                                }
 810                        }
 811                        set msg [string trim [read $fd]]
 812                        close $fd
 813                } err]} {
 814                error_popup "Error loading commit data for amend:\n\n$err"
 815                return
 816        }
 817
 818        set HEAD $curHEAD
 819        set PARENT $parents
 820        set MERGE_HEAD [list]
 821        switch -- [llength $parents] {
 822        0       {set commit_type amend-initial}
 823        1       {set commit_type amend}
 824        default {set commit_type amend-merge}
 825        }
 826
 827        $ui_comm delete 0.0 end
 828        $ui_comm insert end $msg
 829        $ui_comm edit reset
 830        $ui_comm edit modified false
 831        rescan {set ui_status_value {Ready.}}
 832}
 833
 834proc create_new_commit {} {
 835        global commit_type ui_comm
 836
 837        set commit_type normal
 838        $ui_comm delete 0.0 end
 839        $ui_comm edit reset
 840        $ui_comm edit modified false
 841        rescan {set ui_status_value {Ready.}}
 842}
 843
 844set GIT_COMMITTER_IDENT {}
 845
 846proc committer_ident {} {
 847        global GIT_COMMITTER_IDENT
 848
 849        if {$GIT_COMMITTER_IDENT eq {}} {
 850                if {[catch {set me [exec git var GIT_COMMITTER_IDENT]} err]} {
 851                        error_popup "Unable to obtain your identity:\n\n$err"
 852                        return {}
 853                }
 854                if {![regexp {^(.*) [0-9]+ [-+0-9]+$} \
 855                        $me me GIT_COMMITTER_IDENT]} {
 856                        error_popup "Invalid GIT_COMMITTER_IDENT:\n\n$me"
 857                        return {}
 858                }
 859        }
 860
 861        return $GIT_COMMITTER_IDENT
 862}
 863
 864proc commit_tree {} {
 865        global HEAD commit_type file_states ui_comm repo_config
 866        global ui_status_value pch_error
 867
 868        if {![lock_index update]} return
 869        if {[committer_ident] eq {}} return
 870
 871        # -- Our in memory state should match the repository.
 872        #
 873        repository_state curType curHEAD curMERGE_HEAD
 874        if {[string match amend* $commit_type]
 875                && $curType eq {normal}
 876                && $curHEAD eq $HEAD} {
 877        } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
 878                info_popup {Last scanned state does not match repository state.
 879
 880Another Git program has modified this repository
 881since the last scan.  A rescan must be performed
 882before another commit can be created.
 883
 884The rescan will be automatically started now.
 885}
 886                unlock_index
 887                rescan {set ui_status_value {Ready.}}
 888                return
 889        }
 890
 891        # -- At least one file should differ in the index.
 892        #
 893        set files_ready 0
 894        foreach path [array names file_states] {
 895                switch -glob -- [lindex $file_states($path) 0] {
 896                _? {continue}
 897                A? -
 898                D? -
 899                M? {set files_ready 1}
 900                U? {
 901                        error_popup "Unmerged files cannot be committed.
 902
 903File [short_path $path] has merge conflicts.
 904You must resolve them and add the file before committing.
 905"
 906                        unlock_index
 907                        return
 908                }
 909                default {
 910                        error_popup "Unknown file state [lindex $s 0] detected.
 911
 912File [short_path $path] cannot be committed by this program.
 913"
 914                }
 915                }
 916        }
 917        if {!$files_ready} {
 918                info_popup {No changes to commit.
 919
 920You must add at least 1 file before you can commit.
 921}
 922                unlock_index
 923                return
 924        }
 925
 926        # -- A message is required.
 927        #
 928        set msg [string trim [$ui_comm get 1.0 end]]
 929        if {$msg eq {}} {
 930                error_popup {Please supply a commit message.
 931
 932A good commit message has the following format:
 933
 934- First line: Describe in one sentance what you did.
 935- Second line: Blank
 936- Remaining lines: Describe why this change is good.
 937}
 938                unlock_index
 939                return
 940        }
 941
 942        # -- Run the pre-commit hook.
 943        #
 944        set pchook [gitdir hooks pre-commit]
 945
 946        # On Cygwin [file executable] might lie so we need to ask
 947        # the shell if the hook is executable.  Yes that's annoying.
 948        #
 949        if {[is_Windows] && [file isfile $pchook]} {
 950                set pchook [list sh -c [concat \
 951                        "if test -x \"$pchook\";" \
 952                        "then exec \"$pchook\" 2>&1;" \
 953                        "fi"]]
 954        } elseif {[file executable $pchook]} {
 955                set pchook [list $pchook |& cat]
 956        } else {
 957                commit_writetree $curHEAD $msg
 958                return
 959        }
 960
 961        set ui_status_value {Calling pre-commit hook...}
 962        set pch_error {}
 963        set fd_ph [open "| $pchook" r]
 964        fconfigure $fd_ph -blocking 0 -translation binary
 965        fileevent $fd_ph readable \
 966                [list commit_prehook_wait $fd_ph $curHEAD $msg]
 967}
 968
 969proc commit_prehook_wait {fd_ph curHEAD msg} {
 970        global pch_error ui_status_value
 971
 972        append pch_error [read $fd_ph]
 973        fconfigure $fd_ph -blocking 1
 974        if {[eof $fd_ph]} {
 975                if {[catch {close $fd_ph}]} {
 976                        set ui_status_value {Commit declined by pre-commit hook.}
 977                        hook_failed_popup pre-commit $pch_error
 978                        unlock_index
 979                } else {
 980                        commit_writetree $curHEAD $msg
 981                }
 982                set pch_error {}
 983                return
 984        }
 985        fconfigure $fd_ph -blocking 0
 986}
 987
 988proc commit_writetree {curHEAD msg} {
 989        global ui_status_value
 990
 991        set ui_status_value {Committing changes...}
 992        set fd_wt [open "| git write-tree" r]
 993        fileevent $fd_wt readable \
 994                [list commit_committree $fd_wt $curHEAD $msg]
 995}
 996
 997proc commit_committree {fd_wt curHEAD msg} {
 998        global HEAD PARENT MERGE_HEAD commit_type
 999        global single_commit all_heads current_branch
1000        global ui_status_value ui_comm selected_commit_type
1001        global file_states selected_paths rescan_active
1002
1003        gets $fd_wt tree_id
1004        if {$tree_id eq {} || [catch {close $fd_wt} err]} {
1005                error_popup "write-tree failed:\n\n$err"
1006                set ui_status_value {Commit failed.}
1007                unlock_index
1008                return
1009        }
1010
1011        # -- Create the commit.
1012        #
1013        set cmd [list git commit-tree $tree_id]
1014        set parents [concat $PARENT $MERGE_HEAD]
1015        if {[llength $parents] > 0} {
1016                foreach p $parents {
1017                        lappend cmd -p $p
1018                }
1019        } else {
1020                # git commit-tree writes to stderr during initial commit.
1021                lappend cmd 2>/dev/null
1022        }
1023        lappend cmd << $msg
1024        if {[catch {set cmt_id [eval exec $cmd]} err]} {
1025                error_popup "commit-tree failed:\n\n$err"
1026                set ui_status_value {Commit failed.}
1027                unlock_index
1028                return
1029        }
1030
1031        # -- Update the HEAD ref.
1032        #
1033        set reflogm commit
1034        if {$commit_type ne {normal}} {
1035                append reflogm " ($commit_type)"
1036        }
1037        set i [string first "\n" $msg]
1038        if {$i >= 0} {
1039                append reflogm {: } [string range $msg 0 [expr {$i - 1}]]
1040        } else {
1041                append reflogm {: } $msg
1042        }
1043        set cmd [list git update-ref -m $reflogm HEAD $cmt_id $curHEAD]
1044        if {[catch {eval exec $cmd} err]} {
1045                error_popup "update-ref failed:\n\n$err"
1046                set ui_status_value {Commit failed.}
1047                unlock_index
1048                return
1049        }
1050
1051        # -- Make sure our current branch exists.
1052        #
1053        if {$commit_type eq {initial}} {
1054                lappend all_heads $current_branch
1055                set all_heads [lsort -unique $all_heads]
1056                populate_branch_menu
1057        }
1058
1059        # -- Cleanup after ourselves.
1060        #
1061        catch {file delete [gitdir MERGE_HEAD]}
1062        catch {file delete [gitdir MERGE_MSG]}
1063        catch {file delete [gitdir SQUASH_MSG]}
1064        catch {file delete [gitdir GITGUI_MSG]}
1065
1066        # -- Let rerere do its thing.
1067        #
1068        if {[file isdirectory [gitdir rr-cache]]} {
1069                catch {exec git rerere}
1070        }
1071
1072        # -- Run the post-commit hook.
1073        #
1074        set pchook [gitdir hooks post-commit]
1075        if {[is_Windows] && [file isfile $pchook]} {
1076                set pchook [list sh -c [concat \
1077                        "if test -x \"$pchook\";" \
1078                        "then exec \"$pchook\";" \
1079                        "fi"]]
1080        } elseif {![file executable $pchook]} {
1081                set pchook {}
1082        }
1083        if {$pchook ne {}} {
1084                catch {exec $pchook &}
1085        }
1086
1087        $ui_comm delete 0.0 end
1088        $ui_comm edit reset
1089        $ui_comm edit modified false
1090
1091        if {$single_commit} do_quit
1092
1093        # -- Update in memory status
1094        #
1095        set selected_commit_type new
1096        set commit_type normal
1097        set HEAD $cmt_id
1098        set PARENT $cmt_id
1099        set MERGE_HEAD [list]
1100
1101        foreach path [array names file_states] {
1102                set s $file_states($path)
1103                set m [lindex $s 0]
1104                switch -glob -- $m {
1105                _O -
1106                _M -
1107                _D {continue}
1108                __ -
1109                A_ -
1110                M_ -
1111                D_ {
1112                        unset file_states($path)
1113                        catch {unset selected_paths($path)}
1114                }
1115                DO {
1116                        set file_states($path) [list _O [lindex $s 1] {} {}]
1117                }
1118                AM -
1119                AD -
1120                MM -
1121                MD {
1122                        set file_states($path) [list \
1123                                _[string index $m 1] \
1124                                [lindex $s 1] \
1125                                [lindex $s 3] \
1126                                {}]
1127                }
1128                }
1129        }
1130
1131        display_all_files
1132        unlock_index
1133        reshow_diff
1134        set ui_status_value \
1135                "Changes committed as [string range $cmt_id 0 7]."
1136}
1137
1138######################################################################
1139##
1140## fetch pull push
1141
1142proc fetch_from {remote} {
1143        set w [new_console "fetch $remote" \
1144                "Fetching new changes from $remote"]
1145        set cmd [list git fetch]
1146        lappend cmd $remote
1147        console_exec $w $cmd
1148}
1149
1150proc pull_remote {remote branch} {
1151        global HEAD commit_type file_states repo_config
1152
1153        if {![lock_index update]} return
1154
1155        # -- Our in memory state should match the repository.
1156        #
1157        repository_state curType curHEAD curMERGE_HEAD
1158        if {$commit_type ne $curType || $HEAD ne $curHEAD} {
1159                info_popup {Last scanned state does not match repository state.
1160
1161Another Git program has modified this repository
1162since the last scan.  A rescan must be performed
1163before a pull operation can be started.
1164
1165The rescan will be automatically started now.
1166}
1167                unlock_index
1168                rescan {set ui_status_value {Ready.}}
1169                return
1170        }
1171
1172        # -- No differences should exist before a pull.
1173        #
1174        if {[array size file_states] != 0} {
1175                error_popup {Uncommitted but modified files are present.
1176
1177You should not perform a pull with unmodified
1178files in your working directory as Git will be
1179unable to recover from an incorrect merge.
1180
1181You should commit or revert all changes before
1182starting a pull operation.
1183}
1184                unlock_index
1185                return
1186        }
1187
1188        set w [new_console "pull $remote $branch" \
1189                "Pulling new changes from branch $branch in $remote"]
1190        set cmd [list git pull]
1191        if {$repo_config(gui.pullsummary) eq {false}} {
1192                lappend cmd --no-summary
1193        }
1194        lappend cmd $remote
1195        lappend cmd $branch
1196        console_exec $w $cmd [list post_pull_remote $remote $branch]
1197}
1198
1199proc post_pull_remote {remote branch success} {
1200        global HEAD PARENT MERGE_HEAD commit_type selected_commit_type
1201        global ui_status_value
1202
1203        unlock_index
1204        if {$success} {
1205                repository_state commit_type HEAD MERGE_HEAD
1206                set PARENT $HEAD
1207                set selected_commit_type new
1208                set ui_status_value "Pulling $branch from $remote complete."
1209        } else {
1210                rescan [list set ui_status_value \
1211                        "Conflicts detected while pulling $branch from $remote."]
1212        }
1213}
1214
1215proc push_to {remote} {
1216        set w [new_console "push $remote" \
1217                "Pushing changes to $remote"]
1218        set cmd [list git push]
1219        lappend cmd $remote
1220        console_exec $w $cmd
1221}
1222
1223######################################################################
1224##
1225## ui helpers
1226
1227proc mapicon {w state path} {
1228        global all_icons
1229
1230        if {[catch {set r $all_icons($state$w)}]} {
1231                puts "error: no icon for $w state={$state} $path"
1232                return file_plain
1233        }
1234        return $r
1235}
1236
1237proc mapdesc {state path} {
1238        global all_descs
1239
1240        if {[catch {set r $all_descs($state)}]} {
1241                puts "error: no desc for state={$state} $path"
1242                return $state
1243        }
1244        return $r
1245}
1246
1247proc escape_path {path} {
1248        regsub -all "\n" $path "\\n" path
1249        return $path
1250}
1251
1252proc short_path {path} {
1253        return [escape_path [lindex [file split $path] end]]
1254}
1255
1256set next_icon_id 0
1257set null_sha1 [string repeat 0 40]
1258
1259proc merge_state {path new_state {head_info {}} {index_info {}}} {
1260        global file_states next_icon_id null_sha1
1261
1262        set s0 [string index $new_state 0]
1263        set s1 [string index $new_state 1]
1264
1265        if {[catch {set info $file_states($path)}]} {
1266                set state __
1267                set icon n[incr next_icon_id]
1268        } else {
1269                set state [lindex $info 0]
1270                set icon [lindex $info 1]
1271                if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1272                if {$index_info eq {}} {set index_info [lindex $info 3]}
1273        }
1274
1275        if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1276        elseif {$s0 eq {_}} {set s0 _}
1277
1278        if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1279        elseif {$s1 eq {_}} {set s1 _}
1280
1281        if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1282                set head_info [list 0 $null_sha1]
1283        } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1284                && $head_info eq {}} {
1285                set head_info $index_info
1286        }
1287
1288        set file_states($path) [list $s0$s1 $icon \
1289                $head_info $index_info \
1290                ]
1291        return $state
1292}
1293
1294proc display_file_helper {w path icon_name old_m new_m} {
1295        global file_lists
1296
1297        if {$new_m eq {_}} {
1298                set lno [lsearch -sorted $file_lists($w) $path]
1299                if {$lno >= 0} {
1300                        set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1301                        incr lno
1302                        $w conf -state normal
1303                        $w delete $lno.0 [expr {$lno + 1}].0
1304                        $w conf -state disabled
1305                }
1306        } elseif {$old_m eq {_} && $new_m ne {_}} {
1307                lappend file_lists($w) $path
1308                set file_lists($w) [lsort -unique $file_lists($w)]
1309                set lno [lsearch -sorted $file_lists($w) $path]
1310                incr lno
1311                $w conf -state normal
1312                $w image create $lno.0 \
1313                        -align center -padx 5 -pady 1 \
1314                        -name $icon_name \
1315                        -image [mapicon $w $new_m $path]
1316                $w insert $lno.1 "[escape_path $path]\n"
1317                $w conf -state disabled
1318        } elseif {$old_m ne $new_m} {
1319                $w conf -state normal
1320                $w image conf $icon_name -image [mapicon $w $new_m $path]
1321                $w conf -state disabled
1322        }
1323}
1324
1325proc display_file {path state} {
1326        global file_states selected_paths
1327        global ui_index ui_workdir
1328
1329        set old_m [merge_state $path $state]
1330        set s $file_states($path)
1331        set new_m [lindex $s 0]
1332        set icon_name [lindex $s 1]
1333
1334        set o [string index $old_m 0]
1335        set n [string index $new_m 0]
1336        if {$o eq {U}} {
1337                set o _
1338        }
1339        if {$n eq {U}} {
1340                set n _
1341        }
1342        display_file_helper     $ui_index $path $icon_name $o $n
1343
1344        if {[string index $old_m 0] eq {U}} {
1345                set o U
1346        } else {
1347                set o [string index $old_m 1]
1348        }
1349        if {[string index $new_m 0] eq {U}} {
1350                set n U
1351        } else {
1352                set n [string index $new_m 1]
1353        }
1354        display_file_helper     $ui_workdir $path $icon_name $o $n
1355
1356        if {$new_m eq {__}} {
1357                unset file_states($path)
1358                catch {unset selected_paths($path)}
1359        }
1360}
1361
1362proc display_all_files_helper {w path icon_name m} {
1363        global file_lists
1364
1365        lappend file_lists($w) $path
1366        set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1367        $w image create end \
1368                -align center -padx 5 -pady 1 \
1369                -name $icon_name \
1370                -image [mapicon $w $m $path]
1371        $w insert end "[escape_path $path]\n"
1372}
1373
1374proc display_all_files {} {
1375        global ui_index ui_workdir
1376        global file_states file_lists
1377        global last_clicked
1378
1379        $ui_index conf -state normal
1380        $ui_workdir conf -state normal
1381
1382        $ui_index delete 0.0 end
1383        $ui_workdir delete 0.0 end
1384        set last_clicked {}
1385
1386        set file_lists($ui_index) [list]
1387        set file_lists($ui_workdir) [list]
1388
1389        foreach path [lsort [array names file_states]] {
1390                set s $file_states($path)
1391                set m [lindex $s 0]
1392                set icon_name [lindex $s 1]
1393
1394                set s [string index $m 0]
1395                if {$s ne {U} && $s ne {_}} {
1396                        display_all_files_helper $ui_index $path \
1397                                $icon_name $s
1398                }
1399
1400                if {[string index $m 0] eq {U}} {
1401                        set s U
1402                } else {
1403                        set s [string index $m 1]
1404                }
1405                if {$s ne {_}} {
1406                        display_all_files_helper $ui_workdir $path \
1407                                $icon_name $s
1408                }
1409        }
1410
1411        $ui_index conf -state disabled
1412        $ui_workdir conf -state disabled
1413}
1414
1415proc update_indexinfo {msg pathList after} {
1416        global update_index_cp ui_status_value
1417
1418        if {![lock_index update]} return
1419
1420        set update_index_cp 0
1421        set pathList [lsort $pathList]
1422        set totalCnt [llength $pathList]
1423        set batch [expr {int($totalCnt * .01) + 1}]
1424        if {$batch > 25} {set batch 25}
1425
1426        set ui_status_value [format \
1427                "$msg... %i/%i files (%.2f%%)" \
1428                $update_index_cp \
1429                $totalCnt \
1430                0.0]
1431        set fd [open "| git update-index -z --index-info" w]
1432        fconfigure $fd \
1433                -blocking 0 \
1434                -buffering full \
1435                -buffersize 512 \
1436                -translation binary
1437        fileevent $fd writable [list \
1438                write_update_indexinfo \
1439                $fd \
1440                $pathList \
1441                $totalCnt \
1442                $batch \
1443                $msg \
1444                $after \
1445                ]
1446}
1447
1448proc write_update_indexinfo {fd pathList totalCnt batch msg after} {
1449        global update_index_cp ui_status_value
1450        global file_states current_diff_path
1451
1452        if {$update_index_cp >= $totalCnt} {
1453                close $fd
1454                unlock_index
1455                uplevel #0 $after
1456                return
1457        }
1458
1459        for {set i $batch} \
1460                {$update_index_cp < $totalCnt && $i > 0} \
1461                {incr i -1} {
1462                set path [lindex $pathList $update_index_cp]
1463                incr update_index_cp
1464
1465                set s $file_states($path)
1466                switch -glob -- [lindex $s 0] {
1467                A? {set new _O}
1468                M? {set new _M}
1469                D_ {set new _D}
1470                D? {set new _?}
1471                ?? {continue}
1472                }
1473                set info [lindex $s 2]
1474                if {$info eq {}} continue
1475
1476                puts -nonewline $fd "$info\t$path\0"
1477                display_file $path $new
1478        }
1479
1480        set ui_status_value [format \
1481                "$msg... %i/%i files (%.2f%%)" \
1482                $update_index_cp \
1483                $totalCnt \
1484                [expr {100.0 * $update_index_cp / $totalCnt}]]
1485}
1486
1487proc update_index {msg pathList after} {
1488        global update_index_cp ui_status_value
1489
1490        if {![lock_index update]} return
1491
1492        set update_index_cp 0
1493        set pathList [lsort $pathList]
1494        set totalCnt [llength $pathList]
1495        set batch [expr {int($totalCnt * .01) + 1}]
1496        if {$batch > 25} {set batch 25}
1497
1498        set ui_status_value [format \
1499                "$msg... %i/%i files (%.2f%%)" \
1500                $update_index_cp \
1501                $totalCnt \
1502                0.0]
1503        set fd [open "| git update-index --add --remove -z --stdin" w]
1504        fconfigure $fd \
1505                -blocking 0 \
1506                -buffering full \
1507                -buffersize 512 \
1508                -translation binary
1509        fileevent $fd writable [list \
1510                write_update_index \
1511                $fd \
1512                $pathList \
1513                $totalCnt \
1514                $batch \
1515                $msg \
1516                $after \
1517                ]
1518}
1519
1520proc write_update_index {fd pathList totalCnt batch msg after} {
1521        global update_index_cp ui_status_value
1522        global file_states current_diff_path
1523
1524        if {$update_index_cp >= $totalCnt} {
1525                close $fd
1526                unlock_index
1527                uplevel #0 $after
1528                return
1529        }
1530
1531        for {set i $batch} \
1532                {$update_index_cp < $totalCnt && $i > 0} \
1533                {incr i -1} {
1534                set path [lindex $pathList $update_index_cp]
1535                incr update_index_cp
1536
1537                switch -glob -- [lindex $file_states($path) 0] {
1538                AD {set new __}
1539                ?D {set new D_}
1540                _O -
1541                AM {set new A_}
1542                U? {
1543                        if {[file exists $path]} {
1544                                set new M_
1545                        } else {
1546                                set new D_
1547                        }
1548                }
1549                ?M {set new M_}
1550                ?? {continue}
1551                }
1552                puts -nonewline $fd "$path\0"
1553                display_file $path $new
1554        }
1555
1556        set ui_status_value [format \
1557                "$msg... %i/%i files (%.2f%%)" \
1558                $update_index_cp \
1559                $totalCnt \
1560                [expr {100.0 * $update_index_cp / $totalCnt}]]
1561}
1562
1563proc checkout_index {msg pathList after} {
1564        global update_index_cp ui_status_value
1565
1566        if {![lock_index update]} return
1567
1568        set update_index_cp 0
1569        set pathList [lsort $pathList]
1570        set totalCnt [llength $pathList]
1571        set batch [expr {int($totalCnt * .01) + 1}]
1572        if {$batch > 25} {set batch 25}
1573
1574        set ui_status_value [format \
1575                "$msg... %i/%i files (%.2f%%)" \
1576                $update_index_cp \
1577                $totalCnt \
1578                0.0]
1579        set cmd [list git checkout-index]
1580        lappend cmd --index
1581        lappend cmd --quiet
1582        lappend cmd --force
1583        lappend cmd -z
1584        lappend cmd --stdin
1585        set fd [open "| $cmd " w]
1586        fconfigure $fd \
1587                -blocking 0 \
1588                -buffering full \
1589                -buffersize 512 \
1590                -translation binary
1591        fileevent $fd writable [list \
1592                write_checkout_index \
1593                $fd \
1594                $pathList \
1595                $totalCnt \
1596                $batch \
1597                $msg \
1598                $after \
1599                ]
1600}
1601
1602proc write_checkout_index {fd pathList totalCnt batch msg after} {
1603        global update_index_cp ui_status_value
1604        global file_states current_diff_path
1605
1606        if {$update_index_cp >= $totalCnt} {
1607                close $fd
1608                unlock_index
1609                uplevel #0 $after
1610                return
1611        }
1612
1613        for {set i $batch} \
1614                {$update_index_cp < $totalCnt && $i > 0} \
1615                {incr i -1} {
1616                set path [lindex $pathList $update_index_cp]
1617                incr update_index_cp
1618                switch -glob -- [lindex $file_states($path) 0] {
1619                U? {continue}
1620                ?M -
1621                ?D {
1622                        puts -nonewline $fd "$path\0"
1623                        display_file $path ?_
1624                }
1625                }
1626        }
1627
1628        set ui_status_value [format \
1629                "$msg... %i/%i files (%.2f%%)" \
1630                $update_index_cp \
1631                $totalCnt \
1632                [expr {100.0 * $update_index_cp / $totalCnt}]]
1633}
1634
1635######################################################################
1636##
1637## branch management
1638
1639proc is_tracking_branch {name} {
1640        global tracking_branches
1641
1642        if {![catch {set info $tracking_branches($name)}]} {
1643                return 1
1644        }
1645        foreach t [array names tracking_branches] {
1646                if {[string match {*/\*} $t] && [string match $t $name]} {
1647                        return 1
1648                }
1649        }
1650        return 0
1651}
1652
1653proc load_all_heads {} {
1654        global all_heads
1655
1656        set all_heads [list]
1657        set fd [open "| git for-each-ref --format=%(refname) refs/heads" r]
1658        while {[gets $fd line] > 0} {
1659                if {[is_tracking_branch $line]} continue
1660                if {![regsub ^refs/heads/ $line {} name]} continue
1661                lappend all_heads $name
1662        }
1663        close $fd
1664
1665        set all_heads [lsort $all_heads]
1666}
1667
1668proc populate_branch_menu {} {
1669        global all_heads disable_on_lock
1670
1671        set m .mbar.branch
1672        set last [$m index last]
1673        for {set i 0} {$i <= $last} {incr i} {
1674                if {[$m type $i] eq {separator}} {
1675                        $m delete $i last
1676                        set new_dol [list]
1677                        foreach a $disable_on_lock {
1678                                if {[lindex $a 0] ne $m || [lindex $a 2] < $i} {
1679                                        lappend new_dol $a
1680                                }
1681                        }
1682                        set disable_on_lock $new_dol
1683                        break
1684                }
1685        }
1686
1687        $m add separator
1688        foreach b $all_heads {
1689                $m add radiobutton \
1690                        -label $b \
1691                        -command [list switch_branch $b] \
1692                        -variable current_branch \
1693                        -value $b \
1694                        -font font_ui
1695                lappend disable_on_lock \
1696                        [list $m entryconf [$m index last] -state]
1697        }
1698}
1699
1700proc all_tracking_branches {} {
1701        global tracking_branches
1702
1703        set all_trackings {}
1704        set cmd {}
1705        foreach name [array names tracking_branches] {
1706                if {[regsub {/\*$} $name {} name]} {
1707                        lappend cmd $name
1708                } else {
1709                        regsub ^refs/(heads|remotes)/ $name {} name
1710                        lappend all_trackings $name
1711                }
1712        }
1713
1714        if {$cmd ne {}} {
1715                set fd [open "| git for-each-ref --format=%(refname) $cmd" r]
1716                while {[gets $fd name] > 0} {
1717                        regsub ^refs/(heads|remotes)/ $name {} name
1718                        lappend all_trackings $name
1719                }
1720                close $fd
1721        }
1722
1723        return [lsort -unique $all_trackings]
1724}
1725
1726proc do_create_branch_action {w} {
1727        global all_heads null_sha1 repo_config
1728        global create_branch_checkout create_branch_revtype
1729        global create_branch_head create_branch_trackinghead
1730
1731        set newbranch [string trim [$w.desc.name_t get 0.0 end]]
1732        if {$newbranch eq {}
1733                || $newbranch eq $repo_config(gui.newbranchtemplate)} {
1734                tk_messageBox \
1735                        -icon error \
1736                        -type ok \
1737                        -title [wm title $w] \
1738                        -parent $w \
1739                        -message "Please supply a branch name."
1740                focus $w.desc.name_t
1741                return
1742        }
1743        if {![catch {exec git show-ref --verify -- "refs/heads/$newbranch"}]} {
1744                tk_messageBox \
1745                        -icon error \
1746                        -type ok \
1747                        -title [wm title $w] \
1748                        -parent $w \
1749                        -message "Branch '$newbranch' already exists."
1750                focus $w.desc.name_t
1751                return
1752        }
1753        if {[catch {exec git check-ref-format "heads/$newbranch"}]} {
1754                tk_messageBox \
1755                        -icon error \
1756                        -type ok \
1757                        -title [wm title $w] \
1758                        -parent $w \
1759                        -message "We do not like '$newbranch' as a branch name."
1760                focus $w.desc.name_t
1761                return
1762        }
1763
1764        set rev {}
1765        switch -- $create_branch_revtype {
1766        head {set rev $create_branch_head}
1767        tracking {set rev $create_branch_trackinghead}
1768        expression {set rev [string trim [$w.from.exp_t get 0.0 end]]}
1769        }
1770        if {[catch {set cmt [exec git rev-parse --verify "${rev}^0"]}]} {
1771                tk_messageBox \
1772                        -icon error \
1773                        -type ok \
1774                        -title [wm title $w] \
1775                        -parent $w \
1776                        -message "Invalid starting revision: $rev"
1777                return
1778        }
1779        set cmd [list git update-ref]
1780        lappend cmd -m
1781        lappend cmd "branch: Created from $rev"
1782        lappend cmd "refs/heads/$newbranch"
1783        lappend cmd $cmt
1784        lappend cmd $null_sha1
1785        if {[catch {eval exec $cmd} err]} {
1786                tk_messageBox \
1787                        -icon error \
1788                        -type ok \
1789                        -title [wm title $w] \
1790                        -parent $w \
1791                        -message "Failed to create '$newbranch'.\n\n$err"
1792                return
1793        }
1794
1795        lappend all_heads $newbranch
1796        set all_heads [lsort $all_heads]
1797        populate_branch_menu
1798        destroy $w
1799        if {$create_branch_checkout} {
1800                switch_branch $newbranch
1801        }
1802}
1803
1804proc radio_selector {varname value args} {
1805        upvar #0 $varname var
1806        set var $value
1807}
1808
1809trace add variable create_branch_head write \
1810        [list radio_selector create_branch_revtype head]
1811trace add variable create_branch_trackinghead write \
1812        [list radio_selector create_branch_revtype tracking]
1813
1814trace add variable delete_branch_head write \
1815        [list radio_selector delete_branch_checktype head]
1816trace add variable delete_branch_trackinghead write \
1817        [list radio_selector delete_branch_checktype tracking]
1818
1819proc do_create_branch {} {
1820        global all_heads current_branch repo_config
1821        global create_branch_checkout create_branch_revtype
1822        global create_branch_head create_branch_trackinghead
1823
1824        set w .branch_editor
1825        toplevel $w
1826        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
1827
1828        label $w.header -text {Create New Branch} \
1829                -font font_uibold
1830        pack $w.header -side top -fill x
1831
1832        frame $w.buttons
1833        button $w.buttons.create -text Create \
1834                -font font_ui \
1835                -default active \
1836                -command [list do_create_branch_action $w]
1837        pack $w.buttons.create -side right
1838        button $w.buttons.cancel -text {Cancel} \
1839                -font font_ui \
1840                -command [list destroy $w]
1841        pack $w.buttons.cancel -side right -padx 5
1842        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
1843
1844        labelframe $w.desc \
1845                -text {Branch Description} \
1846                -font font_ui
1847        label $w.desc.name_l -text {Name:} -font font_ui
1848        text $w.desc.name_t \
1849                -borderwidth 1 \
1850                -relief sunken \
1851                -height 1 \
1852                -width 40 \
1853                -font font_ui
1854        $w.desc.name_t insert 0.0 $repo_config(gui.newbranchtemplate)
1855        grid $w.desc.name_l $w.desc.name_t -stick we -padx {0 5}
1856        bind $w.desc.name_t <Shift-Key-Tab> {focus [tk_focusPrev %W];break}
1857        bind $w.desc.name_t <Key-Tab> {focus [tk_focusNext %W];break}
1858        bind $w.desc.name_t <Key-Return> "do_create_branch_action $w;break"
1859        bind $w.desc.name_t <Key> {
1860                if {{%K} ne {BackSpace}
1861                        && {%K} ne {Tab}
1862                        && {%K} ne {Escape}
1863                        && {%K} ne {Return}} {
1864                        if {%k <= 32} break
1865                        if {[string first %A {~^:?*[}] >= 0} break
1866                }
1867        }
1868        grid columnconfigure $w.desc 1 -weight 1
1869        pack $w.desc -anchor nw -fill x -pady 5 -padx 5
1870
1871        labelframe $w.from \
1872                -text {Starting Revision} \
1873                -font font_ui
1874        radiobutton $w.from.head_r \
1875                -text {Local Branch:} \
1876                -value head \
1877                -variable create_branch_revtype \
1878                -font font_ui
1879        eval tk_optionMenu $w.from.head_m create_branch_head $all_heads
1880        grid $w.from.head_r $w.from.head_m -sticky w
1881        set all_trackings [all_tracking_branches]
1882        if {$all_trackings ne {}} {
1883                set create_branch_trackinghead [lindex $all_trackings 0]
1884                radiobutton $w.from.tracking_r \
1885                        -text {Tracking Branch:} \
1886                        -value tracking \
1887                        -variable create_branch_revtype \
1888                        -font font_ui
1889                eval tk_optionMenu $w.from.tracking_m \
1890                        create_branch_trackinghead \
1891                        $all_trackings
1892                grid $w.from.tracking_r $w.from.tracking_m -sticky w
1893        }
1894        radiobutton $w.from.exp_r \
1895                -text {Revision Expression:} \
1896                -value expression \
1897                -variable create_branch_revtype \
1898                -font font_ui
1899        text $w.from.exp_t \
1900                -borderwidth 1 \
1901                -relief sunken \
1902                -height 1 \
1903                -width 50 \
1904                -font font_ui
1905        grid $w.from.exp_r $w.from.exp_t -stick we -padx {0 5}
1906        bind $w.from.exp_t <Shift-Key-Tab> {focus [tk_focusPrev %W];break}
1907        bind $w.from.exp_t <Key-Tab> {focus [tk_focusNext %W];break}
1908        bind $w.from.exp_t <Key-Return> "do_create_branch_action $w;break"
1909        bind $w.from.exp_t <Key-space> break
1910        bind $w.from.exp_t <Key> {set create_branch_revtype expression}
1911        grid columnconfigure $w.from 1 -weight 1
1912        pack $w.from -anchor nw -fill x -pady 5 -padx 5
1913
1914        labelframe $w.postActions \
1915                -text {Post Creation Actions} \
1916                -font font_ui
1917        checkbutton $w.postActions.checkout \
1918                -text {Checkout after creation} \
1919                -variable create_branch_checkout \
1920                -font font_ui
1921        pack $w.postActions.checkout -anchor nw
1922        pack $w.postActions -anchor nw -fill x -pady 5 -padx 5
1923
1924        set create_branch_checkout 1
1925        set create_branch_head $current_branch
1926        set create_branch_revtype head
1927
1928        bind $w <Visibility> "grab $w; focus $w.desc.name_t"
1929        bind $w <Key-Escape> "destroy $w"
1930        bind $w <Key-Return> "do_create_branch_action $w;break"
1931        wm title $w "[appname] ([reponame]): Create Branch"
1932        tkwait window $w
1933}
1934
1935proc do_delete_branch_action {w} {
1936        global all_heads
1937        global delete_branch_checktype delete_branch_head delete_branch_trackinghead
1938
1939        set check_rev {}
1940        switch -- $delete_branch_checktype {
1941        head {set check_rev $delete_branch_head}
1942        tracking {set check_rev $delete_branch_trackinghead}
1943        always {set check_rev {:none}}
1944        }
1945        if {$check_rev eq {:none}} {
1946                set check_cmt {}
1947        } elseif {[catch {set check_cmt [exec git rev-parse --verify "${check_rev}^0"]}]} {
1948                tk_messageBox \
1949                        -icon error \
1950                        -type ok \
1951                        -title [wm title $w] \
1952                        -parent $w \
1953                        -message "Invalid check revision: $check_rev"
1954                return
1955        }
1956
1957        set to_delete [list]
1958        set not_merged [list]
1959        foreach i [$w.list.l curselection] {
1960                set b [$w.list.l get $i]
1961                if {[catch {set o [exec git rev-parse --verify $b]}]} continue
1962                if {$check_cmt ne {}} {
1963                        if {$b eq $check_rev} continue
1964                        if {[catch {set m [exec git merge-base $o $check_cmt]}]} continue
1965                        if {$o ne $m} {
1966                                lappend not_merged $b
1967                                continue
1968                        }
1969                }
1970                lappend to_delete [list $b $o]
1971        }
1972        if {$not_merged ne {}} {
1973                set msg "The following branches are not completely merged into $check_rev:
1974
1975 - [join $not_merged "\n - "]"
1976                tk_messageBox \
1977                        -icon info \
1978                        -type ok \
1979                        -title [wm title $w] \
1980                        -parent $w \
1981                        -message $msg
1982        }
1983        if {$to_delete eq {}} return
1984        if {$delete_branch_checktype eq {always}} {
1985                set msg {Recovering deleted branches is difficult.
1986
1987Delete the selected branches?}
1988                if {[tk_messageBox \
1989                        -icon warning \
1990                        -type yesno \
1991                        -title [wm title $w] \
1992                        -parent $w \
1993                        -message $msg] ne yes} {
1994                        return
1995                }
1996        }
1997
1998        set failed {}
1999        foreach i $to_delete {
2000                set b [lindex $i 0]
2001                set o [lindex $i 1]
2002                if {[catch {exec git update-ref -d "refs/heads/$b" $o} err]} {
2003                        append failed " - $b: $err\n"
2004                } else {
2005                        set x [lsearch -sorted $all_heads $b]
2006                        if {$x >= 0} {
2007                                set all_heads [lreplace $all_heads $x $x]
2008                        }
2009                }
2010        }
2011
2012        if {$failed ne {}} {
2013                tk_messageBox \
2014                        -icon error \
2015                        -type ok \
2016                        -title [wm title $w] \
2017                        -parent $w \
2018                        -message "Failed to delete branches:\n$failed"
2019        }
2020
2021        set all_heads [lsort $all_heads]
2022        populate_branch_menu
2023        destroy $w
2024}
2025
2026proc do_delete_branch {} {
2027        global all_heads tracking_branches current_branch
2028        global delete_branch_checktype delete_branch_head delete_branch_trackinghead
2029
2030        set w .branch_editor
2031        toplevel $w
2032        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2033
2034        label $w.header -text {Delete Local Branch} \
2035                -font font_uibold
2036        pack $w.header -side top -fill x
2037
2038        frame $w.buttons
2039        button $w.buttons.create -text Delete \
2040                -font font_ui \
2041                -command [list do_delete_branch_action $w]
2042        pack $w.buttons.create -side right
2043        button $w.buttons.cancel -text {Cancel} \
2044                -font font_ui \
2045                -command [list destroy $w]
2046        pack $w.buttons.cancel -side right -padx 5
2047        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2048
2049        labelframe $w.list \
2050                -text {Local Branches} \
2051                -font font_ui
2052        listbox $w.list.l \
2053                -height 10 \
2054                -width 50 \
2055                -selectmode extended \
2056                -font font_ui
2057        foreach h $all_heads {
2058                if {$h ne $current_branch} {
2059                        $w.list.l insert end $h
2060                }
2061        }
2062        pack $w.list.l -fill both -pady 5 -padx 5
2063        pack $w.list -fill both -pady 5 -padx 5
2064
2065        labelframe $w.validate \
2066                -text {Delete Only If} \
2067                -font font_ui
2068        radiobutton $w.validate.head_r \
2069                -text {Merged Into Local Branch:} \
2070                -value head \
2071                -variable delete_branch_checktype \
2072                -font font_ui
2073        eval tk_optionMenu $w.validate.head_m delete_branch_head $all_heads
2074        grid $w.validate.head_r $w.validate.head_m -sticky w
2075        set all_trackings [all_tracking_branches]
2076        if {$all_trackings ne {}} {
2077                set delete_branch_trackinghead [lindex $all_trackings 0]
2078                radiobutton $w.validate.tracking_r \
2079                        -text {Merged Into Tracking Branch:} \
2080                        -value tracking \
2081                        -variable delete_branch_checktype \
2082                        -font font_ui
2083                eval tk_optionMenu $w.validate.tracking_m \
2084                        delete_branch_trackinghead \
2085                        $all_trackings
2086                grid $w.validate.tracking_r $w.validate.tracking_m -sticky w
2087        }
2088        radiobutton $w.validate.always_r \
2089                -text {Always (Do not perform merge checks)} \
2090                -value always \
2091                -variable delete_branch_checktype \
2092                -font font_ui
2093        grid $w.validate.always_r -columnspan 2 -sticky w
2094        grid columnconfigure $w.validate 1 -weight 1
2095        pack $w.validate -anchor nw -fill x -pady 5 -padx 5
2096
2097        set delete_branch_head $current_branch
2098        set delete_branch_checktype head
2099
2100        bind $w <Visibility> "grab $w; focus $w"
2101        bind $w <Key-Escape> "destroy $w"
2102        wm title $w "[appname] ([reponame]): Delete Branch"
2103        tkwait window $w
2104}
2105
2106proc switch_branch {b} {
2107        global HEAD commit_type file_states current_branch
2108        global selected_commit_type ui_comm
2109
2110        if {![lock_index switch]} return
2111
2112        # -- Backup the selected branch (repository_state resets it)
2113        #
2114        set new_branch $current_branch
2115
2116        # -- Our in memory state should match the repository.
2117        #
2118        repository_state curType curHEAD curMERGE_HEAD
2119        if {[string match amend* $commit_type]
2120                && $curType eq {normal}
2121                && $curHEAD eq $HEAD} {
2122        } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
2123                info_popup {Last scanned state does not match repository state.
2124
2125Another Git program has modified this repository
2126since the last scan.  A rescan must be performed
2127before the current branch can be changed.
2128
2129The rescan will be automatically started now.
2130}
2131                unlock_index
2132                rescan {set ui_status_value {Ready.}}
2133                return
2134        }
2135
2136        # -- Toss the message buffer if we are in amend mode.
2137        #
2138        if {[string match amend* $curType]} {
2139                $ui_comm delete 0.0 end
2140                $ui_comm edit reset
2141                $ui_comm edit modified false
2142        }
2143
2144        set selected_commit_type new
2145        set current_branch $new_branch
2146
2147        unlock_index
2148        error "NOT FINISHED"
2149}
2150
2151######################################################################
2152##
2153## remote management
2154
2155proc load_all_remotes {} {
2156        global repo_config
2157        global all_remotes tracking_branches
2158
2159        set all_remotes [list]
2160        array unset tracking_branches
2161
2162        set rm_dir [gitdir remotes]
2163        if {[file isdirectory $rm_dir]} {
2164                set all_remotes [glob \
2165                        -types f \
2166                        -tails \
2167                        -nocomplain \
2168                        -directory $rm_dir *]
2169
2170                foreach name $all_remotes {
2171                        catch {
2172                                set fd [open [file join $rm_dir $name] r]
2173                                while {[gets $fd line] >= 0} {
2174                                        if {![regexp {^Pull:[   ]*([^:]+):(.+)$} \
2175                                                $line line src dst]} continue
2176                                        if {![regexp ^refs/ $dst]} {
2177                                                set dst "refs/heads/$dst"
2178                                        }
2179                                        set tracking_branches($dst) [list $name $src]
2180                                }
2181                                close $fd
2182                        }
2183                }
2184        }
2185
2186        foreach line [array names repo_config remote.*.url] {
2187                if {![regexp ^remote\.(.*)\.url\$ $line line name]} continue
2188                lappend all_remotes $name
2189
2190                if {[catch {set fl $repo_config(remote.$name.fetch)}]} {
2191                        set fl {}
2192                }
2193                foreach line $fl {
2194                        if {![regexp {^([^:]+):(.+)$} $line line src dst]} continue
2195                        if {![regexp ^refs/ $dst]} {
2196                                set dst "refs/heads/$dst"
2197                        }
2198                        set tracking_branches($dst) [list $name $src]
2199                }
2200        }
2201
2202        set all_remotes [lsort -unique $all_remotes]
2203}
2204
2205proc populate_fetch_menu {m} {
2206        global all_remotes repo_config
2207
2208        foreach r $all_remotes {
2209                set enable 0
2210                if {![catch {set a $repo_config(remote.$r.url)}]} {
2211                        if {![catch {set a $repo_config(remote.$r.fetch)}]} {
2212                                set enable 1
2213                        }
2214                } else {
2215                        catch {
2216                                set fd [open [gitdir remotes $r] r]
2217                                while {[gets $fd n] >= 0} {
2218                                        if {[regexp {^Pull:[ \t]*([^:]+):} $n]} {
2219                                                set enable 1
2220                                                break
2221                                        }
2222                                }
2223                                close $fd
2224                        }
2225                }
2226
2227                if {$enable} {
2228                        $m add command \
2229                                -label "Fetch from $r..." \
2230                                -command [list fetch_from $r] \
2231                                -font font_ui
2232                }
2233        }
2234}
2235
2236proc populate_push_menu {m} {
2237        global all_remotes repo_config
2238
2239        foreach r $all_remotes {
2240                set enable 0
2241                if {![catch {set a $repo_config(remote.$r.url)}]} {
2242                        if {![catch {set a $repo_config(remote.$r.push)}]} {
2243                                set enable 1
2244                        }
2245                } else {
2246                        catch {
2247                                set fd [open [gitdir remotes $r] r]
2248                                while {[gets $fd n] >= 0} {
2249                                        if {[regexp {^Push:[ \t]*([^:]+):} $n]} {
2250                                                set enable 1
2251                                                break
2252                                        }
2253                                }
2254                                close $fd
2255                        }
2256                }
2257
2258                if {$enable} {
2259                        $m add command \
2260                                -label "Push to $r..." \
2261                                -command [list push_to $r] \
2262                                -font font_ui
2263                }
2264        }
2265}
2266
2267proc populate_pull_menu {m} {
2268        global repo_config all_remotes disable_on_lock
2269
2270        foreach remote $all_remotes {
2271                set rb_list [list]
2272                if {[array get repo_config remote.$remote.url] ne {}} {
2273                        if {[array get repo_config remote.$remote.fetch] ne {}} {
2274                                foreach line $repo_config(remote.$remote.fetch) {
2275                                        if {[regexp {^([^:]+):} $line line rb]} {
2276                                                lappend rb_list $rb
2277                                        }
2278                                }
2279                        }
2280                } else {
2281                        catch {
2282                                set fd [open [gitdir remotes $remote] r]
2283                                while {[gets $fd line] >= 0} {
2284                                        if {[regexp {^Pull:[ \t]*([^:]+):} $line line rb]} {
2285                                                lappend rb_list $rb
2286                                        }
2287                                }
2288                                close $fd
2289                        }
2290                }
2291
2292                foreach rb $rb_list {
2293                        regsub ^refs/heads/ $rb {} rb_short
2294                        $m add command \
2295                                -label "Branch $rb_short from $remote..." \
2296                                -command [list pull_remote $remote $rb] \
2297                                -font font_ui
2298                        lappend disable_on_lock \
2299                                [list $m entryconf [$m index last] -state]
2300                }
2301        }
2302}
2303
2304######################################################################
2305##
2306## icons
2307
2308set filemask {
2309#define mask_width 14
2310#define mask_height 15
2311static unsigned char mask_bits[] = {
2312   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2313   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2314   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
2315}
2316
2317image create bitmap file_plain -background white -foreground black -data {
2318#define plain_width 14
2319#define plain_height 15
2320static unsigned char plain_bits[] = {
2321   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2322   0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
2323   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2324} -maskdata $filemask
2325
2326image create bitmap file_mod -background white -foreground blue -data {
2327#define mod_width 14
2328#define mod_height 15
2329static unsigned char mod_bits[] = {
2330   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
2331   0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2332   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2333} -maskdata $filemask
2334
2335image create bitmap file_fulltick -background white -foreground "#007000" -data {
2336#define file_fulltick_width 14
2337#define file_fulltick_height 15
2338static unsigned char file_fulltick_bits[] = {
2339   0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
2340   0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
2341   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2342} -maskdata $filemask
2343
2344image create bitmap file_parttick -background white -foreground "#005050" -data {
2345#define parttick_width 14
2346#define parttick_height 15
2347static unsigned char parttick_bits[] = {
2348   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
2349   0x7a, 0x14, 0x02, 0x16, 0x02, 0x13, 0x8a, 0x11, 0xda, 0x10, 0x72, 0x10,
2350   0x22, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2351} -maskdata $filemask
2352
2353image create bitmap file_question -background white -foreground black -data {
2354#define file_question_width 14
2355#define file_question_height 15
2356static unsigned char file_question_bits[] = {
2357   0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
2358   0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
2359   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2360} -maskdata $filemask
2361
2362image create bitmap file_removed -background white -foreground red -data {
2363#define file_removed_width 14
2364#define file_removed_height 15
2365static unsigned char file_removed_bits[] = {
2366   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2367   0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
2368   0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
2369} -maskdata $filemask
2370
2371image create bitmap file_merge -background white -foreground blue -data {
2372#define file_merge_width 14
2373#define file_merge_height 15
2374static unsigned char file_merge_bits[] = {
2375   0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
2376   0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2377   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2378} -maskdata $filemask
2379
2380set ui_index .vpane.files.index.list
2381set ui_workdir .vpane.files.workdir.list
2382
2383set all_icons(_$ui_index)   file_plain
2384set all_icons(A$ui_index)   file_fulltick
2385set all_icons(M$ui_index)   file_fulltick
2386set all_icons(D$ui_index)   file_removed
2387set all_icons(U$ui_index)   file_merge
2388
2389set all_icons(_$ui_workdir) file_plain
2390set all_icons(M$ui_workdir) file_mod
2391set all_icons(D$ui_workdir) file_question
2392set all_icons(U$ui_workdir) file_merge
2393set all_icons(O$ui_workdir) file_plain
2394
2395set max_status_desc 0
2396foreach i {
2397                {__ "Unmodified"}
2398
2399                {_M "Modified, not staged"}
2400                {M_ "Staged for commit"}
2401                {MM "Portions staged for commit"}
2402                {MD "Staged for commit, missing"}
2403
2404                {_O "Untracked, not staged"}
2405                {A_ "Staged for commit"}
2406                {AM "Portions staged for commit"}
2407                {AD "Staged for commit, missing"}
2408
2409                {_D "Missing"}
2410                {D_ "Staged for removal"}
2411                {DO "Staged for removal, still present"}
2412
2413                {U_ "Requires merge resolution"}
2414                {UU "Requires merge resolution"}
2415                {UM "Requires merge resolution"}
2416                {UD "Requires merge resolution"}
2417        } {
2418        if {$max_status_desc < [string length [lindex $i 1]]} {
2419                set max_status_desc [string length [lindex $i 1]]
2420        }
2421        set all_descs([lindex $i 0]) [lindex $i 1]
2422}
2423unset i
2424
2425######################################################################
2426##
2427## util
2428
2429proc is_MacOSX {} {
2430        global tcl_platform tk_library
2431        if {[tk windowingsystem] eq {aqua}} {
2432                return 1
2433        }
2434        return 0
2435}
2436
2437proc is_Windows {} {
2438        global tcl_platform
2439        if {$tcl_platform(platform) eq {windows}} {
2440                return 1
2441        }
2442        return 0
2443}
2444
2445proc bind_button3 {w cmd} {
2446        bind $w <Any-Button-3> $cmd
2447        if {[is_MacOSX]} {
2448                bind $w <Control-Button-1> $cmd
2449        }
2450}
2451
2452proc incr_font_size {font {amt 1}} {
2453        set sz [font configure $font -size]
2454        incr sz $amt
2455        font configure $font -size $sz
2456        font configure ${font}bold -size $sz
2457}
2458
2459proc hook_failed_popup {hook msg} {
2460        set w .hookfail
2461        toplevel $w
2462
2463        frame $w.m
2464        label $w.m.l1 -text "$hook hook failed:" \
2465                -anchor w \
2466                -justify left \
2467                -font font_uibold
2468        text $w.m.t \
2469                -background white -borderwidth 1 \
2470                -relief sunken \
2471                -width 80 -height 10 \
2472                -font font_diff \
2473                -yscrollcommand [list $w.m.sby set]
2474        label $w.m.l2 \
2475                -text {You must correct the above errors before committing.} \
2476                -anchor w \
2477                -justify left \
2478                -font font_uibold
2479        scrollbar $w.m.sby -command [list $w.m.t yview]
2480        pack $w.m.l1 -side top -fill x
2481        pack $w.m.l2 -side bottom -fill x
2482        pack $w.m.sby -side right -fill y
2483        pack $w.m.t -side left -fill both -expand 1
2484        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
2485
2486        $w.m.t insert 1.0 $msg
2487        $w.m.t conf -state disabled
2488
2489        button $w.ok -text OK \
2490                -width 15 \
2491                -font font_ui \
2492                -command "destroy $w"
2493        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
2494
2495        bind $w <Visibility> "grab $w; focus $w"
2496        bind $w <Key-Return> "destroy $w"
2497        wm title $w "[appname] ([reponame]): error"
2498        tkwait window $w
2499}
2500
2501set next_console_id 0
2502
2503proc new_console {short_title long_title} {
2504        global next_console_id console_data
2505        set w .console[incr next_console_id]
2506        set console_data($w) [list $short_title $long_title]
2507        return [console_init $w]
2508}
2509
2510proc console_init {w} {
2511        global console_cr console_data M1B
2512
2513        set console_cr($w) 1.0
2514        toplevel $w
2515        frame $w.m
2516        label $w.m.l1 -text "[lindex $console_data($w) 1]:" \
2517                -anchor w \
2518                -justify left \
2519                -font font_uibold
2520        text $w.m.t \
2521                -background white -borderwidth 1 \
2522                -relief sunken \
2523                -width 80 -height 10 \
2524                -font font_diff \
2525                -state disabled \
2526                -yscrollcommand [list $w.m.sby set]
2527        label $w.m.s -text {Working... please wait...} \
2528                -anchor w \
2529                -justify left \
2530                -font font_uibold
2531        scrollbar $w.m.sby -command [list $w.m.t yview]
2532        pack $w.m.l1 -side top -fill x
2533        pack $w.m.s -side bottom -fill x
2534        pack $w.m.sby -side right -fill y
2535        pack $w.m.t -side left -fill both -expand 1
2536        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
2537
2538        menu $w.ctxm -tearoff 0
2539        $w.ctxm add command -label "Copy" \
2540                -font font_ui \
2541                -command "tk_textCopy $w.m.t"
2542        $w.ctxm add command -label "Select All" \
2543                -font font_ui \
2544                -command "focus $w.m.t;$w.m.t tag add sel 0.0 end"
2545        $w.ctxm add command -label "Copy All" \
2546                -font font_ui \
2547                -command "
2548                        $w.m.t tag add sel 0.0 end
2549                        tk_textCopy $w.m.t
2550                        $w.m.t tag remove sel 0.0 end
2551                "
2552
2553        button $w.ok -text {Close} \
2554                -font font_ui \
2555                -state disabled \
2556                -command "destroy $w"
2557        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
2558
2559        bind_button3 $w.m.t "tk_popup $w.ctxm %X %Y"
2560        bind $w.m.t <$M1B-Key-a> "$w.m.t tag add sel 0.0 end;break"
2561        bind $w.m.t <$M1B-Key-A> "$w.m.t tag add sel 0.0 end;break"
2562        bind $w <Visibility> "focus $w"
2563        wm title $w "[appname] ([reponame]): [lindex $console_data($w) 0]"
2564        return $w
2565}
2566
2567proc console_exec {w cmd {after {}}} {
2568        # -- Windows tosses the enviroment when we exec our child.
2569        #    But most users need that so we have to relogin. :-(
2570        #
2571        if {[is_Windows]} {
2572                set cmd [list sh --login -c "cd \"[pwd]\" && [join $cmd { }]"]
2573        }
2574
2575        # -- Tcl won't let us redirect both stdout and stderr to
2576        #    the same pipe.  So pass it through cat...
2577        #
2578        set cmd [concat | $cmd |& cat]
2579
2580        set fd_f [open $cmd r]
2581        fconfigure $fd_f -blocking 0 -translation binary
2582        fileevent $fd_f readable [list console_read $w $fd_f $after]
2583}
2584
2585proc console_read {w fd after} {
2586        global console_cr console_data
2587
2588        set buf [read $fd]
2589        if {$buf ne {}} {
2590                if {![winfo exists $w]} {console_init $w}
2591                $w.m.t conf -state normal
2592                set c 0
2593                set n [string length $buf]
2594                while {$c < $n} {
2595                        set cr [string first "\r" $buf $c]
2596                        set lf [string first "\n" $buf $c]
2597                        if {$cr < 0} {set cr [expr {$n + 1}]}
2598                        if {$lf < 0} {set lf [expr {$n + 1}]}
2599
2600                        if {$lf < $cr} {
2601                                $w.m.t insert end [string range $buf $c $lf]
2602                                set console_cr($w) [$w.m.t index {end -1c}]
2603                                set c $lf
2604                                incr c
2605                        } else {
2606                                $w.m.t delete $console_cr($w) end
2607                                $w.m.t insert end "\n"
2608                                $w.m.t insert end [string range $buf $c $cr]
2609                                set c $cr
2610                                incr c
2611                        }
2612                }
2613                $w.m.t conf -state disabled
2614                $w.m.t see end
2615        }
2616
2617        fconfigure $fd -blocking 1
2618        if {[eof $fd]} {
2619                if {[catch {close $fd}]} {
2620                        if {![winfo exists $w]} {console_init $w}
2621                        $w.m.s conf -background red -text {Error: Command Failed}
2622                        $w.ok conf -state normal
2623                        set ok 0
2624                } elseif {[winfo exists $w]} {
2625                        $w.m.s conf -background green -text {Success}
2626                        $w.ok conf -state normal
2627                        set ok 1
2628                }
2629                array unset console_cr $w
2630                array unset console_data $w
2631                if {$after ne {}} {
2632                        uplevel #0 $after $ok
2633                }
2634                return
2635        }
2636        fconfigure $fd -blocking 0
2637}
2638
2639######################################################################
2640##
2641## ui commands
2642
2643set starting_gitk_msg {Starting gitk... please wait...}
2644
2645proc do_gitk {revs} {
2646        global ui_status_value starting_gitk_msg
2647
2648        set cmd gitk
2649        if {$revs ne {}} {
2650                append cmd { }
2651                append cmd $revs
2652        }
2653        if {[is_Windows]} {
2654                set cmd "sh -c \"exec $cmd\""
2655        }
2656        append cmd { &}
2657
2658        if {[catch {eval exec $cmd} err]} {
2659                error_popup "Failed to start gitk:\n\n$err"
2660        } else {
2661                set ui_status_value $starting_gitk_msg
2662                after 10000 {
2663                        if {$ui_status_value eq $starting_gitk_msg} {
2664                                set ui_status_value {Ready.}
2665                        }
2666                }
2667        }
2668}
2669
2670proc do_gc {} {
2671        set w [new_console {gc} {Compressing the object database}]
2672        console_exec $w {git gc}
2673}
2674
2675proc do_fsck_objects {} {
2676        set w [new_console {fsck-objects} \
2677                {Verifying the object database with fsck-objects}]
2678        set cmd [list git fsck-objects]
2679        lappend cmd --full
2680        lappend cmd --cache
2681        lappend cmd --strict
2682        console_exec $w $cmd
2683}
2684
2685set is_quitting 0
2686
2687proc do_quit {} {
2688        global ui_comm is_quitting repo_config commit_type
2689
2690        if {$is_quitting} return
2691        set is_quitting 1
2692
2693        # -- Stash our current commit buffer.
2694        #
2695        set save [gitdir GITGUI_MSG]
2696        set msg [string trim [$ui_comm get 0.0 end]]
2697        if {![string match amend* $commit_type]
2698                && [$ui_comm edit modified]
2699                && $msg ne {}} {
2700                catch {
2701                        set fd [open $save w]
2702                        puts $fd [string trim [$ui_comm get 0.0 end]]
2703                        close $fd
2704                }
2705        } else {
2706                catch {file delete $save}
2707        }
2708
2709        # -- Stash our current window geometry into this repository.
2710        #
2711        set cfg_geometry [list]
2712        lappend cfg_geometry [wm geometry .]
2713        lappend cfg_geometry [lindex [.vpane sash coord 0] 1]
2714        lappend cfg_geometry [lindex [.vpane.files sash coord 0] 0]
2715        if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
2716                set rc_geometry {}
2717        }
2718        if {$cfg_geometry ne $rc_geometry} {
2719                catch {exec git repo-config gui.geometry $cfg_geometry}
2720        }
2721
2722        destroy .
2723}
2724
2725proc do_rescan {} {
2726        rescan {set ui_status_value {Ready.}}
2727}
2728
2729proc unstage_helper {txt paths} {
2730        global file_states current_diff_path
2731
2732        if {![lock_index begin-update]} return
2733
2734        set pathList [list]
2735        set after {}
2736        foreach path $paths {
2737                switch -glob -- [lindex $file_states($path) 0] {
2738                A? -
2739                M? -
2740                D? {
2741                        lappend pathList $path
2742                        if {$path eq $current_diff_path} {
2743                                set after {reshow_diff;}
2744                        }
2745                }
2746                }
2747        }
2748        if {$pathList eq {}} {
2749                unlock_index
2750        } else {
2751                update_indexinfo \
2752                        $txt \
2753                        $pathList \
2754                        [concat $after {set ui_status_value {Ready.}}]
2755        }
2756}
2757
2758proc do_unstage_selection {} {
2759        global current_diff_path selected_paths
2760
2761        if {[array size selected_paths] > 0} {
2762                unstage_helper \
2763                        {Unstaging selected files from commit} \
2764                        [array names selected_paths]
2765        } elseif {$current_diff_path ne {}} {
2766                unstage_helper \
2767                        "Unstaging [short_path $current_diff_path] from commit" \
2768                        [list $current_diff_path]
2769        }
2770}
2771
2772proc add_helper {txt paths} {
2773        global file_states current_diff_path
2774
2775        if {![lock_index begin-update]} return
2776
2777        set pathList [list]
2778        set after {}
2779        foreach path $paths {
2780                switch -glob -- [lindex $file_states($path) 0] {
2781                _O -
2782                ?M -
2783                ?D -
2784                U? {
2785                        lappend pathList $path
2786                        if {$path eq $current_diff_path} {
2787                                set after {reshow_diff;}
2788                        }
2789                }
2790                }
2791        }
2792        if {$pathList eq {}} {
2793                unlock_index
2794        } else {
2795                update_index \
2796                        $txt \
2797                        $pathList \
2798                        [concat $after {set ui_status_value {Ready to commit.}}]
2799        }
2800}
2801
2802proc do_add_selection {} {
2803        global current_diff_path selected_paths
2804
2805        if {[array size selected_paths] > 0} {
2806                add_helper \
2807                        {Adding selected files} \
2808                        [array names selected_paths]
2809        } elseif {$current_diff_path ne {}} {
2810                add_helper \
2811                        "Adding [short_path $current_diff_path]" \
2812                        [list $current_diff_path]
2813        }
2814}
2815
2816proc do_add_all {} {
2817        global file_states
2818
2819        set paths [list]
2820        foreach path [array names file_states] {
2821                switch -glob -- [lindex $file_states($path) 0] {
2822                U? {continue}
2823                ?M -
2824                ?D {lappend paths $path}
2825                }
2826        }
2827        add_helper {Adding all changed files} $paths
2828}
2829
2830proc revert_helper {txt paths} {
2831        global file_states current_diff_path
2832
2833        if {![lock_index begin-update]} return
2834
2835        set pathList [list]
2836        set after {}
2837        foreach path $paths {
2838                switch -glob -- [lindex $file_states($path) 0] {
2839                U? {continue}
2840                ?M -
2841                ?D {
2842                        lappend pathList $path
2843                        if {$path eq $current_diff_path} {
2844                                set after {reshow_diff;}
2845                        }
2846                }
2847                }
2848        }
2849
2850        set n [llength $pathList]
2851        if {$n == 0} {
2852                unlock_index
2853                return
2854        } elseif {$n == 1} {
2855                set s "[short_path [lindex $pathList]]"
2856        } else {
2857                set s "these $n files"
2858        }
2859
2860        set reply [tk_dialog \
2861                .confirm_revert \
2862                "[appname] ([reponame])" \
2863                "Revert changes in $s?
2864
2865Any unadded changes will be permanently lost by the revert." \
2866                question \
2867                1 \
2868                {Do Nothing} \
2869                {Revert Changes} \
2870                ]
2871        if {$reply == 1} {
2872                checkout_index \
2873                        $txt \
2874                        $pathList \
2875                        [concat $after {set ui_status_value {Ready.}}]
2876        } else {
2877                unlock_index
2878        }
2879}
2880
2881proc do_revert_selection {} {
2882        global current_diff_path selected_paths
2883
2884        if {[array size selected_paths] > 0} {
2885                revert_helper \
2886                        {Reverting selected files} \
2887                        [array names selected_paths]
2888        } elseif {$current_diff_path ne {}} {
2889                revert_helper \
2890                        "Reverting [short_path $current_diff_path]" \
2891                        [list $current_diff_path]
2892        }
2893}
2894
2895proc do_signoff {} {
2896        global ui_comm
2897
2898        set me [committer_ident]
2899        if {$me eq {}} return
2900
2901        set sob "Signed-off-by: $me"
2902        set last [$ui_comm get {end -1c linestart} {end -1c}]
2903        if {$last ne $sob} {
2904                $ui_comm edit separator
2905                if {$last ne {}
2906                        && ![regexp {^[A-Z][A-Za-z]*-[A-Za-z-]+: *} $last]} {
2907                        $ui_comm insert end "\n"
2908                }
2909                $ui_comm insert end "\n$sob"
2910                $ui_comm edit separator
2911                $ui_comm see end
2912        }
2913}
2914
2915proc do_select_commit_type {} {
2916        global commit_type selected_commit_type
2917
2918        if {$selected_commit_type eq {new}
2919                && [string match amend* $commit_type]} {
2920                create_new_commit
2921        } elseif {$selected_commit_type eq {amend}
2922                && ![string match amend* $commit_type]} {
2923                load_last_commit
2924
2925                # The amend request was rejected...
2926                #
2927                if {![string match amend* $commit_type]} {
2928                        set selected_commit_type new
2929                }
2930        }
2931}
2932
2933proc do_commit {} {
2934        commit_tree
2935}
2936
2937proc do_about {} {
2938        global appvers copyright
2939        global tcl_patchLevel tk_patchLevel
2940
2941        set w .about_dialog
2942        toplevel $w
2943        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2944
2945        label $w.header -text "About [appname]" \
2946                -font font_uibold
2947        pack $w.header -side top -fill x
2948
2949        frame $w.buttons
2950        button $w.buttons.close -text {Close} \
2951                -font font_ui \
2952                -command [list destroy $w]
2953        pack $w.buttons.close -side right
2954        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2955
2956        label $w.desc \
2957                -text "[appname] - a commit creation tool for Git.
2958$copyright" \
2959                -padx 5 -pady 5 \
2960                -justify left \
2961                -anchor w \
2962                -borderwidth 1 \
2963                -relief solid \
2964                -font font_ui
2965        pack $w.desc -side top -fill x -padx 5 -pady 5
2966
2967        set v {}
2968        append v "[appname] version $appvers\n"
2969        append v "[exec git version]\n"
2970        append v "\n"
2971        if {$tcl_patchLevel eq $tk_patchLevel} {
2972                append v "Tcl/Tk version $tcl_patchLevel"
2973        } else {
2974                append v "Tcl version $tcl_patchLevel"
2975                append v ", Tk version $tk_patchLevel"
2976        }
2977
2978        label $w.vers \
2979                -text $v \
2980                -padx 5 -pady 5 \
2981                -justify left \
2982                -anchor w \
2983                -borderwidth 1 \
2984                -relief solid \
2985                -font font_ui
2986        pack $w.vers -side top -fill x -padx 5 -pady 5
2987
2988        menu $w.ctxm -tearoff 0
2989        $w.ctxm add command \
2990                -label {Copy} \
2991                -font font_ui \
2992                -command "
2993                clipboard clear
2994                clipboard append -format STRING -type STRING -- \[$w.vers cget -text\]
2995        "
2996
2997        bind $w <Visibility> "grab $w; focus $w"
2998        bind $w <Key-Escape> "destroy $w"
2999        bind_button3 $w.vers "tk_popup $w.ctxm %X %Y; grab $w; focus $w"
3000        wm title $w "About [appname]"
3001        tkwait window $w
3002}
3003
3004proc do_options {} {
3005        global repo_config global_config font_descs
3006        global repo_config_new global_config_new
3007
3008        array unset repo_config_new
3009        array unset global_config_new
3010        foreach name [array names repo_config] {
3011                set repo_config_new($name) $repo_config($name)
3012        }
3013        load_config 1
3014        foreach name [array names repo_config] {
3015                switch -- $name {
3016                gui.diffcontext {continue}
3017                }
3018                set repo_config_new($name) $repo_config($name)
3019        }
3020        foreach name [array names global_config] {
3021                set global_config_new($name) $global_config($name)
3022        }
3023
3024        set w .options_editor
3025        toplevel $w
3026        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
3027
3028        label $w.header -text "[appname] Options" \
3029                -font font_uibold
3030        pack $w.header -side top -fill x
3031
3032        frame $w.buttons
3033        button $w.buttons.restore -text {Restore Defaults} \
3034                -font font_ui \
3035                -command do_restore_defaults
3036        pack $w.buttons.restore -side left
3037        button $w.buttons.save -text Save \
3038                -font font_ui \
3039                -command "
3040                        catch {eval \[bind \[focus -displayof $w\] <FocusOut>\]}
3041                        do_save_config $w
3042                "
3043        pack $w.buttons.save -side right
3044        button $w.buttons.cancel -text {Cancel} \
3045                -font font_ui \
3046                -command [list destroy $w]
3047        pack $w.buttons.cancel -side right -padx 5
3048        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
3049
3050        labelframe $w.repo -text "[reponame] Repository" \
3051                -font font_ui \
3052                -relief raised -borderwidth 2
3053        labelframe $w.global -text {Global (All Repositories)} \
3054                -font font_ui \
3055                -relief raised -borderwidth 2
3056        pack $w.repo -side left -fill both -expand 1 -pady 5 -padx 5
3057        pack $w.global -side right -fill both -expand 1 -pady 5 -padx 5
3058
3059        foreach option {
3060                {b pullsummary {Show Pull Summary}}
3061                {b trustmtime  {Trust File Modification Timestamps}}
3062                {i diffcontext {Number of Diff Context Lines}}
3063                {t newbranchtemplate {New Branch Name Template}}
3064                } {
3065                set type [lindex $option 0]
3066                set name [lindex $option 1]
3067                set text [lindex $option 2]
3068                foreach f {repo global} {
3069                        switch $type {
3070                        b {
3071                                checkbutton $w.$f.$name -text $text \
3072                                        -variable ${f}_config_new(gui.$name) \
3073                                        -onvalue true \
3074                                        -offvalue false \
3075                                        -font font_ui
3076                                pack $w.$f.$name -side top -anchor w
3077                        }
3078                        i {
3079                                frame $w.$f.$name
3080                                label $w.$f.$name.l -text "$text:" -font font_ui
3081                                pack $w.$f.$name.l -side left -anchor w -fill x
3082                                spinbox $w.$f.$name.v \
3083                                        -textvariable ${f}_config_new(gui.$name) \
3084                                        -from 1 -to 99 -increment 1 \
3085                                        -width 3 \
3086                                        -font font_ui
3087                                bind $w.$f.$name.v <FocusIn> {%W selection range 0 end}
3088                                pack $w.$f.$name.v -side right -anchor e -padx 5
3089                                pack $w.$f.$name -side top -anchor w -fill x
3090                        }
3091                        t {
3092                                frame $w.$f.$name
3093                                label $w.$f.$name.l -text "$text:" -font font_ui
3094                                text $w.$f.$name.v \
3095                                        -borderwidth 1 \
3096                                        -relief sunken \
3097                                        -height 1 \
3098                                        -width 20 \
3099                                        -font font_ui
3100                                $w.$f.$name.v insert 0.0 [set ${f}_config_new(gui.$name)]
3101                                bind $w.$f.$name.v <Shift-Key-Tab> {focus [tk_focusPrev %W];break}
3102                                bind $w.$f.$name.v <Key-Tab> {focus [tk_focusNext %W];break}
3103                                bind $w.$f.$name.v <Key-Return> break
3104                                bind $w.$f.$name.v <FocusIn> "$w.$f.$name.v tag add sel 0.0 end"
3105                                bind $w.$f.$name.v <FocusOut> "
3106                                        set ${f}_config_new(gui.$name) \
3107                                        \[string trim \[$w.$f.$name.v get 0.0 end\]\]
3108                                "
3109                                pack $w.$f.$name.l -side left -anchor w
3110                                pack $w.$f.$name.v -side left -anchor w \
3111                                        -fill x -expand 1 \
3112                                        -padx 5
3113                                pack $w.$f.$name -side top -anchor w -fill x
3114                        }
3115                        }
3116                }
3117        }
3118
3119        set all_fonts [lsort [font families]]
3120        foreach option $font_descs {
3121                set name [lindex $option 0]
3122                set font [lindex $option 1]
3123                set text [lindex $option 2]
3124
3125                set global_config_new(gui.$font^^family) \
3126                        [font configure $font -family]
3127                set global_config_new(gui.$font^^size) \
3128                        [font configure $font -size]
3129
3130                frame $w.global.$name
3131                label $w.global.$name.l -text "$text:" -font font_ui
3132                pack $w.global.$name.l -side left -anchor w -fill x
3133                eval tk_optionMenu $w.global.$name.family \
3134                        global_config_new(gui.$font^^family) \
3135                        $all_fonts
3136                spinbox $w.global.$name.size \
3137                        -textvariable global_config_new(gui.$font^^size) \
3138                        -from 2 -to 80 -increment 1 \
3139                        -width 3 \
3140                        -font font_ui
3141                bind $w.global.$name.size <FocusIn> {%W selection range 0 end}
3142                pack $w.global.$name.size -side right -anchor e
3143                pack $w.global.$name.family -side right -anchor e
3144                pack $w.global.$name -side top -anchor w -fill x
3145        }
3146
3147        bind $w <Visibility> "grab $w; focus $w"
3148        bind $w <Key-Escape> "destroy $w"
3149        wm title $w "[appname] ([reponame]): Options"
3150        tkwait window $w
3151}
3152
3153proc do_restore_defaults {} {
3154        global font_descs default_config repo_config
3155        global repo_config_new global_config_new
3156
3157        foreach name [array names default_config] {
3158                set repo_config_new($name) $default_config($name)
3159                set global_config_new($name) $default_config($name)
3160        }
3161
3162        foreach option $font_descs {
3163                set name [lindex $option 0]
3164                set repo_config(gui.$name) $default_config(gui.$name)
3165        }
3166        apply_config
3167
3168        foreach option $font_descs {
3169                set name [lindex $option 0]
3170                set font [lindex $option 1]
3171                set global_config_new(gui.$font^^family) \
3172                        [font configure $font -family]
3173                set global_config_new(gui.$font^^size) \
3174                        [font configure $font -size]
3175        }
3176}
3177
3178proc do_save_config {w} {
3179        if {[catch {save_config} err]} {
3180                error_popup "Failed to completely save options:\n\n$err"
3181        }
3182        reshow_diff
3183        destroy $w
3184}
3185
3186proc do_windows_shortcut {} {
3187        global argv0
3188
3189        if {[catch {
3190                set desktop [exec cygpath \
3191                        --windows \
3192                        --absolute \
3193                        --long-name \
3194                        --desktop]
3195                }]} {
3196                        set desktop .
3197        }
3198        set fn [tk_getSaveFile \
3199                -parent . \
3200                -title "[appname] ([reponame]): Create Desktop Icon" \
3201                -initialdir $desktop \
3202                -initialfile "Git [reponame].bat"]
3203        if {$fn != {}} {
3204                if {[catch {
3205                                set fd [open $fn w]
3206                                set sh [exec cygpath \
3207                                        --windows \
3208                                        --absolute \
3209                                        /bin/sh]
3210                                set me [exec cygpath \
3211                                        --unix \
3212                                        --absolute \
3213                                        $argv0]
3214                                set gd [exec cygpath \
3215                                        --unix \
3216                                        --absolute \
3217                                        [gitdir]]
3218                                set gw [exec cygpath \
3219                                        --windows \
3220                                        --absolute \
3221                                        [file dirname [gitdir]]]
3222                                regsub -all ' $me "'\\''" me
3223                                regsub -all ' $gd "'\\''" gd
3224                                puts $fd "@ECHO Entering $gw"
3225                                puts $fd "@ECHO Starting git-gui... please wait..."
3226                                puts -nonewline $fd "@\"$sh\" --login -c \""
3227                                puts -nonewline $fd "GIT_DIR='$gd'"
3228                                puts -nonewline $fd " '$me'"
3229                                puts $fd "&\""
3230                                close $fd
3231                        } err]} {
3232                        error_popup "Cannot write script:\n\n$err"
3233                }
3234        }
3235}
3236
3237proc do_macosx_app {} {
3238        global argv0 env
3239
3240        set fn [tk_getSaveFile \
3241                -parent . \
3242                -title "[appname] ([reponame]): Create Desktop Icon" \
3243                -initialdir [file join $env(HOME) Desktop] \
3244                -initialfile "Git [reponame].app"]
3245        if {$fn != {}} {
3246                if {[catch {
3247                                set Contents [file join $fn Contents]
3248                                set MacOS [file join $Contents MacOS]
3249                                set exe [file join $MacOS git-gui]
3250
3251                                file mkdir $MacOS
3252
3253                                set fd [open [file join $Contents Info.plist] w]
3254                                puts $fd {<?xml version="1.0" encoding="UTF-8"?>
3255<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3256<plist version="1.0">
3257<dict>
3258        <key>CFBundleDevelopmentRegion</key>
3259        <string>English</string>
3260        <key>CFBundleExecutable</key>
3261        <string>git-gui</string>
3262        <key>CFBundleIdentifier</key>
3263        <string>org.spearce.git-gui</string>
3264        <key>CFBundleInfoDictionaryVersion</key>
3265        <string>6.0</string>
3266        <key>CFBundlePackageType</key>
3267        <string>APPL</string>
3268        <key>CFBundleSignature</key>
3269        <string>????</string>
3270        <key>CFBundleVersion</key>
3271        <string>1.0</string>
3272        <key>NSPrincipalClass</key>
3273        <string>NSApplication</string>
3274</dict>
3275</plist>}
3276                                close $fd
3277
3278                                set fd [open $exe w]
3279                                set gd [file normalize [gitdir]]
3280                                set ep [file normalize [exec git --exec-path]]
3281                                regsub -all ' $gd "'\\''" gd
3282                                regsub -all ' $ep "'\\''" ep
3283                                puts $fd "#!/bin/sh"
3284                                foreach name [array names env] {
3285                                        if {[string match GIT_* $name]} {
3286                                                regsub -all ' $env($name) "'\\''" v
3287                                                puts $fd "export $name='$v'"
3288                                        }
3289                                }
3290                                puts $fd "export PATH='$ep':\$PATH"
3291                                puts $fd "export GIT_DIR='$gd'"
3292                                puts $fd "exec [file normalize $argv0]"
3293                                close $fd
3294
3295                                file attributes $exe -permissions u+x,g+x,o+x
3296                        } err]} {
3297                        error_popup "Cannot write icon:\n\n$err"
3298                }
3299        }
3300}
3301
3302proc toggle_or_diff {w x y} {
3303        global file_states file_lists current_diff_path ui_index ui_workdir
3304        global last_clicked selected_paths
3305
3306        set pos [split [$w index @$x,$y] .]
3307        set lno [lindex $pos 0]
3308        set col [lindex $pos 1]
3309        set path [lindex $file_lists($w) [expr {$lno - 1}]]
3310        if {$path eq {}} {
3311                set last_clicked {}
3312                return
3313        }
3314
3315        set last_clicked [list $w $lno]
3316        array unset selected_paths
3317        $ui_index tag remove in_sel 0.0 end
3318        $ui_workdir tag remove in_sel 0.0 end
3319
3320        if {$col == 0} {
3321                if {$current_diff_path eq $path} {
3322                        set after {reshow_diff;}
3323                } else {
3324                        set after {}
3325                }
3326                if {$w eq $ui_index} {
3327                        update_indexinfo \
3328                                "Unstaging [short_path $path] from commit" \
3329                                [list $path] \
3330                                [concat $after {set ui_status_value {Ready.}}]
3331                } elseif {$w eq $ui_workdir} {
3332                        update_index \
3333                                "Adding [short_path $path]" \
3334                                [list $path] \
3335                                [concat $after {set ui_status_value {Ready.}}]
3336                }
3337        } else {
3338                show_diff $path $w $lno
3339        }
3340}
3341
3342proc add_one_to_selection {w x y} {
3343        global file_lists last_clicked selected_paths
3344
3345        set lno [lindex [split [$w index @$x,$y] .] 0]
3346        set path [lindex $file_lists($w) [expr {$lno - 1}]]
3347        if {$path eq {}} {
3348                set last_clicked {}
3349                return
3350        }
3351
3352        if {$last_clicked ne {}
3353                && [lindex $last_clicked 0] ne $w} {
3354                array unset selected_paths
3355                [lindex $last_clicked 0] tag remove in_sel 0.0 end
3356        }
3357
3358        set last_clicked [list $w $lno]
3359        if {[catch {set in_sel $selected_paths($path)}]} {
3360                set in_sel 0
3361        }
3362        if {$in_sel} {
3363                unset selected_paths($path)
3364                $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
3365        } else {
3366                set selected_paths($path) 1
3367                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3368        }
3369}
3370
3371proc add_range_to_selection {w x y} {
3372        global file_lists last_clicked selected_paths
3373
3374        if {[lindex $last_clicked 0] ne $w} {
3375                toggle_or_diff $w $x $y
3376                return
3377        }
3378
3379        set lno [lindex [split [$w index @$x,$y] .] 0]
3380        set lc [lindex $last_clicked 1]
3381        if {$lc < $lno} {
3382                set begin $lc
3383                set end $lno
3384        } else {
3385                set begin $lno
3386                set end $lc
3387        }
3388
3389        foreach path [lrange $file_lists($w) \
3390                [expr {$begin - 1}] \
3391                [expr {$end - 1}]] {
3392                set selected_paths($path) 1
3393        }
3394        $w tag add in_sel $begin.0 [expr {$end + 1}].0
3395}
3396
3397######################################################################
3398##
3399## config defaults
3400
3401set cursor_ptr arrow
3402font create font_diff -family Courier -size 10
3403font create font_ui
3404catch {
3405        label .dummy
3406        eval font configure font_ui [font actual [.dummy cget -font]]
3407        destroy .dummy
3408}
3409
3410font create font_uibold
3411font create font_diffbold
3412
3413if {[is_Windows]} {
3414        set M1B Control
3415        set M1T Ctrl
3416} elseif {[is_MacOSX]} {
3417        set M1B M1
3418        set M1T Cmd
3419} else {
3420        set M1B M1
3421        set M1T M1
3422}
3423
3424proc apply_config {} {
3425        global repo_config font_descs
3426
3427        foreach option $font_descs {
3428                set name [lindex $option 0]
3429                set font [lindex $option 1]
3430                if {[catch {
3431                        foreach {cn cv} $repo_config(gui.$name) {
3432                                font configure $font $cn $cv
3433                        }
3434                        } err]} {
3435                        error_popup "Invalid font specified in gui.$name:\n\n$err"
3436                }
3437                foreach {cn cv} [font configure $font] {
3438                        font configure ${font}bold $cn $cv
3439                }
3440                font configure ${font}bold -weight bold
3441        }
3442}
3443
3444set default_config(gui.trustmtime) false
3445set default_config(gui.pullsummary) true
3446set default_config(gui.diffcontext) 5
3447set default_config(gui.newbranchtemplate) {}
3448set default_config(gui.fontui) [font configure font_ui]
3449set default_config(gui.fontdiff) [font configure font_diff]
3450set font_descs {
3451        {fontui   font_ui   {Main Font}}
3452        {fontdiff font_diff {Diff/Console Font}}
3453}
3454load_config 0
3455apply_config
3456
3457######################################################################
3458##
3459## ui construction
3460
3461# -- Menu Bar
3462#
3463menu .mbar -tearoff 0
3464.mbar add cascade -label Repository -menu .mbar.repository
3465.mbar add cascade -label Edit -menu .mbar.edit
3466if {!$single_commit} {
3467        .mbar add cascade -label Branch -menu .mbar.branch
3468}
3469.mbar add cascade -label Commit -menu .mbar.commit
3470if {!$single_commit} {
3471        .mbar add cascade -label Fetch -menu .mbar.fetch
3472        .mbar add cascade -label Pull -menu .mbar.pull
3473        .mbar add cascade -label Push -menu .mbar.push
3474}
3475. configure -menu .mbar
3476
3477# -- Repository Menu
3478#
3479menu .mbar.repository
3480.mbar.repository add command \
3481        -label {Visualize Current Branch} \
3482        -command {do_gitk {}} \
3483        -font font_ui
3484if {![is_MacOSX]} {
3485        .mbar.repository add command \
3486                -label {Visualize All Branches} \
3487                -command {do_gitk {--all}} \
3488                -font font_ui
3489}
3490.mbar.repository add separator
3491
3492if {!$single_commit} {
3493        .mbar.repository add command -label {Compress Database} \
3494                -command do_gc \
3495                -font font_ui
3496
3497        .mbar.repository add command -label {Verify Database} \
3498                -command do_fsck_objects \
3499                -font font_ui
3500
3501        .mbar.repository add separator
3502
3503        if {[is_Windows]} {
3504                .mbar.repository add command \
3505                        -label {Create Desktop Icon} \
3506                        -command do_windows_shortcut \
3507                        -font font_ui
3508        } elseif {[is_MacOSX]} {
3509                .mbar.repository add command \
3510                        -label {Create Desktop Icon} \
3511                        -command do_macosx_app \
3512                        -font font_ui
3513        }
3514}
3515
3516.mbar.repository add command -label Quit \
3517        -command do_quit \
3518        -accelerator $M1T-Q \
3519        -font font_ui
3520
3521# -- Edit Menu
3522#
3523menu .mbar.edit
3524.mbar.edit add command -label Undo \
3525        -command {catch {[focus] edit undo}} \
3526        -accelerator $M1T-Z \
3527        -font font_ui
3528.mbar.edit add command -label Redo \
3529        -command {catch {[focus] edit redo}} \
3530        -accelerator $M1T-Y \
3531        -font font_ui
3532.mbar.edit add separator
3533.mbar.edit add command -label Cut \
3534        -command {catch {tk_textCut [focus]}} \
3535        -accelerator $M1T-X \
3536        -font font_ui
3537.mbar.edit add command -label Copy \
3538        -command {catch {tk_textCopy [focus]}} \
3539        -accelerator $M1T-C \
3540        -font font_ui
3541.mbar.edit add command -label Paste \
3542        -command {catch {tk_textPaste [focus]; [focus] see insert}} \
3543        -accelerator $M1T-V \
3544        -font font_ui
3545.mbar.edit add command -label Delete \
3546        -command {catch {[focus] delete sel.first sel.last}} \
3547        -accelerator Del \
3548        -font font_ui
3549.mbar.edit add separator
3550.mbar.edit add command -label {Select All} \
3551        -command {catch {[focus] tag add sel 0.0 end}} \
3552        -accelerator $M1T-A \
3553        -font font_ui
3554
3555# -- Branch Menu
3556#
3557if {!$single_commit} {
3558        menu .mbar.branch
3559
3560        .mbar.branch add command -label {Create...} \
3561                -command do_create_branch \
3562                -accelerator $M1T-N \
3563                -font font_ui
3564        lappend disable_on_lock [list .mbar.branch entryconf \
3565                [.mbar.branch index last] -state]
3566
3567        .mbar.branch add command -label {Delete...} \
3568                -command do_delete_branch \
3569                -font font_ui
3570        lappend disable_on_lock [list .mbar.branch entryconf \
3571                [.mbar.branch index last] -state]
3572}
3573
3574# -- Commit Menu
3575#
3576menu .mbar.commit
3577
3578.mbar.commit add radiobutton \
3579        -label {New Commit} \
3580        -command do_select_commit_type \
3581        -variable selected_commit_type \
3582        -value new \
3583        -font font_ui
3584lappend disable_on_lock \
3585        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3586
3587.mbar.commit add radiobutton \
3588        -label {Amend Last Commit} \
3589        -command do_select_commit_type \
3590        -variable selected_commit_type \
3591        -value amend \
3592        -font font_ui
3593lappend disable_on_lock \
3594        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3595
3596.mbar.commit add separator
3597
3598.mbar.commit add command -label Rescan \
3599        -command do_rescan \
3600        -accelerator F5 \
3601        -font font_ui
3602lappend disable_on_lock \
3603        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3604
3605.mbar.commit add command -label {Add To Commit} \
3606        -command do_add_selection \
3607        -font font_ui
3608lappend disable_on_lock \
3609        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3610
3611.mbar.commit add command -label {Add All To Commit} \
3612        -command do_add_all \
3613        -accelerator $M1T-I \
3614        -font font_ui
3615lappend disable_on_lock \
3616        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3617
3618.mbar.commit add command -label {Unstage From Commit} \
3619        -command do_unstage_selection \
3620        -font font_ui
3621lappend disable_on_lock \
3622        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3623
3624.mbar.commit add command -label {Revert Changes} \
3625        -command do_revert_selection \
3626        -font font_ui
3627lappend disable_on_lock \
3628        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3629
3630.mbar.commit add separator
3631
3632.mbar.commit add command -label {Sign Off} \
3633        -command do_signoff \
3634        -accelerator $M1T-S \
3635        -font font_ui
3636
3637.mbar.commit add command -label Commit \
3638        -command do_commit \
3639        -accelerator $M1T-Return \
3640        -font font_ui
3641lappend disable_on_lock \
3642        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3643
3644# -- Transport menus
3645#
3646if {!$single_commit} {
3647        menu .mbar.fetch
3648        menu .mbar.pull
3649        menu .mbar.push
3650}
3651
3652if {[is_MacOSX]} {
3653        # -- Apple Menu (Mac OS X only)
3654        #
3655        .mbar add cascade -label Apple -menu .mbar.apple
3656        menu .mbar.apple
3657
3658        .mbar.apple add command -label "About [appname]" \
3659                -command do_about \
3660                -font font_ui
3661        .mbar.apple add command -label "[appname] Options..." \
3662                -command do_options \
3663                -font font_ui
3664} else {
3665        # -- Edit Menu
3666        #
3667        .mbar.edit add separator
3668        .mbar.edit add command -label {Options...} \
3669                -command do_options \
3670                -font font_ui
3671
3672        # -- Tools Menu
3673        #
3674        if {[file exists /usr/local/miga/lib/gui-miga]
3675                && [file exists .pvcsrc]} {
3676        proc do_miga {} {
3677                global ui_status_value
3678                if {![lock_index update]} return
3679                set cmd [list sh --login -c "/usr/local/miga/lib/gui-miga \"[pwd]\""]
3680                set miga_fd [open "|$cmd" r]
3681                fconfigure $miga_fd -blocking 0
3682                fileevent $miga_fd readable [list miga_done $miga_fd]
3683                set ui_status_value {Running miga...}
3684        }
3685        proc miga_done {fd} {
3686                read $fd 512
3687                if {[eof $fd]} {
3688                        close $fd
3689                        unlock_index
3690                        rescan [list set ui_status_value {Ready.}]
3691                }
3692        }
3693        .mbar add cascade -label Tools -menu .mbar.tools
3694        menu .mbar.tools
3695        .mbar.tools add command -label "Migrate" \
3696                -command do_miga \
3697                -font font_ui
3698        lappend disable_on_lock \
3699                [list .mbar.tools entryconf [.mbar.tools index last] -state]
3700        }
3701
3702        # -- Help Menu
3703        #
3704        .mbar add cascade -label Help -menu .mbar.help
3705        menu .mbar.help
3706
3707        .mbar.help add command -label "About [appname]" \
3708                -command do_about \
3709                -font font_ui
3710}
3711
3712
3713# -- Branch Control
3714#
3715frame .branch \
3716        -borderwidth 1 \
3717        -relief sunken
3718label .branch.l1 \
3719        -text {Current Branch:} \
3720        -anchor w \
3721        -justify left \
3722        -font font_ui
3723label .branch.cb \
3724        -textvariable current_branch \
3725        -anchor w \
3726        -justify left \
3727        -font font_ui
3728pack .branch.l1 -side left
3729pack .branch.cb -side left -fill x
3730pack .branch -side top -fill x
3731
3732# -- Main Window Layout
3733#
3734panedwindow .vpane -orient vertical
3735panedwindow .vpane.files -orient horizontal
3736.vpane add .vpane.files -sticky nsew -height 100 -width 200
3737pack .vpane -anchor n -side top -fill both -expand 1
3738
3739# -- Index File List
3740#
3741frame .vpane.files.index -height 100 -width 200
3742label .vpane.files.index.title -text {Changes To Be Committed} \
3743        -background green \
3744        -font font_ui
3745text $ui_index -background white -borderwidth 0 \
3746        -width 20 -height 10 \
3747        -wrap none \
3748        -font font_ui \
3749        -cursor $cursor_ptr \
3750        -xscrollcommand {.vpane.files.index.sx set} \
3751        -yscrollcommand {.vpane.files.index.sy set} \
3752        -state disabled
3753scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
3754scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
3755pack .vpane.files.index.title -side top -fill x
3756pack .vpane.files.index.sx -side bottom -fill x
3757pack .vpane.files.index.sy -side right -fill y
3758pack $ui_index -side left -fill both -expand 1
3759.vpane.files add .vpane.files.index -sticky nsew
3760
3761# -- Working Directory File List
3762#
3763frame .vpane.files.workdir -height 100 -width 200
3764label .vpane.files.workdir.title -text {Changed But Not Updated} \
3765        -background red \
3766        -font font_ui
3767text $ui_workdir -background white -borderwidth 0 \
3768        -width 20 -height 10 \
3769        -wrap none \
3770        -font font_ui \
3771        -cursor $cursor_ptr \
3772        -xscrollcommand {.vpane.files.workdir.sx set} \
3773        -yscrollcommand {.vpane.files.workdir.sy set} \
3774        -state disabled
3775scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
3776scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
3777pack .vpane.files.workdir.title -side top -fill x
3778pack .vpane.files.workdir.sx -side bottom -fill x
3779pack .vpane.files.workdir.sy -side right -fill y
3780pack $ui_workdir -side left -fill both -expand 1
3781.vpane.files add .vpane.files.workdir -sticky nsew
3782
3783foreach i [list $ui_index $ui_workdir] {
3784        $i tag conf in_diff -font font_uibold
3785        $i tag conf in_sel \
3786                -background [$i cget -foreground] \
3787                -foreground [$i cget -background]
3788}
3789unset i
3790
3791# -- Diff and Commit Area
3792#
3793frame .vpane.lower -height 300 -width 400
3794frame .vpane.lower.commarea
3795frame .vpane.lower.diff -relief sunken -borderwidth 1
3796pack .vpane.lower.commarea -side top -fill x
3797pack .vpane.lower.diff -side bottom -fill both -expand 1
3798.vpane add .vpane.lower -stick nsew
3799
3800# -- Commit Area Buttons
3801#
3802frame .vpane.lower.commarea.buttons
3803label .vpane.lower.commarea.buttons.l -text {} \
3804        -anchor w \
3805        -justify left \
3806        -font font_ui
3807pack .vpane.lower.commarea.buttons.l -side top -fill x
3808pack .vpane.lower.commarea.buttons -side left -fill y
3809
3810button .vpane.lower.commarea.buttons.rescan -text {Rescan} \
3811        -command do_rescan \
3812        -font font_ui
3813pack .vpane.lower.commarea.buttons.rescan -side top -fill x
3814lappend disable_on_lock \
3815        {.vpane.lower.commarea.buttons.rescan conf -state}
3816
3817button .vpane.lower.commarea.buttons.incall -text {Add All} \
3818        -command do_add_all \
3819        -font font_ui
3820pack .vpane.lower.commarea.buttons.incall -side top -fill x
3821lappend disable_on_lock \
3822        {.vpane.lower.commarea.buttons.incall conf -state}
3823
3824button .vpane.lower.commarea.buttons.signoff -text {Sign Off} \
3825        -command do_signoff \
3826        -font font_ui
3827pack .vpane.lower.commarea.buttons.signoff -side top -fill x
3828
3829button .vpane.lower.commarea.buttons.commit -text {Commit} \
3830        -command do_commit \
3831        -font font_ui
3832pack .vpane.lower.commarea.buttons.commit -side top -fill x
3833lappend disable_on_lock \
3834        {.vpane.lower.commarea.buttons.commit conf -state}
3835
3836# -- Commit Message Buffer
3837#
3838frame .vpane.lower.commarea.buffer
3839frame .vpane.lower.commarea.buffer.header
3840set ui_comm .vpane.lower.commarea.buffer.t
3841set ui_coml .vpane.lower.commarea.buffer.header.l
3842radiobutton .vpane.lower.commarea.buffer.header.new \
3843        -text {New Commit} \
3844        -command do_select_commit_type \
3845        -variable selected_commit_type \
3846        -value new \
3847        -font font_ui
3848lappend disable_on_lock \
3849        [list .vpane.lower.commarea.buffer.header.new conf -state]
3850radiobutton .vpane.lower.commarea.buffer.header.amend \
3851        -text {Amend Last Commit} \
3852        -command do_select_commit_type \
3853        -variable selected_commit_type \
3854        -value amend \
3855        -font font_ui
3856lappend disable_on_lock \
3857        [list .vpane.lower.commarea.buffer.header.amend conf -state]
3858label $ui_coml \
3859        -anchor w \
3860        -justify left \
3861        -font font_ui
3862proc trace_commit_type {varname args} {
3863        global ui_coml commit_type
3864        switch -glob -- $commit_type {
3865        initial       {set txt {Initial Commit Message:}}
3866        amend         {set txt {Amended Commit Message:}}
3867        amend-initial {set txt {Amended Initial Commit Message:}}
3868        amend-merge   {set txt {Amended Merge Commit Message:}}
3869        merge         {set txt {Merge Commit Message:}}
3870        *             {set txt {Commit Message:}}
3871        }
3872        $ui_coml conf -text $txt
3873}
3874trace add variable commit_type write trace_commit_type
3875pack $ui_coml -side left -fill x
3876pack .vpane.lower.commarea.buffer.header.amend -side right
3877pack .vpane.lower.commarea.buffer.header.new -side right
3878
3879text $ui_comm -background white -borderwidth 1 \
3880        -undo true \
3881        -maxundo 20 \
3882        -autoseparators true \
3883        -relief sunken \
3884        -width 75 -height 9 -wrap none \
3885        -font font_diff \
3886        -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
3887scrollbar .vpane.lower.commarea.buffer.sby \
3888        -command [list $ui_comm yview]
3889pack .vpane.lower.commarea.buffer.header -side top -fill x
3890pack .vpane.lower.commarea.buffer.sby -side right -fill y
3891pack $ui_comm -side left -fill y
3892pack .vpane.lower.commarea.buffer -side left -fill y
3893
3894# -- Commit Message Buffer Context Menu
3895#
3896set ctxm .vpane.lower.commarea.buffer.ctxm
3897menu $ctxm -tearoff 0
3898$ctxm add command \
3899        -label {Cut} \
3900        -font font_ui \
3901        -command {tk_textCut $ui_comm}
3902$ctxm add command \
3903        -label {Copy} \
3904        -font font_ui \
3905        -command {tk_textCopy $ui_comm}
3906$ctxm add command \
3907        -label {Paste} \
3908        -font font_ui \
3909        -command {tk_textPaste $ui_comm}
3910$ctxm add command \
3911        -label {Delete} \
3912        -font font_ui \
3913        -command {$ui_comm delete sel.first sel.last}
3914$ctxm add separator
3915$ctxm add command \
3916        -label {Select All} \
3917        -font font_ui \
3918        -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
3919$ctxm add command \
3920        -label {Copy All} \
3921        -font font_ui \
3922        -command {
3923                $ui_comm tag add sel 0.0 end
3924                tk_textCopy $ui_comm
3925                $ui_comm tag remove sel 0.0 end
3926        }
3927$ctxm add separator
3928$ctxm add command \
3929        -label {Sign Off} \
3930        -font font_ui \
3931        -command do_signoff
3932bind_button3 $ui_comm "tk_popup $ctxm %X %Y"
3933
3934# -- Diff Header
3935#
3936set current_diff_path {}
3937set diff_actions [list]
3938proc trace_current_diff_path {varname args} {
3939        global current_diff_path diff_actions file_states
3940        if {$current_diff_path eq {}} {
3941                set s {}
3942                set f {}
3943                set p {}
3944                set o disabled
3945        } else {
3946                set p $current_diff_path
3947                set s [mapdesc [lindex $file_states($p) 0] $p]
3948                set f {File:}
3949                set p [escape_path $p]
3950                set o normal
3951        }
3952
3953        .vpane.lower.diff.header.status configure -text $s
3954        .vpane.lower.diff.header.file configure -text $f
3955        .vpane.lower.diff.header.path configure -text $p
3956        foreach w $diff_actions {
3957                uplevel #0 $w $o
3958        }
3959}
3960trace add variable current_diff_path write trace_current_diff_path
3961
3962frame .vpane.lower.diff.header -background orange
3963label .vpane.lower.diff.header.status \
3964        -background orange \
3965        -width $max_status_desc \
3966        -anchor w \
3967        -justify left \
3968        -font font_ui
3969label .vpane.lower.diff.header.file \
3970        -background orange \
3971        -anchor w \
3972        -justify left \
3973        -font font_ui
3974label .vpane.lower.diff.header.path \
3975        -background orange \
3976        -anchor w \
3977        -justify left \
3978        -font font_ui
3979pack .vpane.lower.diff.header.status -side left
3980pack .vpane.lower.diff.header.file -side left
3981pack .vpane.lower.diff.header.path -fill x
3982set ctxm .vpane.lower.diff.header.ctxm
3983menu $ctxm -tearoff 0
3984$ctxm add command \
3985        -label {Copy} \
3986        -font font_ui \
3987        -command {
3988                clipboard clear
3989                clipboard append \
3990                        -format STRING \
3991                        -type STRING \
3992                        -- $current_diff_path
3993        }
3994lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3995bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
3996
3997# -- Diff Body
3998#
3999frame .vpane.lower.diff.body
4000set ui_diff .vpane.lower.diff.body.t
4001text $ui_diff -background white -borderwidth 0 \
4002        -width 80 -height 15 -wrap none \
4003        -font font_diff \
4004        -xscrollcommand {.vpane.lower.diff.body.sbx set} \
4005        -yscrollcommand {.vpane.lower.diff.body.sby set} \
4006        -state disabled
4007scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
4008        -command [list $ui_diff xview]
4009scrollbar .vpane.lower.diff.body.sby -orient vertical \
4010        -command [list $ui_diff yview]
4011pack .vpane.lower.diff.body.sbx -side bottom -fill x
4012pack .vpane.lower.diff.body.sby -side right -fill y
4013pack $ui_diff -side left -fill both -expand 1
4014pack .vpane.lower.diff.header -side top -fill x
4015pack .vpane.lower.diff.body -side bottom -fill both -expand 1
4016
4017$ui_diff tag conf d_@ -foreground blue -font font_diffbold
4018$ui_diff tag conf d_+ -foreground {#00a000}
4019$ui_diff tag conf d_- -foreground red
4020
4021$ui_diff tag conf d_++ -foreground {#00a000}
4022$ui_diff tag conf d_-- -foreground red
4023$ui_diff tag conf d_+s \
4024        -foreground {#00a000} \
4025        -background {#e2effa}
4026$ui_diff tag conf d_-s \
4027        -foreground red \
4028        -background {#e2effa}
4029$ui_diff tag conf d_s+ \
4030        -foreground {#00a000} \
4031        -background ivory1
4032$ui_diff tag conf d_s- \
4033        -foreground red \
4034        -background ivory1
4035
4036$ui_diff tag conf d<<<<<<< \
4037        -foreground orange \
4038        -font font_diffbold
4039$ui_diff tag conf d======= \
4040        -foreground orange \
4041        -font font_diffbold
4042$ui_diff tag conf d>>>>>>> \
4043        -foreground orange \
4044        -font font_diffbold
4045
4046$ui_diff tag raise sel
4047
4048# -- Diff Body Context Menu
4049#
4050set ctxm .vpane.lower.diff.body.ctxm
4051menu $ctxm -tearoff 0
4052$ctxm add command \
4053        -label {Refresh} \
4054        -font font_ui \
4055        -command reshow_diff
4056$ctxm add command \
4057        -label {Copy} \
4058        -font font_ui \
4059        -command {tk_textCopy $ui_diff}
4060lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4061$ctxm add command \
4062        -label {Select All} \
4063        -font font_ui \
4064        -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
4065lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4066$ctxm add command \
4067        -label {Copy All} \
4068        -font font_ui \
4069        -command {
4070                $ui_diff tag add sel 0.0 end
4071                tk_textCopy $ui_diff
4072                $ui_diff tag remove sel 0.0 end
4073        }
4074lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4075$ctxm add separator
4076$ctxm add command \
4077        -label {Decrease Font Size} \
4078        -font font_ui \
4079        -command {incr_font_size font_diff -1}
4080lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4081$ctxm add command \
4082        -label {Increase Font Size} \
4083        -font font_ui \
4084        -command {incr_font_size font_diff 1}
4085lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4086$ctxm add separator
4087$ctxm add command \
4088        -label {Show Less Context} \
4089        -font font_ui \
4090        -command {if {$repo_config(gui.diffcontext) >= 2} {
4091                incr repo_config(gui.diffcontext) -1
4092                reshow_diff
4093        }}
4094lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4095$ctxm add command \
4096        -label {Show More Context} \
4097        -font font_ui \
4098        -command {
4099                incr repo_config(gui.diffcontext)
4100                reshow_diff
4101        }
4102lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
4103$ctxm add separator
4104$ctxm add command -label {Options...} \
4105        -font font_ui \
4106        -command do_options
4107bind_button3 $ui_diff "tk_popup $ctxm %X %Y"
4108
4109# -- Status Bar
4110#
4111set ui_status_value {Initializing...}
4112label .status -textvariable ui_status_value \
4113        -anchor w \
4114        -justify left \
4115        -borderwidth 1 \
4116        -relief sunken \
4117        -font font_ui
4118pack .status -anchor w -side bottom -fill x
4119
4120# -- Load geometry
4121#
4122catch {
4123set gm $repo_config(gui.geometry)
4124wm geometry . [lindex $gm 0]
4125.vpane sash place 0 \
4126        [lindex [.vpane sash coord 0] 0] \
4127        [lindex $gm 1]
4128.vpane.files sash place 0 \
4129        [lindex $gm 2] \
4130        [lindex [.vpane.files sash coord 0] 1]
4131unset gm
4132}
4133
4134# -- Key Bindings
4135#
4136bind $ui_comm <$M1B-Key-Return> {do_commit;break}
4137bind $ui_comm <$M1B-Key-i> {do_add_all;break}
4138bind $ui_comm <$M1B-Key-I> {do_add_all;break}
4139bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
4140bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
4141bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
4142bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
4143bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
4144bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
4145bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
4146bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
4147
4148bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
4149bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
4150bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
4151bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
4152bind $ui_diff <$M1B-Key-v> {break}
4153bind $ui_diff <$M1B-Key-V> {break}
4154bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
4155bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
4156bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
4157bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
4158bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
4159bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
4160
4161if {!$single_commit} {
4162        bind . <$M1B-Key-n> do_create_branch
4163        bind . <$M1B-Key-N> do_create_branch
4164}
4165
4166bind .   <Destroy> do_quit
4167bind all <Key-F5> do_rescan
4168bind all <$M1B-Key-r> do_rescan
4169bind all <$M1B-Key-R> do_rescan
4170bind .   <$M1B-Key-s> do_signoff
4171bind .   <$M1B-Key-S> do_signoff
4172bind .   <$M1B-Key-i> do_add_all
4173bind .   <$M1B-Key-I> do_add_all
4174bind .   <$M1B-Key-Return> do_commit
4175bind all <$M1B-Key-q> do_quit
4176bind all <$M1B-Key-Q> do_quit
4177bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
4178bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
4179foreach i [list $ui_index $ui_workdir] {
4180        bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
4181        bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
4182        bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
4183}
4184unset i
4185
4186set file_lists($ui_index) [list]
4187set file_lists($ui_workdir) [list]
4188
4189set HEAD {}
4190set PARENT {}
4191set MERGE_HEAD [list]
4192set commit_type {}
4193set empty_tree {}
4194set current_branch {}
4195set current_diff_path {}
4196set selected_commit_type new
4197
4198wm title . "[appname] ([file normalize [file dirname [gitdir]]])"
4199focus -force $ui_comm
4200
4201# -- Warn the user about environmental problems.  Cygwin's Tcl
4202#    does *not* pass its env array onto any processes it spawns.
4203#    This means that git processes get none of our environment.
4204#
4205if {[is_Windows]} {
4206        set ignored_env 0
4207        set suggest_user {}
4208        set msg "Possible environment issues exist.
4209
4210The following environment variables are probably
4211going to be ignored by any Git subprocess run
4212by [appname]:
4213
4214"
4215        foreach name [array names env] {
4216                switch -regexp -- $name {
4217                {^GIT_INDEX_FILE$} -
4218                {^GIT_OBJECT_DIRECTORY$} -
4219                {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
4220                {^GIT_DIFF_OPTS$} -
4221                {^GIT_EXTERNAL_DIFF$} -
4222                {^GIT_PAGER$} -
4223                {^GIT_TRACE$} -
4224                {^GIT_CONFIG$} -
4225                {^GIT_CONFIG_LOCAL$} -
4226                {^GIT_(AUTHOR|COMMITTER)_DATE$} {
4227                        append msg " - $name\n"
4228                        incr ignored_env
4229                }
4230                {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
4231                        append msg " - $name\n"
4232                        incr ignored_env
4233                        set suggest_user $name
4234                }
4235                }
4236        }
4237        if {$ignored_env > 0} {
4238                append msg "
4239This is due to a known issue with the
4240Tcl binary distributed by Cygwin."
4241
4242                if {$suggest_user ne {}} {
4243                        append msg "
4244
4245A good replacement for $suggest_user
4246is placing values for the user.name and
4247user.email settings into your personal
4248~/.gitconfig file.
4249"
4250                }
4251                warn_popup $msg
4252        }
4253        unset ignored_env msg suggest_user name
4254}
4255
4256# -- Only initialize complex UI if we are going to stay running.
4257#
4258if {!$single_commit} {
4259        load_all_remotes
4260        load_all_heads
4261
4262        populate_branch_menu
4263        populate_fetch_menu .mbar.fetch
4264        populate_pull_menu .mbar.pull
4265        populate_push_menu .mbar.push
4266}
4267
4268# -- Only suggest a gc run if we are going to stay running.
4269#
4270if {!$single_commit} {
4271        set object_limit 2000
4272        if {[is_Windows]} {set object_limit 200}
4273        regexp {^([0-9]+) objects,} [exec git count-objects] _junk objects_current
4274        if {$objects_current >= $object_limit} {
4275                if {[ask_popup \
4276                        "This repository currently has $objects_current loose objects.
4277
4278To maintain optimal performance it is strongly
4279recommended that you compress the database
4280when more than $object_limit loose objects exist.
4281
4282Compress the database now?"] eq yes} {
4283                        do_gc
4284                }
4285        }
4286        unset object_limit _junk objects_current
4287}
4288
4289lock_index begin-read
4290after 1 do_rescan