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