Merge branch 'bw/commit-scrollbuffer'
[git] / git-gui.sh
1 #!/bin/sh
2 # Tcl ignores the next line -*- tcl -*- \
3  if test "z$*" = zversion \
4  || test "z$*" = z--version; \
5  then \
6         echo 'git-gui version @@GITGUI_VERSION@@'; \
7         exit; \
8  fi; \
9  argv0=$0; \
10  exec wish "$argv0" -- "$@"
11
12 set appvers {@@GITGUI_VERSION@@}
13 set copyright [string map [list (c) \u00a9] {
14 Copyright (c) 2006-2010 Shawn Pearce, et. al.
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA}]
29
30 ######################################################################
31 ##
32 ## Tcl/Tk sanity check
33
34 if {[catch {package require Tcl 8.4} err]
35  || [catch {package require Tk  8.4} err]
36 } {
37         catch {wm withdraw .}
38         tk_messageBox \
39                 -icon error \
40                 -type ok \
41                 -title "git-gui: fatal error" \
42                 -message $err
43         exit 1
44 }
45
46 catch {rename send {}} ; # What an evil concept...
47
48 ######################################################################
49 ##
50 ## locate our library
51
52 if { [info exists ::env(GIT_GUI_LIB_DIR) ] } {
53         set oguilib $::env(GIT_GUI_LIB_DIR)
54 } else {
55         set oguilib {@@GITGUI_LIBDIR@@}
56 }
57 set oguirel {@@GITGUI_RELATIVE@@}
58 if {$oguirel eq {1}} {
59         set oguilib [file dirname [file normalize $argv0]]
60         if {[file tail $oguilib] eq {git-core}} {
61                 set oguilib [file dirname $oguilib]
62         }
63         set oguilib [file dirname $oguilib]
64         set oguilib [file join $oguilib share git-gui lib]
65         set oguimsg [file join $oguilib msgs]
66 } elseif {[string match @@* $oguirel]} {
67         set oguilib [file join [file dirname [file normalize $argv0]] lib]
68         set oguimsg [file join [file dirname [file normalize $argv0]] po]
69 } else {
70         set oguimsg [file join $oguilib msgs]
71 }
72 unset oguirel
73
74 ######################################################################
75 ##
76 ## enable verbose loading?
77
78 if {![catch {set _verbose $env(GITGUI_VERBOSE)}]} {
79         unset _verbose
80         rename auto_load real__auto_load
81         proc auto_load {name args} {
82                 puts stderr "auto_load $name"
83                 return [uplevel 1 real__auto_load $name $args]
84         }
85         rename source real__source
86         proc source {args} {
87                 puts stderr "source    $args"
88                 uplevel 1 [linsert $args 0 real__source]
89         }
90         if {[tk windowingsystem] eq "win32"} { console show }
91 }
92
93 ######################################################################
94 ##
95 ## Internationalization (i18n) through msgcat and gettext. See
96 ## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
97
98 package require msgcat
99
100 # Check for Windows 7 MUI language pack (missed by msgcat < 1.4.4)
101 if {[tk windowingsystem] eq "win32"
102         && [package vcompare [package provide msgcat] 1.4.4] < 0
103 } then {
104         proc _mc_update_locale {} {
105                 set key {HKEY_CURRENT_USER\Control Panel\Desktop}
106                 if {![catch {
107                         package require registry
108                         set uilocale [registry get $key "PreferredUILanguages"]
109                         msgcat::ConvertLocale [string map {- _} [lindex $uilocale 0]]
110                 } uilocale]} {
111                         if {[string length $uilocale] > 0} {
112                                 msgcat::mclocale $uilocale
113                         }
114                 }
115         }
116         _mc_update_locale
117 }
118
119 proc _mc_trim {fmt} {
120         set cmk [string first @@ $fmt]
121         if {$cmk > 0} {
122                 return [string range $fmt 0 [expr {$cmk - 1}]]
123         }
124         return $fmt
125 }
126
127 proc mc {en_fmt args} {
128         set fmt [_mc_trim [::msgcat::mc $en_fmt]]
129         if {[catch {set msg [eval [list format $fmt] $args]} err]} {
130                 set msg [eval [list format [_mc_trim $en_fmt]] $args]
131         }
132         return $msg
133 }
134
135 proc strcat {args} {
136         return [join $args {}]
137 }
138
139 ::msgcat::mcload $oguimsg
140 unset oguimsg
141
142 ######################################################################
143 ##
144 ## On Mac, bring the current Wish process window to front
145
146 if {[tk windowingsystem] eq "aqua"} {
147         catch {
148                 exec osascript -e [format {
149                         tell application "System Events"
150                                 set frontmost of processes whose unix id is %d to true
151                         end tell
152                 } [pid]]
153         }
154 }
155
156 ######################################################################
157 ##
158 ## read only globals
159
160 set _appname {Git Gui}
161 set _gitdir {}
162 set _gitworktree {}
163 set _isbare {}
164 set _gitexec {}
165 set _githtmldir {}
166 set _reponame {}
167 set _iscygwin {}
168 set _search_path {}
169 set _shellpath {@@SHELL_PATH@@}
170
171 set _trace [lsearch -exact $argv --trace]
172 if {$_trace >= 0} {
173         set argv [lreplace $argv $_trace $_trace]
174         set _trace 1
175         if {[tk windowingsystem] eq "win32"} { console show }
176 } else {
177         set _trace 0
178 }
179
180 # variable for the last merged branch (useful for a default when deleting
181 # branches).
182 set _last_merged_branch {}
183
184 proc shellpath {} {
185         global _shellpath env
186         if {[string match @@* $_shellpath]} {
187                 if {[info exists env(SHELL)]} {
188                         return $env(SHELL)
189                 } else {
190                         return /bin/sh
191                 }
192         }
193         return $_shellpath
194 }
195
196 proc appname {} {
197         global _appname
198         return $_appname
199 }
200
201 proc gitdir {args} {
202         global _gitdir
203         if {$args eq {}} {
204                 return $_gitdir
205         }
206         return [eval [list file join $_gitdir] $args]
207 }
208
209 proc gitexec {args} {
210         global _gitexec
211         if {$_gitexec eq {}} {
212                 if {[catch {set _gitexec [git --exec-path]} err]} {
213                         error "Git not installed?\n\n$err"
214                 }
215                 if {[is_Cygwin]} {
216                         set _gitexec [exec cygpath \
217                                 --windows \
218                                 --absolute \
219                                 $_gitexec]
220                 } else {
221                         set _gitexec [file normalize $_gitexec]
222                 }
223         }
224         if {$args eq {}} {
225                 return $_gitexec
226         }
227         return [eval [list file join $_gitexec] $args]
228 }
229
230 proc githtmldir {args} {
231         global _githtmldir
232         if {$_githtmldir eq {}} {
233                 if {[catch {set _githtmldir [git --html-path]}]} {
234                         # Git not installed or option not yet supported
235                         return {}
236                 }
237                 if {[is_Cygwin]} {
238                         set _githtmldir [exec cygpath \
239                                 --windows \
240                                 --absolute \
241                                 $_githtmldir]
242                 } else {
243                         set _githtmldir [file normalize $_githtmldir]
244                 }
245         }
246         if {$args eq {}} {
247                 return $_githtmldir
248         }
249         return [eval [list file join $_githtmldir] $args]
250 }
251
252 proc reponame {} {
253         return $::_reponame
254 }
255
256 proc is_MacOSX {} {
257         if {[tk windowingsystem] eq {aqua}} {
258                 return 1
259         }
260         return 0
261 }
262
263 proc is_Windows {} {
264         if {$::tcl_platform(platform) eq {windows}} {
265                 return 1
266         }
267         return 0
268 }
269
270 proc is_Cygwin {} {
271         global _iscygwin
272         if {$_iscygwin eq {}} {
273                 if {$::tcl_platform(platform) eq {windows}} {
274                         if {[catch {set p [exec cygpath --windir]} err]} {
275                                 set _iscygwin 0
276                         } else {
277                                 set _iscygwin 1
278                                 # Handle MSys2 which is only cygwin when MSYSTEM is MSYS.
279                                 if {[info exists ::env(MSYSTEM)] && $::env(MSYSTEM) ne "MSYS"} {
280                                         set _iscygwin 0
281                                 }
282                         }
283                 } else {
284                         set _iscygwin 0
285                 }
286         }
287         return $_iscygwin
288 }
289
290 proc is_enabled {option} {
291         global enabled_options
292         if {[catch {set on $enabled_options($option)}]} {return 0}
293         return $on
294 }
295
296 proc enable_option {option} {
297         global enabled_options
298         set enabled_options($option) 1
299 }
300
301 proc disable_option {option} {
302         global enabled_options
303         set enabled_options($option) 0
304 }
305
306 ######################################################################
307 ##
308 ## config
309
310 proc is_many_config {name} {
311         switch -glob -- $name {
312         gui.recentrepo -
313         remote.*.fetch -
314         remote.*.push
315                 {return 1}
316         *
317                 {return 0}
318         }
319 }
320
321 proc is_config_true {name} {
322         global repo_config
323         if {[catch {set v $repo_config($name)}]} {
324                 return 0
325         }
326         set v [string tolower $v]
327         if {$v eq {} || $v eq {true} || $v eq {1} || $v eq {yes} || $v eq {on}} {
328                 return 1
329         } else {
330                 return 0
331         }
332 }
333
334 proc is_config_false {name} {
335         global repo_config
336         if {[catch {set v $repo_config($name)}]} {
337                 return 0
338         }
339         set v [string tolower $v]
340         if {$v eq {false} || $v eq {0} || $v eq {no} || $v eq {off}} {
341                 return 1
342         } else {
343                 return 0
344         }
345 }
346
347 proc get_config {name} {
348         global repo_config
349         if {[catch {set v $repo_config($name)}]} {
350                 return {}
351         } else {
352                 return $v
353         }
354 }
355
356 proc is_bare {} {
357         global _isbare
358         global _gitdir
359         global _gitworktree
360
361         if {$_isbare eq {}} {
362                 if {[catch {
363                         set _bare [git rev-parse --is-bare-repository]
364                         switch  -- $_bare {
365                         true { set _isbare 1 }
366                         false { set _isbare 0}
367                         default { throw }
368                         }
369                 }]} {
370                         if {[is_config_true core.bare]
371                                 || ($_gitworktree eq {}
372                                         && [lindex [file split $_gitdir] end] ne {.git})} {
373                                 set _isbare 1
374                         } else {
375                                 set _isbare 0
376                         }
377                 }
378         }
379         return $_isbare
380 }
381
382 ######################################################################
383 ##
384 ## handy utils
385
386 proc _trace_exec {cmd} {
387         if {!$::_trace} return
388         set d {}
389         foreach v $cmd {
390                 if {$d ne {}} {
391                         append d { }
392                 }
393                 if {[regexp {[ \t\r\n'"$?*]} $v]} {
394                         set v [sq $v]
395                 }
396                 append d $v
397         }
398         puts stderr $d
399 }
400
401 #'"  fix poor old emacs font-lock mode
402
403 proc _git_cmd {name} {
404         global _git_cmd_path
405
406         if {[catch {set v $_git_cmd_path($name)}]} {
407                 switch -- $name {
408                   version   -
409                 --version   -
410                 --exec-path { return [list $::_git $name] }
411                 }
412
413                 set p [gitexec git-$name$::_search_exe]
414                 if {[file exists $p]} {
415                         set v [list $p]
416                 } elseif {[is_Windows] && [file exists [gitexec git-$name]]} {
417                         # Try to determine what sort of magic will make
418                         # git-$name go and do its thing, because native
419                         # Tcl on Windows doesn't know it.
420                         #
421                         set p [gitexec git-$name]
422                         set f [open $p r]
423                         set s [gets $f]
424                         close $f
425
426                         switch -glob -- [lindex $s 0] {
427                         #!*sh     { set i sh     }
428                         #!*perl   { set i perl   }
429                         #!*python { set i python }
430                         default   { error "git-$name is not supported: $s" }
431                         }
432
433                         upvar #0 _$i interp
434                         if {![info exists interp]} {
435                                 set interp [_which $i]
436                         }
437                         if {$interp eq {}} {
438                                 error "git-$name requires $i (not in PATH)"
439                         }
440                         set v [concat [list $interp] [lrange $s 1 end] [list $p]]
441                 } else {
442                         # Assume it is builtin to git somehow and we
443                         # aren't actually able to see a file for it.
444                         #
445                         set v [list $::_git $name]
446                 }
447                 set _git_cmd_path($name) $v
448         }
449         return $v
450 }
451
452 proc _which {what args} {
453         global env _search_exe _search_path
454
455         if {$_search_path eq {}} {
456                 if {[is_Cygwin] && [regexp {^(/|\.:)} $env(PATH)]} {
457                         set _search_path [split [exec cygpath \
458                                 --windows \
459                                 --path \
460                                 --absolute \
461                                 $env(PATH)] {;}]
462                         set _search_exe .exe
463                 } elseif {[is_Windows]} {
464                         set gitguidir [file dirname [info script]]
465                         regsub -all ";" $gitguidir "\\;" gitguidir
466                         set env(PATH) "$gitguidir;$env(PATH)"
467                         set _search_path [split $env(PATH) {;}]
468                         set _search_exe .exe
469                 } else {
470                         set _search_path [split $env(PATH) :]
471                         set _search_exe {}
472                 }
473         }
474
475         if {[is_Windows] && [lsearch -exact $args -script] >= 0} {
476                 set suffix {}
477         } else {
478                 set suffix $_search_exe
479         }
480
481         foreach p $_search_path {
482                 set p [file join $p $what$suffix]
483                 if {[file exists $p]} {
484                         return [file normalize $p]
485                 }
486         }
487         return {}
488 }
489
490 # Test a file for a hashbang to identify executable scripts on Windows.
491 proc is_shellscript {filename} {
492         if {![file exists $filename]} {return 0}
493         set f [open $filename r]
494         fconfigure $f -encoding binary
495         set magic [read $f 2]
496         close $f
497         return [expr {$magic eq "#!"}]
498 }
499
500 # Run a command connected via pipes on stdout.
501 # This is for use with textconv filters and uses sh -c "..." to allow it to
502 # contain a command with arguments. On windows we must check for shell
503 # scripts specifically otherwise just call the filter command.
504 proc open_cmd_pipe {cmd path} {
505         global env
506         if {![file executable [shellpath]]} {
507                 set exe [auto_execok [lindex $cmd 0]]
508                 if {[is_shellscript [lindex $exe 0]]} {
509                         set run [linsert [auto_execok sh] end -c "$cmd \"\$0\"" $path]
510                 } else {
511                         set run [concat $exe [lrange $cmd 1 end] $path]
512                 }
513         } else {
514                 set run [list [shellpath] -c "$cmd \"\$0\"" $path]
515         }
516         return [open |$run r]
517 }
518
519 proc _lappend_nice {cmd_var} {
520         global _nice
521         upvar $cmd_var cmd
522
523         if {![info exists _nice]} {
524                 set _nice [_which nice]
525                 if {[catch {exec $_nice git version}]} {
526                         set _nice {}
527                 } elseif {[is_Windows] && [file dirname $_nice] ne [file dirname $::_git]} {
528                         set _nice {}
529                 }
530         }
531         if {$_nice ne {}} {
532                 lappend cmd $_nice
533         }
534 }
535
536 proc git {args} {
537         set fd [eval [list git_read] $args]
538         fconfigure $fd -translation binary -encoding utf-8
539         set result [string trimright [read $fd] "\n"]
540         close $fd
541         if {$::_trace} {
542                 puts stderr "< $result"
543         }
544         return $result
545 }
546
547 proc _open_stdout_stderr {cmd} {
548         _trace_exec $cmd
549         if {[catch {
550                         set fd [open [concat [list | ] $cmd] r]
551                 } err]} {
552                 if {   [lindex $cmd end] eq {2>@1}
553                     && $err eq {can not find channel named "1"}
554                         } {
555                         # Older versions of Tcl 8.4 don't have this 2>@1 IO
556                         # redirect operator.  Fallback to |& cat for those.
557                         # The command was not actually started, so its safe
558                         # to try to start it a second time.
559                         #
560                         set fd [open [concat \
561                                 [list | ] \
562                                 [lrange $cmd 0 end-1] \
563                                 [list |& cat] \
564                                 ] r]
565                 } else {
566                         error $err
567                 }
568         }
569         fconfigure $fd -eofchar {}
570         return $fd
571 }
572
573 proc git_read {args} {
574         set opt [list]
575
576         while {1} {
577                 switch -- [lindex $args 0] {
578                 --nice {
579                         _lappend_nice opt
580                 }
581
582                 --stderr {
583                         lappend args 2>@1
584                 }
585
586                 default {
587                         break
588                 }
589
590                 }
591
592                 set args [lrange $args 1 end]
593         }
594
595         set cmdp [_git_cmd [lindex $args 0]]
596         set args [lrange $args 1 end]
597
598         return [_open_stdout_stderr [concat $opt $cmdp $args]]
599 }
600
601 proc git_write {args} {
602         set opt [list]
603
604         while {1} {
605                 switch -- [lindex $args 0] {
606                 --nice {
607                         _lappend_nice opt
608                 }
609
610                 default {
611                         break
612                 }
613
614                 }
615
616                 set args [lrange $args 1 end]
617         }
618
619         set cmdp [_git_cmd [lindex $args 0]]
620         set args [lrange $args 1 end]
621
622         _trace_exec [concat $opt $cmdp $args]
623         return [open [concat [list | ] $opt $cmdp $args] w]
624 }
625
626 proc githook_read {hook_name args} {
627         set pchook [gitdir hooks $hook_name]
628         lappend args 2>@1
629
630         # On Windows [file executable] might lie so we need to ask
631         # the shell if the hook is executable.  Yes that's annoying.
632         #
633         if {[is_Windows]} {
634                 upvar #0 _sh interp
635                 if {![info exists interp]} {
636                         set interp [_which sh]
637                 }
638                 if {$interp eq {}} {
639                         error "hook execution requires sh (not in PATH)"
640                 }
641
642                 set scr {if test -x "$1";then exec "$@";fi}
643                 set sh_c [list $interp -c $scr $interp $pchook]
644                 return [_open_stdout_stderr [concat $sh_c $args]]
645         }
646
647         if {[file executable $pchook]} {
648                 return [_open_stdout_stderr [concat [list $pchook] $args]]
649         }
650
651         return {}
652 }
653
654 proc kill_file_process {fd} {
655         set process [pid $fd]
656
657         catch {
658                 if {[is_Windows]} {
659                         exec taskkill /pid $process
660                 } else {
661                         exec kill $process
662                 }
663         }
664 }
665
666 proc gitattr {path attr default} {
667         if {[catch {set r [git check-attr $attr -- $path]}]} {
668                 set r unspecified
669         } else {
670                 set r [join [lrange [split $r :] 2 end] :]
671                 regsub {^ } $r {} r
672         }
673         if {$r eq {unspecified}} {
674                 return $default
675         }
676         return $r
677 }
678
679 proc sq {value} {
680         regsub -all ' $value "'\\''" value
681         return "'$value'"
682 }
683
684 proc load_current_branch {} {
685         global current_branch is_detached
686
687         set fd [open [gitdir HEAD] r]
688         if {[gets $fd ref] < 1} {
689                 set ref {}
690         }
691         close $fd
692
693         set pfx {ref: refs/heads/}
694         set len [string length $pfx]
695         if {[string equal -length $len $pfx $ref]} {
696                 # We're on a branch.  It might not exist.  But
697                 # HEAD looks good enough to be a branch.
698                 #
699                 set current_branch [string range $ref $len end]
700                 set is_detached 0
701         } else {
702                 # Assume this is a detached head.
703                 #
704                 set current_branch HEAD
705                 set is_detached 1
706         }
707 }
708
709 auto_load tk_optionMenu
710 rename tk_optionMenu real__tkOptionMenu
711 proc tk_optionMenu {w varName args} {
712         set m [eval real__tkOptionMenu $w $varName $args]
713         $m configure -font font_ui
714         $w configure -font font_ui
715         return $m
716 }
717
718 proc rmsel_tag {text} {
719         $text tag conf sel \
720                 -background [$text cget -background] \
721                 -foreground [$text cget -foreground] \
722                 -borderwidth 0
723         $text tag conf in_sel -background lightgray
724         bind $text <Motion> break
725         return $text
726 }
727
728 wm withdraw .
729 set root_exists 0
730 bind . <Visibility> {
731         bind . <Visibility> {}
732         set root_exists 1
733 }
734
735 if {[is_Windows]} {
736         wm iconbitmap . -default $oguilib/git-gui.ico
737         set ::tk::AlwaysShowSelection 1
738         bind . <Control-F2> {console show}
739
740         # Spoof an X11 display for SSH
741         if {![info exists env(DISPLAY)]} {
742                 set env(DISPLAY) :9999
743         }
744 } else {
745         catch {
746                 image create photo gitlogo -width 16 -height 16
747
748                 gitlogo put #33CC33 -to  7  0  9  2
749                 gitlogo put #33CC33 -to  4  2 12  4
750                 gitlogo put #33CC33 -to  7  4  9  6
751                 gitlogo put #CC3333 -to  4  6 12  8
752                 gitlogo put gray26  -to  4  9  6 10
753                 gitlogo put gray26  -to  3 10  6 12
754                 gitlogo put gray26  -to  8  9 13 11
755                 gitlogo put gray26  -to  8 11 10 12
756                 gitlogo put gray26  -to 11 11 13 14
757                 gitlogo put gray26  -to  3 12  5 14
758                 gitlogo put gray26  -to  5 13
759                 gitlogo put gray26  -to 10 13
760                 gitlogo put gray26  -to  4 14 12 15
761                 gitlogo put gray26  -to  5 15 11 16
762                 gitlogo redither
763
764                 image create photo gitlogo32 -width 32 -height 32
765                 gitlogo32 copy gitlogo -zoom 2 2
766
767                 wm iconphoto . -default gitlogo gitlogo32
768         }
769 }
770
771 ######################################################################
772 ##
773 ## config defaults
774
775 set cursor_ptr arrow
776 font create font_ui
777 if {[lsearch -exact [font names] TkDefaultFont] != -1} {
778         eval [linsert [font actual TkDefaultFont] 0 font configure font_ui]
779         eval [linsert [font actual TkFixedFont] 0 font create font_diff]
780 } else {
781         font create font_diff -family Courier -size 10
782         catch {
783                 label .dummy
784                 eval font configure font_ui [font actual [.dummy cget -font]]
785                 destroy .dummy
786         }
787 }
788
789 font create font_uiitalic
790 font create font_uibold
791 font create font_diffbold
792 font create font_diffitalic
793
794 foreach class {Button Checkbutton Entry Label
795                 Labelframe Listbox Message
796                 Radiobutton Spinbox Text} {
797         option add *$class.font font_ui
798 }
799 if {![is_MacOSX]} {
800         option add *Menu.font font_ui
801         option add *Entry.borderWidth 1 startupFile
802         option add *Entry.relief sunken startupFile
803         option add *RadioButton.anchor w startupFile
804 }
805 unset class
806
807 if {[is_Windows] || [is_MacOSX]} {
808         option add *Menu.tearOff 0
809 }
810
811 if {[is_MacOSX]} {
812         set M1B M1
813         set M1T Cmd
814 } else {
815         set M1B Control
816         set M1T Ctrl
817 }
818
819 proc bind_button3 {w cmd} {
820         bind $w <Any-Button-3> $cmd
821         if {[is_MacOSX]} {
822                 # Mac OS X sends Button-2 on right click through three-button mouse,
823                 # or through trackpad right-clicking (two-finger touch + click).
824                 bind $w <Any-Button-2> $cmd
825                 bind $w <Control-Button-1> $cmd
826         }
827 }
828
829 proc apply_config {} {
830         global repo_config font_descs
831
832         foreach option $font_descs {
833                 set name [lindex $option 0]
834                 set font [lindex $option 1]
835                 if {[catch {
836                         set need_weight 1
837                         foreach {cn cv} $repo_config(gui.$name) {
838                                 if {$cn eq {-weight}} {
839                                         set need_weight 0
840                                 }
841                                 font configure $font $cn $cv
842                         }
843                         if {$need_weight} {
844                                 font configure $font -weight normal
845                         }
846                         } err]} {
847                         error_popup [strcat [mc "Invalid font specified in %s:" "gui.$name"] "\n\n$err"]
848                 }
849                 foreach {cn cv} [font configure $font] {
850                         font configure ${font}bold $cn $cv
851                         font configure ${font}italic $cn $cv
852                 }
853                 font configure ${font}bold -weight bold
854                 font configure ${font}italic -slant italic
855         }
856
857         global use_ttk NS
858         set use_ttk 0
859         set NS {}
860         if {$repo_config(gui.usettk)} {
861                 set use_ttk [package vsatisfies [package provide Tk] 8.5]
862                 if {$use_ttk} {
863                         set NS ttk
864                         bind [winfo class .] <<ThemeChanged>> [list InitTheme]
865                         pave_toplevel .
866                 }
867         }
868 }
869
870 set default_config(branch.autosetupmerge) true
871 set default_config(merge.tool) {}
872 set default_config(mergetool.keepbackup) true
873 set default_config(merge.diffstat) true
874 set default_config(merge.summary) false
875 set default_config(merge.verbosity) 2
876 set default_config(user.name) {}
877 set default_config(user.email) {}
878
879 set default_config(gui.encoding) [encoding system]
880 set default_config(gui.matchtrackingbranch) false
881 set default_config(gui.textconv) true
882 set default_config(gui.pruneduringfetch) false
883 set default_config(gui.trustmtime) false
884 set default_config(gui.fastcopyblame) false
885 set default_config(gui.maxrecentrepo) 10
886 set default_config(gui.copyblamethreshold) 40
887 set default_config(gui.blamehistoryctx) 7
888 set default_config(gui.diffcontext) 5
889 set default_config(gui.diffopts) {}
890 set default_config(gui.commitmsgwidth) 75
891 set default_config(gui.newbranchtemplate) {}
892 set default_config(gui.spellingdictionary) {}
893 set default_config(gui.fontui) [font configure font_ui]
894 set default_config(gui.fontdiff) [font configure font_diff]
895 # TODO: this option should be added to the git-config documentation
896 set default_config(gui.maxfilesdisplayed) 5000
897 set default_config(gui.usettk) 1
898 set default_config(gui.warndetachedcommit) 1
899 set default_config(gui.tabsize) 8
900 set font_descs {
901         {fontui   font_ui   {mc "Main Font"}}
902         {fontdiff font_diff {mc "Diff/Console Font"}}
903 }
904 set default_config(gui.stageuntracked) ask
905 set default_config(gui.displayuntracked) true
906
907 ######################################################################
908 ##
909 ## find git
910
911 set _git  [_which git]
912 if {$_git eq {}} {
913         catch {wm withdraw .}
914         tk_messageBox \
915                 -icon error \
916                 -type ok \
917                 -title [mc "git-gui: fatal error"] \
918                 -message [mc "Cannot find git in PATH."]
919         exit 1
920 }
921
922 ######################################################################
923 ##
924 ## version check
925
926 if {[catch {set _git_version [git --version]} err]} {
927         catch {wm withdraw .}
928         tk_messageBox \
929                 -icon error \
930                 -type ok \
931                 -title [mc "git-gui: fatal error"] \
932                 -message "Cannot determine Git version:
933
934 $err
935
936 [appname] requires Git 1.5.0 or later."
937         exit 1
938 }
939 if {![regsub {^git version } $_git_version {} _git_version]} {
940         catch {wm withdraw .}
941         tk_messageBox \
942                 -icon error \
943                 -type ok \
944                 -title [mc "git-gui: fatal error"] \
945                 -message [strcat [mc "Cannot parse Git version string:"] "\n\n$_git_version"]
946         exit 1
947 }
948
949 proc get_trimmed_version {s} {
950     set r {}
951     foreach x [split $s -._] {
952         if {[string is integer -strict $x]} {
953             lappend r $x
954         } else {
955             break
956         }
957     }
958     return [join $r .]
959 }
960 set _real_git_version $_git_version
961 set _git_version [get_trimmed_version $_git_version]
962
963 if {![regexp {^[1-9]+(\.[0-9]+)+$} $_git_version]} {
964         catch {wm withdraw .}
965         if {[tk_messageBox \
966                 -icon warning \
967                 -type yesno \
968                 -default no \
969                 -title "[appname]: warning" \
970                  -message [mc "Git version cannot be determined.
971
972 %s claims it is version '%s'.
973
974 %s requires at least Git 1.5.0 or later.
975
976 Assume '%s' is version 1.5.0?
977 " $_git $_real_git_version [appname] $_real_git_version]] eq {yes}} {
978                 set _git_version 1.5.0
979         } else {
980                 exit 1
981         }
982 }
983 unset _real_git_version
984
985 proc git-version {args} {
986         global _git_version
987
988         switch [llength $args] {
989         0 {
990                 return $_git_version
991         }
992
993         2 {
994                 set op [lindex $args 0]
995                 set vr [lindex $args 1]
996                 set cm [package vcompare $_git_version $vr]
997                 return [expr $cm $op 0]
998         }
999
1000         4 {
1001                 set type [lindex $args 0]
1002                 set name [lindex $args 1]
1003                 set parm [lindex $args 2]
1004                 set body [lindex $args 3]
1005
1006                 if {($type ne {proc} && $type ne {method})} {
1007                         error "Invalid arguments to git-version"
1008                 }
1009                 if {[llength $body] < 2 || [lindex $body end-1] ne {default}} {
1010                         error "Last arm of $type $name must be default"
1011                 }
1012
1013                 foreach {op vr cb} [lrange $body 0 end-2] {
1014                         if {[git-version $op $vr]} {
1015                                 return [uplevel [list $type $name $parm $cb]]
1016                         }
1017                 }
1018
1019                 return [uplevel [list $type $name $parm [lindex $body end]]]
1020         }
1021
1022         default {
1023                 error "git-version >= x"
1024         }
1025
1026         }
1027 }
1028
1029 if {[git-version < 1.5]} {
1030         catch {wm withdraw .}
1031         tk_messageBox \
1032                 -icon error \
1033                 -type ok \
1034                 -title [mc "git-gui: fatal error"] \
1035                 -message "[appname] requires Git 1.5.0 or later.
1036
1037 You are using [git-version]:
1038
1039 [git --version]"
1040         exit 1
1041 }
1042
1043 ######################################################################
1044 ##
1045 ## configure our library
1046
1047 set idx [file join $oguilib tclIndex]
1048 if {[catch {set fd [open $idx r]} err]} {
1049         catch {wm withdraw .}
1050         tk_messageBox \
1051                 -icon error \
1052                 -type ok \
1053                 -title [mc "git-gui: fatal error"] \
1054                 -message $err
1055         exit 1
1056 }
1057 if {[gets $fd] eq {# Autogenerated by git-gui Makefile}} {
1058         set idx [list]
1059         while {[gets $fd n] >= 0} {
1060                 if {$n ne {} && ![string match #* $n]} {
1061                         lappend idx $n
1062                 }
1063         }
1064 } else {
1065         set idx {}
1066 }
1067 close $fd
1068
1069 if {$idx ne {}} {
1070         set loaded [list]
1071         foreach p $idx {
1072                 if {[lsearch -exact $loaded $p] >= 0} continue
1073                 source [file join $oguilib $p]
1074                 lappend loaded $p
1075         }
1076         unset loaded p
1077 } else {
1078         set auto_path [concat [list $oguilib] $auto_path]
1079 }
1080 unset -nocomplain idx fd
1081
1082 ######################################################################
1083 ##
1084 ## config file parsing
1085
1086 git-version proc _parse_config {arr_name args} {
1087         >= 1.5.3 {
1088                 upvar $arr_name arr
1089                 array unset arr
1090                 set buf {}
1091                 catch {
1092                         set fd_rc [eval \
1093                                 [list git_read config] \
1094                                 $args \
1095                                 [list --null --list]]
1096                         fconfigure $fd_rc -translation binary -encoding utf-8
1097                         set buf [read $fd_rc]
1098                         close $fd_rc
1099                 }
1100                 foreach line [split $buf "\0"] {
1101                         if {[regexp {^([^\n]+)\n(.*)$} $line line name value]} {
1102                                 if {[is_many_config $name]} {
1103                                         lappend arr($name) $value
1104                                 } else {
1105                                         set arr($name) $value
1106                                 }
1107                         } elseif {[regexp {^([^\n]+)$} $line line name]} {
1108                                 # no value given, but interpreting them as
1109                                 # boolean will be handled as true
1110                                 set arr($name) {}
1111                         }
1112                 }
1113         }
1114         default {
1115                 upvar $arr_name arr
1116                 array unset arr
1117                 catch {
1118                         set fd_rc [eval [list git_read config --list] $args]
1119                         while {[gets $fd_rc line] >= 0} {
1120                                 if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
1121                                         if {[is_many_config $name]} {
1122                                                 lappend arr($name) $value
1123                                         } else {
1124                                                 set arr($name) $value
1125                                         }
1126                                 } elseif {[regexp {^([^=]+)$} $line line name]} {
1127                                         # no value given, but interpreting them as
1128                                         # boolean will be handled as true
1129                                         set arr($name) {}
1130                                 }
1131                         }
1132                         close $fd_rc
1133                 }
1134         }
1135 }
1136
1137 proc load_config {include_global} {
1138         global repo_config global_config system_config default_config
1139
1140         if {$include_global} {
1141                 _parse_config system_config --system
1142                 _parse_config global_config --global
1143         }
1144         _parse_config repo_config
1145
1146         foreach name [array names default_config] {
1147                 if {[catch {set v $system_config($name)}]} {
1148                         set system_config($name) $default_config($name)
1149                 }
1150         }
1151         foreach name [array names system_config] {
1152                 if {[catch {set v $global_config($name)}]} {
1153                         set global_config($name) $system_config($name)
1154                 }
1155                 if {[catch {set v $repo_config($name)}]} {
1156                         set repo_config($name) $system_config($name)
1157                 }
1158         }
1159 }
1160
1161 ######################################################################
1162 ##
1163 ## feature option selection
1164
1165 if {[regexp {^git-(.+)$} [file tail $argv0] _junk subcommand]} {
1166         unset _junk
1167 } else {
1168         set subcommand gui
1169 }
1170 if {$subcommand eq {gui.sh}} {
1171         set subcommand gui
1172 }
1173 if {$subcommand eq {gui} && [llength $argv] > 0} {
1174         set subcommand [lindex $argv 0]
1175         set argv [lrange $argv 1 end]
1176 }
1177
1178 enable_option multicommit
1179 enable_option branch
1180 enable_option transport
1181 disable_option bare
1182
1183 switch -- $subcommand {
1184 browser -
1185 blame {
1186         enable_option bare
1187
1188         disable_option multicommit
1189         disable_option branch
1190         disable_option transport
1191 }
1192 citool {
1193         enable_option singlecommit
1194         enable_option retcode
1195
1196         disable_option multicommit
1197         disable_option branch
1198         disable_option transport
1199
1200         while {[llength $argv] > 0} {
1201                 set a [lindex $argv 0]
1202                 switch -- $a {
1203                 --amend {
1204                         enable_option initialamend
1205                 }
1206                 --nocommit {
1207                         enable_option nocommit
1208                         enable_option nocommitmsg
1209                 }
1210                 --commitmsg {
1211                         disable_option nocommitmsg
1212                 }
1213                 default {
1214                         break
1215                 }
1216                 }
1217
1218                 set argv [lrange $argv 1 end]
1219         }
1220 }
1221 }
1222
1223 ######################################################################
1224 ##
1225 ## execution environment
1226
1227 set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
1228
1229 # Suggest our implementation of askpass, if none is set
1230 if {![info exists env(SSH_ASKPASS)]} {
1231         set env(SSH_ASKPASS) [gitexec git-gui--askpass]
1232 }
1233
1234 ######################################################################
1235 ##
1236 ## repository setup
1237
1238 set picked 0
1239 if {[catch {
1240                 set _gitdir $env(GIT_DIR)
1241                 set _prefix {}
1242                 }]
1243         && [catch {
1244                 # beware that from the .git dir this sets _gitdir to .
1245                 # and _prefix to the empty string
1246                 set _gitdir [git rev-parse --git-dir]
1247                 set _prefix [git rev-parse --show-prefix]
1248         } err]} {
1249         load_config 1
1250         apply_config
1251         choose_repository::pick
1252         set picked 1
1253 }
1254
1255 # we expand the _gitdir when it's just a single dot (i.e. when we're being
1256 # run from the .git dir itself) lest the routines to find the worktree
1257 # get confused
1258 if {$_gitdir eq "."} {
1259         set _gitdir [pwd]
1260 }
1261
1262 if {![file isdirectory $_gitdir] && [is_Cygwin]} {
1263         catch {set _gitdir [exec cygpath --windows $_gitdir]}
1264 }
1265 if {![file isdirectory $_gitdir]} {
1266         catch {wm withdraw .}
1267         error_popup [strcat [mc "Git directory not found:"] "\n\n$_gitdir"]
1268         exit 1
1269 }
1270 # _gitdir exists, so try loading the config
1271 load_config 0
1272 apply_config
1273
1274 # v1.7.0 introduced --show-toplevel to return the canonical work-tree
1275 if {[package vcompare $_git_version 1.7.0] >= 0} {
1276         if { [is_Cygwin] } {
1277                 catch {set _gitworktree [exec cygpath --windows [git rev-parse --show-toplevel]]}
1278         } else {
1279                 set _gitworktree [git rev-parse --show-toplevel]
1280         }
1281 } else {
1282         # try to set work tree from environment, core.worktree or use
1283         # cdup to obtain a relative path to the top of the worktree. If
1284         # run from the top, the ./ prefix ensures normalize expands pwd.
1285         if {[catch { set _gitworktree $env(GIT_WORK_TREE) }]} {
1286                 set _gitworktree [get_config core.worktree]
1287                 if {$_gitworktree eq ""} {
1288                         set _gitworktree [file normalize ./[git rev-parse --show-cdup]]
1289                 }
1290         }
1291 }
1292
1293 if {$_prefix ne {}} {
1294         if {$_gitworktree eq {}} {
1295                 regsub -all {[^/]+/} $_prefix ../ cdup
1296         } else {
1297                 set cdup $_gitworktree
1298         }
1299         if {[catch {cd $cdup} err]} {
1300                 catch {wm withdraw .}
1301                 error_popup [strcat [mc "Cannot move to top of working directory:"] "\n\n$err"]
1302                 exit 1
1303         }
1304         set _gitworktree [pwd]
1305         unset cdup
1306 } elseif {![is_enabled bare]} {
1307         if {[is_bare]} {
1308                 catch {wm withdraw .}
1309                 error_popup [strcat [mc "Cannot use bare repository:"] "\n\n$_gitdir"]
1310                 exit 1
1311         }
1312         if {$_gitworktree eq {}} {
1313                 set _gitworktree [file dirname $_gitdir]
1314         }
1315         if {[catch {cd $_gitworktree} err]} {
1316                 catch {wm withdraw .}
1317                 error_popup [strcat [mc "No working directory"] " $_gitworktree:\n\n$err"]
1318                 exit 1
1319         }
1320         set _gitworktree [pwd]
1321 }
1322 set _reponame [file split [file normalize $_gitdir]]
1323 if {[lindex $_reponame end] eq {.git}} {
1324         set _reponame [lindex $_reponame end-1]
1325 } else {
1326         set _reponame [lindex $_reponame end]
1327 }
1328
1329 set env(GIT_DIR) $_gitdir
1330 set env(GIT_WORK_TREE) $_gitworktree
1331
1332 ######################################################################
1333 ##
1334 ## global init
1335
1336 set current_diff_path {}
1337 set current_diff_side {}
1338 set diff_actions [list]
1339
1340 set HEAD {}
1341 set PARENT {}
1342 set MERGE_HEAD [list]
1343 set commit_type {}
1344 set commit_type_is_amend 0
1345 set empty_tree {}
1346 set current_branch {}
1347 set is_detached 0
1348 set current_diff_path {}
1349 set is_3way_diff 0
1350 set is_submodule_diff 0
1351 set is_conflict_diff 0
1352 set diff_empty_count 0
1353 set last_revert {}
1354 set last_revert_enc {}
1355
1356 set nullid "0000000000000000000000000000000000000000"
1357 set nullid2 "0000000000000000000000000000000000000001"
1358
1359 ######################################################################
1360 ##
1361 ## task management
1362
1363 set rescan_active 0
1364 set diff_active 0
1365 set last_clicked {}
1366
1367 set disable_on_lock [list]
1368 set index_lock_type none
1369
1370 proc lock_index {type} {
1371         global index_lock_type disable_on_lock
1372
1373         if {$index_lock_type eq {none}} {
1374                 set index_lock_type $type
1375                 foreach w $disable_on_lock {
1376                         uplevel #0 $w disabled
1377                 }
1378                 return 1
1379         } elseif {$index_lock_type eq "begin-$type"} {
1380                 set index_lock_type $type
1381                 return 1
1382         }
1383         return 0
1384 }
1385
1386 proc unlock_index {} {
1387         global index_lock_type disable_on_lock
1388
1389         set index_lock_type none
1390         foreach w $disable_on_lock {
1391                 uplevel #0 $w normal
1392         }
1393 }
1394
1395 ######################################################################
1396 ##
1397 ## status
1398
1399 proc repository_state {ctvar hdvar mhvar} {
1400         global current_branch
1401         upvar $ctvar ct $hdvar hd $mhvar mh
1402
1403         set mh [list]
1404
1405         load_current_branch
1406         if {[catch {set hd [git rev-parse --verify HEAD]}]} {
1407                 set hd {}
1408                 set ct initial
1409                 return
1410         }
1411
1412         set merge_head [gitdir MERGE_HEAD]
1413         if {[file exists $merge_head]} {
1414                 set ct merge
1415                 set fd_mh [open $merge_head r]
1416                 while {[gets $fd_mh line] >= 0} {
1417                         lappend mh $line
1418                 }
1419                 close $fd_mh
1420                 return
1421         }
1422
1423         set ct normal
1424 }
1425
1426 proc PARENT {} {
1427         global PARENT empty_tree
1428
1429         set p [lindex $PARENT 0]
1430         if {$p ne {}} {
1431                 return $p
1432         }
1433         if {$empty_tree eq {}} {
1434                 set empty_tree [git mktree << {}]
1435         }
1436         return $empty_tree
1437 }
1438
1439 proc force_amend {} {
1440         global commit_type_is_amend
1441         global HEAD PARENT MERGE_HEAD commit_type
1442
1443         repository_state newType newHEAD newMERGE_HEAD
1444         set HEAD $newHEAD
1445         set PARENT $newHEAD
1446         set MERGE_HEAD $newMERGE_HEAD
1447         set commit_type $newType
1448
1449         set commit_type_is_amend 1
1450         do_select_commit_type
1451 }
1452
1453 proc rescan {after {honor_trustmtime 1}} {
1454         global HEAD PARENT MERGE_HEAD commit_type
1455         global ui_index ui_workdir ui_comm
1456         global rescan_active file_states
1457         global repo_config
1458
1459         if {$rescan_active > 0 || ![lock_index read]} return
1460
1461         repository_state newType newHEAD newMERGE_HEAD
1462         if {[string match amend* $commit_type]
1463                 && $newType eq {normal}
1464                 && $newHEAD eq $HEAD} {
1465         } else {
1466                 set HEAD $newHEAD
1467                 set PARENT $newHEAD
1468                 set MERGE_HEAD $newMERGE_HEAD
1469                 set commit_type $newType
1470         }
1471
1472         array unset file_states
1473
1474         if {!$::GITGUI_BCK_exists &&
1475                 (![$ui_comm edit modified]
1476                 || [string trim [$ui_comm get 0.0 end]] eq {})} {
1477                 if {[string match amend* $commit_type]} {
1478                 } elseif {[load_message GITGUI_MSG utf-8]} {
1479                 } elseif {[run_prepare_commit_msg_hook]} {
1480                 } elseif {[load_message MERGE_MSG]} {
1481                 } elseif {[load_message SQUASH_MSG]} {
1482                 }
1483                 $ui_comm edit reset
1484                 $ui_comm edit modified false
1485         }
1486
1487         if {$honor_trustmtime && $repo_config(gui.trustmtime) eq {true}} {
1488                 rescan_stage2 {} $after
1489         } else {
1490                 set rescan_active 1
1491                 ui_status [mc "Refreshing file status..."]
1492                 set fd_rf [git_read update-index \
1493                         -q \
1494                         --unmerged \
1495                         --ignore-missing \
1496                         --refresh \
1497                         ]
1498                 fconfigure $fd_rf -blocking 0 -translation binary
1499                 fileevent $fd_rf readable \
1500                         [list rescan_stage2 $fd_rf $after]
1501         }
1502 }
1503
1504 if {[is_Cygwin]} {
1505         set is_git_info_exclude {}
1506         proc have_info_exclude {} {
1507                 global is_git_info_exclude
1508
1509                 if {$is_git_info_exclude eq {}} {
1510                         if {[catch {exec test -f [gitdir info exclude]}]} {
1511                                 set is_git_info_exclude 0
1512                         } else {
1513                                 set is_git_info_exclude 1
1514                         }
1515                 }
1516                 return $is_git_info_exclude
1517         }
1518 } else {
1519         proc have_info_exclude {} {
1520                 return [file readable [gitdir info exclude]]
1521         }
1522 }
1523
1524 proc rescan_stage2 {fd after} {
1525         global rescan_active buf_rdi buf_rdf buf_rlo
1526
1527         if {$fd ne {}} {
1528                 read $fd
1529                 if {![eof $fd]} return
1530                 close $fd
1531         }
1532
1533         if {[package vcompare $::_git_version 1.6.3] >= 0} {
1534                 set ls_others [list --exclude-standard]
1535         } else {
1536                 set ls_others [list --exclude-per-directory=.gitignore]
1537                 if {[have_info_exclude]} {
1538                         lappend ls_others "--exclude-from=[gitdir info exclude]"
1539                 }
1540                 set user_exclude [get_config core.excludesfile]
1541                 if {$user_exclude ne {} && [file readable $user_exclude]} {
1542                         lappend ls_others "--exclude-from=[file normalize $user_exclude]"
1543                 }
1544         }
1545
1546         set buf_rdi {}
1547         set buf_rdf {}
1548         set buf_rlo {}
1549
1550         set rescan_active 2
1551         ui_status [mc "Scanning for modified files ..."]
1552         if {[git-version >= "1.7.2"]} {
1553                 set fd_di [git_read diff-index --cached --ignore-submodules=dirty -z [PARENT]]
1554         } else {
1555                 set fd_di [git_read diff-index --cached -z [PARENT]]
1556         }
1557         set fd_df [git_read diff-files -z]
1558
1559         fconfigure $fd_di -blocking 0 -translation binary -encoding binary
1560         fconfigure $fd_df -blocking 0 -translation binary -encoding binary
1561
1562         fileevent $fd_di readable [list read_diff_index $fd_di $after]
1563         fileevent $fd_df readable [list read_diff_files $fd_df $after]
1564
1565         if {[is_config_true gui.displayuntracked]} {
1566                 set fd_lo [eval git_read ls-files --others -z $ls_others]
1567                 fconfigure $fd_lo -blocking 0 -translation binary -encoding binary
1568                 fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
1569                 incr rescan_active
1570         }
1571 }
1572
1573 proc load_message {file {encoding {}}} {
1574         global ui_comm
1575
1576         set f [gitdir $file]
1577         if {[file isfile $f]} {
1578                 if {[catch {set fd [open $f r]}]} {
1579                         return 0
1580                 }
1581                 fconfigure $fd -eofchar {}
1582                 if {$encoding ne {}} {
1583                         fconfigure $fd -encoding $encoding
1584                 }
1585                 set content [string trim [read $fd]]
1586                 close $fd
1587                 regsub -all -line {[ \r\t]+$} $content {} content
1588                 $ui_comm delete 0.0 end
1589                 $ui_comm insert end $content
1590                 return 1
1591         }
1592         return 0
1593 }
1594
1595 proc run_prepare_commit_msg_hook {} {
1596         global pch_error
1597
1598         # prepare-commit-msg requires PREPARE_COMMIT_MSG exist.  From git-gui
1599         # it will be .git/MERGE_MSG (merge), .git/SQUASH_MSG (squash), or an
1600         # empty file but existent file.
1601
1602         set fd_pcm [open [gitdir PREPARE_COMMIT_MSG] a]
1603
1604         if {[file isfile [gitdir MERGE_MSG]]} {
1605                 set pcm_source "merge"
1606                 set fd_mm [open [gitdir MERGE_MSG] r]
1607                 fconfigure $fd_mm -encoding utf-8
1608                 puts -nonewline $fd_pcm [read $fd_mm]
1609                 close $fd_mm
1610         } elseif {[file isfile [gitdir SQUASH_MSG]]} {
1611                 set pcm_source "squash"
1612                 set fd_sm [open [gitdir SQUASH_MSG] r]
1613                 fconfigure $fd_sm -encoding utf-8
1614                 puts -nonewline $fd_pcm [read $fd_sm]
1615                 close $fd_sm
1616         } else {
1617                 set pcm_source ""
1618         }
1619
1620         close $fd_pcm
1621
1622         set fd_ph [githook_read prepare-commit-msg \
1623                         [gitdir PREPARE_COMMIT_MSG] $pcm_source]
1624         if {$fd_ph eq {}} {
1625                 catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1626                 return 0;
1627         }
1628
1629         ui_status [mc "Calling prepare-commit-msg hook..."]
1630         set pch_error {}
1631
1632         fconfigure $fd_ph -blocking 0 -translation binary -eofchar {}
1633         fileevent $fd_ph readable \
1634                 [list prepare_commit_msg_hook_wait $fd_ph]
1635
1636         return 1;
1637 }
1638
1639 proc prepare_commit_msg_hook_wait {fd_ph} {
1640         global pch_error
1641
1642         append pch_error [read $fd_ph]
1643         fconfigure $fd_ph -blocking 1
1644         if {[eof $fd_ph]} {
1645                 if {[catch {close $fd_ph}]} {
1646                         ui_status [mc "Commit declined by prepare-commit-msg hook."]
1647                         hook_failed_popup prepare-commit-msg $pch_error
1648                         catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1649                         exit 1
1650                 } else {
1651                         load_message PREPARE_COMMIT_MSG
1652                 }
1653                 set pch_error {}
1654                 catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1655                 return
1656         }
1657         fconfigure $fd_ph -blocking 0
1658         catch {file delete [gitdir PREPARE_COMMIT_MSG]}
1659 }
1660
1661 proc read_diff_index {fd after} {
1662         global buf_rdi
1663
1664         append buf_rdi [read $fd]
1665         set c 0
1666         set n [string length $buf_rdi]
1667         while {$c < $n} {
1668                 set z1 [string first "\0" $buf_rdi $c]
1669                 if {$z1 == -1} break
1670                 incr z1
1671                 set z2 [string first "\0" $buf_rdi $z1]
1672                 if {$z2 == -1} break
1673
1674                 incr c
1675                 set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
1676                 set p [string range $buf_rdi $z1 [expr {$z2 - 1}]]
1677                 merge_state \
1678                         [encoding convertfrom utf-8 $p] \
1679                         [lindex $i 4]? \
1680                         [list [lindex $i 0] [lindex $i 2]] \
1681                         [list]
1682                 set c $z2
1683                 incr c
1684         }
1685         if {$c < $n} {
1686                 set buf_rdi [string range $buf_rdi $c end]
1687         } else {
1688                 set buf_rdi {}
1689         }
1690
1691         rescan_done $fd buf_rdi $after
1692 }
1693
1694 proc read_diff_files {fd after} {
1695         global buf_rdf
1696
1697         append buf_rdf [read $fd]
1698         set c 0
1699         set n [string length $buf_rdf]
1700         while {$c < $n} {
1701                 set z1 [string first "\0" $buf_rdf $c]
1702                 if {$z1 == -1} break
1703                 incr z1
1704                 set z2 [string first "\0" $buf_rdf $z1]
1705                 if {$z2 == -1} break
1706
1707                 incr c
1708                 set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
1709                 set p [string range $buf_rdf $z1 [expr {$z2 - 1}]]
1710                 merge_state \
1711                         [encoding convertfrom utf-8 $p] \
1712                         ?[lindex $i 4] \
1713                         [list] \
1714                         [list [lindex $i 0] [lindex $i 2]]
1715                 set c $z2
1716                 incr c
1717         }
1718         if {$c < $n} {
1719                 set buf_rdf [string range $buf_rdf $c end]
1720         } else {
1721                 set buf_rdf {}
1722         }
1723
1724         rescan_done $fd buf_rdf $after
1725 }
1726
1727 proc read_ls_others {fd after} {
1728         global buf_rlo
1729
1730         append buf_rlo [read $fd]
1731         set pck [split $buf_rlo "\0"]
1732         set buf_rlo [lindex $pck end]
1733         foreach p [lrange $pck 0 end-1] {
1734                 set p [encoding convertfrom utf-8 $p]
1735                 if {[string index $p end] eq {/}} {
1736                         set p [string range $p 0 end-1]
1737                 }
1738                 merge_state $p ?O
1739         }
1740         rescan_done $fd buf_rlo $after
1741 }
1742
1743 proc rescan_done {fd buf after} {
1744         global rescan_active current_diff_path
1745         global file_states repo_config
1746         upvar $buf to_clear
1747
1748         if {![eof $fd]} return
1749         set to_clear {}
1750         close $fd
1751         if {[incr rescan_active -1] > 0} return
1752
1753         prune_selection
1754         unlock_index
1755         display_all_files
1756         if {$current_diff_path ne {}} { reshow_diff $after }
1757         if {$current_diff_path eq {}} { select_first_diff $after }
1758 }
1759
1760 proc prune_selection {} {
1761         global file_states selected_paths
1762
1763         foreach path [array names selected_paths] {
1764                 if {[catch {set still_here $file_states($path)}]} {
1765                         unset selected_paths($path)
1766                 }
1767         }
1768 }
1769
1770 ######################################################################
1771 ##
1772 ## ui helpers
1773
1774 proc mapicon {w state path} {
1775         global all_icons
1776
1777         if {[catch {set r $all_icons($state$w)}]} {
1778                 puts "error: no icon for $w state={$state} $path"
1779                 return file_plain
1780         }
1781         return $r
1782 }
1783
1784 proc mapdesc {state path} {
1785         global all_descs
1786
1787         if {[catch {set r $all_descs($state)}]} {
1788                 puts "error: no desc for state={$state} $path"
1789                 return $state
1790         }
1791         return $r
1792 }
1793
1794 proc ui_status {msg} {
1795         global main_status
1796         if {[info exists main_status]} {
1797                 $main_status show $msg
1798         }
1799 }
1800
1801 proc ui_ready {{test {}}} {
1802         global main_status
1803         if {[info exists main_status]} {
1804                 $main_status show [mc "Ready."] $test
1805         }
1806 }
1807
1808 proc escape_path {path} {
1809         regsub -all {\\} $path "\\\\" path
1810         regsub -all "\n" $path "\\n" path
1811         return $path
1812 }
1813
1814 proc short_path {path} {
1815         return [escape_path [lindex [file split $path] end]]
1816 }
1817
1818 set next_icon_id 0
1819 set null_sha1 [string repeat 0 40]
1820
1821 proc merge_state {path new_state {head_info {}} {index_info {}}} {
1822         global file_states next_icon_id null_sha1
1823
1824         set s0 [string index $new_state 0]
1825         set s1 [string index $new_state 1]
1826
1827         if {[catch {set info $file_states($path)}]} {
1828                 set state __
1829                 set icon n[incr next_icon_id]
1830         } else {
1831                 set state [lindex $info 0]
1832                 set icon [lindex $info 1]
1833                 if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1834                 if {$index_info eq {}} {set index_info [lindex $info 3]}
1835         }
1836
1837         if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1838         elseif {$s0 eq {_}} {set s0 _}
1839
1840         if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1841         elseif {$s1 eq {_}} {set s1 _}
1842
1843         if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1844                 set head_info [list 0 $null_sha1]
1845         } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1846                 && $head_info eq {}} {
1847                 set head_info $index_info
1848         } elseif {$s0 eq {_} && [string index $state 0] ne {_}} {
1849                 set index_info $head_info
1850                 set head_info {}
1851         }
1852
1853         set file_states($path) [list $s0$s1 $icon \
1854                 $head_info $index_info \
1855                 ]
1856         return $state
1857 }
1858
1859 proc display_file_helper {w path icon_name old_m new_m} {
1860         global file_lists
1861
1862         if {$new_m eq {_}} {
1863                 set lno [lsearch -sorted -exact $file_lists($w) $path]
1864                 if {$lno >= 0} {
1865                         set file_lists($w) [lreplace $file_lists($w) $lno $lno]
1866                         incr lno
1867                         $w conf -state normal
1868                         $w delete $lno.0 [expr {$lno + 1}].0
1869                         $w conf -state disabled
1870                 }
1871         } elseif {$old_m eq {_} && $new_m ne {_}} {
1872                 lappend file_lists($w) $path
1873                 set file_lists($w) [lsort -unique $file_lists($w)]
1874                 set lno [lsearch -sorted -exact $file_lists($w) $path]
1875                 incr lno
1876                 $w conf -state normal
1877                 $w image create $lno.0 \
1878                         -align center -padx 5 -pady 1 \
1879                         -name $icon_name \
1880                         -image [mapicon $w $new_m $path]
1881                 $w insert $lno.1 "[escape_path $path]\n"
1882                 $w conf -state disabled
1883         } elseif {$old_m ne $new_m} {
1884                 $w conf -state normal
1885                 $w image conf $icon_name -image [mapicon $w $new_m $path]
1886                 $w conf -state disabled
1887         }
1888 }
1889
1890 proc display_file {path state} {
1891         global file_states selected_paths
1892         global ui_index ui_workdir
1893
1894         set old_m [merge_state $path $state]
1895         set s $file_states($path)
1896         set new_m [lindex $s 0]
1897         set icon_name [lindex $s 1]
1898
1899         set o [string index $old_m 0]
1900         set n [string index $new_m 0]
1901         if {$o eq {U}} {
1902                 set o _
1903         }
1904         if {$n eq {U}} {
1905                 set n _
1906         }
1907         display_file_helper     $ui_index $path $icon_name $o $n
1908
1909         if {[string index $old_m 0] eq {U}} {
1910                 set o U
1911         } else {
1912                 set o [string index $old_m 1]
1913         }
1914         if {[string index $new_m 0] eq {U}} {
1915                 set n U
1916         } else {
1917                 set n [string index $new_m 1]
1918         }
1919         display_file_helper     $ui_workdir $path $icon_name $o $n
1920
1921         if {$new_m eq {__}} {
1922                 unset file_states($path)
1923                 catch {unset selected_paths($path)}
1924         }
1925 }
1926
1927 proc display_all_files_helper {w path icon_name m} {
1928         global file_lists
1929
1930         lappend file_lists($w) $path
1931         set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1932         $w image create end \
1933                 -align center -padx 5 -pady 1 \
1934                 -name $icon_name \
1935                 -image [mapicon $w $m $path]
1936         $w insert end "[escape_path $path]\n"
1937 }
1938
1939 set files_warning 0
1940 proc display_all_files {} {
1941         global ui_index ui_workdir
1942         global file_states file_lists
1943         global last_clicked
1944         global files_warning
1945
1946         $ui_index conf -state normal
1947         $ui_workdir conf -state normal
1948
1949         $ui_index delete 0.0 end
1950         $ui_workdir delete 0.0 end
1951         set last_clicked {}
1952
1953         set file_lists($ui_index) [list]
1954         set file_lists($ui_workdir) [list]
1955
1956         set to_display [lsort [array names file_states]]
1957         set display_limit [get_config gui.maxfilesdisplayed]
1958         set displayed 0
1959         foreach path $to_display {
1960                 set s $file_states($path)
1961                 set m [lindex $s 0]
1962                 set icon_name [lindex $s 1]
1963
1964                 if {$displayed > $display_limit && [string index $m 1] eq {O} } {
1965                         if {!$files_warning} {
1966                                 # do not repeatedly warn:
1967                                 set files_warning 1
1968                                 info_popup [mc "Display limit (gui.maxfilesdisplayed = %s) reached, not showing all %s files." \
1969                                         $display_limit [llength $to_display]]
1970                         }
1971                         continue
1972                 }
1973
1974                 set s [string index $m 0]
1975                 if {$s ne {U} && $s ne {_}} {
1976                         display_all_files_helper $ui_index $path \
1977                                 $icon_name $s
1978                 }
1979
1980                 if {[string index $m 0] eq {U}} {
1981                         set s U
1982                 } else {
1983                         set s [string index $m 1]
1984                 }
1985                 if {$s ne {_}} {
1986                         display_all_files_helper $ui_workdir $path \
1987                                 $icon_name $s
1988                         incr displayed
1989                 }
1990         }
1991
1992         $ui_index conf -state disabled
1993         $ui_workdir conf -state disabled
1994 }
1995
1996 ######################################################################
1997 ##
1998 ## icons
1999
2000 set filemask {
2001 #define mask_width 14
2002 #define mask_height 15
2003 static unsigned char mask_bits[] = {
2004    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2005    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
2006    0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
2007 }
2008
2009 image create bitmap file_plain -background white -foreground black -data {
2010 #define plain_width 14
2011 #define plain_height 15
2012 static unsigned char plain_bits[] = {
2013    0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2014    0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
2015    0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2016 } -maskdata $filemask
2017
2018 image create bitmap file_mod -background white -foreground blue -data {
2019 #define mod_width 14
2020 #define mod_height 15
2021 static unsigned char mod_bits[] = {
2022    0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
2023    0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2024    0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2025 } -maskdata $filemask
2026
2027 image create bitmap file_fulltick -background white -foreground "#007000" -data {
2028 #define file_fulltick_width 14
2029 #define file_fulltick_height 15
2030 static unsigned char file_fulltick_bits[] = {
2031    0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
2032    0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
2033    0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2034 } -maskdata $filemask
2035
2036 image create bitmap file_question -background white -foreground black -data {
2037 #define file_question_width 14
2038 #define file_question_height 15
2039 static unsigned char file_question_bits[] = {
2040    0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
2041    0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
2042    0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2043 } -maskdata $filemask
2044
2045 image create bitmap file_removed -background white -foreground red -data {
2046 #define file_removed_width 14
2047 #define file_removed_height 15
2048 static unsigned char file_removed_bits[] = {
2049    0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
2050    0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
2051    0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
2052 } -maskdata $filemask
2053
2054 image create bitmap file_merge -background white -foreground blue -data {
2055 #define file_merge_width 14
2056 #define file_merge_height 15
2057 static unsigned char file_merge_bits[] = {
2058    0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
2059    0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
2060    0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
2061 } -maskdata $filemask
2062
2063 image create bitmap file_statechange -background white -foreground green -data {
2064 #define file_statechange_width 14
2065 #define file_statechange_height 15
2066 static unsigned char file_statechange_bits[] = {
2067    0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x62, 0x10,
2068    0x62, 0x10, 0xba, 0x11, 0xba, 0x11, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10,
2069    0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
2070 } -maskdata $filemask
2071
2072 set ui_index .vpane.files.index.list
2073 set ui_workdir .vpane.files.workdir.list
2074
2075 set all_icons(_$ui_index)   file_plain
2076 set all_icons(A$ui_index)   file_plain
2077 set all_icons(M$ui_index)   file_fulltick
2078 set all_icons(D$ui_index)   file_removed
2079 set all_icons(U$ui_index)   file_merge
2080 set all_icons(T$ui_index)   file_statechange
2081
2082 set all_icons(_$ui_workdir) file_plain
2083 set all_icons(M$ui_workdir) file_mod
2084 set all_icons(D$ui_workdir) file_question
2085 set all_icons(U$ui_workdir) file_merge
2086 set all_icons(O$ui_workdir) file_plain
2087 set all_icons(T$ui_workdir) file_statechange
2088
2089 set max_status_desc 0
2090 foreach i {
2091                 {__ {mc "Unmodified"}}
2092
2093                 {_M {mc "Modified, not staged"}}
2094                 {M_ {mc "Staged for commit"}}
2095                 {MM {mc "Portions staged for commit"}}
2096                 {MD {mc "Staged for commit, missing"}}
2097
2098                 {_T {mc "File type changed, not staged"}}
2099                 {MT {mc "File type changed, old type staged for commit"}}
2100                 {AT {mc "File type changed, old type staged for commit"}}
2101                 {T_ {mc "File type changed, staged"}}
2102                 {TM {mc "File type change staged, modification not staged"}}
2103                 {TD {mc "File type change staged, file missing"}}
2104
2105                 {_O {mc "Untracked, not staged"}}
2106                 {A_ {mc "Staged for commit"}}
2107                 {AM {mc "Portions staged for commit"}}
2108                 {AD {mc "Staged for commit, missing"}}
2109
2110                 {_D {mc "Missing"}}
2111                 {D_ {mc "Staged for removal"}}
2112                 {DO {mc "Staged for removal, still present"}}
2113
2114                 {_U {mc "Requires merge resolution"}}
2115                 {U_ {mc "Requires merge resolution"}}
2116                 {UU {mc "Requires merge resolution"}}
2117                 {UM {mc "Requires merge resolution"}}
2118                 {UD {mc "Requires merge resolution"}}
2119                 {UT {mc "Requires merge resolution"}}
2120         } {
2121         set text [eval [lindex $i 1]]
2122         if {$max_status_desc < [string length $text]} {
2123                 set max_status_desc [string length $text]
2124         }
2125         set all_descs([lindex $i 0]) $text
2126 }
2127 unset i
2128
2129 ######################################################################
2130 ##
2131 ## util
2132
2133 proc scrollbar2many {list mode args} {
2134         foreach w $list {eval $w $mode $args}
2135 }
2136
2137 proc many2scrollbar {list mode sb top bottom} {
2138         $sb set $top $bottom
2139         foreach w $list {$w $mode moveto $top}
2140 }
2141
2142 proc incr_font_size {font {amt 1}} {
2143         set sz [font configure $font -size]
2144         incr sz $amt
2145         font configure $font -size $sz
2146         font configure ${font}bold -size $sz
2147         font configure ${font}italic -size $sz
2148 }
2149
2150 ######################################################################
2151 ##
2152 ## ui commands
2153
2154 set starting_gitk_msg [mc "Starting gitk... please wait..."]
2155
2156 proc do_gitk {revs {is_submodule false}} {
2157         global current_diff_path file_states current_diff_side ui_index
2158         global _gitdir _gitworktree
2159
2160         # -- Always start gitk through whatever we were loaded with.  This
2161         #    lets us bypass using shell process on Windows systems.
2162         #
2163         set exe [_which gitk -script]
2164         set cmd [list [info nameofexecutable] $exe]
2165         if {$exe eq {}} {
2166                 error_popup [mc "Couldn't find gitk in PATH"]
2167         } else {
2168                 global env
2169
2170                 set pwd [pwd]
2171
2172                 if {!$is_submodule} {
2173                         if {![is_bare]} {
2174                                 cd $_gitworktree
2175                         }
2176                 } else {
2177                         cd $current_diff_path
2178                         if {$revs eq {--}} {
2179                                 set s $file_states($current_diff_path)
2180                                 set old_sha1 {}
2181                                 set new_sha1 {}
2182                                 switch -glob -- [lindex $s 0] {
2183                                 M_ { set old_sha1 [lindex [lindex $s 2] 1] }
2184                                 _M { set old_sha1 [lindex [lindex $s 3] 1] }
2185                                 MM {
2186                                         if {$current_diff_side eq $ui_index} {
2187                                                 set old_sha1 [lindex [lindex $s 2] 1]
2188                                                 set new_sha1 [lindex [lindex $s 3] 1]
2189                                         } else {
2190                                                 set old_sha1 [lindex [lindex $s 3] 1]
2191                                         }
2192                                 }
2193                                 }
2194                                 set revs $old_sha1...$new_sha1
2195                         }
2196                         # GIT_DIR and GIT_WORK_TREE for the submodule are not the ones
2197                         # we've been using for the main repository, so unset them.
2198                         # TODO we could make life easier (start up faster?) for gitk
2199                         # by setting these to the appropriate values to allow gitk
2200                         # to skip the heuristics to find their proper value
2201                         unset env(GIT_DIR)
2202                         unset env(GIT_WORK_TREE)
2203                 }
2204                 eval exec $cmd $revs "--" "--" &
2205
2206                 set env(GIT_DIR) $_gitdir
2207                 set env(GIT_WORK_TREE) $_gitworktree
2208                 cd $pwd
2209
2210                 ui_status $::starting_gitk_msg
2211                 after 10000 {
2212                         ui_ready $starting_gitk_msg
2213                 }
2214         }
2215 }
2216
2217 proc do_git_gui {} {
2218         global current_diff_path
2219
2220         # -- Always start git gui through whatever we were loaded with.  This
2221         #    lets us bypass using shell process on Windows systems.
2222         #
2223         set exe [list [_which git]]
2224         if {$exe eq {}} {
2225                 error_popup [mc "Couldn't find git gui in PATH"]
2226         } else {
2227                 global env
2228                 global _gitdir _gitworktree
2229
2230                 # see note in do_gitk about unsetting these vars when
2231                 # running tools in a submodule
2232                 unset env(GIT_DIR)
2233                 unset env(GIT_WORK_TREE)
2234
2235                 set pwd [pwd]
2236                 cd $current_diff_path
2237
2238                 eval exec $exe gui &
2239
2240                 set env(GIT_DIR) $_gitdir
2241                 set env(GIT_WORK_TREE) $_gitworktree
2242                 cd $pwd
2243
2244                 ui_status $::starting_gitk_msg
2245                 after 10000 {
2246                         ui_ready $starting_gitk_msg
2247                 }
2248         }
2249 }
2250
2251 proc do_explore {} {
2252         global _gitworktree
2253         set explorer {}
2254         if {[is_Cygwin] || [is_Windows]} {
2255                 set explorer "explorer.exe"
2256         } elseif {[is_MacOSX]} {
2257                 set explorer "open"
2258         } else {
2259                 # freedesktop.org-conforming system is our best shot
2260                 set explorer "xdg-open"
2261         }
2262         eval exec $explorer [list [file nativename $_gitworktree]] &
2263 }
2264
2265 set is_quitting 0
2266 set ret_code    1
2267
2268 proc terminate_me {win} {
2269         global ret_code
2270         if {$win ne {.}} return
2271         exit $ret_code
2272 }
2273
2274 proc do_quit {{rc {1}}} {
2275         global ui_comm is_quitting repo_config commit_type
2276         global GITGUI_BCK_exists GITGUI_BCK_i
2277         global ui_comm_spell
2278         global ret_code use_ttk
2279
2280         if {$is_quitting} return
2281         set is_quitting 1
2282
2283         if {[winfo exists $ui_comm]} {
2284                 # -- Stash our current commit buffer.
2285                 #
2286                 set save [gitdir GITGUI_MSG]
2287                 if {$GITGUI_BCK_exists && ![$ui_comm edit modified]} {
2288                         file rename -force [gitdir GITGUI_BCK] $save
2289                         set GITGUI_BCK_exists 0
2290                 } else {
2291                         set msg [string trim [$ui_comm get 0.0 end]]
2292                         regsub -all -line {[ \r\t]+$} $msg {} msg
2293                         if {(![string match amend* $commit_type]
2294                                 || [$ui_comm edit modified])
2295                                 && $msg ne {}} {
2296                                 catch {
2297                                         set fd [open $save w]
2298                                         fconfigure $fd -encoding utf-8
2299                                         puts -nonewline $fd $msg
2300                                         close $fd
2301                                 }
2302                         } else {
2303                                 catch {file delete $save}
2304                         }
2305                 }
2306
2307                 # -- Cancel our spellchecker if its running.
2308                 #
2309                 if {[info exists ui_comm_spell]} {
2310                         $ui_comm_spell stop
2311                 }
2312
2313                 # -- Remove our editor backup, its not needed.
2314                 #
2315                 after cancel $GITGUI_BCK_i
2316                 if {$GITGUI_BCK_exists} {
2317                         catch {file delete [gitdir GITGUI_BCK]}
2318                 }
2319
2320                 # -- Stash our current window geometry into this repository.
2321                 #
2322                 set cfg_wmstate [wm state .]
2323                 if {[catch {set rc_wmstate $repo_config(gui.wmstate)}]} {
2324                         set rc_wmstate {}
2325                 }
2326                 if {$cfg_wmstate ne $rc_wmstate} {
2327                         catch {git config gui.wmstate $cfg_wmstate}
2328                 }
2329                 if {$cfg_wmstate eq {zoomed}} {
2330                         # on Windows wm geometry will lie about window
2331                         # position (but not size) when window is zoomed
2332                         # restore the window before querying wm geometry
2333                         wm state . normal
2334                 }
2335                 set cfg_geometry [list]
2336                 lappend cfg_geometry [wm geometry .]
2337                 if {$use_ttk} {
2338                         lappend cfg_geometry [.vpane sashpos 0]
2339                         lappend cfg_geometry [.vpane.files sashpos 0]
2340                 } else {
2341                         lappend cfg_geometry [lindex [.vpane sash coord 0] 0]
2342                         lappend cfg_geometry [lindex [.vpane.files sash coord 0] 1]
2343                 }
2344                 if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
2345                         set rc_geometry {}
2346                 }
2347                 if {$cfg_geometry ne $rc_geometry} {
2348                         catch {git config gui.geometry $cfg_geometry}
2349                 }
2350         }
2351
2352         set ret_code $rc
2353
2354         # Briefly enable send again, working around Tk bug
2355         # http://sourceforge.net/tracker/?func=detail&atid=112997&aid=1821174&group_id=12997
2356         tk appname [appname]
2357
2358         destroy .
2359 }
2360
2361 proc do_rescan {} {
2362         rescan ui_ready
2363 }
2364
2365 proc ui_do_rescan {} {
2366         rescan {force_first_diff ui_ready}
2367 }
2368
2369 proc do_commit {} {
2370         commit_tree
2371 }
2372
2373 proc next_diff {{after {}}} {
2374         global next_diff_p next_diff_w next_diff_i
2375         show_diff $next_diff_p $next_diff_w {} {} $after
2376 }
2377
2378 proc find_anchor_pos {lst name} {
2379         set lid [lsearch -sorted -exact $lst $name]
2380
2381         if {$lid == -1} {
2382                 set lid 0
2383                 foreach lname $lst {
2384                         if {$lname >= $name} break
2385                         incr lid
2386                 }
2387         }
2388
2389         return $lid
2390 }
2391
2392 proc find_file_from {flist idx delta path mmask} {
2393         global file_states
2394
2395         set len [llength $flist]
2396         while {$idx >= 0 && $idx < $len} {
2397                 set name [lindex $flist $idx]
2398
2399                 if {$name ne $path && [info exists file_states($name)]} {
2400                         set state [lindex $file_states($name) 0]
2401
2402                         if {$mmask eq {} || [regexp $mmask $state]} {
2403                                 return $idx
2404                         }
2405                 }
2406
2407                 incr idx $delta
2408         }
2409
2410         return {}
2411 }
2412
2413 proc find_next_diff {w path {lno {}} {mmask {}}} {
2414         global next_diff_p next_diff_w next_diff_i
2415         global file_lists ui_index ui_workdir
2416
2417         set flist $file_lists($w)
2418         if {$lno eq {}} {
2419                 set lno [find_anchor_pos $flist $path]
2420         } else {
2421                 incr lno -1
2422         }
2423
2424         if {$mmask ne {} && ![regexp {(^\^)|(\$$)} $mmask]} {
2425                 if {$w eq $ui_index} {
2426                         set mmask "^$mmask"
2427                 } else {
2428                         set mmask "$mmask\$"
2429                 }
2430         }
2431
2432         set idx [find_file_from $flist $lno 1 $path $mmask]
2433         if {$idx eq {}} {
2434                 incr lno -1
2435                 set idx [find_file_from $flist $lno -1 $path $mmask]
2436         }
2437
2438         if {$idx ne {}} {
2439                 set next_diff_w $w
2440                 set next_diff_p [lindex $flist $idx]
2441                 set next_diff_i [expr {$idx+1}]
2442                 return 1
2443         } else {
2444                 return 0
2445         }
2446 }
2447
2448 proc next_diff_after_action {w path {lno {}} {mmask {}}} {
2449         global current_diff_path
2450
2451         if {$path ne $current_diff_path} {
2452                 return {}
2453         } elseif {[find_next_diff $w $path $lno $mmask]} {
2454                 return {next_diff;}
2455         } else {
2456                 return {reshow_diff;}
2457         }
2458 }
2459
2460 proc select_first_diff {after} {
2461         global ui_workdir
2462
2463         if {[find_next_diff $ui_workdir {} 1 {^_?U}] ||
2464             [find_next_diff $ui_workdir {} 1 {[^O]$}]} {
2465                 next_diff $after
2466         } else {
2467                 uplevel #0 $after
2468         }
2469 }
2470
2471 proc force_first_diff {after} {
2472         global ui_workdir current_diff_path file_states
2473
2474         if {[info exists file_states($current_diff_path)]} {
2475                 set state [lindex $file_states($current_diff_path) 0]
2476         } else {
2477                 set state {OO}
2478         }
2479
2480         set reselect 0
2481         if {[string first {U} $state] >= 0} {
2482                 # Already a conflict, do nothing
2483         } elseif {[find_next_diff $ui_workdir $current_diff_path {} {^_?U}]} {
2484                 set reselect 1
2485         } elseif {[string index $state 1] ne {O}} {
2486                 # Already a diff & no conflicts, do nothing
2487         } elseif {[find_next_diff $ui_workdir $current_diff_path {} {[^O]$}]} {
2488                 set reselect 1
2489         }
2490
2491         if {$reselect} {
2492                 next_diff $after
2493         } else {
2494                 uplevel #0 $after
2495         }
2496 }
2497
2498 proc toggle_or_diff {mode w args} {
2499         global file_states file_lists current_diff_path ui_index ui_workdir
2500         global last_clicked selected_paths file_lists_last_clicked
2501
2502         if {$mode eq "click"} {
2503                 foreach {x y} $args break
2504                 set pos [split [$w index @$x,$y] .]
2505                 foreach {lno col} $pos break
2506         } else {
2507                 if {$last_clicked ne {}} {
2508                         set lno [lindex $last_clicked 1]
2509                 } else {
2510                         set lno [expr {int([lindex [$w tag ranges in_diff] 0])}]
2511                 }
2512                 if {$mode eq "toggle"} {
2513                         set col 0; set y 2
2514                 } else {
2515                         incr lno [expr {$mode eq "up" ? -1 : 1}]
2516                         set col 1
2517                 }
2518         }
2519
2520         set path [lindex $file_lists($w) [expr {$lno - 1}]]
2521         if {$path eq {}} {
2522                 set last_clicked {}
2523                 return
2524         }
2525
2526         set last_clicked [list $w $lno]
2527         focus $w
2528         array unset selected_paths
2529         $ui_index tag remove in_sel 0.0 end
2530         $ui_workdir tag remove in_sel 0.0 end
2531
2532         set file_lists_last_clicked($w) $path
2533
2534         # Determine the state of the file
2535         if {[info exists file_states($path)]} {
2536                 set state [lindex $file_states($path) 0]
2537         } else {
2538                 set state {__}
2539         }
2540
2541         # Restage the file, or simply show the diff
2542         if {$col == 0 && $y > 1} {
2543                 # Conflicts need special handling
2544                 if {[string first {U} $state] >= 0} {
2545                         # $w must always be $ui_workdir, but...
2546                         if {$w ne $ui_workdir} { set lno {} }
2547                         merge_stage_workdir $path $lno
2548                         return
2549                 }
2550
2551                 if {[string index $state 1] eq {O}} {
2552                         set mmask {}
2553                 } else {
2554                         set mmask {[^O]}
2555                 }
2556
2557                 set after [next_diff_after_action $w $path $lno $mmask]
2558
2559                 if {$w eq $ui_index} {
2560                         update_indexinfo \
2561                                 "Unstaging [short_path $path] from commit" \
2562                                 [list $path] \
2563                                 [concat $after [list ui_ready]]
2564                 } elseif {$w eq $ui_workdir} {
2565                         update_index \
2566                                 "Adding [short_path $path]" \
2567                                 [list $path] \
2568                                 [concat $after [list ui_ready]]
2569                 }
2570         } else {
2571                 set selected_paths($path) 1
2572                 show_diff $path $w $lno
2573         }
2574 }
2575
2576 proc add_one_to_selection {w x y} {
2577         global file_lists last_clicked selected_paths
2578
2579         set lno [lindex [split [$w index @$x,$y] .] 0]
2580         set path [lindex $file_lists($w) [expr {$lno - 1}]]
2581         if {$path eq {}} {
2582                 set last_clicked {}
2583                 return
2584         }
2585
2586         if {$last_clicked ne {}
2587                 && [lindex $last_clicked 0] ne $w} {
2588                 array unset selected_paths
2589                 [lindex $last_clicked 0] tag remove in_sel 0.0 end
2590         }
2591
2592         set last_clicked [list $w $lno]
2593         if {[catch {set in_sel $selected_paths($path)}]} {
2594                 set in_sel 0
2595         }
2596         if {$in_sel} {
2597                 unset selected_paths($path)
2598                 $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
2599         } else {
2600                 set selected_paths($path) 1
2601                 $w tag add in_sel $lno.0 [expr {$lno + 1}].0
2602         }
2603 }
2604
2605 proc add_range_to_selection {w x y} {
2606         global file_lists last_clicked selected_paths
2607
2608         if {[lindex $last_clicked 0] ne $w} {
2609                 toggle_or_diff click $w $x $y
2610                 return
2611         }
2612
2613         set lno [lindex [split [$w index @$x,$y] .] 0]
2614         set lc [lindex $last_clicked 1]
2615         if {$lc < $lno} {
2616                 set begin $lc
2617                 set end $lno
2618         } else {
2619                 set begin $lno
2620                 set end $lc
2621         }
2622
2623         foreach path [lrange $file_lists($w) \
2624                 [expr {$begin - 1}] \
2625                 [expr {$end - 1}]] {
2626                 set selected_paths($path) 1
2627         }
2628         $w tag add in_sel $begin.0 [expr {$end + 1}].0
2629 }
2630
2631 proc show_more_context {} {
2632         global repo_config
2633         if {$repo_config(gui.diffcontext) < 99} {
2634                 incr repo_config(gui.diffcontext)
2635                 reshow_diff
2636         }
2637 }
2638
2639 proc show_less_context {} {
2640         global repo_config
2641         if {$repo_config(gui.diffcontext) > 1} {
2642                 incr repo_config(gui.diffcontext) -1
2643                 reshow_diff
2644         }
2645 }
2646
2647 proc focus_widget {widget} {
2648         global file_lists last_clicked selected_paths
2649         global file_lists_last_clicked
2650
2651         if {[llength $file_lists($widget)] > 0} {
2652                 set path $file_lists_last_clicked($widget)
2653                 set index [lsearch -sorted -exact $file_lists($widget) $path]
2654                 if {$index < 0} {
2655                         set index 0
2656                         set path [lindex $file_lists($widget) $index]
2657                 }
2658
2659                 focus $widget
2660                 set last_clicked [list $widget [expr $index + 1]]
2661                 array unset selected_paths
2662                 set selected_paths($path) 1
2663                 show_diff $path $widget
2664         }
2665 }
2666
2667 ######################################################################
2668 ##
2669 ## ui construction
2670
2671 set ui_comm {}
2672
2673 # -- Menu Bar
2674 #
2675 menu .mbar -tearoff 0
2676 if {[is_MacOSX]} {
2677         # -- Apple Menu (Mac OS X only)
2678         #
2679         .mbar add cascade -label Apple -menu .mbar.apple
2680         menu .mbar.apple
2681 }
2682 .mbar add cascade -label [mc Repository] -menu .mbar.repository
2683 .mbar add cascade -label [mc Edit] -menu .mbar.edit
2684 if {[is_enabled branch]} {
2685         .mbar add cascade -label [mc Branch] -menu .mbar.branch
2686 }
2687 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2688         .mbar add cascade -label [mc Commit@@noun] -menu .mbar.commit
2689 }
2690 if {[is_enabled transport]} {
2691         .mbar add cascade -label [mc Merge] -menu .mbar.merge
2692         .mbar add cascade -label [mc Remote] -menu .mbar.remote
2693 }
2694 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2695         .mbar add cascade -label [mc Tools] -menu .mbar.tools
2696 }
2697
2698 # -- Repository Menu
2699 #
2700 menu .mbar.repository
2701
2702 if {![is_bare]} {
2703         .mbar.repository add command \
2704                 -label [mc "Explore Working Copy"] \
2705                 -command {do_explore}
2706 }
2707
2708 if {[is_Windows]} {
2709         .mbar.repository add command \
2710                 -label [mc "Git Bash"] \
2711                 -command {eval exec [auto_execok start] \
2712                                           [list "Git Bash" bash --login -l &]}
2713 }
2714
2715 if {[is_Windows] || ![is_bare]} {
2716         .mbar.repository add separator
2717 }
2718
2719 .mbar.repository add command \
2720         -label [mc "Browse Current Branch's Files"] \
2721         -command {browser::new $current_branch}
2722 set ui_browse_current [.mbar.repository index last]
2723 .mbar.repository add command \
2724         -label [mc "Browse Branch Files..."] \
2725         -command browser_open::dialog
2726 .mbar.repository add separator
2727
2728 .mbar.repository add command \
2729         -label [mc "Visualize Current Branch's History"] \
2730         -command {do_gitk $current_branch}
2731 set ui_visualize_current [.mbar.repository index last]
2732 .mbar.repository add command \
2733         -label [mc "Visualize All Branch History"] \
2734         -command {do_gitk --all}
2735 .mbar.repository add separator
2736
2737 proc current_branch_write {args} {
2738         global current_branch
2739         .mbar.repository entryconf $::ui_browse_current \
2740                 -label [mc "Browse %s's Files" $current_branch]
2741         .mbar.repository entryconf $::ui_visualize_current \
2742                 -label [mc "Visualize %s's History" $current_branch]
2743 }
2744 trace add variable current_branch write current_branch_write
2745
2746 if {[is_enabled multicommit]} {
2747         .mbar.repository add command -label [mc "Database Statistics"] \
2748                 -command do_stats
2749
2750         .mbar.repository add command -label [mc "Compress Database"] \
2751                 -command do_gc
2752
2753         .mbar.repository add command -label [mc "Verify Database"] \
2754                 -command do_fsck_objects
2755
2756         .mbar.repository add separator
2757
2758         if {[is_Cygwin]} {
2759                 .mbar.repository add command \
2760                         -label [mc "Create Desktop Icon"] \
2761                         -command do_cygwin_shortcut
2762         } elseif {[is_Windows]} {
2763                 .mbar.repository add command \
2764                         -label [mc "Create Desktop Icon"] \
2765                         -command do_windows_shortcut
2766         } elseif {[is_MacOSX]} {
2767                 .mbar.repository add command \
2768                         -label [mc "Create Desktop Icon"] \
2769                         -command do_macosx_app
2770         }
2771 }
2772
2773 if {[is_MacOSX]} {
2774         proc ::tk::mac::Quit {args} { do_quit }
2775 } else {
2776         .mbar.repository add command -label [mc Quit] \
2777                 -command do_quit \
2778                 -accelerator $M1T-Q
2779 }
2780
2781 # -- Edit Menu
2782 #
2783 menu .mbar.edit
2784 .mbar.edit add command -label [mc Undo] \
2785         -command {catch {[focus] edit undo}} \
2786         -accelerator $M1T-Z
2787 .mbar.edit add command -label [mc Redo] \
2788         -command {catch {[focus] edit redo}} \
2789         -accelerator $M1T-Y
2790 .mbar.edit add separator
2791 .mbar.edit add command -label [mc Cut] \
2792         -command {catch {tk_textCut [focus]}} \
2793         -accelerator $M1T-X
2794 .mbar.edit add command -label [mc Copy] \
2795         -command {catch {tk_textCopy [focus]}} \
2796         -accelerator $M1T-C
2797 .mbar.edit add command -label [mc Paste] \
2798         -command {catch {tk_textPaste [focus]; [focus] see insert}} \
2799         -accelerator $M1T-V
2800 .mbar.edit add command -label [mc Delete] \
2801         -command {catch {[focus] delete sel.first sel.last}} \
2802         -accelerator Del
2803 .mbar.edit add separator
2804 .mbar.edit add command -label [mc "Select All"] \
2805         -command {catch {[focus] tag add sel 0.0 end}} \
2806         -accelerator $M1T-A
2807
2808 # -- Branch Menu
2809 #
2810 if {[is_enabled branch]} {
2811         menu .mbar.branch
2812
2813         .mbar.branch add command -label [mc "Create..."] \
2814                 -command branch_create::dialog \
2815                 -accelerator $M1T-N
2816         lappend disable_on_lock [list .mbar.branch entryconf \
2817                 [.mbar.branch index last] -state]
2818
2819         .mbar.branch add command -label [mc "Checkout..."] \
2820                 -command branch_checkout::dialog \
2821                 -accelerator $M1T-O
2822         lappend disable_on_lock [list .mbar.branch entryconf \
2823                 [.mbar.branch index last] -state]
2824
2825         .mbar.branch add command -label [mc "Rename..."] \
2826                 -command branch_rename::dialog
2827         lappend disable_on_lock [list .mbar.branch entryconf \
2828                 [.mbar.branch index last] -state]
2829
2830         .mbar.branch add command -label [mc "Delete..."] \
2831                 -command branch_delete::dialog
2832         lappend disable_on_lock [list .mbar.branch entryconf \
2833                 [.mbar.branch index last] -state]
2834
2835         .mbar.branch add command -label [mc "Reset..."] \
2836                 -command merge::reset_hard
2837         lappend disable_on_lock [list .mbar.branch entryconf \
2838                 [.mbar.branch index last] -state]
2839 }
2840
2841 # -- Commit Menu
2842 #
2843 proc commit_btn_caption {} {
2844         if {[is_enabled nocommit]} {
2845                 return [mc "Done"]
2846         } else {
2847                 return [mc Commit@@verb]
2848         }
2849 }
2850
2851 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2852         menu .mbar.commit
2853
2854         if {![is_enabled nocommit]} {
2855                 .mbar.commit add checkbutton \
2856                         -label [mc "Amend Last Commit"] \
2857                         -variable commit_type_is_amend \
2858                         -command do_select_commit_type
2859                 lappend disable_on_lock \
2860                         [list .mbar.commit entryconf [.mbar.commit index last] -state]
2861
2862                 .mbar.commit add separator
2863         }
2864
2865         .mbar.commit add command -label [mc Rescan] \
2866                 -command ui_do_rescan \
2867                 -accelerator F5
2868         lappend disable_on_lock \
2869                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2870
2871         .mbar.commit add command -label [mc "Stage To Commit"] \
2872                 -command do_add_selection \
2873                 -accelerator $M1T-T
2874         lappend disable_on_lock \
2875                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2876
2877         .mbar.commit add command -label [mc "Stage Changed Files To Commit"] \
2878                 -command do_add_all \
2879                 -accelerator $M1T-I
2880         lappend disable_on_lock \
2881                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2882
2883         .mbar.commit add command -label [mc "Unstage From Commit"] \
2884                 -command do_unstage_selection \
2885                 -accelerator $M1T-U
2886         lappend disable_on_lock \
2887                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2888
2889         .mbar.commit add command -label [mc "Revert Changes"] \
2890                 -command do_revert_selection \
2891                 -accelerator $M1T-J
2892         lappend disable_on_lock \
2893                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2894
2895         .mbar.commit add separator
2896
2897         .mbar.commit add command -label [mc "Show Less Context"] \
2898                 -command show_less_context \
2899                 -accelerator $M1T-\-
2900
2901         .mbar.commit add command -label [mc "Show More Context"] \
2902                 -command show_more_context \
2903                 -accelerator $M1T-=
2904
2905         .mbar.commit add separator
2906
2907         if {![is_enabled nocommitmsg]} {
2908                 .mbar.commit add command -label [mc "Sign Off"] \
2909                         -command do_signoff \
2910                         -accelerator $M1T-S
2911         }
2912
2913         .mbar.commit add command -label [commit_btn_caption] \
2914                 -command do_commit \
2915                 -accelerator $M1T-Return
2916         lappend disable_on_lock \
2917                 [list .mbar.commit entryconf [.mbar.commit index last] -state]
2918 }
2919
2920 # -- Merge Menu
2921 #
2922 if {[is_enabled branch]} {
2923         menu .mbar.merge
2924         .mbar.merge add command -label [mc "Local Merge..."] \
2925                 -command merge::dialog \
2926                 -accelerator $M1T-M
2927         lappend disable_on_lock \
2928                 [list .mbar.merge entryconf [.mbar.merge index last] -state]
2929         .mbar.merge add command -label [mc "Abort Merge..."] \
2930                 -command merge::reset_hard
2931         lappend disable_on_lock \
2932                 [list .mbar.merge entryconf [.mbar.merge index last] -state]
2933 }
2934
2935 # -- Transport Menu
2936 #
2937 if {[is_enabled transport]} {
2938         menu .mbar.remote
2939
2940         .mbar.remote add command \
2941                 -label [mc "Add..."] \
2942                 -command remote_add::dialog \
2943                 -accelerator $M1T-A
2944         .mbar.remote add command \
2945                 -label [mc "Push..."] \
2946                 -command do_push_anywhere \
2947                 -accelerator $M1T-P
2948         .mbar.remote add command \
2949                 -label [mc "Delete Branch..."] \
2950                 -command remote_branch_delete::dialog
2951 }
2952
2953 if {[is_MacOSX]} {
2954         proc ::tk::mac::ShowPreferences {} {do_options}
2955 } else {
2956         # -- Edit Menu
2957         #
2958         .mbar.edit add separator
2959         .mbar.edit add command -label [mc "Options..."] \
2960                 -command do_options
2961 }
2962
2963 # -- Tools Menu
2964 #
2965 if {[is_enabled multicommit] || [is_enabled singlecommit]} {
2966         set tools_menubar .mbar.tools
2967         menu $tools_menubar
2968         $tools_menubar add separator
2969         $tools_menubar add command -label [mc "Add..."] -command tools_add::dialog
2970         $tools_menubar add command -label [mc "Remove..."] -command tools_remove::dialog
2971         set tools_tailcnt 3
2972         if {[array names repo_config guitool.*.cmd] ne {}} {
2973                 tools_populate_all
2974         }
2975 }
2976
2977 # -- Help Menu
2978 #
2979 .mbar add cascade -label [mc Help] -menu .mbar.help
2980 menu .mbar.help
2981
2982 if {[is_MacOSX]} {
2983         .mbar.apple add command -label [mc "About %s" [appname]] \
2984                 -command do_about
2985         .mbar.apple add separator
2986 } else {
2987         .mbar.help add command -label [mc "About %s" [appname]] \
2988                 -command do_about
2989 }
2990 . configure -menu .mbar
2991
2992 set doc_path [githtmldir]
2993 if {$doc_path ne {}} {
2994         set doc_path [file join $doc_path index.html]
2995
2996         if {[is_Cygwin]} {
2997                 set doc_path [exec cygpath --mixed $doc_path]
2998         }
2999 }
3000
3001 if {[file isfile $doc_path]} {
3002         set doc_url "file:$doc_path"
3003 } else {
3004         set doc_url {http://www.kernel.org/pub/software/scm/git/docs/}
3005 }
3006
3007 proc start_browser {url} {
3008         git "web--browse" $url
3009 }
3010
3011 .mbar.help add command -label [mc "Online Documentation"] \
3012         -command [list start_browser $doc_url]
3013
3014 .mbar.help add command -label [mc "Show SSH Key"] \
3015         -command do_ssh_key
3016
3017 unset doc_path doc_url
3018
3019 # -- Standard bindings
3020 #
3021 wm protocol . WM_DELETE_WINDOW do_quit
3022 bind all <$M1B-Key-q> do_quit
3023 bind all <$M1B-Key-Q> do_quit
3024 bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
3025 bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
3026
3027 set subcommand_args {}
3028 proc usage {} {
3029         set s "[mc usage:] $::argv0 $::subcommand $::subcommand_args"
3030         if {[tk windowingsystem] eq "win32"} {
3031                 wm withdraw .
3032                 tk_messageBox -icon info -message $s \
3033                         -title [mc "Usage"]
3034         } else {
3035                 puts stderr $s
3036         }
3037         exit 1
3038 }
3039
3040 proc normalize_relpath {path} {
3041         set elements {}
3042         foreach item [file split $path] {
3043                 if {$item eq {.}} continue
3044                 if {$item eq {..} && [llength $elements] > 0
3045                     && [lindex $elements end] ne {..}} {
3046                         set elements [lrange $elements 0 end-1]
3047                         continue
3048                 }
3049                 lappend elements $item
3050         }
3051         return [eval file join $elements]
3052 }
3053
3054 # -- Not a normal commit type invocation?  Do that instead!
3055 #
3056 switch -- $subcommand {
3057 browser -
3058 blame {
3059         if {$subcommand eq "blame"} {
3060                 set subcommand_args {[--line=<num>] rev? path}
3061         } else {
3062                 set subcommand_args {rev? path}
3063         }
3064         if {$argv eq {}} usage
3065         set head {}
3066         set path {}
3067         set jump_spec {}
3068         set is_path 0
3069         foreach a $argv {
3070                 set p [file join $_prefix $a]
3071
3072                 if {$is_path || [file exists $p]} {
3073                         if {$path ne {}} usage
3074                         set path [normalize_relpath $p]
3075                         break
3076                 } elseif {$a eq {--}} {
3077                         if {$path ne {}} {
3078                                 if {$head ne {}} usage
3079                                 set head $path
3080                                 set path {}
3081                         }
3082                         set is_path 1
3083                 } elseif {[regexp {^--line=(\d+)$} $a a lnum]} {
3084                         if {$jump_spec ne {} || $head ne {}} usage
3085                         set jump_spec [list $lnum]
3086                 } elseif {$head eq {}} {
3087                         if {$head ne {}} usage
3088                         set head $a
3089                         set is_path 1
3090                 } else {
3091                         usage
3092                 }
3093         }
3094         unset is_path
3095
3096         if {$head ne {} && $path eq {}} {
3097                 if {[string index $head 0] eq {/}} {
3098                         set path [normalize_relpath $head]
3099                         set head {}
3100                 } else {
3101                         set path [normalize_relpath $_prefix$head]
3102                         set head {}
3103                 }
3104         }
3105
3106         if {$head eq {}} {
3107                 load_current_branch
3108         } else {
3109                 if {[regexp {^[0-9a-f]{1,39}$} $head]} {
3110                         if {[catch {
3111                                         set head [git rev-parse --verify $head]
3112                                 } err]} {
3113                                 if {[tk windowingsystem] eq "win32"} {
3114                                         tk_messageBox -icon error -title [mc Error] -message $err
3115                                 } else {
3116                                         puts stderr $err
3117                                 }
3118                                 exit 1
3119                         }
3120                 }
3121                 set current_branch $head
3122         }
3123
3124         wm deiconify .
3125         switch -- $subcommand {
3126         browser {
3127                 if {$jump_spec ne {}} usage
3128                 if {$head eq {}} {
3129                         if {$path ne {} && [file isdirectory $path]} {
3130                                 set head $current_branch
3131                         } else {
3132                                 set head $path
3133                                 set path {}
3134                         }
3135                 }
3136                 browser::new $head $path
3137         }
3138         blame   {
3139                 if {$head eq {} && ![file exists $path]} {
3140                         catch {wm withdraw .}
3141                         tk_messageBox \
3142                                 -icon error \
3143                                 -type ok \
3144                                 -title [mc "git-gui: fatal error"] \
3145                                 -message [mc "fatal: cannot stat path %s: No such file or directory" $path]
3146                         exit 1
3147                 }
3148                 blame::new $head $path $jump_spec
3149         }
3150         }
3151         return
3152 }
3153 citool -
3154 gui {
3155         if {[llength $argv] != 0} {
3156                 usage
3157         }
3158         # fall through to setup UI for commits
3159 }
3160 default {
3161         set err "[mc usage:] $argv0 \[{blame|browser|citool}\]"
3162         if {[tk windowingsystem] eq "win32"} {
3163                 wm withdraw .
3164                 tk_messageBox -icon error -message $err \
3165                         -title [mc "Usage"]
3166         } else {
3167                 puts stderr $err
3168         }
3169         exit 1
3170 }
3171 }
3172
3173 # -- Branch Control
3174 #
3175 ${NS}::frame .branch
3176 if {!$use_ttk} {.branch configure -borderwidth 1 -relief sunken}
3177 ${NS}::label .branch.l1 \
3178         -text [mc "Current Branch:"] \
3179         -anchor w \
3180         -justify left
3181 ${NS}::label .branch.cb \
3182         -textvariable current_branch \
3183         -anchor w \
3184         -justify left
3185 pack .branch.l1 -side left
3186 pack .branch.cb -side left -fill x
3187 pack .branch -side top -fill x
3188
3189 # -- Main Window Layout
3190 #
3191 ${NS}::panedwindow .vpane -orient horizontal
3192 ${NS}::panedwindow .vpane.files -orient vertical
3193 if {$use_ttk} {
3194         .vpane add .vpane.files
3195 } else {
3196         .vpane add .vpane.files -sticky nsew -height 100 -width 200
3197 }
3198 pack .vpane -anchor n -side top -fill both -expand 1
3199
3200 # -- Working Directory File List
3201
3202 textframe .vpane.files.workdir -height 100 -width 200
3203 tlabel .vpane.files.workdir.title -text [mc "Unstaged Changes"] \
3204         -background lightsalmon -foreground black
3205 ttext $ui_workdir -background white -foreground black \
3206         -borderwidth 0 \
3207         -width 20 -height 10 \
3208         -wrap none \
3209         -takefocus 1 -highlightthickness 1\
3210         -cursor $cursor_ptr \
3211         -xscrollcommand {.vpane.files.workdir.sx set} \
3212         -yscrollcommand {.vpane.files.workdir.sy set} \
3213         -state disabled
3214 ${NS}::scrollbar .vpane.files.workdir.sx -orient h -command [list $ui_workdir xview]
3215 ${NS}::scrollbar .vpane.files.workdir.sy -orient v -command [list $ui_workdir yview]
3216 pack .vpane.files.workdir.title -side top -fill x
3217 pack .vpane.files.workdir.sx -side bottom -fill x
3218 pack .vpane.files.workdir.sy -side right -fill y
3219 pack $ui_workdir -side left -fill both -expand 1
3220
3221 # -- Index File List
3222 #
3223 textframe .vpane.files.index -height 100 -width 200
3224 tlabel .vpane.files.index.title \
3225         -text [mc "Staged Changes (Will Commit)"] \
3226         -background lightgreen -foreground black
3227 ttext $ui_index -background white -foreground black \
3228         -borderwidth 0 \
3229         -width 20 -height 10 \
3230         -wrap none \
3231         -takefocus 1 -highlightthickness 1\
3232         -cursor $cursor_ptr \
3233         -xscrollcommand {.vpane.files.index.sx set} \
3234         -yscrollcommand {.vpane.files.index.sy set} \
3235         -state disabled
3236 ${NS}::scrollbar .vpane.files.index.sx -orient h -command [list $ui_index xview]
3237 ${NS}::scrollbar .vpane.files.index.sy -orient v -command [list $ui_index yview]
3238 pack .vpane.files.index.title -side top -fill x
3239 pack .vpane.files.index.sx -side bottom -fill x
3240 pack .vpane.files.index.sy -side right -fill y
3241 pack $ui_index -side left -fill both -expand 1
3242
3243 # -- Insert the workdir and index into the panes
3244 #
3245 .vpane.files add .vpane.files.workdir
3246 .vpane.files add .vpane.files.index
3247 if {!$use_ttk} {
3248         .vpane.files paneconfigure .vpane.files.workdir -sticky news
3249         .vpane.files paneconfigure .vpane.files.index -sticky news
3250 }
3251
3252 foreach i [list $ui_index $ui_workdir] {
3253         rmsel_tag $i
3254         $i tag conf in_diff -background [$i tag cget in_sel -background]
3255 }
3256 unset i
3257
3258 # -- Diff and Commit Area
3259 #
3260 if {$have_tk85} {
3261         ${NS}::panedwindow .vpane.lower -orient vertical
3262         ${NS}::frame .vpane.lower.commarea
3263         ${NS}::frame .vpane.lower.diff -relief sunken -borderwidth 1 -height 500
3264         .vpane.lower add .vpane.lower.diff
3265         .vpane.lower add .vpane.lower.commarea
3266         .vpane add .vpane.lower
3267         if {$use_ttk} {
3268                 .vpane.lower pane .vpane.lower.diff -weight 1
3269                 .vpane.lower pane .vpane.lower.commarea -weight 0
3270         } else {
3271                 .vpane.lower paneconfigure .vpane.lower.diff -stretch always
3272                 .vpane.lower paneconfigure .vpane.lower.commarea -stretch never
3273         }
3274 } else {
3275         frame .vpane.lower -height 300 -width 400
3276         frame .vpane.lower.commarea
3277         frame .vpane.lower.diff -relief sunken -borderwidth 1
3278         pack .vpane.lower.diff -fill both -expand 1
3279         pack .vpane.lower.commarea -side bottom -fill x
3280         .vpane add .vpane.lower
3281         .vpane paneconfigure .vpane.lower -sticky nsew
3282 }
3283
3284 # -- Commit Area Buttons
3285 #
3286 ${NS}::frame .vpane.lower.commarea.buttons
3287 ${NS}::label .vpane.lower.commarea.buttons.l -text {} \
3288         -anchor w \
3289         -justify left
3290 pack .vpane.lower.commarea.buttons.l -side top -fill x
3291 pack .vpane.lower.commarea.buttons -side left -fill y
3292
3293 ${NS}::button .vpane.lower.commarea.buttons.rescan -text [mc Rescan] \
3294         -command ui_do_rescan
3295 pack .vpane.lower.commarea.buttons.rescan -side top -fill x
3296 lappend disable_on_lock \
3297         {.vpane.lower.commarea.buttons.rescan conf -state}
3298
3299 ${NS}::button .vpane.lower.commarea.buttons.incall -text [mc "Stage Changed"] \
3300         -command do_add_all
3301 pack .vpane.lower.commarea.buttons.incall -side top -fill x
3302 lappend disable_on_lock \
3303         {.vpane.lower.commarea.buttons.incall conf -state}
3304
3305 if {![is_enabled nocommitmsg]} {
3306         ${NS}::button .vpane.lower.commarea.buttons.signoff -text [mc "Sign Off"] \
3307                 -command do_signoff
3308         pack .vpane.lower.commarea.buttons.signoff -side top -fill x
3309 }
3310
3311 ${NS}::button .vpane.lower.commarea.buttons.commit -text [commit_btn_caption] \
3312         -command do_commit
3313 pack .vpane.lower.commarea.buttons.commit -side top -fill x
3314 lappend disable_on_lock \
3315         {.vpane.lower.commarea.buttons.commit conf -state}
3316
3317 if {![is_enabled nocommit]} {
3318         ${NS}::button .vpane.lower.commarea.buttons.push -text [mc Push] \
3319                 -command do_push_anywhere
3320         pack .vpane.lower.commarea.buttons.push -side top -fill x
3321 }
3322
3323 # -- Commit Message Buffer
3324 #
3325 ${NS}::frame .vpane.lower.commarea.buffer
3326 ${NS}::frame .vpane.lower.commarea.buffer.header
3327 set ui_comm .vpane.lower.commarea.buffer.frame.t
3328 set ui_coml .vpane.lower.commarea.buffer.header.l
3329
3330 if {![is_enabled nocommit]} {
3331         ${NS}::checkbutton .vpane.lower.commarea.buffer.header.amend \
3332                 -text [mc "Amend Last Commit"] \
3333                 -variable commit_type_is_amend \
3334                 -command do_select_commit_type
3335         lappend disable_on_lock \
3336                 [list .vpane.lower.commarea.buffer.header.amend conf -state]
3337 }
3338
3339 ${NS}::label $ui_coml \
3340         -anchor w \
3341         -justify left
3342 proc trace_commit_type {varname args} {
3343         global ui_coml commit_type
3344         switch -glob -- $commit_type {
3345         initial       {set txt [mc "Initial Commit Message:"]}
3346         amend         {set txt [mc "Amended Commit Message:"]}
3347         amend-initial {set txt [mc "Amended Initial Commit Message:"]}
3348         amend-merge   {set txt [mc "Amended Merge Commit Message:"]}
3349         merge         {set txt [mc "Merge Commit Message:"]}
3350         *             {set txt [mc "Commit Message:"]}
3351         }
3352         $ui_coml conf -text $txt
3353 }
3354 trace add variable commit_type write trace_commit_type
3355 pack $ui_coml -side left -fill x
3356
3357 if {![is_enabled nocommit]} {
3358         pack .vpane.lower.commarea.buffer.header.amend -side right
3359 }
3360
3361 textframe .vpane.lower.commarea.buffer.frame
3362 ttext $ui_comm -background white -foreground black \
3363         -borderwidth 1 \
3364         -undo true \
3365         -maxundo 20 \
3366         -autoseparators true \
3367         -takefocus 1 \
3368         -highlightthickness 1 \
3369         -relief sunken \
3370         -width $repo_config(gui.commitmsgwidth) -height 9 -wrap none \
3371         -font font_diff \
3372         -xscrollcommand {.vpane.lower.commarea.buffer.frame.sbx set} \
3373         -yscrollcommand {.vpane.lower.commarea.buffer.frame.sby set}
3374 ${NS}::scrollbar .vpane.lower.commarea.buffer.frame.sbx \
3375         -orient horizontal \
3376         -command [list $ui_comm xview]
3377 ${NS}::scrollbar .vpane.lower.commarea.buffer.frame.sby \
3378         -orient vertical \
3379         -command [list $ui_comm yview]
3380
3381 pack .vpane.lower.commarea.buffer.frame.sbx -side bottom -fill x
3382 pack .vpane.lower.commarea.buffer.frame.sby -side right -fill y
3383 pack $ui_comm -side left -fill y
3384 pack .vpane.lower.commarea.buffer.header -side top -fill x
3385 pack .vpane.lower.commarea.buffer.frame -side left -fill y
3386 pack .vpane.lower.commarea.buffer -side left -fill y
3387
3388 # -- Commit Message Buffer Context Menu
3389 #
3390 set ctxm .vpane.lower.commarea.buffer.ctxm
3391 menu $ctxm -tearoff 0
3392 $ctxm add command \
3393         -label [mc Cut] \
3394         -command {tk_textCut $ui_comm}
3395 $ctxm add command \
3396         -label [mc Copy] \
3397         -command {tk_textCopy $ui_comm}
3398 $ctxm add command \
3399         -label [mc Paste] \
3400         -command {tk_textPaste $ui_comm}
3401 $ctxm add command \
3402         -label [mc Delete] \
3403         -command {catch {$ui_comm delete sel.first sel.last}}
3404 $ctxm add separator
3405 $ctxm add command \
3406         -label [mc "Select All"] \
3407         -command {focus $ui_comm;$ui_comm tag add sel 0.0 end}
3408 $ctxm add command \
3409         -label [mc "Copy All"] \
3410         -command {
3411                 $ui_comm tag add sel 0.0 end
3412                 tk_textCopy $ui_comm
3413                 $ui_comm tag remove sel 0.0 end
3414         }
3415 $ctxm add separator
3416 $ctxm add command \
3417         -label [mc "Sign Off"] \
3418         -command do_signoff
3419 set ui_comm_ctxm $ctxm
3420
3421 # -- Diff Header
3422 #
3423 proc trace_current_diff_path {varname args} {
3424         global current_diff_path diff_actions file_states
3425         if {$current_diff_path eq {}} {
3426                 set s {}
3427                 set f {}
3428                 set p {}
3429                 set o disabled
3430         } else {
3431                 set p $current_diff_path
3432                 set s [mapdesc [lindex $file_states($p) 0] $p]
3433                 set f [mc "File:"]
3434                 set p [escape_path $p]
3435                 set o normal
3436         }
3437
3438         .vpane.lower.diff.header.status configure -text $s
3439         .vpane.lower.diff.header.file configure -text $f
3440         .vpane.lower.diff.header.path configure -text $p
3441         foreach w $diff_actions {
3442                 uplevel #0 $w $o
3443         }
3444 }
3445 trace add variable current_diff_path write trace_current_diff_path
3446
3447 gold_frame .vpane.lower.diff.header
3448 tlabel .vpane.lower.diff.header.status \
3449         -background gold \
3450         -foreground black \
3451         -width $max_status_desc \
3452         -anchor w \
3453         -justify left
3454 tlabel .vpane.lower.diff.header.file \
3455         -background gold \
3456         -foreground black \
3457         -anchor w \
3458         -justify left
3459 tlabel .vpane.lower.diff.header.path \
3460         -background gold \
3461         -foreground black \
3462         -anchor w \
3463         -justify left
3464 pack .vpane.lower.diff.header.status -side left
3465 pack .vpane.lower.diff.header.file -side left
3466 pack .vpane.lower.diff.header.path -fill x
3467 set ctxm .vpane.lower.diff.header.ctxm
3468 menu $ctxm -tearoff 0
3469 $ctxm add command \
3470         -label [mc Copy] \
3471         -command {
3472                 clipboard clear
3473                 clipboard append \
3474                         -format STRING \
3475                         -type STRING \
3476                         -- $current_diff_path
3477         }
3478 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3479 bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
3480
3481 # -- Diff Body
3482 #
3483 textframe .vpane.lower.diff.body
3484 set ui_diff .vpane.lower.diff.body.t
3485 ttext $ui_diff -background white -foreground black \
3486         -borderwidth 0 \
3487         -width 80 -height 5 -wrap none \
3488         -font font_diff \
3489         -takefocus 1 -highlightthickness 1 \
3490         -xscrollcommand {.vpane.lower.diff.body.sbx set} \
3491         -yscrollcommand {.vpane.lower.diff.body.sby set} \
3492         -state disabled
3493 catch {$ui_diff configure -tabstyle wordprocessor}
3494 ${NS}::scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
3495         -command [list $ui_diff xview]
3496 ${NS}::scrollbar .vpane.lower.diff.body.sby -orient vertical \
3497         -command [list $ui_diff yview]
3498 pack .vpane.lower.diff.body.sbx -side bottom -fill x
3499 pack .vpane.lower.diff.body.sby -side right -fill y
3500 pack $ui_diff -side left -fill both -expand 1
3501 pack .vpane.lower.diff.header -side top -fill x
3502 pack .vpane.lower.diff.body -side bottom -fill both -expand 1
3503
3504 foreach {n c} {0 black 1 red4 2 green4 3 yellow4 4 blue4 5 magenta4 6 cyan4 7 grey60} {
3505         $ui_diff tag configure clr4$n -background $c
3506         $ui_diff tag configure clri4$n -foreground $c
3507         $ui_diff tag configure clr3$n -foreground $c
3508         $ui_diff tag configure clri3$n -background $c
3509 }
3510 $ui_diff tag configure clr1 -font font_diffbold
3511 $ui_diff tag configure clr4 -underline 1
3512
3513 $ui_diff tag conf d_info -foreground blue -font font_diffbold
3514
3515 $ui_diff tag conf d_cr -elide true
3516 $ui_diff tag conf d_@ -font font_diffbold
3517 $ui_diff tag conf d_+ -foreground {#00a000}
3518 $ui_diff tag conf d_- -foreground red
3519
3520 $ui_diff tag conf d_++ -foreground {#00a000}
3521 $ui_diff tag conf d_-- -foreground red
3522 $ui_diff tag conf d_+s \
3523         -foreground {#00a000} \
3524         -background {#e2effa}
3525 $ui_diff tag conf d_-s \
3526         -foreground red \
3527         -background {#e2effa}
3528 $ui_diff tag conf d_s+ \
3529         -foreground {#00a000} \
3530         -background ivory1
3531 $ui_diff tag conf d_s- \
3532         -foreground red \
3533         -background ivory1
3534
3535 $ui_diff tag conf d< \
3536         -foreground orange \
3537         -font font_diffbold
3538 $ui_diff tag conf d= \
3539         -foreground orange \
3540         -font font_diffbold
3541 $ui_diff tag conf d> \
3542         -foreground orange \
3543         -font font_diffbold
3544
3545 $ui_diff tag raise sel
3546
3547 # -- Diff Body Context Menu
3548 #
3549
3550 proc create_common_diff_popup {ctxm} {
3551         $ctxm add command \
3552                 -label [mc Refresh] \
3553                 -command reshow_diff
3554         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3555         $ctxm add command \
3556                 -label [mc Copy] \
3557                 -command {tk_textCopy $ui_diff}
3558         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3559         $ctxm add command \
3560                 -label [mc "Select All"] \
3561                 -command {focus $ui_diff;$ui_diff tag add sel 0.0 end}
3562         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3563         $ctxm add command \
3564                 -label [mc "Copy All"] \
3565                 -command {
3566                         $ui_diff tag add sel 0.0 end
3567                         tk_textCopy $ui_diff
3568                         $ui_diff tag remove sel 0.0 end
3569                 }
3570         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3571         $ctxm add separator
3572         $ctxm add command \
3573                 -label [mc "Decrease Font Size"] \
3574                 -command {incr_font_size font_diff -1}
3575         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3576         $ctxm add command \
3577                 -label [mc "Increase Font Size"] \
3578                 -command {incr_font_size font_diff 1}
3579         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3580         $ctxm add separator
3581         set emenu $ctxm.enc
3582         menu $emenu
3583         build_encoding_menu $emenu [list force_diff_encoding]
3584         $ctxm add cascade \
3585                 -label [mc "Encoding"] \
3586                 -menu $emenu
3587         lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3588         $ctxm add separator
3589         $ctxm add command -label [mc "Options..."] \
3590                 -command do_options
3591 }
3592
3593 set ctxm .vpane.lower.diff.body.ctxm
3594 menu $ctxm -tearoff 0
3595 $ctxm add command \
3596         -label [mc "Apply/Reverse Hunk"] \
3597         -command {apply_or_revert_hunk $cursorX $cursorY 0}
3598 set ui_diff_applyhunk [$ctxm index last]
3599 lappend diff_actions [list $ctxm entryconf $ui_diff_applyhunk -state]
3600 $ctxm add command \
3601         -label [mc "Apply/Reverse Line"] \
3602         -command {apply_or_revert_range_or_line $cursorX $cursorY 0; do_rescan}
3603 set ui_diff_applyline [$ctxm index last]
3604 lappend diff_actions [list $ctxm entryconf $ui_diff_applyline -state]
3605 $ctxm add separator
3606 $ctxm add command \
3607         -label [mc "Revert Hunk"] \
3608         -command {apply_or_revert_hunk $cursorX $cursorY 1}
3609 set ui_diff_reverthunk [$ctxm index last]
3610 lappend diff_actions [list $ctxm entryconf $ui_diff_reverthunk -state]
3611 $ctxm add command \
3612         -label [mc "Revert Line"] \
3613         -command {apply_or_revert_range_or_line $cursorX $cursorY 1; do_rescan}
3614 set ui_diff_revertline [$ctxm index last]
3615 lappend diff_actions [list $ctxm entryconf $ui_diff_revertline -state]
3616 $ctxm add command \
3617         -label [mc "Undo Last Revert"] \
3618         -command {undo_last_revert; do_rescan}
3619 set ui_diff_undorevert [$ctxm index last]
3620 lappend diff_actions [list $ctxm entryconf $ui_diff_undorevert -state]
3621 $ctxm add separator
3622 $ctxm add command \
3623         -label [mc "Show Less Context"] \
3624         -command show_less_context
3625 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3626 $ctxm add command \
3627         -label [mc "Show More Context"] \
3628         -command show_more_context
3629 lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3630 $ctxm add separator
3631 create_common_diff_popup $ctxm
3632
3633 set ctxmmg .vpane.lower.diff.body.ctxmmg
3634 menu $ctxmmg -tearoff 0
3635 $ctxmmg add command \
3636         -label [mc "Run Merge Tool"] \
3637         -command {merge_resolve_tool}
3638 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3639 $ctxmmg add separator
3640 $ctxmmg add command \
3641         -label [mc "Use Remote Version"] \
3642         -command {merge_resolve_one 3}
3643 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3644 $ctxmmg add command \
3645         -label [mc "Use Local Version"] \
3646         -command {merge_resolve_one 2}
3647 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3648 $ctxmmg add command \
3649         -label [mc "Revert To Base"] \
3650         -command {merge_resolve_one 1}
3651 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3652 $ctxmmg add separator
3653 $ctxmmg add command \
3654         -label [mc "Show Less Context"] \
3655         -command show_less_context
3656 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3657 $ctxmmg add command \
3658         -label [mc "Show More Context"] \
3659         -command show_more_context
3660 lappend diff_actions [list $ctxmmg entryconf [$ctxmmg index last] -state]
3661 $ctxmmg add separator
3662 create_common_diff_popup $ctxmmg
3663
3664 set ctxmsm .vpane.lower.diff.body.ctxmsm
3665 menu $ctxmsm -tearoff 0
3666 $ctxmsm add command \
3667         -label [mc "Visualize These Changes In The Submodule"] \
3668         -command {do_gitk -- true}
3669 lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3670 $ctxmsm add command \
3671         -label [mc "Visualize Current Branch History In The Submodule"] \
3672         -command {do_gitk {} true}
3673 lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3674 $ctxmsm add command \
3675         -label [mc "Visualize All Branch History In The Submodule"] \
3676         -command {do_gitk --all true}
3677 lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3678 $ctxmsm add separator
3679 $ctxmsm add command \
3680         -label [mc "Start git gui In The Submodule"] \
3681         -command {do_git_gui}
3682 lappend diff_actions [list $ctxmsm entryconf [$ctxmsm index last] -state]
3683 $ctxmsm add separator
3684 create_common_diff_popup $ctxmsm
3685
3686 proc has_textconv {path} {
3687         if {[is_config_false gui.textconv]} {
3688                 return 0
3689         }
3690         set filter [gitattr $path diff set]
3691         set textconv [get_config [join [list diff $filter textconv] .]]
3692         if {$filter ne {set} && $textconv ne {}} {
3693                 return 1
3694         } else {
3695                 return 0
3696         }
3697 }
3698
3699 proc popup_diff_menu {ctxm ctxmmg ctxmsm x y X Y} {
3700         global current_diff_path file_states last_revert
3701         set ::cursorX $x
3702         set ::cursorY $y
3703         if {[info exists file_states($current_diff_path)]} {
3704                 set state [lindex $file_states($current_diff_path) 0]
3705         } else {
3706                 set state {__}
3707         }
3708         if {[string first {U} $state] >= 0} {
3709                 tk_popup $ctxmmg $X $Y
3710         } elseif {$::is_submodule_diff} {
3711                 tk_popup $ctxmsm $X $Y
3712         } else {
3713                 set has_range [expr {[$::ui_diff tag nextrange sel 0.0] != {}}]
3714                 set u [mc "Undo Last Revert"]
3715                 if {$::ui_index eq $::current_diff_side} {
3716                         set l [mc "Unstage Hunk From Commit"]
3717                         set h [mc "Revert Hunk"]
3718
3719                         if {$has_range} {
3720                                 set t [mc "Unstage Lines From Commit"]
3721                                 set r [mc "Revert Lines"]
3722                         } else {
3723                                 set t [mc "Unstage Line From Commit"]
3724                                 set r [mc "Revert Line"]
3725                         }
3726                 } else {
3727                         set l [mc "Stage Hunk For Commit"]
3728                         set h [mc "Revert Hunk"]
3729
3730                         if {$has_range} {
3731                                 set t [mc "Stage Lines For Commit"]
3732                                 set r [mc "Revert Lines"]
3733                         } else {
3734                                 set t [mc "Stage Line For Commit"]
3735                                 set r [mc "Revert Line"]
3736                         }
3737                 }
3738                 if {$::is_3way_diff
3739                         || $current_diff_path eq {}
3740                         || {__} eq $state
3741                         || {_O} eq $state
3742                         || [string match {?T} $state]
3743                         || [string match {T?} $state]
3744                         || [has_textconv $current_diff_path]} {
3745                         set s disabled
3746                         set revert_state disabled
3747                 } else {
3748                         set s normal
3749
3750                         # Only allow reverting changes in the working tree. If
3751                         # the user wants to revert changes in the index, they
3752                         # need to unstage those first.
3753                         if {$::ui_workdir eq $::current_diff_side} {
3754                                 set revert_state normal
3755                         } else {
3756                                 set revert_state disabled
3757                         }
3758                 }
3759
3760                 if {$last_revert eq {}} {
3761                         set undo_state disabled
3762                 } else {
3763                         set undo_state normal
3764                 }
3765
3766                 $ctxm entryconf $::ui_diff_applyhunk -state $s -label $l
3767                 $ctxm entryconf $::ui_diff_applyline -state $s -label $t
3768                 $ctxm entryconf $::ui_diff_revertline -state $revert_state \
3769                         -label $r
3770                 $ctxm entryconf $::ui_diff_reverthunk -state $revert_state \
3771                         -label $h
3772                 $ctxm entryconf $::ui_diff_undorevert -state $undo_state \
3773                         -label $u
3774
3775                 tk_popup $ctxm $X $Y
3776         }
3777 }
3778 bind_button3 $ui_diff [list popup_diff_menu $ctxm $ctxmmg $ctxmsm %x %y %X %Y]
3779
3780 # -- Status Bar
3781 #
3782 set main_status [::status_bar::new .status]
3783 pack .status -anchor w -side bottom -fill x
3784 $main_status show [mc "Initializing..."]
3785
3786 # -- Load geometry
3787 #
3788 proc on_ttk_pane_mapped {w pane pos} {
3789         bind $w <Map> {}
3790         after 0 [list after idle [list $w sashpos $pane $pos]]
3791 }
3792 proc on_tk_pane_mapped {w pane x y} {
3793         bind $w <Map> {}
3794         after 0 [list after idle [list $w sash place $pane $x $y]]
3795 }
3796 proc on_application_mapped {} {
3797         global repo_config use_ttk
3798         bind . <Map> {}
3799         set gm $repo_config(gui.geometry)
3800         if {$use_ttk} {
3801                 bind .vpane <Map> \
3802                     [list on_ttk_pane_mapped %W 0 [lindex $gm 1]]
3803                 bind .vpane.files <Map> \
3804                     [list on_ttk_pane_mapped %W 0 [lindex $gm 2]]
3805         } else {
3806                 bind .vpane <Map> \
3807                     [list on_tk_pane_mapped %W 0 \
3808                          [lindex $gm 1] \
3809                          [lindex [.vpane sash coord 0] 1]]
3810                 bind .vpane.files <Map> \
3811                     [list on_tk_pane_mapped %W 0 \
3812                          [lindex [.vpane.files sash coord 0] 0] \
3813                          [lindex $gm 2]]
3814         }
3815         wm geometry . [lindex $gm 0]
3816 }
3817 if {[info exists repo_config(gui.geometry)]} {
3818         bind . <Map> [list on_application_mapped]
3819         wm geometry . [lindex $repo_config(gui.geometry) 0]
3820 }
3821
3822 # -- Load window state
3823 #
3824 if {[info exists repo_config(gui.wmstate)]} {
3825         catch {wm state . $repo_config(gui.wmstate)}
3826 }
3827
3828 # -- Key Bindings
3829 #
3830 bind $ui_comm <$M1B-Key-Return> {do_commit;break}
3831 bind $ui_comm <$M1B-Key-t> {do_add_selection;break}
3832 bind $ui_comm <$M1B-Key-T> {do_add_selection;break}
3833 bind $ui_comm <$M1B-Key-u> {do_unstage_selection;break}
3834 bind $ui_comm <$M1B-Key-U> {do_unstage_selection;break}
3835 bind $ui_comm <$M1B-Key-j> {do_revert_selection;break}
3836 bind $ui_comm <$M1B-Key-J> {do_revert_selection;break}
3837 bind $ui_comm <$M1B-Key-i> {do_add_all;break}
3838 bind $ui_comm <$M1B-Key-I> {do_add_all;break}
3839 bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
3840 bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
3841 bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
3842 bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
3843 bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
3844 bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
3845 bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3846 bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3847 bind $ui_comm <$M1B-Key-minus> {show_less_context;break}
3848 bind $ui_comm <$M1B-Key-KP_Subtract> {show_less_context;break}
3849 bind $ui_comm <$M1B-Key-equal> {show_more_context;break}
3850 bind $ui_comm <$M1B-Key-plus> {show_more_context;break}
3851 bind $ui_comm <$M1B-Key-KP_Add> {show_more_context;break}
3852
3853 bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
3854 bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
3855 bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
3856 bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
3857 bind $ui_diff <$M1B-Key-v> {break}
3858 bind $ui_diff <$M1B-Key-V> {break}
3859 bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3860 bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3861 bind $ui_diff <$M1B-Key-j> {do_revert_selection;break}
3862 bind $ui_diff <$M1B-Key-J> {do_revert_selection;break}
3863 bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
3864 bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
3865 bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
3866 bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
3867 bind $ui_diff <Key-k>         {catch {%W yview scroll -1 units};break}
3868 bind $ui_diff <Key-j>         {catch {%W yview scroll  1 units};break}
3869 bind $ui_diff <Key-h>         {catch {%W xview scroll -1 units};break}
3870 bind $ui_diff <Key-l>         {catch {%W xview scroll  1 units};break}
3871 bind $ui_diff <Control-Key-b> {catch {%W yview scroll -1 pages};break}
3872 bind $ui_diff <Control-Key-f> {catch {%W yview scroll  1 pages};break}
3873 bind $ui_diff <Button-1>   {focus %W}
3874
3875 if {[is_enabled branch]} {
3876         bind . <$M1B-Key-n> branch_create::dialog
3877         bind . <$M1B-Key-N> branch_create::dialog
3878         bind . <$M1B-Key-o> branch_checkout::dialog
3879         bind . <$M1B-Key-O> branch_checkout::dialog
3880         bind . <$M1B-Key-m> merge::dialog
3881         bind . <$M1B-Key-M> merge::dialog
3882 }
3883 if {[is_enabled transport]} {
3884         bind . <$M1B-Key-p> do_push_anywhere
3885         bind . <$M1B-Key-P> do_push_anywhere
3886 }
3887
3888 bind .   <Key-F5>     ui_do_rescan
3889 bind .   <$M1B-Key-r> ui_do_rescan
3890 bind .   <$M1B-Key-R> ui_do_rescan
3891 bind .   <$M1B-Key-s> do_signoff
3892 bind .   <$M1B-Key-S> do_signoff
3893 bind .   <$M1B-Key-t> { toggle_or_diff toggle %W }
3894 bind .   <$M1B-Key-T> { toggle_or_diff toggle %W }
3895 bind .   <$M1B-Key-u> { toggle_or_diff toggle %W }
3896 bind .   <$M1B-Key-U> { toggle_or_diff toggle %W }
3897 bind .   <$M1B-Key-j> do_revert_selection
3898 bind .   <$M1B-Key-J> do_revert_selection
3899 bind .   <$M1B-Key-i> do_add_all
3900 bind .   <$M1B-Key-I> do_add_all
3901 bind .   <$M1B-Key-minus> {show_less_context;break}
3902 bind .   <$M1B-Key-KP_Subtract> {show_less_context;break}
3903 bind .   <$M1B-Key-equal> {show_more_context;break}
3904 bind .   <$M1B-Key-plus> {show_more_context;break}
3905 bind .   <$M1B-Key-KP_Add> {show_more_context;break}
3906 bind .   <$M1B-Key-Return> do_commit
3907 foreach i [list $ui_index $ui_workdir] {
3908         bind $i <Button-1>       { toggle_or_diff click %W %x %y; break }
3909         bind $i <$M1B-Button-1>  { add_one_to_selection %W %x %y; break }
3910         bind $i <Shift-Button-1> { add_range_to_selection %W %x %y; break }
3911         bind $i <Key-Up>         { toggle_or_diff up %W; break }
3912         bind $i <Key-Down>       { toggle_or_diff down %W; break }
3913 }
3914 unset i
3915
3916 bind .   <Alt-Key-1> {focus_widget $::ui_workdir}
3917 bind .   <Alt-Key-2> {focus_widget $::ui_index}
3918 bind .   <Alt-Key-3> {focus $::ui_diff}
3919 bind .   <Alt-Key-4> {focus $::ui_comm}
3920
3921 set file_lists_last_clicked($ui_index) {}
3922 set file_lists_last_clicked($ui_workdir) {}
3923
3924 set file_lists($ui_index) [list]
3925 set file_lists($ui_workdir) [list]
3926
3927 wm title . "[appname] ([reponame]) [file normalize $_gitworktree]"
3928 focus -force $ui_comm
3929
3930 # -- Warn the user about environmental problems.  Cygwin's Tcl
3931 #    does *not* pass its env array onto any processes it spawns.
3932 #    This means that git processes get none of our environment.
3933 #
3934 if {[is_Cygwin]} {
3935         set ignored_env 0
3936         set suggest_user {}
3937         set msg [mc "Possible environment issues exist.
3938
3939 The following environment variables are probably
3940 going to be ignored by any Git subprocess run
3941 by %s:
3942
3943 " [appname]]
3944         foreach name [array names env] {
3945                 switch -regexp -- $name {
3946                 {^GIT_INDEX_FILE$} -
3947                 {^GIT_OBJECT_DIRECTORY$} -
3948                 {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
3949                 {^GIT_DIFF_OPTS$} -
3950                 {^GIT_EXTERNAL_DIFF$} -
3951                 {^GIT_PAGER$} -
3952                 {^GIT_TRACE$} -
3953                 {^GIT_CONFIG$} -
3954                 {^GIT_(AUTHOR|COMMITTER)_DATE$} {
3955                         append msg " - $name\n"
3956                         incr ignored_env
3957                 }
3958                 {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
3959                         append msg " - $name\n"
3960                         incr ignored_env
3961                         set suggest_user $name
3962                 }
3963                 }
3964         }
3965         if {$ignored_env > 0} {
3966                 append msg [mc "
3967 This is due to a known issue with the
3968 Tcl binary distributed by Cygwin."]
3969
3970                 if {$suggest_user ne {}} {
3971                         append msg [mc "
3972
3973 A good replacement for %s
3974 is placing values for the user.name and
3975 user.email settings into your personal
3976 ~/.gitconfig file.
3977 " $suggest_user]
3978                 }
3979                 warn_popup $msg
3980         }
3981         unset ignored_env msg suggest_user name
3982 }
3983
3984 # -- Only initialize complex UI if we are going to stay running.
3985 #
3986 if {[is_enabled transport]} {
3987         load_all_remotes
3988
3989         set n [.mbar.remote index end]
3990         populate_remotes_menu
3991         set n [expr {[.mbar.remote index end] - $n}]
3992         if {$n > 0} {
3993                 if {[.mbar.remote type 0] eq "tearoff"} { incr n }
3994                 .mbar.remote insert $n separator
3995         }
3996         unset n
3997 }
3998
3999 if {[winfo exists $ui_comm]} {
4000         set GITGUI_BCK_exists [load_message GITGUI_BCK utf-8]
4001
4002         # -- If both our backup and message files exist use the
4003         #    newer of the two files to initialize the buffer.
4004         #
4005         if {$GITGUI_BCK_exists} {
4006                 set m [gitdir GITGUI_MSG]
4007                 if {[file isfile $m]} {
4008                         if {[file mtime [gitdir GITGUI_BCK]] > [file mtime $m]} {
4009                                 catch {file delete [gitdir GITGUI_MSG]}
4010                         } else {
4011                                 $ui_comm delete 0.0 end
4012                                 $ui_comm edit reset
4013                                 $ui_comm edit modified false
4014                                 catch {file delete [gitdir GITGUI_BCK]}
4015                                 set GITGUI_BCK_exists 0
4016                         }
4017                 }
4018                 unset m
4019         }
4020
4021         proc backup_commit_buffer {} {
4022                 global ui_comm GITGUI_BCK_exists
4023
4024                 set m [$ui_comm edit modified]
4025                 if {$m || $GITGUI_BCK_exists} {
4026                         set msg [string trim [$ui_comm get 0.0 end]]
4027                         regsub -all -line {[ \r\t]+$} $msg {} msg
4028
4029                         if {$msg eq {}} {
4030                                 if {$GITGUI_BCK_exists} {
4031                                         catch {file delete [gitdir GITGUI_BCK]}
4032                                         set GITGUI_BCK_exists 0
4033                                 }
4034                         } elseif {$m} {
4035                                 catch {
4036                                         set fd [open [gitdir GITGUI_BCK] w]
4037                                         fconfigure $fd -encoding utf-8
4038                                         puts -nonewline $fd $msg
4039                                         close $fd
4040                                         set GITGUI_BCK_exists 1
4041                                 }
4042                         }
4043
4044                         $ui_comm edit modified false
4045                 }
4046
4047                 set ::GITGUI_BCK_i [after 2000 backup_commit_buffer]
4048         }
4049
4050         backup_commit_buffer
4051
4052         # -- If the user has aspell available we can drive it
4053         #    in pipe mode to spellcheck the commit message.
4054         #
4055         set spell_cmd [list |]
4056         set spell_dict [get_config gui.spellingdictionary]
4057         lappend spell_cmd aspell
4058         if {$spell_dict ne {}} {
4059                 lappend spell_cmd --master=$spell_dict
4060         }
4061         lappend spell_cmd --mode=none
4062         lappend spell_cmd --encoding=utf-8
4063         lappend spell_cmd pipe
4064         if {$spell_dict eq {none}
4065          || [catch {set spell_fd [open $spell_cmd r+]} spell_err]} {
4066                 bind_button3 $ui_comm [list tk_popup $ui_comm_ctxm %X %Y]
4067         } else {
4068                 set ui_comm_spell [spellcheck::init \
4069                         $spell_fd \
4070                         $ui_comm \
4071                         $ui_comm_ctxm \
4072                 ]
4073         }
4074         unset -nocomplain spell_cmd spell_fd spell_err spell_dict
4075 }
4076
4077 lock_index begin-read
4078 if {![winfo ismapped .]} {
4079         wm deiconify .
4080 }
4081 after 1 {
4082         if {[is_enabled initialamend]} {
4083                 force_amend
4084         } else {
4085                 do_rescan
4086         }
4087
4088         if {[is_enabled nocommitmsg]} {
4089                 $ui_comm configure -state disabled -background gray
4090         }
4091 }
4092 if {[is_enabled multicommit] && ![is_config_false gui.gcwarning]} {
4093         after 1000 hint_gc
4094 }
4095 if {[is_enabled retcode]} {
4096         bind . <Destroy> {+terminate_me %W}
4097 }
4098 if {$picked && [is_config_true gui.autoexplore]} {
4099         do_explore
4100 }
4101
4102 # Local variables:
4103 # mode: tcl
4104 # indent-tabs-mode: t
4105 # tab-width: 4
4106 # End: