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