]> asedeno.scripts.mit.edu Git - git.git/blob - git-gui.sh
git-gui: Expose the browser as a subcommand.
[git.git] / git-gui.sh
1 #!/bin/sh
2 # Tcl ignores the next line -*- tcl -*- \
3 exec wish "$0" -- "$@"
4
5 set appvers {@@GITGUI_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 _gitexec {}
30 set _reponame {}
31 set _iscygwin {}
32
33 proc appname {} {
34         global _appname
35         return $_appname
36 }
37
38 proc gitdir {args} {
39         global _gitdir
40         if {$args eq {}} {
41                 return $_gitdir
42         }
43         return [eval [concat [list file join $_gitdir] $args]]
44 }
45
46 proc gitexec {args} {
47         global _gitexec
48         if {$_gitexec eq {}} {
49                 if {[catch {set _gitexec [git --exec-path]} err]} {
50                         error "Git not installed?\n\n$err"
51                 }
52         }
53         if {$args eq {}} {
54                 return $_gitexec
55         }
56         return [eval [concat [list file join $_gitexec] $args]]
57 }
58
59 proc reponame {} {
60         global _reponame
61         return $_reponame
62 }
63
64 proc is_MacOSX {} {
65         global tcl_platform tk_library
66         if {[tk windowingsystem] eq {aqua}} {
67                 return 1
68         }
69         return 0
70 }
71
72 proc is_Windows {} {
73         global tcl_platform
74         if {$tcl_platform(platform) eq {windows}} {
75                 return 1
76         }
77         return 0
78 }
79
80 proc is_Cygwin {} {
81         global tcl_platform _iscygwin
82         if {$_iscygwin eq {}} {
83                 if {$tcl_platform(platform) eq {windows}} {
84                         if {[catch {set p [exec cygpath --windir]} err]} {
85                                 set _iscygwin 0
86                         } else {
87                                 set _iscygwin 1
88                         }
89                 } else {
90                         set _iscygwin 0
91                 }
92         }
93         return $_iscygwin
94 }
95
96 proc is_enabled {option} {
97         global enabled_options
98         if {[catch {set on $enabled_options($option)}]} {return 0}
99         return $on
100 }
101
102 proc enable_option {option} {
103         global enabled_options
104         set enabled_options($option) 1
105 }
106
107 proc disable_option {option} {
108         global enabled_options
109         set enabled_options($option) 0
110 }
111
112 ######################################################################
113 ##
114 ## config
115
116 proc is_many_config {name} {
117         switch -glob -- $name {
118         remote.*.fetch -
119         remote.*.push
120                 {return 1}
121         *
122                 {return 0}
123         }
124 }
125
126 proc is_config_true {name} {
127         global repo_config
128         if {[catch {set v $repo_config($name)}]} {
129                 return 0
130         } elseif {$v eq {true} || $v eq {1} || $v eq {yes}} {
131                 return 1
132         } else {
133                 return 0
134         }
135 }
136
137 proc load_config {include_global} {
138         global repo_config global_config default_config
139
140         array unset global_config
141         if {$include_global} {
142                 catch {
143                         set fd_rc [open "| git config --global --list" r]
144                         while {[gets $fd_rc line] >= 0} {
145                                 if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
146                                         if {[is_many_config $name]} {
147                                                 lappend global_config($name) $value
148                                         } else {
149                                                 set global_config($name) $value
150                                         }
151                                 }
152                         }
153                         close $fd_rc
154                 }
155         }
156
157         array unset repo_config
158         catch {
159                 set fd_rc [open "| git config --list" r]
160                 while {[gets $fd_rc line] >= 0} {
161                         if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
162                                 if {[is_many_config $name]} {
163                                         lappend repo_config($name) $value
164                                 } else {
165                                         set repo_config($name) $value
166                                 }
167                         }
168                 }
169                 close $fd_rc
170         }
171
172         foreach name [array names default_config] {
173                 if {[catch {set v $global_config($name)}]} {
174                         set global_config($name) $default_config($name)
175                 }
176                 if {[catch {set v $repo_config($name)}]} {
177                         set repo_config($name) $default_config($name)
178                 }
179         }
180 }
181
182 proc save_config {} {
183         global default_config font_descs
184         global repo_config global_config
185         global repo_config_new global_config_new
186
187         foreach option $font_descs {
188                 set name [lindex $option 0]
189                 set font [lindex $option 1]
190                 font configure $font \
191                         -family $global_config_new(gui.$font^^family) \
192                         -size $global_config_new(gui.$font^^size)
193                 font configure ${font}bold \
194                         -family $global_config_new(gui.$font^^family) \
195                         -size $global_config_new(gui.$font^^size)
196                 set global_config_new(gui.$name) [font configure $font]
197                 unset global_config_new(gui.$font^^family)
198                 unset global_config_new(gui.$font^^size)
199         }
200
201         foreach name [array names default_config] {
202                 set value $global_config_new($name)
203                 if {$value ne $global_config($name)} {
204                         if {$value eq $default_config($name)} {
205                                 catch {git config --global --unset $name}
206                         } else {
207                                 regsub -all "\[{}\]" $value {"} value
208                                 git config --global $name $value
209                         }
210                         set global_config($name) $value
211                         if {$value eq $repo_config($name)} {
212                                 catch {git config --unset $name}
213                                 set repo_config($name) $value
214                         }
215                 }
216         }
217
218         foreach name [array names default_config] {
219                 set value $repo_config_new($name)
220                 if {$value ne $repo_config($name)} {
221                         if {$value eq $global_config($name)} {
222                                 catch {git config --unset $name}
223                         } else {
224                                 regsub -all "\[{}\]" $value {"} value
225                                 git config $name $value
226                         }
227                         set repo_config($name) $value
228                 }
229         }
230 }
231
232 ######################################################################
233 ##
234 ## handy utils
235
236 proc git {args} {
237         return [eval exec git $args]
238 }
239
240 proc error_popup {msg} {
241         set title [appname]
242         if {[reponame] ne {}} {
243                 append title " ([reponame])"
244         }
245         set cmd [list tk_messageBox \
246                 -icon error \
247                 -type ok \
248                 -title "$title: error" \
249                 -message $msg]
250         if {[winfo ismapped .]} {
251                 lappend cmd -parent .
252         }
253         eval $cmd
254 }
255
256 proc warn_popup {msg} {
257         set title [appname]
258         if {[reponame] ne {}} {
259                 append title " ([reponame])"
260         }
261         set cmd [list tk_messageBox \
262                 -icon warning \
263                 -type ok \
264                 -title "$title: warning" \
265                 -message $msg]
266         if {[winfo ismapped .]} {
267                 lappend cmd -parent .
268         }
269         eval $cmd
270 }
271
272 proc info_popup {msg {parent .}} {
273         set title [appname]
274         if {[reponame] ne {}} {
275                 append title " ([reponame])"
276         }
277         tk_messageBox \
278                 -parent $parent \
279                 -icon info \
280                 -type ok \
281                 -title $title \
282                 -message $msg
283 }
284
285 proc ask_popup {msg} {
286         set title [appname]
287         if {[reponame] ne {}} {
288                 append title " ([reponame])"
289         }
290         return [tk_messageBox \
291                 -parent . \
292                 -icon question \
293                 -type yesno \
294                 -title $title \
295                 -message $msg]
296 }
297
298 ######################################################################
299 ##
300 ## version check
301
302 set req_maj 1
303 set req_min 5
304
305 if {[catch {set v [git --version]} err]} {
306         catch {wm withdraw .}
307         error_popup "Cannot determine Git version:
308
309 $err
310
311 [appname] requires Git $req_maj.$req_min or later."
312         exit 1
313 }
314 if {[regexp {^git version (\d+)\.(\d+)} $v _junk act_maj act_min]} {
315         if {$act_maj < $req_maj
316                 || ($act_maj == $req_maj && $act_min < $req_min)} {
317                 catch {wm withdraw .}
318                 error_popup "[appname] requires Git $req_maj.$req_min or later.
319
320 You are using $v."
321                 exit 1
322         }
323 } else {
324         catch {wm withdraw .}
325         error_popup "Cannot parse Git version string:\n\n$v"
326         exit 1
327 }
328 unset -nocomplain v _junk act_maj act_min req_maj req_min
329
330 ######################################################################
331 ##
332 ## repository setup
333
334 if {   [catch {set _gitdir $env(GIT_DIR)}]
335         && [catch {set _gitdir [git rev-parse --git-dir]} err]} {
336         catch {wm withdraw .}
337         error_popup "Cannot find the git directory:\n\n$err"
338         exit 1
339 }
340 if {![file isdirectory $_gitdir] && [is_Cygwin]} {
341         catch {set _gitdir [exec cygpath --unix $_gitdir]}
342 }
343 if {![file isdirectory $_gitdir]} {
344         catch {wm withdraw .}
345         error_popup "Git directory not found:\n\n$_gitdir"
346         exit 1
347 }
348 if {[lindex [file split $_gitdir] end] ne {.git}} {
349         catch {wm withdraw .}
350         error_popup "Cannot use funny .git directory:\n\n$_gitdir"
351         exit 1
352 }
353 if {[catch {cd [file dirname $_gitdir]} err]} {
354         catch {wm withdraw .}
355         error_popup "No working directory [file dirname $_gitdir]:\n\n$err"
356         exit 1
357 }
358 set _reponame [lindex [file split \
359         [file normalize [file dirname $_gitdir]]] \
360         end]
361
362 ######################################################################
363 ##
364 ## task management
365
366 set rescan_active 0
367 set diff_active 0
368 set last_clicked {}
369
370 set disable_on_lock [list]
371 set index_lock_type none
372
373 proc lock_index {type} {
374         global index_lock_type disable_on_lock
375
376         if {$index_lock_type eq {none}} {
377                 set index_lock_type $type
378                 foreach w $disable_on_lock {
379                         uplevel #0 $w disabled
380                 }
381                 return 1
382         } elseif {$index_lock_type eq "begin-$type"} {
383                 set index_lock_type $type
384                 return 1
385         }
386         return 0
387 }
388
389 proc unlock_index {} {
390         global index_lock_type disable_on_lock
391
392         set index_lock_type none
393         foreach w $disable_on_lock {
394                 uplevel #0 $w normal
395         }
396 }
397
398 ######################################################################
399 ##
400 ## status
401
402 proc repository_state {ctvar hdvar mhvar} {
403         global current_branch
404         upvar $ctvar ct $hdvar hd $mhvar mh
405
406         set mh [list]
407
408         if {[catch {set current_branch [git symbolic-ref HEAD]}]} {
409                 set current_branch {}
410         } else {
411                 regsub ^refs/((heads|tags|remotes)/)? \
412                         $current_branch \
413                         {} \
414                         current_branch
415         }
416
417         if {[catch {set hd [git rev-parse --verify HEAD]}]} {
418                 set hd {}
419                 set ct initial
420                 return
421         }
422
423         set merge_head [gitdir MERGE_HEAD]
424         if {[file exists $merge_head]} {
425                 set ct merge
426                 set fd_mh [open $merge_head r]
427                 while {[gets $fd_mh line] >= 0} {
428                         lappend mh $line
429                 }
430                 close $fd_mh
431                 return
432         }
433
434         set ct normal
435 }
436
437 proc PARENT {} {
438         global PARENT empty_tree
439
440         set p [lindex $PARENT 0]
441         if {$p ne {}} {
442                 return $p
443         }
444         if {$empty_tree eq {}} {
445                 set empty_tree [git mktree << {}]
446         }
447         return $empty_tree
448 }
449
450 proc rescan {after {honor_trustmtime 1}} {
451         global HEAD PARENT MERGE_HEAD commit_type
452         global ui_index ui_workdir ui_status_value ui_comm
453         global rescan_active file_states
454         global repo_config
455
456         if {$rescan_active > 0 || ![lock_index read]} return
457
458         repository_state newType newHEAD newMERGE_HEAD
459         if {[string match amend* $commit_type]
460                 && $newType eq {normal}
461                 && $newHEAD eq $HEAD} {
462         } else {
463                 set HEAD $newHEAD
464                 set PARENT $newHEAD
465                 set MERGE_HEAD $newMERGE_HEAD
466                 set commit_type $newType
467         }
468
469         array unset file_states
470
471         if {![$ui_comm edit modified]
472                 || [string trim [$ui_comm get 0.0 end]] eq {}} {
473                 if {[load_message GITGUI_MSG]} {
474                 } elseif {[load_message MERGE_MSG]} {
475                 } elseif {[load_message SQUASH_MSG]} {
476                 }
477                 $ui_comm edit reset
478                 $ui_comm edit modified false
479         }
480
481         if {[is_enabled branch]} {
482                 load_all_heads
483                 populate_branch_menu
484         }
485
486         if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
487                 rescan_stage2 {} $after
488         } else {
489                 set rescan_active 1
490                 set ui_status_value {Refreshing file status...}
491                 set cmd [list git update-index]
492                 lappend cmd -q
493                 lappend cmd --unmerged
494                 lappend cmd --ignore-missing
495                 lappend cmd --refresh
496                 set fd_rf [open "| $cmd" r]
497                 fconfigure $fd_rf -blocking 0 -translation binary
498                 fileevent $fd_rf readable \
499                         [list rescan_stage2 $fd_rf $after]
500         }
501 }
502
503 proc rescan_stage2 {fd after} {
504         global ui_status_value
505         global rescan_active buf_rdi buf_rdf buf_rlo
506
507         if {$fd ne {}} {
508                 read $fd
509                 if {![eof $fd]} return
510                 close $fd
511         }
512
513         set ls_others [list | git ls-files --others -z \
514                 --exclude-per-directory=.gitignore]
515         set info_exclude [gitdir info exclude]
516         if {[file readable $info_exclude]} {
517                 lappend ls_others "--exclude-from=$info_exclude"
518         }
519
520         set buf_rdi {}
521         set buf_rdf {}
522         set buf_rlo {}
523
524         set rescan_active 3
525         set ui_status_value {Scanning for modified files ...}
526         set fd_di [open "| git diff-index --cached -z [PARENT]" r]
527         set fd_df [open "| git diff-files -z" r]
528         set fd_lo [open $ls_others r]
529
530         fconfigure $fd_di -blocking 0 -translation binary -encoding binary
531         fconfigure $fd_df -blocking 0 -translation binary -encoding binary
532         fconfigure $fd_lo -blocking 0 -translation binary -encoding binary
533         fileevent $fd_di readable [list read_diff_index $fd_di $after]
534         fileevent $fd_df readable [list read_diff_files $fd_df $after]
535         fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
536 }
537
538 proc load_message {file} {
539         global ui_comm
540
541         set f [gitdir $file]
542         if {[file isfile $f]} {
543                 if {[catch {set fd [open $f r]}]} {
544                         return 0
545                 }
546                 set content [string trim [read $fd]]
547                 close $fd
548                 regsub -all -line {[ \r\t]+$} $content {} content
549                 $ui_comm delete 0.0 end
550                 $ui_comm insert end $content
551                 return 1
552         }
553         return 0
554 }
555
556 proc read_diff_index {fd after} {
557         global buf_rdi
558
559         append buf_rdi [read $fd]
560         set c 0
561         set n [string length $buf_rdi]
562         while {$c < $n} {
563                 set z1 [string first "\0" $buf_rdi $c]
564                 if {$z1 == -1} break
565                 incr z1
566                 set z2 [string first "\0" $buf_rdi $z1]
567                 if {$z2 == -1} break
568
569                 incr c
570                 set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
571                 set p [string range $buf_rdi $z1 [expr {$z2 - 1}]]
572                 merge_state \
573                         [encoding convertfrom $p] \
574                         [lindex $i 4]? \
575                         [list [lindex $i 0] [lindex $i 2]] \
576                         [list]
577                 set c $z2
578                 incr c
579         }
580         if {$c < $n} {
581                 set buf_rdi [string range $buf_rdi $c end]
582         } else {
583                 set buf_rdi {}
584         }
585
586         rescan_done $fd buf_rdi $after
587 }
588
589 proc read_diff_files {fd after} {
590         global buf_rdf
591
592         append buf_rdf [read $fd]
593         set c 0
594         set n [string length $buf_rdf]
595         while {$c < $n} {
596                 set z1 [string first "\0" $buf_rdf $c]
597                 if {$z1 == -1} break
598                 incr z1
599                 set z2 [string first "\0" $buf_rdf $z1]
600                 if {$z2 == -1} break
601
602                 incr c
603                 set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
604                 set p [string range $buf_rdf $z1 [expr {$z2 - 1}]]
605                 merge_state \
606                         [encoding convertfrom $p] \
607                         ?[lindex $i 4] \
608                         [list] \
609                         [list [lindex $i 0] [lindex $i 2]]
610                 set c $z2
611                 incr c
612         }
613         if {$c < $n} {
614                 set buf_rdf [string range $buf_rdf $c end]
615         } else {
616                 set buf_rdf {}
617         }
618
619         rescan_done $fd buf_rdf $after
620 }
621
622 proc read_ls_others {fd after} {
623         global buf_rlo
624
625         append buf_rlo [read $fd]
626         set pck [split $buf_rlo "\0"]
627         set buf_rlo [lindex $pck end]
628         foreach p [lrange $pck 0 end-1] {
629                 merge_state [encoding convertfrom $p] ?O
630         }
631         rescan_done $fd buf_rlo $after
632 }
633
634 proc rescan_done {fd buf after} {
635         global rescan_active
636         global file_states repo_config
637         upvar $buf to_clear
638
639         if {![eof $fd]} return
640         set to_clear {}
641         close $fd
642         if {[incr rescan_active -1] > 0} return
643
644         prune_selection
645         unlock_index
646         display_all_files
647         reshow_diff
648         uplevel #0 $after
649 }
650
651 proc prune_selection {} {
652         global file_states selected_paths
653
654         foreach path [array names selected_paths] {
655                 if {[catch {set still_here $file_states($path)}]} {
656                         unset selected_paths($path)
657                 }
658         }
659 }
660
661 ######################################################################
662 ##
663 ## diff
664
665 proc clear_diff {} {
666         global ui_diff current_diff_path current_diff_header
667         global ui_index ui_workdir
668
669         $ui_diff conf -state normal
670         $ui_diff delete 0.0 end
671         $ui_diff conf -state disabled
672
673         set current_diff_path {}
674         set current_diff_header {}
675
676         $ui_index tag remove in_diff 0.0 end
677         $ui_workdir tag remove in_diff 0.0 end
678 }
679
680 proc reshow_diff {} {
681         global ui_status_value file_states file_lists
682         global current_diff_path current_diff_side
683
684         set p $current_diff_path
685         if {$p eq {}
686                 || $current_diff_side eq {}
687                 || [catch {set s $file_states($p)}]
688                 || [lsearch -sorted -exact $file_lists($current_diff_side) $p] == -1} {
689                 clear_diff
690         } else {
691                 show_diff $p $current_diff_side
692         }
693 }
694
695 proc handle_empty_diff {} {
696         global current_diff_path file_states file_lists
697
698         set path $current_diff_path
699         set s $file_states($path)
700         if {[lindex $s 0] ne {_M}} return
701
702         info_popup "No differences detected.
703
704 [short_path $path] has no changes.
705
706 The modification date of this file was updated
707 by another application, but the content within
708 the file was not changed.
709
710 A rescan will be automatically started to find
711 other files which may have the same state."
712
713         clear_diff
714         display_file $path __
715         rescan {set ui_status_value {Ready.}} 0
716 }
717
718 proc show_diff {path w {lno {}}} {
719         global file_states file_lists
720         global is_3way_diff diff_active repo_config
721         global ui_diff ui_status_value ui_index ui_workdir
722         global current_diff_path current_diff_side current_diff_header
723
724         if {$diff_active || ![lock_index read]} return
725
726         clear_diff
727         if {$lno == {}} {
728                 set lno [lsearch -sorted -exact $file_lists($w) $path]
729                 if {$lno >= 0} {
730                         incr lno
731                 }
732         }
733         if {$lno >= 1} {
734                 $w tag add in_diff $lno.0 [expr {$lno + 1}].0
735         }
736
737         set s $file_states($path)
738         set m [lindex $s 0]
739         set is_3way_diff 0
740         set diff_active 1
741         set current_diff_path $path
742         set current_diff_side $w
743         set current_diff_header {}
744         set ui_status_value "Loading diff of [escape_path $path]..."
745
746         # - Git won't give us the diff, there's nothing to compare to!
747         #
748         if {$m eq {_O}} {
749                 set max_sz [expr {128 * 1024}]
750                 if {[catch {
751                                 set fd [open $path r]
752                                 set content [read $fd $max_sz]
753                                 close $fd
754                                 set sz [file size $path]
755                         } err ]} {
756                         set diff_active 0
757                         unlock_index
758                         set ui_status_value "Unable to display [escape_path $path]"
759                         error_popup "Error loading file:\n\n$err"
760                         return
761                 }
762                 $ui_diff conf -state normal
763                 if {![catch {set type [exec file $path]}]} {
764                         set n [string length $path]
765                         if {[string equal -length $n $path $type]} {
766                                 set type [string range $type $n end]
767                                 regsub {^:?\s*} $type {} type
768                         }
769                         $ui_diff insert end "* $type\n" d_@
770                 }
771                 if {[string first "\0" $content] != -1} {
772                         $ui_diff insert end \
773                                 "* Binary file (not showing content)." \
774                                 d_@
775                 } else {
776                         if {$sz > $max_sz} {
777                                 $ui_diff insert end \
778 "* Untracked file is $sz bytes.
779 * Showing only first $max_sz bytes.
780 " d_@
781                         }
782                         $ui_diff insert end $content
783                         if {$sz > $max_sz} {
784                                 $ui_diff insert end "
785 * Untracked file clipped here by [appname].
786 * To see the entire file, use an external editor.
787 " d_@
788                         }
789                 }
790                 $ui_diff conf -state disabled
791                 set diff_active 0
792                 unlock_index
793                 set ui_status_value {Ready.}
794                 return
795         }
796
797         set cmd [list | git]
798         if {$w eq $ui_index} {
799                 lappend cmd diff-index
800                 lappend cmd --cached
801         } elseif {$w eq $ui_workdir} {
802                 if {[string index $m 0] eq {U}} {
803                         lappend cmd diff
804                 } else {
805                         lappend cmd diff-files
806                 }
807         }
808
809         lappend cmd -p
810         lappend cmd --no-color
811         if {$repo_config(gui.diffcontext) > 0} {
812                 lappend cmd "-U$repo_config(gui.diffcontext)"
813         }
814         if {$w eq $ui_index} {
815                 lappend cmd [PARENT]
816         }
817         lappend cmd --
818         lappend cmd $path
819
820         if {[catch {set fd [open $cmd r]} err]} {
821                 set diff_active 0
822                 unlock_index
823                 set ui_status_value "Unable to display [escape_path $path]"
824                 error_popup "Error loading diff:\n\n$err"
825                 return
826         }
827
828         fconfigure $fd \
829                 -blocking 0 \
830                 -encoding binary \
831                 -translation binary
832         fileevent $fd readable [list read_diff $fd]
833 }
834
835 proc read_diff {fd} {
836         global ui_diff ui_status_value diff_active
837         global is_3way_diff current_diff_header
838
839         $ui_diff conf -state normal
840         while {[gets $fd line] >= 0} {
841                 # -- Cleanup uninteresting diff header lines.
842                 #
843                 if {   [string match {diff --git *}      $line]
844                         || [string match {diff --cc *}       $line]
845                         || [string match {diff --combined *} $line]
846                         || [string match {--- *}             $line]
847                         || [string match {+++ *}             $line]} {
848                         append current_diff_header $line "\n"
849                         continue
850                 }
851                 if {[string match {index *} $line]} continue
852                 if {$line eq {deleted file mode 120000}} {
853                         set line "deleted symlink"
854                 }
855
856                 # -- Automatically detect if this is a 3 way diff.
857                 #
858                 if {[string match {@@@ *} $line]} {set is_3way_diff 1}
859
860                 if {[string match {mode *} $line]
861                         || [string match {new file *} $line]
862                         || [string match {deleted file *} $line]
863                         || [string match {Binary files * and * differ} $line]
864                         || $line eq {\ No newline at end of file}
865                         || [regexp {^\* Unmerged path } $line]} {
866                         set tags {}
867                 } elseif {$is_3way_diff} {
868                         set op [string range $line 0 1]
869                         switch -- $op {
870                         {  } {set tags {}}
871                         {@@} {set tags d_@}
872                         { +} {set tags d_s+}
873                         { -} {set tags d_s-}
874                         {+ } {set tags d_+s}
875                         {- } {set tags d_-s}
876                         {--} {set tags d_--}
877                         {++} {
878                                 if {[regexp {^\+\+([<>]{7} |={7})} $line _g op]} {
879                                         set line [string replace $line 0 1 {  }]
880                                         set tags d$op
881                                 } else {
882                                         set tags d_++
883                                 }
884                         }
885                         default {
886                                 puts "error: Unhandled 3 way diff marker: {$op}"
887                                 set tags {}
888                         }
889                         }
890                 } else {
891                         set op [string index $line 0]
892                         switch -- $op {
893                         { } {set tags {}}
894                         {@} {set tags d_@}
895                         {-} {set tags d_-}
896                         {+} {
897                                 if {[regexp {^\+([<>]{7} |={7})} $line _g op]} {
898                                         set line [string replace $line 0 0 { }]
899                                         set tags d$op
900                                 } else {
901                                         set tags d_+
902                                 }
903                         }
904                         default {
905                                 puts "error: Unhandled 2 way diff marker: {$op}"
906                                 set tags {}
907                         }
908                         }
909                 }
910                 $ui_diff insert end $line $tags
911                 if {[string index $line end] eq "\r"} {
912                         $ui_diff tag add d_cr {end - 2c}
913                 }
914                 $ui_diff insert end "\n" $tags
915         }
916         $ui_diff conf -state disabled
917
918         if {[eof $fd]} {
919                 close $fd
920                 set diff_active 0
921                 unlock_index
922                 set ui_status_value {Ready.}
923
924                 if {[$ui_diff index end] eq {2.0}} {
925                         handle_empty_diff
926                 }
927         }
928 }
929
930 proc apply_hunk {x y} {
931         global current_diff_path current_diff_header current_diff_side
932         global ui_diff ui_index file_states
933
934         if {$current_diff_path eq {} || $current_diff_header eq {}} return
935         if {![lock_index apply_hunk]} return
936
937         set apply_cmd {git apply --cached --whitespace=nowarn}
938         set mi [lindex $file_states($current_diff_path) 0]
939         if {$current_diff_side eq $ui_index} {
940                 set mode unstage
941                 lappend apply_cmd --reverse
942                 if {[string index $mi 0] ne {M}} {
943                         unlock_index
944                         return
945                 }
946         } else {
947                 set mode stage
948                 if {[string index $mi 1] ne {M}} {
949                         unlock_index
950                         return
951                 }
952         }
953
954         set s_lno [lindex [split [$ui_diff index @$x,$y] .] 0]
955         set s_lno [$ui_diff search -backwards -regexp ^@@ $s_lno.0 0.0]
956         if {$s_lno eq {}} {
957                 unlock_index
958                 return
959         }
960
961         set e_lno [$ui_diff search -forwards -regexp ^@@ "$s_lno + 1 lines" end]
962         if {$e_lno eq {}} {
963                 set e_lno end
964         }
965
966         if {[catch {
967                 set p [open "| $apply_cmd" w]
968                 fconfigure $p -translation binary -encoding binary
969                 puts -nonewline $p $current_diff_header
970                 puts -nonewline $p [$ui_diff get $s_lno $e_lno]
971                 close $p} err]} {
972                 error_popup "Failed to $mode selected hunk.\n\n$err"
973                 unlock_index
974                 return
975         }
976
977         $ui_diff conf -state normal
978         $ui_diff delete $s_lno $e_lno
979         $ui_diff conf -state disabled
980
981         if {[$ui_diff get 1.0 end] eq "\n"} {
982                 set o _
983         } else {
984                 set o ?
985         }
986
987         if {$current_diff_side eq $ui_index} {
988                 set mi ${o}M
989         } elseif {[string index $mi 0] eq {_}} {
990                 set mi M$o
991         } else {
992                 set mi ?$o
993         }
994         unlock_index
995         display_file $current_diff_path $mi
996         if {$o eq {_}} {
997                 clear_diff
998         }
999 }
1000
1001 ######################################################################
1002 ##
1003 ## commit
1004
1005 proc load_last_commit {} {
1006         global HEAD PARENT MERGE_HEAD commit_type ui_comm
1007         global repo_config
1008
1009         if {[llength $PARENT] == 0} {
1010                 error_popup {There is nothing to amend.
1011
1012 You are about to create the initial commit.
1013 There is no commit before this to amend.
1014 }
1015                 return
1016         }
1017
1018         repository_state curType curHEAD curMERGE_HEAD
1019         if {$curType eq {merge}} {
1020                 error_popup {Cannot amend while merging.
1021
1022 You are currently in the middle of a merge that
1023 has not been fully completed.  You cannot amend
1024 the prior commit unless you first abort the
1025 current merge activity.
1026 }
1027                 return
1028         }
1029
1030         set msg {}
1031         set parents [list]
1032         if {[catch {
1033                         set fd [open "| git cat-file commit $curHEAD" r]
1034                         fconfigure $fd -encoding binary -translation lf
1035                         if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
1036                                 set enc utf-8
1037                         }
1038                         while {[gets $fd line] > 0} {
1039                                 if {[string match {parent *} $line]} {
1040                                         lappend parents [string range $line 7 end]
1041                                 } elseif {[string match {encoding *} $line]} {
1042                                         set enc [string tolower [string range $line 9 end]]
1043                                 }
1044                         }
1045                         fconfigure $fd -encoding $enc
1046                         set msg [string trim [read $fd]]
1047                         close $fd
1048                 } err]} {
1049                 error_popup "Error loading commit data for amend:\n\n$err"
1050                 return
1051         }
1052
1053         set HEAD $curHEAD
1054         set PARENT $parents
1055         set MERGE_HEAD [list]
1056         switch -- [llength $parents] {
1057         0       {set commit_type amend-initial}
1058         1       {set commit_type amend}
1059         default {set commit_type amend-merge}
1060         }
1061
1062         $ui_comm delete 0.0 end
1063         $ui_comm insert end $msg
1064         $ui_comm edit reset
1065         $ui_comm edit modified false
1066         rescan {set ui_status_value {Ready.}}
1067 }
1068
1069 proc create_new_commit {} {
1070         global commit_type ui_comm
1071
1072         set commit_type normal
1073         $ui_comm delete 0.0 end
1074         $ui_comm edit reset
1075         $ui_comm edit modified false
1076         rescan {set ui_status_value {Ready.}}
1077 }
1078
1079 set GIT_COMMITTER_IDENT {}
1080
1081 proc committer_ident {} {
1082         global GIT_COMMITTER_IDENT
1083
1084         if {$GIT_COMMITTER_IDENT eq {}} {
1085                 if {[catch {set me [git var GIT_COMMITTER_IDENT]} err]} {
1086                         error_popup "Unable to obtain your identity:\n\n$err"
1087                         return {}
1088                 }
1089                 if {![regexp {^(.*) [0-9]+ [-+0-9]+$} \
1090                         $me me GIT_COMMITTER_IDENT]} {
1091                         error_popup "Invalid GIT_COMMITTER_IDENT:\n\n$me"
1092                         return {}
1093                 }
1094         }
1095
1096         return $GIT_COMMITTER_IDENT
1097 }
1098
1099 proc commit_tree {} {
1100         global HEAD commit_type file_states ui_comm repo_config
1101         global ui_status_value pch_error
1102
1103         if {[committer_ident] eq {}} return
1104         if {![lock_index update]} return
1105
1106         # -- Our in memory state should match the repository.
1107         #
1108         repository_state curType curHEAD curMERGE_HEAD
1109         if {[string match amend* $commit_type]
1110                 && $curType eq {normal}
1111                 && $curHEAD eq $HEAD} {
1112         } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
1113                 info_popup {Last scanned state does not match repository state.
1114
1115 Another Git program has modified this repository
1116 since the last scan.  A rescan must be performed
1117 before another commit can be created.
1118
1119 The rescan will be automatically started now.
1120 }
1121                 unlock_index
1122                 rescan {set ui_status_value {Ready.}}
1123                 return
1124         }
1125
1126         # -- At least one file should differ in the index.
1127         #
1128         set files_ready 0
1129         foreach path [array names file_states] {
1130                 switch -glob -- [lindex $file_states($path) 0] {
1131                 _? {continue}
1132                 A? -
1133                 D? -
1134                 M? {set files_ready 1}
1135                 U? {
1136                         error_popup "Unmerged files cannot be committed.
1137
1138 File [short_path $path] has merge conflicts.
1139 You must resolve them and add the file before committing.
1140 "
1141                         unlock_index
1142                         return
1143                 }
1144                 default {
1145                         error_popup "Unknown file state [lindex $s 0] detected.
1146
1147 File [short_path $path] cannot be committed by this program.
1148 "
1149                 }
1150                 }
1151         }
1152         if {!$files_ready} {
1153                 info_popup {No changes to commit.
1154
1155 You must add at least 1 file before you can commit.
1156 }
1157                 unlock_index
1158                 return
1159         }
1160
1161         # -- A message is required.
1162         #
1163         set msg [string trim [$ui_comm get 1.0 end]]
1164         regsub -all -line {[ \t\r]+$} $msg {} msg
1165         if {$msg eq {}} {
1166                 error_popup {Please supply a commit message.
1167
1168 A good commit message has the following format:
1169
1170 - First line: Describe in one sentance what you did.
1171 - Second line: Blank
1172 - Remaining lines: Describe why this change is good.
1173 }
1174                 unlock_index
1175                 return
1176         }
1177
1178         # -- Run the pre-commit hook.
1179         #
1180         set pchook [gitdir hooks pre-commit]
1181
1182         # On Cygwin [file executable] might lie so we need to ask
1183         # the shell if the hook is executable.  Yes that's annoying.
1184         #
1185         if {[is_Cygwin] && [file isfile $pchook]} {
1186                 set pchook [list sh -c [concat \
1187                         "if test -x \"$pchook\";" \
1188                         "then exec \"$pchook\" 2>&1;" \
1189                         "fi"]]
1190         } elseif {[file executable $pchook]} {
1191                 set pchook [list $pchook |& cat]
1192         } else {
1193                 commit_writetree $curHEAD $msg
1194                 return
1195         }
1196
1197         set ui_status_value {Calling pre-commit hook...}
1198         set pch_error {}
1199         set fd_ph [open "| $pchook" r]
1200         fconfigure $fd_ph -blocking 0 -translation binary
1201         fileevent $fd_ph readable \
1202                 [list commit_prehook_wait $fd_ph $curHEAD $msg]
1203 }
1204
1205 proc commit_prehook_wait {fd_ph curHEAD msg} {
1206         global pch_error ui_status_value
1207
1208         append pch_error [read $fd_ph]
1209         fconfigure $fd_ph -blocking 1
1210         if {[eof $fd_ph]} {
1211                 if {[catch {close $fd_ph}]} {
1212                         set ui_status_value {Commit declined by pre-commit hook.}
1213                         hook_failed_popup pre-commit $pch_error
1214                         unlock_index
1215                 } else {
1216                         commit_writetree $curHEAD $msg
1217                 }
1218                 set pch_error {}
1219                 return
1220         }
1221         fconfigure $fd_ph -blocking 0
1222 }
1223
1224 proc commit_writetree {curHEAD msg} {
1225         global ui_status_value
1226
1227         set ui_status_value {Committing changes...}
1228         set fd_wt [open "| git write-tree" r]
1229         fileevent $fd_wt readable \
1230                 [list commit_committree $fd_wt $curHEAD $msg]
1231 }
1232
1233 proc commit_committree {fd_wt curHEAD msg} {
1234         global HEAD PARENT MERGE_HEAD commit_type
1235         global all_heads current_branch
1236         global ui_status_value ui_comm selected_commit_type
1237         global file_states selected_paths rescan_active
1238         global repo_config
1239
1240         gets $fd_wt tree_id
1241         if {$tree_id eq {} || [catch {close $fd_wt} err]} {
1242                 error_popup "write-tree failed:\n\n$err"
1243                 set ui_status_value {Commit failed.}
1244                 unlock_index
1245                 return
1246         }
1247
1248         # -- Build the message.
1249         #
1250         set msg_p [gitdir COMMIT_EDITMSG]
1251         set msg_wt [open $msg_p w]
1252         if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
1253                 set enc utf-8
1254         }
1255         fconfigure $msg_wt -encoding $enc -translation binary
1256         puts -nonewline $msg_wt $msg
1257         close $msg_wt
1258
1259         # -- Create the commit.
1260         #
1261         set cmd [list git commit-tree $tree_id]
1262         set parents [concat $PARENT $MERGE_HEAD]
1263         if {[llength $parents] > 0} {
1264                 foreach p $parents {
1265                         lappend cmd -p $p
1266                 }
1267         } else {
1268                 # git commit-tree writes to stderr during initial commit.
1269                 lappend cmd 2>/dev/null
1270         }
1271         lappend cmd <$msg_p
1272         if {[catch {set cmt_id [eval exec $cmd]} err]} {
1273                 error_popup "commit-tree failed:\n\n$err"
1274                 set ui_status_value {Commit failed.}
1275                 unlock_index
1276                 return
1277         }
1278
1279         # -- Update the HEAD ref.
1280         #
1281         set reflogm commit
1282         if {$commit_type ne {normal}} {
1283                 append reflogm " ($commit_type)"
1284         }
1285         set i [string first "\n" $msg]
1286         if {$i >= 0} {
1287                 append reflogm {: } [string range $msg 0 [expr {$i - 1}]]
1288         } else {
1289                 append reflogm {: } $msg
1290         }
1291         set cmd [list git update-ref -m $reflogm HEAD $cmt_id $curHEAD]
1292         if {[catch {eval exec $cmd} err]} {
1293                 error_popup "update-ref failed:\n\n$err"
1294                 set ui_status_value {Commit failed.}
1295                 unlock_index
1296                 return
1297         }
1298
1299         # -- Make sure our current branch exists.
1300         #
1301         if {$commit_type eq {initial}} {
1302                 lappend all_heads $current_branch
1303                 set all_heads [lsort -unique $all_heads]
1304                 populate_branch_menu
1305         }
1306
1307         # -- Cleanup after ourselves.
1308         #
1309         catch {file delete $msg_p}
1310         catch {file delete [gitdir MERGE_HEAD]}
1311         catch {file delete [gitdir MERGE_MSG]}
1312         catch {file delete [gitdir SQUASH_MSG]}
1313         catch {file delete [gitdir GITGUI_MSG]}
1314
1315         # -- Let rerere do its thing.
1316         #
1317         if {[file isdirectory [gitdir rr-cache]]} {
1318                 catch {git rerere}
1319         }
1320
1321         # -- Run the post-commit hook.
1322         #
1323         set pchook [gitdir hooks post-commit]
1324         if {[is_Cygwin] && [file isfile $pchook]} {
1325                 set pchook [list sh -c [concat \
1326                         "if test -x \"$pchook\";" \
1327                         "then exec \"$pchook\";" \
1328                         "fi"]]
1329         } elseif {![file executable $pchook]} {
1330                 set pchook {}
1331         }
1332         if {$pchook ne {}} {
1333                 catch {exec $pchook &}
1334         }
1335
1336         $ui_comm delete 0.0 end
1337         $ui_comm edit reset
1338         $ui_comm edit modified false
1339
1340         if {[is_enabled singlecommit]} do_quit
1341
1342         # -- Update in memory status
1343         #
1344         set selected_commit_type new
1345         set commit_type normal
1346         set HEAD $cmt_id
1347         set PARENT $cmt_id
1348         set MERGE_HEAD [list]
1349
1350         foreach path [array names file_states] {
1351                 set s $file_states($path)
1352                 set m [lindex $s 0]
1353                 switch -glob -- $m {
1354                 _O -
1355                 _M -
1356                 _D {continue}
1357                 __ -
1358                 A_ -
1359                 M_ -
1360                 D_ {
1361                         unset file_states($path)
1362                         catch {unset selected_paths($path)}
1363                 }
1364                 DO {
1365                         set file_states($path) [list _O [lindex $s 1] {} {}]
1366                 }
1367                 AM -
1368                 AD -
1369                 MM -
1370                 MD {
1371                         set file_states($path) [list \
1372                                 _[string index $m 1] \
1373                                 [lindex $s 1] \
1374                                 [lindex $s 3] \
1375                                 {}]
1376                 }
1377                 }
1378         }
1379
1380         display_all_files
1381         unlock_index
1382         reshow_diff
1383         set ui_status_value \
1384                 "Changes committed as [string range $cmt_id 0 7]."
1385 }
1386
1387 ######################################################################
1388 ##
1389 ## fetch push
1390
1391 proc fetch_from {remote} {
1392         set w [new_console \
1393                 "fetch $remote" \
1394                 "Fetching new changes from $remote"]
1395         set cmd [list git fetch]
1396         lappend cmd $remote
1397         console_exec $w $cmd console_done
1398 }
1399
1400 proc push_to {remote} {
1401         set w [new_console \
1402                 "push $remote" \
1403                 "Pushing changes to $remote"]
1404         set cmd [list git push]
1405         lappend cmd -v
1406         lappend cmd $remote
1407         console_exec $w $cmd console_done
1408 }
1409
1410 ######################################################################
1411 ##
1412 ## ui helpers
1413
1414 proc mapicon {w state path} {
1415         global all_icons
1416
1417         if {[catch {set r $all_icons($state$w)}]} {
1418                 puts "error: no icon for $w state={$state} $path"
1419                 return file_plain
1420         }
1421         return $r
1422 }
1423
1424 proc mapdesc {state path} {
1425         global all_descs
1426
1427         if {[catch {set r $all_descs($state)}]} {
1428                 puts "error: no desc for state={$state} $path"
1429                 return $state
1430         }
1431         return $r
1432 }
1433
1434 proc escape_path {path} {
1435         regsub -all {\\} $path "\\\\" path
1436         regsub -all "\n" $path "\\n" path
1437         return $path
1438 }
1439
1440 proc short_path {path} {
1441         return [escape_path [lindex [file split $path] end]]
1442 }
1443
1444 set next_icon_id 0
1445 set null_sha1 [string repeat 0 40]
1446
1447 proc merge_state {path new_state {head_info {}} {index_info {}}} {
1448         global file_states next_icon_id null_sha1
1449
1450         set s0 [string index $new_state 0]
1451         set s1 [string index $new_state 1]
1452
1453         if {[catch {set info $file_states($path)}]} {
1454                 set state __
1455                 set icon n[incr next_icon_id]
1456         } else {
1457                 set state [lindex $info 0]
1458                 set icon [lindex $info 1]
1459                 if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1460                 if {$index_info eq {}} {set index_info [lindex $info 3]}
1461         }
1462
1463         if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1464         elseif {$s0 eq {_}} {set s0 _}
1465
1466         if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1467         elseif {$s1 eq {_}} {set s1 _}
1468
1469         if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1470                 set head_info [list 0 $null_sha1]
1471         } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1472                 && $head_info eq {}} {
1473                 set head_info $index_info
1474         }
1475
1476         set file_states($path) [list $s0$s1 $icon \
1477                 $head_info $index_info \
1478                 ]
1479         return $state
1480 }
1481
1482 proc display_file_helper {w path icon_name old_m new_m} {
1483         global file_lists
1484
1485         if {$new_m eq {_}} {
1486                 set lno [lsearch -sorted -exact $file_lists($w) $path]
1487                 if {$lno >= 0} {
1488                         set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1489                         incr lno
1490                         $w conf -state normal
1491                         $w delete $lno.0 [expr {$lno + 1}].0
1492                         $w conf -state disabled
1493                 }
1494         } elseif {$old_m eq {_} && $new_m ne {_}} {
1495                 lappend file_lists($w) $path
1496                 set file_lists($w) [lsort -unique $file_lists($w)]
1497                 set lno [lsearch -sorted -exact $file_lists($w) $path]
1498                 incr lno
1499                 $w conf -state normal
1500                 $w image create $lno.0 \
1501                         -align center -padx 5 -pady 1 \
1502                         -name $icon_name \
1503                         -image [mapicon $w $new_m $path]
1504                 $w insert $lno.1 "[escape_path $path]\n"
1505                 $w conf -state disabled
1506         } elseif {$old_m ne $new_m} {
1507                 $w conf -state normal
1508                 $w image conf $icon_name -image [mapicon $w $new_m $path]
1509                 $w conf -state disabled
1510         }
1511 }
1512
1513 proc display_file {path state} {
1514         global file_states selected_paths
1515         global ui_index ui_workdir
1516
1517         set old_m [merge_state $path $state]
1518         set s $file_states($path)
1519         set new_m [lindex $s 0]
1520         set icon_name [lindex $s 1]
1521
1522         set o [string index $old_m 0]
1523         set n [string index $new_m 0]
1524         if {$o eq {U}} {
1525                 set o _
1526         }
1527         if {$n eq {U}} {
1528                 set n _
1529         }
1530         display_file_helper     $ui_index $path $icon_name $o $n
1531
1532         if {[string index $old_m 0] eq {U}} {
1533                 set o U
1534         } else {
1535                 set o [string index $old_m 1]
1536         }
1537         if {[string index $new_m 0] eq {U}} {
1538                 set n U
1539         } else {
1540                 set n [string index $new_m 1]
1541         }
1542         display_file_helper     $ui_workdir $path $icon_name $o $n
1543
1544         if {$new_m eq {__}} {
1545                 unset file_states($path)
1546                 catch {unset selected_paths($path)}
1547         }
1548 }
1549
1550 proc display_all_files_helper {w path icon_name m} {
1551         global file_lists
1552
1553         lappend file_lists($w) $path
1554         set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1555         $w image create end \
1556                 -align center -padx 5 -pady 1 \
1557                 -name $icon_name \
1558                 -image [mapicon $w $m $path]
1559         $w insert end "[escape_path $path]\n"
1560 }
1561
1562 proc display_all_files {} {
1563         global ui_index ui_workdir
1564         global file_states file_lists
1565         global last_clicked
1566
1567         $ui_index conf -state normal
1568         $ui_workdir conf -state normal
1569
1570         $ui_index delete 0.0 end
1571         $ui_workdir delete 0.0 end
1572         set last_clicked {}
1573
1574         set file_lists($ui_index) [list]
1575         set file_lists($ui_workdir) [list]
1576
1577         foreach path [lsort [array names file_states]] {
1578                 set s $file_states($path)
1579                 set m [lindex $s 0]
1580                 set icon_name [lindex $s 1]
1581
1582                 set s [string index $m 0]
1583                 if {$s ne {U} && $s ne {_}} {
1584                         display_all_files_helper $ui_index $path \
1585                                 $icon_name $s
1586                 }
1587
1588                 if {[string index $m 0] eq {U}} {
1589                         set s U
1590                 } else {
1591                         set s [string index $m 1]
1592                 }
1593                 if {$s ne {_}} {
1594                         display_all_files_helper $ui_workdir $path \
1595                                 $icon_name $s
1596                 }
1597         }
1598
1599         $ui_index conf -state disabled
1600         $ui_workdir conf -state disabled
1601 }
1602
1603 proc update_indexinfo {msg pathList after} {
1604         global update_index_cp ui_status_value
1605
1606         if {![lock_index update]} return
1607
1608         set update_index_cp 0
1609         set pathList [lsort $pathList]
1610         set totalCnt [llength $pathList]
1611         set batch [expr {int($totalCnt * .01) + 1}]
1612         if {$batch > 25} {set batch 25}
1613
1614         set ui_status_value [format \
1615                 "$msg... %i/%i files (%.2f%%)" \
1616                 $update_index_cp \
1617                 $totalCnt \
1618                 0.0]
1619         set fd [open "| git update-index -z --index-info" w]
1620         fconfigure $fd \
1621                 -blocking 0 \
1622                 -buffering full \
1623                 -buffersize 512 \
1624                 -encoding binary \
1625                 -translation binary
1626         fileevent $fd writable [list \
1627                 write_update_indexinfo \
1628                 $fd \
1629                 $pathList \
1630                 $totalCnt \
1631                 $batch \
1632                 $msg \
1633                 $after \
1634                 ]
1635 }
1636
1637 proc write_update_indexinfo {fd pathList totalCnt batch msg after} {
1638         global update_index_cp ui_status_value
1639         global file_states current_diff_path
1640
1641         if {$update_index_cp >= $totalCnt} {
1642                 close $fd
1643                 unlock_index
1644                 uplevel #0 $after
1645                 return
1646         }
1647
1648         for {set i $batch} \
1649                 {$update_index_cp < $totalCnt && $i > 0} \
1650                 {incr i -1} {
1651                 set path [lindex $pathList $update_index_cp]
1652                 incr update_index_cp
1653
1654                 set s $file_states($path)
1655                 switch -glob -- [lindex $s 0] {
1656                 A? {set new _O}
1657                 M? {set new _M}
1658                 D_ {set new _D}
1659                 D? {set new _?}
1660                 ?? {continue}
1661                 }
1662                 set info [lindex $s 2]
1663                 if {$info eq {}} continue
1664
1665                 puts -nonewline $fd "$info\t[encoding convertto $path]\0"
1666                 display_file $path $new
1667         }
1668
1669         set ui_status_value [format \
1670                 "$msg... %i/%i files (%.2f%%)" \
1671                 $update_index_cp \
1672                 $totalCnt \
1673                 [expr {100.0 * $update_index_cp / $totalCnt}]]
1674 }
1675
1676 proc update_index {msg pathList after} {
1677         global update_index_cp ui_status_value
1678
1679         if {![lock_index update]} return
1680
1681         set update_index_cp 0
1682         set pathList [lsort $pathList]
1683         set totalCnt [llength $pathList]
1684         set batch [expr {int($totalCnt * .01) + 1}]
1685         if {$batch > 25} {set batch 25}
1686
1687         set ui_status_value [format \
1688                 "$msg... %i/%i files (%.2f%%)" \
1689                 $update_index_cp \
1690                 $totalCnt \
1691                 0.0]
1692         set fd [open "| git update-index --add --remove -z --stdin" w]
1693         fconfigure $fd \
1694                 -blocking 0 \
1695                 -buffering full \
1696                 -buffersize 512 \
1697                 -encoding binary \
1698                 -translation binary
1699         fileevent $fd writable [list \
1700                 write_update_index \
1701                 $fd \
1702                 $pathList \
1703                 $totalCnt \
1704                 $batch \
1705                 $msg \
1706                 $after \
1707                 ]
1708 }
1709
1710 proc write_update_index {fd pathList totalCnt batch msg after} {
1711         global update_index_cp ui_status_value
1712         global file_states current_diff_path
1713
1714         if {$update_index_cp >= $totalCnt} {
1715                 close $fd
1716                 unlock_index
1717                 uplevel #0 $after
1718                 return
1719         }
1720
1721         for {set i $batch} \
1722                 {$update_index_cp < $totalCnt && $i > 0} \
1723                 {incr i -1} {
1724                 set path [lindex $pathList $update_index_cp]
1725                 incr update_index_cp
1726
1727                 switch -glob -- [lindex $file_states($path) 0] {
1728                 AD {set new __}
1729                 ?D {set new D_}
1730                 _O -
1731                 AM {set new A_}
1732                 U? {
1733                         if {[file exists $path]} {
1734                                 set new M_
1735                         } else {
1736                                 set new D_
1737                         }
1738                 }
1739                 ?M {set new M_}
1740                 ?? {continue}
1741                 }
1742                 puts -nonewline $fd "[encoding convertto $path]\0"
1743                 display_file $path $new
1744         }
1745
1746         set ui_status_value [format \
1747                 "$msg... %i/%i files (%.2f%%)" \
1748                 $update_index_cp \
1749                 $totalCnt \
1750                 [expr {100.0 * $update_index_cp / $totalCnt}]]
1751 }
1752
1753 proc checkout_index {msg pathList after} {
1754         global update_index_cp ui_status_value
1755
1756         if {![lock_index update]} return
1757
1758         set update_index_cp 0
1759         set pathList [lsort $pathList]
1760         set totalCnt [llength $pathList]
1761         set batch [expr {int($totalCnt * .01) + 1}]
1762         if {$batch > 25} {set batch 25}
1763
1764         set ui_status_value [format \
1765                 "$msg... %i/%i files (%.2f%%)" \
1766                 $update_index_cp \
1767                 $totalCnt \
1768                 0.0]
1769         set cmd [list git checkout-index]
1770         lappend cmd --index
1771         lappend cmd --quiet
1772         lappend cmd --force
1773         lappend cmd -z
1774         lappend cmd --stdin
1775         set fd [open "| $cmd " w]
1776         fconfigure $fd \
1777                 -blocking 0 \
1778                 -buffering full \
1779                 -buffersize 512 \
1780                 -encoding binary \
1781                 -translation binary
1782         fileevent $fd writable [list \
1783                 write_checkout_index \
1784                 $fd \
1785                 $pathList \
1786                 $totalCnt \
1787                 $batch \
1788                 $msg \
1789                 $after \
1790                 ]
1791 }
1792
1793 proc write_checkout_index {fd pathList totalCnt batch msg after} {
1794         global update_index_cp ui_status_value
1795         global file_states current_diff_path
1796
1797         if {$update_index_cp >= $totalCnt} {
1798                 close $fd
1799                 unlock_index
1800                 uplevel #0 $after
1801                 return
1802         }
1803
1804         for {set i $batch} \
1805                 {$update_index_cp < $totalCnt && $i > 0} \
1806                 {incr i -1} {
1807                 set path [lindex $pathList $update_index_cp]
1808                 incr update_index_cp
1809                 switch -glob -- [lindex $file_states($path) 0] {
1810                 U? {continue}
1811                 ?M -
1812                 ?D {
1813                         puts -nonewline $fd "[encoding convertto $path]\0"
1814                         display_file $path ?_
1815                 }
1816                 }
1817         }
1818
1819         set ui_status_value [format \
1820                 "$msg... %i/%i files (%.2f%%)" \
1821                 $update_index_cp \
1822                 $totalCnt \
1823                 [expr {100.0 * $update_index_cp / $totalCnt}]]
1824 }
1825
1826 ######################################################################
1827 ##
1828 ## branch management
1829
1830 proc is_tracking_branch {name} {
1831         global tracking_branches
1832
1833         if {![catch {set info $tracking_branches($name)}]} {
1834                 return 1
1835         }
1836         foreach t [array names tracking_branches] {
1837                 if {[string match {*/\*} $t] && [string match $t $name]} {
1838                         return 1
1839                 }
1840         }
1841         return 0
1842 }
1843
1844 proc load_all_heads {} {
1845         global all_heads
1846
1847         set all_heads [list]
1848         set fd [open "| git for-each-ref --format=%(refname) refs/heads" r]
1849         while {[gets $fd line] > 0} {
1850                 if {[is_tracking_branch $line]} continue
1851                 if {![regsub ^refs/heads/ $line {} name]} continue
1852                 lappend all_heads $name
1853         }
1854         close $fd
1855
1856         set all_heads [lsort $all_heads]
1857 }
1858
1859 proc populate_branch_menu {} {
1860         global all_heads disable_on_lock
1861
1862         set m .mbar.branch
1863         set last [$m index last]
1864         for {set i 0} {$i <= $last} {incr i} {
1865                 if {[$m type $i] eq {separator}} {
1866                         $m delete $i last
1867                         set new_dol [list]
1868                         foreach a $disable_on_lock {
1869                                 if {[lindex $a 0] ne $m || [lindex $a 2] < $i} {
1870                                         lappend new_dol $a
1871                                 }
1872                         }
1873                         set disable_on_lock $new_dol
1874                         break
1875                 }
1876         }
1877
1878         if {$all_heads ne {}} {
1879                 $m add separator
1880         }
1881         foreach b $all_heads {
1882                 $m add radiobutton \
1883                         -label $b \
1884                         -command [list switch_branch $b] \
1885                         -variable current_branch \
1886                         -value $b \
1887                         -font font_ui
1888                 lappend disable_on_lock \
1889                         [list $m entryconf [$m index last] -state]
1890         }
1891 }
1892
1893 proc all_tracking_branches {} {
1894         global tracking_branches
1895
1896         set all_trackings {}
1897         set cmd {}
1898         foreach name [array names tracking_branches] {
1899                 if {[regsub {/\*$} $name {} name]} {
1900                         lappend cmd $name
1901                 } else {
1902                         regsub ^refs/(heads|remotes)/ $name {} name
1903                         lappend all_trackings $name
1904                 }
1905         }
1906
1907         if {$cmd ne {}} {
1908                 set fd [open "| git for-each-ref --format=%(refname) $cmd" r]
1909                 while {[gets $fd name] > 0} {
1910                         regsub ^refs/(heads|remotes)/ $name {} name
1911                         lappend all_trackings $name
1912                 }
1913                 close $fd
1914         }
1915
1916         return [lsort -unique $all_trackings]
1917 }
1918
1919 proc load_all_tags {} {
1920         set all_tags [list]
1921         set fd [open "| git for-each-ref --format=%(refname) refs/tags" r]
1922         while {[gets $fd line] > 0} {
1923                 if {![regsub ^refs/tags/ $line {} name]} continue
1924                 lappend all_tags $name
1925         }
1926         close $fd
1927
1928         return [lsort $all_tags]
1929 }
1930
1931 proc do_create_branch_action {w} {
1932         global all_heads null_sha1 repo_config
1933         global create_branch_checkout create_branch_revtype
1934         global create_branch_head create_branch_trackinghead
1935         global create_branch_name create_branch_revexp
1936         global create_branch_tag
1937
1938         set newbranch $create_branch_name
1939         if {$newbranch eq {}
1940                 || $newbranch eq $repo_config(gui.newbranchtemplate)} {
1941                 tk_messageBox \
1942                         -icon error \
1943                         -type ok \
1944                         -title [wm title $w] \
1945                         -parent $w \
1946                         -message "Please supply a branch name."
1947                 focus $w.desc.name_t
1948                 return
1949         }
1950         if {![catch {git show-ref --verify -- "refs/heads/$newbranch"}]} {
1951                 tk_messageBox \
1952                         -icon error \
1953                         -type ok \
1954                         -title [wm title $w] \
1955                         -parent $w \
1956                         -message "Branch '$newbranch' already exists."
1957                 focus $w.desc.name_t
1958                 return
1959         }
1960         if {[catch {git check-ref-format "heads/$newbranch"}]} {
1961                 tk_messageBox \
1962                         -icon error \
1963                         -type ok \
1964                         -title [wm title $w] \
1965                         -parent $w \
1966                         -message "We do not like '$newbranch' as a branch name."
1967                 focus $w.desc.name_t
1968                 return
1969         }
1970
1971         set rev {}
1972         switch -- $create_branch_revtype {
1973         head {set rev $create_branch_head}
1974         tracking {set rev $create_branch_trackinghead}
1975         tag {set rev $create_branch_tag}
1976         expression {set rev $create_branch_revexp}
1977         }
1978         if {[catch {set cmt [git rev-parse --verify "${rev}^0"]}]} {
1979                 tk_messageBox \
1980                         -icon error \
1981                         -type ok \
1982                         -title [wm title $w] \
1983                         -parent $w \
1984                         -message "Invalid starting revision: $rev"
1985                 return
1986         }
1987         set cmd [list git update-ref]
1988         lappend cmd -m
1989         lappend cmd "branch: Created from $rev"
1990         lappend cmd "refs/heads/$newbranch"
1991         lappend cmd $cmt
1992         lappend cmd $null_sha1
1993         if {[catch {eval exec $cmd} err]} {
1994                 tk_messageBox \
1995                         -icon error \
1996                         -type ok \
1997                         -title [wm title $w] \
1998                         -parent $w \
1999                         -message "Failed to create '$newbranch'.\n\n$err"
2000                 return
2001         }
2002
2003         lappend all_heads $newbranch
2004         set all_heads [lsort $all_heads]
2005         populate_branch_menu
2006         destroy $w
2007         if {$create_branch_checkout} {
2008                 switch_branch $newbranch
2009         }
2010 }
2011
2012 proc radio_selector {varname value args} {
2013         upvar #0 $varname var
2014         set var $value
2015 }
2016
2017 trace add variable create_branch_head write \
2018         [list radio_selector create_branch_revtype head]
2019 trace add variable create_branch_trackinghead write \
2020         [list radio_selector create_branch_revtype tracking]
2021 trace add variable create_branch_tag write \
2022         [list radio_selector create_branch_revtype tag]
2023
2024 trace add variable delete_branch_head write \
2025         [list radio_selector delete_branch_checktype head]
2026 trace add variable delete_branch_trackinghead write \
2027         [list radio_selector delete_branch_checktype tracking]
2028
2029 proc do_create_branch {} {
2030         global all_heads current_branch repo_config
2031         global create_branch_checkout create_branch_revtype
2032         global create_branch_head create_branch_trackinghead
2033         global create_branch_name create_branch_revexp
2034         global create_branch_tag
2035
2036         set w .branch_editor
2037         toplevel $w
2038         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2039
2040         label $w.header -text {Create New Branch} \
2041                 -font font_uibold
2042         pack $w.header -side top -fill x
2043
2044         frame $w.buttons
2045         button $w.buttons.create -text Create \
2046                 -font font_ui \
2047                 -default active \
2048                 -command [list do_create_branch_action $w]
2049         pack $w.buttons.create -side right
2050         button $w.buttons.cancel -text {Cancel} \
2051                 -font font_ui \
2052                 -command [list destroy $w]
2053         pack $w.buttons.cancel -side right -padx 5
2054         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2055
2056         labelframe $w.desc \
2057                 -text {Branch Description} \
2058                 -font font_ui
2059         label $w.desc.name_l -text {Name:} -font font_ui
2060         entry $w.desc.name_t \
2061                 -borderwidth 1 \
2062                 -relief sunken \
2063                 -width 40 \
2064                 -textvariable create_branch_name \
2065                 -font font_ui \
2066                 -validate key \
2067                 -validatecommand {
2068                         if {%d == 1 && [regexp {[~^:?*\[\0- ]} %S]} {return 0}
2069                         return 1
2070                 }
2071         grid $w.desc.name_l $w.desc.name_t -sticky we -padx {0 5}
2072         grid columnconfigure $w.desc 1 -weight 1
2073         pack $w.desc -anchor nw -fill x -pady 5 -padx 5
2074
2075         labelframe $w.from \
2076                 -text {Starting Revision} \
2077                 -font font_ui
2078         radiobutton $w.from.head_r \
2079                 -text {Local Branch:} \
2080                 -value head \
2081                 -variable create_branch_revtype \
2082                 -font font_ui
2083         eval tk_optionMenu $w.from.head_m create_branch_head $all_heads
2084         grid $w.from.head_r $w.from.head_m -sticky w
2085         set all_trackings [all_tracking_branches]
2086         if {$all_trackings ne {}} {
2087                 set create_branch_trackinghead [lindex $all_trackings 0]
2088                 radiobutton $w.from.tracking_r \
2089                         -text {Tracking Branch:} \
2090                         -value tracking \
2091                         -variable create_branch_revtype \
2092                         -font font_ui
2093                 eval tk_optionMenu $w.from.tracking_m \
2094                         create_branch_trackinghead \
2095                         $all_trackings
2096                 grid $w.from.tracking_r $w.from.tracking_m -sticky w
2097         }
2098         set all_tags [load_all_tags]
2099         if {$all_tags ne {}} {
2100                 set create_branch_tag [lindex $all_tags 0]
2101                 radiobutton $w.from.tag_r \
2102                         -text {Tag:} \
2103                         -value tag \
2104                         -variable create_branch_revtype \
2105                         -font font_ui
2106                 eval tk_optionMenu $w.from.tag_m \
2107                         create_branch_tag \
2108                         $all_tags
2109                 grid $w.from.tag_r $w.from.tag_m -sticky w
2110         }
2111         radiobutton $w.from.exp_r \
2112                 -text {Revision Expression:} \
2113                 -value expression \
2114                 -variable create_branch_revtype \
2115                 -font font_ui
2116         entry $w.from.exp_t \
2117                 -borderwidth 1 \
2118                 -relief sunken \
2119                 -width 50 \
2120                 -textvariable create_branch_revexp \
2121                 -font font_ui \
2122                 -validate key \
2123                 -validatecommand {
2124                         if {%d == 1 && [regexp {\s} %S]} {return 0}
2125                         if {%d == 1 && [string length %S] > 0} {
2126                                 set create_branch_revtype expression
2127                         }
2128                         return 1
2129                 }
2130         grid $w.from.exp_r $w.from.exp_t -sticky we -padx {0 5}
2131         grid columnconfigure $w.from 1 -weight 1
2132         pack $w.from -anchor nw -fill x -pady 5 -padx 5
2133
2134         labelframe $w.postActions \
2135                 -text {Post Creation Actions} \
2136                 -font font_ui
2137         checkbutton $w.postActions.checkout \
2138                 -text {Checkout after creation} \
2139                 -variable create_branch_checkout \
2140                 -font font_ui
2141         pack $w.postActions.checkout -anchor nw
2142         pack $w.postActions -anchor nw -fill x -pady 5 -padx 5
2143
2144         set create_branch_checkout 1
2145         set create_branch_head $current_branch
2146         set create_branch_revtype head
2147         set create_branch_name $repo_config(gui.newbranchtemplate)
2148         set create_branch_revexp {}
2149
2150         bind $w <Visibility> "
2151                 grab $w
2152                 $w.desc.name_t icursor end
2153                 focus $w.desc.name_t
2154         "
2155         bind $w <Key-Escape> "destroy $w"
2156         bind $w <Key-Return> "do_create_branch_action $w;break"
2157         wm title $w "[appname] ([reponame]): Create Branch"
2158         tkwait window $w
2159 }
2160
2161 proc do_delete_branch_action {w} {
2162         global all_heads
2163         global delete_branch_checktype delete_branch_head delete_branch_trackinghead
2164
2165         set check_rev {}
2166         switch -- $delete_branch_checktype {
2167         head {set check_rev $delete_branch_head}
2168         tracking {set check_rev $delete_branch_trackinghead}
2169         always {set check_rev {:none}}
2170         }
2171         if {$check_rev eq {:none}} {
2172                 set check_cmt {}
2173         } elseif {[catch {set check_cmt [git rev-parse --verify "${check_rev}^0"]}]} {
2174                 tk_messageBox \
2175                         -icon error \
2176                         -type ok \
2177                         -title [wm title $w] \
2178                         -parent $w \
2179                         -message "Invalid check revision: $check_rev"
2180                 return
2181         }
2182
2183         set to_delete [list]
2184         set not_merged [list]
2185         foreach i [$w.list.l curselection] {
2186                 set b [$w.list.l get $i]
2187                 if {[catch {set o [git rev-parse --verify $b]}]} continue
2188                 if {$check_cmt ne {}} {
2189                         if {$b eq $check_rev} continue
2190                         if {[catch {set m [git merge-base $o $check_cmt]}]} continue
2191                         if {$o ne $m} {
2192                                 lappend not_merged $b
2193                                 continue
2194                         }
2195                 }
2196                 lappend to_delete [list $b $o]
2197         }
2198         if {$not_merged ne {}} {
2199                 set msg "The following branches are not completely merged into $check_rev:
2200
2201  - [join $not_merged "\n - "]"
2202                 tk_messageBox \
2203                         -icon info \
2204                         -type ok \
2205                         -title [wm title $w] \
2206                         -parent $w \
2207                         -message $msg
2208         }
2209         if {$to_delete eq {}} return
2210         if {$delete_branch_checktype eq {always}} {
2211                 set msg {Recovering deleted branches is difficult.
2212
2213 Delete the selected branches?}
2214                 if {[tk_messageBox \
2215                         -icon warning \
2216                         -type yesno \
2217                         -title [wm title $w] \
2218                         -parent $w \
2219                         -message $msg] ne yes} {
2220                         return
2221                 }
2222         }
2223
2224         set failed {}
2225         foreach i $to_delete {
2226                 set b [lindex $i 0]
2227                 set o [lindex $i 1]
2228                 if {[catch {git update-ref -d "refs/heads/$b" $o} err]} {
2229                         append failed " - $b: $err\n"
2230                 } else {
2231                         set x [lsearch -sorted -exact $all_heads $b]
2232                         if {$x >= 0} {
2233                                 set all_heads [lreplace $all_heads $x $x]
2234                         }
2235                 }
2236         }
2237
2238         if {$failed ne {}} {
2239                 tk_messageBox \
2240                         -icon error \
2241                         -type ok \
2242                         -title [wm title $w] \
2243                         -parent $w \
2244                         -message "Failed to delete branches:\n$failed"
2245         }
2246
2247         set all_heads [lsort $all_heads]
2248         populate_branch_menu
2249         destroy $w
2250 }
2251
2252 proc do_delete_branch {} {
2253         global all_heads tracking_branches current_branch
2254         global delete_branch_checktype delete_branch_head delete_branch_trackinghead
2255
2256         set w .branch_editor
2257         toplevel $w
2258         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2259
2260         label $w.header -text {Delete Local Branch} \
2261                 -font font_uibold
2262         pack $w.header -side top -fill x
2263
2264         frame $w.buttons
2265         button $w.buttons.create -text Delete \
2266                 -font font_ui \
2267                 -command [list do_delete_branch_action $w]
2268         pack $w.buttons.create -side right
2269         button $w.buttons.cancel -text {Cancel} \
2270                 -font font_ui \
2271                 -command [list destroy $w]
2272         pack $w.buttons.cancel -side right -padx 5
2273         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2274
2275         labelframe $w.list \
2276                 -text {Local Branches} \
2277                 -font font_ui
2278         listbox $w.list.l \
2279                 -height 10 \
2280                 -width 70 \
2281                 -selectmode extended \
2282                 -yscrollcommand [list $w.list.sby set] \
2283                 -font font_ui
2284         foreach h $all_heads {
2285                 if {$h ne $current_branch} {
2286                         $w.list.l insert end $h
2287                 }
2288         }
2289         scrollbar $w.list.sby -command [list $w.list.l yview]
2290         pack $w.list.sby -side right -fill y
2291         pack $w.list.l -side left -fill both -expand 1
2292         pack $w.list -fill both -expand 1 -pady 5 -padx 5
2293
2294         labelframe $w.validate \
2295                 -text {Delete Only If} \
2296                 -font font_ui
2297         radiobutton $w.validate.head_r \
2298                 -text {Merged Into Local Branch:} \
2299                 -value head \
2300                 -variable delete_branch_checktype \
2301                 -font font_ui
2302         eval tk_optionMenu $w.validate.head_m delete_branch_head $all_heads
2303         grid $w.validate.head_r $w.validate.head_m -sticky w
2304         set all_trackings [all_tracking_branches]
2305         if {$all_trackings ne {}} {
2306                 set delete_branch_trackinghead [lindex $all_trackings 0]
2307                 radiobutton $w.validate.tracking_r \
2308                         -text {Merged Into Tracking Branch:} \
2309                         -value tracking \
2310                         -variable delete_branch_checktype \
2311                         -font font_ui
2312                 eval tk_optionMenu $w.validate.tracking_m \
2313                         delete_branch_trackinghead \
2314                         $all_trackings
2315                 grid $w.validate.tracking_r $w.validate.tracking_m -sticky w
2316         }
2317         radiobutton $w.validate.always_r \
2318                 -text {Always (Do not perform merge checks)} \
2319                 -value always \
2320                 -variable delete_branch_checktype \
2321                 -font font_ui
2322         grid $w.validate.always_r -columnspan 2 -sticky w
2323         grid columnconfigure $w.validate 1 -weight 1
2324         pack $w.validate -anchor nw -fill x -pady 5 -padx 5
2325
2326         set delete_branch_head $current_branch
2327         set delete_branch_checktype head
2328
2329         bind $w <Visibility> "grab $w; focus $w"
2330         bind $w <Key-Escape> "destroy $w"
2331         wm title $w "[appname] ([reponame]): Delete Branch"
2332         tkwait window $w
2333 }
2334
2335 proc switch_branch {new_branch} {
2336         global HEAD commit_type current_branch repo_config
2337
2338         if {![lock_index switch]} return
2339
2340         # -- Our in memory state should match the repository.
2341         #
2342         repository_state curType curHEAD curMERGE_HEAD
2343         if {[string match amend* $commit_type]
2344                 && $curType eq {normal}
2345                 && $curHEAD eq $HEAD} {
2346         } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
2347                 info_popup {Last scanned state does not match repository state.
2348
2349 Another Git program has modified this repository
2350 since the last scan.  A rescan must be performed
2351 before the current branch can be changed.
2352
2353 The rescan will be automatically started now.
2354 }
2355                 unlock_index
2356                 rescan {set ui_status_value {Ready.}}
2357                 return
2358         }
2359
2360         # -- Don't do a pointless switch.
2361         #
2362         if {$current_branch eq $new_branch} {
2363                 unlock_index
2364                 return
2365         }
2366
2367         if {$repo_config(gui.trustmtime) eq {true}} {
2368                 switch_branch_stage2 {} $new_branch
2369         } else {
2370                 set ui_status_value {Refreshing file status...}
2371                 set cmd [list git update-index]
2372                 lappend cmd -q
2373                 lappend cmd --unmerged
2374                 lappend cmd --ignore-missing
2375                 lappend cmd --refresh
2376                 set fd_rf [open "| $cmd" r]
2377                 fconfigure $fd_rf -blocking 0 -translation binary
2378                 fileevent $fd_rf readable \
2379                         [list switch_branch_stage2 $fd_rf $new_branch]
2380         }
2381 }
2382
2383 proc switch_branch_stage2 {fd_rf new_branch} {
2384         global ui_status_value HEAD
2385
2386         if {$fd_rf ne {}} {
2387                 read $fd_rf
2388                 if {![eof $fd_rf]} return
2389                 close $fd_rf
2390         }
2391
2392         set ui_status_value "Updating working directory to '$new_branch'..."
2393         set cmd [list git read-tree]
2394         lappend cmd -m
2395         lappend cmd -u
2396         lappend cmd --exclude-per-directory=.gitignore
2397         lappend cmd $HEAD
2398         lappend cmd $new_branch
2399         set fd_rt [open "| $cmd" r]
2400         fconfigure $fd_rt -blocking 0 -translation binary
2401         fileevent $fd_rt readable \
2402                 [list switch_branch_readtree_wait $fd_rt $new_branch]
2403 }
2404
2405 proc switch_branch_readtree_wait {fd_rt new_branch} {
2406         global selected_commit_type commit_type HEAD MERGE_HEAD PARENT
2407         global current_branch
2408         global ui_comm ui_status_value
2409
2410         # -- We never get interesting output on stdout; only stderr.
2411         #
2412         read $fd_rt
2413         fconfigure $fd_rt -blocking 1
2414         if {![eof $fd_rt]} {
2415                 fconfigure $fd_rt -blocking 0
2416                 return
2417         }
2418
2419         # -- The working directory wasn't in sync with the index and
2420         #    we'd have to overwrite something to make the switch. A
2421         #    merge is required.
2422         #
2423         if {[catch {close $fd_rt} err]} {
2424                 regsub {^fatal: } $err {} err
2425                 warn_popup "File level merge required.
2426
2427 $err
2428
2429 Staying on branch '$current_branch'."
2430                 set ui_status_value "Aborted checkout of '$new_branch' (file level merging is required)."
2431                 unlock_index
2432                 return
2433         }
2434
2435         # -- Update the symbolic ref.  Core git doesn't even check for failure
2436         #    here, it Just Works(tm).  If it doesn't we are in some really ugly
2437         #    state that is difficult to recover from within git-gui.
2438         #
2439         if {[catch {git symbolic-ref HEAD "refs/heads/$new_branch"} err]} {
2440                 error_popup "Failed to set current branch.
2441
2442 This working directory is only partially switched.
2443 We successfully updated your files, but failed to
2444 update an internal Git file.
2445
2446 This should not have occurred.  [appname] will now
2447 close and give up.
2448
2449 $err"
2450                 do_quit
2451                 return
2452         }
2453
2454         # -- Update our repository state.  If we were previously in amend mode
2455         #    we need to toss the current buffer and do a full rescan to update
2456         #    our file lists.  If we weren't in amend mode our file lists are
2457         #    accurate and we can avoid the rescan.
2458         #
2459         unlock_index
2460         set selected_commit_type new
2461         if {[string match amend* $commit_type]} {
2462                 $ui_comm delete 0.0 end
2463                 $ui_comm edit reset
2464                 $ui_comm edit modified false
2465                 rescan {set ui_status_value "Checked out branch '$current_branch'."}
2466         } else {
2467                 repository_state commit_type HEAD MERGE_HEAD
2468                 set PARENT $HEAD
2469                 set ui_status_value "Checked out branch '$current_branch'."
2470         }
2471 }
2472
2473 ######################################################################
2474 ##
2475 ## remote management
2476
2477 proc load_all_remotes {} {
2478         global repo_config
2479         global all_remotes tracking_branches
2480
2481         set all_remotes [list]
2482         array unset tracking_branches
2483
2484         set rm_dir [gitdir remotes]
2485         if {[file isdirectory $rm_dir]} {
2486                 set all_remotes [glob \
2487                         -types f \
2488                         -tails \
2489                         -nocomplain \
2490                         -directory $rm_dir *]
2491
2492                 foreach name $all_remotes {
2493                         catch {
2494                                 set fd [open [file join $rm_dir $name] r]
2495                                 while {[gets $fd line] >= 0} {
2496                                         if {![regexp {^Pull:[   ]*([^:]+):(.+)$} \
2497                                                 $line line src dst]} continue
2498                                         if {![regexp ^refs/ $dst]} {
2499                                                 set dst "refs/heads/$dst"
2500                                         }
2501                                         set tracking_branches($dst) [list $name $src]
2502                                 }
2503                                 close $fd
2504                         }
2505                 }
2506         }
2507
2508         foreach line [array names repo_config remote.*.url] {
2509                 if {![regexp ^remote\.(.*)\.url\$ $line line name]} continue
2510                 lappend all_remotes $name
2511
2512                 if {[catch {set fl $repo_config(remote.$name.fetch)}]} {
2513                         set fl {}
2514                 }
2515                 foreach line $fl {
2516                         if {![regexp {^([^:]+):(.+)$} $line line src dst]} continue
2517                         if {![regexp ^refs/ $dst]} {
2518                                 set dst "refs/heads/$dst"
2519                         }
2520                         set tracking_branches($dst) [list $name $src]
2521                 }
2522         }
2523
2524         set all_remotes [lsort -unique $all_remotes]
2525 }
2526
2527 proc populate_fetch_menu {} {
2528         global all_remotes repo_config
2529
2530         set m .mbar.fetch
2531         foreach r $all_remotes {
2532                 set enable 0
2533                 if {![catch {set a $repo_config(remote.$r.url)}]} {
2534                         if {![catch {set a $repo_config(remote.$r.fetch)}]} {
2535                                 set enable 1
2536                         }
2537                 } else {
2538                         catch {
2539                                 set fd [open [gitdir remotes $r] r]
2540                                 while {[gets $fd n] >= 0} {
2541                                         if {[regexp {^Pull:[ \t]*([^:]+):} $n]} {
2542                                                 set enable 1
2543                                                 break
2544                                         }
2545                                 }
2546                                 close $fd
2547                         }
2548                 }
2549
2550                 if {$enable} {
2551                         $m add command \
2552                                 -label "Fetch from $r..." \
2553                                 -command [list fetch_from $r] \
2554                                 -font font_ui
2555                 }
2556         }
2557 }
2558
2559 proc populate_push_menu {} {
2560         global all_remotes repo_config
2561
2562         set m .mbar.push
2563         set fast_count 0
2564         foreach r $all_remotes {
2565                 set enable 0
2566                 if {![catch {set a $repo_config(remote.$r.url)}]} {
2567                         if {![catch {set a $repo_config(remote.$r.push)}]} {
2568                                 set enable 1
2569                         }
2570                 } else {
2571                         catch {
2572                                 set fd [open [gitdir remotes $r] r]
2573                                 while {[gets $fd n] >= 0} {
2574                                         if {[regexp {^Push:[ \t]*([^:]+):} $n]} {
2575                                                 set enable 1
2576                                                 break
2577                                         }
2578                                 }
2579                                 close $fd
2580                         }
2581                 }
2582
2583                 if {$enable} {
2584                         if {!$fast_count} {
2585                                 $m add separator
2586                         }
2587                         $m add command \
2588                                 -label "Push to $r..." \
2589                                 -command [list push_to $r] \
2590                                 -font font_ui
2591                         incr fast_count
2592                 }
2593         }
2594 }
2595
2596 proc start_push_anywhere_action {w} {
2597         global push_urltype push_remote push_url push_thin push_tags
2598
2599         set r_url {}
2600         switch -- $push_urltype {
2601         remote {set r_url $push_remote}
2602         url {set r_url $push_url}
2603         }
2604         if {$r_url eq {}} return
2605
2606         set cmd [list git push]
2607         lappend cmd -v
2608         if {$push_thin} {
2609                 lappend cmd --thin
2610         }
2611         if {$push_tags} {
2612                 lappend cmd --tags
2613         }
2614         lappend cmd $r_url
2615         set cnt 0
2616         foreach i [$w.source.l curselection] {
2617                 set b [$w.source.l get $i]
2618                 lappend cmd "refs/heads/$b:refs/heads/$b"
2619                 incr cnt
2620         }
2621         if {$cnt == 0} {
2622                 return
2623         } elseif {$cnt == 1} {
2624                 set unit branch
2625         } else {
2626                 set unit branches
2627         }
2628
2629         set cons [new_console "push $r_url" "Pushing $cnt $unit to $r_url"]
2630         console_exec $cons $cmd console_done
2631         destroy $w
2632 }
2633
2634 trace add variable push_remote write \
2635         [list radio_selector push_urltype remote]
2636
2637 proc do_push_anywhere {} {
2638         global all_heads all_remotes current_branch
2639         global push_urltype push_remote push_url push_thin push_tags
2640
2641         set w .push_setup
2642         toplevel $w
2643         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2644
2645         label $w.header -text {Push Branches} -font font_uibold
2646         pack $w.header -side top -fill x
2647
2648         frame $w.buttons
2649         button $w.buttons.create -text Push \
2650                 -font font_ui \
2651                 -command [list start_push_anywhere_action $w]
2652         pack $w.buttons.create -side right
2653         button $w.buttons.cancel -text {Cancel} \
2654                 -font font_ui \
2655                 -command [list destroy $w]
2656         pack $w.buttons.cancel -side right -padx 5
2657         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2658
2659         labelframe $w.source \
2660                 -text {Source Branches} \
2661                 -font font_ui
2662         listbox $w.source.l \
2663                 -height 10 \
2664                 -width 70 \
2665                 -selectmode extended \
2666                 -yscrollcommand [list $w.source.sby set] \
2667                 -font font_ui
2668         foreach h $all_heads {
2669                 $w.source.l insert end $h
2670                 if {$h eq $current_branch} {
2671                         $w.source.l select set end
2672                 }
2673         }
2674         scrollbar $w.source.sby -command [list $w.source.l yview]
2675         pack $w.source.sby -side right -fill y
2676         pack $w.source.l -side left -fill both -expand 1
2677         pack $w.source -fill both -expand 1 -pady 5 -padx 5
2678
2679         labelframe $w.dest \
2680                 -text {Destination Repository} \
2681                 -font font_ui
2682         if {$all_remotes ne {}} {
2683                 radiobutton $w.dest.remote_r \
2684                         -text {Remote:} \
2685                         -value remote \
2686                         -variable push_urltype \
2687                         -font font_ui
2688                 eval tk_optionMenu $w.dest.remote_m push_remote $all_remotes
2689                 grid $w.dest.remote_r $w.dest.remote_m -sticky w
2690                 if {[lsearch -sorted -exact $all_remotes origin] != -1} {
2691                         set push_remote origin
2692                 } else {
2693                         set push_remote [lindex $all_remotes 0]
2694                 }
2695                 set push_urltype remote
2696         } else {
2697                 set push_urltype url
2698         }
2699         radiobutton $w.dest.url_r \
2700                 -text {Arbitrary URL:} \
2701                 -value url \
2702                 -variable push_urltype \
2703                 -font font_ui
2704         entry $w.dest.url_t \
2705                 -borderwidth 1 \
2706                 -relief sunken \
2707                 -width 50 \
2708                 -textvariable push_url \
2709                 -font font_ui \
2710                 -validate key \
2711                 -validatecommand {
2712                         if {%d == 1 && [regexp {\s} %S]} {return 0}
2713                         if {%d == 1 && [string length %S] > 0} {
2714                                 set push_urltype url
2715                         }
2716                         return 1
2717                 }
2718         grid $w.dest.url_r $w.dest.url_t -sticky we -padx {0 5}
2719         grid columnconfigure $w.dest 1 -weight 1
2720         pack $w.dest -anchor nw -fill x -pady 5 -padx 5
2721
2722         labelframe $w.options \
2723                 -text {Transfer Options} \
2724                 -font font_ui
2725         checkbutton $w.options.thin \
2726                 -text {Use thin pack (for slow network connections)} \
2727                 -variable push_thin \
2728                 -font font_ui
2729         grid $w.options.thin -columnspan 2 -sticky w
2730         checkbutton $w.options.tags \
2731                 -text {Include tags} \
2732                 -variable push_tags \
2733                 -font font_ui
2734         grid $w.options.tags -columnspan 2 -sticky w
2735         grid columnconfigure $w.options 1 -weight 1
2736         pack $w.options -anchor nw -fill x -pady 5 -padx 5
2737
2738         set push_url {}
2739         set push_thin 0
2740         set push_tags 0
2741
2742         bind $w <Visibility> "grab $w"
2743         bind $w <Key-Escape> "destroy $w"
2744         wm title $w "[appname] ([reponame]): Push"
2745         tkwait window $w
2746 }
2747
2748 ######################################################################
2749 ##
2750 ## merge
2751
2752 proc can_merge {} {
2753         global HEAD commit_type file_states
2754
2755         if {[string match amend* $commit_type]} {
2756                 info_popup {Cannot merge while amending.
2757
2758 You must finish amending this commit before
2759 starting any type of merge.
2760 }
2761                 return 0
2762         }
2763
2764         if {[committer_ident] eq {}} {return 0}
2765         if {![lock_index merge]} {return 0}
2766
2767         # -- Our in memory state should match the repository.
2768         #
2769         repository_state curType curHEAD curMERGE_HEAD
2770         if {$commit_type ne $curType || $HEAD ne $curHEAD} {
2771                 info_popup {Last scanned state does not match repository state.
2772
2773 Another Git program has modified this repository
2774 since the last scan.  A rescan must be performed
2775 before a merge can be performed.
2776
2777 The rescan will be automatically started now.
2778 }
2779                 unlock_index
2780                 rescan {set ui_status_value {Ready.}}
2781                 return 0
2782         }
2783
2784         foreach path [array names file_states] {
2785                 switch -glob -- [lindex $file_states($path) 0] {
2786                 _O {
2787                         continue; # and pray it works!
2788                 }
2789                 U? {
2790                         error_popup "You are in the middle of a conflicted merge.
2791
2792 File [short_path $path] has merge conflicts.
2793
2794 You must resolve them, add the file, and commit to
2795 complete the current merge.  Only then can you
2796 begin another merge.
2797 "
2798                         unlock_index
2799                         return 0
2800                 }
2801                 ?? {
2802                         error_popup "You are in the middle of a change.
2803
2804 File [short_path $path] is modified.
2805
2806 You should complete the current commit before
2807 starting a merge.  Doing so will help you abort
2808 a failed merge, should the need arise.
2809 "
2810                         unlock_index
2811                         return 0
2812                 }
2813                 }
2814         }
2815
2816         return 1
2817 }
2818
2819 proc visualize_local_merge {w} {
2820         set revs {}
2821         foreach i [$w.source.l curselection] {
2822                 lappend revs [$w.source.l get $i]
2823         }
2824         if {$revs eq {}} return
2825         lappend revs --not HEAD
2826         do_gitk $revs
2827 }
2828
2829 proc start_local_merge_action {w} {
2830         global HEAD ui_status_value current_branch
2831
2832         set cmd [list git merge]
2833         set names {}
2834         set revcnt 0
2835         foreach i [$w.source.l curselection] {
2836                 set b [$w.source.l get $i]
2837                 lappend cmd $b
2838                 lappend names $b
2839                 incr revcnt
2840         }
2841
2842         if {$revcnt == 0} {
2843                 return
2844         } elseif {$revcnt == 1} {
2845                 set unit branch
2846         } elseif {$revcnt <= 15} {
2847                 set unit branches
2848         } else {
2849                 tk_messageBox \
2850                         -icon error \
2851                         -type ok \
2852                         -title [wm title $w] \
2853                         -parent $w \
2854                         -message "Too many branches selected.
2855
2856 You have requested to merge $revcnt branches
2857 in an octopus merge.  This exceeds Git's
2858 internal limit of 15 branches per merge.
2859
2860 Please select fewer branches.  To merge more
2861 than 15 branches, merge the branches in batches.
2862 "
2863                 return
2864         }
2865
2866         set msg "Merging $current_branch, [join $names {, }]"
2867         set ui_status_value "$msg..."
2868         set cons [new_console "Merge" $msg]
2869         console_exec $cons $cmd [list finish_merge $revcnt]
2870         bind $w <Destroy> {}
2871         destroy $w
2872 }
2873
2874 proc finish_merge {revcnt w ok} {
2875         console_done $w $ok
2876         if {$ok} {
2877                 set msg {Merge completed successfully.}
2878         } else {
2879                 if {$revcnt != 1} {
2880                         info_popup "Octopus merge failed.
2881
2882 Your merge of $revcnt branches has failed.
2883
2884 There are file-level conflicts between the
2885 branches which must be resolved manually.
2886
2887 The working directory will now be reset.
2888
2889 You can attempt this merge again
2890 by merging only one branch at a time." $w
2891
2892                         set fd [open "| git read-tree --reset -u HEAD" r]
2893                         fconfigure $fd -blocking 0 -translation binary
2894                         fileevent $fd readable [list reset_hard_wait $fd]
2895                         set ui_status_value {Aborting... please wait...}
2896                         return
2897                 }
2898
2899                 set msg {Merge failed.  Conflict resolution is required.}
2900         }
2901         unlock_index
2902         rescan [list set ui_status_value $msg]
2903 }
2904
2905 proc do_local_merge {} {
2906         global current_branch
2907
2908         if {![can_merge]} return
2909
2910         set w .merge_setup
2911         toplevel $w
2912         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2913
2914         label $w.header \
2915                 -text "Merge Into $current_branch" \
2916                 -font font_uibold
2917         pack $w.header -side top -fill x
2918
2919         frame $w.buttons
2920         button $w.buttons.visualize -text Visualize \
2921                 -font font_ui \
2922                 -command [list visualize_local_merge $w]
2923         pack $w.buttons.visualize -side left
2924         button $w.buttons.create -text Merge \
2925                 -font font_ui \
2926                 -command [list start_local_merge_action $w]
2927         pack $w.buttons.create -side right
2928         button $w.buttons.cancel -text {Cancel} \
2929                 -font font_ui \
2930                 -command [list destroy $w]
2931         pack $w.buttons.cancel -side right -padx 5
2932         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2933
2934         labelframe $w.source \
2935                 -text {Source Branches} \
2936                 -font font_ui
2937         listbox $w.source.l \
2938                 -height 10 \
2939                 -width 70 \
2940                 -selectmode extended \
2941                 -yscrollcommand [list $w.source.sby set] \
2942                 -font font_ui
2943         scrollbar $w.source.sby -command [list $w.source.l yview]
2944         pack $w.source.sby -side right -fill y
2945         pack $w.source.l -side left -fill both -expand 1
2946         pack $w.source -fill both -expand 1 -pady 5 -padx 5
2947
2948         set cmd [list git for-each-ref]
2949         lappend cmd {--format=%(objectname) %(*objectname) %(refname)}
2950         lappend cmd refs/heads
2951         lappend cmd refs/remotes
2952         lappend cmd refs/tags
2953         set fr_fd [open "| $cmd" r]
2954         fconfigure $fr_fd -translation binary
2955         while {[gets $fr_fd line] > 0} {
2956                 set line [split $line { }]
2957                 set sha1([lindex $line 0]) [lindex $line 2]
2958                 set sha1([lindex $line 1]) [lindex $line 2]
2959         }
2960         close $fr_fd
2961
2962         set to_show {}
2963         set fr_fd [open "| git rev-list --all --not HEAD"]
2964         while {[gets $fr_fd line] > 0} {
2965                 if {[catch {set ref $sha1($line)}]} continue
2966                 regsub ^refs/(heads|remotes|tags)/ $ref {} ref
2967                 lappend to_show $ref
2968         }
2969         close $fr_fd
2970
2971         foreach ref [lsort -unique $to_show] {
2972                 $w.source.l insert end $ref
2973         }
2974
2975         bind $w <Visibility> "grab $w"
2976         bind $w <Key-Escape> "unlock_index;destroy $w"
2977         bind $w <Destroy> unlock_index
2978         wm title $w "[appname] ([reponame]): Merge"
2979         tkwait window $w
2980 }
2981
2982 proc do_reset_hard {} {
2983         global HEAD commit_type file_states
2984
2985         if {[string match amend* $commit_type]} {
2986                 info_popup {Cannot abort while amending.
2987
2988 You must finish amending this commit.
2989 }
2990                 return
2991         }
2992
2993         if {![lock_index abort]} return
2994
2995         if {[string match *merge* $commit_type]} {
2996                 set op merge
2997         } else {
2998                 set op commit
2999         }
3000
3001         if {[ask_popup "Abort $op?
3002
3003 Aborting the current $op will cause
3004 *ALL* uncommitted changes to be lost.
3005
3006 Continue with aborting the current $op?"] eq {yes}} {
3007                 set fd [open "| git read-tree --reset -u HEAD" r]
3008                 fconfigure $fd -blocking 0 -translation binary
3009                 fileevent $fd readable [list reset_hard_wait $fd]
3010                 set ui_status_value {Aborting... please wait...}
3011         } else {
3012                 unlock_index
3013         }
3014 }
3015
3016 proc reset_hard_wait {fd} {
3017         global ui_comm
3018
3019         read $fd
3020         if {[eof $fd]} {
3021                 close $fd
3022                 unlock_index
3023
3024                 $ui_comm delete 0.0 end
3025                 $ui_comm edit modified false
3026
3027                 catch {file delete [gitdir MERGE_HEAD]}
3028                 catch {file delete [gitdir rr-cache MERGE_RR]}
3029                 catch {file delete [gitdir SQUASH_MSG]}
3030                 catch {file delete [gitdir MERGE_MSG]}
3031                 catch {file delete [gitdir GITGUI_MSG]}
3032
3033                 rescan {set ui_status_value {Abort completed.  Ready.}}
3034         }
3035 }
3036
3037 ######################################################################
3038 ##
3039 ## browser
3040
3041 set next_browser_id 0
3042
3043 proc new_browser {commit} {
3044         global next_browser_id cursor_ptr M1B
3045         global browser_commit browser_status browser_stack browser_path browser_busy
3046
3047         if {[winfo ismapped .]} {
3048                 set w .browser[incr next_browser_id]
3049                 set tl $w
3050                 toplevel $w
3051         } else {
3052                 set w {}
3053                 set tl .
3054         }
3055         set w_list $w.list.l
3056         set browser_commit($w_list) $commit
3057         set browser_status($w_list) {Starting...}
3058         set browser_stack($w_list) {}
3059         set browser_path($w_list) $browser_commit($w_list):
3060         set browser_busy($w_list) 1
3061
3062         label $w.path -textvariable browser_path($w_list) \
3063                 -anchor w \
3064                 -justify left \
3065                 -borderwidth 1 \
3066                 -relief sunken \
3067                 -font font_uibold
3068         pack $w.path -anchor w -side top -fill x
3069
3070         frame $w.list
3071         text $w_list -background white -borderwidth 0 \
3072                 -cursor $cursor_ptr \
3073                 -state disabled \
3074                 -wrap none \
3075                 -height 20 \
3076                 -width 70 \
3077                 -xscrollcommand [list $w.list.sbx set] \
3078                 -yscrollcommand [list $w.list.sby set] \
3079                 -font font_ui
3080         $w_list tag conf in_sel \
3081                 -background [$w_list cget -foreground] \
3082                 -foreground [$w_list cget -background]
3083         scrollbar $w.list.sbx -orient h -command [list $w_list xview]
3084         scrollbar $w.list.sby -orient v -command [list $w_list yview]
3085         pack $w.list.sbx -side bottom -fill x
3086         pack $w.list.sby -side right -fill y
3087         pack $w_list -side left -fill both -expand 1
3088         pack $w.list -side top -fill both -expand 1
3089
3090         label $w.status -textvariable browser_status($w_list) \
3091                 -anchor w \
3092                 -justify left \
3093                 -borderwidth 1 \
3094                 -relief sunken \
3095                 -font font_ui
3096         pack $w.status -anchor w -side bottom -fill x
3097
3098         bind $w_list <Button-1>        "browser_click 0 $w_list @%x,%y;break"
3099         bind $w_list <Double-Button-1> "browser_click 1 $w_list @%x,%y;break"
3100         bind $w_list <$M1B-Up>         "browser_parent $w_list;break"
3101         bind $w_list <$M1B-Left>       "browser_parent $w_list;break"
3102         bind $w_list <Up>              "browser_move -1 $w_list;break"
3103         bind $w_list <Down>            "browser_move 1 $w_list;break"
3104         bind $w_list <$M1B-Right>      "browser_enter $w_list;break"
3105         bind $w_list <Return>          "browser_enter $w_list;break"
3106         bind $w_list <Prior>           "browser_page -1 $w_list;break"
3107         bind $w_list <Next>            "browser_page 1 $w_list;break"
3108         bind $w_list <Left>            break
3109         bind $w_list <Right>           break
3110
3111         bind $tl <Visibility> "focus $w"
3112         bind $tl <Destroy> "
3113                 array unset browser_buffer $w_list
3114                 array unset browser_files $w_list
3115                 array unset browser_status $w_list
3116                 array unset browser_stack $w_list
3117                 array unset browser_path $w_list
3118                 array unset browser_commit $w_list
3119                 array unset browser_busy $w_list
3120         "
3121         wm title $tl "[appname] ([reponame]): File Browser"
3122         ls_tree $w_list $browser_commit($w_list) {}
3123 }
3124
3125 proc browser_move {dir w} {
3126         global browser_files browser_busy
3127
3128         if {$browser_busy($w)} return
3129         set lno [lindex [split [$w index in_sel.first] .] 0]
3130         incr lno $dir
3131         if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3132                 $w tag remove in_sel 0.0 end
3133                 $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3134                 $w see $lno.0
3135         }
3136 }
3137
3138 proc browser_page {dir w} {
3139         global browser_files browser_busy
3140
3141         if {$browser_busy($w)} return
3142         $w yview scroll $dir pages
3143         set lno [expr {int(
3144                   [lindex [$w yview] 0]
3145                 * [llength $browser_files($w)]
3146                 + 1)}]
3147         if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3148                 $w tag remove in_sel 0.0 end
3149                 $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3150                 $w see $lno.0
3151         }
3152 }
3153
3154 proc browser_parent {w} {
3155         global browser_files browser_status browser_path
3156         global browser_stack browser_busy
3157
3158         if {$browser_busy($w)} return
3159         set info [lindex $browser_files($w) 0]
3160         if {[lindex $info 0] eq {parent}} {
3161                 set parent [lindex $browser_stack($w) end-1]
3162                 set browser_stack($w) [lrange $browser_stack($w) 0 end-2]
3163                 if {$browser_stack($w) eq {}} {
3164                         regsub {:.*$} $browser_path($w) {:} browser_path($w)
3165                 } else {
3166                         regsub {/[^/]+$} $browser_path($w) {} browser_path($w)
3167                 }
3168                 set browser_status($w) "Loading $browser_path($w)..."
3169                 ls_tree $w [lindex $parent 0] [lindex $parent 1]
3170         }
3171 }
3172
3173 proc browser_enter {w} {
3174         global browser_files browser_status browser_path
3175         global browser_commit browser_stack browser_busy
3176
3177         if {$browser_busy($w)} return
3178         set lno [lindex [split [$w index in_sel.first] .] 0]
3179         set info [lindex $browser_files($w) [expr {$lno - 1}]]
3180         if {$info ne {}} {
3181                 switch -- [lindex $info 0] {
3182                 parent {
3183                         browser_parent $w
3184                 }
3185                 tree {
3186                         set name [lindex $info 2]
3187                         set escn [escape_path $name]
3188                         set browser_status($w) "Loading $escn..."
3189                         append browser_path($w) $escn
3190                         ls_tree $w [lindex $info 1] $name
3191                 }
3192                 blob {
3193                         set name [lindex $info 2]
3194                         set p {}
3195                         foreach n $browser_stack($w) {
3196                                 append p [lindex $n 1]
3197                         }
3198                         append p $name
3199                         show_blame $browser_commit($w) $p
3200                 }
3201                 }
3202         }
3203 }
3204
3205 proc browser_click {was_double_click w pos} {
3206         global browser_files browser_busy
3207
3208         if {$browser_busy($w)} return
3209         set lno [lindex [split [$w index $pos] .] 0]
3210         focus $w
3211
3212         if {[lindex $browser_files($w) [expr {$lno - 1}]] ne {}} {
3213                 $w tag remove in_sel 0.0 end
3214                 $w tag add in_sel $lno.0 [expr {$lno + 1}].0
3215                 if {$was_double_click} {
3216                         browser_enter $w
3217                 }
3218         }
3219 }
3220
3221 proc ls_tree {w tree_id name} {
3222         global browser_buffer browser_files browser_stack browser_busy
3223
3224         set browser_buffer($w) {}
3225         set browser_files($w) {}
3226         set browser_busy($w) 1
3227
3228         $w conf -state normal
3229         $w tag remove in_sel 0.0 end
3230         $w delete 0.0 end
3231         if {$browser_stack($w) ne {}} {
3232                 $w image create end \
3233                         -align center -padx 5 -pady 1 \
3234                         -name icon0 \
3235                         -image file_uplevel
3236                 $w insert end {[Up To Parent]}
3237                 lappend browser_files($w) parent
3238         }
3239         lappend browser_stack($w) [list $tree_id $name]
3240         $w conf -state disabled
3241
3242         set cmd [list git ls-tree -z $tree_id]
3243         set fd [open "| $cmd" r]
3244         fconfigure $fd -blocking 0 -translation binary -encoding binary
3245         fileevent $fd readable [list read_ls_tree $fd $w]
3246 }
3247
3248 proc read_ls_tree {fd w} {
3249         global browser_buffer browser_files browser_status browser_busy
3250
3251         if {![winfo exists $w]} {
3252                 catch {close $fd}
3253                 return
3254         }
3255
3256         append browser_buffer($w) [read $fd]
3257         set pck [split $browser_buffer($w) "\0"]
3258         set browser_buffer($w) [lindex $pck end]
3259
3260         set n [llength $browser_files($w)]
3261         $w conf -state normal
3262         foreach p [lrange $pck 0 end-1] {
3263                 set info [split $p "\t"]
3264                 set path [lindex $info 1]
3265                 set info [split [lindex $info 0] { }]
3266                 set type [lindex $info 1]
3267                 set object [lindex $info 2]
3268
3269                 switch -- $type {
3270                 blob {
3271                         set image file_mod
3272                 }
3273                 tree {
3274                         set image file_dir
3275                         append path /
3276                 }
3277                 default {
3278                         set image file_question
3279                 }
3280                 }
3281
3282                 if {$n > 0} {$w insert end "\n"}
3283                 $w image create end \
3284                         -align center -padx 5 -pady 1 \
3285                         -name icon[incr n] \
3286                         -image $image
3287                 $w insert end [escape_path $path]
3288                 lappend browser_files($w) [list $type $object $path]
3289         }
3290         $w conf -state disabled
3291
3292         if {[eof $fd]} {
3293                 close $fd
3294                 set browser_status($w) Ready.
3295                 set browser_busy($w) 0
3296                 array unset browser_buffer $w
3297                 if {$n > 0} {
3298                         $w tag add in_sel 1.0 2.0
3299                         focus -force $w
3300                 }
3301         }
3302 }
3303
3304 proc show_blame {commit path} {
3305         global next_browser_id blame_status blame_data
3306
3307         if {[winfo ismapped .]} {
3308                 set w .browser[incr next_browser_id]
3309                 set tl $w
3310                 toplevel $w
3311         } else {
3312                 set w {}
3313                 set tl .
3314         }
3315         set blame_status($w) {Loading current file content...}
3316
3317         label $w.path -text "$commit:$path" \
3318                 -anchor w \
3319                 -justify left \
3320                 -borderwidth 1 \
3321                 -relief sunken \
3322                 -font font_uibold
3323         pack $w.path -side top -fill x
3324
3325         frame $w.out
3326         text $w.out.loaded_t \
3327                 -background white -borderwidth 0 \
3328                 -state disabled \
3329                 -wrap none \
3330                 -height 40 \
3331                 -width 1 \
3332                 -font font_diff
3333         $w.out.loaded_t tag conf annotated -background grey
3334
3335         text $w.out.linenumber_t \
3336                 -background white -borderwidth 0 \
3337                 -state disabled \
3338                 -wrap none \
3339                 -height 40 \
3340                 -width 5 \
3341                 -font font_diff
3342         $w.out.linenumber_t tag conf linenumber -justify right
3343
3344         text $w.out.file_t \
3345                 -background white -borderwidth 0 \
3346                 -state disabled \
3347                 -wrap none \
3348                 -height 40 \
3349                 -width 80 \
3350                 -xscrollcommand [list $w.out.sbx set] \
3351                 -font font_diff
3352
3353         scrollbar $w.out.sbx -orient h -command [list $w.out.file_t xview]
3354         scrollbar $w.out.sby -orient v \
3355                 -command [list scrollbar2many [list \
3356                 $w.out.loaded_t \
3357                 $w.out.linenumber_t \
3358                 $w.out.file_t \
3359                 ] yview]
3360         grid \
3361                 $w.out.linenumber_t \
3362                 $w.out.loaded_t \
3363                 $w.out.file_t \
3364                 $w.out.sby \
3365                 -sticky nsew
3366         grid conf $w.out.sbx -column 2 -sticky we
3367         grid columnconfigure $w.out 2 -weight 1
3368         grid rowconfigure $w.out 0 -weight 1
3369         pack $w.out -fill both -expand 1
3370
3371         label $w.status -textvariable blame_status($w) \
3372                 -anchor w \
3373                 -justify left \
3374                 -borderwidth 1 \
3375                 -relief sunken \
3376                 -font font_ui
3377         pack $w.status -side bottom -fill x
3378
3379         frame $w.cm
3380         text $w.cm.t \
3381                 -background white -borderwidth 0 \
3382                 -state disabled \
3383                 -wrap none \
3384                 -height 10 \
3385                 -width 80 \
3386                 -xscrollcommand [list $w.cm.sbx set] \
3387                 -yscrollcommand [list $w.cm.sby set] \
3388                 -font font_diff
3389         scrollbar $w.cm.sbx -orient h -command [list $w.cm.t xview]
3390         scrollbar $w.cm.sby -orient v -command [list $w.cm.t yview]
3391         pack $w.cm.sby -side right -fill y
3392         pack $w.cm.sbx -side bottom -fill x
3393         pack $w.cm.t -expand 1 -fill both
3394         pack $w.cm -side bottom -fill x
3395
3396         menu $w.ctxm -tearoff 0
3397         $w.ctxm add command -label "Copy Commit" \
3398                 -font font_ui \
3399                 -command "blame_copycommit $w \$cursorW @\$cursorX,\$cursorY"
3400
3401         foreach i [list \
3402                 $w.out.loaded_t \
3403                 $w.out.linenumber_t \
3404                 $w.out.file_t] {
3405                 $i tag conf in_sel \
3406                         -background [$i cget -foreground] \
3407                         -foreground [$i cget -background]
3408                 $i conf -yscrollcommand \
3409                         [list many2scrollbar [list \
3410                         $w.out.loaded_t \
3411                         $w.out.linenumber_t \
3412                         $w.out.file_t \
3413                         ] yview $w.out.sby]
3414                 bind $i <Button-1> "
3415                         blame_click {$w} \\
3416                                 $w.cm.t \\
3417                                 $w.out.linenumber_t \\
3418                                 $w.out.file_t \\
3419                                 $i @%x,%y
3420                         focus $i
3421                 "
3422                 bind_button3 $i "
3423                         set cursorX %x
3424                         set cursorY %y
3425                         set cursorW %W
3426                         tk_popup $w.ctxm %X %Y
3427                 "
3428         }
3429
3430         bind $w.cm.t <Button-1> "focus $w.cm.t"
3431         bind $tl <Visibility> "focus $tl"
3432         bind $tl <Destroy> "
3433                 array unset blame_status {$w}
3434                 array unset blame_data $w,*
3435         "
3436         wm title $tl "[appname] ([reponame]): File Viewer"
3437
3438         set blame_data($w,commit_count) 0
3439         set blame_data($w,commit_list) {}
3440         set blame_data($w,total_lines) 0
3441         set blame_data($w,blame_lines) 0
3442         set blame_data($w,highlight_commit) {}
3443         set blame_data($w,highlight_line) -1
3444
3445         set cmd [list git cat-file blob "$commit:$path"]
3446         set fd [open "| $cmd" r]
3447         fconfigure $fd -blocking 0 -translation lf -encoding binary
3448         fileevent $fd readable [list read_blame_catfile \
3449                 $fd $w $commit $path \
3450                 $w.cm.t $w.out.loaded_t $w.out.linenumber_t $w.out.file_t]
3451 }
3452
3453 proc read_blame_catfile {fd w commit path w_cmit w_load w_line w_file} {
3454         global blame_status blame_data
3455
3456         if {![winfo exists $w_file]} {
3457                 catch {close $fd}
3458                 return
3459         }
3460
3461         set n $blame_data($w,total_lines)
3462         $w_load conf -state normal
3463         $w_line conf -state normal
3464         $w_file conf -state normal
3465         while {[gets $fd line] >= 0} {
3466                 regsub "\r\$" $line {} line
3467                 incr n
3468                 $w_load insert end "\n"
3469                 $w_line insert end "$n\n" linenumber
3470                 $w_file insert end "$line\n"
3471         }
3472         $w_load conf -state disabled
3473         $w_line conf -state disabled
3474         $w_file conf -state disabled
3475         set blame_data($w,total_lines) $n
3476
3477         if {[eof $fd]} {
3478                 close $fd
3479                 blame_incremental_status $w
3480                 set cmd [list git blame -M -C --incremental]
3481                 lappend cmd $commit -- $path
3482                 set fd [open "| $cmd" r]
3483                 fconfigure $fd -blocking 0 -translation lf -encoding binary
3484                 fileevent $fd readable [list read_blame_incremental $fd $w \
3485                         $w_load $w_cmit $w_line $w_file]
3486         }
3487 }
3488
3489 proc read_blame_incremental {fd w w_load w_cmit w_line w_file} {
3490         global blame_status blame_data
3491
3492         if {![winfo exists $w_file]} {
3493                 catch {close $fd}
3494                 return
3495         }
3496
3497         while {[gets $fd line] >= 0} {
3498                 if {[regexp {^([a-z0-9]{40}) (\d+) (\d+) (\d+)$} $line line \
3499                         cmit original_line final_line line_count]} {
3500                         set blame_data($w,commit) $cmit
3501                         set blame_data($w,original_line) $original_line
3502                         set blame_data($w,final_line) $final_line
3503                         set blame_data($w,line_count) $line_count
3504
3505                         if {[catch {set g $blame_data($w,$cmit,order)}]} {
3506                                 $w_line tag conf g$cmit
3507                                 $w_file tag conf g$cmit
3508                                 $w_line tag raise in_sel
3509                                 $w_file tag raise in_sel
3510                                 $w_file tag raise sel
3511                                 set blame_data($w,$cmit,order) $blame_data($w,commit_count)
3512                                 incr blame_data($w,commit_count)
3513                                 lappend blame_data($w,commit_list) $cmit
3514                         }
3515                 } elseif {[string match {filename *} $line]} {
3516                         set file [string range $line 9 end]
3517                         set n $blame_data($w,line_count)
3518                         set lno $blame_data($w,final_line)
3519                         set cmit $blame_data($w,commit)
3520
3521                         while {$n > 0} {
3522                                 if {[catch {set g g$blame_data($w,line$lno,commit)}]} {
3523                                         $w_load tag add annotated $lno.0 "$lno.0 lineend + 1c"
3524                                 } else {
3525                                         $w_line tag remove g$g $lno.0 "$lno.0 lineend + 1c"
3526                                         $w_file tag remove g$g $lno.0 "$lno.0 lineend + 1c"
3527                                 }
3528
3529                                 set blame_data($w,line$lno,commit) $cmit
3530                                 set blame_data($w,line$lno,file) $file
3531                                 $w_line tag add g$cmit $lno.0 "$lno.0 lineend + 1c"
3532                                 $w_file tag add g$cmit $lno.0 "$lno.0 lineend + 1c"
3533
3534                                 if {$blame_data($w,highlight_line) == -1} {
3535                                         if {[lindex [$w_file yview] 0] == 0} {
3536                                                 $w_file see $lno.0
3537                                                 blame_showcommit $w $w_cmit $w_line $w_file $lno
3538                                         }
3539                                 } elseif {$blame_data($w,highlight_line) == $lno} {
3540                                         blame_showcommit $w $w_cmit $w_line $w_file $lno
3541                                 }
3542
3543                                 incr n -1
3544                                 incr lno
3545                                 incr blame_data($w,blame_lines)
3546                         }
3547
3548                         set hc $blame_data($w,highlight_commit)
3549                         if {$hc ne {}
3550                                 && [expr {$blame_data($w,$hc,order) + 1}]
3551                                         == $blame_data($w,$cmit,order)} {
3552                                 blame_showcommit $w $w_cmit $w_line $w_file \
3553                                         $blame_data($w,highlight_line)
3554                         }
3555                 } elseif {[regexp {^([a-z-]+) (.*)$} $line line header data]} {
3556                         set blame_data($w,$blame_data($w,commit),$header) $data
3557                 }
3558         }
3559
3560         if {[eof $fd]} {
3561                 close $fd
3562                 set blame_status($w) {Annotation complete.}
3563         } else {
3564                 blame_incremental_status $w
3565         }
3566 }
3567
3568 proc blame_incremental_status {w} {
3569         global blame_status blame_data
3570
3571         set blame_status($w) [format \
3572                 "Loading annotations... %i of %i lines annotated (%2i%%)" \
3573                 $blame_data($w,blame_lines) \
3574                 $blame_data($w,total_lines) \
3575                 [expr {100 * $blame_data($w,blame_lines)
3576                         / $blame_data($w,total_lines)}]]
3577 }
3578
3579 proc blame_click {w w_cmit w_line w_file cur_w pos} {
3580         set lno [lindex [split [$cur_w index $pos] .] 0]
3581         if {$lno eq {}} return
3582
3583         $w_line tag remove in_sel 0.0 end
3584         $w_file tag remove in_sel 0.0 end
3585         $w_line tag add in_sel $lno.0 "$lno.0 + 1 line"
3586         $w_file tag add in_sel $lno.0 "$lno.0 + 1 line"
3587
3588         blame_showcommit $w $w_cmit $w_line $w_file $lno
3589 }
3590
3591 set blame_colors {
3592         #ff4040
3593         #ff40ff
3594         #4040ff
3595 }
3596
3597 proc blame_showcommit {w w_cmit w_line w_file lno} {
3598         global blame_colors blame_data repo_config
3599
3600         set cmit $blame_data($w,highlight_commit)
3601         if {$cmit ne {}} {
3602                 set idx $blame_data($w,$cmit,order)
3603                 set i 0
3604                 foreach c $blame_colors {
3605                         set h [lindex $blame_data($w,commit_list) [expr {$idx - 1 + $i}]]
3606                         $w_line tag conf g$h -background white
3607                         $w_file tag conf g$h -background white
3608                         incr i
3609                 }
3610         }
3611
3612         $w_cmit conf -state normal
3613         $w_cmit delete 0.0 end
3614         if {[catch {set cmit $blame_data($w,line$lno,commit)}]} {
3615                 set cmit {}
3616                 $w_cmit insert end "Loading annotation..."
3617         } else {
3618                 set idx $blame_data($w,$cmit,order)
3619                 set i 0
3620                 foreach c $blame_colors {
3621                         set h [lindex $blame_data($w,commit_list) [expr {$idx - 1 + $i}]]
3622                         $w_line tag conf g$h -background $c
3623                         $w_file tag conf g$h -background $c
3624                         incr i
3625                 }
3626
3627                 if {[catch {set msg $blame_data($w,$cmit,message)}]} {
3628                         set msg {}
3629                         catch {
3630                                 set fd [open "| git cat-file commit $cmit" r]
3631                                 fconfigure $fd -encoding binary -translation lf
3632                                 if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
3633                                         set enc utf-8
3634                                 }
3635                                 while {[gets $fd line] > 0} {
3636                                         if {[string match {encoding *} $line]} {
3637                                                 set enc [string tolower [string range $line 9 end]]
3638                                         }
3639                                 }
3640                                 fconfigure $fd -encoding $enc
3641                                 set msg [string trim [read $fd]]
3642                                 close $fd
3643                         }
3644                         set blame_data($w,$cmit,message) $msg
3645                 }
3646
3647                 set author_name {}
3648                 set author_email {}
3649                 set author_time {}
3650                 catch {set author_name $blame_data($w,$cmit,author)}
3651                 catch {set author_email $blame_data($w,$cmit,author-mail)}
3652                 catch {set author_time [clock format $blame_data($w,$cmit,author-time)]}
3653
3654                 set committer_name {}
3655                 set committer_email {}
3656                 set committer_time {}
3657                 catch {set committer_name $blame_data($w,$cmit,committer)}
3658                 catch {set committer_email $blame_data($w,$cmit,committer-mail)}
3659                 catch {set committer_time [clock format $blame_data($w,$cmit,committer-time)]}
3660
3661                 $w_cmit insert end "commit $cmit\n"
3662                 $w_cmit insert end "Author: $author_name $author_email $author_time\n"
3663                 $w_cmit insert end "Committer: $committer_name $committer_email $committer_time\n"
3664                 $w_cmit insert end "Original File: [escape_path $blame_data($w,line$lno,file)]\n"
3665                 $w_cmit insert end "\n"
3666                 $w_cmit insert end $msg
3667         }
3668         $w_cmit conf -state disabled
3669
3670         set blame_data($w,highlight_line) $lno
3671         set blame_data($w,highlight_commit) $cmit
3672 }
3673
3674 proc blame_copycommit {w i pos} {
3675         global blame_data
3676         set lno [lindex [split [$i index $pos] .] 0]
3677         if {![catch {set commit $blame_data($w,line$lno,commit)}]} {
3678                 clipboard clear
3679                 clipboard append \
3680                         -format STRING \
3681                         -type STRING \
3682                         -- $commit
3683         }
3684 }
3685
3686 ######################################################################
3687 ##
3688 ## icons
3689
3690 set filemask {
3691 #define mask_width 14
3692 #define mask_height 15
3693 static unsigned char mask_bits[] = {
3694    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
3695    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
3696    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
3697 }
3698
3699 image create bitmap file_plain -background white -foreground black -data {
3700 #define plain_width 14
3701 #define plain_height 15
3702 static unsigned char plain_bits[] = {
3703    0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
3704    0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
3705    0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3706 } -maskdata $filemask
3707
3708 image create bitmap file_mod -background white -foreground blue -data {
3709 #define mod_width 14
3710 #define mod_height 15
3711 static unsigned char mod_bits[] = {
3712    0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
3713    0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
3714    0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
3715 } -maskdata $filemask
3716
3717 image create bitmap file_fulltick -background white -foreground "#007000" -data {
3718 #define file_fulltick_width 14
3719 #define file_fulltick_height 15
3720 static unsigned char file_fulltick_bits[] = {
3721    0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
3722    0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
3723    0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3724 } -maskdata $filemask
3725
3726 image create bitmap file_parttick -background white -foreground "#005050" -data {
3727 #define parttick_width 14
3728 #define parttick_height 15
3729 static unsigned char parttick_bits[] = {
3730    0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
3731    0x7a, 0x14, 0x02, 0x16, 0x02, 0x13, 0x8a, 0x11, 0xda, 0x10, 0x72, 0x10,
3732    0x22, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3733 } -maskdata $filemask
3734
3735 image create bitmap file_question -background white -foreground black -data {
3736 #define file_question_width 14
3737 #define file_question_height 15
3738 static unsigned char file_question_bits[] = {
3739    0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
3740    0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
3741    0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
3742 } -maskdata $filemask
3743
3744 image create bitmap file_removed -background white -foreground red -data {
3745 #define file_removed_width 14
3746 #define file_removed_height 15
3747 static unsigned char file_removed_bits[] = {
3748    0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
3749    0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
3750    0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
3751 } -maskdata $filemask
3752
3753 image create bitmap file_merge -background white -foreground blue -data {
3754 #define file_merge_width 14
3755 #define file_merge_height 15
3756 static unsigned char file_merge_bits[] = {
3757    0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
3758    0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
3759    0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
3760 } -maskdata $filemask
3761
3762 set file_dir_data {
3763 #define file_width 18
3764 #define file_height 18
3765 static unsigned char file_bits[] = {
3766   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x03, 0x00,
3767   0x0c, 0x03, 0x00, 0x04, 0xfe, 0x00, 0x06, 0x80, 0x00, 0xff, 0x9f, 0x00,
3768   0x03, 0x98, 0x00, 0x02, 0x90, 0x00, 0x06, 0xb0, 0x00, 0x04, 0xa0, 0x00,
3769   0x0c, 0xe0, 0x00, 0x08, 0xc0, 0x00, 0xf8, 0xff, 0x00, 0x00, 0x00, 0x00,
3770   0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
3771 }
3772 image create bitmap file_dir -background white -foreground blue \
3773         -data $file_dir_data -maskdata $file_dir_data
3774 unset file_dir_data
3775
3776 set file_uplevel_data {
3777 #define up_width 15
3778 #define up_height 15
3779 static unsigned char up_bits[] = {
3780   0x80, 0x00, 0xc0, 0x01, 0xe0, 0x03, 0xf0, 0x07, 0xf8, 0x0f, 0xfc, 0x1f,
3781   0xfe, 0x3f, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01,
3782   0xc0, 0x01, 0xc0, 0x01, 0x00, 0x00};
3783 }
3784 image create bitmap file_uplevel -background white -foreground red \
3785         -data $file_uplevel_data -maskdata $file_uplevel_data
3786 unset file_uplevel_data
3787
3788 set ui_index .vpane.files.index.list
3789 set ui_workdir .vpane.files.workdir.list
3790
3791 set all_icons(_$ui_index)   file_plain
3792 set all_icons(A$ui_index)   file_fulltick
3793 set all_icons(M$ui_index)   file_fulltick
3794 set all_icons(D$ui_index)   file_removed
3795 set all_icons(U$ui_index)   file_merge
3796
3797 set all_icons(_$ui_workdir) file_plain
3798 set all_icons(M$ui_workdir) file_mod
3799 set all_icons(D$ui_workdir) file_question
3800 set all_icons(U$ui_workdir) file_merge
3801 set all_icons(O$ui_workdir) file_plain
3802
3803 set max_status_desc 0
3804 foreach i {
3805                 {__ "Unmodified"}
3806
3807                 {_M "Modified, not staged"}
3808                 {M_ "Staged for commit"}
3809                 {MM "Portions staged for commit"}
3810                 {MD "Staged for commit, missing"}
3811
3812                 {_O "Untracked, not staged"}
3813                 {A_ "Staged for commit"}
3814                 {AM "Portions staged for commit"}
3815                 {AD "Staged for commit, missing"}
3816
3817                 {_D "Missing"}
3818                 {D_ "Staged for removal"}
3819                 {DO "Staged for removal, still present"}
3820
3821                 {U_ "Requires merge resolution"}
3822                 {UU "Requires merge resolution"}
3823                 {UM "Requires merge resolution"}
3824                 {UD "Requires merge resolution"}
3825         } {
3826         if {$max_status_desc < [string length [lindex $i 1]]} {
3827                 set max_status_desc [string length [lindex $i 1]]
3828         }
3829         set all_descs([lindex $i 0]) [lindex $i 1]
3830 }
3831 unset i
3832
3833 ######################################################################
3834 ##
3835 ## util
3836
3837 proc bind_button3 {w cmd} {
3838         bind $w <Any-Button-3> $cmd
3839         if {[is_MacOSX]} {
3840                 bind $w <Control-Button-1> $cmd
3841         }
3842 }
3843
3844 proc scrollbar2many {list mode args} {
3845         foreach w $list {eval $w $mode $args}
3846 }
3847
3848 proc many2scrollbar {list mode sb top bottom} {
3849         $sb set $top $bottom
3850         foreach w $list {$w $mode moveto $top}
3851 }
3852
3853 proc incr_font_size {font {amt 1}} {
3854         set sz [font configure $font -size]
3855         incr sz $amt
3856         font configure $font -size $sz
3857         font configure ${font}bold -size $sz
3858 }
3859
3860 proc hook_failed_popup {hook msg} {
3861         set w .hookfail
3862         toplevel $w
3863
3864         frame $w.m
3865         label $w.m.l1 -text "$hook hook failed:" \
3866                 -anchor w \
3867                 -justify left \
3868                 -font font_uibold
3869         text $w.m.t \
3870                 -background white -borderwidth 1 \
3871                 -relief sunken \
3872                 -width 80 -height 10 \
3873                 -font font_diff \
3874                 -yscrollcommand [list $w.m.sby set]
3875         label $w.m.l2 \
3876                 -text {You must correct the above errors before committing.} \
3877                 -anchor w \
3878                 -justify left \
3879                 -font font_uibold
3880         scrollbar $w.m.sby -command [list $w.m.t yview]
3881         pack $w.m.l1 -side top -fill x
3882         pack $w.m.l2 -side bottom -fill x
3883         pack $w.m.sby -side right -fill y
3884         pack $w.m.t -side left -fill both -expand 1
3885         pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
3886
3887         $w.m.t insert 1.0 $msg
3888         $w.m.t conf -state disabled
3889
3890         button $w.ok -text OK \
3891                 -width 15 \
3892                 -font font_ui \
3893                 -command "destroy $w"
3894         pack $w.ok -side bottom -anchor e -pady 10 -padx 10
3895
3896         bind $w <Visibility> "grab $w; focus $w"
3897         bind $w <Key-Return> "destroy $w"
3898         wm title $w "[appname] ([reponame]): error"
3899         tkwait window $w
3900 }
3901
3902 set next_console_id 0
3903
3904 proc new_console {short_title long_title} {
3905         global next_console_id console_data
3906         set w .console[incr next_console_id]
3907         set console_data($w) [list $short_title $long_title]
3908         return [console_init $w]
3909 }
3910
3911 proc console_init {w} {
3912         global console_cr console_data M1B
3913
3914         set console_cr($w) 1.0
3915         toplevel $w
3916         frame $w.m
3917         label $w.m.l1 -text "[lindex $console_data($w) 1]:" \
3918                 -anchor w \
3919                 -justify left \
3920                 -font font_uibold
3921         text $w.m.t \
3922                 -background white -borderwidth 1 \
3923                 -relief sunken \
3924                 -width 80 -height 10 \
3925                 -font font_diff \
3926                 -state disabled \
3927                 -yscrollcommand [list $w.m.sby set]
3928         label $w.m.s -text {Working... please wait...} \
3929                 -anchor w \
3930                 -justify left \
3931                 -font font_uibold
3932         scrollbar $w.m.sby -command [list $w.m.t yview]
3933         pack $w.m.l1 -side top -fill x
3934         pack $w.m.s -side bottom -fill x
3935         pack $w.m.sby -side right -fill y
3936         pack $w.m.t -side left -fill both -expand 1
3937         pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
3938
3939         menu $w.ctxm -tearoff 0
3940         $w.ctxm add command -label "Copy" \
3941                 -font font_ui \
3942                 -command "tk_textCopy $w.m.t"
3943         $w.ctxm add command -label "Select All" \
3944                 -font font_ui \
3945                 -command "focus $w.m.t;$w.m.t tag add sel 0.0 end"
3946         $w.ctxm add command -label "Copy All" \
3947                 -font font_ui \
3948                 -command "
3949                         $w.m.t tag add sel 0.0 end
3950                         tk_textCopy $w.m.t
3951                         $w.m.t tag remove sel 0.0 end
3952                 "
3953
3954         button $w.ok -text {Close} \
3955                 -font font_ui \
3956                 -state disabled \
3957                 -command "destroy $w"
3958         pack $w.ok -side bottom -anchor e -pady 10 -padx 10
3959
3960         bind_button3 $w.m.t "tk_popup $w.ctxm %X %Y"
3961         bind $w.m.t <$M1B-Key-a> "$w.m.t tag add sel 0.0 end;break"
3962         bind $w.m.t <$M1B-Key-A> "$w.m.t tag add sel 0.0 end;break"
3963         bind $w <Visibility> "focus $w"
3964         wm title $w "[appname] ([reponame]): [lindex $console_data($w) 0]"
3965         return $w
3966 }
3967
3968 proc console_exec {w cmd after} {
3969         # -- Cygwin's Tcl tosses the enviroment when we exec our child.
3970         #    But most users need that so we have to relogin. :-(
3971         #
3972         if {[is_Cygwin]} {
3973                 set cmd [list sh --login -c "cd \"[pwd]\" && [join $cmd { }]"]
3974         }
3975
3976         # -- Tcl won't let us redirect both stdout and stderr to
3977         #    the same pipe.  So pass it through cat...
3978         #
3979         set cmd [concat | $cmd |& cat]
3980
3981         set fd_f [open $cmd r]
3982         fconfigure $fd_f -blocking 0 -translation binary
3983         fileevent $fd_f readable [list console_read $w $fd_f $after]
3984 }
3985
3986 proc console_read {w fd after} {
3987         global console_cr
3988
3989         set buf [read $fd]
3990         if {$buf ne {}} {
3991                 if {![winfo exists $w]} {console_init $w}
3992                 $w.m.t conf -state normal
3993                 set c 0
3994                 set n [string length $buf]
3995                 while {$c < $n} {
3996                         set cr [string first "\r" $buf $c]
3997                         set lf [string first "\n" $buf $c]
3998                         if {$cr < 0} {set cr [expr {$n + 1}]}
3999                         if {$lf < 0} {set lf [expr {$n + 1}]}
4000
4001                         if {$lf < $cr} {
4002                                 $w.m.t insert end [string range $buf $c $lf]
4003                                 set console_cr($w) [$w.m.t index {end -1c}]
4004                                 set c $lf
4005                                 incr c
4006                         } else {
4007                                 $w.m.t delete $console_cr($w) end
4008                                 $w.m.t insert end "\n"
4009                                 $w.m.t insert end [string range $buf $c $cr]
4010                                 set c $cr
4011                                 incr c
4012                         }
4013                 }
4014                 $w.m.t conf -state disabled
4015                 $w.m.t see end
4016         }
4017
4018         fconfigure $fd -blocking 1
4019         if {[eof $fd]} {
4020                 if {[catch {close $fd}]} {
4021                         set ok 0
4022                 } else {
4023                         set ok 1
4024                 }
4025                 uplevel #0 $after $w $ok
4026                 return
4027         }
4028         fconfigure $fd -blocking 0
4029 }
4030
4031 proc console_chain {cmdlist w {ok 1}} {
4032         if {$ok} {
4033                 if {[llength $cmdlist] == 0} {
4034                         console_done $w $ok
4035                         return
4036                 }
4037
4038                 set cmd [lindex $cmdlist 0]
4039                 set cmdlist [lrange $cmdlist 1 end]
4040
4041                 if {[lindex $cmd 0] eq {console_exec}} {
4042                         console_exec $w \
4043                                 [lindex $cmd 1] \
4044                                 [list console_chain $cmdlist]
4045                 } else {
4046                         uplevel #0 $cmd $cmdlist $w $ok
4047                 }
4048         } else {
4049                 console_done $w $ok
4050         }
4051 }
4052
4053 proc console_done {args} {
4054         global console_cr console_data
4055
4056         switch -- [llength $args] {
4057         2 {
4058                 set w [lindex $args 0]
4059                 set ok [lindex $args 1]
4060         }
4061         3 {
4062                 set w [lindex $args 1]
4063                 set ok [lindex $args 2]
4064         }
4065         default {
4066                 error "wrong number of args: console_done ?ignored? w ok"
4067         }
4068         }
4069
4070         if {$ok} {
4071                 if {[winfo exists $w]} {
4072                         $w.m.s conf -background green -text {Success}
4073                         $w.ok conf -state normal
4074                 }
4075         } else {
4076                 if {![winfo exists $w]} {
4077                         console_init $w
4078                 }
4079                 $w.m.s conf -background red -text {Error: Command Failed}
4080                 $w.ok conf -state normal
4081         }
4082
4083         array unset console_cr $w
4084         array unset console_data $w
4085 }
4086
4087 ######################################################################
4088 ##
4089 ## ui commands
4090
4091 set starting_gitk_msg {Starting gitk... please wait...}
4092
4093 proc do_gitk {revs} {
4094         global env ui_status_value starting_gitk_msg
4095
4096         # -- Always start gitk through whatever we were loaded with.  This
4097         #    lets us bypass using shell process on Windows systems.
4098         #
4099         set cmd [info nameofexecutable]
4100         lappend cmd [gitexec gitk]
4101         if {$revs ne {}} {
4102                 append cmd { }
4103                 append cmd $revs
4104         }
4105
4106         if {[catch {eval exec $cmd &} err]} {
4107                 error_popup "Failed to start gitk:\n\n$err"
4108         } else {
4109                 set ui_status_value $starting_gitk_msg
4110                 after 10000 {
4111                         if {$ui_status_value eq $starting_gitk_msg} {
4112                                 set ui_status_value {Ready.}
4113                         }
4114                 }
4115         }
4116 }
4117
4118 proc do_stats {} {
4119         set fd [open "| git count-objects -v" r]
4120         while {[gets $fd line] > 0} {
4121                 if {[regexp {^([^:]+): (\d+)$} $line _ name value]} {
4122                         set stats($name) $value
4123                 }
4124         }
4125         close $fd
4126
4127         set packed_sz 0
4128         foreach p [glob -directory [gitdir objects pack] \
4129                 -type f \
4130                 -nocomplain -- *] {
4131                 incr packed_sz [file size $p]
4132         }
4133         if {$packed_sz > 0} {
4134                 set stats(size-pack) [expr {$packed_sz / 1024}]
4135         }
4136
4137         set w .stats_view
4138         toplevel $w
4139         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4140
4141         label $w.header -text {Database Statistics} \
4142                 -font font_uibold
4143         pack $w.header -side top -fill x
4144
4145         frame $w.buttons -border 1
4146         button $w.buttons.close -text Close \
4147                 -font font_ui \
4148                 -command [list destroy $w]
4149         button $w.buttons.gc -text {Compress Database} \
4150                 -font font_ui \
4151                 -command "destroy $w;do_gc"
4152         pack $w.buttons.close -side right
4153         pack $w.buttons.gc -side left
4154         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4155
4156         frame $w.stat -borderwidth 1 -relief solid
4157         foreach s {
4158                 {count           {Number of loose objects}}
4159                 {size            {Disk space used by loose objects} { KiB}}
4160                 {in-pack         {Number of packed objects}}
4161                 {packs           {Number of packs}}
4162                 {size-pack       {Disk space used by packed objects} { KiB}}
4163                 {prune-packable  {Packed objects waiting for pruning}}
4164                 {garbage         {Garbage files}}
4165                 } {
4166                 set name [lindex $s 0]
4167                 set label [lindex $s 1]
4168                 if {[catch {set value $stats($name)}]} continue
4169                 if {[llength $s] > 2} {
4170                         set value "$value[lindex $s 2]"
4171                 }
4172
4173                 label $w.stat.l_$name -text "$label:" -anchor w -font font_ui
4174                 label $w.stat.v_$name -text $value -anchor w -font font_ui
4175                 grid $w.stat.l_$name $w.stat.v_$name -sticky we -padx {0 5}
4176         }
4177         pack $w.stat -pady 10 -padx 10
4178
4179         bind $w <Visibility> "grab $w; focus $w"
4180         bind $w <Key-Escape> [list destroy $w]
4181         bind $w <Key-Return> [list destroy $w]
4182         wm title $w "[appname] ([reponame]): Database Statistics"
4183         tkwait window $w
4184 }
4185
4186 proc do_gc {} {
4187         set w [new_console {gc} {Compressing the object database}]
4188         console_chain {
4189                 {console_exec {git pack-refs --prune}}
4190                 {console_exec {git reflog expire --all}}
4191                 {console_exec {git repack -a -d -l}}
4192                 {console_exec {git rerere gc}}
4193         } $w
4194 }
4195
4196 proc do_fsck_objects {} {
4197         set w [new_console {fsck-objects} \
4198                 {Verifying the object database with fsck-objects}]
4199         set cmd [list git fsck-objects]
4200         lappend cmd --full
4201         lappend cmd --cache
4202         lappend cmd --strict
4203         console_exec $w $cmd console_done
4204 }
4205
4206 set is_quitting 0
4207
4208 proc do_quit {} {
4209         global ui_comm is_quitting repo_config commit_type
4210
4211         if {$is_quitting} return
4212         set is_quitting 1
4213
4214         if {[winfo exists $ui_comm]} {
4215                 # -- Stash our current commit buffer.
4216                 #
4217                 set save [gitdir GITGUI_MSG]
4218                 set msg [string trim [$ui_comm get 0.0 end]]
4219                 regsub -all -line {[ \r\t]+$} $msg {} msg
4220                 if {(![string match amend* $commit_type]
4221                         || [$ui_comm edit modified])
4222                         && $msg ne {}} {
4223                         catch {
4224                                 set fd [open $save w]
4225                                 puts -nonewline $fd $msg
4226                                 close $fd
4227                         }
4228                 } else {
4229                         catch {file delete $save}
4230                 }
4231
4232                 # -- Stash our current window geometry into this repository.
4233                 #
4234                 set cfg_geometry [list]
4235                 lappend cfg_geometry [wm geometry .]
4236                 lappend cfg_geometry [lindex [.vpane sash coord 0] 1]
4237                 lappend cfg_geometry [lindex [.vpane.files sash coord 0] 0]
4238                 if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
4239                         set rc_geometry {}
4240                 }
4241                 if {$cfg_geometry ne $rc_geometry} {
4242                         catch {git config gui.geometry $cfg_geometry}
4243                 }
4244         }
4245
4246         destroy .
4247 }
4248
4249 proc do_rescan {} {
4250         rescan {set ui_status_value {Ready.}}
4251 }
4252
4253 proc unstage_helper {txt paths} {
4254         global file_states current_diff_path
4255
4256         if {![lock_index begin-update]} return
4257
4258         set pathList [list]
4259         set after {}
4260         foreach path $paths {
4261                 switch -glob -- [lindex $file_states($path) 0] {
4262                 A? -
4263                 M? -
4264                 D? {
4265                         lappend pathList $path
4266                         if {$path eq $current_diff_path} {
4267                                 set after {reshow_diff;}
4268                         }
4269                 }
4270                 }
4271         }
4272         if {$pathList eq {}} {
4273                 unlock_index
4274         } else {
4275                 update_indexinfo \
4276                         $txt \
4277                         $pathList \
4278                         [concat $after {set ui_status_value {Ready.}}]
4279         }
4280 }
4281
4282 proc do_unstage_selection {} {
4283         global current_diff_path selected_paths
4284
4285         if {[array size selected_paths] > 0} {
4286                 unstage_helper \
4287                         {Unstaging selected files from commit} \
4288                         [array names selected_paths]
4289         } elseif {$current_diff_path ne {}} {
4290                 unstage_helper \
4291                         "Unstaging [short_path $current_diff_path] from commit" \
4292                         [list $current_diff_path]
4293         }
4294 }
4295
4296 proc add_helper {txt paths} {
4297         global file_states current_diff_path
4298
4299         if {![lock_index begin-update]} return
4300
4301         set pathList [list]
4302         set after {}
4303         foreach path $paths {
4304                 switch -glob -- [lindex $file_states($path) 0] {
4305                 _O -
4306                 ?M -
4307                 ?D -
4308                 U? {
4309                         lappend pathList $path
4310                         if {$path eq $current_diff_path} {
4311                                 set after {reshow_diff;}
4312                         }
4313                 }
4314                 }
4315         }
4316         if {$pathList eq {}} {
4317                 unlock_index
4318         } else {
4319                 update_index \
4320                         $txt \
4321                         $pathList \
4322                         [concat $after {set ui_status_value {Ready to commit.}}]
4323         }
4324 }
4325
4326 proc do_add_selection {} {
4327         global current_diff_path selected_paths
4328
4329         if {[array size selected_paths] > 0} {
4330                 add_helper \
4331                         {Adding selected files} \
4332                         [array names selected_paths]
4333         } elseif {$current_diff_path ne {}} {
4334                 add_helper \
4335                         "Adding [short_path $current_diff_path]" \
4336                         [list $current_diff_path]
4337         }
4338 }
4339
4340 proc do_add_all {} {
4341         global file_states
4342
4343         set paths [list]
4344         foreach path [array names file_states] {
4345                 switch -glob -- [lindex $file_states($path) 0] {
4346                 U? {continue}
4347                 ?M -
4348                 ?D {lappend paths $path}
4349                 }
4350         }
4351         add_helper {Adding all changed files} $paths
4352 }
4353
4354 proc revert_helper {txt paths} {
4355         global file_states current_diff_path
4356
4357         if {![lock_index begin-update]} return
4358
4359         set pathList [list]
4360         set after {}
4361         foreach path $paths {
4362                 switch -glob -- [lindex $file_states($path) 0] {
4363                 U? {continue}
4364                 ?M -
4365                 ?D {
4366                         lappend pathList $path
4367                         if {$path eq $current_diff_path} {
4368                                 set after {reshow_diff;}
4369                         }
4370                 }
4371                 }
4372         }
4373
4374         set n [llength $pathList]
4375         if {$n == 0} {
4376                 unlock_index
4377                 return
4378         } elseif {$n == 1} {
4379                 set s "[short_path [lindex $pathList]]"
4380         } else {
4381                 set s "these $n files"
4382         }
4383
4384         set reply [tk_dialog \
4385                 .confirm_revert \
4386                 "[appname] ([reponame])" \
4387                 "Revert changes in $s?
4388
4389 Any unadded changes will be permanently lost by the revert." \
4390                 question \
4391                 1 \
4392                 {Do Nothing} \
4393                 {Revert Changes} \
4394                 ]
4395         if {$reply == 1} {
4396                 checkout_index \
4397                         $txt \
4398                         $pathList \
4399                         [concat $after {set ui_status_value {Ready.}}]
4400         } else {
4401                 unlock_index
4402         }
4403 }
4404
4405 proc do_revert_selection {} {
4406         global current_diff_path selected_paths
4407
4408         if {[array size selected_paths] > 0} {
4409                 revert_helper \
4410                         {Reverting selected files} \
4411                         [array names selected_paths]
4412         } elseif {$current_diff_path ne {}} {
4413                 revert_helper \
4414                         "Reverting [short_path $current_diff_path]" \
4415                         [list $current_diff_path]
4416         }
4417 }
4418
4419 proc do_signoff {} {
4420         global ui_comm
4421
4422         set me [committer_ident]
4423         if {$me eq {}} return
4424
4425         set sob "Signed-off-by: $me"
4426         set last [$ui_comm get {end -1c linestart} {end -1c}]
4427         if {$last ne $sob} {
4428                 $ui_comm edit separator
4429                 if {$last ne {}
4430                         && ![regexp {^[A-Z][A-Za-z]*-[A-Za-z-]+: *} $last]} {
4431                         $ui_comm insert end "\n"
4432                 }
4433                 $ui_comm insert end "\n$sob"
4434                 $ui_comm edit separator
4435                 $ui_comm see end
4436         }
4437 }
4438
4439 proc do_select_commit_type {} {
4440         global commit_type selected_commit_type
4441
4442         if {$selected_commit_type eq {new}
4443                 && [string match amend* $commit_type]} {
4444                 create_new_commit
4445         } elseif {$selected_commit_type eq {amend}
4446                 && ![string match amend* $commit_type]} {
4447                 load_last_commit
4448
4449                 # The amend request was rejected...
4450                 #
4451                 if {![string match amend* $commit_type]} {
4452                         set selected_commit_type new
4453                 }
4454         }
4455 }
4456
4457 proc do_commit {} {
4458         commit_tree
4459 }
4460
4461 proc do_about {} {
4462         global appvers copyright
4463         global tcl_patchLevel tk_patchLevel
4464
4465         set w .about_dialog
4466         toplevel $w
4467         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4468
4469         label $w.header -text "About [appname]" \
4470                 -font font_uibold
4471         pack $w.header -side top -fill x
4472
4473         frame $w.buttons
4474         button $w.buttons.close -text {Close} \
4475                 -font font_ui \
4476                 -command [list destroy $w]
4477         pack $w.buttons.close -side right
4478         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4479
4480         label $w.desc \
4481                 -text "git-gui - a commit creation tool for Git.
4482 $copyright" \
4483                 -padx 5 -pady 5 \
4484                 -justify left \
4485                 -anchor w \
4486                 -borderwidth 1 \
4487                 -relief solid \
4488                 -font font_ui
4489         pack $w.desc -side top -fill x -padx 5 -pady 5
4490
4491         set v {}
4492         append v "git-gui version $appvers\n"
4493         append v "[git version]\n"
4494         append v "\n"
4495         if {$tcl_patchLevel eq $tk_patchLevel} {
4496                 append v "Tcl/Tk version $tcl_patchLevel"
4497         } else {
4498                 append v "Tcl version $tcl_patchLevel"
4499                 append v ", Tk version $tk_patchLevel"
4500         }
4501
4502         label $w.vers \
4503                 -text $v \
4504                 -padx 5 -pady 5 \
4505                 -justify left \
4506                 -anchor w \
4507                 -borderwidth 1 \
4508                 -relief solid \
4509                 -font font_ui
4510         pack $w.vers -side top -fill x -padx 5 -pady 5
4511
4512         menu $w.ctxm -tearoff 0
4513         $w.ctxm add command \
4514                 -label {Copy} \
4515                 -font font_ui \
4516                 -command "
4517                 clipboard clear
4518                 clipboard append -format STRING -type STRING -- \[$w.vers cget -text\]
4519         "
4520
4521         bind $w <Visibility> "grab $w; focus $w"
4522         bind $w <Key-Escape> "destroy $w"
4523         bind_button3 $w.vers "tk_popup $w.ctxm %X %Y; grab $w; focus $w"
4524         wm title $w "About [appname]"
4525         tkwait window $w
4526 }
4527
4528 proc do_options {} {
4529         global repo_config global_config font_descs
4530         global repo_config_new global_config_new
4531
4532         array unset repo_config_new
4533         array unset global_config_new
4534         foreach name [array names repo_config] {
4535                 set repo_config_new($name) $repo_config($name)
4536         }
4537         load_config 1
4538         foreach name [array names repo_config] {
4539                 switch -- $name {
4540                 gui.diffcontext {continue}
4541                 }
4542                 set repo_config_new($name) $repo_config($name)
4543         }
4544         foreach name [array names global_config] {
4545                 set global_config_new($name) $global_config($name)
4546         }
4547
4548         set w .options_editor
4549         toplevel $w
4550         wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
4551
4552         label $w.header -text "Options" \
4553                 -font font_uibold
4554         pack $w.header -side top -fill x
4555
4556         frame $w.buttons
4557         button $w.buttons.restore -text {Restore Defaults} \
4558                 -font font_ui \
4559                 -command do_restore_defaults
4560         pack $w.buttons.restore -side left
4561         button $w.buttons.save -text Save \
4562                 -font font_ui \
4563                 -command [list do_save_config $w]
4564         pack $w.buttons.save -side right
4565         button $w.buttons.cancel -text {Cancel} \
4566                 -font font_ui \
4567                 -command [list destroy $w]
4568         pack $w.buttons.cancel -side right -padx 5
4569         pack $w.buttons -side bottom -fill x -pady 10 -padx 10
4570
4571         labelframe $w.repo -text "[reponame] Repository" \
4572                 -font font_ui
4573         labelframe $w.global -text {Global (All Repositories)} \
4574                 -font font_ui
4575         pack $w.repo -side left -fill both -expand 1 -pady 5 -padx 5
4576         pack $w.global -side right -fill both -expand 1 -pady 5 -padx 5
4577
4578         set optid 0
4579         foreach option {
4580                 {t user.name {User Name}}
4581                 {t user.email {Email Address}}
4582
4583                 {b merge.summary {Summarize Merge Commits}}
4584                 {i-1..5 merge.verbosity {Merge Verbosity}}
4585
4586                 {b gui.trustmtime  {Trust File Modification Timestamps}}
4587                 {i-1..99 gui.diffcontext {Number of Diff Context Lines}}
4588                 {t gui.newbranchtemplate {New Branch Name Template}}
4589                 } {
4590                 set type [lindex $option 0]
4591                 set name [lindex $option 1]
4592                 set text [lindex $option 2]
4593                 incr optid
4594                 foreach f {repo global} {
4595                         switch -glob -- $type {
4596                         b {
4597                                 checkbutton $w.$f.$optid -text $text \
4598                                         -variable ${f}_config_new($name) \
4599                                         -onvalue true \
4600                                         -offvalue false \
4601                                         -font font_ui
4602                                 pack $w.$f.$optid -side top -anchor w
4603                         }
4604                         i-* {
4605                                 regexp -- {-(\d+)\.\.(\d+)$} $type _junk min max
4606                                 frame $w.$f.$optid
4607                                 label $w.$f.$optid.l -text "$text:" -font font_ui
4608                                 pack $w.$f.$optid.l -side left -anchor w -fill x
4609                                 spinbox $w.$f.$optid.v \
4610                                         -textvariable ${f}_config_new($name) \
4611                                         -from $min \
4612                                         -to $max \
4613                                         -increment 1 \
4614                                         -width [expr {1 + [string length $max]}] \
4615                                         -font font_ui
4616                                 bind $w.$f.$optid.v <FocusIn> {%W selection range 0 end}
4617                                 pack $w.$f.$optid.v -side right -anchor e -padx 5
4618                                 pack $w.$f.$optid -side top -anchor w -fill x
4619                         }
4620                         t {
4621                                 frame $w.$f.$optid
4622                                 label $w.$f.$optid.l -text "$text:" -font font_ui
4623                                 entry $w.$f.$optid.v \
4624                                         -borderwidth 1 \
4625                                         -relief sunken \
4626                                         -width 20 \
4627                                         -textvariable ${f}_config_new($name) \
4628                                         -font font_ui
4629                                 pack $w.$f.$optid.l -side left -anchor w
4630                                 pack $w.$f.$optid.v -side left -anchor w \
4631                                         -fill x -expand 1 \
4632                                         -padx 5
4633                                 pack $w.$f.$optid -side top -anchor w -fill x
4634                         }
4635                         }
4636                 }
4637         }
4638
4639         set all_fonts [lsort [font families]]
4640         foreach option $font_descs {
4641                 set name [lindex $option 0]
4642                 set font [lindex $option 1]
4643                 set text [lindex $option 2]
4644
4645                 set global_config_new(gui.$font^^family) \
4646                         [font configure $font -family]
4647                 set global_config_new(gui.$font^^size) \
4648                         [font configure $font -size]
4649
4650                 frame $w.global.$name
4651                 label $w.global.$name.l -text "$text:" -font font_ui
4652                 pack $w.global.$name.l -side left -anchor w -fill x
4653                 eval tk_optionMenu $w.global.$name.family \
4654                         global_config_new(gui.$font^^family) \
4655                         $all_fonts
4656                 spinbox $w.global.$name.size \
4657                         -textvariable global_config_new(gui.$font^^size) \
4658                         -from 2 -to 80 -increment 1 \
4659                         -width 3 \
4660                         -font font_ui
4661                 bind $w.global.$name.size <FocusIn> {%W selection range 0 end}
4662                 pack $w.global.$name.size -side right -anchor e
4663                 pack $w.global.$name.family -side right -anchor e
4664                 pack $w.global.$name -side top -anchor w -fill x
4665         }
4666
4667         bind $w <Visibility> "grab $w; focus $w"
4668         bind $w <Key-Escape> "destroy $w"
4669         wm title $w "[appname] ([reponame]): Options"
4670         tkwait window $w
4671 }
4672
4673 proc do_restore_defaults {} {
4674         global font_descs default_config repo_config
4675         global repo_config_new global_config_new
4676
4677         foreach name [array names default_config] {
4678                 set repo_config_new($name) $default_config($name)
4679                 set global_config_new($name) $default_config($name)
4680         }
4681
4682         foreach option $font_descs {
4683                 set name [lindex $option 0]
4684                 set repo_config(gui.$name) $default_config(gui.$name)
4685         }
4686         apply_config
4687
4688         foreach option $font_descs {
4689                 set name [lindex $option 0]
4690                 set font [lindex $option 1]
4691                 set global_config_new(gui.$font^^family) \
4692                         [font configure $font -family]
4693                 set global_config_new(gui.$font^^size) \
4694                         [font configure $font -size]
4695         }
4696 }
4697
4698 proc do_save_config {w} {
4699         if {[catch {save_config} err]} {
4700                 error_popup "Failed to completely save options:\n\n$err"
4701         }
4702         reshow_diff
4703         destroy $w
4704 }
4705
4706 proc do_windows_shortcut {} {
4707         global argv0
4708
4709         set fn [tk_getSaveFile \
4710                 -parent . \
4711                 -title "[appname] ([reponame]): Create Desktop Icon" \
4712                 -initialfile "Git [reponame].bat"]
4713         if {$fn != {}} {
4714                 if {[catch {
4715                                 set fd [open $fn w]
4716                                 puts $fd "@ECHO Entering [reponame]"
4717                                 puts $fd "@ECHO Starting git-gui... please wait..."
4718                                 puts $fd "@SET PATH=[file normalize [gitexec]];%PATH%"
4719                                 puts $fd "@SET GIT_DIR=[file normalize [gitdir]]"
4720                                 puts -nonewline $fd "@\"[info nameofexecutable]\""
4721                                 puts $fd " \"[file normalize $argv0]\""
4722                                 close $fd
4723                         } err]} {
4724                         error_popup "Cannot write script:\n\n$err"
4725                 }
4726         }
4727 }
4728
4729 proc do_cygwin_shortcut {} {
4730         global argv0
4731
4732         if {[catch {
4733                 set desktop [exec cygpath \
4734                         --windows \
4735                         --absolute \
4736                         --long-name \
4737                         --desktop]
4738                 }]} {
4739                         set desktop .
4740         }
4741         set fn [tk_getSaveFile \
4742                 -parent . \
4743                 -title "[appname] ([reponame]): Create Desktop Icon" \
4744                 -initialdir $desktop \
4745                 -initialfile "Git [reponame].bat"]
4746         if {$fn != {}} {
4747                 if {[catch {
4748                                 set fd [open $fn w]
4749                                 set sh [exec cygpath \
4750                                         --windows \
4751                                         --absolute \
4752                                         /bin/sh]
4753                                 set me [exec cygpath \
4754                                         --unix \
4755                                         --absolute \
4756                                         $argv0]
4757                                 set gd [exec cygpath \
4758                                         --unix \
4759                                         --absolute \
4760                                         [gitdir]]
4761                                 set gw [exec cygpath \
4762                                         --windows \
4763                                         --absolute \
4764                                         [file dirname [gitdir]]]
4765                                 regsub -all ' $me "'\\''" me
4766                                 regsub -all ' $gd "'\\''" gd
4767                                 puts $fd "@ECHO Entering $gw"
4768                                 puts $fd "@ECHO Starting git-gui... please wait..."
4769                                 puts -nonewline $fd "@\"$sh\" --login -c \""
4770                                 puts -nonewline $fd "GIT_DIR='$gd'"
4771                                 puts -nonewline $fd " '$me'"
4772                                 puts $fd "&\""
4773                                 close $fd
4774                         } err]} {
4775                         error_popup "Cannot write script:\n\n$err"
4776                 }
4777         }
4778 }
4779
4780 proc do_macosx_app {} {
4781         global argv0 env
4782
4783         set fn [tk_getSaveFile \
4784                 -parent . \
4785                 -title "[appname] ([reponame]): Create Desktop Icon" \
4786                 -initialdir [file join $env(HOME) Desktop] \
4787                 -initialfile "Git [reponame].app"]
4788         if {$fn != {}} {
4789                 if {[catch {
4790                                 set Contents [file join $fn Contents]
4791                                 set MacOS [file join $Contents MacOS]
4792                                 set exe [file join $MacOS git-gui]
4793
4794                                 file mkdir $MacOS
4795
4796                                 set fd [open [file join $Contents Info.plist] w]
4797                                 puts $fd {<?xml version="1.0" encoding="UTF-8"?>
4798 <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4799 <plist version="1.0">
4800 <dict>
4801         <key>CFBundleDevelopmentRegion</key>
4802         <string>English</string>
4803         <key>CFBundleExecutable</key>
4804         <string>git-gui</string>
4805         <key>CFBundleIdentifier</key>
4806         <string>org.spearce.git-gui</string>
4807         <key>CFBundleInfoDictionaryVersion</key>
4808         <string>6.0</string>
4809         <key>CFBundlePackageType</key>
4810         <string>APPL</string>
4811         <key>CFBundleSignature</key>
4812         <string>????</string>
4813         <key>CFBundleVersion</key>
4814         <string>1.0</string>
4815         <key>NSPrincipalClass</key>
4816         <string>NSApplication</string>
4817 </dict>
4818 </plist>}
4819                                 close $fd
4820
4821                                 set fd [open $exe w]
4822                                 set gd [file normalize [gitdir]]
4823                                 set ep [file normalize [gitexec]]
4824                                 regsub -all ' $gd "'\\''" gd
4825                                 regsub -all ' $ep "'\\''" ep
4826                                 puts $fd "#!/bin/sh"
4827                                 foreach name [array names env] {
4828                                         if {[string match GIT_* $name]} {
4829                                                 regsub -all ' $env($name) "'\\''" v
4830                                                 puts $fd "export $name='$v'"
4831                                         }
4832                                 }
4833                                 puts $fd "export PATH='$ep':\$PATH"
4834                                 puts $fd "export GIT_DIR='$gd'"
4835                                 puts $fd "exec [file normalize $argv0]"
4836                                 close $fd
4837
4838                                 file attributes $exe -permissions u+x,g+x,o+x
4839                         } err]} {
4840                         error_popup "Cannot write icon:\n\n$err"
4841                 }
4842         }
4843 }
4844
4845 proc toggle_or_diff {w x y} {
4846         global file_states file_lists current_diff_path ui_index ui_workdir
4847         global last_clicked selected_paths
4848
4849         set pos [split [$w index @$x,$y] .]
4850         set lno [lindex $pos 0]
4851         set col [lindex $pos 1]
4852         set path [lindex $file_lists($w) [expr {$lno - 1}]]
4853         if {$path eq {}} {
4854                 set last_clicked {}
4855                 return
4856         }
4857
4858         set last_clicked [list $w $lno]
4859         array unset selected_paths
4860         $ui_index tag remove in_sel 0.0 end
4861         $ui_workdir tag remove in_sel 0.0 end
4862
4863         if {$col == 0} {
4864                 if {$current_diff_path eq $path} {
4865                         set after {reshow_diff;}
4866                 } else {
4867                         set after {}
4868                 }
4869                 if {$w eq $ui_index} {
4870                         update_indexinfo \
4871                                 "Unstaging [short_path $path] from commit" \
4872                                 [list $path] \
4873                                 [concat $after {set ui_status_value {Ready.}}]
4874                 } elseif {$w eq $ui_workdir} {
4875                         update_index \
4876                                 "Adding [short_path $path]" \
4877                                 [list $path] \
4878                                 [concat $after {set ui_status_value {Ready.}}]
4879                 }
4880         } else {
4881                 show_diff $path $w $lno
4882         }
4883 }
4884
4885 proc add_one_to_selection {w x y} {
4886         global file_lists last_clicked selected_paths
4887
4888         set lno [lindex [split [$w index @$x,$y] .] 0]
4889         set path [lindex $file_lists($w) [expr {$lno - 1}]]
4890         if {$path eq {}} {
4891                 set last_clicked {}
4892                 return
4893         }
4894
4895         if {$last_clicked ne {}
4896                 && [lindex $last_clicked 0] ne $w} {
4897                 array unset selected_paths
4898                 [lindex $last_clicked 0] tag remove in_sel 0.0 end
4899         }
4900
4901         set last_clicked [list $w $lno]
4902         if {[catch {set in_sel $selected_paths($path)}]} {
4903                 set in_sel 0
4904         }
4905         if {$in_sel} {
4906                 unset selected_paths($path)
4907                 $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
4908         } else {
4909                 set selected_paths($path) 1
4910                 $w tag add in_sel $lno.0 [expr {$lno + 1}].0
4911         }
4912 }
4913
4914 proc add_range_to_selection {w x y} {
4915         global file_lists last_clicked selected_paths
4916
4917         if {[lindex $last_clicked 0] ne $w} {
4918                 toggle_or_diff $w $x $y
4919                 return
4920         }
4921
4922         set lno [lindex [split [$w index @$x,$y] .] 0]
4923         set lc [lindex $last_clicked 1]
4924         if {$lc < $lno} {
4925                 set begin $lc
4926                 set end $lno
4927         } else {
4928                 set begin $lno
4929                 set end $lc
4930         }
4931
4932         foreach path [lrange $file_lists($w) \
4933                 [expr {$begin - 1}] \
4934                 [expr {$end - 1}]] {
4935                 set selected_paths($path) 1
4936         }
4937         $w tag add in_sel $begin.0 [expr {$end + 1}].0
4938 }
4939
4940 ######################################################################
4941 ##
4942 ## config defaults
4943
4944 set cursor_ptr arrow
4945 font create font_diff -family Courier -size 10
4946 font create font_ui
4947 catch {
4948         label .dummy
4949         eval font configure font_ui [font actual [.dummy cget -font]]
4950         destroy .dummy
4951 }
4952
4953 font create font_uibold
4954 font create font_diffbold
4955
4956 if {[is_Windows]} {
4957         set M1B Control
4958         set M1T Ctrl
4959 } elseif {[is_MacOSX]} {
4960         set M1B M1
4961         set M1T Cmd
4962 } else {
4963         set M1B M1
4964         set M1T M1
4965 }
4966
4967 proc apply_config {} {
4968         global repo_config font_descs
4969
4970         foreach option $font_descs {
4971                 set name [lindex $option 0]
4972                 set font [lindex $option 1]
4973                 if {[catch {
4974                         foreach {cn cv} $repo_config(gui.$name) {
4975                                 font configure $font $cn $cv
4976                         }
4977                         } err]} {
4978                         error_popup "Invalid font specified in gui.$name:\n\n$err"
4979                 }
4980                 foreach {cn cv} [font configure $font] {
4981                         font configure ${font}bold $cn $cv
4982                 }
4983                 font configure ${font}bold -weight bold
4984         }
4985 }
4986
4987 set default_config(merge.summary) false
4988 set default_config(merge.verbosity) 2
4989 set default_config(user.name) {}
4990 set default_config(user.email) {}
4991
4992 set default_config(gui.trustmtime) false
4993 set default_config(gui.diffcontext) 5
4994 set default_config(gui.newbranchtemplate) {}
4995 set default_config(gui.fontui) [font configure font_ui]
4996 set default_config(gui.fontdiff) [font configure font_diff]
4997 set font_descs {
4998         {fontui   font_ui   {Main Font}}
4999         {fontdiff font_diff {Diff/Console Font}}
5000 }
5001 load_config 0
5002 apply_config
5003
5004 ######################################################################
5005 ##
5006 ## feature option selection
5007
5008 if {[regexp {^git-(.+)$} [appname] _junk subcommand]} {
5009         unset _junk
5010 } else {
5011         set subcommand gui
5012 }
5013 if {$subcommand eq {gui.sh}} {
5014         set subcommand gui
5015 }
5016 if {$subcommand eq {gui} && [llength $argv] > 0} {
5017         set subcommand [lindex $argv 0]
5018         set argv [lrange $argv 1 end]
5019 }
5020
5021 enable_option multicommit
5022 enable_option branch
5023 enable_option transport
5024
5025 switch -- $subcommand {
5026 --version -
5027 version -
5028 browser -
5029 blame {
5030         disable_option multicommit
5031         disable_option branch
5032         disable_option transport
5033 }
5034 citool {
5035         enable_option singlecommit
5036
5037         disable_option multicommit
5038         disable_option branch
5039         disable_option transport
5040 }
5041 }
5042
5043 ######################################################################
5044 ##
5045 ## ui construction
5046
5047 set ui_comm {}
5048
5049 # -- Menu Bar
5050 #
5051 menu .mbar -tearoff 0
5052 .mbar add cascade -label Repository -menu .mbar.repository
5053 .mbar add cascade -label Edit -menu .mbar.edit
5054 if {[is_enabled branch]} {
5055         .mbar add cascade -label Branch -menu .mbar.branch
5056 }
5057 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
5058         .mbar add cascade -label Commit -menu .mbar.commit
5059 }
5060 if {[is_enabled transport]} {
5061         .mbar add cascade -label Merge -menu .mbar.merge
5062         .mbar add cascade -label Fetch -menu .mbar.fetch
5063         .mbar add cascade -label Push -menu .mbar.push
5064 }
5065 . configure -menu .mbar
5066
5067 # -- Repository Menu
5068 #
5069 menu .mbar.repository
5070
5071 .mbar.repository add command \
5072         -label {Browse Current Branch} \
5073         -command {new_browser $current_branch} \
5074         -font font_ui
5075 trace add variable current_branch write ".mbar.repository entryconf [.mbar.repository index last] -label \"Browse \$current_branch\" ;#"
5076 .mbar.repository add separator
5077
5078 .mbar.repository add command \
5079         -label {Visualize Current Branch} \
5080         -command {do_gitk $current_branch} \
5081         -font font_ui
5082 trace add variable current_branch write ".mbar.repository entryconf [.mbar.repository index last] -label \"Visualize \$current_branch\" ;#"
5083 .mbar.repository add command \
5084         -label {Visualize All Branches} \
5085         -command {do_gitk --all} \
5086         -font font_ui
5087 .mbar.repository add separator
5088
5089 if {[is_enabled multicommit]} {
5090         .mbar.repository add command -label {Database Statistics} \
5091                 -command do_stats \
5092                 -font font_ui
5093
5094         .mbar.repository add command -label {Compress Database} \
5095                 -command do_gc \
5096                 -font font_ui
5097
5098         .mbar.repository add command -label {Verify Database} \
5099                 -command do_fsck_objects \
5100                 -font font_ui
5101
5102         .mbar.repository add separator
5103
5104         if {[is_Cygwin]} {
5105                 .mbar.repository add command \
5106                         -label {Create Desktop Icon} \
5107                         -command do_cygwin_shortcut \
5108                         -font font_ui
5109         } elseif {[is_Windows]} {
5110                 .mbar.repository add command \
5111                         -label {Create Desktop Icon} \
5112                         -command do_windows_shortcut \
5113                         -font font_ui
5114         } elseif {[is_MacOSX]} {
5115                 .mbar.repository add command \
5116                         -label {Create Desktop Icon} \
5117                         -command do_macosx_app \
5118                         -font font_ui
5119         }
5120 }
5121
5122 .mbar.repository add command -label Quit \
5123         -command do_quit \
5124         -accelerator $M1T-Q \
5125         -font font_ui
5126
5127 # -- Edit Menu
5128 #
5129 menu .mbar.edit
5130 .mbar.edit add command -label Undo \
5131         -command {catch {[focus] edit undo}} \
5132         -accelerator $M1T-Z \
5133         -font font_ui
5134 .mbar.edit add command -label Redo \
5135         -command {catch {[focus] edit redo}} \
5136         -accelerator $M1T-Y \
5137         -font font_ui
5138 .mbar.edit add separator
5139 .mbar.edit add command -label Cut \
5140         -command {catch {tk_textCut [focus]}} \
5141         -accelerator $M1T-X \
5142         -font font_ui
5143 .mbar.edit add command -label Copy \
5144         -command {catch {tk_textCopy [focus]}} \
5145         -accelerator $M1T-C \
5146         -font font_ui
5147 .mbar.edit add command -label Paste \
5148         -command {catch {tk_textPaste [focus]; [focus] see insert}} \
5149         -accelerator $M1T-V \
5150         -font font_ui
5151 .mbar.edit add command -label Delete \
5152         -command {catch {[focus] delete sel.first sel.last}} \
5153         -accelerator Del \
5154         -font font_ui
5155 .mbar.edit add separator
5156 .mbar.edit add command -label {Select All} \
5157         -command {catch {[focus] tag add sel 0.0 end}} \
5158         -accelerator $M1T-A \
5159         -font font_ui
5160
5161 # -- Branch Menu
5162 #
5163 if {[is_enabled branch]} {
5164         menu .mbar.branch
5165
5166         .mbar.branch add command -label {Create...} \
5167                 -command do_create_branch \
5168                 -accelerator $M1T-N \
5169                 -font font_ui
5170         lappend disable_on_lock [list .mbar.branch entryconf \
5171                 [.mbar.branch index last] -state]
5172
5173         .mbar.branch add command -label {Delete...} \
5174                 -command do_delete_branch \
5175                 -font font_ui
5176         lappend disable_on_lock [list .mbar.branch entryconf \
5177                 [.mbar.branch index last] -state]
5178 }
5179
5180 # -- Commit Menu
5181 #
5182 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
5183         menu .mbar.commit
5184
5185         .mbar.commit add radiobutton \
5186                 -label {New Commit} \
5187                 -command do_select_commit_type \
5188                 -variable selected_commit_type \
5189                 -value new \
5190                 -font font_ui
5191         lappend disable_on_lock \
5192                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5193
5194         .mbar.commit add radiobutton \
5195                 -label {Amend Last Commit} \
5196                 -command do_select_commit_type \
5197                 -variable selected_commit_type \
5198                 -value amend \
5199                 -font font_ui
5200         lappend disable_on_lock \
5201                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5202
5203         .mbar.commit add separator
5204
5205         .mbar.commit add command -label Rescan \
5206                 -command do_rescan \
5207                 -accelerator F5 \
5208                 -font font_ui
5209         lappend disable_on_lock \
5210                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5211
5212         .mbar.commit add command -label {Add To Commit} \
5213                 -command do_add_selection \
5214                 -font font_ui
5215         lappend disable_on_lock \
5216                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5217
5218         .mbar.commit add command -label {Add Existing To Commit} \
5219                 -command do_add_all \
5220                 -accelerator $M1T-I \
5221                 -font font_ui
5222         lappend disable_on_lock \
5223                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5224
5225         .mbar.commit add command -label {Unstage From Commit} \
5226                 -command do_unstage_selection \
5227                 -font font_ui
5228         lappend disable_on_lock \
5229                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5230
5231         .mbar.commit add command -label {Revert Changes} \
5232                 -command do_revert_selection \
5233                 -font font_ui
5234         lappend disable_on_lock \
5235                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5236
5237         .mbar.commit add separator
5238
5239         .mbar.commit add command -label {Sign Off} \
5240                 -command do_signoff \
5241                 -accelerator $M1T-S \
5242                 -font font_ui
5243
5244         .mbar.commit add command -label Commit \
5245                 -command do_commit \
5246                 -accelerator $M1T-Return \
5247                 -font font_ui
5248         lappend disable_on_lock \
5249                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
5250 }
5251
5252 if {[is_MacOSX]} {
5253         # -- Apple Menu (Mac OS X only)
5254         #
5255         .mbar add cascade -label Apple -menu .mbar.apple
5256         menu .mbar.apple
5257
5258         .mbar.apple add command -label "About [appname]" \
5259                 -command do_about \
5260                 -font font_ui
5261         .mbar.apple add command -label "Options..." \
5262                 -command do_options \
5263                 -font font_ui
5264 } else {
5265         # -- Edit Menu
5266         #
5267         .mbar.edit add separator
5268         .mbar.edit add command -label {Options...} \
5269                 -command do_options \
5270                 -font font_ui
5271
5272         # -- Tools Menu
5273         #
5274         if {[file exists /usr/local/miga/lib/gui-miga]
5275                 && [file exists .pvcsrc]} {
5276         proc do_miga {} {
5277                 global ui_status_value
5278                 if {![lock_index update]} return
5279                 set cmd [list sh --login -c "/usr/local/miga/lib/gui-miga \"[pwd]\""]
5280                 set miga_fd [open "|$cmd" r]
5281                 fconfigure $miga_fd -blocking 0
5282                 fileevent $miga_fd readable [list miga_done $miga_fd]
5283                 set ui_status_value {Running miga...}
5284         }
5285         proc miga_done {fd} {
5286                 read $fd 512
5287                 if {[eof $fd]} {
5288                         close $fd
5289                         unlock_index
5290                         rescan [list set ui_status_value {Ready.}]
5291                 }
5292         }
5293         .mbar add cascade -label Tools -menu .mbar.tools
5294         menu .mbar.tools
5295         .mbar.tools add command -label "Migrate" \
5296                 -command do_miga \
5297                 -font font_ui
5298         lappend disable_on_lock \
5299                 [list .mbar.tools entryconf [.mbar.tools index last] -state]
5300         }
5301 }
5302
5303 # -- Help Menu
5304 #
5305 .mbar add cascade -label Help -menu .mbar.help
5306 menu .mbar.help
5307
5308 if {![is_MacOSX]} {
5309         .mbar.help add command -label "About [appname]" \
5310                 -command do_about \
5311                 -font font_ui
5312 }
5313
5314 set browser {}
5315 catch {set browser $repo_config(instaweb.browser)}
5316 set doc_path [file dirname [gitexec]]
5317 set doc_path [file join $doc_path Documentation index.html]
5318
5319 if {[is_Cygwin]} {
5320         set doc_path [exec cygpath --windows $doc_path]
5321 }
5322
5323 if {$browser eq {}} {
5324         if {[is_MacOSX]} {
5325                 set browser open
5326         } elseif {[is_Cygwin]} {
5327                 set program_files [file dirname [exec cygpath --windir]]
5328                 set program_files [file join $program_files {Program Files}]
5329                 set firefox [file join $program_files {Mozilla Firefox} firefox.exe]
5330                 set ie [file join $program_files {Internet Explorer} IEXPLORE.EXE]
5331                 if {[file exists $firefox]} {
5332                         set browser $firefox
5333                 } elseif {[file exists $ie]} {
5334                         set browser $ie
5335                 }
5336                 unset program_files firefox ie
5337         }
5338 }
5339
5340 if {[file isfile $doc_path]} {
5341         set doc_url "file:$doc_path"
5342 } else {
5343         set doc_url {http://www.kernel.org/pub/software/scm/git/docs/}
5344 }
5345
5346 if {$browser ne {}} {
5347         .mbar.help add command -label {Online Documentation} \
5348                 -command [list exec $browser $doc_url &] \
5349                 -font font_ui
5350 }
5351 unset browser doc_path doc_url
5352
5353 # -- Standard bindings
5354 #
5355 bind .   <Destroy> do_quit
5356 bind all <$M1B-Key-q> do_quit
5357 bind all <$M1B-Key-Q> do_quit
5358 bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
5359 bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
5360
5361 # -- Not a normal commit type invocation?  Do that instead!
5362 #
5363 switch -- $subcommand {
5364 --version -
5365 version {
5366         puts "git-gui version $appvers"
5367         exit
5368 }
5369 browser {
5370         if {[llength $argv] != 1} {
5371                 puts stderr "usage: $argv0 browser commit"
5372                 exit 1
5373         }
5374         set current_branch [lindex $argv 0]
5375         new_browser $current_branch
5376         return
5377 }
5378 blame {
5379         if {[llength $argv] != 2} {
5380                 puts stderr "usage: $argv0 blame commit path"
5381                 exit 1
5382         }
5383         set current_branch [lindex $argv 0]
5384         show_blame $current_branch [lindex $argv 1]
5385         return
5386 }
5387 citool -
5388 gui {
5389         if {[llength $argv] != 0} {
5390                 puts -nonewline stderr "usage: $argv0"
5391                 if {$subcommand ne {gui} && [appname] ne "git-$subcommand"} {
5392                         puts -nonewline stderr " $subcommand"
5393                 }
5394                 puts stderr {}
5395                 exit 1
5396         }
5397         # fall through to setup UI for commits
5398 }
5399 default {
5400         puts stderr "usage: $argv0 \[{blame|citool}\]"
5401         exit 1
5402 }
5403 }
5404
5405 # -- Branch Control
5406 #
5407 frame .branch \
5408         -borderwidth 1 \
5409         -relief sunken
5410 label .branch.l1 \
5411         -text {Current Branch:} \
5412         -anchor w \
5413         -justify left \
5414         -font font_ui
5415 label .branch.cb \
5416         -textvariable current_branch \
5417         -anchor w \
5418         -justify left \
5419         -font font_ui
5420 pack .branch.l1 -side left
5421 pack .branch.cb -side left -fill x
5422 pack .branch -side top -fill x
5423
5424 if {[is_enabled branch]} {
5425         menu .mbar.merge
5426         .mbar.merge add command -label {Local Merge...} \
5427                 -command do_local_merge \
5428                 -font font_ui
5429         lappend disable_on_lock \
5430                 [list .mbar.merge entryconf [.mbar.merge index last] -state]
5431         .mbar.merge add command -label {Abort Merge...} \
5432                 -command do_reset_hard \
5433                 -font font_ui
5434         lappend disable_on_lock \
5435                 [list .mbar.merge entryconf [.mbar.merge index last] -state]
5436
5437
5438         menu .mbar.fetch
5439
5440         menu .mbar.push
5441         .mbar.push add command -label {Push...} \
5442                 -command do_push_anywhere \
5443                 -font font_ui
5444 }
5445
5446 # -- Main Window Layout
5447 #
5448 panedwindow .vpane -orient vertical
5449 panedwindow .vpane.files -orient horizontal
5450 .vpane add .vpane.files -sticky nsew -height 100 -width 200
5451 pack .vpane -anchor n -side top -fill both -expand 1
5452
5453 # -- Index File List
5454 #
5455 frame .vpane.files.index -height 100 -width 200
5456 label .vpane.files.index.title -text {Changes To Be Committed} \
5457         -background green \
5458         -font font_ui
5459 text $ui_index -background white -borderwidth 0 \
5460         -width 20 -height 10 \
5461         -wrap none \
5462         -font font_ui \
5463         -cursor $cursor_ptr \
5464         -xscrollcommand {.vpane.files.index.sx set} \
5465         -yscrollcommand {.vpane.files.index.sy set} \
5466         -state disabled
5467 scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
5468 scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
5469 pack .vpane.files.index.title -side top -fill x
5470 pack .vpane.files.index.sx -side bottom -fill x
5471 pack .vpane.files.index.sy -side right -fill y
5472 pack $ui_index -side left -fill both -expand 1
5473 .vpane.files add .vpane.files.index -sticky nsew
5474
5475 # -- Working Directory File List
5476 #
5477 frame .vpane.files.workdir -height 100 -width 200
5478 label .vpane.files.workdir.title -text {Changed But Not Updated} \
5479         -background red \
5480         -font font_ui
5481 text $ui_workdir -background white -borderwidth 0 \
5482         -width 20 -height 10 \
5483         -wrap none \
5484         -font font_ui \
5485         -cursor $cursor_ptr \
5486         -xscrollcommand {.vpane.files.workdir.sx set} \
5487         -yscrollcommand {.vpane.files.workdir.sy set} \
5488         -state disabled
5489 scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
5490 scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
5491 pack .vpane.files.workdir.title -side top -fill x
5492 pack .vpane.files.workdir.sx -side bottom -fill x
5493 pack .vpane.files.workdir.sy -side right -fill y
5494 pack $ui_workdir -side left -fill both -expand 1
5495 .vpane.files add .vpane.files.workdir -sticky nsew
5496
5497 foreach i [list $ui_index $ui_workdir] {
5498         $i tag conf in_diff -font font_uibold
5499         $i tag conf in_sel \
5500                 -background [$i cget -foreground] \
5501                 -foreground [$i cget -background]
5502 }
5503 unset i
5504
5505 # -- Diff and Commit Area
5506 #
5507 frame .vpane.lower -height 300 -width 400
5508 frame .vpane.lower.commarea
5509 frame .vpane.lower.diff -relief sunken -borderwidth 1
5510 pack .vpane.lower.commarea -side top -fill x
5511 pack .vpane.lower.diff -side bottom -fill both -expand 1
5512 .vpane add .vpane.lower -sticky nsew
5513
5514 # -- Commit Area Buttons
5515 #
5516 frame .vpane.lower.commarea.buttons
5517 label .vpane.lower.commarea.buttons.l -text {} \
5518         -anchor w \
5519         -justify left \
5520         -font font_ui
5521 pack .vpane.lower.commarea.buttons.l -side top -fill x
5522 pack .vpane.lower.commarea.buttons -side left -fill y
5523
5524 button .vpane.lower.commarea.buttons.rescan -text {Rescan} \
5525         -command do_rescan \
5526         -font font_ui
5527 pack .vpane.lower.commarea.buttons.rescan -side top -fill x
5528 lappend disable_on_lock \
5529         {.vpane.lower.commarea.buttons.rescan conf -state}
5530
5531 button .vpane.lower.commarea.buttons.incall -text {Add Existing} \
5532         -command do_add_all \
5533         -font font_ui
5534 pack .vpane.lower.commarea.buttons.incall -side top -fill x
5535 lappend disable_on_lock \
5536         {.vpane.lower.commarea.buttons.incall conf -state}
5537
5538 button .vpane.lower.commarea.buttons.signoff -text {Sign Off} \
5539         -command do_signoff \
5540         -font font_ui
5541 pack .vpane.lower.commarea.buttons.signoff -side top -fill x
5542
5543 button .vpane.lower.commarea.buttons.commit -text {Commit} \
5544         -command do_commit \
5545         -font font_ui
5546 pack .vpane.lower.commarea.buttons.commit -side top -fill x
5547 lappend disable_on_lock \
5548         {.vpane.lower.commarea.buttons.commit conf -state}
5549
5550 # -- Commit Message Buffer
5551 #
5552 frame .vpane.lower.commarea.buffer
5553 frame .vpane.lower.commarea.buffer.header
5554 set ui_comm .vpane.lower.commarea.buffer.t
5555 set ui_coml .vpane.lower.commarea.buffer.header.l
5556 radiobutton .vpane.lower.commarea.buffer.header.new \
5557         -text {New Commit} \
5558         -command do_select_commit_type \
5559         -variable selected_commit_type \
5560         -value new \
5561         -font font_ui
5562 lappend disable_on_lock \
5563         [list .vpane.lower.commarea.buffer.header.new conf -state]
5564 radiobutton .vpane.lower.commarea.buffer.header.amend \
5565         -text {Amend Last Commit} \
5566         -command do_select_commit_type \
5567         -variable selected_commit_type \
5568         -value amend \
5569         -font font_ui
5570 lappend disable_on_lock \
5571         [list .vpane.lower.commarea.buffer.header.amend conf -state]
5572 label $ui_coml \
5573         -anchor w \
5574         -justify left \
5575         -font font_ui
5576 proc trace_commit_type {varname args} {
5577         global ui_coml commit_type
5578         switch -glob -- $commit_type {
5579         initial       {set txt {Initial Commit Message:}}
5580         amend         {set txt {Amended Commit Message:}}
5581         amend-initial {set txt {Amended Initial Commit Message:}}
5582         amend-merge   {set txt {Amended Merge Commit Message:}}
5583         merge         {set txt {Merge Commit Message:}}
5584         *             {set txt {Commit Message:}}
5585         }
5586         $ui_coml conf -text $txt
5587 }
5588 trace add variable commit_type write trace_commit_type
5589 pack $ui_coml -side left -fill x
5590 pack .vpane.lower.commarea.buffer.header.amend -side right
5591 pack .vpane.lower.commarea.buffer.header.new -side right
5592
5593 text $ui_comm -background white -borderwidth 1 \
5594         -undo true \
5595         -maxundo 20 \
5596         -autoseparators true \
5597         -relief sunken \
5598         -width 75 -height 9 -wrap none \
5599         -font font_diff \
5600         -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
5601 scrollbar .vpane.lower.commarea.buffer.sby \
5602         -command [list $ui_comm yview]
5603 pack .vpane.lower.commarea.buffer.header -side top -fill x
5604 pack .vpane.lower.commarea.buffer.sby -side right -fill y
5605 pack $ui_comm -side left -fill y
5606 pack .vpane.lower.commarea.buffer -side left -fill y
5607
5608 # -- Commit Message Buffer Context Menu
5609 #
5610 set ctxm .vpane.lower.commarea.buffer.ctxm
5611 menu $ctxm -tearoff 0
5612 $ctxm add command \
5613         -label {Cut} \
5614         -font font_ui \
5615         -command {tk_textCut $ui_comm}
5616 $ctxm add command \
5617         -label {Copy} \
5618         -font font_ui \
5619         -command {tk_textCopy $ui_comm}
5620 $ctxm add command \
5621         -label {Paste} \
5622         -font font_ui \
5623         -command {tk_textPaste $ui_comm}
5624 $ctxm add command \
5625         -label {Delete} \
5626         -font font_ui \
5627         -command {$ui_comm delete sel.first sel.last}
5628 $ctxm add separator
5629 $ctxm add command \
5630         -label {Select All} \
5631         -font font_ui \
5632         -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
5633 $ctxm add command \
5634         -label {Copy All} \
5635         -font font_ui \
5636         -command {
5637                 $ui_comm tag add sel 0.0 end
5638                 tk_textCopy $ui_comm
5639                 $ui_comm tag remove sel 0.0 end
5640         }
5641 $ctxm add separator
5642 $ctxm add command \
5643         -label {Sign Off} \
5644         -font font_ui \
5645         -command do_signoff
5646 bind_button3 $ui_comm "tk_popup $ctxm %X %Y"
5647
5648 # -- Diff Header
5649 #
5650 set current_diff_path {}
5651 set current_diff_side {}
5652 set diff_actions [list]
5653 proc trace_current_diff_path {varname args} {
5654         global current_diff_path diff_actions file_states
5655         if {$current_diff_path eq {}} {
5656                 set s {}
5657                 set f {}
5658                 set p {}
5659                 set o disabled
5660         } else {
5661                 set p $current_diff_path
5662                 set s [mapdesc [lindex $file_states($p) 0] $p]
5663                 set f {File:}
5664                 set p [escape_path $p]
5665                 set o normal
5666         }
5667
5668         .vpane.lower.diff.header.status configure -text $s
5669         .vpane.lower.diff.header.file configure -text $f
5670         .vpane.lower.diff.header.path configure -text $p
5671         foreach w $diff_actions {
5672                 uplevel #0 $w $o
5673         }
5674 }
5675 trace add variable current_diff_path write trace_current_diff_path
5676
5677 frame .vpane.lower.diff.header -background orange
5678 label .vpane.lower.diff.header.status \
5679         -background orange \
5680         -width $max_status_desc \
5681         -anchor w \
5682         -justify left \
5683         -font font_ui
5684 label .vpane.lower.diff.header.file \
5685         -background orange \
5686         -anchor w \
5687         -justify left \
5688         -font font_ui
5689 label .vpane.lower.diff.header.path \
5690         -background orange \
5691         -anchor w \
5692         -justify left \
5693         -font font_ui
5694 pack .vpane.lower.diff.header.status -side left
5695 pack .vpane.lower.diff.header.file -side left
5696 pack .vpane.lower.diff.header.path -fill x
5697 set ctxm .vpane.lower.diff.header.ctxm
5698 menu $ctxm -tearoff 0
5699 $ctxm add command \
5700         -label {Copy} \
5701         -font font_ui \
5702         -command {
5703                 clipboard clear
5704                 clipboard append \
5705                         -format STRING \
5706                         -type STRING \
5707                         -- $current_diff_path
5708         }
5709 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5710 bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
5711
5712 # -- Diff Body
5713 #
5714 frame .vpane.lower.diff.body
5715 set ui_diff .vpane.lower.diff.body.t
5716 text $ui_diff -background white -borderwidth 0 \
5717         -width 80 -height 15 -wrap none \
5718         -font font_diff \
5719         -xscrollcommand {.vpane.lower.diff.body.sbx set} \
5720         -yscrollcommand {.vpane.lower.diff.body.sby set} \
5721         -state disabled
5722 scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
5723         -command [list $ui_diff xview]
5724 scrollbar .vpane.lower.diff.body.sby -orient vertical \
5725         -command [list $ui_diff yview]
5726 pack .vpane.lower.diff.body.sbx -side bottom -fill x
5727 pack .vpane.lower.diff.body.sby -side right -fill y
5728 pack $ui_diff -side left -fill both -expand 1
5729 pack .vpane.lower.diff.header -side top -fill x
5730 pack .vpane.lower.diff.body -side bottom -fill both -expand 1
5731
5732 $ui_diff tag conf d_cr -elide true
5733 $ui_diff tag conf d_@ -foreground blue -font font_diffbold
5734 $ui_diff tag conf d_+ -foreground {#00a000}
5735 $ui_diff tag conf d_- -foreground red
5736
5737 $ui_diff tag conf d_++ -foreground {#00a000}
5738 $ui_diff tag conf d_-- -foreground red
5739 $ui_diff tag conf d_+s \
5740         -foreground {#00a000} \
5741         -background {#e2effa}
5742 $ui_diff tag conf d_-s \
5743         -foreground red \
5744         -background {#e2effa}
5745 $ui_diff tag conf d_s+ \
5746         -foreground {#00a000} \
5747         -background ivory1
5748 $ui_diff tag conf d_s- \
5749         -foreground red \
5750         -background ivory1
5751
5752 $ui_diff tag conf d<<<<<<< \
5753         -foreground orange \
5754         -font font_diffbold
5755 $ui_diff tag conf d======= \
5756         -foreground orange \
5757         -font font_diffbold
5758 $ui_diff tag conf d>>>>>>> \
5759         -foreground orange \
5760         -font font_diffbold
5761
5762 $ui_diff tag raise sel
5763
5764 # -- Diff Body Context Menu
5765 #
5766 set ctxm .vpane.lower.diff.body.ctxm
5767 menu $ctxm -tearoff 0
5768 $ctxm add command \
5769         -label {Refresh} \
5770         -font font_ui \
5771         -command reshow_diff
5772 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5773 $ctxm add command \
5774         -label {Copy} \
5775         -font font_ui \
5776         -command {tk_textCopy $ui_diff}
5777 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5778 $ctxm add command \
5779         -label {Select All} \
5780         -font font_ui \
5781         -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
5782 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5783 $ctxm add command \
5784         -label {Copy All} \
5785         -font font_ui \
5786         -command {
5787                 $ui_diff tag add sel 0.0 end
5788                 tk_textCopy $ui_diff
5789                 $ui_diff tag remove sel 0.0 end
5790         }
5791 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5792 $ctxm add separator
5793 $ctxm add command \
5794         -label {Apply/Reverse Hunk} \
5795         -font font_ui \
5796         -command {apply_hunk $cursorX $cursorY}
5797 set ui_diff_applyhunk [$ctxm index last]
5798 lappend diff_actions [list $ctxm entryconf $ui_diff_applyhunk -state]
5799 $ctxm add separator
5800 $ctxm add command \
5801         -label {Decrease Font Size} \
5802         -font font_ui \
5803         -command {incr_font_size font_diff -1}
5804 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5805 $ctxm add command \
5806         -label {Increase Font Size} \
5807         -font font_ui \
5808         -command {incr_font_size font_diff 1}
5809 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5810 $ctxm add separator
5811 $ctxm add command \
5812         -label {Show Less Context} \
5813         -font font_ui \
5814         -command {if {$repo_config(gui.diffcontext) >= 2} {
5815                 incr repo_config(gui.diffcontext) -1
5816                 reshow_diff
5817         }}
5818 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5819 $ctxm add command \
5820         -label {Show More Context} \
5821         -font font_ui \
5822         -command {
5823                 incr repo_config(gui.diffcontext)
5824                 reshow_diff
5825         }
5826 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
5827 $ctxm add separator
5828 $ctxm add command -label {Options...} \
5829         -font font_ui \
5830         -command do_options
5831 bind_button3 $ui_diff "
5832         set cursorX %x
5833         set cursorY %y
5834         if {\$ui_index eq \$current_diff_side} {
5835                 $ctxm entryconf $ui_diff_applyhunk -label {Unstage Hunk From Commit}
5836         } else {
5837                 $ctxm entryconf $ui_diff_applyhunk -label {Stage Hunk For Commit}
5838         }
5839         tk_popup $ctxm %X %Y
5840 "
5841 unset ui_diff_applyhunk
5842
5843 # -- Status Bar
5844 #
5845 set ui_status_value {Initializing...}
5846 label .status -textvariable ui_status_value \
5847         -anchor w \
5848         -justify left \
5849         -borderwidth 1 \
5850         -relief sunken \
5851         -font font_ui
5852 pack .status -anchor w -side bottom -fill x
5853
5854 # -- Load geometry
5855 #
5856 catch {
5857 set gm $repo_config(gui.geometry)
5858 wm geometry . [lindex $gm 0]
5859 .vpane sash place 0 \
5860         [lindex [.vpane sash coord 0] 0] \
5861         [lindex $gm 1]
5862 .vpane.files sash place 0 \
5863         [lindex $gm 2] \
5864         [lindex [.vpane.files sash coord 0] 1]
5865 unset gm
5866 }
5867
5868 # -- Key Bindings
5869 #
5870 bind $ui_comm <$M1B-Key-Return> {do_commit;break}
5871 bind $ui_comm <$M1B-Key-i> {do_add_all;break}
5872 bind $ui_comm <$M1B-Key-I> {do_add_all;break}
5873 bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
5874 bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
5875 bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
5876 bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
5877 bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
5878 bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
5879 bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
5880 bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
5881
5882 bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
5883 bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
5884 bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
5885 bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
5886 bind $ui_diff <$M1B-Key-v> {break}
5887 bind $ui_diff <$M1B-Key-V> {break}
5888 bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
5889 bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
5890 bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
5891 bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
5892 bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
5893 bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
5894 bind $ui_diff <Button-1>   {focus %W}
5895
5896 if {[is_enabled branch]} {
5897         bind . <$M1B-Key-n> do_create_branch
5898         bind . <$M1B-Key-N> do_create_branch
5899 }
5900
5901 bind all <Key-F5> do_rescan
5902 bind all <$M1B-Key-r> do_rescan
5903 bind all <$M1B-Key-R> do_rescan
5904 bind .   <$M1B-Key-s> do_signoff
5905 bind .   <$M1B-Key-S> do_signoff
5906 bind .   <$M1B-Key-i> do_add_all
5907 bind .   <$M1B-Key-I> do_add_all
5908 bind .   <$M1B-Key-Return> do_commit
5909 foreach i [list $ui_index $ui_workdir] {
5910         bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
5911         bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
5912         bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
5913 }
5914 unset i
5915
5916 set file_lists($ui_index) [list]
5917 set file_lists($ui_workdir) [list]
5918
5919 set HEAD {}
5920 set PARENT {}
5921 set MERGE_HEAD [list]
5922 set commit_type {}
5923 set empty_tree {}
5924 set current_branch {}
5925 set current_diff_path {}
5926 set selected_commit_type new
5927
5928 wm title . "[appname] ([file normalize [file dirname [gitdir]]])"
5929 focus -force $ui_comm
5930
5931 # -- Warn the user about environmental problems.  Cygwin's Tcl
5932 #    does *not* pass its env array onto any processes it spawns.
5933 #    This means that git processes get none of our environment.
5934 #
5935 if {[is_Cygwin]} {
5936         set ignored_env 0
5937         set suggest_user {}
5938         set msg "Possible environment issues exist.
5939
5940 The following environment variables are probably
5941 going to be ignored by any Git subprocess run
5942 by [appname]:
5943
5944 "
5945         foreach name [array names env] {
5946                 switch -regexp -- $name {
5947                 {^GIT_INDEX_FILE$} -
5948                 {^GIT_OBJECT_DIRECTORY$} -
5949                 {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
5950                 {^GIT_DIFF_OPTS$} -
5951                 {^GIT_EXTERNAL_DIFF$} -
5952                 {^GIT_PAGER$} -
5953                 {^GIT_TRACE$} -
5954                 {^GIT_CONFIG$} -
5955                 {^GIT_CONFIG_LOCAL$} -
5956                 {^GIT_(AUTHOR|COMMITTER)_DATE$} {
5957                         append msg " - $name\n"
5958                         incr ignored_env
5959                 }
5960                 {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
5961                         append msg " - $name\n"
5962                         incr ignored_env
5963                         set suggest_user $name
5964                 }
5965                 }
5966         }
5967         if {$ignored_env > 0} {
5968                 append msg "
5969 This is due to a known issue with the
5970 Tcl binary distributed by Cygwin."
5971
5972                 if {$suggest_user ne {}} {
5973                         append msg "
5974
5975 A good replacement for $suggest_user
5976 is placing values for the user.name and
5977 user.email settings into your personal
5978 ~/.gitconfig file.
5979 "
5980                 }
5981                 warn_popup $msg
5982         }
5983         unset ignored_env msg suggest_user name
5984 }
5985
5986 # -- Only initialize complex UI if we are going to stay running.
5987 #
5988 if {[is_enabled transport]} {
5989         load_all_remotes
5990         load_all_heads
5991
5992         populate_branch_menu
5993         populate_fetch_menu
5994         populate_push_menu
5995 }
5996
5997 # -- Only suggest a gc run if we are going to stay running.
5998 #
5999 if {[is_enabled multicommit]} {
6000         set object_limit 2000
6001         if {[is_Windows]} {set object_limit 200}
6002         regexp {^([0-9]+) objects,} [git count-objects] _junk objects_current
6003         if {$objects_current >= $object_limit} {
6004                 if {[ask_popup \
6005                         "This repository currently has $objects_current loose objects.
6006
6007 To maintain optimal performance it is strongly
6008 recommended that you compress the database
6009 when more than $object_limit loose objects exist.
6010
6011 Compress the database now?"] eq yes} {
6012                         do_gc
6013                 }
6014         }
6015         unset object_limit _junk objects_current
6016 }
6017
6018 lock_index begin-read
6019 after 1 do_rescan