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