1#!/bin/sh
2# Tcl ignores the next line -*- tcl -*- \
3exec wish "$0" -- "$@"
4
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.
9
10package require Tk
11
12proc hasworktree {} {
13 return [expr {[exec git rev-parse --is-bare-repository] == "false" &&
14 [exec git rev-parse --is-inside-git-dir] == "false"}]
15}
16
17proc 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]
22 }
23 return [file tail $n]
24}
25
26proc gitworktree {} {
27 variable _gitworktree
28 if {[info exists _gitworktree]} {
29 return $_gitworktree
30 }
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]]
40 }
41 }
42 }
43 return $_gitworktree
44}
45
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.
51proc run args {
52 global isonrunq runq currunq
53
54 set script $args
55 if {[info exists isonrunq($script)]} return
56 if {$runq eq {} && ![info exists currunq]} {
57 after idle dorunq
58 }
59 lappend runq [list {} $script]
60 set isonrunq($script) 1
61}
62
63proc filerun {fd script} {
64 fileevent $fd readable [list filereadable $fd $script]
65}
66
67proc filereadable {fd script} {
68 global runq currunq
69
70 fileevent $fd readable {}
71 if {$runq eq {} && ![info exists currunq]} {
72 after idle dorunq
73 }
74 lappend runq [list $fd $script]
75}
76
77proc nukefile {fd} {
78 global runq
79
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
85 }
86 }
87}
88
89proc dorunq {} {
90 global isonrunq runq currunq
91
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]
110 }
111 } elseif {$fd eq {}} {
112 unset isonrunq($script)
113 }
114 set t0 $t1
115 if {$t1 - $tstart >= 80} break
116 }
117 if {$runq ne {}} {
118 after idle dorunq
119 }
120}
121
122proc reg_instance {fd} {
123 global commfd leftover loginstance
124
125 set i [incr loginstance]
126 set commfd($i) $fd
127 set leftover($i) {}
128 return $i
129}
130
131proc unmerged_files {files} {
132 global nr_unmerged
133
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
142 }
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
151 }
152 }
153 catch {close $fd}
154 return $mlist
155}
156
157proc parseviewargs {n arglist} {
158 global vdatemode vmergeonly vflags vdflags vrevs vfiltered vorigargs env
159 global vinlinediff
160 global worddiff git_version
161
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
179 }
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
187 }
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
197 }
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.
207 }
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"]
213 }
214 }
215 "--word-diff*" {
216 if {[package vcompare $git_version "1.7.2"] >= 0} {
217 set worddiff [mc "Markup words"]
218 }
219 }
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
226 }
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
237 }
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
245 }
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
252 }
253 "--not" - "--all" {
254 lappend revargs $arg
255 }
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
260 }
261 "--no-replace-objects" {
262 set env(GIT_NO_REPLACE_OBJECTS) "1"
263 }
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
272 }
273 lappend glflags $arg
274 }
275 default {
276 # Non-flag arguments specify commits or ranges of commits
277 if {[string match "*...*" $arg]} {
278 lappend revargs --gitk-symmetric-diff-marker
279 }
280 lappend revargs $arg
281 }
282 }
283 }
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
290}
291
292proc parseviewrevs {view revs} {
293 global vposids vnegids
294
295 if {$revs eq {}} {
296 set revs HEAD
297 }
298 if {[catch {set ids [eval exec git rev-parse $revs]} err]} {
299 # we get stdout followed by stderr in $err
300 # for an unknown rev, git rev-parse echoes it and then errors out
301 set errlines [split $err "\n"]
302 set badrev {}
303 for {set l 0} {$l < [llength $errlines]} {incr l} {
304 set line [lindex $errlines $l]
305 if {!([string length $line] == 40 && [string is xdigit $line])} {
306 if {[string match "fatal:*" $line]} {
307 if {[string match "fatal: ambiguous argument*" $line]
308 && $badrev ne {}} {
309 if {[llength $badrev] == 1} {
310 set err "unknown revision $badrev"
311 } else {
312 set err "unknown revisions: [join $badrev ", "]"
313 }
314 } else {
315 set err [join [lrange $errlines $l end] "\n"]
316 }
317 break
318 }
319 lappend badrev $line
320 }
321 }
322 error_popup "[mc "Error parsing revisions:"] $err"
323 return {}
324 }
325 set ret {}
326 set pos {}
327 set neg {}
328 set sdm 0
329 foreach id [split $ids "\n"] {
330 if {$id eq "--gitk-symmetric-diff-marker"} {
331 set sdm 4
332 } elseif {[string match "^*" $id]} {
333 if {$sdm != 1} {
334 lappend ret $id
335 if {$sdm == 3} {
336 set sdm 0
337 }
338 }
339 lappend neg [string range $id 1 end]
340 } else {
341 if {$sdm != 2} {
342 lappend ret $id
343 } else {
344 lset ret end $id...[lindex $ret end]
345 }
346 lappend pos $id
347 }
348 incr sdm -1
349 }
350 set vposids($view) $pos
351 set vnegids($view) $neg
352 return $ret
353}
354
355# Start off a git log process and arrange to read its output
356proc start_rev_list {view} {
357 global startmsecs commitidx viewcomplete curview
358 global tclencoding
359 global viewargs viewargscmd viewfiles vfilelimit
360 global showlocalchanges
361 global viewactive viewinstances vmergeonly
362 global mainheadid viewmainheadid viewmainheadid_orig
363 global vcanopt vflags vrevs vorigargs
364 global show_notes
365
366 set startmsecs [clock clicks -milliseconds]
367 set commitidx($view) 0
368 # these are set this way for the error exits
369 set viewcomplete($view) 1
370 set viewactive($view) 0
371 varcinit $view
372
373 set args $viewargs($view)
374 if {$viewargscmd($view) ne {}} {
375 if {[catch {
376 set str [exec sh -c $viewargscmd($view)]
377 } err]} {
378 error_popup "[mc "Error executing --argscmd command:"] $err"
379 return 0
380 }
381 set args [concat $args [split $str "\n"]]
382 }
383 set vcanopt($view) [parseviewargs $view $args]
384
385 set files $viewfiles($view)
386 if {$vmergeonly($view)} {
387 set files [unmerged_files $files]
388 if {$files eq {}} {
389 global nr_unmerged
390 if {$nr_unmerged == 0} {
391 error_popup [mc "No files selected: --merge specified but\
392 no files are unmerged."]
393 } else {
394 error_popup [mc "No files selected: --merge specified but\
395 no unmerged files are within file limit."]
396 }
397 return 0
398 }
399 }
400 set vfilelimit($view) $files
401
402 if {$vcanopt($view)} {
403 set revs [parseviewrevs $view $vrevs($view)]
404 if {$revs eq {}} {
405 return 0
406 }
407 set args [concat $vflags($view) $revs]
408 } else {
409 set args $vorigargs($view)
410 }
411
412 if {[catch {
413 set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
414 --parents --boundary $args "--" $files] r]
415 } err]} {
416 error_popup "[mc "Error executing git log:"] $err"
417 return 0
418 }
419 set i [reg_instance $fd]
420 set viewinstances($view) [list $i]
421 set viewmainheadid($view) $mainheadid
422 set viewmainheadid_orig($view) $mainheadid
423 if {$files ne {} && $mainheadid ne {}} {
424 get_viewmainhead $view
425 }
426 if {$showlocalchanges && $viewmainheadid($view) ne {}} {
427 interestedin $viewmainheadid($view) dodiffindex
428 }
429 fconfigure $fd -blocking 0 -translation lf -eofchar {}
430 if {$tclencoding != {}} {
431 fconfigure $fd -encoding $tclencoding
432 }
433 filerun $fd [list getcommitlines $fd $i $view 0]
434 nowbusy $view [mc "Reading"]
435 set viewcomplete($view) 0
436 set viewactive($view) 1
437 return 1
438}
439
440proc stop_instance {inst} {
441 global commfd leftover
442
443 set fd $commfd($inst)
444 catch {
445 set pid [pid $fd]
446
447 if {$::tcl_platform(platform) eq {windows}} {
448 exec kill -f $pid
449 } else {
450 exec kill $pid
451 }
452 }
453 catch {close $fd}
454 nukefile $fd
455 unset commfd($inst)
456 unset leftover($inst)
457}
458
459proc stop_backends {} {
460 global commfd
461
462 foreach inst [array names commfd] {
463 stop_instance $inst
464 }
465}
466
467proc stop_rev_list {view} {
468 global viewinstances
469
470 foreach inst $viewinstances($view) {
471 stop_instance $inst
472 }
473 set viewinstances($view) {}
474}
475
476proc reset_pending_select {selid} {
477 global pending_select mainheadid selectheadid
478
479 if {$selid ne {}} {
480 set pending_select $selid
481 } elseif {$selectheadid ne {}} {
482 set pending_select $selectheadid
483 } else {
484 set pending_select $mainheadid
485 }
486}
487
488proc getcommits {selid} {
489 global canv curview need_redisplay viewactive
490
491 initlayout
492 if {[start_rev_list $curview]} {
493 reset_pending_select $selid
494 show_status [mc "Reading commits..."]
495 set need_redisplay 1
496 } else {
497 show_status [mc "No commits selected"]
498 }
499}
500
501proc updatecommits {} {
502 global curview vcanopt vorigargs vfilelimit viewinstances
503 global viewactive viewcomplete tclencoding
504 global startmsecs showneartags showlocalchanges
505 global mainheadid viewmainheadid viewmainheadid_orig pending_select
506 global hasworktree
507 global varcid vposids vnegids vflags vrevs
508 global show_notes
509
510 set hasworktree [hasworktree]
511 rereadrefs
512 set view $curview
513 if {$mainheadid ne $viewmainheadid_orig($view)} {
514 if {$showlocalchanges} {
515 dohidelocalchanges
516 }
517 set viewmainheadid($view) $mainheadid
518 set viewmainheadid_orig($view) $mainheadid
519 if {$vfilelimit($view) ne {}} {
520 get_viewmainhead $view
521 }
522 }
523 if {$showlocalchanges} {
524 doshowlocalchanges
525 }
526 if {$vcanopt($view)} {
527 set oldpos $vposids($view)
528 set oldneg $vnegids($view)
529 set revs [parseviewrevs $view $vrevs($view)]
530 if {$revs eq {}} {
531 return
532 }
533 # note: getting the delta when negative refs change is hard,
534 # and could require multiple git log invocations, so in that
535 # case we ask git log for all the commits (not just the delta)
536 if {$oldneg eq $vnegids($view)} {
537 set newrevs {}
538 set npos 0
539 # take out positive refs that we asked for before or
540 # that we have already seen
541 foreach rev $revs {
542 if {[string length $rev] == 40} {
543 if {[lsearch -exact $oldpos $rev] < 0
544 && ![info exists varcid($view,$rev)]} {
545 lappend newrevs $rev
546 incr npos
547 }
548 } else {
549 lappend $newrevs $rev
550 }
551 }
552 if {$npos == 0} return
553 set revs $newrevs
554 set vposids($view) [lsort -unique [concat $oldpos $vposids($view)]]
555 }
556 set args [concat $vflags($view) $revs --not $oldpos]
557 } else {
558 set args $vorigargs($view)
559 }
560 if {[catch {
561 set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
562 --parents --boundary $args "--" $vfilelimit($view)] r]
563 } err]} {
564 error_popup "[mc "Error executing git log:"] $err"
565 return
566 }
567 if {$viewactive($view) == 0} {
568 set startmsecs [clock clicks -milliseconds]
569 }
570 set i [reg_instance $fd]
571 lappend viewinstances($view) $i
572 fconfigure $fd -blocking 0 -translation lf -eofchar {}
573 if {$tclencoding != {}} {
574 fconfigure $fd -encoding $tclencoding
575 }
576 filerun $fd [list getcommitlines $fd $i $view 1]
577 incr viewactive($view)
578 set viewcomplete($view) 0
579 reset_pending_select {}
580 nowbusy $view [mc "Reading"]
581 if {$showneartags} {
582 getallcommits
583 }
584}
585
586proc reloadcommits {} {
587 global curview viewcomplete selectedline currentid thickerline
588 global showneartags treediffs commitinterest cached_commitrow
589 global targetid
590
591 set selid {}
592 if {$selectedline ne {}} {
593 set selid $currentid
594 }
595
596 if {!$viewcomplete($curview)} {
597 stop_rev_list $curview
598 }
599 resetvarcs $curview
600 set selectedline {}
601 catch {unset currentid}
602 catch {unset thickerline}
603 catch {unset treediffs}
604 readrefs
605 changedrefs
606 if {$showneartags} {
607 getallcommits
608 }
609 clear_display
610 catch {unset commitinterest}
611 catch {unset cached_commitrow}
612 catch {unset targetid}
613 setcanvscroll
614 getcommits $selid
615 return 0
616}
617
618# This makes a string representation of a positive integer which
619# sorts as a string in numerical order
620proc strrep {n} {
621 if {$n < 16} {
622 return [format "%x" $n]
623 } elseif {$n < 256} {
624 return [format "x%.2x" $n]
625 } elseif {$n < 65536} {
626 return [format "y%.4x" $n]
627 }
628 return [format "z%.8x" $n]
629}
630
631# Procedures used in reordering commits from git log (without
632# --topo-order) into the order for display.
633
634proc varcinit {view} {
635 global varcstart vupptr vdownptr vleftptr vbackptr varctok varcrow
636 global vtokmod varcmod vrowmod varcix vlastins
637
638 set varcstart($view) {{}}
639 set vupptr($view) {0}
640 set vdownptr($view) {0}
641 set vleftptr($view) {0}
642 set vbackptr($view) {0}
643 set varctok($view) {{}}
644 set varcrow($view) {{}}
645 set vtokmod($view) {}
646 set varcmod($view) 0
647 set vrowmod($view) 0
648 set varcix($view) {{}}
649 set vlastins($view) {0}
650}
651
652proc resetvarcs {view} {
653 global varcid varccommits parents children vseedcount ordertok
654 global vshortids
655
656 foreach vid [array names varcid $view,*] {
657 unset varcid($vid)
658 unset children($vid)
659 unset parents($vid)
660 }
661 foreach vid [array names vshortids $view,*] {
662 unset vshortids($vid)
663 }
664 # some commits might have children but haven't been seen yet
665 foreach vid [array names children $view,*] {
666 unset children($vid)
667 }
668 foreach va [array names varccommits $view,*] {
669 unset varccommits($va)
670 }
671 foreach vd [array names vseedcount $view,*] {
672 unset vseedcount($vd)
673 }
674 catch {unset ordertok}
675}
676
677# returns a list of the commits with no children
678proc seeds {v} {
679 global vdownptr vleftptr varcstart
680
681 set ret {}
682 set a [lindex $vdownptr($v) 0]
683 while {$a != 0} {
684 lappend ret [lindex $varcstart($v) $a]
685 set a [lindex $vleftptr($v) $a]
686 }
687 return $ret
688}
689
690proc newvarc {view id} {
691 global varcid varctok parents children vdatemode
692 global vupptr vdownptr vleftptr vbackptr varcrow varcix varcstart
693 global commitdata commitinfo vseedcount varccommits vlastins
694
695 set a [llength $varctok($view)]
696 set vid $view,$id
697 if {[llength $children($vid)] == 0 || $vdatemode($view)} {
698 if {![info exists commitinfo($id)]} {
699 parsecommit $id $commitdata($id) 1
700 }
701 set cdate [lindex [lindex $commitinfo($id) 4] 0]
702 if {![string is integer -strict $cdate]} {
703 set cdate 0
704 }
705 if {![info exists vseedcount($view,$cdate)]} {
706 set vseedcount($view,$cdate) -1
707 }
708 set c [incr vseedcount($view,$cdate)]
709 set cdate [expr {$cdate ^ 0xffffffff}]
710 set tok "s[strrep $cdate][strrep $c]"
711 } else {
712 set tok {}
713 }
714 set ka 0
715 if {[llength $children($vid)] > 0} {
716 set kid [lindex $children($vid) end]
717 set k $varcid($view,$kid)
718 if {[string compare [lindex $varctok($view) $k] $tok] > 0} {
719 set ki $kid
720 set ka $k
721 set tok [lindex $varctok($view) $k]
722 }
723 }
724 if {$ka != 0} {
725 set i [lsearch -exact $parents($view,$ki) $id]
726 set j [expr {[llength $parents($view,$ki)] - 1 - $i}]
727 append tok [strrep $j]
728 }
729 set c [lindex $vlastins($view) $ka]
730 if {$c == 0 || [string compare $tok [lindex $varctok($view) $c]] < 0} {
731 set c $ka
732 set b [lindex $vdownptr($view) $ka]
733 } else {
734 set b [lindex $vleftptr($view) $c]
735 }
736 while {$b != 0 && [string compare $tok [lindex $varctok($view) $b]] >= 0} {
737 set c $b
738 set b [lindex $vleftptr($view) $c]
739 }
740 if {$c == $ka} {
741 lset vdownptr($view) $ka $a
742 lappend vbackptr($view) 0
743 } else {
744 lset vleftptr($view) $c $a
745 lappend vbackptr($view) $c
746 }
747 lset vlastins($view) $ka $a
748 lappend vupptr($view) $ka
749 lappend vleftptr($view) $b
750 if {$b != 0} {
751 lset vbackptr($view) $b $a
752 }
753 lappend varctok($view) $tok
754 lappend varcstart($view) $id
755 lappend vdownptr($view) 0
756 lappend varcrow($view) {}
757 lappend varcix($view) {}
758 set varccommits($view,$a) {}
759 lappend vlastins($view) 0
760 return $a
761}
762
763proc splitvarc {p v} {
764 global varcid varcstart varccommits varctok vtokmod
765 global vupptr vdownptr vleftptr vbackptr varcix varcrow vlastins
766
767 set oa $varcid($v,$p)
768 set otok [lindex $varctok($v) $oa]
769 set ac $varccommits($v,$oa)
770 set i [lsearch -exact $varccommits($v,$oa) $p]
771 if {$i <= 0} return
772 set na [llength $varctok($v)]
773 # "%" sorts before "0"...
774 set tok "$otok%[strrep $i]"
775 lappend varctok($v) $tok
776 lappend varcrow($v) {}
777 lappend varcix($v) {}
778 set varccommits($v,$oa) [lrange $ac 0 [expr {$i - 1}]]
779 set varccommits($v,$na) [lrange $ac $i end]
780 lappend varcstart($v) $p
781 foreach id $varccommits($v,$na) {
782 set varcid($v,$id) $na
783 }
784 lappend vdownptr($v) [lindex $vdownptr($v) $oa]
785 lappend vlastins($v) [lindex $vlastins($v) $oa]
786 lset vdownptr($v) $oa $na
787 lset vlastins($v) $oa 0
788 lappend vupptr($v) $oa
789 lappend vleftptr($v) 0
790 lappend vbackptr($v) 0
791 for {set b [lindex $vdownptr($v) $na]} {$b != 0} {set b [lindex $vleftptr($v) $b]} {
792 lset vupptr($v) $b $na
793 }
794 if {[string compare $otok $vtokmod($v)] <= 0} {
795 modify_arc $v $oa
796 }
797}
798
799proc renumbervarc {a v} {
800 global parents children varctok varcstart varccommits
801 global vupptr vdownptr vleftptr vbackptr vlastins varcid vtokmod vdatemode
802
803 set t1 [clock clicks -milliseconds]
804 set todo {}
805 set isrelated($a) 1
806 set kidchanged($a) 1
807 set ntot 0
808 while {$a != 0} {
809 if {[info exists isrelated($a)]} {
810 lappend todo $a
811 set id [lindex $varccommits($v,$a) end]
812 foreach p $parents($v,$id) {
813 if {[info exists varcid($v,$p)]} {
814 set isrelated($varcid($v,$p)) 1
815 }
816 }
817 }
818 incr ntot
819 set b [lindex $vdownptr($v) $a]
820 if {$b == 0} {
821 while {$a != 0} {
822 set b [lindex $vleftptr($v) $a]
823 if {$b != 0} break
824 set a [lindex $vupptr($v) $a]
825 }
826 }
827 set a $b
828 }
829 foreach a $todo {
830 if {![info exists kidchanged($a)]} continue
831 set id [lindex $varcstart($v) $a]
832 if {[llength $children($v,$id)] > 1} {
833 set children($v,$id) [lsort -command [list vtokcmp $v] \
834 $children($v,$id)]
835 }
836 set oldtok [lindex $varctok($v) $a]
837 if {!$vdatemode($v)} {
838 set tok {}
839 } else {
840 set tok $oldtok
841 }
842 set ka 0
843 set kid [last_real_child $v,$id]
844 if {$kid ne {}} {
845 set k $varcid($v,$kid)
846 if {[string compare [lindex $varctok($v) $k] $tok] > 0} {
847 set ki $kid
848 set ka $k
849 set tok [lindex $varctok($v) $k]
850 }
851 }
852 if {$ka != 0} {
853 set i [lsearch -exact $parents($v,$ki) $id]
854 set j [expr {[llength $parents($v,$ki)] - 1 - $i}]
855 append tok [strrep $j]
856 }
857 if {$tok eq $oldtok} {
858 continue
859 }
860 set id [lindex $varccommits($v,$a) end]
861 foreach p $parents($v,$id) {
862 if {[info exists varcid($v,$p)]} {
863 set kidchanged($varcid($v,$p)) 1
864 } else {
865 set sortkids($p) 1
866 }
867 }
868 lset varctok($v) $a $tok
869 set b [lindex $vupptr($v) $a]
870 if {$b != $ka} {
871 if {[string compare [lindex $varctok($v) $ka] $vtokmod($v)] < 0} {
872 modify_arc $v $ka
873 }
874 if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
875 modify_arc $v $b
876 }
877 set c [lindex $vbackptr($v) $a]
878 set d [lindex $vleftptr($v) $a]
879 if {$c == 0} {
880 lset vdownptr($v) $b $d
881 } else {
882 lset vleftptr($v) $c $d
883 }
884 if {$d != 0} {
885 lset vbackptr($v) $d $c
886 }
887 if {[lindex $vlastins($v) $b] == $a} {
888 lset vlastins($v) $b $c
889 }
890 lset vupptr($v) $a $ka
891 set c [lindex $vlastins($v) $ka]
892 if {$c == 0 || \
893 [string compare $tok [lindex $varctok($v) $c]] < 0} {
894 set c $ka
895 set b [lindex $vdownptr($v) $ka]
896 } else {
897 set b [lindex $vleftptr($v) $c]
898 }
899 while {$b != 0 && \
900 [string compare $tok [lindex $varctok($v) $b]] >= 0} {
901 set c $b
902 set b [lindex $vleftptr($v) $c]
903 }
904 if {$c == $ka} {
905 lset vdownptr($v) $ka $a
906 lset vbackptr($v) $a 0
907 } else {
908 lset vleftptr($v) $c $a
909 lset vbackptr($v) $a $c
910 }
911 lset vleftptr($v) $a $b
912 if {$b != 0} {
913 lset vbackptr($v) $b $a
914 }
915 lset vlastins($v) $ka $a
916 }
917 }
918 foreach id [array names sortkids] {
919 if {[llength $children($v,$id)] > 1} {
920 set children($v,$id) [lsort -command [list vtokcmp $v] \
921 $children($v,$id)]
922 }
923 }
924 set t2 [clock clicks -milliseconds]
925 #puts "renumbervarc did [llength $todo] of $ntot arcs in [expr {$t2-$t1}]ms"
926}
927
928# Fix up the graph after we have found out that in view $v,
929# $p (a commit that we have already seen) is actually the parent
930# of the last commit in arc $a.
931proc fix_reversal {p a v} {
932 global varcid varcstart varctok vupptr
933
934 set pa $varcid($v,$p)
935 if {$p ne [lindex $varcstart($v) $pa]} {
936 splitvarc $p $v
937 set pa $varcid($v,$p)
938 }
939 # seeds always need to be renumbered
940 if {[lindex $vupptr($v) $pa] == 0 ||
941 [string compare [lindex $varctok($v) $a] \
942 [lindex $varctok($v) $pa]] > 0} {
943 renumbervarc $pa $v
944 }
945}
946
947proc insertrow {id p v} {
948 global cmitlisted children parents varcid varctok vtokmod
949 global varccommits ordertok commitidx numcommits curview
950 global targetid targetrow vshortids
951
952 readcommit $id
953 set vid $v,$id
954 set cmitlisted($vid) 1
955 set children($vid) {}
956 set parents($vid) [list $p]
957 set a [newvarc $v $id]
958 set varcid($vid) $a
959 lappend vshortids($v,[string range $id 0 3]) $id
960 if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] < 0} {
961 modify_arc $v $a
962 }
963 lappend varccommits($v,$a) $id
964 set vp $v,$p
965 if {[llength [lappend children($vp) $id]] > 1} {
966 set children($vp) [lsort -command [list vtokcmp $v] $children($vp)]
967 catch {unset ordertok}
968 }
969 fix_reversal $p $a $v
970 incr commitidx($v)
971 if {$v == $curview} {
972 set numcommits $commitidx($v)
973 setcanvscroll
974 if {[info exists targetid]} {
975 if {![comes_before $targetid $p]} {
976 incr targetrow
977 }
978 }
979 }
980}
981
982proc insertfakerow {id p} {
983 global varcid varccommits parents children cmitlisted
984 global commitidx varctok vtokmod targetid targetrow curview numcommits
985
986 set v $curview
987 set a $varcid($v,$p)
988 set i [lsearch -exact $varccommits($v,$a) $p]
989 if {$i < 0} {
990 puts "oops: insertfakerow can't find [shortids $p] on arc $a"
991 return
992 }
993 set children($v,$id) {}
994 set parents($v,$id) [list $p]
995 set varcid($v,$id) $a
996 lappend children($v,$p) $id
997 set cmitlisted($v,$id) 1
998 set numcommits [incr commitidx($v)]
999 # note we deliberately don't update varcstart($v) even if $i == 0
1000 set varccommits($v,$a) [linsert $varccommits($v,$a) $i $id]
1001 modify_arc $v $a $i
1002 if {[info exists targetid]} {
1003 if {![comes_before $targetid $p]} {
1004 incr targetrow
1005 }
1006 }
1007 setcanvscroll
1008 drawvisible
1009}
1010
1011proc removefakerow {id} {
1012 global varcid varccommits parents children commitidx
1013 global varctok vtokmod cmitlisted currentid selectedline
1014 global targetid curview numcommits
1015
1016 set v $curview
1017 if {[llength $parents($v,$id)] != 1} {
1018 puts "oops: removefakerow [shortids $id] has [llength $parents($v,$id)] parents"
1019 return
1020 }
1021 set p [lindex $parents($v,$id) 0]
1022 set a $varcid($v,$id)
1023 set i [lsearch -exact $varccommits($v,$a) $id]
1024 if {$i < 0} {
1025 puts "oops: removefakerow can't find [shortids $id] on arc $a"
1026 return
1027 }
1028 unset varcid($v,$id)
1029 set varccommits($v,$a) [lreplace $varccommits($v,$a) $i $i]
1030 unset parents($v,$id)
1031 unset children($v,$id)
1032 unset cmitlisted($v,$id)
1033 set numcommits [incr commitidx($v) -1]
1034 set j [lsearch -exact $children($v,$p) $id]
1035 if {$j >= 0} {
1036 set children($v,$p) [lreplace $children($v,$p) $j $j]
1037 }
1038 modify_arc $v $a $i
1039 if {[info exist currentid] && $id eq $currentid} {
1040 unset currentid
1041 set selectedline {}
1042 }
1043 if {[info exists targetid] && $targetid eq $id} {
1044 set targetid $p
1045 }
1046 setcanvscroll
1047 drawvisible
1048}
1049
1050proc real_children {vp} {
1051 global children nullid nullid2
1052
1053 set kids {}
1054 foreach id $children($vp) {
1055 if {$id ne $nullid && $id ne $nullid2} {
1056 lappend kids $id
1057 }
1058 }
1059 return $kids
1060}
1061
1062proc first_real_child {vp} {
1063 global children nullid nullid2
1064
1065 foreach id $children($vp) {
1066 if {$id ne $nullid && $id ne $nullid2} {
1067 return $id
1068 }
1069 }
1070 return {}
1071}
1072
1073proc last_real_child {vp} {
1074 global children nullid nullid2
1075
1076 set kids $children($vp)
1077 for {set i [llength $kids]} {[incr i -1] >= 0} {} {
1078 set id [lindex $kids $i]
1079 if {$id ne $nullid && $id ne $nullid2} {
1080 return $id
1081 }
1082 }
1083 return {}
1084}
1085
1086proc vtokcmp {v a b} {
1087 global varctok varcid
1088
1089 return [string compare [lindex $varctok($v) $varcid($v,$a)] \
1090 [lindex $varctok($v) $varcid($v,$b)]]
1091}
1092
1093# This assumes that if lim is not given, the caller has checked that
1094# arc a's token is less than $vtokmod($v)
1095proc modify_arc {v a {lim {}}} {
1096 global varctok vtokmod varcmod varcrow vupptr curview vrowmod varccommits
1097
1098 if {$lim ne {}} {
1099 set c [string compare [lindex $varctok($v) $a] $vtokmod($v)]
1100 if {$c > 0} return
1101 if {$c == 0} {
1102 set r [lindex $varcrow($v) $a]
1103 if {$r ne {} && $vrowmod($v) <= $r + $lim} return
1104 }
1105 }
1106 set vtokmod($v) [lindex $varctok($v) $a]
1107 set varcmod($v) $a
1108 if {$v == $curview} {
1109 while {$a != 0 && [lindex $varcrow($v) $a] eq {}} {
1110 set a [lindex $vupptr($v) $a]
1111 set lim {}
1112 }
1113 set r 0
1114 if {$a != 0} {
1115 if {$lim eq {}} {
1116 set lim [llength $varccommits($v,$a)]
1117 }
1118 set r [expr {[lindex $varcrow($v) $a] + $lim}]
1119 }
1120 set vrowmod($v) $r
1121 undolayout $r
1122 }
1123}
1124
1125proc update_arcrows {v} {
1126 global vtokmod varcmod vrowmod varcrow commitidx currentid selectedline
1127 global varcid vrownum varcorder varcix varccommits
1128 global vupptr vdownptr vleftptr varctok
1129 global displayorder parentlist curview cached_commitrow
1130
1131 if {$vrowmod($v) == $commitidx($v)} return
1132 if {$v == $curview} {
1133 if {[llength $displayorder] > $vrowmod($v)} {
1134 set displayorder [lrange $displayorder 0 [expr {$vrowmod($v) - 1}]]
1135 set parentlist [lrange $parentlist 0 [expr {$vrowmod($v) - 1}]]
1136 }
1137 catch {unset cached_commitrow}
1138 }
1139 set narctot [expr {[llength $varctok($v)] - 1}]
1140 set a $varcmod($v)
1141 while {$a != 0 && [lindex $varcix($v) $a] eq {}} {
1142 # go up the tree until we find something that has a row number,
1143 # or we get to a seed
1144 set a [lindex $vupptr($v) $a]
1145 }
1146 if {$a == 0} {
1147 set a [lindex $vdownptr($v) 0]
1148 if {$a == 0} return
1149 set vrownum($v) {0}
1150 set varcorder($v) [list $a]
1151 lset varcix($v) $a 0
1152 lset varcrow($v) $a 0
1153 set arcn 0
1154 set row 0
1155 } else {
1156 set arcn [lindex $varcix($v) $a]
1157 if {[llength $vrownum($v)] > $arcn + 1} {
1158 set vrownum($v) [lrange $vrownum($v) 0 $arcn]
1159 set varcorder($v) [lrange $varcorder($v) 0 $arcn]
1160 }
1161 set row [lindex $varcrow($v) $a]
1162 }
1163 while {1} {
1164 set p $a
1165 incr row [llength $varccommits($v,$a)]
1166 # go down if possible
1167 set b [lindex $vdownptr($v) $a]
1168 if {$b == 0} {
1169 # if not, go left, or go up until we can go left
1170 while {$a != 0} {
1171 set b [lindex $vleftptr($v) $a]
1172 if {$b != 0} break
1173 set a [lindex $vupptr($v) $a]
1174 }
1175 if {$a == 0} break
1176 }
1177 set a $b
1178 incr arcn
1179 lappend vrownum($v) $row
1180 lappend varcorder($v) $a
1181 lset varcix($v) $a $arcn
1182 lset varcrow($v) $a $row
1183 }
1184 set vtokmod($v) [lindex $varctok($v) $p]
1185 set varcmod($v) $p
1186 set vrowmod($v) $row
1187 if {[info exists currentid]} {
1188 set selectedline [rowofcommit $currentid]
1189 }
1190}
1191
1192# Test whether view $v contains commit $id
1193proc commitinview {id v} {
1194 global varcid
1195
1196 return [info exists varcid($v,$id)]
1197}
1198
1199# Return the row number for commit $id in the current view
1200proc rowofcommit {id} {
1201 global varcid varccommits varcrow curview cached_commitrow
1202 global varctok vtokmod
1203
1204 set v $curview
1205 if {![info exists varcid($v,$id)]} {
1206 puts "oops rowofcommit no arc for [shortids $id]"
1207 return {}
1208 }
1209 set a $varcid($v,$id)
1210 if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] >= 0} {
1211 update_arcrows $v
1212 }
1213 if {[info exists cached_commitrow($id)]} {
1214 return $cached_commitrow($id)
1215 }
1216 set i [lsearch -exact $varccommits($v,$a) $id]
1217 if {$i < 0} {
1218 puts "oops didn't find commit [shortids $id] in arc $a"
1219 return {}
1220 }
1221 incr i [lindex $varcrow($v) $a]
1222 set cached_commitrow($id) $i
1223 return $i
1224}
1225
1226# Returns 1 if a is on an earlier row than b, otherwise 0
1227proc comes_before {a b} {
1228 global varcid varctok curview
1229
1230 set v $curview
1231 if {$a eq $b || ![info exists varcid($v,$a)] || \
1232 ![info exists varcid($v,$b)]} {
1233 return 0
1234 }
1235 if {$varcid($v,$a) != $varcid($v,$b)} {
1236 return [expr {[string compare [lindex $varctok($v) $varcid($v,$a)] \
1237 [lindex $varctok($v) $varcid($v,$b)]] < 0}]
1238 }
1239 return [expr {[rowofcommit $a] < [rowofcommit $b]}]
1240}
1241
1242proc bsearch {l elt} {
1243 if {[llength $l] == 0 || $elt <= [lindex $l 0]} {
1244 return 0
1245 }
1246 set lo 0
1247 set hi [llength $l]
1248 while {$hi - $lo > 1} {
1249 set mid [expr {int(($lo + $hi) / 2)}]
1250 set t [lindex $l $mid]
1251 if {$elt < $t} {
1252 set hi $mid
1253 } elseif {$elt > $t} {
1254 set lo $mid
1255 } else {
1256 return $mid
1257 }
1258 }
1259 return $lo
1260}
1261
1262# Make sure rows $start..$end-1 are valid in displayorder and parentlist
1263proc make_disporder {start end} {
1264 global vrownum curview commitidx displayorder parentlist
1265 global varccommits varcorder parents vrowmod varcrow
1266 global d_valid_start d_valid_end
1267
1268 if {$end > $vrowmod($curview)} {
1269 update_arcrows $curview
1270 }
1271 set ai [bsearch $vrownum($curview) $start]
1272 set start [lindex $vrownum($curview) $ai]
1273 set narc [llength $vrownum($curview)]
1274 for {set r $start} {$ai < $narc && $r < $end} {incr ai} {
1275 set a [lindex $varcorder($curview) $ai]
1276 set l [llength $displayorder]
1277 set al [llength $varccommits($curview,$a)]
1278 if {$l < $r + $al} {
1279 if {$l < $r} {
1280 set pad [ntimes [expr {$r - $l}] {}]
1281 set displayorder [concat $displayorder $pad]
1282 set parentlist [concat $parentlist $pad]
1283 } elseif {$l > $r} {
1284 set displayorder [lrange $displayorder 0 [expr {$r - 1}]]
1285 set parentlist [lrange $parentlist 0 [expr {$r - 1}]]
1286 }
1287 foreach id $varccommits($curview,$a) {
1288 lappend displayorder $id
1289 lappend parentlist $parents($curview,$id)
1290 }
1291 } elseif {[lindex $displayorder [expr {$r + $al - 1}]] eq {}} {
1292 set i $r
1293 foreach id $varccommits($curview,$a) {
1294 lset displayorder $i $id
1295 lset parentlist $i $parents($curview,$id)
1296 incr i
1297 }
1298 }
1299 incr r $al
1300 }
1301}
1302
1303proc commitonrow {row} {
1304 global displayorder
1305
1306 set id [lindex $displayorder $row]
1307 if {$id eq {}} {
1308 make_disporder $row [expr {$row + 1}]
1309 set id [lindex $displayorder $row]
1310 }
1311 return $id
1312}
1313
1314proc closevarcs {v} {
1315 global varctok varccommits varcid parents children
1316 global cmitlisted commitidx vtokmod
1317
1318 set missing_parents 0
1319 set scripts {}
1320 set narcs [llength $varctok($v)]
1321 for {set a 1} {$a < $narcs} {incr a} {
1322 set id [lindex $varccommits($v,$a) end]
1323 foreach p $parents($v,$id) {
1324 if {[info exists varcid($v,$p)]} continue
1325 # add p as a new commit
1326 incr missing_parents
1327 set cmitlisted($v,$p) 0
1328 set parents($v,$p) {}
1329 if {[llength $children($v,$p)] == 1 &&
1330 [llength $parents($v,$id)] == 1} {
1331 set b $a
1332 } else {
1333 set b [newvarc $v $p]
1334 }
1335 set varcid($v,$p) $b
1336 if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
1337 modify_arc $v $b
1338 }
1339 lappend varccommits($v,$b) $p
1340 incr commitidx($v)
1341 set scripts [check_interest $p $scripts]
1342 }
1343 }
1344 if {$missing_parents > 0} {
1345 foreach s $scripts {
1346 eval $s
1347 }
1348 }
1349}
1350
1351# Use $rwid as a substitute for $id, i.e. reparent $id's children to $rwid
1352# Assumes we already have an arc for $rwid.
1353proc rewrite_commit {v id rwid} {
1354 global children parents varcid varctok vtokmod varccommits
1355
1356 foreach ch $children($v,$id) {
1357 # make $rwid be $ch's parent in place of $id
1358 set i [lsearch -exact $parents($v,$ch) $id]
1359 if {$i < 0} {
1360 puts "oops rewrite_commit didn't find $id in parent list for $ch"
1361 }
1362 set parents($v,$ch) [lreplace $parents($v,$ch) $i $i $rwid]
1363 # add $ch to $rwid's children and sort the list if necessary
1364 if {[llength [lappend children($v,$rwid) $ch]] > 1} {
1365 set children($v,$rwid) [lsort -command [list vtokcmp $v] \
1366 $children($v,$rwid)]
1367 }
1368 # fix the graph after joining $id to $rwid
1369 set a $varcid($v,$ch)
1370 fix_reversal $rwid $a $v
1371 # parentlist is wrong for the last element of arc $a
1372 # even if displayorder is right, hence the 3rd arg here
1373 modify_arc $v $a [expr {[llength $varccommits($v,$a)] - 1}]
1374 }
1375}
1376
1377# Mechanism for registering a command to be executed when we come
1378# across a particular commit. To handle the case when only the
1379# prefix of the commit is known, the commitinterest array is now
1380# indexed by the first 4 characters of the ID. Each element is a
1381# list of id, cmd pairs.
1382proc interestedin {id cmd} {
1383 global commitinterest
1384
1385 lappend commitinterest([string range $id 0 3]) $id $cmd
1386}
1387
1388proc check_interest {id scripts} {
1389 global commitinterest
1390
1391 set prefix [string range $id 0 3]
1392 if {[info exists commitinterest($prefix)]} {
1393 set newlist {}
1394 foreach {i script} $commitinterest($prefix) {
1395 if {[string match "$i*" $id]} {
1396 lappend scripts [string map [list "%I" $id "%P" $i] $script]
1397 } else {
1398 lappend newlist $i $script
1399 }
1400 }
1401 if {$newlist ne {}} {
1402 set commitinterest($prefix) $newlist
1403 } else {
1404 unset commitinterest($prefix)
1405 }
1406 }
1407 return $scripts
1408}
1409
1410proc getcommitlines {fd inst view updating} {
1411 global cmitlisted leftover
1412 global commitidx commitdata vdatemode
1413 global parents children curview hlview
1414 global idpending ordertok
1415 global varccommits varcid varctok vtokmod vfilelimit vshortids
1416
1417 set stuff [read $fd 500000]
1418 # git log doesn't terminate the last commit with a null...
1419 if {$stuff == {} && $leftover($inst) ne {} && [eof $fd]} {
1420 set stuff "\0"
1421 }
1422 if {$stuff == {}} {
1423 if {![eof $fd]} {
1424 return 1
1425 }
1426 global commfd viewcomplete viewactive viewname
1427 global viewinstances
1428 unset commfd($inst)
1429 set i [lsearch -exact $viewinstances($view) $inst]
1430 if {$i >= 0} {
1431 set viewinstances($view) [lreplace $viewinstances($view) $i $i]
1432 }
1433 # set it blocking so we wait for the process to terminate
1434 fconfigure $fd -blocking 1
1435 if {[catch {close $fd} err]} {
1436 set fv {}
1437 if {$view != $curview} {
1438 set fv " for the \"$viewname($view)\" view"
1439 }
1440 if {[string range $err 0 4] == "usage"} {
1441 set err "Gitk: error reading commits$fv:\
1442 bad arguments to git log."
1443 if {$viewname($view) eq "Command line"} {
1444 append err \
1445 " (Note: arguments to gitk are passed to git log\
1446 to allow selection of commits to be displayed.)"
1447 }
1448 } else {
1449 set err "Error reading commits$fv: $err"
1450 }
1451 error_popup $err
1452 }
1453 if {[incr viewactive($view) -1] <= 0} {
1454 set viewcomplete($view) 1
1455 # Check if we have seen any ids listed as parents that haven't
1456 # appeared in the list
1457 closevarcs $view
1458 notbusy $view
1459 }
1460 if {$view == $curview} {
1461 run chewcommits
1462 }
1463 return 0
1464 }
1465 set start 0
1466 set gotsome 0
1467 set scripts {}
1468 while 1 {
1469 set i [string first "\0" $stuff $start]
1470 if {$i < 0} {
1471 append leftover($inst) [string range $stuff $start end]
1472 break
1473 }
1474 if {$start == 0} {
1475 set cmit $leftover($inst)
1476 append cmit [string range $stuff 0 [expr {$i - 1}]]
1477 set leftover($inst) {}
1478 } else {
1479 set cmit [string range $stuff $start [expr {$i - 1}]]
1480 }
1481 set start [expr {$i + 1}]
1482 set j [string first "\n" $cmit]
1483 set ok 0
1484 set listed 1
1485 if {$j >= 0 && [string match "commit *" $cmit]} {
1486 set ids [string range $cmit 7 [expr {$j - 1}]]
1487 if {[string match {[-^<>]*} $ids]} {
1488 switch -- [string index $ids 0] {
1489 "-" {set listed 0}
1490 "^" {set listed 2}
1491 "<" {set listed 3}
1492 ">" {set listed 4}
1493 }
1494 set ids [string range $ids 1 end]
1495 }
1496 set ok 1
1497 foreach id $ids {
1498 if {[string length $id] != 40} {
1499 set ok 0
1500 break
1501 }
1502 }
1503 }
1504 if {!$ok} {
1505 set shortcmit $cmit
1506 if {[string length $shortcmit] > 80} {
1507 set shortcmit "[string range $shortcmit 0 80]..."
1508 }
1509 error_popup "[mc "Can't parse git log output:"] {$shortcmit}"
1510 exit 1
1511 }
1512 set id [lindex $ids 0]
1513 set vid $view,$id
1514
1515 lappend vshortids($view,[string range $id 0 3]) $id
1516
1517 if {!$listed && $updating && ![info exists varcid($vid)] &&
1518 $vfilelimit($view) ne {}} {
1519 # git log doesn't rewrite parents for unlisted commits
1520 # when doing path limiting, so work around that here
1521 # by working out the rewritten parent with git rev-list
1522 # and if we already know about it, using the rewritten
1523 # parent as a substitute parent for $id's children.
1524 if {![catch {
1525 set rwid [exec git rev-list --first-parent --max-count=1 \
1526 $id -- $vfilelimit($view)]
1527 }]} {
1528 if {$rwid ne {} && [info exists varcid($view,$rwid)]} {
1529 # use $rwid in place of $id
1530 rewrite_commit $view $id $rwid
1531 continue
1532 }
1533 }
1534 }
1535
1536 set a 0
1537 if {[info exists varcid($vid)]} {
1538 if {$cmitlisted($vid) || !$listed} continue
1539 set a $varcid($vid)
1540 }
1541 if {$listed} {
1542 set olds [lrange $ids 1 end]
1543 } else {
1544 set olds {}
1545 }
1546 set commitdata($id) [string range $cmit [expr {$j + 1}] end]
1547 set cmitlisted($vid) $listed
1548 set parents($vid) $olds
1549 if {![info exists children($vid)]} {
1550 set children($vid) {}
1551 } elseif {$a == 0 && [llength $children($vid)] == 1} {
1552 set k [lindex $children($vid) 0]
1553 if {[llength $parents($view,$k)] == 1 &&
1554 (!$vdatemode($view) ||
1555 $varcid($view,$k) == [llength $varctok($view)] - 1)} {
1556 set a $varcid($view,$k)
1557 }
1558 }
1559 if {$a == 0} {
1560 # new arc
1561 set a [newvarc $view $id]
1562 }
1563 if {[string compare [lindex $varctok($view) $a] $vtokmod($view)] < 0} {
1564 modify_arc $view $a
1565 }
1566 if {![info exists varcid($vid)]} {
1567 set varcid($vid) $a
1568 lappend varccommits($view,$a) $id
1569 incr commitidx($view)
1570 }
1571
1572 set i 0
1573 foreach p $olds {
1574 if {$i == 0 || [lsearch -exact $olds $p] >= $i} {
1575 set vp $view,$p
1576 if {[llength [lappend children($vp) $id]] > 1 &&
1577 [vtokcmp $view [lindex $children($vp) end-1] $id] > 0} {
1578 set children($vp) [lsort -command [list vtokcmp $view] \
1579 $children($vp)]
1580 catch {unset ordertok}
1581 }
1582 if {[info exists varcid($view,$p)]} {
1583 fix_reversal $p $a $view
1584 }
1585 }
1586 incr i
1587 }
1588
1589 set scripts [check_interest $id $scripts]
1590 set gotsome 1
1591 }
1592 if {$gotsome} {
1593 global numcommits hlview
1594
1595 if {$view == $curview} {
1596 set numcommits $commitidx($view)
1597 run chewcommits
1598 }
1599 if {[info exists hlview] && $view == $hlview} {
1600 # we never actually get here...
1601 run vhighlightmore
1602 }
1603 foreach s $scripts {
1604 eval $s
1605 }
1606 }
1607 return 2
1608}
1609
1610proc chewcommits {} {
1611 global curview hlview viewcomplete
1612 global pending_select
1613
1614 layoutmore
1615 if {$viewcomplete($curview)} {
1616 global commitidx varctok
1617 global numcommits startmsecs
1618
1619 if {[info exists pending_select]} {
1620 update
1621 reset_pending_select {}
1622
1623 if {[commitinview $pending_select $curview]} {
1624 selectline [rowofcommit $pending_select] 1
1625 } else {
1626 set row [first_real_row]
1627 selectline $row 1
1628 }
1629 }
1630 if {$commitidx($curview) > 0} {
1631 #set ms [expr {[clock clicks -milliseconds] - $startmsecs}]
1632 #puts "overall $ms ms for $numcommits commits"
1633 #puts "[llength $varctok($view)] arcs, $commitidx($view) commits"
1634 } else {
1635 show_status [mc "No commits selected"]
1636 }
1637 notbusy layout
1638 }
1639 return 0
1640}
1641
1642proc do_readcommit {id} {
1643 global tclencoding
1644
1645 # Invoke git-log to handle automatic encoding conversion
1646 set fd [open [concat | git log --no-color --pretty=raw -1 $id] r]
1647 # Read the results using i18n.logoutputencoding
1648 fconfigure $fd -translation lf -eofchar {}
1649 if {$tclencoding != {}} {
1650 fconfigure $fd -encoding $tclencoding
1651 }
1652 set contents [read $fd]
1653 close $fd
1654 # Remove the heading line
1655 regsub {^commit [0-9a-f]+\n} $contents {} contents
1656
1657 return $contents
1658}
1659
1660proc readcommit {id} {
1661 if {[catch {set contents [do_readcommit $id]}]} return
1662 parsecommit $id $contents 1
1663}
1664
1665proc parsecommit {id contents listed} {
1666 global commitinfo
1667
1668 set inhdr 1
1669 set comment {}
1670 set headline {}
1671 set auname {}
1672 set audate {}
1673 set comname {}
1674 set comdate {}
1675 set hdrend [string first "\n\n" $contents]
1676 if {$hdrend < 0} {
1677 # should never happen...
1678 set hdrend [string length $contents]
1679 }
1680 set header [string range $contents 0 [expr {$hdrend - 1}]]
1681 set comment [string range $contents [expr {$hdrend + 2}] end]
1682 foreach line [split $header "\n"] {
1683 set line [split $line " "]
1684 set tag [lindex $line 0]
1685 if {$tag == "author"} {
1686 set audate [lrange $line end-1 end]
1687 set auname [join [lrange $line 1 end-2] " "]
1688 } elseif {$tag == "committer"} {
1689 set comdate [lrange $line end-1 end]
1690 set comname [join [lrange $line 1 end-2] " "]
1691 }
1692 }
1693 set headline {}
1694 # take the first non-blank line of the comment as the headline
1695 set headline [string trimleft $comment]
1696 set i [string first "\n" $headline]
1697 if {$i >= 0} {
1698 set headline [string range $headline 0 $i]
1699 }
1700 set headline [string trimright $headline]
1701 set i [string first "\r" $headline]
1702 if {$i >= 0} {
1703 set headline [string trimright [string range $headline 0 $i]]
1704 }
1705 if {!$listed} {
1706 # git log indents the comment by 4 spaces;
1707 # if we got this via git cat-file, add the indentation
1708 set newcomment {}
1709 foreach line [split $comment "\n"] {
1710 append newcomment " "
1711 append newcomment $line
1712 append newcomment "\n"
1713 }
1714 set comment $newcomment
1715 }
1716 set hasnote [string first "\nNotes:\n" $contents]
1717 set diff ""
1718 # If there is diff output shown in the git-log stream, split it
1719 # out. But get rid of the empty line that always precedes the
1720 # diff.
1721 set i [string first "\n\ndiff" $comment]
1722 if {$i >= 0} {
1723 set diff [string range $comment $i+1 end]
1724 set comment [string range $comment 0 $i-1]
1725 }
1726 set commitinfo($id) [list $headline $auname $audate \
1727 $comname $comdate $comment $hasnote $diff]
1728}
1729
1730proc getcommit {id} {
1731 global commitdata commitinfo
1732
1733 if {[info exists commitdata($id)]} {
1734 parsecommit $id $commitdata($id) 1
1735 } else {
1736 readcommit $id
1737 if {![info exists commitinfo($id)]} {
1738 set commitinfo($id) [list [mc "No commit information available"]]
1739 }
1740 }
1741 return 1
1742}
1743
1744# Expand an abbreviated commit ID to a list of full 40-char IDs that match
1745# and are present in the current view.
1746# This is fairly slow...
1747proc longid {prefix} {
1748 global varcid curview vshortids
1749
1750 set ids {}
1751 if {[string length $prefix] >= 4} {
1752 set vshortid $curview,[string range $prefix 0 3]
1753 if {[info exists vshortids($vshortid)]} {
1754 foreach id $vshortids($vshortid) {
1755 if {[string match "$prefix*" $id]} {
1756 if {[lsearch -exact $ids $id] < 0} {
1757 lappend ids $id
1758 if {[llength $ids] >= 2} break
1759 }
1760 }
1761 }
1762 }
1763 } else {
1764 foreach match [array names varcid "$curview,$prefix*"] {
1765 lappend ids [lindex [split $match ","] 1]
1766 if {[llength $ids] >= 2} break
1767 }
1768 }
1769 return $ids
1770}
1771
1772proc readrefs {} {
1773 global tagids idtags headids idheads tagobjid
1774 global otherrefids idotherrefs mainhead mainheadid
1775 global selecthead selectheadid
1776 global hideremotes
1777
1778 foreach v {tagids idtags headids idheads otherrefids idotherrefs} {
1779 catch {unset $v}
1780 }
1781 set refd [open [list | git show-ref -d] r]
1782 while {[gets $refd line] >= 0} {
1783 if {[string index $line 40] ne " "} continue
1784 set id [string range $line 0 39]
1785 set ref [string range $line 41 end]
1786 if {![string match "refs/*" $ref]} continue
1787 set name [string range $ref 5 end]
1788 if {[string match "remotes/*" $name]} {
1789 if {![string match "*/HEAD" $name] && !$hideremotes} {
1790 set headids($name) $id
1791 lappend idheads($id) $name
1792 }
1793 } elseif {[string match "heads/*" $name]} {
1794 set name [string range $name 6 end]
1795 set headids($name) $id
1796 lappend idheads($id) $name
1797 } elseif {[string match "tags/*" $name]} {
1798 # this lets refs/tags/foo^{} overwrite refs/tags/foo,
1799 # which is what we want since the former is the commit ID
1800 set name [string range $name 5 end]
1801 if {[string match "*^{}" $name]} {
1802 set name [string range $name 0 end-3]
1803 } else {
1804 set tagobjid($name) $id
1805 }
1806 set tagids($name) $id
1807 lappend idtags($id) $name
1808 } else {
1809 set otherrefids($name) $id
1810 lappend idotherrefs($id) $name
1811 }
1812 }
1813 catch {close $refd}
1814 set mainhead {}
1815 set mainheadid {}
1816 catch {
1817 set mainheadid [exec git rev-parse HEAD]
1818 set thehead [exec git symbolic-ref HEAD]
1819 if {[string match "refs/heads/*" $thehead]} {
1820 set mainhead [string range $thehead 11 end]
1821 }
1822 }
1823 set selectheadid {}
1824 if {$selecthead ne {}} {
1825 catch {
1826 set selectheadid [exec git rev-parse --verify $selecthead]
1827 }
1828 }
1829}
1830
1831# skip over fake commits
1832proc first_real_row {} {
1833 global nullid nullid2 numcommits
1834
1835 for {set row 0} {$row < $numcommits} {incr row} {
1836 set id [commitonrow $row]
1837 if {$id ne $nullid && $id ne $nullid2} {
1838 break
1839 }
1840 }
1841 return $row
1842}
1843
1844# update things for a head moved to a child of its previous location
1845proc movehead {id name} {
1846 global headids idheads
1847
1848 removehead $headids($name) $name
1849 set headids($name) $id
1850 lappend idheads($id) $name
1851}
1852
1853# update things when a head has been removed
1854proc removehead {id name} {
1855 global headids idheads
1856
1857 if {$idheads($id) eq $name} {
1858 unset idheads($id)
1859 } else {
1860 set i [lsearch -exact $idheads($id) $name]
1861 if {$i >= 0} {
1862 set idheads($id) [lreplace $idheads($id) $i $i]
1863 }
1864 }
1865 unset headids($name)
1866}
1867
1868proc ttk_toplevel {w args} {
1869 global use_ttk
1870 eval [linsert $args 0 ::toplevel $w]
1871 if {$use_ttk} {
1872 place [ttk::frame $w._toplevel_background] -x 0 -y 0 -relwidth 1 -relheight 1
1873 }
1874 return $w
1875}
1876
1877proc make_transient {window origin} {
1878 global have_tk85
1879
1880 # In MacOS Tk 8.4 transient appears to work by setting
1881 # overrideredirect, which is utterly useless, since the
1882 # windows get no border, and are not even kept above
1883 # the parent.
1884 if {!$have_tk85 && [tk windowingsystem] eq {aqua}} return
1885
1886 wm transient $window $origin
1887
1888 # Windows fails to place transient windows normally, so
1889 # schedule a callback to center them on the parent.
1890 if {[tk windowingsystem] eq {win32}} {
1891 after idle [list tk::PlaceWindow $window widget $origin]
1892 }
1893}
1894
1895proc show_error {w top msg {mc mc}} {
1896 global NS
1897 if {![info exists NS]} {set NS ""}
1898 if {[wm state $top] eq "withdrawn"} { wm deiconify $top }
1899 message $w.m -text $msg -justify center -aspect 400
1900 pack $w.m -side top -fill x -padx 20 -pady 20
1901 ${NS}::button $w.ok -default active -text [$mc OK] -command "destroy $top"
1902 pack $w.ok -side bottom -fill x
1903 bind $top <Visibility> "grab $top; focus $top"
1904 bind $top <Key-Return> "destroy $top"
1905 bind $top <Key-space> "destroy $top"
1906 bind $top <Key-Escape> "destroy $top"
1907 tkwait window $top
1908}
1909
1910proc error_popup {msg {owner .}} {
1911 if {[tk windowingsystem] eq "win32"} {
1912 tk_messageBox -icon error -type ok -title [wm title .] \
1913 -parent $owner -message $msg
1914 } else {
1915 set w .error
1916 ttk_toplevel $w
1917 make_transient $w $owner
1918 show_error $w $w $msg
1919 }
1920}
1921
1922proc confirm_popup {msg {owner .}} {
1923 global confirm_ok NS
1924 set confirm_ok 0
1925 set w .confirm
1926 ttk_toplevel $w
1927 make_transient $w $owner
1928 message $w.m -text $msg -justify center -aspect 400
1929 pack $w.m -side top -fill x -padx 20 -pady 20
1930 ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
1931 pack $w.ok -side left -fill x
1932 ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
1933 pack $w.cancel -side right -fill x
1934 bind $w <Visibility> "grab $w; focus $w"
1935 bind $w <Key-Return> "set confirm_ok 1; destroy $w"
1936 bind $w <Key-space> "set confirm_ok 1; destroy $w"
1937 bind $w <Key-Escape> "destroy $w"
1938 tk::PlaceWindow $w widget $owner
1939 tkwait window $w
1940 return $confirm_ok
1941}
1942
1943proc setoptions {} {
1944 if {[tk windowingsystem] ne "win32"} {
1945 option add *Panedwindow.showHandle 1 startupFile
1946 option add *Panedwindow.sashRelief raised startupFile
1947 if {[tk windowingsystem] ne "aqua"} {
1948 option add *Menu.font uifont startupFile
1949 }
1950 } else {
1951 option add *Menu.TearOff 0 startupFile
1952 }
1953 option add *Button.font uifont startupFile
1954 option add *Checkbutton.font uifont startupFile
1955 option add *Radiobutton.font uifont startupFile
1956 option add *Menubutton.font uifont startupFile
1957 option add *Label.font uifont startupFile
1958 option add *Message.font uifont startupFile
1959 option add *Entry.font textfont startupFile
1960 option add *Text.font textfont startupFile
1961 option add *Labelframe.font uifont startupFile
1962 option add *Spinbox.font textfont startupFile
1963 option add *Listbox.font mainfont startupFile
1964}
1965
1966# Make a menu and submenus.
1967# m is the window name for the menu, items is the list of menu items to add.
1968# Each item is a list {mc label type description options...}
1969# mc is ignored; it's so we can put mc there to alert xgettext
1970# label is the string that appears in the menu
1971# type is cascade, command or radiobutton (should add checkbutton)
1972# description depends on type; it's the sublist for cascade, the
1973# command to invoke for command, or {variable value} for radiobutton
1974proc makemenu {m items} {
1975 menu $m
1976 if {[tk windowingsystem] eq {aqua}} {
1977 set Meta1 Cmd
1978 } else {
1979 set Meta1 Ctrl
1980 }
1981 foreach i $items {
1982 set name [mc [lindex $i 1]]
1983 set type [lindex $i 2]
1984 set thing [lindex $i 3]
1985 set params [list $type]
1986 if {$name ne {}} {
1987 set u [string first "&" [string map {&& x} $name]]
1988 lappend params -label [string map {&& & & {}} $name]
1989 if {$u >= 0} {
1990 lappend params -underline $u
1991 }
1992 }
1993 switch -- $type {
1994 "cascade" {
1995 set submenu [string tolower [string map {& ""} [lindex $i 1]]]
1996 lappend params -menu $m.$submenu
1997 }
1998 "command" {
1999 lappend params -command $thing
2000 }
2001 "radiobutton" {
2002 lappend params -variable [lindex $thing 0] \
2003 -value [lindex $thing 1]
2004 }
2005 }
2006 set tail [lrange $i 4 end]
2007 regsub -all {\yMeta1\y} $tail $Meta1 tail
2008 eval $m add $params $tail
2009 if {$type eq "cascade"} {
2010 makemenu $m.$submenu $thing
2011 }
2012 }
2013}
2014
2015# translate string and remove ampersands
2016proc mca {str} {
2017 return [string map {&& & & {}} [mc $str]]
2018}
2019
2020proc cleardropsel {w} {
2021 $w selection clear
2022}
2023proc makedroplist {w varname args} {
2024 global use_ttk
2025 if {$use_ttk} {
2026 set width 0
2027 foreach label $args {
2028 set cx [string length $label]
2029 if {$cx > $width} {set width $cx}
2030 }
2031 set gm [ttk::combobox $w -width $width -state readonly\
2032 -textvariable $varname -values $args \
2033 -exportselection false]
2034 bind $gm <<ComboboxSelected>> [list $gm selection clear]
2035 } else {
2036 set gm [eval [linsert $args 0 tk_optionMenu $w $varname]]
2037 }
2038 return $gm
2039}
2040
2041proc makewindow {} {
2042 global canv canv2 canv3 linespc charspc ctext cflist cscroll
2043 global tabstop
2044 global findtype findtypemenu findloc findstring fstring geometry
2045 global entries sha1entry sha1string sha1but
2046 global diffcontextstring diffcontext
2047 global ignorespace
2048 global maincursor textcursor curtextcursor
2049 global rowctxmenu fakerowmenu mergemax wrapcomment
2050 global highlight_files gdttype
2051 global searchstring sstring
2052 global bgcolor fgcolor bglist fglist diffcolors selectbgcolor
2053 global uifgcolor uifgdisabledcolor
2054 global filesepbgcolor filesepfgcolor
2055 global mergecolors foundbgcolor currentsearchhitbgcolor
2056 global headctxmenu progresscanv progressitem progresscoords statusw
2057 global fprogitem fprogcoord lastprogupdate progupdatepending
2058 global rprogitem rprogcoord rownumsel numcommits
2059 global have_tk85 use_ttk NS
2060 global git_version
2061 global worddiff
2062
2063 # The "mc" arguments here are purely so that xgettext
2064 # sees the following string as needing to be translated
2065 set file {
2066 mc "File" cascade {
2067 {mc "Update" command updatecommits -accelerator F5}
2068 {mc "Reload" command reloadcommits -accelerator Shift-F5}
2069 {mc "Reread references" command rereadrefs}
2070 {mc "List references" command showrefs -accelerator F2}
2071 {xx "" separator}
2072 {mc "Start git gui" command {exec git gui &}}
2073 {xx "" separator}
2074 {mc "Quit" command doquit -accelerator Meta1-Q}
2075 }}
2076 set edit {
2077 mc "Edit" cascade {
2078 {mc "Preferences" command doprefs}
2079 }}
2080 set view {
2081 mc "View" cascade {
2082 {mc "New view..." command {newview 0} -accelerator Shift-F4}
2083 {mc "Edit view..." command editview -state disabled -accelerator F4}
2084 {mc "Delete view" command delview -state disabled}
2085 {xx "" separator}
2086 {mc "All files" radiobutton {selectedview 0} -command {showview 0}}
2087 }}
2088 if {[tk windowingsystem] ne "aqua"} {
2089 set help {
2090 mc "Help" cascade {
2091 {mc "About gitk" command about}
2092 {mc "Key bindings" command keys}
2093 }}
2094 set bar [list $file $edit $view $help]
2095 } else {
2096 proc ::tk::mac::ShowPreferences {} {doprefs}
2097 proc ::tk::mac::Quit {} {doquit}
2098 lset file end [lreplace [lindex $file end] end-1 end]
2099 set apple {
2100 xx "Apple" cascade {
2101 {mc "About gitk" command about}
2102 {xx "" separator}
2103 }}
2104 set help {
2105 mc "Help" cascade {
2106 {mc "Key bindings" command keys}
2107 }}
2108 set bar [list $apple $file $view $help]
2109 }
2110 makemenu .bar $bar
2111 . configure -menu .bar
2112
2113 if {$use_ttk} {
2114 # cover the non-themed toplevel with a themed frame.
2115 place [ttk::frame ._main_background] -x 0 -y 0 -relwidth 1 -relheight 1
2116 }
2117
2118 # the gui has upper and lower half, parts of a paned window.
2119 ${NS}::panedwindow .ctop -orient vertical
2120
2121 # possibly use assumed geometry
2122 if {![info exists geometry(pwsash0)]} {
2123 set geometry(topheight) [expr {15 * $linespc}]
2124 set geometry(topwidth) [expr {80 * $charspc}]
2125 set geometry(botheight) [expr {15 * $linespc}]
2126 set geometry(botwidth) [expr {50 * $charspc}]
2127 set geometry(pwsash0) [list [expr {40 * $charspc}] 2]
2128 set geometry(pwsash1) [list [expr {60 * $charspc}] 2]
2129 }
2130
2131 # the upper half will have a paned window, a scroll bar to the right, and some stuff below
2132 ${NS}::frame .tf -height $geometry(topheight) -width $geometry(topwidth)
2133 ${NS}::frame .tf.histframe
2134 ${NS}::panedwindow .tf.histframe.pwclist -orient horizontal
2135 if {!$use_ttk} {
2136 .tf.histframe.pwclist configure -sashpad 0 -handlesize 4
2137 }
2138
2139 # create three canvases
2140 set cscroll .tf.histframe.csb
2141 set canv .tf.histframe.pwclist.canv
2142 canvas $canv \
2143 -selectbackground $selectbgcolor \
2144 -background $bgcolor -bd 0 \
2145 -yscrollincr $linespc -yscrollcommand "scrollcanv $cscroll"
2146 .tf.histframe.pwclist add $canv
2147 set canv2 .tf.histframe.pwclist.canv2
2148 canvas $canv2 \
2149 -selectbackground $selectbgcolor \
2150 -background $bgcolor -bd 0 -yscrollincr $linespc
2151 .tf.histframe.pwclist add $canv2
2152 set canv3 .tf.histframe.pwclist.canv3
2153 canvas $canv3 \
2154 -selectbackground $selectbgcolor \
2155 -background $bgcolor -bd 0 -yscrollincr $linespc
2156 .tf.histframe.pwclist add $canv3
2157 if {$use_ttk} {
2158 bind .tf.histframe.pwclist <Map> {
2159 bind %W <Map> {}
2160 .tf.histframe.pwclist sashpos 1 [lindex $::geometry(pwsash1) 0]
2161 .tf.histframe.pwclist sashpos 0 [lindex $::geometry(pwsash0) 0]
2162 }
2163 } else {
2164 eval .tf.histframe.pwclist sash place 0 $geometry(pwsash0)
2165 eval .tf.histframe.pwclist sash place 1 $geometry(pwsash1)
2166 }
2167
2168 # a scroll bar to rule them
2169 ${NS}::scrollbar $cscroll -command {allcanvs yview}
2170 if {!$use_ttk} {$cscroll configure -highlightthickness 0}
2171 pack $cscroll -side right -fill y
2172 bind .tf.histframe.pwclist <Configure> {resizeclistpanes %W %w}
2173 lappend bglist $canv $canv2 $canv3
2174 pack .tf.histframe.pwclist -fill both -expand 1 -side left
2175
2176 # we have two button bars at bottom of top frame. Bar 1
2177 ${NS}::frame .tf.bar
2178 ${NS}::frame .tf.lbar -height 15
2179
2180 set sha1entry .tf.bar.sha1
2181 set entries $sha1entry
2182 set sha1but .tf.bar.sha1label
2183 button $sha1but -text "[mc "SHA1 ID:"] " -state disabled -relief flat \
2184 -command gotocommit -width 8
2185 $sha1but conf -disabledforeground [$sha1but cget -foreground]
2186 pack .tf.bar.sha1label -side left
2187 ${NS}::entry $sha1entry -width 40 -font textfont -textvariable sha1string
2188 trace add variable sha1string write sha1change
2189 pack $sha1entry -side left -pady 2
2190
2191 set bm_left_data {
2192 #define left_width 16
2193 #define left_height 16
2194 static unsigned char left_bits[] = {
2195 0x00, 0x00, 0xc0, 0x01, 0xe0, 0x00, 0x70, 0x00, 0x38, 0x00, 0x1c, 0x00,
2196 0x0e, 0x00, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x0e, 0x00, 0x1c, 0x00,
2197 0x38, 0x00, 0x70, 0x00, 0xe0, 0x00, 0xc0, 0x01};
2198 }
2199 set bm_right_data {
2200 #define right_width 16
2201 #define right_height 16
2202 static unsigned char right_bits[] = {
2203 0x00, 0x00, 0xc0, 0x01, 0x80, 0x03, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x1c,
2204 0x00, 0x38, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x00, 0x38, 0x00, 0x1c,
2205 0x00, 0x0e, 0x00, 0x07, 0x80, 0x03, 0xc0, 0x01};
2206 }
2207 image create bitmap bm-left -data $bm_left_data -foreground $uifgcolor
2208 image create bitmap bm-left-gray -data $bm_left_data -foreground $uifgdisabledcolor
2209 image create bitmap bm-right -data $bm_right_data -foreground $uifgcolor
2210 image create bitmap bm-right-gray -data $bm_right_data -foreground $uifgdisabledcolor
2211
2212 ${NS}::button .tf.bar.leftbut -command goback -state disabled -width 26
2213 if {$use_ttk} {
2214 .tf.bar.leftbut configure -image [list bm-left disabled bm-left-gray]
2215 } else {
2216 .tf.bar.leftbut configure -image bm-left
2217 }
2218 pack .tf.bar.leftbut -side left -fill y
2219 ${NS}::button .tf.bar.rightbut -command goforw -state disabled -width 26
2220 if {$use_ttk} {
2221 .tf.bar.rightbut configure -image [list bm-right disabled bm-right-gray]
2222 } else {
2223 .tf.bar.rightbut configure -image bm-right
2224 }
2225 pack .tf.bar.rightbut -side left -fill y
2226
2227 ${NS}::label .tf.bar.rowlabel -text [mc "Row"]
2228 set rownumsel {}
2229 ${NS}::label .tf.bar.rownum -width 7 -textvariable rownumsel \
2230 -relief sunken -anchor e
2231 ${NS}::label .tf.bar.rowlabel2 -text "/"
2232 ${NS}::label .tf.bar.numcommits -width 7 -textvariable numcommits \
2233 -relief sunken -anchor e
2234 pack .tf.bar.rowlabel .tf.bar.rownum .tf.bar.rowlabel2 .tf.bar.numcommits \
2235 -side left
2236 if {!$use_ttk} {
2237 foreach w {rownum numcommits} {.tf.bar.$w configure -font textfont}
2238 }
2239 global selectedline
2240 trace add variable selectedline write selectedline_change
2241
2242 # Status label and progress bar
2243 set statusw .tf.bar.status
2244 ${NS}::label $statusw -width 15 -relief sunken
2245 pack $statusw -side left -padx 5
2246 if {$use_ttk} {
2247 set progresscanv [ttk::progressbar .tf.bar.progress]
2248 } else {
2249 set h [expr {[font metrics uifont -linespace] + 2}]
2250 set progresscanv .tf.bar.progress
2251 canvas $progresscanv -relief sunken -height $h -borderwidth 2
2252 set progressitem [$progresscanv create rect -1 0 0 $h -fill green]
2253 set fprogitem [$progresscanv create rect -1 0 0 $h -fill yellow]
2254 set rprogitem [$progresscanv create rect -1 0 0 $h -fill red]
2255 }
2256 pack $progresscanv -side right -expand 1 -fill x -padx {0 2}
2257 set progresscoords {0 0}
2258 set fprogcoord 0
2259 set rprogcoord 0
2260 bind $progresscanv <Configure> adjustprogress
2261 set lastprogupdate [clock clicks -milliseconds]
2262 set progupdatepending 0
2263
2264 # build up the bottom bar of upper window
2265 ${NS}::label .tf.lbar.flabel -text "[mc "Find"] "
2266
2267 set bm_down_data {
2268 #define down_width 16
2269 #define down_height 16
2270 static unsigned char down_bits[] = {
2271 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2272 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2273 0x87, 0xe1, 0x8e, 0x71, 0x9c, 0x39, 0xb8, 0x1d,
2274 0xf0, 0x0f, 0xe0, 0x07, 0xc0, 0x03, 0x80, 0x01};
2275 }
2276 image create bitmap bm-down -data $bm_down_data -foreground $uifgcolor
2277 ${NS}::button .tf.lbar.fnext -width 26 -command {dofind 1 1}
2278 .tf.lbar.fnext configure -image bm-down
2279
2280 set bm_up_data {
2281 #define up_width 16
2282 #define up_height 16
2283 static unsigned char up_bits[] = {
2284 0x80, 0x01, 0xc0, 0x03, 0xe0, 0x07, 0xf0, 0x0f,
2285 0xb8, 0x1d, 0x9c, 0x39, 0x8e, 0x71, 0x87, 0xe1,
2286 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2287 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01};
2288 }
2289 image create bitmap bm-up -data $bm_up_data -foreground $uifgcolor
2290 ${NS}::button .tf.lbar.fprev -width 26 -command {dofind -1 1}
2291 .tf.lbar.fprev configure -image bm-up
2292
2293 ${NS}::label .tf.lbar.flab2 -text " [mc "commit"] "
2294
2295 pack .tf.lbar.flabel .tf.lbar.fnext .tf.lbar.fprev .tf.lbar.flab2 \
2296 -side left -fill y
2297 set gdttype [mc "containing:"]
2298 set gm [makedroplist .tf.lbar.gdttype gdttype \
2299 [mc "containing:"] \
2300 [mc "touching paths:"] \
2301 [mc "adding/removing string:"] \
2302 [mc "changing lines matching:"]]
2303 trace add variable gdttype write gdttype_change
2304 pack .tf.lbar.gdttype -side left -fill y
2305
2306 set findstring {}
2307 set fstring .tf.lbar.findstring
2308 lappend entries $fstring
2309 ${NS}::entry $fstring -width 30 -textvariable findstring
2310 trace add variable findstring write find_change
2311 set findtype [mc "Exact"]
2312 set findtypemenu [makedroplist .tf.lbar.findtype \
2313 findtype [mc "Exact"] [mc "IgnCase"] [mc "Regexp"]]
2314 trace add variable findtype write findcom_change
2315 set findloc [mc "All fields"]
2316 makedroplist .tf.lbar.findloc findloc [mc "All fields"] [mc "Headline"] \
2317 [mc "Comments"] [mc "Author"] [mc "Committer"]
2318 trace add variable findloc write find_change
2319 pack .tf.lbar.findloc -side right
2320 pack .tf.lbar.findtype -side right
2321 pack $fstring -side left -expand 1 -fill x
2322
2323 # Finish putting the upper half of the viewer together
2324 pack .tf.lbar -in .tf -side bottom -fill x
2325 pack .tf.bar -in .tf -side bottom -fill x
2326 pack .tf.histframe -fill both -side top -expand 1
2327 .ctop add .tf
2328 if {!$use_ttk} {
2329 .ctop paneconfigure .tf -height $geometry(topheight)
2330 .ctop paneconfigure .tf -width $geometry(topwidth)
2331 }
2332
2333 # now build up the bottom
2334 ${NS}::panedwindow .pwbottom -orient horizontal
2335
2336 # lower left, a text box over search bar, scroll bar to the right
2337 # if we know window height, then that will set the lower text height, otherwise
2338 # we set lower text height which will drive window height
2339 if {[info exists geometry(main)]} {
2340 ${NS}::frame .bleft -width $geometry(botwidth)
2341 } else {
2342 ${NS}::frame .bleft -width $geometry(botwidth) -height $geometry(botheight)
2343 }
2344 ${NS}::frame .bleft.top
2345 ${NS}::frame .bleft.mid
2346 ${NS}::frame .bleft.bottom
2347
2348 ${NS}::button .bleft.top.search -text [mc "Search"] -command dosearch
2349 pack .bleft.top.search -side left -padx 5
2350 set sstring .bleft.top.sstring
2351 set searchstring ""
2352 ${NS}::entry $sstring -width 20 -textvariable searchstring
2353 lappend entries $sstring
2354 trace add variable searchstring write incrsearch
2355 pack $sstring -side left -expand 1 -fill x
2356 ${NS}::radiobutton .bleft.mid.diff -text [mc "Diff"] \
2357 -command changediffdisp -variable diffelide -value {0 0}
2358 ${NS}::radiobutton .bleft.mid.old -text [mc "Old version"] \
2359 -command changediffdisp -variable diffelide -value {0 1}
2360 ${NS}::radiobutton .bleft.mid.new -text [mc "New version"] \
2361 -command changediffdisp -variable diffelide -value {1 0}
2362 ${NS}::label .bleft.mid.labeldiffcontext -text " [mc "Lines of context"]: "
2363 pack .bleft.mid.diff .bleft.mid.old .bleft.mid.new -side left
2364 spinbox .bleft.mid.diffcontext -width 5 \
2365 -from 0 -increment 1 -to 10000000 \
2366 -validate all -validatecommand "diffcontextvalidate %P" \
2367 -textvariable diffcontextstring
2368 .bleft.mid.diffcontext set $diffcontext
2369 trace add variable diffcontextstring write diffcontextchange
2370 lappend entries .bleft.mid.diffcontext
2371 pack .bleft.mid.labeldiffcontext .bleft.mid.diffcontext -side left
2372 ${NS}::checkbutton .bleft.mid.ignspace -text [mc "Ignore space change"] \
2373 -command changeignorespace -variable ignorespace
2374 pack .bleft.mid.ignspace -side left -padx 5
2375
2376 set worddiff [mc "Line diff"]
2377 if {[package vcompare $git_version "1.7.2"] >= 0} {
2378 makedroplist .bleft.mid.worddiff worddiff [mc "Line diff"] \
2379 [mc "Markup words"] [mc "Color words"]
2380 trace add variable worddiff write changeworddiff
2381 pack .bleft.mid.worddiff -side left -padx 5
2382 }
2383
2384 set ctext .bleft.bottom.ctext
2385 text $ctext -background $bgcolor -foreground $fgcolor \
2386 -state disabled -font textfont \
2387 -yscrollcommand scrolltext -wrap none \
2388 -xscrollcommand ".bleft.bottom.sbhorizontal set"
2389 if {$have_tk85} {
2390 $ctext conf -tabstyle wordprocessor
2391 }
2392 ${NS}::scrollbar .bleft.bottom.sb -command "$ctext yview"
2393 ${NS}::scrollbar .bleft.bottom.sbhorizontal -command "$ctext xview" -orient h
2394 pack .bleft.top -side top -fill x
2395 pack .bleft.mid -side top -fill x
2396 grid $ctext .bleft.bottom.sb -sticky nsew
2397 grid .bleft.bottom.sbhorizontal -sticky ew
2398 grid columnconfigure .bleft.bottom 0 -weight 1
2399 grid rowconfigure .bleft.bottom 0 -weight 1
2400 grid rowconfigure .bleft.bottom 1 -weight 0
2401 pack .bleft.bottom -side top -fill both -expand 1
2402 lappend bglist $ctext
2403 lappend fglist $ctext
2404
2405 $ctext tag conf comment -wrap $wrapcomment
2406 $ctext tag conf filesep -font textfontbold -fore $filesepfgcolor -back $filesepbgcolor
2407 $ctext tag conf hunksep -fore [lindex $diffcolors 2]
2408 $ctext tag conf d0 -fore [lindex $diffcolors 0]
2409 $ctext tag conf dresult -fore [lindex $diffcolors 1]
2410 $ctext tag conf m0 -fore [lindex $mergecolors 0]
2411 $ctext tag conf m1 -fore [lindex $mergecolors 1]
2412 $ctext tag conf m2 -fore [lindex $mergecolors 2]
2413 $ctext tag conf m3 -fore [lindex $mergecolors 3]
2414 $ctext tag conf m4 -fore [lindex $mergecolors 4]
2415 $ctext tag conf m5 -fore [lindex $mergecolors 5]
2416 $ctext tag conf m6 -fore [lindex $mergecolors 6]
2417 $ctext tag conf m7 -fore [lindex $mergecolors 7]
2418 $ctext tag conf m8 -fore [lindex $mergecolors 8]
2419 $ctext tag conf m9 -fore [lindex $mergecolors 9]
2420 $ctext tag conf m10 -fore [lindex $mergecolors 10]
2421 $ctext tag conf m11 -fore [lindex $mergecolors 11]
2422 $ctext tag conf m12 -fore [lindex $mergecolors 12]
2423 $ctext tag conf m13 -fore [lindex $mergecolors 13]
2424 $ctext tag conf m14 -fore [lindex $mergecolors 14]
2425 $ctext tag conf m15 -fore [lindex $mergecolors 15]
2426 $ctext tag conf mmax -fore darkgrey
2427 set mergemax 16
2428 $ctext tag conf mresult -font textfontbold
2429 $ctext tag conf msep -font textfontbold
2430 $ctext tag conf found -back $foundbgcolor
2431 $ctext tag conf currentsearchhit -back $currentsearchhitbgcolor
2432 $ctext tag conf wwrap -wrap word -lmargin2 1c
2433 $ctext tag conf bold -font textfontbold
2434
2435 .pwbottom add .bleft
2436 if {!$use_ttk} {
2437 .pwbottom paneconfigure .bleft -width $geometry(botwidth)
2438 }
2439
2440 # lower right
2441 ${NS}::frame .bright
2442 ${NS}::frame .bright.mode
2443 ${NS}::radiobutton .bright.mode.patch -text [mc "Patch"] \
2444 -command reselectline -variable cmitmode -value "patch"
2445 ${NS}::radiobutton .bright.mode.tree -text [mc "Tree"] \
2446 -command reselectline -variable cmitmode -value "tree"
2447 grid .bright.mode.patch .bright.mode.tree -sticky ew
2448 pack .bright.mode -side top -fill x
2449 set cflist .bright.cfiles
2450 set indent [font measure mainfont "nn"]
2451 text $cflist \
2452 -selectbackground $selectbgcolor \
2453 -background $bgcolor -foreground $fgcolor \
2454 -font mainfont \
2455 -tabs [list $indent [expr {2 * $indent}]] \
2456 -yscrollcommand ".bright.sb set" \
2457 -cursor [. cget -cursor] \
2458 -spacing1 1 -spacing3 1
2459 lappend bglist $cflist
2460 lappend fglist $cflist
2461 ${NS}::scrollbar .bright.sb -command "$cflist yview"
2462 pack .bright.sb -side right -fill y
2463 pack $cflist -side left -fill both -expand 1
2464 $cflist tag configure highlight \
2465 -background [$cflist cget -selectbackground]
2466 $cflist tag configure bold -font mainfontbold
2467
2468 .pwbottom add .bright
2469 .ctop add .pwbottom
2470
2471 # restore window width & height if known
2472 if {[info exists geometry(main)]} {
2473 if {[scan $geometry(main) "%dx%d" w h] >= 2} {
2474 if {$w > [winfo screenwidth .]} {
2475 set w [winfo screenwidth .]
2476 }
2477 if {$h > [winfo screenheight .]} {
2478 set h [winfo screenheight .]
2479 }
2480 wm geometry . "${w}x$h"
2481 }
2482 }
2483
2484 if {[info exists geometry(state)] && $geometry(state) eq "zoomed"} {
2485 wm state . $geometry(state)
2486 }
2487
2488 if {[tk windowingsystem] eq {aqua}} {
2489 set M1B M1
2490 set ::BM "3"
2491 } else {
2492 set M1B Control
2493 set ::BM "2"
2494 }
2495
2496 if {$use_ttk} {
2497 bind .ctop <Map> {
2498 bind %W <Map> {}
2499 %W sashpos 0 $::geometry(topheight)
2500 }
2501 bind .pwbottom <Map> {
2502 bind %W <Map> {}
2503 %W sashpos 0 $::geometry(botwidth)
2504 }
2505 }
2506
2507 bind .pwbottom <Configure> {resizecdetpanes %W %w}
2508 pack .ctop -fill both -expand 1
2509 bindall <1> {selcanvline %W %x %y}
2510 #bindall <B1-Motion> {selcanvline %W %x %y}
2511 if {[tk windowingsystem] == "win32"} {
2512 bind . <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D }
2513 bind $ctext <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D ; break }
2514 } else {
2515 bindall <ButtonRelease-4> "allcanvs yview scroll -5 units"
2516 bindall <ButtonRelease-5> "allcanvs yview scroll 5 units"
2517 if {[tk windowingsystem] eq "aqua"} {
2518 bindall <MouseWheel> {
2519 set delta [expr {- (%D)}]
2520 allcanvs yview scroll $delta units
2521 }
2522 bindall <Shift-MouseWheel> {
2523 set delta [expr {- (%D)}]
2524 $canv xview scroll $delta units
2525 }
2526 }
2527 }
2528 bindall <$::BM> "canvscan mark %W %x %y"
2529 bindall <B$::BM-Motion> "canvscan dragto %W %x %y"
2530 bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
2531 bind . <$M1B-Key-w> doquit
2532 bindkey <Home> selfirstline
2533 bindkey <End> sellastline
2534 bind . <Key-Up> "selnextline -1"
2535 bind . <Key-Down> "selnextline 1"
2536 bind . <Shift-Key-Up> "dofind -1 0"
2537 bind . <Shift-Key-Down> "dofind 1 0"
2538 bindkey <Key-Right> "goforw"
2539 bindkey <Key-Left> "goback"
2540 bind . <Key-Prior> "selnextpage -1"
2541 bind . <Key-Next> "selnextpage 1"
2542 bind . <$M1B-Home> "allcanvs yview moveto 0.0"
2543 bind . <$M1B-End> "allcanvs yview moveto 1.0"
2544 bind . <$M1B-Key-Up> "allcanvs yview scroll -1 units"
2545 bind . <$M1B-Key-Down> "allcanvs yview scroll 1 units"
2546 bind . <$M1B-Key-Prior> "allcanvs yview scroll -1 pages"
2547 bind . <$M1B-Key-Next> "allcanvs yview scroll 1 pages"
2548 bindkey <Key-Delete> "$ctext yview scroll -1 pages"
2549 bindkey <Key-BackSpace> "$ctext yview scroll -1 pages"
2550 bindkey <Key-space> "$ctext yview scroll 1 pages"
2551 bindkey p "selnextline -1"
2552 bindkey n "selnextline 1"
2553 bindkey z "goback"
2554 bindkey x "goforw"
2555 bindkey k "selnextline -1"
2556 bindkey j "selnextline 1"
2557 bindkey h "goback"
2558 bindkey l "goforw"
2559 bindkey b prevfile
2560 bindkey d "$ctext yview scroll 18 units"
2561 bindkey u "$ctext yview scroll -18 units"
2562 bindkey / {focus $fstring}
2563 bindkey <Key-KP_Divide> {focus $fstring}
2564 bindkey <Key-Return> {dofind 1 1}
2565 bindkey ? {dofind -1 1}
2566 bindkey f nextfile
2567 bind . <F5> updatecommits
2568 bindmodfunctionkey Shift 5 reloadcommits
2569 bind . <F2> showrefs
2570 bindmodfunctionkey Shift 4 {newview 0}
2571 bind . <F4> edit_or_newview
2572 bind . <$M1B-q> doquit
2573 bind . <$M1B-f> {dofind 1 1}
2574 bind . <$M1B-g> {dofind 1 0}
2575 bind . <$M1B-r> dosearchback
2576 bind . <$M1B-s> dosearch
2577 bind . <$M1B-equal> {incrfont 1}
2578 bind . <$M1B-plus> {incrfont 1}
2579 bind . <$M1B-KP_Add> {incrfont 1}
2580 bind . <$M1B-minus> {incrfont -1}
2581 bind . <$M1B-KP_Subtract> {incrfont -1}
2582 wm protocol . WM_DELETE_WINDOW doquit
2583 bind . <Destroy> {stop_backends}
2584 bind . <Button-1> "click %W"
2585 bind $fstring <Key-Return> {dofind 1 1}
2586 bind $sha1entry <Key-Return> {gotocommit; break}
2587 bind $sha1entry <<PasteSelection>> clearsha1
2588 bind $sha1entry <<Paste>> clearsha1
2589 bind $cflist <1> {sel_flist %W %x %y; break}
2590 bind $cflist <B1-Motion> {sel_flist %W %x %y; break}
2591 bind $cflist <ButtonRelease-1> {treeclick %W %x %y}
2592 global ctxbut
2593 bind $cflist $ctxbut {pop_flist_menu %W %X %Y %x %y}
2594 bind $ctext $ctxbut {pop_diff_menu %W %X %Y %x %y}
2595 bind $ctext <Button-1> {focus %W}
2596 bind $ctext <<Selection>> rehighlight_search_results
2597
2598 set maincursor [. cget -cursor]
2599 set textcursor [$ctext cget -cursor]
2600 set curtextcursor $textcursor
2601
2602 set rowctxmenu .rowctxmenu
2603 makemenu $rowctxmenu {
2604 {mc "Diff this -> selected" command {diffvssel 0}}
2605 {mc "Diff selected -> this" command {diffvssel 1}}
2606 {mc "Make patch" command mkpatch}
2607 {mc "Create tag" command mktag}
2608 {mc "Write commit to file" command writecommit}
2609 {mc "Create new branch" command mkbranch}
2610 {mc "Cherry-pick this commit" command cherrypick}
2611 {mc "Reset HEAD branch to here" command resethead}
2612 {mc "Mark this commit" command markhere}
2613 {mc "Return to mark" command gotomark}
2614 {mc "Find descendant of this and mark" command find_common_desc}
2615 {mc "Compare with marked commit" command compare_commits}
2616 {mc "Diff this -> marked commit" command {diffvsmark 0}}
2617 {mc "Diff marked commit -> this" command {diffvsmark 1}}
2618 {mc "Revert this commit" command revert}
2619 }
2620 $rowctxmenu configure -tearoff 0
2621
2622 set fakerowmenu .fakerowmenu
2623 makemenu $fakerowmenu {
2624 {mc "Diff this -> selected" command {diffvssel 0}}
2625 {mc "Diff selected -> this" command {diffvssel 1}}
2626 {mc "Make patch" command mkpatch}
2627 {mc "Diff this -> marked commit" command {diffvsmark 0}}
2628 {mc "Diff marked commit -> this" command {diffvsmark 1}}
2629 }
2630 $fakerowmenu configure -tearoff 0
2631
2632 set headctxmenu .headctxmenu
2633 makemenu $headctxmenu {
2634 {mc "Check out this branch" command cobranch}
2635 {mc "Remove this branch" command rmbranch}
2636 }
2637 $headctxmenu configure -tearoff 0
2638
2639 global flist_menu
2640 set flist_menu .flistctxmenu
2641 makemenu $flist_menu {
2642 {mc "Highlight this too" command {flist_hl 0}}
2643 {mc "Highlight this only" command {flist_hl 1}}
2644 {mc "External diff" command {external_diff}}
2645 {mc "Blame parent commit" command {external_blame 1}}
2646 }
2647 $flist_menu configure -tearoff 0
2648
2649 global diff_menu
2650 set diff_menu .diffctxmenu
2651 makemenu $diff_menu {
2652 {mc "Show origin of this line" command show_line_source}
2653 {mc "Run git gui blame on this line" command {external_blame_diff}}
2654 }
2655 $diff_menu configure -tearoff 0
2656}
2657
2658# Windows sends all mouse wheel events to the current focused window, not
2659# the one where the mouse hovers, so bind those events here and redirect
2660# to the correct window
2661proc windows_mousewheel_redirector {W X Y D} {
2662 global canv canv2 canv3
2663 set w [winfo containing -displayof $W $X $Y]
2664 if {$w ne ""} {
2665 set u [expr {$D < 0 ? 5 : -5}]
2666 if {$w == $canv || $w == $canv2 || $w == $canv3} {
2667 allcanvs yview scroll $u units
2668 } else {
2669 catch {
2670 $w yview scroll $u units
2671 }
2672 }
2673 }
2674}
2675
2676# Update row number label when selectedline changes
2677proc selectedline_change {n1 n2 op} {
2678 global selectedline rownumsel
2679
2680 if {$selectedline eq {}} {
2681 set rownumsel {}
2682 } else {
2683 set rownumsel [expr {$selectedline + 1}]
2684 }
2685}
2686
2687# mouse-2 makes all windows scan vertically, but only the one
2688# the cursor is in scans horizontally
2689proc canvscan {op w x y} {
2690 global canv canv2 canv3
2691 foreach c [list $canv $canv2 $canv3] {
2692 if {$c == $w} {
2693 $c scan $op $x $y
2694 } else {
2695 $c scan $op 0 $y
2696 }
2697 }
2698}
2699
2700proc scrollcanv {cscroll f0 f1} {
2701 $cscroll set $f0 $f1
2702 drawvisible
2703 flushhighlights
2704}
2705
2706# when we make a key binding for the toplevel, make sure
2707# it doesn't get triggered when that key is pressed in the
2708# find string entry widget.
2709proc bindkey {ev script} {
2710 global entries
2711 bind . $ev $script
2712 set escript [bind Entry $ev]
2713 if {$escript == {}} {
2714 set escript [bind Entry <Key>]
2715 }
2716 foreach e $entries {
2717 bind $e $ev "$escript; break"
2718 }
2719}
2720
2721proc bindmodfunctionkey {mod n script} {
2722 bind . <$mod-F$n> $script
2723 catch { bind . <$mod-XF86_Switch_VT_$n> $script }
2724}
2725
2726# set the focus back to the toplevel for any click outside
2727# the entry widgets
2728proc click {w} {
2729 global ctext entries
2730 foreach e [concat $entries $ctext] {
2731 if {$w == $e} return
2732 }
2733 focus .
2734}
2735
2736# Adjust the progress bar for a change in requested extent or canvas size
2737proc adjustprogress {} {
2738 global progresscanv progressitem progresscoords
2739 global fprogitem fprogcoord lastprogupdate progupdatepending
2740 global rprogitem rprogcoord use_ttk
2741
2742 if {$use_ttk} {
2743 $progresscanv configure -value [expr {int($fprogcoord * 100)}]
2744 return
2745 }
2746
2747 set w [expr {[winfo width $progresscanv] - 4}]
2748 set x0 [expr {$w * [lindex $progresscoords 0]}]
2749 set x1 [expr {$w * [lindex $progresscoords 1]}]
2750 set h [winfo height $progresscanv]
2751 $progresscanv coords $progressitem $x0 0 $x1 $h
2752 $progresscanv coords $fprogitem 0 0 [expr {$w * $fprogcoord}] $h
2753 $progresscanv coords $rprogitem 0 0 [expr {$w * $rprogcoord}] $h
2754 set now [clock clicks -milliseconds]
2755 if {$now >= $lastprogupdate + 100} {
2756 set progupdatepending 0
2757 update
2758 } elseif {!$progupdatepending} {
2759 set progupdatepending 1
2760 after [expr {$lastprogupdate + 100 - $now}] doprogupdate
2761 }
2762}
2763
2764proc doprogupdate {} {
2765 global lastprogupdate progupdatepending
2766
2767 if {$progupdatepending} {
2768 set progupdatepending 0
2769 set lastprogupdate [clock clicks -milliseconds]
2770 update
2771 }
2772}
2773
2774proc savestuff {w} {
2775 global canv canv2 canv3 mainfont textfont uifont tabstop
2776 global stuffsaved findmergefiles maxgraphpct
2777 global maxwidth showneartags showlocalchanges
2778 global viewname viewfiles viewargs viewargscmd viewperm nextviewnum
2779 global cmitmode wrapcomment datetimeformat limitdiffs
2780 global colors uicolor bgcolor fgcolor diffcolors diffcontext selectbgcolor
2781 global uifgcolor uifgdisabledcolor
2782 global headbgcolor headfgcolor headoutlinecolor remotebgcolor
2783 global tagbgcolor tagfgcolor tagoutlinecolor
2784 global reflinecolor filesepbgcolor filesepfgcolor
2785 global mergecolors foundbgcolor currentsearchhitbgcolor
2786 global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor circlecolors
2787 global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
2788 global linkfgcolor circleoutlinecolor
2789 global autoselect autosellen extdifftool perfile_attrs markbgcolor use_ttk
2790 global hideremotes want_ttk maxrefs
2791 global config_file config_file_tmp
2792
2793 if {$stuffsaved} return
2794 if {![winfo viewable .]} return
2795 catch {
2796 if {[file exists $config_file_tmp]} {
2797 file delete -force $config_file_tmp
2798 }
2799 set f [open $config_file_tmp w]
2800 if {$::tcl_platform(platform) eq {windows}} {
2801 file attributes $config_file_tmp -hidden true
2802 }
2803 puts $f [list set mainfont $mainfont]
2804 puts $f [list set textfont $textfont]
2805 puts $f [list set uifont $uifont]
2806 puts $f [list set tabstop $tabstop]
2807 puts $f [list set findmergefiles $findmergefiles]
2808 puts $f [list set maxgraphpct $maxgraphpct]
2809 puts $f [list set maxwidth $maxwidth]
2810 puts $f [list set cmitmode $cmitmode]
2811 puts $f [list set wrapcomment $wrapcomment]
2812 puts $f [list set autoselect $autoselect]
2813 puts $f [list set autosellen $autosellen]
2814 puts $f [list set showneartags $showneartags]
2815 puts $f [list set maxrefs $maxrefs]
2816 puts $f [list set hideremotes $hideremotes]
2817 puts $f [list set showlocalchanges $showlocalchanges]
2818 puts $f [list set datetimeformat $datetimeformat]
2819 puts $f [list set limitdiffs $limitdiffs]
2820 puts $f [list set uicolor $uicolor]
2821 puts $f [list set want_ttk $want_ttk]
2822 puts $f [list set bgcolor $bgcolor]
2823 puts $f [list set fgcolor $fgcolor]
2824 puts $f [list set uifgcolor $uifgcolor]
2825 puts $f [list set uifgdisabledcolor $uifgdisabledcolor]
2826 puts $f [list set colors $colors]
2827 puts $f [list set diffcolors $diffcolors]
2828 puts $f [list set mergecolors $mergecolors]
2829 puts $f [list set markbgcolor $markbgcolor]
2830 puts $f [list set diffcontext $diffcontext]
2831 puts $f [list set selectbgcolor $selectbgcolor]
2832 puts $f [list set foundbgcolor $foundbgcolor]
2833 puts $f [list set currentsearchhitbgcolor $currentsearchhitbgcolor]
2834 puts $f [list set extdifftool $extdifftool]
2835 puts $f [list set perfile_attrs $perfile_attrs]
2836 puts $f [list set headbgcolor $headbgcolor]
2837 puts $f [list set headfgcolor $headfgcolor]
2838 puts $f [list set headoutlinecolor $headoutlinecolor]
2839 puts $f [list set remotebgcolor $remotebgcolor]
2840 puts $f [list set tagbgcolor $tagbgcolor]
2841 puts $f [list set tagfgcolor $tagfgcolor]
2842 puts $f [list set tagoutlinecolor $tagoutlinecolor]
2843 puts $f [list set reflinecolor $reflinecolor]
2844 puts $f [list set filesepbgcolor $filesepbgcolor]
2845 puts $f [list set filesepfgcolor $filesepfgcolor]
2846 puts $f [list set linehoverbgcolor $linehoverbgcolor]
2847 puts $f [list set linehoverfgcolor $linehoverfgcolor]
2848 puts $f [list set linehoveroutlinecolor $linehoveroutlinecolor]
2849 puts $f [list set mainheadcirclecolor $mainheadcirclecolor]
2850 puts $f [list set workingfilescirclecolor $workingfilescirclecolor]
2851 puts $f [list set indexcirclecolor $indexcirclecolor]
2852 puts $f [list set circlecolors $circlecolors]
2853 puts $f [list set linkfgcolor $linkfgcolor]
2854 puts $f [list set circleoutlinecolor $circleoutlinecolor]
2855
2856 puts $f "set geometry(main) [wm geometry .]"
2857 puts $f "set geometry(state) [wm state .]"
2858 puts $f "set geometry(topwidth) [winfo width .tf]"
2859 puts $f "set geometry(topheight) [winfo height .tf]"
2860 if {$use_ttk} {
2861 puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sashpos 0] 1\""
2862 puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sashpos 1] 1\""
2863 } else {
2864 puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sash coord 0]\""
2865 puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sash coord 1]\""
2866 }
2867 puts $f "set geometry(botwidth) [winfo width .bleft]"
2868 puts $f "set geometry(botheight) [winfo height .bleft]"
2869
2870 puts -nonewline $f "set permviews {"
2871 for {set v 0} {$v < $nextviewnum} {incr v} {
2872 if {$viewperm($v)} {
2873 puts $f "{[list $viewname($v) $viewfiles($v) $viewargs($v) $viewargscmd($v)]}"
2874 }
2875 }
2876 puts $f "}"
2877 close $f
2878 file rename -force $config_file_tmp $config_file
2879 }
2880 set stuffsaved 1
2881}
2882
2883proc resizeclistpanes {win w} {
2884 global oldwidth use_ttk
2885 if {[info exists oldwidth($win)]} {
2886 if {$use_ttk} {
2887 set s0 [$win sashpos 0]
2888 set s1 [$win sashpos 1]
2889 } else {
2890 set s0 [$win sash coord 0]
2891 set s1 [$win sash coord 1]
2892 }
2893 if {$w < 60} {
2894 set sash0 [expr {int($w/2 - 2)}]
2895 set sash1 [expr {int($w*5/6 - 2)}]
2896 } else {
2897 set factor [expr {1.0 * $w / $oldwidth($win)}]
2898 set sash0 [expr {int($factor * [lindex $s0 0])}]
2899 set sash1 [expr {int($factor * [lindex $s1 0])}]
2900 if {$sash0 < 30} {
2901 set sash0 30
2902 }
2903 if {$sash1 < $sash0 + 20} {
2904 set sash1 [expr {$sash0 + 20}]
2905 }
2906 if {$sash1 > $w - 10} {
2907 set sash1 [expr {$w - 10}]
2908 if {$sash0 > $sash1 - 20} {
2909 set sash0 [expr {$sash1 - 20}]
2910 }
2911 }
2912 }
2913 if {$use_ttk} {
2914 $win sashpos 0 $sash0
2915 $win sashpos 1 $sash1
2916 } else {
2917 $win sash place 0 $sash0 [lindex $s0 1]
2918 $win sash place 1 $sash1 [lindex $s1 1]
2919 }
2920 }
2921 set oldwidth($win) $w
2922}
2923
2924proc resizecdetpanes {win w} {
2925 global oldwidth use_ttk
2926 if {[info exists oldwidth($win)]} {
2927 if {$use_ttk} {
2928 set s0 [$win sashpos 0]
2929 } else {
2930 set s0 [$win sash coord 0]
2931 }
2932 if {$w < 60} {
2933 set sash0 [expr {int($w*3/4 - 2)}]
2934 } else {
2935 set factor [expr {1.0 * $w / $oldwidth($win)}]
2936 set sash0 [expr {int($factor * [lindex $s0 0])}]
2937 if {$sash0 < 45} {
2938 set sash0 45
2939 }
2940 if {$sash0 > $w - 15} {
2941 set sash0 [expr {$w - 15}]
2942 }
2943 }
2944 if {$use_ttk} {
2945 $win sashpos 0 $sash0
2946 } else {
2947 $win sash place 0 $sash0 [lindex $s0 1]
2948 }
2949 }
2950 set oldwidth($win) $w
2951}
2952
2953proc allcanvs args {
2954 global canv canv2 canv3
2955 eval $canv $args
2956 eval $canv2 $args
2957 eval $canv3 $args
2958}
2959
2960proc bindall {event action} {
2961 global canv canv2 canv3
2962 bind $canv $event $action
2963 bind $canv2 $event $action
2964 bind $canv3 $event $action
2965}
2966
2967proc about {} {
2968 global uifont NS
2969 set w .about
2970 if {[winfo exists $w]} {
2971 raise $w
2972 return
2973 }
2974 ttk_toplevel $w
2975 wm title $w [mc "About gitk"]
2976 make_transient $w .
2977 message $w.m -text [mc "
2978Gitk - a commit viewer for git
2979
2980Copyright \u00a9 2005-2014 Paul Mackerras
2981
2982Use and redistribute under the terms of the GNU General Public License"] \
2983 -justify center -aspect 400 -border 2 -bg white -relief groove
2984 pack $w.m -side top -fill x -padx 2 -pady 2
2985 ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
2986 pack $w.ok -side bottom
2987 bind $w <Visibility> "focus $w.ok"
2988 bind $w <Key-Escape> "destroy $w"
2989 bind $w <Key-Return> "destroy $w"
2990 tk::PlaceWindow $w widget .
2991}
2992
2993proc keys {} {
2994 global NS
2995 set w .keys
2996 if {[winfo exists $w]} {
2997 raise $w
2998 return
2999 }
3000 if {[tk windowingsystem] eq {aqua}} {
3001 set M1T Cmd
3002 } else {
3003 set M1T Ctrl
3004 }
3005 ttk_toplevel $w
3006 wm title $w [mc "Gitk key bindings"]
3007 make_transient $w .
3008 message $w.m -text "
3009[mc "Gitk key bindings:"]
3010
3011[mc "<%s-Q> Quit" $M1T]
3012[mc "<%s-W> Close window" $M1T]
3013[mc "<Home> Move to first commit"]
3014[mc "<End> Move to last commit"]
3015[mc "<Up>, p, k Move up one commit"]
3016[mc "<Down>, n, j Move down one commit"]
3017[mc "<Left>, z, h Go back in history list"]
3018[mc "<Right>, x, l Go forward in history list"]
3019[mc "<PageUp> Move up one page in commit list"]
3020[mc "<PageDown> Move down one page in commit list"]
3021[mc "<%s-Home> Scroll to top of commit list" $M1T]
3022[mc "<%s-End> Scroll to bottom of commit list" $M1T]
3023[mc "<%s-Up> Scroll commit list up one line" $M1T]
3024[mc "<%s-Down> Scroll commit list down one line" $M1T]
3025[mc "<%s-PageUp> Scroll commit list up one page" $M1T]
3026[mc "<%s-PageDown> Scroll commit list down one page" $M1T]
3027[mc "<Shift-Up> Find backwards (upwards, later commits)"]
3028[mc "<Shift-Down> Find forwards (downwards, earlier commits)"]
3029[mc "<Delete>, b Scroll diff view up one page"]
3030[mc "<Backspace> Scroll diff view up one page"]
3031[mc "<Space> Scroll diff view down one page"]
3032[mc "u Scroll diff view up 18 lines"]
3033[mc "d Scroll diff view down 18 lines"]
3034[mc "<%s-F> Find" $M1T]
3035[mc "<%s-G> Move to next find hit" $M1T]
3036[mc "<Return> Move to next find hit"]
3037[mc "/ Focus the search box"]
3038[mc "? Move to previous find hit"]
3039[mc "f Scroll diff view to next file"]
3040[mc "<%s-S> Search for next hit in diff view" $M1T]
3041[mc "<%s-R> Search for previous hit in diff view" $M1T]
3042[mc "<%s-KP+> Increase font size" $M1T]
3043[mc "<%s-plus> Increase font size" $M1T]
3044[mc "<%s-KP-> Decrease font size" $M1T]
3045[mc "<%s-minus> Decrease font size" $M1T]
3046[mc "<F5> Update"]
3047" \
3048 -justify left -bg white -border 2 -relief groove
3049 pack $w.m -side top -fill both -padx 2 -pady 2
3050 ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
3051 bind $w <Key-Escape> [list destroy $w]
3052 pack $w.ok -side bottom
3053 bind $w <Visibility> "focus $w.ok"
3054 bind $w <Key-Escape> "destroy $w"
3055 bind $w <Key-Return> "destroy $w"
3056}
3057
3058# Procedures for manipulating the file list window at the
3059# bottom right of the overall window.
3060
3061proc treeview {w l openlevs} {
3062 global treecontents treediropen treeheight treeparent treeindex
3063
3064 set ix 0
3065 set treeindex() 0
3066 set lev 0
3067 set prefix {}
3068 set prefixend -1
3069 set prefendstack {}
3070 set htstack {}
3071 set ht 0
3072 set treecontents() {}
3073 $w conf -state normal
3074 foreach f $l {
3075 while {[string range $f 0 $prefixend] ne $prefix} {
3076 if {$lev <= $openlevs} {
3077 $w mark set e:$treeindex($prefix) "end -1c"
3078 $w mark gravity e:$treeindex($prefix) left
3079 }
3080 set treeheight($prefix) $ht
3081 incr ht [lindex $htstack end]
3082 set htstack [lreplace $htstack end end]
3083 set prefixend [lindex $prefendstack end]
3084 set prefendstack [lreplace $prefendstack end end]
3085 set prefix [string range $prefix 0 $prefixend]
3086 incr lev -1
3087 }
3088 set tail [string range $f [expr {$prefixend+1}] end]
3089 while {[set slash [string first "/" $tail]] >= 0} {
3090 lappend htstack $ht
3091 set ht 0
3092 lappend prefendstack $prefixend
3093 incr prefixend [expr {$slash + 1}]
3094 set d [string range $tail 0 $slash]
3095 lappend treecontents($prefix) $d
3096 set oldprefix $prefix
3097 append prefix $d
3098 set treecontents($prefix) {}
3099 set treeindex($prefix) [incr ix]
3100 set treeparent($prefix) $oldprefix
3101 set tail [string range $tail [expr {$slash+1}] end]
3102 if {$lev <= $openlevs} {
3103 set ht 1
3104 set treediropen($prefix) [expr {$lev < $openlevs}]
3105 set bm [expr {$lev == $openlevs? "tri-rt": "tri-dn"}]
3106 $w mark set d:$ix "end -1c"
3107 $w mark gravity d:$ix left
3108 set str "\n"
3109 for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3110 $w insert end $str
3111 $w image create end -align center -image $bm -padx 1 \
3112 -name a:$ix
3113 $w insert end $d [highlight_tag $prefix]
3114 $w mark set s:$ix "end -1c"
3115 $w mark gravity s:$ix left
3116 }
3117 incr lev
3118 }
3119 if {$tail ne {}} {
3120 if {$lev <= $openlevs} {
3121 incr ht
3122 set str "\n"
3123 for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3124 $w insert end $str
3125 $w insert end $tail [highlight_tag $f]
3126 }
3127 lappend treecontents($prefix) $tail
3128 }
3129 }
3130 while {$htstack ne {}} {
3131 set treeheight($prefix) $ht
3132 incr ht [lindex $htstack end]
3133 set htstack [lreplace $htstack end end]
3134 set prefixend [lindex $prefendstack end]
3135 set prefendstack [lreplace $prefendstack end end]
3136 set prefix [string range $prefix 0 $prefixend]
3137 }
3138 $w conf -state disabled
3139}
3140
3141proc linetoelt {l} {
3142 global treeheight treecontents
3143
3144 set y 2
3145 set prefix {}
3146 while {1} {
3147 foreach e $treecontents($prefix) {
3148 if {$y == $l} {
3149 return "$prefix$e"
3150 }
3151 set n 1
3152 if {[string index $e end] eq "/"} {
3153 set n $treeheight($prefix$e)
3154 if {$y + $n > $l} {
3155 append prefix $e
3156 incr y
3157 break
3158 }
3159 }
3160 incr y $n
3161 }
3162 }
3163}
3164
3165proc highlight_tree {y prefix} {
3166 global treeheight treecontents cflist
3167
3168 foreach e $treecontents($prefix) {
3169 set path $prefix$e
3170 if {[highlight_tag $path] ne {}} {
3171 $cflist tag add bold $y.0 "$y.0 lineend"
3172 }
3173 incr y
3174 if {[string index $e end] eq "/" && $treeheight($path) > 1} {
3175 set y [highlight_tree $y $path]
3176 }
3177 }
3178 return $y
3179}
3180
3181proc treeclosedir {w dir} {
3182 global treediropen treeheight treeparent treeindex
3183
3184 set ix $treeindex($dir)
3185 $w conf -state normal
3186 $w delete s:$ix e:$ix
3187 set treediropen($dir) 0
3188 $w image configure a:$ix -image tri-rt
3189 $w conf -state disabled
3190 set n [expr {1 - $treeheight($dir)}]
3191 while {$dir ne {}} {
3192 incr treeheight($dir) $n
3193 set dir $treeparent($dir)
3194 }
3195}
3196
3197proc treeopendir {w dir} {
3198 global treediropen treeheight treeparent treecontents treeindex
3199
3200 set ix $treeindex($dir)
3201 $w conf -state normal
3202 $w image configure a:$ix -image tri-dn
3203 $w mark set e:$ix s:$ix
3204 $w mark gravity e:$ix right
3205 set lev 0
3206 set str "\n"
3207 set n [llength $treecontents($dir)]
3208 for {set x $dir} {$x ne {}} {set x $treeparent($x)} {
3209 incr lev
3210 append str "\t"
3211 incr treeheight($x) $n
3212 }
3213 foreach e $treecontents($dir) {
3214 set de $dir$e
3215 if {[string index $e end] eq "/"} {
3216 set iy $treeindex($de)
3217 $w mark set d:$iy e:$ix
3218 $w mark gravity d:$iy left
3219 $w insert e:$ix $str
3220 set treediropen($de) 0
3221 $w image create e:$ix -align center -image tri-rt -padx 1 \
3222 -name a:$iy
3223 $w insert e:$ix $e [highlight_tag $de]
3224 $w mark set s:$iy e:$ix
3225 $w mark gravity s:$iy left
3226 set treeheight($de) 1
3227 } else {
3228 $w insert e:$ix $str
3229 $w insert e:$ix $e [highlight_tag $de]
3230 }
3231 }
3232 $w mark gravity e:$ix right
3233 $w conf -state disabled
3234 set treediropen($dir) 1
3235 set top [lindex [split [$w index @0,0] .] 0]
3236 set ht [$w cget -height]
3237 set l [lindex [split [$w index s:$ix] .] 0]
3238 if {$l < $top} {
3239 $w yview $l.0
3240 } elseif {$l + $n + 1 > $top + $ht} {
3241 set top [expr {$l + $n + 2 - $ht}]
3242 if {$l < $top} {
3243 set top $l
3244 }
3245 $w yview $top.0
3246 }
3247}
3248
3249proc treeclick {w x y} {
3250 global treediropen cmitmode ctext cflist cflist_top
3251
3252 if {$cmitmode ne "tree"} return
3253 if {![info exists cflist_top]} return
3254 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3255 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3256 $cflist tag add highlight $l.0 "$l.0 lineend"
3257 set cflist_top $l
3258 if {$l == 1} {
3259 $ctext yview 1.0
3260 return
3261 }
3262 set e [linetoelt $l]
3263 if {[string index $e end] ne "/"} {
3264 showfile $e
3265 } elseif {$treediropen($e)} {
3266 treeclosedir $w $e
3267 } else {
3268 treeopendir $w $e
3269 }
3270}
3271
3272proc setfilelist {id} {
3273 global treefilelist cflist jump_to_here
3274
3275 treeview $cflist $treefilelist($id) 0
3276 if {$jump_to_here ne {}} {
3277 set f [lindex $jump_to_here 0]
3278 if {[lsearch -exact $treefilelist($id) $f] >= 0} {
3279 showfile $f
3280 }
3281 }
3282}
3283
3284image create bitmap tri-rt -background black -foreground blue -data {
3285 #define tri-rt_width 13
3286 #define tri-rt_height 13
3287 static unsigned char tri-rt_bits[] = {
3288 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x30, 0x00, 0x70, 0x00, 0xf0, 0x00,
3289 0xf0, 0x01, 0xf0, 0x00, 0x70, 0x00, 0x30, 0x00, 0x10, 0x00, 0x00, 0x00,
3290 0x00, 0x00};
3291} -maskdata {
3292 #define tri-rt-mask_width 13
3293 #define tri-rt-mask_height 13
3294 static unsigned char tri-rt-mask_bits[] = {
3295 0x08, 0x00, 0x18, 0x00, 0x38, 0x00, 0x78, 0x00, 0xf8, 0x00, 0xf8, 0x01,
3296 0xf8, 0x03, 0xf8, 0x01, 0xf8, 0x00, 0x78, 0x00, 0x38, 0x00, 0x18, 0x00,
3297 0x08, 0x00};
3298}
3299image create bitmap tri-dn -background black -foreground blue -data {
3300 #define tri-dn_width 13
3301 #define tri-dn_height 13
3302 static unsigned char tri-dn_bits[] = {
3303 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xf8, 0x03,
3304 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3305 0x00, 0x00};
3306} -maskdata {
3307 #define tri-dn-mask_width 13
3308 #define tri-dn-mask_height 13
3309 static unsigned char tri-dn-mask_bits[] = {
3310 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x1f, 0xfe, 0x0f, 0xfc, 0x07,
3311 0xf8, 0x03, 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
3312 0x00, 0x00};
3313}
3314
3315image create bitmap reficon-T -background black -foreground yellow -data {
3316 #define tagicon_width 13
3317 #define tagicon_height 9
3318 static unsigned char tagicon_bits[] = {
3319 0x00, 0x00, 0x00, 0x00, 0xf0, 0x07, 0xf8, 0x07,
3320 0xfc, 0x07, 0xf8, 0x07, 0xf0, 0x07, 0x00, 0x00, 0x00, 0x00};
3321} -maskdata {
3322 #define tagicon-mask_width 13
3323 #define tagicon-mask_height 9
3324 static unsigned char tagicon-mask_bits[] = {
3325 0x00, 0x00, 0xf0, 0x0f, 0xf8, 0x0f, 0xfc, 0x0f,
3326 0xfe, 0x0f, 0xfc, 0x0f, 0xf8, 0x0f, 0xf0, 0x0f, 0x00, 0x00};
3327}
3328set rectdata {
3329 #define headicon_width 13
3330 #define headicon_height 9
3331 static unsigned char headicon_bits[] = {
3332 0x00, 0x00, 0x00, 0x00, 0xf8, 0x07, 0xf8, 0x07,
3333 0xf8, 0x07, 0xf8, 0x07, 0xf8, 0x07, 0x00, 0x00, 0x00, 0x00};
3334}
3335set rectmask {
3336 #define headicon-mask_width 13
3337 #define headicon-mask_height 9
3338 static unsigned char headicon-mask_bits[] = {
3339 0x00, 0x00, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f,
3340 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0x00, 0x00};
3341}
3342image create bitmap reficon-H -background black -foreground green \
3343 -data $rectdata -maskdata $rectmask
3344image create bitmap reficon-o -background black -foreground "#ddddff" \
3345 -data $rectdata -maskdata $rectmask
3346
3347proc init_flist {first} {
3348 global cflist cflist_top difffilestart
3349
3350 $cflist conf -state normal
3351 $cflist delete 0.0 end
3352 if {$first ne {}} {
3353 $cflist insert end $first
3354 set cflist_top 1
3355 $cflist tag add highlight 1.0 "1.0 lineend"
3356 } else {
3357 catch {unset cflist_top}
3358 }
3359 $cflist conf -state disabled
3360 set difffilestart {}
3361}
3362
3363proc highlight_tag {f} {
3364 global highlight_paths
3365
3366 foreach p $highlight_paths {
3367 if {[string match $p $f]} {
3368 return "bold"
3369 }
3370 }
3371 return {}
3372}
3373
3374proc highlight_filelist {} {
3375 global cmitmode cflist
3376
3377 $cflist conf -state normal
3378 if {$cmitmode ne "tree"} {
3379 set end [lindex [split [$cflist index end] .] 0]
3380 for {set l 2} {$l < $end} {incr l} {
3381 set line [$cflist get $l.0 "$l.0 lineend"]
3382 if {[highlight_tag $line] ne {}} {
3383 $cflist tag add bold $l.0 "$l.0 lineend"
3384 }
3385 }
3386 } else {
3387 highlight_tree 2 {}
3388 }
3389 $cflist conf -state disabled
3390}
3391
3392proc unhighlight_filelist {} {
3393 global cflist
3394
3395 $cflist conf -state normal
3396 $cflist tag remove bold 1.0 end
3397 $cflist conf -state disabled
3398}
3399
3400proc add_flist {fl} {
3401 global cflist
3402
3403 $cflist conf -state normal
3404 foreach f $fl {
3405 $cflist insert end "\n"
3406 $cflist insert end $f [highlight_tag $f]
3407 }
3408 $cflist conf -state disabled
3409}
3410
3411proc sel_flist {w x y} {
3412 global ctext difffilestart cflist cflist_top cmitmode
3413
3414 if {$cmitmode eq "tree"} return
3415 if {![info exists cflist_top]} return
3416 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3417 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3418 $cflist tag add highlight $l.0 "$l.0 lineend"
3419 set cflist_top $l
3420 if {$l == 1} {
3421 $ctext yview 1.0
3422 } else {
3423 catch {$ctext yview [lindex $difffilestart [expr {$l - 2}]]}
3424 }
3425 suppress_highlighting_file_for_current_scrollpos
3426}
3427
3428proc pop_flist_menu {w X Y x y} {
3429 global ctext cflist cmitmode flist_menu flist_menu_file
3430 global treediffs diffids
3431
3432 stopfinding
3433 set l [lindex [split [$w index "@$x,$y"] "."] 0]
3434 if {$l <= 1} return
3435 if {$cmitmode eq "tree"} {
3436 set e [linetoelt $l]
3437 if {[string index $e end] eq "/"} return
3438 } else {
3439 set e [lindex $treediffs($diffids) [expr {$l-2}]]
3440 }
3441 set flist_menu_file $e
3442 set xdiffstate "normal"
3443 if {$cmitmode eq "tree"} {
3444 set xdiffstate "disabled"
3445 }
3446 # Disable "External diff" item in tree mode
3447 $flist_menu entryconf 2 -state $xdiffstate
3448 tk_popup $flist_menu $X $Y
3449}
3450
3451proc find_ctext_fileinfo {line} {
3452 global ctext_file_names ctext_file_lines
3453
3454 set ok [bsearch $ctext_file_lines $line]
3455 set tline [lindex $ctext_file_lines $ok]
3456
3457 if {$ok >= [llength $ctext_file_lines] || $line < $tline} {
3458 return {}
3459 } else {
3460 return [list [lindex $ctext_file_names $ok] $tline]
3461 }
3462}
3463
3464proc pop_diff_menu {w X Y x y} {
3465 global ctext diff_menu flist_menu_file
3466 global diff_menu_txtpos diff_menu_line
3467 global diff_menu_filebase
3468
3469 set diff_menu_txtpos [split [$w index "@$x,$y"] "."]
3470 set diff_menu_line [lindex $diff_menu_txtpos 0]
3471 # don't pop up the menu on hunk-separator or file-separator lines
3472 if {[lsearch -glob [$ctext tag names $diff_menu_line.0] "*sep"] >= 0} {
3473 return
3474 }
3475 stopfinding
3476 set f [find_ctext_fileinfo $diff_menu_line]
3477 if {$f eq {}} return
3478 set flist_menu_file [lindex $f 0]
3479 set diff_menu_filebase [lindex $f 1]
3480 tk_popup $diff_menu $X $Y
3481}
3482
3483proc flist_hl {only} {
3484 global flist_menu_file findstring gdttype
3485
3486 set x [shellquote $flist_menu_file]
3487 if {$only || $findstring eq {} || $gdttype ne [mc "touching paths:"]} {
3488 set findstring $x
3489 } else {
3490 append findstring " " $x
3491 }
3492 set gdttype [mc "touching paths:"]
3493}
3494
3495proc gitknewtmpdir {} {
3496 global diffnum gitktmpdir gitdir env
3497
3498 if {![info exists gitktmpdir]} {
3499 if {[info exists env(GITK_TMPDIR)]} {
3500 set tmpdir $env(GITK_TMPDIR)
3501 } elseif {[info exists env(TMPDIR)]} {
3502 set tmpdir $env(TMPDIR)
3503 } else {
3504 set tmpdir $gitdir
3505 }
3506 set gitktmpformat [file join $tmpdir ".gitk-tmp.XXXXXX"]
3507 set gitktmpdir [exec mktemp -d $gitktmpformat]
3508 if {[catch {file mkdir $gitktmpdir} err]} {
3509 error_popup "[mc "Error creating temporary directory %s:" $gitktmpdir] $err"
3510 unset gitktmpdir
3511 return {}
3512 }
3513 set diffnum 0
3514 }
3515 incr diffnum
3516 set diffdir [file join $gitktmpdir $diffnum]
3517 if {[catch {file mkdir $diffdir} err]} {
3518 error_popup "[mc "Error creating temporary directory %s:" $diffdir] $err"
3519 return {}
3520 }
3521 return $diffdir
3522}
3523
3524proc save_file_from_commit {filename output what} {
3525 global nullfile
3526
3527 if {[catch {exec git show $filename -- > $output} err]} {
3528 if {[string match "fatal: bad revision *" $err]} {
3529 return $nullfile
3530 }
3531 error_popup "[mc "Error getting \"%s\" from %s:" $filename $what] $err"
3532 return {}
3533 }
3534 return $output
3535}
3536
3537proc external_diff_get_one_file {diffid filename diffdir} {
3538 global nullid nullid2 nullfile
3539 global worktree
3540
3541 if {$diffid == $nullid} {
3542 set difffile [file join $worktree $filename]
3543 if {[file exists $difffile]} {
3544 return $difffile
3545 }
3546 return $nullfile
3547 }
3548 if {$diffid == $nullid2} {
3549 set difffile [file join $diffdir "\[index\] [file tail $filename]"]
3550 return [save_file_from_commit :$filename $difffile index]
3551 }
3552 set difffile [file join $diffdir "\[$diffid\] [file tail $filename]"]
3553 return [save_file_from_commit $diffid:$filename $difffile \
3554 "revision $diffid"]
3555}
3556
3557proc external_diff {} {
3558 global nullid nullid2
3559 global flist_menu_file
3560 global diffids
3561 global extdifftool
3562
3563 if {[llength $diffids] == 1} {
3564 # no reference commit given
3565 set diffidto [lindex $diffids 0]
3566 if {$diffidto eq $nullid} {
3567 # diffing working copy with index
3568 set diffidfrom $nullid2
3569 } elseif {$diffidto eq $nullid2} {
3570 # diffing index with HEAD
3571 set diffidfrom "HEAD"
3572 } else {
3573 # use first parent commit
3574 global parentlist selectedline
3575 set diffidfrom [lindex $parentlist $selectedline 0]
3576 }
3577 } else {
3578 set diffidfrom [lindex $diffids 0]
3579 set diffidto [lindex $diffids 1]
3580 }
3581
3582 # make sure that several diffs wont collide
3583 set diffdir [gitknewtmpdir]
3584 if {$diffdir eq {}} return
3585
3586 # gather files to diff
3587 set difffromfile [external_diff_get_one_file $diffidfrom $flist_menu_file $diffdir]
3588 set difftofile [external_diff_get_one_file $diffidto $flist_menu_file $diffdir]
3589
3590 if {$difffromfile ne {} && $difftofile ne {}} {
3591 set cmd [list [shellsplit $extdifftool] $difffromfile $difftofile]
3592 if {[catch {set fl [open |$cmd r]} err]} {
3593 file delete -force $diffdir
3594 error_popup "$extdifftool: [mc "command failed:"] $err"
3595 } else {
3596 fconfigure $fl -blocking 0
3597 filerun $fl [list delete_at_eof $fl $diffdir]
3598 }
3599 }
3600}
3601
3602proc find_hunk_blamespec {base line} {
3603 global ctext
3604
3605 # Find and parse the hunk header
3606 set s_lix [$ctext search -backwards -regexp ^@@ "$line.0 lineend" $base.0]
3607 if {$s_lix eq {}} return
3608
3609 set s_line [$ctext get $s_lix "$s_lix + 1 lines"]
3610 if {![regexp {^@@@*(( -\d+(,\d+)?)+) \+(\d+)(,\d+)? @@} $s_line \
3611 s_line old_specs osz osz1 new_line nsz]} {
3612 return
3613 }
3614
3615 # base lines for the parents
3616 set base_lines [list $new_line]
3617 foreach old_spec [lrange [split $old_specs " "] 1 end] {
3618 if {![regexp -- {-(\d+)(,\d+)?} $old_spec \
3619 old_spec old_line osz]} {
3620 return
3621 }
3622 lappend base_lines $old_line
3623 }
3624
3625 # Now scan the lines to determine offset within the hunk
3626 set max_parent [expr {[llength $base_lines]-2}]
3627 set dline 0
3628 set s_lno [lindex [split $s_lix "."] 0]
3629
3630 # Determine if the line is removed
3631 set chunk [$ctext get $line.0 "$line.1 + $max_parent chars"]
3632 if {[string match {[-+ ]*} $chunk]} {
3633 set removed_idx [string first "-" $chunk]
3634 # Choose a parent index
3635 if {$removed_idx >= 0} {
3636 set parent $removed_idx
3637 } else {
3638 set unchanged_idx [string first " " $chunk]
3639 if {$unchanged_idx >= 0} {
3640 set parent $unchanged_idx
3641 } else {
3642 # blame the current commit
3643 set parent -1
3644 }
3645 }
3646 # then count other lines that belong to it
3647 for {set i $line} {[incr i -1] > $s_lno} {} {
3648 set chunk [$ctext get $i.0 "$i.1 + $max_parent chars"]
3649 # Determine if the line is removed
3650 set removed_idx [string first "-" $chunk]
3651 if {$parent >= 0} {
3652 set code [string index $chunk $parent]
3653 if {$code eq "-" || ($removed_idx < 0 && $code ne "+")} {
3654 incr dline
3655 }
3656 } else {
3657 if {$removed_idx < 0} {
3658 incr dline
3659 }
3660 }
3661 }
3662 incr parent
3663 } else {
3664 set parent 0
3665 }
3666
3667 incr dline [lindex $base_lines $parent]
3668 return [list $parent $dline]
3669}
3670
3671proc external_blame_diff {} {
3672 global currentid cmitmode
3673 global diff_menu_txtpos diff_menu_line
3674 global diff_menu_filebase flist_menu_file
3675
3676 if {$cmitmode eq "tree"} {
3677 set parent_idx 0
3678 set line [expr {$diff_menu_line - $diff_menu_filebase}]
3679 } else {
3680 set hinfo [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3681 if {$hinfo ne {}} {
3682 set parent_idx [lindex $hinfo 0]
3683 set line [lindex $hinfo 1]
3684 } else {
3685 set parent_idx 0
3686 set line 0
3687 }
3688 }
3689
3690 external_blame $parent_idx $line
3691}
3692
3693# Find the SHA1 ID of the blob for file $fname in the index
3694# at stage 0 or 2
3695proc index_sha1 {fname} {
3696 set f [open [list | git ls-files -s $fname] r]
3697 while {[gets $f line] >= 0} {
3698 set info [lindex [split $line "\t"] 0]
3699 set stage [lindex $info 2]
3700 if {$stage eq "0" || $stage eq "2"} {
3701 close $f
3702 return [lindex $info 1]
3703 }
3704 }
3705 close $f
3706 return {}
3707}
3708
3709# Turn an absolute path into one relative to the current directory
3710proc make_relative {f} {
3711 if {[file pathtype $f] eq "relative"} {
3712 return $f
3713 }
3714 set elts [file split $f]
3715 set here [file split [pwd]]
3716 set ei 0
3717 set hi 0
3718 set res {}
3719 foreach d $here {
3720 if {$ei < $hi || $ei >= [llength $elts] || [lindex $elts $ei] ne $d} {
3721 lappend res ".."
3722 } else {
3723 incr ei
3724 }
3725 incr hi
3726 }
3727 set elts [concat $res [lrange $elts $ei end]]
3728 return [eval file join $elts]
3729}
3730
3731proc external_blame {parent_idx {line {}}} {
3732 global flist_menu_file cdup
3733 global nullid nullid2
3734 global parentlist selectedline currentid
3735
3736 if {$parent_idx > 0} {
3737 set base_commit [lindex $parentlist $selectedline [expr {$parent_idx-1}]]
3738 } else {
3739 set base_commit $currentid
3740 }
3741
3742 if {$base_commit eq {} || $base_commit eq $nullid || $base_commit eq $nullid2} {
3743 error_popup [mc "No such commit"]
3744 return
3745 }
3746
3747 set cmdline [list git gui blame]
3748 if {$line ne {} && $line > 1} {
3749 lappend cmdline "--line=$line"
3750 }
3751 set f [file join $cdup $flist_menu_file]
3752 # Unfortunately it seems git gui blame doesn't like
3753 # being given an absolute path...
3754 set f [make_relative $f]
3755 lappend cmdline $base_commit $f
3756 if {[catch {eval exec $cmdline &} err]} {
3757 error_popup "[mc "git gui blame: command failed:"] $err"
3758 }
3759}
3760
3761proc show_line_source {} {
3762 global cmitmode currentid parents curview blamestuff blameinst
3763 global diff_menu_line diff_menu_filebase flist_menu_file
3764 global nullid nullid2 gitdir cdup
3765
3766 set from_index {}
3767 if {$cmitmode eq "tree"} {
3768 set id $currentid
3769 set line [expr {$diff_menu_line - $diff_menu_filebase}]
3770 } else {
3771 set h [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3772 if {$h eq {}} return
3773 set pi [lindex $h 0]
3774 if {$pi == 0} {
3775 mark_ctext_line $diff_menu_line
3776 return
3777 }
3778 incr pi -1
3779 if {$currentid eq $nullid} {
3780 if {$pi > 0} {
3781 # must be a merge in progress...
3782 if {[catch {
3783 # get the last line from .git/MERGE_HEAD
3784 set f [open [file join $gitdir MERGE_HEAD] r]
3785 set id [lindex [split [read $f] "\n"] end-1]
3786 close $f
3787 } err]} {
3788 error_popup [mc "Couldn't read merge head: %s" $err]
3789 return
3790 }
3791 } elseif {$parents($curview,$currentid) eq $nullid2} {
3792 # need to do the blame from the index
3793 if {[catch {
3794 set from_index [index_sha1 $flist_menu_file]
3795 } err]} {
3796 error_popup [mc "Error reading index: %s" $err]
3797 return
3798 }
3799 } else {
3800 set id $parents($curview,$currentid)
3801 }
3802 } else {
3803 set id [lindex $parents($curview,$currentid) $pi]
3804 }
3805 set line [lindex $h 1]
3806 }
3807 set blameargs {}
3808 if {$from_index ne {}} {
3809 lappend blameargs | git cat-file blob $from_index
3810 }
3811 lappend blameargs | git blame -p -L$line,+1
3812 if {$from_index ne {}} {
3813 lappend blameargs --contents -
3814 } else {
3815 lappend blameargs $id
3816 }
3817 lappend blameargs -- [file join $cdup $flist_menu_file]
3818 if {[catch {
3819 set f [open $blameargs r]
3820 } err]} {
3821 error_popup [mc "Couldn't start git blame: %s" $err]
3822 return
3823 }
3824 nowbusy blaming [mc "Searching"]
3825 fconfigure $f -blocking 0
3826 set i [reg_instance $f]
3827 set blamestuff($i) {}
3828 set blameinst $i
3829 filerun $f [list read_line_source $f $i]
3830}
3831
3832proc stopblaming {} {
3833 global blameinst
3834
3835 if {[info exists blameinst]} {
3836 stop_instance $blameinst
3837 unset blameinst
3838 notbusy blaming
3839 }
3840}
3841
3842proc read_line_source {fd inst} {
3843 global blamestuff curview commfd blameinst nullid nullid2
3844
3845 while {[gets $fd line] >= 0} {
3846 lappend blamestuff($inst) $line
3847 }
3848 if {![eof $fd]} {
3849 return 1
3850 }
3851 unset commfd($inst)
3852 unset blameinst
3853 notbusy blaming
3854 fconfigure $fd -blocking 1
3855 if {[catch {close $fd} err]} {
3856 error_popup [mc "Error running git blame: %s" $err]
3857 return 0
3858 }
3859
3860 set fname {}
3861 set line [split [lindex $blamestuff($inst) 0] " "]
3862 set id [lindex $line 0]
3863 set lnum [lindex $line 1]
3864 if {[string length $id] == 40 && [string is xdigit $id] &&
3865 [string is digit -strict $lnum]} {
3866 # look for "filename" line
3867 foreach l $blamestuff($inst) {
3868 if {[string match "filename *" $l]} {
3869 set fname [string range $l 9 end]
3870 break
3871 }
3872 }
3873 }
3874 if {$fname ne {}} {
3875 # all looks good, select it
3876 if {$id eq $nullid} {
3877 # blame uses all-zeroes to mean not committed,
3878 # which would mean a change in the index
3879 set id $nullid2
3880 }
3881 if {[commitinview $id $curview]} {
3882 selectline [rowofcommit $id] 1 [list $fname $lnum] 1
3883 } else {
3884 error_popup [mc "That line comes from commit %s, \
3885 which is not in this view" [shortids $id]]
3886 }
3887 } else {
3888 puts "oops couldn't parse git blame output"
3889 }
3890 return 0
3891}
3892
3893# delete $dir when we see eof on $f (presumably because the child has exited)
3894proc delete_at_eof {f dir} {
3895 while {[gets $f line] >= 0} {}
3896 if {[eof $f]} {
3897 if {[catch {close $f} err]} {
3898 error_popup "[mc "External diff viewer failed:"] $err"
3899 }
3900 file delete -force $dir
3901 return 0
3902 }
3903 return 1
3904}
3905
3906# Functions for adding and removing shell-type quoting
3907
3908proc shellquote {str} {
3909 if {![string match "*\['\"\\ \t]*" $str]} {
3910 return $str
3911 }
3912 if {![string match "*\['\"\\]*" $str]} {
3913 return "\"$str\""
3914 }
3915 if {![string match "*'*" $str]} {
3916 return "'$str'"
3917 }
3918 return "\"[string map {\" \\\" \\ \\\\} $str]\""
3919}
3920
3921proc shellarglist {l} {
3922 set str {}
3923 foreach a $l {
3924 if {$str ne {}} {
3925 append str " "
3926 }
3927 append str [shellquote $a]
3928 }
3929 return $str
3930}
3931
3932proc shelldequote {str} {
3933 set ret {}
3934 set used -1
3935 while {1} {
3936 incr used
3937 if {![regexp -start $used -indices "\['\"\\\\ \t]" $str first]} {
3938 append ret [string range $str $used end]
3939 set used [string length $str]
3940 break
3941 }
3942 set first [lindex $first 0]
3943 set ch [string index $str $first]
3944 if {$first > $used} {
3945 append ret [string range $str $used [expr {$first - 1}]]
3946 set used $first
3947 }
3948 if {$ch eq " " || $ch eq "\t"} break
3949 incr used
3950 if {$ch eq "'"} {
3951 set first [string first "'" $str $used]
3952 if {$first < 0} {
3953 error "unmatched single-quote"
3954 }
3955 append ret [string range $str $used [expr {$first - 1}]]
3956 set used $first
3957 continue
3958 }
3959 if {$ch eq "\\"} {
3960 if {$used >= [string length $str]} {
3961 error "trailing backslash"
3962 }
3963 append ret [string index $str $used]
3964 continue
3965 }
3966 # here ch == "\""
3967 while {1} {
3968 if {![regexp -start $used -indices "\[\"\\\\]" $str first]} {
3969 error "unmatched double-quote"
3970 }
3971 set first [lindex $first 0]
3972 set ch [string index $str $first]
3973 if {$first > $used} {
3974 append ret [string range $str $used [expr {$first - 1}]]
3975 set used $first
3976 }
3977 if {$ch eq "\""} break
3978 incr used
3979 append ret [string index $str $used]
3980 incr used
3981 }
3982 }
3983 return [list $used $ret]
3984}
3985
3986proc shellsplit {str} {
3987 set l {}
3988 while {1} {
3989 set str [string trimleft $str]
3990 if {$str eq {}} break
3991 set dq [shelldequote $str]
3992 set n [lindex $dq 0]
3993 set word [lindex $dq 1]
3994 set str [string range $str $n end]
3995 lappend l $word
3996 }
3997 return $l
3998}
3999
4000# Code to implement multiple views
4001
4002proc newview {ishighlight} {
4003 global nextviewnum newviewname newishighlight
4004 global revtreeargs viewargscmd newviewopts curview
4005
4006 set newishighlight $ishighlight
4007 set top .gitkview
4008 if {[winfo exists $top]} {
4009 raise $top
4010 return
4011 }
4012 decode_view_opts $nextviewnum $revtreeargs
4013 set newviewname($nextviewnum) "[mc "View"] $nextviewnum"
4014 set newviewopts($nextviewnum,perm) 0
4015 set newviewopts($nextviewnum,cmd) $viewargscmd($curview)
4016 vieweditor $top $nextviewnum [mc "Gitk view definition"]
4017}
4018
4019set known_view_options {
4020 {perm b . {} {mc "Remember this view"}}
4021 {reflabel l + {} {mc "References (space separated list):"}}
4022 {refs t15 .. {} {mc "Branches & tags:"}}
4023 {allrefs b *. "--all" {mc "All refs"}}
4024 {branches b . "--branches" {mc "All (local) branches"}}
4025 {tags b . "--tags" {mc "All tags"}}
4026 {remotes b . "--remotes" {mc "All remote-tracking branches"}}
4027 {commitlbl l + {} {mc "Commit Info (regular expressions):"}}
4028 {author t15 .. "--author=*" {mc "Author:"}}
4029 {committer t15 . "--committer=*" {mc "Committer:"}}
4030 {loginfo t15 .. "--grep=*" {mc "Commit Message:"}}
4031 {allmatch b .. "--all-match" {mc "Matches all Commit Info criteria"}}
4032 {changes_l l + {} {mc "Changes to Files:"}}
4033 {pickaxe_s r0 . {} {mc "Fixed String"}}
4034 {pickaxe_t r1 . "--pickaxe-regex" {mc "Regular Expression"}}
4035 {pickaxe t15 .. "-S*" {mc "Search string:"}}
4036 {datelabel l + {} {mc "Commit Dates (\"2 weeks ago\", \"2009-03-17 15:27:38\", \"March 17, 2009 15:27:38\"):"}}
4037 {since t15 .. {"--since=*" "--after=*"} {mc "Since:"}}
4038 {until t15 . {"--until=*" "--before=*"} {mc "Until:"}}
4039 {limit_lbl l + {} {mc "Limit and/or skip a number of revisions (positive integer):"}}
4040 {limit t10 *. "--max-count=*" {mc "Number to show:"}}
4041 {skip t10 . "--skip=*" {mc "Number to skip:"}}
4042 {misc_lbl l + {} {mc "Miscellaneous options:"}}
4043 {dorder b *. {"--date-order" "-d"} {mc "Strictly sort by date"}}
4044 {lright b . "--left-right" {mc "Mark branch sides"}}
4045 {first b . "--first-parent" {mc "Limit to first parent"}}
4046 {smplhst b . "--simplify-by-decoration" {mc "Simple history"}}
4047 {args t50 *. {} {mc "Additional arguments to git log:"}}
4048 {allpaths path + {} {mc "Enter files and directories to include, one per line:"}}
4049 {cmd t50= + {} {mc "Command to generate more commits to include:"}}
4050 }
4051
4052# Convert $newviewopts($n, ...) into args for git log.
4053proc encode_view_opts {n} {
4054 global known_view_options newviewopts
4055
4056 set rargs [list]
4057 foreach opt $known_view_options {
4058 set patterns [lindex $opt 3]
4059 if {$patterns eq {}} continue
4060 set pattern [lindex $patterns 0]
4061
4062 if {[lindex $opt 1] eq "b"} {
4063 set val $newviewopts($n,[lindex $opt 0])
4064 if {$val} {
4065 lappend rargs $pattern
4066 }
4067 } elseif {[regexp {^r(\d+)$} [lindex $opt 1] type value]} {
4068 regexp {^(.*_)} [lindex $opt 0] uselessvar button_id
4069 set val $newviewopts($n,$button_id)
4070 if {$val eq $value} {
4071 lappend rargs $pattern
4072 }
4073 } else {
4074 set val $newviewopts($n,[lindex $opt 0])
4075 set val [string trim $val]
4076 if {$val ne {}} {
4077 set pfix [string range $pattern 0 end-1]
4078 lappend rargs $pfix$val
4079 }
4080 }
4081 }
4082 set rargs [concat $rargs [shellsplit $newviewopts($n,refs)]]
4083 return [concat $rargs [shellsplit $newviewopts($n,args)]]
4084}
4085
4086# Fill $newviewopts($n, ...) based on args for git log.
4087proc decode_view_opts {n view_args} {
4088 global known_view_options newviewopts
4089
4090 foreach opt $known_view_options {
4091 set id [lindex $opt 0]
4092 if {[lindex $opt 1] eq "b"} {
4093 # Checkboxes
4094 set val 0
4095 } elseif {[regexp {^r(\d+)$} [lindex $opt 1]]} {
4096 # Radiobuttons
4097 regexp {^(.*_)} $id uselessvar id
4098 set val 0
4099 } else {
4100 # Text fields
4101 set val {}
4102 }
4103 set newviewopts($n,$id) $val
4104 }
4105 set oargs [list]
4106 set refargs [list]
4107 foreach arg $view_args {
4108 if {[regexp -- {^-([0-9]+)$} $arg arg cnt]
4109 && ![info exists found(limit)]} {
4110 set newviewopts($n,limit) $cnt
4111 set found(limit) 1
4112 continue
4113 }
4114 catch { unset val }
4115 foreach opt $known_view_options {
4116 set id [lindex $opt 0]
4117 if {[info exists found($id)]} continue
4118 foreach pattern [lindex $opt 3] {
4119 if {![string match $pattern $arg]} continue
4120 if {[lindex $opt 1] eq "b"} {
4121 # Check buttons
4122 set val 1
4123 } elseif {[regexp {^r(\d+)$} [lindex $opt 1] match num]} {
4124 # Radio buttons
4125 regexp {^(.*_)} $id uselessvar id
4126 set val $num
4127 } else {
4128 # Text input fields
4129 set size [string length $pattern]
4130 set val [string range $arg [expr {$size-1}] end]
4131 }
4132 set newviewopts($n,$id) $val
4133 set found($id) 1
4134 break
4135 }
4136 if {[info exists val]} break
4137 }
4138 if {[info exists val]} continue
4139 if {[regexp {^-} $arg]} {
4140 lappend oargs $arg
4141 } else {
4142 lappend refargs $arg
4143 }
4144 }
4145 set newviewopts($n,refs) [shellarglist $refargs]
4146 set newviewopts($n,args) [shellarglist $oargs]
4147}
4148
4149proc edit_or_newview {} {
4150 global curview
4151
4152 if {$curview > 0} {
4153 editview
4154 } else {
4155 newview 0
4156 }
4157}
4158
4159proc editview {} {
4160 global curview
4161 global viewname viewperm newviewname newviewopts
4162 global viewargs viewargscmd
4163
4164 set top .gitkvedit-$curview
4165 if {[winfo exists $top]} {
4166 raise $top
4167 return
4168 }
4169 decode_view_opts $curview $viewargs($curview)
4170 set newviewname($curview) $viewname($curview)
4171 set newviewopts($curview,perm) $viewperm($curview)
4172 set newviewopts($curview,cmd) $viewargscmd($curview)
4173 vieweditor $top $curview "[mc "Gitk: edit view"] $viewname($curview)"
4174}
4175
4176proc vieweditor {top n title} {
4177 global newviewname newviewopts viewfiles bgcolor
4178 global known_view_options NS
4179
4180 ttk_toplevel $top
4181 wm title $top [concat $title [mc "-- criteria for selecting revisions"]]
4182 make_transient $top .
4183
4184 # View name
4185 ${NS}::frame $top.nfr
4186 ${NS}::label $top.nl -text [mc "View Name"]
4187 ${NS}::entry $top.name -width 20 -textvariable newviewname($n)
4188 pack $top.nfr -in $top -fill x -pady 5 -padx 3
4189 pack $top.nl -in $top.nfr -side left -padx {0 5}
4190 pack $top.name -in $top.nfr -side left -padx {0 25}
4191
4192 # View options
4193 set cframe $top.nfr
4194 set cexpand 0
4195 set cnt 0
4196 foreach opt $known_view_options {
4197 set id [lindex $opt 0]
4198 set type [lindex $opt 1]
4199 set flags [lindex $opt 2]
4200 set title [eval [lindex $opt 4]]
4201 set lxpad 0
4202
4203 if {$flags eq "+" || $flags eq "*"} {
4204 set cframe $top.fr$cnt
4205 incr cnt
4206 ${NS}::frame $cframe
4207 pack $cframe -in $top -fill x -pady 3 -padx 3
4208 set cexpand [expr {$flags eq "*"}]
4209 } elseif {$flags eq ".." || $flags eq "*."} {
4210 set cframe $top.fr$cnt
4211 incr cnt
4212 ${NS}::frame $cframe
4213 pack $cframe -in $top -fill x -pady 3 -padx [list 15 3]
4214 set cexpand [expr {$flags eq "*."}]
4215 } else {
4216 set lxpad 5
4217 }
4218
4219 if {$type eq "l"} {
4220 ${NS}::label $cframe.l_$id -text $title
4221 pack $cframe.l_$id -in $cframe -side left -pady [list 3 0] -anchor w
4222 } elseif {$type eq "b"} {
4223 ${NS}::checkbutton $cframe.c_$id -text $title -variable newviewopts($n,$id)
4224 pack $cframe.c_$id -in $cframe -side left \
4225 -padx [list $lxpad 0] -expand $cexpand -anchor w
4226 } elseif {[regexp {^r(\d+)$} $type type sz]} {
4227 regexp {^(.*_)} $id uselessvar button_id
4228 ${NS}::radiobutton $cframe.c_$id -text $title -variable newviewopts($n,$button_id) -value $sz
4229 pack $cframe.c_$id -in $cframe -side left \
4230 -padx [list $lxpad 0] -expand $cexpand -anchor w
4231 } elseif {[regexp {^t(\d+)$} $type type sz]} {
4232 ${NS}::label $cframe.l_$id -text $title
4233 ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4234 -textvariable newviewopts($n,$id)
4235 pack $cframe.l_$id -in $cframe -side left -padx [list $lxpad 0]
4236 pack $cframe.e_$id -in $cframe -side left -expand 1 -fill x
4237 } elseif {[regexp {^t(\d+)=$} $type type sz]} {
4238 ${NS}::label $cframe.l_$id -text $title
4239 ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4240 -textvariable newviewopts($n,$id)
4241 pack $cframe.l_$id -in $cframe -side top -pady [list 3 0] -anchor w
4242 pack $cframe.e_$id -in $cframe -side top -fill x
4243 } elseif {$type eq "path"} {
4244 ${NS}::label $top.l -text $title
4245 pack $top.l -in $top -side top -pady [list 3 0] -anchor w -padx 3
4246 text $top.t -width 40 -height 5 -background $bgcolor
4247 if {[info exists viewfiles($n)]} {
4248 foreach f $viewfiles($n) {
4249 $top.t insert end $f
4250 $top.t insert end "\n"
4251 }
4252 $top.t delete {end - 1c} end
4253 $top.t mark set insert 0.0
4254 }
4255 pack $top.t -in $top -side top -pady [list 0 5] -fill both -expand 1 -padx 3
4256 }
4257 }
4258
4259 ${NS}::frame $top.buts
4260 ${NS}::button $top.buts.ok -text [mc "OK"] -command [list newviewok $top $n]
4261 ${NS}::button $top.buts.apply -text [mc "Apply (F5)"] -command [list newviewok $top $n 1]
4262 ${NS}::button $top.buts.can -text [mc "Cancel"] -command [list destroy $top]
4263 bind $top <Control-Return> [list newviewok $top $n]
4264 bind $top <F5> [list newviewok $top $n 1]
4265 bind $top <Escape> [list destroy $top]
4266 grid $top.buts.ok $top.buts.apply $top.buts.can
4267 grid columnconfigure $top.buts 0 -weight 1 -uniform a
4268 grid columnconfigure $top.buts 1 -weight 1 -uniform a
4269 grid columnconfigure $top.buts 2 -weight 1 -uniform a
4270 pack $top.buts -in $top -side top -fill x
4271 focus $top.t
4272}
4273
4274proc doviewmenu {m first cmd op argv} {
4275 set nmenu [$m index end]
4276 for {set i $first} {$i <= $nmenu} {incr i} {
4277 if {[$m entrycget $i -command] eq $cmd} {
4278 eval $m $op $i $argv
4279 break
4280 }
4281 }
4282}
4283
4284proc allviewmenus {n op args} {
4285 # global viewhlmenu
4286
4287 doviewmenu .bar.view 5 [list showview $n] $op $args
4288 # doviewmenu $viewhlmenu 1 [list addvhighlight $n] $op $args
4289}
4290
4291proc newviewok {top n {apply 0}} {
4292 global nextviewnum newviewperm newviewname newishighlight
4293 global viewname viewfiles viewperm selectedview curview
4294 global viewargs viewargscmd newviewopts viewhlmenu
4295
4296 if {[catch {
4297 set newargs [encode_view_opts $n]
4298 } err]} {
4299 error_popup "[mc "Error in commit selection arguments:"] $err" $top
4300 return
4301 }
4302 set files {}
4303 foreach f [split [$top.t get 0.0 end] "\n"] {
4304 set ft [string trim $f]
4305 if {$ft ne {}} {
4306 lappend files $ft
4307 }
4308 }
4309 if {![info exists viewfiles($n)]} {
4310 # creating a new view
4311 incr nextviewnum
4312 set viewname($n) $newviewname($n)
4313 set viewperm($n) $newviewopts($n,perm)
4314 set viewfiles($n) $files
4315 set viewargs($n) $newargs
4316 set viewargscmd($n) $newviewopts($n,cmd)
4317 addviewmenu $n
4318 if {!$newishighlight} {
4319 run showview $n
4320 } else {
4321 run addvhighlight $n
4322 }
4323 } else {
4324 # editing an existing view
4325 set viewperm($n) $newviewopts($n,perm)
4326 if {$newviewname($n) ne $viewname($n)} {
4327 set viewname($n) $newviewname($n)
4328 doviewmenu .bar.view 5 [list showview $n] \
4329 entryconf [list -label $viewname($n)]
4330 # doviewmenu $viewhlmenu 1 [list addvhighlight $n] \
4331 # entryconf [list -label $viewname($n) -value $viewname($n)]
4332 }
4333 if {$files ne $viewfiles($n) || $newargs ne $viewargs($n) || \
4334 $newviewopts($n,cmd) ne $viewargscmd($n)} {
4335 set viewfiles($n) $files
4336 set viewargs($n) $newargs
4337 set viewargscmd($n) $newviewopts($n,cmd)
4338 if {$curview == $n} {
4339 run reloadcommits
4340 }
4341 }
4342 }
4343 if {$apply} return
4344 catch {destroy $top}
4345}
4346
4347proc delview {} {
4348 global curview viewperm hlview selectedhlview
4349
4350 if {$curview == 0} return
4351 if {[info exists hlview] && $hlview == $curview} {
4352 set selectedhlview [mc "None"]
4353 unset hlview
4354 }
4355 allviewmenus $curview delete
4356 set viewperm($curview) 0
4357 showview 0
4358}
4359
4360proc addviewmenu {n} {
4361 global viewname viewhlmenu
4362
4363 .bar.view add radiobutton -label $viewname($n) \
4364 -command [list showview $n] -variable selectedview -value $n
4365 #$viewhlmenu add radiobutton -label $viewname($n) \
4366 # -command [list addvhighlight $n] -variable selectedhlview
4367}
4368
4369proc showview {n} {
4370 global curview cached_commitrow ordertok
4371 global displayorder parentlist rowidlist rowisopt rowfinal
4372 global colormap rowtextx nextcolor canvxmax
4373 global numcommits viewcomplete
4374 global selectedline currentid canv canvy0
4375 global treediffs
4376 global pending_select mainheadid
4377 global commitidx
4378 global selectedview
4379 global hlview selectedhlview commitinterest
4380
4381 if {$n == $curview} return
4382 set selid {}
4383 set ymax [lindex [$canv cget -scrollregion] 3]
4384 set span [$canv yview]
4385 set ytop [expr {[lindex $span 0] * $ymax}]
4386 set ybot [expr {[lindex $span 1] * $ymax}]
4387 set yscreen [expr {($ybot - $ytop) / 2}]
4388 if {$selectedline ne {}} {
4389 set selid $currentid
4390 set y [yc $selectedline]
4391 if {$ytop < $y && $y < $ybot} {
4392 set yscreen [expr {$y - $ytop}]
4393 }
4394 } elseif {[info exists pending_select]} {
4395 set selid $pending_select
4396 unset pending_select
4397 }
4398 unselectline
4399 normalline
4400 catch {unset treediffs}
4401 clear_display
4402 if {[info exists hlview] && $hlview == $n} {
4403 unset hlview
4404 set selectedhlview [mc "None"]
4405 }
4406 catch {unset commitinterest}
4407 catch {unset cached_commitrow}
4408 catch {unset ordertok}
4409
4410 set curview $n
4411 set selectedview $n
4412 .bar.view entryconf [mca "Edit view..."] -state [expr {$n == 0? "disabled": "normal"}]
4413 .bar.view entryconf [mca "Delete view"] -state [expr {$n == 0? "disabled": "normal"}]
4414
4415 run refill_reflist
4416 if {![info exists viewcomplete($n)]} {
4417 getcommits $selid
4418 return
4419 }
4420
4421 set displayorder {}
4422 set parentlist {}
4423 set rowidlist {}
4424 set rowisopt {}
4425 set rowfinal {}
4426 set numcommits $commitidx($n)
4427
4428 catch {unset colormap}
4429 catch {unset rowtextx}
4430 set nextcolor 0
4431 set canvxmax [$canv cget -width]
4432 set curview $n
4433 set row 0
4434 setcanvscroll
4435 set yf 0
4436 set row {}
4437 if {$selid ne {} && [commitinview $selid $n]} {
4438 set row [rowofcommit $selid]
4439 # try to get the selected row in the same position on the screen
4440 set ymax [lindex [$canv cget -scrollregion] 3]
4441 set ytop [expr {[yc $row] - $yscreen}]
4442 if {$ytop < 0} {
4443 set ytop 0
4444 }
4445 set yf [expr {$ytop * 1.0 / $ymax}]
4446 }
4447 allcanvs yview moveto $yf
4448 drawvisible
4449 if {$row ne {}} {
4450 selectline $row 0
4451 } elseif {!$viewcomplete($n)} {
4452 reset_pending_select $selid
4453 } else {
4454 reset_pending_select {}
4455
4456 if {[commitinview $pending_select $curview]} {
4457 selectline [rowofcommit $pending_select] 1
4458 } else {
4459 set row [first_real_row]
4460 if {$row < $numcommits} {
4461 selectline $row 0
4462 }
4463 }
4464 }
4465 if {!$viewcomplete($n)} {
4466 if {$numcommits == 0} {
4467 show_status [mc "Reading commits..."]
4468 }
4469 } elseif {$numcommits == 0} {
4470 show_status [mc "No commits selected"]
4471 }
4472}
4473
4474# Stuff relating to the highlighting facility
4475
4476proc ishighlighted {id} {
4477 global vhighlights fhighlights nhighlights rhighlights
4478
4479 if {[info exists nhighlights($id)] && $nhighlights($id) > 0} {
4480 return $nhighlights($id)
4481 }
4482 if {[info exists vhighlights($id)] && $vhighlights($id) > 0} {
4483 return $vhighlights($id)
4484 }
4485 if {[info exists fhighlights($id)] && $fhighlights($id) > 0} {
4486 return $fhighlights($id)
4487 }
4488 if {[info exists rhighlights($id)] && $rhighlights($id) > 0} {
4489 return $rhighlights($id)
4490 }
4491 return 0
4492}
4493
4494proc bolden {id font} {
4495 global canv linehtag currentid boldids need_redisplay markedid
4496
4497 # need_redisplay = 1 means the display is stale and about to be redrawn
4498 if {$need_redisplay} return
4499 lappend boldids $id
4500 $canv itemconf $linehtag($id) -font $font
4501 if {[info exists currentid] && $id eq $currentid} {
4502 $canv delete secsel
4503 set t [eval $canv create rect [$canv bbox $linehtag($id)] \
4504 -outline {{}} -tags secsel \
4505 -fill [$canv cget -selectbackground]]
4506 $canv lower $t
4507 }
4508 if {[info exists markedid] && $id eq $markedid} {
4509 make_idmark $id
4510 }
4511}
4512
4513proc bolden_name {id font} {
4514 global canv2 linentag currentid boldnameids need_redisplay
4515
4516 if {$need_redisplay} return
4517 lappend boldnameids $id
4518 $canv2 itemconf $linentag($id) -font $font
4519 if {[info exists currentid] && $id eq $currentid} {
4520 $canv2 delete secsel
4521 set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] \
4522 -outline {{}} -tags secsel \
4523 -fill [$canv2 cget -selectbackground]]
4524 $canv2 lower $t
4525 }
4526}
4527
4528proc unbolden {} {
4529 global boldids
4530
4531 set stillbold {}
4532 foreach id $boldids {
4533 if {![ishighlighted $id]} {
4534 bolden $id mainfont
4535 } else {
4536 lappend stillbold $id
4537 }
4538 }
4539 set boldids $stillbold
4540}
4541
4542proc addvhighlight {n} {
4543 global hlview viewcomplete curview vhl_done commitidx
4544
4545 if {[info exists hlview]} {
4546 delvhighlight
4547 }
4548 set hlview $n
4549 if {$n != $curview && ![info exists viewcomplete($n)]} {
4550 start_rev_list $n
4551 }
4552 set vhl_done $commitidx($hlview)
4553 if {$vhl_done > 0} {
4554 drawvisible
4555 }
4556}
4557
4558proc delvhighlight {} {
4559 global hlview vhighlights
4560
4561 if {![info exists hlview]} return
4562 unset hlview
4563 catch {unset vhighlights}
4564 unbolden
4565}
4566
4567proc vhighlightmore {} {
4568 global hlview vhl_done commitidx vhighlights curview
4569
4570 set max $commitidx($hlview)
4571 set vr [visiblerows]
4572 set r0 [lindex $vr 0]
4573 set r1 [lindex $vr 1]
4574 for {set i $vhl_done} {$i < $max} {incr i} {
4575 set id [commitonrow $i $hlview]
4576 if {[commitinview $id $curview]} {
4577 set row [rowofcommit $id]
4578 if {$r0 <= $row && $row <= $r1} {
4579 if {![highlighted $row]} {
4580 bolden $id mainfontbold
4581 }
4582 set vhighlights($id) 1
4583 }
4584 }
4585 }
4586 set vhl_done $max
4587 return 0
4588}
4589
4590proc askvhighlight {row id} {
4591 global hlview vhighlights iddrawn
4592
4593 if {[commitinview $id $hlview]} {
4594 if {[info exists iddrawn($id)] && ![ishighlighted $id]} {
4595 bolden $id mainfontbold
4596 }
4597 set vhighlights($id) 1
4598 } else {
4599 set vhighlights($id) 0
4600 }
4601}
4602
4603proc hfiles_change {} {
4604 global highlight_files filehighlight fhighlights fh_serial
4605 global highlight_paths
4606
4607 if {[info exists filehighlight]} {
4608 # delete previous highlights
4609 catch {close $filehighlight}
4610 unset filehighlight
4611 catch {unset fhighlights}
4612 unbolden
4613 unhighlight_filelist
4614 }
4615 set highlight_paths {}
4616 after cancel do_file_hl $fh_serial
4617 incr fh_serial
4618 if {$highlight_files ne {}} {
4619 after 300 do_file_hl $fh_serial
4620 }
4621}
4622
4623proc gdttype_change {name ix op} {
4624 global gdttype highlight_files findstring findpattern
4625
4626 stopfinding
4627 if {$findstring ne {}} {
4628 if {$gdttype eq [mc "containing:"]} {
4629 if {$highlight_files ne {}} {
4630 set highlight_files {}
4631 hfiles_change
4632 }
4633 findcom_change
4634 } else {
4635 if {$findpattern ne {}} {
4636 set findpattern {}
4637 findcom_change
4638 }
4639 set highlight_files $findstring
4640 hfiles_change
4641 }
4642 drawvisible
4643 }
4644 # enable/disable findtype/findloc menus too
4645}
4646
4647proc find_change {name ix op} {
4648 global gdttype findstring highlight_files
4649
4650 stopfinding
4651 if {$gdttype eq [mc "containing:"]} {
4652 findcom_change
4653 } else {
4654 if {$highlight_files ne $findstring} {
4655 set highlight_files $findstring
4656 hfiles_change
4657 }
4658 }
4659 drawvisible
4660}
4661
4662proc findcom_change args {
4663 global nhighlights boldnameids
4664 global findpattern findtype findstring gdttype
4665
4666 stopfinding
4667 # delete previous highlights, if any
4668 foreach id $boldnameids {
4669 bolden_name $id mainfont
4670 }
4671 set boldnameids {}
4672 catch {unset nhighlights}
4673 unbolden
4674 unmarkmatches
4675 if {$gdttype ne [mc "containing:"] || $findstring eq {}} {
4676 set findpattern {}
4677 } elseif {$findtype eq [mc "Regexp"]} {
4678 set findpattern $findstring
4679 } else {
4680 set e [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} \
4681 $findstring]
4682 set findpattern "*$e*"
4683 }
4684}
4685
4686proc makepatterns {l} {
4687 set ret {}
4688 foreach e $l {
4689 set ee [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} $e]
4690 if {[string index $ee end] eq "/"} {
4691 lappend ret "$ee*"
4692 } else {
4693 lappend ret $ee
4694 lappend ret "$ee/*"
4695 }
4696 }
4697 return $ret
4698}
4699
4700proc do_file_hl {serial} {
4701 global highlight_files filehighlight highlight_paths gdttype fhl_list
4702 global cdup findtype
4703
4704 if {$gdttype eq [mc "touching paths:"]} {
4705 # If "exact" match then convert backslashes to forward slashes.
4706 # Most useful to support Windows-flavoured file paths.
4707 if {$findtype eq [mc "Exact"]} {
4708 set highlight_files [string map {"\\" "/"} $highlight_files]
4709 }
4710 if {[catch {set paths [shellsplit $highlight_files]}]} return
4711 set highlight_paths [makepatterns $paths]
4712 highlight_filelist
4713 set relative_paths {}
4714 foreach path $paths {
4715 lappend relative_paths [file join $cdup $path]
4716 }
4717 set gdtargs [concat -- $relative_paths]
4718 } elseif {$gdttype eq [mc "adding/removing string:"]} {
4719 set gdtargs [list "-S$highlight_files"]
4720 } elseif {$gdttype eq [mc "changing lines matching:"]} {
4721 set gdtargs [list "-G$highlight_files"]
4722 } else {
4723 # must be "containing:", i.e. we're searching commit info
4724 return
4725 }
4726 set cmd [concat | git diff-tree -r -s --stdin $gdtargs]
4727 set filehighlight [open $cmd r+]
4728 fconfigure $filehighlight -blocking 0
4729 filerun $filehighlight readfhighlight
4730 set fhl_list {}
4731 drawvisible
4732 flushhighlights
4733}
4734
4735proc flushhighlights {} {
4736 global filehighlight fhl_list
4737
4738 if {[info exists filehighlight]} {
4739 lappend fhl_list {}
4740 puts $filehighlight ""
4741 flush $filehighlight
4742 }
4743}
4744
4745proc askfilehighlight {row id} {
4746 global filehighlight fhighlights fhl_list
4747
4748 lappend fhl_list $id
4749 set fhighlights($id) -1
4750 puts $filehighlight $id
4751}
4752
4753proc readfhighlight {} {
4754 global filehighlight fhighlights curview iddrawn
4755 global fhl_list find_dirn
4756
4757 if {![info exists filehighlight]} {
4758 return 0
4759 }
4760 set nr 0
4761 while {[incr nr] <= 100 && [gets $filehighlight line] >= 0} {
4762 set line [string trim $line]
4763 set i [lsearch -exact $fhl_list $line]
4764 if {$i < 0} continue
4765 for {set j 0} {$j < $i} {incr j} {
4766 set id [lindex $fhl_list $j]
4767 set fhighlights($id) 0
4768 }
4769 set fhl_list [lrange $fhl_list [expr {$i+1}] end]
4770 if {$line eq {}} continue
4771 if {![commitinview $line $curview]} continue
4772 if {[info exists iddrawn($line)] && ![ishighlighted $line]} {
4773 bolden $line mainfontbold
4774 }
4775 set fhighlights($line) 1
4776 }
4777 if {[eof $filehighlight]} {
4778 # strange...
4779 puts "oops, git diff-tree died"
4780 catch {close $filehighlight}
4781 unset filehighlight
4782 return 0
4783 }
4784 if {[info exists find_dirn]} {
4785 run findmore
4786 }
4787 return 1
4788}
4789
4790proc doesmatch {f} {
4791 global findtype findpattern
4792
4793 if {$findtype eq [mc "Regexp"]} {
4794 return [regexp $findpattern $f]
4795 } elseif {$findtype eq [mc "IgnCase"]} {
4796 return [string match -nocase $findpattern $f]
4797 } else {
4798 return [string match $findpattern $f]
4799 }
4800}
4801
4802proc askfindhighlight {row id} {
4803 global nhighlights commitinfo iddrawn
4804 global findloc
4805 global markingmatches
4806
4807 if {![info exists commitinfo($id)]} {
4808 getcommit $id
4809 }
4810 set info $commitinfo($id)
4811 set isbold 0
4812 set fldtypes [list [mc Headline] [mc Author] "" [mc Committer] "" [mc Comments]]
4813 foreach f $info ty $fldtypes {
4814 if {$ty eq ""} continue
4815 if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
4816 [doesmatch $f]} {
4817 if {$ty eq [mc "Author"]} {
4818 set isbold 2
4819 break
4820 }
4821 set isbold 1
4822 }
4823 }
4824 if {$isbold && [info exists iddrawn($id)]} {
4825 if {![ishighlighted $id]} {
4826 bolden $id mainfontbold
4827 if {$isbold > 1} {
4828 bolden_name $id mainfontbold
4829 }
4830 }
4831 if {$markingmatches} {
4832 markrowmatches $row $id
4833 }
4834 }
4835 set nhighlights($id) $isbold
4836}
4837
4838proc markrowmatches {row id} {
4839 global canv canv2 linehtag linentag commitinfo findloc
4840
4841 set headline [lindex $commitinfo($id) 0]
4842 set author [lindex $commitinfo($id) 1]
4843 $canv delete match$row
4844 $canv2 delete match$row
4845 if {$findloc eq [mc "All fields"] || $findloc eq [mc "Headline"]} {
4846 set m [findmatches $headline]
4847 if {$m ne {}} {
4848 markmatches $canv $row $headline $linehtag($id) $m \
4849 [$canv itemcget $linehtag($id) -font] $row
4850 }
4851 }
4852 if {$findloc eq [mc "All fields"] || $findloc eq [mc "Author"]} {
4853 set m [findmatches $author]
4854 if {$m ne {}} {
4855 markmatches $canv2 $row $author $linentag($id) $m \
4856 [$canv2 itemcget $linentag($id) -font] $row
4857 }
4858 }
4859}
4860
4861proc vrel_change {name ix op} {
4862 global highlight_related
4863
4864 rhighlight_none
4865 if {$highlight_related ne [mc "None"]} {
4866 run drawvisible
4867 }
4868}
4869
4870# prepare for testing whether commits are descendents or ancestors of a
4871proc rhighlight_sel {a} {
4872 global descendent desc_todo ancestor anc_todo
4873 global highlight_related
4874
4875 catch {unset descendent}
4876 set desc_todo [list $a]
4877 catch {unset ancestor}
4878 set anc_todo [list $a]
4879 if {$highlight_related ne [mc "None"]} {
4880 rhighlight_none
4881 run drawvisible
4882 }
4883}
4884
4885proc rhighlight_none {} {
4886 global rhighlights
4887
4888 catch {unset rhighlights}
4889 unbolden
4890}
4891
4892proc is_descendent {a} {
4893 global curview children descendent desc_todo
4894
4895 set v $curview
4896 set la [rowofcommit $a]
4897 set todo $desc_todo
4898 set leftover {}
4899 set done 0
4900 for {set i 0} {$i < [llength $todo]} {incr i} {
4901 set do [lindex $todo $i]
4902 if {[rowofcommit $do] < $la} {
4903 lappend leftover $do
4904 continue
4905 }
4906 foreach nk $children($v,$do) {
4907 if {![info exists descendent($nk)]} {
4908 set descendent($nk) 1
4909 lappend todo $nk
4910 if {$nk eq $a} {
4911 set done 1
4912 }
4913 }
4914 }
4915 if {$done} {
4916 set desc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4917 return
4918 }
4919 }
4920 set descendent($a) 0
4921 set desc_todo $leftover
4922}
4923
4924proc is_ancestor {a} {
4925 global curview parents ancestor anc_todo
4926
4927 set v $curview
4928 set la [rowofcommit $a]
4929 set todo $anc_todo
4930 set leftover {}
4931 set done 0
4932 for {set i 0} {$i < [llength $todo]} {incr i} {
4933 set do [lindex $todo $i]
4934 if {![commitinview $do $v] || [rowofcommit $do] > $la} {
4935 lappend leftover $do
4936 continue
4937 }
4938 foreach np $parents($v,$do) {
4939 if {![info exists ancestor($np)]} {
4940 set ancestor($np) 1
4941 lappend todo $np
4942 if {$np eq $a} {
4943 set done 1
4944 }
4945 }
4946 }
4947 if {$done} {
4948 set anc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4949 return
4950 }
4951 }
4952 set ancestor($a) 0
4953 set anc_todo $leftover
4954}
4955
4956proc askrelhighlight {row id} {
4957 global descendent highlight_related iddrawn rhighlights
4958 global selectedline ancestor
4959
4960 if {$selectedline eq {}} return
4961 set isbold 0
4962 if {$highlight_related eq [mc "Descendant"] ||
4963 $highlight_related eq [mc "Not descendant"]} {
4964 if {![info exists descendent($id)]} {
4965 is_descendent $id
4966 }
4967 if {$descendent($id) == ($highlight_related eq [mc "Descendant"])} {
4968 set isbold 1
4969 }
4970 } elseif {$highlight_related eq [mc "Ancestor"] ||
4971 $highlight_related eq [mc "Not ancestor"]} {
4972 if {![info exists ancestor($id)]} {
4973 is_ancestor $id
4974 }
4975 if {$ancestor($id) == ($highlight_related eq [mc "Ancestor"])} {
4976 set isbold 1
4977 }
4978 }
4979 if {[info exists iddrawn($id)]} {
4980 if {$isbold && ![ishighlighted $id]} {
4981 bolden $id mainfontbold
4982 }
4983 }
4984 set rhighlights($id) $isbold
4985}
4986
4987# Graph layout functions
4988
4989proc shortids {ids} {
4990 set res {}
4991 foreach id $ids {
4992 if {[llength $id] > 1} {
4993 lappend res [shortids $id]
4994 } elseif {[regexp {^[0-9a-f]{40}$} $id]} {
4995 lappend res [string range $id 0 7]
4996 } else {
4997 lappend res $id
4998 }
4999 }
5000 return $res
5001}
5002
5003proc ntimes {n o} {
5004 set ret {}
5005 set o [list $o]
5006 for {set mask 1} {$mask <= $n} {incr mask $mask} {
5007 if {($n & $mask) != 0} {
5008 set ret [concat $ret $o]
5009 }
5010 set o [concat $o $o]
5011 }
5012 return $ret
5013}
5014
5015proc ordertoken {id} {
5016 global ordertok curview varcid varcstart varctok curview parents children
5017 global nullid nullid2
5018
5019 if {[info exists ordertok($id)]} {
5020 return $ordertok($id)
5021 }
5022 set origid $id
5023 set todo {}
5024 while {1} {
5025 if {[info exists varcid($curview,$id)]} {
5026 set a $varcid($curview,$id)
5027 set p [lindex $varcstart($curview) $a]
5028 } else {
5029 set p [lindex $children($curview,$id) 0]
5030 }
5031 if {[info exists ordertok($p)]} {
5032 set tok $ordertok($p)
5033 break
5034 }
5035 set id [first_real_child $curview,$p]
5036 if {$id eq {}} {
5037 # it's a root
5038 set tok [lindex $varctok($curview) $varcid($curview,$p)]
5039 break
5040 }
5041 if {[llength $parents($curview,$id)] == 1} {
5042 lappend todo [list $p {}]
5043 } else {
5044 set j [lsearch -exact $parents($curview,$id) $p]
5045 if {$j < 0} {
5046 puts "oops didn't find [shortids $p] in parents of [shortids $id]"
5047 }
5048 lappend todo [list $p [strrep $j]]
5049 }
5050 }
5051 for {set i [llength $todo]} {[incr i -1] >= 0} {} {
5052 set p [lindex $todo $i 0]
5053 append tok [lindex $todo $i 1]
5054 set ordertok($p) $tok
5055 }
5056 set ordertok($origid) $tok
5057 return $tok
5058}
5059
5060# Work out where id should go in idlist so that order-token
5061# values increase from left to right
5062proc idcol {idlist id {i 0}} {
5063 set t [ordertoken $id]
5064 if {$i < 0} {
5065 set i 0
5066 }
5067 if {$i >= [llength $idlist] || $t < [ordertoken [lindex $idlist $i]]} {
5068 if {$i > [llength $idlist]} {
5069 set i [llength $idlist]
5070 }
5071 while {[incr i -1] >= 0 && $t < [ordertoken [lindex $idlist $i]]} {}
5072 incr i
5073 } else {
5074 if {$t > [ordertoken [lindex $idlist $i]]} {
5075 while {[incr i] < [llength $idlist] &&
5076 $t >= [ordertoken [lindex $idlist $i]]} {}
5077 }
5078 }
5079 return $i
5080}
5081
5082proc initlayout {} {
5083 global rowidlist rowisopt rowfinal displayorder parentlist
5084 global numcommits canvxmax canv
5085 global nextcolor
5086 global colormap rowtextx
5087
5088 set numcommits 0
5089 set displayorder {}
5090 set parentlist {}
5091 set nextcolor 0
5092 set rowidlist {}
5093 set rowisopt {}
5094 set rowfinal {}
5095 set canvxmax [$canv cget -width]
5096 catch {unset colormap}
5097 catch {unset rowtextx}
5098 setcanvscroll
5099}
5100
5101proc setcanvscroll {} {
5102 global canv canv2 canv3 numcommits linespc canvxmax canvy0
5103 global lastscrollset lastscrollrows
5104
5105 set ymax [expr {$canvy0 + ($numcommits - 0.5) * $linespc + 2}]
5106 $canv conf -scrollregion [list 0 0 $canvxmax $ymax]
5107 $canv2 conf -scrollregion [list 0 0 0 $ymax]
5108 $canv3 conf -scrollregion [list 0 0 0 $ymax]
5109 set lastscrollset [clock clicks -milliseconds]
5110 set lastscrollrows $numcommits
5111}
5112
5113proc visiblerows {} {
5114 global canv numcommits linespc
5115
5116 set ymax [lindex [$canv cget -scrollregion] 3]
5117 if {$ymax eq {} || $ymax == 0} return
5118 set f [$canv yview]
5119 set y0 [expr {int([lindex $f 0] * $ymax)}]
5120 set r0 [expr {int(($y0 - 3) / $linespc) - 1}]
5121 if {$r0 < 0} {
5122 set r0 0
5123 }
5124 set y1 [expr {int([lindex $f 1] * $ymax)}]
5125 set r1 [expr {int(($y1 - 3) / $linespc) + 1}]
5126 if {$r1 >= $numcommits} {
5127 set r1 [expr {$numcommits - 1}]
5128 }
5129 return [list $r0 $r1]
5130}
5131
5132proc layoutmore {} {
5133 global commitidx viewcomplete curview
5134 global numcommits pending_select curview
5135 global lastscrollset lastscrollrows
5136
5137 if {$lastscrollrows < 100 || $viewcomplete($curview) ||
5138 [clock clicks -milliseconds] - $lastscrollset > 500} {
5139 setcanvscroll
5140 }
5141 if {[info exists pending_select] &&
5142 [commitinview $pending_select $curview]} {
5143 update
5144 selectline [rowofcommit $pending_select] 1
5145 }
5146 drawvisible
5147}
5148
5149# With path limiting, we mightn't get the actual HEAD commit,
5150# so ask git rev-list what is the first ancestor of HEAD that
5151# touches a file in the path limit.
5152proc get_viewmainhead {view} {
5153 global viewmainheadid vfilelimit viewinstances mainheadid
5154
5155 catch {
5156 set rfd [open [concat | git rev-list -1 $mainheadid \
5157 -- $vfilelimit($view)] r]
5158 set j [reg_instance $rfd]
5159 lappend viewinstances($view) $j
5160 fconfigure $rfd -blocking 0
5161 filerun $rfd [list getviewhead $rfd $j $view]
5162 set viewmainheadid($curview) {}
5163 }
5164}
5165
5166# git rev-list should give us just 1 line to use as viewmainheadid($view)
5167proc getviewhead {fd inst view} {
5168 global viewmainheadid commfd curview viewinstances showlocalchanges
5169
5170 set id {}
5171 if {[gets $fd line] < 0} {
5172 if {![eof $fd]} {
5173 return 1
5174 }
5175 } elseif {[string length $line] == 40 && [string is xdigit $line]} {
5176 set id $line
5177 }
5178 set viewmainheadid($view) $id
5179 close $fd
5180 unset commfd($inst)
5181 set i [lsearch -exact $viewinstances($view) $inst]
5182 if {$i >= 0} {
5183 set viewinstances($view) [lreplace $viewinstances($view) $i $i]
5184 }
5185 if {$showlocalchanges && $id ne {} && $view == $curview} {
5186 doshowlocalchanges
5187 }
5188 return 0
5189}
5190
5191proc doshowlocalchanges {} {
5192 global curview viewmainheadid
5193
5194 if {$viewmainheadid($curview) eq {}} return
5195 if {[commitinview $viewmainheadid($curview) $curview]} {
5196 dodiffindex
5197 } else {
5198 interestedin $viewmainheadid($curview) dodiffindex
5199 }
5200}
5201
5202proc dohidelocalchanges {} {
5203 global nullid nullid2 lserial curview
5204
5205 if {[commitinview $nullid $curview]} {
5206 removefakerow $nullid
5207 }
5208 if {[commitinview $nullid2 $curview]} {
5209 removefakerow $nullid2
5210 }
5211 incr lserial
5212}
5213
5214# spawn off a process to do git diff-index --cached HEAD
5215proc dodiffindex {} {
5216 global lserial showlocalchanges vfilelimit curview
5217 global hasworktree git_version
5218
5219 if {!$showlocalchanges || !$hasworktree} return
5220 incr lserial
5221 if {[package vcompare $git_version "1.7.2"] >= 0} {
5222 set cmd "|git diff-index --cached --ignore-submodules=dirty HEAD"
5223 } else {
5224 set cmd "|git diff-index --cached HEAD"
5225 }
5226 if {$vfilelimit($curview) ne {}} {
5227 set cmd [concat $cmd -- $vfilelimit($curview)]
5228 }
5229 set fd [open $cmd r]
5230 fconfigure $fd -blocking 0
5231 set i [reg_instance $fd]
5232 filerun $fd [list readdiffindex $fd $lserial $i]
5233}
5234
5235proc readdiffindex {fd serial inst} {
5236 global viewmainheadid nullid nullid2 curview commitinfo commitdata lserial
5237 global vfilelimit
5238
5239 set isdiff 1
5240 if {[gets $fd line] < 0} {
5241 if {![eof $fd]} {
5242 return 1
5243 }
5244 set isdiff 0
5245 }
5246 # we only need to see one line and we don't really care what it says...
5247 stop_instance $inst
5248
5249 if {$serial != $lserial} {
5250 return 0
5251 }
5252
5253 # now see if there are any local changes not checked in to the index
5254 set cmd "|git diff-files"
5255 if {$vfilelimit($curview) ne {}} {
5256 set cmd [concat $cmd -- $vfilelimit($curview)]
5257 }
5258 set fd [open $cmd r]
5259 fconfigure $fd -blocking 0
5260 set i [reg_instance $fd]
5261 filerun $fd [list readdifffiles $fd $serial $i]
5262
5263 if {$isdiff && ![commitinview $nullid2 $curview]} {
5264 # add the line for the changes in the index to the graph
5265 set hl [mc "Local changes checked in to index but not committed"]
5266 set commitinfo($nullid2) [list $hl {} {} {} {} " $hl\n"]
5267 set commitdata($nullid2) "\n $hl\n"
5268 if {[commitinview $nullid $curview]} {
5269 removefakerow $nullid
5270 }
5271 insertfakerow $nullid2 $viewmainheadid($curview)
5272 } elseif {!$isdiff && [commitinview $nullid2 $curview]} {
5273 if {[commitinview $nullid $curview]} {
5274 removefakerow $nullid
5275 }
5276 removefakerow $nullid2
5277 }
5278 return 0
5279}
5280
5281proc readdifffiles {fd serial inst} {
5282 global viewmainheadid nullid nullid2 curview
5283 global commitinfo commitdata lserial
5284
5285 set isdiff 1
5286 if {[gets $fd line] < 0} {
5287 if {![eof $fd]} {
5288 return 1
5289 }
5290 set isdiff 0
5291 }
5292 # we only need to see one line and we don't really care what it says...
5293 stop_instance $inst
5294
5295 if {$serial != $lserial} {
5296 return 0
5297 }
5298
5299 if {$isdiff && ![commitinview $nullid $curview]} {
5300 # add the line for the local diff to the graph
5301 set hl [mc "Local uncommitted changes, not checked in to index"]
5302 set commitinfo($nullid) [list $hl {} {} {} {} " $hl\n"]
5303 set commitdata($nullid) "\n $hl\n"
5304 if {[commitinview $nullid2 $curview]} {
5305 set p $nullid2
5306 } else {
5307 set p $viewmainheadid($curview)
5308 }
5309 insertfakerow $nullid $p
5310 } elseif {!$isdiff && [commitinview $nullid $curview]} {
5311 removefakerow $nullid
5312 }
5313 return 0
5314}
5315
5316proc nextuse {id row} {
5317 global curview children
5318
5319 if {[info exists children($curview,$id)]} {
5320 foreach kid $children($curview,$id) {
5321 if {![commitinview $kid $curview]} {
5322 return -1
5323 }
5324 if {[rowofcommit $kid] > $row} {
5325 return [rowofcommit $kid]
5326 }
5327 }
5328 }
5329 if {[commitinview $id $curview]} {
5330 return [rowofcommit $id]
5331 }
5332 return -1
5333}
5334
5335proc prevuse {id row} {
5336 global curview children
5337
5338 set ret -1
5339 if {[info exists children($curview,$id)]} {
5340 foreach kid $children($curview,$id) {
5341 if {![commitinview $kid $curview]} break
5342 if {[rowofcommit $kid] < $row} {
5343 set ret [rowofcommit $kid]
5344 }
5345 }
5346 }
5347 return $ret
5348}
5349
5350proc make_idlist {row} {
5351 global displayorder parentlist uparrowlen downarrowlen mingaplen
5352 global commitidx curview children
5353
5354 set r [expr {$row - $mingaplen - $downarrowlen - 1}]
5355 if {$r < 0} {
5356 set r 0
5357 }
5358 set ra [expr {$row - $downarrowlen}]
5359 if {$ra < 0} {
5360 set ra 0
5361 }
5362 set rb [expr {$row + $uparrowlen}]
5363 if {$rb > $commitidx($curview)} {
5364 set rb $commitidx($curview)
5365 }
5366 make_disporder $r [expr {$rb + 1}]
5367 set ids {}
5368 for {} {$r < $ra} {incr r} {
5369 set nextid [lindex $displayorder [expr {$r + 1}]]
5370 foreach p [lindex $parentlist $r] {
5371 if {$p eq $nextid} continue
5372 set rn [nextuse $p $r]
5373 if {$rn >= $row &&
5374 $rn <= $r + $downarrowlen + $mingaplen + $uparrowlen} {
5375 lappend ids [list [ordertoken $p] $p]
5376 }
5377 }
5378 }
5379 for {} {$r < $row} {incr r} {
5380 set nextid [lindex $displayorder [expr {$r + 1}]]
5381 foreach p [lindex $parentlist $r] {
5382 if {$p eq $nextid} continue
5383 set rn [nextuse $p $r]
5384 if {$rn < 0 || $rn >= $row} {
5385 lappend ids [list [ordertoken $p] $p]
5386 }
5387 }
5388 }
5389 set id [lindex $displayorder $row]
5390 lappend ids [list [ordertoken $id] $id]
5391 while {$r < $rb} {
5392 foreach p [lindex $parentlist $r] {
5393 set firstkid [lindex $children($curview,$p) 0]
5394 if {[rowofcommit $firstkid] < $row} {
5395 lappend ids [list [ordertoken $p] $p]
5396 }
5397 }
5398 incr r
5399 set id [lindex $displayorder $r]
5400 if {$id ne {}} {
5401 set firstkid [lindex $children($curview,$id) 0]
5402 if {$firstkid ne {} && [rowofcommit $firstkid] < $row} {
5403 lappend ids [list [ordertoken $id] $id]
5404 }
5405 }
5406 }
5407 set idlist {}
5408 foreach idx [lsort -unique $ids] {
5409 lappend idlist [lindex $idx 1]
5410 }
5411 return $idlist
5412}
5413
5414proc rowsequal {a b} {
5415 while {[set i [lsearch -exact $a {}]] >= 0} {
5416 set a [lreplace $a $i $i]
5417 }
5418 while {[set i [lsearch -exact $b {}]] >= 0} {
5419 set b [lreplace $b $i $i]
5420 }
5421 return [expr {$a eq $b}]
5422}
5423
5424proc makeupline {id row rend col} {
5425 global rowidlist uparrowlen downarrowlen mingaplen
5426
5427 for {set r $rend} {1} {set r $rstart} {
5428 set rstart [prevuse $id $r]
5429 if {$rstart < 0} return
5430 if {$rstart < $row} break
5431 }
5432 if {$rstart + $uparrowlen + $mingaplen + $downarrowlen < $rend} {
5433 set rstart [expr {$rend - $uparrowlen - 1}]
5434 }
5435 for {set r $rstart} {[incr r] <= $row} {} {
5436 set idlist [lindex $rowidlist $r]
5437 if {$idlist ne {} && [lsearch -exact $idlist $id] < 0} {
5438 set col [idcol $idlist $id $col]
5439 lset rowidlist $r [linsert $idlist $col $id]
5440 changedrow $r
5441 }
5442 }
5443}
5444
5445proc layoutrows {row endrow} {
5446 global rowidlist rowisopt rowfinal displayorder
5447 global uparrowlen downarrowlen maxwidth mingaplen
5448 global children parentlist
5449 global commitidx viewcomplete curview
5450
5451 make_disporder [expr {$row - 1}] [expr {$endrow + $uparrowlen}]
5452 set idlist {}
5453 if {$row > 0} {
5454 set rm1 [expr {$row - 1}]
5455 foreach id [lindex $rowidlist $rm1] {
5456 if {$id ne {}} {
5457 lappend idlist $id
5458 }
5459 }
5460 set final [lindex $rowfinal $rm1]
5461 }
5462 for {} {$row < $endrow} {incr row} {
5463 set rm1 [expr {$row - 1}]
5464 if {$rm1 < 0 || $idlist eq {}} {
5465 set idlist [make_idlist $row]
5466 set final 1
5467 } else {
5468 set id [lindex $displayorder $rm1]
5469 set col [lsearch -exact $idlist $id]
5470 set idlist [lreplace $idlist $col $col]
5471 foreach p [lindex $parentlist $rm1] {
5472 if {[lsearch -exact $idlist $p] < 0} {
5473 set col [idcol $idlist $p $col]
5474 set idlist [linsert $idlist $col $p]
5475 # if not the first child, we have to insert a line going up
5476 if {$id ne [lindex $children($curview,$p) 0]} {
5477 makeupline $p $rm1 $row $col
5478 }
5479 }
5480 }
5481 set id [lindex $displayorder $row]
5482 if {$row > $downarrowlen} {
5483 set termrow [expr {$row - $downarrowlen - 1}]
5484 foreach p [lindex $parentlist $termrow] {
5485 set i [lsearch -exact $idlist $p]
5486 if {$i < 0} continue
5487 set nr [nextuse $p $termrow]
5488 if {$nr < 0 || $nr >= $row + $mingaplen + $uparrowlen} {
5489 set idlist [lreplace $idlist $i $i]
5490 }
5491 }
5492 }
5493 set col [lsearch -exact $idlist $id]
5494 if {$col < 0} {
5495 set col [idcol $idlist $id]
5496 set idlist [linsert $idlist $col $id]
5497 if {$children($curview,$id) ne {}} {
5498 makeupline $id $rm1 $row $col
5499 }
5500 }
5501 set r [expr {$row + $uparrowlen - 1}]
5502 if {$r < $commitidx($curview)} {
5503 set x $col
5504 foreach p [lindex $parentlist $r] {
5505 if {[lsearch -exact $idlist $p] >= 0} continue
5506 set fk [lindex $children($curview,$p) 0]
5507 if {[rowofcommit $fk] < $row} {
5508 set x [idcol $idlist $p $x]
5509 set idlist [linsert $idlist $x $p]
5510 }
5511 }
5512 if {[incr r] < $commitidx($curview)} {
5513 set p [lindex $displayorder $r]
5514 if {[lsearch -exact $idlist $p] < 0} {
5515 set fk [lindex $children($curview,$p) 0]
5516 if {$fk ne {} && [rowofcommit $fk] < $row} {
5517 set x [idcol $idlist $p $x]
5518 set idlist [linsert $idlist $x $p]
5519 }
5520 }
5521 }
5522 }
5523 }
5524 if {$final && !$viewcomplete($curview) &&
5525 $row + $uparrowlen + $mingaplen + $downarrowlen
5526 >= $commitidx($curview)} {
5527 set final 0
5528 }
5529 set l [llength $rowidlist]
5530 if {$row == $l} {
5531 lappend rowidlist $idlist
5532 lappend rowisopt 0
5533 lappend rowfinal $final
5534 } elseif {$row < $l} {
5535 if {![rowsequal $idlist [lindex $rowidlist $row]]} {
5536 lset rowidlist $row $idlist
5537 changedrow $row
5538 }
5539 lset rowfinal $row $final
5540 } else {
5541 set pad [ntimes [expr {$row - $l}] {}]
5542 set rowidlist [concat $rowidlist $pad]
5543 lappend rowidlist $idlist
5544 set rowfinal [concat $rowfinal $pad]
5545 lappend rowfinal $final
5546 set rowisopt [concat $rowisopt [ntimes [expr {$row - $l + 1}] 0]]
5547 }
5548 }
5549 return $row
5550}
5551
5552proc changedrow {row} {
5553 global displayorder iddrawn rowisopt need_redisplay
5554
5555 set l [llength $rowisopt]
5556 if {$row < $l} {
5557 lset rowisopt $row 0
5558 if {$row + 1 < $l} {
5559 lset rowisopt [expr {$row + 1}] 0
5560 if {$row + 2 < $l} {
5561 lset rowisopt [expr {$row + 2}] 0
5562 }
5563 }
5564 }
5565 set id [lindex $displayorder $row]
5566 if {[info exists iddrawn($id)]} {
5567 set need_redisplay 1
5568 }
5569}
5570
5571proc insert_pad {row col npad} {
5572 global rowidlist
5573
5574 set pad [ntimes $npad {}]
5575 set idlist [lindex $rowidlist $row]
5576 set bef [lrange $idlist 0 [expr {$col - 1}]]
5577 set aft [lrange $idlist $col end]
5578 set i [lsearch -exact $aft {}]
5579 if {$i > 0} {
5580 set aft [lreplace $aft $i $i]
5581 }
5582 lset rowidlist $row [concat $bef $pad $aft]
5583 changedrow $row
5584}
5585
5586proc optimize_rows {row col endrow} {
5587 global rowidlist rowisopt displayorder curview children
5588
5589 if {$row < 1} {
5590 set row 1
5591 }
5592 for {} {$row < $endrow} {incr row; set col 0} {
5593 if {[lindex $rowisopt $row]} continue
5594 set haspad 0
5595 set y0 [expr {$row - 1}]
5596 set ym [expr {$row - 2}]
5597 set idlist [lindex $rowidlist $row]
5598 set previdlist [lindex $rowidlist $y0]
5599 if {$idlist eq {} || $previdlist eq {}} continue
5600 if {$ym >= 0} {
5601 set pprevidlist [lindex $rowidlist $ym]
5602 if {$pprevidlist eq {}} continue
5603 } else {
5604 set pprevidlist {}
5605 }
5606 set x0 -1
5607 set xm -1
5608 for {} {$col < [llength $idlist]} {incr col} {
5609 set id [lindex $idlist $col]
5610 if {[lindex $previdlist $col] eq $id} continue
5611 if {$id eq {}} {
5612 set haspad 1
5613 continue
5614 }
5615 set x0 [lsearch -exact $previdlist $id]
5616 if {$x0 < 0} continue
5617 set z [expr {$x0 - $col}]
5618 set isarrow 0
5619 set z0 {}
5620 if {$ym >= 0} {
5621 set xm [lsearch -exact $pprevidlist $id]
5622 if {$xm >= 0} {
5623 set z0 [expr {$xm - $x0}]
5624 }
5625 }
5626 if {$z0 eq {}} {
5627 # if row y0 is the first child of $id then it's not an arrow
5628 if {[lindex $children($curview,$id) 0] ne
5629 [lindex $displayorder $y0]} {
5630 set isarrow 1
5631 }
5632 }
5633 if {!$isarrow && $id ne [lindex $displayorder $row] &&
5634 [lsearch -exact [lindex $rowidlist [expr {$row+1}]] $id] < 0} {
5635 set isarrow 1
5636 }
5637 # Looking at lines from this row to the previous row,
5638 # make them go straight up if they end in an arrow on
5639 # the previous row; otherwise make them go straight up
5640 # or at 45 degrees.
5641 if {$z < -1 || ($z < 0 && $isarrow)} {
5642 # Line currently goes left too much;
5643 # insert pads in the previous row, then optimize it
5644 set npad [expr {-1 - $z + $isarrow}]
5645 insert_pad $y0 $x0 $npad
5646 if {$y0 > 0} {
5647 optimize_rows $y0 $x0 $row
5648 }
5649 set previdlist [lindex $rowidlist $y0]
5650 set x0 [lsearch -exact $previdlist $id]
5651 set z [expr {$x0 - $col}]
5652 if {$z0 ne {}} {
5653 set pprevidlist [lindex $rowidlist $ym]
5654 set xm [lsearch -exact $pprevidlist $id]
5655 set z0 [expr {$xm - $x0}]
5656 }
5657 } elseif {$z > 1 || ($z > 0 && $isarrow)} {
5658 # Line currently goes right too much;
5659 # insert pads in this line
5660 set npad [expr {$z - 1 + $isarrow}]
5661 insert_pad $row $col $npad
5662 set idlist [lindex $rowidlist $row]
5663 incr col $npad
5664 set z [expr {$x0 - $col}]
5665 set haspad 1
5666 }
5667 if {$z0 eq {} && !$isarrow && $ym >= 0} {
5668 # this line links to its first child on row $row-2
5669 set id [lindex $displayorder $ym]
5670 set xc [lsearch -exact $pprevidlist $id]
5671 if {$xc >= 0} {
5672 set z0 [expr {$xc - $x0}]
5673 }
5674 }
5675 # avoid lines jigging left then immediately right
5676 if {$z0 ne {} && $z < 0 && $z0 > 0} {
5677 insert_pad $y0 $x0 1
5678 incr x0
5679 optimize_rows $y0 $x0 $row
5680 set previdlist [lindex $rowidlist $y0]
5681 }
5682 }
5683 if {!$haspad} {
5684 # Find the first column that doesn't have a line going right
5685 for {set col [llength $idlist]} {[incr col -1] >= 0} {} {
5686 set id [lindex $idlist $col]
5687 if {$id eq {}} break
5688 set x0 [lsearch -exact $previdlist $id]
5689 if {$x0 < 0} {
5690 # check if this is the link to the first child
5691 set kid [lindex $displayorder $y0]
5692 if {[lindex $children($curview,$id) 0] eq $kid} {
5693 # it is, work out offset to child
5694 set x0 [lsearch -exact $previdlist $kid]
5695 }
5696 }
5697 if {$x0 <= $col} break
5698 }
5699 # Insert a pad at that column as long as it has a line and
5700 # isn't the last column
5701 if {$x0 >= 0 && [incr col] < [llength $idlist]} {
5702 set idlist [linsert $idlist $col {}]
5703 lset rowidlist $row $idlist
5704 changedrow $row
5705 }
5706 }
5707 }
5708}
5709
5710proc xc {row col} {
5711 global canvx0 linespc
5712 return [expr {$canvx0 + $col * $linespc}]
5713}
5714
5715proc yc {row} {
5716 global canvy0 linespc
5717 return [expr {$canvy0 + $row * $linespc}]
5718}
5719
5720proc linewidth {id} {
5721 global thickerline lthickness
5722
5723 set wid $lthickness
5724 if {[info exists thickerline] && $id eq $thickerline} {
5725 set wid [expr {2 * $lthickness}]
5726 }
5727 return $wid
5728}
5729
5730proc rowranges {id} {
5731 global curview children uparrowlen downarrowlen
5732 global rowidlist
5733
5734 set kids $children($curview,$id)
5735 if {$kids eq {}} {
5736 return {}
5737 }
5738 set ret {}
5739 lappend kids $id
5740 foreach child $kids {
5741 if {![commitinview $child $curview]} break
5742 set row [rowofcommit $child]
5743 if {![info exists prev]} {
5744 lappend ret [expr {$row + 1}]
5745 } else {
5746 if {$row <= $prevrow} {
5747 puts "oops children of [shortids $id] out of order [shortids $child] $row <= [shortids $prev] $prevrow"
5748 }
5749 # see if the line extends the whole way from prevrow to row
5750 if {$row > $prevrow + $uparrowlen + $downarrowlen &&
5751 [lsearch -exact [lindex $rowidlist \
5752 [expr {int(($row + $prevrow) / 2)}]] $id] < 0} {
5753 # it doesn't, see where it ends
5754 set r [expr {$prevrow + $downarrowlen}]
5755 if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5756 while {[incr r -1] > $prevrow &&
5757 [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5758 } else {
5759 while {[incr r] <= $row &&
5760 [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5761 incr r -1
5762 }
5763 lappend ret $r
5764 # see where it starts up again
5765 set r [expr {$row - $uparrowlen}]
5766 if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5767 while {[incr r] < $row &&
5768 [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5769 } else {
5770 while {[incr r -1] >= $prevrow &&
5771 [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5772 incr r
5773 }
5774 lappend ret $r
5775 }
5776 }
5777 if {$child eq $id} {
5778 lappend ret $row
5779 }
5780 set prev $child
5781 set prevrow $row
5782 }
5783 return $ret
5784}
5785
5786proc drawlineseg {id row endrow arrowlow} {
5787 global rowidlist displayorder iddrawn linesegs
5788 global canv colormap linespc curview maxlinelen parentlist
5789
5790 set cols [list [lsearch -exact [lindex $rowidlist $row] $id]]
5791 set le [expr {$row + 1}]
5792 set arrowhigh 1
5793 while {1} {
5794 set c [lsearch -exact [lindex $rowidlist $le] $id]
5795 if {$c < 0} {
5796 incr le -1
5797 break
5798 }
5799 lappend cols $c
5800 set x [lindex $displayorder $le]
5801 if {$x eq $id} {
5802 set arrowhigh 0
5803 break
5804 }
5805 if {[info exists iddrawn($x)] || $le == $endrow} {
5806 set c [lsearch -exact [lindex $rowidlist [expr {$le+1}]] $id]
5807 if {$c >= 0} {
5808 lappend cols $c
5809 set arrowhigh 0
5810 }
5811 break
5812 }
5813 incr le
5814 }
5815 if {$le <= $row} {
5816 return $row
5817 }
5818
5819 set lines {}
5820 set i 0
5821 set joinhigh 0
5822 if {[info exists linesegs($id)]} {
5823 set lines $linesegs($id)
5824 foreach li $lines {
5825 set r0 [lindex $li 0]
5826 if {$r0 > $row} {
5827 if {$r0 == $le && [lindex $li 1] - $row <= $maxlinelen} {
5828 set joinhigh 1
5829 }
5830 break
5831 }
5832 incr i
5833 }
5834 }
5835 set joinlow 0
5836 if {$i > 0} {
5837 set li [lindex $lines [expr {$i-1}]]
5838 set r1 [lindex $li 1]
5839 if {$r1 == $row && $le - [lindex $li 0] <= $maxlinelen} {
5840 set joinlow 1
5841 }
5842 }
5843
5844 set x [lindex $cols [expr {$le - $row}]]
5845 set xp [lindex $cols [expr {$le - 1 - $row}]]
5846 set dir [expr {$xp - $x}]
5847 if {$joinhigh} {
5848 set ith [lindex $lines $i 2]
5849 set coords [$canv coords $ith]
5850 set ah [$canv itemcget $ith -arrow]
5851 set arrowhigh [expr {$ah eq "first" || $ah eq "both"}]
5852 set x2 [lindex $cols [expr {$le + 1 - $row}]]
5853 if {$x2 ne {} && $x - $x2 == $dir} {
5854 set coords [lrange $coords 0 end-2]
5855 }
5856 } else {
5857 set coords [list [xc $le $x] [yc $le]]
5858 }
5859 if {$joinlow} {
5860 set itl [lindex $lines [expr {$i-1}] 2]
5861 set al [$canv itemcget $itl -arrow]
5862 set arrowlow [expr {$al eq "last" || $al eq "both"}]
5863 } elseif {$arrowlow} {
5864 if {[lsearch -exact [lindex $rowidlist [expr {$row-1}]] $id] >= 0 ||
5865 [lsearch -exact [lindex $parentlist [expr {$row-1}]] $id] >= 0} {
5866 set arrowlow 0
5867 }
5868 }
5869 set arrow [lindex {none first last both} [expr {$arrowhigh + 2*$arrowlow}]]
5870 for {set y $le} {[incr y -1] > $row} {} {
5871 set x $xp
5872 set xp [lindex $cols [expr {$y - 1 - $row}]]
5873 set ndir [expr {$xp - $x}]
5874 if {$dir != $ndir || $xp < 0} {
5875 lappend coords [xc $y $x] [yc $y]
5876 }
5877 set dir $ndir
5878 }
5879 if {!$joinlow} {
5880 if {$xp < 0} {
5881 # join parent line to first child
5882 set ch [lindex $displayorder $row]
5883 set xc [lsearch -exact [lindex $rowidlist $row] $ch]
5884 if {$xc < 0} {
5885 puts "oops: drawlineseg: child $ch not on row $row"
5886 } elseif {$xc != $x} {
5887 if {($arrowhigh && $le == $row + 1) || $dir == 0} {
5888 set d [expr {int(0.5 * $linespc)}]
5889 set x1 [xc $row $x]
5890 if {$xc < $x} {
5891 set x2 [expr {$x1 - $d}]
5892 } else {
5893 set x2 [expr {$x1 + $d}]
5894 }
5895 set y2 [yc $row]
5896 set y1 [expr {$y2 + $d}]
5897 lappend coords $x1 $y1 $x2 $y2
5898 } elseif {$xc < $x - 1} {
5899 lappend coords [xc $row [expr {$x-1}]] [yc $row]
5900 } elseif {$xc > $x + 1} {
5901 lappend coords [xc $row [expr {$x+1}]] [yc $row]
5902 }
5903 set x $xc
5904 }
5905 lappend coords [xc $row $x] [yc $row]
5906 } else {
5907 set xn [xc $row $xp]
5908 set yn [yc $row]
5909 lappend coords $xn $yn
5910 }
5911 if {!$joinhigh} {
5912 assigncolor $id
5913 set t [$canv create line $coords -width [linewidth $id] \
5914 -fill $colormap($id) -tags lines.$id -arrow $arrow]
5915 $canv lower $t
5916 bindline $t $id
5917 set lines [linsert $lines $i [list $row $le $t]]
5918 } else {
5919 $canv coords $ith $coords
5920 if {$arrow ne $ah} {
5921 $canv itemconf $ith -arrow $arrow
5922 }
5923 lset lines $i 0 $row
5924 }
5925 } else {
5926 set xo [lsearch -exact [lindex $rowidlist [expr {$row - 1}]] $id]
5927 set ndir [expr {$xo - $xp}]
5928 set clow [$canv coords $itl]
5929 if {$dir == $ndir} {
5930 set clow [lrange $clow 2 end]
5931 }
5932 set coords [concat $coords $clow]
5933 if {!$joinhigh} {
5934 lset lines [expr {$i-1}] 1 $le
5935 } else {
5936 # coalesce two pieces
5937 $canv delete $ith
5938 set b [lindex $lines [expr {$i-1}] 0]
5939 set e [lindex $lines $i 1]
5940 set lines [lreplace $lines [expr {$i-1}] $i [list $b $e $itl]]
5941 }
5942 $canv coords $itl $coords
5943 if {$arrow ne $al} {
5944 $canv itemconf $itl -arrow $arrow
5945 }
5946 }
5947
5948 set linesegs($id) $lines
5949 return $le
5950}
5951
5952proc drawparentlinks {id row} {
5953 global rowidlist canv colormap curview parentlist
5954 global idpos linespc
5955
5956 set rowids [lindex $rowidlist $row]
5957 set col [lsearch -exact $rowids $id]
5958 if {$col < 0} return
5959 set olds [lindex $parentlist $row]
5960 set row2 [expr {$row + 1}]
5961 set x [xc $row $col]
5962 set y [yc $row]
5963 set y2 [yc $row2]
5964 set d [expr {int(0.5 * $linespc)}]
5965 set ymid [expr {$y + $d}]
5966 set ids [lindex $rowidlist $row2]
5967 # rmx = right-most X coord used
5968 set rmx 0
5969 foreach p $olds {
5970 set i [lsearch -exact $ids $p]
5971 if {$i < 0} {
5972 puts "oops, parent $p of $id not in list"
5973 continue
5974 }
5975 set x2 [xc $row2 $i]
5976 if {$x2 > $rmx} {
5977 set rmx $x2
5978 }
5979 set j [lsearch -exact $rowids $p]
5980 if {$j < 0} {
5981 # drawlineseg will do this one for us
5982 continue
5983 }
5984 assigncolor $p
5985 # should handle duplicated parents here...
5986 set coords [list $x $y]
5987 if {$i != $col} {
5988 # if attaching to a vertical segment, draw a smaller
5989 # slant for visual distinctness
5990 if {$i == $j} {
5991 if {$i < $col} {
5992 lappend coords [expr {$x2 + $d}] $y $x2 $ymid
5993 } else {
5994 lappend coords [expr {$x2 - $d}] $y $x2 $ymid
5995 }
5996 } elseif {$i < $col && $i < $j} {
5997 # segment slants towards us already
5998 lappend coords [xc $row $j] $y
5999 } else {
6000 if {$i < $col - 1} {
6001 lappend coords [expr {$x2 + $linespc}] $y
6002 } elseif {$i > $col + 1} {
6003 lappend coords [expr {$x2 - $linespc}] $y
6004 }
6005 lappend coords $x2 $y2
6006 }
6007 } else {
6008 lappend coords $x2 $y2
6009 }
6010 set t [$canv create line $coords -width [linewidth $p] \
6011 -fill $colormap($p) -tags lines.$p]
6012 $canv lower $t
6013 bindline $t $p
6014 }
6015 if {$rmx > [lindex $idpos($id) 1]} {
6016 lset idpos($id) 1 $rmx
6017 redrawtags $id
6018 }
6019}
6020
6021proc drawlines {id} {
6022 global canv
6023
6024 $canv itemconf lines.$id -width [linewidth $id]
6025}
6026
6027proc drawcmittext {id row col} {
6028 global linespc canv canv2 canv3 fgcolor curview
6029 global cmitlisted commitinfo rowidlist parentlist
6030 global rowtextx idpos idtags idheads idotherrefs
6031 global linehtag linentag linedtag selectedline
6032 global canvxmax boldids boldnameids fgcolor markedid
6033 global mainheadid nullid nullid2 circleitem circlecolors ctxbut
6034 global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
6035 global circleoutlinecolor
6036
6037 # listed is 0 for boundary, 1 for normal, 2 for negative, 3 for left, 4 for right
6038 set listed $cmitlisted($curview,$id)
6039 if {$id eq $nullid} {
6040 set ofill $workingfilescirclecolor
6041 } elseif {$id eq $nullid2} {
6042 set ofill $indexcirclecolor
6043 } elseif {$id eq $mainheadid} {
6044 set ofill $mainheadcirclecolor
6045 } else {
6046 set ofill [lindex $circlecolors $listed]
6047 }
6048 set x [xc $row $col]
6049 set y [yc $row]
6050 set orad [expr {$linespc / 3}]
6051 if {$listed <= 2} {
6052 set t [$canv create oval [expr {$x - $orad}] [expr {$y - $orad}] \
6053 [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6054 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6055 } elseif {$listed == 3} {
6056 # triangle pointing left for left-side commits
6057 set t [$canv create polygon \
6058 [expr {$x - $orad}] $y \
6059 [expr {$x + $orad - 1}] [expr {$y - $orad}] \
6060 [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6061 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6062 } else {
6063 # triangle pointing right for right-side commits
6064 set t [$canv create polygon \
6065 [expr {$x + $orad - 1}] $y \
6066 [expr {$x - $orad}] [expr {$y - $orad}] \
6067 [expr {$x - $orad}] [expr {$y + $orad - 1}] \
6068 -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6069 }
6070 set circleitem($row) $t
6071 $canv raise $t
6072 $canv bind $t <1> {selcanvline {} %x %y}
6073 set rmx [llength [lindex $rowidlist $row]]
6074 set olds [lindex $parentlist $row]
6075 if {$olds ne {}} {
6076 set nextids [lindex $rowidlist [expr {$row + 1}]]
6077 foreach p $olds {
6078 set i [lsearch -exact $nextids $p]
6079 if {$i > $rmx} {
6080 set rmx $i
6081 }
6082 }
6083 }
6084 set xt [xc $row $rmx]
6085 set rowtextx($row) $xt
6086 set idpos($id) [list $x $xt $y]
6087 if {[info exists idtags($id)] || [info exists idheads($id)]
6088 || [info exists idotherrefs($id)]} {
6089 set xt [drawtags $id $x $xt $y]
6090 }
6091 if {[lindex $commitinfo($id) 6] > 0} {
6092 set xt [drawnotesign $xt $y]
6093 }
6094 set headline [lindex $commitinfo($id) 0]
6095 set name [lindex $commitinfo($id) 1]
6096 set date [lindex $commitinfo($id) 2]
6097 set date [formatdate $date]
6098 set font mainfont
6099 set nfont mainfont
6100 set isbold [ishighlighted $id]
6101 if {$isbold > 0} {
6102 lappend boldids $id
6103 set font mainfontbold
6104 if {$isbold > 1} {
6105 lappend boldnameids $id
6106 set nfont mainfontbold
6107 }
6108 }
6109 set linehtag($id) [$canv create text $xt $y -anchor w -fill $fgcolor \
6110 -text $headline -font $font -tags text]
6111 $canv bind $linehtag($id) $ctxbut "rowmenu %X %Y $id"
6112 set linentag($id) [$canv2 create text 3 $y -anchor w -fill $fgcolor \
6113 -text $name -font $nfont -tags text]
6114 set linedtag($id) [$canv3 create text 3 $y -anchor w -fill $fgcolor \
6115 -text $date -font mainfont -tags text]
6116 if {$selectedline == $row} {
6117 make_secsel $id
6118 }
6119 if {[info exists markedid] && $markedid eq $id} {
6120 make_idmark $id
6121 }
6122 set xr [expr {$xt + [font measure $font $headline]}]
6123 if {$xr > $canvxmax} {
6124 set canvxmax $xr
6125 setcanvscroll
6126 }
6127}
6128
6129proc drawcmitrow {row} {
6130 global displayorder rowidlist nrows_drawn
6131 global iddrawn markingmatches
6132 global commitinfo numcommits
6133 global filehighlight fhighlights findpattern nhighlights
6134 global hlview vhighlights
6135 global highlight_related rhighlights
6136
6137 if {$row >= $numcommits} return
6138
6139 set id [lindex $displayorder $row]
6140 if {[info exists hlview] && ![info exists vhighlights($id)]} {
6141 askvhighlight $row $id
6142 }
6143 if {[info exists filehighlight] && ![info exists fhighlights($id)]} {
6144 askfilehighlight $row $id
6145 }
6146 if {$findpattern ne {} && ![info exists nhighlights($id)]} {
6147 askfindhighlight $row $id
6148 }
6149 if {$highlight_related ne [mc "None"] && ![info exists rhighlights($id)]} {
6150 askrelhighlight $row $id
6151 }
6152 if {![info exists iddrawn($id)]} {
6153 set col [lsearch -exact [lindex $rowidlist $row] $id]
6154 if {$col < 0} {
6155 puts "oops, row $row id $id not in list"
6156 return
6157 }
6158 if {![info exists commitinfo($id)]} {
6159 getcommit $id
6160 }
6161 assigncolor $id
6162 drawcmittext $id $row $col
6163 set iddrawn($id) 1
6164 incr nrows_drawn
6165 }
6166 if {$markingmatches} {
6167 markrowmatches $row $id
6168 }
6169}
6170
6171proc drawcommits {row {endrow {}}} {
6172 global numcommits iddrawn displayorder curview need_redisplay
6173 global parentlist rowidlist rowfinal uparrowlen downarrowlen nrows_drawn
6174
6175 if {$row < 0} {
6176 set row 0
6177 }
6178 if {$endrow eq {}} {
6179 set endrow $row
6180 }
6181 if {$endrow >= $numcommits} {
6182 set endrow [expr {$numcommits - 1}]
6183 }
6184
6185 set rl1 [expr {$row - $downarrowlen - 3}]
6186 if {$rl1 < 0} {
6187 set rl1 0
6188 }
6189 set ro1 [expr {$row - 3}]
6190 if {$ro1 < 0} {
6191 set ro1 0
6192 }
6193 set r2 [expr {$endrow + $uparrowlen + 3}]
6194 if {$r2 > $numcommits} {
6195 set r2 $numcommits
6196 }
6197 for {set r $rl1} {$r < $r2} {incr r} {
6198 if {[lindex $rowidlist $r] ne {} && [lindex $rowfinal $r]} {
6199 if {$rl1 < $r} {
6200 layoutrows $rl1 $r
6201 }
6202 set rl1 [expr {$r + 1}]
6203 }
6204 }
6205 if {$rl1 < $r} {
6206 layoutrows $rl1 $r
6207 }
6208 optimize_rows $ro1 0 $r2
6209 if {$need_redisplay || $nrows_drawn > 2000} {
6210 clear_display
6211 }
6212
6213 # make the lines join to already-drawn rows either side
6214 set r [expr {$row - 1}]
6215 if {$r < 0 || ![info exists iddrawn([lindex $displayorder $r])]} {
6216 set r $row
6217 }
6218 set er [expr {$endrow + 1}]
6219 if {$er >= $numcommits ||
6220 ![info exists iddrawn([lindex $displayorder $er])]} {
6221 set er $endrow
6222 }
6223 for {} {$r <= $er} {incr r} {
6224 set id [lindex $displayorder $r]
6225 set wasdrawn [info exists iddrawn($id)]
6226 drawcmitrow $r
6227 if {$r == $er} break
6228 set nextid [lindex $displayorder [expr {$r + 1}]]
6229 if {$wasdrawn && [info exists iddrawn($nextid)]} continue
6230 drawparentlinks $id $r
6231
6232 set rowids [lindex $rowidlist $r]
6233 foreach lid $rowids {
6234 if {$lid eq {}} continue
6235 if {[info exists lineend($lid)] && $lineend($lid) > $r} continue
6236 if {$lid eq $id} {
6237 # see if this is the first child of any of its parents
6238 foreach p [lindex $parentlist $r] {
6239 if {[lsearch -exact $rowids $p] < 0} {
6240 # make this line extend up to the child
6241 set lineend($p) [drawlineseg $p $r $er 0]
6242 }
6243 }
6244 } else {
6245 set lineend($lid) [drawlineseg $lid $r $er 1]
6246 }
6247 }
6248 }
6249}
6250
6251proc undolayout {row} {
6252 global uparrowlen mingaplen downarrowlen
6253 global rowidlist rowisopt rowfinal need_redisplay
6254
6255 set r [expr {$row - ($uparrowlen + $mingaplen + $downarrowlen)}]
6256 if {$r < 0} {
6257 set r 0
6258 }
6259 if {[llength $rowidlist] > $r} {
6260 incr r -1
6261 set rowidlist [lrange $rowidlist 0 $r]
6262 set rowfinal [lrange $rowfinal 0 $r]
6263 set rowisopt [lrange $rowisopt 0 $r]
6264 set need_redisplay 1
6265 run drawvisible
6266 }
6267}
6268
6269proc drawvisible {} {
6270 global canv linespc curview vrowmod selectedline targetrow targetid
6271 global need_redisplay cscroll numcommits
6272
6273 set fs [$canv yview]
6274 set ymax [lindex [$canv cget -scrollregion] 3]
6275 if {$ymax eq {} || $ymax == 0 || $numcommits == 0} return
6276 set f0 [lindex $fs 0]
6277 set f1 [lindex $fs 1]
6278 set y0 [expr {int($f0 * $ymax)}]
6279 set y1 [expr {int($f1 * $ymax)}]
6280
6281 if {[info exists targetid]} {
6282 if {[commitinview $targetid $curview]} {
6283 set r [rowofcommit $targetid]
6284 if {$r != $targetrow} {
6285 # Fix up the scrollregion and change the scrolling position
6286 # now that our target row has moved.
6287 set diff [expr {($r - $targetrow) * $linespc}]
6288 set targetrow $r
6289 setcanvscroll
6290 set ymax [lindex [$canv cget -scrollregion] 3]
6291 incr y0 $diff
6292 incr y1 $diff
6293 set f0 [expr {$y0 / $ymax}]
6294 set f1 [expr {$y1 / $ymax}]
6295 allcanvs yview moveto $f0
6296 $cscroll set $f0 $f1
6297 set need_redisplay 1
6298 }
6299 } else {
6300 unset targetid
6301 }
6302 }
6303
6304 set row [expr {int(($y0 - 3) / $linespc) - 1}]
6305 set endrow [expr {int(($y1 - 3) / $linespc) + 1}]
6306 if {$endrow >= $vrowmod($curview)} {
6307 update_arcrows $curview
6308 }
6309 if {$selectedline ne {} &&
6310 $row <= $selectedline && $selectedline <= $endrow} {
6311 set targetrow $selectedline
6312 } elseif {[info exists targetid]} {
6313 set targetrow [expr {int(($row + $endrow) / 2)}]
6314 }
6315 if {[info exists targetrow]} {
6316 if {$targetrow >= $numcommits} {
6317 set targetrow [expr {$numcommits - 1}]
6318 }
6319 set targetid [commitonrow $targetrow]
6320 }
6321 drawcommits $row $endrow
6322}
6323
6324proc clear_display {} {
6325 global iddrawn linesegs need_redisplay nrows_drawn
6326 global vhighlights fhighlights nhighlights rhighlights
6327 global linehtag linentag linedtag boldids boldnameids
6328
6329 allcanvs delete all
6330 catch {unset iddrawn}
6331 catch {unset linesegs}
6332 catch {unset linehtag}
6333 catch {unset linentag}
6334 catch {unset linedtag}
6335 set boldids {}
6336 set boldnameids {}
6337 catch {unset vhighlights}
6338 catch {unset fhighlights}
6339 catch {unset nhighlights}
6340 catch {unset rhighlights}
6341 set need_redisplay 0
6342 set nrows_drawn 0
6343}
6344
6345proc findcrossings {id} {
6346 global rowidlist parentlist numcommits displayorder
6347
6348 set cross {}
6349 set ccross {}
6350 foreach {s e} [rowranges $id] {
6351 if {$e >= $numcommits} {
6352 set e [expr {$numcommits - 1}]
6353 }
6354 if {$e <= $s} continue
6355 for {set row $e} {[incr row -1] >= $s} {} {
6356 set x [lsearch -exact [lindex $rowidlist $row] $id]
6357 if {$x < 0} break
6358 set olds [lindex $parentlist $row]
6359 set kid [lindex $displayorder $row]
6360 set kidx [lsearch -exact [lindex $rowidlist $row] $kid]
6361 if {$kidx < 0} continue
6362 set nextrow [lindex $rowidlist [expr {$row + 1}]]
6363 foreach p $olds {
6364 set px [lsearch -exact $nextrow $p]
6365 if {$px < 0} continue
6366 if {($kidx < $x && $x < $px) || ($px < $x && $x < $kidx)} {
6367 if {[lsearch -exact $ccross $p] >= 0} continue
6368 if {$x == $px + ($kidx < $px? -1: 1)} {
6369 lappend ccross $p
6370 } elseif {[lsearch -exact $cross $p] < 0} {
6371 lappend cross $p
6372 }
6373 }
6374 }
6375 }
6376 }
6377 return [concat $ccross {{}} $cross]
6378}
6379
6380proc assigncolor {id} {
6381 global colormap colors nextcolor
6382 global parents children children curview
6383
6384 if {[info exists colormap($id)]} return
6385 set ncolors [llength $colors]
6386 if {[info exists children($curview,$id)]} {
6387 set kids $children($curview,$id)
6388 } else {
6389 set kids {}
6390 }
6391 if {[llength $kids] == 1} {
6392 set child [lindex $kids 0]
6393 if {[info exists colormap($child)]
6394 && [llength $parents($curview,$child)] == 1} {
6395 set colormap($id) $colormap($child)
6396 return
6397 }
6398 }
6399 set badcolors {}
6400 set origbad {}
6401 foreach x [findcrossings $id] {
6402 if {$x eq {}} {
6403 # delimiter between corner crossings and other crossings
6404 if {[llength $badcolors] >= $ncolors - 1} break
6405 set origbad $badcolors
6406 }
6407 if {[info exists colormap($x)]
6408 && [lsearch -exact $badcolors $colormap($x)] < 0} {
6409 lappend badcolors $colormap($x)
6410 }
6411 }
6412 if {[llength $badcolors] >= $ncolors} {
6413 set badcolors $origbad
6414 }
6415 set origbad $badcolors
6416 if {[llength $badcolors] < $ncolors - 1} {
6417 foreach child $kids {
6418 if {[info exists colormap($child)]
6419 && [lsearch -exact $badcolors $colormap($child)] < 0} {
6420 lappend badcolors $colormap($child)
6421 }
6422 foreach p $parents($curview,$child) {
6423 if {[info exists colormap($p)]
6424 && [lsearch -exact $badcolors $colormap($p)] < 0} {
6425 lappend badcolors $colormap($p)
6426 }
6427 }
6428 }
6429 if {[llength $badcolors] >= $ncolors} {
6430 set badcolors $origbad
6431 }
6432 }
6433 for {set i 0} {$i <= $ncolors} {incr i} {
6434 set c [lindex $colors $nextcolor]
6435 if {[incr nextcolor] >= $ncolors} {
6436 set nextcolor 0
6437 }
6438 if {[lsearch -exact $badcolors $c]} break
6439 }
6440 set colormap($id) $c
6441}
6442
6443proc bindline {t id} {
6444 global canv
6445
6446 $canv bind $t <Enter> "lineenter %x %y $id"
6447 $canv bind $t <Motion> "linemotion %x %y $id"
6448 $canv bind $t <Leave> "lineleave $id"
6449 $canv bind $t <Button-1> "lineclick %x %y $id 1"
6450}
6451
6452proc graph_pane_width {} {
6453 global use_ttk
6454
6455 if {$use_ttk} {
6456 set g [.tf.histframe.pwclist sashpos 0]
6457 } else {
6458 set g [.tf.histframe.pwclist sash coord 0]
6459 }
6460 return [lindex $g 0]
6461}
6462
6463proc totalwidth {l font extra} {
6464 set tot 0
6465 foreach str $l {
6466 set tot [expr {$tot + [font measure $font $str] + $extra}]
6467 }
6468 return $tot
6469}
6470
6471proc drawtags {id x xt y1} {
6472 global idtags idheads idotherrefs mainhead
6473 global linespc lthickness
6474 global canv rowtextx curview fgcolor bgcolor ctxbut
6475 global headbgcolor headfgcolor headoutlinecolor remotebgcolor
6476 global tagbgcolor tagfgcolor tagoutlinecolor
6477 global reflinecolor
6478
6479 set marks {}
6480 set ntags 0
6481 set nheads 0
6482 set singletag 0
6483 set maxtags 3
6484 set maxtagpct 25
6485 set maxwidth [expr {[graph_pane_width] * $maxtagpct / 100}]
6486 set delta [expr {int(0.5 * ($linespc - $lthickness))}]
6487 set extra [expr {$delta + $lthickness + $linespc}]
6488
6489 if {[info exists idtags($id)]} {
6490 set marks $idtags($id)
6491 set ntags [llength $marks]
6492 if {$ntags > $maxtags ||
6493 [totalwidth $marks mainfont $extra] > $maxwidth} {
6494 # show just a single "n tags..." tag
6495 set singletag 1
6496 if {$ntags == 1} {
6497 set marks [list "tag..."]
6498 } else {
6499 set marks [list [format "%d tags..." $ntags]]
6500 }
6501 set ntags 1
6502 }
6503 }
6504 if {[info exists idheads($id)]} {
6505 set marks [concat $marks $idheads($id)]
6506 set nheads [llength $idheads($id)]
6507 }
6508 if {[info exists idotherrefs($id)]} {
6509 set marks [concat $marks $idotherrefs($id)]
6510 }
6511 if {$marks eq {}} {
6512 return $xt
6513 }
6514
6515 set yt [expr {$y1 - 0.5 * $linespc}]
6516 set yb [expr {$yt + $linespc - 1}]
6517 set xvals {}
6518 set wvals {}
6519 set i -1
6520 foreach tag $marks {
6521 incr i
6522 if {$i >= $ntags && $i < $ntags + $nheads && $tag eq $mainhead} {
6523 set wid [font measure mainfontbold $tag]
6524 } else {
6525 set wid [font measure mainfont $tag]
6526 }
6527 lappend xvals $xt
6528 lappend wvals $wid
6529 set xt [expr {$xt + $wid + $extra}]
6530 }
6531 set t [$canv create line $x $y1 [lindex $xvals end] $y1 \
6532 -width $lthickness -fill $reflinecolor -tags tag.$id]
6533 $canv lower $t
6534 foreach tag $marks x $xvals wid $wvals {
6535 set tag_quoted [string map {% %%} $tag]
6536 set xl [expr {$x + $delta}]
6537 set xr [expr {$x + $delta + $wid + $lthickness}]
6538 set font mainfont
6539 if {[incr ntags -1] >= 0} {
6540 # draw a tag
6541 set t [$canv create polygon $x [expr {$yt + $delta}] $xl $yt \
6542 $xr $yt $xr $yb $xl $yb $x [expr {$yb - $delta}] \
6543 -width 1 -outline $tagoutlinecolor -fill $tagbgcolor \
6544 -tags tag.$id]
6545 if {$singletag} {
6546 set tagclick [list showtags $id 1]
6547 } else {
6548 set tagclick [list showtag $tag_quoted 1]
6549 }
6550 $canv bind $t <1> $tagclick
6551 set rowtextx([rowofcommit $id]) [expr {$xr + $linespc}]
6552 } else {
6553 # draw a head or other ref
6554 if {[incr nheads -1] >= 0} {
6555 set col $headbgcolor
6556 if {$tag eq $mainhead} {
6557 set font mainfontbold
6558 }
6559 } else {
6560 set col "#ddddff"
6561 }
6562 set xl [expr {$xl - $delta/2}]
6563 $canv create polygon $x $yt $xr $yt $xr $yb $x $yb \
6564 -width 1 -outline black -fill $col -tags tag.$id
6565 if {[regexp {^(remotes/.*/|remotes/)} $tag match remoteprefix]} {
6566 set rwid [font measure mainfont $remoteprefix]
6567 set xi [expr {$x + 1}]
6568 set yti [expr {$yt + 1}]
6569 set xri [expr {$x + $rwid}]
6570 $canv create polygon $xi $yti $xri $yti $xri $yb $xi $yb \
6571 -width 0 -fill $remotebgcolor -tags tag.$id
6572 }
6573 }
6574 set t [$canv create text $xl $y1 -anchor w -text $tag -fill $headfgcolor \
6575 -font $font -tags [list tag.$id text]]
6576 if {$ntags >= 0} {
6577 $canv bind $t <1> $tagclick
6578 } elseif {$nheads >= 0} {
6579 $canv bind $t $ctxbut [list headmenu %X %Y $id $tag_quoted]
6580 }
6581 }
6582 return $xt
6583}
6584
6585proc drawnotesign {xt y} {
6586 global linespc canv fgcolor
6587
6588 set orad [expr {$linespc / 3}]
6589 set t [$canv create rectangle [expr {$xt - $orad}] [expr {$y - $orad}] \
6590 [expr {$xt + $orad - 1}] [expr {$y + $orad - 1}] \
6591 -fill yellow -outline $fgcolor -width 1 -tags circle]
6592 set xt [expr {$xt + $orad * 3}]
6593 return $xt
6594}
6595
6596proc xcoord {i level ln} {
6597 global canvx0 xspc1 xspc2
6598
6599 set x [expr {$canvx0 + $i * $xspc1($ln)}]
6600 if {$i > 0 && $i == $level} {
6601 set x [expr {$x + 0.5 * ($xspc2 - $xspc1($ln))}]
6602 } elseif {$i > $level} {
6603 set x [expr {$x + $xspc2 - $xspc1($ln)}]
6604 }
6605 return $x
6606}
6607
6608proc show_status {msg} {
6609 global canv fgcolor
6610
6611 clear_display
6612 $canv create text 3 3 -anchor nw -text $msg -font mainfont \
6613 -tags text -fill $fgcolor
6614}
6615
6616# Don't change the text pane cursor if it is currently the hand cursor,
6617# showing that we are over a sha1 ID link.
6618proc settextcursor {c} {
6619 global ctext curtextcursor
6620
6621 if {[$ctext cget -cursor] == $curtextcursor} {
6622 $ctext config -cursor $c
6623 }
6624 set curtextcursor $c
6625}
6626
6627proc nowbusy {what {name {}}} {
6628 global isbusy busyname statusw
6629
6630 if {[array names isbusy] eq {}} {
6631 . config -cursor watch
6632 settextcursor watch
6633 }
6634 set isbusy($what) 1
6635 set busyname($what) $name
6636 if {$name ne {}} {
6637 $statusw conf -text $name
6638 }
6639}
6640
6641proc notbusy {what} {
6642 global isbusy maincursor textcursor busyname statusw
6643
6644 catch {
6645 unset isbusy($what)
6646 if {$busyname($what) ne {} &&
6647 [$statusw cget -text] eq $busyname($what)} {
6648 $statusw conf -text {}
6649 }
6650 }
6651 if {[array names isbusy] eq {}} {
6652 . config -cursor $maincursor
6653 settextcursor $textcursor
6654 }
6655}
6656
6657proc findmatches {f} {
6658 global findtype findstring
6659 if {$findtype == [mc "Regexp"]} {
6660 set matches [regexp -indices -all -inline $findstring $f]
6661 } else {
6662 set fs $findstring
6663 if {$findtype == [mc "IgnCase"]} {
6664 set f [string tolower $f]
6665 set fs [string tolower $fs]
6666 }
6667 set matches {}
6668 set i 0
6669 set l [string length $fs]
6670 while {[set j [string first $fs $f $i]] >= 0} {
6671 lappend matches [list $j [expr {$j+$l-1}]]
6672 set i [expr {$j + $l}]
6673 }
6674 }
6675 return $matches
6676}
6677
6678proc dofind {{dirn 1} {wrap 1}} {
6679 global findstring findstartline findcurline selectedline numcommits
6680 global gdttype filehighlight fh_serial find_dirn findallowwrap
6681
6682 if {[info exists find_dirn]} {
6683 if {$find_dirn == $dirn} return
6684 stopfinding
6685 }
6686 focus .
6687 if {$findstring eq {} || $numcommits == 0} return
6688 if {$selectedline eq {}} {
6689 set findstartline [lindex [visiblerows] [expr {$dirn < 0}]]
6690 } else {
6691 set findstartline $selectedline
6692 }
6693 set findcurline $findstartline
6694 nowbusy finding [mc "Searching"]
6695 if {$gdttype ne [mc "containing:"] && ![info exists filehighlight]} {
6696 after cancel do_file_hl $fh_serial
6697 do_file_hl $fh_serial
6698 }
6699 set find_dirn $dirn
6700 set findallowwrap $wrap
6701 run findmore
6702}
6703
6704proc stopfinding {} {
6705 global find_dirn findcurline fprogcoord
6706
6707 if {[info exists find_dirn]} {
6708 unset find_dirn
6709 unset findcurline
6710 notbusy finding
6711 set fprogcoord 0
6712 adjustprogress
6713 }
6714 stopblaming
6715}
6716
6717proc findmore {} {
6718 global commitdata commitinfo numcommits findpattern findloc
6719 global findstartline findcurline findallowwrap
6720 global find_dirn gdttype fhighlights fprogcoord
6721 global curview varcorder vrownum varccommits vrowmod
6722
6723 if {![info exists find_dirn]} {
6724 return 0
6725 }
6726 set fldtypes [list [mc "Headline"] [mc "Author"] "" [mc "Committer"] "" [mc "Comments"]]
6727 set l $findcurline
6728 set moretodo 0
6729 if {$find_dirn > 0} {
6730 incr l
6731 if {$l >= $numcommits} {
6732 set l 0
6733 }
6734 if {$l <= $findstartline} {
6735 set lim [expr {$findstartline + 1}]
6736 } else {
6737 set lim $numcommits
6738 set moretodo $findallowwrap
6739 }
6740 } else {
6741 if {$l == 0} {
6742 set l $numcommits
6743 }
6744 incr l -1
6745 if {$l >= $findstartline} {
6746 set lim [expr {$findstartline - 1}]
6747 } else {
6748 set lim -1
6749 set moretodo $findallowwrap
6750 }
6751 }
6752 set n [expr {($lim - $l) * $find_dirn}]
6753 if {$n > 500} {
6754 set n 500
6755 set moretodo 1
6756 }
6757 if {$l + ($find_dirn > 0? $n: 1) > $vrowmod($curview)} {
6758 update_arcrows $curview
6759 }
6760 set found 0
6761 set domore 1
6762 set ai [bsearch $vrownum($curview) $l]
6763 set a [lindex $varcorder($curview) $ai]
6764 set arow [lindex $vrownum($curview) $ai]
6765 set ids [lindex $varccommits($curview,$a)]
6766 set arowend [expr {$arow + [llength $ids]}]
6767 if {$gdttype eq [mc "containing:"]} {
6768 for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6769 if {$l < $arow || $l >= $arowend} {
6770 incr ai $find_dirn
6771 set a [lindex $varcorder($curview) $ai]
6772 set arow [lindex $vrownum($curview) $ai]
6773 set ids [lindex $varccommits($curview,$a)]
6774 set arowend [expr {$arow + [llength $ids]}]
6775 }
6776 set id [lindex $ids [expr {$l - $arow}]]
6777 # shouldn't happen unless git log doesn't give all the commits...
6778 if {![info exists commitdata($id)] ||
6779 ![doesmatch $commitdata($id)]} {
6780 continue
6781 }
6782 if {![info exists commitinfo($id)]} {
6783 getcommit $id
6784 }
6785 set info $commitinfo($id)
6786 foreach f $info ty $fldtypes {
6787 if {$ty eq ""} continue
6788 if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
6789 [doesmatch $f]} {
6790 set found 1
6791 break
6792 }
6793 }
6794 if {$found} break
6795 }
6796 } else {
6797 for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6798 if {$l < $arow || $l >= $arowend} {
6799 incr ai $find_dirn
6800 set a [lindex $varcorder($curview) $ai]
6801 set arow [lindex $vrownum($curview) $ai]
6802 set ids [lindex $varccommits($curview,$a)]
6803 set arowend [expr {$arow + [llength $ids]}]
6804 }
6805 set id [lindex $ids [expr {$l - $arow}]]
6806 if {![info exists fhighlights($id)]} {
6807 # this sets fhighlights($id) to -1
6808 askfilehighlight $l $id
6809 }
6810 if {$fhighlights($id) > 0} {
6811 set found $domore
6812 break
6813 }
6814 if {$fhighlights($id) < 0} {
6815 if {$domore} {
6816 set domore 0
6817 set findcurline [expr {$l - $find_dirn}]
6818 }
6819 }
6820 }
6821 }
6822 if {$found || ($domore && !$moretodo)} {
6823 unset findcurline
6824 unset find_dirn
6825 notbusy finding
6826 set fprogcoord 0
6827 adjustprogress
6828 if {$found} {
6829 findselectline $l
6830 } else {
6831 bell
6832 }
6833 return 0
6834 }
6835 if {!$domore} {
6836 flushhighlights
6837 } else {
6838 set findcurline [expr {$l - $find_dirn}]
6839 }
6840 set n [expr {($findcurline - $findstartline) * $find_dirn - 1}]
6841 if {$n < 0} {
6842 incr n $numcommits
6843 }
6844 set fprogcoord [expr {$n * 1.0 / $numcommits}]
6845 adjustprogress
6846 return $domore
6847}
6848
6849proc findselectline {l} {
6850 global findloc commentend ctext findcurline markingmatches gdttype
6851
6852 set markingmatches [expr {$gdttype eq [mc "containing:"]}]
6853 set findcurline $l
6854 selectline $l 1
6855 if {$markingmatches &&
6856 ($findloc eq [mc "All fields"] || $findloc eq [mc "Comments"])} {
6857 # highlight the matches in the comments
6858 set f [$ctext get 1.0 $commentend]
6859 set matches [findmatches $f]
6860 foreach match $matches {
6861 set start [lindex $match 0]
6862 set end [expr {[lindex $match 1] + 1}]
6863 $ctext tag add found "1.0 + $start c" "1.0 + $end c"
6864 }
6865 }
6866 drawvisible
6867}
6868
6869# mark the bits of a headline or author that match a find string
6870proc markmatches {canv l str tag matches font row} {
6871 global selectedline
6872
6873 set bbox [$canv bbox $tag]
6874 set x0 [lindex $bbox 0]
6875 set y0 [lindex $bbox 1]
6876 set y1 [lindex $bbox 3]
6877 foreach match $matches {
6878 set start [lindex $match 0]
6879 set end [lindex $match 1]
6880 if {$start > $end} continue
6881 set xoff [font measure $font [string range $str 0 [expr {$start-1}]]]
6882 set xlen [font measure $font [string range $str 0 [expr {$end}]]]
6883 set t [$canv create rect [expr {$x0+$xoff}] $y0 \
6884 [expr {$x0+$xlen+2}] $y1 \
6885 -outline {} -tags [list match$l matches] -fill yellow]
6886 $canv lower $t
6887 if {$row == $selectedline} {
6888 $canv raise $t secsel
6889 }
6890 }
6891}
6892
6893proc unmarkmatches {} {
6894 global markingmatches
6895
6896 allcanvs delete matches
6897 set markingmatches 0
6898 stopfinding
6899}
6900
6901proc selcanvline {w x y} {
6902 global canv canvy0 ctext linespc
6903 global rowtextx
6904 set ymax [lindex [$canv cget -scrollregion] 3]
6905 if {$ymax == {}} return
6906 set yfrac [lindex [$canv yview] 0]
6907 set y [expr {$y + $yfrac * $ymax}]
6908 set l [expr {int(($y - $canvy0) / $linespc + 0.5)}]
6909 if {$l < 0} {
6910 set l 0
6911 }
6912 if {$w eq $canv} {
6913 set xmax [lindex [$canv cget -scrollregion] 2]
6914 set xleft [expr {[lindex [$canv xview] 0] * $xmax}]
6915 if {![info exists rowtextx($l)] || $xleft + $x < $rowtextx($l)} return
6916 }
6917 unmarkmatches
6918 selectline $l 1
6919}
6920
6921proc commit_descriptor {p} {
6922 global commitinfo
6923 if {![info exists commitinfo($p)]} {
6924 getcommit $p
6925 }
6926 set l "..."
6927 if {[llength $commitinfo($p)] > 1} {
6928 set l [lindex $commitinfo($p) 0]
6929 }
6930 return "$p ($l)\n"
6931}
6932
6933# append some text to the ctext widget, and make any SHA1 ID
6934# that we know about be a clickable link.
6935proc appendwithlinks {text tags} {
6936 global ctext linknum curview
6937
6938 set start [$ctext index "end - 1c"]
6939 $ctext insert end $text $tags
6940 set links [regexp -indices -all -inline {(?:\m|-g)[0-9a-f]{6,40}\M} $text]
6941 foreach l $links {
6942 set s [lindex $l 0]
6943 set e [lindex $l 1]
6944 set linkid [string range $text $s $e]
6945 incr e
6946 $ctext tag delete link$linknum
6947 $ctext tag add link$linknum "$start + $s c" "$start + $e c"
6948 setlink $linkid link$linknum
6949 incr linknum
6950 }
6951}
6952
6953proc setlink {id lk} {
6954 global curview ctext pendinglinks
6955 global linkfgcolor
6956
6957 if {[string range $id 0 1] eq "-g"} {
6958 set id [string range $id 2 end]
6959 }
6960
6961 set known 0
6962 if {[string length $id] < 40} {
6963 set matches [longid $id]
6964 if {[llength $matches] > 0} {
6965 if {[llength $matches] > 1} return
6966 set known 1
6967 set id [lindex $matches 0]
6968 }
6969 } else {
6970 set known [commitinview $id $curview]
6971 }
6972 if {$known} {
6973 $ctext tag conf $lk -foreground $linkfgcolor -underline 1
6974 $ctext tag bind $lk <1> [list selbyid $id]
6975 $ctext tag bind $lk <Enter> {linkcursor %W 1}
6976 $ctext tag bind $lk <Leave> {linkcursor %W -1}
6977 } else {
6978 lappend pendinglinks($id) $lk
6979 interestedin $id {makelink %P}
6980 }
6981}
6982
6983proc appendshortlink {id {pre {}} {post {}}} {
6984 global ctext linknum
6985
6986 $ctext insert end $pre
6987 $ctext tag delete link$linknum
6988 $ctext insert end [string range $id 0 7] link$linknum
6989 $ctext insert end $post
6990 setlink $id link$linknum
6991 incr linknum
6992}
6993
6994proc makelink {id} {
6995 global pendinglinks
6996
6997 if {![info exists pendinglinks($id)]} return
6998 foreach lk $pendinglinks($id) {
6999 setlink $id $lk
7000 }
7001 unset pendinglinks($id)
7002}
7003
7004proc linkcursor {w inc} {
7005 global linkentercount curtextcursor
7006
7007 if {[incr linkentercount $inc] > 0} {
7008 $w configure -cursor hand2
7009 } else {
7010 $w configure -cursor $curtextcursor
7011 if {$linkentercount < 0} {
7012 set linkentercount 0
7013 }
7014 }
7015}
7016
7017proc viewnextline {dir} {
7018 global canv linespc
7019
7020 $canv delete hover
7021 set ymax [lindex [$canv cget -scrollregion] 3]
7022 set wnow [$canv yview]
7023 set wtop [expr {[lindex $wnow 0] * $ymax}]
7024 set newtop [expr {$wtop + $dir * $linespc}]
7025 if {$newtop < 0} {
7026 set newtop 0
7027 } elseif {$newtop > $ymax} {
7028 set newtop $ymax
7029 }
7030 allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7031}
7032
7033# add a list of tag or branch names at position pos
7034# returns the number of names inserted
7035proc appendrefs {pos ids var} {
7036 global ctext linknum curview $var maxrefs mainheadid
7037
7038 if {[catch {$ctext index $pos}]} {
7039 return 0
7040 }
7041 $ctext conf -state normal
7042 $ctext delete $pos "$pos lineend"
7043 set tags {}
7044 foreach id $ids {
7045 foreach tag [set $var\($id\)] {
7046 lappend tags [list $tag $id]
7047 }
7048 }
7049
7050 set sep {}
7051 set tags [lsort -index 0 -decreasing $tags]
7052 set nutags 0
7053
7054 if {[llength $tags] > $maxrefs} {
7055 # If we are displaying heads, and there are too many,
7056 # see if there are some important heads to display.
7057 # Currently this means "master" and the current head.
7058 set itags {}
7059 if {$var eq "idheads"} {
7060 set utags {}
7061 foreach ti $tags {
7062 set hname [lindex $ti 0]
7063 set id [lindex $ti 1]
7064 if {($hname eq "master" || $id eq $mainheadid) &&
7065 [llength $itags] < $maxrefs} {
7066 lappend itags $ti
7067 } else {
7068 lappend utags $ti
7069 }
7070 }
7071 set tags $utags
7072 }
7073 if {$itags ne {}} {
7074 set str [mc "and many more"]
7075 set sep " "
7076 } else {
7077 set str [mc "many"]
7078 }
7079 $ctext insert $pos "$str ([llength $tags])"
7080 set nutags [llength $tags]
7081 set tags $itags
7082 }
7083
7084 foreach ti $tags {
7085 set id [lindex $ti 1]
7086 set lk link$linknum
7087 incr linknum
7088 $ctext tag delete $lk
7089 $ctext insert $pos $sep
7090 $ctext insert $pos [lindex $ti 0] $lk
7091 setlink $id $lk
7092 set sep ", "
7093 }
7094 $ctext tag add wwrap "$pos linestart" "$pos lineend"
7095 $ctext conf -state disabled
7096 return [expr {[llength $tags] + $nutags}]
7097}
7098
7099# called when we have finished computing the nearby tags
7100proc dispneartags {delay} {
7101 global selectedline currentid showneartags tagphase
7102
7103 if {$selectedline eq {} || !$showneartags} return
7104 after cancel dispnexttag
7105 if {$delay} {
7106 after 200 dispnexttag
7107 set tagphase -1
7108 } else {
7109 after idle dispnexttag
7110 set tagphase 0
7111 }
7112}
7113
7114proc dispnexttag {} {
7115 global selectedline currentid showneartags tagphase ctext
7116
7117 if {$selectedline eq {} || !$showneartags} return
7118 switch -- $tagphase {
7119 0 {
7120 set dtags [desctags $currentid]
7121 if {$dtags ne {}} {
7122 appendrefs precedes $dtags idtags
7123 }
7124 }
7125 1 {
7126 set atags [anctags $currentid]
7127 if {$atags ne {}} {
7128 appendrefs follows $atags idtags
7129 }
7130 }
7131 2 {
7132 set dheads [descheads $currentid]
7133 if {$dheads ne {}} {
7134 if {[appendrefs branch $dheads idheads] > 1
7135 && [$ctext get "branch -3c"] eq "h"} {
7136 # turn "Branch" into "Branches"
7137 $ctext conf -state normal
7138 $ctext insert "branch -2c" "es"
7139 $ctext conf -state disabled
7140 }
7141 }
7142 }
7143 }
7144 if {[incr tagphase] <= 2} {
7145 after idle dispnexttag
7146 }
7147}
7148
7149proc make_secsel {id} {
7150 global linehtag linentag linedtag canv canv2 canv3
7151
7152 if {![info exists linehtag($id)]} return
7153 $canv delete secsel
7154 set t [eval $canv create rect [$canv bbox $linehtag($id)] -outline {{}} \
7155 -tags secsel -fill [$canv cget -selectbackground]]
7156 $canv lower $t
7157 $canv2 delete secsel
7158 set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] -outline {{}} \
7159 -tags secsel -fill [$canv2 cget -selectbackground]]
7160 $canv2 lower $t
7161 $canv3 delete secsel
7162 set t [eval $canv3 create rect [$canv3 bbox $linedtag($id)] -outline {{}} \
7163 -tags secsel -fill [$canv3 cget -selectbackground]]
7164 $canv3 lower $t
7165}
7166
7167proc make_idmark {id} {
7168 global linehtag canv fgcolor
7169
7170 if {![info exists linehtag($id)]} return
7171 $canv delete markid
7172 set t [eval $canv create rect [$canv bbox $linehtag($id)] \
7173 -tags markid -outline $fgcolor]
7174 $canv raise $t
7175}
7176
7177proc selectline {l isnew {desired_loc {}} {switch_to_patch 0}} {
7178 global canv ctext commitinfo selectedline
7179 global canvy0 linespc parents children curview
7180 global currentid sha1entry
7181 global commentend idtags linknum
7182 global mergemax numcommits pending_select
7183 global cmitmode showneartags allcommits
7184 global targetrow targetid lastscrollrows
7185 global autoselect autosellen jump_to_here
7186 global vinlinediff
7187
7188 catch {unset pending_select}
7189 $canv delete hover
7190 normalline
7191 unsel_reflist
7192 stopfinding
7193 if {$l < 0 || $l >= $numcommits} return
7194 set id [commitonrow $l]
7195 set targetid $id
7196 set targetrow $l
7197 set selectedline $l
7198 set currentid $id
7199 if {$lastscrollrows < $numcommits} {
7200 setcanvscroll
7201 }
7202
7203 if {$cmitmode ne "patch" && $switch_to_patch} {
7204 set cmitmode "patch"
7205 }
7206
7207 set y [expr {$canvy0 + $l * $linespc}]
7208 set ymax [lindex [$canv cget -scrollregion] 3]
7209 set ytop [expr {$y - $linespc - 1}]
7210 set ybot [expr {$y + $linespc + 1}]
7211 set wnow [$canv yview]
7212 set wtop [expr {[lindex $wnow 0] * $ymax}]
7213 set wbot [expr {[lindex $wnow 1] * $ymax}]
7214 set wh [expr {$wbot - $wtop}]
7215 set newtop $wtop
7216 if {$ytop < $wtop} {
7217 if {$ybot < $wtop} {
7218 set newtop [expr {$y - $wh / 2.0}]
7219 } else {
7220 set newtop $ytop
7221 if {$newtop > $wtop - $linespc} {
7222 set newtop [expr {$wtop - $linespc}]
7223 }
7224 }
7225 } elseif {$ybot > $wbot} {
7226 if {$ytop > $wbot} {
7227 set newtop [expr {$y - $wh / 2.0}]
7228 } else {
7229 set newtop [expr {$ybot - $wh}]
7230 if {$newtop < $wtop + $linespc} {
7231 set newtop [expr {$wtop + $linespc}]
7232 }
7233 }
7234 }
7235 if {$newtop != $wtop} {
7236 if {$newtop < 0} {
7237 set newtop 0
7238 }
7239 allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7240 drawvisible
7241 }
7242
7243 make_secsel $id
7244
7245 if {$isnew} {
7246 addtohistory [list selbyid $id 0] savecmitpos
7247 }
7248
7249 $sha1entry delete 0 end
7250 $sha1entry insert 0 $id
7251 if {$autoselect} {
7252 $sha1entry selection range 0 $autosellen
7253 }
7254 rhighlight_sel $id
7255
7256 $ctext conf -state normal
7257 clear_ctext
7258 set linknum 0
7259 if {![info exists commitinfo($id)]} {
7260 getcommit $id
7261 }
7262 set info $commitinfo($id)
7263 set date [formatdate [lindex $info 2]]
7264 $ctext insert end "[mc "Author"]: [lindex $info 1] $date\n"
7265 set date [formatdate [lindex $info 4]]
7266 $ctext insert end "[mc "Committer"]: [lindex $info 3] $date\n"
7267 if {[info exists idtags($id)]} {
7268 $ctext insert end [mc "Tags:"]
7269 foreach tag $idtags($id) {
7270 $ctext insert end " $tag"
7271 }
7272 $ctext insert end "\n"
7273 }
7274
7275 set headers {}
7276 set olds $parents($curview,$id)
7277 if {[llength $olds] > 1} {
7278 set np 0
7279 foreach p $olds {
7280 if {$np >= $mergemax} {
7281 set tag mmax
7282 } else {
7283 set tag m$np
7284 }
7285 $ctext insert end "[mc "Parent"]: " $tag
7286 appendwithlinks [commit_descriptor $p] {}
7287 incr np
7288 }
7289 } else {
7290 foreach p $olds {
7291 append headers "[mc "Parent"]: [commit_descriptor $p]"
7292 }
7293 }
7294
7295 foreach c $children($curview,$id) {
7296 append headers "[mc "Child"]: [commit_descriptor $c]"
7297 }
7298
7299 # make anything that looks like a SHA1 ID be a clickable link
7300 appendwithlinks $headers {}
7301 if {$showneartags} {
7302 if {![info exists allcommits]} {
7303 getallcommits
7304 }
7305 $ctext insert end "[mc "Branch"]: "
7306 $ctext mark set branch "end -1c"
7307 $ctext mark gravity branch left
7308 $ctext insert end "\n[mc "Follows"]: "
7309 $ctext mark set follows "end -1c"
7310 $ctext mark gravity follows left
7311 $ctext insert end "\n[mc "Precedes"]: "
7312 $ctext mark set precedes "end -1c"
7313 $ctext mark gravity precedes left
7314 $ctext insert end "\n"
7315 dispneartags 1
7316 }
7317 $ctext insert end "\n"
7318 set comment [lindex $info 5]
7319 if {[string first "\r" $comment] >= 0} {
7320 set comment [string map {"\r" "\n "} $comment]
7321 }
7322 appendwithlinks $comment {comment}
7323
7324 $ctext tag remove found 1.0 end
7325 $ctext conf -state disabled
7326 set commentend [$ctext index "end - 1c"]
7327
7328 set jump_to_here $desired_loc
7329 init_flist [mc "Comments"]
7330 if {$cmitmode eq "tree"} {
7331 gettree $id
7332 } elseif {$vinlinediff($curview) == 1} {
7333 showinlinediff $id
7334 } elseif {[llength $olds] <= 1} {
7335 startdiff $id
7336 } else {
7337 mergediff $id
7338 }
7339}
7340
7341proc selfirstline {} {
7342 unmarkmatches
7343 selectline 0 1
7344}
7345
7346proc sellastline {} {
7347 global numcommits
7348 unmarkmatches
7349 set l [expr {$numcommits - 1}]
7350 selectline $l 1
7351}
7352
7353proc selnextline {dir} {
7354 global selectedline
7355 focus .
7356 if {$selectedline eq {}} return
7357 set l [expr {$selectedline + $dir}]
7358 unmarkmatches
7359 selectline $l 1
7360}
7361
7362proc selnextpage {dir} {
7363 global canv linespc selectedline numcommits
7364
7365 set lpp [expr {([winfo height $canv] - 2) / $linespc}]
7366 if {$lpp < 1} {
7367 set lpp 1
7368 }
7369 allcanvs yview scroll [expr {$dir * $lpp}] units
7370 drawvisible
7371 if {$selectedline eq {}} return
7372 set l [expr {$selectedline + $dir * $lpp}]
7373 if {$l < 0} {
7374 set l 0
7375 } elseif {$l >= $numcommits} {
7376 set l [expr $numcommits - 1]
7377 }
7378 unmarkmatches
7379 selectline $l 1
7380}
7381
7382proc unselectline {} {
7383 global selectedline currentid
7384
7385 set selectedline {}
7386 catch {unset currentid}
7387 allcanvs delete secsel
7388 rhighlight_none
7389}
7390
7391proc reselectline {} {
7392 global selectedline
7393
7394 if {$selectedline ne {}} {
7395 selectline $selectedline 0
7396 }
7397}
7398
7399proc addtohistory {cmd {saveproc {}}} {
7400 global history historyindex curview
7401
7402 unset_posvars
7403 save_position
7404 set elt [list $curview $cmd $saveproc {}]
7405 if {$historyindex > 0
7406 && [lindex $history [expr {$historyindex - 1}]] == $elt} {
7407 return
7408 }
7409
7410 if {$historyindex < [llength $history]} {
7411 set history [lreplace $history $historyindex end $elt]
7412 } else {
7413 lappend history $elt
7414 }
7415 incr historyindex
7416 if {$historyindex > 1} {
7417 .tf.bar.leftbut conf -state normal
7418 } else {
7419 .tf.bar.leftbut conf -state disabled
7420 }
7421 .tf.bar.rightbut conf -state disabled
7422}
7423
7424# save the scrolling position of the diff display pane
7425proc save_position {} {
7426 global historyindex history
7427
7428 if {$historyindex < 1} return
7429 set hi [expr {$historyindex - 1}]
7430 set fn [lindex $history $hi 2]
7431 if {$fn ne {}} {
7432 lset history $hi 3 [eval $fn]
7433 }
7434}
7435
7436proc unset_posvars {} {
7437 global last_posvars
7438
7439 if {[info exists last_posvars]} {
7440 foreach {var val} $last_posvars {
7441 global $var
7442 catch {unset $var}
7443 }
7444 unset last_posvars
7445 }
7446}
7447
7448proc godo {elt} {
7449 global curview last_posvars
7450
7451 set view [lindex $elt 0]
7452 set cmd [lindex $elt 1]
7453 set pv [lindex $elt 3]
7454 if {$curview != $view} {
7455 showview $view
7456 }
7457 unset_posvars
7458 foreach {var val} $pv {
7459 global $var
7460 set $var $val
7461 }
7462 set last_posvars $pv
7463 eval $cmd
7464}
7465
7466proc goback {} {
7467 global history historyindex
7468 focus .
7469
7470 if {$historyindex > 1} {
7471 save_position
7472 incr historyindex -1
7473 godo [lindex $history [expr {$historyindex - 1}]]
7474 .tf.bar.rightbut conf -state normal
7475 }
7476 if {$historyindex <= 1} {
7477 .tf.bar.leftbut conf -state disabled
7478 }
7479}
7480
7481proc goforw {} {
7482 global history historyindex
7483 focus .
7484
7485 if {$historyindex < [llength $history]} {
7486 save_position
7487 set cmd [lindex $history $historyindex]
7488 incr historyindex
7489 godo $cmd
7490 .tf.bar.leftbut conf -state normal
7491 }
7492 if {$historyindex >= [llength $history]} {
7493 .tf.bar.rightbut conf -state disabled
7494 }
7495}
7496
7497proc gettree {id} {
7498 global treefilelist treeidlist diffids diffmergeid treepending
7499 global nullid nullid2
7500
7501 set diffids $id
7502 catch {unset diffmergeid}
7503 if {![info exists treefilelist($id)]} {
7504 if {![info exists treepending]} {
7505 if {$id eq $nullid} {
7506 set cmd [list | git ls-files]
7507 } elseif {$id eq $nullid2} {
7508 set cmd [list | git ls-files --stage -t]
7509 } else {
7510 set cmd [list | git ls-tree -r $id]
7511 }
7512 if {[catch {set gtf [open $cmd r]}]} {
7513 return
7514 }
7515 set treepending $id
7516 set treefilelist($id) {}
7517 set treeidlist($id) {}
7518 fconfigure $gtf -blocking 0 -encoding binary
7519 filerun $gtf [list gettreeline $gtf $id]
7520 }
7521 } else {
7522 setfilelist $id
7523 }
7524}
7525
7526proc gettreeline {gtf id} {
7527 global treefilelist treeidlist treepending cmitmode diffids nullid nullid2
7528
7529 set nl 0
7530 while {[incr nl] <= 1000 && [gets $gtf line] >= 0} {
7531 if {$diffids eq $nullid} {
7532 set fname $line
7533 } else {
7534 set i [string first "\t" $line]
7535 if {$i < 0} continue
7536 set fname [string range $line [expr {$i+1}] end]
7537 set line [string range $line 0 [expr {$i-1}]]
7538 if {$diffids ne $nullid2 && [lindex $line 1] ne "blob"} continue
7539 set sha1 [lindex $line 2]
7540 lappend treeidlist($id) $sha1
7541 }
7542 if {[string index $fname 0] eq "\""} {
7543 set fname [lindex $fname 0]
7544 }
7545 set fname [encoding convertfrom $fname]
7546 lappend treefilelist($id) $fname
7547 }
7548 if {![eof $gtf]} {
7549 return [expr {$nl >= 1000? 2: 1}]
7550 }
7551 close $gtf
7552 unset treepending
7553 if {$cmitmode ne "tree"} {
7554 if {![info exists diffmergeid]} {
7555 gettreediffs $diffids
7556 }
7557 } elseif {$id ne $diffids} {
7558 gettree $diffids
7559 } else {
7560 setfilelist $id
7561 }
7562 return 0
7563}
7564
7565proc showfile {f} {
7566 global treefilelist treeidlist diffids nullid nullid2
7567 global ctext_file_names ctext_file_lines
7568 global ctext commentend
7569
7570 set i [lsearch -exact $treefilelist($diffids) $f]
7571 if {$i < 0} {
7572 puts "oops, $f not in list for id $diffids"
7573 return
7574 }
7575 if {$diffids eq $nullid} {
7576 if {[catch {set bf [open $f r]} err]} {
7577 puts "oops, can't read $f: $err"
7578 return
7579 }
7580 } else {
7581 set blob [lindex $treeidlist($diffids) $i]
7582 if {[catch {set bf [open [concat | git cat-file blob $blob] r]} err]} {
7583 puts "oops, error reading blob $blob: $err"
7584 return
7585 }
7586 }
7587 fconfigure $bf -blocking 0 -encoding [get_path_encoding $f]
7588 filerun $bf [list getblobline $bf $diffids]
7589 $ctext config -state normal
7590 clear_ctext $commentend
7591 lappend ctext_file_names $f
7592 lappend ctext_file_lines [lindex [split $commentend "."] 0]
7593 $ctext insert end "\n"
7594 $ctext insert end "$f\n" filesep
7595 $ctext config -state disabled
7596 $ctext yview $commentend
7597 settabs 0
7598}
7599
7600proc getblobline {bf id} {
7601 global diffids cmitmode ctext
7602
7603 if {$id ne $diffids || $cmitmode ne "tree"} {
7604 catch {close $bf}
7605 return 0
7606 }
7607 $ctext config -state normal
7608 set nl 0
7609 while {[incr nl] <= 1000 && [gets $bf line] >= 0} {
7610 $ctext insert end "$line\n"
7611 }
7612 if {[eof $bf]} {
7613 global jump_to_here ctext_file_names commentend
7614
7615 # delete last newline
7616 $ctext delete "end - 2c" "end - 1c"
7617 close $bf
7618 if {$jump_to_here ne {} &&
7619 [lindex $jump_to_here 0] eq [lindex $ctext_file_names 0]} {
7620 set lnum [expr {[lindex $jump_to_here 1] +
7621 [lindex [split $commentend .] 0]}]
7622 mark_ctext_line $lnum
7623 }
7624 $ctext config -state disabled
7625 return 0
7626 }
7627 $ctext config -state disabled
7628 return [expr {$nl >= 1000? 2: 1}]
7629}
7630
7631proc mark_ctext_line {lnum} {
7632 global ctext markbgcolor
7633
7634 $ctext tag delete omark
7635 $ctext tag add omark $lnum.0 "$lnum.0 + 1 line"
7636 $ctext tag conf omark -background $markbgcolor
7637 $ctext see $lnum.0
7638}
7639
7640proc mergediff {id} {
7641 global diffmergeid
7642 global diffids treediffs
7643 global parents curview
7644
7645 set diffmergeid $id
7646 set diffids $id
7647 set treediffs($id) {}
7648 set np [llength $parents($curview,$id)]
7649 settabs $np
7650 getblobdiffs $id
7651}
7652
7653proc startdiff {ids} {
7654 global treediffs diffids treepending diffmergeid nullid nullid2
7655
7656 settabs 1
7657 set diffids $ids
7658 catch {unset diffmergeid}
7659 if {![info exists treediffs($ids)] ||
7660 [lsearch -exact $ids $nullid] >= 0 ||
7661 [lsearch -exact $ids $nullid2] >= 0} {
7662 if {![info exists treepending]} {
7663 gettreediffs $ids
7664 }
7665 } else {
7666 addtocflist $ids
7667 }
7668}
7669
7670proc showinlinediff {ids} {
7671 global commitinfo commitdata ctext
7672 global treediffs
7673
7674 set info $commitinfo($ids)
7675 set diff [lindex $info 7]
7676 set difflines [split $diff "\n"]
7677
7678 initblobdiffvars
7679 set treediff {}
7680
7681 set inhdr 0
7682 foreach line $difflines {
7683 if {![string compare -length 5 "diff " $line]} {
7684 set inhdr 1
7685 } elseif {$inhdr && ![string compare -length 4 "+++ " $line]} {
7686 # offset also accounts for the b/ prefix
7687 lappend treediff [string range $line 6 end]
7688 set inhdr 0
7689 }
7690 }
7691
7692 set treediffs($ids) $treediff
7693 add_flist $treediff
7694
7695 $ctext conf -state normal
7696 foreach line $difflines {
7697 parseblobdiffline $ids $line
7698 }
7699 maybe_scroll_ctext 1
7700 $ctext conf -state disabled
7701}
7702
7703# If the filename (name) is under any of the passed filter paths
7704# then return true to include the file in the listing.
7705proc path_filter {filter name} {
7706 set worktree [gitworktree]
7707 foreach p $filter {
7708 set fq_p [file normalize $p]
7709 set fq_n [file normalize [file join $worktree $name]]
7710 if {[string match [file normalize $fq_p]* $fq_n]} {
7711 return 1
7712 }
7713 }
7714 return 0
7715}
7716
7717proc addtocflist {ids} {
7718 global treediffs
7719
7720 add_flist $treediffs($ids)
7721 getblobdiffs $ids
7722}
7723
7724proc diffcmd {ids flags} {
7725 global log_showroot nullid nullid2 git_version
7726
7727 set i [lsearch -exact $ids $nullid]
7728 set j [lsearch -exact $ids $nullid2]
7729 if {$i >= 0} {
7730 if {[llength $ids] > 1 && $j < 0} {
7731 # comparing working directory with some specific revision
7732 set cmd [concat | git diff-index $flags]
7733 if {$i == 0} {
7734 lappend cmd -R [lindex $ids 1]
7735 } else {
7736 lappend cmd [lindex $ids 0]
7737 }
7738 } else {
7739 # comparing working directory with index
7740 set cmd [concat | git diff-files $flags]
7741 if {$j == 1} {
7742 lappend cmd -R
7743 }
7744 }
7745 } elseif {$j >= 0} {
7746 if {[package vcompare $git_version "1.7.2"] >= 0} {
7747 set flags "$flags --ignore-submodules=dirty"
7748 }
7749 set cmd [concat | git diff-index --cached $flags]
7750 if {[llength $ids] > 1} {
7751 # comparing index with specific revision
7752 if {$j == 0} {
7753 lappend cmd -R [lindex $ids 1]
7754 } else {
7755 lappend cmd [lindex $ids 0]
7756 }
7757 } else {
7758 # comparing index with HEAD
7759 lappend cmd HEAD
7760 }
7761 } else {
7762 if {$log_showroot} {
7763 lappend flags --root
7764 }
7765 set cmd [concat | git diff-tree -r $flags $ids]
7766 }
7767 return $cmd
7768}
7769
7770proc gettreediffs {ids} {
7771 global treediff treepending limitdiffs vfilelimit curview
7772
7773 set cmd [diffcmd $ids {--no-commit-id}]
7774 if {$limitdiffs && $vfilelimit($curview) ne {}} {
7775 set cmd [concat $cmd -- $vfilelimit($curview)]
7776 }
7777 if {[catch {set gdtf [open $cmd r]}]} return
7778
7779 set treepending $ids
7780 set treediff {}
7781 fconfigure $gdtf -blocking 0 -encoding binary
7782 filerun $gdtf [list gettreediffline $gdtf $ids]
7783}
7784
7785proc gettreediffline {gdtf ids} {
7786 global treediff treediffs treepending diffids diffmergeid
7787 global cmitmode vfilelimit curview limitdiffs perfile_attrs
7788
7789 set nr 0
7790 set sublist {}
7791 set max 1000
7792 if {$perfile_attrs} {
7793 # cache_gitattr is slow, and even slower on win32 where we
7794 # have to invoke it for only about 30 paths at a time
7795 set max 500
7796 if {[tk windowingsystem] == "win32"} {
7797 set max 120
7798 }
7799 }
7800 while {[incr nr] <= $max && [gets $gdtf line] >= 0} {
7801 set i [string first "\t" $line]
7802 if {$i >= 0} {
7803 set file [string range $line [expr {$i+1}] end]
7804 if {[string index $file 0] eq "\""} {
7805 set file [lindex $file 0]
7806 }
7807 set file [encoding convertfrom $file]
7808 if {$file ne [lindex $treediff end]} {
7809 lappend treediff $file
7810 lappend sublist $file
7811 }
7812 }
7813 }
7814 if {$perfile_attrs} {
7815 cache_gitattr encoding $sublist
7816 }
7817 if {![eof $gdtf]} {
7818 return [expr {$nr >= $max? 2: 1}]
7819 }
7820 close $gdtf
7821 set treediffs($ids) $treediff
7822 unset treepending
7823 if {$cmitmode eq "tree" && [llength $diffids] == 1} {
7824 gettree $diffids
7825 } elseif {$ids != $diffids} {
7826 if {![info exists diffmergeid]} {
7827 gettreediffs $diffids
7828 }
7829 } else {
7830 addtocflist $ids
7831 }
7832 return 0
7833}
7834
7835# empty string or positive integer
7836proc diffcontextvalidate {v} {
7837 return [regexp {^(|[1-9][0-9]*)$} $v]
7838}
7839
7840proc diffcontextchange {n1 n2 op} {
7841 global diffcontextstring diffcontext
7842
7843 if {[string is integer -strict $diffcontextstring]} {
7844 if {$diffcontextstring >= 0} {
7845 set diffcontext $diffcontextstring
7846 reselectline
7847 }
7848 }
7849}
7850
7851proc changeignorespace {} {
7852 reselectline
7853}
7854
7855proc changeworddiff {name ix op} {
7856 reselectline
7857}
7858
7859proc initblobdiffvars {} {
7860 global diffencoding targetline diffnparents
7861 global diffinhdr currdiffsubmod diffseehere
7862 set targetline {}
7863 set diffnparents 0
7864 set diffinhdr 0
7865 set diffencoding [get_path_encoding {}]
7866 set currdiffsubmod ""
7867 set diffseehere -1
7868}
7869
7870proc getblobdiffs {ids} {
7871 global blobdifffd diffids env
7872 global treediffs
7873 global diffcontext
7874 global ignorespace
7875 global worddiff
7876 global limitdiffs vfilelimit curview
7877 global git_version
7878
7879 set textconv {}
7880 if {[package vcompare $git_version "1.6.1"] >= 0} {
7881 set textconv "--textconv"
7882 }
7883 set submodule {}
7884 if {[package vcompare $git_version "1.6.6"] >= 0} {
7885 set submodule "--submodule"
7886 }
7887 set cmd [diffcmd $ids "-p $textconv $submodule -C --cc --no-commit-id -U$diffcontext"]
7888 if {$ignorespace} {
7889 append cmd " -w"
7890 }
7891 if {$worddiff ne [mc "Line diff"]} {
7892 append cmd " --word-diff=porcelain"
7893 }
7894 if {$limitdiffs && $vfilelimit($curview) ne {}} {
7895 set cmd [concat $cmd -- $vfilelimit($curview)]
7896 }
7897 if {[catch {set bdf [open $cmd r]} err]} {
7898 error_popup [mc "Error getting diffs: %s" $err]
7899 return
7900 }
7901 fconfigure $bdf -blocking 0 -encoding binary -eofchar {}
7902 set blobdifffd($ids) $bdf
7903 initblobdiffvars
7904 filerun $bdf [list getblobdiffline $bdf $diffids]
7905}
7906
7907proc savecmitpos {} {
7908 global ctext cmitmode
7909
7910 if {$cmitmode eq "tree"} {
7911 return {}
7912 }
7913 return [list target_scrollpos [$ctext index @0,0]]
7914}
7915
7916proc savectextpos {} {
7917 global ctext
7918
7919 return [list target_scrollpos [$ctext index @0,0]]
7920}
7921
7922proc maybe_scroll_ctext {ateof} {
7923 global ctext target_scrollpos
7924
7925 if {![info exists target_scrollpos]} return
7926 if {!$ateof} {
7927 set nlines [expr {[winfo height $ctext]
7928 / [font metrics textfont -linespace]}]
7929 if {[$ctext compare "$target_scrollpos + $nlines lines" <= end]} return
7930 }
7931 $ctext yview $target_scrollpos
7932 unset target_scrollpos
7933}
7934
7935proc setinlist {var i val} {
7936 global $var
7937
7938 while {[llength [set $var]] < $i} {
7939 lappend $var {}
7940 }
7941 if {[llength [set $var]] == $i} {
7942 lappend $var $val
7943 } else {
7944 lset $var $i $val
7945 }
7946}
7947
7948proc makediffhdr {fname ids} {
7949 global ctext curdiffstart treediffs diffencoding
7950 global ctext_file_names jump_to_here targetline diffline
7951
7952 set fname [encoding convertfrom $fname]
7953 set diffencoding [get_path_encoding $fname]
7954 set i [lsearch -exact $treediffs($ids) $fname]
7955 if {$i >= 0} {
7956 setinlist difffilestart $i $curdiffstart
7957 }
7958 lset ctext_file_names end $fname
7959 set l [expr {(78 - [string length $fname]) / 2}]
7960 set pad [string range "----------------------------------------" 1 $l]
7961 $ctext insert $curdiffstart "$pad $fname $pad" filesep
7962 set targetline {}
7963 if {$jump_to_here ne {} && [lindex $jump_to_here 0] eq $fname} {
7964 set targetline [lindex $jump_to_here 1]
7965 }
7966 set diffline 0
7967}
7968
7969proc blobdiffmaybeseehere {ateof} {
7970 global diffseehere
7971 if {$diffseehere >= 0} {
7972 mark_ctext_line [lindex [split $diffseehere .] 0]
7973 }
7974 maybe_scroll_ctext $ateof
7975}
7976
7977proc getblobdiffline {bdf ids} {
7978 global diffids blobdifffd
7979 global ctext
7980
7981 set nr 0
7982 $ctext conf -state normal
7983 while {[incr nr] <= 1000 && [gets $bdf line] >= 0} {
7984 if {$ids != $diffids || $bdf != $blobdifffd($ids)} {
7985 catch {close $bdf}
7986 return 0
7987 }
7988 parseblobdiffline $ids $line
7989 }
7990 $ctext conf -state disabled
7991 blobdiffmaybeseehere [eof $bdf]
7992 if {[eof $bdf]} {
7993 catch {close $bdf}
7994 return 0
7995 }
7996 return [expr {$nr >= 1000? 2: 1}]
7997}
7998
7999proc parseblobdiffline {ids line} {
8000 global ctext curdiffstart
8001 global diffnexthead diffnextnote difffilestart
8002 global ctext_file_names ctext_file_lines
8003 global diffinhdr treediffs mergemax diffnparents
8004 global diffencoding jump_to_here targetline diffline currdiffsubmod
8005 global worddiff diffseehere
8006
8007 if {![string compare -length 5 "diff " $line]} {
8008 if {![regexp {^diff (--cc|--git) } $line m type]} {
8009 set line [encoding convertfrom $line]
8010 $ctext insert end "$line\n" hunksep
8011 continue
8012 }
8013 # start of a new file
8014 set diffinhdr 1
8015 $ctext insert end "\n"
8016 set curdiffstart [$ctext index "end - 1c"]
8017 lappend ctext_file_names ""
8018 lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8019 $ctext insert end "\n" filesep
8020
8021 if {$type eq "--cc"} {
8022 # start of a new file in a merge diff
8023 set fname [string range $line 10 end]
8024 if {[lsearch -exact $treediffs($ids) $fname] < 0} {
8025 lappend treediffs($ids) $fname
8026 add_flist [list $fname]
8027 }
8028
8029 } else {
8030 set line [string range $line 11 end]
8031 # If the name hasn't changed the length will be odd,
8032 # the middle char will be a space, and the two bits either
8033 # side will be a/name and b/name, or "a/name" and "b/name".
8034 # If the name has changed we'll get "rename from" and
8035 # "rename to" or "copy from" and "copy to" lines following
8036 # this, and we'll use them to get the filenames.
8037 # This complexity is necessary because spaces in the
8038 # filename(s) don't get escaped.
8039 set l [string length $line]
8040 set i [expr {$l / 2}]
8041 if {!(($l & 1) && [string index $line $i] eq " " &&
8042 [string range $line 2 [expr {$i - 1}]] eq \
8043 [string range $line [expr {$i + 3}] end])} {
8044 return
8045 }
8046 # unescape if quoted and chop off the a/ from the front
8047 if {[string index $line 0] eq "\""} {
8048 set fname [string range [lindex $line 0] 2 end]
8049 } else {
8050 set fname [string range $line 2 [expr {$i - 1}]]
8051 }
8052 }
8053 makediffhdr $fname $ids
8054
8055 } elseif {![string compare -length 16 "* Unmerged path " $line]} {
8056 set fname [encoding convertfrom [string range $line 16 end]]
8057 $ctext insert end "\n"
8058 set curdiffstart [$ctext index "end - 1c"]
8059 lappend ctext_file_names $fname
8060 lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8061 $ctext insert end "$line\n" filesep
8062 set i [lsearch -exact $treediffs($ids) $fname]
8063 if {$i >= 0} {
8064 setinlist difffilestart $i $curdiffstart
8065 }
8066
8067 } elseif {![string compare -length 2 "@@" $line]} {
8068 regexp {^@@+} $line ats
8069 set line [encoding convertfrom $diffencoding $line]
8070 $ctext insert end "$line\n" hunksep
8071 if {[regexp { \+(\d+),\d+ @@} $line m nl]} {
8072 set diffline $nl
8073 }
8074 set diffnparents [expr {[string length $ats] - 1}]
8075 set diffinhdr 0
8076
8077 } elseif {![string compare -length 10 "Submodule " $line]} {
8078 # start of a new submodule
8079 if {[regexp -indices "\[0-9a-f\]+\\.\\." $line nameend]} {
8080 set fname [string range $line 10 [expr [lindex $nameend 0] - 2]]
8081 } else {
8082 set fname [string range $line 10 [expr [string first "contains " $line] - 2]]
8083 }
8084 if {$currdiffsubmod != $fname} {
8085 $ctext insert end "\n"; # Add newline after commit message
8086 }
8087 set curdiffstart [$ctext index "end - 1c"]
8088 lappend ctext_file_names ""
8089 if {$currdiffsubmod != $fname} {
8090 lappend ctext_file_lines $fname
8091 makediffhdr $fname $ids
8092 set currdiffsubmod $fname
8093 $ctext insert end "\n$line\n" filesep
8094 } else {
8095 $ctext insert end "$line\n" filesep
8096 }
8097 } elseif {![string compare -length 3 " >" $line]} {
8098 set $currdiffsubmod ""
8099 set line [encoding convertfrom $diffencoding $line]
8100 $ctext insert end "$line\n" dresult
8101 } elseif {![string compare -length 3 " <" $line]} {
8102 set $currdiffsubmod ""
8103 set line [encoding convertfrom $diffencoding $line]
8104 $ctext insert end "$line\n" d0
8105 } elseif {$diffinhdr} {
8106 if {![string compare -length 12 "rename from " $line]} {
8107 set fname [string range $line [expr 6 + [string first " from " $line] ] end]
8108 if {[string index $fname 0] eq "\""} {
8109 set fname [lindex $fname 0]
8110 }
8111 set fname [encoding convertfrom $fname]
8112 set i [lsearch -exact $treediffs($ids) $fname]
8113 if {$i >= 0} {
8114 setinlist difffilestart $i $curdiffstart
8115 }
8116 } elseif {![string compare -length 10 $line "rename to "] ||
8117 ![string compare -length 8 $line "copy to "]} {
8118 set fname [string range $line [expr 4 + [string first " to " $line] ] end]
8119 if {[string index $fname 0] eq "\""} {
8120 set fname [lindex $fname 0]
8121 }
8122 makediffhdr $fname $ids
8123 } elseif {[string compare -length 3 $line "---"] == 0} {
8124 # do nothing
8125 return
8126 } elseif {[string compare -length 3 $line "+++"] == 0} {
8127 set diffinhdr 0
8128 return
8129 }
8130 $ctext insert end "$line\n" filesep
8131
8132 } else {
8133 set line [string map {\x1A ^Z} \
8134 [encoding convertfrom $diffencoding $line]]
8135 # parse the prefix - one ' ', '-' or '+' for each parent
8136 set prefix [string range $line 0 [expr {$diffnparents - 1}]]
8137 set tag [expr {$diffnparents > 1? "m": "d"}]
8138 set dowords [expr {$worddiff ne [mc "Line diff"] && $diffnparents == 1}]
8139 set words_pre_markup ""
8140 set words_post_markup ""
8141 if {[string trim $prefix " -+"] eq {}} {
8142 # prefix only has " ", "-" and "+" in it: normal diff line
8143 set num [string first "-" $prefix]
8144 if {$dowords} {
8145 set line [string range $line 1 end]
8146 }
8147 if {$num >= 0} {
8148 # removed line, first parent with line is $num
8149 if {$num >= $mergemax} {
8150 set num "max"
8151 }
8152 if {$dowords && $worddiff eq [mc "Markup words"]} {
8153 $ctext insert end "\[-$line-\]" $tag$num
8154 } else {
8155 $ctext insert end "$line" $tag$num
8156 }
8157 if {!$dowords} {
8158 $ctext insert end "\n" $tag$num
8159 }
8160 } else {
8161 set tags {}
8162 if {[string first "+" $prefix] >= 0} {
8163 # added line
8164 lappend tags ${tag}result
8165 if {$diffnparents > 1} {
8166 set num [string first " " $prefix]
8167 if {$num >= 0} {
8168 if {$num >= $mergemax} {
8169 set num "max"
8170 }
8171 lappend tags m$num
8172 }
8173 }
8174 set words_pre_markup "{+"
8175 set words_post_markup "+}"
8176 }
8177 if {$targetline ne {}} {
8178 if {$diffline == $targetline} {
8179 set diffseehere [$ctext index "end - 1 chars"]
8180 set targetline {}
8181 } else {
8182 incr diffline
8183 }
8184 }
8185 if {$dowords && $worddiff eq [mc "Markup words"]} {
8186 $ctext insert end "$words_pre_markup$line$words_post_markup" $tags
8187 } else {
8188 $ctext insert end "$line" $tags
8189 }
8190 if {!$dowords} {
8191 $ctext insert end "\n" $tags
8192 }
8193 }
8194 } elseif {$dowords && $prefix eq "~"} {
8195 $ctext insert end "\n" {}
8196 } else {
8197 # "\ No newline at end of file",
8198 # or something else we don't recognize
8199 $ctext insert end "$line\n" hunksep
8200 }
8201 }
8202}
8203
8204proc changediffdisp {} {
8205 global ctext diffelide
8206
8207 $ctext tag conf d0 -elide [lindex $diffelide 0]
8208 $ctext tag conf dresult -elide [lindex $diffelide 1]
8209}
8210
8211proc highlightfile {cline} {
8212 global cflist cflist_top
8213
8214 if {![info exists cflist_top]} return
8215
8216 $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
8217 $cflist tag add highlight $cline.0 "$cline.0 lineend"
8218 $cflist see $cline.0
8219 set cflist_top $cline
8220}
8221
8222proc highlightfile_for_scrollpos {topidx} {
8223 global cmitmode difffilestart
8224
8225 if {$cmitmode eq "tree"} return
8226 if {![info exists difffilestart]} return
8227
8228 set top [lindex [split $topidx .] 0]
8229 if {$difffilestart eq {} || $top < [lindex $difffilestart 0]} {
8230 highlightfile 0
8231 } else {
8232 highlightfile [expr {[bsearch $difffilestart $top] + 2}]
8233 }
8234}
8235
8236proc prevfile {} {
8237 global difffilestart ctext cmitmode
8238
8239 if {$cmitmode eq "tree"} return
8240 set prev 0.0
8241 set here [$ctext index @0,0]
8242 foreach loc $difffilestart {
8243 if {[$ctext compare $loc >= $here]} {
8244 $ctext yview $prev
8245 return
8246 }
8247 set prev $loc
8248 }
8249 $ctext yview $prev
8250}
8251
8252proc nextfile {} {
8253 global difffilestart ctext cmitmode
8254
8255 if {$cmitmode eq "tree"} return
8256 set here [$ctext index @0,0]
8257 foreach loc $difffilestart {
8258 if {[$ctext compare $loc > $here]} {
8259 $ctext yview $loc
8260 return
8261 }
8262 }
8263}
8264
8265proc clear_ctext {{first 1.0}} {
8266 global ctext smarktop smarkbot
8267 global ctext_file_names ctext_file_lines
8268 global pendinglinks
8269
8270 set l [lindex [split $first .] 0]
8271 if {![info exists smarktop] || [$ctext compare $first < $smarktop.0]} {
8272 set smarktop $l
8273 }
8274 if {![info exists smarkbot] || [$ctext compare $first < $smarkbot.0]} {
8275 set smarkbot $l
8276 }
8277 $ctext delete $first end
8278 if {$first eq "1.0"} {
8279 catch {unset pendinglinks}
8280 }
8281 set ctext_file_names {}
8282 set ctext_file_lines {}
8283}
8284
8285proc settabs {{firstab {}}} {
8286 global firsttabstop tabstop ctext have_tk85
8287
8288 if {$firstab ne {} && $have_tk85} {
8289 set firsttabstop $firstab
8290 }
8291 set w [font measure textfont "0"]
8292 if {$firsttabstop != 0} {
8293 $ctext conf -tabs [list [expr {($firsttabstop + $tabstop) * $w}] \
8294 [expr {($firsttabstop + 2 * $tabstop) * $w}]]
8295 } elseif {$have_tk85 || $tabstop != 8} {
8296 $ctext conf -tabs [expr {$tabstop * $w}]
8297 } else {
8298 $ctext conf -tabs {}
8299 }
8300}
8301
8302proc incrsearch {name ix op} {
8303 global ctext searchstring searchdirn
8304
8305 if {[catch {$ctext index anchor}]} {
8306 # no anchor set, use start of selection, or of visible area
8307 set sel [$ctext tag ranges sel]
8308 if {$sel ne {}} {
8309 $ctext mark set anchor [lindex $sel 0]
8310 } elseif {$searchdirn eq "-forwards"} {
8311 $ctext mark set anchor @0,0
8312 } else {
8313 $ctext mark set anchor @0,[winfo height $ctext]
8314 }
8315 }
8316 if {$searchstring ne {}} {
8317 set here [$ctext search -count mlen $searchdirn -- $searchstring anchor]
8318 if {$here ne {}} {
8319 $ctext see $here
8320 set mend "$here + $mlen c"
8321 $ctext tag remove sel 1.0 end
8322 $ctext tag add sel $here $mend
8323 suppress_highlighting_file_for_current_scrollpos
8324 highlightfile_for_scrollpos $here
8325 }
8326 }
8327 rehighlight_search_results
8328}
8329
8330proc dosearch {} {
8331 global sstring ctext searchstring searchdirn
8332
8333 focus $sstring
8334 $sstring icursor end
8335 set searchdirn -forwards
8336 if {$searchstring ne {}} {
8337 set sel [$ctext tag ranges sel]
8338 if {$sel ne {}} {
8339 set start "[lindex $sel 0] + 1c"
8340 } elseif {[catch {set start [$ctext index anchor]}]} {
8341 set start "@0,0"
8342 }
8343 set match [$ctext search -count mlen -- $searchstring $start]
8344 $ctext tag remove sel 1.0 end
8345 if {$match eq {}} {
8346 bell
8347 return
8348 }
8349 $ctext see $match
8350 suppress_highlighting_file_for_current_scrollpos
8351 highlightfile_for_scrollpos $match
8352 set mend "$match + $mlen c"
8353 $ctext tag add sel $match $mend
8354 $ctext mark unset anchor
8355 rehighlight_search_results
8356 }
8357}
8358
8359proc dosearchback {} {
8360 global sstring ctext searchstring searchdirn
8361
8362 focus $sstring
8363 $sstring icursor end
8364 set searchdirn -backwards
8365 if {$searchstring ne {}} {
8366 set sel [$ctext tag ranges sel]
8367 if {$sel ne {}} {
8368 set start [lindex $sel 0]
8369 } elseif {[catch {set start [$ctext index anchor]}]} {
8370 set start @0,[winfo height $ctext]
8371 }
8372 set match [$ctext search -backwards -count ml -- $searchstring $start]
8373 $ctext tag remove sel 1.0 end
8374 if {$match eq {}} {
8375 bell
8376 return
8377 }
8378 $ctext see $match
8379 suppress_highlighting_file_for_current_scrollpos
8380 highlightfile_for_scrollpos $match
8381 set mend "$match + $ml c"
8382 $ctext tag add sel $match $mend
8383 $ctext mark unset anchor
8384 rehighlight_search_results
8385 }
8386}
8387
8388proc rehighlight_search_results {} {
8389 global ctext searchstring
8390
8391 $ctext tag remove found 1.0 end
8392 $ctext tag remove currentsearchhit 1.0 end
8393
8394 if {$searchstring ne {}} {
8395 searchmarkvisible 1
8396 }
8397}
8398
8399proc searchmark {first last} {
8400 global ctext searchstring
8401
8402 set sel [$ctext tag ranges sel]
8403
8404 set mend $first.0
8405 while {1} {
8406 set match [$ctext search -count mlen -- $searchstring $mend $last.end]
8407 if {$match eq {}} break
8408 set mend "$match + $mlen c"
8409 if {$sel ne {} && [$ctext compare $match == [lindex $sel 0]]} {
8410 $ctext tag add currentsearchhit $match $mend
8411 } else {
8412 $ctext tag add found $match $mend
8413 }
8414 }
8415}
8416
8417proc searchmarkvisible {doall} {
8418 global ctext smarktop smarkbot
8419
8420 set topline [lindex [split [$ctext index @0,0] .] 0]
8421 set botline [lindex [split [$ctext index @0,[winfo height $ctext]] .] 0]
8422 if {$doall || $botline < $smarktop || $topline > $smarkbot} {
8423 # no overlap with previous
8424 searchmark $topline $botline
8425 set smarktop $topline
8426 set smarkbot $botline
8427 } else {
8428 if {$topline < $smarktop} {
8429 searchmark $topline [expr {$smarktop-1}]
8430 set smarktop $topline
8431 }
8432 if {$botline > $smarkbot} {
8433 searchmark [expr {$smarkbot+1}] $botline
8434 set smarkbot $botline
8435 }
8436 }
8437}
8438
8439proc suppress_highlighting_file_for_current_scrollpos {} {
8440 global ctext suppress_highlighting_file_for_this_scrollpos
8441
8442 set suppress_highlighting_file_for_this_scrollpos [$ctext index @0,0]
8443}
8444
8445proc scrolltext {f0 f1} {
8446 global searchstring cmitmode ctext
8447 global suppress_highlighting_file_for_this_scrollpos
8448
8449 set topidx [$ctext index @0,0]
8450 if {![info exists suppress_highlighting_file_for_this_scrollpos]
8451 || $topidx ne $suppress_highlighting_file_for_this_scrollpos} {
8452 highlightfile_for_scrollpos $topidx
8453 }
8454
8455 catch {unset suppress_highlighting_file_for_this_scrollpos}
8456
8457 .bleft.bottom.sb set $f0 $f1
8458 if {$searchstring ne {}} {
8459 searchmarkvisible 0
8460 }
8461}
8462
8463proc setcoords {} {
8464 global linespc charspc canvx0 canvy0
8465 global xspc1 xspc2 lthickness
8466
8467 set linespc [font metrics mainfont -linespace]
8468 set charspc [font measure mainfont "m"]
8469 set canvy0 [expr {int(3 + 0.5 * $linespc)}]
8470 set canvx0 [expr {int(3 + 0.5 * $linespc)}]
8471 set lthickness [expr {int($linespc / 9) + 1}]
8472 set xspc1(0) $linespc
8473 set xspc2 $linespc
8474}
8475
8476proc redisplay {} {
8477 global canv
8478 global selectedline
8479
8480 set ymax [lindex [$canv cget -scrollregion] 3]
8481 if {$ymax eq {} || $ymax == 0} return
8482 set span [$canv yview]
8483 clear_display
8484 setcanvscroll
8485 allcanvs yview moveto [lindex $span 0]
8486 drawvisible
8487 if {$selectedline ne {}} {
8488 selectline $selectedline 0
8489 allcanvs yview moveto [lindex $span 0]
8490 }
8491}
8492
8493proc parsefont {f n} {
8494 global fontattr
8495
8496 set fontattr($f,family) [lindex $n 0]
8497 set s [lindex $n 1]
8498 if {$s eq {} || $s == 0} {
8499 set s 10
8500 } elseif {$s < 0} {
8501 set s [expr {int(-$s / [winfo fpixels . 1p] + 0.5)}]
8502 }
8503 set fontattr($f,size) $s
8504 set fontattr($f,weight) normal
8505 set fontattr($f,slant) roman
8506 foreach style [lrange $n 2 end] {
8507 switch -- $style {
8508 "normal" -
8509 "bold" {set fontattr($f,weight) $style}
8510 "roman" -
8511 "italic" {set fontattr($f,slant) $style}
8512 }
8513 }
8514}
8515
8516proc fontflags {f {isbold 0}} {
8517 global fontattr
8518
8519 return [list -family $fontattr($f,family) -size $fontattr($f,size) \
8520 -weight [expr {$isbold? "bold": $fontattr($f,weight)}] \
8521 -slant $fontattr($f,slant)]
8522}
8523
8524proc fontname {f} {
8525 global fontattr
8526
8527 set n [list $fontattr($f,family) $fontattr($f,size)]
8528 if {$fontattr($f,weight) eq "bold"} {
8529 lappend n "bold"
8530 }
8531 if {$fontattr($f,slant) eq "italic"} {
8532 lappend n "italic"
8533 }
8534 return $n
8535}
8536
8537proc incrfont {inc} {
8538 global mainfont textfont ctext canv cflist showrefstop
8539 global stopped entries fontattr
8540
8541 unmarkmatches
8542 set s $fontattr(mainfont,size)
8543 incr s $inc
8544 if {$s < 1} {
8545 set s 1
8546 }
8547 set fontattr(mainfont,size) $s
8548 font config mainfont -size $s
8549 font config mainfontbold -size $s
8550 set mainfont [fontname mainfont]
8551 set s $fontattr(textfont,size)
8552 incr s $inc
8553 if {$s < 1} {
8554 set s 1
8555 }
8556 set fontattr(textfont,size) $s
8557 font config textfont -size $s
8558 font config textfontbold -size $s
8559 set textfont [fontname textfont]
8560 setcoords
8561 settabs
8562 redisplay
8563}
8564
8565proc clearsha1 {} {
8566 global sha1entry sha1string
8567 if {[string length $sha1string] == 40} {
8568 $sha1entry delete 0 end
8569 }
8570}
8571
8572proc sha1change {n1 n2 op} {
8573 global sha1string currentid sha1but
8574 if {$sha1string == {}
8575 || ([info exists currentid] && $sha1string == $currentid)} {
8576 set state disabled
8577 } else {
8578 set state normal
8579 }
8580 if {[$sha1but cget -state] == $state} return
8581 if {$state == "normal"} {
8582 $sha1but conf -state normal -relief raised -text "[mc "Goto:"] "
8583 } else {
8584 $sha1but conf -state disabled -relief flat -text "[mc "SHA1 ID:"] "
8585 }
8586}
8587
8588proc gotocommit {} {
8589 global sha1string tagids headids curview varcid
8590
8591 if {$sha1string == {}
8592 || ([info exists currentid] && $sha1string == $currentid)} return
8593 if {[info exists tagids($sha1string)]} {
8594 set id $tagids($sha1string)
8595 } elseif {[info exists headids($sha1string)]} {
8596 set id $headids($sha1string)
8597 } else {
8598 set id [string tolower $sha1string]
8599 if {[regexp {^[0-9a-f]{4,39}$} $id]} {
8600 set matches [longid $id]
8601 if {$matches ne {}} {
8602 if {[llength $matches] > 1} {
8603 error_popup [mc "Short SHA1 id %s is ambiguous" $id]
8604 return
8605 }
8606 set id [lindex $matches 0]
8607 }
8608 } else {
8609 if {[catch {set id [exec git rev-parse --verify $sha1string]}]} {
8610 error_popup [mc "Revision %s is not known" $sha1string]
8611 return
8612 }
8613 }
8614 }
8615 if {[commitinview $id $curview]} {
8616 selectline [rowofcommit $id] 1
8617 return
8618 }
8619 if {[regexp {^[0-9a-fA-F]{4,}$} $sha1string]} {
8620 set msg [mc "SHA1 id %s is not known" $sha1string]
8621 } else {
8622 set msg [mc "Revision %s is not in the current view" $sha1string]
8623 }
8624 error_popup $msg
8625}
8626
8627proc lineenter {x y id} {
8628 global hoverx hovery hoverid hovertimer
8629 global commitinfo canv
8630
8631 if {![info exists commitinfo($id)] && ![getcommit $id]} return
8632 set hoverx $x
8633 set hovery $y
8634 set hoverid $id
8635 if {[info exists hovertimer]} {
8636 after cancel $hovertimer
8637 }
8638 set hovertimer [after 500 linehover]
8639 $canv delete hover
8640}
8641
8642proc linemotion {x y id} {
8643 global hoverx hovery hoverid hovertimer
8644
8645 if {[info exists hoverid] && $id == $hoverid} {
8646 set hoverx $x
8647 set hovery $y
8648 if {[info exists hovertimer]} {
8649 after cancel $hovertimer
8650 }
8651 set hovertimer [after 500 linehover]
8652 }
8653}
8654
8655proc lineleave {id} {
8656 global hoverid hovertimer canv
8657
8658 if {[info exists hoverid] && $id == $hoverid} {
8659 $canv delete hover
8660 if {[info exists hovertimer]} {
8661 after cancel $hovertimer
8662 unset hovertimer
8663 }
8664 unset hoverid
8665 }
8666}
8667
8668proc linehover {} {
8669 global hoverx hovery hoverid hovertimer
8670 global canv linespc lthickness
8671 global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor
8672
8673 global commitinfo
8674
8675 set text [lindex $commitinfo($hoverid) 0]
8676 set ymax [lindex [$canv cget -scrollregion] 3]
8677 if {$ymax == {}} return
8678 set yfrac [lindex [$canv yview] 0]
8679 set x [expr {$hoverx + 2 * $linespc}]
8680 set y [expr {$hovery + $yfrac * $ymax - $linespc / 2}]
8681 set x0 [expr {$x - 2 * $lthickness}]
8682 set y0 [expr {$y - 2 * $lthickness}]
8683 set x1 [expr {$x + [font measure mainfont $text] + 2 * $lthickness}]
8684 set y1 [expr {$y + $linespc + 2 * $lthickness}]
8685 set t [$canv create rectangle $x0 $y0 $x1 $y1 \
8686 -fill $linehoverbgcolor -outline $linehoveroutlinecolor \
8687 -width 1 -tags hover]
8688 $canv raise $t
8689 set t [$canv create text $x $y -anchor nw -text $text -tags hover \
8690 -font mainfont -fill $linehoverfgcolor]
8691 $canv raise $t
8692}
8693
8694proc clickisonarrow {id y} {
8695 global lthickness
8696
8697 set ranges [rowranges $id]
8698 set thresh [expr {2 * $lthickness + 6}]
8699 set n [expr {[llength $ranges] - 1}]
8700 for {set i 1} {$i < $n} {incr i} {
8701 set row [lindex $ranges $i]
8702 if {abs([yc $row] - $y) < $thresh} {
8703 return $i
8704 }
8705 }
8706 return {}
8707}
8708
8709proc arrowjump {id n y} {
8710 global canv
8711
8712 # 1 <-> 2, 3 <-> 4, etc...
8713 set n [expr {(($n - 1) ^ 1) + 1}]
8714 set row [lindex [rowranges $id] $n]
8715 set yt [yc $row]
8716 set ymax [lindex [$canv cget -scrollregion] 3]
8717 if {$ymax eq {} || $ymax <= 0} return
8718 set view [$canv yview]
8719 set yspan [expr {[lindex $view 1] - [lindex $view 0]}]
8720 set yfrac [expr {$yt / $ymax - $yspan / 2}]
8721 if {$yfrac < 0} {
8722 set yfrac 0
8723 }
8724 allcanvs yview moveto $yfrac
8725}
8726
8727proc lineclick {x y id isnew} {
8728 global ctext commitinfo children canv thickerline curview
8729
8730 if {![info exists commitinfo($id)] && ![getcommit $id]} return
8731 unmarkmatches
8732 unselectline
8733 normalline
8734 $canv delete hover
8735 # draw this line thicker than normal
8736 set thickerline $id
8737 drawlines $id
8738 if {$isnew} {
8739 set ymax [lindex [$canv cget -scrollregion] 3]
8740 if {$ymax eq {}} return
8741 set yfrac [lindex [$canv yview] 0]
8742 set y [expr {$y + $yfrac * $ymax}]
8743 }
8744 set dirn [clickisonarrow $id $y]
8745 if {$dirn ne {}} {
8746 arrowjump $id $dirn $y
8747 return
8748 }
8749
8750 if {$isnew} {
8751 addtohistory [list lineclick $x $y $id 0] savectextpos
8752 }
8753 # fill the details pane with info about this line
8754 $ctext conf -state normal
8755 clear_ctext
8756 settabs 0
8757 $ctext insert end "[mc "Parent"]:\t"
8758 $ctext insert end $id link0
8759 setlink $id link0
8760 set info $commitinfo($id)
8761 $ctext insert end "\n\t[lindex $info 0]\n"
8762 $ctext insert end "\t[mc "Author"]:\t[lindex $info 1]\n"
8763 set date [formatdate [lindex $info 2]]
8764 $ctext insert end "\t[mc "Date"]:\t$date\n"
8765 set kids $children($curview,$id)
8766 if {$kids ne {}} {
8767 $ctext insert end "\n[mc "Children"]:"
8768 set i 0
8769 foreach child $kids {
8770 incr i
8771 if {![info exists commitinfo($child)] && ![getcommit $child]} continue
8772 set info $commitinfo($child)
8773 $ctext insert end "\n\t"
8774 $ctext insert end $child link$i
8775 setlink $child link$i
8776 $ctext insert end "\n\t[lindex $info 0]"
8777 $ctext insert end "\n\t[mc "Author"]:\t[lindex $info 1]"
8778 set date [formatdate [lindex $info 2]]
8779 $ctext insert end "\n\t[mc "Date"]:\t$date\n"
8780 }
8781 }
8782 maybe_scroll_ctext 1
8783 $ctext conf -state disabled
8784 init_flist {}
8785}
8786
8787proc normalline {} {
8788 global thickerline
8789 if {[info exists thickerline]} {
8790 set id $thickerline
8791 unset thickerline
8792 drawlines $id
8793 }
8794}
8795
8796proc selbyid {id {isnew 1}} {
8797 global curview
8798 if {[commitinview $id $curview]} {
8799 selectline [rowofcommit $id] $isnew
8800 }
8801}
8802
8803proc mstime {} {
8804 global startmstime
8805 if {![info exists startmstime]} {
8806 set startmstime [clock clicks -milliseconds]
8807 }
8808 return [format "%.3f" [expr {([clock click -milliseconds] - $startmstime) / 1000.0}]]
8809}
8810
8811proc rowmenu {x y id} {
8812 global rowctxmenu selectedline rowmenuid curview
8813 global nullid nullid2 fakerowmenu mainhead markedid
8814
8815 stopfinding
8816 set rowmenuid $id
8817 if {$selectedline eq {} || [rowofcommit $id] eq $selectedline} {
8818 set state disabled
8819 } else {
8820 set state normal
8821 }
8822 if {[info exists markedid] && $markedid ne $id} {
8823 set mstate normal
8824 } else {
8825 set mstate disabled
8826 }
8827 if {$id ne $nullid && $id ne $nullid2} {
8828 set menu $rowctxmenu
8829 if {$mainhead ne {}} {
8830 $menu entryconfigure 7 -label [mc "Reset %s branch to here" $mainhead] -state normal
8831 } else {
8832 $menu entryconfigure 7 -label [mc "Detached head: can't reset" $mainhead] -state disabled
8833 }
8834 $menu entryconfigure 9 -state $mstate
8835 $menu entryconfigure 10 -state $mstate
8836 $menu entryconfigure 11 -state $mstate
8837 } else {
8838 set menu $fakerowmenu
8839 }
8840 $menu entryconfigure [mca "Diff this -> selected"] -state $state
8841 $menu entryconfigure [mca "Diff selected -> this"] -state $state
8842 $menu entryconfigure [mca "Make patch"] -state $state
8843 $menu entryconfigure [mca "Diff this -> marked commit"] -state $mstate
8844 $menu entryconfigure [mca "Diff marked commit -> this"] -state $mstate
8845 tk_popup $menu $x $y
8846}
8847
8848proc markhere {} {
8849 global rowmenuid markedid canv
8850
8851 set markedid $rowmenuid
8852 make_idmark $markedid
8853}
8854
8855proc gotomark {} {
8856 global markedid
8857
8858 if {[info exists markedid]} {
8859 selbyid $markedid
8860 }
8861}
8862
8863proc replace_by_kids {l r} {
8864 global curview children
8865
8866 set id [commitonrow $r]
8867 set l [lreplace $l 0 0]
8868 foreach kid $children($curview,$id) {
8869 lappend l [rowofcommit $kid]
8870 }
8871 return [lsort -integer -decreasing -unique $l]
8872}
8873
8874proc find_common_desc {} {
8875 global markedid rowmenuid curview children
8876
8877 if {![info exists markedid]} return
8878 if {![commitinview $markedid $curview] ||
8879 ![commitinview $rowmenuid $curview]} return
8880 #set t1 [clock clicks -milliseconds]
8881 set l1 [list [rowofcommit $markedid]]
8882 set l2 [list [rowofcommit $rowmenuid]]
8883 while 1 {
8884 set r1 [lindex $l1 0]
8885 set r2 [lindex $l2 0]
8886 if {$r1 eq {} || $r2 eq {}} break
8887 if {$r1 == $r2} {
8888 selectline $r1 1
8889 break
8890 }
8891 if {$r1 > $r2} {
8892 set l1 [replace_by_kids $l1 $r1]
8893 } else {
8894 set l2 [replace_by_kids $l2 $r2]
8895 }
8896 }
8897 #set t2 [clock clicks -milliseconds]
8898 #puts "took [expr {$t2-$t1}]ms"
8899}
8900
8901proc compare_commits {} {
8902 global markedid rowmenuid curview children
8903
8904 if {![info exists markedid]} return
8905 if {![commitinview $markedid $curview]} return
8906 addtohistory [list do_cmp_commits $markedid $rowmenuid]
8907 do_cmp_commits $markedid $rowmenuid
8908}
8909
8910proc getpatchid {id} {
8911 global patchids
8912
8913 if {![info exists patchids($id)]} {
8914 set cmd [diffcmd [list $id] {-p --root}]
8915 # trim off the initial "|"
8916 set cmd [lrange $cmd 1 end]
8917 if {[catch {
8918 set x [eval exec $cmd | git patch-id]
8919 set patchids($id) [lindex $x 0]
8920 }]} {
8921 set patchids($id) "error"
8922 }
8923 }
8924 return $patchids($id)
8925}
8926
8927proc do_cmp_commits {a b} {
8928 global ctext curview parents children patchids commitinfo
8929
8930 $ctext conf -state normal
8931 clear_ctext
8932 init_flist {}
8933 for {set i 0} {$i < 100} {incr i} {
8934 set skipa 0
8935 set skipb 0
8936 if {[llength $parents($curview,$a)] > 1} {
8937 appendshortlink $a [mc "Skipping merge commit "] "\n"
8938 set skipa 1
8939 } else {
8940 set patcha [getpatchid $a]
8941 }
8942 if {[llength $parents($curview,$b)] > 1} {
8943 appendshortlink $b [mc "Skipping merge commit "] "\n"
8944 set skipb 1
8945 } else {
8946 set patchb [getpatchid $b]
8947 }
8948 if {!$skipa && !$skipb} {
8949 set heada [lindex $commitinfo($a) 0]
8950 set headb [lindex $commitinfo($b) 0]
8951 if {$patcha eq "error"} {
8952 appendshortlink $a [mc "Error getting patch ID for "] \
8953 [mc " - stopping\n"]
8954 break
8955 }
8956 if {$patchb eq "error"} {
8957 appendshortlink $b [mc "Error getting patch ID for "] \
8958 [mc " - stopping\n"]
8959 break
8960 }
8961 if {$patcha eq $patchb} {
8962 if {$heada eq $headb} {
8963 appendshortlink $a [mc "Commit "]
8964 appendshortlink $b " == " " $heada\n"
8965 } else {
8966 appendshortlink $a [mc "Commit "] " $heada\n"
8967 appendshortlink $b [mc " is the same patch as\n "] \
8968 " $headb\n"
8969 }
8970 set skipa 1
8971 set skipb 1
8972 } else {
8973 $ctext insert end "\n"
8974 appendshortlink $a [mc "Commit "] " $heada\n"
8975 appendshortlink $b [mc " differs from\n "] \
8976 " $headb\n"
8977 $ctext insert end [mc "Diff of commits:\n\n"]
8978 $ctext conf -state disabled
8979 update
8980 diffcommits $a $b
8981 return
8982 }
8983 }
8984 if {$skipa} {
8985 set kids [real_children $curview,$a]
8986 if {[llength $kids] != 1} {
8987 $ctext insert end "\n"
8988 appendshortlink $a [mc "Commit "] \
8989 [mc " has %s children - stopping\n" [llength $kids]]
8990 break
8991 }
8992 set a [lindex $kids 0]
8993 }
8994 if {$skipb} {
8995 set kids [real_children $curview,$b]
8996 if {[llength $kids] != 1} {
8997 appendshortlink $b [mc "Commit "] \
8998 [mc " has %s children - stopping\n" [llength $kids]]
8999 break
9000 }
9001 set b [lindex $kids 0]
9002 }
9003 }
9004 $ctext conf -state disabled
9005}
9006
9007proc diffcommits {a b} {
9008 global diffcontext diffids blobdifffd diffinhdr currdiffsubmod
9009
9010 set tmpdir [gitknewtmpdir]
9011 set fna [file join $tmpdir "commit-[string range $a 0 7]"]
9012 set fnb [file join $tmpdir "commit-[string range $b 0 7]"]
9013 if {[catch {
9014 exec git diff-tree -p --pretty $a >$fna
9015 exec git diff-tree -p --pretty $b >$fnb
9016 } err]} {
9017 error_popup [mc "Error writing commit to file: %s" $err]
9018 return
9019 }
9020 if {[catch {
9021 set fd [open "| diff -U$diffcontext $fna $fnb" r]
9022 } err]} {
9023 error_popup [mc "Error diffing commits: %s" $err]
9024 return
9025 }
9026 set diffids [list commits $a $b]
9027 set blobdifffd($diffids) $fd
9028 set diffinhdr 0
9029 set currdiffsubmod ""
9030 filerun $fd [list getblobdiffline $fd $diffids]
9031}
9032
9033proc diffvssel {dirn} {
9034 global rowmenuid selectedline
9035
9036 if {$selectedline eq {}} return
9037 if {$dirn} {
9038 set oldid [commitonrow $selectedline]
9039 set newid $rowmenuid
9040 } else {
9041 set oldid $rowmenuid
9042 set newid [commitonrow $selectedline]
9043 }
9044 addtohistory [list doseldiff $oldid $newid] savectextpos
9045 doseldiff $oldid $newid
9046}
9047
9048proc diffvsmark {dirn} {
9049 global rowmenuid markedid
9050
9051 if {![info exists markedid]} return
9052 if {$dirn} {
9053 set oldid $markedid
9054 set newid $rowmenuid
9055 } else {
9056 set oldid $rowmenuid
9057 set newid $markedid
9058 }
9059 addtohistory [list doseldiff $oldid $newid] savectextpos
9060 doseldiff $oldid $newid
9061}
9062
9063proc doseldiff {oldid newid} {
9064 global ctext
9065 global commitinfo
9066
9067 $ctext conf -state normal
9068 clear_ctext
9069 init_flist [mc "Top"]
9070 $ctext insert end "[mc "From"] "
9071 $ctext insert end $oldid link0
9072 setlink $oldid link0
9073 $ctext insert end "\n "
9074 $ctext insert end [lindex $commitinfo($oldid) 0]
9075 $ctext insert end "\n\n[mc "To"] "
9076 $ctext insert end $newid link1
9077 setlink $newid link1
9078 $ctext insert end "\n "
9079 $ctext insert end [lindex $commitinfo($newid) 0]
9080 $ctext insert end "\n"
9081 $ctext conf -state disabled
9082 $ctext tag remove found 1.0 end
9083 startdiff [list $oldid $newid]
9084}
9085
9086proc mkpatch {} {
9087 global rowmenuid currentid commitinfo patchtop patchnum NS
9088
9089 if {![info exists currentid]} return
9090 set oldid $currentid
9091 set oldhead [lindex $commitinfo($oldid) 0]
9092 set newid $rowmenuid
9093 set newhead [lindex $commitinfo($newid) 0]
9094 set top .patch
9095 set patchtop $top
9096 catch {destroy $top}
9097 ttk_toplevel $top
9098 make_transient $top .
9099 ${NS}::label $top.title -text [mc "Generate patch"]
9100 grid $top.title - -pady 10
9101 ${NS}::label $top.from -text [mc "From:"]
9102 ${NS}::entry $top.fromsha1 -width 40
9103 $top.fromsha1 insert 0 $oldid
9104 $top.fromsha1 conf -state readonly
9105 grid $top.from $top.fromsha1 -sticky w
9106 ${NS}::entry $top.fromhead -width 60
9107 $top.fromhead insert 0 $oldhead
9108 $top.fromhead conf -state readonly
9109 grid x $top.fromhead -sticky w
9110 ${NS}::label $top.to -text [mc "To:"]
9111 ${NS}::entry $top.tosha1 -width 40
9112 $top.tosha1 insert 0 $newid
9113 $top.tosha1 conf -state readonly
9114 grid $top.to $top.tosha1 -sticky w
9115 ${NS}::entry $top.tohead -width 60
9116 $top.tohead insert 0 $newhead
9117 $top.tohead conf -state readonly
9118 grid x $top.tohead -sticky w
9119 ${NS}::button $top.rev -text [mc "Reverse"] -command mkpatchrev
9120 grid $top.rev x -pady 10 -padx 5
9121 ${NS}::label $top.flab -text [mc "Output file:"]
9122 ${NS}::entry $top.fname -width 60
9123 $top.fname insert 0 [file normalize "patch$patchnum.patch"]
9124 incr patchnum
9125 grid $top.flab $top.fname -sticky w
9126 ${NS}::frame $top.buts
9127 ${NS}::button $top.buts.gen -text [mc "Generate"] -command mkpatchgo
9128 ${NS}::button $top.buts.can -text [mc "Cancel"] -command mkpatchcan
9129 bind $top <Key-Return> mkpatchgo
9130 bind $top <Key-Escape> mkpatchcan
9131 grid $top.buts.gen $top.buts.can
9132 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9133 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9134 grid $top.buts - -pady 10 -sticky ew
9135 focus $top.fname
9136}
9137
9138proc mkpatchrev {} {
9139 global patchtop
9140
9141 set oldid [$patchtop.fromsha1 get]
9142 set oldhead [$patchtop.fromhead get]
9143 set newid [$patchtop.tosha1 get]
9144 set newhead [$patchtop.tohead get]
9145 foreach e [list fromsha1 fromhead tosha1 tohead] \
9146 v [list $newid $newhead $oldid $oldhead] {
9147 $patchtop.$e conf -state normal
9148 $patchtop.$e delete 0 end
9149 $patchtop.$e insert 0 $v
9150 $patchtop.$e conf -state readonly
9151 }
9152}
9153
9154proc mkpatchgo {} {
9155 global patchtop nullid nullid2
9156
9157 set oldid [$patchtop.fromsha1 get]
9158 set newid [$patchtop.tosha1 get]
9159 set fname [$patchtop.fname get]
9160 set cmd [diffcmd [list $oldid $newid] -p]
9161 # trim off the initial "|"
9162 set cmd [lrange $cmd 1 end]
9163 lappend cmd >$fname &
9164 if {[catch {eval exec $cmd} err]} {
9165 error_popup "[mc "Error creating patch:"] $err" $patchtop
9166 }
9167 catch {destroy $patchtop}
9168 unset patchtop
9169}
9170
9171proc mkpatchcan {} {
9172 global patchtop
9173
9174 catch {destroy $patchtop}
9175 unset patchtop
9176}
9177
9178proc mktag {} {
9179 global rowmenuid mktagtop commitinfo NS
9180
9181 set top .maketag
9182 set mktagtop $top
9183 catch {destroy $top}
9184 ttk_toplevel $top
9185 make_transient $top .
9186 ${NS}::label $top.title -text [mc "Create tag"]
9187 grid $top.title - -pady 10
9188 ${NS}::label $top.id -text [mc "ID:"]
9189 ${NS}::entry $top.sha1 -width 40
9190 $top.sha1 insert 0 $rowmenuid
9191 $top.sha1 conf -state readonly
9192 grid $top.id $top.sha1 -sticky w
9193 ${NS}::entry $top.head -width 60
9194 $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9195 $top.head conf -state readonly
9196 grid x $top.head -sticky w
9197 ${NS}::label $top.tlab -text [mc "Tag name:"]
9198 ${NS}::entry $top.tag -width 60
9199 grid $top.tlab $top.tag -sticky w
9200 ${NS}::label $top.op -text [mc "Tag message is optional"]
9201 grid $top.op -columnspan 2 -sticky we
9202 ${NS}::label $top.mlab -text [mc "Tag message:"]
9203 ${NS}::entry $top.msg -width 60
9204 grid $top.mlab $top.msg -sticky w
9205 ${NS}::frame $top.buts
9206 ${NS}::button $top.buts.gen -text [mc "Create"] -command mktaggo
9207 ${NS}::button $top.buts.can -text [mc "Cancel"] -command mktagcan
9208 bind $top <Key-Return> mktaggo
9209 bind $top <Key-Escape> mktagcan
9210 grid $top.buts.gen $top.buts.can
9211 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9212 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9213 grid $top.buts - -pady 10 -sticky ew
9214 focus $top.tag
9215}
9216
9217proc domktag {} {
9218 global mktagtop env tagids idtags
9219
9220 set id [$mktagtop.sha1 get]
9221 set tag [$mktagtop.tag get]
9222 set msg [$mktagtop.msg get]
9223 if {$tag == {}} {
9224 error_popup [mc "No tag name specified"] $mktagtop
9225 return 0
9226 }
9227 if {[info exists tagids($tag)]} {
9228 error_popup [mc "Tag \"%s\" already exists" $tag] $mktagtop
9229 return 0
9230 }
9231 if {[catch {
9232 if {$msg != {}} {
9233 exec git tag -a -m $msg $tag $id
9234 } else {
9235 exec git tag $tag $id
9236 }
9237 } err]} {
9238 error_popup "[mc "Error creating tag:"] $err" $mktagtop
9239 return 0
9240 }
9241
9242 set tagids($tag) $id
9243 lappend idtags($id) $tag
9244 redrawtags $id
9245 addedtag $id
9246 dispneartags 0
9247 run refill_reflist
9248 return 1
9249}
9250
9251proc redrawtags {id} {
9252 global canv linehtag idpos currentid curview cmitlisted markedid
9253 global canvxmax iddrawn circleitem mainheadid circlecolors
9254 global mainheadcirclecolor
9255
9256 if {![commitinview $id $curview]} return
9257 if {![info exists iddrawn($id)]} return
9258 set row [rowofcommit $id]
9259 if {$id eq $mainheadid} {
9260 set ofill $mainheadcirclecolor
9261 } else {
9262 set ofill [lindex $circlecolors $cmitlisted($curview,$id)]
9263 }
9264 $canv itemconf $circleitem($row) -fill $ofill
9265 $canv delete tag.$id
9266 set xt [eval drawtags $id $idpos($id)]
9267 $canv coords $linehtag($id) $xt [lindex $idpos($id) 2]
9268 set text [$canv itemcget $linehtag($id) -text]
9269 set font [$canv itemcget $linehtag($id) -font]
9270 set xr [expr {$xt + [font measure $font $text]}]
9271 if {$xr > $canvxmax} {
9272 set canvxmax $xr
9273 setcanvscroll
9274 }
9275 if {[info exists currentid] && $currentid == $id} {
9276 make_secsel $id
9277 }
9278 if {[info exists markedid] && $markedid eq $id} {
9279 make_idmark $id
9280 }
9281}
9282
9283proc mktagcan {} {
9284 global mktagtop
9285
9286 catch {destroy $mktagtop}
9287 unset mktagtop
9288}
9289
9290proc mktaggo {} {
9291 if {![domktag]} return
9292 mktagcan
9293}
9294
9295proc writecommit {} {
9296 global rowmenuid wrcomtop commitinfo wrcomcmd NS
9297
9298 set top .writecommit
9299 set wrcomtop $top
9300 catch {destroy $top}
9301 ttk_toplevel $top
9302 make_transient $top .
9303 ${NS}::label $top.title -text [mc "Write commit to file"]
9304 grid $top.title - -pady 10
9305 ${NS}::label $top.id -text [mc "ID:"]
9306 ${NS}::entry $top.sha1 -width 40
9307 $top.sha1 insert 0 $rowmenuid
9308 $top.sha1 conf -state readonly
9309 grid $top.id $top.sha1 -sticky w
9310 ${NS}::entry $top.head -width 60
9311 $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9312 $top.head conf -state readonly
9313 grid x $top.head -sticky w
9314 ${NS}::label $top.clab -text [mc "Command:"]
9315 ${NS}::entry $top.cmd -width 60 -textvariable wrcomcmd
9316 grid $top.clab $top.cmd -sticky w -pady 10
9317 ${NS}::label $top.flab -text [mc "Output file:"]
9318 ${NS}::entry $top.fname -width 60
9319 $top.fname insert 0 [file normalize "commit-[string range $rowmenuid 0 6]"]
9320 grid $top.flab $top.fname -sticky w
9321 ${NS}::frame $top.buts
9322 ${NS}::button $top.buts.gen -text [mc "Write"] -command wrcomgo
9323 ${NS}::button $top.buts.can -text [mc "Cancel"] -command wrcomcan
9324 bind $top <Key-Return> wrcomgo
9325 bind $top <Key-Escape> wrcomcan
9326 grid $top.buts.gen $top.buts.can
9327 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9328 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9329 grid $top.buts - -pady 10 -sticky ew
9330 focus $top.fname
9331}
9332
9333proc wrcomgo {} {
9334 global wrcomtop
9335
9336 set id [$wrcomtop.sha1 get]
9337 set cmd "echo $id | [$wrcomtop.cmd get]"
9338 set fname [$wrcomtop.fname get]
9339 if {[catch {exec sh -c $cmd >$fname &} err]} {
9340 error_popup "[mc "Error writing commit:"] $err" $wrcomtop
9341 }
9342 catch {destroy $wrcomtop}
9343 unset wrcomtop
9344}
9345
9346proc wrcomcan {} {
9347 global wrcomtop
9348
9349 catch {destroy $wrcomtop}
9350 unset wrcomtop
9351}
9352
9353proc mkbranch {} {
9354 global rowmenuid mkbrtop NS
9355
9356 set top .makebranch
9357 catch {destroy $top}
9358 ttk_toplevel $top
9359 make_transient $top .
9360 ${NS}::label $top.title -text [mc "Create new branch"]
9361 grid $top.title - -pady 10
9362 ${NS}::label $top.id -text [mc "ID:"]
9363 ${NS}::entry $top.sha1 -width 40
9364 $top.sha1 insert 0 $rowmenuid
9365 $top.sha1 conf -state readonly
9366 grid $top.id $top.sha1 -sticky w
9367 ${NS}::label $top.nlab -text [mc "Name:"]
9368 ${NS}::entry $top.name -width 40
9369 grid $top.nlab $top.name -sticky w
9370 ${NS}::frame $top.buts
9371 ${NS}::button $top.buts.go -text [mc "Create"] -command [list mkbrgo $top]
9372 ${NS}::button $top.buts.can -text [mc "Cancel"] -command "catch {destroy $top}"
9373 bind $top <Key-Return> [list mkbrgo $top]
9374 bind $top <Key-Escape> "catch {destroy $top}"
9375 grid $top.buts.go $top.buts.can
9376 grid columnconfigure $top.buts 0 -weight 1 -uniform a
9377 grid columnconfigure $top.buts 1 -weight 1 -uniform a
9378 grid $top.buts - -pady 10 -sticky ew
9379 focus $top.name
9380}
9381
9382proc mkbrgo {top} {
9383 global headids idheads
9384
9385 set name [$top.name get]
9386 set id [$top.sha1 get]
9387 set cmdargs {}
9388 set old_id {}
9389 if {$name eq {}} {
9390 error_popup [mc "Please specify a name for the new branch"] $top
9391 return
9392 }
9393 if {[info exists headids($name)]} {
9394 if {![confirm_popup [mc \
9395 "Branch '%s' already exists. Overwrite?" $name] $top]} {
9396 return
9397 }
9398 set old_id $headids($name)
9399 lappend cmdargs -f
9400 }
9401 catch {destroy $top}
9402 lappend cmdargs $name $id
9403 nowbusy newbranch
9404 update
9405 if {[catch {
9406 eval exec git branch $cmdargs
9407 } err]} {
9408 notbusy newbranch
9409 error_popup $err
9410 } else {
9411 notbusy newbranch
9412 if {$old_id ne {}} {
9413 movehead $id $name
9414 movedhead $id $name
9415 redrawtags $old_id
9416 redrawtags $id
9417 } else {
9418 set headids($name) $id
9419 lappend idheads($id) $name
9420 addedhead $id $name
9421 redrawtags $id
9422 }
9423 dispneartags 0
9424 run refill_reflist
9425 }
9426}
9427
9428proc exec_citool {tool_args {baseid {}}} {
9429 global commitinfo env
9430
9431 set save_env [array get env GIT_AUTHOR_*]
9432
9433 if {$baseid ne {}} {
9434 if {![info exists commitinfo($baseid)]} {
9435 getcommit $baseid
9436 }
9437 set author [lindex $commitinfo($baseid) 1]
9438 set date [lindex $commitinfo($baseid) 2]
9439 if {[regexp {^\s*(\S.*\S|\S)\s*<(.*)>\s*$} \
9440 $author author name email]
9441 && $date ne {}} {
9442 set env(GIT_AUTHOR_NAME) $name
9443 set env(GIT_AUTHOR_EMAIL) $email
9444 set env(GIT_AUTHOR_DATE) $date
9445 }
9446 }
9447
9448 eval exec git citool $tool_args &
9449
9450 array unset env GIT_AUTHOR_*
9451 array set env $save_env
9452}
9453
9454proc cherrypick {} {
9455 global rowmenuid curview
9456 global mainhead mainheadid
9457 global gitdir
9458
9459 set oldhead [exec git rev-parse HEAD]
9460 set dheads [descheads $rowmenuid]
9461 if {$dheads ne {} && [lsearch -exact $dheads $oldhead] >= 0} {
9462 set ok [confirm_popup [mc "Commit %s is already\
9463 included in branch %s -- really re-apply it?" \
9464 [string range $rowmenuid 0 7] $mainhead]]
9465 if {!$ok} return
9466 }
9467 nowbusy cherrypick [mc "Cherry-picking"]
9468 update
9469 # Unfortunately git-cherry-pick writes stuff to stderr even when
9470 # no error occurs, and exec takes that as an indication of error...
9471 if {[catch {exec sh -c "git cherry-pick -r $rowmenuid 2>&1"} err]} {
9472 notbusy cherrypick
9473 if {[regexp -line \
9474 {Entry '(.*)' (would be overwritten by merge|not uptodate)} \
9475 $err msg fname]} {
9476 error_popup [mc "Cherry-pick failed because of local changes\
9477 to file '%s'.\nPlease commit, reset or stash\
9478 your changes and try again." $fname]
9479 } elseif {[regexp -line \
9480 {^(CONFLICT \(.*\):|Automatic cherry-pick failed|error: could not apply)} \
9481 $err]} {
9482 if {[confirm_popup [mc "Cherry-pick failed because of merge\
9483 conflict.\nDo you wish to run git citool to\
9484 resolve it?"]]} {
9485 # Force citool to read MERGE_MSG
9486 file delete [file join $gitdir "GITGUI_MSG"]
9487 exec_citool {} $rowmenuid
9488 }
9489 } else {
9490 error_popup $err
9491 }
9492 run updatecommits
9493 return
9494 }
9495 set newhead [exec git rev-parse HEAD]
9496 if {$newhead eq $oldhead} {
9497 notbusy cherrypick
9498 error_popup [mc "No changes committed"]
9499 return
9500 }
9501 addnewchild $newhead $oldhead
9502 if {[commitinview $oldhead $curview]} {
9503 # XXX this isn't right if we have a path limit...
9504 insertrow $newhead $oldhead $curview
9505 if {$mainhead ne {}} {
9506 movehead $newhead $mainhead
9507 movedhead $newhead $mainhead
9508 }
9509 set mainheadid $newhead
9510 redrawtags $oldhead
9511 redrawtags $newhead
9512 selbyid $newhead
9513 }
9514 notbusy cherrypick
9515}
9516
9517proc revert {} {
9518 global rowmenuid curview
9519 global mainhead mainheadid
9520 global gitdir
9521
9522 set oldhead [exec git rev-parse HEAD]
9523 set dheads [descheads $rowmenuid]
9524 if { $dheads eq {} || [lsearch -exact $dheads $oldhead] == -1 } {
9525 set ok [confirm_popup [mc "Commit %s is not\
9526 included in branch %s -- really revert it?" \
9527 [string range $rowmenuid 0 7] $mainhead]]
9528 if {!$ok} return
9529 }
9530 nowbusy revert [mc "Reverting"]
9531 update
9532
9533 if [catch {exec git revert --no-edit $rowmenuid} err] {
9534 notbusy revert
9535 if [regexp {files would be overwritten by merge:(\n(( |\t)+[^\n]+\n)+)}\
9536 $err match files] {
9537 regsub {\n( |\t)+} $files "\n" files
9538 error_popup [mc "Revert failed because of local changes to\
9539 the following files:%s Please commit, reset or stash \
9540 your changes and try again." $files]
9541 } elseif [regexp {error: could not revert} $err] {
9542 if [confirm_popup [mc "Revert failed because of merge conflict.\n\
9543 Do you wish to run git citool to resolve it?"]] {
9544 # Force citool to read MERGE_MSG
9545 file delete [file join $gitdir "GITGUI_MSG"]
9546 exec_citool {} $rowmenuid
9547 }
9548 } else { error_popup $err }
9549 run updatecommits
9550 return
9551 }
9552
9553 set newhead [exec git rev-parse HEAD]
9554 if { $newhead eq $oldhead } {
9555 notbusy revert
9556 error_popup [mc "No changes committed"]
9557 return
9558 }
9559
9560 addnewchild $newhead $oldhead
9561
9562 if [commitinview $oldhead $curview] {
9563 # XXX this isn't right if we have a path limit...
9564 insertrow $newhead $oldhead $curview
9565 if {$mainhead ne {}} {
9566 movehead $newhead $mainhead
9567 movedhead $newhead $mainhead
9568 }
9569 set mainheadid $newhead
9570 redrawtags $oldhead
9571 redrawtags $newhead
9572 selbyid $newhead
9573 }
9574
9575 notbusy revert
9576}
9577
9578proc resethead {} {
9579 global mainhead rowmenuid confirm_ok resettype NS
9580
9581 set confirm_ok 0
9582 set w ".confirmreset"
9583 ttk_toplevel $w
9584 make_transient $w .
9585 wm title $w [mc "Confirm reset"]
9586 ${NS}::label $w.m -text \
9587 [mc "Reset branch %s to %s?" $mainhead [string range $rowmenuid 0 7]]
9588 pack $w.m -side top -fill x -padx 20 -pady 20
9589 ${NS}::labelframe $w.f -text [mc "Reset type:"]
9590 set resettype mixed
9591 ${NS}::radiobutton $w.f.soft -value soft -variable resettype \
9592 -text [mc "Soft: Leave working tree and index untouched"]
9593 grid $w.f.soft -sticky w
9594 ${NS}::radiobutton $w.f.mixed -value mixed -variable resettype \
9595 -text [mc "Mixed: Leave working tree untouched, reset index"]
9596 grid $w.f.mixed -sticky w
9597 ${NS}::radiobutton $w.f.hard -value hard -variable resettype \
9598 -text [mc "Hard: Reset working tree and index\n(discard ALL local changes)"]
9599 grid $w.f.hard -sticky w
9600 pack $w.f -side top -fill x -padx 4
9601 ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
9602 pack $w.ok -side left -fill x -padx 20 -pady 20
9603 ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
9604 bind $w <Key-Escape> [list destroy $w]
9605 pack $w.cancel -side right -fill x -padx 20 -pady 20
9606 bind $w <Visibility> "grab $w; focus $w"
9607 tkwait window $w
9608 if {!$confirm_ok} return
9609 if {[catch {set fd [open \
9610 [list | git reset --$resettype $rowmenuid 2>@1] r]} err]} {
9611 error_popup $err
9612 } else {
9613 dohidelocalchanges
9614 filerun $fd [list readresetstat $fd]
9615 nowbusy reset [mc "Resetting"]
9616 selbyid $rowmenuid
9617 }
9618}
9619
9620proc readresetstat {fd} {
9621 global mainhead mainheadid showlocalchanges rprogcoord
9622
9623 if {[gets $fd line] >= 0} {
9624 if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9625 set rprogcoord [expr {1.0 * $m / $n}]
9626 adjustprogress
9627 }
9628 return 1
9629 }
9630 set rprogcoord 0
9631 adjustprogress
9632 notbusy reset
9633 if {[catch {close $fd} err]} {
9634 error_popup $err
9635 }
9636 set oldhead $mainheadid
9637 set newhead [exec git rev-parse HEAD]
9638 if {$newhead ne $oldhead} {
9639 movehead $newhead $mainhead
9640 movedhead $newhead $mainhead
9641 set mainheadid $newhead
9642 redrawtags $oldhead
9643 redrawtags $newhead
9644 }
9645 if {$showlocalchanges} {
9646 doshowlocalchanges
9647 }
9648 return 0
9649}
9650
9651# context menu for a head
9652proc headmenu {x y id head} {
9653 global headmenuid headmenuhead headctxmenu mainhead
9654
9655 stopfinding
9656 set headmenuid $id
9657 set headmenuhead $head
9658 set state normal
9659 if {[string match "remotes/*" $head]} {
9660 set state disabled
9661 }
9662 if {$head eq $mainhead} {
9663 set state disabled
9664 }
9665 $headctxmenu entryconfigure 0 -state $state
9666 $headctxmenu entryconfigure 1 -state $state
9667 tk_popup $headctxmenu $x $y
9668}
9669
9670proc cobranch {} {
9671 global headmenuid headmenuhead headids
9672 global showlocalchanges
9673
9674 # check the tree is clean first??
9675 nowbusy checkout [mc "Checking out"]
9676 update
9677 dohidelocalchanges
9678 if {[catch {
9679 set fd [open [list | git checkout $headmenuhead 2>@1] r]
9680 } err]} {
9681 notbusy checkout
9682 error_popup $err
9683 if {$showlocalchanges} {
9684 dodiffindex
9685 }
9686 } else {
9687 filerun $fd [list readcheckoutstat $fd $headmenuhead $headmenuid]
9688 }
9689}
9690
9691proc readcheckoutstat {fd newhead newheadid} {
9692 global mainhead mainheadid headids showlocalchanges progresscoords
9693 global viewmainheadid curview
9694
9695 if {[gets $fd line] >= 0} {
9696 if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9697 set progresscoords [list 0 [expr {1.0 * $m / $n}]]
9698 adjustprogress
9699 }
9700 return 1
9701 }
9702 set progresscoords {0 0}
9703 adjustprogress
9704 notbusy checkout
9705 if {[catch {close $fd} err]} {
9706 error_popup $err
9707 }
9708 set oldmainid $mainheadid
9709 set mainhead $newhead
9710 set mainheadid $newheadid
9711 set viewmainheadid($curview) $newheadid
9712 redrawtags $oldmainid
9713 redrawtags $newheadid
9714 selbyid $newheadid
9715 if {$showlocalchanges} {
9716 dodiffindex
9717 }
9718}
9719
9720proc rmbranch {} {
9721 global headmenuid headmenuhead mainhead
9722 global idheads
9723
9724 set head $headmenuhead
9725 set id $headmenuid
9726 # this check shouldn't be needed any more...
9727 if {$head eq $mainhead} {
9728 error_popup [mc "Cannot delete the currently checked-out branch"]
9729 return
9730 }
9731 set dheads [descheads $id]
9732 if {[llength $dheads] == 1 && $idheads($dheads) eq $head} {
9733 # the stuff on this branch isn't on any other branch
9734 if {![confirm_popup [mc "The commits on branch %s aren't on any other\
9735 branch.\nReally delete branch %s?" $head $head]]} return
9736 }
9737 nowbusy rmbranch
9738 update
9739 if {[catch {exec git branch -D $head} err]} {
9740 notbusy rmbranch
9741 error_popup $err
9742 return
9743 }
9744 removehead $id $head
9745 removedhead $id $head
9746 redrawtags $id
9747 notbusy rmbranch
9748 dispneartags 0
9749 run refill_reflist
9750}
9751
9752# Display a list of tags and heads
9753proc showrefs {} {
9754 global showrefstop bgcolor fgcolor selectbgcolor NS
9755 global bglist fglist reflistfilter reflist maincursor
9756
9757 set top .showrefs
9758 set showrefstop $top
9759 if {[winfo exists $top]} {
9760 raise $top
9761 refill_reflist
9762 return
9763 }
9764 ttk_toplevel $top
9765 wm title $top [mc "Tags and heads: %s" [file tail [pwd]]]
9766 make_transient $top .
9767 text $top.list -background $bgcolor -foreground $fgcolor \
9768 -selectbackground $selectbgcolor -font mainfont \
9769 -xscrollcommand "$top.xsb set" -yscrollcommand "$top.ysb set" \
9770 -width 30 -height 20 -cursor $maincursor \
9771 -spacing1 1 -spacing3 1 -state disabled
9772 $top.list tag configure highlight -background $selectbgcolor
9773 lappend bglist $top.list
9774 lappend fglist $top.list
9775 ${NS}::scrollbar $top.ysb -command "$top.list yview" -orient vertical
9776 ${NS}::scrollbar $top.xsb -command "$top.list xview" -orient horizontal
9777 grid $top.list $top.ysb -sticky nsew
9778 grid $top.xsb x -sticky ew
9779 ${NS}::frame $top.f
9780 ${NS}::label $top.f.l -text "[mc "Filter"]: "
9781 ${NS}::entry $top.f.e -width 20 -textvariable reflistfilter
9782 set reflistfilter "*"
9783 trace add variable reflistfilter write reflistfilter_change
9784 pack $top.f.e -side right -fill x -expand 1
9785 pack $top.f.l -side left
9786 grid $top.f - -sticky ew -pady 2
9787 ${NS}::button $top.close -command [list destroy $top] -text [mc "Close"]
9788 bind $top <Key-Escape> [list destroy $top]
9789 grid $top.close -
9790 grid columnconfigure $top 0 -weight 1
9791 grid rowconfigure $top 0 -weight 1
9792 bind $top.list <1> {break}
9793 bind $top.list <B1-Motion> {break}
9794 bind $top.list <ButtonRelease-1> {sel_reflist %W %x %y; break}
9795 set reflist {}
9796 refill_reflist
9797}
9798
9799proc sel_reflist {w x y} {
9800 global showrefstop reflist headids tagids otherrefids
9801
9802 if {![winfo exists $showrefstop]} return
9803 set l [lindex [split [$w index "@$x,$y"] "."] 0]
9804 set ref [lindex $reflist [expr {$l-1}]]
9805 set n [lindex $ref 0]
9806 switch -- [lindex $ref 1] {
9807 "H" {selbyid $headids($n)}
9808 "T" {selbyid $tagids($n)}
9809 "o" {selbyid $otherrefids($n)}
9810 }
9811 $showrefstop.list tag add highlight $l.0 "$l.0 lineend"
9812}
9813
9814proc unsel_reflist {} {
9815 global showrefstop
9816
9817 if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9818 $showrefstop.list tag remove highlight 0.0 end
9819}
9820
9821proc reflistfilter_change {n1 n2 op} {
9822 global reflistfilter
9823
9824 after cancel refill_reflist
9825 after 200 refill_reflist
9826}
9827
9828proc refill_reflist {} {
9829 global reflist reflistfilter showrefstop headids tagids otherrefids
9830 global curview
9831
9832 if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9833 set refs {}
9834 foreach n [array names headids] {
9835 if {[string match $reflistfilter $n]} {
9836 if {[commitinview $headids($n) $curview]} {
9837 lappend refs [list $n H]
9838 } else {
9839 interestedin $headids($n) {run refill_reflist}
9840 }
9841 }
9842 }
9843 foreach n [array names tagids] {
9844 if {[string match $reflistfilter $n]} {
9845 if {[commitinview $tagids($n) $curview]} {
9846 lappend refs [list $n T]
9847 } else {
9848 interestedin $tagids($n) {run refill_reflist}
9849 }
9850 }
9851 }
9852 foreach n [array names otherrefids] {
9853 if {[string match $reflistfilter $n]} {
9854 if {[commitinview $otherrefids($n) $curview]} {
9855 lappend refs [list $n o]
9856 } else {
9857 interestedin $otherrefids($n) {run refill_reflist}
9858 }
9859 }
9860 }
9861 set refs [lsort -index 0 $refs]
9862 if {$refs eq $reflist} return
9863
9864 # Update the contents of $showrefstop.list according to the
9865 # differences between $reflist (old) and $refs (new)
9866 $showrefstop.list conf -state normal
9867 $showrefstop.list insert end "\n"
9868 set i 0
9869 set j 0
9870 while {$i < [llength $reflist] || $j < [llength $refs]} {
9871 if {$i < [llength $reflist]} {
9872 if {$j < [llength $refs]} {
9873 set cmp [string compare [lindex $reflist $i 0] \
9874 [lindex $refs $j 0]]
9875 if {$cmp == 0} {
9876 set cmp [string compare [lindex $reflist $i 1] \
9877 [lindex $refs $j 1]]
9878 }
9879 } else {
9880 set cmp -1
9881 }
9882 } else {
9883 set cmp 1
9884 }
9885 switch -- $cmp {
9886 -1 {
9887 $showrefstop.list delete "[expr {$j+1}].0" "[expr {$j+2}].0"
9888 incr i
9889 }
9890 0 {
9891 incr i
9892 incr j
9893 }
9894 1 {
9895 set l [expr {$j + 1}]
9896 $showrefstop.list image create $l.0 -align baseline \
9897 -image reficon-[lindex $refs $j 1] -padx 2
9898 $showrefstop.list insert $l.1 "[lindex $refs $j 0]\n"
9899 incr j
9900 }
9901 }
9902 }
9903 set reflist $refs
9904 # delete last newline
9905 $showrefstop.list delete end-2c end-1c
9906 $showrefstop.list conf -state disabled
9907}
9908
9909# Stuff for finding nearby tags
9910proc getallcommits {} {
9911 global allcommits nextarc seeds allccache allcwait cachedarcs allcupdate
9912 global idheads idtags idotherrefs allparents tagobjid
9913 global gitdir
9914
9915 if {![info exists allcommits]} {
9916 set nextarc 0
9917 set allcommits 0
9918 set seeds {}
9919 set allcwait 0
9920 set cachedarcs 0
9921 set allccache [file join $gitdir "gitk.cache"]
9922 if {![catch {
9923 set f [open $allccache r]
9924 set allcwait 1
9925 getcache $f
9926 }]} return
9927 }
9928
9929 if {$allcwait} {
9930 return
9931 }
9932 set cmd [list | git rev-list --parents]
9933 set allcupdate [expr {$seeds ne {}}]
9934 if {!$allcupdate} {
9935 set ids "--all"
9936 } else {
9937 set refs [concat [array names idheads] [array names idtags] \
9938 [array names idotherrefs]]
9939 set ids {}
9940 set tagobjs {}
9941 foreach name [array names tagobjid] {
9942 lappend tagobjs $tagobjid($name)
9943 }
9944 foreach id [lsort -unique $refs] {
9945 if {![info exists allparents($id)] &&
9946 [lsearch -exact $tagobjs $id] < 0} {
9947 lappend ids $id
9948 }
9949 }
9950 if {$ids ne {}} {
9951 foreach id $seeds {
9952 lappend ids "^$id"
9953 }
9954 }
9955 }
9956 if {$ids ne {}} {
9957 set fd [open [concat $cmd $ids] r]
9958 fconfigure $fd -blocking 0
9959 incr allcommits
9960 nowbusy allcommits
9961 filerun $fd [list getallclines $fd]
9962 } else {
9963 dispneartags 0
9964 }
9965}
9966
9967# Since most commits have 1 parent and 1 child, we group strings of
9968# such commits into "arcs" joining branch/merge points (BMPs), which
9969# are commits that either don't have 1 parent or don't have 1 child.
9970#
9971# arcnos(id) - incoming arcs for BMP, arc we're on for other nodes
9972# arcout(id) - outgoing arcs for BMP
9973# arcids(a) - list of IDs on arc including end but not start
9974# arcstart(a) - BMP ID at start of arc
9975# arcend(a) - BMP ID at end of arc
9976# growing(a) - arc a is still growing
9977# arctags(a) - IDs out of arcids (excluding end) that have tags
9978# archeads(a) - IDs out of arcids (excluding end) that have heads
9979# The start of an arc is at the descendent end, so "incoming" means
9980# coming from descendents, and "outgoing" means going towards ancestors.
9981
9982proc getallclines {fd} {
9983 global allparents allchildren idtags idheads nextarc
9984 global arcnos arcids arctags arcout arcend arcstart archeads growing
9985 global seeds allcommits cachedarcs allcupdate
9986
9987 set nid 0
9988 while {[incr nid] <= 1000 && [gets $fd line] >= 0} {
9989 set id [lindex $line 0]
9990 if {[info exists allparents($id)]} {
9991 # seen it already
9992 continue
9993 }
9994 set cachedarcs 0
9995 set olds [lrange $line 1 end]
9996 set allparents($id) $olds
9997 if {![info exists allchildren($id)]} {
9998 set allchildren($id) {}
9999 set arcnos($id) {}
10000 lappend seeds $id
10001 } else {
10002 set a $arcnos($id)
10003 if {[llength $olds] == 1 && [llength $a] == 1} {
10004 lappend arcids($a) $id
10005 if {[info exists idtags($id)]} {
10006 lappend arctags($a) $id
10007 }
10008 if {[info exists idheads($id)]} {
10009 lappend archeads($a) $id
10010 }
10011 if {[info exists allparents($olds)]} {
10012 # seen parent already
10013 if {![info exists arcout($olds)]} {
10014 splitarc $olds
10015 }
10016 lappend arcids($a) $olds
10017 set arcend($a) $olds
10018 unset growing($a)
10019 }
10020 lappend allchildren($olds) $id
10021 lappend arcnos($olds) $a
10022 continue
10023 }
10024 }
10025 foreach a $arcnos($id) {
10026 lappend arcids($a) $id
10027 set arcend($a) $id
10028 unset growing($a)
10029 }
10030
10031 set ao {}
10032 foreach p $olds {
10033 lappend allchildren($p) $id
10034 set a [incr nextarc]
10035 set arcstart($a) $id
10036 set archeads($a) {}
10037 set arctags($a) {}
10038 set archeads($a) {}
10039 set arcids($a) {}
10040 lappend ao $a
10041 set growing($a) 1
10042 if {[info exists allparents($p)]} {
10043 # seen it already, may need to make a new branch
10044 if {![info exists arcout($p)]} {
10045 splitarc $p
10046 }
10047 lappend arcids($a) $p
10048 set arcend($a) $p
10049 unset growing($a)
10050 }
10051 lappend arcnos($p) $a
10052 }
10053 set arcout($id) $ao
10054 }
10055 if {$nid > 0} {
10056 global cached_dheads cached_dtags cached_atags
10057 catch {unset cached_dheads}
10058 catch {unset cached_dtags}
10059 catch {unset cached_atags}
10060 }
10061 if {![eof $fd]} {
10062 return [expr {$nid >= 1000? 2: 1}]
10063 }
10064 set cacheok 1
10065 if {[catch {
10066 fconfigure $fd -blocking 1
10067 close $fd
10068 } err]} {
10069 # got an error reading the list of commits
10070 # if we were updating, try rereading the whole thing again
10071 if {$allcupdate} {
10072 incr allcommits -1
10073 dropcache $err
10074 return
10075 }
10076 error_popup "[mc "Error reading commit topology information;\
10077 branch and preceding/following tag information\
10078 will be incomplete."]\n($err)"
10079 set cacheok 0
10080 }
10081 if {[incr allcommits -1] == 0} {
10082 notbusy allcommits
10083 if {$cacheok} {
10084 run savecache
10085 }
10086 }
10087 dispneartags 0
10088 return 0
10089}
10090
10091proc recalcarc {a} {
10092 global arctags archeads arcids idtags idheads
10093
10094 set at {}
10095 set ah {}
10096 foreach id [lrange $arcids($a) 0 end-1] {
10097 if {[info exists idtags($id)]} {
10098 lappend at $id
10099 }
10100 if {[info exists idheads($id)]} {
10101 lappend ah $id
10102 }
10103 }
10104 set arctags($a) $at
10105 set archeads($a) $ah
10106}
10107
10108proc splitarc {p} {
10109 global arcnos arcids nextarc arctags archeads idtags idheads
10110 global arcstart arcend arcout allparents growing
10111
10112 set a $arcnos($p)
10113 if {[llength $a] != 1} {
10114 puts "oops splitarc called but [llength $a] arcs already"
10115 return
10116 }
10117 set a [lindex $a 0]
10118 set i [lsearch -exact $arcids($a) $p]
10119 if {$i < 0} {
10120 puts "oops splitarc $p not in arc $a"
10121 return
10122 }
10123 set na [incr nextarc]
10124 if {[info exists arcend($a)]} {
10125 set arcend($na) $arcend($a)
10126 } else {
10127 set l [lindex $allparents([lindex $arcids($a) end]) 0]
10128 set j [lsearch -exact $arcnos($l) $a]
10129 set arcnos($l) [lreplace $arcnos($l) $j $j $na]
10130 }
10131 set tail [lrange $arcids($a) [expr {$i+1}] end]
10132 set arcids($a) [lrange $arcids($a) 0 $i]
10133 set arcend($a) $p
10134 set arcstart($na) $p
10135 set arcout($p) $na
10136 set arcids($na) $tail
10137 if {[info exists growing($a)]} {
10138 set growing($na) 1
10139 unset growing($a)
10140 }
10141
10142 foreach id $tail {
10143 if {[llength $arcnos($id)] == 1} {
10144 set arcnos($id) $na
10145 } else {
10146 set j [lsearch -exact $arcnos($id) $a]
10147 set arcnos($id) [lreplace $arcnos($id) $j $j $na]
10148 }
10149 }
10150
10151 # reconstruct tags and heads lists
10152 if {$arctags($a) ne {} || $archeads($a) ne {}} {
10153 recalcarc $a
10154 recalcarc $na
10155 } else {
10156 set arctags($na) {}
10157 set archeads($na) {}
10158 }
10159}
10160
10161# Update things for a new commit added that is a child of one
10162# existing commit. Used when cherry-picking.
10163proc addnewchild {id p} {
10164 global allparents allchildren idtags nextarc
10165 global arcnos arcids arctags arcout arcend arcstart archeads growing
10166 global seeds allcommits
10167
10168 if {![info exists allcommits] || ![info exists arcnos($p)]} return
10169 set allparents($id) [list $p]
10170 set allchildren($id) {}
10171 set arcnos($id) {}
10172 lappend seeds $id
10173 lappend allchildren($p) $id
10174 set a [incr nextarc]
10175 set arcstart($a) $id
10176 set archeads($a) {}
10177 set arctags($a) {}
10178 set arcids($a) [list $p]
10179 set arcend($a) $p
10180 if {![info exists arcout($p)]} {
10181 splitarc $p
10182 }
10183 lappend arcnos($p) $a
10184 set arcout($id) [list $a]
10185}
10186
10187# This implements a cache for the topology information.
10188# The cache saves, for each arc, the start and end of the arc,
10189# the ids on the arc, and the outgoing arcs from the end.
10190proc readcache {f} {
10191 global arcnos arcids arcout arcstart arcend arctags archeads nextarc
10192 global idtags idheads allparents cachedarcs possible_seeds seeds growing
10193 global allcwait
10194
10195 set a $nextarc
10196 set lim $cachedarcs
10197 if {$lim - $a > 500} {
10198 set lim [expr {$a + 500}]
10199 }
10200 if {[catch {
10201 if {$a == $lim} {
10202 # finish reading the cache and setting up arctags, etc.
10203 set line [gets $f]
10204 if {$line ne "1"} {error "bad final version"}
10205 close $f
10206 foreach id [array names idtags] {
10207 if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10208 [llength $allparents($id)] == 1} {
10209 set a [lindex $arcnos($id) 0]
10210 if {$arctags($a) eq {}} {
10211 recalcarc $a
10212 }
10213 }
10214 }
10215 foreach id [array names idheads] {
10216 if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10217 [llength $allparents($id)] == 1} {
10218 set a [lindex $arcnos($id) 0]
10219 if {$archeads($a) eq {}} {
10220 recalcarc $a
10221 }
10222 }
10223 }
10224 foreach id [lsort -unique $possible_seeds] {
10225 if {$arcnos($id) eq {}} {
10226 lappend seeds $id
10227 }
10228 }
10229 set allcwait 0
10230 } else {
10231 while {[incr a] <= $lim} {
10232 set line [gets $f]
10233 if {[llength $line] != 3} {error "bad line"}
10234 set s [lindex $line 0]
10235 set arcstart($a) $s
10236 lappend arcout($s) $a
10237 if {![info exists arcnos($s)]} {
10238 lappend possible_seeds $s
10239 set arcnos($s) {}
10240 }
10241 set e [lindex $line 1]
10242 if {$e eq {}} {
10243 set growing($a) 1
10244 } else {
10245 set arcend($a) $e
10246 if {![info exists arcout($e)]} {
10247 set arcout($e) {}
10248 }
10249 }
10250 set arcids($a) [lindex $line 2]
10251 foreach id $arcids($a) {
10252 lappend allparents($s) $id
10253 set s $id
10254 lappend arcnos($id) $a
10255 }
10256 if {![info exists allparents($s)]} {
10257 set allparents($s) {}
10258 }
10259 set arctags($a) {}
10260 set archeads($a) {}
10261 }
10262 set nextarc [expr {$a - 1}]
10263 }
10264 } err]} {
10265 dropcache $err
10266 return 0
10267 }
10268 if {!$allcwait} {
10269 getallcommits
10270 }
10271 return $allcwait
10272}
10273
10274proc getcache {f} {
10275 global nextarc cachedarcs possible_seeds
10276
10277 if {[catch {
10278 set line [gets $f]
10279 if {[llength $line] != 2 || [lindex $line 0] ne "1"} {error "bad version"}
10280 # make sure it's an integer
10281 set cachedarcs [expr {int([lindex $line 1])}]
10282 if {$cachedarcs < 0} {error "bad number of arcs"}
10283 set nextarc 0
10284 set possible_seeds {}
10285 run readcache $f
10286 } err]} {
10287 dropcache $err
10288 }
10289 return 0
10290}
10291
10292proc dropcache {err} {
10293 global allcwait nextarc cachedarcs seeds
10294
10295 #puts "dropping cache ($err)"
10296 foreach v {arcnos arcout arcids arcstart arcend growing \
10297 arctags archeads allparents allchildren} {
10298 global $v
10299 catch {unset $v}
10300 }
10301 set allcwait 0
10302 set nextarc 0
10303 set cachedarcs 0
10304 set seeds {}
10305 getallcommits
10306}
10307
10308proc writecache {f} {
10309 global cachearc cachedarcs allccache
10310 global arcstart arcend arcnos arcids arcout
10311
10312 set a $cachearc
10313 set lim $cachedarcs
10314 if {$lim - $a > 1000} {
10315 set lim [expr {$a + 1000}]
10316 }
10317 if {[catch {
10318 while {[incr a] <= $lim} {
10319 if {[info exists arcend($a)]} {
10320 puts $f [list $arcstart($a) $arcend($a) $arcids($a)]
10321 } else {
10322 puts $f [list $arcstart($a) {} $arcids($a)]
10323 }
10324 }
10325 } err]} {
10326 catch {close $f}
10327 catch {file delete $allccache}
10328 #puts "writing cache failed ($err)"
10329 return 0
10330 }
10331 set cachearc [expr {$a - 1}]
10332 if {$a > $cachedarcs} {
10333 puts $f "1"
10334 close $f
10335 return 0
10336 }
10337 return 1
10338}
10339
10340proc savecache {} {
10341 global nextarc cachedarcs cachearc allccache
10342
10343 if {$nextarc == $cachedarcs} return
10344 set cachearc 0
10345 set cachedarcs $nextarc
10346 catch {
10347 set f [open $allccache w]
10348 puts $f [list 1 $cachedarcs]
10349 run writecache $f
10350 }
10351}
10352
10353# Returns 1 if a is an ancestor of b, -1 if b is an ancestor of a,
10354# or 0 if neither is true.
10355proc anc_or_desc {a b} {
10356 global arcout arcstart arcend arcnos cached_isanc
10357
10358 if {$arcnos($a) eq $arcnos($b)} {
10359 # Both are on the same arc(s); either both are the same BMP,
10360 # or if one is not a BMP, the other is also not a BMP or is
10361 # the BMP at end of the arc (and it only has 1 incoming arc).
10362 # Or both can be BMPs with no incoming arcs.
10363 if {$a eq $b || $arcnos($a) eq {}} {
10364 return 0
10365 }
10366 # assert {[llength $arcnos($a)] == 1}
10367 set arc [lindex $arcnos($a) 0]
10368 set i [lsearch -exact $arcids($arc) $a]
10369 set j [lsearch -exact $arcids($arc) $b]
10370 if {$i < 0 || $i > $j} {
10371 return 1
10372 } else {
10373 return -1
10374 }
10375 }
10376
10377 if {![info exists arcout($a)]} {
10378 set arc [lindex $arcnos($a) 0]
10379 if {[info exists arcend($arc)]} {
10380 set aend $arcend($arc)
10381 } else {
10382 set aend {}
10383 }
10384 set a $arcstart($arc)
10385 } else {
10386 set aend $a
10387 }
10388 if {![info exists arcout($b)]} {
10389 set arc [lindex $arcnos($b) 0]
10390 if {[info exists arcend($arc)]} {
10391 set bend $arcend($arc)
10392 } else {
10393 set bend {}
10394 }
10395 set b $arcstart($arc)
10396 } else {
10397 set bend $b
10398 }
10399 if {$a eq $bend} {
10400 return 1
10401 }
10402 if {$b eq $aend} {
10403 return -1
10404 }
10405 if {[info exists cached_isanc($a,$bend)]} {
10406 if {$cached_isanc($a,$bend)} {
10407 return 1
10408 }
10409 }
10410 if {[info exists cached_isanc($b,$aend)]} {
10411 if {$cached_isanc($b,$aend)} {
10412 return -1
10413 }
10414 if {[info exists cached_isanc($a,$bend)]} {
10415 return 0
10416 }
10417 }
10418
10419 set todo [list $a $b]
10420 set anc($a) a
10421 set anc($b) b
10422 for {set i 0} {$i < [llength $todo]} {incr i} {
10423 set x [lindex $todo $i]
10424 if {$anc($x) eq {}} {
10425 continue
10426 }
10427 foreach arc $arcnos($x) {
10428 set xd $arcstart($arc)
10429 if {$xd eq $bend} {
10430 set cached_isanc($a,$bend) 1
10431 set cached_isanc($b,$aend) 0
10432 return 1
10433 } elseif {$xd eq $aend} {
10434 set cached_isanc($b,$aend) 1
10435 set cached_isanc($a,$bend) 0
10436 return -1
10437 }
10438 if {![info exists anc($xd)]} {
10439 set anc($xd) $anc($x)
10440 lappend todo $xd
10441 } elseif {$anc($xd) ne $anc($x)} {
10442 set anc($xd) {}
10443 }
10444 }
10445 }
10446 set cached_isanc($a,$bend) 0
10447 set cached_isanc($b,$aend) 0
10448 return 0
10449}
10450
10451# This identifies whether $desc has an ancestor that is
10452# a growing tip of the graph and which is not an ancestor of $anc
10453# and returns 0 if so and 1 if not.
10454# If we subsequently discover a tag on such a growing tip, and that
10455# turns out to be a descendent of $anc (which it could, since we
10456# don't necessarily see children before parents), then $desc
10457# isn't a good choice to display as a descendent tag of
10458# $anc (since it is the descendent of another tag which is
10459# a descendent of $anc). Similarly, $anc isn't a good choice to
10460# display as a ancestor tag of $desc.
10461#
10462proc is_certain {desc anc} {
10463 global arcnos arcout arcstart arcend growing problems
10464
10465 set certain {}
10466 if {[llength $arcnos($anc)] == 1} {
10467 # tags on the same arc are certain
10468 if {$arcnos($desc) eq $arcnos($anc)} {
10469 return 1
10470 }
10471 if {![info exists arcout($anc)]} {
10472 # if $anc is partway along an arc, use the start of the arc instead
10473 set a [lindex $arcnos($anc) 0]
10474 set anc $arcstart($a)
10475 }
10476 }
10477 if {[llength $arcnos($desc)] > 1 || [info exists arcout($desc)]} {
10478 set x $desc
10479 } else {
10480 set a [lindex $arcnos($desc) 0]
10481 set x $arcend($a)
10482 }
10483 if {$x == $anc} {
10484 return 1
10485 }
10486 set anclist [list $x]
10487 set dl($x) 1
10488 set nnh 1
10489 set ngrowanc 0
10490 for {set i 0} {$i < [llength $anclist] && ($nnh > 0 || $ngrowanc > 0)} {incr i} {
10491 set x [lindex $anclist $i]
10492 if {$dl($x)} {
10493 incr nnh -1
10494 }
10495 set done($x) 1
10496 foreach a $arcout($x) {
10497 if {[info exists growing($a)]} {
10498 if {![info exists growanc($x)] && $dl($x)} {
10499 set growanc($x) 1
10500 incr ngrowanc
10501 }
10502 } else {
10503 set y $arcend($a)
10504 if {[info exists dl($y)]} {
10505 if {$dl($y)} {
10506 if {!$dl($x)} {
10507 set dl($y) 0
10508 if {![info exists done($y)]} {
10509 incr nnh -1
10510 }
10511 if {[info exists growanc($x)]} {
10512 incr ngrowanc -1
10513 }
10514 set xl [list $y]
10515 for {set k 0} {$k < [llength $xl]} {incr k} {
10516 set z [lindex $xl $k]
10517 foreach c $arcout($z) {
10518 if {[info exists arcend($c)]} {
10519 set v $arcend($c)
10520 if {[info exists dl($v)] && $dl($v)} {
10521 set dl($v) 0
10522 if {![info exists done($v)]} {
10523 incr nnh -1
10524 }
10525 if {[info exists growanc($v)]} {
10526 incr ngrowanc -1
10527 }
10528 lappend xl $v
10529 }
10530 }
10531 }
10532 }
10533 }
10534 }
10535 } elseif {$y eq $anc || !$dl($x)} {
10536 set dl($y) 0
10537 lappend anclist $y
10538 } else {
10539 set dl($y) 1
10540 lappend anclist $y
10541 incr nnh
10542 }
10543 }
10544 }
10545 }
10546 foreach x [array names growanc] {
10547 if {$dl($x)} {
10548 return 0
10549 }
10550 return 0
10551 }
10552 return 1
10553}
10554
10555proc validate_arctags {a} {
10556 global arctags idtags
10557
10558 set i -1
10559 set na $arctags($a)
10560 foreach id $arctags($a) {
10561 incr i
10562 if {![info exists idtags($id)]} {
10563 set na [lreplace $na $i $i]
10564 incr i -1
10565 }
10566 }
10567 set arctags($a) $na
10568}
10569
10570proc validate_archeads {a} {
10571 global archeads idheads
10572
10573 set i -1
10574 set na $archeads($a)
10575 foreach id $archeads($a) {
10576 incr i
10577 if {![info exists idheads($id)]} {
10578 set na [lreplace $na $i $i]
10579 incr i -1
10580 }
10581 }
10582 set archeads($a) $na
10583}
10584
10585# Return the list of IDs that have tags that are descendents of id,
10586# ignoring IDs that are descendents of IDs already reported.
10587proc desctags {id} {
10588 global arcnos arcstart arcids arctags idtags allparents
10589 global growing cached_dtags
10590
10591 if {![info exists allparents($id)]} {
10592 return {}
10593 }
10594 set t1 [clock clicks -milliseconds]
10595 set argid $id
10596 if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10597 # part-way along an arc; check that arc first
10598 set a [lindex $arcnos($id) 0]
10599 if {$arctags($a) ne {}} {
10600 validate_arctags $a
10601 set i [lsearch -exact $arcids($a) $id]
10602 set tid {}
10603 foreach t $arctags($a) {
10604 set j [lsearch -exact $arcids($a) $t]
10605 if {$j >= $i} break
10606 set tid $t
10607 }
10608 if {$tid ne {}} {
10609 return $tid
10610 }
10611 }
10612 set id $arcstart($a)
10613 if {[info exists idtags($id)]} {
10614 return $id
10615 }
10616 }
10617 if {[info exists cached_dtags($id)]} {
10618 return $cached_dtags($id)
10619 }
10620
10621 set origid $id
10622 set todo [list $id]
10623 set queued($id) 1
10624 set nc 1
10625 for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10626 set id [lindex $todo $i]
10627 set done($id) 1
10628 set ta [info exists hastaggedancestor($id)]
10629 if {!$ta} {
10630 incr nc -1
10631 }
10632 # ignore tags on starting node
10633 if {!$ta && $i > 0} {
10634 if {[info exists idtags($id)]} {
10635 set tagloc($id) $id
10636 set ta 1
10637 } elseif {[info exists cached_dtags($id)]} {
10638 set tagloc($id) $cached_dtags($id)
10639 set ta 1
10640 }
10641 }
10642 foreach a $arcnos($id) {
10643 set d $arcstart($a)
10644 if {!$ta && $arctags($a) ne {}} {
10645 validate_arctags $a
10646 if {$arctags($a) ne {}} {
10647 lappend tagloc($id) [lindex $arctags($a) end]
10648 }
10649 }
10650 if {$ta || $arctags($a) ne {}} {
10651 set tomark [list $d]
10652 for {set j 0} {$j < [llength $tomark]} {incr j} {
10653 set dd [lindex $tomark $j]
10654 if {![info exists hastaggedancestor($dd)]} {
10655 if {[info exists done($dd)]} {
10656 foreach b $arcnos($dd) {
10657 lappend tomark $arcstart($b)
10658 }
10659 if {[info exists tagloc($dd)]} {
10660 unset tagloc($dd)
10661 }
10662 } elseif {[info exists queued($dd)]} {
10663 incr nc -1
10664 }
10665 set hastaggedancestor($dd) 1
10666 }
10667 }
10668 }
10669 if {![info exists queued($d)]} {
10670 lappend todo $d
10671 set queued($d) 1
10672 if {![info exists hastaggedancestor($d)]} {
10673 incr nc
10674 }
10675 }
10676 }
10677 }
10678 set tags {}
10679 foreach id [array names tagloc] {
10680 if {![info exists hastaggedancestor($id)]} {
10681 foreach t $tagloc($id) {
10682 if {[lsearch -exact $tags $t] < 0} {
10683 lappend tags $t
10684 }
10685 }
10686 }
10687 }
10688 set t2 [clock clicks -milliseconds]
10689 set loopix $i
10690
10691 # remove tags that are descendents of other tags
10692 for {set i 0} {$i < [llength $tags]} {incr i} {
10693 set a [lindex $tags $i]
10694 for {set j 0} {$j < $i} {incr j} {
10695 set b [lindex $tags $j]
10696 set r [anc_or_desc $a $b]
10697 if {$r == 1} {
10698 set tags [lreplace $tags $j $j]
10699 incr j -1
10700 incr i -1
10701 } elseif {$r == -1} {
10702 set tags [lreplace $tags $i $i]
10703 incr i -1
10704 break
10705 }
10706 }
10707 }
10708
10709 if {[array names growing] ne {}} {
10710 # graph isn't finished, need to check if any tag could get
10711 # eclipsed by another tag coming later. Simply ignore any
10712 # tags that could later get eclipsed.
10713 set ctags {}
10714 foreach t $tags {
10715 if {[is_certain $t $origid]} {
10716 lappend ctags $t
10717 }
10718 }
10719 if {$tags eq $ctags} {
10720 set cached_dtags($origid) $tags
10721 } else {
10722 set tags $ctags
10723 }
10724 } else {
10725 set cached_dtags($origid) $tags
10726 }
10727 set t3 [clock clicks -milliseconds]
10728 if {0 && $t3 - $t1 >= 100} {
10729 puts "iterating descendents ($loopix/[llength $todo] nodes) took\
10730 [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10731 }
10732 return $tags
10733}
10734
10735proc anctags {id} {
10736 global arcnos arcids arcout arcend arctags idtags allparents
10737 global growing cached_atags
10738
10739 if {![info exists allparents($id)]} {
10740 return {}
10741 }
10742 set t1 [clock clicks -milliseconds]
10743 set argid $id
10744 if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10745 # part-way along an arc; check that arc first
10746 set a [lindex $arcnos($id) 0]
10747 if {$arctags($a) ne {}} {
10748 validate_arctags $a
10749 set i [lsearch -exact $arcids($a) $id]
10750 foreach t $arctags($a) {
10751 set j [lsearch -exact $arcids($a) $t]
10752 if {$j > $i} {
10753 return $t
10754 }
10755 }
10756 }
10757 if {![info exists arcend($a)]} {
10758 return {}
10759 }
10760 set id $arcend($a)
10761 if {[info exists idtags($id)]} {
10762 return $id
10763 }
10764 }
10765 if {[info exists cached_atags($id)]} {
10766 return $cached_atags($id)
10767 }
10768
10769 set origid $id
10770 set todo [list $id]
10771 set queued($id) 1
10772 set taglist {}
10773 set nc 1
10774 for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10775 set id [lindex $todo $i]
10776 set done($id) 1
10777 set td [info exists hastaggeddescendent($id)]
10778 if {!$td} {
10779 incr nc -1
10780 }
10781 # ignore tags on starting node
10782 if {!$td && $i > 0} {
10783 if {[info exists idtags($id)]} {
10784 set tagloc($id) $id
10785 set td 1
10786 } elseif {[info exists cached_atags($id)]} {
10787 set tagloc($id) $cached_atags($id)
10788 set td 1
10789 }
10790 }
10791 foreach a $arcout($id) {
10792 if {!$td && $arctags($a) ne {}} {
10793 validate_arctags $a
10794 if {$arctags($a) ne {}} {
10795 lappend tagloc($id) [lindex $arctags($a) 0]
10796 }
10797 }
10798 if {![info exists arcend($a)]} continue
10799 set d $arcend($a)
10800 if {$td || $arctags($a) ne {}} {
10801 set tomark [list $d]
10802 for {set j 0} {$j < [llength $tomark]} {incr j} {
10803 set dd [lindex $tomark $j]
10804 if {![info exists hastaggeddescendent($dd)]} {
10805 if {[info exists done($dd)]} {
10806 foreach b $arcout($dd) {
10807 if {[info exists arcend($b)]} {
10808 lappend tomark $arcend($b)
10809 }
10810 }
10811 if {[info exists tagloc($dd)]} {
10812 unset tagloc($dd)
10813 }
10814 } elseif {[info exists queued($dd)]} {
10815 incr nc -1
10816 }
10817 set hastaggeddescendent($dd) 1
10818 }
10819 }
10820 }
10821 if {![info exists queued($d)]} {
10822 lappend todo $d
10823 set queued($d) 1
10824 if {![info exists hastaggeddescendent($d)]} {
10825 incr nc
10826 }
10827 }
10828 }
10829 }
10830 set t2 [clock clicks -milliseconds]
10831 set loopix $i
10832 set tags {}
10833 foreach id [array names tagloc] {
10834 if {![info exists hastaggeddescendent($id)]} {
10835 foreach t $tagloc($id) {
10836 if {[lsearch -exact $tags $t] < 0} {
10837 lappend tags $t
10838 }
10839 }
10840 }
10841 }
10842
10843 # remove tags that are ancestors of other tags
10844 for {set i 0} {$i < [llength $tags]} {incr i} {
10845 set a [lindex $tags $i]
10846 for {set j 0} {$j < $i} {incr j} {
10847 set b [lindex $tags $j]
10848 set r [anc_or_desc $a $b]
10849 if {$r == -1} {
10850 set tags [lreplace $tags $j $j]
10851 incr j -1
10852 incr i -1
10853 } elseif {$r == 1} {
10854 set tags [lreplace $tags $i $i]
10855 incr i -1
10856 break
10857 }
10858 }
10859 }
10860
10861 if {[array names growing] ne {}} {
10862 # graph isn't finished, need to check if any tag could get
10863 # eclipsed by another tag coming later. Simply ignore any
10864 # tags that could later get eclipsed.
10865 set ctags {}
10866 foreach t $tags {
10867 if {[is_certain $origid $t]} {
10868 lappend ctags $t
10869 }
10870 }
10871 if {$tags eq $ctags} {
10872 set cached_atags($origid) $tags
10873 } else {
10874 set tags $ctags
10875 }
10876 } else {
10877 set cached_atags($origid) $tags
10878 }
10879 set t3 [clock clicks -milliseconds]
10880 if {0 && $t3 - $t1 >= 100} {
10881 puts "iterating ancestors ($loopix/[llength $todo] nodes) took\
10882 [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10883 }
10884 return $tags
10885}
10886
10887# Return the list of IDs that have heads that are descendents of id,
10888# including id itself if it has a head.
10889proc descheads {id} {
10890 global arcnos arcstart arcids archeads idheads cached_dheads
10891 global allparents arcout
10892
10893 if {![info exists allparents($id)]} {
10894 return {}
10895 }
10896 set aret {}
10897 if {![info exists arcout($id)]} {
10898 # part-way along an arc; check it first
10899 set a [lindex $arcnos($id) 0]
10900 if {$archeads($a) ne {}} {
10901 validate_archeads $a
10902 set i [lsearch -exact $arcids($a) $id]
10903 foreach t $archeads($a) {
10904 set j [lsearch -exact $arcids($a) $t]
10905 if {$j > $i} break
10906 lappend aret $t
10907 }
10908 }
10909 set id $arcstart($a)
10910 }
10911 set origid $id
10912 set todo [list $id]
10913 set seen($id) 1
10914 set ret {}
10915 for {set i 0} {$i < [llength $todo]} {incr i} {
10916 set id [lindex $todo $i]
10917 if {[info exists cached_dheads($id)]} {
10918 set ret [concat $ret $cached_dheads($id)]
10919 } else {
10920 if {[info exists idheads($id)]} {
10921 lappend ret $id
10922 }
10923 foreach a $arcnos($id) {
10924 if {$archeads($a) ne {}} {
10925 validate_archeads $a
10926 if {$archeads($a) ne {}} {
10927 set ret [concat $ret $archeads($a)]
10928 }
10929 }
10930 set d $arcstart($a)
10931 if {![info exists seen($d)]} {
10932 lappend todo $d
10933 set seen($d) 1
10934 }
10935 }
10936 }
10937 }
10938 set ret [lsort -unique $ret]
10939 set cached_dheads($origid) $ret
10940 return [concat $ret $aret]
10941}
10942
10943proc addedtag {id} {
10944 global arcnos arcout cached_dtags cached_atags
10945
10946 if {![info exists arcnos($id)]} return
10947 if {![info exists arcout($id)]} {
10948 recalcarc [lindex $arcnos($id) 0]
10949 }
10950 catch {unset cached_dtags}
10951 catch {unset cached_atags}
10952}
10953
10954proc addedhead {hid head} {
10955 global arcnos arcout cached_dheads
10956
10957 if {![info exists arcnos($hid)]} return
10958 if {![info exists arcout($hid)]} {
10959 recalcarc [lindex $arcnos($hid) 0]
10960 }
10961 catch {unset cached_dheads}
10962}
10963
10964proc removedhead {hid head} {
10965 global cached_dheads
10966
10967 catch {unset cached_dheads}
10968}
10969
10970proc movedhead {hid head} {
10971 global arcnos arcout cached_dheads
10972
10973 if {![info exists arcnos($hid)]} return
10974 if {![info exists arcout($hid)]} {
10975 recalcarc [lindex $arcnos($hid) 0]
10976 }
10977 catch {unset cached_dheads}
10978}
10979
10980proc changedrefs {} {
10981 global cached_dheads cached_dtags cached_atags cached_tagcontent
10982 global arctags archeads arcnos arcout idheads idtags
10983
10984 foreach id [concat [array names idheads] [array names idtags]] {
10985 if {[info exists arcnos($id)] && ![info exists arcout($id)]} {
10986 set a [lindex $arcnos($id) 0]
10987 if {![info exists donearc($a)]} {
10988 recalcarc $a
10989 set donearc($a) 1
10990 }
10991 }
10992 }
10993 catch {unset cached_tagcontent}
10994 catch {unset cached_dtags}
10995 catch {unset cached_atags}
10996 catch {unset cached_dheads}
10997}
10998
10999proc rereadrefs {} {
11000 global idtags idheads idotherrefs mainheadid
11001
11002 set refids [concat [array names idtags] \
11003 [array names idheads] [array names idotherrefs]]
11004 foreach id $refids {
11005 if {![info exists ref($id)]} {
11006 set ref($id) [listrefs $id]
11007 }
11008 }
11009 set oldmainhead $mainheadid
11010 readrefs
11011 changedrefs
11012 set refids [lsort -unique [concat $refids [array names idtags] \
11013 [array names idheads] [array names idotherrefs]]]
11014 foreach id $refids {
11015 set v [listrefs $id]
11016 if {![info exists ref($id)] || $ref($id) != $v} {
11017 redrawtags $id
11018 }
11019 }
11020 if {$oldmainhead ne $mainheadid} {
11021 redrawtags $oldmainhead
11022 redrawtags $mainheadid
11023 }
11024 run refill_reflist
11025}
11026
11027proc listrefs {id} {
11028 global idtags idheads idotherrefs
11029
11030 set x {}
11031 if {[info exists idtags($id)]} {
11032 set x $idtags($id)
11033 }
11034 set y {}
11035 if {[info exists idheads($id)]} {
11036 set y $idheads($id)
11037 }
11038 set z {}
11039 if {[info exists idotherrefs($id)]} {
11040 set z $idotherrefs($id)
11041 }
11042 return [list $x $y $z]
11043}
11044
11045proc add_tag_ctext {tag} {
11046 global ctext cached_tagcontent tagids
11047
11048 if {![info exists cached_tagcontent($tag)]} {
11049 catch {
11050 set cached_tagcontent($tag) [exec git cat-file -p $tag]
11051 }
11052 }
11053 $ctext insert end "[mc "Tag"]: $tag\n" bold
11054 if {[info exists cached_tagcontent($tag)]} {
11055 set text $cached_tagcontent($tag)
11056 } else {
11057 set text "[mc "Id"]: $tagids($tag)"
11058 }
11059 appendwithlinks $text {}
11060}
11061
11062proc showtag {tag isnew} {
11063 global ctext cached_tagcontent tagids linknum tagobjid
11064
11065 if {$isnew} {
11066 addtohistory [list showtag $tag 0] savectextpos
11067 }
11068 $ctext conf -state normal
11069 clear_ctext
11070 settabs 0
11071 set linknum 0
11072 add_tag_ctext $tag
11073 maybe_scroll_ctext 1
11074 $ctext conf -state disabled
11075 init_flist {}
11076}
11077
11078proc showtags {id isnew} {
11079 global idtags ctext linknum
11080
11081 if {$isnew} {
11082 addtohistory [list showtags $id 0] savectextpos
11083 }
11084 $ctext conf -state normal
11085 clear_ctext
11086 settabs 0
11087 set linknum 0
11088 set sep {}
11089 foreach tag $idtags($id) {
11090 $ctext insert end $sep
11091 add_tag_ctext $tag
11092 set sep "\n\n"
11093 }
11094 maybe_scroll_ctext 1
11095 $ctext conf -state disabled
11096 init_flist {}
11097}
11098
11099proc doquit {} {
11100 global stopped
11101 global gitktmpdir
11102
11103 set stopped 100
11104 savestuff .
11105 destroy .
11106
11107 if {[info exists gitktmpdir]} {
11108 catch {file delete -force $gitktmpdir}
11109 }
11110}
11111
11112proc mkfontdisp {font top which} {
11113 global fontattr fontpref $font NS use_ttk
11114
11115 set fontpref($font) [set $font]
11116 ${NS}::button $top.${font}but -text $which \
11117 -command [list choosefont $font $which]
11118 ${NS}::label $top.$font -relief flat -font $font \
11119 -text $fontattr($font,family) -justify left
11120 grid x $top.${font}but $top.$font -sticky w
11121}
11122
11123proc choosefont {font which} {
11124 global fontparam fontlist fonttop fontattr
11125 global prefstop NS
11126
11127 set fontparam(which) $which
11128 set fontparam(font) $font
11129 set fontparam(family) [font actual $font -family]
11130 set fontparam(size) $fontattr($font,size)
11131 set fontparam(weight) $fontattr($font,weight)
11132 set fontparam(slant) $fontattr($font,slant)
11133 set top .gitkfont
11134 set fonttop $top
11135 if {![winfo exists $top]} {
11136 font create sample
11137 eval font config sample [font actual $font]
11138 ttk_toplevel $top
11139 make_transient $top $prefstop
11140 wm title $top [mc "Gitk font chooser"]
11141 ${NS}::label $top.l -textvariable fontparam(which)
11142 pack $top.l -side top
11143 set fontlist [lsort [font families]]
11144 ${NS}::frame $top.f
11145 listbox $top.f.fam -listvariable fontlist \
11146 -yscrollcommand [list $top.f.sb set]
11147 bind $top.f.fam <<ListboxSelect>> selfontfam
11148 ${NS}::scrollbar $top.f.sb -command [list $top.f.fam yview]
11149 pack $top.f.sb -side right -fill y
11150 pack $top.f.fam -side left -fill both -expand 1
11151 pack $top.f -side top -fill both -expand 1
11152 ${NS}::frame $top.g
11153 spinbox $top.g.size -from 4 -to 40 -width 4 \
11154 -textvariable fontparam(size) \
11155 -validatecommand {string is integer -strict %s}
11156 checkbutton $top.g.bold -padx 5 \
11157 -font {{Times New Roman} 12 bold} -text [mc "B"] -indicatoron 0 \
11158 -variable fontparam(weight) -onvalue bold -offvalue normal
11159 checkbutton $top.g.ital -padx 5 \
11160 -font {{Times New Roman} 12 italic} -text [mc "I"] -indicatoron 0 \
11161 -variable fontparam(slant) -onvalue italic -offvalue roman
11162 pack $top.g.size $top.g.bold $top.g.ital -side left
11163 pack $top.g -side top
11164 canvas $top.c -width 150 -height 50 -border 2 -relief sunk \
11165 -background white
11166 $top.c create text 100 25 -anchor center -text $which -font sample \
11167 -fill black -tags text
11168 bind $top.c <Configure> [list centertext $top.c]
11169 pack $top.c -side top -fill x
11170 ${NS}::frame $top.buts
11171 ${NS}::button $top.buts.ok -text [mc "OK"] -command fontok -default active
11172 ${NS}::button $top.buts.can -text [mc "Cancel"] -command fontcan -default normal
11173 bind $top <Key-Return> fontok
11174 bind $top <Key-Escape> fontcan
11175 grid $top.buts.ok $top.buts.can
11176 grid columnconfigure $top.buts 0 -weight 1 -uniform a
11177 grid columnconfigure $top.buts 1 -weight 1 -uniform a
11178 pack $top.buts -side bottom -fill x
11179 trace add variable fontparam write chg_fontparam
11180 } else {
11181 raise $top
11182 $top.c itemconf text -text $which
11183 }
11184 set i [lsearch -exact $fontlist $fontparam(family)]
11185 if {$i >= 0} {
11186 $top.f.fam selection set $i
11187 $top.f.fam see $i
11188 }
11189}
11190
11191proc centertext {w} {
11192 $w coords text [expr {[winfo width $w] / 2}] [expr {[winfo height $w] / 2}]
11193}
11194
11195proc fontok {} {
11196 global fontparam fontpref prefstop
11197
11198 set f $fontparam(font)
11199 set fontpref($f) [list $fontparam(family) $fontparam(size)]
11200 if {$fontparam(weight) eq "bold"} {
11201 lappend fontpref($f) "bold"
11202 }
11203 if {$fontparam(slant) eq "italic"} {
11204 lappend fontpref($f) "italic"
11205 }
11206 set w $prefstop.notebook.fonts.$f
11207 $w conf -text $fontparam(family) -font $fontpref($f)
11208
11209 fontcan
11210}
11211
11212proc fontcan {} {
11213 global fonttop fontparam
11214
11215 if {[info exists fonttop]} {
11216 catch {destroy $fonttop}
11217 catch {font delete sample}
11218 unset fonttop
11219 unset fontparam
11220 }
11221}
11222
11223if {[package vsatisfies [package provide Tk] 8.6]} {
11224 # In Tk 8.6 we have a native font chooser dialog. Overwrite the above
11225 # function to make use of it.
11226 proc choosefont {font which} {
11227 tk fontchooser configure -title $which -font $font \
11228 -command [list on_choosefont $font $which]
11229 tk fontchooser show
11230 }
11231 proc on_choosefont {font which newfont} {
11232 global fontparam
11233 puts stderr "$font $newfont"
11234 array set f [font actual $newfont]
11235 set fontparam(which) $which
11236 set fontparam(font) $font
11237 set fontparam(family) $f(-family)
11238 set fontparam(size) $f(-size)
11239 set fontparam(weight) $f(-weight)
11240 set fontparam(slant) $f(-slant)
11241 fontok
11242 }
11243}
11244
11245proc selfontfam {} {
11246 global fonttop fontparam
11247
11248 set i [$fonttop.f.fam curselection]
11249 if {$i ne {}} {
11250 set fontparam(family) [$fonttop.f.fam get $i]
11251 }
11252}
11253
11254proc chg_fontparam {v sub op} {
11255 global fontparam
11256
11257 font config sample -$sub $fontparam($sub)
11258}
11259
11260# Create a property sheet tab page
11261proc create_prefs_page {w} {
11262 global NS
11263 set parent [join [lrange [split $w .] 0 end-1] .]
11264 if {[winfo class $parent] eq "TNotebook"} {
11265 ${NS}::frame $w
11266 } else {
11267 ${NS}::labelframe $w
11268 }
11269}
11270
11271proc prefspage_general {notebook} {
11272 global NS maxwidth maxgraphpct showneartags showlocalchanges
11273 global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11274 global hideremotes want_ttk have_ttk maxrefs
11275
11276 set page [create_prefs_page $notebook.general]
11277
11278 ${NS}::label $page.ldisp -text [mc "Commit list display options"]
11279 grid $page.ldisp - -sticky w -pady 10
11280 ${NS}::label $page.spacer -text " "
11281 ${NS}::label $page.maxwidthl -text [mc "Maximum graph width (lines)"]
11282 spinbox $page.maxwidth -from 0 -to 100 -width 4 -textvariable maxwidth
11283 grid $page.spacer $page.maxwidthl $page.maxwidth -sticky w
11284 ${NS}::label $page.maxpctl -text [mc "Maximum graph width (% of pane)"]
11285 spinbox $page.maxpct -from 1 -to 100 -width 4 -textvariable maxgraphpct
11286 grid x $page.maxpctl $page.maxpct -sticky w
11287 ${NS}::checkbutton $page.showlocal -text [mc "Show local changes"] \
11288 -variable showlocalchanges
11289 grid x $page.showlocal -sticky w
11290 ${NS}::checkbutton $page.autoselect -text [mc "Auto-select SHA1 (length)"] \
11291 -variable autoselect
11292 spinbox $page.autosellen -from 1 -to 40 -width 4 -textvariable autosellen
11293 grid x $page.autoselect $page.autosellen -sticky w
11294 ${NS}::checkbutton $page.hideremotes -text [mc "Hide remote refs"] \
11295 -variable hideremotes
11296 grid x $page.hideremotes -sticky w
11297
11298 ${NS}::label $page.ddisp -text [mc "Diff display options"]
11299 grid $page.ddisp - -sticky w -pady 10
11300 ${NS}::label $page.tabstopl -text [mc "Tab spacing"]
11301 spinbox $page.tabstop -from 1 -to 20 -width 4 -textvariable tabstop
11302 grid x $page.tabstopl $page.tabstop -sticky w
11303 ${NS}::checkbutton $page.ntag -text [mc "Display nearby tags/heads"] \
11304 -variable showneartags
11305 grid x $page.ntag -sticky w
11306 ${NS}::label $page.maxrefsl -text [mc "Maximum # tags/heads to show"]
11307 spinbox $page.maxrefs -from 1 -to 1000 -width 4 -textvariable maxrefs
11308 grid x $page.maxrefsl $page.maxrefs -sticky w
11309 ${NS}::checkbutton $page.ldiff -text [mc "Limit diffs to listed paths"] \
11310 -variable limitdiffs
11311 grid x $page.ldiff -sticky w
11312 ${NS}::checkbutton $page.lattr -text [mc "Support per-file encodings"] \
11313 -variable perfile_attrs
11314 grid x $page.lattr -sticky w
11315
11316 ${NS}::entry $page.extdifft -textvariable extdifftool
11317 ${NS}::frame $page.extdifff
11318 ${NS}::label $page.extdifff.l -text [mc "External diff tool" ]
11319 ${NS}::button $page.extdifff.b -text [mc "Choose..."] -command choose_extdiff
11320 pack $page.extdifff.l $page.extdifff.b -side left
11321 pack configure $page.extdifff.l -padx 10
11322 grid x $page.extdifff $page.extdifft -sticky ew
11323
11324 ${NS}::label $page.lgen -text [mc "General options"]
11325 grid $page.lgen - -sticky w -pady 10
11326 ${NS}::checkbutton $page.want_ttk -variable want_ttk \
11327 -text [mc "Use themed widgets"]
11328 if {$have_ttk} {
11329 ${NS}::label $page.ttk_note -text [mc "(change requires restart)"]
11330 } else {
11331 ${NS}::label $page.ttk_note -text [mc "(currently unavailable)"]
11332 }
11333 grid x $page.want_ttk $page.ttk_note -sticky w
11334 return $page
11335}
11336
11337proc prefspage_colors {notebook} {
11338 global NS uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11339
11340 set page [create_prefs_page $notebook.colors]
11341
11342 ${NS}::label $page.cdisp -text [mc "Colors: press to choose"]
11343 grid $page.cdisp - -sticky w -pady 10
11344 label $page.ui -padx 40 -relief sunk -background $uicolor
11345 ${NS}::button $page.uibut -text [mc "Interface"] \
11346 -command [list choosecolor uicolor {} $page.ui [mc "interface"] setui]
11347 grid x $page.uibut $page.ui -sticky w
11348 label $page.bg -padx 40 -relief sunk -background $bgcolor
11349 ${NS}::button $page.bgbut -text [mc "Background"] \
11350 -command [list choosecolor bgcolor {} $page.bg [mc "background"] setbg]
11351 grid x $page.bgbut $page.bg -sticky w
11352 label $page.fg -padx 40 -relief sunk -background $fgcolor
11353 ${NS}::button $page.fgbut -text [mc "Foreground"] \
11354 -command [list choosecolor fgcolor {} $page.fg [mc "foreground"] setfg]
11355 grid x $page.fgbut $page.fg -sticky w
11356 label $page.diffold -padx 40 -relief sunk -background [lindex $diffcolors 0]
11357 ${NS}::button $page.diffoldbut -text [mc "Diff: old lines"] \
11358 -command [list choosecolor diffcolors 0 $page.diffold [mc "diff old lines"] \
11359 [list $ctext tag conf d0 -foreground]]
11360 grid x $page.diffoldbut $page.diffold -sticky w
11361 label $page.diffnew -padx 40 -relief sunk -background [lindex $diffcolors 1]
11362 ${NS}::button $page.diffnewbut -text [mc "Diff: new lines"] \
11363 -command [list choosecolor diffcolors 1 $page.diffnew [mc "diff new lines"] \
11364 [list $ctext tag conf dresult -foreground]]
11365 grid x $page.diffnewbut $page.diffnew -sticky w
11366 label $page.hunksep -padx 40 -relief sunk -background [lindex $diffcolors 2]
11367 ${NS}::button $page.hunksepbut -text [mc "Diff: hunk header"] \
11368 -command [list choosecolor diffcolors 2 $page.hunksep \
11369 [mc "diff hunk header"] \
11370 [list $ctext tag conf hunksep -foreground]]
11371 grid x $page.hunksepbut $page.hunksep -sticky w
11372 label $page.markbgsep -padx 40 -relief sunk -background $markbgcolor
11373 ${NS}::button $page.markbgbut -text [mc "Marked line bg"] \
11374 -command [list choosecolor markbgcolor {} $page.markbgsep \
11375 [mc "marked line background"] \
11376 [list $ctext tag conf omark -background]]
11377 grid x $page.markbgbut $page.markbgsep -sticky w
11378 label $page.selbgsep -padx 40 -relief sunk -background $selectbgcolor
11379 ${NS}::button $page.selbgbut -text [mc "Select bg"] \
11380 -command [list choosecolor selectbgcolor {} $page.selbgsep [mc "background"] setselbg]
11381 grid x $page.selbgbut $page.selbgsep -sticky w
11382 return $page
11383}
11384
11385proc prefspage_fonts {notebook} {
11386 global NS
11387 set page [create_prefs_page $notebook.fonts]
11388 ${NS}::label $page.cfont -text [mc "Fonts: press to choose"]
11389 grid $page.cfont - -sticky w -pady 10
11390 mkfontdisp mainfont $page [mc "Main font"]
11391 mkfontdisp textfont $page [mc "Diff display font"]
11392 mkfontdisp uifont $page [mc "User interface font"]
11393 return $page
11394}
11395
11396proc doprefs {} {
11397 global maxwidth maxgraphpct use_ttk NS
11398 global oldprefs prefstop showneartags showlocalchanges
11399 global uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11400 global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11401 global hideremotes want_ttk have_ttk
11402
11403 set top .gitkprefs
11404 set prefstop $top
11405 if {[winfo exists $top]} {
11406 raise $top
11407 return
11408 }
11409 foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11410 limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11411 set oldprefs($v) [set $v]
11412 }
11413 ttk_toplevel $top
11414 wm title $top [mc "Gitk preferences"]
11415 make_transient $top .
11416
11417 if {[set use_notebook [expr {$use_ttk && [info command ::ttk::notebook] ne ""}]]} {
11418 set notebook [ttk::notebook $top.notebook]
11419 } else {
11420 set notebook [${NS}::frame $top.notebook -borderwidth 0 -relief flat]
11421 }
11422
11423 lappend pages [prefspage_general $notebook] [mc "General"]
11424 lappend pages [prefspage_colors $notebook] [mc "Colors"]
11425 lappend pages [prefspage_fonts $notebook] [mc "Fonts"]
11426 set col 0
11427 foreach {page title} $pages {
11428 if {$use_notebook} {
11429 $notebook add $page -text $title
11430 } else {
11431 set btn [${NS}::button $notebook.b_[string map {. X} $page] \
11432 -text $title -command [list raise $page]]
11433 $page configure -text $title
11434 grid $btn -row 0 -column [incr col] -sticky w
11435 grid $page -row 1 -column 0 -sticky news -columnspan 100
11436 }
11437 }
11438
11439 if {!$use_notebook} {
11440 grid columnconfigure $notebook 0 -weight 1
11441 grid rowconfigure $notebook 1 -weight 1
11442 raise [lindex $pages 0]
11443 }
11444
11445 grid $notebook -sticky news -padx 2 -pady 2
11446 grid rowconfigure $top 0 -weight 1
11447 grid columnconfigure $top 0 -weight 1
11448
11449 ${NS}::frame $top.buts
11450 ${NS}::button $top.buts.ok -text [mc "OK"] -command prefsok -default active
11451 ${NS}::button $top.buts.can -text [mc "Cancel"] -command prefscan -default normal
11452 bind $top <Key-Return> prefsok
11453 bind $top <Key-Escape> prefscan
11454 grid $top.buts.ok $top.buts.can
11455 grid columnconfigure $top.buts 0 -weight 1 -uniform a
11456 grid columnconfigure $top.buts 1 -weight 1 -uniform a
11457 grid $top.buts - - -pady 10 -sticky ew
11458 grid columnconfigure $top 2 -weight 1
11459 bind $top <Visibility> [list focus $top.buts.ok]
11460}
11461
11462proc choose_extdiff {} {
11463 global extdifftool
11464
11465 set prog [tk_getOpenFile -title [mc "External diff tool"] -multiple false]
11466 if {$prog ne {}} {
11467 set extdifftool $prog
11468 }
11469}
11470
11471proc choosecolor {v vi w x cmd} {
11472 global $v
11473
11474 set c [tk_chooseColor -initialcolor [lindex [set $v] $vi] \
11475 -title [mc "Gitk: choose color for %s" $x]]
11476 if {$c eq {}} return
11477 $w conf -background $c
11478 lset $v $vi $c
11479 eval $cmd $c
11480}
11481
11482proc setselbg {c} {
11483 global bglist cflist
11484 foreach w $bglist {
11485 $w configure -selectbackground $c
11486 }
11487 $cflist tag configure highlight \
11488 -background [$cflist cget -selectbackground]
11489 allcanvs itemconf secsel -fill $c
11490}
11491
11492# This sets the background color and the color scheme for the whole UI.
11493# For some reason, tk_setPalette chooses a nasty dark red for selectColor
11494# if we don't specify one ourselves, which makes the checkbuttons and
11495# radiobuttons look bad. This chooses white for selectColor if the
11496# background color is light, or black if it is dark.
11497proc setui {c} {
11498 if {[tk windowingsystem] eq "win32"} { return }
11499 set bg [winfo rgb . $c]
11500 set selc black
11501 if {[lindex $bg 0] + 1.5 * [lindex $bg 1] + 0.5 * [lindex $bg 2] > 100000} {
11502 set selc white
11503 }
11504 tk_setPalette background $c selectColor $selc
11505}
11506
11507proc setbg {c} {
11508 global bglist
11509
11510 foreach w $bglist {
11511 $w conf -background $c
11512 }
11513}
11514
11515proc setfg {c} {
11516 global fglist canv
11517
11518 foreach w $fglist {
11519 $w conf -foreground $c
11520 }
11521 allcanvs itemconf text -fill $c
11522 $canv itemconf circle -outline $c
11523 $canv itemconf markid -outline $c
11524}
11525
11526proc prefscan {} {
11527 global oldprefs prefstop
11528
11529 foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11530 limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11531 global $v
11532 set $v $oldprefs($v)
11533 }
11534 catch {destroy $prefstop}
11535 unset prefstop
11536 fontcan
11537}
11538
11539proc prefsok {} {
11540 global maxwidth maxgraphpct
11541 global oldprefs prefstop showneartags showlocalchanges
11542 global fontpref mainfont textfont uifont
11543 global limitdiffs treediffs perfile_attrs
11544 global hideremotes
11545
11546 catch {destroy $prefstop}
11547 unset prefstop
11548 fontcan
11549 set fontchanged 0
11550 if {$mainfont ne $fontpref(mainfont)} {
11551 set mainfont $fontpref(mainfont)
11552 parsefont mainfont $mainfont
11553 eval font configure mainfont [fontflags mainfont]
11554 eval font configure mainfontbold [fontflags mainfont 1]
11555 setcoords
11556 set fontchanged 1
11557 }
11558 if {$textfont ne $fontpref(textfont)} {
11559 set textfont $fontpref(textfont)
11560 parsefont textfont $textfont
11561 eval font configure textfont [fontflags textfont]
11562 eval font configure textfontbold [fontflags textfont 1]
11563 }
11564 if {$uifont ne $fontpref(uifont)} {
11565 set uifont $fontpref(uifont)
11566 parsefont uifont $uifont
11567 eval font configure uifont [fontflags uifont]
11568 }
11569 settabs
11570 if {$showlocalchanges != $oldprefs(showlocalchanges)} {
11571 if {$showlocalchanges} {
11572 doshowlocalchanges
11573 } else {
11574 dohidelocalchanges
11575 }
11576 }
11577 if {$limitdiffs != $oldprefs(limitdiffs) ||
11578 ($perfile_attrs && !$oldprefs(perfile_attrs))} {
11579 # treediffs elements are limited by path;
11580 # won't have encodings cached if perfile_attrs was just turned on
11581 catch {unset treediffs}
11582 }
11583 if {$fontchanged || $maxwidth != $oldprefs(maxwidth)
11584 || $maxgraphpct != $oldprefs(maxgraphpct)} {
11585 redisplay
11586 } elseif {$showneartags != $oldprefs(showneartags) ||
11587 $limitdiffs != $oldprefs(limitdiffs)} {
11588 reselectline
11589 }
11590 if {$hideremotes != $oldprefs(hideremotes)} {
11591 rereadrefs
11592 }
11593}
11594
11595proc formatdate {d} {
11596 global datetimeformat
11597 if {$d ne {}} {
11598 # If $datetimeformat includes a timezone, display in the
11599 # timezone of the argument. Otherwise, display in local time.
11600 if {[string match {*%[zZ]*} $datetimeformat]} {
11601 if {[catch {set d [clock format [lindex $d 0] -timezone [lindex $d 1] -format $datetimeformat]}]} {
11602 # Tcl < 8.5 does not support -timezone. Emulate it by
11603 # setting TZ (e.g. TZ=<-0430>+04:30).
11604 global env
11605 if {[info exists env(TZ)]} {
11606 set savedTZ $env(TZ)
11607 }
11608 set zone [lindex $d 1]
11609 set sign [string map {+ - - +} [string index $zone 0]]
11610 set env(TZ) <$zone>$sign[string range $zone 1 2]:[string range $zone 3 4]
11611 set d [clock format [lindex $d 0] -format $datetimeformat]
11612 if {[info exists savedTZ]} {
11613 set env(TZ) $savedTZ
11614 } else {
11615 unset env(TZ)
11616 }
11617 }
11618 } else {
11619 set d [clock format [lindex $d 0] -format $datetimeformat]
11620 }
11621 }
11622 return $d
11623}
11624
11625# This list of encoding names and aliases is distilled from
11626# http://www.iana.org/assignments/character-sets.
11627# Not all of them are supported by Tcl.
11628set encoding_aliases {
11629 { ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ASCII
11630 ISO646-US US-ASCII us IBM367 cp367 csASCII }
11631 { ISO-10646-UTF-1 csISO10646UTF1 }
11632 { ISO_646.basic:1983 ref csISO646basic1983 }
11633 { INVARIANT csINVARIANT }
11634 { ISO_646.irv:1983 iso-ir-2 irv csISO2IntlRefVersion }
11635 { BS_4730 iso-ir-4 ISO646-GB gb uk csISO4UnitedKingdom }
11636 { NATS-SEFI iso-ir-8-1 csNATSSEFI }
11637 { NATS-SEFI-ADD iso-ir-8-2 csNATSSEFIADD }
11638 { NATS-DANO iso-ir-9-1 csNATSDANO }
11639 { NATS-DANO-ADD iso-ir-9-2 csNATSDANOADD }
11640 { SEN_850200_B iso-ir-10 FI ISO646-FI ISO646-SE se csISO10Swedish }
11641 { SEN_850200_C iso-ir-11 ISO646-SE2 se2 csISO11SwedishForNames }
11642 { KS_C_5601-1987 iso-ir-149 KS_C_5601-1989 KSC_5601 korean csKSC56011987 }
11643 { ISO-2022-KR csISO2022KR }
11644 { EUC-KR csEUCKR }
11645 { ISO-2022-JP csISO2022JP }
11646 { ISO-2022-JP-2 csISO2022JP2 }
11647 { JIS_C6220-1969-jp JIS_C6220-1969 iso-ir-13 katakana x0201-7
11648 csISO13JISC6220jp }
11649 { JIS_C6220-1969-ro iso-ir-14 jp ISO646-JP csISO14JISC6220ro }
11650 { IT iso-ir-15 ISO646-IT csISO15Italian }
11651 { PT iso-ir-16 ISO646-PT csISO16Portuguese }
11652 { ES iso-ir-17 ISO646-ES csISO17Spanish }
11653 { greek7-old iso-ir-18 csISO18Greek7Old }
11654 { latin-greek iso-ir-19 csISO19LatinGreek }
11655 { DIN_66003 iso-ir-21 de ISO646-DE csISO21German }
11656 { NF_Z_62-010_(1973) iso-ir-25 ISO646-FR1 csISO25French }
11657 { Latin-greek-1 iso-ir-27 csISO27LatinGreek1 }
11658 { ISO_5427 iso-ir-37 csISO5427Cyrillic }
11659 { JIS_C6226-1978 iso-ir-42 csISO42JISC62261978 }
11660 { BS_viewdata iso-ir-47 csISO47BSViewdata }
11661 { INIS iso-ir-49 csISO49INIS }
11662 { INIS-8 iso-ir-50 csISO50INIS8 }
11663 { INIS-cyrillic iso-ir-51 csISO51INISCyrillic }
11664 { ISO_5427:1981 iso-ir-54 ISO5427Cyrillic1981 }
11665 { ISO_5428:1980 iso-ir-55 csISO5428Greek }
11666 { GB_1988-80 iso-ir-57 cn ISO646-CN csISO57GB1988 }
11667 { GB_2312-80 iso-ir-58 chinese csISO58GB231280 }
11668 { NS_4551-1 iso-ir-60 ISO646-NO no csISO60DanishNorwegian
11669 csISO60Norwegian1 }
11670 { NS_4551-2 ISO646-NO2 iso-ir-61 no2 csISO61Norwegian2 }
11671 { NF_Z_62-010 iso-ir-69 ISO646-FR fr csISO69French }
11672 { videotex-suppl iso-ir-70 csISO70VideotexSupp1 }
11673 { PT2 iso-ir-84 ISO646-PT2 csISO84Portuguese2 }
11674 { ES2 iso-ir-85 ISO646-ES2 csISO85Spanish2 }
11675 { MSZ_7795.3 iso-ir-86 ISO646-HU hu csISO86Hungarian }
11676 { JIS_C6226-1983 iso-ir-87 x0208 JIS_X0208-1983 csISO87JISX0208 }
11677 { greek7 iso-ir-88 csISO88Greek7 }
11678 { ASMO_449 ISO_9036 arabic7 iso-ir-89 csISO89ASMO449 }
11679 { iso-ir-90 csISO90 }
11680 { JIS_C6229-1984-a iso-ir-91 jp-ocr-a csISO91JISC62291984a }
11681 { JIS_C6229-1984-b iso-ir-92 ISO646-JP-OCR-B jp-ocr-b
11682 csISO92JISC62991984b }
11683 { JIS_C6229-1984-b-add iso-ir-93 jp-ocr-b-add csISO93JIS62291984badd }
11684 { JIS_C6229-1984-hand iso-ir-94 jp-ocr-hand csISO94JIS62291984hand }
11685 { JIS_C6229-1984-hand-add iso-ir-95 jp-ocr-hand-add
11686 csISO95JIS62291984handadd }
11687 { JIS_C6229-1984-kana iso-ir-96 csISO96JISC62291984kana }
11688 { ISO_2033-1983 iso-ir-98 e13b csISO2033 }
11689 { ANSI_X3.110-1983 iso-ir-99 CSA_T500-1983 NAPLPS csISO99NAPLPS }
11690 { ISO_8859-1:1987 iso-ir-100 ISO_8859-1 ISO-8859-1 latin1 l1 IBM819
11691 CP819 csISOLatin1 }
11692 { ISO_8859-2:1987 iso-ir-101 ISO_8859-2 ISO-8859-2 latin2 l2 csISOLatin2 }
11693 { T.61-7bit iso-ir-102 csISO102T617bit }
11694 { T.61-8bit T.61 iso-ir-103 csISO103T618bit }
11695 { ISO_8859-3:1988 iso-ir-109 ISO_8859-3 ISO-8859-3 latin3 l3 csISOLatin3 }
11696 { ISO_8859-4:1988 iso-ir-110 ISO_8859-4 ISO-8859-4 latin4 l4 csISOLatin4 }
11697 { ECMA-cyrillic iso-ir-111 KOI8-E csISO111ECMACyrillic }
11698 { CSA_Z243.4-1985-1 iso-ir-121 ISO646-CA csa7-1 ca csISO121Canadian1 }
11699 { CSA_Z243.4-1985-2 iso-ir-122 ISO646-CA2 csa7-2 csISO122Canadian2 }
11700 { CSA_Z243.4-1985-gr iso-ir-123 csISO123CSAZ24341985gr }
11701 { ISO_8859-6:1987 iso-ir-127 ISO_8859-6 ISO-8859-6 ECMA-114 ASMO-708
11702 arabic csISOLatinArabic }
11703 { ISO_8859-6-E csISO88596E ISO-8859-6-E }
11704 { ISO_8859-6-I csISO88596I ISO-8859-6-I }
11705 { ISO_8859-7:1987 iso-ir-126 ISO_8859-7 ISO-8859-7 ELOT_928 ECMA-118
11706 greek greek8 csISOLatinGreek }
11707 { T.101-G2 iso-ir-128 csISO128T101G2 }
11708 { ISO_8859-8:1988 iso-ir-138 ISO_8859-8 ISO-8859-8 hebrew
11709 csISOLatinHebrew }
11710 { ISO_8859-8-E csISO88598E ISO-8859-8-E }
11711 { ISO_8859-8-I csISO88598I ISO-8859-8-I }
11712 { CSN_369103 iso-ir-139 csISO139CSN369103 }
11713 { JUS_I.B1.002 iso-ir-141 ISO646-YU js yu csISO141JUSIB1002 }
11714 { ISO_6937-2-add iso-ir-142 csISOTextComm }
11715 { IEC_P27-1 iso-ir-143 csISO143IECP271 }
11716 { ISO_8859-5:1988 iso-ir-144 ISO_8859-5 ISO-8859-5 cyrillic
11717 csISOLatinCyrillic }
11718 { JUS_I.B1.003-serb iso-ir-146 serbian csISO146Serbian }
11719 { JUS_I.B1.003-mac macedonian iso-ir-147 csISO147Macedonian }
11720 { ISO_8859-9:1989 iso-ir-148 ISO_8859-9 ISO-8859-9 latin5 l5 csISOLatin5 }
11721 { greek-ccitt iso-ir-150 csISO150 csISO150GreekCCITT }
11722 { NC_NC00-10:81 cuba iso-ir-151 ISO646-CU csISO151Cuba }
11723 { ISO_6937-2-25 iso-ir-152 csISO6937Add }
11724 { GOST_19768-74 ST_SEV_358-88 iso-ir-153 csISO153GOST1976874 }
11725 { ISO_8859-supp iso-ir-154 latin1-2-5 csISO8859Supp }
11726 { ISO_10367-box iso-ir-155 csISO10367Box }
11727 { ISO-8859-10 iso-ir-157 l6 ISO_8859-10:1992 csISOLatin6 latin6 }
11728 { latin-lap lap iso-ir-158 csISO158Lap }
11729 { JIS_X0212-1990 x0212 iso-ir-159 csISO159JISX02121990 }
11730 { DS_2089 DS2089 ISO646-DK dk csISO646Danish }
11731 { us-dk csUSDK }
11732 { dk-us csDKUS }
11733 { JIS_X0201 X0201 csHalfWidthKatakana }
11734 { KSC5636 ISO646-KR csKSC5636 }
11735 { ISO-10646-UCS-2 csUnicode }
11736 { ISO-10646-UCS-4 csUCS4 }
11737 { DEC-MCS dec csDECMCS }
11738 { hp-roman8 roman8 r8 csHPRoman8 }
11739 { macintosh mac csMacintosh }
11740 { IBM037 cp037 ebcdic-cp-us ebcdic-cp-ca ebcdic-cp-wt ebcdic-cp-nl
11741 csIBM037 }
11742 { IBM038 EBCDIC-INT cp038 csIBM038 }
11743 { IBM273 CP273 csIBM273 }
11744 { IBM274 EBCDIC-BE CP274 csIBM274 }
11745 { IBM275 EBCDIC-BR cp275 csIBM275 }
11746 { IBM277 EBCDIC-CP-DK EBCDIC-CP-NO csIBM277 }
11747 { IBM278 CP278 ebcdic-cp-fi ebcdic-cp-se csIBM278 }
11748 { IBM280 CP280 ebcdic-cp-it csIBM280 }
11749 { IBM281 EBCDIC-JP-E cp281 csIBM281 }
11750 { IBM284 CP284 ebcdic-cp-es csIBM284 }
11751 { IBM285 CP285 ebcdic-cp-gb csIBM285 }
11752 { IBM290 cp290 EBCDIC-JP-kana csIBM290 }
11753 { IBM297 cp297 ebcdic-cp-fr csIBM297 }
11754 { IBM420 cp420 ebcdic-cp-ar1 csIBM420 }
11755 { IBM423 cp423 ebcdic-cp-gr csIBM423 }
11756 { IBM424 cp424 ebcdic-cp-he csIBM424 }
11757 { IBM437 cp437 437 csPC8CodePage437 }
11758 { IBM500 CP500 ebcdic-cp-be ebcdic-cp-ch csIBM500 }
11759 { IBM775 cp775 csPC775Baltic }
11760 { IBM850 cp850 850 csPC850Multilingual }
11761 { IBM851 cp851 851 csIBM851 }
11762 { IBM852 cp852 852 csPCp852 }
11763 { IBM855 cp855 855 csIBM855 }
11764 { IBM857 cp857 857 csIBM857 }
11765 { IBM860 cp860 860 csIBM860 }
11766 { IBM861 cp861 861 cp-is csIBM861 }
11767 { IBM862 cp862 862 csPC862LatinHebrew }
11768 { IBM863 cp863 863 csIBM863 }
11769 { IBM864 cp864 csIBM864 }
11770 { IBM865 cp865 865 csIBM865 }
11771 { IBM866 cp866 866 csIBM866 }
11772 { IBM868 CP868 cp-ar csIBM868 }
11773 { IBM869 cp869 869 cp-gr csIBM869 }
11774 { IBM870 CP870 ebcdic-cp-roece ebcdic-cp-yu csIBM870 }
11775 { IBM871 CP871 ebcdic-cp-is csIBM871 }
11776 { IBM880 cp880 EBCDIC-Cyrillic csIBM880 }
11777 { IBM891 cp891 csIBM891 }
11778 { IBM903 cp903 csIBM903 }
11779 { IBM904 cp904 904 csIBBM904 }
11780 { IBM905 CP905 ebcdic-cp-tr csIBM905 }
11781 { IBM918 CP918 ebcdic-cp-ar2 csIBM918 }
11782 { IBM1026 CP1026 csIBM1026 }
11783 { EBCDIC-AT-DE csIBMEBCDICATDE }
11784 { EBCDIC-AT-DE-A csEBCDICATDEA }
11785 { EBCDIC-CA-FR csEBCDICCAFR }
11786 { EBCDIC-DK-NO csEBCDICDKNO }
11787 { EBCDIC-DK-NO-A csEBCDICDKNOA }
11788 { EBCDIC-FI-SE csEBCDICFISE }
11789 { EBCDIC-FI-SE-A csEBCDICFISEA }
11790 { EBCDIC-FR csEBCDICFR }
11791 { EBCDIC-IT csEBCDICIT }
11792 { EBCDIC-PT csEBCDICPT }
11793 { EBCDIC-ES csEBCDICES }
11794 { EBCDIC-ES-A csEBCDICESA }
11795 { EBCDIC-ES-S csEBCDICESS }
11796 { EBCDIC-UK csEBCDICUK }
11797 { EBCDIC-US csEBCDICUS }
11798 { UNKNOWN-8BIT csUnknown8BiT }
11799 { MNEMONIC csMnemonic }
11800 { MNEM csMnem }
11801 { VISCII csVISCII }
11802 { VIQR csVIQR }
11803 { KOI8-R csKOI8R }
11804 { IBM00858 CCSID00858 CP00858 PC-Multilingual-850+euro }
11805 { IBM00924 CCSID00924 CP00924 ebcdic-Latin9--euro }
11806 { IBM01140 CCSID01140 CP01140 ebcdic-us-37+euro }
11807 { IBM01141 CCSID01141 CP01141 ebcdic-de-273+euro }
11808 { IBM01142 CCSID01142 CP01142 ebcdic-dk-277+euro ebcdic-no-277+euro }
11809 { IBM01143 CCSID01143 CP01143 ebcdic-fi-278+euro ebcdic-se-278+euro }
11810 { IBM01144 CCSID01144 CP01144 ebcdic-it-280+euro }
11811 { IBM01145 CCSID01145 CP01145 ebcdic-es-284+euro }
11812 { IBM01146 CCSID01146 CP01146 ebcdic-gb-285+euro }
11813 { IBM01147 CCSID01147 CP01147 ebcdic-fr-297+euro }
11814 { IBM01148 CCSID01148 CP01148 ebcdic-international-500+euro }
11815 { IBM01149 CCSID01149 CP01149 ebcdic-is-871+euro }
11816 { IBM1047 IBM-1047 }
11817 { PTCP154 csPTCP154 PT154 CP154 Cyrillic-Asian }
11818 { Amiga-1251 Ami1251 Amiga1251 Ami-1251 }
11819 { UNICODE-1-1 csUnicode11 }
11820 { CESU-8 csCESU-8 }
11821 { BOCU-1 csBOCU-1 }
11822 { UNICODE-1-1-UTF-7 csUnicode11UTF7 }
11823 { ISO-8859-14 iso-ir-199 ISO_8859-14:1998 ISO_8859-14 latin8 iso-celtic
11824 l8 }
11825 { ISO-8859-15 ISO_8859-15 Latin-9 }
11826 { ISO-8859-16 iso-ir-226 ISO_8859-16:2001 ISO_8859-16 latin10 l10 }
11827 { GBK CP936 MS936 windows-936 }
11828 { JIS_Encoding csJISEncoding }
11829 { Shift_JIS MS_Kanji csShiftJIS ShiftJIS Shift-JIS }
11830 { Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese
11831 EUC-JP }
11832 { Extended_UNIX_Code_Fixed_Width_for_Japanese csEUCFixWidJapanese }
11833 { ISO-10646-UCS-Basic csUnicodeASCII }
11834 { ISO-10646-Unicode-Latin1 csUnicodeLatin1 ISO-10646 }
11835 { ISO-Unicode-IBM-1261 csUnicodeIBM1261 }
11836 { ISO-Unicode-IBM-1268 csUnicodeIBM1268 }
11837 { ISO-Unicode-IBM-1276 csUnicodeIBM1276 }
11838 { ISO-Unicode-IBM-1264 csUnicodeIBM1264 }
11839 { ISO-Unicode-IBM-1265 csUnicodeIBM1265 }
11840 { ISO-8859-1-Windows-3.0-Latin-1 csWindows30Latin1 }
11841 { ISO-8859-1-Windows-3.1-Latin-1 csWindows31Latin1 }
11842 { ISO-8859-2-Windows-Latin-2 csWindows31Latin2 }
11843 { ISO-8859-9-Windows-Latin-5 csWindows31Latin5 }
11844 { Adobe-Standard-Encoding csAdobeStandardEncoding }
11845 { Ventura-US csVenturaUS }
11846 { Ventura-International csVenturaInternational }
11847 { PC8-Danish-Norwegian csPC8DanishNorwegian }
11848 { PC8-Turkish csPC8Turkish }
11849 { IBM-Symbols csIBMSymbols }
11850 { IBM-Thai csIBMThai }
11851 { HP-Legal csHPLegal }
11852 { HP-Pi-font csHPPiFont }
11853 { HP-Math8 csHPMath8 }
11854 { Adobe-Symbol-Encoding csHPPSMath }
11855 { HP-DeskTop csHPDesktop }
11856 { Ventura-Math csVenturaMath }
11857 { Microsoft-Publishing csMicrosoftPublishing }
11858 { Windows-31J csWindows31J }
11859 { GB2312 csGB2312 }
11860 { Big5 csBig5 }
11861}
11862
11863proc tcl_encoding {enc} {
11864 global encoding_aliases tcl_encoding_cache
11865 if {[info exists tcl_encoding_cache($enc)]} {
11866 return $tcl_encoding_cache($enc)
11867 }
11868 set names [encoding names]
11869 set lcnames [string tolower $names]
11870 set enc [string tolower $enc]
11871 set i [lsearch -exact $lcnames $enc]
11872 if {$i < 0} {
11873 # look for "isonnn" instead of "iso-nnn" or "iso_nnn"
11874 if {[regsub {^(iso|cp|ibm|jis)[-_]} $enc {\1} encx]} {
11875 set i [lsearch -exact $lcnames $encx]
11876 }
11877 }
11878 if {$i < 0} {
11879 foreach l $encoding_aliases {
11880 set ll [string tolower $l]
11881 if {[lsearch -exact $ll $enc] < 0} continue
11882 # look through the aliases for one that tcl knows about
11883 foreach e $ll {
11884 set i [lsearch -exact $lcnames $e]
11885 if {$i < 0} {
11886 if {[regsub {^(iso|cp|ibm|jis)[-_]} $e {\1} ex]} {
11887 set i [lsearch -exact $lcnames $ex]
11888 }
11889 }
11890 if {$i >= 0} break
11891 }
11892 break
11893 }
11894 }
11895 set tclenc {}
11896 if {$i >= 0} {
11897 set tclenc [lindex $names $i]
11898 }
11899 set tcl_encoding_cache($enc) $tclenc
11900 return $tclenc
11901}
11902
11903proc gitattr {path attr default} {
11904 global path_attr_cache
11905 if {[info exists path_attr_cache($attr,$path)]} {
11906 set r $path_attr_cache($attr,$path)
11907 } else {
11908 set r "unspecified"
11909 if {![catch {set line [exec git check-attr $attr -- $path]}]} {
11910 regexp "(.*): $attr: (.*)" $line m f r
11911 }
11912 set path_attr_cache($attr,$path) $r
11913 }
11914 if {$r eq "unspecified"} {
11915 return $default
11916 }
11917 return $r
11918}
11919
11920proc cache_gitattr {attr pathlist} {
11921 global path_attr_cache
11922 set newlist {}
11923 foreach path $pathlist {
11924 if {![info exists path_attr_cache($attr,$path)]} {
11925 lappend newlist $path
11926 }
11927 }
11928 set lim 1000
11929 if {[tk windowingsystem] == "win32"} {
11930 # windows has a 32k limit on the arguments to a command...
11931 set lim 30
11932 }
11933 while {$newlist ne {}} {
11934 set head [lrange $newlist 0 [expr {$lim - 1}]]
11935 set newlist [lrange $newlist $lim end]
11936 if {![catch {set rlist [eval exec git check-attr $attr -- $head]}]} {
11937 foreach row [split $rlist "\n"] {
11938 if {[regexp "(.*): $attr: (.*)" $row m path value]} {
11939 if {[string index $path 0] eq "\""} {
11940 set path [encoding convertfrom [lindex $path 0]]
11941 }
11942 set path_attr_cache($attr,$path) $value
11943 }
11944 }
11945 }
11946 }
11947}
11948
11949proc get_path_encoding {path} {
11950 global gui_encoding perfile_attrs
11951 set tcl_enc $gui_encoding
11952 if {$path ne {} && $perfile_attrs} {
11953 set enc2 [tcl_encoding [gitattr $path encoding $tcl_enc]]
11954 if {$enc2 ne {}} {
11955 set tcl_enc $enc2
11956 }
11957 }
11958 return $tcl_enc
11959}
11960
11961# First check that Tcl/Tk is recent enough
11962if {[catch {package require Tk 8.4} err]} {
11963 show_error {} . "Sorry, gitk cannot run with this version of Tcl/Tk.\n\
11964 Gitk requires at least Tcl/Tk 8.4." list
11965 exit 1
11966}
11967
11968# on OSX bring the current Wish process window to front
11969if {[tk windowingsystem] eq "aqua"} {
11970 exec osascript -e [format {
11971 tell application "System Events"
11972 set frontmost of processes whose unix id is %d to true
11973 end tell
11974 } [pid] ]
11975}
11976
11977# Unset GIT_TRACE var if set
11978if { [info exists ::env(GIT_TRACE)] } {
11979 unset ::env(GIT_TRACE)
11980}
11981
11982# defaults...
11983set wrcomcmd "git diff-tree --stdin -p --pretty"
11984
11985set gitencoding {}
11986catch {
11987 set gitencoding [exec git config --get i18n.commitencoding]
11988}
11989catch {
11990 set gitencoding [exec git config --get i18n.logoutputencoding]
11991}
11992if {$gitencoding == ""} {
11993 set gitencoding "utf-8"
11994}
11995set tclencoding [tcl_encoding $gitencoding]
11996if {$tclencoding == {}} {
11997 puts stderr "Warning: encoding $gitencoding is not supported by Tcl/Tk"
11998}
11999
12000set gui_encoding [encoding system]
12001catch {
12002 set enc [exec git config --get gui.encoding]
12003 if {$enc ne {}} {
12004 set tclenc [tcl_encoding $enc]
12005 if {$tclenc ne {}} {
12006 set gui_encoding $tclenc
12007 } else {
12008 puts stderr "Warning: encoding $enc is not supported by Tcl/Tk"
12009 }
12010 }
12011}
12012
12013set log_showroot true
12014catch {
12015 set log_showroot [exec git config --bool --get log.showroot]
12016}
12017
12018if {[tk windowingsystem] eq "aqua"} {
12019 set mainfont {{Lucida Grande} 9}
12020 set textfont {Monaco 9}
12021 set uifont {{Lucida Grande} 9 bold}
12022} elseif {![catch {::tk::pkgconfig get fontsystem} xft] && $xft eq "xft"} {
12023 # fontconfig!
12024 set mainfont {sans 9}
12025 set textfont {monospace 9}
12026 set uifont {sans 9 bold}
12027} else {
12028 set mainfont {Helvetica 9}
12029 set textfont {Courier 9}
12030 set uifont {Helvetica 9 bold}
12031}
12032set tabstop 8
12033set findmergefiles 0
12034set maxgraphpct 50
12035set maxwidth 16
12036set revlistorder 0
12037set fastdate 0
12038set uparrowlen 5
12039set downarrowlen 5
12040set mingaplen 100
12041set cmitmode "patch"
12042set wrapcomment "none"
12043set showneartags 1
12044set hideremotes 0
12045set maxrefs 20
12046set maxlinelen 200
12047set showlocalchanges 1
12048set limitdiffs 1
12049set datetimeformat "%Y-%m-%d %H:%M:%S"
12050set autoselect 1
12051set autosellen 40
12052set perfile_attrs 0
12053set want_ttk 1
12054
12055if {[tk windowingsystem] eq "aqua"} {
12056 set extdifftool "opendiff"
12057} else {
12058 set extdifftool "meld"
12059}
12060
12061set colors {green red blue magenta darkgrey brown orange}
12062if {[tk windowingsystem] eq "win32"} {
12063 set uicolor SystemButtonFace
12064 set uifgcolor SystemButtonText
12065 set uifgdisabledcolor SystemDisabledText
12066 set bgcolor SystemWindow
12067 set fgcolor SystemWindowText
12068 set selectbgcolor SystemHighlight
12069} else {
12070 set uicolor grey85
12071 set uifgcolor black
12072 set uifgdisabledcolor "#999"
12073 set bgcolor white
12074 set fgcolor black
12075 set selectbgcolor gray85
12076}
12077set diffcolors {red "#00a000" blue}
12078set diffcontext 3
12079set mergecolors {red blue green purple brown "#009090" magenta "#808000" "#009000" "#ff0080" cyan "#b07070" "#70b0f0" "#70f0b0" "#f0b070" "#ff70b0"}
12080set ignorespace 0
12081set worddiff ""
12082set markbgcolor "#e0e0ff"
12083
12084set headbgcolor green
12085set headfgcolor black
12086set headoutlinecolor black
12087set remotebgcolor #ffddaa
12088set tagbgcolor yellow
12089set tagfgcolor black
12090set tagoutlinecolor black
12091set reflinecolor black
12092set filesepbgcolor #aaaaaa
12093set filesepfgcolor black
12094set linehoverbgcolor #ffff80
12095set linehoverfgcolor black
12096set linehoveroutlinecolor black
12097set mainheadcirclecolor yellow
12098set workingfilescirclecolor red
12099set indexcirclecolor green
12100set circlecolors {white blue gray blue blue}
12101set linkfgcolor blue
12102set circleoutlinecolor $fgcolor
12103set foundbgcolor yellow
12104set currentsearchhitbgcolor orange
12105
12106# button for popping up context menus
12107if {[tk windowingsystem] eq "aqua"} {
12108 set ctxbut <Button-2>
12109} else {
12110 set ctxbut <Button-3>
12111}
12112
12113## For msgcat loading, first locate the installation location.
12114if { [info exists ::env(GITK_MSGSDIR)] } {
12115 ## Msgsdir was manually set in the environment.
12116 set gitk_msgsdir $::env(GITK_MSGSDIR)
12117} else {
12118 ## Let's guess the prefix from argv0.
12119 set gitk_prefix [file dirname [file dirname [file normalize $argv0]]]
12120 set gitk_libdir [file join $gitk_prefix share gitk lib]
12121 set gitk_msgsdir [file join $gitk_libdir msgs]
12122 unset gitk_prefix
12123}
12124
12125## Internationalization (i18n) through msgcat and gettext. See
12126## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
12127package require msgcat
12128namespace import ::msgcat::mc
12129## And eventually load the actual message catalog
12130::msgcat::mcload $gitk_msgsdir
12131
12132catch {
12133 # follow the XDG base directory specification by default. See
12134 # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
12135 if {[info exists env(XDG_CONFIG_HOME)] && $env(XDG_CONFIG_HOME) ne ""} {
12136 # XDG_CONFIG_HOME environment variable is set
12137 set config_file [file join $env(XDG_CONFIG_HOME) git gitk]
12138 set config_file_tmp [file join $env(XDG_CONFIG_HOME) git gitk-tmp]
12139 } else {
12140 # default XDG_CONFIG_HOME
12141 set config_file "~/.config/git/gitk"
12142 set config_file_tmp "~/.config/git/gitk-tmp"
12143 }
12144 if {![file exists $config_file]} {
12145 # for backward compatibility use the old config file if it exists
12146 if {[file exists "~/.gitk"]} {
12147 set config_file "~/.gitk"
12148 set config_file_tmp "~/.gitk-tmp"
12149 } elseif {![file exists [file dirname $config_file]]} {
12150 file mkdir [file dirname $config_file]
12151 }
12152 }
12153 source $config_file
12154}
12155
12156parsefont mainfont $mainfont
12157eval font create mainfont [fontflags mainfont]
12158eval font create mainfontbold [fontflags mainfont 1]
12159
12160parsefont textfont $textfont
12161eval font create textfont [fontflags textfont]
12162eval font create textfontbold [fontflags textfont 1]
12163
12164parsefont uifont $uifont
12165eval font create uifont [fontflags uifont]
12166
12167setui $uicolor
12168
12169setoptions
12170
12171# check that we can find a .git directory somewhere...
12172if {[catch {set gitdir [exec git rev-parse --git-dir]}]} {
12173 show_error {} . [mc "Cannot find a git repository here."]
12174 exit 1
12175}
12176
12177set selecthead {}
12178set selectheadid {}
12179
12180set revtreeargs {}
12181set cmdline_files {}
12182set i 0
12183set revtreeargscmd {}
12184foreach arg $argv {
12185 switch -glob -- $arg {
12186 "" { }
12187 "--" {
12188 set cmdline_files [lrange $argv [expr {$i + 1}] end]
12189 break
12190 }
12191 "--select-commit=*" {
12192 set selecthead [string range $arg 16 end]
12193 }
12194 "--argscmd=*" {
12195 set revtreeargscmd [string range $arg 10 end]
12196 }
12197 default {
12198 lappend revtreeargs $arg
12199 }
12200 }
12201 incr i
12202}
12203
12204if {$selecthead eq "HEAD"} {
12205 set selecthead {}
12206}
12207
12208if {$i >= [llength $argv] && $revtreeargs ne {}} {
12209 # no -- on command line, but some arguments (other than --argscmd)
12210 if {[catch {
12211 set f [eval exec git rev-parse --no-revs --no-flags $revtreeargs]
12212 set cmdline_files [split $f "\n"]
12213 set n [llength $cmdline_files]
12214 set revtreeargs [lrange $revtreeargs 0 end-$n]
12215 # Unfortunately git rev-parse doesn't produce an error when
12216 # something is both a revision and a filename. To be consistent
12217 # with git log and git rev-list, check revtreeargs for filenames.
12218 foreach arg $revtreeargs {
12219 if {[file exists $arg]} {
12220 show_error {} . [mc "Ambiguous argument '%s': both revision\
12221 and filename" $arg]
12222 exit 1
12223 }
12224 }
12225 } err]} {
12226 # unfortunately we get both stdout and stderr in $err,
12227 # so look for "fatal:".
12228 set i [string first "fatal:" $err]
12229 if {$i > 0} {
12230 set err [string range $err [expr {$i + 6}] end]
12231 }
12232 show_error {} . "[mc "Bad arguments to gitk:"]\n$err"
12233 exit 1
12234 }
12235}
12236
12237set nullid "0000000000000000000000000000000000000000"
12238set nullid2 "0000000000000000000000000000000000000001"
12239set nullfile "/dev/null"
12240
12241set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
12242if {![info exists have_ttk]} {
12243 set have_ttk [llength [info commands ::ttk::style]]
12244}
12245set use_ttk [expr {$have_ttk && $want_ttk}]
12246set NS [expr {$use_ttk ? "ttk" : ""}]
12247
12248regexp {^git version ([\d.]*\d)} [exec git version] _ git_version
12249
12250set show_notes {}
12251if {[package vcompare $git_version "1.6.6.2"] >= 0} {
12252 set show_notes "--show-notes"
12253}
12254
12255set appname "gitk"
12256
12257set runq {}
12258set history {}
12259set historyindex 0
12260set fh_serial 0
12261set nhl_names {}
12262set highlight_paths {}
12263set findpattern {}
12264set searchdirn -forwards
12265set boldids {}
12266set boldnameids {}
12267set diffelide {0 0}
12268set markingmatches 0
12269set linkentercount 0
12270set need_redisplay 0
12271set nrows_drawn 0
12272set firsttabstop 0
12273
12274set nextviewnum 1
12275set curview 0
12276set selectedview 0
12277set selectedhlview [mc "None"]
12278set highlight_related [mc "None"]
12279set highlight_files {}
12280set viewfiles(0) {}
12281set viewperm(0) 0
12282set viewargs(0) {}
12283set viewargscmd(0) {}
12284
12285set selectedline {}
12286set numcommits 0
12287set loginstance 0
12288set cmdlineok 0
12289set stopped 0
12290set stuffsaved 0
12291set patchnum 0
12292set lserial 0
12293set hasworktree [hasworktree]
12294set cdup {}
12295if {[expr {[exec git rev-parse --is-inside-work-tree] == "true"}]} {
12296 set cdup [exec git rev-parse --show-cdup]
12297}
12298set worktree [exec git rev-parse --show-toplevel]
12299setcoords
12300makewindow
12301catch {
12302 image create photo gitlogo -width 16 -height 16
12303
12304 image create photo gitlogominus -width 4 -height 2
12305 gitlogominus put #C00000 -to 0 0 4 2
12306 gitlogo copy gitlogominus -to 1 5
12307 gitlogo copy gitlogominus -to 6 5
12308 gitlogo copy gitlogominus -to 11 5
12309 image delete gitlogominus
12310
12311 image create photo gitlogoplus -width 4 -height 4
12312 gitlogoplus put #008000 -to 1 0 3 4
12313 gitlogoplus put #008000 -to 0 1 4 3
12314 gitlogo copy gitlogoplus -to 1 9
12315 gitlogo copy gitlogoplus -to 6 9
12316 gitlogo copy gitlogoplus -to 11 9
12317 image delete gitlogoplus
12318
12319 image create photo gitlogo32 -width 32 -height 32
12320 gitlogo32 copy gitlogo -zoom 2 2
12321
12322 wm iconphoto . -default gitlogo gitlogo32
12323}
12324# wait for the window to become visible
12325tkwait visibility .
12326wm title . "$appname: [reponame]"
12327update
12328readrefs
12329
12330if {$cmdline_files ne {} || $revtreeargs ne {} || $revtreeargscmd ne {}} {
12331 # create a view for the files/dirs specified on the command line
12332 set curview 1
12333 set selectedview 1
12334 set nextviewnum 2
12335 set viewname(1) [mc "Command line"]
12336 set viewfiles(1) $cmdline_files
12337 set viewargs(1) $revtreeargs
12338 set viewargscmd(1) $revtreeargscmd
12339 set viewperm(1) 0
12340 set vdatemode(1) 0
12341 addviewmenu 1
12342 .bar.view entryconf [mca "Edit view..."] -state normal
12343 .bar.view entryconf [mca "Delete view"] -state normal
12344}
12345
12346if {[info exists permviews]} {
12347 foreach v $permviews {
12348 set n $nextviewnum
12349 incr nextviewnum
12350 set viewname($n) [lindex $v 0]
12351 set viewfiles($n) [lindex $v 1]
12352 set viewargs($n) [lindex $v 2]
12353 set viewargscmd($n) [lindex $v 3]
12354 set viewperm($n) 1
12355 addviewmenu $n
12356 }
12357}
12358
12359if {[tk windowingsystem] eq "win32"} {
12360 focus -force .
12361}
12362
12363getcommits {}
12364
12365# Local variables:
12366# mode: tcl
12367# indent-tabs-mode: t
12368# tab-width: 8
12369# End: