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