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