Merge branch 'master' of git://repo.or.cz/alt-git
[git/mingw.git] / gitk-git / gitk
blobffcfe49e9fc82105ef43ef3ad0dc654264b3d472
1 #!/bin/sh
2 # Tcl ignores the next line -*- tcl -*- \
3 exec wish "$0" -- "$@"
5 # Copyright © 2005-2014 Paul Mackerras. All rights reserved.
6 # This program is free software; it may be used, copied, modified
7 # and distributed under the terms of the GNU General Public Licence,
8 # either version 2, or (at your option) any later version.
10 package require Tk
12 proc hasworktree {} {
13 return [expr {[exec git rev-parse --is-bare-repository] == "false" &&
14 [exec git rev-parse --is-inside-git-dir] == "false"}]
17 proc reponame {} {
18 global gitdir
19 set n [file normalize $gitdir]
20 if {[string match "*/.git" $n]} {
21 set n [string range $n 0 end-5]
23 return [file tail $n]
26 proc gitworktree {} {
27 variable _gitworktree
28 if {[info exists _gitworktree]} {
29 return $_gitworktree
31 # v1.7.0 introduced --show-toplevel to return the canonical work-tree
32 if {[catch {set _gitworktree [exec git rev-parse --show-toplevel]}]} {
33 # try to set work tree from environment, core.worktree or use
34 # cdup to obtain a relative path to the top of the worktree. If
35 # run from the top, the ./ prefix ensures normalize expands pwd.
36 if {[catch { set _gitworktree $env(GIT_WORK_TREE) }]} {
37 catch {set _gitworktree [exec git config --get core.worktree]}
38 if {$_gitworktree eq ""} {
39 set _gitworktree [file normalize ./[exec git rev-parse --show-cdup]]
43 return $_gitworktree
46 # A simple scheduler for compute-intensive stuff.
47 # The aim is to make sure that event handlers for GUI actions can
48 # run at least every 50-100 ms. Unfortunately fileevent handlers are
49 # run before X event handlers, so reading from a fast source can
50 # make the GUI completely unresponsive.
51 proc run args {
52 global isonrunq runq currunq
54 set script $args
55 if {[info exists isonrunq($script)]} return
56 if {$runq eq {} && ![info exists currunq]} {
57 after idle dorunq
59 lappend runq [list {} $script]
60 set isonrunq($script) 1
63 proc filerun {fd script} {
64 fileevent $fd readable [list filereadable $fd $script]
67 proc filereadable {fd script} {
68 global runq currunq
70 fileevent $fd readable {}
71 if {$runq eq {} && ![info exists currunq]} {
72 after idle dorunq
74 lappend runq [list $fd $script]
77 proc nukefile {fd} {
78 global runq
80 for {set i 0} {$i < [llength $runq]} {} {
81 if {[lindex $runq $i 0] eq $fd} {
82 set runq [lreplace $runq $i $i]
83 } else {
84 incr i
89 proc dorunq {} {
90 global isonrunq runq currunq
92 set tstart [clock clicks -milliseconds]
93 set t0 $tstart
94 while {[llength $runq] > 0} {
95 set fd [lindex $runq 0 0]
96 set script [lindex $runq 0 1]
97 set currunq [lindex $runq 0]
98 set runq [lrange $runq 1 end]
99 set repeat [eval $script]
100 unset currunq
101 set t1 [clock clicks -milliseconds]
102 set t [expr {$t1 - $t0}]
103 if {$repeat ne {} && $repeat} {
104 if {$fd eq {} || $repeat == 2} {
105 # script returns 1 if it wants to be readded
106 # file readers return 2 if they could do more straight away
107 lappend runq [list $fd $script]
108 } else {
109 fileevent $fd readable [list filereadable $fd $script]
111 } elseif {$fd eq {}} {
112 unset isonrunq($script)
114 set t0 $t1
115 if {$t1 - $tstart >= 80} break
117 if {$runq ne {}} {
118 after idle dorunq
122 proc reg_instance {fd} {
123 global commfd leftover loginstance
125 set i [incr loginstance]
126 set commfd($i) $fd
127 set leftover($i) {}
128 return $i
131 proc unmerged_files {files} {
132 global nr_unmerged
134 # find the list of unmerged files
135 set mlist {}
136 set nr_unmerged 0
137 if {[catch {
138 set fd [open "| git ls-files -u" r]
139 } err]} {
140 show_error {} . "[mc "Couldn't get list of unmerged files:"] $err"
141 exit 1
143 while {[gets $fd line] >= 0} {
144 set i [string first "\t" $line]
145 if {$i < 0} continue
146 set fname [string range $line [expr {$i+1}] end]
147 if {[lsearch -exact $mlist $fname] >= 0} continue
148 incr nr_unmerged
149 if {$files eq {} || [path_filter $files $fname]} {
150 lappend mlist $fname
153 catch {close $fd}
154 return $mlist
157 proc parseviewargs {n arglist} {
158 global vdatemode vmergeonly vflags vdflags vrevs vfiltered vorigargs env
159 global vinlinediff
160 global worddiff git_version
162 set vdatemode($n) 0
163 set vmergeonly($n) 0
164 set vinlinediff($n) 0
165 set glflags {}
166 set diffargs {}
167 set nextisval 0
168 set revargs {}
169 set origargs $arglist
170 set allknown 1
171 set filtered 0
172 set i -1
173 foreach arg $arglist {
174 incr i
175 if {$nextisval} {
176 lappend glflags $arg
177 set nextisval 0
178 continue
180 switch -glob -- $arg {
181 "-d" -
182 "--date-order" {
183 set vdatemode($n) 1
184 # remove from origargs in case we hit an unknown option
185 set origargs [lreplace $origargs $i $i]
186 incr i -1
188 "-[puabwcrRBMC]" -
189 "--no-renames" - "--full-index" - "--binary" - "--abbrev=*" -
190 "--find-copies-harder" - "-l*" - "--ext-diff" - "--no-ext-diff" -
191 "--src-prefix=*" - "--dst-prefix=*" - "--no-prefix" -
192 "-O*" - "--text" - "--full-diff" - "--ignore-space-at-eol" -
193 "--ignore-space-change" - "-U*" - "--unified=*" {
194 # These request or affect diff output, which we don't want.
195 # Some could be used to set our defaults for diff display.
196 lappend diffargs $arg
198 "--raw" - "--patch-with-raw" - "--patch-with-stat" -
199 "--name-only" - "--name-status" - "--color" -
200 "--log-size" - "--pretty=*" - "--decorate" - "--abbrev-commit" -
201 "--cc" - "-z" - "--header" - "--parents" - "--boundary" -
202 "--no-color" - "-g" - "--walk-reflogs" - "--no-walk" -
203 "--timestamp" - "relative-date" - "--date=*" - "--stdin" -
204 "--objects" - "--objects-edge" - "--reverse" {
205 # These cause our parsing of git log's output to fail, or else
206 # they're options we want to set ourselves, so ignore them.
208 "--color-words*" - "--word-diff=color" {
209 # These trigger a word diff in the console interface,
210 # so help the user by enabling our own support
211 if {[package vcompare $git_version "1.7.2"] >= 0} {
212 set worddiff [mc "Color words"]
215 "--word-diff*" {
216 if {[package vcompare $git_version "1.7.2"] >= 0} {
217 set worddiff [mc "Markup words"]
220 "--stat=*" - "--numstat" - "--shortstat" - "--summary" -
221 "--check" - "--exit-code" - "--quiet" - "--topo-order" -
222 "--full-history" - "--dense" - "--sparse" -
223 "--follow" - "--left-right" - "--encoding=*" {
224 # These are harmless, and some are even useful
225 lappend glflags $arg
227 "--diff-filter=*" - "--no-merges" - "--unpacked" -
228 "--max-count=*" - "--skip=*" - "--since=*" - "--after=*" -
229 "--until=*" - "--before=*" - "--max-age=*" - "--min-age=*" -
230 "--author=*" - "--committer=*" - "--grep=*" - "-[iE]" -
231 "--remove-empty" - "--first-parent" - "--cherry-pick" -
232 "-S*" - "-G*" - "--pickaxe-all" - "--pickaxe-regex" -
233 "--simplify-by-decoration" {
234 # These mean that we get a subset of the commits
235 set filtered 1
236 lappend glflags $arg
238 "-L*" {
239 # Line-log with 'stuck' argument (unstuck form is
240 # not supported)
241 set filtered 1
242 set vinlinediff($n) 1
243 set allknown 0
244 lappend glflags $arg
246 "-n" {
247 # This appears to be the only one that has a value as a
248 # separate word following it
249 set filtered 1
250 set nextisval 1
251 lappend glflags $arg
253 "--not" - "--all" {
254 lappend revargs $arg
256 "--merge" {
257 set vmergeonly($n) 1
258 # git rev-parse doesn't understand --merge
259 lappend revargs --gitk-symmetric-diff-marker MERGE_HEAD...HEAD
261 "--no-replace-objects" {
262 set env(GIT_NO_REPLACE_OBJECTS) "1"
264 "-*" {
265 # Other flag arguments including -<n>
266 if {[string is digit -strict [string range $arg 1 end]]} {
267 set filtered 1
268 } else {
269 # a flag argument that we don't recognize;
270 # that means we can't optimize
271 set allknown 0
273 lappend glflags $arg
275 default {
276 # Non-flag arguments specify commits or ranges of commits
277 if {[string match "*...*" $arg]} {
278 lappend revargs --gitk-symmetric-diff-marker
280 lappend revargs $arg
284 set vdflags($n) $diffargs
285 set vflags($n) $glflags
286 set vrevs($n) $revargs
287 set vfiltered($n) $filtered
288 set vorigargs($n) $origargs
289 return $allknown
292 proc parseviewrevs {view revs} {
293 global vposids vnegids
295 if {$revs eq {}} {
296 set revs HEAD
297 } elseif {[lsearch -exact $revs --all] >= 0} {
298 lappend revs HEAD
300 if {[catch {set ids [eval exec git rev-parse $revs]} err]} {
301 # we get stdout followed by stderr in $err
302 # for an unknown rev, git rev-parse echoes it and then errors out
303 set errlines [split $err "\n"]
304 set badrev {}
305 for {set l 0} {$l < [llength $errlines]} {incr l} {
306 set line [lindex $errlines $l]
307 if {!([string length $line] == 40 && [string is xdigit $line])} {
308 if {[string match "fatal:*" $line]} {
309 if {[string match "fatal: ambiguous argument*" $line]
310 && $badrev ne {}} {
311 if {[llength $badrev] == 1} {
312 set err "unknown revision $badrev"
313 } else {
314 set err "unknown revisions: [join $badrev ", "]"
316 } else {
317 set err [join [lrange $errlines $l end] "\n"]
319 break
321 lappend badrev $line
324 error_popup "[mc "Error parsing revisions:"] $err"
325 return {}
327 set ret {}
328 set pos {}
329 set neg {}
330 set sdm 0
331 foreach id [split $ids "\n"] {
332 if {$id eq "--gitk-symmetric-diff-marker"} {
333 set sdm 4
334 } elseif {[string match "^*" $id]} {
335 if {$sdm != 1} {
336 lappend ret $id
337 if {$sdm == 3} {
338 set sdm 0
341 lappend neg [string range $id 1 end]
342 } else {
343 if {$sdm != 2} {
344 lappend ret $id
345 } else {
346 lset ret end $id...[lindex $ret end]
348 lappend pos $id
350 incr sdm -1
352 set vposids($view) $pos
353 set vnegids($view) $neg
354 return $ret
357 # Start off a git log process and arrange to read its output
358 proc start_rev_list {view} {
359 global startmsecs commitidx viewcomplete curview
360 global tclencoding
361 global viewargs viewargscmd viewfiles vfilelimit
362 global showlocalchanges
363 global viewactive viewinstances vmergeonly
364 global mainheadid viewmainheadid viewmainheadid_orig
365 global vcanopt vflags vrevs vorigargs
366 global show_notes
368 set startmsecs [clock clicks -milliseconds]
369 set commitidx($view) 0
370 # these are set this way for the error exits
371 set viewcomplete($view) 1
372 set viewactive($view) 0
373 varcinit $view
375 set args $viewargs($view)
376 if {$viewargscmd($view) ne {}} {
377 if {[catch {
378 set str [exec sh -c $viewargscmd($view)]
379 } err]} {
380 error_popup "[mc "Error executing --argscmd command:"] $err"
381 return 0
383 set args [concat $args [split $str "\n"]]
385 set vcanopt($view) [parseviewargs $view $args]
387 set files $viewfiles($view)
388 if {$vmergeonly($view)} {
389 set files [unmerged_files $files]
390 if {$files eq {}} {
391 global nr_unmerged
392 if {$nr_unmerged == 0} {
393 error_popup [mc "No files selected: --merge specified but\
394 no files are unmerged."]
395 } else {
396 error_popup [mc "No files selected: --merge specified but\
397 no unmerged files are within file limit."]
399 return 0
402 set vfilelimit($view) $files
404 if {$vcanopt($view)} {
405 set revs [parseviewrevs $view $vrevs($view)]
406 if {$revs eq {}} {
407 return 0
409 set args [concat $vflags($view) $revs]
410 } else {
411 set args $vorigargs($view)
414 if {[catch {
415 set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
416 --parents --boundary $args "--" $files] r]
417 } err]} {
418 error_popup "[mc "Error executing git log:"] $err"
419 return 0
421 set i [reg_instance $fd]
422 set viewinstances($view) [list $i]
423 set viewmainheadid($view) $mainheadid
424 set viewmainheadid_orig($view) $mainheadid
425 if {$files ne {} && $mainheadid ne {}} {
426 get_viewmainhead $view
428 if {$showlocalchanges && $viewmainheadid($view) ne {}} {
429 interestedin $viewmainheadid($view) dodiffindex
431 fconfigure $fd -blocking 0 -translation lf -eofchar {}
432 if {$tclencoding != {}} {
433 fconfigure $fd -encoding $tclencoding
435 filerun $fd [list getcommitlines $fd $i $view 0]
436 nowbusy $view [mc "Reading"]
437 set viewcomplete($view) 0
438 set viewactive($view) 1
439 return 1
442 proc stop_instance {inst} {
443 global commfd leftover
445 set fd $commfd($inst)
446 catch {
447 set pid [pid $fd]
449 if {$::tcl_platform(platform) eq {windows}} {
450 exec taskkill /pid $pid
451 } else {
452 exec kill $pid
455 catch {close $fd}
456 nukefile $fd
457 unset commfd($inst)
458 unset leftover($inst)
461 proc stop_backends {} {
462 global commfd
464 foreach inst [array names commfd] {
465 stop_instance $inst
469 proc stop_rev_list {view} {
470 global viewinstances
472 foreach inst $viewinstances($view) {
473 stop_instance $inst
475 set viewinstances($view) {}
478 proc reset_pending_select {selid} {
479 global pending_select mainheadid selectheadid
481 if {$selid ne {}} {
482 set pending_select $selid
483 } elseif {$selectheadid ne {}} {
484 set pending_select $selectheadid
485 } else {
486 set pending_select $mainheadid
490 proc getcommits {selid} {
491 global canv curview need_redisplay viewactive
493 initlayout
494 if {[start_rev_list $curview]} {
495 reset_pending_select $selid
496 show_status [mc "Reading commits..."]
497 set need_redisplay 1
498 } else {
499 show_status [mc "No commits selected"]
503 proc updatecommits {} {
504 global curview vcanopt vorigargs vfilelimit viewinstances
505 global viewactive viewcomplete tclencoding
506 global startmsecs showneartags showlocalchanges
507 global mainheadid viewmainheadid viewmainheadid_orig pending_select
508 global hasworktree
509 global varcid vposids vnegids vflags vrevs
510 global show_notes
512 set hasworktree [hasworktree]
513 rereadrefs
514 set view $curview
515 if {$mainheadid ne $viewmainheadid_orig($view)} {
516 if {$showlocalchanges} {
517 dohidelocalchanges
519 set viewmainheadid($view) $mainheadid
520 set viewmainheadid_orig($view) $mainheadid
521 if {$vfilelimit($view) ne {}} {
522 get_viewmainhead $view
525 if {$showlocalchanges} {
526 doshowlocalchanges
528 if {$vcanopt($view)} {
529 set oldpos $vposids($view)
530 set oldneg $vnegids($view)
531 set revs [parseviewrevs $view $vrevs($view)]
532 if {$revs eq {}} {
533 return
535 # note: getting the delta when negative refs change is hard,
536 # and could require multiple git log invocations, so in that
537 # case we ask git log for all the commits (not just the delta)
538 if {$oldneg eq $vnegids($view)} {
539 set newrevs {}
540 set npos 0
541 # take out positive refs that we asked for before or
542 # that we have already seen
543 foreach rev $revs {
544 if {[string length $rev] == 40} {
545 if {[lsearch -exact $oldpos $rev] < 0
546 && ![info exists varcid($view,$rev)]} {
547 lappend newrevs $rev
548 incr npos
550 } else {
551 lappend $newrevs $rev
554 if {$npos == 0} return
555 set revs $newrevs
556 set vposids($view) [lsort -unique [concat $oldpos $vposids($view)]]
558 set args [concat $vflags($view) $revs --not $oldpos]
559 } else {
560 set args $vorigargs($view)
562 if {[catch {
563 set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
564 --parents --boundary $args "--" $vfilelimit($view)] r]
565 } err]} {
566 error_popup "[mc "Error executing git log:"] $err"
567 return
569 if {$viewactive($view) == 0} {
570 set startmsecs [clock clicks -milliseconds]
572 set i [reg_instance $fd]
573 lappend viewinstances($view) $i
574 fconfigure $fd -blocking 0 -translation lf -eofchar {}
575 if {$tclencoding != {}} {
576 fconfigure $fd -encoding $tclencoding
578 filerun $fd [list getcommitlines $fd $i $view 1]
579 incr viewactive($view)
580 set viewcomplete($view) 0
581 reset_pending_select {}
582 nowbusy $view [mc "Reading"]
583 if {$showneartags} {
584 getallcommits
588 proc reloadcommits {} {
589 global curview viewcomplete selectedline currentid thickerline
590 global showneartags treediffs commitinterest cached_commitrow
591 global targetid
593 set selid {}
594 if {$selectedline ne {}} {
595 set selid $currentid
598 if {!$viewcomplete($curview)} {
599 stop_rev_list $curview
601 resetvarcs $curview
602 set selectedline {}
603 unset -nocomplain currentid
604 unset -nocomplain thickerline
605 unset -nocomplain treediffs
606 readrefs
607 changedrefs
608 if {$showneartags} {
609 getallcommits
611 clear_display
612 unset -nocomplain commitinterest
613 unset -nocomplain cached_commitrow
614 unset -nocomplain targetid
615 setcanvscroll
616 getcommits $selid
617 return 0
620 # This makes a string representation of a positive integer which
621 # sorts as a string in numerical order
622 proc strrep {n} {
623 if {$n < 16} {
624 return [format "%x" $n]
625 } elseif {$n < 256} {
626 return [format "x%.2x" $n]
627 } elseif {$n < 65536} {
628 return [format "y%.4x" $n]
630 return [format "z%.8x" $n]
633 # Procedures used in reordering commits from git log (without
634 # --topo-order) into the order for display.
636 proc varcinit {view} {
637 global varcstart vupptr vdownptr vleftptr vbackptr varctok varcrow
638 global vtokmod varcmod vrowmod varcix vlastins
640 set varcstart($view) {{}}
641 set vupptr($view) {0}
642 set vdownptr($view) {0}
643 set vleftptr($view) {0}
644 set vbackptr($view) {0}
645 set varctok($view) {{}}
646 set varcrow($view) {{}}
647 set vtokmod($view) {}
648 set varcmod($view) 0
649 set vrowmod($view) 0
650 set varcix($view) {{}}
651 set vlastins($view) {0}
654 proc resetvarcs {view} {
655 global varcid varccommits parents children vseedcount ordertok
656 global vshortids
658 foreach vid [array names varcid $view,*] {
659 unset varcid($vid)
660 unset children($vid)
661 unset parents($vid)
663 foreach vid [array names vshortids $view,*] {
664 unset vshortids($vid)
666 # some commits might have children but haven't been seen yet
667 foreach vid [array names children $view,*] {
668 unset children($vid)
670 foreach va [array names varccommits $view,*] {
671 unset varccommits($va)
673 foreach vd [array names vseedcount $view,*] {
674 unset vseedcount($vd)
676 unset -nocomplain ordertok
679 # returns a list of the commits with no children
680 proc seeds {v} {
681 global vdownptr vleftptr varcstart
683 set ret {}
684 set a [lindex $vdownptr($v) 0]
685 while {$a != 0} {
686 lappend ret [lindex $varcstart($v) $a]
687 set a [lindex $vleftptr($v) $a]
689 return $ret
692 proc newvarc {view id} {
693 global varcid varctok parents children vdatemode
694 global vupptr vdownptr vleftptr vbackptr varcrow varcix varcstart
695 global commitdata commitinfo vseedcount varccommits vlastins
697 set a [llength $varctok($view)]
698 set vid $view,$id
699 if {[llength $children($vid)] == 0 || $vdatemode($view)} {
700 if {![info exists commitinfo($id)]} {
701 parsecommit $id $commitdata($id) 1
703 set cdate [lindex [lindex $commitinfo($id) 4] 0]
704 if {![string is integer -strict $cdate]} {
705 set cdate 0
707 if {![info exists vseedcount($view,$cdate)]} {
708 set vseedcount($view,$cdate) -1
710 set c [incr vseedcount($view,$cdate)]
711 set cdate [expr {$cdate ^ 0xffffffff}]
712 set tok "s[strrep $cdate][strrep $c]"
713 } else {
714 set tok {}
716 set ka 0
717 if {[llength $children($vid)] > 0} {
718 set kid [lindex $children($vid) end]
719 set k $varcid($view,$kid)
720 if {[string compare [lindex $varctok($view) $k] $tok] > 0} {
721 set ki $kid
722 set ka $k
723 set tok [lindex $varctok($view) $k]
726 if {$ka != 0} {
727 set i [lsearch -exact $parents($view,$ki) $id]
728 set j [expr {[llength $parents($view,$ki)] - 1 - $i}]
729 append tok [strrep $j]
731 set c [lindex $vlastins($view) $ka]
732 if {$c == 0 || [string compare $tok [lindex $varctok($view) $c]] < 0} {
733 set c $ka
734 set b [lindex $vdownptr($view) $ka]
735 } else {
736 set b [lindex $vleftptr($view) $c]
738 while {$b != 0 && [string compare $tok [lindex $varctok($view) $b]] >= 0} {
739 set c $b
740 set b [lindex $vleftptr($view) $c]
742 if {$c == $ka} {
743 lset vdownptr($view) $ka $a
744 lappend vbackptr($view) 0
745 } else {
746 lset vleftptr($view) $c $a
747 lappend vbackptr($view) $c
749 lset vlastins($view) $ka $a
750 lappend vupptr($view) $ka
751 lappend vleftptr($view) $b
752 if {$b != 0} {
753 lset vbackptr($view) $b $a
755 lappend varctok($view) $tok
756 lappend varcstart($view) $id
757 lappend vdownptr($view) 0
758 lappend varcrow($view) {}
759 lappend varcix($view) {}
760 set varccommits($view,$a) {}
761 lappend vlastins($view) 0
762 return $a
765 proc splitvarc {p v} {
766 global varcid varcstart varccommits varctok vtokmod
767 global vupptr vdownptr vleftptr vbackptr varcix varcrow vlastins
769 set oa $varcid($v,$p)
770 set otok [lindex $varctok($v) $oa]
771 set ac $varccommits($v,$oa)
772 set i [lsearch -exact $varccommits($v,$oa) $p]
773 if {$i <= 0} return
774 set na [llength $varctok($v)]
775 # "%" sorts before "0"...
776 set tok "$otok%[strrep $i]"
777 lappend varctok($v) $tok
778 lappend varcrow($v) {}
779 lappend varcix($v) {}
780 set varccommits($v,$oa) [lrange $ac 0 [expr {$i - 1}]]
781 set varccommits($v,$na) [lrange $ac $i end]
782 lappend varcstart($v) $p
783 foreach id $varccommits($v,$na) {
784 set varcid($v,$id) $na
786 lappend vdownptr($v) [lindex $vdownptr($v) $oa]
787 lappend vlastins($v) [lindex $vlastins($v) $oa]
788 lset vdownptr($v) $oa $na
789 lset vlastins($v) $oa 0
790 lappend vupptr($v) $oa
791 lappend vleftptr($v) 0
792 lappend vbackptr($v) 0
793 for {set b [lindex $vdownptr($v) $na]} {$b != 0} {set b [lindex $vleftptr($v) $b]} {
794 lset vupptr($v) $b $na
796 if {[string compare $otok $vtokmod($v)] <= 0} {
797 modify_arc $v $oa
801 proc renumbervarc {a v} {
802 global parents children varctok varcstart varccommits
803 global vupptr vdownptr vleftptr vbackptr vlastins varcid vtokmod vdatemode
805 set t1 [clock clicks -milliseconds]
806 set todo {}
807 set isrelated($a) 1
808 set kidchanged($a) 1
809 set ntot 0
810 while {$a != 0} {
811 if {[info exists isrelated($a)]} {
812 lappend todo $a
813 set id [lindex $varccommits($v,$a) end]
814 foreach p $parents($v,$id) {
815 if {[info exists varcid($v,$p)]} {
816 set isrelated($varcid($v,$p)) 1
820 incr ntot
821 set b [lindex $vdownptr($v) $a]
822 if {$b == 0} {
823 while {$a != 0} {
824 set b [lindex $vleftptr($v) $a]
825 if {$b != 0} break
826 set a [lindex $vupptr($v) $a]
829 set a $b
831 foreach a $todo {
832 if {![info exists kidchanged($a)]} continue
833 set id [lindex $varcstart($v) $a]
834 if {[llength $children($v,$id)] > 1} {
835 set children($v,$id) [lsort -command [list vtokcmp $v] \
836 $children($v,$id)]
838 set oldtok [lindex $varctok($v) $a]
839 if {!$vdatemode($v)} {
840 set tok {}
841 } else {
842 set tok $oldtok
844 set ka 0
845 set kid [last_real_child $v,$id]
846 if {$kid ne {}} {
847 set k $varcid($v,$kid)
848 if {[string compare [lindex $varctok($v) $k] $tok] > 0} {
849 set ki $kid
850 set ka $k
851 set tok [lindex $varctok($v) $k]
854 if {$ka != 0} {
855 set i [lsearch -exact $parents($v,$ki) $id]
856 set j [expr {[llength $parents($v,$ki)] - 1 - $i}]
857 append tok [strrep $j]
859 if {$tok eq $oldtok} {
860 continue
862 set id [lindex $varccommits($v,$a) end]
863 foreach p $parents($v,$id) {
864 if {[info exists varcid($v,$p)]} {
865 set kidchanged($varcid($v,$p)) 1
866 } else {
867 set sortkids($p) 1
870 lset varctok($v) $a $tok
871 set b [lindex $vupptr($v) $a]
872 if {$b != $ka} {
873 if {[string compare [lindex $varctok($v) $ka] $vtokmod($v)] < 0} {
874 modify_arc $v $ka
876 if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
877 modify_arc $v $b
879 set c [lindex $vbackptr($v) $a]
880 set d [lindex $vleftptr($v) $a]
881 if {$c == 0} {
882 lset vdownptr($v) $b $d
883 } else {
884 lset vleftptr($v) $c $d
886 if {$d != 0} {
887 lset vbackptr($v) $d $c
889 if {[lindex $vlastins($v) $b] == $a} {
890 lset vlastins($v) $b $c
892 lset vupptr($v) $a $ka
893 set c [lindex $vlastins($v) $ka]
894 if {$c == 0 || \
895 [string compare $tok [lindex $varctok($v) $c]] < 0} {
896 set c $ka
897 set b [lindex $vdownptr($v) $ka]
898 } else {
899 set b [lindex $vleftptr($v) $c]
901 while {$b != 0 && \
902 [string compare $tok [lindex $varctok($v) $b]] >= 0} {
903 set c $b
904 set b [lindex $vleftptr($v) $c]
906 if {$c == $ka} {
907 lset vdownptr($v) $ka $a
908 lset vbackptr($v) $a 0
909 } else {
910 lset vleftptr($v) $c $a
911 lset vbackptr($v) $a $c
913 lset vleftptr($v) $a $b
914 if {$b != 0} {
915 lset vbackptr($v) $b $a
917 lset vlastins($v) $ka $a
920 foreach id [array names sortkids] {
921 if {[llength $children($v,$id)] > 1} {
922 set children($v,$id) [lsort -command [list vtokcmp $v] \
923 $children($v,$id)]
926 set t2 [clock clicks -milliseconds]
927 #puts "renumbervarc did [llength $todo] of $ntot arcs in [expr {$t2-$t1}]ms"
930 # Fix up the graph after we have found out that in view $v,
931 # $p (a commit that we have already seen) is actually the parent
932 # of the last commit in arc $a.
933 proc fix_reversal {p a v} {
934 global varcid varcstart varctok vupptr
936 set pa $varcid($v,$p)
937 if {$p ne [lindex $varcstart($v) $pa]} {
938 splitvarc $p $v
939 set pa $varcid($v,$p)
941 # seeds always need to be renumbered
942 if {[lindex $vupptr($v) $pa] == 0 ||
943 [string compare [lindex $varctok($v) $a] \
944 [lindex $varctok($v) $pa]] > 0} {
945 renumbervarc $pa $v
949 proc insertrow {id p v} {
950 global cmitlisted children parents varcid varctok vtokmod
951 global varccommits ordertok commitidx numcommits curview
952 global targetid targetrow vshortids
954 readcommit $id
955 set vid $v,$id
956 set cmitlisted($vid) 1
957 set children($vid) {}
958 set parents($vid) [list $p]
959 set a [newvarc $v $id]
960 set varcid($vid) $a
961 lappend vshortids($v,[string range $id 0 3]) $id
962 if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] < 0} {
963 modify_arc $v $a
965 lappend varccommits($v,$a) $id
966 set vp $v,$p
967 if {[llength [lappend children($vp) $id]] > 1} {
968 set children($vp) [lsort -command [list vtokcmp $v] $children($vp)]
969 unset -nocomplain ordertok
971 fix_reversal $p $a $v
972 incr commitidx($v)
973 if {$v == $curview} {
974 set numcommits $commitidx($v)
975 setcanvscroll
976 if {[info exists targetid]} {
977 if {![comes_before $targetid $p]} {
978 incr targetrow
984 proc insertfakerow {id p} {
985 global varcid varccommits parents children cmitlisted
986 global commitidx varctok vtokmod targetid targetrow curview numcommits
988 set v $curview
989 set a $varcid($v,$p)
990 set i [lsearch -exact $varccommits($v,$a) $p]
991 if {$i < 0} {
992 puts "oops: insertfakerow can't find [shortids $p] on arc $a"
993 return
995 set children($v,$id) {}
996 set parents($v,$id) [list $p]
997 set varcid($v,$id) $a
998 lappend children($v,$p) $id
999 set cmitlisted($v,$id) 1
1000 set numcommits [incr commitidx($v)]
1001 # note we deliberately don't update varcstart($v) even if $i == 0
1002 set varccommits($v,$a) [linsert $varccommits($v,$a) $i $id]
1003 modify_arc $v $a $i
1004 if {[info exists targetid]} {
1005 if {![comes_before $targetid $p]} {
1006 incr targetrow
1009 setcanvscroll
1010 drawvisible
1013 proc removefakerow {id} {
1014 global varcid varccommits parents children commitidx
1015 global varctok vtokmod cmitlisted currentid selectedline
1016 global targetid curview numcommits
1018 set v $curview
1019 if {[llength $parents($v,$id)] != 1} {
1020 puts "oops: removefakerow [shortids $id] has [llength $parents($v,$id)] parents"
1021 return
1023 set p [lindex $parents($v,$id) 0]
1024 set a $varcid($v,$id)
1025 set i [lsearch -exact $varccommits($v,$a) $id]
1026 if {$i < 0} {
1027 puts "oops: removefakerow can't find [shortids $id] on arc $a"
1028 return
1030 unset varcid($v,$id)
1031 set varccommits($v,$a) [lreplace $varccommits($v,$a) $i $i]
1032 unset parents($v,$id)
1033 unset children($v,$id)
1034 unset cmitlisted($v,$id)
1035 set numcommits [incr commitidx($v) -1]
1036 set j [lsearch -exact $children($v,$p) $id]
1037 if {$j >= 0} {
1038 set children($v,$p) [lreplace $children($v,$p) $j $j]
1040 modify_arc $v $a $i
1041 if {[info exist currentid] && $id eq $currentid} {
1042 unset currentid
1043 set selectedline {}
1045 if {[info exists targetid] && $targetid eq $id} {
1046 set targetid $p
1048 setcanvscroll
1049 drawvisible
1052 proc real_children {vp} {
1053 global children nullid nullid2
1055 set kids {}
1056 foreach id $children($vp) {
1057 if {$id ne $nullid && $id ne $nullid2} {
1058 lappend kids $id
1061 return $kids
1064 proc first_real_child {vp} {
1065 global children nullid nullid2
1067 foreach id $children($vp) {
1068 if {$id ne $nullid && $id ne $nullid2} {
1069 return $id
1072 return {}
1075 proc last_real_child {vp} {
1076 global children nullid nullid2
1078 set kids $children($vp)
1079 for {set i [llength $kids]} {[incr i -1] >= 0} {} {
1080 set id [lindex $kids $i]
1081 if {$id ne $nullid && $id ne $nullid2} {
1082 return $id
1085 return {}
1088 proc vtokcmp {v a b} {
1089 global varctok varcid
1091 return [string compare [lindex $varctok($v) $varcid($v,$a)] \
1092 [lindex $varctok($v) $varcid($v,$b)]]
1095 # This assumes that if lim is not given, the caller has checked that
1096 # arc a's token is less than $vtokmod($v)
1097 proc modify_arc {v a {lim {}}} {
1098 global varctok vtokmod varcmod varcrow vupptr curview vrowmod varccommits
1100 if {$lim ne {}} {
1101 set c [string compare [lindex $varctok($v) $a] $vtokmod($v)]
1102 if {$c > 0} return
1103 if {$c == 0} {
1104 set r [lindex $varcrow($v) $a]
1105 if {$r ne {} && $vrowmod($v) <= $r + $lim} return
1108 set vtokmod($v) [lindex $varctok($v) $a]
1109 set varcmod($v) $a
1110 if {$v == $curview} {
1111 while {$a != 0 && [lindex $varcrow($v) $a] eq {}} {
1112 set a [lindex $vupptr($v) $a]
1113 set lim {}
1115 set r 0
1116 if {$a != 0} {
1117 if {$lim eq {}} {
1118 set lim [llength $varccommits($v,$a)]
1120 set r [expr {[lindex $varcrow($v) $a] + $lim}]
1122 set vrowmod($v) $r
1123 undolayout $r
1127 proc update_arcrows {v} {
1128 global vtokmod varcmod vrowmod varcrow commitidx currentid selectedline
1129 global varcid vrownum varcorder varcix varccommits
1130 global vupptr vdownptr vleftptr varctok
1131 global displayorder parentlist curview cached_commitrow
1133 if {$vrowmod($v) == $commitidx($v)} return
1134 if {$v == $curview} {
1135 if {[llength $displayorder] > $vrowmod($v)} {
1136 set displayorder [lrange $displayorder 0 [expr {$vrowmod($v) - 1}]]
1137 set parentlist [lrange $parentlist 0 [expr {$vrowmod($v) - 1}]]
1139 unset -nocomplain cached_commitrow
1141 set narctot [expr {[llength $varctok($v)] - 1}]
1142 set a $varcmod($v)
1143 while {$a != 0 && [lindex $varcix($v) $a] eq {}} {
1144 # go up the tree until we find something that has a row number,
1145 # or we get to a seed
1146 set a [lindex $vupptr($v) $a]
1148 if {$a == 0} {
1149 set a [lindex $vdownptr($v) 0]
1150 if {$a == 0} return
1151 set vrownum($v) {0}
1152 set varcorder($v) [list $a]
1153 lset varcix($v) $a 0
1154 lset varcrow($v) $a 0
1155 set arcn 0
1156 set row 0
1157 } else {
1158 set arcn [lindex $varcix($v) $a]
1159 if {[llength $vrownum($v)] > $arcn + 1} {
1160 set vrownum($v) [lrange $vrownum($v) 0 $arcn]
1161 set varcorder($v) [lrange $varcorder($v) 0 $arcn]
1163 set row [lindex $varcrow($v) $a]
1165 while {1} {
1166 set p $a
1167 incr row [llength $varccommits($v,$a)]
1168 # go down if possible
1169 set b [lindex $vdownptr($v) $a]
1170 if {$b == 0} {
1171 # if not, go left, or go up until we can go left
1172 while {$a != 0} {
1173 set b [lindex $vleftptr($v) $a]
1174 if {$b != 0} break
1175 set a [lindex $vupptr($v) $a]
1177 if {$a == 0} break
1179 set a $b
1180 incr arcn
1181 lappend vrownum($v) $row
1182 lappend varcorder($v) $a
1183 lset varcix($v) $a $arcn
1184 lset varcrow($v) $a $row
1186 set vtokmod($v) [lindex $varctok($v) $p]
1187 set varcmod($v) $p
1188 set vrowmod($v) $row
1189 if {[info exists currentid]} {
1190 set selectedline [rowofcommit $currentid]
1194 # Test whether view $v contains commit $id
1195 proc commitinview {id v} {
1196 global varcid
1198 return [info exists varcid($v,$id)]
1201 # Return the row number for commit $id in the current view
1202 proc rowofcommit {id} {
1203 global varcid varccommits varcrow curview cached_commitrow
1204 global varctok vtokmod
1206 set v $curview
1207 if {![info exists varcid($v,$id)]} {
1208 puts "oops rowofcommit no arc for [shortids $id]"
1209 return {}
1211 set a $varcid($v,$id)
1212 if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] >= 0} {
1213 update_arcrows $v
1215 if {[info exists cached_commitrow($id)]} {
1216 return $cached_commitrow($id)
1218 set i [lsearch -exact $varccommits($v,$a) $id]
1219 if {$i < 0} {
1220 puts "oops didn't find commit [shortids $id] in arc $a"
1221 return {}
1223 incr i [lindex $varcrow($v) $a]
1224 set cached_commitrow($id) $i
1225 return $i
1228 # Returns 1 if a is on an earlier row than b, otherwise 0
1229 proc comes_before {a b} {
1230 global varcid varctok curview
1232 set v $curview
1233 if {$a eq $b || ![info exists varcid($v,$a)] || \
1234 ![info exists varcid($v,$b)]} {
1235 return 0
1237 if {$varcid($v,$a) != $varcid($v,$b)} {
1238 return [expr {[string compare [lindex $varctok($v) $varcid($v,$a)] \
1239 [lindex $varctok($v) $varcid($v,$b)]] < 0}]
1241 return [expr {[rowofcommit $a] < [rowofcommit $b]}]
1244 proc bsearch {l elt} {
1245 if {[llength $l] == 0 || $elt <= [lindex $l 0]} {
1246 return 0
1248 set lo 0
1249 set hi [llength $l]
1250 while {$hi - $lo > 1} {
1251 set mid [expr {int(($lo + $hi) / 2)}]
1252 set t [lindex $l $mid]
1253 if {$elt < $t} {
1254 set hi $mid
1255 } elseif {$elt > $t} {
1256 set lo $mid
1257 } else {
1258 return $mid
1261 return $lo
1264 # Make sure rows $start..$end-1 are valid in displayorder and parentlist
1265 proc make_disporder {start end} {
1266 global vrownum curview commitidx displayorder parentlist
1267 global varccommits varcorder parents vrowmod varcrow
1268 global d_valid_start d_valid_end
1270 if {$end > $vrowmod($curview)} {
1271 update_arcrows $curview
1273 set ai [bsearch $vrownum($curview) $start]
1274 set start [lindex $vrownum($curview) $ai]
1275 set narc [llength $vrownum($curview)]
1276 for {set r $start} {$ai < $narc && $r < $end} {incr ai} {
1277 set a [lindex $varcorder($curview) $ai]
1278 set l [llength $displayorder]
1279 set al [llength $varccommits($curview,$a)]
1280 if {$l < $r + $al} {
1281 if {$l < $r} {
1282 set pad [ntimes [expr {$r - $l}] {}]
1283 set displayorder [concat $displayorder $pad]
1284 set parentlist [concat $parentlist $pad]
1285 } elseif {$l > $r} {
1286 set displayorder [lrange $displayorder 0 [expr {$r - 1}]]
1287 set parentlist [lrange $parentlist 0 [expr {$r - 1}]]
1289 foreach id $varccommits($curview,$a) {
1290 lappend displayorder $id
1291 lappend parentlist $parents($curview,$id)
1293 } elseif {[lindex $displayorder [expr {$r + $al - 1}]] eq {}} {
1294 set i $r
1295 foreach id $varccommits($curview,$a) {
1296 lset displayorder $i $id
1297 lset parentlist $i $parents($curview,$id)
1298 incr i
1301 incr r $al
1305 proc commitonrow {row} {
1306 global displayorder
1308 set id [lindex $displayorder $row]
1309 if {$id eq {}} {
1310 make_disporder $row [expr {$row + 1}]
1311 set id [lindex $displayorder $row]
1313 return $id
1316 proc closevarcs {v} {
1317 global varctok varccommits varcid parents children
1318 global cmitlisted commitidx vtokmod
1320 set missing_parents 0
1321 set scripts {}
1322 set narcs [llength $varctok($v)]
1323 for {set a 1} {$a < $narcs} {incr a} {
1324 set id [lindex $varccommits($v,$a) end]
1325 foreach p $parents($v,$id) {
1326 if {[info exists varcid($v,$p)]} continue
1327 # add p as a new commit
1328 incr missing_parents
1329 set cmitlisted($v,$p) 0
1330 set parents($v,$p) {}
1331 if {[llength $children($v,$p)] == 1 &&
1332 [llength $parents($v,$id)] == 1} {
1333 set b $a
1334 } else {
1335 set b [newvarc $v $p]
1337 set varcid($v,$p) $b
1338 if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
1339 modify_arc $v $b
1341 lappend varccommits($v,$b) $p
1342 incr commitidx($v)
1343 set scripts [check_interest $p $scripts]
1346 if {$missing_parents > 0} {
1347 foreach s $scripts {
1348 eval $s
1353 # Use $rwid as a substitute for $id, i.e. reparent $id's children to $rwid
1354 # Assumes we already have an arc for $rwid.
1355 proc rewrite_commit {v id rwid} {
1356 global children parents varcid varctok vtokmod varccommits
1358 foreach ch $children($v,$id) {
1359 # make $rwid be $ch's parent in place of $id
1360 set i [lsearch -exact $parents($v,$ch) $id]
1361 if {$i < 0} {
1362 puts "oops rewrite_commit didn't find $id in parent list for $ch"
1364 set parents($v,$ch) [lreplace $parents($v,$ch) $i $i $rwid]
1365 # add $ch to $rwid's children and sort the list if necessary
1366 if {[llength [lappend children($v,$rwid) $ch]] > 1} {
1367 set children($v,$rwid) [lsort -command [list vtokcmp $v] \
1368 $children($v,$rwid)]
1370 # fix the graph after joining $id to $rwid
1371 set a $varcid($v,$ch)
1372 fix_reversal $rwid $a $v
1373 # parentlist is wrong for the last element of arc $a
1374 # even if displayorder is right, hence the 3rd arg here
1375 modify_arc $v $a [expr {[llength $varccommits($v,$a)] - 1}]
1379 # Mechanism for registering a command to be executed when we come
1380 # across a particular commit. To handle the case when only the
1381 # prefix of the commit is known, the commitinterest array is now
1382 # indexed by the first 4 characters of the ID. Each element is a
1383 # list of id, cmd pairs.
1384 proc interestedin {id cmd} {
1385 global commitinterest
1387 lappend commitinterest([string range $id 0 3]) $id $cmd
1390 proc check_interest {id scripts} {
1391 global commitinterest
1393 set prefix [string range $id 0 3]
1394 if {[info exists commitinterest($prefix)]} {
1395 set newlist {}
1396 foreach {i script} $commitinterest($prefix) {
1397 if {[string match "$i*" $id]} {
1398 lappend scripts [string map [list "%I" $id "%P" $i] $script]
1399 } else {
1400 lappend newlist $i $script
1403 if {$newlist ne {}} {
1404 set commitinterest($prefix) $newlist
1405 } else {
1406 unset commitinterest($prefix)
1409 return $scripts
1412 proc getcommitlines {fd inst view updating} {
1413 global cmitlisted leftover
1414 global commitidx commitdata vdatemode
1415 global parents children curview hlview
1416 global idpending ordertok
1417 global varccommits varcid varctok vtokmod vfilelimit vshortids
1419 set stuff [read $fd 500000]
1420 # git log doesn't terminate the last commit with a null...
1421 if {$stuff == {} && $leftover($inst) ne {} && [eof $fd]} {
1422 set stuff "\0"
1424 if {$stuff == {}} {
1425 if {![eof $fd]} {
1426 return 1
1428 global commfd viewcomplete viewactive viewname
1429 global viewinstances
1430 unset commfd($inst)
1431 set i [lsearch -exact $viewinstances($view) $inst]
1432 if {$i >= 0} {
1433 set viewinstances($view) [lreplace $viewinstances($view) $i $i]
1435 # set it blocking so we wait for the process to terminate
1436 fconfigure $fd -blocking 1
1437 if {[catch {close $fd} err]} {
1438 set fv {}
1439 if {$view != $curview} {
1440 set fv " for the \"$viewname($view)\" view"
1442 if {[string range $err 0 4] == "usage"} {
1443 set err "Gitk: error reading commits$fv:\
1444 bad arguments to git log."
1445 if {$viewname($view) eq [mc "Command line"]} {
1446 append err \
1447 " (Note: arguments to gitk are passed to git log\
1448 to allow selection of commits to be displayed.)"
1450 } else {
1451 set err "Error reading commits$fv: $err"
1453 error_popup $err
1455 if {[incr viewactive($view) -1] <= 0} {
1456 set viewcomplete($view) 1
1457 # Check if we have seen any ids listed as parents that haven't
1458 # appeared in the list
1459 closevarcs $view
1460 notbusy $view
1462 if {$view == $curview} {
1463 run chewcommits
1465 return 0
1467 set start 0
1468 set gotsome 0
1469 set scripts {}
1470 while 1 {
1471 set i [string first "\0" $stuff $start]
1472 if {$i < 0} {
1473 append leftover($inst) [string range $stuff $start end]
1474 break
1476 if {$start == 0} {
1477 set cmit $leftover($inst)
1478 append cmit [string range $stuff 0 [expr {$i - 1}]]
1479 set leftover($inst) {}
1480 } else {
1481 set cmit [string range $stuff $start [expr {$i - 1}]]
1483 set start [expr {$i + 1}]
1484 set j [string first "\n" $cmit]
1485 set ok 0
1486 set listed 1
1487 if {$j >= 0 && [string match "commit *" $cmit]} {
1488 set ids [string range $cmit 7 [expr {$j - 1}]]
1489 if {[string match {[-^<>]*} $ids]} {
1490 switch -- [string index $ids 0] {
1491 "-" {set listed 0}
1492 "^" {set listed 2}
1493 "<" {set listed 3}
1494 ">" {set listed 4}
1496 set ids [string range $ids 1 end]
1498 set ok 1
1499 foreach id $ids {
1500 if {[string length $id] != 40} {
1501 set ok 0
1502 break
1506 if {!$ok} {
1507 set shortcmit $cmit
1508 if {[string length $shortcmit] > 80} {
1509 set shortcmit "[string range $shortcmit 0 80]..."
1511 error_popup "[mc "Can't parse git log output:"] {$shortcmit}"
1512 exit 1
1514 set id [lindex $ids 0]
1515 set vid $view,$id
1517 lappend vshortids($view,[string range $id 0 3]) $id
1519 if {!$listed && $updating && ![info exists varcid($vid)] &&
1520 $vfilelimit($view) ne {}} {
1521 # git log doesn't rewrite parents for unlisted commits
1522 # when doing path limiting, so work around that here
1523 # by working out the rewritten parent with git rev-list
1524 # and if we already know about it, using the rewritten
1525 # parent as a substitute parent for $id's children.
1526 if {![catch {
1527 set rwid [exec git rev-list --first-parent --max-count=1 \
1528 $id -- $vfilelimit($view)]
1529 }]} {
1530 if {$rwid ne {} && [info exists varcid($view,$rwid)]} {
1531 # use $rwid in place of $id
1532 rewrite_commit $view $id $rwid
1533 continue
1538 set a 0
1539 if {[info exists varcid($vid)]} {
1540 if {$cmitlisted($vid) || !$listed} continue
1541 set a $varcid($vid)
1543 if {$listed} {
1544 set olds [lrange $ids 1 end]
1545 } else {
1546 set olds {}
1548 set commitdata($id) [string range $cmit [expr {$j + 1}] end]
1549 set cmitlisted($vid) $listed
1550 set parents($vid) $olds
1551 if {![info exists children($vid)]} {
1552 set children($vid) {}
1553 } elseif {$a == 0 && [llength $children($vid)] == 1} {
1554 set k [lindex $children($vid) 0]
1555 if {[llength $parents($view,$k)] == 1 &&
1556 (!$vdatemode($view) ||
1557 $varcid($view,$k) == [llength $varctok($view)] - 1)} {
1558 set a $varcid($view,$k)
1561 if {$a == 0} {
1562 # new arc
1563 set a [newvarc $view $id]
1565 if {[string compare [lindex $varctok($view) $a] $vtokmod($view)] < 0} {
1566 modify_arc $view $a
1568 if {![info exists varcid($vid)]} {
1569 set varcid($vid) $a
1570 lappend varccommits($view,$a) $id
1571 incr commitidx($view)
1574 set i 0
1575 foreach p $olds {
1576 if {$i == 0 || [lsearch -exact $olds $p] >= $i} {
1577 set vp $view,$p
1578 if {[llength [lappend children($vp) $id]] > 1 &&
1579 [vtokcmp $view [lindex $children($vp) end-1] $id] > 0} {
1580 set children($vp) [lsort -command [list vtokcmp $view] \
1581 $children($vp)]
1582 unset -nocomplain ordertok
1584 if {[info exists varcid($view,$p)]} {
1585 fix_reversal $p $a $view
1588 incr i
1591 set scripts [check_interest $id $scripts]
1592 set gotsome 1
1594 if {$gotsome} {
1595 global numcommits hlview
1597 if {$view == $curview} {
1598 set numcommits $commitidx($view)
1599 run chewcommits
1601 if {[info exists hlview] && $view == $hlview} {
1602 # we never actually get here...
1603 run vhighlightmore
1605 foreach s $scripts {
1606 eval $s
1609 return 2
1612 proc chewcommits {} {
1613 global curview hlview viewcomplete
1614 global pending_select
1616 layoutmore
1617 if {$viewcomplete($curview)} {
1618 global commitidx varctok
1619 global numcommits startmsecs
1621 if {[info exists pending_select]} {
1622 update
1623 reset_pending_select {}
1625 if {[commitinview $pending_select $curview]} {
1626 selectline [rowofcommit $pending_select] 1
1627 } else {
1628 set row [first_real_row]
1629 selectline $row 1
1632 if {$commitidx($curview) > 0} {
1633 #set ms [expr {[clock clicks -milliseconds] - $startmsecs}]
1634 #puts "overall $ms ms for $numcommits commits"
1635 #puts "[llength $varctok($view)] arcs, $commitidx($view) commits"
1636 } else {
1637 show_status [mc "No commits selected"]
1639 notbusy layout
1641 return 0
1644 proc do_readcommit {id} {
1645 global tclencoding
1647 # Invoke git-log to handle automatic encoding conversion
1648 set fd [open [concat | git log --no-color --pretty=raw -1 $id] r]
1649 # Read the results using i18n.logoutputencoding
1650 fconfigure $fd -translation lf -eofchar {}
1651 if {$tclencoding != {}} {
1652 fconfigure $fd -encoding $tclencoding
1654 set contents [read $fd]
1655 close $fd
1656 # Remove the heading line
1657 regsub {^commit [0-9a-f]+\n} $contents {} contents
1659 return $contents
1662 proc readcommit {id} {
1663 if {[catch {set contents [do_readcommit $id]}]} return
1664 parsecommit $id $contents 1
1667 proc parsecommit {id contents listed} {
1668 global commitinfo
1670 set inhdr 1
1671 set comment {}
1672 set headline {}
1673 set auname {}
1674 set audate {}
1675 set comname {}
1676 set comdate {}
1677 set hdrend [string first "\n\n" $contents]
1678 if {$hdrend < 0} {
1679 # should never happen...
1680 set hdrend [string length $contents]
1682 set header [string range $contents 0 [expr {$hdrend - 1}]]
1683 set comment [string range $contents [expr {$hdrend + 2}] end]
1684 foreach line [split $header "\n"] {
1685 set line [split $line " "]
1686 set tag [lindex $line 0]
1687 if {$tag == "author"} {
1688 set audate [lrange $line end-1 end]
1689 set auname [join [lrange $line 1 end-2] " "]
1690 } elseif {$tag == "committer"} {
1691 set comdate [lrange $line end-1 end]
1692 set comname [join [lrange $line 1 end-2] " "]
1695 set headline {}
1696 # take the first non-blank line of the comment as the headline
1697 set headline [string trimleft $comment]
1698 set i [string first "\n" $headline]
1699 if {$i >= 0} {
1700 set headline [string range $headline 0 $i]
1702 set headline [string trimright $headline]
1703 set i [string first "\r" $headline]
1704 if {$i >= 0} {
1705 set headline [string trimright [string range $headline 0 $i]]
1707 if {!$listed} {
1708 # git log indents the comment by 4 spaces;
1709 # if we got this via git cat-file, add the indentation
1710 set newcomment {}
1711 foreach line [split $comment "\n"] {
1712 append newcomment " "
1713 append newcomment $line
1714 append newcomment "\n"
1716 set comment $newcomment
1718 set hasnote [string first "\nNotes:\n" $contents]
1719 set diff ""
1720 # If there is diff output shown in the git-log stream, split it
1721 # out. But get rid of the empty line that always precedes the
1722 # diff.
1723 set i [string first "\n\ndiff" $comment]
1724 if {$i >= 0} {
1725 set diff [string range $comment $i+1 end]
1726 set comment [string range $comment 0 $i-1]
1728 set commitinfo($id) [list $headline $auname $audate \
1729 $comname $comdate $comment $hasnote $diff]
1732 proc getcommit {id} {
1733 global commitdata commitinfo
1735 if {[info exists commitdata($id)]} {
1736 parsecommit $id $commitdata($id) 1
1737 } else {
1738 readcommit $id
1739 if {![info exists commitinfo($id)]} {
1740 set commitinfo($id) [list [mc "No commit information available"]]
1743 return 1
1746 # Expand an abbreviated commit ID to a list of full 40-char IDs that match
1747 # and are present in the current view.
1748 # This is fairly slow...
1749 proc longid {prefix} {
1750 global varcid curview vshortids
1752 set ids {}
1753 if {[string length $prefix] >= 4} {
1754 set vshortid $curview,[string range $prefix 0 3]
1755 if {[info exists vshortids($vshortid)]} {
1756 foreach id $vshortids($vshortid) {
1757 if {[string match "$prefix*" $id]} {
1758 if {[lsearch -exact $ids $id] < 0} {
1759 lappend ids $id
1760 if {[llength $ids] >= 2} break
1765 } else {
1766 foreach match [array names varcid "$curview,$prefix*"] {
1767 lappend ids [lindex [split $match ","] 1]
1768 if {[llength $ids] >= 2} break
1771 return $ids
1774 proc readrefs {} {
1775 global tagids idtags headids idheads tagobjid
1776 global otherrefids idotherrefs mainhead mainheadid
1777 global selecthead selectheadid
1778 global hideremotes
1780 foreach v {tagids idtags headids idheads otherrefids idotherrefs} {
1781 unset -nocomplain $v
1783 set refd [open [list | git show-ref -d] r]
1784 while {[gets $refd line] >= 0} {
1785 if {[string index $line 40] ne " "} continue
1786 set id [string range $line 0 39]
1787 set ref [string range $line 41 end]
1788 if {![string match "refs/*" $ref]} continue
1789 set name [string range $ref 5 end]
1790 if {[string match "remotes/*" $name]} {
1791 if {![string match "*/HEAD" $name] && !$hideremotes} {
1792 set headids($name) $id
1793 lappend idheads($id) $name
1795 } elseif {[string match "heads/*" $name]} {
1796 set name [string range $name 6 end]
1797 set headids($name) $id
1798 lappend idheads($id) $name
1799 } elseif {[string match "tags/*" $name]} {
1800 # this lets refs/tags/foo^{} overwrite refs/tags/foo,
1801 # which is what we want since the former is the commit ID
1802 set name [string range $name 5 end]
1803 if {[string match "*^{}" $name]} {
1804 set name [string range $name 0 end-3]
1805 } else {
1806 set tagobjid($name) $id
1808 set tagids($name) $id
1809 lappend idtags($id) $name
1810 } else {
1811 set otherrefids($name) $id
1812 lappend idotherrefs($id) $name
1815 catch {close $refd}
1816 set mainhead {}
1817 set mainheadid {}
1818 catch {
1819 set mainheadid [exec git rev-parse HEAD]
1820 set thehead [exec git symbolic-ref HEAD]
1821 if {[string match "refs/heads/*" $thehead]} {
1822 set mainhead [string range $thehead 11 end]
1825 set selectheadid {}
1826 if {$selecthead ne {}} {
1827 catch {
1828 set selectheadid [exec git rev-parse --verify $selecthead]
1833 # skip over fake commits
1834 proc first_real_row {} {
1835 global nullid nullid2 numcommits
1837 for {set row 0} {$row < $numcommits} {incr row} {
1838 set id [commitonrow $row]
1839 if {$id ne $nullid && $id ne $nullid2} {
1840 break
1843 return $row
1846 # update things for a head moved to a child of its previous location
1847 proc movehead {id name} {
1848 global headids idheads
1850 removehead $headids($name) $name
1851 set headids($name) $id
1852 lappend idheads($id) $name
1855 # update things when a head has been removed
1856 proc removehead {id name} {
1857 global headids idheads
1859 if {$idheads($id) eq $name} {
1860 unset idheads($id)
1861 } else {
1862 set i [lsearch -exact $idheads($id) $name]
1863 if {$i >= 0} {
1864 set idheads($id) [lreplace $idheads($id) $i $i]
1867 unset headids($name)
1870 proc ttk_toplevel {w args} {
1871 global use_ttk
1872 eval [linsert $args 0 ::toplevel $w]
1873 if {$use_ttk} {
1874 place [ttk::frame $w._toplevel_background] -x 0 -y 0 -relwidth 1 -relheight 1
1876 return $w
1879 proc make_transient {window origin} {
1880 global have_tk85
1882 # In MacOS Tk 8.4 transient appears to work by setting
1883 # overrideredirect, which is utterly useless, since the
1884 # windows get no border, and are not even kept above
1885 # the parent.
1886 if {!$have_tk85 && [tk windowingsystem] eq {aqua}} return
1888 wm transient $window $origin
1890 # Windows fails to place transient windows normally, so
1891 # schedule a callback to center them on the parent.
1892 if {[tk windowingsystem] eq {win32}} {
1893 after idle [list tk::PlaceWindow $window widget $origin]
1897 proc show_error {w top msg} {
1898 global NS
1899 if {![info exists NS]} {set NS ""}
1900 if {[wm state $top] eq "withdrawn"} { wm deiconify $top }
1901 message $w.m -text $msg -justify center -aspect 400
1902 pack $w.m -side top -fill x -padx 20 -pady 20
1903 ${NS}::button $w.ok -default active -text [mc OK] -command "destroy $top"
1904 pack $w.ok -side bottom -fill x
1905 bind $top <Visibility> "grab $top; focus $top"
1906 bind $top <Key-Return> "destroy $top"
1907 bind $top <Key-space> "destroy $top"
1908 bind $top <Key-Escape> "destroy $top"
1909 tkwait window $top
1912 proc error_popup {msg {owner .}} {
1913 if {[tk windowingsystem] eq "win32"} {
1914 tk_messageBox -icon error -type ok -title [wm title .] \
1915 -parent $owner -message $msg
1916 } else {
1917 set w .error
1918 ttk_toplevel $w
1919 make_transient $w $owner
1920 show_error $w $w $msg
1924 proc confirm_popup {msg {owner .}} {
1925 global confirm_ok NS
1926 set confirm_ok 0
1927 set w .confirm
1928 ttk_toplevel $w
1929 make_transient $w $owner
1930 message $w.m -text $msg -justify center -aspect 400
1931 pack $w.m -side top -fill x -padx 20 -pady 20
1932 ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
1933 pack $w.ok -side left -fill x
1934 ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
1935 pack $w.cancel -side right -fill x
1936 bind $w <Visibility> "grab $w; focus $w"
1937 bind $w <Key-Return> "set confirm_ok 1; destroy $w"
1938 bind $w <Key-space> "set confirm_ok 1; destroy $w"
1939 bind $w <Key-Escape> "destroy $w"
1940 tk::PlaceWindow $w widget $owner
1941 tkwait window $w
1942 return $confirm_ok
1945 proc setoptions {} {
1946 if {[tk windowingsystem] ne "win32"} {
1947 option add *Panedwindow.showHandle 1 startupFile
1948 option add *Panedwindow.sashRelief raised startupFile
1949 if {[tk windowingsystem] ne "aqua"} {
1950 option add *Menu.font uifont startupFile
1952 } else {
1953 option add *Menu.TearOff 0 startupFile
1955 option add *Button.font uifont startupFile
1956 option add *Checkbutton.font uifont startupFile
1957 option add *Radiobutton.font uifont startupFile
1958 option add *Menubutton.font uifont startupFile
1959 option add *Label.font uifont startupFile
1960 option add *Message.font uifont startupFile
1961 option add *Entry.font textfont startupFile
1962 option add *Text.font textfont startupFile
1963 option add *Labelframe.font uifont startupFile
1964 option add *Spinbox.font textfont startupFile
1965 option add *Listbox.font mainfont startupFile
1968 # Make a menu and submenus.
1969 # m is the window name for the menu, items is the list of menu items to add.
1970 # Each item is a list {mc label type description options...}
1971 # mc is ignored; it's so we can put mc there to alert xgettext
1972 # label is the string that appears in the menu
1973 # type is cascade, command or radiobutton (should add checkbutton)
1974 # description depends on type; it's the sublist for cascade, the
1975 # command to invoke for command, or {variable value} for radiobutton
1976 proc makemenu {m items} {
1977 menu $m
1978 if {[tk windowingsystem] eq {aqua}} {
1979 set Meta1 Cmd
1980 } else {
1981 set Meta1 Ctrl
1983 foreach i $items {
1984 set name [mc [lindex $i 1]]
1985 set type [lindex $i 2]
1986 set thing [lindex $i 3]
1987 set params [list $type]
1988 if {$name ne {}} {
1989 set u [string first "&" [string map {&& x} $name]]
1990 lappend params -label [string map {&& & & {}} $name]
1991 if {$u >= 0} {
1992 lappend params -underline $u
1995 switch -- $type {
1996 "cascade" {
1997 set submenu [string tolower [string map {& ""} [lindex $i 1]]]
1998 lappend params -menu $m.$submenu
2000 "command" {
2001 lappend params -command $thing
2003 "radiobutton" {
2004 lappend params -variable [lindex $thing 0] \
2005 -value [lindex $thing 1]
2008 set tail [lrange $i 4 end]
2009 regsub -all {\yMeta1\y} $tail $Meta1 tail
2010 eval $m add $params $tail
2011 if {$type eq "cascade"} {
2012 makemenu $m.$submenu $thing
2017 # translate string and remove ampersands
2018 proc mca {str} {
2019 return [string map {&& & & {}} [mc $str]]
2022 proc cleardropsel {w} {
2023 $w selection clear
2025 proc makedroplist {w varname args} {
2026 global use_ttk
2027 if {$use_ttk} {
2028 set width 0
2029 foreach label $args {
2030 set cx [string length $label]
2031 if {$cx > $width} {set width $cx}
2033 set gm [ttk::combobox $w -width $width -state readonly\
2034 -textvariable $varname -values $args \
2035 -exportselection false]
2036 bind $gm <<ComboboxSelected>> [list $gm selection clear]
2037 } else {
2038 set gm [eval [linsert $args 0 tk_optionMenu $w $varname]]
2040 return $gm
2043 proc makewindow {} {
2044 global canv canv2 canv3 linespc charspc ctext cflist cscroll
2045 global tabstop
2046 global findtype findtypemenu findloc findstring fstring geometry
2047 global entries sha1entry sha1string sha1but
2048 global diffcontextstring diffcontext
2049 global ignorespace
2050 global maincursor textcursor curtextcursor
2051 global rowctxmenu fakerowmenu mergemax wrapcomment
2052 global highlight_files gdttype
2053 global searchstring sstring
2054 global bgcolor fgcolor bglist fglist diffcolors selectbgcolor
2055 global uifgcolor uifgdisabledcolor
2056 global filesepbgcolor filesepfgcolor
2057 global mergecolors foundbgcolor currentsearchhitbgcolor
2058 global headctxmenu progresscanv progressitem progresscoords statusw
2059 global fprogitem fprogcoord lastprogupdate progupdatepending
2060 global rprogitem rprogcoord rownumsel numcommits
2061 global have_tk85 use_ttk NS
2062 global git_version
2063 global worddiff
2065 # The "mc" arguments here are purely so that xgettext
2066 # sees the following string as needing to be translated
2067 set file {
2068 mc "&File" cascade {
2069 {mc "&Update" command updatecommits -accelerator F5}
2070 {mc "&Reload" command reloadcommits -accelerator Shift-F5}
2071 {mc "Reread re&ferences" command rereadrefs}
2072 {mc "&List references" command showrefs -accelerator F2}
2073 {xx "" separator}
2074 {mc "Start git &gui" command {exec git gui &}}
2075 {xx "" separator}
2076 {mc "&Quit" command doquit -accelerator Meta1-Q}
2078 set edit {
2079 mc "&Edit" cascade {
2080 {mc "&Preferences" command doprefs}
2082 set view {
2083 mc "&View" cascade {
2084 {mc "&New view..." command {newview 0} -accelerator Shift-F4}
2085 {mc "&Edit view..." command editview -state disabled -accelerator F4}
2086 {mc "&Delete view" command delview -state disabled}
2087 {xx "" separator}
2088 {mc "&All files" radiobutton {selectedview 0} -command {showview 0}}
2090 if {[tk windowingsystem] ne "aqua"} {
2091 set help {
2092 mc "&Help" cascade {
2093 {mc "&About gitk" command about}
2094 {mc "&Key bindings" command keys}
2096 set bar [list $file $edit $view $help]
2097 } else {
2098 proc ::tk::mac::ShowPreferences {} {doprefs}
2099 proc ::tk::mac::Quit {} {doquit}
2100 lset file end [lreplace [lindex $file end] end-1 end]
2101 set apple {
2102 xx "&Apple" cascade {
2103 {mc "&About gitk" command about}
2104 {xx "" separator}
2106 set help {
2107 mc "&Help" cascade {
2108 {mc "&Key bindings" command keys}
2110 set bar [list $apple $file $view $help]
2112 makemenu .bar $bar
2113 . configure -menu .bar
2115 if {$use_ttk} {
2116 # cover the non-themed toplevel with a themed frame.
2117 place [ttk::frame ._main_background] -x 0 -y 0 -relwidth 1 -relheight 1
2120 # the gui has upper and lower half, parts of a paned window.
2121 ${NS}::panedwindow .ctop -orient vertical
2123 # possibly use assumed geometry
2124 if {![info exists geometry(pwsash0)]} {
2125 set geometry(topheight) [expr {15 * $linespc}]
2126 set geometry(topwidth) [expr {80 * $charspc}]
2127 set geometry(botheight) [expr {15 * $linespc}]
2128 set geometry(botwidth) [expr {50 * $charspc}]
2129 set geometry(pwsash0) [list [expr {40 * $charspc}] 2]
2130 set geometry(pwsash1) [list [expr {60 * $charspc}] 2]
2133 # the upper half will have a paned window, a scroll bar to the right, and some stuff below
2134 ${NS}::frame .tf -height $geometry(topheight) -width $geometry(topwidth)
2135 ${NS}::frame .tf.histframe
2136 ${NS}::panedwindow .tf.histframe.pwclist -orient horizontal
2137 if {!$use_ttk} {
2138 .tf.histframe.pwclist configure -sashpad 0 -handlesize 4
2141 # create three canvases
2142 set cscroll .tf.histframe.csb
2143 set canv .tf.histframe.pwclist.canv
2144 canvas $canv \
2145 -selectbackground $selectbgcolor \
2146 -background $bgcolor -bd 0 \
2147 -yscrollincr $linespc -yscrollcommand "scrollcanv $cscroll"
2148 .tf.histframe.pwclist add $canv
2149 set canv2 .tf.histframe.pwclist.canv2
2150 canvas $canv2 \
2151 -selectbackground $selectbgcolor \
2152 -background $bgcolor -bd 0 -yscrollincr $linespc
2153 .tf.histframe.pwclist add $canv2
2154 set canv3 .tf.histframe.pwclist.canv3
2155 canvas $canv3 \
2156 -selectbackground $selectbgcolor \
2157 -background $bgcolor -bd 0 -yscrollincr $linespc
2158 .tf.histframe.pwclist add $canv3
2159 if {$use_ttk} {
2160 bind .tf.histframe.pwclist <Map> {
2161 bind %W <Map> {}
2162 .tf.histframe.pwclist sashpos 1 [lindex $::geometry(pwsash1) 0]
2163 .tf.histframe.pwclist sashpos 0 [lindex $::geometry(pwsash0) 0]
2165 } else {
2166 eval .tf.histframe.pwclist sash place 0 $geometry(pwsash0)
2167 eval .tf.histframe.pwclist sash place 1 $geometry(pwsash1)
2170 # a scroll bar to rule them
2171 ${NS}::scrollbar $cscroll -command {allcanvs yview}
2172 if {!$use_ttk} {$cscroll configure -highlightthickness 0}
2173 pack $cscroll -side right -fill y
2174 bind .tf.histframe.pwclist <Configure> {resizeclistpanes %W %w}
2175 lappend bglist $canv $canv2 $canv3
2176 pack .tf.histframe.pwclist -fill both -expand 1 -side left
2178 # we have two button bars at bottom of top frame. Bar 1
2179 ${NS}::frame .tf.bar
2180 ${NS}::frame .tf.lbar -height 15
2182 set sha1entry .tf.bar.sha1
2183 set entries $sha1entry
2184 set sha1but .tf.bar.sha1label
2185 button $sha1but -text "[mc "SHA1 ID:"] " -state disabled -relief flat \
2186 -command gotocommit -width 8
2187 $sha1but conf -disabledforeground [$sha1but cget -foreground]
2188 pack .tf.bar.sha1label -side left
2189 ${NS}::entry $sha1entry -width 40 -font textfont -textvariable sha1string
2190 trace add variable sha1string write sha1change
2191 pack $sha1entry -side left -pady 2
2193 set bm_left_data {
2194 #define left_width 16
2195 #define left_height 16
2196 static unsigned char left_bits[] = {
2197 0x00, 0x00, 0xc0, 0x01, 0xe0, 0x00, 0x70, 0x00, 0x38, 0x00, 0x1c, 0x00,
2198 0x0e, 0x00, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x0e, 0x00, 0x1c, 0x00,
2199 0x38, 0x00, 0x70, 0x00, 0xe0, 0x00, 0xc0, 0x01};
2201 set bm_right_data {
2202 #define right_width 16
2203 #define right_height 16
2204 static unsigned char right_bits[] = {
2205 0x00, 0x00, 0xc0, 0x01, 0x80, 0x03, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x1c,
2206 0x00, 0x38, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x00, 0x38, 0x00, 0x1c,
2207 0x00, 0x0e, 0x00, 0x07, 0x80, 0x03, 0xc0, 0x01};
2209 image create bitmap bm-left -data $bm_left_data -foreground $uifgcolor
2210 image create bitmap bm-left-gray -data $bm_left_data -foreground $uifgdisabledcolor
2211 image create bitmap bm-right -data $bm_right_data -foreground $uifgcolor
2212 image create bitmap bm-right-gray -data $bm_right_data -foreground $uifgdisabledcolor
2214 ${NS}::button .tf.bar.leftbut -command goback -state disabled -width 26
2215 if {$use_ttk} {
2216 .tf.bar.leftbut configure -image [list bm-left disabled bm-left-gray]
2217 } else {
2218 .tf.bar.leftbut configure -image bm-left
2220 pack .tf.bar.leftbut -side left -fill y
2221 ${NS}::button .tf.bar.rightbut -command goforw -state disabled -width 26
2222 if {$use_ttk} {
2223 .tf.bar.rightbut configure -image [list bm-right disabled bm-right-gray]
2224 } else {
2225 .tf.bar.rightbut configure -image bm-right
2227 pack .tf.bar.rightbut -side left -fill y
2229 ${NS}::label .tf.bar.rowlabel -text [mc "Row"]
2230 set rownumsel {}
2231 ${NS}::label .tf.bar.rownum -width 7 -textvariable rownumsel \
2232 -relief sunken -anchor e
2233 ${NS}::label .tf.bar.rowlabel2 -text "/"
2234 ${NS}::label .tf.bar.numcommits -width 7 -textvariable numcommits \
2235 -relief sunken -anchor e
2236 pack .tf.bar.rowlabel .tf.bar.rownum .tf.bar.rowlabel2 .tf.bar.numcommits \
2237 -side left
2238 if {!$use_ttk} {
2239 foreach w {rownum numcommits} {.tf.bar.$w configure -font textfont}
2241 global selectedline
2242 trace add variable selectedline write selectedline_change
2244 # Status label and progress bar
2245 set statusw .tf.bar.status
2246 ${NS}::label $statusw -width 15 -relief sunken
2247 pack $statusw -side left -padx 5
2248 if {$use_ttk} {
2249 set progresscanv [ttk::progressbar .tf.bar.progress]
2250 } else {
2251 set h [expr {[font metrics uifont -linespace] + 2}]
2252 set progresscanv .tf.bar.progress
2253 canvas $progresscanv -relief sunken -height $h -borderwidth 2
2254 set progressitem [$progresscanv create rect -1 0 0 $h -fill green]
2255 set fprogitem [$progresscanv create rect -1 0 0 $h -fill yellow]
2256 set rprogitem [$progresscanv create rect -1 0 0 $h -fill red]
2258 pack $progresscanv -side right -expand 1 -fill x -padx {0 2}
2259 set progresscoords {0 0}
2260 set fprogcoord 0
2261 set rprogcoord 0
2262 bind $progresscanv <Configure> adjustprogress
2263 set lastprogupdate [clock clicks -milliseconds]
2264 set progupdatepending 0
2266 # build up the bottom bar of upper window
2267 ${NS}::label .tf.lbar.flabel -text "[mc "Find"] "
2269 set bm_down_data {
2270 #define down_width 16
2271 #define down_height 16
2272 static unsigned char down_bits[] = {
2273 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2274 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2275 0x87, 0xe1, 0x8e, 0x71, 0x9c, 0x39, 0xb8, 0x1d,
2276 0xf0, 0x0f, 0xe0, 0x07, 0xc0, 0x03, 0x80, 0x01};
2278 image create bitmap bm-down -data $bm_down_data -foreground $uifgcolor
2279 ${NS}::button .tf.lbar.fnext -width 26 -command {dofind 1 1}
2280 .tf.lbar.fnext configure -image bm-down
2282 set bm_up_data {
2283 #define up_width 16
2284 #define up_height 16
2285 static unsigned char up_bits[] = {
2286 0x80, 0x01, 0xc0, 0x03, 0xe0, 0x07, 0xf0, 0x0f,
2287 0xb8, 0x1d, 0x9c, 0x39, 0x8e, 0x71, 0x87, 0xe1,
2288 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2289 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01};
2291 image create bitmap bm-up -data $bm_up_data -foreground $uifgcolor
2292 ${NS}::button .tf.lbar.fprev -width 26 -command {dofind -1 1}
2293 .tf.lbar.fprev configure -image bm-up
2295 ${NS}::label .tf.lbar.flab2 -text " [mc "commit"] "
2297 pack .tf.lbar.flabel .tf.lbar.fnext .tf.lbar.fprev .tf.lbar.flab2 \
2298 -side left -fill y
2299 set gdttype [mc "containing:"]
2300 set gm [makedroplist .tf.lbar.gdttype gdttype \
2301 [mc "containing:"] \
2302 [mc "touching paths:"] \
2303 [mc "adding/removing string:"] \
2304 [mc "changing lines matching:"]]
2305 trace add variable gdttype write gdttype_change
2306 pack .tf.lbar.gdttype -side left -fill y
2308 set findstring {}
2309 set fstring .tf.lbar.findstring
2310 lappend entries $fstring
2311 ${NS}::entry $fstring -width 30 -textvariable findstring
2312 trace add variable findstring write find_change
2313 set findtype [mc "Exact"]
2314 set findtypemenu [makedroplist .tf.lbar.findtype \
2315 findtype [mc "Exact"] [mc "IgnCase"] [mc "Regexp"]]
2316 trace add variable findtype write findcom_change
2317 set findloc [mc "All fields"]
2318 makedroplist .tf.lbar.findloc findloc [mc "All fields"] [mc "Headline"] \
2319 [mc "Comments"] [mc "Author"] [mc "Committer"]
2320 trace add variable findloc write find_change
2321 pack .tf.lbar.findloc -side right
2322 pack .tf.lbar.findtype -side right
2323 pack $fstring -side left -expand 1 -fill x
2325 # Finish putting the upper half of the viewer together
2326 pack .tf.lbar -in .tf -side bottom -fill x
2327 pack .tf.bar -in .tf -side bottom -fill x
2328 pack .tf.histframe -fill both -side top -expand 1
2329 .ctop add .tf
2330 if {!$use_ttk} {
2331 .ctop paneconfigure .tf -height $geometry(topheight)
2332 .ctop paneconfigure .tf -width $geometry(topwidth)
2335 # now build up the bottom
2336 ${NS}::panedwindow .pwbottom -orient horizontal
2338 # lower left, a text box over search bar, scroll bar to the right
2339 # if we know window height, then that will set the lower text height, otherwise
2340 # we set lower text height which will drive window height
2341 if {[info exists geometry(main)]} {
2342 ${NS}::frame .bleft -width $geometry(botwidth)
2343 } else {
2344 ${NS}::frame .bleft -width $geometry(botwidth) -height $geometry(botheight)
2346 ${NS}::frame .bleft.top
2347 ${NS}::frame .bleft.mid
2348 ${NS}::frame .bleft.bottom
2350 ${NS}::button .bleft.top.search -text [mc "Search"] -command dosearch
2351 pack .bleft.top.search -side left -padx 5
2352 set sstring .bleft.top.sstring
2353 set searchstring ""
2354 ${NS}::entry $sstring -width 20 -textvariable searchstring
2355 lappend entries $sstring
2356 trace add variable searchstring write incrsearch
2357 pack $sstring -side left -expand 1 -fill x
2358 ${NS}::radiobutton .bleft.mid.diff -text [mc "Diff"] \
2359 -command changediffdisp -variable diffelide -value {0 0}
2360 ${NS}::radiobutton .bleft.mid.old -text [mc "Old version"] \
2361 -command changediffdisp -variable diffelide -value {0 1}
2362 ${NS}::radiobutton .bleft.mid.new -text [mc "New version"] \
2363 -command changediffdisp -variable diffelide -value {1 0}
2364 ${NS}::label .bleft.mid.labeldiffcontext -text " [mc "Lines of context"]: "
2365 pack .bleft.mid.diff .bleft.mid.old .bleft.mid.new -side left
2366 spinbox .bleft.mid.diffcontext -width 5 \
2367 -from 0 -increment 1 -to 10000000 \
2368 -validate all -validatecommand "diffcontextvalidate %P" \
2369 -textvariable diffcontextstring
2370 .bleft.mid.diffcontext set $diffcontext
2371 trace add variable diffcontextstring write diffcontextchange
2372 lappend entries .bleft.mid.diffcontext
2373 pack .bleft.mid.labeldiffcontext .bleft.mid.diffcontext -side left
2374 ${NS}::checkbutton .bleft.mid.ignspace -text [mc "Ignore space change"] \
2375 -command changeignorespace -variable ignorespace
2376 pack .bleft.mid.ignspace -side left -padx 5
2378 set worddiff [mc "Line diff"]
2379 if {[package vcompare $git_version "1.7.2"] >= 0} {
2380 makedroplist .bleft.mid.worddiff worddiff [mc "Line diff"] \
2381 [mc "Markup words"] [mc "Color words"]
2382 trace add variable worddiff write changeworddiff
2383 pack .bleft.mid.worddiff -side left -padx 5
2386 set ctext .bleft.bottom.ctext
2387 text $ctext -background $bgcolor -foreground $fgcolor \
2388 -state disabled -font textfont \
2389 -yscrollcommand scrolltext -wrap none \
2390 -xscrollcommand ".bleft.bottom.sbhorizontal set"
2391 if {$have_tk85} {
2392 $ctext conf -tabstyle wordprocessor
2394 ${NS}::scrollbar .bleft.bottom.sb -command "$ctext yview"
2395 ${NS}::scrollbar .bleft.bottom.sbhorizontal -command "$ctext xview" -orient h
2396 pack .bleft.top -side top -fill x
2397 pack .bleft.mid -side top -fill x
2398 grid $ctext .bleft.bottom.sb -sticky nsew
2399 grid .bleft.bottom.sbhorizontal -sticky ew
2400 grid columnconfigure .bleft.bottom 0 -weight 1
2401 grid rowconfigure .bleft.bottom 0 -weight 1
2402 grid rowconfigure .bleft.bottom 1 -weight 0
2403 pack .bleft.bottom -side top -fill both -expand 1
2404 lappend bglist $ctext
2405 lappend fglist $ctext
2407 $ctext tag conf comment -wrap $wrapcomment
2408 $ctext tag conf filesep -font textfontbold -fore $filesepfgcolor -back $filesepbgcolor
2409 $ctext tag conf hunksep -fore [lindex $diffcolors 2]
2410 $ctext tag conf d0 -fore [lindex $diffcolors 0]
2411 $ctext tag conf dresult -fore [lindex $diffcolors 1]
2412 $ctext tag conf m0 -fore [lindex $mergecolors 0]
2413 $ctext tag conf m1 -fore [lindex $mergecolors 1]
2414 $ctext tag conf m2 -fore [lindex $mergecolors 2]
2415 $ctext tag conf m3 -fore [lindex $mergecolors 3]
2416 $ctext tag conf m4 -fore [lindex $mergecolors 4]
2417 $ctext tag conf m5 -fore [lindex $mergecolors 5]
2418 $ctext tag conf m6 -fore [lindex $mergecolors 6]
2419 $ctext tag conf m7 -fore [lindex $mergecolors 7]
2420 $ctext tag conf m8 -fore [lindex $mergecolors 8]
2421 $ctext tag conf m9 -fore [lindex $mergecolors 9]
2422 $ctext tag conf m10 -fore [lindex $mergecolors 10]
2423 $ctext tag conf m11 -fore [lindex $mergecolors 11]
2424 $ctext tag conf m12 -fore [lindex $mergecolors 12]
2425 $ctext tag conf m13 -fore [lindex $mergecolors 13]
2426 $ctext tag conf m14 -fore [lindex $mergecolors 14]
2427 $ctext tag conf m15 -fore [lindex $mergecolors 15]
2428 $ctext tag conf mmax -fore darkgrey
2429 set mergemax 16
2430 $ctext tag conf mresult -font textfontbold
2431 $ctext tag conf msep -font textfontbold
2432 $ctext tag conf found -back $foundbgcolor
2433 $ctext tag conf currentsearchhit -back $currentsearchhitbgcolor
2434 $ctext tag conf wwrap -wrap word -lmargin2 1c
2435 $ctext tag conf bold -font textfontbold
2437 .pwbottom add .bleft
2438 if {!$use_ttk} {
2439 .pwbottom paneconfigure .bleft -width $geometry(botwidth)
2442 # lower right
2443 ${NS}::frame .bright
2444 ${NS}::frame .bright.mode
2445 ${NS}::radiobutton .bright.mode.patch -text [mc "Patch"] \
2446 -command reselectline -variable cmitmode -value "patch"
2447 ${NS}::radiobutton .bright.mode.tree -text [mc "Tree"] \
2448 -command reselectline -variable cmitmode -value "tree"
2449 grid .bright.mode.patch .bright.mode.tree -sticky ew
2450 pack .bright.mode -side top -fill x
2451 set cflist .bright.cfiles
2452 set indent [font measure mainfont "nn"]
2453 text $cflist \
2454 -selectbackground $selectbgcolor \
2455 -background $bgcolor -foreground $fgcolor \
2456 -font mainfont \
2457 -tabs [list $indent [expr {2 * $indent}]] \
2458 -yscrollcommand ".bright.sb set" \
2459 -cursor [. cget -cursor] \
2460 -spacing1 1 -spacing3 1
2461 lappend bglist $cflist
2462 lappend fglist $cflist
2463 ${NS}::scrollbar .bright.sb -command "$cflist yview"
2464 pack .bright.sb -side right -fill y
2465 pack $cflist -side left -fill both -expand 1
2466 $cflist tag configure highlight \
2467 -background [$cflist cget -selectbackground]
2468 $cflist tag configure bold -font mainfontbold
2470 .pwbottom add .bright
2471 .ctop add .pwbottom
2473 # restore window width & height if known
2474 if {[info exists geometry(main)]} {
2475 if {[scan $geometry(main) "%dx%d" w h] >= 2} {
2476 if {$w > [winfo screenwidth .]} {
2477 set w [winfo screenwidth .]
2479 if {$h > [winfo screenheight .]} {
2480 set h [winfo screenheight .]
2482 wm geometry . "${w}x$h"
2486 if {[info exists geometry(state)] && $geometry(state) eq "zoomed"} {
2487 wm state . $geometry(state)
2490 if {[tk windowingsystem] eq {aqua}} {
2491 set M1B M1
2492 set ::BM "3"
2493 } else {
2494 set M1B Control
2495 set ::BM "2"
2498 if {$use_ttk} {
2499 bind .ctop <Map> {
2500 bind %W <Map> {}
2501 %W sashpos 0 $::geometry(topheight)
2503 bind .pwbottom <Map> {
2504 bind %W <Map> {}
2505 %W sashpos 0 $::geometry(botwidth)
2509 bind .pwbottom <Configure> {resizecdetpanes %W %w}
2510 pack .ctop -fill both -expand 1
2511 bindall <1> {selcanvline %W %x %y}
2512 #bindall <B1-Motion> {selcanvline %W %x %y}
2513 if {[tk windowingsystem] == "win32"} {
2514 bind . <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D }
2515 bind $ctext <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D ; break }
2516 } else {
2517 bindall <ButtonRelease-4> "allcanvs yview scroll -5 units"
2518 bindall <ButtonRelease-5> "allcanvs yview scroll 5 units"
2519 bind $ctext <Button> {
2520 if {"%b" eq 6} {
2521 $ctext xview scroll -5 units
2522 } elseif {"%b" eq 7} {
2523 $ctext xview scroll 5 units
2526 if {[tk windowingsystem] eq "aqua"} {
2527 bindall <MouseWheel> {
2528 set delta [expr {- (%D)}]
2529 allcanvs yview scroll $delta units
2531 bindall <Shift-MouseWheel> {
2532 set delta [expr {- (%D)}]
2533 $canv xview scroll $delta units
2537 bindall <$::BM> "canvscan mark %W %x %y"
2538 bindall <B$::BM-Motion> "canvscan dragto %W %x %y"
2539 bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
2540 bind . <$M1B-Key-w> doquit
2541 bindkey <Home> selfirstline
2542 bindkey <End> sellastline
2543 bind . <Key-Up> "selnextline -1"
2544 bind . <Key-Down> "selnextline 1"
2545 bind . <Shift-Key-Up> "dofind -1 0"
2546 bind . <Shift-Key-Down> "dofind 1 0"
2547 bindkey <Key-Right> "goforw"
2548 bindkey <Key-Left> "goback"
2549 bind . <Key-Prior> "selnextpage -1"
2550 bind . <Key-Next> "selnextpage 1"
2551 bind . <$M1B-Home> "allcanvs yview moveto 0.0"
2552 bind . <$M1B-End> "allcanvs yview moveto 1.0"
2553 bind . <$M1B-Key-Up> "allcanvs yview scroll -1 units"
2554 bind . <$M1B-Key-Down> "allcanvs yview scroll 1 units"
2555 bind . <$M1B-Key-Prior> "allcanvs yview scroll -1 pages"
2556 bind . <$M1B-Key-Next> "allcanvs yview scroll 1 pages"
2557 bindkey <Key-Delete> "$ctext yview scroll -1 pages"
2558 bindkey <Key-BackSpace> "$ctext yview scroll -1 pages"
2559 bindkey <Key-space> "$ctext yview scroll 1 pages"
2560 bindkey p "selnextline -1"
2561 bindkey n "selnextline 1"
2562 bindkey z "goback"
2563 bindkey x "goforw"
2564 bindkey k "selnextline -1"
2565 bindkey j "selnextline 1"
2566 bindkey h "goback"
2567 bindkey l "goforw"
2568 bindkey b prevfile
2569 bindkey d "$ctext yview scroll 18 units"
2570 bindkey u "$ctext yview scroll -18 units"
2571 bindkey g {$sha1entry delete 0 end; focus $sha1entry}
2572 bindkey / {focus $fstring}
2573 bindkey <Key-KP_Divide> {focus $fstring}
2574 bindkey <Key-Return> {dofind 1 1}
2575 bindkey ? {dofind -1 1}
2576 bindkey f nextfile
2577 bind . <F5> updatecommits
2578 bindmodfunctionkey Shift 5 reloadcommits
2579 bind . <F2> showrefs
2580 bindmodfunctionkey Shift 4 {newview 0}
2581 bind . <F4> edit_or_newview
2582 bind . <$M1B-q> doquit
2583 bind . <$M1B-f> {dofind 1 1}
2584 bind . <$M1B-g> {dofind 1 0}
2585 bind . <$M1B-r> dosearchback
2586 bind . <$M1B-s> dosearch
2587 bind . <$M1B-equal> {incrfont 1}
2588 bind . <$M1B-plus> {incrfont 1}
2589 bind . <$M1B-KP_Add> {incrfont 1}
2590 bind . <$M1B-minus> {incrfont -1}
2591 bind . <$M1B-KP_Subtract> {incrfont -1}
2592 wm protocol . WM_DELETE_WINDOW doquit
2593 bind . <Destroy> {stop_backends}
2594 bind . <Button-1> "click %W"
2595 bind $fstring <Key-Return> {dofind 1 1}
2596 bind $sha1entry <Key-Return> {gotocommit; break}
2597 bind $sha1entry <<PasteSelection>> clearsha1
2598 bind $sha1entry <<Paste>> clearsha1
2599 bind $cflist <1> {sel_flist %W %x %y; break}
2600 bind $cflist <B1-Motion> {sel_flist %W %x %y; break}
2601 bind $cflist <ButtonRelease-1> {treeclick %W %x %y}
2602 global ctxbut
2603 bind $cflist $ctxbut {pop_flist_menu %W %X %Y %x %y}
2604 bind $ctext $ctxbut {pop_diff_menu %W %X %Y %x %y}
2605 bind $ctext <Button-1> {focus %W}
2606 bind $ctext <<Selection>> rehighlight_search_results
2607 for {set i 1} {$i < 10} {incr i} {
2608 bind . <$M1B-Key-$i> [list go_to_parent $i]
2611 set maincursor [. cget -cursor]
2612 set textcursor [$ctext cget -cursor]
2613 set curtextcursor $textcursor
2615 set rowctxmenu .rowctxmenu
2616 makemenu $rowctxmenu {
2617 {mc "Diff this -> selected" command {diffvssel 0}}
2618 {mc "Diff selected -> this" command {diffvssel 1}}
2619 {mc "Make patch" command mkpatch}
2620 {mc "Create tag" command mktag}
2621 {mc "Copy commit summary" command copysummary}
2622 {mc "Write commit to file" command writecommit}
2623 {mc "Create new branch" command mkbranch}
2624 {mc "Cherry-pick this commit" command cherrypick}
2625 {mc "Reset HEAD branch to here" command resethead}
2626 {mc "Mark this commit" command markhere}
2627 {mc "Return to mark" command gotomark}
2628 {mc "Find descendant of this and mark" command find_common_desc}
2629 {mc "Compare with marked commit" command compare_commits}
2630 {mc "Diff this -> marked commit" command {diffvsmark 0}}
2631 {mc "Diff marked commit -> this" command {diffvsmark 1}}
2632 {mc "Revert this commit" command revert}
2634 $rowctxmenu configure -tearoff 0
2636 set fakerowmenu .fakerowmenu
2637 makemenu $fakerowmenu {
2638 {mc "Diff this -> selected" command {diffvssel 0}}
2639 {mc "Diff selected -> this" command {diffvssel 1}}
2640 {mc "Make patch" command mkpatch}
2641 {mc "Diff this -> marked commit" command {diffvsmark 0}}
2642 {mc "Diff marked commit -> this" command {diffvsmark 1}}
2644 $fakerowmenu configure -tearoff 0
2646 set headctxmenu .headctxmenu
2647 makemenu $headctxmenu {
2648 {mc "Check out this branch" command cobranch}
2649 {mc "Remove this branch" command rmbranch}
2650 {mc "Copy branch name" command {clipboard clear; clipboard append $headmenuhead}}
2652 $headctxmenu configure -tearoff 0
2654 global flist_menu
2655 set flist_menu .flistctxmenu
2656 makemenu $flist_menu {
2657 {mc "Highlight this too" command {flist_hl 0}}
2658 {mc "Highlight this only" command {flist_hl 1}}
2659 {mc "External diff" command {external_diff}}
2660 {mc "Blame parent commit" command {external_blame 1}}
2661 {mc "Copy path" command {clipboard clear; clipboard append $flist_menu_file}}
2663 $flist_menu configure -tearoff 0
2665 global diff_menu
2666 set diff_menu .diffctxmenu
2667 makemenu $diff_menu {
2668 {mc "Show origin of this line" command show_line_source}
2669 {mc "Run git gui blame on this line" command {external_blame_diff}}
2671 $diff_menu configure -tearoff 0
2674 # Windows sends all mouse wheel events to the current focused window, not
2675 # the one where the mouse hovers, so bind those events here and redirect
2676 # to the correct window
2677 proc windows_mousewheel_redirector {W X Y D} {
2678 global canv canv2 canv3
2679 set w [winfo containing -displayof $W $X $Y]
2680 if {$w ne ""} {
2681 set u [expr {$D < 0 ? 5 : -5}]
2682 if {$w == $canv || $w == $canv2 || $w == $canv3} {
2683 allcanvs yview scroll $u units
2684 } else {
2685 catch {
2686 $w yview scroll $u units
2692 # Update row number label when selectedline changes
2693 proc selectedline_change {n1 n2 op} {
2694 global selectedline rownumsel
2696 if {$selectedline eq {}} {
2697 set rownumsel {}
2698 } else {
2699 set rownumsel [expr {$selectedline + 1}]
2703 # mouse-2 makes all windows scan vertically, but only the one
2704 # the cursor is in scans horizontally
2705 proc canvscan {op w x y} {
2706 global canv canv2 canv3
2707 foreach c [list $canv $canv2 $canv3] {
2708 if {$c == $w} {
2709 $c scan $op $x $y
2710 } else {
2711 $c scan $op 0 $y
2716 proc scrollcanv {cscroll f0 f1} {
2717 $cscroll set $f0 $f1
2718 drawvisible
2719 flushhighlights
2722 # when we make a key binding for the toplevel, make sure
2723 # it doesn't get triggered when that key is pressed in the
2724 # find string entry widget.
2725 proc bindkey {ev script} {
2726 global entries
2727 bind . $ev $script
2728 set escript [bind Entry $ev]
2729 if {$escript == {}} {
2730 set escript [bind Entry <Key>]
2732 foreach e $entries {
2733 bind $e $ev "$escript; break"
2737 proc bindmodfunctionkey {mod n script} {
2738 bind . <$mod-F$n> $script
2739 catch { bind . <$mod-XF86_Switch_VT_$n> $script }
2742 # set the focus back to the toplevel for any click outside
2743 # the entry widgets
2744 proc click {w} {
2745 global ctext entries
2746 foreach e [concat $entries $ctext] {
2747 if {$w == $e} return
2749 focus .
2752 # Adjust the progress bar for a change in requested extent or canvas size
2753 proc adjustprogress {} {
2754 global progresscanv progressitem progresscoords
2755 global fprogitem fprogcoord lastprogupdate progupdatepending
2756 global rprogitem rprogcoord use_ttk
2758 if {$use_ttk} {
2759 $progresscanv configure -value [expr {int($fprogcoord * 100)}]
2760 return
2763 set w [expr {[winfo width $progresscanv] - 4}]
2764 set x0 [expr {$w * [lindex $progresscoords 0]}]
2765 set x1 [expr {$w * [lindex $progresscoords 1]}]
2766 set h [winfo height $progresscanv]
2767 $progresscanv coords $progressitem $x0 0 $x1 $h
2768 $progresscanv coords $fprogitem 0 0 [expr {$w * $fprogcoord}] $h
2769 $progresscanv coords $rprogitem 0 0 [expr {$w * $rprogcoord}] $h
2770 set now [clock clicks -milliseconds]
2771 if {$now >= $lastprogupdate + 100} {
2772 set progupdatepending 0
2773 update
2774 } elseif {!$progupdatepending} {
2775 set progupdatepending 1
2776 after [expr {$lastprogupdate + 100 - $now}] doprogupdate
2780 proc doprogupdate {} {
2781 global lastprogupdate progupdatepending
2783 if {$progupdatepending} {
2784 set progupdatepending 0
2785 set lastprogupdate [clock clicks -milliseconds]
2786 update
2790 proc config_check_tmp_exists {tries_left} {
2791 global config_file_tmp
2793 if {[file exists $config_file_tmp]} {
2794 incr tries_left -1
2795 if {$tries_left > 0} {
2796 after 100 [list config_check_tmp_exists $tries_left]
2797 } else {
2798 error_popup "There appears to be a stale $config_file_tmp\
2799 file, which will prevent gitk from saving its configuration on exit.\
2800 Please remove it if it is not being used by any existing gitk process."
2805 proc config_init_trace {name} {
2806 global config_variable_changed config_variable_original
2808 upvar #0 $name var
2809 set config_variable_changed($name) 0
2810 set config_variable_original($name) $var
2813 proc config_variable_change_cb {name name2 op} {
2814 global config_variable_changed config_variable_original
2816 upvar #0 $name var
2817 if {$op eq "write" &&
2818 (![info exists config_variable_original($name)] ||
2819 $config_variable_original($name) ne $var)} {
2820 set config_variable_changed($name) 1
2824 proc savestuff {w} {
2825 global stuffsaved
2826 global config_file config_file_tmp
2827 global config_variables config_variable_changed
2828 global viewchanged
2830 upvar #0 viewname current_viewname
2831 upvar #0 viewfiles current_viewfiles
2832 upvar #0 viewargs current_viewargs
2833 upvar #0 viewargscmd current_viewargscmd
2834 upvar #0 viewperm current_viewperm
2835 upvar #0 nextviewnum current_nextviewnum
2836 upvar #0 use_ttk current_use_ttk
2838 if {$stuffsaved} return
2839 if {![winfo viewable .]} return
2840 set remove_tmp 0
2841 if {[catch {
2842 set try_count 0
2843 while {[catch {set f [open $config_file_tmp {WRONLY CREAT EXCL}]}]} {
2844 if {[incr try_count] > 50} {
2845 error "Unable to write config file: $config_file_tmp exists"
2847 after 100
2849 set remove_tmp 1
2850 if {$::tcl_platform(platform) eq {windows}} {
2851 file attributes $config_file_tmp -hidden true
2853 if {[file exists $config_file]} {
2854 source $config_file
2856 foreach var_name $config_variables {
2857 upvar #0 $var_name var
2858 upvar 0 $var_name old_var
2859 if {!$config_variable_changed($var_name) && [info exists old_var]} {
2860 puts $f [list set $var_name $old_var]
2861 } else {
2862 puts $f [list set $var_name $var]
2866 puts $f "set geometry(main) [wm geometry .]"
2867 puts $f "set geometry(state) [wm state .]"
2868 puts $f "set geometry(topwidth) [winfo width .tf]"
2869 puts $f "set geometry(topheight) [winfo height .tf]"
2870 if {$current_use_ttk} {
2871 puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sashpos 0] 1\""
2872 puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sashpos 1] 1\""
2873 } else {
2874 puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sash coord 0]\""
2875 puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sash coord 1]\""
2877 puts $f "set geometry(botwidth) [winfo width .bleft]"
2878 puts $f "set geometry(botheight) [winfo height .bleft]"
2880 array set view_save {}
2881 array set views {}
2882 if {![info exists permviews]} { set permviews {} }
2883 foreach view $permviews {
2884 set view_save([lindex $view 0]) 1
2885 set views([lindex $view 0]) $view
2887 puts -nonewline $f "set permviews {"
2888 for {set v 1} {$v < $current_nextviewnum} {incr v} {
2889 if {$viewchanged($v)} {
2890 if {$current_viewperm($v)} {
2891 set views($current_viewname($v)) [list $current_viewname($v) $current_viewfiles($v) $current_viewargs($v) $current_viewargscmd($v)]
2892 } else {
2893 set view_save($current_viewname($v)) 0
2897 # write old and updated view to their places and append remaining to the end
2898 foreach view $permviews {
2899 set view_name [lindex $view 0]
2900 if {$view_save($view_name)} {
2901 puts $f "{$views($view_name)}"
2903 unset views($view_name)
2905 foreach view_name [array names views] {
2906 puts $f "{$views($view_name)}"
2908 puts $f "}"
2909 close $f
2910 catch {file delete $config_file}
2911 file rename -force $config_file_tmp $config_file
2912 set remove_tmp 0
2913 } err]} {
2914 puts "Error saving config: $err"
2916 if {$remove_tmp} {
2917 file delete -force $config_file_tmp
2919 set stuffsaved 1
2922 proc resizeclistpanes {win w} {
2923 global oldwidth use_ttk
2924 if {[info exists oldwidth($win)]} {
2925 if {$use_ttk} {
2926 set s0 [$win sashpos 0]
2927 set s1 [$win sashpos 1]
2928 } else {
2929 set s0 [$win sash coord 0]
2930 set s1 [$win sash coord 1]
2932 if {$w < 60} {
2933 set sash0 [expr {int($w/2 - 2)}]
2934 set sash1 [expr {int($w*5/6 - 2)}]
2935 } else {
2936 set factor [expr {1.0 * $w / $oldwidth($win)}]
2937 set sash0 [expr {int($factor * [lindex $s0 0])}]
2938 set sash1 [expr {int($factor * [lindex $s1 0])}]
2939 if {$sash0 < 30} {
2940 set sash0 30
2942 if {$sash1 < $sash0 + 20} {
2943 set sash1 [expr {$sash0 + 20}]
2945 if {$sash1 > $w - 10} {
2946 set sash1 [expr {$w - 10}]
2947 if {$sash0 > $sash1 - 20} {
2948 set sash0 [expr {$sash1 - 20}]
2952 if {$use_ttk} {
2953 $win sashpos 0 $sash0
2954 $win sashpos 1 $sash1
2955 } else {
2956 $win sash place 0 $sash0 [lindex $s0 1]
2957 $win sash place 1 $sash1 [lindex $s1 1]
2960 set oldwidth($win) $w
2963 proc resizecdetpanes {win w} {
2964 global oldwidth use_ttk
2965 if {[info exists oldwidth($win)]} {
2966 if {$use_ttk} {
2967 set s0 [$win sashpos 0]
2968 } else {
2969 set s0 [$win sash coord 0]
2971 if {$w < 60} {
2972 set sash0 [expr {int($w*3/4 - 2)}]
2973 } else {
2974 set factor [expr {1.0 * $w / $oldwidth($win)}]
2975 set sash0 [expr {int($factor * [lindex $s0 0])}]
2976 if {$sash0 < 45} {
2977 set sash0 45
2979 if {$sash0 > $w - 15} {
2980 set sash0 [expr {$w - 15}]
2983 if {$use_ttk} {
2984 $win sashpos 0 $sash0
2985 } else {
2986 $win sash place 0 $sash0 [lindex $s0 1]
2989 set oldwidth($win) $w
2992 proc allcanvs args {
2993 global canv canv2 canv3
2994 eval $canv $args
2995 eval $canv2 $args
2996 eval $canv3 $args
2999 proc bindall {event action} {
3000 global canv canv2 canv3
3001 bind $canv $event $action
3002 bind $canv2 $event $action
3003 bind $canv3 $event $action
3006 proc about {} {
3007 global uifont NS
3008 set w .about
3009 if {[winfo exists $w]} {
3010 raise $w
3011 return
3013 ttk_toplevel $w
3014 wm title $w [mc "About gitk"]
3015 make_transient $w .
3016 message $w.m -text [mc "
3017 Gitk - a commit viewer for git
3019 Copyright \u00a9 2005-2014 Paul Mackerras
3021 Use and redistribute under the terms of the GNU General Public License"] \
3022 -justify center -aspect 400 -border 2 -bg white -relief groove
3023 pack $w.m -side top -fill x -padx 2 -pady 2
3024 ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
3025 pack $w.ok -side bottom
3026 bind $w <Visibility> "focus $w.ok"
3027 bind $w <Key-Escape> "destroy $w"
3028 bind $w <Key-Return> "destroy $w"
3029 tk::PlaceWindow $w widget .
3032 proc keys {} {
3033 global NS
3034 set w .keys
3035 if {[winfo exists $w]} {
3036 raise $w
3037 return
3039 if {[tk windowingsystem] eq {aqua}} {
3040 set M1T Cmd
3041 } else {
3042 set M1T Ctrl
3044 ttk_toplevel $w
3045 wm title $w [mc "Gitk key bindings"]
3046 make_transient $w .
3047 message $w.m -text "
3048 [mc "Gitk key bindings:"]
3050 [mc "<%s-Q> Quit" $M1T]
3051 [mc "<%s-W> Close window" $M1T]
3052 [mc "<Home> Move to first commit"]
3053 [mc "<End> Move to last commit"]
3054 [mc "<Up>, p, k Move up one commit"]
3055 [mc "<Down>, n, j Move down one commit"]
3056 [mc "<Left>, z, h Go back in history list"]
3057 [mc "<Right>, x, l Go forward in history list"]
3058 [mc "<%s-n> Go to n-th parent of current commit in history list" $M1T]
3059 [mc "<PageUp> Move up one page in commit list"]
3060 [mc "<PageDown> Move down one page in commit list"]
3061 [mc "<%s-Home> Scroll to top of commit list" $M1T]
3062 [mc "<%s-End> Scroll to bottom of commit list" $M1T]
3063 [mc "<%s-Up> Scroll commit list up one line" $M1T]
3064 [mc "<%s-Down> Scroll commit list down one line" $M1T]
3065 [mc "<%s-PageUp> Scroll commit list up one page" $M1T]
3066 [mc "<%s-PageDown> Scroll commit list down one page" $M1T]
3067 [mc "<Shift-Up> Find backwards (upwards, later commits)"]
3068 [mc "<Shift-Down> Find forwards (downwards, earlier commits)"]
3069 [mc "<Delete>, b Scroll diff view up one page"]
3070 [mc "<Backspace> Scroll diff view up one page"]
3071 [mc "<Space> Scroll diff view down one page"]
3072 [mc "u Scroll diff view up 18 lines"]
3073 [mc "d Scroll diff view down 18 lines"]
3074 [mc "<%s-F> Find" $M1T]
3075 [mc "<%s-G> Move to next find hit" $M1T]
3076 [mc "<Return> Move to next find hit"]
3077 [mc "g Go to commit"]
3078 [mc "/ Focus the search box"]
3079 [mc "? Move to previous find hit"]
3080 [mc "f Scroll diff view to next file"]
3081 [mc "<%s-S> Search for next hit in diff view" $M1T]
3082 [mc "<%s-R> Search for previous hit in diff view" $M1T]
3083 [mc "<%s-KP+> Increase font size" $M1T]
3084 [mc "<%s-plus> Increase font size" $M1T]
3085 [mc "<%s-KP-> Decrease font size" $M1T]
3086 [mc "<%s-minus> Decrease font size" $M1T]
3087 [mc "<F5> Update"]
3089 -justify left -bg white -border 2 -relief groove
3090 pack $w.m -side top -fill both -padx 2 -pady 2
3091 ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
3092 bind $w <Key-Escape> [list destroy $w]
3093 pack $w.ok -side bottom
3094 bind $w <Visibility> "focus $w.ok"
3095 bind $w <Key-Escape> "destroy $w"
3096 bind $w <Key-Return> "destroy $w"
3099 # Procedures for manipulating the file list window at the
3100 # bottom right of the overall window.
3102 proc treeview {w l openlevs} {
3103 global treecontents treediropen treeheight treeparent treeindex
3105 set ix 0
3106 set treeindex() 0
3107 set lev 0
3108 set prefix {}
3109 set prefixend -1
3110 set prefendstack {}
3111 set htstack {}
3112 set ht 0
3113 set treecontents() {}
3114 $w conf -state normal
3115 foreach f $l {
3116 while {[string range $f 0 $prefixend] ne $prefix} {
3117 if {$lev <= $openlevs} {
3118 $w mark set e:$treeindex($prefix) "end -1c"
3119 $w mark gravity e:$treeindex($prefix) left
3121 set treeheight($prefix) $ht
3122 incr ht [lindex $htstack end]
3123 set htstack [lreplace $htstack end end]
3124 set prefixend [lindex $prefendstack end]
3125 set prefendstack [lreplace $prefendstack end end]
3126 set prefix [string range $prefix 0 $prefixend]
3127 incr lev -1
3129 set tail [string range $f [expr {$prefixend+1}] end]
3130 while {[set slash [string first "/" $tail]] >= 0} {
3131 lappend htstack $ht
3132 set ht 0
3133 lappend prefendstack $prefixend
3134 incr prefixend [expr {$slash + 1}]
3135 set d [string range $tail 0 $slash]
3136 lappend treecontents($prefix) $d
3137 set oldprefix $prefix
3138 append prefix $d
3139 set treecontents($prefix) {}
3140 set treeindex($prefix) [incr ix]
3141 set treeparent($prefix) $oldprefix
3142 set tail [string range $tail [expr {$slash+1}] end]
3143 if {$lev <= $openlevs} {
3144 set ht 1
3145 set treediropen($prefix) [expr {$lev < $openlevs}]
3146 set bm [expr {$lev == $openlevs? "tri-rt": "tri-dn"}]
3147 $w mark set d:$ix "end -1c"
3148 $w mark gravity d:$ix left
3149 set str "\n"
3150 for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3151 $w insert end $str
3152 $w image create end -align center -image $bm -padx 1 \
3153 -name a:$ix
3154 $w insert end $d [highlight_tag $prefix]
3155 $w mark set s:$ix "end -1c"
3156 $w mark gravity s:$ix left
3158 incr lev
3160 if {$tail ne {}} {
3161 if {$lev <= $openlevs} {
3162 incr ht
3163 set str "\n"
3164 for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3165 $w insert end $str
3166 $w insert end $tail [highlight_tag $f]
3168 lappend treecontents($prefix) $tail
3171 while {$htstack ne {}} {
3172 set treeheight($prefix) $ht
3173 incr ht [lindex $htstack end]
3174 set htstack [lreplace $htstack end end]
3175 set prefixend [lindex $prefendstack end]
3176 set prefendstack [lreplace $prefendstack end end]
3177 set prefix [string range $prefix 0 $prefixend]
3179 $w conf -state disabled
3182 proc linetoelt {l} {
3183 global treeheight treecontents
3185 set y 2
3186 set prefix {}
3187 while {1} {
3188 foreach e $treecontents($prefix) {
3189 if {$y == $l} {
3190 return "$prefix$e"
3192 set n 1
3193 if {[string index $e end] eq "/"} {
3194 set n $treeheight($prefix$e)
3195 if {$y + $n > $l} {
3196 append prefix $e
3197 incr y
3198 break
3201 incr y $n
3206 proc highlight_tree {y prefix} {
3207 global treeheight treecontents cflist
3209 foreach e $treecontents($prefix) {
3210 set path $prefix$e
3211 if {[highlight_tag $path] ne {}} {
3212 $cflist tag add bold $y.0 "$y.0 lineend"
3214 incr y
3215 if {[string index $e end] eq "/" && $treeheight($path) > 1} {
3216 set y [highlight_tree $y $path]
3219 return $y
3222 proc treeclosedir {w dir} {
3223 global treediropen treeheight treeparent treeindex
3225 set ix $treeindex($dir)
3226 $w conf -state normal
3227 $w delete s:$ix e:$ix
3228 set treediropen($dir) 0
3229 $w image configure a:$ix -image tri-rt
3230 $w conf -state disabled
3231 set n [expr {1 - $treeheight($dir)}]
3232 while {$dir ne {}} {
3233 incr treeheight($dir) $n
3234 set dir $treeparent($dir)
3238 proc treeopendir {w dir} {
3239 global treediropen treeheight treeparent treecontents treeindex
3241 set ix $treeindex($dir)
3242 $w conf -state normal
3243 $w image configure a:$ix -image tri-dn
3244 $w mark set e:$ix s:$ix
3245 $w mark gravity e:$ix right
3246 set lev 0
3247 set str "\n"
3248 set n [llength $treecontents($dir)]
3249 for {set x $dir} {$x ne {}} {set x $treeparent($x)} {
3250 incr lev
3251 append str "\t"
3252 incr treeheight($x) $n
3254 foreach e $treecontents($dir) {
3255 set de $dir$e
3256 if {[string index $e end] eq "/"} {
3257 set iy $treeindex($de)
3258 $w mark set d:$iy e:$ix
3259 $w mark gravity d:$iy left
3260 $w insert e:$ix $str
3261 set treediropen($de) 0
3262 $w image create e:$ix -align center -image tri-rt -padx 1 \
3263 -name a:$iy
3264 $w insert e:$ix $e [highlight_tag $de]
3265 $w mark set s:$iy e:$ix
3266 $w mark gravity s:$iy left
3267 set treeheight($de) 1
3268 } else {
3269 $w insert e:$ix $str
3270 $w insert e:$ix $e [highlight_tag $de]
3273 $w mark gravity e:$ix right
3274 $w conf -state disabled
3275 set treediropen($dir) 1
3276 set top [lindex [split [$w index @0,0] .] 0]
3277 set ht [$w cget -height]
3278 set l [lindex [split [$w index s:$ix] .] 0]
3279 if {$l < $top} {
3280 $w yview $l.0
3281 } elseif {$l + $n + 1 > $top + $ht} {
3282 set top [expr {$l + $n + 2 - $ht}]
3283 if {$l < $top} {
3284 set top $l
3286 $w yview $top.0
3290 proc treeclick {w x y} {
3291 global treediropen cmitmode ctext cflist cflist_top
3293 if {$cmitmode ne "tree"} return
3294 if {![info exists cflist_top]} return
3295 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3296 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3297 $cflist tag add highlight $l.0 "$l.0 lineend"
3298 set cflist_top $l
3299 if {$l == 1} {
3300 $ctext yview 1.0
3301 return
3303 set e [linetoelt $l]
3304 if {[string index $e end] ne "/"} {
3305 showfile $e
3306 } elseif {$treediropen($e)} {
3307 treeclosedir $w $e
3308 } else {
3309 treeopendir $w $e
3313 proc setfilelist {id} {
3314 global treefilelist cflist jump_to_here
3316 treeview $cflist $treefilelist($id) 0
3317 if {$jump_to_here ne {}} {
3318 set f [lindex $jump_to_here 0]
3319 if {[lsearch -exact $treefilelist($id) $f] >= 0} {
3320 showfile $f
3325 image create bitmap tri-rt -background black -foreground blue -data {
3326 #define tri-rt_width 13
3327 #define tri-rt_height 13
3328 static unsigned char tri-rt_bits[] = {
3329 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x30, 0x00, 0x70, 0x00, 0xf0, 0x00,
3330 0xf0, 0x01, 0xf0, 0x00, 0x70, 0x00, 0x30, 0x00, 0x10, 0x00, 0x00, 0x00,
3331 0x00, 0x00};
3332 } -maskdata {
3333 #define tri-rt-mask_width 13
3334 #define tri-rt-mask_height 13
3335 static unsigned char tri-rt-mask_bits[] = {
3336 0x08, 0x00, 0x18, 0x00, 0x38, 0x00, 0x78, 0x00, 0xf8, 0x00, 0xf8, 0x01,
3337 0xf8, 0x03, 0xf8, 0x01, 0xf8, 0x00, 0x78, 0x00, 0x38, 0x00, 0x18, 0x00,
3338 0x08, 0x00};
3340 image create bitmap tri-dn -background black -foreground blue -data {
3341 #define tri-dn_width 13
3342 #define tri-dn_height 13
3343 static unsigned char tri-dn_bits[] = {
3344 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xf8, 0x03,
3345 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3346 0x00, 0x00};
3347 } -maskdata {
3348 #define tri-dn-mask_width 13
3349 #define tri-dn-mask_height 13
3350 static unsigned char tri-dn-mask_bits[] = {
3351 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x1f, 0xfe, 0x0f, 0xfc, 0x07,
3352 0xf8, 0x03, 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
3353 0x00, 0x00};
3356 image create bitmap reficon-T -background black -foreground yellow -data {
3357 #define tagicon_width 13
3358 #define tagicon_height 9
3359 static unsigned char tagicon_bits[] = {
3360 0x00, 0x00, 0x00, 0x00, 0xf0, 0x07, 0xf8, 0x07,
3361 0xfc, 0x07, 0xf8, 0x07, 0xf0, 0x07, 0x00, 0x00, 0x00, 0x00};
3362 } -maskdata {
3363 #define tagicon-mask_width 13
3364 #define tagicon-mask_height 9
3365 static unsigned char tagicon-mask_bits[] = {
3366 0x00, 0x00, 0xf0, 0x0f, 0xf8, 0x0f, 0xfc, 0x0f,
3367 0xfe, 0x0f, 0xfc, 0x0f, 0xf8, 0x0f, 0xf0, 0x0f, 0x00, 0x00};
3369 set rectdata {
3370 #define headicon_width 13
3371 #define headicon_height 9
3372 static unsigned char headicon_bits[] = {
3373 0x00, 0x00, 0x00, 0x00, 0xf8, 0x07, 0xf8, 0x07,
3374 0xf8, 0x07, 0xf8, 0x07, 0xf8, 0x07, 0x00, 0x00, 0x00, 0x00};
3376 set rectmask {
3377 #define headicon-mask_width 13
3378 #define headicon-mask_height 9
3379 static unsigned char headicon-mask_bits[] = {
3380 0x00, 0x00, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f,
3381 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0x00, 0x00};
3383 image create bitmap reficon-H -background black -foreground green \
3384 -data $rectdata -maskdata $rectmask
3385 image create bitmap reficon-o -background black -foreground "#ddddff" \
3386 -data $rectdata -maskdata $rectmask
3388 proc init_flist {first} {
3389 global cflist cflist_top difffilestart
3391 $cflist conf -state normal
3392 $cflist delete 0.0 end
3393 if {$first ne {}} {
3394 $cflist insert end $first
3395 set cflist_top 1
3396 $cflist tag add highlight 1.0 "1.0 lineend"
3397 } else {
3398 unset -nocomplain cflist_top
3400 $cflist conf -state disabled
3401 set difffilestart {}
3404 proc highlight_tag {f} {
3405 global highlight_paths
3407 foreach p $highlight_paths {
3408 if {[string match $p $f]} {
3409 return "bold"
3412 return {}
3415 proc highlight_filelist {} {
3416 global cmitmode cflist
3418 $cflist conf -state normal
3419 if {$cmitmode ne "tree"} {
3420 set end [lindex [split [$cflist index end] .] 0]
3421 for {set l 2} {$l < $end} {incr l} {
3422 set line [$cflist get $l.0 "$l.0 lineend"]
3423 if {[highlight_tag $line] ne {}} {
3424 $cflist tag add bold $l.0 "$l.0 lineend"
3427 } else {
3428 highlight_tree 2 {}
3430 $cflist conf -state disabled
3433 proc unhighlight_filelist {} {
3434 global cflist
3436 $cflist conf -state normal
3437 $cflist tag remove bold 1.0 end
3438 $cflist conf -state disabled
3441 proc add_flist {fl} {
3442 global cflist
3444 $cflist conf -state normal
3445 foreach f $fl {
3446 $cflist insert end "\n"
3447 $cflist insert end $f [highlight_tag $f]
3449 $cflist conf -state disabled
3452 proc sel_flist {w x y} {
3453 global ctext difffilestart cflist cflist_top cmitmode
3455 if {$cmitmode eq "tree"} return
3456 if {![info exists cflist_top]} return
3457 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3458 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3459 $cflist tag add highlight $l.0 "$l.0 lineend"
3460 set cflist_top $l
3461 if {$l == 1} {
3462 $ctext yview 1.0
3463 } else {
3464 catch {$ctext yview [lindex $difffilestart [expr {$l - 2}]]}
3466 suppress_highlighting_file_for_current_scrollpos
3469 proc pop_flist_menu {w X Y x y} {
3470 global ctext cflist cmitmode flist_menu flist_menu_file
3471 global treediffs diffids
3473 stopfinding
3474 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3475 if {$l <= 1} return
3476 if {$cmitmode eq "tree"} {
3477 set e [linetoelt $l]
3478 if {[string index $e end] eq "/"} return
3479 } else {
3480 set e [lindex $treediffs($diffids) [expr {$l-2}]]
3482 set flist_menu_file $e
3483 set xdiffstate "normal"
3484 if {$cmitmode eq "tree"} {
3485 set xdiffstate "disabled"
3487 # Disable "External diff" item in tree mode
3488 $flist_menu entryconf 2 -state $xdiffstate
3489 tk_popup $flist_menu $X $Y
3492 proc find_ctext_fileinfo {line} {
3493 global ctext_file_names ctext_file_lines
3495 set ok [bsearch $ctext_file_lines $line]
3496 set tline [lindex $ctext_file_lines $ok]
3498 if {$ok >= [llength $ctext_file_lines] || $line < $tline} {
3499 return {}
3500 } else {
3501 return [list [lindex $ctext_file_names $ok] $tline]
3505 proc pop_diff_menu {w X Y x y} {
3506 global ctext diff_menu flist_menu_file
3507 global diff_menu_txtpos diff_menu_line
3508 global diff_menu_filebase
3510 set diff_menu_txtpos [split [$w index "@$x,$y"] "."]
3511 set diff_menu_line [lindex $diff_menu_txtpos 0]
3512 # don't pop up the menu on hunk-separator or file-separator lines
3513 if {[lsearch -glob [$ctext tag names $diff_menu_line.0] "*sep"] >= 0} {
3514 return
3516 stopfinding
3517 set f [find_ctext_fileinfo $diff_menu_line]
3518 if {$f eq {}} return
3519 set flist_menu_file [lindex $f 0]
3520 set diff_menu_filebase [lindex $f 1]
3521 tk_popup $diff_menu $X $Y
3524 proc flist_hl {only} {
3525 global flist_menu_file findstring gdttype
3527 set x [shellquote $flist_menu_file]
3528 if {$only || $findstring eq {} || $gdttype ne [mc "touching paths:"]} {
3529 set findstring $x
3530 } else {
3531 append findstring " " $x
3533 set gdttype [mc "touching paths:"]
3536 proc gitknewtmpdir {} {
3537 global diffnum gitktmpdir gitdir env
3539 if {![info exists gitktmpdir]} {
3540 if {[info exists env(GITK_TMPDIR)]} {
3541 set tmpdir $env(GITK_TMPDIR)
3542 } elseif {[info exists env(TMPDIR)]} {
3543 set tmpdir $env(TMPDIR)
3544 } else {
3545 set tmpdir $gitdir
3547 set gitktmpformat [file join $tmpdir ".gitk-tmp.XXXXXX"]
3548 if {[catch {set gitktmpdir [exec mktemp -d $gitktmpformat]}]} {
3549 set gitktmpdir [file join $gitdir [format ".gitk-tmp.%s" [pid]]]
3551 if {[catch {file mkdir $gitktmpdir} err]} {
3552 error_popup "[mc "Error creating temporary directory %s:" $gitktmpdir] $err"
3553 unset gitktmpdir
3554 return {}
3556 set diffnum 0
3558 incr diffnum
3559 set diffdir [file join $gitktmpdir $diffnum]
3560 if {[catch {file mkdir $diffdir} err]} {
3561 error_popup "[mc "Error creating temporary directory %s:" $diffdir] $err"
3562 return {}
3564 return $diffdir
3567 proc save_file_from_commit {filename output what} {
3568 global nullfile
3570 if {[catch {exec git show $filename -- > $output} err]} {
3571 if {[string match "fatal: bad revision *" $err]} {
3572 return $nullfile
3574 error_popup "[mc "Error getting \"%s\" from %s:" $filename $what] $err"
3575 return {}
3577 return $output
3580 proc external_diff_get_one_file {diffid filename diffdir} {
3581 global nullid nullid2 nullfile
3582 global worktree
3584 if {$diffid == $nullid} {
3585 set difffile [file join $worktree $filename]
3586 if {[file exists $difffile]} {
3587 return $difffile
3589 return $nullfile
3591 if {$diffid == $nullid2} {
3592 set difffile [file join $diffdir "\[index\] [file tail $filename]"]
3593 return [save_file_from_commit :$filename $difffile index]
3595 set difffile [file join $diffdir "\[$diffid\] [file tail $filename]"]
3596 return [save_file_from_commit $diffid:$filename $difffile \
3597 "revision $diffid"]
3600 proc external_diff {} {
3601 global nullid nullid2
3602 global flist_menu_file
3603 global diffids
3604 global extdifftool
3606 if {[llength $diffids] == 1} {
3607 # no reference commit given
3608 set diffidto [lindex $diffids 0]
3609 if {$diffidto eq $nullid} {
3610 # diffing working copy with index
3611 set diffidfrom $nullid2
3612 } elseif {$diffidto eq $nullid2} {
3613 # diffing index with HEAD
3614 set diffidfrom "HEAD"
3615 } else {
3616 # use first parent commit
3617 global parentlist selectedline
3618 set diffidfrom [lindex $parentlist $selectedline 0]
3620 } else {
3621 set diffidfrom [lindex $diffids 0]
3622 set diffidto [lindex $diffids 1]
3625 # make sure that several diffs wont collide
3626 set diffdir [gitknewtmpdir]
3627 if {$diffdir eq {}} return
3629 # gather files to diff
3630 set difffromfile [external_diff_get_one_file $diffidfrom $flist_menu_file $diffdir]
3631 set difftofile [external_diff_get_one_file $diffidto $flist_menu_file $diffdir]
3633 if {$difffromfile ne {} && $difftofile ne {}} {
3634 set cmd [list [shellsplit $extdifftool] $difffromfile $difftofile]
3635 if {[catch {set fl [open |$cmd r]} err]} {
3636 file delete -force $diffdir
3637 error_popup "$extdifftool: [mc "command failed:"] $err"
3638 } else {
3639 fconfigure $fl -blocking 0
3640 filerun $fl [list delete_at_eof $fl $diffdir]
3645 proc find_hunk_blamespec {base line} {
3646 global ctext
3648 # Find and parse the hunk header
3649 set s_lix [$ctext search -backwards -regexp ^@@ "$line.0 lineend" $base.0]
3650 if {$s_lix eq {}} return
3652 set s_line [$ctext get $s_lix "$s_lix + 1 lines"]
3653 if {![regexp {^@@@*(( -\d+(,\d+)?)+) \+(\d+)(,\d+)? @@} $s_line \
3654 s_line old_specs osz osz1 new_line nsz]} {
3655 return
3658 # base lines for the parents
3659 set base_lines [list $new_line]
3660 foreach old_spec [lrange [split $old_specs " "] 1 end] {
3661 if {![regexp -- {-(\d+)(,\d+)?} $old_spec \
3662 old_spec old_line osz]} {
3663 return
3665 lappend base_lines $old_line
3668 # Now scan the lines to determine offset within the hunk
3669 set max_parent [expr {[llength $base_lines]-2}]
3670 set dline 0
3671 set s_lno [lindex [split $s_lix "."] 0]
3673 # Determine if the line is removed
3674 set chunk [$ctext get $line.0 "$line.1 + $max_parent chars"]
3675 if {[string match {[-+ ]*} $chunk]} {
3676 set removed_idx [string first "-" $chunk]
3677 # Choose a parent index
3678 if {$removed_idx >= 0} {
3679 set parent $removed_idx
3680 } else {
3681 set unchanged_idx [string first " " $chunk]
3682 if {$unchanged_idx >= 0} {
3683 set parent $unchanged_idx
3684 } else {
3685 # blame the current commit
3686 set parent -1
3689 # then count other lines that belong to it
3690 for {set i $line} {[incr i -1] > $s_lno} {} {
3691 set chunk [$ctext get $i.0 "$i.1 + $max_parent chars"]
3692 # Determine if the line is removed
3693 set removed_idx [string first "-" $chunk]
3694 if {$parent >= 0} {
3695 set code [string index $chunk $parent]
3696 if {$code eq "-" || ($removed_idx < 0 && $code ne "+")} {
3697 incr dline
3699 } else {
3700 if {$removed_idx < 0} {
3701 incr dline
3705 incr parent
3706 } else {
3707 set parent 0
3710 incr dline [lindex $base_lines $parent]
3711 return [list $parent $dline]
3714 proc external_blame_diff {} {
3715 global currentid cmitmode
3716 global diff_menu_txtpos diff_menu_line
3717 global diff_menu_filebase flist_menu_file
3719 if {$cmitmode eq "tree"} {
3720 set parent_idx 0
3721 set line [expr {$diff_menu_line - $diff_menu_filebase}]
3722 } else {
3723 set hinfo [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3724 if {$hinfo ne {}} {
3725 set parent_idx [lindex $hinfo 0]
3726 set line [lindex $hinfo 1]
3727 } else {
3728 set parent_idx 0
3729 set line 0
3733 external_blame $parent_idx $line
3736 # Find the SHA1 ID of the blob for file $fname in the index
3737 # at stage 0 or 2
3738 proc index_sha1 {fname} {
3739 set f [open [list | git ls-files -s $fname] r]
3740 while {[gets $f line] >= 0} {
3741 set info [lindex [split $line "\t"] 0]
3742 set stage [lindex $info 2]
3743 if {$stage eq "0" || $stage eq "2"} {
3744 close $f
3745 return [lindex $info 1]
3748 close $f
3749 return {}
3752 # Turn an absolute path into one relative to the current directory
3753 proc make_relative {f} {
3754 if {[file pathtype $f] eq "relative"} {
3755 return $f
3757 set elts [file split $f]
3758 set here [file split [pwd]]
3759 set ei 0
3760 set hi 0
3761 set res {}
3762 foreach d $here {
3763 if {$ei < $hi || $ei >= [llength $elts] || [lindex $elts $ei] ne $d} {
3764 lappend res ".."
3765 } else {
3766 incr ei
3768 incr hi
3770 set elts [concat $res [lrange $elts $ei end]]
3771 return [eval file join $elts]
3774 proc external_blame {parent_idx {line {}}} {
3775 global flist_menu_file cdup
3776 global nullid nullid2
3777 global parentlist selectedline currentid
3779 if {$parent_idx > 0} {
3780 set base_commit [lindex $parentlist $selectedline [expr {$parent_idx-1}]]
3781 } else {
3782 set base_commit $currentid
3785 if {$base_commit eq {} || $base_commit eq $nullid || $base_commit eq $nullid2} {
3786 error_popup [mc "No such commit"]
3787 return
3790 set cmdline [list git gui blame]
3791 if {$line ne {} && $line > 1} {
3792 lappend cmdline "--line=$line"
3794 set f [file join $cdup $flist_menu_file]
3795 # Unfortunately it seems git gui blame doesn't like
3796 # being given an absolute path...
3797 set f [make_relative $f]
3798 lappend cmdline $base_commit $f
3799 if {[catch {eval exec $cmdline &} err]} {
3800 error_popup "[mc "git gui blame: command failed:"] $err"
3804 proc show_line_source {} {
3805 global cmitmode currentid parents curview blamestuff blameinst
3806 global diff_menu_line diff_menu_filebase flist_menu_file
3807 global nullid nullid2 gitdir cdup
3809 set from_index {}
3810 if {$cmitmode eq "tree"} {
3811 set id $currentid
3812 set line [expr {$diff_menu_line - $diff_menu_filebase}]
3813 } else {
3814 set h [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3815 if {$h eq {}} return
3816 set pi [lindex $h 0]
3817 if {$pi == 0} {
3818 mark_ctext_line $diff_menu_line
3819 return
3821 incr pi -1
3822 if {$currentid eq $nullid} {
3823 if {$pi > 0} {
3824 # must be a merge in progress...
3825 if {[catch {
3826 # get the last line from .git/MERGE_HEAD
3827 set f [open [file join $gitdir MERGE_HEAD] r]
3828 set id [lindex [split [read $f] "\n"] end-1]
3829 close $f
3830 } err]} {
3831 error_popup [mc "Couldn't read merge head: %s" $err]
3832 return
3834 } elseif {$parents($curview,$currentid) eq $nullid2} {
3835 # need to do the blame from the index
3836 if {[catch {
3837 set from_index [index_sha1 $flist_menu_file]
3838 } err]} {
3839 error_popup [mc "Error reading index: %s" $err]
3840 return
3842 } else {
3843 set id $parents($curview,$currentid)
3845 } else {
3846 set id [lindex $parents($curview,$currentid) $pi]
3848 set line [lindex $h 1]
3850 set blameargs {}
3851 if {$from_index ne {}} {
3852 lappend blameargs | git cat-file blob $from_index
3854 lappend blameargs | git blame -p -L$line,+1
3855 if {$from_index ne {}} {
3856 lappend blameargs --contents -
3857 } else {
3858 lappend blameargs $id
3860 lappend blameargs -- [file join $cdup $flist_menu_file]
3861 if {[catch {
3862 set f [open $blameargs r]
3863 } err]} {
3864 error_popup [mc "Couldn't start git blame: %s" $err]
3865 return
3867 nowbusy blaming [mc "Searching"]
3868 fconfigure $f -blocking 0
3869 set i [reg_instance $f]
3870 set blamestuff($i) {}
3871 set blameinst $i
3872 filerun $f [list read_line_source $f $i]
3875 proc stopblaming {} {
3876 global blameinst
3878 if {[info exists blameinst]} {
3879 stop_instance $blameinst
3880 unset blameinst
3881 notbusy blaming
3885 proc read_line_source {fd inst} {
3886 global blamestuff curview commfd blameinst nullid nullid2
3888 while {[gets $fd line] >= 0} {
3889 lappend blamestuff($inst) $line
3891 if {![eof $fd]} {
3892 return 1
3894 unset commfd($inst)
3895 unset blameinst
3896 notbusy blaming
3897 fconfigure $fd -blocking 1
3898 if {[catch {close $fd} err]} {
3899 error_popup [mc "Error running git blame: %s" $err]
3900 return 0
3903 set fname {}
3904 set line [split [lindex $blamestuff($inst) 0] " "]
3905 set id [lindex $line 0]
3906 set lnum [lindex $line 1]
3907 if {[string length $id] == 40 && [string is xdigit $id] &&
3908 [string is digit -strict $lnum]} {
3909 # look for "filename" line
3910 foreach l $blamestuff($inst) {
3911 if {[string match "filename *" $l]} {
3912 set fname [string range $l 9 end]
3913 break
3917 if {$fname ne {}} {
3918 # all looks good, select it
3919 if {$id eq $nullid} {
3920 # blame uses all-zeroes to mean not committed,
3921 # which would mean a change in the index
3922 set id $nullid2
3924 if {[commitinview $id $curview]} {
3925 selectline [rowofcommit $id] 1 [list $fname $lnum] 1
3926 } else {
3927 error_popup [mc "That line comes from commit %s, \
3928 which is not in this view" [shortids $id]]
3930 } else {
3931 puts "oops couldn't parse git blame output"
3933 return 0
3936 # delete $dir when we see eof on $f (presumably because the child has exited)
3937 proc delete_at_eof {f dir} {
3938 while {[gets $f line] >= 0} {}
3939 if {[eof $f]} {
3940 if {[catch {close $f} err]} {
3941 error_popup "[mc "External diff viewer failed:"] $err"
3943 file delete -force $dir
3944 return 0
3946 return 1
3949 # Functions for adding and removing shell-type quoting
3951 proc shellquote {str} {
3952 if {![string match "*\['\"\\ \t]*" $str]} {
3953 return $str
3955 if {![string match "*\['\"\\]*" $str]} {
3956 return "\"$str\""
3958 if {![string match "*'*" $str]} {
3959 return "'$str'"
3961 return "\"[string map {\" \\\" \\ \\\\} $str]\""
3964 proc shellarglist {l} {
3965 set str {}
3966 foreach a $l {
3967 if {$str ne {}} {
3968 append str " "
3970 append str [shellquote $a]
3972 return $str
3975 proc shelldequote {str} {
3976 set ret {}
3977 set used -1
3978 while {1} {
3979 incr used
3980 if {![regexp -start $used -indices "\['\"\\\\ \t]" $str first]} {
3981 append ret [string range $str $used end]
3982 set used [string length $str]
3983 break
3985 set first [lindex $first 0]
3986 set ch [string index $str $first]
3987 if {$first > $used} {
3988 append ret [string range $str $used [expr {$first - 1}]]
3989 set used $first
3991 if {$ch eq " " || $ch eq "\t"} break
3992 incr used
3993 if {$ch eq "'"} {
3994 set first [string first "'" $str $used]
3995 if {$first < 0} {
3996 error "unmatched single-quote"
3998 append ret [string range $str $used [expr {$first - 1}]]
3999 set used $first
4000 continue
4002 if {$ch eq "\\"} {
4003 if {$used >= [string length $str]} {
4004 error "trailing backslash"
4006 append ret [string index $str $used]
4007 continue
4009 # here ch == "\""
4010 while {1} {
4011 if {![regexp -start $used -indices "\[\"\\\\]" $str first]} {
4012 error "unmatched double-quote"
4014 set first [lindex $first 0]
4015 set ch [string index $str $first]
4016 if {$first > $used} {
4017 append ret [string range $str $used [expr {$first - 1}]]
4018 set used $first
4020 if {$ch eq "\""} break
4021 incr used
4022 append ret [string index $str $used]
4023 incr used
4026 return [list $used $ret]
4029 proc shellsplit {str} {
4030 set l {}
4031 while {1} {
4032 set str [string trimleft $str]
4033 if {$str eq {}} break
4034 set dq [shelldequote $str]
4035 set n [lindex $dq 0]
4036 set word [lindex $dq 1]
4037 set str [string range $str $n end]
4038 lappend l $word
4040 return $l
4043 proc set_window_title {} {
4044 global appname curview viewname vrevs
4045 set rev [mc "All files"]
4046 if {$curview ne 0} {
4047 if {$viewname($curview) eq [mc "Command line"]} {
4048 set rev [string map {"--gitk-symmetric-diff-marker" "--merge"} $vrevs($curview)]
4049 } else {
4050 set rev $viewname($curview)
4053 wm title . "[reponame]: $rev - $appname"
4056 # Code to implement multiple views
4058 proc newview {ishighlight} {
4059 global nextviewnum newviewname newishighlight
4060 global revtreeargs viewargscmd newviewopts curview
4062 set newishighlight $ishighlight
4063 set top .gitkview
4064 if {[winfo exists $top]} {
4065 raise $top
4066 return
4068 decode_view_opts $nextviewnum $revtreeargs
4069 set newviewname($nextviewnum) "[mc "View"] $nextviewnum"
4070 set newviewopts($nextviewnum,perm) 0
4071 set newviewopts($nextviewnum,cmd) $viewargscmd($curview)
4072 vieweditor $top $nextviewnum [mc "Gitk view definition"]
4075 set known_view_options {
4076 {perm b . {} {mc "Remember this view"}}
4077 {reflabel l + {} {mc "References (space separated list):"}}
4078 {refs t15 .. {} {mc "Branches & tags:"}}
4079 {allrefs b *. "--all" {mc "All refs"}}
4080 {branches b . "--branches" {mc "All (local) branches"}}
4081 {tags b . "--tags" {mc "All tags"}}
4082 {remotes b . "--remotes" {mc "All remote-tracking branches"}}
4083 {commitlbl l + {} {mc "Commit Info (regular expressions):"}}
4084 {author t15 .. "--author=*" {mc "Author:"}}
4085 {committer t15 . "--committer=*" {mc "Committer:"}}
4086 {loginfo t15 .. "--grep=*" {mc "Commit Message:"}}
4087 {allmatch b .. "--all-match" {mc "Matches all Commit Info criteria"}}
4088 {igrep b .. "--invert-grep" {mc "Matches no Commit Info criteria"}}
4089 {changes_l l + {} {mc "Changes to Files:"}}
4090 {pickaxe_s r0 . {} {mc "Fixed String"}}
4091 {pickaxe_t r1 . "--pickaxe-regex" {mc "Regular Expression"}}
4092 {pickaxe t15 .. "-S*" {mc "Search string:"}}
4093 {datelabel l + {} {mc "Commit Dates (\"2 weeks ago\", \"2009-03-17 15:27:38\", \"March 17, 2009 15:27:38\"):"}}
4094 {since t15 .. {"--since=*" "--after=*"} {mc "Since:"}}
4095 {until t15 . {"--until=*" "--before=*"} {mc "Until:"}}
4096 {limit_lbl l + {} {mc "Limit and/or skip a number of revisions (positive integer):"}}
4097 {limit t10 *. "--max-count=*" {mc "Number to show:"}}
4098 {skip t10 . "--skip=*" {mc "Number to skip:"}}
4099 {misc_lbl l + {} {mc "Miscellaneous options:"}}
4100 {dorder b *. {"--date-order" "-d"} {mc "Strictly sort by date"}}
4101 {lright b . "--left-right" {mc "Mark branch sides"}}
4102 {first b . "--first-parent" {mc "Limit to first parent"}}
4103 {smplhst b . "--simplify-by-decoration" {mc "Simple history"}}
4104 {args t50 *. {} {mc "Additional arguments to git log:"}}
4105 {allpaths path + {} {mc "Enter files and directories to include, one per line:"}}
4106 {cmd t50= + {} {mc "Command to generate more commits to include:"}}
4109 # Convert $newviewopts($n, ...) into args for git log.
4110 proc encode_view_opts {n} {
4111 global known_view_options newviewopts
4113 set rargs [list]
4114 foreach opt $known_view_options {
4115 set patterns [lindex $opt 3]
4116 if {$patterns eq {}} continue
4117 set pattern [lindex $patterns 0]
4119 if {[lindex $opt 1] eq "b"} {
4120 set val $newviewopts($n,[lindex $opt 0])
4121 if {$val} {
4122 lappend rargs $pattern
4124 } elseif {[regexp {^r(\d+)$} [lindex $opt 1] type value]} {
4125 regexp {^(.*_)} [lindex $opt 0] uselessvar button_id
4126 set val $newviewopts($n,$button_id)
4127 if {$val eq $value} {
4128 lappend rargs $pattern
4130 } else {
4131 set val $newviewopts($n,[lindex $opt 0])
4132 set val [string trim $val]
4133 if {$val ne {}} {
4134 set pfix [string range $pattern 0 end-1]
4135 lappend rargs $pfix$val
4139 set rargs [concat $rargs [shellsplit $newviewopts($n,refs)]]
4140 return [concat $rargs [shellsplit $newviewopts($n,args)]]
4143 # Fill $newviewopts($n, ...) based on args for git log.
4144 proc decode_view_opts {n view_args} {
4145 global known_view_options newviewopts
4147 foreach opt $known_view_options {
4148 set id [lindex $opt 0]
4149 if {[lindex $opt 1] eq "b"} {
4150 # Checkboxes
4151 set val 0
4152 } elseif {[regexp {^r(\d+)$} [lindex $opt 1]]} {
4153 # Radiobuttons
4154 regexp {^(.*_)} $id uselessvar id
4155 set val 0
4156 } else {
4157 # Text fields
4158 set val {}
4160 set newviewopts($n,$id) $val
4162 set oargs [list]
4163 set refargs [list]
4164 foreach arg $view_args {
4165 if {[regexp -- {^-([0-9]+)$} $arg arg cnt]
4166 && ![info exists found(limit)]} {
4167 set newviewopts($n,limit) $cnt
4168 set found(limit) 1
4169 continue
4171 catch { unset val }
4172 foreach opt $known_view_options {
4173 set id [lindex $opt 0]
4174 if {[info exists found($id)]} continue
4175 foreach pattern [lindex $opt 3] {
4176 if {![string match $pattern $arg]} continue
4177 if {[lindex $opt 1] eq "b"} {
4178 # Check buttons
4179 set val 1
4180 } elseif {[regexp {^r(\d+)$} [lindex $opt 1] match num]} {
4181 # Radio buttons
4182 regexp {^(.*_)} $id uselessvar id
4183 set val $num
4184 } else {
4185 # Text input fields
4186 set size [string length $pattern]
4187 set val [string range $arg [expr {$size-1}] end]
4189 set newviewopts($n,$id) $val
4190 set found($id) 1
4191 break
4193 if {[info exists val]} break
4195 if {[info exists val]} continue
4196 if {[regexp {^-} $arg]} {
4197 lappend oargs $arg
4198 } else {
4199 lappend refargs $arg
4202 set newviewopts($n,refs) [shellarglist $refargs]
4203 set newviewopts($n,args) [shellarglist $oargs]
4206 proc edit_or_newview {} {
4207 global curview
4209 if {$curview > 0} {
4210 editview
4211 } else {
4212 newview 0
4216 proc editview {} {
4217 global curview
4218 global viewname viewperm newviewname newviewopts
4219 global viewargs viewargscmd
4221 set top .gitkvedit-$curview
4222 if {[winfo exists $top]} {
4223 raise $top
4224 return
4226 decode_view_opts $curview $viewargs($curview)
4227 set newviewname($curview) $viewname($curview)
4228 set newviewopts($curview,perm) $viewperm($curview)
4229 set newviewopts($curview,cmd) $viewargscmd($curview)
4230 vieweditor $top $curview "[mc "Gitk: edit view"] $viewname($curview)"
4233 proc vieweditor {top n title} {
4234 global newviewname newviewopts viewfiles bgcolor
4235 global known_view_options NS
4237 ttk_toplevel $top
4238 wm title $top [concat $title [mc "-- criteria for selecting revisions"]]
4239 make_transient $top .
4241 # View name
4242 ${NS}::frame $top.nfr
4243 ${NS}::label $top.nl -text [mc "View Name"]
4244 ${NS}::entry $top.name -width 20 -textvariable newviewname($n)
4245 pack $top.nfr -in $top -fill x -pady 5 -padx 3
4246 pack $top.nl -in $top.nfr -side left -padx {0 5}
4247 pack $top.name -in $top.nfr -side left -padx {0 25}
4249 # View options
4250 set cframe $top.nfr
4251 set cexpand 0
4252 set cnt 0
4253 foreach opt $known_view_options {
4254 set id [lindex $opt 0]
4255 set type [lindex $opt 1]
4256 set flags [lindex $opt 2]
4257 set title [eval [lindex $opt 4]]
4258 set lxpad 0
4260 if {$flags eq "+" || $flags eq "*"} {
4261 set cframe $top.fr$cnt
4262 incr cnt
4263 ${NS}::frame $cframe
4264 pack $cframe -in $top -fill x -pady 3 -padx 3
4265 set cexpand [expr {$flags eq "*"}]
4266 } elseif {$flags eq ".." || $flags eq "*."} {
4267 set cframe $top.fr$cnt
4268 incr cnt
4269 ${NS}::frame $cframe
4270 pack $cframe -in $top -fill x -pady 3 -padx [list 15 3]
4271 set cexpand [expr {$flags eq "*."}]
4272 } else {
4273 set lxpad 5
4276 if {$type eq "l"} {
4277 ${NS}::label $cframe.l_$id -text $title
4278 pack $cframe.l_$id -in $cframe -side left -pady [list 3 0] -anchor w
4279 } elseif {$type eq "b"} {
4280 ${NS}::checkbutton $cframe.c_$id -text $title -variable newviewopts($n,$id)
4281 pack $cframe.c_$id -in $cframe -side left \
4282 -padx [list $lxpad 0] -expand $cexpand -anchor w
4283 } elseif {[regexp {^r(\d+)$} $type type sz]} {
4284 regexp {^(.*_)} $id uselessvar button_id
4285 ${NS}::radiobutton $cframe.c_$id -text $title -variable newviewopts($n,$button_id) -value $sz
4286 pack $cframe.c_$id -in $cframe -side left \
4287 -padx [list $lxpad 0] -expand $cexpand -anchor w
4288 } elseif {[regexp {^t(\d+)$} $type type sz]} {
4289 ${NS}::label $cframe.l_$id -text $title
4290 ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4291 -textvariable newviewopts($n,$id)
4292 pack $cframe.l_$id -in $cframe -side left -padx [list $lxpad 0]
4293 pack $cframe.e_$id -in $cframe -side left -expand 1 -fill x
4294 } elseif {[regexp {^t(\d+)=$} $type type sz]} {
4295 ${NS}::label $cframe.l_$id -text $title
4296 ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4297 -textvariable newviewopts($n,$id)
4298 pack $cframe.l_$id -in $cframe -side top -pady [list 3 0] -anchor w
4299 pack $cframe.e_$id -in $cframe -side top -fill x
4300 } elseif {$type eq "path"} {
4301 ${NS}::label $top.l -text $title
4302 pack $top.l -in $top -side top -pady [list 3 0] -anchor w -padx 3
4303 text $top.t -width 40 -height 5 -background $bgcolor
4304 if {[info exists viewfiles($n)]} {
4305 foreach f $viewfiles($n) {
4306 $top.t insert end $f
4307 $top.t insert end "\n"
4309 $top.t delete {end - 1c} end
4310 $top.t mark set insert 0.0
4312 pack $top.t -in $top -side top -pady [list 0 5] -fill both -expand 1 -padx 3
4316 ${NS}::frame $top.buts
4317 ${NS}::button $top.buts.ok -text [mc "OK"] -command [list newviewok $top $n]
4318 ${NS}::button $top.buts.apply -text [mc "Apply (F5)"] -command [list newviewok $top $n 1]
4319 ${NS}::button $top.buts.can -text [mc "Cancel"] -command [list destroy $top]
4320 bind $top <Control-Return> [list newviewok $top $n]
4321 bind $top <F5> [list newviewok $top $n 1]
4322 bind $top <Escape> [list destroy $top]
4323 grid $top.buts.ok $top.buts.apply $top.buts.can
4324 grid columnconfigure $top.buts 0 -weight 1 -uniform a
4325 grid columnconfigure $top.buts 1 -weight 1 -uniform a
4326 grid columnconfigure $top.buts 2 -weight 1 -uniform a
4327 pack $top.buts -in $top -side top -fill x
4328 focus $top.t
4331 proc doviewmenu {m first cmd op argv} {
4332 set nmenu [$m index end]
4333 for {set i $first} {$i <= $nmenu} {incr i} {
4334 if {[$m entrycget $i -command] eq $cmd} {
4335 eval $m $op $i $argv
4336 break
4341 proc allviewmenus {n op args} {
4342 # global viewhlmenu
4344 doviewmenu .bar.view 5 [list showview $n] $op $args
4345 # doviewmenu $viewhlmenu 1 [list addvhighlight $n] $op $args
4348 proc newviewok {top n {apply 0}} {
4349 global nextviewnum newviewperm newviewname newishighlight
4350 global viewname viewfiles viewperm viewchanged selectedview curview
4351 global viewargs viewargscmd newviewopts viewhlmenu
4353 if {[catch {
4354 set newargs [encode_view_opts $n]
4355 } err]} {
4356 error_popup "[mc "Error in commit selection arguments:"] $err" $top
4357 return
4359 set files {}
4360 foreach f [split [$top.t get 0.0 end] "\n"] {
4361 set ft [string trim $f]
4362 if {$ft ne {}} {
4363 lappend files $ft
4366 if {![info exists viewfiles($n)]} {
4367 # creating a new view
4368 incr nextviewnum
4369 set viewname($n) $newviewname($n)
4370 set viewperm($n) $newviewopts($n,perm)
4371 set viewchanged($n) 1
4372 set viewfiles($n) $files
4373 set viewargs($n) $newargs
4374 set viewargscmd($n) $newviewopts($n,cmd)
4375 addviewmenu $n
4376 if {!$newishighlight} {
4377 run showview $n
4378 } else {
4379 run addvhighlight $n
4381 } else {
4382 # editing an existing view
4383 set viewperm($n) $newviewopts($n,perm)
4384 set viewchanged($n) 1
4385 if {$newviewname($n) ne $viewname($n)} {
4386 set viewname($n) $newviewname($n)
4387 doviewmenu .bar.view 5 [list showview $n] \
4388 entryconf [list -label $viewname($n)]
4389 # doviewmenu $viewhlmenu 1 [list addvhighlight $n] \
4390 # entryconf [list -label $viewname($n) -value $viewname($n)]
4392 if {$files ne $viewfiles($n) || $newargs ne $viewargs($n) || \
4393 $newviewopts($n,cmd) ne $viewargscmd($n)} {
4394 set viewfiles($n) $files
4395 set viewargs($n) $newargs
4396 set viewargscmd($n) $newviewopts($n,cmd)
4397 if {$curview == $n} {
4398 run reloadcommits
4402 if {$apply} return
4403 catch {destroy $top}
4406 proc delview {} {
4407 global curview viewperm hlview selectedhlview viewchanged
4409 if {$curview == 0} return
4410 if {[info exists hlview] && $hlview == $curview} {
4411 set selectedhlview [mc "None"]
4412 unset hlview
4414 allviewmenus $curview delete
4415 set viewperm($curview) 0
4416 set viewchanged($curview) 1
4417 showview 0
4420 proc addviewmenu {n} {
4421 global viewname viewhlmenu
4423 .bar.view add radiobutton -label $viewname($n) \
4424 -command [list showview $n] -variable selectedview -value $n
4425 #$viewhlmenu add radiobutton -label $viewname($n) \
4426 # -command [list addvhighlight $n] -variable selectedhlview
4429 proc showview {n} {
4430 global curview cached_commitrow ordertok
4431 global displayorder parentlist rowidlist rowisopt rowfinal
4432 global colormap rowtextx nextcolor canvxmax
4433 global numcommits viewcomplete
4434 global selectedline currentid canv canvy0
4435 global treediffs
4436 global pending_select mainheadid
4437 global commitidx
4438 global selectedview
4439 global hlview selectedhlview commitinterest
4441 if {$n == $curview} return
4442 set selid {}
4443 set ymax [lindex [$canv cget -scrollregion] 3]
4444 set span [$canv yview]
4445 set ytop [expr {[lindex $span 0] * $ymax}]
4446 set ybot [expr {[lindex $span 1] * $ymax}]
4447 set yscreen [expr {($ybot - $ytop) / 2}]
4448 if {$selectedline ne {}} {
4449 set selid $currentid
4450 set y [yc $selectedline]
4451 if {$ytop < $y && $y < $ybot} {
4452 set yscreen [expr {$y - $ytop}]
4454 } elseif {[info exists pending_select]} {
4455 set selid $pending_select
4456 unset pending_select
4458 unselectline
4459 normalline
4460 unset -nocomplain treediffs
4461 clear_display
4462 if {[info exists hlview] && $hlview == $n} {
4463 unset hlview
4464 set selectedhlview [mc "None"]
4466 unset -nocomplain commitinterest
4467 unset -nocomplain cached_commitrow
4468 unset -nocomplain ordertok
4470 set curview $n
4471 set selectedview $n
4472 .bar.view entryconf [mca "&Edit view..."] -state [expr {$n == 0? "disabled": "normal"}]
4473 .bar.view entryconf [mca "&Delete view"] -state [expr {$n == 0? "disabled": "normal"}]
4475 run refill_reflist
4476 if {![info exists viewcomplete($n)]} {
4477 getcommits $selid
4478 return
4481 set displayorder {}
4482 set parentlist {}
4483 set rowidlist {}
4484 set rowisopt {}
4485 set rowfinal {}
4486 set numcommits $commitidx($n)
4488 unset -nocomplain colormap
4489 unset -nocomplain rowtextx
4490 set nextcolor 0
4491 set canvxmax [$canv cget -width]
4492 set curview $n
4493 set row 0
4494 setcanvscroll
4495 set yf 0
4496 set row {}
4497 if {$selid ne {} && [commitinview $selid $n]} {
4498 set row [rowofcommit $selid]
4499 # try to get the selected row in the same position on the screen
4500 set ymax [lindex [$canv cget -scrollregion] 3]
4501 set ytop [expr {[yc $row] - $yscreen}]
4502 if {$ytop < 0} {
4503 set ytop 0
4505 set yf [expr {$ytop * 1.0 / $ymax}]
4507 allcanvs yview moveto $yf
4508 drawvisible
4509 if {$row ne {}} {
4510 selectline $row 0
4511 } elseif {!$viewcomplete($n)} {
4512 reset_pending_select $selid
4513 } else {
4514 reset_pending_select {}
4516 if {[commitinview $pending_select $curview]} {
4517 selectline [rowofcommit $pending_select] 1
4518 } else {
4519 set row [first_real_row]
4520 if {$row < $numcommits} {
4521 selectline $row 0
4525 if {!$viewcomplete($n)} {
4526 if {$numcommits == 0} {
4527 show_status [mc "Reading commits..."]
4529 } elseif {$numcommits == 0} {
4530 show_status [mc "No commits selected"]
4532 set_window_title
4535 # Stuff relating to the highlighting facility
4537 proc ishighlighted {id} {
4538 global vhighlights fhighlights nhighlights rhighlights
4540 if {[info exists nhighlights($id)] && $nhighlights($id) > 0} {
4541 return $nhighlights($id)
4543 if {[info exists vhighlights($id)] && $vhighlights($id) > 0} {
4544 return $vhighlights($id)
4546 if {[info exists fhighlights($id)] && $fhighlights($id) > 0} {
4547 return $fhighlights($id)
4549 if {[info exists rhighlights($id)] && $rhighlights($id) > 0} {
4550 return $rhighlights($id)
4552 return 0
4555 proc bolden {id font} {
4556 global canv linehtag currentid boldids need_redisplay markedid
4558 # need_redisplay = 1 means the display is stale and about to be redrawn
4559 if {$need_redisplay} return
4560 lappend boldids $id
4561 $canv itemconf $linehtag($id) -font $font
4562 if {[info exists currentid] && $id eq $currentid} {
4563 $canv delete secsel
4564 set t [eval $canv create rect [$canv bbox $linehtag($id)] \
4565 -outline {{}} -tags secsel \
4566 -fill [$canv cget -selectbackground]]
4567 $canv lower $t
4569 if {[info exists markedid] && $id eq $markedid} {
4570 make_idmark $id
4574 proc bolden_name {id font} {
4575 global canv2 linentag currentid boldnameids need_redisplay
4577 if {$need_redisplay} return
4578 lappend boldnameids $id
4579 $canv2 itemconf $linentag($id) -font $font
4580 if {[info exists currentid] && $id eq $currentid} {
4581 $canv2 delete secsel
4582 set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] \
4583 -outline {{}} -tags secsel \
4584 -fill [$canv2 cget -selectbackground]]
4585 $canv2 lower $t
4589 proc unbolden {} {
4590 global boldids
4592 set stillbold {}
4593 foreach id $boldids {
4594 if {![ishighlighted $id]} {
4595 bolden $id mainfont
4596 } else {
4597 lappend stillbold $id
4600 set boldids $stillbold
4603 proc addvhighlight {n} {
4604 global hlview viewcomplete curview vhl_done commitidx
4606 if {[info exists hlview]} {
4607 delvhighlight
4609 set hlview $n
4610 if {$n != $curview && ![info exists viewcomplete($n)]} {
4611 start_rev_list $n
4613 set vhl_done $commitidx($hlview)
4614 if {$vhl_done > 0} {
4615 drawvisible
4619 proc delvhighlight {} {
4620 global hlview vhighlights
4622 if {![info exists hlview]} return
4623 unset hlview
4624 unset -nocomplain vhighlights
4625 unbolden
4628 proc vhighlightmore {} {
4629 global hlview vhl_done commitidx vhighlights curview
4631 set max $commitidx($hlview)
4632 set vr [visiblerows]
4633 set r0 [lindex $vr 0]
4634 set r1 [lindex $vr 1]
4635 for {set i $vhl_done} {$i < $max} {incr i} {
4636 set id [commitonrow $i $hlview]
4637 if {[commitinview $id $curview]} {
4638 set row [rowofcommit $id]
4639 if {$r0 <= $row && $row <= $r1} {
4640 if {![highlighted $row]} {
4641 bolden $id mainfontbold
4643 set vhighlights($id) 1
4647 set vhl_done $max
4648 return 0
4651 proc askvhighlight {row id} {
4652 global hlview vhighlights iddrawn
4654 if {[commitinview $id $hlview]} {
4655 if {[info exists iddrawn($id)] && ![ishighlighted $id]} {
4656 bolden $id mainfontbold
4658 set vhighlights($id) 1
4659 } else {
4660 set vhighlights($id) 0
4664 proc hfiles_change {} {
4665 global highlight_files filehighlight fhighlights fh_serial
4666 global highlight_paths
4668 if {[info exists filehighlight]} {
4669 # delete previous highlights
4670 catch {close $filehighlight}
4671 unset filehighlight
4672 unset -nocomplain fhighlights
4673 unbolden
4674 unhighlight_filelist
4676 set highlight_paths {}
4677 after cancel do_file_hl $fh_serial
4678 incr fh_serial
4679 if {$highlight_files ne {}} {
4680 after 300 do_file_hl $fh_serial
4684 proc gdttype_change {name ix op} {
4685 global gdttype highlight_files findstring findpattern
4687 stopfinding
4688 if {$findstring ne {}} {
4689 if {$gdttype eq [mc "containing:"]} {
4690 if {$highlight_files ne {}} {
4691 set highlight_files {}
4692 hfiles_change
4694 findcom_change
4695 } else {
4696 if {$findpattern ne {}} {
4697 set findpattern {}
4698 findcom_change
4700 set highlight_files $findstring
4701 hfiles_change
4703 drawvisible
4705 # enable/disable findtype/findloc menus too
4708 proc find_change {name ix op} {
4709 global gdttype findstring highlight_files
4711 stopfinding
4712 if {$gdttype eq [mc "containing:"]} {
4713 findcom_change
4714 } else {
4715 if {$highlight_files ne $findstring} {
4716 set highlight_files $findstring
4717 hfiles_change
4720 drawvisible
4723 proc findcom_change args {
4724 global nhighlights boldnameids
4725 global findpattern findtype findstring gdttype
4727 stopfinding
4728 # delete previous highlights, if any
4729 foreach id $boldnameids {
4730 bolden_name $id mainfont
4732 set boldnameids {}
4733 unset -nocomplain nhighlights
4734 unbolden
4735 unmarkmatches
4736 if {$gdttype ne [mc "containing:"] || $findstring eq {}} {
4737 set findpattern {}
4738 } elseif {$findtype eq [mc "Regexp"]} {
4739 set findpattern $findstring
4740 } else {
4741 set e [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} \
4742 $findstring]
4743 set findpattern "*$e*"
4747 proc makepatterns {l} {
4748 set ret {}
4749 foreach e $l {
4750 set ee [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} $e]
4751 if {[string index $ee end] eq "/"} {
4752 lappend ret "$ee*"
4753 } else {
4754 lappend ret $ee
4755 lappend ret "$ee/*"
4758 return $ret
4761 proc do_file_hl {serial} {
4762 global highlight_files filehighlight highlight_paths gdttype fhl_list
4763 global cdup findtype
4765 if {$gdttype eq [mc "touching paths:"]} {
4766 # If "exact" match then convert backslashes to forward slashes.
4767 # Most useful to support Windows-flavoured file paths.
4768 if {$findtype eq [mc "Exact"]} {
4769 set highlight_files [string map {"\\" "/"} $highlight_files]
4771 if {[catch {set paths [shellsplit $highlight_files]}]} return
4772 set highlight_paths [makepatterns $paths]
4773 highlight_filelist
4774 set relative_paths {}
4775 foreach path $paths {
4776 lappend relative_paths [file join $cdup $path]
4778 set gdtargs [concat -- $relative_paths]
4779 } elseif {$gdttype eq [mc "adding/removing string:"]} {
4780 set gdtargs [list "-S$highlight_files"]
4781 } elseif {$gdttype eq [mc "changing lines matching:"]} {
4782 set gdtargs [list "-G$highlight_files"]
4783 } else {
4784 # must be "containing:", i.e. we're searching commit info
4785 return
4787 set cmd [concat | git diff-tree -r -s --stdin $gdtargs]
4788 set filehighlight [open $cmd r+]
4789 fconfigure $filehighlight -blocking 0
4790 filerun $filehighlight readfhighlight
4791 set fhl_list {}
4792 drawvisible
4793 flushhighlights
4796 proc flushhighlights {} {
4797 global filehighlight fhl_list
4799 if {[info exists filehighlight]} {
4800 lappend fhl_list {}
4801 puts $filehighlight ""
4802 flush $filehighlight
4806 proc askfilehighlight {row id} {
4807 global filehighlight fhighlights fhl_list
4809 lappend fhl_list $id
4810 set fhighlights($id) -1
4811 puts $filehighlight $id
4814 proc readfhighlight {} {
4815 global filehighlight fhighlights curview iddrawn
4816 global fhl_list find_dirn
4818 if {![info exists filehighlight]} {
4819 return 0
4821 set nr 0
4822 while {[incr nr] <= 100 && [gets $filehighlight line] >= 0} {
4823 set line [string trim $line]
4824 set i [lsearch -exact $fhl_list $line]
4825 if {$i < 0} continue
4826 for {set j 0} {$j < $i} {incr j} {
4827 set id [lindex $fhl_list $j]
4828 set fhighlights($id) 0
4830 set fhl_list [lrange $fhl_list [expr {$i+1}] end]
4831 if {$line eq {}} continue
4832 if {![commitinview $line $curview]} continue
4833 if {[info exists iddrawn($line)] && ![ishighlighted $line]} {
4834 bolden $line mainfontbold
4836 set fhighlights($line) 1
4838 if {[eof $filehighlight]} {
4839 # strange...
4840 puts "oops, git diff-tree died"
4841 catch {close $filehighlight}
4842 unset filehighlight
4843 return 0
4845 if {[info exists find_dirn]} {
4846 run findmore
4848 return 1
4851 proc doesmatch {f} {
4852 global findtype findpattern
4854 if {$findtype eq [mc "Regexp"]} {
4855 return [regexp $findpattern $f]
4856 } elseif {$findtype eq [mc "IgnCase"]} {
4857 return [string match -nocase $findpattern $f]
4858 } else {
4859 return [string match $findpattern $f]
4863 proc askfindhighlight {row id} {
4864 global nhighlights commitinfo iddrawn
4865 global findloc
4866 global markingmatches
4868 if {![info exists commitinfo($id)]} {
4869 getcommit $id
4871 set info $commitinfo($id)
4872 set isbold 0
4873 set fldtypes [list [mc Headline] [mc Author] "" [mc Committer] "" [mc Comments]]
4874 foreach f $info ty $fldtypes {
4875 if {$ty eq ""} continue
4876 if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
4877 [doesmatch $f]} {
4878 if {$ty eq [mc "Author"]} {
4879 set isbold 2
4880 break
4882 set isbold 1
4885 if {$isbold && [info exists iddrawn($id)]} {
4886 if {![ishighlighted $id]} {
4887 bolden $id mainfontbold
4888 if {$isbold > 1} {
4889 bolden_name $id mainfontbold
4892 if {$markingmatches} {
4893 markrowmatches $row $id
4896 set nhighlights($id) $isbold
4899 proc markrowmatches {row id} {
4900 global canv canv2 linehtag linentag commitinfo findloc
4902 set headline [lindex $commitinfo($id) 0]
4903 set author [lindex $commitinfo($id) 1]
4904 $canv delete match$row
4905 $canv2 delete match$row
4906 if {$findloc eq [mc "All fields"] || $findloc eq [mc "Headline"]} {
4907 set m [findmatches $headline]
4908 if {$m ne {}} {
4909 markmatches $canv $row $headline $linehtag($id) $m \
4910 [$canv itemcget $linehtag($id) -font] $row
4913 if {$findloc eq [mc "All fields"] || $findloc eq [mc "Author"]} {
4914 set m [findmatches $author]
4915 if {$m ne {}} {
4916 markmatches $canv2 $row $author $linentag($id) $m \
4917 [$canv2 itemcget $linentag($id) -font] $row
4922 proc vrel_change {name ix op} {
4923 global highlight_related
4925 rhighlight_none
4926 if {$highlight_related ne [mc "None"]} {
4927 run drawvisible
4931 # prepare for testing whether commits are descendents or ancestors of a
4932 proc rhighlight_sel {a} {
4933 global descendent desc_todo ancestor anc_todo
4934 global highlight_related
4936 unset -nocomplain descendent
4937 set desc_todo [list $a]
4938 unset -nocomplain ancestor
4939 set anc_todo [list $a]
4940 if {$highlight_related ne [mc "None"]} {
4941 rhighlight_none
4942 run drawvisible
4946 proc rhighlight_none {} {
4947 global rhighlights
4949 unset -nocomplain rhighlights
4950 unbolden
4953 proc is_descendent {a} {
4954 global curview children descendent desc_todo
4956 set v $curview
4957 set la [rowofcommit $a]
4958 set todo $desc_todo
4959 set leftover {}
4960 set done 0
4961 for {set i 0} {$i < [llength $todo]} {incr i} {
4962 set do [lindex $todo $i]
4963 if {[rowofcommit $do] < $la} {
4964 lappend leftover $do
4965 continue
4967 foreach nk $children($v,$do) {
4968 if {![info exists descendent($nk)]} {
4969 set descendent($nk) 1
4970 lappend todo $nk
4971 if {$nk eq $a} {
4972 set done 1
4976 if {$done} {
4977 set desc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4978 return
4981 set descendent($a) 0
4982 set desc_todo $leftover
4985 proc is_ancestor {a} {
4986 global curview parents ancestor anc_todo
4988 set v $curview
4989 set la [rowofcommit $a]
4990 set todo $anc_todo
4991 set leftover {}
4992 set done 0
4993 for {set i 0} {$i < [llength $todo]} {incr i} {
4994 set do [lindex $todo $i]
4995 if {![commitinview $do $v] || [rowofcommit $do] > $la} {
4996 lappend leftover $do
4997 continue
4999 foreach np $parents($v,$do) {
5000 if {![info exists ancestor($np)]} {
5001 set ancestor($np) 1
5002 lappend todo $np
5003 if {$np eq $a} {
5004 set done 1
5008 if {$done} {
5009 set anc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
5010 return
5013 set ancestor($a) 0
5014 set anc_todo $leftover
5017 proc askrelhighlight {row id} {
5018 global descendent highlight_related iddrawn rhighlights
5019 global selectedline ancestor
5021 if {$selectedline eq {}} return
5022 set isbold 0
5023 if {$highlight_related eq [mc "Descendant"] ||
5024 $highlight_related eq [mc "Not descendant"]} {
5025 if {![info exists descendent($id)]} {
5026 is_descendent $id
5028 if {$descendent($id) == ($highlight_related eq [mc "Descendant"])} {
5029 set isbold 1
5031 } elseif {$highlight_related eq [mc "Ancestor"] ||
5032 $highlight_related eq [mc "Not ancestor"]} {
5033 if {![info exists ancestor($id)]} {
5034 is_ancestor $id
5036 if {$ancestor($id) == ($highlight_related eq [mc "Ancestor"])} {
5037 set isbold 1
5040 if {[info exists iddrawn($id)]} {
5041 if {$isbold && ![ishighlighted $id]} {
5042 bolden $id mainfontbold
5045 set rhighlights($id) $isbold
5048 # Graph layout functions
5050 proc shortids {ids} {
5051 set res {}
5052 foreach id $ids {
5053 if {[llength $id] > 1} {
5054 lappend res [shortids $id]
5055 } elseif {[regexp {^[0-9a-f]{40}$} $id]} {
5056 lappend res [string range $id 0 7]
5057 } else {
5058 lappend res $id
5061 return $res
5064 proc ntimes {n o} {
5065 set ret {}
5066 set o [list $o]
5067 for {set mask 1} {$mask <= $n} {incr mask $mask} {
5068 if {($n & $mask) != 0} {
5069 set ret [concat $ret $o]
5071 set o [concat $o $o]
5073 return $ret
5076 proc ordertoken {id} {
5077 global ordertok curview varcid varcstart varctok curview parents children
5078 global nullid nullid2
5080 if {[info exists ordertok($id)]} {
5081 return $ordertok($id)
5083 set origid $id
5084 set todo {}
5085 while {1} {
5086 if {[info exists varcid($curview,$id)]} {
5087 set a $varcid($curview,$id)
5088 set p [lindex $varcstart($curview) $a]
5089 } else {
5090 set p [lindex $children($curview,$id) 0]
5092 if {[info exists ordertok($p)]} {
5093 set tok $ordertok($p)
5094 break
5096 set id [first_real_child $curview,$p]
5097 if {$id eq {}} {
5098 # it's a root
5099 set tok [lindex $varctok($curview) $varcid($curview,$p)]
5100 break
5102 if {[llength $parents($curview,$id)] == 1} {
5103 lappend todo [list $p {}]
5104 } else {
5105 set j [lsearch -exact $parents($curview,$id) $p]
5106 if {$j < 0} {
5107 puts "oops didn't find [shortids $p] in parents of [shortids $id]"
5109 lappend todo [list $p [strrep $j]]
5112 for {set i [llength $todo]} {[incr i -1] >= 0} {} {
5113 set p [lindex $todo $i 0]
5114 append tok [lindex $todo $i 1]
5115 set ordertok($p) $tok
5117 set ordertok($origid) $tok
5118 return $tok
5121 # Work out where id should go in idlist so that order-token
5122 # values increase from left to right
5123 proc idcol {idlist id {i 0}} {
5124 set t [ordertoken $id]
5125 if {$i < 0} {
5126 set i 0
5128 if {$i >= [llength $idlist] || $t < [ordertoken [lindex $idlist $i]]} {
5129 if {$i > [llength $idlist]} {
5130 set i [llength $idlist]
5132 while {[incr i -1] >= 0 && $t < [ordertoken [lindex $idlist $i]]} {}
5133 incr i
5134 } else {
5135 if {$t > [ordertoken [lindex $idlist $i]]} {
5136 while {[incr i] < [llength $idlist] &&
5137 $t >= [ordertoken [lindex $idlist $i]]} {}
5140 return $i
5143 proc initlayout {} {
5144 global rowidlist rowisopt rowfinal displayorder parentlist
5145 global numcommits canvxmax canv
5146 global nextcolor
5147 global colormap rowtextx
5149 set numcommits 0
5150 set displayorder {}
5151 set parentlist {}
5152 set nextcolor 0
5153 set rowidlist {}
5154 set rowisopt {}
5155 set rowfinal {}
5156 set canvxmax [$canv cget -width]
5157 unset -nocomplain colormap
5158 unset -nocomplain rowtextx
5159 setcanvscroll
5162 proc setcanvscroll {} {
5163 global canv canv2 canv3 numcommits linespc canvxmax canvy0
5164 global lastscrollset lastscrollrows
5166 set ymax [expr {$canvy0 + ($numcommits - 0.5) * $linespc + 2}]
5167 $canv conf -scrollregion [list 0 0 $canvxmax $ymax]
5168 $canv2 conf -scrollregion [list 0 0 0 $ymax]
5169 $canv3 conf -scrollregion [list 0 0 0 $ymax]
5170 set lastscrollset [clock clicks -milliseconds]
5171 set lastscrollrows $numcommits
5174 proc visiblerows {} {
5175 global canv numcommits linespc
5177 set ymax [lindex [$canv cget -scrollregion] 3]
5178 if {$ymax eq {} || $ymax == 0} return
5179 set f [$canv yview]
5180 set y0 [expr {int([lindex $f 0] * $ymax)}]
5181 set r0 [expr {int(($y0 - 3) / $linespc) - 1}]
5182 if {$r0 < 0} {
5183 set r0 0
5185 set y1 [expr {int([lindex $f 1] * $ymax)}]
5186 set r1 [expr {int(($y1 - 3) / $linespc) + 1}]
5187 if {$r1 >= $numcommits} {
5188 set r1 [expr {$numcommits - 1}]
5190 return [list $r0 $r1]
5193 proc layoutmore {} {
5194 global commitidx viewcomplete curview
5195 global numcommits pending_select curview
5196 global lastscrollset lastscrollrows
5198 if {$lastscrollrows < 100 || $viewcomplete($curview) ||
5199 [clock clicks -milliseconds] - $lastscrollset > 500} {
5200 setcanvscroll
5202 if {[info exists pending_select] &&
5203 [commitinview $pending_select $curview]} {
5204 update
5205 selectline [rowofcommit $pending_select] 1
5207 drawvisible
5210 # With path limiting, we mightn't get the actual HEAD commit,
5211 # so ask git rev-list what is the first ancestor of HEAD that
5212 # touches a file in the path limit.
5213 proc get_viewmainhead {view} {
5214 global viewmainheadid vfilelimit viewinstances mainheadid
5216 catch {
5217 set rfd [open [concat | git rev-list -1 $mainheadid \
5218 -- $vfilelimit($view)] r]
5219 set j [reg_instance $rfd]
5220 lappend viewinstances($view) $j
5221 fconfigure $rfd -blocking 0
5222 filerun $rfd [list getviewhead $rfd $j $view]
5223 set viewmainheadid($curview) {}
5227 # git rev-list should give us just 1 line to use as viewmainheadid($view)
5228 proc getviewhead {fd inst view} {
5229 global viewmainheadid commfd curview viewinstances showlocalchanges
5231 set id {}
5232 if {[gets $fd line] < 0} {
5233 if {![eof $fd]} {
5234 return 1
5236 } elseif {[string length $line] == 40 && [string is xdigit $line]} {
5237 set id $line
5239 set viewmainheadid($view) $id
5240 close $fd
5241 unset commfd($inst)
5242 set i [lsearch -exact $viewinstances($view) $inst]
5243 if {$i >= 0} {
5244 set viewinstances($view) [lreplace $viewinstances($view) $i $i]
5246 if {$showlocalchanges && $id ne {} && $view == $curview} {
5247 doshowlocalchanges
5249 return 0
5252 proc doshowlocalchanges {} {
5253 global curview viewmainheadid
5255 if {$viewmainheadid($curview) eq {}} return
5256 if {[commitinview $viewmainheadid($curview) $curview]} {
5257 dodiffindex
5258 } else {
5259 interestedin $viewmainheadid($curview) dodiffindex
5263 proc dohidelocalchanges {} {
5264 global nullid nullid2 lserial curview
5266 if {[commitinview $nullid $curview]} {
5267 removefakerow $nullid
5269 if {[commitinview $nullid2 $curview]} {
5270 removefakerow $nullid2
5272 incr lserial
5275 # spawn off a process to do git diff-index --cached HEAD
5276 proc dodiffindex {} {
5277 global lserial showlocalchanges vfilelimit curview
5278 global hasworktree git_version
5280 if {!$showlocalchanges || !$hasworktree} return
5281 incr lserial
5282 if {[package vcompare $git_version "1.7.2"] >= 0} {
5283 set cmd "|git diff-index --cached --ignore-submodules=dirty HEAD"
5284 } else {
5285 set cmd "|git diff-index --cached HEAD"
5287 if {$vfilelimit($curview) ne {}} {
5288 set cmd [concat $cmd -- $vfilelimit($curview)]
5290 set fd [open $cmd r]
5291 fconfigure $fd -blocking 0
5292 set i [reg_instance $fd]
5293 filerun $fd [list readdiffindex $fd $lserial $i]
5296 proc readdiffindex {fd serial inst} {
5297 global viewmainheadid nullid nullid2 curview commitinfo commitdata lserial
5298 global vfilelimit
5300 set isdiff 1
5301 if {[gets $fd line] < 0} {
5302 if {![eof $fd]} {
5303 return 1
5305 set isdiff 0
5307 # we only need to see one line and we don't really care what it says...
5308 stop_instance $inst
5310 if {$serial != $lserial} {
5311 return 0
5314 # now see if there are any local changes not checked in to the index
5315 set cmd "|git diff-files"
5316 if {$vfilelimit($curview) ne {}} {
5317 set cmd [concat $cmd -- $vfilelimit($curview)]
5319 set fd [open $cmd r]
5320 fconfigure $fd -blocking 0
5321 set i [reg_instance $fd]
5322 filerun $fd [list readdifffiles $fd $serial $i]
5324 if {$isdiff && ![commitinview $nullid2 $curview]} {
5325 # add the line for the changes in the index to the graph
5326 set hl [mc "Local changes checked in to index but not committed"]
5327 set commitinfo($nullid2) [list $hl {} {} {} {} " $hl\n"]
5328 set commitdata($nullid2) "\n $hl\n"
5329 if {[commitinview $nullid $curview]} {
5330 removefakerow $nullid
5332 insertfakerow $nullid2 $viewmainheadid($curview)
5333 } elseif {!$isdiff && [commitinview $nullid2 $curview]} {
5334 if {[commitinview $nullid $curview]} {
5335 removefakerow $nullid
5337 removefakerow $nullid2
5339 return 0
5342 proc readdifffiles {fd serial inst} {
5343 global viewmainheadid nullid nullid2 curview
5344 global commitinfo commitdata lserial
5346 set isdiff 1
5347 if {[gets $fd line] < 0} {
5348 if {![eof $fd]} {
5349 return 1
5351 set isdiff 0
5353 # we only need to see one line and we don't really care what it says...
5354 stop_instance $inst
5356 if {$serial != $lserial} {
5357 return 0
5360 if {$isdiff && ![commitinview $nullid $curview]} {
5361 # add the line for the local diff to the graph
5362 set hl [mc "Local uncommitted changes, not checked in to index"]
5363 set commitinfo($nullid) [list $hl {} {} {} {} " $hl\n"]
5364 set commitdata($nullid) "\n $hl\n"
5365 if {[commitinview $nullid2 $curview]} {
5366 set p $nullid2
5367 } else {
5368 set p $viewmainheadid($curview)
5370 insertfakerow $nullid $p
5371 } elseif {!$isdiff && [commitinview $nullid $curview]} {
5372 removefakerow $nullid
5374 return 0
5377 proc nextuse {id row} {
5378 global curview children
5380 if {[info exists children($curview,$id)]} {
5381 foreach kid $children($curview,$id) {
5382 if {![commitinview $kid $curview]} {
5383 return -1
5385 if {[rowofcommit $kid] > $row} {
5386 return [rowofcommit $kid]
5390 if {[commitinview $id $curview]} {
5391 return [rowofcommit $id]
5393 return -1
5396 proc prevuse {id row} {
5397 global curview children
5399 set ret -1
5400 if {[info exists children($curview,$id)]} {
5401 foreach kid $children($curview,$id) {
5402 if {![commitinview $kid $curview]} break
5403 if {[rowofcommit $kid] < $row} {
5404 set ret [rowofcommit $kid]
5408 return $ret
5411 proc make_idlist {row} {
5412 global displayorder parentlist uparrowlen downarrowlen mingaplen
5413 global commitidx curview children
5415 set r [expr {$row - $mingaplen - $downarrowlen - 1}]
5416 if {$r < 0} {
5417 set r 0
5419 set ra [expr {$row - $downarrowlen}]
5420 if {$ra < 0} {
5421 set ra 0
5423 set rb [expr {$row + $uparrowlen}]
5424 if {$rb > $commitidx($curview)} {
5425 set rb $commitidx($curview)
5427 make_disporder $r [expr {$rb + 1}]
5428 set ids {}
5429 for {} {$r < $ra} {incr r} {
5430 set nextid [lindex $displayorder [expr {$r + 1}]]
5431 foreach p [lindex $parentlist $r] {
5432 if {$p eq $nextid} continue
5433 set rn [nextuse $p $r]
5434 if {$rn >= $row &&
5435 $rn <= $r + $downarrowlen + $mingaplen + $uparrowlen} {
5436 lappend ids [list [ordertoken $p] $p]
5440 for {} {$r < $row} {incr r} {
5441 set nextid [lindex $displayorder [expr {$r + 1}]]
5442 foreach p [lindex $parentlist $r] {
5443 if {$p eq $nextid} continue
5444 set rn [nextuse $p $r]
5445 if {$rn < 0 || $rn >= $row} {
5446 lappend ids [list [ordertoken $p] $p]
5450 set id [lindex $displayorder $row]
5451 lappend ids [list [ordertoken $id] $id]
5452 while {$r < $rb} {
5453 foreach p [lindex $parentlist $r] {
5454 set firstkid [lindex $children($curview,$p) 0]
5455 if {[rowofcommit $firstkid] < $row} {
5456 lappend ids [list [ordertoken $p] $p]
5459 incr r
5460 set id [lindex $displayorder $r]
5461 if {$id ne {}} {
5462 set firstkid [lindex $children($curview,$id) 0]
5463 if {$firstkid ne {} && [rowofcommit $firstkid] < $row} {
5464 lappend ids [list [ordertoken $id] $id]
5468 set idlist {}
5469 foreach idx [lsort -unique $ids] {
5470 lappend idlist [lindex $idx 1]
5472 return $idlist
5475 proc rowsequal {a b} {
5476 while {[set i [lsearch -exact $a {}]] >= 0} {
5477 set a [lreplace $a $i $i]
5479 while {[set i [lsearch -exact $b {}]] >= 0} {
5480 set b [lreplace $b $i $i]
5482 return [expr {$a eq $b}]
5485 proc makeupline {id row rend col} {
5486 global rowidlist uparrowlen downarrowlen mingaplen
5488 for {set r $rend} {1} {set r $rstart} {
5489 set rstart [prevuse $id $r]
5490 if {$rstart < 0} return
5491 if {$rstart < $row} break
5493 if {$rstart + $uparrowlen + $mingaplen + $downarrowlen < $rend} {
5494 set rstart [expr {$rend - $uparrowlen - 1}]
5496 for {set r $rstart} {[incr r] <= $row} {} {
5497 set idlist [lindex $rowidlist $r]
5498 if {$idlist ne {} && [lsearch -exact $idlist $id] < 0} {
5499 set col [idcol $idlist $id $col]
5500 lset rowidlist $r [linsert $idlist $col $id]
5501 changedrow $r
5506 proc layoutrows {row endrow} {
5507 global rowidlist rowisopt rowfinal displayorder
5508 global uparrowlen downarrowlen maxwidth mingaplen
5509 global children parentlist
5510 global commitidx viewcomplete curview
5512 make_disporder [expr {$row - 1}] [expr {$endrow + $uparrowlen}]
5513 set idlist {}
5514 if {$row > 0} {
5515 set rm1 [expr {$row - 1}]
5516 foreach id [lindex $rowidlist $rm1] {
5517 if {$id ne {}} {
5518 lappend idlist $id
5521 set final [lindex $rowfinal $rm1]
5523 for {} {$row < $endrow} {incr row} {
5524 set rm1 [expr {$row - 1}]
5525 if {$rm1 < 0 || $idlist eq {}} {
5526 set idlist [make_idlist $row]
5527 set final 1
5528 } else {
5529 set id [lindex $displayorder $rm1]
5530 set col [lsearch -exact $idlist $id]
5531 set idlist [lreplace $idlist $col $col]
5532 foreach p [lindex $parentlist $rm1] {
5533 if {[lsearch -exact $idlist $p] < 0} {
5534 set col [idcol $idlist $p $col]
5535 set idlist [linsert $idlist $col $p]
5536 # if not the first child, we have to insert a line going up
5537 if {$id ne [lindex $children($curview,$p) 0]} {
5538 makeupline $p $rm1 $row $col
5542 set id [lindex $displayorder $row]
5543 if {$row > $downarrowlen} {
5544 set termrow [expr {$row - $downarrowlen - 1}]
5545 foreach p [lindex $parentlist $termrow] {
5546 set i [lsearch -exact $idlist $p]
5547 if {$i < 0} continue
5548 set nr [nextuse $p $termrow]
5549 if {$nr < 0 || $nr >= $row + $mingaplen + $uparrowlen} {
5550 set idlist [lreplace $idlist $i $i]
5554 set col [lsearch -exact $idlist $id]
5555 if {$col < 0} {
5556 set col [idcol $idlist $id]
5557 set idlist [linsert $idlist $col $id]
5558 if {$children($curview,$id) ne {}} {
5559 makeupline $id $rm1 $row $col
5562 set r [expr {$row + $uparrowlen - 1}]
5563 if {$r < $commitidx($curview)} {
5564 set x $col
5565 foreach p [lindex $parentlist $r] {
5566 if {[lsearch -exact $idlist $p] >= 0} continue
5567 set fk [lindex $children($curview,$p) 0]
5568 if {[rowofcommit $fk] < $row} {
5569 set x [idcol $idlist $p $x]
5570 set idlist [linsert $idlist $x $p]
5573 if {[incr r] < $commitidx($curview)} {
5574 set p [lindex $displayorder $r]
5575 if {[lsearch -exact $idlist $p] < 0} {
5576 set fk [lindex $children($curview,$p) 0]
5577 if {$fk ne {} && [rowofcommit $fk] < $row} {
5578 set x [idcol $idlist $p $x]
5579 set idlist [linsert $idlist $x $p]
5585 if {$final && !$viewcomplete($curview) &&
5586 $row + $uparrowlen + $mingaplen + $downarrowlen
5587 >= $commitidx($curview)} {
5588 set final 0
5590 set l [llength $rowidlist]
5591 if {$row == $l} {
5592 lappend rowidlist $idlist
5593 lappend rowisopt 0
5594 lappend rowfinal $final
5595 } elseif {$row < $l} {
5596 if {![rowsequal $idlist [lindex $rowidlist $row]]} {
5597 lset rowidlist $row $idlist
5598 changedrow $row
5600 lset rowfinal $row $final
5601 } else {
5602 set pad [ntimes [expr {$row - $l}] {}]
5603 set rowidlist [concat $rowidlist $pad]
5604 lappend rowidlist $idlist
5605 set rowfinal [concat $rowfinal $pad]
5606 lappend rowfinal $final
5607 set rowisopt [concat $rowisopt [ntimes [expr {$row - $l + 1}] 0]]
5610 return $row
5613 proc changedrow {row} {
5614 global displayorder iddrawn rowisopt need_redisplay
5616 set l [llength $rowisopt]
5617 if {$row < $l} {
5618 lset rowisopt $row 0
5619 if {$row + 1 < $l} {
5620 lset rowisopt [expr {$row + 1}] 0
5621 if {$row + 2 < $l} {
5622 lset rowisopt [expr {$row + 2}] 0
5626 set id [lindex $displayorder $row]
5627 if {[info exists iddrawn($id)]} {
5628 set need_redisplay 1
5632 proc insert_pad {row col npad} {
5633 global rowidlist
5635 set pad [ntimes $npad {}]
5636 set idlist [lindex $rowidlist $row]
5637 set bef [lrange $idlist 0 [expr {$col - 1}]]
5638 set aft [lrange $idlist $col end]
5639 set i [lsearch -exact $aft {}]
5640 if {$i > 0} {
5641 set aft [lreplace $aft $i $i]
5643 lset rowidlist $row [concat $bef $pad $aft]
5644 changedrow $row
5647 proc optimize_rows {row col endrow} {
5648 global rowidlist rowisopt displayorder curview children
5650 if {$row < 1} {
5651 set row 1
5653 for {} {$row < $endrow} {incr row; set col 0} {
5654 if {[lindex $rowisopt $row]} continue
5655 set haspad 0
5656 set y0 [expr {$row - 1}]
5657 set ym [expr {$row - 2}]
5658 set idlist [lindex $rowidlist $row]
5659 set previdlist [lindex $rowidlist $y0]
5660 if {$idlist eq {} || $previdlist eq {}} continue
5661 if {$ym >= 0} {
5662 set pprevidlist [lindex $rowidlist $ym]
5663 if {$pprevidlist eq {}} continue
5664 } else {
5665 set pprevidlist {}
5667 set x0 -1
5668 set xm -1
5669 for {} {$col < [llength $idlist]} {incr col} {
5670 set id [lindex $idlist $col]
5671 if {[lindex $previdlist $col] eq $id} continue
5672 if {$id eq {}} {
5673 set haspad 1
5674 continue
5676 set x0 [lsearch -exact $previdlist $id]
5677 if {$x0 < 0} continue
5678 set z [expr {$x0 - $col}]
5679 set isarrow 0
5680 set z0 {}
5681 if {$ym >= 0} {
5682 set xm [lsearch -exact $pprevidlist $id]
5683 if {$xm >= 0} {
5684 set z0 [expr {$xm - $x0}]
5687 if {$z0 eq {}} {
5688 # if row y0 is the first child of $id then it's not an arrow
5689 if {[lindex $children($curview,$id) 0] ne
5690 [lindex $displayorder $y0]} {
5691 set isarrow 1
5694 if {!$isarrow && $id ne [lindex $displayorder $row] &&
5695 [lsearch -exact [lindex $rowidlist [expr {$row+1}]] $id] < 0} {
5696 set isarrow 1
5698 # Looking at lines from this row to the previous row,
5699 # make them go straight up if they end in an arrow on
5700 # the previous row; otherwise make them go straight up
5701 # or at 45 degrees.
5702 if {$z < -1 || ($z < 0 && $isarrow)} {
5703 # Line currently goes left too much;
5704 # insert pads in the previous row, then optimize it
5705 set npad [expr {-1 - $z + $isarrow}]
5706 insert_pad $y0 $x0 $npad
5707 if {$y0 > 0} {
5708 optimize_rows $y0 $x0 $row
5710 set previdlist [lindex $rowidlist $y0]
5711 set x0 [lsearch -exact $previdlist $id]
5712 set z [expr {$x0 - $col}]
5713 if {$z0 ne {}} {
5714 set pprevidlist [lindex $rowidlist $ym]
5715 set xm [lsearch -exact $pprevidlist $id]
5716 set z0 [expr {$xm - $x0}]
5718 } elseif {$z > 1 || ($z > 0 && $isarrow)} {
5719 # Line currently goes right too much;
5720 # insert pads in this line
5721 set npad [expr {$z - 1 + $isarrow}]
5722 insert_pad $row $col $npad
5723 set idlist [lindex $rowidlist $row]
5724 incr col $npad
5725 set z [expr {$x0 - $col}]
5726 set haspad 1
5728 if {$z0 eq {} && !$isarrow && $ym >= 0} {
5729 # this line links to its first child on row $row-2
5730 set id [lindex $displayorder $ym]
5731 set xc [lsearch -exact $pprevidlist $id]
5732 if {$xc >= 0} {
5733 set z0 [expr {$xc - $x0}]
5736 # avoid lines jigging left then immediately right
5737 if {$z0 ne {} && $z < 0 && $z0 > 0} {
5738 insert_pad $y0 $x0 1
5739 incr x0
5740 optimize_rows $y0 $x0 $row
5741 set previdlist [lindex $rowidlist $y0]
5744 if {!$haspad} {
5745 # Find the first column that doesn't have a line going right
5746 for {set col [llength $idlist]} {[incr col -1] >= 0} {} {
5747 set id [lindex $idlist $col]
5748 if {$id eq {}} break
5749 set x0 [lsearch -exact $previdlist $id]
5750 if {$x0 < 0} {
5751 # check if this is the link to the first child
5752 set kid [lindex $displayorder $y0]
5753 if {[lindex $children($curview,$id) 0] eq $kid} {
5754 # it is, work out offset to child
5755 set x0 [lsearch -exact $previdlist $kid]
5758 if {$x0 <= $col} break
5760 # Insert a pad at that column as long as it has a line and
5761 # isn't the last column
5762 if {$x0 >= 0 && [incr col] < [llength $idlist]} {
5763 set idlist [linsert $idlist $col {}]
5764 lset rowidlist $row $idlist
5765 changedrow $row
5771 proc xc {row col} {
5772 global canvx0 linespc
5773 return [expr {$canvx0 + $col * $linespc}]
5776 proc yc {row} {
5777 global canvy0 linespc
5778 return [expr {$canvy0 + $row * $linespc}]
5781 proc linewidth {id} {
5782 global thickerline lthickness
5784 set wid $lthickness
5785 if {[info exists thickerline] && $id eq $thickerline} {
5786 set wid [expr {2 * $lthickness}]
5788 return $wid
5791 proc rowranges {id} {
5792 global curview children uparrowlen downarrowlen
5793 global rowidlist
5795 set kids $children($curview,$id)
5796 if {$kids eq {}} {
5797 return {}
5799 set ret {}
5800 lappend kids $id
5801 foreach child $kids {
5802 if {![commitinview $child $curview]} break
5803 set row [rowofcommit $child]
5804 if {![info exists prev]} {
5805 lappend ret [expr {$row + 1}]
5806 } else {
5807 if {$row <= $prevrow} {
5808 puts "oops children of [shortids $id] out of order [shortids $child] $row <= [shortids $prev] $prevrow"
5810 # see if the line extends the whole way from prevrow to row
5811 if {$row > $prevrow + $uparrowlen + $downarrowlen &&
5812 [lsearch -exact [lindex $rowidlist \
5813 [expr {int(($row + $prevrow) / 2)}]] $id] < 0} {
5814 # it doesn't, see where it ends
5815 set r [expr {$prevrow + $downarrowlen}]
5816 if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5817 while {[incr r -1] > $prevrow &&
5818 [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5819 } else {
5820 while {[incr r] <= $row &&
5821 [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5822 incr r -1
5824 lappend ret $r
5825 # see where it starts up again
5826 set r [expr {$row - $uparrowlen}]
5827 if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5828 while {[incr r] < $row &&
5829 [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5830 } else {
5831 while {[incr r -1] >= $prevrow &&
5832 [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5833 incr r
5835 lappend ret $r
5838 if {$child eq $id} {
5839 lappend ret $row
5841 set prev $child
5842 set prevrow $row
5844 return $ret
5847 proc drawlineseg {id row endrow arrowlow} {
5848 global rowidlist displayorder iddrawn linesegs
5849 global canv colormap linespc curview maxlinelen parentlist
5851 set cols [list [lsearch -exact [lindex $rowidlist $row] $id]]
5852 set le [expr {$row + 1}]
5853 set arrowhigh 1
5854 while {1} {
5855 set c [lsearch -exact [lindex $rowidlist $le] $id]
5856 if {$c < 0} {
5857 incr le -1
5858 break
5860 lappend cols $c
5861 set x [lindex $displayorder $le]
5862 if {$x eq $id} {
5863 set arrowhigh 0
5864 break
5866 if {[info exists iddrawn($x)] || $le == $endrow} {
5867 set c [lsearch -exact [lindex $rowidlist [expr {$le+1}]] $id]
5868 if {$c >= 0} {
5869 lappend cols $c
5870 set arrowhigh 0
5872 break
5874 incr le
5876 if {$le <= $row} {
5877 return $row
5880 set lines {}
5881 set i 0
5882 set joinhigh 0
5883 if {[info exists linesegs($id)]} {
5884 set lines $linesegs($id)
5885 foreach li $lines {
5886 set r0 [lindex $li 0]
5887 if {$r0 > $row} {
5888 if {$r0 == $le && [lindex $li 1] - $row <= $maxlinelen} {
5889 set joinhigh 1
5891 break
5893 incr i
5896 set joinlow 0
5897 if {$i > 0} {
5898 set li [lindex $lines [expr {$i-1}]]
5899 set r1 [lindex $li 1]
5900 if {$r1 == $row && $le - [lindex $li 0] <= $maxlinelen} {
5901 set joinlow 1
5905 set x [lindex $cols [expr {$le - $row}]]
5906 set xp [lindex $cols [expr {$le - 1 - $row}]]
5907 set dir [expr {$xp - $x}]
5908 if {$joinhigh} {
5909 set ith [lindex $lines $i 2]
5910 set coords [$canv coords $ith]
5911 set ah [$canv itemcget $ith -arrow]
5912 set arrowhigh [expr {$ah eq "first" || $ah eq "both"}]
5913 set x2 [lindex $cols [expr {$le + 1 - $row}]]
5914 if {$x2 ne {} && $x - $x2 == $dir} {
5915 set coords [lrange $coords 0 end-2]
5917 } else {
5918 set coords [list [xc $le $x] [yc $le]]
5920 if {$joinlow} {
5921 set itl [lindex $lines [expr {$i-1}] 2]
5922 set al [$canv itemcget $itl -arrow]
5923 set arrowlow [expr {$al eq "last" || $al eq "both"}]
5924 } elseif {$arrowlow} {
5925 if {[lsearch -exact [lindex $rowidlist [expr {$row-1}]] $id] >= 0 ||
5926 [lsearch -exact [lindex $parentlist [expr {$row-1}]] $id] >= 0} {
5927 set arrowlow 0
5930 set arrow [lindex {none first last both} [expr {$arrowhigh + 2*$arrowlow}]]
5931 for {set y $le} {[incr y -1] > $row} {} {
5932 set x $xp
5933 set xp [lindex $cols [expr {$y - 1 - $row}]]
5934 set ndir [expr {$xp - $x}]
5935 if {$dir != $ndir || $xp < 0} {
5936 lappend coords [xc $y $x] [yc $y]
5938 set dir $ndir
5940 if {!$joinlow} {
5941 if {$xp < 0} {
5942 # join parent line to first child
5943 set ch [lindex $displayorder $row]
5944 set xc [lsearch -exact [lindex $rowidlist $row] $ch]
5945 if {$xc < 0} {
5946 puts "oops: drawlineseg: child $ch not on row $row"
5947 } elseif {$xc != $x} {
5948 if {($arrowhigh && $le == $row + 1) || $dir == 0} {
5949 set d [expr {int(0.5 * $linespc)}]
5950 set x1 [xc $row $x]
5951 if {$xc < $x} {
5952 set x2 [expr {$x1 - $d}]
5953 } else {
5954 set x2 [expr {$x1 + $d}]
5956 set y2 [yc $row]
5957 set y1 [expr {$y2 + $d}]
5958 lappend coords $x1 $y1 $x2 $y2
5959 } elseif {$xc < $x - 1} {
5960 lappend coords [xc $row [expr {$x-1}]] [yc $row]
5961 } elseif {$xc > $x + 1} {
5962 lappend coords [xc $row [expr {$x+1}]] [yc $row]
5964 set x $xc
5966 lappend coords [xc $row $x] [yc $row]
5967 } else {
5968 set xn [xc $row $xp]
5969 set yn [yc $row]
5970 lappend coords $xn $yn
5972 if {!$joinhigh} {
5973 assigncolor $id
5974 set t [$canv create line $coords -width [linewidth $id] \
5975 -fill $colormap($id) -tags lines.$id -arrow $arrow]
5976 $canv lower $t
5977 bindline $t $id
5978 set lines [linsert $lines $i [list $row $le $t]]
5979 } else {
5980 $canv coords $ith $coords
5981 if {$arrow ne $ah} {
5982 $canv itemconf $ith -arrow $arrow
5984 lset lines $i 0 $row
5986 } else {
5987 set xo [lsearch -exact [lindex $rowidlist [expr {$row - 1}]] $id]
5988 set ndir [expr {$xo - $xp}]
5989 set clow [$canv coords $itl]
5990 if {$dir == $ndir} {
5991 set clow [lrange $clow 2 end]
5993 set coords [concat $coords $clow]
5994 if {!$joinhigh} {
5995 lset lines [expr {$i-1}] 1 $le
5996 } else {
5997 # coalesce two pieces
5998 $canv delete $ith
5999 set b [lindex $lines [expr {$i-1}] 0]
6000 set e [lindex $lines $i 1]
6001 set lines [lreplace $lines [expr {$i-1}] $i [list $b $e $itl]]
6003 $canv coords $itl $coords
6004 if {$arrow ne $al} {
6005 $canv itemconf $itl -arrow $arrow
6009 set linesegs($id) $lines
6010 return $le
6013 proc drawparentlinks {id row} {
6014 global rowidlist canv colormap curview parentlist
6015 global idpos linespc
6017 set rowids [lindex $rowidlist $row]
6018 set col [lsearch -exact $rowids $id]
6019 if {$col < 0} return
6020 set olds [lindex $parentlist $row]
6021 set row2 [expr {$row + 1}]
6022 set x [xc $row $col]
6023 set y [yc $row]
6024 set y2 [yc $row2]
6025 set d [expr {int(0.5 * $linespc)}]
6026 set ymid [expr {$y + $d}]
6027 set ids [lindex $rowidlist $row2]
6028 # rmx = right-most X coord used
6029 set rmx 0
6030 foreach p $olds {
6031 set i [lsearch -exact $ids $p]
6032 if {$i < 0} {
6033 puts "oops, parent $p of $id not in list"
6034 continue
6036 set x2 [xc $row2 $i]
6037 if {$x2 > $rmx} {
6038 set rmx $x2
6040 set j [lsearch -exact $rowids $p]
6041 if {$j < 0} {
6042 # drawlineseg will do this one for us
6043 continue
6045 assigncolor $p
6046 # should handle duplicated parents here...
6047 set coords [list $x $y]
6048 if {$i != $col} {
6049 # if attaching to a vertical segment, draw a smaller
6050 # slant for visual distinctness
6051 if {$i == $j} {
6052 if {$i < $col} {
6053 lappend coords [expr {$x2 + $d}] $y $x2 $ymid
6054 } else {
6055 lappend coords [expr {$x2 - $d}] $y $x2 $ymid
6057 } elseif {$i < $col && $i < $j} {
6058 # segment slants towards us already
6059 lappend coords [xc $row $j] $y
6060 } else {
6061 if {$i < $col - 1} {
6062 lappend coords [expr {$x2 + $linespc}] $y
6063 } elseif {$i > $col + 1} {
6064 lappend coords [expr {$x2 - $linespc}] $y
6066 lappend coords $x2 $y2
6068 } else {
6069 lappend coords $x2 $y2
6071 set t [$canv create line $coords -width [linewidth $p] \
6072 -fill $colormap($p) -tags lines.$p]
6073 $canv lower $t
6074 bindline $t $p
6076 if {$rmx > [lindex $idpos($id) 1]} {
6077 lset idpos($id) 1 $rmx
6078 redrawtags $id
6082 proc drawlines {id} {
6083 global canv
6085 $canv itemconf lines.$id -width [linewidth $id]
6088 proc drawcmittext {id row col} {
6089 global linespc canv canv2 canv3 fgcolor curview
6090 global cmitlisted commitinfo rowidlist parentlist
6091 global rowtextx idpos idtags idheads idotherrefs
6092 global linehtag linentag linedtag selectedline
6093 global canvxmax boldids boldnameids fgcolor markedid
6094 global mainheadid nullid nullid2 circleitem circlecolors ctxbut
6095 global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
6096 global circleoutlinecolor
6098 # listed is 0 for boundary, 1 for normal, 2 for negative, 3 for left, 4 for right
6099 set listed $cmitlisted($curview,$id)
6100 if {$id eq $nullid} {
6101 set ofill $workingfilescirclecolor
6102 } elseif {$id eq $nullid2} {
6103 set ofill $indexcirclecolor
6104 } elseif {$id eq $mainheadid} {
6105 set ofill $mainheadcirclecolor
6106 } else {
6107 set ofill [lindex $circlecolors $listed]
6109 set x [xc $row $col]
6110 set y [yc $row]
6111 set orad [expr {$linespc / 3}]
6112 if {$listed <= 2} {
6113 set t [$canv create oval [expr {$x - $orad}] [expr {$y - $orad}] \
6114 [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6115 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6116 } elseif {$listed == 3} {
6117 # triangle pointing left for left-side commits
6118 set t [$canv create polygon \
6119 [expr {$x - $orad}] $y \
6120 [expr {$x + $orad - 1}] [expr {$y - $orad}] \
6121 [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6122 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6123 } else {
6124 # triangle pointing right for right-side commits
6125 set t [$canv create polygon \
6126 [expr {$x + $orad - 1}] $y \
6127 [expr {$x - $orad}] [expr {$y - $orad}] \
6128 [expr {$x - $orad}] [expr {$y + $orad - 1}] \
6129 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6131 set circleitem($row) $t
6132 $canv raise $t
6133 $canv bind $t <1> {selcanvline {} %x %y}
6134 set rmx [llength [lindex $rowidlist $row]]
6135 set olds [lindex $parentlist $row]
6136 if {$olds ne {}} {
6137 set nextids [lindex $rowidlist [expr {$row + 1}]]
6138 foreach p $olds {
6139 set i [lsearch -exact $nextids $p]
6140 if {$i > $rmx} {
6141 set rmx $i
6145 set xt [xc $row $rmx]
6146 set rowtextx($row) $xt
6147 set idpos($id) [list $x $xt $y]
6148 if {[info exists idtags($id)] || [info exists idheads($id)]
6149 || [info exists idotherrefs($id)]} {
6150 set xt [drawtags $id $x $xt $y]
6152 if {[lindex $commitinfo($id) 6] > 0} {
6153 set xt [drawnotesign $xt $y]
6155 set headline [lindex $commitinfo($id) 0]
6156 set name [lindex $commitinfo($id) 1]
6157 set date [lindex $commitinfo($id) 2]
6158 set date [formatdate $date]
6159 set font mainfont
6160 set nfont mainfont
6161 set isbold [ishighlighted $id]
6162 if {$isbold > 0} {
6163 lappend boldids $id
6164 set font mainfontbold
6165 if {$isbold > 1} {
6166 lappend boldnameids $id
6167 set nfont mainfontbold
6170 set linehtag($id) [$canv create text $xt $y -anchor w -fill $fgcolor \
6171 -text $headline -font $font -tags text]
6172 $canv bind $linehtag($id) $ctxbut "rowmenu %X %Y $id"
6173 set linentag($id) [$canv2 create text 3 $y -anchor w -fill $fgcolor \
6174 -text $name -font $nfont -tags text]
6175 set linedtag($id) [$canv3 create text 3 $y -anchor w -fill $fgcolor \
6176 -text $date -font mainfont -tags text]
6177 if {$selectedline == $row} {
6178 make_secsel $id
6180 if {[info exists markedid] && $markedid eq $id} {
6181 make_idmark $id
6183 set xr [expr {$xt + [font measure $font $headline]}]
6184 if {$xr > $canvxmax} {
6185 set canvxmax $xr
6186 setcanvscroll
6190 proc drawcmitrow {row} {
6191 global displayorder rowidlist nrows_drawn
6192 global iddrawn markingmatches
6193 global commitinfo numcommits
6194 global filehighlight fhighlights findpattern nhighlights
6195 global hlview vhighlights
6196 global highlight_related rhighlights
6198 if {$row >= $numcommits} return
6200 set id [lindex $displayorder $row]
6201 if {[info exists hlview] && ![info exists vhighlights($id)]} {
6202 askvhighlight $row $id
6204 if {[info exists filehighlight] && ![info exists fhighlights($id)]} {
6205 askfilehighlight $row $id
6207 if {$findpattern ne {} && ![info exists nhighlights($id)]} {
6208 askfindhighlight $row $id
6210 if {$highlight_related ne [mc "None"] && ![info exists rhighlights($id)]} {
6211 askrelhighlight $row $id
6213 if {![info exists iddrawn($id)]} {
6214 set col [lsearch -exact [lindex $rowidlist $row] $id]
6215 if {$col < 0} {
6216 puts "oops, row $row id $id not in list"
6217 return
6219 if {![info exists commitinfo($id)]} {
6220 getcommit $id
6222 assigncolor $id
6223 drawcmittext $id $row $col
6224 set iddrawn($id) 1
6225 incr nrows_drawn
6227 if {$markingmatches} {
6228 markrowmatches $row $id
6232 proc drawcommits {row {endrow {}}} {
6233 global numcommits iddrawn displayorder curview need_redisplay
6234 global parentlist rowidlist rowfinal uparrowlen downarrowlen nrows_drawn
6236 if {$row < 0} {
6237 set row 0
6239 if {$endrow eq {}} {
6240 set endrow $row
6242 if {$endrow >= $numcommits} {
6243 set endrow [expr {$numcommits - 1}]
6246 set rl1 [expr {$row - $downarrowlen - 3}]
6247 if {$rl1 < 0} {
6248 set rl1 0
6250 set ro1 [expr {$row - 3}]
6251 if {$ro1 < 0} {
6252 set ro1 0
6254 set r2 [expr {$endrow + $uparrowlen + 3}]
6255 if {$r2 > $numcommits} {
6256 set r2 $numcommits
6258 for {set r $rl1} {$r < $r2} {incr r} {
6259 if {[lindex $rowidlist $r] ne {} && [lindex $rowfinal $r]} {
6260 if {$rl1 < $r} {
6261 layoutrows $rl1 $r
6263 set rl1 [expr {$r + 1}]
6266 if {$rl1 < $r} {
6267 layoutrows $rl1 $r
6269 optimize_rows $ro1 0 $r2
6270 if {$need_redisplay || $nrows_drawn > 2000} {
6271 clear_display
6274 # make the lines join to already-drawn rows either side
6275 set r [expr {$row - 1}]
6276 if {$r < 0 || ![info exists iddrawn([lindex $displayorder $r])]} {
6277 set r $row
6279 set er [expr {$endrow + 1}]
6280 if {$er >= $numcommits ||
6281 ![info exists iddrawn([lindex $displayorder $er])]} {
6282 set er $endrow
6284 for {} {$r <= $er} {incr r} {
6285 set id [lindex $displayorder $r]
6286 set wasdrawn [info exists iddrawn($id)]
6287 drawcmitrow $r
6288 if {$r == $er} break
6289 set nextid [lindex $displayorder [expr {$r + 1}]]
6290 if {$wasdrawn && [info exists iddrawn($nextid)]} continue
6291 drawparentlinks $id $r
6293 set rowids [lindex $rowidlist $r]
6294 foreach lid $rowids {
6295 if {$lid eq {}} continue
6296 if {[info exists lineend($lid)] && $lineend($lid) > $r} continue
6297 if {$lid eq $id} {
6298 # see if this is the first child of any of its parents
6299 foreach p [lindex $parentlist $r] {
6300 if {[lsearch -exact $rowids $p] < 0} {
6301 # make this line extend up to the child
6302 set lineend($p) [drawlineseg $p $r $er 0]
6305 } else {
6306 set lineend($lid) [drawlineseg $lid $r $er 1]
6312 proc undolayout {row} {
6313 global uparrowlen mingaplen downarrowlen
6314 global rowidlist rowisopt rowfinal need_redisplay
6316 set r [expr {$row - ($uparrowlen + $mingaplen + $downarrowlen)}]
6317 if {$r < 0} {
6318 set r 0
6320 if {[llength $rowidlist] > $r} {
6321 incr r -1
6322 set rowidlist [lrange $rowidlist 0 $r]
6323 set rowfinal [lrange $rowfinal 0 $r]
6324 set rowisopt [lrange $rowisopt 0 $r]
6325 set need_redisplay 1
6326 run drawvisible
6330 proc drawvisible {} {
6331 global canv linespc curview vrowmod selectedline targetrow targetid
6332 global need_redisplay cscroll numcommits
6334 set fs [$canv yview]
6335 set ymax [lindex [$canv cget -scrollregion] 3]
6336 if {$ymax eq {} || $ymax == 0 || $numcommits == 0} return
6337 set f0 [lindex $fs 0]
6338 set f1 [lindex $fs 1]
6339 set y0 [expr {int($f0 * $ymax)}]
6340 set y1 [expr {int($f1 * $ymax)}]
6342 if {[info exists targetid]} {
6343 if {[commitinview $targetid $curview]} {
6344 set r [rowofcommit $targetid]
6345 if {$r != $targetrow} {
6346 # Fix up the scrollregion and change the scrolling position
6347 # now that our target row has moved.
6348 set diff [expr {($r - $targetrow) * $linespc}]
6349 set targetrow $r
6350 setcanvscroll
6351 set ymax [lindex [$canv cget -scrollregion] 3]
6352 incr y0 $diff
6353 incr y1 $diff
6354 set f0 [expr {$y0 / $ymax}]
6355 set f1 [expr {$y1 / $ymax}]
6356 allcanvs yview moveto $f0
6357 $cscroll set $f0 $f1
6358 set need_redisplay 1
6360 } else {
6361 unset targetid
6365 set row [expr {int(($y0 - 3) / $linespc) - 1}]
6366 set endrow [expr {int(($y1 - 3) / $linespc) + 1}]
6367 if {$endrow >= $vrowmod($curview)} {
6368 update_arcrows $curview
6370 if {$selectedline ne {} &&
6371 $row <= $selectedline && $selectedline <= $endrow} {
6372 set targetrow $selectedline
6373 } elseif {[info exists targetid]} {
6374 set targetrow [expr {int(($row + $endrow) / 2)}]
6376 if {[info exists targetrow]} {
6377 if {$targetrow >= $numcommits} {
6378 set targetrow [expr {$numcommits - 1}]
6380 set targetid [commitonrow $targetrow]
6382 drawcommits $row $endrow
6385 proc clear_display {} {
6386 global iddrawn linesegs need_redisplay nrows_drawn
6387 global vhighlights fhighlights nhighlights rhighlights
6388 global linehtag linentag linedtag boldids boldnameids
6390 allcanvs delete all
6391 unset -nocomplain iddrawn
6392 unset -nocomplain linesegs
6393 unset -nocomplain linehtag
6394 unset -nocomplain linentag
6395 unset -nocomplain linedtag
6396 set boldids {}
6397 set boldnameids {}
6398 unset -nocomplain vhighlights
6399 unset -nocomplain fhighlights
6400 unset -nocomplain nhighlights
6401 unset -nocomplain rhighlights
6402 set need_redisplay 0
6403 set nrows_drawn 0
6406 proc findcrossings {id} {
6407 global rowidlist parentlist numcommits displayorder
6409 set cross {}
6410 set ccross {}
6411 foreach {s e} [rowranges $id] {
6412 if {$e >= $numcommits} {
6413 set e [expr {$numcommits - 1}]
6415 if {$e <= $s} continue
6416 for {set row $e} {[incr row -1] >= $s} {} {
6417 set x [lsearch -exact [lindex $rowidlist $row] $id]
6418 if {$x < 0} break
6419 set olds [lindex $parentlist $row]
6420 set kid [lindex $displayorder $row]
6421 set kidx [lsearch -exact [lindex $rowidlist $row] $kid]
6422 if {$kidx < 0} continue
6423 set nextrow [lindex $rowidlist [expr {$row + 1}]]
6424 foreach p $olds {
6425 set px [lsearch -exact $nextrow $p]
6426 if {$px < 0} continue
6427 if {($kidx < $x && $x < $px) || ($px < $x && $x < $kidx)} {
6428 if {[lsearch -exact $ccross $p] >= 0} continue
6429 if {$x == $px + ($kidx < $px? -1: 1)} {
6430 lappend ccross $p
6431 } elseif {[lsearch -exact $cross $p] < 0} {
6432 lappend cross $p
6438 return [concat $ccross {{}} $cross]
6441 proc assigncolor {id} {
6442 global colormap colors nextcolor
6443 global parents children children curview
6445 if {[info exists colormap($id)]} return
6446 set ncolors [llength $colors]
6447 if {[info exists children($curview,$id)]} {
6448 set kids $children($curview,$id)
6449 } else {
6450 set kids {}
6452 if {[llength $kids] == 1} {
6453 set child [lindex $kids 0]
6454 if {[info exists colormap($child)]
6455 && [llength $parents($curview,$child)] == 1} {
6456 set colormap($id) $colormap($child)
6457 return
6460 set badcolors {}
6461 set origbad {}
6462 foreach x [findcrossings $id] {
6463 if {$x eq {}} {
6464 # delimiter between corner crossings and other crossings
6465 if {[llength $badcolors] >= $ncolors - 1} break
6466 set origbad $badcolors
6468 if {[info exists colormap($x)]
6469 && [lsearch -exact $badcolors $colormap($x)] < 0} {
6470 lappend badcolors $colormap($x)
6473 if {[llength $badcolors] >= $ncolors} {
6474 set badcolors $origbad
6476 set origbad $badcolors
6477 if {[llength $badcolors] < $ncolors - 1} {
6478 foreach child $kids {
6479 if {[info exists colormap($child)]
6480 && [lsearch -exact $badcolors $colormap($child)] < 0} {
6481 lappend badcolors $colormap($child)
6483 foreach p $parents($curview,$child) {
6484 if {[info exists colormap($p)]
6485 && [lsearch -exact $badcolors $colormap($p)] < 0} {
6486 lappend badcolors $colormap($p)
6490 if {[llength $badcolors] >= $ncolors} {
6491 set badcolors $origbad
6494 for {set i 0} {$i <= $ncolors} {incr i} {
6495 set c [lindex $colors $nextcolor]
6496 if {[incr nextcolor] >= $ncolors} {
6497 set nextcolor 0
6499 if {[lsearch -exact $badcolors $c]} break
6501 set colormap($id) $c
6504 proc bindline {t id} {
6505 global canv
6507 $canv bind $t <Enter> "lineenter %x %y $id"
6508 $canv bind $t <Motion> "linemotion %x %y $id"
6509 $canv bind $t <Leave> "lineleave $id"
6510 $canv bind $t <Button-1> "lineclick %x %y $id 1"
6513 proc graph_pane_width {} {
6514 global use_ttk
6516 if {$use_ttk} {
6517 set g [.tf.histframe.pwclist sashpos 0]
6518 } else {
6519 set g [.tf.histframe.pwclist sash coord 0]
6521 return [lindex $g 0]
6524 proc totalwidth {l font extra} {
6525 set tot 0
6526 foreach str $l {
6527 set tot [expr {$tot + [font measure $font $str] + $extra}]
6529 return $tot
6532 proc drawtags {id x xt y1} {
6533 global idtags idheads idotherrefs mainhead
6534 global linespc lthickness
6535 global canv rowtextx curview fgcolor bgcolor ctxbut
6536 global headbgcolor headfgcolor headoutlinecolor remotebgcolor
6537 global tagbgcolor tagfgcolor tagoutlinecolor
6538 global reflinecolor
6540 set marks {}
6541 set ntags 0
6542 set nheads 0
6543 set singletag 0
6544 set maxtags 3
6545 set maxtagpct 25
6546 set maxwidth [expr {[graph_pane_width] * $maxtagpct / 100}]
6547 set delta [expr {int(0.5 * ($linespc - $lthickness))}]
6548 set extra [expr {$delta + $lthickness + $linespc}]
6550 if {[info exists idtags($id)]} {
6551 set marks $idtags($id)
6552 set ntags [llength $marks]
6553 if {$ntags > $maxtags ||
6554 [totalwidth $marks mainfont $extra] > $maxwidth} {
6555 # show just a single "n tags..." tag
6556 set singletag 1
6557 if {$ntags == 1} {
6558 set marks [list "tag..."]
6559 } else {
6560 set marks [list [format "%d tags..." $ntags]]
6562 set ntags 1
6565 if {[info exists idheads($id)]} {
6566 set marks [concat $marks $idheads($id)]
6567 set nheads [llength $idheads($id)]
6569 if {[info exists idotherrefs($id)]} {
6570 set marks [concat $marks $idotherrefs($id)]
6572 if {$marks eq {}} {
6573 return $xt
6576 set yt [expr {$y1 - 0.5 * $linespc}]
6577 set yb [expr {$yt + $linespc - 1}]
6578 set xvals {}
6579 set wvals {}
6580 set i -1
6581 foreach tag $marks {
6582 incr i
6583 if {$i >= $ntags && $i < $ntags + $nheads && $tag eq $mainhead} {
6584 set wid [font measure mainfontbold $tag]
6585 } else {
6586 set wid [font measure mainfont $tag]
6588 lappend xvals $xt
6589 lappend wvals $wid
6590 set xt [expr {$xt + $wid + $extra}]
6592 set t [$canv create line $x $y1 [lindex $xvals end] $y1 \
6593 -width $lthickness -fill $reflinecolor -tags tag.$id]
6594 $canv lower $t
6595 foreach tag $marks x $xvals wid $wvals {
6596 set tag_quoted [string map {% %%} $tag]
6597 set xl [expr {$x + $delta}]
6598 set xr [expr {$x + $delta + $wid + $lthickness}]
6599 set font mainfont
6600 if {[incr ntags -1] >= 0} {
6601 # draw a tag
6602 set t [$canv create polygon $x [expr {$yt + $delta}] $xl $yt \
6603 $xr $yt $xr $yb $xl $yb $x [expr {$yb - $delta}] \
6604 -width 1 -outline $tagoutlinecolor -fill $tagbgcolor \
6605 -tags tag.$id]
6606 if {$singletag} {
6607 set tagclick [list showtags $id 1]
6608 } else {
6609 set tagclick [list showtag $tag_quoted 1]
6611 $canv bind $t <1> $tagclick
6612 set rowtextx([rowofcommit $id]) [expr {$xr + $linespc}]
6613 } else {
6614 # draw a head or other ref
6615 if {[incr nheads -1] >= 0} {
6616 set col $headbgcolor
6617 if {$tag eq $mainhead} {
6618 set font mainfontbold
6620 } else {
6621 set col "#ddddff"
6623 set xl [expr {$xl - $delta/2}]
6624 $canv create polygon $x $yt $xr $yt $xr $yb $x $yb \
6625 -width 1 -outline black -fill $col -tags tag.$id
6626 if {[regexp {^(remotes/.*/|remotes/)} $tag match remoteprefix]} {
6627 set rwid [font measure mainfont $remoteprefix]
6628 set xi [expr {$x + 1}]
6629 set yti [expr {$yt + 1}]
6630 set xri [expr {$x + $rwid}]
6631 $canv create polygon $xi $yti $xri $yti $xri $yb $xi $yb \
6632 -width 0 -fill $remotebgcolor -tags tag.$id
6635 set t [$canv create text $xl $y1 -anchor w -text $tag -fill $headfgcolor \
6636 -font $font -tags [list tag.$id text]]
6637 if {$ntags >= 0} {
6638 $canv bind $t <1> $tagclick
6639 } elseif {$nheads >= 0} {
6640 $canv bind $t $ctxbut [list headmenu %X %Y $id $tag_quoted]
6643 return $xt
6646 proc drawnotesign {xt y} {
6647 global linespc canv fgcolor
6649 set orad [expr {$linespc / 3}]
6650 set t [$canv create rectangle [expr {$xt - $orad}] [expr {$y - $orad}] \
6651 [expr {$xt + $orad - 1}] [expr {$y + $orad - 1}] \
6652 -fill yellow -outline $fgcolor -width 1 -tags circle]
6653 set xt [expr {$xt + $orad * 3}]
6654 return $xt
6657 proc xcoord {i level ln} {
6658 global canvx0 xspc1 xspc2
6660 set x [expr {$canvx0 + $i * $xspc1($ln)}]
6661 if {$i > 0 && $i == $level} {
6662 set x [expr {$x + 0.5 * ($xspc2 - $xspc1($ln))}]
6663 } elseif {$i > $level} {
6664 set x [expr {$x + $xspc2 - $xspc1($ln)}]
6666 return $x
6669 proc show_status {msg} {
6670 global canv fgcolor
6672 clear_display
6673 set_window_title
6674 $canv create text 3 3 -anchor nw -text $msg -font mainfont \
6675 -tags text -fill $fgcolor
6678 # Don't change the text pane cursor if it is currently the hand cursor,
6679 # showing that we are over a sha1 ID link.
6680 proc settextcursor {c} {
6681 global ctext curtextcursor
6683 if {[$ctext cget -cursor] == $curtextcursor} {
6684 $ctext config -cursor $c
6686 set curtextcursor $c
6689 proc nowbusy {what {name {}}} {
6690 global isbusy busyname statusw
6692 if {[array names isbusy] eq {}} {
6693 . config -cursor watch
6694 settextcursor watch
6696 set isbusy($what) 1
6697 set busyname($what) $name
6698 if {$name ne {}} {
6699 $statusw conf -text $name
6703 proc notbusy {what} {
6704 global isbusy maincursor textcursor busyname statusw
6706 catch {
6707 unset isbusy($what)
6708 if {$busyname($what) ne {} &&
6709 [$statusw cget -text] eq $busyname($what)} {
6710 $statusw conf -text {}
6713 if {[array names isbusy] eq {}} {
6714 . config -cursor $maincursor
6715 settextcursor $textcursor
6719 proc findmatches {f} {
6720 global findtype findstring
6721 if {$findtype == [mc "Regexp"]} {
6722 set matches [regexp -indices -all -inline $findstring $f]
6723 } else {
6724 set fs $findstring
6725 if {$findtype == [mc "IgnCase"]} {
6726 set f [string tolower $f]
6727 set fs [string tolower $fs]
6729 set matches {}
6730 set i 0
6731 set l [string length $fs]
6732 while {[set j [string first $fs $f $i]] >= 0} {
6733 lappend matches [list $j [expr {$j+$l-1}]]
6734 set i [expr {$j + $l}]
6737 return $matches
6740 proc dofind {{dirn 1} {wrap 1}} {
6741 global findstring findstartline findcurline selectedline numcommits
6742 global gdttype filehighlight fh_serial find_dirn findallowwrap
6744 if {[info exists find_dirn]} {
6745 if {$find_dirn == $dirn} return
6746 stopfinding
6748 focus .
6749 if {$findstring eq {} || $numcommits == 0} return
6750 if {$selectedline eq {}} {
6751 set findstartline [lindex [visiblerows] [expr {$dirn < 0}]]
6752 } else {
6753 set findstartline $selectedline
6755 set findcurline $findstartline
6756 nowbusy finding [mc "Searching"]
6757 if {$gdttype ne [mc "containing:"] && ![info exists filehighlight]} {
6758 after cancel do_file_hl $fh_serial
6759 do_file_hl $fh_serial
6761 set find_dirn $dirn
6762 set findallowwrap $wrap
6763 run findmore
6766 proc stopfinding {} {
6767 global find_dirn findcurline fprogcoord
6769 if {[info exists find_dirn]} {
6770 unset find_dirn
6771 unset findcurline
6772 notbusy finding
6773 set fprogcoord 0
6774 adjustprogress
6776 stopblaming
6779 proc findmore {} {
6780 global commitdata commitinfo numcommits findpattern findloc
6781 global findstartline findcurline findallowwrap
6782 global find_dirn gdttype fhighlights fprogcoord
6783 global curview varcorder vrownum varccommits vrowmod
6785 if {![info exists find_dirn]} {
6786 return 0
6788 set fldtypes [list [mc "Headline"] [mc "Author"] "" [mc "Committer"] "" [mc "Comments"]]
6789 set l $findcurline
6790 set moretodo 0
6791 if {$find_dirn > 0} {
6792 incr l
6793 if {$l >= $numcommits} {
6794 set l 0
6796 if {$l <= $findstartline} {
6797 set lim [expr {$findstartline + 1}]
6798 } else {
6799 set lim $numcommits
6800 set moretodo $findallowwrap
6802 } else {
6803 if {$l == 0} {
6804 set l $numcommits
6806 incr l -1
6807 if {$l >= $findstartline} {
6808 set lim [expr {$findstartline - 1}]
6809 } else {
6810 set lim -1
6811 set moretodo $findallowwrap
6814 set n [expr {($lim - $l) * $find_dirn}]
6815 if {$n > 500} {
6816 set n 500
6817 set moretodo 1
6819 if {$l + ($find_dirn > 0? $n: 1) > $vrowmod($curview)} {
6820 update_arcrows $curview
6822 set found 0
6823 set domore 1
6824 set ai [bsearch $vrownum($curview) $l]
6825 set a [lindex $varcorder($curview) $ai]
6826 set arow [lindex $vrownum($curview) $ai]
6827 set ids [lindex $varccommits($curview,$a)]
6828 set arowend [expr {$arow + [llength $ids]}]
6829 if {$gdttype eq [mc "containing:"]} {
6830 for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6831 if {$l < $arow || $l >= $arowend} {
6832 incr ai $find_dirn
6833 set a [lindex $varcorder($curview) $ai]
6834 set arow [lindex $vrownum($curview) $ai]
6835 set ids [lindex $varccommits($curview,$a)]
6836 set arowend [expr {$arow + [llength $ids]}]
6838 set id [lindex $ids [expr {$l - $arow}]]
6839 # shouldn't happen unless git log doesn't give all the commits...
6840 if {![info exists commitdata($id)] ||
6841 ![doesmatch $commitdata($id)]} {
6842 continue
6844 if {![info exists commitinfo($id)]} {
6845 getcommit $id
6847 set info $commitinfo($id)
6848 foreach f $info ty $fldtypes {
6849 if {$ty eq ""} continue
6850 if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
6851 [doesmatch $f]} {
6852 set found 1
6853 break
6856 if {$found} break
6858 } else {
6859 for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6860 if {$l < $arow || $l >= $arowend} {
6861 incr ai $find_dirn
6862 set a [lindex $varcorder($curview) $ai]
6863 set arow [lindex $vrownum($curview) $ai]
6864 set ids [lindex $varccommits($curview,$a)]
6865 set arowend [expr {$arow + [llength $ids]}]
6867 set id [lindex $ids [expr {$l - $arow}]]
6868 if {![info exists fhighlights($id)]} {
6869 # this sets fhighlights($id) to -1
6870 askfilehighlight $l $id
6872 if {$fhighlights($id) > 0} {
6873 set found $domore
6874 break
6876 if {$fhighlights($id) < 0} {
6877 if {$domore} {
6878 set domore 0
6879 set findcurline [expr {$l - $find_dirn}]
6884 if {$found || ($domore && !$moretodo)} {
6885 unset findcurline
6886 unset find_dirn
6887 notbusy finding
6888 set fprogcoord 0
6889 adjustprogress
6890 if {$found} {
6891 findselectline $l
6892 } else {
6893 bell
6895 return 0
6897 if {!$domore} {
6898 flushhighlights
6899 } else {
6900 set findcurline [expr {$l - $find_dirn}]
6902 set n [expr {($findcurline - $findstartline) * $find_dirn - 1}]
6903 if {$n < 0} {
6904 incr n $numcommits
6906 set fprogcoord [expr {$n * 1.0 / $numcommits}]
6907 adjustprogress
6908 return $domore
6911 proc findselectline {l} {
6912 global findloc commentend ctext findcurline markingmatches gdttype
6914 set markingmatches [expr {$gdttype eq [mc "containing:"]}]
6915 set findcurline $l
6916 selectline $l 1
6917 if {$markingmatches &&
6918 ($findloc eq [mc "All fields"] || $findloc eq [mc "Comments"])} {
6919 # highlight the matches in the comments
6920 set f [$ctext get 1.0 $commentend]
6921 set matches [findmatches $f]
6922 foreach match $matches {
6923 set start [lindex $match 0]
6924 set end [expr {[lindex $match 1] + 1}]
6925 $ctext tag add found "1.0 + $start c" "1.0 + $end c"
6928 drawvisible
6931 # mark the bits of a headline or author that match a find string
6932 proc markmatches {canv l str tag matches font row} {
6933 global selectedline
6935 set bbox [$canv bbox $tag]
6936 set x0 [lindex $bbox 0]
6937 set y0 [lindex $bbox 1]
6938 set y1 [lindex $bbox 3]
6939 foreach match $matches {
6940 set start [lindex $match 0]
6941 set end [lindex $match 1]
6942 if {$start > $end} continue
6943 set xoff [font measure $font [string range $str 0 [expr {$start-1}]]]
6944 set xlen [font measure $font [string range $str 0 [expr {$end}]]]
6945 set t [$canv create rect [expr {$x0+$xoff}] $y0 \
6946 [expr {$x0+$xlen+2}] $y1 \
6947 -outline {} -tags [list match$l matches] -fill yellow]
6948 $canv lower $t
6949 if {$row == $selectedline} {
6950 $canv raise $t secsel
6955 proc unmarkmatches {} {
6956 global markingmatches
6958 allcanvs delete matches
6959 set markingmatches 0
6960 stopfinding
6963 proc selcanvline {w x y} {
6964 global canv canvy0 ctext linespc
6965 global rowtextx
6966 set ymax [lindex [$canv cget -scrollregion] 3]
6967 if {$ymax == {}} return
6968 set yfrac [lindex [$canv yview] 0]
6969 set y [expr {$y + $yfrac * $ymax}]
6970 set l [expr {int(($y - $canvy0) / $linespc + 0.5)}]
6971 if {$l < 0} {
6972 set l 0
6974 if {$w eq $canv} {
6975 set xmax [lindex [$canv cget -scrollregion] 2]
6976 set xleft [expr {[lindex [$canv xview] 0] * $xmax}]
6977 if {![info exists rowtextx($l)] || $xleft + $x < $rowtextx($l)} return
6979 unmarkmatches
6980 selectline $l 1
6983 proc commit_descriptor {p} {
6984 global commitinfo
6985 if {![info exists commitinfo($p)]} {
6986 getcommit $p
6988 set l "..."
6989 if {[llength $commitinfo($p)] > 1} {
6990 set l [lindex $commitinfo($p) 0]
6992 return "$p ($l)\n"
6995 # append some text to the ctext widget, and make any SHA1 ID
6996 # that we know about be a clickable link.
6997 proc appendwithlinks {text tags} {
6998 global ctext linknum curview
7000 set start [$ctext index "end - 1c"]
7001 $ctext insert end $text $tags
7002 set links [regexp -indices -all -inline {(?:\m|-g)[0-9a-f]{6,40}\M} $text]
7003 foreach l $links {
7004 set s [lindex $l 0]
7005 set e [lindex $l 1]
7006 set linkid [string range $text $s $e]
7007 incr e
7008 $ctext tag delete link$linknum
7009 $ctext tag add link$linknum "$start + $s c" "$start + $e c"
7010 setlink $linkid link$linknum
7011 incr linknum
7015 proc setlink {id lk} {
7016 global curview ctext pendinglinks
7017 global linkfgcolor
7019 if {[string range $id 0 1] eq "-g"} {
7020 set id [string range $id 2 end]
7023 set known 0
7024 if {[string length $id] < 40} {
7025 set matches [longid $id]
7026 if {[llength $matches] > 0} {
7027 if {[llength $matches] > 1} return
7028 set known 1
7029 set id [lindex $matches 0]
7031 } else {
7032 set known [commitinview $id $curview]
7034 if {$known} {
7035 $ctext tag conf $lk -foreground $linkfgcolor -underline 1
7036 $ctext tag bind $lk <1> [list selbyid $id]
7037 $ctext tag bind $lk <Enter> {linkcursor %W 1}
7038 $ctext tag bind $lk <Leave> {linkcursor %W -1}
7039 } else {
7040 lappend pendinglinks($id) $lk
7041 interestedin $id {makelink %P}
7045 proc appendshortlink {id {pre {}} {post {}}} {
7046 global ctext linknum
7048 $ctext insert end $pre
7049 $ctext tag delete link$linknum
7050 $ctext insert end [string range $id 0 7] link$linknum
7051 $ctext insert end $post
7052 setlink $id link$linknum
7053 incr linknum
7056 proc makelink {id} {
7057 global pendinglinks
7059 if {![info exists pendinglinks($id)]} return
7060 foreach lk $pendinglinks($id) {
7061 setlink $id $lk
7063 unset pendinglinks($id)
7066 proc linkcursor {w inc} {
7067 global linkentercount curtextcursor
7069 if {[incr linkentercount $inc] > 0} {
7070 $w configure -cursor hand2
7071 } else {
7072 $w configure -cursor $curtextcursor
7073 if {$linkentercount < 0} {
7074 set linkentercount 0
7079 proc viewnextline {dir} {
7080 global canv linespc
7082 $canv delete hover
7083 set ymax [lindex [$canv cget -scrollregion] 3]
7084 set wnow [$canv yview]
7085 set wtop [expr {[lindex $wnow 0] * $ymax}]
7086 set newtop [expr {$wtop + $dir * $linespc}]
7087 if {$newtop < 0} {
7088 set newtop 0
7089 } elseif {$newtop > $ymax} {
7090 set newtop $ymax
7092 allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7095 # add a list of tag or branch names at position pos
7096 # returns the number of names inserted
7097 proc appendrefs {pos ids var} {
7098 global ctext linknum curview $var maxrefs visiblerefs mainheadid
7100 if {[catch {$ctext index $pos}]} {
7101 return 0
7103 $ctext conf -state normal
7104 $ctext delete $pos "$pos lineend"
7105 set tags {}
7106 foreach id $ids {
7107 foreach tag [set $var\($id\)] {
7108 lappend tags [list $tag $id]
7112 set sep {}
7113 set tags [lsort -index 0 -decreasing $tags]
7114 set nutags 0
7116 if {[llength $tags] > $maxrefs} {
7117 # If we are displaying heads, and there are too many,
7118 # see if there are some important heads to display.
7119 # Currently that are the current head and heads listed in $visiblerefs option
7120 set itags {}
7121 if {$var eq "idheads"} {
7122 set utags {}
7123 foreach ti $tags {
7124 set hname [lindex $ti 0]
7125 set id [lindex $ti 1]
7126 if {([lsearch -exact $visiblerefs $hname] != -1 || $id eq $mainheadid) &&
7127 [llength $itags] < $maxrefs} {
7128 lappend itags $ti
7129 } else {
7130 lappend utags $ti
7133 set tags $utags
7135 if {$itags ne {}} {
7136 set str [mc "and many more"]
7137 set sep " "
7138 } else {
7139 set str [mc "many"]
7141 $ctext insert $pos "$str ([llength $tags])"
7142 set nutags [llength $tags]
7143 set tags $itags
7146 foreach ti $tags {
7147 set id [lindex $ti 1]
7148 set lk link$linknum
7149 incr linknum
7150 $ctext tag delete $lk
7151 $ctext insert $pos $sep
7152 $ctext insert $pos [lindex $ti 0] $lk
7153 setlink $id $lk
7154 set sep ", "
7156 $ctext tag add wwrap "$pos linestart" "$pos lineend"
7157 $ctext conf -state disabled
7158 return [expr {[llength $tags] + $nutags}]
7161 # called when we have finished computing the nearby tags
7162 proc dispneartags {delay} {
7163 global selectedline currentid showneartags tagphase
7165 if {$selectedline eq {} || !$showneartags} return
7166 after cancel dispnexttag
7167 if {$delay} {
7168 after 200 dispnexttag
7169 set tagphase -1
7170 } else {
7171 after idle dispnexttag
7172 set tagphase 0
7176 proc dispnexttag {} {
7177 global selectedline currentid showneartags tagphase ctext
7179 if {$selectedline eq {} || !$showneartags} return
7180 switch -- $tagphase {
7182 set dtags [desctags $currentid]
7183 if {$dtags ne {}} {
7184 appendrefs precedes $dtags idtags
7188 set atags [anctags $currentid]
7189 if {$atags ne {}} {
7190 appendrefs follows $atags idtags
7194 set dheads [descheads $currentid]
7195 if {$dheads ne {}} {
7196 if {[appendrefs branch $dheads idheads] > 1
7197 && [$ctext get "branch -3c"] eq "h"} {
7198 # turn "Branch" into "Branches"
7199 $ctext conf -state normal
7200 $ctext insert "branch -2c" "es"
7201 $ctext conf -state disabled
7206 if {[incr tagphase] <= 2} {
7207 after idle dispnexttag
7211 proc make_secsel {id} {
7212 global linehtag linentag linedtag canv canv2 canv3
7214 if {![info exists linehtag($id)]} return
7215 $canv delete secsel
7216 set t [eval $canv create rect [$canv bbox $linehtag($id)] -outline {{}} \
7217 -tags secsel -fill [$canv cget -selectbackground]]
7218 $canv lower $t
7219 $canv2 delete secsel
7220 set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] -outline {{}} \
7221 -tags secsel -fill [$canv2 cget -selectbackground]]
7222 $canv2 lower $t
7223 $canv3 delete secsel
7224 set t [eval $canv3 create rect [$canv3 bbox $linedtag($id)] -outline {{}} \
7225 -tags secsel -fill [$canv3 cget -selectbackground]]
7226 $canv3 lower $t
7229 proc make_idmark {id} {
7230 global linehtag canv fgcolor
7232 if {![info exists linehtag($id)]} return
7233 $canv delete markid
7234 set t [eval $canv create rect [$canv bbox $linehtag($id)] \
7235 -tags markid -outline $fgcolor]
7236 $canv raise $t
7239 proc selectline {l isnew {desired_loc {}} {switch_to_patch 0}} {
7240 global canv ctext commitinfo selectedline
7241 global canvy0 linespc parents children curview
7242 global currentid sha1entry
7243 global commentend idtags linknum
7244 global mergemax numcommits pending_select
7245 global cmitmode showneartags allcommits
7246 global targetrow targetid lastscrollrows
7247 global autoselect autosellen jump_to_here
7248 global vinlinediff
7250 unset -nocomplain pending_select
7251 $canv delete hover
7252 normalline
7253 unsel_reflist
7254 stopfinding
7255 if {$l < 0 || $l >= $numcommits} return
7256 set id [commitonrow $l]
7257 set targetid $id
7258 set targetrow $l
7259 set selectedline $l
7260 set currentid $id
7261 if {$lastscrollrows < $numcommits} {
7262 setcanvscroll
7265 if {$cmitmode ne "patch" && $switch_to_patch} {
7266 set cmitmode "patch"
7269 set y [expr {$canvy0 + $l * $linespc}]
7270 set ymax [lindex [$canv cget -scrollregion] 3]
7271 set ytop [expr {$y - $linespc - 1}]
7272 set ybot [expr {$y + $linespc + 1}]
7273 set wnow [$canv yview]
7274 set wtop [expr {[lindex $wnow 0] * $ymax}]
7275 set wbot [expr {[lindex $wnow 1] * $ymax}]
7276 set wh [expr {$wbot - $wtop}]
7277 set newtop $wtop
7278 if {$ytop < $wtop} {
7279 if {$ybot < $wtop} {
7280 set newtop [expr {$y - $wh / 2.0}]
7281 } else {
7282 set newtop $ytop
7283 if {$newtop > $wtop - $linespc} {
7284 set newtop [expr {$wtop - $linespc}]
7287 } elseif {$ybot > $wbot} {
7288 if {$ytop > $wbot} {
7289 set newtop [expr {$y - $wh / 2.0}]
7290 } else {
7291 set newtop [expr {$ybot - $wh}]
7292 if {$newtop < $wtop + $linespc} {
7293 set newtop [expr {$wtop + $linespc}]
7297 if {$newtop != $wtop} {
7298 if {$newtop < 0} {
7299 set newtop 0
7301 allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7302 drawvisible
7305 make_secsel $id
7307 if {$isnew} {
7308 addtohistory [list selbyid $id 0] savecmitpos
7311 $sha1entry delete 0 end
7312 $sha1entry insert 0 $id
7313 if {$autoselect} {
7314 $sha1entry selection range 0 $autosellen
7316 rhighlight_sel $id
7318 $ctext conf -state normal
7319 clear_ctext
7320 set linknum 0
7321 if {![info exists commitinfo($id)]} {
7322 getcommit $id
7324 set info $commitinfo($id)
7325 set date [formatdate [lindex $info 2]]
7326 $ctext insert end "[mc "Author"]: [lindex $info 1] $date\n"
7327 set date [formatdate [lindex $info 4]]
7328 $ctext insert end "[mc "Committer"]: [lindex $info 3] $date\n"
7329 if {[info exists idtags($id)]} {
7330 $ctext insert end [mc "Tags:"]
7331 foreach tag $idtags($id) {
7332 $ctext insert end " $tag"
7334 $ctext insert end "\n"
7337 set headers {}
7338 set olds $parents($curview,$id)
7339 if {[llength $olds] > 1} {
7340 set np 0
7341 foreach p $olds {
7342 if {$np >= $mergemax} {
7343 set tag mmax
7344 } else {
7345 set tag m$np
7347 $ctext insert end "[mc "Parent"]: " $tag
7348 appendwithlinks [commit_descriptor $p] {}
7349 incr np
7351 } else {
7352 foreach p $olds {
7353 append headers "[mc "Parent"]: [commit_descriptor $p]"
7357 foreach c $children($curview,$id) {
7358 append headers "[mc "Child"]: [commit_descriptor $c]"
7361 # make anything that looks like a SHA1 ID be a clickable link
7362 appendwithlinks $headers {}
7363 if {$showneartags} {
7364 if {![info exists allcommits]} {
7365 getallcommits
7367 $ctext insert end "[mc "Branch"]: "
7368 $ctext mark set branch "end -1c"
7369 $ctext mark gravity branch left
7370 $ctext insert end "\n[mc "Follows"]: "
7371 $ctext mark set follows "end -1c"
7372 $ctext mark gravity follows left
7373 $ctext insert end "\n[mc "Precedes"]: "
7374 $ctext mark set precedes "end -1c"
7375 $ctext mark gravity precedes left
7376 $ctext insert end "\n"
7377 dispneartags 1
7379 $ctext insert end "\n"
7380 set comment [lindex $info 5]
7381 if {[string first "\r" $comment] >= 0} {
7382 set comment [string map {"\r" "\n "} $comment]
7384 appendwithlinks $comment {comment}
7386 $ctext tag remove found 1.0 end
7387 $ctext conf -state disabled
7388 set commentend [$ctext index "end - 1c"]
7390 set jump_to_here $desired_loc
7391 init_flist [mc "Comments"]
7392 if {$cmitmode eq "tree"} {
7393 gettree $id
7394 } elseif {$vinlinediff($curview) == 1} {
7395 showinlinediff $id
7396 } elseif {[llength $olds] <= 1} {
7397 startdiff $id
7398 } else {
7399 mergediff $id
7403 proc selfirstline {} {
7404 unmarkmatches
7405 selectline 0 1
7408 proc sellastline {} {
7409 global numcommits
7410 unmarkmatches
7411 set l [expr {$numcommits - 1}]
7412 selectline $l 1
7415 proc selnextline {dir} {
7416 global selectedline
7417 focus .
7418 if {$selectedline eq {}} return
7419 set l [expr {$selectedline + $dir}]
7420 unmarkmatches
7421 selectline $l 1
7424 proc selnextpage {dir} {
7425 global canv linespc selectedline numcommits
7427 set lpp [expr {([winfo height $canv] - 2) / $linespc}]
7428 if {$lpp < 1} {
7429 set lpp 1
7431 allcanvs yview scroll [expr {$dir * $lpp}] units
7432 drawvisible
7433 if {$selectedline eq {}} return
7434 set l [expr {$selectedline + $dir * $lpp}]
7435 if {$l < 0} {
7436 set l 0
7437 } elseif {$l >= $numcommits} {
7438 set l [expr $numcommits - 1]
7440 unmarkmatches
7441 selectline $l 1
7444 proc unselectline {} {
7445 global selectedline currentid
7447 set selectedline {}
7448 unset -nocomplain currentid
7449 allcanvs delete secsel
7450 rhighlight_none
7453 proc reselectline {} {
7454 global selectedline
7456 if {$selectedline ne {}} {
7457 selectline $selectedline 0
7461 proc addtohistory {cmd {saveproc {}}} {
7462 global history historyindex curview
7464 unset_posvars
7465 save_position
7466 set elt [list $curview $cmd $saveproc {}]
7467 if {$historyindex > 0
7468 && [lindex $history [expr {$historyindex - 1}]] == $elt} {
7469 return
7472 if {$historyindex < [llength $history]} {
7473 set history [lreplace $history $historyindex end $elt]
7474 } else {
7475 lappend history $elt
7477 incr historyindex
7478 if {$historyindex > 1} {
7479 .tf.bar.leftbut conf -state normal
7480 } else {
7481 .tf.bar.leftbut conf -state disabled
7483 .tf.bar.rightbut conf -state disabled
7486 # save the scrolling position of the diff display pane
7487 proc save_position {} {
7488 global historyindex history
7490 if {$historyindex < 1} return
7491 set hi [expr {$historyindex - 1}]
7492 set fn [lindex $history $hi 2]
7493 if {$fn ne {}} {
7494 lset history $hi 3 [eval $fn]
7498 proc unset_posvars {} {
7499 global last_posvars
7501 if {[info exists last_posvars]} {
7502 foreach {var val} $last_posvars {
7503 global $var
7504 unset -nocomplain $var
7506 unset last_posvars
7510 proc godo {elt} {
7511 global curview last_posvars
7513 set view [lindex $elt 0]
7514 set cmd [lindex $elt 1]
7515 set pv [lindex $elt 3]
7516 if {$curview != $view} {
7517 showview $view
7519 unset_posvars
7520 foreach {var val} $pv {
7521 global $var
7522 set $var $val
7524 set last_posvars $pv
7525 eval $cmd
7528 proc goback {} {
7529 global history historyindex
7530 focus .
7532 if {$historyindex > 1} {
7533 save_position
7534 incr historyindex -1
7535 godo [lindex $history [expr {$historyindex - 1}]]
7536 .tf.bar.rightbut conf -state normal
7538 if {$historyindex <= 1} {
7539 .tf.bar.leftbut conf -state disabled
7543 proc goforw {} {
7544 global history historyindex
7545 focus .
7547 if {$historyindex < [llength $history]} {
7548 save_position
7549 set cmd [lindex $history $historyindex]
7550 incr historyindex
7551 godo $cmd
7552 .tf.bar.leftbut conf -state normal
7554 if {$historyindex >= [llength $history]} {
7555 .tf.bar.rightbut conf -state disabled
7559 proc go_to_parent {i} {
7560 global parents curview targetid
7561 set ps $parents($curview,$targetid)
7562 if {[llength $ps] >= $i} {
7563 selbyid [lindex $ps [expr $i - 1]]
7567 proc gettree {id} {
7568 global treefilelist treeidlist diffids diffmergeid treepending
7569 global nullid nullid2
7571 set diffids $id
7572 unset -nocomplain diffmergeid
7573 if {![info exists treefilelist($id)]} {
7574 if {![info exists treepending]} {
7575 if {$id eq $nullid} {
7576 set cmd [list | git ls-files]
7577 } elseif {$id eq $nullid2} {
7578 set cmd [list | git ls-files --stage -t]
7579 } else {
7580 set cmd [list | git ls-tree -r $id]
7582 if {[catch {set gtf [open $cmd r]}]} {
7583 return
7585 set treepending $id
7586 set treefilelist($id) {}
7587 set treeidlist($id) {}
7588 fconfigure $gtf -blocking 0 -encoding binary
7589 filerun $gtf [list gettreeline $gtf $id]
7591 } else {
7592 setfilelist $id
7596 proc gettreeline {gtf id} {
7597 global treefilelist treeidlist treepending cmitmode diffids nullid nullid2
7599 set nl 0
7600 while {[incr nl] <= 1000 && [gets $gtf line] >= 0} {
7601 if {$diffids eq $nullid} {
7602 set fname $line
7603 } else {
7604 set i [string first "\t" $line]
7605 if {$i < 0} continue
7606 set fname [string range $line [expr {$i+1}] end]
7607 set line [string range $line 0 [expr {$i-1}]]
7608 if {$diffids ne $nullid2 && [lindex $line 1] ne "blob"} continue
7609 set sha1 [lindex $line 2]
7610 lappend treeidlist($id) $sha1
7612 if {[string index $fname 0] eq "\""} {
7613 set fname [lindex $fname 0]
7615 set fname [encoding convertfrom $fname]
7616 lappend treefilelist($id) $fname
7618 if {![eof $gtf]} {
7619 return [expr {$nl >= 1000? 2: 1}]
7621 close $gtf
7622 unset treepending
7623 if {$cmitmode ne "tree"} {
7624 if {![info exists diffmergeid]} {
7625 gettreediffs $diffids
7627 } elseif {$id ne $diffids} {
7628 gettree $diffids
7629 } else {
7630 setfilelist $id
7632 return 0
7635 proc showfile {f} {
7636 global treefilelist treeidlist diffids nullid nullid2
7637 global ctext_file_names ctext_file_lines
7638 global ctext commentend
7640 set i [lsearch -exact $treefilelist($diffids) $f]
7641 if {$i < 0} {
7642 puts "oops, $f not in list for id $diffids"
7643 return
7645 if {$diffids eq $nullid} {
7646 if {[catch {set bf [open $f r]} err]} {
7647 puts "oops, can't read $f: $err"
7648 return
7650 } else {
7651 set blob [lindex $treeidlist($diffids) $i]
7652 if {[catch {set bf [open [concat | git cat-file blob $blob] r]} err]} {
7653 puts "oops, error reading blob $blob: $err"
7654 return
7657 fconfigure $bf -blocking 0 -encoding [get_path_encoding $f]
7658 filerun $bf [list getblobline $bf $diffids]
7659 $ctext config -state normal
7660 clear_ctext $commentend
7661 lappend ctext_file_names $f
7662 lappend ctext_file_lines [lindex [split $commentend "."] 0]
7663 $ctext insert end "\n"
7664 $ctext insert end "$f\n" filesep
7665 $ctext config -state disabled
7666 $ctext yview $commentend
7667 settabs 0
7670 proc getblobline {bf id} {
7671 global diffids cmitmode ctext
7673 if {$id ne $diffids || $cmitmode ne "tree"} {
7674 catch {close $bf}
7675 return 0
7677 $ctext config -state normal
7678 set nl 0
7679 while {[incr nl] <= 1000 && [gets $bf line] >= 0} {
7680 $ctext insert end "$line\n"
7682 if {[eof $bf]} {
7683 global jump_to_here ctext_file_names commentend
7685 # delete last newline
7686 $ctext delete "end - 2c" "end - 1c"
7687 close $bf
7688 if {$jump_to_here ne {} &&
7689 [lindex $jump_to_here 0] eq [lindex $ctext_file_names 0]} {
7690 set lnum [expr {[lindex $jump_to_here 1] +
7691 [lindex [split $commentend .] 0]}]
7692 mark_ctext_line $lnum
7694 $ctext config -state disabled
7695 return 0
7697 $ctext config -state disabled
7698 return [expr {$nl >= 1000? 2: 1}]
7701 proc mark_ctext_line {lnum} {
7702 global ctext markbgcolor
7704 $ctext tag delete omark
7705 $ctext tag add omark $lnum.0 "$lnum.0 + 1 line"
7706 $ctext tag conf omark -background $markbgcolor
7707 $ctext see $lnum.0
7710 proc mergediff {id} {
7711 global diffmergeid
7712 global diffids treediffs
7713 global parents curview
7715 set diffmergeid $id
7716 set diffids $id
7717 set treediffs($id) {}
7718 set np [llength $parents($curview,$id)]
7719 settabs $np
7720 getblobdiffs $id
7723 proc startdiff {ids} {
7724 global treediffs diffids treepending diffmergeid nullid nullid2
7726 settabs 1
7727 set diffids $ids
7728 unset -nocomplain diffmergeid
7729 if {![info exists treediffs($ids)] ||
7730 [lsearch -exact $ids $nullid] >= 0 ||
7731 [lsearch -exact $ids $nullid2] >= 0} {
7732 if {![info exists treepending]} {
7733 gettreediffs $ids
7735 } else {
7736 addtocflist $ids
7740 proc showinlinediff {ids} {
7741 global commitinfo commitdata ctext
7742 global treediffs
7744 set info $commitinfo($ids)
7745 set diff [lindex $info 7]
7746 set difflines [split $diff "\n"]
7748 initblobdiffvars
7749 set treediff {}
7751 set inhdr 0
7752 foreach line $difflines {
7753 if {![string compare -length 5 "diff " $line]} {
7754 set inhdr 1
7755 } elseif {$inhdr && ![string compare -length 4 "+++ " $line]} {
7756 # offset also accounts for the b/ prefix
7757 lappend treediff [string range $line 6 end]
7758 set inhdr 0
7762 set treediffs($ids) $treediff
7763 add_flist $treediff
7765 $ctext conf -state normal
7766 foreach line $difflines {
7767 parseblobdiffline $ids $line
7769 maybe_scroll_ctext 1
7770 $ctext conf -state disabled
7773 # If the filename (name) is under any of the passed filter paths
7774 # then return true to include the file in the listing.
7775 proc path_filter {filter name} {
7776 set worktree [gitworktree]
7777 foreach p $filter {
7778 set fq_p [file normalize $p]
7779 set fq_n [file normalize [file join $worktree $name]]
7780 if {[string match [file normalize $fq_p]* $fq_n]} {
7781 return 1
7784 return 0
7787 proc addtocflist {ids} {
7788 global treediffs
7790 add_flist $treediffs($ids)
7791 getblobdiffs $ids
7794 proc diffcmd {ids flags} {
7795 global log_showroot nullid nullid2 git_version
7797 set i [lsearch -exact $ids $nullid]
7798 set j [lsearch -exact $ids $nullid2]
7799 if {$i >= 0} {
7800 if {[llength $ids] > 1 && $j < 0} {
7801 # comparing working directory with some specific revision
7802 set cmd [concat | git diff-index $flags]
7803 if {$i == 0} {
7804 lappend cmd -R [lindex $ids 1]
7805 } else {
7806 lappend cmd [lindex $ids 0]
7808 } else {
7809 # comparing working directory with index
7810 set cmd [concat | git diff-files $flags]
7811 if {$j == 1} {
7812 lappend cmd -R
7815 } elseif {$j >= 0} {
7816 if {[package vcompare $git_version "1.7.2"] >= 0} {
7817 set flags "$flags --ignore-submodules=dirty"
7819 set cmd [concat | git diff-index --cached $flags]
7820 if {[llength $ids] > 1} {
7821 # comparing index with specific revision
7822 if {$j == 0} {
7823 lappend cmd -R [lindex $ids 1]
7824 } else {
7825 lappend cmd [lindex $ids 0]
7827 } else {
7828 # comparing index with HEAD
7829 lappend cmd HEAD
7831 } else {
7832 if {$log_showroot} {
7833 lappend flags --root
7835 set cmd [concat | git diff-tree -r $flags $ids]
7837 return $cmd
7840 proc gettreediffs {ids} {
7841 global treediff treepending limitdiffs vfilelimit curview
7843 set cmd [diffcmd $ids {--no-commit-id}]
7844 if {$limitdiffs && $vfilelimit($curview) ne {}} {
7845 set cmd [concat $cmd -- $vfilelimit($curview)]
7847 if {[catch {set gdtf [open $cmd r]}]} return
7849 set treepending $ids
7850 set treediff {}
7851 fconfigure $gdtf -blocking 0 -encoding binary
7852 filerun $gdtf [list gettreediffline $gdtf $ids]
7855 proc gettreediffline {gdtf ids} {
7856 global treediff treediffs treepending diffids diffmergeid
7857 global cmitmode vfilelimit curview limitdiffs perfile_attrs
7859 set nr 0
7860 set sublist {}
7861 set max 1000
7862 if {$perfile_attrs} {
7863 # cache_gitattr is slow, and even slower on win32 where we
7864 # have to invoke it for only about 30 paths at a time
7865 set max 500
7866 if {[tk windowingsystem] == "win32"} {
7867 set max 120
7870 while {[incr nr] <= $max && [gets $gdtf line] >= 0} {
7871 set i [string first "\t" $line]
7872 if {$i >= 0} {
7873 set file [string range $line [expr {$i+1}] end]
7874 if {[string index $file 0] eq "\""} {
7875 set file [lindex $file 0]
7877 set file [encoding convertfrom $file]
7878 if {$file ne [lindex $treediff end]} {
7879 lappend treediff $file
7880 lappend sublist $file
7884 if {$perfile_attrs} {
7885 cache_gitattr encoding $sublist
7887 if {![eof $gdtf]} {
7888 return [expr {$nr >= $max? 2: 1}]
7890 close $gdtf
7891 set treediffs($ids) $treediff
7892 unset treepending
7893 if {$cmitmode eq "tree" && [llength $diffids] == 1} {
7894 gettree $diffids
7895 } elseif {$ids != $diffids} {
7896 if {![info exists diffmergeid]} {
7897 gettreediffs $diffids
7899 } else {
7900 addtocflist $ids
7902 return 0
7905 # empty string or positive integer
7906 proc diffcontextvalidate {v} {
7907 return [regexp {^(|[1-9][0-9]*)$} $v]
7910 proc diffcontextchange {n1 n2 op} {
7911 global diffcontextstring diffcontext
7913 if {[string is integer -strict $diffcontextstring]} {
7914 if {$diffcontextstring >= 0} {
7915 set diffcontext $diffcontextstring
7916 reselectline
7921 proc changeignorespace {} {
7922 reselectline
7925 proc changeworddiff {name ix op} {
7926 reselectline
7929 proc initblobdiffvars {} {
7930 global diffencoding targetline diffnparents
7931 global diffinhdr currdiffsubmod diffseehere
7932 set targetline {}
7933 set diffnparents 0
7934 set diffinhdr 0
7935 set diffencoding [get_path_encoding {}]
7936 set currdiffsubmod ""
7937 set diffseehere -1
7940 proc getblobdiffs {ids} {
7941 global blobdifffd diffids env
7942 global treediffs
7943 global diffcontext
7944 global ignorespace
7945 global worddiff
7946 global limitdiffs vfilelimit curview
7947 global git_version
7949 set textconv {}
7950 if {[package vcompare $git_version "1.6.1"] >= 0} {
7951 set textconv "--textconv"
7953 set submodule {}
7954 if {[package vcompare $git_version "1.6.6"] >= 0} {
7955 set submodule "--submodule"
7957 set cmd [diffcmd $ids "-p $textconv $submodule -C --cc --no-commit-id -U$diffcontext"]
7958 if {$ignorespace} {
7959 append cmd " -w"
7961 if {$worddiff ne [mc "Line diff"]} {
7962 append cmd " --word-diff=porcelain"
7964 if {$limitdiffs && $vfilelimit($curview) ne {}} {
7965 set cmd [concat $cmd -- $vfilelimit($curview)]
7967 if {[catch {set bdf [open $cmd r]} err]} {
7968 error_popup [mc "Error getting diffs: %s" $err]
7969 return
7971 fconfigure $bdf -blocking 0 -encoding binary -eofchar {}
7972 set blobdifffd($ids) $bdf
7973 initblobdiffvars
7974 filerun $bdf [list getblobdiffline $bdf $diffids]
7977 proc savecmitpos {} {
7978 global ctext cmitmode
7980 if {$cmitmode eq "tree"} {
7981 return {}
7983 return [list target_scrollpos [$ctext index @0,0]]
7986 proc savectextpos {} {
7987 global ctext
7989 return [list target_scrollpos [$ctext index @0,0]]
7992 proc maybe_scroll_ctext {ateof} {
7993 global ctext target_scrollpos
7995 if {![info exists target_scrollpos]} return
7996 if {!$ateof} {
7997 set nlines [expr {[winfo height $ctext]
7998 / [font metrics textfont -linespace]}]
7999 if {[$ctext compare "$target_scrollpos + $nlines lines" <= end]} return
8001 $ctext yview $target_scrollpos
8002 unset target_scrollpos
8005 proc setinlist {var i val} {
8006 global $var
8008 while {[llength [set $var]] < $i} {
8009 lappend $var {}
8011 if {[llength [set $var]] == $i} {
8012 lappend $var $val
8013 } else {
8014 lset $var $i $val
8018 proc makediffhdr {fname ids} {
8019 global ctext curdiffstart treediffs diffencoding
8020 global ctext_file_names jump_to_here targetline diffline
8022 set fname [encoding convertfrom $fname]
8023 set diffencoding [get_path_encoding $fname]
8024 set i [lsearch -exact $treediffs($ids) $fname]
8025 if {$i >= 0} {
8026 setinlist difffilestart $i $curdiffstart
8028 lset ctext_file_names end $fname
8029 set l [expr {(78 - [string length $fname]) / 2}]
8030 set pad [string range "----------------------------------------" 1 $l]
8031 $ctext insert $curdiffstart "$pad $fname $pad" filesep
8032 set targetline {}
8033 if {$jump_to_here ne {} && [lindex $jump_to_here 0] eq $fname} {
8034 set targetline [lindex $jump_to_here 1]
8036 set diffline 0
8039 proc blobdiffmaybeseehere {ateof} {
8040 global diffseehere
8041 if {$diffseehere >= 0} {
8042 mark_ctext_line [lindex [split $diffseehere .] 0]
8044 maybe_scroll_ctext $ateof
8047 proc getblobdiffline {bdf ids} {
8048 global diffids blobdifffd
8049 global ctext
8051 set nr 0
8052 $ctext conf -state normal
8053 while {[incr nr] <= 1000 && [gets $bdf line] >= 0} {
8054 if {$ids != $diffids || $bdf != $blobdifffd($ids)} {
8055 catch {close $bdf}
8056 return 0
8058 parseblobdiffline $ids $line
8060 $ctext conf -state disabled
8061 blobdiffmaybeseehere [eof $bdf]
8062 if {[eof $bdf]} {
8063 catch {close $bdf}
8064 return 0
8066 return [expr {$nr >= 1000? 2: 1}]
8069 proc parseblobdiffline {ids line} {
8070 global ctext curdiffstart
8071 global diffnexthead diffnextnote difffilestart
8072 global ctext_file_names ctext_file_lines
8073 global diffinhdr treediffs mergemax diffnparents
8074 global diffencoding jump_to_here targetline diffline currdiffsubmod
8075 global worddiff diffseehere
8077 if {![string compare -length 5 "diff " $line]} {
8078 if {![regexp {^diff (--cc|--git) } $line m type]} {
8079 set line [encoding convertfrom $line]
8080 $ctext insert end "$line\n" hunksep
8081 continue
8083 # start of a new file
8084 set diffinhdr 1
8085 $ctext insert end "\n"
8086 set curdiffstart [$ctext index "end - 1c"]
8087 lappend ctext_file_names ""
8088 lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8089 $ctext insert end "\n" filesep
8091 if {$type eq "--cc"} {
8092 # start of a new file in a merge diff
8093 set fname [string range $line 10 end]
8094 if {[lsearch -exact $treediffs($ids) $fname] < 0} {
8095 lappend treediffs($ids) $fname
8096 add_flist [list $fname]
8099 } else {
8100 set line [string range $line 11 end]
8101 # If the name hasn't changed the length will be odd,
8102 # the middle char will be a space, and the two bits either
8103 # side will be a/name and b/name, or "a/name" and "b/name".
8104 # If the name has changed we'll get "rename from" and
8105 # "rename to" or "copy from" and "copy to" lines following
8106 # this, and we'll use them to get the filenames.
8107 # This complexity is necessary because spaces in the
8108 # filename(s) don't get escaped.
8109 set l [string length $line]
8110 set i [expr {$l / 2}]
8111 if {!(($l & 1) && [string index $line $i] eq " " &&
8112 [string range $line 2 [expr {$i - 1}]] eq \
8113 [string range $line [expr {$i + 3}] end])} {
8114 return
8116 # unescape if quoted and chop off the a/ from the front
8117 if {[string index $line 0] eq "\""} {
8118 set fname [string range [lindex $line 0] 2 end]
8119 } else {
8120 set fname [string range $line 2 [expr {$i - 1}]]
8123 makediffhdr $fname $ids
8125 } elseif {![string compare -length 16 "* Unmerged path " $line]} {
8126 set fname [encoding convertfrom [string range $line 16 end]]
8127 $ctext insert end "\n"
8128 set curdiffstart [$ctext index "end - 1c"]
8129 lappend ctext_file_names $fname
8130 lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8131 $ctext insert end "$line\n" filesep
8132 set i [lsearch -exact $treediffs($ids) $fname]
8133 if {$i >= 0} {
8134 setinlist difffilestart $i $curdiffstart
8137 } elseif {![string compare -length 2 "@@" $line]} {
8138 regexp {^@@+} $line ats
8139 set line [encoding convertfrom $diffencoding $line]
8140 $ctext insert end "$line\n" hunksep
8141 if {[regexp { \+(\d+),\d+ @@} $line m nl]} {
8142 set diffline $nl
8144 set diffnparents [expr {[string length $ats] - 1}]
8145 set diffinhdr 0
8147 } elseif {![string compare -length 10 "Submodule " $line]} {
8148 # start of a new submodule
8149 if {[regexp -indices "\[0-9a-f\]+\\.\\." $line nameend]} {
8150 set fname [string range $line 10 [expr [lindex $nameend 0] - 2]]
8151 } else {
8152 set fname [string range $line 10 [expr [string first "contains " $line] - 2]]
8154 if {$currdiffsubmod != $fname} {
8155 $ctext insert end "\n"; # Add newline after commit message
8157 set curdiffstart [$ctext index "end - 1c"]
8158 lappend ctext_file_names ""
8159 if {$currdiffsubmod != $fname} {
8160 lappend ctext_file_lines $fname
8161 makediffhdr $fname $ids
8162 set currdiffsubmod $fname
8163 $ctext insert end "\n$line\n" filesep
8164 } else {
8165 $ctext insert end "$line\n" filesep
8167 } elseif {![string compare -length 3 " >" $line]} {
8168 set $currdiffsubmod ""
8169 set line [encoding convertfrom $diffencoding $line]
8170 $ctext insert end "$line\n" dresult
8171 } elseif {![string compare -length 3 " <" $line]} {
8172 set $currdiffsubmod ""
8173 set line [encoding convertfrom $diffencoding $line]
8174 $ctext insert end "$line\n" d0
8175 } elseif {$diffinhdr} {
8176 if {![string compare -length 12 "rename from " $line]} {
8177 set fname [string range $line [expr 6 + [string first " from " $line] ] end]
8178 if {[string index $fname 0] eq "\""} {
8179 set fname [lindex $fname 0]
8181 set fname [encoding convertfrom $fname]
8182 set i [lsearch -exact $treediffs($ids) $fname]
8183 if {$i >= 0} {
8184 setinlist difffilestart $i $curdiffstart
8186 } elseif {![string compare -length 10 $line "rename to "] ||
8187 ![string compare -length 8 $line "copy to "]} {
8188 set fname [string range $line [expr 4 + [string first " to " $line] ] end]
8189 if {[string index $fname 0] eq "\""} {
8190 set fname [lindex $fname 0]
8192 makediffhdr $fname $ids
8193 } elseif {[string compare -length 3 $line "---"] == 0} {
8194 # do nothing
8195 return
8196 } elseif {[string compare -length 3 $line "+++"] == 0} {
8197 set diffinhdr 0
8198 return
8200 $ctext insert end "$line\n" filesep
8202 } else {
8203 set line [string map {\x1A ^Z} \
8204 [encoding convertfrom $diffencoding $line]]
8205 # parse the prefix - one ' ', '-' or '+' for each parent
8206 set prefix [string range $line 0 [expr {$diffnparents - 1}]]
8207 set tag [expr {$diffnparents > 1? "m": "d"}]
8208 set dowords [expr {$worddiff ne [mc "Line diff"] && $diffnparents == 1}]
8209 set words_pre_markup ""
8210 set words_post_markup ""
8211 if {[string trim $prefix " -+"] eq {}} {
8212 # prefix only has " ", "-" and "+" in it: normal diff line
8213 set num [string first "-" $prefix]
8214 if {$dowords} {
8215 set line [string range $line 1 end]
8217 if {$num >= 0} {
8218 # removed line, first parent with line is $num
8219 if {$num >= $mergemax} {
8220 set num "max"
8222 if {$dowords && $worddiff eq [mc "Markup words"]} {
8223 $ctext insert end "\[-$line-\]" $tag$num
8224 } else {
8225 $ctext insert end "$line" $tag$num
8227 if {!$dowords} {
8228 $ctext insert end "\n" $tag$num
8230 } else {
8231 set tags {}
8232 if {[string first "+" $prefix] >= 0} {
8233 # added line
8234 lappend tags ${tag}result
8235 if {$diffnparents > 1} {
8236 set num [string first " " $prefix]
8237 if {$num >= 0} {
8238 if {$num >= $mergemax} {
8239 set num "max"
8241 lappend tags m$num
8244 set words_pre_markup "{+"
8245 set words_post_markup "+}"
8247 if {$targetline ne {}} {
8248 if {$diffline == $targetline} {
8249 set diffseehere [$ctext index "end - 1 chars"]
8250 set targetline {}
8251 } else {
8252 incr diffline
8255 if {$dowords && $worddiff eq [mc "Markup words"]} {
8256 $ctext insert end "$words_pre_markup$line$words_post_markup" $tags
8257 } else {
8258 $ctext insert end "$line" $tags
8260 if {!$dowords} {
8261 $ctext insert end "\n" $tags
8264 } elseif {$dowords && $prefix eq "~"} {
8265 $ctext insert end "\n" {}
8266 } else {
8267 # "\ No newline at end of file",
8268 # or something else we don't recognize
8269 $ctext insert end "$line\n" hunksep
8274 proc changediffdisp {} {
8275 global ctext diffelide
8277 $ctext tag conf d0 -elide [lindex $diffelide 0]
8278 $ctext tag conf dresult -elide [lindex $diffelide 1]
8281 proc highlightfile {cline} {
8282 global cflist cflist_top
8284 if {![info exists cflist_top]} return
8286 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
8287 $cflist tag add highlight $cline.0 "$cline.0 lineend"
8288 $cflist see $cline.0
8289 set cflist_top $cline
8292 proc highlightfile_for_scrollpos {topidx} {
8293 global cmitmode difffilestart
8295 if {$cmitmode eq "tree"} return
8296 if {![info exists difffilestart]} return
8298 set top [lindex [split $topidx .] 0]
8299 if {$difffilestart eq {} || $top < [lindex $difffilestart 0]} {
8300 highlightfile 0
8301 } else {
8302 highlightfile [expr {[bsearch $difffilestart $top] + 2}]
8306 proc prevfile {} {
8307 global difffilestart ctext cmitmode
8309 if {$cmitmode eq "tree"} return
8310 set prev 0.0
8311 set here [$ctext index @0,0]
8312 foreach loc $difffilestart {
8313 if {[$ctext compare $loc >= $here]} {
8314 $ctext yview $prev
8315 return
8317 set prev $loc
8319 $ctext yview $prev
8322 proc nextfile {} {
8323 global difffilestart ctext cmitmode
8325 if {$cmitmode eq "tree"} return
8326 set here [$ctext index @0,0]
8327 foreach loc $difffilestart {
8328 if {[$ctext compare $loc > $here]} {
8329 $ctext yview $loc
8330 return
8335 proc clear_ctext {{first 1.0}} {
8336 global ctext smarktop smarkbot
8337 global ctext_file_names ctext_file_lines
8338 global pendinglinks
8340 set l [lindex [split $first .] 0]
8341 if {![info exists smarktop] || [$ctext compare $first < $smarktop.0]} {
8342 set smarktop $l
8344 if {![info exists smarkbot] || [$ctext compare $first < $smarkbot.0]} {
8345 set smarkbot $l
8347 $ctext delete $first end
8348 if {$first eq "1.0"} {
8349 unset -nocomplain pendinglinks
8351 set ctext_file_names {}
8352 set ctext_file_lines {}
8355 proc settabs {{firstab {}}} {
8356 global firsttabstop tabstop ctext have_tk85
8358 if {$firstab ne {} && $have_tk85} {
8359 set firsttabstop $firstab
8361 set w [font measure textfont "0"]
8362 if {$firsttabstop != 0} {
8363 $ctext conf -tabs [list [expr {($firsttabstop + $tabstop) * $w}] \
8364 [expr {($firsttabstop + 2 * $tabstop) * $w}]]
8365 } elseif {$have_tk85 || $tabstop != 8} {
8366 $ctext conf -tabs [expr {$tabstop * $w}]
8367 } else {
8368 $ctext conf -tabs {}
8372 proc incrsearch {name ix op} {
8373 global ctext searchstring searchdirn
8375 if {[catch {$ctext index anchor}]} {
8376 # no anchor set, use start of selection, or of visible area
8377 set sel [$ctext tag ranges sel]
8378 if {$sel ne {}} {
8379 $ctext mark set anchor [lindex $sel 0]
8380 } elseif {$searchdirn eq "-forwards"} {
8381 $ctext mark set anchor @0,0
8382 } else {
8383 $ctext mark set anchor @0,[winfo height $ctext]
8386 if {$searchstring ne {}} {
8387 set here [$ctext search -count mlen $searchdirn -- $searchstring anchor]
8388 if {$here ne {}} {
8389 $ctext see $here
8390 set mend "$here + $mlen c"
8391 $ctext tag remove sel 1.0 end
8392 $ctext tag add sel $here $mend
8393 suppress_highlighting_file_for_current_scrollpos
8394 highlightfile_for_scrollpos $here
8397 rehighlight_search_results
8400 proc dosearch {} {
8401 global sstring ctext searchstring searchdirn
8403 focus $sstring
8404 $sstring icursor end
8405 set searchdirn -forwards
8406 if {$searchstring ne {}} {
8407 set sel [$ctext tag ranges sel]
8408 if {$sel ne {}} {
8409 set start "[lindex $sel 0] + 1c"
8410 } elseif {[catch {set start [$ctext index anchor]}]} {
8411 set start "@0,0"
8413 set match [$ctext search -count mlen -- $searchstring $start]
8414 $ctext tag remove sel 1.0 end
8415 if {$match eq {}} {
8416 bell
8417 return
8419 $ctext see $match
8420 suppress_highlighting_file_for_current_scrollpos
8421 highlightfile_for_scrollpos $match
8422 set mend "$match + $mlen c"
8423 $ctext tag add sel $match $mend
8424 $ctext mark unset anchor
8425 rehighlight_search_results
8429 proc dosearchback {} {
8430 global sstring ctext searchstring searchdirn
8432 focus $sstring
8433 $sstring icursor end
8434 set searchdirn -backwards
8435 if {$searchstring ne {}} {
8436 set sel [$ctext tag ranges sel]
8437 if {$sel ne {}} {
8438 set start [lindex $sel 0]
8439 } elseif {[catch {set start [$ctext index anchor]}]} {
8440 set start @0,[winfo height $ctext]
8442 set match [$ctext search -backwards -count ml -- $searchstring $start]
8443 $ctext tag remove sel 1.0 end
8444 if {$match eq {}} {
8445 bell
8446 return
8448 $ctext see $match
8449 suppress_highlighting_file_for_current_scrollpos
8450 highlightfile_for_scrollpos $match
8451 set mend "$match + $ml c"
8452 $ctext tag add sel $match $mend
8453 $ctext mark unset anchor
8454 rehighlight_search_results
8458 proc rehighlight_search_results {} {
8459 global ctext searchstring
8461 $ctext tag remove found 1.0 end
8462 $ctext tag remove currentsearchhit 1.0 end
8464 if {$searchstring ne {}} {
8465 searchmarkvisible 1
8469 proc searchmark {first last} {
8470 global ctext searchstring
8472 set sel [$ctext tag ranges sel]
8474 set mend $first.0
8475 while {1} {
8476 set match [$ctext search -count mlen -- $searchstring $mend $last.end]
8477 if {$match eq {}} break
8478 set mend "$match + $mlen c"
8479 if {$sel ne {} && [$ctext compare $match == [lindex $sel 0]]} {
8480 $ctext tag add currentsearchhit $match $mend
8481 } else {
8482 $ctext tag add found $match $mend
8487 proc searchmarkvisible {doall} {
8488 global ctext smarktop smarkbot
8490 set topline [lindex [split [$ctext index @0,0] .] 0]
8491 set botline [lindex [split [$ctext index @0,[winfo height $ctext]] .] 0]
8492 if {$doall || $botline < $smarktop || $topline > $smarkbot} {
8493 # no overlap with previous
8494 searchmark $topline $botline
8495 set smarktop $topline
8496 set smarkbot $botline
8497 } else {
8498 if {$topline < $smarktop} {
8499 searchmark $topline [expr {$smarktop-1}]
8500 set smarktop $topline
8502 if {$botline > $smarkbot} {
8503 searchmark [expr {$smarkbot+1}] $botline
8504 set smarkbot $botline
8509 proc suppress_highlighting_file_for_current_scrollpos {} {
8510 global ctext suppress_highlighting_file_for_this_scrollpos
8512 set suppress_highlighting_file_for_this_scrollpos [$ctext index @0,0]
8515 proc scrolltext {f0 f1} {
8516 global searchstring cmitmode ctext
8517 global suppress_highlighting_file_for_this_scrollpos
8519 set topidx [$ctext index @0,0]
8520 if {![info exists suppress_highlighting_file_for_this_scrollpos]
8521 || $topidx ne $suppress_highlighting_file_for_this_scrollpos} {
8522 highlightfile_for_scrollpos $topidx
8525 unset -nocomplain suppress_highlighting_file_for_this_scrollpos
8527 .bleft.bottom.sb set $f0 $f1
8528 if {$searchstring ne {}} {
8529 searchmarkvisible 0
8533 proc setcoords {} {
8534 global linespc charspc canvx0 canvy0
8535 global xspc1 xspc2 lthickness
8537 set linespc [font metrics mainfont -linespace]
8538 set charspc [font measure mainfont "m"]
8539 set canvy0 [expr {int(3 + 0.5 * $linespc)}]
8540 set canvx0 [expr {int(3 + 0.5 * $linespc)}]
8541 set lthickness [expr {int($linespc / 9) + 1}]
8542 set xspc1(0) $linespc
8543 set xspc2 $linespc
8546 proc redisplay {} {
8547 global canv
8548 global selectedline
8550 set ymax [lindex [$canv cget -scrollregion] 3]
8551 if {$ymax eq {} || $ymax == 0} return
8552 set span [$canv yview]
8553 clear_display
8554 setcanvscroll
8555 allcanvs yview moveto [lindex $span 0]
8556 drawvisible
8557 if {$selectedline ne {}} {
8558 selectline $selectedline 0
8559 allcanvs yview moveto [lindex $span 0]
8563 proc parsefont {f n} {
8564 global fontattr
8566 set fontattr($f,family) [lindex $n 0]
8567 set s [lindex $n 1]
8568 if {$s eq {} || $s == 0} {
8569 set s 10
8570 } elseif {$s < 0} {
8571 set s [expr {int(-$s / [winfo fpixels . 1p] + 0.5)}]
8573 set fontattr($f,size) $s
8574 set fontattr($f,weight) normal
8575 set fontattr($f,slant) roman
8576 foreach style [lrange $n 2 end] {
8577 switch -- $style {
8578 "normal" -
8579 "bold" {set fontattr($f,weight) $style}
8580 "roman" -
8581 "italic" {set fontattr($f,slant) $style}
8586 proc fontflags {f {isbold 0}} {
8587 global fontattr
8589 return [list -family $fontattr($f,family) -size $fontattr($f,size) \
8590 -weight [expr {$isbold? "bold": $fontattr($f,weight)}] \
8591 -slant $fontattr($f,slant)]
8594 proc fontname {f} {
8595 global fontattr
8597 set n [list $fontattr($f,family) $fontattr($f,size)]
8598 if {$fontattr($f,weight) eq "bold"} {
8599 lappend n "bold"
8601 if {$fontattr($f,slant) eq "italic"} {
8602 lappend n "italic"
8604 return $n
8607 proc incrfont {inc} {
8608 global mainfont textfont ctext canv cflist showrefstop
8609 global stopped entries fontattr
8611 unmarkmatches
8612 set s $fontattr(mainfont,size)
8613 incr s $inc
8614 if {$s < 1} {
8615 set s 1
8617 set fontattr(mainfont,size) $s
8618 font config mainfont -size $s
8619 font config mainfontbold -size $s
8620 set mainfont [fontname mainfont]
8621 set s $fontattr(textfont,size)
8622 incr s $inc
8623 if {$s < 1} {
8624 set s 1
8626 set fontattr(textfont,size) $s
8627 font config textfont -size $s
8628 font config textfontbold -size $s
8629 set textfont [fontname textfont]
8630 setcoords
8631 settabs
8632 redisplay
8635 proc clearsha1 {} {
8636 global sha1entry sha1string
8637 if {[string length $sha1string] == 40} {
8638 $sha1entry delete 0 end
8642 proc sha1change {n1 n2 op} {
8643 global sha1string currentid sha1but
8644 if {$sha1string == {}
8645 || ([info exists currentid] && $sha1string == $currentid)} {
8646 set state disabled
8647 } else {
8648 set state normal
8650 if {[$sha1but cget -state] == $state} return
8651 if {$state == "normal"} {
8652 $sha1but conf -state normal -relief raised -text "[mc "Goto:"] "
8653 } else {
8654 $sha1but conf -state disabled -relief flat -text "[mc "SHA1 ID:"] "
8658 proc gotocommit {} {
8659 global sha1string tagids headids curview varcid
8661 if {$sha1string == {}
8662 || ([info exists currentid] && $sha1string == $currentid)} return
8663 if {[info exists tagids($sha1string)]} {
8664 set id $tagids($sha1string)
8665 } elseif {[info exists headids($sha1string)]} {
8666 set id $headids($sha1string)
8667 } else {
8668 set id [string tolower $sha1string]
8669 if {[regexp {^[0-9a-f]{4,39}$} $id]} {
8670 set matches [longid $id]
8671 if {$matches ne {}} {
8672 if {[llength $matches] > 1} {
8673 error_popup [mc "Short SHA1 id %s is ambiguous" $id]
8674 return
8676 set id [lindex $matches 0]
8678 } else {
8679 if {[catch {set id [exec git rev-parse --verify $sha1string]}]} {
8680 error_popup [mc "Revision %s is not known" $sha1string]
8681 return
8685 if {[commitinview $id $curview]} {
8686 selectline [rowofcommit $id] 1
8687 return
8689 if {[regexp {^[0-9a-fA-F]{4,}$} $sha1string]} {
8690 set msg [mc "SHA1 id %s is not known" $sha1string]
8691 } else {
8692 set msg [mc "Revision %s is not in the current view" $sha1string]
8694 error_popup $msg
8697 proc lineenter {x y id} {
8698 global hoverx hovery hoverid hovertimer
8699 global commitinfo canv
8701 if {![info exists commitinfo($id)] && ![getcommit $id]} return
8702 set hoverx $x
8703 set hovery $y
8704 set hoverid $id
8705 if {[info exists hovertimer]} {
8706 after cancel $hovertimer
8708 set hovertimer [after 500 linehover]
8709 $canv delete hover
8712 proc linemotion {x y id} {
8713 global hoverx hovery hoverid hovertimer
8715 if {[info exists hoverid] && $id == $hoverid} {
8716 set hoverx $x
8717 set hovery $y
8718 if {[info exists hovertimer]} {
8719 after cancel $hovertimer
8721 set hovertimer [after 500 linehover]
8725 proc lineleave {id} {
8726 global hoverid hovertimer canv
8728 if {[info exists hoverid] && $id == $hoverid} {
8729 $canv delete hover
8730 if {[info exists hovertimer]} {
8731 after cancel $hovertimer
8732 unset hovertimer
8734 unset hoverid
8738 proc linehover {} {
8739 global hoverx hovery hoverid hovertimer
8740 global canv linespc lthickness
8741 global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor
8743 global commitinfo
8745 set text [lindex $commitinfo($hoverid) 0]
8746 set ymax [lindex [$canv cget -scrollregion] 3]
8747 if {$ymax == {}} return
8748 set yfrac [lindex [$canv yview] 0]
8749 set x [expr {$hoverx + 2 * $linespc}]
8750 set y [expr {$hovery + $yfrac * $ymax - $linespc / 2}]
8751 set x0 [expr {$x - 2 * $lthickness}]
8752 set y0 [expr {$y - 2 * $lthickness}]
8753 set x1 [expr {$x + [font measure mainfont $text] + 2 * $lthickness}]
8754 set y1 [expr {$y + $linespc + 2 * $lthickness}]
8755 set t [$canv create rectangle $x0 $y0 $x1 $y1 \
8756 -fill $linehoverbgcolor -outline $linehoveroutlinecolor \
8757 -width 1 -tags hover]
8758 $canv raise $t
8759 set t [$canv create text $x $y -anchor nw -text $text -tags hover \
8760 -font mainfont -fill $linehoverfgcolor]
8761 $canv raise $t
8764 proc clickisonarrow {id y} {
8765 global lthickness
8767 set ranges [rowranges $id]
8768 set thresh [expr {2 * $lthickness + 6}]
8769 set n [expr {[llength $ranges] - 1}]
8770 for {set i 1} {$i < $n} {incr i} {
8771 set row [lindex $ranges $i]
8772 if {abs([yc $row] - $y) < $thresh} {
8773 return $i
8776 return {}
8779 proc arrowjump {id n y} {
8780 global canv
8782 # 1 <-> 2, 3 <-> 4, etc...
8783 set n [expr {(($n - 1) ^ 1) + 1}]
8784 set row [lindex [rowranges $id] $n]
8785 set yt [yc $row]
8786 set ymax [lindex [$canv cget -scrollregion] 3]
8787 if {$ymax eq {} || $ymax <= 0} return
8788 set view [$canv yview]
8789 set yspan [expr {[lindex $view 1] - [lindex $view 0]}]
8790 set yfrac [expr {$yt / $ymax - $yspan / 2}]
8791 if {$yfrac < 0} {
8792 set yfrac 0
8794 allcanvs yview moveto $yfrac
8797 proc lineclick {x y id isnew} {
8798 global ctext commitinfo children canv thickerline curview
8800 if {![info exists commitinfo($id)] && ![getcommit $id]} return
8801 unmarkmatches
8802 unselectline
8803 normalline
8804 $canv delete hover
8805 # draw this line thicker than normal
8806 set thickerline $id
8807 drawlines $id
8808 if {$isnew} {
8809 set ymax [lindex [$canv cget -scrollregion] 3]
8810 if {$ymax eq {}} return
8811 set yfrac [lindex [$canv yview] 0]
8812 set y [expr {$y + $yfrac * $ymax}]
8814 set dirn [clickisonarrow $id $y]
8815 if {$dirn ne {}} {
8816 arrowjump $id $dirn $y
8817 return
8820 if {$isnew} {
8821 addtohistory [list lineclick $x $y $id 0] savectextpos
8823 # fill the details pane with info about this line
8824 $ctext conf -state normal
8825 clear_ctext
8826 settabs 0
8827 $ctext insert end "[mc "Parent"]:\t"
8828 $ctext insert end $id link0
8829 setlink $id link0
8830 set info $commitinfo($id)
8831 $ctext insert end "\n\t[lindex $info 0]\n"
8832 $ctext insert end "\t[mc "Author"]:\t[lindex $info 1]\n"
8833 set date [formatdate [lindex $info 2]]
8834 $ctext insert end "\t[mc "Date"]:\t$date\n"
8835 set kids $children($curview,$id)
8836 if {$kids ne {}} {
8837 $ctext insert end "\n[mc "Children"]:"
8838 set i 0
8839 foreach child $kids {
8840 incr i
8841 if {![info exists commitinfo($child)] && ![getcommit $child]} continue
8842 set info $commitinfo($child)
8843 $ctext insert end "\n\t"
8844 $ctext insert end $child link$i
8845 setlink $child link$i
8846 $ctext insert end "\n\t[lindex $info 0]"
8847 $ctext insert end "\n\t[mc "Author"]:\t[lindex $info 1]"
8848 set date [formatdate [lindex $info 2]]
8849 $ctext insert end "\n\t[mc "Date"]:\t$date\n"
8852 maybe_scroll_ctext 1
8853 $ctext conf -state disabled
8854 init_flist {}
8857 proc normalline {} {
8858 global thickerline
8859 if {[info exists thickerline]} {
8860 set id $thickerline
8861 unset thickerline
8862 drawlines $id
8866 proc selbyid {id {isnew 1}} {
8867 global curview
8868 if {[commitinview $id $curview]} {
8869 selectline [rowofcommit $id] $isnew
8873 proc mstime {} {
8874 global startmstime
8875 if {![info exists startmstime]} {
8876 set startmstime [clock clicks -milliseconds]
8878 return [format "%.3f" [expr {([clock click -milliseconds] - $startmstime) / 1000.0}]]
8881 proc rowmenu {x y id} {
8882 global rowctxmenu selectedline rowmenuid curview
8883 global nullid nullid2 fakerowmenu mainhead markedid
8885 stopfinding
8886 set rowmenuid $id
8887 if {$selectedline eq {} || [rowofcommit $id] eq $selectedline} {
8888 set state disabled
8889 } else {
8890 set state normal
8892 if {[info exists markedid] && $markedid ne $id} {
8893 set mstate normal
8894 } else {
8895 set mstate disabled
8897 if {$id ne $nullid && $id ne $nullid2} {
8898 set menu $rowctxmenu
8899 if {$mainhead ne {}} {
8900 $menu entryconfigure 8 -label [mc "Reset %s branch to here" $mainhead] -state normal
8901 } else {
8902 $menu entryconfigure 8 -label [mc "Detached head: can't reset" $mainhead] -state disabled
8904 $menu entryconfigure 10 -state $mstate
8905 $menu entryconfigure 11 -state $mstate
8906 $menu entryconfigure 12 -state $mstate
8907 } else {
8908 set menu $fakerowmenu
8910 $menu entryconfigure [mca "Diff this -> selected"] -state $state
8911 $menu entryconfigure [mca "Diff selected -> this"] -state $state
8912 $menu entryconfigure [mca "Make patch"] -state $state
8913 $menu entryconfigure [mca "Diff this -> marked commit"] -state $mstate
8914 $menu entryconfigure [mca "Diff marked commit -> this"] -state $mstate
8915 tk_popup $menu $x $y
8918 proc markhere {} {
8919 global rowmenuid markedid canv
8921 set markedid $rowmenuid
8922 make_idmark $markedid
8925 proc gotomark {} {
8926 global markedid
8928 if {[info exists markedid]} {
8929 selbyid $markedid
8933 proc replace_by_kids {l r} {
8934 global curview children
8936 set id [commitonrow $r]
8937 set l [lreplace $l 0 0]
8938 foreach kid $children($curview,$id) {
8939 lappend l [rowofcommit $kid]
8941 return [lsort -integer -decreasing -unique $l]
8944 proc find_common_desc {} {
8945 global markedid rowmenuid curview children
8947 if {![info exists markedid]} return
8948 if {![commitinview $markedid $curview] ||
8949 ![commitinview $rowmenuid $curview]} return
8950 #set t1 [clock clicks -milliseconds]
8951 set l1 [list [rowofcommit $markedid]]
8952 set l2 [list [rowofcommit $rowmenuid]]
8953 while 1 {
8954 set r1 [lindex $l1 0]
8955 set r2 [lindex $l2 0]
8956 if {$r1 eq {} || $r2 eq {}} break
8957 if {$r1 == $r2} {
8958 selectline $r1 1
8959 break
8961 if {$r1 > $r2} {
8962 set l1 [replace_by_kids $l1 $r1]
8963 } else {
8964 set l2 [replace_by_kids $l2 $r2]
8967 #set t2 [clock clicks -milliseconds]
8968 #puts "took [expr {$t2-$t1}]ms"
8971 proc compare_commits {} {
8972 global markedid rowmenuid curview children
8974 if {![info exists markedid]} return
8975 if {![commitinview $markedid $curview]} return
8976 addtohistory [list do_cmp_commits $markedid $rowmenuid]
8977 do_cmp_commits $markedid $rowmenuid
8980 proc getpatchid {id} {
8981 global patchids
8983 if {![info exists patchids($id)]} {
8984 set cmd [diffcmd [list $id] {-p --root}]
8985 # trim off the initial "|"
8986 set cmd [lrange $cmd 1 end]
8987 if {[catch {
8988 set x [eval exec $cmd | git patch-id]
8989 set patchids($id) [lindex $x 0]
8990 }]} {
8991 set patchids($id) "error"
8994 return $patchids($id)
8997 proc do_cmp_commits {a b} {
8998 global ctext curview parents children patchids commitinfo
9000 $ctext conf -state normal
9001 clear_ctext
9002 init_flist {}
9003 for {set i 0} {$i < 100} {incr i} {
9004 set skipa 0
9005 set skipb 0
9006 if {[llength $parents($curview,$a)] > 1} {
9007 appendshortlink $a [mc "Skipping merge commit "] "\n"
9008 set skipa 1
9009 } else {
9010 set patcha [getpatchid $a]
9012 if {[llength $parents($curview,$b)] > 1} {
9013 appendshortlink $b [mc "Skipping merge commit "] "\n"
9014 set skipb 1
9015 } else {
9016 set patchb [getpatchid $b]
9018 if {!$skipa && !$skipb} {
9019 set heada [lindex $commitinfo($a) 0]
9020 set headb [lindex $commitinfo($b) 0]
9021 if {$patcha eq "error"} {
9022 appendshortlink $a [mc "Error getting patch ID for "] \
9023 [mc " - stopping\n"]
9024 break
9026 if {$patchb eq "error"} {
9027 appendshortlink $b [mc "Error getting patch ID for "] \
9028 [mc " - stopping\n"]
9029 break
9031 if {$patcha eq $patchb} {
9032 if {$heada eq $headb} {
9033 appendshortlink $a [mc "Commit "]
9034 appendshortlink $b " == " " $heada\n"
9035 } else {
9036 appendshortlink $a [mc "Commit "] " $heada\n"
9037 appendshortlink $b [mc " is the same patch as\n "] \
9038 " $headb\n"
9040 set skipa 1
9041 set skipb 1
9042 } else {
9043 $ctext insert end "\n"
9044 appendshortlink $a [mc "Commit "] " $heada\n"
9045 appendshortlink $b [mc " differs from\n "] \
9046 " $headb\n"
9047 $ctext insert end [mc "Diff of commits:\n\n"]
9048 $ctext conf -state disabled
9049 update
9050 diffcommits $a $b
9051 return
9054 if {$skipa} {
9055 set kids [real_children $curview,$a]
9056 if {[llength $kids] != 1} {
9057 $ctext insert end "\n"
9058 appendshortlink $a [mc "Commit "] \
9059 [mc " has %s children - stopping\n" [llength $kids]]
9060 break
9062 set a [lindex $kids 0]
9064 if {$skipb} {
9065 set kids [real_children $curview,$b]
9066 if {[llength $kids] != 1} {
9067 appendshortlink $b [mc "Commit "] \
9068 [mc " has %s children - stopping\n" [llength $kids]]
9069 break
9071 set b [lindex $kids 0]
9074 $ctext conf -state disabled
9077 proc diffcommits {a b} {
9078 global diffcontext diffids blobdifffd diffinhdr currdiffsubmod
9080 set tmpdir [gitknewtmpdir]
9081 set fna [file join $tmpdir "commit-[string range $a 0 7]"]
9082 set fnb [file join $tmpdir "commit-[string range $b 0 7]"]
9083 if {[catch {
9084 exec git diff-tree -p --pretty $a >$fna
9085 exec git diff-tree -p --pretty $b >$fnb
9086 } err]} {
9087 error_popup [mc "Error writing commit to file: %s" $err]
9088 return
9090 if {[catch {
9091 set fd [open "| diff -U$diffcontext $fna $fnb" r]
9092 } err]} {
9093 error_popup [mc "Error diffing commits: %s" $err]
9094 return
9096 set diffids [list commits $a $b]
9097 set blobdifffd($diffids) $fd
9098 set diffinhdr 0
9099 set currdiffsubmod ""
9100 filerun $fd [list getblobdiffline $fd $diffids]
9103 proc diffvssel {dirn} {
9104 global rowmenuid selectedline
9106 if {$selectedline eq {}} return
9107 if {$dirn} {
9108 set oldid [commitonrow $selectedline]
9109 set newid $rowmenuid
9110 } else {
9111 set oldid $rowmenuid
9112 set newid [commitonrow $selectedline]
9114 addtohistory [list doseldiff $oldid $newid] savectextpos
9115 doseldiff $oldid $newid
9118 proc diffvsmark {dirn} {
9119 global rowmenuid markedid
9121 if {![info exists markedid]} return
9122 if {$dirn} {
9123 set oldid $markedid
9124 set newid $rowmenuid
9125 } else {
9126 set oldid $rowmenuid
9127 set newid $markedid
9129 addtohistory [list doseldiff $oldid $newid] savectextpos
9130 doseldiff $oldid $newid
9133 proc doseldiff {oldid newid} {
9134 global ctext
9135 global commitinfo
9137 $ctext conf -state normal
9138 clear_ctext
9139 init_flist [mc "Top"]
9140 $ctext insert end "[mc "From"] "
9141 $ctext insert end $oldid link0
9142 setlink $oldid link0
9143 $ctext insert end "\n "
9144 $ctext insert end [lindex $commitinfo($oldid) 0]
9145 $ctext insert end "\n\n[mc "To"] "
9146 $ctext insert end $newid link1
9147 setlink $newid link1
9148 $ctext insert end "\n "
9149 $ctext insert end [lindex $commitinfo($newid) 0]
9150 $ctext insert end "\n"
9151 $ctext conf -state disabled
9152 $ctext tag remove found 1.0 end
9153 startdiff [list $oldid $newid]
9156 proc mkpatch {} {
9157 global rowmenuid currentid commitinfo patchtop patchnum NS
9159 if {![info exists currentid]} return
9160 set oldid $currentid
9161 set oldhead [lindex $commitinfo($oldid) 0]
9162 set newid $rowmenuid
9163 set newhead [lindex $commitinfo($newid) 0]
9164 set top .patch
9165 set patchtop $top
9166 catch {destroy $top}
9167 ttk_toplevel $top
9168 make_transient $top .
9169 ${NS}::label $top.title -text [mc "Generate patch"]
9170 grid $top.title - -pady 10
9171 ${NS}::label $top.from -text [mc "From:"]
9172 ${NS}::entry $top.fromsha1 -width 40
9173 $top.fromsha1 insert 0 $oldid
9174 $top.fromsha1 conf -state readonly
9175 grid $top.from $top.fromsha1 -sticky w
9176 ${NS}::entry $top.fromhead -width 60
9177 $top.fromhead insert 0 $oldhead
9178 $top.fromhead conf -state readonly
9179 grid x $top.fromhead -sticky w
9180 ${NS}::label $top.to -text [mc "To:"]
9181 ${NS}::entry $top.tosha1 -width 40
9182 $top.tosha1 insert 0 $newid
9183 $top.tosha1 conf -state readonly
9184 grid $top.to $top.tosha1 -sticky w
9185 ${NS}::entry $top.tohead -width 60
9186 $top.tohead insert 0 $newhead
9187 $top.tohead conf -state readonly
9188 grid x $top.tohead -sticky w
9189 ${NS}::button $top.rev -text [mc "Reverse"] -command mkpatchrev
9190 grid $top.rev x -pady 10 -padx 5
9191 ${NS}::label $top.flab -text [mc "Output file:"]
9192 ${NS}::entry $top.fname -width 60
9193 $top.fname insert 0 [file normalize "patch$patchnum.patch"]
9194 incr patchnum
9195 grid $top.flab $top.fname -sticky w
9196 ${NS}::frame $top.buts
9197 ${NS}::button $top.buts.gen -text [mc "Generate"] -command mkpatchgo
9198 ${NS}::button $top.buts.can -text [mc "Cancel"] -command mkpatchcan
9199 bind $top <Key-Return> mkpatchgo
9200 bind $top <Key-Escape> mkpatchcan
9201 grid $top.buts.gen $top.buts.can
9202 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9203 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9204 grid $top.buts - -pady 10 -sticky ew
9205 focus $top.fname
9208 proc mkpatchrev {} {
9209 global patchtop
9211 set oldid [$patchtop.fromsha1 get]
9212 set oldhead [$patchtop.fromhead get]
9213 set newid [$patchtop.tosha1 get]
9214 set newhead [$patchtop.tohead get]
9215 foreach e [list fromsha1 fromhead tosha1 tohead] \
9216 v [list $newid $newhead $oldid $oldhead] {
9217 $patchtop.$e conf -state normal
9218 $patchtop.$e delete 0 end
9219 $patchtop.$e insert 0 $v
9220 $patchtop.$e conf -state readonly
9224 proc mkpatchgo {} {
9225 global patchtop nullid nullid2
9227 set oldid [$patchtop.fromsha1 get]
9228 set newid [$patchtop.tosha1 get]
9229 set fname [$patchtop.fname get]
9230 set cmd [diffcmd [list $oldid $newid] -p]
9231 # trim off the initial "|"
9232 set cmd [lrange $cmd 1 end]
9233 lappend cmd >$fname &
9234 if {[catch {eval exec $cmd} err]} {
9235 error_popup "[mc "Error creating patch:"] $err" $patchtop
9237 catch {destroy $patchtop}
9238 unset patchtop
9241 proc mkpatchcan {} {
9242 global patchtop
9244 catch {destroy $patchtop}
9245 unset patchtop
9248 proc mktag {} {
9249 global rowmenuid mktagtop commitinfo NS
9251 set top .maketag
9252 set mktagtop $top
9253 catch {destroy $top}
9254 ttk_toplevel $top
9255 make_transient $top .
9256 ${NS}::label $top.title -text [mc "Create tag"]
9257 grid $top.title - -pady 10
9258 ${NS}::label $top.id -text [mc "ID:"]
9259 ${NS}::entry $top.sha1 -width 40
9260 $top.sha1 insert 0 $rowmenuid
9261 $top.sha1 conf -state readonly
9262 grid $top.id $top.sha1 -sticky w
9263 ${NS}::entry $top.head -width 60
9264 $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9265 $top.head conf -state readonly
9266 grid x $top.head -sticky w
9267 ${NS}::label $top.tlab -text [mc "Tag name:"]
9268 ${NS}::entry $top.tag -width 60
9269 grid $top.tlab $top.tag -sticky w
9270 ${NS}::label $top.op -text [mc "Tag message is optional"]
9271 grid $top.op -columnspan 2 -sticky we
9272 ${NS}::label $top.mlab -text [mc "Tag message:"]
9273 ${NS}::entry $top.msg -width 60
9274 grid $top.mlab $top.msg -sticky w
9275 ${NS}::frame $top.buts
9276 ${NS}::button $top.buts.gen -text [mc "Create"] -command mktaggo
9277 ${NS}::button $top.buts.can -text [mc "Cancel"] -command mktagcan
9278 bind $top <Key-Return> mktaggo
9279 bind $top <Key-Escape> mktagcan
9280 grid $top.buts.gen $top.buts.can
9281 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9282 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9283 grid $top.buts - -pady 10 -sticky ew
9284 focus $top.tag
9287 proc domktag {} {
9288 global mktagtop env tagids idtags
9290 set id [$mktagtop.sha1 get]
9291 set tag [$mktagtop.tag get]
9292 set msg [$mktagtop.msg get]
9293 if {$tag == {}} {
9294 error_popup [mc "No tag name specified"] $mktagtop
9295 return 0
9297 if {[info exists tagids($tag)]} {
9298 error_popup [mc "Tag \"%s\" already exists" $tag] $mktagtop
9299 return 0
9301 if {[catch {
9302 if {$msg != {}} {
9303 exec git tag -a -m $msg $tag $id
9304 } else {
9305 exec git tag $tag $id
9307 } err]} {
9308 error_popup "[mc "Error creating tag:"] $err" $mktagtop
9309 return 0
9312 set tagids($tag) $id
9313 lappend idtags($id) $tag
9314 redrawtags $id
9315 addedtag $id
9316 dispneartags 0
9317 run refill_reflist
9318 return 1
9321 proc redrawtags {id} {
9322 global canv linehtag idpos currentid curview cmitlisted markedid
9323 global canvxmax iddrawn circleitem mainheadid circlecolors
9324 global mainheadcirclecolor
9326 if {![commitinview $id $curview]} return
9327 if {![info exists iddrawn($id)]} return
9328 set row [rowofcommit $id]
9329 if {$id eq $mainheadid} {
9330 set ofill $mainheadcirclecolor
9331 } else {
9332 set ofill [lindex $circlecolors $cmitlisted($curview,$id)]
9334 $canv itemconf $circleitem($row) -fill $ofill
9335 $canv delete tag.$id
9336 set xt [eval drawtags $id $idpos($id)]
9337 $canv coords $linehtag($id) $xt [lindex $idpos($id) 2]
9338 set text [$canv itemcget $linehtag($id) -text]
9339 set font [$canv itemcget $linehtag($id) -font]
9340 set xr [expr {$xt + [font measure $font $text]}]
9341 if {$xr > $canvxmax} {
9342 set canvxmax $xr
9343 setcanvscroll
9345 if {[info exists currentid] && $currentid == $id} {
9346 make_secsel $id
9348 if {[info exists markedid] && $markedid eq $id} {
9349 make_idmark $id
9353 proc mktagcan {} {
9354 global mktagtop
9356 catch {destroy $mktagtop}
9357 unset mktagtop
9360 proc mktaggo {} {
9361 if {![domktag]} return
9362 mktagcan
9365 proc copysummary {} {
9366 global rowmenuid autosellen
9368 set format "%h (\"%s\", %ad)"
9369 set cmd [list git show -s --pretty=format:$format --date=short]
9370 if {$autosellen < 40} {
9371 lappend cmd --abbrev=$autosellen
9373 set summary [eval exec $cmd $rowmenuid]
9375 clipboard clear
9376 clipboard append $summary
9379 proc writecommit {} {
9380 global rowmenuid wrcomtop commitinfo wrcomcmd NS
9382 set top .writecommit
9383 set wrcomtop $top
9384 catch {destroy $top}
9385 ttk_toplevel $top
9386 make_transient $top .
9387 ${NS}::label $top.title -text [mc "Write commit to file"]
9388 grid $top.title - -pady 10
9389 ${NS}::label $top.id -text [mc "ID:"]
9390 ${NS}::entry $top.sha1 -width 40
9391 $top.sha1 insert 0 $rowmenuid
9392 $top.sha1 conf -state readonly
9393 grid $top.id $top.sha1 -sticky w
9394 ${NS}::entry $top.head -width 60
9395 $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9396 $top.head conf -state readonly
9397 grid x $top.head -sticky w
9398 ${NS}::label $top.clab -text [mc "Command:"]
9399 ${NS}::entry $top.cmd -width 60 -textvariable wrcomcmd
9400 grid $top.clab $top.cmd -sticky w -pady 10
9401 ${NS}::label $top.flab -text [mc "Output file:"]
9402 ${NS}::entry $top.fname -width 60
9403 $top.fname insert 0 [file normalize "commit-[string range $rowmenuid 0 6]"]
9404 grid $top.flab $top.fname -sticky w
9405 ${NS}::frame $top.buts
9406 ${NS}::button $top.buts.gen -text [mc "Write"] -command wrcomgo
9407 ${NS}::button $top.buts.can -text [mc "Cancel"] -command wrcomcan
9408 bind $top <Key-Return> wrcomgo
9409 bind $top <Key-Escape> wrcomcan
9410 grid $top.buts.gen $top.buts.can
9411 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9412 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9413 grid $top.buts - -pady 10 -sticky ew
9414 focus $top.fname
9417 proc wrcomgo {} {
9418 global wrcomtop
9420 set id [$wrcomtop.sha1 get]
9421 set cmd "echo $id | [$wrcomtop.cmd get]"
9422 set fname [$wrcomtop.fname get]
9423 if {[catch {exec sh -c $cmd >$fname &} err]} {
9424 error_popup "[mc "Error writing commit:"] $err" $wrcomtop
9426 catch {destroy $wrcomtop}
9427 unset wrcomtop
9430 proc wrcomcan {} {
9431 global wrcomtop
9433 catch {destroy $wrcomtop}
9434 unset wrcomtop
9437 proc mkbranch {} {
9438 global rowmenuid mkbrtop NS
9440 set top .makebranch
9441 catch {destroy $top}
9442 ttk_toplevel $top
9443 make_transient $top .
9444 ${NS}::label $top.title -text [mc "Create new branch"]
9445 grid $top.title - -pady 10
9446 ${NS}::label $top.id -text [mc "ID:"]
9447 ${NS}::entry $top.sha1 -width 40
9448 $top.sha1 insert 0 $rowmenuid
9449 $top.sha1 conf -state readonly
9450 grid $top.id $top.sha1 -sticky w
9451 ${NS}::label $top.nlab -text [mc "Name:"]
9452 ${NS}::entry $top.name -width 40
9453 grid $top.nlab $top.name -sticky w
9454 ${NS}::frame $top.buts
9455 ${NS}::button $top.buts.go -text [mc "Create"] -command [list mkbrgo $top]
9456 ${NS}::button $top.buts.can -text [mc "Cancel"] -command "catch {destroy $top}"
9457 bind $top <Key-Return> [list mkbrgo $top]
9458 bind $top <Key-Escape> "catch {destroy $top}"
9459 grid $top.buts.go $top.buts.can
9460 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9461 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9462 grid $top.buts - -pady 10 -sticky ew
9463 focus $top.name
9466 proc mkbrgo {top} {
9467 global headids idheads
9469 set name [$top.name get]
9470 set id [$top.sha1 get]
9471 set cmdargs {}
9472 set old_id {}
9473 if {$name eq {}} {
9474 error_popup [mc "Please specify a name for the new branch"] $top
9475 return
9477 if {[info exists headids($name)]} {
9478 if {![confirm_popup [mc \
9479 "Branch '%s' already exists. Overwrite?" $name] $top]} {
9480 return
9482 set old_id $headids($name)
9483 lappend cmdargs -f
9485 catch {destroy $top}
9486 lappend cmdargs $name $id
9487 nowbusy newbranch
9488 update
9489 if {[catch {
9490 eval exec git branch $cmdargs
9491 } err]} {
9492 notbusy newbranch
9493 error_popup $err
9494 } else {
9495 notbusy newbranch
9496 if {$old_id ne {}} {
9497 movehead $id $name
9498 movedhead $id $name
9499 redrawtags $old_id
9500 redrawtags $id
9501 } else {
9502 set headids($name) $id
9503 lappend idheads($id) $name
9504 addedhead $id $name
9505 redrawtags $id
9507 dispneartags 0
9508 run refill_reflist
9512 proc exec_citool {tool_args {baseid {}}} {
9513 global commitinfo env
9515 set save_env [array get env GIT_AUTHOR_*]
9517 if {$baseid ne {}} {
9518 if {![info exists commitinfo($baseid)]} {
9519 getcommit $baseid
9521 set author [lindex $commitinfo($baseid) 1]
9522 set date [lindex $commitinfo($baseid) 2]
9523 if {[regexp {^\s*(\S.*\S|\S)\s*<(.*)>\s*$} \
9524 $author author name email]
9525 && $date ne {}} {
9526 set env(GIT_AUTHOR_NAME) $name
9527 set env(GIT_AUTHOR_EMAIL) $email
9528 set env(GIT_AUTHOR_DATE) $date
9532 eval exec git citool $tool_args &
9534 array unset env GIT_AUTHOR_*
9535 array set env $save_env
9538 proc cherrypick {} {
9539 global rowmenuid curview
9540 global mainhead mainheadid
9541 global gitdir
9543 set oldhead [exec git rev-parse HEAD]
9544 set dheads [descheads $rowmenuid]
9545 if {$dheads ne {} && [lsearch -exact $dheads $oldhead] >= 0} {
9546 set ok [confirm_popup [mc "Commit %s is already\
9547 included in branch %s -- really re-apply it?" \
9548 [string range $rowmenuid 0 7] $mainhead]]
9549 if {!$ok} return
9551 nowbusy cherrypick [mc "Cherry-picking"]
9552 update
9553 # Unfortunately git-cherry-pick writes stuff to stderr even when
9554 # no error occurs, and exec takes that as an indication of error...
9555 if {[catch {exec sh -c "git cherry-pick -r $rowmenuid 2>&1"} err]} {
9556 notbusy cherrypick
9557 if {[regexp -line \
9558 {Entry '(.*)' (would be overwritten by merge|not uptodate)} \
9559 $err msg fname]} {
9560 error_popup [mc "Cherry-pick failed because of local changes\
9561 to file '%s'.\nPlease commit, reset or stash\
9562 your changes and try again." $fname]
9563 } elseif {[regexp -line \
9564 {^(CONFLICT \(.*\):|Automatic cherry-pick failed|error: could not apply)} \
9565 $err]} {
9566 if {[confirm_popup [mc "Cherry-pick failed because of merge\
9567 conflict.\nDo you wish to run git citool to\
9568 resolve it?"]]} {
9569 # Force citool to read MERGE_MSG
9570 file delete [file join $gitdir "GITGUI_MSG"]
9571 exec_citool {} $rowmenuid
9573 } else {
9574 error_popup $err
9576 run updatecommits
9577 return
9579 set newhead [exec git rev-parse HEAD]
9580 if {$newhead eq $oldhead} {
9581 notbusy cherrypick
9582 error_popup [mc "No changes committed"]
9583 return
9585 addnewchild $newhead $oldhead
9586 if {[commitinview $oldhead $curview]} {
9587 # XXX this isn't right if we have a path limit...
9588 insertrow $newhead $oldhead $curview
9589 if {$mainhead ne {}} {
9590 movehead $newhead $mainhead
9591 movedhead $newhead $mainhead
9593 set mainheadid $newhead
9594 redrawtags $oldhead
9595 redrawtags $newhead
9596 selbyid $newhead
9598 notbusy cherrypick
9601 proc revert {} {
9602 global rowmenuid curview
9603 global mainhead mainheadid
9604 global gitdir
9606 set oldhead [exec git rev-parse HEAD]
9607 set dheads [descheads $rowmenuid]
9608 if { $dheads eq {} || [lsearch -exact $dheads $oldhead] == -1 } {
9609 set ok [confirm_popup [mc "Commit %s is not\
9610 included in branch %s -- really revert it?" \
9611 [string range $rowmenuid 0 7] $mainhead]]
9612 if {!$ok} return
9614 nowbusy revert [mc "Reverting"]
9615 update
9617 if [catch {exec git revert --no-edit $rowmenuid} err] {
9618 notbusy revert
9619 if [regexp {files would be overwritten by merge:(\n(( |\t)+[^\n]+\n)+)}\
9620 $err match files] {
9621 regsub {\n( |\t)+} $files "\n" files
9622 error_popup [mc "Revert failed because of local changes to\
9623 the following files:%s Please commit, reset or stash \
9624 your changes and try again." $files]
9625 } elseif [regexp {error: could not revert} $err] {
9626 if [confirm_popup [mc "Revert failed because of merge conflict.\n\
9627 Do you wish to run git citool to resolve it?"]] {
9628 # Force citool to read MERGE_MSG
9629 file delete [file join $gitdir "GITGUI_MSG"]
9630 exec_citool {} $rowmenuid
9632 } else { error_popup $err }
9633 run updatecommits
9634 return
9637 set newhead [exec git rev-parse HEAD]
9638 if { $newhead eq $oldhead } {
9639 notbusy revert
9640 error_popup [mc "No changes committed"]
9641 return
9644 addnewchild $newhead $oldhead
9646 if [commitinview $oldhead $curview] {
9647 # XXX this isn't right if we have a path limit...
9648 insertrow $newhead $oldhead $curview
9649 if {$mainhead ne {}} {
9650 movehead $newhead $mainhead
9651 movedhead $newhead $mainhead
9653 set mainheadid $newhead
9654 redrawtags $oldhead
9655 redrawtags $newhead
9656 selbyid $newhead
9659 notbusy revert
9662 proc resethead {} {
9663 global mainhead rowmenuid confirm_ok resettype NS
9665 set confirm_ok 0
9666 set w ".confirmreset"
9667 ttk_toplevel $w
9668 make_transient $w .
9669 wm title $w [mc "Confirm reset"]
9670 ${NS}::label $w.m -text \
9671 [mc "Reset branch %s to %s?" $mainhead [string range $rowmenuid 0 7]]
9672 pack $w.m -side top -fill x -padx 20 -pady 20
9673 ${NS}::labelframe $w.f -text [mc "Reset type:"]
9674 set resettype mixed
9675 ${NS}::radiobutton $w.f.soft -value soft -variable resettype \
9676 -text [mc "Soft: Leave working tree and index untouched"]
9677 grid $w.f.soft -sticky w
9678 ${NS}::radiobutton $w.f.mixed -value mixed -variable resettype \
9679 -text [mc "Mixed: Leave working tree untouched, reset index"]
9680 grid $w.f.mixed -sticky w
9681 ${NS}::radiobutton $w.f.hard -value hard -variable resettype \
9682 -text [mc "Hard: Reset working tree and index\n(discard ALL local changes)"]
9683 grid $w.f.hard -sticky w
9684 pack $w.f -side top -fill x -padx 4
9685 ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
9686 pack $w.ok -side left -fill x -padx 20 -pady 20
9687 ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
9688 bind $w <Key-Escape> [list destroy $w]
9689 pack $w.cancel -side right -fill x -padx 20 -pady 20
9690 bind $w <Visibility> "grab $w; focus $w"
9691 tkwait window $w
9692 if {!$confirm_ok} return
9693 if {[catch {set fd [open \
9694 [list | git reset --$resettype $rowmenuid 2>@1] r]} err]} {
9695 error_popup $err
9696 } else {
9697 dohidelocalchanges
9698 filerun $fd [list readresetstat $fd]
9699 nowbusy reset [mc "Resetting"]
9700 selbyid $rowmenuid
9704 proc readresetstat {fd} {
9705 global mainhead mainheadid showlocalchanges rprogcoord
9707 if {[gets $fd line] >= 0} {
9708 if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9709 set rprogcoord [expr {1.0 * $m / $n}]
9710 adjustprogress
9712 return 1
9714 set rprogcoord 0
9715 adjustprogress
9716 notbusy reset
9717 if {[catch {close $fd} err]} {
9718 error_popup $err
9720 set oldhead $mainheadid
9721 set newhead [exec git rev-parse HEAD]
9722 if {$newhead ne $oldhead} {
9723 movehead $newhead $mainhead
9724 movedhead $newhead $mainhead
9725 set mainheadid $newhead
9726 redrawtags $oldhead
9727 redrawtags $newhead
9729 if {$showlocalchanges} {
9730 doshowlocalchanges
9732 return 0
9735 # context menu for a head
9736 proc headmenu {x y id head} {
9737 global headmenuid headmenuhead headctxmenu mainhead
9739 stopfinding
9740 set headmenuid $id
9741 set headmenuhead $head
9742 set state normal
9743 if {[string match "remotes/*" $head]} {
9744 set state disabled
9746 if {$head eq $mainhead} {
9747 set state disabled
9749 $headctxmenu entryconfigure 0 -state $state
9750 $headctxmenu entryconfigure 1 -state $state
9751 tk_popup $headctxmenu $x $y
9754 proc cobranch {} {
9755 global headmenuid headmenuhead headids
9756 global showlocalchanges
9758 # check the tree is clean first??
9759 nowbusy checkout [mc "Checking out"]
9760 update
9761 dohidelocalchanges
9762 if {[catch {
9763 set fd [open [list | git checkout $headmenuhead 2>@1] r]
9764 } err]} {
9765 notbusy checkout
9766 error_popup $err
9767 if {$showlocalchanges} {
9768 dodiffindex
9770 } else {
9771 filerun $fd [list readcheckoutstat $fd $headmenuhead $headmenuid]
9775 proc readcheckoutstat {fd newhead newheadid} {
9776 global mainhead mainheadid headids showlocalchanges progresscoords
9777 global viewmainheadid curview
9779 if {[gets $fd line] >= 0} {
9780 if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9781 set progresscoords [list 0 [expr {1.0 * $m / $n}]]
9782 adjustprogress
9784 return 1
9786 set progresscoords {0 0}
9787 adjustprogress
9788 notbusy checkout
9789 if {[catch {close $fd} err]} {
9790 error_popup $err
9792 set oldmainid $mainheadid
9793 set mainhead $newhead
9794 set mainheadid $newheadid
9795 set viewmainheadid($curview) $newheadid
9796 redrawtags $oldmainid
9797 redrawtags $newheadid
9798 selbyid $newheadid
9799 if {$showlocalchanges} {
9800 dodiffindex
9804 proc rmbranch {} {
9805 global headmenuid headmenuhead mainhead
9806 global idheads
9808 set head $headmenuhead
9809 set id $headmenuid
9810 # this check shouldn't be needed any more...
9811 if {$head eq $mainhead} {
9812 error_popup [mc "Cannot delete the currently checked-out branch"]
9813 return
9815 set dheads [descheads $id]
9816 if {[llength $dheads] == 1 && $idheads($dheads) eq $head} {
9817 # the stuff on this branch isn't on any other branch
9818 if {![confirm_popup [mc "The commits on branch %s aren't on any other\
9819 branch.\nReally delete branch %s?" $head $head]]} return
9821 nowbusy rmbranch
9822 update
9823 if {[catch {exec git branch -D $head} err]} {
9824 notbusy rmbranch
9825 error_popup $err
9826 return
9828 removehead $id $head
9829 removedhead $id $head
9830 redrawtags $id
9831 notbusy rmbranch
9832 dispneartags 0
9833 run refill_reflist
9836 # Display a list of tags and heads
9837 proc showrefs {} {
9838 global showrefstop bgcolor fgcolor selectbgcolor NS
9839 global bglist fglist reflistfilter reflist maincursor
9841 set top .showrefs
9842 set showrefstop $top
9843 if {[winfo exists $top]} {
9844 raise $top
9845 refill_reflist
9846 return
9848 ttk_toplevel $top
9849 wm title $top [mc "Tags and heads: %s" [file tail [pwd]]]
9850 make_transient $top .
9851 text $top.list -background $bgcolor -foreground $fgcolor \
9852 -selectbackground $selectbgcolor -font mainfont \
9853 -xscrollcommand "$top.xsb set" -yscrollcommand "$top.ysb set" \
9854 -width 30 -height 20 -cursor $maincursor \
9855 -spacing1 1 -spacing3 1 -state disabled
9856 $top.list tag configure highlight -background $selectbgcolor
9857 if {![lsearch -exact $bglist $top.list]} {
9858 lappend bglist $top.list
9859 lappend fglist $top.list
9861 ${NS}::scrollbar $top.ysb -command "$top.list yview" -orient vertical
9862 ${NS}::scrollbar $top.xsb -command "$top.list xview" -orient horizontal
9863 grid $top.list $top.ysb -sticky nsew
9864 grid $top.xsb x -sticky ew
9865 ${NS}::frame $top.f
9866 ${NS}::label $top.f.l -text "[mc "Filter"]: "
9867 ${NS}::entry $top.f.e -width 20 -textvariable reflistfilter
9868 set reflistfilter "*"
9869 trace add variable reflistfilter write reflistfilter_change
9870 pack $top.f.e -side right -fill x -expand 1
9871 pack $top.f.l -side left
9872 grid $top.f - -sticky ew -pady 2
9873 ${NS}::button $top.close -command [list destroy $top] -text [mc "Close"]
9874 bind $top <Key-Escape> [list destroy $top]
9875 grid $top.close -
9876 grid columnconfigure $top 0 -weight 1
9877 grid rowconfigure $top 0 -weight 1
9878 bind $top.list <1> {break}
9879 bind $top.list <B1-Motion> {break}
9880 bind $top.list <ButtonRelease-1> {sel_reflist %W %x %y; break}
9881 set reflist {}
9882 refill_reflist
9885 proc sel_reflist {w x y} {
9886 global showrefstop reflist headids tagids otherrefids
9888 if {![winfo exists $showrefstop]} return
9889 set l [lindex [split [$w index "@$x,$y"] "."] 0]
9890 set ref [lindex $reflist [expr {$l-1}]]
9891 set n [lindex $ref 0]
9892 switch -- [lindex $ref 1] {
9893 "H" {selbyid $headids($n)}
9894 "T" {selbyid $tagids($n)}
9895 "o" {selbyid $otherrefids($n)}
9897 $showrefstop.list tag add highlight $l.0 "$l.0 lineend"
9900 proc unsel_reflist {} {
9901 global showrefstop
9903 if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9904 $showrefstop.list tag remove highlight 0.0 end
9907 proc reflistfilter_change {n1 n2 op} {
9908 global reflistfilter
9910 after cancel refill_reflist
9911 after 200 refill_reflist
9914 proc refill_reflist {} {
9915 global reflist reflistfilter showrefstop headids tagids otherrefids
9916 global curview
9918 if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9919 set refs {}
9920 foreach n [array names headids] {
9921 if {[string match $reflistfilter $n]} {
9922 if {[commitinview $headids($n) $curview]} {
9923 lappend refs [list $n H]
9924 } else {
9925 interestedin $headids($n) {run refill_reflist}
9929 foreach n [array names tagids] {
9930 if {[string match $reflistfilter $n]} {
9931 if {[commitinview $tagids($n) $curview]} {
9932 lappend refs [list $n T]
9933 } else {
9934 interestedin $tagids($n) {run refill_reflist}
9938 foreach n [array names otherrefids] {
9939 if {[string match $reflistfilter $n]} {
9940 if {[commitinview $otherrefids($n) $curview]} {
9941 lappend refs [list $n o]
9942 } else {
9943 interestedin $otherrefids($n) {run refill_reflist}
9947 set refs [lsort -index 0 $refs]
9948 if {$refs eq $reflist} return
9950 # Update the contents of $showrefstop.list according to the
9951 # differences between $reflist (old) and $refs (new)
9952 $showrefstop.list conf -state normal
9953 $showrefstop.list insert end "\n"
9954 set i 0
9955 set j 0
9956 while {$i < [llength $reflist] || $j < [llength $refs]} {
9957 if {$i < [llength $reflist]} {
9958 if {$j < [llength $refs]} {
9959 set cmp [string compare [lindex $reflist $i 0] \
9960 [lindex $refs $j 0]]
9961 if {$cmp == 0} {
9962 set cmp [string compare [lindex $reflist $i 1] \
9963 [lindex $refs $j 1]]
9965 } else {
9966 set cmp -1
9968 } else {
9969 set cmp 1
9971 switch -- $cmp {
9972 -1 {
9973 $showrefstop.list delete "[expr {$j+1}].0" "[expr {$j+2}].0"
9974 incr i
9977 incr i
9978 incr j
9981 set l [expr {$j + 1}]
9982 $showrefstop.list image create $l.0 -align baseline \
9983 -image reficon-[lindex $refs $j 1] -padx 2
9984 $showrefstop.list insert $l.1 "[lindex $refs $j 0]\n"
9985 incr j
9989 set reflist $refs
9990 # delete last newline
9991 $showrefstop.list delete end-2c end-1c
9992 $showrefstop.list conf -state disabled
9995 # Stuff for finding nearby tags
9996 proc getallcommits {} {
9997 global allcommits nextarc seeds allccache allcwait cachedarcs allcupdate
9998 global idheads idtags idotherrefs allparents tagobjid
9999 global gitdir
10001 if {![info exists allcommits]} {
10002 set nextarc 0
10003 set allcommits 0
10004 set seeds {}
10005 set allcwait 0
10006 set cachedarcs 0
10007 set allccache [file join $gitdir "gitk.cache"]
10008 if {![catch {
10009 set f [open $allccache r]
10010 set allcwait 1
10011 getcache $f
10012 }]} return
10015 if {$allcwait} {
10016 return
10018 set cmd [list | git rev-list --parents]
10019 set allcupdate [expr {$seeds ne {}}]
10020 if {!$allcupdate} {
10021 set ids "--all"
10022 } else {
10023 set refs [concat [array names idheads] [array names idtags] \
10024 [array names idotherrefs]]
10025 set ids {}
10026 set tagobjs {}
10027 foreach name [array names tagobjid] {
10028 lappend tagobjs $tagobjid($name)
10030 foreach id [lsort -unique $refs] {
10031 if {![info exists allparents($id)] &&
10032 [lsearch -exact $tagobjs $id] < 0} {
10033 lappend ids $id
10036 if {$ids ne {}} {
10037 foreach id $seeds {
10038 lappend ids "^$id"
10042 if {$ids ne {}} {
10043 set fd [open [concat $cmd $ids] r]
10044 fconfigure $fd -blocking 0
10045 incr allcommits
10046 nowbusy allcommits
10047 filerun $fd [list getallclines $fd]
10048 } else {
10049 dispneartags 0
10053 # Since most commits have 1 parent and 1 child, we group strings of
10054 # such commits into "arcs" joining branch/merge points (BMPs), which
10055 # are commits that either don't have 1 parent or don't have 1 child.
10057 # arcnos(id) - incoming arcs for BMP, arc we're on for other nodes
10058 # arcout(id) - outgoing arcs for BMP
10059 # arcids(a) - list of IDs on arc including end but not start
10060 # arcstart(a) - BMP ID at start of arc
10061 # arcend(a) - BMP ID at end of arc
10062 # growing(a) - arc a is still growing
10063 # arctags(a) - IDs out of arcids (excluding end) that have tags
10064 # archeads(a) - IDs out of arcids (excluding end) that have heads
10065 # The start of an arc is at the descendent end, so "incoming" means
10066 # coming from descendents, and "outgoing" means going towards ancestors.
10068 proc getallclines {fd} {
10069 global allparents allchildren idtags idheads nextarc
10070 global arcnos arcids arctags arcout arcend arcstart archeads growing
10071 global seeds allcommits cachedarcs allcupdate
10073 set nid 0
10074 while {[incr nid] <= 1000 && [gets $fd line] >= 0} {
10075 set id [lindex $line 0]
10076 if {[info exists allparents($id)]} {
10077 # seen it already
10078 continue
10080 set cachedarcs 0
10081 set olds [lrange $line 1 end]
10082 set allparents($id) $olds
10083 if {![info exists allchildren($id)]} {
10084 set allchildren($id) {}
10085 set arcnos($id) {}
10086 lappend seeds $id
10087 } else {
10088 set a $arcnos($id)
10089 if {[llength $olds] == 1 && [llength $a] == 1} {
10090 lappend arcids($a) $id
10091 if {[info exists idtags($id)]} {
10092 lappend arctags($a) $id
10094 if {[info exists idheads($id)]} {
10095 lappend archeads($a) $id
10097 if {[info exists allparents($olds)]} {
10098 # seen parent already
10099 if {![info exists arcout($olds)]} {
10100 splitarc $olds
10102 lappend arcids($a) $olds
10103 set arcend($a) $olds
10104 unset growing($a)
10106 lappend allchildren($olds) $id
10107 lappend arcnos($olds) $a
10108 continue
10111 foreach a $arcnos($id) {
10112 lappend arcids($a) $id
10113 set arcend($a) $id
10114 unset growing($a)
10117 set ao {}
10118 foreach p $olds {
10119 lappend allchildren($p) $id
10120 set a [incr nextarc]
10121 set arcstart($a) $id
10122 set archeads($a) {}
10123 set arctags($a) {}
10124 set archeads($a) {}
10125 set arcids($a) {}
10126 lappend ao $a
10127 set growing($a) 1
10128 if {[info exists allparents($p)]} {
10129 # seen it already, may need to make a new branch
10130 if {![info exists arcout($p)]} {
10131 splitarc $p
10133 lappend arcids($a) $p
10134 set arcend($a) $p
10135 unset growing($a)
10137 lappend arcnos($p) $a
10139 set arcout($id) $ao
10141 if {$nid > 0} {
10142 global cached_dheads cached_dtags cached_atags
10143 unset -nocomplain cached_dheads
10144 unset -nocomplain cached_dtags
10145 unset -nocomplain cached_atags
10147 if {![eof $fd]} {
10148 return [expr {$nid >= 1000? 2: 1}]
10150 set cacheok 1
10151 if {[catch {
10152 fconfigure $fd -blocking 1
10153 close $fd
10154 } err]} {
10155 # got an error reading the list of commits
10156 # if we were updating, try rereading the whole thing again
10157 if {$allcupdate} {
10158 incr allcommits -1
10159 dropcache $err
10160 return
10162 error_popup "[mc "Error reading commit topology information;\
10163 branch and preceding/following tag information\
10164 will be incomplete."]\n($err)"
10165 set cacheok 0
10167 if {[incr allcommits -1] == 0} {
10168 notbusy allcommits
10169 if {$cacheok} {
10170 run savecache
10173 dispneartags 0
10174 return 0
10177 proc recalcarc {a} {
10178 global arctags archeads arcids idtags idheads
10180 set at {}
10181 set ah {}
10182 foreach id [lrange $arcids($a) 0 end-1] {
10183 if {[info exists idtags($id)]} {
10184 lappend at $id
10186 if {[info exists idheads($id)]} {
10187 lappend ah $id
10190 set arctags($a) $at
10191 set archeads($a) $ah
10194 proc splitarc {p} {
10195 global arcnos arcids nextarc arctags archeads idtags idheads
10196 global arcstart arcend arcout allparents growing
10198 set a $arcnos($p)
10199 if {[llength $a] != 1} {
10200 puts "oops splitarc called but [llength $a] arcs already"
10201 return
10203 set a [lindex $a 0]
10204 set i [lsearch -exact $arcids($a) $p]
10205 if {$i < 0} {
10206 puts "oops splitarc $p not in arc $a"
10207 return
10209 set na [incr nextarc]
10210 if {[info exists arcend($a)]} {
10211 set arcend($na) $arcend($a)
10212 } else {
10213 set l [lindex $allparents([lindex $arcids($a) end]) 0]
10214 set j [lsearch -exact $arcnos($l) $a]
10215 set arcnos($l) [lreplace $arcnos($l) $j $j $na]
10217 set tail [lrange $arcids($a) [expr {$i+1}] end]
10218 set arcids($a) [lrange $arcids($a) 0 $i]
10219 set arcend($a) $p
10220 set arcstart($na) $p
10221 set arcout($p) $na
10222 set arcids($na) $tail
10223 if {[info exists growing($a)]} {
10224 set growing($na) 1
10225 unset growing($a)
10228 foreach id $tail {
10229 if {[llength $arcnos($id)] == 1} {
10230 set arcnos($id) $na
10231 } else {
10232 set j [lsearch -exact $arcnos($id) $a]
10233 set arcnos($id) [lreplace $arcnos($id) $j $j $na]
10237 # reconstruct tags and heads lists
10238 if {$arctags($a) ne {} || $archeads($a) ne {}} {
10239 recalcarc $a
10240 recalcarc $na
10241 } else {
10242 set arctags($na) {}
10243 set archeads($na) {}
10247 # Update things for a new commit added that is a child of one
10248 # existing commit. Used when cherry-picking.
10249 proc addnewchild {id p} {
10250 global allparents allchildren idtags nextarc
10251 global arcnos arcids arctags arcout arcend arcstart archeads growing
10252 global seeds allcommits
10254 if {![info exists allcommits] || ![info exists arcnos($p)]} return
10255 set allparents($id) [list $p]
10256 set allchildren($id) {}
10257 set arcnos($id) {}
10258 lappend seeds $id
10259 lappend allchildren($p) $id
10260 set a [incr nextarc]
10261 set arcstart($a) $id
10262 set archeads($a) {}
10263 set arctags($a) {}
10264 set arcids($a) [list $p]
10265 set arcend($a) $p
10266 if {![info exists arcout($p)]} {
10267 splitarc $p
10269 lappend arcnos($p) $a
10270 set arcout($id) [list $a]
10273 # This implements a cache for the topology information.
10274 # The cache saves, for each arc, the start and end of the arc,
10275 # the ids on the arc, and the outgoing arcs from the end.
10276 proc readcache {f} {
10277 global arcnos arcids arcout arcstart arcend arctags archeads nextarc
10278 global idtags idheads allparents cachedarcs possible_seeds seeds growing
10279 global allcwait
10281 set a $nextarc
10282 set lim $cachedarcs
10283 if {$lim - $a > 500} {
10284 set lim [expr {$a + 500}]
10286 if {[catch {
10287 if {$a == $lim} {
10288 # finish reading the cache and setting up arctags, etc.
10289 set line [gets $f]
10290 if {$line ne "1"} {error "bad final version"}
10291 close $f
10292 foreach id [array names idtags] {
10293 if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10294 [llength $allparents($id)] == 1} {
10295 set a [lindex $arcnos($id) 0]
10296 if {$arctags($a) eq {}} {
10297 recalcarc $a
10301 foreach id [array names idheads] {
10302 if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10303 [llength $allparents($id)] == 1} {
10304 set a [lindex $arcnos($id) 0]
10305 if {$archeads($a) eq {}} {
10306 recalcarc $a
10310 foreach id [lsort -unique $possible_seeds] {
10311 if {$arcnos($id) eq {}} {
10312 lappend seeds $id
10315 set allcwait 0
10316 } else {
10317 while {[incr a] <= $lim} {
10318 set line [gets $f]
10319 if {[llength $line] != 3} {error "bad line"}
10320 set s [lindex $line 0]
10321 set arcstart($a) $s
10322 lappend arcout($s) $a
10323 if {![info exists arcnos($s)]} {
10324 lappend possible_seeds $s
10325 set arcnos($s) {}
10327 set e [lindex $line 1]
10328 if {$e eq {}} {
10329 set growing($a) 1
10330 } else {
10331 set arcend($a) $e
10332 if {![info exists arcout($e)]} {
10333 set arcout($e) {}
10336 set arcids($a) [lindex $line 2]
10337 foreach id $arcids($a) {
10338 lappend allparents($s) $id
10339 set s $id
10340 lappend arcnos($id) $a
10342 if {![info exists allparents($s)]} {
10343 set allparents($s) {}
10345 set arctags($a) {}
10346 set archeads($a) {}
10348 set nextarc [expr {$a - 1}]
10350 } err]} {
10351 dropcache $err
10352 return 0
10354 if {!$allcwait} {
10355 getallcommits
10357 return $allcwait
10360 proc getcache {f} {
10361 global nextarc cachedarcs possible_seeds
10363 if {[catch {
10364 set line [gets $f]
10365 if {[llength $line] != 2 || [lindex $line 0] ne "1"} {error "bad version"}
10366 # make sure it's an integer
10367 set cachedarcs [expr {int([lindex $line 1])}]
10368 if {$cachedarcs < 0} {error "bad number of arcs"}
10369 set nextarc 0
10370 set possible_seeds {}
10371 run readcache $f
10372 } err]} {
10373 dropcache $err
10375 return 0
10378 proc dropcache {err} {
10379 global allcwait nextarc cachedarcs seeds
10381 #puts "dropping cache ($err)"
10382 foreach v {arcnos arcout arcids arcstart arcend growing \
10383 arctags archeads allparents allchildren} {
10384 global $v
10385 unset -nocomplain $v
10387 set allcwait 0
10388 set nextarc 0
10389 set cachedarcs 0
10390 set seeds {}
10391 getallcommits
10394 proc writecache {f} {
10395 global cachearc cachedarcs allccache
10396 global arcstart arcend arcnos arcids arcout
10398 set a $cachearc
10399 set lim $cachedarcs
10400 if {$lim - $a > 1000} {
10401 set lim [expr {$a + 1000}]
10403 if {[catch {
10404 while {[incr a] <= $lim} {
10405 if {[info exists arcend($a)]} {
10406 puts $f [list $arcstart($a) $arcend($a) $arcids($a)]
10407 } else {
10408 puts $f [list $arcstart($a) {} $arcids($a)]
10411 } err]} {
10412 catch {close $f}
10413 catch {file delete $allccache}
10414 #puts "writing cache failed ($err)"
10415 return 0
10417 set cachearc [expr {$a - 1}]
10418 if {$a > $cachedarcs} {
10419 puts $f "1"
10420 close $f
10421 return 0
10423 return 1
10426 proc savecache {} {
10427 global nextarc cachedarcs cachearc allccache
10429 if {$nextarc == $cachedarcs} return
10430 set cachearc 0
10431 set cachedarcs $nextarc
10432 catch {
10433 set f [open $allccache w]
10434 puts $f [list 1 $cachedarcs]
10435 run writecache $f
10439 # Returns 1 if a is an ancestor of b, -1 if b is an ancestor of a,
10440 # or 0 if neither is true.
10441 proc anc_or_desc {a b} {
10442 global arcout arcstart arcend arcnos cached_isanc
10444 if {$arcnos($a) eq $arcnos($b)} {
10445 # Both are on the same arc(s); either both are the same BMP,
10446 # or if one is not a BMP, the other is also not a BMP or is
10447 # the BMP at end of the arc (and it only has 1 incoming arc).
10448 # Or both can be BMPs with no incoming arcs.
10449 if {$a eq $b || $arcnos($a) eq {}} {
10450 return 0
10452 # assert {[llength $arcnos($a)] == 1}
10453 set arc [lindex $arcnos($a) 0]
10454 set i [lsearch -exact $arcids($arc) $a]
10455 set j [lsearch -exact $arcids($arc) $b]
10456 if {$i < 0 || $i > $j} {
10457 return 1
10458 } else {
10459 return -1
10463 if {![info exists arcout($a)]} {
10464 set arc [lindex $arcnos($a) 0]
10465 if {[info exists arcend($arc)]} {
10466 set aend $arcend($arc)
10467 } else {
10468 set aend {}
10470 set a $arcstart($arc)
10471 } else {
10472 set aend $a
10474 if {![info exists arcout($b)]} {
10475 set arc [lindex $arcnos($b) 0]
10476 if {[info exists arcend($arc)]} {
10477 set bend $arcend($arc)
10478 } else {
10479 set bend {}
10481 set b $arcstart($arc)
10482 } else {
10483 set bend $b
10485 if {$a eq $bend} {
10486 return 1
10488 if {$b eq $aend} {
10489 return -1
10491 if {[info exists cached_isanc($a,$bend)]} {
10492 if {$cached_isanc($a,$bend)} {
10493 return 1
10496 if {[info exists cached_isanc($b,$aend)]} {
10497 if {$cached_isanc($b,$aend)} {
10498 return -1
10500 if {[info exists cached_isanc($a,$bend)]} {
10501 return 0
10505 set todo [list $a $b]
10506 set anc($a) a
10507 set anc($b) b
10508 for {set i 0} {$i < [llength $todo]} {incr i} {
10509 set x [lindex $todo $i]
10510 if {$anc($x) eq {}} {
10511 continue
10513 foreach arc $arcnos($x) {
10514 set xd $arcstart($arc)
10515 if {$xd eq $bend} {
10516 set cached_isanc($a,$bend) 1
10517 set cached_isanc($b,$aend) 0
10518 return 1
10519 } elseif {$xd eq $aend} {
10520 set cached_isanc($b,$aend) 1
10521 set cached_isanc($a,$bend) 0
10522 return -1
10524 if {![info exists anc($xd)]} {
10525 set anc($xd) $anc($x)
10526 lappend todo $xd
10527 } elseif {$anc($xd) ne $anc($x)} {
10528 set anc($xd) {}
10532 set cached_isanc($a,$bend) 0
10533 set cached_isanc($b,$aend) 0
10534 return 0
10537 # This identifies whether $desc has an ancestor that is
10538 # a growing tip of the graph and which is not an ancestor of $anc
10539 # and returns 0 if so and 1 if not.
10540 # If we subsequently discover a tag on such a growing tip, and that
10541 # turns out to be a descendent of $anc (which it could, since we
10542 # don't necessarily see children before parents), then $desc
10543 # isn't a good choice to display as a descendent tag of
10544 # $anc (since it is the descendent of another tag which is
10545 # a descendent of $anc). Similarly, $anc isn't a good choice to
10546 # display as a ancestor tag of $desc.
10548 proc is_certain {desc anc} {
10549 global arcnos arcout arcstart arcend growing problems
10551 set certain {}
10552 if {[llength $arcnos($anc)] == 1} {
10553 # tags on the same arc are certain
10554 if {$arcnos($desc) eq $arcnos($anc)} {
10555 return 1
10557 if {![info exists arcout($anc)]} {
10558 # if $anc is partway along an arc, use the start of the arc instead
10559 set a [lindex $arcnos($anc) 0]
10560 set anc $arcstart($a)
10563 if {[llength $arcnos($desc)] > 1 || [info exists arcout($desc)]} {
10564 set x $desc
10565 } else {
10566 set a [lindex $arcnos($desc) 0]
10567 set x $arcend($a)
10569 if {$x == $anc} {
10570 return 1
10572 set anclist [list $x]
10573 set dl($x) 1
10574 set nnh 1
10575 set ngrowanc 0
10576 for {set i 0} {$i < [llength $anclist] && ($nnh > 0 || $ngrowanc > 0)} {incr i} {
10577 set x [lindex $anclist $i]
10578 if {$dl($x)} {
10579 incr nnh -1
10581 set done($x) 1
10582 foreach a $arcout($x) {
10583 if {[info exists growing($a)]} {
10584 if {![info exists growanc($x)] && $dl($x)} {
10585 set growanc($x) 1
10586 incr ngrowanc
10588 } else {
10589 set y $arcend($a)
10590 if {[info exists dl($y)]} {
10591 if {$dl($y)} {
10592 if {!$dl($x)} {
10593 set dl($y) 0
10594 if {![info exists done($y)]} {
10595 incr nnh -1
10597 if {[info exists growanc($x)]} {
10598 incr ngrowanc -1
10600 set xl [list $y]
10601 for {set k 0} {$k < [llength $xl]} {incr k} {
10602 set z [lindex $xl $k]
10603 foreach c $arcout($z) {
10604 if {[info exists arcend($c)]} {
10605 set v $arcend($c)
10606 if {[info exists dl($v)] && $dl($v)} {
10607 set dl($v) 0
10608 if {![info exists done($v)]} {
10609 incr nnh -1
10611 if {[info exists growanc($v)]} {
10612 incr ngrowanc -1
10614 lappend xl $v
10621 } elseif {$y eq $anc || !$dl($x)} {
10622 set dl($y) 0
10623 lappend anclist $y
10624 } else {
10625 set dl($y) 1
10626 lappend anclist $y
10627 incr nnh
10632 foreach x [array names growanc] {
10633 if {$dl($x)} {
10634 return 0
10636 return 0
10638 return 1
10641 proc validate_arctags {a} {
10642 global arctags idtags
10644 set i -1
10645 set na $arctags($a)
10646 foreach id $arctags($a) {
10647 incr i
10648 if {![info exists idtags($id)]} {
10649 set na [lreplace $na $i $i]
10650 incr i -1
10653 set arctags($a) $na
10656 proc validate_archeads {a} {
10657 global archeads idheads
10659 set i -1
10660 set na $archeads($a)
10661 foreach id $archeads($a) {
10662 incr i
10663 if {![info exists idheads($id)]} {
10664 set na [lreplace $na $i $i]
10665 incr i -1
10668 set archeads($a) $na
10671 # Return the list of IDs that have tags that are descendents of id,
10672 # ignoring IDs that are descendents of IDs already reported.
10673 proc desctags {id} {
10674 global arcnos arcstart arcids arctags idtags allparents
10675 global growing cached_dtags
10677 if {![info exists allparents($id)]} {
10678 return {}
10680 set t1 [clock clicks -milliseconds]
10681 set argid $id
10682 if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10683 # part-way along an arc; check that arc first
10684 set a [lindex $arcnos($id) 0]
10685 if {$arctags($a) ne {}} {
10686 validate_arctags $a
10687 set i [lsearch -exact $arcids($a) $id]
10688 set tid {}
10689 foreach t $arctags($a) {
10690 set j [lsearch -exact $arcids($a) $t]
10691 if {$j >= $i} break
10692 set tid $t
10694 if {$tid ne {}} {
10695 return $tid
10698 set id $arcstart($a)
10699 if {[info exists idtags($id)]} {
10700 return $id
10703 if {[info exists cached_dtags($id)]} {
10704 return $cached_dtags($id)
10707 set origid $id
10708 set todo [list $id]
10709 set queued($id) 1
10710 set nc 1
10711 for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10712 set id [lindex $todo $i]
10713 set done($id) 1
10714 set ta [info exists hastaggedancestor($id)]
10715 if {!$ta} {
10716 incr nc -1
10718 # ignore tags on starting node
10719 if {!$ta && $i > 0} {
10720 if {[info exists idtags($id)]} {
10721 set tagloc($id) $id
10722 set ta 1
10723 } elseif {[info exists cached_dtags($id)]} {
10724 set tagloc($id) $cached_dtags($id)
10725 set ta 1
10728 foreach a $arcnos($id) {
10729 set d $arcstart($a)
10730 if {!$ta && $arctags($a) ne {}} {
10731 validate_arctags $a
10732 if {$arctags($a) ne {}} {
10733 lappend tagloc($id) [lindex $arctags($a) end]
10736 if {$ta || $arctags($a) ne {}} {
10737 set tomark [list $d]
10738 for {set j 0} {$j < [llength $tomark]} {incr j} {
10739 set dd [lindex $tomark $j]
10740 if {![info exists hastaggedancestor($dd)]} {
10741 if {[info exists done($dd)]} {
10742 foreach b $arcnos($dd) {
10743 lappend tomark $arcstart($b)
10745 if {[info exists tagloc($dd)]} {
10746 unset tagloc($dd)
10748 } elseif {[info exists queued($dd)]} {
10749 incr nc -1
10751 set hastaggedancestor($dd) 1
10755 if {![info exists queued($d)]} {
10756 lappend todo $d
10757 set queued($d) 1
10758 if {![info exists hastaggedancestor($d)]} {
10759 incr nc
10764 set tags {}
10765 foreach id [array names tagloc] {
10766 if {![info exists hastaggedancestor($id)]} {
10767 foreach t $tagloc($id) {
10768 if {[lsearch -exact $tags $t] < 0} {
10769 lappend tags $t
10774 set t2 [clock clicks -milliseconds]
10775 set loopix $i
10777 # remove tags that are descendents of other tags
10778 for {set i 0} {$i < [llength $tags]} {incr i} {
10779 set a [lindex $tags $i]
10780 for {set j 0} {$j < $i} {incr j} {
10781 set b [lindex $tags $j]
10782 set r [anc_or_desc $a $b]
10783 if {$r == 1} {
10784 set tags [lreplace $tags $j $j]
10785 incr j -1
10786 incr i -1
10787 } elseif {$r == -1} {
10788 set tags [lreplace $tags $i $i]
10789 incr i -1
10790 break
10795 if {[array names growing] ne {}} {
10796 # graph isn't finished, need to check if any tag could get
10797 # eclipsed by another tag coming later. Simply ignore any
10798 # tags that could later get eclipsed.
10799 set ctags {}
10800 foreach t $tags {
10801 if {[is_certain $t $origid]} {
10802 lappend ctags $t
10805 if {$tags eq $ctags} {
10806 set cached_dtags($origid) $tags
10807 } else {
10808 set tags $ctags
10810 } else {
10811 set cached_dtags($origid) $tags
10813 set t3 [clock clicks -milliseconds]
10814 if {0 && $t3 - $t1 >= 100} {
10815 puts "iterating descendents ($loopix/[llength $todo] nodes) took\
10816 [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10818 return $tags
10821 proc anctags {id} {
10822 global arcnos arcids arcout arcend arctags idtags allparents
10823 global growing cached_atags
10825 if {![info exists allparents($id)]} {
10826 return {}
10828 set t1 [clock clicks -milliseconds]
10829 set argid $id
10830 if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10831 # part-way along an arc; check that arc first
10832 set a [lindex $arcnos($id) 0]
10833 if {$arctags($a) ne {}} {
10834 validate_arctags $a
10835 set i [lsearch -exact $arcids($a) $id]
10836 foreach t $arctags($a) {
10837 set j [lsearch -exact $arcids($a) $t]
10838 if {$j > $i} {
10839 return $t
10843 if {![info exists arcend($a)]} {
10844 return {}
10846 set id $arcend($a)
10847 if {[info exists idtags($id)]} {
10848 return $id
10851 if {[info exists cached_atags($id)]} {
10852 return $cached_atags($id)
10855 set origid $id
10856 set todo [list $id]
10857 set queued($id) 1
10858 set taglist {}
10859 set nc 1
10860 for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10861 set id [lindex $todo $i]
10862 set done($id) 1
10863 set td [info exists hastaggeddescendent($id)]
10864 if {!$td} {
10865 incr nc -1
10867 # ignore tags on starting node
10868 if {!$td && $i > 0} {
10869 if {[info exists idtags($id)]} {
10870 set tagloc($id) $id
10871 set td 1
10872 } elseif {[info exists cached_atags($id)]} {
10873 set tagloc($id) $cached_atags($id)
10874 set td 1
10877 foreach a $arcout($id) {
10878 if {!$td && $arctags($a) ne {}} {
10879 validate_arctags $a
10880 if {$arctags($a) ne {}} {
10881 lappend tagloc($id) [lindex $arctags($a) 0]
10884 if {![info exists arcend($a)]} continue
10885 set d $arcend($a)
10886 if {$td || $arctags($a) ne {}} {
10887 set tomark [list $d]
10888 for {set j 0} {$j < [llength $tomark]} {incr j} {
10889 set dd [lindex $tomark $j]
10890 if {![info exists hastaggeddescendent($dd)]} {
10891 if {[info exists done($dd)]} {
10892 foreach b $arcout($dd) {
10893 if {[info exists arcend($b)]} {
10894 lappend tomark $arcend($b)
10897 if {[info exists tagloc($dd)]} {
10898 unset tagloc($dd)
10900 } elseif {[info exists queued($dd)]} {
10901 incr nc -1
10903 set hastaggeddescendent($dd) 1
10907 if {![info exists queued($d)]} {
10908 lappend todo $d
10909 set queued($d) 1
10910 if {![info exists hastaggeddescendent($d)]} {
10911 incr nc
10916 set t2 [clock clicks -milliseconds]
10917 set loopix $i
10918 set tags {}
10919 foreach id [array names tagloc] {
10920 if {![info exists hastaggeddescendent($id)]} {
10921 foreach t $tagloc($id) {
10922 if {[lsearch -exact $tags $t] < 0} {
10923 lappend tags $t
10929 # remove tags that are ancestors of other tags
10930 for {set i 0} {$i < [llength $tags]} {incr i} {
10931 set a [lindex $tags $i]
10932 for {set j 0} {$j < $i} {incr j} {
10933 set b [lindex $tags $j]
10934 set r [anc_or_desc $a $b]
10935 if {$r == -1} {
10936 set tags [lreplace $tags $j $j]
10937 incr j -1
10938 incr i -1
10939 } elseif {$r == 1} {
10940 set tags [lreplace $tags $i $i]
10941 incr i -1
10942 break
10947 if {[array names growing] ne {}} {
10948 # graph isn't finished, need to check if any tag could get
10949 # eclipsed by another tag coming later. Simply ignore any
10950 # tags that could later get eclipsed.
10951 set ctags {}
10952 foreach t $tags {
10953 if {[is_certain $origid $t]} {
10954 lappend ctags $t
10957 if {$tags eq $ctags} {
10958 set cached_atags($origid) $tags
10959 } else {
10960 set tags $ctags
10962 } else {
10963 set cached_atags($origid) $tags
10965 set t3 [clock clicks -milliseconds]
10966 if {0 && $t3 - $t1 >= 100} {
10967 puts "iterating ancestors ($loopix/[llength $todo] nodes) took\
10968 [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10970 return $tags
10973 # Return the list of IDs that have heads that are descendents of id,
10974 # including id itself if it has a head.
10975 proc descheads {id} {
10976 global arcnos arcstart arcids archeads idheads cached_dheads
10977 global allparents arcout
10979 if {![info exists allparents($id)]} {
10980 return {}
10982 set aret {}
10983 if {![info exists arcout($id)]} {
10984 # part-way along an arc; check it first
10985 set a [lindex $arcnos($id) 0]
10986 if {$archeads($a) ne {}} {
10987 validate_archeads $a
10988 set i [lsearch -exact $arcids($a) $id]
10989 foreach t $archeads($a) {
10990 set j [lsearch -exact $arcids($a) $t]
10991 if {$j > $i} break
10992 lappend aret $t
10995 set id $arcstart($a)
10997 set origid $id
10998 set todo [list $id]
10999 set seen($id) 1
11000 set ret {}
11001 for {set i 0} {$i < [llength $todo]} {incr i} {
11002 set id [lindex $todo $i]
11003 if {[info exists cached_dheads($id)]} {
11004 set ret [concat $ret $cached_dheads($id)]
11005 } else {
11006 if {[info exists idheads($id)]} {
11007 lappend ret $id
11009 foreach a $arcnos($id) {
11010 if {$archeads($a) ne {}} {
11011 validate_archeads $a
11012 if {$archeads($a) ne {}} {
11013 set ret [concat $ret $archeads($a)]
11016 set d $arcstart($a)
11017 if {![info exists seen($d)]} {
11018 lappend todo $d
11019 set seen($d) 1
11024 set ret [lsort -unique $ret]
11025 set cached_dheads($origid) $ret
11026 return [concat $ret $aret]
11029 proc addedtag {id} {
11030 global arcnos arcout cached_dtags cached_atags
11032 if {![info exists arcnos($id)]} return
11033 if {![info exists arcout($id)]} {
11034 recalcarc [lindex $arcnos($id) 0]
11036 unset -nocomplain cached_dtags
11037 unset -nocomplain cached_atags
11040 proc addedhead {hid head} {
11041 global arcnos arcout cached_dheads
11043 if {![info exists arcnos($hid)]} return
11044 if {![info exists arcout($hid)]} {
11045 recalcarc [lindex $arcnos($hid) 0]
11047 unset -nocomplain cached_dheads
11050 proc removedhead {hid head} {
11051 global cached_dheads
11053 unset -nocomplain cached_dheads
11056 proc movedhead {hid head} {
11057 global arcnos arcout cached_dheads
11059 if {![info exists arcnos($hid)]} return
11060 if {![info exists arcout($hid)]} {
11061 recalcarc [lindex $arcnos($hid) 0]
11063 unset -nocomplain cached_dheads
11066 proc changedrefs {} {
11067 global cached_dheads cached_dtags cached_atags cached_tagcontent
11068 global arctags archeads arcnos arcout idheads idtags
11070 foreach id [concat [array names idheads] [array names idtags]] {
11071 if {[info exists arcnos($id)] && ![info exists arcout($id)]} {
11072 set a [lindex $arcnos($id) 0]
11073 if {![info exists donearc($a)]} {
11074 recalcarc $a
11075 set donearc($a) 1
11079 unset -nocomplain cached_tagcontent
11080 unset -nocomplain cached_dtags
11081 unset -nocomplain cached_atags
11082 unset -nocomplain cached_dheads
11085 proc rereadrefs {} {
11086 global idtags idheads idotherrefs mainheadid
11088 set refids [concat [array names idtags] \
11089 [array names idheads] [array names idotherrefs]]
11090 foreach id $refids {
11091 if {![info exists ref($id)]} {
11092 set ref($id) [listrefs $id]
11095 set oldmainhead $mainheadid
11096 readrefs
11097 changedrefs
11098 set refids [lsort -unique [concat $refids [array names idtags] \
11099 [array names idheads] [array names idotherrefs]]]
11100 foreach id $refids {
11101 set v [listrefs $id]
11102 if {![info exists ref($id)] || $ref($id) != $v} {
11103 redrawtags $id
11106 if {$oldmainhead ne $mainheadid} {
11107 redrawtags $oldmainhead
11108 redrawtags $mainheadid
11110 run refill_reflist
11113 proc listrefs {id} {
11114 global idtags idheads idotherrefs
11116 set x {}
11117 if {[info exists idtags($id)]} {
11118 set x $idtags($id)
11120 set y {}
11121 if {[info exists idheads($id)]} {
11122 set y $idheads($id)
11124 set z {}
11125 if {[info exists idotherrefs($id)]} {
11126 set z $idotherrefs($id)
11128 return [list $x $y $z]
11131 proc add_tag_ctext {tag} {
11132 global ctext cached_tagcontent tagids
11134 if {![info exists cached_tagcontent($tag)]} {
11135 catch {
11136 set cached_tagcontent($tag) [exec git cat-file -p $tag]
11139 $ctext insert end "[mc "Tag"]: $tag\n" bold
11140 if {[info exists cached_tagcontent($tag)]} {
11141 set text $cached_tagcontent($tag)
11142 } else {
11143 set text "[mc "Id"]: $tagids($tag)"
11145 appendwithlinks $text {}
11148 proc showtag {tag isnew} {
11149 global ctext cached_tagcontent tagids linknum tagobjid
11151 if {$isnew} {
11152 addtohistory [list showtag $tag 0] savectextpos
11154 $ctext conf -state normal
11155 clear_ctext
11156 settabs 0
11157 set linknum 0
11158 add_tag_ctext $tag
11159 maybe_scroll_ctext 1
11160 $ctext conf -state disabled
11161 init_flist {}
11164 proc showtags {id isnew} {
11165 global idtags ctext linknum
11167 if {$isnew} {
11168 addtohistory [list showtags $id 0] savectextpos
11170 $ctext conf -state normal
11171 clear_ctext
11172 settabs 0
11173 set linknum 0
11174 set sep {}
11175 foreach tag $idtags($id) {
11176 $ctext insert end $sep
11177 add_tag_ctext $tag
11178 set sep "\n\n"
11180 maybe_scroll_ctext 1
11181 $ctext conf -state disabled
11182 init_flist {}
11185 proc doquit {} {
11186 global stopped
11187 global gitktmpdir
11189 set stopped 100
11190 savestuff .
11191 destroy .
11193 if {[info exists gitktmpdir]} {
11194 catch {file delete -force $gitktmpdir}
11198 proc mkfontdisp {font top which} {
11199 global fontattr fontpref $font NS use_ttk
11201 set fontpref($font) [set $font]
11202 ${NS}::button $top.${font}but -text $which \
11203 -command [list choosefont $font $which]
11204 ${NS}::label $top.$font -relief flat -font $font \
11205 -text $fontattr($font,family) -justify left
11206 grid x $top.${font}but $top.$font -sticky w
11209 proc choosefont {font which} {
11210 global fontparam fontlist fonttop fontattr
11211 global prefstop NS
11213 set fontparam(which) $which
11214 set fontparam(font) $font
11215 set fontparam(family) [font actual $font -family]
11216 set fontparam(size) $fontattr($font,size)
11217 set fontparam(weight) $fontattr($font,weight)
11218 set fontparam(slant) $fontattr($font,slant)
11219 set top .gitkfont
11220 set fonttop $top
11221 if {![winfo exists $top]} {
11222 font create sample
11223 eval font config sample [font actual $font]
11224 ttk_toplevel $top
11225 make_transient $top $prefstop
11226 wm title $top [mc "Gitk font chooser"]
11227 ${NS}::label $top.l -textvariable fontparam(which)
11228 pack $top.l -side top
11229 set fontlist [lsort [font families]]
11230 ${NS}::frame $top.f
11231 listbox $top.f.fam -listvariable fontlist \
11232 -yscrollcommand [list $top.f.sb set]
11233 bind $top.f.fam <<ListboxSelect>> selfontfam
11234 ${NS}::scrollbar $top.f.sb -command [list $top.f.fam yview]
11235 pack $top.f.sb -side right -fill y
11236 pack $top.f.fam -side left -fill both -expand 1
11237 pack $top.f -side top -fill both -expand 1
11238 ${NS}::frame $top.g
11239 spinbox $top.g.size -from 4 -to 40 -width 4 \
11240 -textvariable fontparam(size) \
11241 -validatecommand {string is integer -strict %s}
11242 checkbutton $top.g.bold -padx 5 \
11243 -font {{Times New Roman} 12 bold} -text [mc "B"] -indicatoron 0 \
11244 -variable fontparam(weight) -onvalue bold -offvalue normal
11245 checkbutton $top.g.ital -padx 5 \
11246 -font {{Times New Roman} 12 italic} -text [mc "I"] -indicatoron 0 \
11247 -variable fontparam(slant) -onvalue italic -offvalue roman
11248 pack $top.g.size $top.g.bold $top.g.ital -side left
11249 pack $top.g -side top
11250 canvas $top.c -width 150 -height 50 -border 2 -relief sunk \
11251 -background white
11252 $top.c create text 100 25 -anchor center -text $which -font sample \
11253 -fill black -tags text
11254 bind $top.c <Configure> [list centertext $top.c]
11255 pack $top.c -side top -fill x
11256 ${NS}::frame $top.buts
11257 ${NS}::button $top.buts.ok -text [mc "OK"] -command fontok -default active
11258 ${NS}::button $top.buts.can -text [mc "Cancel"] -command fontcan -default normal
11259 bind $top <Key-Return> fontok
11260 bind $top <Key-Escape> fontcan
11261 grid $top.buts.ok $top.buts.can
11262 grid columnconfigure $top.buts 0 -weight 1 -uniform a
11263 grid columnconfigure $top.buts 1 -weight 1 -uniform a
11264 pack $top.buts -side bottom -fill x
11265 trace add variable fontparam write chg_fontparam
11266 } else {
11267 raise $top
11268 $top.c itemconf text -text $which
11270 set i [lsearch -exact $fontlist $fontparam(family)]
11271 if {$i >= 0} {
11272 $top.f.fam selection set $i
11273 $top.f.fam see $i
11277 proc centertext {w} {
11278 $w coords text [expr {[winfo width $w] / 2}] [expr {[winfo height $w] / 2}]
11281 proc fontok {} {
11282 global fontparam fontpref prefstop
11284 set f $fontparam(font)
11285 set fontpref($f) [list $fontparam(family) $fontparam(size)]
11286 if {$fontparam(weight) eq "bold"} {
11287 lappend fontpref($f) "bold"
11289 if {$fontparam(slant) eq "italic"} {
11290 lappend fontpref($f) "italic"
11292 set w $prefstop.notebook.fonts.$f
11293 $w conf -text $fontparam(family) -font $fontpref($f)
11295 fontcan
11298 proc fontcan {} {
11299 global fonttop fontparam
11301 if {[info exists fonttop]} {
11302 catch {destroy $fonttop}
11303 catch {font delete sample}
11304 unset fonttop
11305 unset fontparam
11309 if {[package vsatisfies [package provide Tk] 8.6]} {
11310 # In Tk 8.6 we have a native font chooser dialog. Overwrite the above
11311 # function to make use of it.
11312 proc choosefont {font which} {
11313 tk fontchooser configure -title $which -font $font \
11314 -command [list on_choosefont $font $which]
11315 tk fontchooser show
11317 proc on_choosefont {font which newfont} {
11318 global fontparam
11319 puts stderr "$font $newfont"
11320 array set f [font actual $newfont]
11321 set fontparam(which) $which
11322 set fontparam(font) $font
11323 set fontparam(family) $f(-family)
11324 set fontparam(size) $f(-size)
11325 set fontparam(weight) $f(-weight)
11326 set fontparam(slant) $f(-slant)
11327 fontok
11331 proc selfontfam {} {
11332 global fonttop fontparam
11334 set i [$fonttop.f.fam curselection]
11335 if {$i ne {}} {
11336 set fontparam(family) [$fonttop.f.fam get $i]
11340 proc chg_fontparam {v sub op} {
11341 global fontparam
11343 font config sample -$sub $fontparam($sub)
11346 # Create a property sheet tab page
11347 proc create_prefs_page {w} {
11348 global NS
11349 set parent [join [lrange [split $w .] 0 end-1] .]
11350 if {[winfo class $parent] eq "TNotebook"} {
11351 ${NS}::frame $w
11352 } else {
11353 ${NS}::labelframe $w
11357 proc prefspage_general {notebook} {
11358 global NS maxwidth maxgraphpct showneartags showlocalchanges
11359 global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11360 global hideremotes want_ttk have_ttk maxrefs
11362 set page [create_prefs_page $notebook.general]
11364 ${NS}::label $page.ldisp -text [mc "Commit list display options"]
11365 grid $page.ldisp - -sticky w -pady 10
11366 ${NS}::label $page.spacer -text " "
11367 ${NS}::label $page.maxwidthl -text [mc "Maximum graph width (lines)"]
11368 spinbox $page.maxwidth -from 0 -to 100 -width 4 -textvariable maxwidth
11369 grid $page.spacer $page.maxwidthl $page.maxwidth -sticky w
11370 #xgettext:no-tcl-format
11371 ${NS}::label $page.maxpctl -text [mc "Maximum graph width (% of pane)"]
11372 spinbox $page.maxpct -from 1 -to 100 -width 4 -textvariable maxgraphpct
11373 grid x $page.maxpctl $page.maxpct -sticky w
11374 ${NS}::checkbutton $page.showlocal -text [mc "Show local changes"] \
11375 -variable showlocalchanges
11376 grid x $page.showlocal -sticky w
11377 ${NS}::checkbutton $page.autoselect -text [mc "Auto-select SHA1 (length)"] \
11378 -variable autoselect
11379 spinbox $page.autosellen -from 1 -to 40 -width 4 -textvariable autosellen
11380 grid x $page.autoselect $page.autosellen -sticky w
11381 ${NS}::checkbutton $page.hideremotes -text [mc "Hide remote refs"] \
11382 -variable hideremotes
11383 grid x $page.hideremotes -sticky w
11385 ${NS}::label $page.ddisp -text [mc "Diff display options"]
11386 grid $page.ddisp - -sticky w -pady 10
11387 ${NS}::label $page.tabstopl -text [mc "Tab spacing"]
11388 spinbox $page.tabstop -from 1 -to 20 -width 4 -textvariable tabstop
11389 grid x $page.tabstopl $page.tabstop -sticky w
11390 ${NS}::checkbutton $page.ntag -text [mc "Display nearby tags/heads"] \
11391 -variable showneartags
11392 grid x $page.ntag -sticky w
11393 ${NS}::label $page.maxrefsl -text [mc "Maximum # tags/heads to show"]
11394 spinbox $page.maxrefs -from 1 -to 1000 -width 4 -textvariable maxrefs
11395 grid x $page.maxrefsl $page.maxrefs -sticky w
11396 ${NS}::checkbutton $page.ldiff -text [mc "Limit diffs to listed paths"] \
11397 -variable limitdiffs
11398 grid x $page.ldiff -sticky w
11399 ${NS}::checkbutton $page.lattr -text [mc "Support per-file encodings"] \
11400 -variable perfile_attrs
11401 grid x $page.lattr -sticky w
11403 ${NS}::entry $page.extdifft -textvariable extdifftool
11404 ${NS}::frame $page.extdifff
11405 ${NS}::label $page.extdifff.l -text [mc "External diff tool" ]
11406 ${NS}::button $page.extdifff.b -text [mc "Choose..."] -command choose_extdiff
11407 pack $page.extdifff.l $page.extdifff.b -side left
11408 pack configure $page.extdifff.l -padx 10
11409 grid x $page.extdifff $page.extdifft -sticky ew
11411 ${NS}::label $page.lgen -text [mc "General options"]
11412 grid $page.lgen - -sticky w -pady 10
11413 ${NS}::checkbutton $page.want_ttk -variable want_ttk \
11414 -text [mc "Use themed widgets"]
11415 if {$have_ttk} {
11416 ${NS}::label $page.ttk_note -text [mc "(change requires restart)"]
11417 } else {
11418 ${NS}::label $page.ttk_note -text [mc "(currently unavailable)"]
11420 grid x $page.want_ttk $page.ttk_note -sticky w
11421 return $page
11424 proc prefspage_colors {notebook} {
11425 global NS uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11427 set page [create_prefs_page $notebook.colors]
11429 ${NS}::label $page.cdisp -text [mc "Colors: press to choose"]
11430 grid $page.cdisp - -sticky w -pady 10
11431 label $page.ui -padx 40 -relief sunk -background $uicolor
11432 ${NS}::button $page.uibut -text [mc "Interface"] \
11433 -command [list choosecolor uicolor {} $page.ui [mc "interface"] setui]
11434 grid x $page.uibut $page.ui -sticky w
11435 label $page.bg -padx 40 -relief sunk -background $bgcolor
11436 ${NS}::button $page.bgbut -text [mc "Background"] \
11437 -command [list choosecolor bgcolor {} $page.bg [mc "background"] setbg]
11438 grid x $page.bgbut $page.bg -sticky w
11439 label $page.fg -padx 40 -relief sunk -background $fgcolor
11440 ${NS}::button $page.fgbut -text [mc "Foreground"] \
11441 -command [list choosecolor fgcolor {} $page.fg [mc "foreground"] setfg]
11442 grid x $page.fgbut $page.fg -sticky w
11443 label $page.diffold -padx 40 -relief sunk -background [lindex $diffcolors 0]
11444 ${NS}::button $page.diffoldbut -text [mc "Diff: old lines"] \
11445 -command [list choosecolor diffcolors 0 $page.diffold [mc "diff old lines"] \
11446 [list $ctext tag conf d0 -foreground]]
11447 grid x $page.diffoldbut $page.diffold -sticky w
11448 label $page.diffnew -padx 40 -relief sunk -background [lindex $diffcolors 1]
11449 ${NS}::button $page.diffnewbut -text [mc "Diff: new lines"] \
11450 -command [list choosecolor diffcolors 1 $page.diffnew [mc "diff new lines"] \
11451 [list $ctext tag conf dresult -foreground]]
11452 grid x $page.diffnewbut $page.diffnew -sticky w
11453 label $page.hunksep -padx 40 -relief sunk -background [lindex $diffcolors 2]
11454 ${NS}::button $page.hunksepbut -text [mc "Diff: hunk header"] \
11455 -command [list choosecolor diffcolors 2 $page.hunksep \
11456 [mc "diff hunk header"] \
11457 [list $ctext tag conf hunksep -foreground]]
11458 grid x $page.hunksepbut $page.hunksep -sticky w
11459 label $page.markbgsep -padx 40 -relief sunk -background $markbgcolor
11460 ${NS}::button $page.markbgbut -text [mc "Marked line bg"] \
11461 -command [list choosecolor markbgcolor {} $page.markbgsep \
11462 [mc "marked line background"] \
11463 [list $ctext tag conf omark -background]]
11464 grid x $page.markbgbut $page.markbgsep -sticky w
11465 label $page.selbgsep -padx 40 -relief sunk -background $selectbgcolor
11466 ${NS}::button $page.selbgbut -text [mc "Select bg"] \
11467 -command [list choosecolor selectbgcolor {} $page.selbgsep [mc "background"] setselbg]
11468 grid x $page.selbgbut $page.selbgsep -sticky w
11469 return $page
11472 proc prefspage_fonts {notebook} {
11473 global NS
11474 set page [create_prefs_page $notebook.fonts]
11475 ${NS}::label $page.cfont -text [mc "Fonts: press to choose"]
11476 grid $page.cfont - -sticky w -pady 10
11477 mkfontdisp mainfont $page [mc "Main font"]
11478 mkfontdisp textfont $page [mc "Diff display font"]
11479 mkfontdisp uifont $page [mc "User interface font"]
11480 return $page
11483 proc doprefs {} {
11484 global maxwidth maxgraphpct use_ttk NS
11485 global oldprefs prefstop showneartags showlocalchanges
11486 global uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11487 global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11488 global hideremotes want_ttk have_ttk
11490 set top .gitkprefs
11491 set prefstop $top
11492 if {[winfo exists $top]} {
11493 raise $top
11494 return
11496 foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11497 limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11498 set oldprefs($v) [set $v]
11500 ttk_toplevel $top
11501 wm title $top [mc "Gitk preferences"]
11502 make_transient $top .
11504 if {[set use_notebook [expr {$use_ttk && [info command ::ttk::notebook] ne ""}]]} {
11505 set notebook [ttk::notebook $top.notebook]
11506 } else {
11507 set notebook [${NS}::frame $top.notebook -borderwidth 0 -relief flat]
11510 lappend pages [prefspage_general $notebook] [mc "General"]
11511 lappend pages [prefspage_colors $notebook] [mc "Colors"]
11512 lappend pages [prefspage_fonts $notebook] [mc "Fonts"]
11513 set col 0
11514 foreach {page title} $pages {
11515 if {$use_notebook} {
11516 $notebook add $page -text $title
11517 } else {
11518 set btn [${NS}::button $notebook.b_[string map {. X} $page] \
11519 -text $title -command [list raise $page]]
11520 $page configure -text $title
11521 grid $btn -row 0 -column [incr col] -sticky w
11522 grid $page -row 1 -column 0 -sticky news -columnspan 100
11526 if {!$use_notebook} {
11527 grid columnconfigure $notebook 0 -weight 1
11528 grid rowconfigure $notebook 1 -weight 1
11529 raise [lindex $pages 0]
11532 grid $notebook -sticky news -padx 2 -pady 2
11533 grid rowconfigure $top 0 -weight 1
11534 grid columnconfigure $top 0 -weight 1
11536 ${NS}::frame $top.buts
11537 ${NS}::button $top.buts.ok -text [mc "OK"] -command prefsok -default active
11538 ${NS}::button $top.buts.can -text [mc "Cancel"] -command prefscan -default normal
11539 bind $top <Key-Return> prefsok
11540 bind $top <Key-Escape> prefscan
11541 grid $top.buts.ok $top.buts.can
11542 grid columnconfigure $top.buts 0 -weight 1 -uniform a
11543 grid columnconfigure $top.buts 1 -weight 1 -uniform a
11544 grid $top.buts - - -pady 10 -sticky ew
11545 grid columnconfigure $top 2 -weight 1
11546 bind $top <Visibility> [list focus $top.buts.ok]
11549 proc choose_extdiff {} {
11550 global extdifftool
11552 set prog [tk_getOpenFile -title [mc "External diff tool"] -multiple false]
11553 if {$prog ne {}} {
11554 set extdifftool $prog
11558 proc choosecolor {v vi w x cmd} {
11559 global $v
11561 set c [tk_chooseColor -initialcolor [lindex [set $v] $vi] \
11562 -title [mc "Gitk: choose color for %s" $x]]
11563 if {$c eq {}} return
11564 $w conf -background $c
11565 lset $v $vi $c
11566 eval $cmd $c
11569 proc setselbg {c} {
11570 global bglist cflist
11571 foreach w $bglist {
11572 if {[winfo exists $w]} {
11573 $w configure -selectbackground $c
11576 $cflist tag configure highlight \
11577 -background [$cflist cget -selectbackground]
11578 allcanvs itemconf secsel -fill $c
11581 # This sets the background color and the color scheme for the whole UI.
11582 # For some reason, tk_setPalette chooses a nasty dark red for selectColor
11583 # if we don't specify one ourselves, which makes the checkbuttons and
11584 # radiobuttons look bad. This chooses white for selectColor if the
11585 # background color is light, or black if it is dark.
11586 proc setui {c} {
11587 if {[tk windowingsystem] eq "win32"} { return }
11588 set bg [winfo rgb . $c]
11589 set selc black
11590 if {[lindex $bg 0] + 1.5 * [lindex $bg 1] + 0.5 * [lindex $bg 2] > 100000} {
11591 set selc white
11593 tk_setPalette background $c selectColor $selc
11596 proc setbg {c} {
11597 global bglist
11599 foreach w $bglist {
11600 if {[winfo exists $w]} {
11601 $w conf -background $c
11606 proc setfg {c} {
11607 global fglist canv
11609 foreach w $fglist {
11610 if {[winfo exists $w]} {
11611 $w conf -foreground $c
11614 allcanvs itemconf text -fill $c
11615 $canv itemconf circle -outline $c
11616 $canv itemconf markid -outline $c
11619 proc prefscan {} {
11620 global oldprefs prefstop
11622 foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11623 limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11624 global $v
11625 set $v $oldprefs($v)
11627 catch {destroy $prefstop}
11628 unset prefstop
11629 fontcan
11632 proc prefsok {} {
11633 global maxwidth maxgraphpct
11634 global oldprefs prefstop showneartags showlocalchanges
11635 global fontpref mainfont textfont uifont
11636 global limitdiffs treediffs perfile_attrs
11637 global hideremotes
11639 catch {destroy $prefstop}
11640 unset prefstop
11641 fontcan
11642 set fontchanged 0
11643 if {$mainfont ne $fontpref(mainfont)} {
11644 set mainfont $fontpref(mainfont)
11645 parsefont mainfont $mainfont
11646 eval font configure mainfont [fontflags mainfont]
11647 eval font configure mainfontbold [fontflags mainfont 1]
11648 setcoords
11649 set fontchanged 1
11651 if {$textfont ne $fontpref(textfont)} {
11652 set textfont $fontpref(textfont)
11653 parsefont textfont $textfont
11654 eval font configure textfont [fontflags textfont]
11655 eval font configure textfontbold [fontflags textfont 1]
11657 if {$uifont ne $fontpref(uifont)} {
11658 set uifont $fontpref(uifont)
11659 parsefont uifont $uifont
11660 eval font configure uifont [fontflags uifont]
11662 settabs
11663 if {$showlocalchanges != $oldprefs(showlocalchanges)} {
11664 if {$showlocalchanges} {
11665 doshowlocalchanges
11666 } else {
11667 dohidelocalchanges
11670 if {$limitdiffs != $oldprefs(limitdiffs) ||
11671 ($perfile_attrs && !$oldprefs(perfile_attrs))} {
11672 # treediffs elements are limited by path;
11673 # won't have encodings cached if perfile_attrs was just turned on
11674 unset -nocomplain treediffs
11676 if {$fontchanged || $maxwidth != $oldprefs(maxwidth)
11677 || $maxgraphpct != $oldprefs(maxgraphpct)} {
11678 redisplay
11679 } elseif {$showneartags != $oldprefs(showneartags) ||
11680 $limitdiffs != $oldprefs(limitdiffs)} {
11681 reselectline
11683 if {$hideremotes != $oldprefs(hideremotes)} {
11684 rereadrefs
11688 proc formatdate {d} {
11689 global datetimeformat
11690 if {$d ne {}} {
11691 # If $datetimeformat includes a timezone, display in the
11692 # timezone of the argument. Otherwise, display in local time.
11693 if {[string match {*%[zZ]*} $datetimeformat]} {
11694 if {[catch {set d [clock format [lindex $d 0] -timezone [lindex $d 1] -format $datetimeformat]}]} {
11695 # Tcl < 8.5 does not support -timezone. Emulate it by
11696 # setting TZ (e.g. TZ=<-0430>+04:30).
11697 global env
11698 if {[info exists env(TZ)]} {
11699 set savedTZ $env(TZ)
11701 set zone [lindex $d 1]
11702 set sign [string map {+ - - +} [string index $zone 0]]
11703 set env(TZ) <$zone>$sign[string range $zone 1 2]:[string range $zone 3 4]
11704 set d [clock format [lindex $d 0] -format $datetimeformat]
11705 if {[info exists savedTZ]} {
11706 set env(TZ) $savedTZ
11707 } else {
11708 unset env(TZ)
11711 } else {
11712 set d [clock format [lindex $d 0] -format $datetimeformat]
11715 return $d
11718 # This list of encoding names and aliases is distilled from
11719 # http://www.iana.org/assignments/character-sets.
11720 # Not all of them are supported by Tcl.
11721 set encoding_aliases {
11722 { ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ASCII
11723 ISO646-US US-ASCII us IBM367 cp367 csASCII }
11724 { ISO-10646-UTF-1 csISO10646UTF1 }
11725 { ISO_646.basic:1983 ref csISO646basic1983 }
11726 { INVARIANT csINVARIANT }
11727 { ISO_646.irv:1983 iso-ir-2 irv csISO2IntlRefVersion }
11728 { BS_4730 iso-ir-4 ISO646-GB gb uk csISO4UnitedKingdom }
11729 { NATS-SEFI iso-ir-8-1 csNATSSEFI }
11730 { NATS-SEFI-ADD iso-ir-8-2 csNATSSEFIADD }
11731 { NATS-DANO iso-ir-9-1 csNATSDANO }
11732 { NATS-DANO-ADD iso-ir-9-2 csNATSDANOADD }
11733 { SEN_850200_B iso-ir-10 FI ISO646-FI ISO646-SE se csISO10Swedish }
11734 { SEN_850200_C iso-ir-11 ISO646-SE2 se2 csISO11SwedishForNames }
11735 { KS_C_5601-1987 iso-ir-149 KS_C_5601-1989 KSC_5601 korean csKSC56011987 }
11736 { ISO-2022-KR csISO2022KR }
11737 { EUC-KR csEUCKR }
11738 { ISO-2022-JP csISO2022JP }
11739 { ISO-2022-JP-2 csISO2022JP2 }
11740 { JIS_C6220-1969-jp JIS_C6220-1969 iso-ir-13 katakana x0201-7
11741 csISO13JISC6220jp }
11742 { JIS_C6220-1969-ro iso-ir-14 jp ISO646-JP csISO14JISC6220ro }
11743 { IT iso-ir-15 ISO646-IT csISO15Italian }
11744 { PT iso-ir-16 ISO646-PT csISO16Portuguese }
11745 { ES iso-ir-17 ISO646-ES csISO17Spanish }
11746 { greek7-old iso-ir-18 csISO18Greek7Old }
11747 { latin-greek iso-ir-19 csISO19LatinGreek }
11748 { DIN_66003 iso-ir-21 de ISO646-DE csISO21German }
11749 { NF_Z_62-010_(1973) iso-ir-25 ISO646-FR1 csISO25French }
11750 { Latin-greek-1 iso-ir-27 csISO27LatinGreek1 }
11751 { ISO_5427 iso-ir-37 csISO5427Cyrillic }
11752 { JIS_C6226-1978 iso-ir-42 csISO42JISC62261978 }
11753 { BS_viewdata iso-ir-47 csISO47BSViewdata }
11754 { INIS iso-ir-49 csISO49INIS }
11755 { INIS-8 iso-ir-50 csISO50INIS8 }
11756 { INIS-cyrillic iso-ir-51 csISO51INISCyrillic }
11757 { ISO_5427:1981 iso-ir-54 ISO5427Cyrillic1981 }
11758 { ISO_5428:1980 iso-ir-55 csISO5428Greek }
11759 { GB_1988-80 iso-ir-57 cn ISO646-CN csISO57GB1988 }
11760 { GB_2312-80 iso-ir-58 chinese csISO58GB231280 }
11761 { NS_4551-1 iso-ir-60 ISO646-NO no csISO60DanishNorwegian
11762 csISO60Norwegian1 }
11763 { NS_4551-2 ISO646-NO2 iso-ir-61 no2 csISO61Norwegian2 }
11764 { NF_Z_62-010 iso-ir-69 ISO646-FR fr csISO69French }
11765 { videotex-suppl iso-ir-70 csISO70VideotexSupp1 }
11766 { PT2 iso-ir-84 ISO646-PT2 csISO84Portuguese2 }
11767 { ES2 iso-ir-85 ISO646-ES2 csISO85Spanish2 }
11768 { MSZ_7795.3 iso-ir-86 ISO646-HU hu csISO86Hungarian }
11769 { JIS_C6226-1983 iso-ir-87 x0208 JIS_X0208-1983 csISO87JISX0208 }
11770 { greek7 iso-ir-88 csISO88Greek7 }
11771 { ASMO_449 ISO_9036 arabic7 iso-ir-89 csISO89ASMO449 }
11772 { iso-ir-90 csISO90 }
11773 { JIS_C6229-1984-a iso-ir-91 jp-ocr-a csISO91JISC62291984a }
11774 { JIS_C6229-1984-b iso-ir-92 ISO646-JP-OCR-B jp-ocr-b
11775 csISO92JISC62991984b }
11776 { JIS_C6229-1984-b-add iso-ir-93 jp-ocr-b-add csISO93JIS62291984badd }
11777 { JIS_C6229-1984-hand iso-ir-94 jp-ocr-hand csISO94JIS62291984hand }
11778 { JIS_C6229-1984-hand-add iso-ir-95 jp-ocr-hand-add
11779 csISO95JIS62291984handadd }
11780 { JIS_C6229-1984-kana iso-ir-96 csISO96JISC62291984kana }
11781 { ISO_2033-1983 iso-ir-98 e13b csISO2033 }
11782 { ANSI_X3.110-1983 iso-ir-99 CSA_T500-1983 NAPLPS csISO99NAPLPS }
11783 { ISO_8859-1:1987 iso-ir-100 ISO_8859-1 ISO-8859-1 latin1 l1 IBM819
11784 CP819 csISOLatin1 }
11785 { ISO_8859-2:1987 iso-ir-101 ISO_8859-2 ISO-8859-2 latin2 l2 csISOLatin2 }
11786 { T.61-7bit iso-ir-102 csISO102T617bit }
11787 { T.61-8bit T.61 iso-ir-103 csISO103T618bit }
11788 { ISO_8859-3:1988 iso-ir-109 ISO_8859-3 ISO-8859-3 latin3 l3 csISOLatin3 }
11789 { ISO_8859-4:1988 iso-ir-110 ISO_8859-4 ISO-8859-4 latin4 l4 csISOLatin4 }
11790 { ECMA-cyrillic iso-ir-111 KOI8-E csISO111ECMACyrillic }
11791 { CSA_Z243.4-1985-1 iso-ir-121 ISO646-CA csa7-1 ca csISO121Canadian1 }
11792 { CSA_Z243.4-1985-2 iso-ir-122 ISO646-CA2 csa7-2 csISO122Canadian2 }
11793 { CSA_Z243.4-1985-gr iso-ir-123 csISO123CSAZ24341985gr }
11794 { ISO_8859-6:1987 iso-ir-127 ISO_8859-6 ISO-8859-6 ECMA-114 ASMO-708
11795 arabic csISOLatinArabic }
11796 { ISO_8859-6-E csISO88596E ISO-8859-6-E }
11797 { ISO_8859-6-I csISO88596I ISO-8859-6-I }
11798 { ISO_8859-7:1987 iso-ir-126 ISO_8859-7 ISO-8859-7 ELOT_928 ECMA-118
11799 greek greek8 csISOLatinGreek }
11800 { T.101-G2 iso-ir-128 csISO128T101G2 }
11801 { ISO_8859-8:1988 iso-ir-138 ISO_8859-8 ISO-8859-8 hebrew
11802 csISOLatinHebrew }
11803 { ISO_8859-8-E csISO88598E ISO-8859-8-E }
11804 { ISO_8859-8-I csISO88598I ISO-8859-8-I }
11805 { CSN_369103 iso-ir-139 csISO139CSN369103 }
11806 { JUS_I.B1.002 iso-ir-141 ISO646-YU js yu csISO141JUSIB1002 }
11807 { ISO_6937-2-add iso-ir-142 csISOTextComm }
11808 { IEC_P27-1 iso-ir-143 csISO143IECP271 }
11809 { ISO_8859-5:1988 iso-ir-144 ISO_8859-5 ISO-8859-5 cyrillic
11810 csISOLatinCyrillic }
11811 { JUS_I.B1.003-serb iso-ir-146 serbian csISO146Serbian }
11812 { JUS_I.B1.003-mac macedonian iso-ir-147 csISO147Macedonian }
11813 { ISO_8859-9:1989 iso-ir-148 ISO_8859-9 ISO-8859-9 latin5 l5 csISOLatin5 }
11814 { greek-ccitt iso-ir-150 csISO150 csISO150GreekCCITT }
11815 { NC_NC00-10:81 cuba iso-ir-151 ISO646-CU csISO151Cuba }
11816 { ISO_6937-2-25 iso-ir-152 csISO6937Add }
11817 { GOST_19768-74 ST_SEV_358-88 iso-ir-153 csISO153GOST1976874 }
11818 { ISO_8859-supp iso-ir-154 latin1-2-5 csISO8859Supp }
11819 { ISO_10367-box iso-ir-155 csISO10367Box }
11820 { ISO-8859-10 iso-ir-157 l6 ISO_8859-10:1992 csISOLatin6 latin6 }
11821 { latin-lap lap iso-ir-158 csISO158Lap }
11822 { JIS_X0212-1990 x0212 iso-ir-159 csISO159JISX02121990 }
11823 { DS_2089 DS2089 ISO646-DK dk csISO646Danish }
11824 { us-dk csUSDK }
11825 { dk-us csDKUS }
11826 { JIS_X0201 X0201 csHalfWidthKatakana }
11827 { KSC5636 ISO646-KR csKSC5636 }
11828 { ISO-10646-UCS-2 csUnicode }
11829 { ISO-10646-UCS-4 csUCS4 }
11830 { DEC-MCS dec csDECMCS }
11831 { hp-roman8 roman8 r8 csHPRoman8 }
11832 { macintosh mac csMacintosh }
11833 { IBM037 cp037 ebcdic-cp-us ebcdic-cp-ca ebcdic-cp-wt ebcdic-cp-nl
11834 csIBM037 }
11835 { IBM038 EBCDIC-INT cp038 csIBM038 }
11836 { IBM273 CP273 csIBM273 }
11837 { IBM274 EBCDIC-BE CP274 csIBM274 }
11838 { IBM275 EBCDIC-BR cp275 csIBM275 }
11839 { IBM277 EBCDIC-CP-DK EBCDIC-CP-NO csIBM277 }
11840 { IBM278 CP278 ebcdic-cp-fi ebcdic-cp-se csIBM278 }
11841 { IBM280 CP280 ebcdic-cp-it csIBM280 }
11842 { IBM281 EBCDIC-JP-E cp281 csIBM281 }
11843 { IBM284 CP284 ebcdic-cp-es csIBM284 }
11844 { IBM285 CP285 ebcdic-cp-gb csIBM285 }
11845 { IBM290 cp290 EBCDIC-JP-kana csIBM290 }
11846 { IBM297 cp297 ebcdic-cp-fr csIBM297 }
11847 { IBM420 cp420 ebcdic-cp-ar1 csIBM420 }
11848 { IBM423 cp423 ebcdic-cp-gr csIBM423 }
11849 { IBM424 cp424 ebcdic-cp-he csIBM424 }
11850 { IBM437 cp437 437 csPC8CodePage437 }
11851 { IBM500 CP500 ebcdic-cp-be ebcdic-cp-ch csIBM500 }
11852 { IBM775 cp775 csPC775Baltic }
11853 { IBM850 cp850 850 csPC850Multilingual }
11854 { IBM851 cp851 851 csIBM851 }
11855 { IBM852 cp852 852 csPCp852 }
11856 { IBM855 cp855 855 csIBM855 }
11857 { IBM857 cp857 857 csIBM857 }
11858 { IBM860 cp860 860 csIBM860 }
11859 { IBM861 cp861 861 cp-is csIBM861 }
11860 { IBM862 cp862 862 csPC862LatinHebrew }
11861 { IBM863 cp863 863 csIBM863 }
11862 { IBM864 cp864 csIBM864 }
11863 { IBM865 cp865 865 csIBM865 }
11864 { IBM866 cp866 866 csIBM866 }
11865 { IBM868 CP868 cp-ar csIBM868 }
11866 { IBM869 cp869 869 cp-gr csIBM869 }
11867 { IBM870 CP870 ebcdic-cp-roece ebcdic-cp-yu csIBM870 }
11868 { IBM871 CP871 ebcdic-cp-is csIBM871 }
11869 { IBM880 cp880 EBCDIC-Cyrillic csIBM880 }
11870 { IBM891 cp891 csIBM891 }
11871 { IBM903 cp903 csIBM903 }
11872 { IBM904 cp904 904 csIBBM904 }
11873 { IBM905 CP905 ebcdic-cp-tr csIBM905 }
11874 { IBM918 CP918 ebcdic-cp-ar2 csIBM918 }
11875 { IBM1026 CP1026 csIBM1026 }
11876 { EBCDIC-AT-DE csIBMEBCDICATDE }
11877 { EBCDIC-AT-DE-A csEBCDICATDEA }
11878 { EBCDIC-CA-FR csEBCDICCAFR }
11879 { EBCDIC-DK-NO csEBCDICDKNO }
11880 { EBCDIC-DK-NO-A csEBCDICDKNOA }
11881 { EBCDIC-FI-SE csEBCDICFISE }
11882 { EBCDIC-FI-SE-A csEBCDICFISEA }
11883 { EBCDIC-FR csEBCDICFR }
11884 { EBCDIC-IT csEBCDICIT }
11885 { EBCDIC-PT csEBCDICPT }
11886 { EBCDIC-ES csEBCDICES }
11887 { EBCDIC-ES-A csEBCDICESA }
11888 { EBCDIC-ES-S csEBCDICESS }
11889 { EBCDIC-UK csEBCDICUK }
11890 { EBCDIC-US csEBCDICUS }
11891 { UNKNOWN-8BIT csUnknown8BiT }
11892 { MNEMONIC csMnemonic }
11893 { MNEM csMnem }
11894 { VISCII csVISCII }
11895 { VIQR csVIQR }
11896 { KOI8-R csKOI8R }
11897 { IBM00858 CCSID00858 CP00858 PC-Multilingual-850+euro }
11898 { IBM00924 CCSID00924 CP00924 ebcdic-Latin9--euro }
11899 { IBM01140 CCSID01140 CP01140 ebcdic-us-37+euro }
11900 { IBM01141 CCSID01141 CP01141 ebcdic-de-273+euro }
11901 { IBM01142 CCSID01142 CP01142 ebcdic-dk-277+euro ebcdic-no-277+euro }
11902 { IBM01143 CCSID01143 CP01143 ebcdic-fi-278+euro ebcdic-se-278+euro }
11903 { IBM01144 CCSID01144 CP01144 ebcdic-it-280+euro }
11904 { IBM01145 CCSID01145 CP01145 ebcdic-es-284+euro }
11905 { IBM01146 CCSID01146 CP01146 ebcdic-gb-285+euro }
11906 { IBM01147 CCSID01147 CP01147 ebcdic-fr-297+euro }
11907 { IBM01148 CCSID01148 CP01148 ebcdic-international-500+euro }
11908 { IBM01149 CCSID01149 CP01149 ebcdic-is-871+euro }
11909 { IBM1047 IBM-1047 }
11910 { PTCP154 csPTCP154 PT154 CP154 Cyrillic-Asian }
11911 { Amiga-1251 Ami1251 Amiga1251 Ami-1251 }
11912 { UNICODE-1-1 csUnicode11 }
11913 { CESU-8 csCESU-8 }
11914 { BOCU-1 csBOCU-1 }
11915 { UNICODE-1-1-UTF-7 csUnicode11UTF7 }
11916 { ISO-8859-14 iso-ir-199 ISO_8859-14:1998 ISO_8859-14 latin8 iso-celtic
11917 l8 }
11918 { ISO-8859-15 ISO_8859-15 Latin-9 }
11919 { ISO-8859-16 iso-ir-226 ISO_8859-16:2001 ISO_8859-16 latin10 l10 }
11920 { GBK CP936 MS936 windows-936 }
11921 { JIS_Encoding csJISEncoding }
11922 { Shift_JIS MS_Kanji csShiftJIS ShiftJIS Shift-JIS }
11923 { Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese
11924 EUC-JP }
11925 { Extended_UNIX_Code_Fixed_Width_for_Japanese csEUCFixWidJapanese }
11926 { ISO-10646-UCS-Basic csUnicodeASCII }
11927 { ISO-10646-Unicode-Latin1 csUnicodeLatin1 ISO-10646 }
11928 { ISO-Unicode-IBM-1261 csUnicodeIBM1261 }
11929 { ISO-Unicode-IBM-1268 csUnicodeIBM1268 }
11930 { ISO-Unicode-IBM-1276 csUnicodeIBM1276 }
11931 { ISO-Unicode-IBM-1264 csUnicodeIBM1264 }
11932 { ISO-Unicode-IBM-1265 csUnicodeIBM1265 }
11933 { ISO-8859-1-Windows-3.0-Latin-1 csWindows30Latin1 }
11934 { ISO-8859-1-Windows-3.1-Latin-1 csWindows31Latin1 }
11935 { ISO-8859-2-Windows-Latin-2 csWindows31Latin2 }
11936 { ISO-8859-9-Windows-Latin-5 csWindows31Latin5 }
11937 { Adobe-Standard-Encoding csAdobeStandardEncoding }
11938 { Ventura-US csVenturaUS }
11939 { Ventura-International csVenturaInternational }
11940 { PC8-Danish-Norwegian csPC8DanishNorwegian }
11941 { PC8-Turkish csPC8Turkish }
11942 { IBM-Symbols csIBMSymbols }
11943 { IBM-Thai csIBMThai }
11944 { HP-Legal csHPLegal }
11945 { HP-Pi-font csHPPiFont }
11946 { HP-Math8 csHPMath8 }
11947 { Adobe-Symbol-Encoding csHPPSMath }
11948 { HP-DeskTop csHPDesktop }
11949 { Ventura-Math csVenturaMath }
11950 { Microsoft-Publishing csMicrosoftPublishing }
11951 { Windows-31J csWindows31J }
11952 { GB2312 csGB2312 }
11953 { Big5 csBig5 }
11956 proc tcl_encoding {enc} {
11957 global encoding_aliases tcl_encoding_cache
11958 if {[info exists tcl_encoding_cache($enc)]} {
11959 return $tcl_encoding_cache($enc)
11961 set names [encoding names]
11962 set lcnames [string tolower $names]
11963 set enc [string tolower $enc]
11964 set i [lsearch -exact $lcnames $enc]
11965 if {$i < 0} {
11966 # look for "isonnn" instead of "iso-nnn" or "iso_nnn"
11967 if {[regsub {^(iso|cp|ibm|jis)[-_]} $enc {\1} encx]} {
11968 set i [lsearch -exact $lcnames $encx]
11971 if {$i < 0} {
11972 foreach l $encoding_aliases {
11973 set ll [string tolower $l]
11974 if {[lsearch -exact $ll $enc] < 0} continue
11975 # look through the aliases for one that tcl knows about
11976 foreach e $ll {
11977 set i [lsearch -exact $lcnames $e]
11978 if {$i < 0} {
11979 if {[regsub {^(iso|cp|ibm|jis)[-_]} $e {\1} ex]} {
11980 set i [lsearch -exact $lcnames $ex]
11983 if {$i >= 0} break
11985 break
11988 set tclenc {}
11989 if {$i >= 0} {
11990 set tclenc [lindex $names $i]
11992 set tcl_encoding_cache($enc) $tclenc
11993 return $tclenc
11996 proc gitattr {path attr default} {
11997 global path_attr_cache
11998 if {[info exists path_attr_cache($attr,$path)]} {
11999 set r $path_attr_cache($attr,$path)
12000 } else {
12001 set r "unspecified"
12002 if {![catch {set line [exec git check-attr $attr -- $path]}]} {
12003 regexp "(.*): $attr: (.*)" $line m f r
12005 set path_attr_cache($attr,$path) $r
12007 if {$r eq "unspecified"} {
12008 return $default
12010 return $r
12013 proc cache_gitattr {attr pathlist} {
12014 global path_attr_cache
12015 set newlist {}
12016 foreach path $pathlist {
12017 if {![info exists path_attr_cache($attr,$path)]} {
12018 lappend newlist $path
12021 set lim 1000
12022 if {[tk windowingsystem] == "win32"} {
12023 # windows has a 32k limit on the arguments to a command...
12024 set lim 30
12026 while {$newlist ne {}} {
12027 set head [lrange $newlist 0 [expr {$lim - 1}]]
12028 set newlist [lrange $newlist $lim end]
12029 if {![catch {set rlist [eval exec git check-attr $attr -- $head]}]} {
12030 foreach row [split $rlist "\n"] {
12031 if {[regexp "(.*): $attr: (.*)" $row m path value]} {
12032 if {[string index $path 0] eq "\""} {
12033 set path [encoding convertfrom [lindex $path 0]]
12035 set path_attr_cache($attr,$path) $value
12042 proc get_path_encoding {path} {
12043 global gui_encoding perfile_attrs
12044 set tcl_enc $gui_encoding
12045 if {$path ne {} && $perfile_attrs} {
12046 set enc2 [tcl_encoding [gitattr $path encoding $tcl_enc]]
12047 if {$enc2 ne {}} {
12048 set tcl_enc $enc2
12051 return $tcl_enc
12054 ## For msgcat loading, first locate the installation location.
12055 if { [info exists ::env(GITK_MSGSDIR)] } {
12056 ## Msgsdir was manually set in the environment.
12057 set gitk_msgsdir $::env(GITK_MSGSDIR)
12058 } else {
12059 ## Let's guess the prefix from argv0.
12060 set gitk_prefix [file dirname [file dirname [file normalize $argv0]]]
12061 set gitk_libdir [file join $gitk_prefix share gitk lib]
12062 set gitk_msgsdir [file join $gitk_libdir msgs]
12063 unset gitk_prefix
12066 ## Internationalization (i18n) through msgcat and gettext. See
12067 ## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
12068 package require msgcat
12069 namespace import ::msgcat::mc
12070 ## And eventually load the actual message catalog
12071 ::msgcat::mcload $gitk_msgsdir
12073 # First check that Tcl/Tk is recent enough
12074 if {[catch {package require Tk 8.4} err]} {
12075 show_error {} . [mc "Sorry, gitk cannot run with this version of Tcl/Tk.\n\
12076 Gitk requires at least Tcl/Tk 8.4."]
12077 exit 1
12080 # on OSX bring the current Wish process window to front
12081 if {[tk windowingsystem] eq "aqua"} {
12082 exec osascript -e [format {
12083 tell application "System Events"
12084 set frontmost of processes whose unix id is %d to true
12085 end tell
12086 } [pid] ]
12089 # Unset GIT_TRACE var if set
12090 if { [info exists ::env(GIT_TRACE)] } {
12091 unset ::env(GIT_TRACE)
12094 # defaults...
12095 set wrcomcmd "git diff-tree --stdin -p --pretty=email"
12097 set gitencoding {}
12098 catch {
12099 set gitencoding [exec git config --get i18n.commitencoding]
12101 catch {
12102 set gitencoding [exec git config --get i18n.logoutputencoding]
12104 if {$gitencoding == ""} {
12105 set gitencoding "utf-8"
12107 set tclencoding [tcl_encoding $gitencoding]
12108 if {$tclencoding == {}} {
12109 puts stderr "Warning: encoding $gitencoding is not supported by Tcl/Tk"
12112 set gui_encoding [encoding system]
12113 catch {
12114 set enc [exec git config --get gui.encoding]
12115 if {$enc ne {}} {
12116 set tclenc [tcl_encoding $enc]
12117 if {$tclenc ne {}} {
12118 set gui_encoding $tclenc
12119 } else {
12120 puts stderr "Warning: encoding $enc is not supported by Tcl/Tk"
12125 set log_showroot true
12126 catch {
12127 set log_showroot [exec git config --bool --get log.showroot]
12130 if {[tk windowingsystem] eq "aqua"} {
12131 set mainfont {{Lucida Grande} 9}
12132 set textfont {Monaco 9}
12133 set uifont {{Lucida Grande} 9 bold}
12134 } elseif {![catch {::tk::pkgconfig get fontsystem} xft] && $xft eq "xft"} {
12135 # fontconfig!
12136 set mainfont {sans 9}
12137 set textfont {monospace 9}
12138 set uifont {sans 9 bold}
12139 } else {
12140 set mainfont {Helvetica 9}
12141 set textfont {Courier 9}
12142 set uifont {Helvetica 9 bold}
12144 set tabstop 8
12145 set findmergefiles 0
12146 set maxgraphpct 50
12147 set maxwidth 16
12148 set revlistorder 0
12149 set fastdate 0
12150 set uparrowlen 5
12151 set downarrowlen 5
12152 set mingaplen 100
12153 set cmitmode "patch"
12154 set wrapcomment "none"
12155 set showneartags 1
12156 set hideremotes 0
12157 set maxrefs 20
12158 set visiblerefs {"master"}
12159 set maxlinelen 200
12160 set showlocalchanges 1
12161 set limitdiffs 1
12162 set datetimeformat "%Y-%m-%d %H:%M:%S"
12163 set autoselect 1
12164 set autosellen 40
12165 set perfile_attrs 0
12166 set want_ttk 1
12168 if {[tk windowingsystem] eq "aqua"} {
12169 set extdifftool "opendiff"
12170 } else {
12171 set extdifftool "meld"
12174 set colors {green red blue magenta darkgrey brown orange}
12175 if {[tk windowingsystem] eq "win32"} {
12176 set uicolor SystemButtonFace
12177 set uifgcolor SystemButtonText
12178 set uifgdisabledcolor SystemDisabledText
12179 set bgcolor SystemWindow
12180 set fgcolor SystemWindowText
12181 set selectbgcolor SystemHighlight
12182 } else {
12183 set uicolor grey85
12184 set uifgcolor black
12185 set uifgdisabledcolor "#999"
12186 set bgcolor white
12187 set fgcolor black
12188 set selectbgcolor gray85
12190 set diffcolors {red "#00a000" blue}
12191 set diffcontext 3
12192 set mergecolors {red blue green purple brown "#009090" magenta "#808000" "#009000" "#ff0080" cyan "#b07070" "#70b0f0" "#70f0b0" "#f0b070" "#ff70b0"}
12193 set ignorespace 0
12194 set worddiff ""
12195 set markbgcolor "#e0e0ff"
12197 set headbgcolor green
12198 set headfgcolor black
12199 set headoutlinecolor black
12200 set remotebgcolor #ffddaa
12201 set tagbgcolor yellow
12202 set tagfgcolor black
12203 set tagoutlinecolor black
12204 set reflinecolor black
12205 set filesepbgcolor #aaaaaa
12206 set filesepfgcolor black
12207 set linehoverbgcolor #ffff80
12208 set linehoverfgcolor black
12209 set linehoveroutlinecolor black
12210 set mainheadcirclecolor yellow
12211 set workingfilescirclecolor red
12212 set indexcirclecolor green
12213 set circlecolors {white blue gray blue blue}
12214 set linkfgcolor blue
12215 set circleoutlinecolor $fgcolor
12216 set foundbgcolor yellow
12217 set currentsearchhitbgcolor orange
12219 # button for popping up context menus
12220 if {[tk windowingsystem] eq "aqua"} {
12221 set ctxbut <Button-2>
12222 } else {
12223 set ctxbut <Button-3>
12226 catch {
12227 # follow the XDG base directory specification by default. See
12228 # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
12229 if {[info exists env(XDG_CONFIG_HOME)] && $env(XDG_CONFIG_HOME) ne ""} {
12230 # XDG_CONFIG_HOME environment variable is set
12231 set config_file [file join $env(XDG_CONFIG_HOME) git gitk]
12232 set config_file_tmp [file join $env(XDG_CONFIG_HOME) git gitk-tmp]
12233 } else {
12234 # default XDG_CONFIG_HOME
12235 set config_file "~/.config/git/gitk"
12236 set config_file_tmp "~/.config/git/gitk-tmp"
12238 if {![file exists $config_file]} {
12239 # for backward compatibility use the old config file if it exists
12240 if {[file exists "~/.gitk"]} {
12241 set config_file "~/.gitk"
12242 set config_file_tmp "~/.gitk-tmp"
12243 } elseif {![file exists [file dirname $config_file]]} {
12244 file mkdir [file dirname $config_file]
12247 source $config_file
12249 config_check_tmp_exists 50
12251 set config_variables {
12252 mainfont textfont uifont tabstop findmergefiles maxgraphpct maxwidth
12253 cmitmode wrapcomment autoselect autosellen showneartags maxrefs visiblerefs
12254 hideremotes showlocalchanges datetimeformat limitdiffs uicolor want_ttk
12255 bgcolor fgcolor uifgcolor uifgdisabledcolor colors diffcolors mergecolors
12256 markbgcolor diffcontext selectbgcolor foundbgcolor currentsearchhitbgcolor
12257 extdifftool perfile_attrs headbgcolor headfgcolor headoutlinecolor
12258 remotebgcolor tagbgcolor tagfgcolor tagoutlinecolor reflinecolor
12259 filesepbgcolor filesepfgcolor linehoverbgcolor linehoverfgcolor
12260 linehoveroutlinecolor mainheadcirclecolor workingfilescirclecolor
12261 indexcirclecolor circlecolors linkfgcolor circleoutlinecolor
12263 foreach var $config_variables {
12264 config_init_trace $var
12265 trace add variable $var write config_variable_change_cb
12268 parsefont mainfont $mainfont
12269 eval font create mainfont [fontflags mainfont]
12270 eval font create mainfontbold [fontflags mainfont 1]
12272 parsefont textfont $textfont
12273 eval font create textfont [fontflags textfont]
12274 eval font create textfontbold [fontflags textfont 1]
12276 parsefont uifont $uifont
12277 eval font create uifont [fontflags uifont]
12279 setui $uicolor
12281 setoptions
12283 # check that we can find a .git directory somewhere...
12284 if {[catch {set gitdir [exec git rev-parse --git-dir]}]} {
12285 show_error {} . [mc "Cannot find a git repository here."]
12286 exit 1
12289 set selecthead {}
12290 set selectheadid {}
12292 set revtreeargs {}
12293 set cmdline_files {}
12294 set i 0
12295 set revtreeargscmd {}
12296 foreach arg $argv {
12297 switch -glob -- $arg {
12298 "" { }
12299 "--" {
12300 set cmdline_files [lrange $argv [expr {$i + 1}] end]
12301 break
12303 "--select-commit=*" {
12304 set selecthead [string range $arg 16 end]
12306 "--argscmd=*" {
12307 set revtreeargscmd [string range $arg 10 end]
12309 default {
12310 lappend revtreeargs $arg
12313 incr i
12316 if {$selecthead eq "HEAD"} {
12317 set selecthead {}
12320 if {$i >= [llength $argv] && $revtreeargs ne {}} {
12321 # no -- on command line, but some arguments (other than --argscmd)
12322 if {[catch {
12323 set f [eval exec git rev-parse --no-revs --no-flags $revtreeargs]
12324 set cmdline_files [split $f "\n"]
12325 set n [llength $cmdline_files]
12326 set revtreeargs [lrange $revtreeargs 0 end-$n]
12327 # Unfortunately git rev-parse doesn't produce an error when
12328 # something is both a revision and a filename. To be consistent
12329 # with git log and git rev-list, check revtreeargs for filenames.
12330 foreach arg $revtreeargs {
12331 if {[file exists $arg]} {
12332 show_error {} . [mc "Ambiguous argument '%s': both revision\
12333 and filename" $arg]
12334 exit 1
12337 } err]} {
12338 # unfortunately we get both stdout and stderr in $err,
12339 # so look for "fatal:".
12340 set i [string first "fatal:" $err]
12341 if {$i > 0} {
12342 set err [string range $err [expr {$i + 6}] end]
12344 show_error {} . "[mc "Bad arguments to gitk:"]\n$err"
12345 exit 1
12349 set nullid "0000000000000000000000000000000000000000"
12350 set nullid2 "0000000000000000000000000000000000000001"
12351 set nullfile "/dev/null"
12353 set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
12354 if {![info exists have_ttk]} {
12355 set have_ttk [llength [info commands ::ttk::style]]
12357 set use_ttk [expr {$have_ttk && $want_ttk}]
12358 set NS [expr {$use_ttk ? "ttk" : ""}]
12360 regexp {^git version ([\d.]*\d)} [exec git version] _ git_version
12362 set show_notes {}
12363 if {[package vcompare $git_version "1.6.6.2"] >= 0} {
12364 set show_notes "--show-notes"
12367 set appname "gitk"
12369 set runq {}
12370 set history {}
12371 set historyindex 0
12372 set fh_serial 0
12373 set nhl_names {}
12374 set highlight_paths {}
12375 set findpattern {}
12376 set searchdirn -forwards
12377 set boldids {}
12378 set boldnameids {}
12379 set diffelide {0 0}
12380 set markingmatches 0
12381 set linkentercount 0
12382 set need_redisplay 0
12383 set nrows_drawn 0
12384 set firsttabstop 0
12386 set nextviewnum 1
12387 set curview 0
12388 set selectedview 0
12389 set selectedhlview [mc "None"]
12390 set highlight_related [mc "None"]
12391 set highlight_files {}
12392 set viewfiles(0) {}
12393 set viewperm(0) 0
12394 set viewchanged(0) 0
12395 set viewargs(0) {}
12396 set viewargscmd(0) {}
12398 set selectedline {}
12399 set numcommits 0
12400 set loginstance 0
12401 set cmdlineok 0
12402 set stopped 0
12403 set stuffsaved 0
12404 set patchnum 0
12405 set lserial 0
12406 set hasworktree [hasworktree]
12407 set cdup {}
12408 if {[expr {[exec git rev-parse --is-inside-work-tree] == "true"}]} {
12409 set cdup [exec git rev-parse --show-cdup]
12411 set worktree [exec git rev-parse --show-toplevel]
12412 setcoords
12413 makewindow
12414 catch {
12415 image create photo gitlogo -width 16 -height 16
12417 image create photo gitlogominus -width 4 -height 2
12418 gitlogominus put #C00000 -to 0 0 4 2
12419 gitlogo copy gitlogominus -to 1 5
12420 gitlogo copy gitlogominus -to 6 5
12421 gitlogo copy gitlogominus -to 11 5
12422 image delete gitlogominus
12424 image create photo gitlogoplus -width 4 -height 4
12425 gitlogoplus put #008000 -to 1 0 3 4
12426 gitlogoplus put #008000 -to 0 1 4 3
12427 gitlogo copy gitlogoplus -to 1 9
12428 gitlogo copy gitlogoplus -to 6 9
12429 gitlogo copy gitlogoplus -to 11 9
12430 image delete gitlogoplus
12432 image create photo gitlogo32 -width 32 -height 32
12433 gitlogo32 copy gitlogo -zoom 2 2
12435 wm iconphoto . -default gitlogo gitlogo32
12437 # wait for the window to become visible
12438 tkwait visibility .
12439 set_window_title
12440 update
12441 readrefs
12443 if {$cmdline_files ne {} || $revtreeargs ne {} || $revtreeargscmd ne {}} {
12444 # create a view for the files/dirs specified on the command line
12445 set curview 1
12446 set selectedview 1
12447 set nextviewnum 2
12448 set viewname(1) [mc "Command line"]
12449 set viewfiles(1) $cmdline_files
12450 set viewargs(1) $revtreeargs
12451 set viewargscmd(1) $revtreeargscmd
12452 set viewperm(1) 0
12453 set viewchanged(1) 0
12454 set vdatemode(1) 0
12455 addviewmenu 1
12456 .bar.view entryconf [mca "&Edit view..."] -state normal
12457 .bar.view entryconf [mca "&Delete view"] -state normal
12460 if {[info exists permviews]} {
12461 foreach v $permviews {
12462 set n $nextviewnum
12463 incr nextviewnum
12464 set viewname($n) [lindex $v 0]
12465 set viewfiles($n) [lindex $v 1]
12466 set viewargs($n) [lindex $v 2]
12467 set viewargscmd($n) [lindex $v 3]
12468 set viewperm($n) 1
12469 set viewchanged($n) 0
12470 addviewmenu $n
12474 if {[tk windowingsystem] eq "win32"} {
12475 focus -force .
12478 getcommits {}
12480 # Local variables:
12481 # mode: tcl
12482 # indent-tabs-mode: t
12483 # tab-width: 8
12484 # End: