gitk-git / gitkon commit git log: support "auto" decorations (1571586)
   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 $cflist <1> {sel_flist %W %x %y; break}
2589    bind $cflist <B1-Motion> {sel_flist %W %x %y; break}
2590    bind $cflist <ButtonRelease-1> {treeclick %W %x %y}
2591    global ctxbut
2592    bind $cflist $ctxbut {pop_flist_menu %W %X %Y %x %y}
2593    bind $ctext $ctxbut {pop_diff_menu %W %X %Y %x %y}
2594    bind $ctext <Button-1> {focus %W}
2595    bind $ctext <<Selection>> rehighlight_search_results
2596
2597    set maincursor [. cget -cursor]
2598    set textcursor [$ctext cget -cursor]
2599    set curtextcursor $textcursor
2600
2601    set rowctxmenu .rowctxmenu
2602    makemenu $rowctxmenu {
2603        {mc "Diff this -> selected" command {diffvssel 0}}
2604        {mc "Diff selected -> this" command {diffvssel 1}}
2605        {mc "Make patch" command mkpatch}
2606        {mc "Create tag" command mktag}
2607        {mc "Write commit to file" command writecommit}
2608        {mc "Create new branch" command mkbranch}
2609        {mc "Cherry-pick this commit" command cherrypick}
2610        {mc "Reset HEAD branch to here" command resethead}
2611        {mc "Mark this commit" command markhere}
2612        {mc "Return to mark" command gotomark}
2613        {mc "Find descendant of this and mark" command find_common_desc}
2614        {mc "Compare with marked commit" command compare_commits}
2615        {mc "Diff this -> marked commit" command {diffvsmark 0}}
2616        {mc "Diff marked commit -> this" command {diffvsmark 1}}
2617        {mc "Revert this commit" command revert}
2618    }
2619    $rowctxmenu configure -tearoff 0
2620
2621    set fakerowmenu .fakerowmenu
2622    makemenu $fakerowmenu {
2623        {mc "Diff this -> selected" command {diffvssel 0}}
2624        {mc "Diff selected -> this" command {diffvssel 1}}
2625        {mc "Make patch" command mkpatch}
2626        {mc "Diff this -> marked commit" command {diffvsmark 0}}
2627        {mc "Diff marked commit -> this" command {diffvsmark 1}}
2628    }
2629    $fakerowmenu configure -tearoff 0
2630
2631    set headctxmenu .headctxmenu
2632    makemenu $headctxmenu {
2633        {mc "Check out this branch" command cobranch}
2634        {mc "Remove this branch" command rmbranch}
2635    }
2636    $headctxmenu configure -tearoff 0
2637
2638    global flist_menu
2639    set flist_menu .flistctxmenu
2640    makemenu $flist_menu {
2641        {mc "Highlight this too" command {flist_hl 0}}
2642        {mc "Highlight this only" command {flist_hl 1}}
2643        {mc "External diff" command {external_diff}}
2644        {mc "Blame parent commit" command {external_blame 1}}
2645    }
2646    $flist_menu configure -tearoff 0
2647
2648    global diff_menu
2649    set diff_menu .diffctxmenu
2650    makemenu $diff_menu {
2651        {mc "Show origin of this line" command show_line_source}
2652        {mc "Run git gui blame on this line" command {external_blame_diff}}
2653    }
2654    $diff_menu configure -tearoff 0
2655}
2656
2657# Windows sends all mouse wheel events to the current focused window, not
2658# the one where the mouse hovers, so bind those events here and redirect
2659# to the correct window
2660proc windows_mousewheel_redirector {W X Y D} {
2661    global canv canv2 canv3
2662    set w [winfo containing -displayof $W $X $Y]
2663    if {$w ne ""} {
2664        set u [expr {$D < 0 ? 5 : -5}]
2665        if {$w == $canv || $w == $canv2 || $w == $canv3} {
2666            allcanvs yview scroll $u units
2667        } else {
2668            catch {
2669                $w yview scroll $u units
2670            }
2671        }
2672    }
2673}
2674
2675# Update row number label when selectedline changes
2676proc selectedline_change {n1 n2 op} {
2677    global selectedline rownumsel
2678
2679    if {$selectedline eq {}} {
2680        set rownumsel {}
2681    } else {
2682        set rownumsel [expr {$selectedline + 1}]
2683    }
2684}
2685
2686# mouse-2 makes all windows scan vertically, but only the one
2687# the cursor is in scans horizontally
2688proc canvscan {op w x y} {
2689    global canv canv2 canv3
2690    foreach c [list $canv $canv2 $canv3] {
2691        if {$c == $w} {
2692            $c scan $op $x $y
2693        } else {
2694            $c scan $op 0 $y
2695        }
2696    }
2697}
2698
2699proc scrollcanv {cscroll f0 f1} {
2700    $cscroll set $f0 $f1
2701    drawvisible
2702    flushhighlights
2703}
2704
2705# when we make a key binding for the toplevel, make sure
2706# it doesn't get triggered when that key is pressed in the
2707# find string entry widget.
2708proc bindkey {ev script} {
2709    global entries
2710    bind . $ev $script
2711    set escript [bind Entry $ev]
2712    if {$escript == {}} {
2713        set escript [bind Entry <Key>]
2714    }
2715    foreach e $entries {
2716        bind $e $ev "$escript; break"
2717    }
2718}
2719
2720proc bindmodfunctionkey {mod n script} {
2721    bind . <$mod-F$n> $script
2722    catch { bind . <$mod-XF86_Switch_VT_$n> $script }
2723}
2724
2725# set the focus back to the toplevel for any click outside
2726# the entry widgets
2727proc click {w} {
2728    global ctext entries
2729    foreach e [concat $entries $ctext] {
2730        if {$w == $e} return
2731    }
2732    focus .
2733}
2734
2735# Adjust the progress bar for a change in requested extent or canvas size
2736proc adjustprogress {} {
2737    global progresscanv progressitem progresscoords
2738    global fprogitem fprogcoord lastprogupdate progupdatepending
2739    global rprogitem rprogcoord use_ttk
2740
2741    if {$use_ttk} {
2742        $progresscanv configure -value [expr {int($fprogcoord * 100)}]
2743        return
2744    }
2745
2746    set w [expr {[winfo width $progresscanv] - 4}]
2747    set x0 [expr {$w * [lindex $progresscoords 0]}]
2748    set x1 [expr {$w * [lindex $progresscoords 1]}]
2749    set h [winfo height $progresscanv]
2750    $progresscanv coords $progressitem $x0 0 $x1 $h
2751    $progresscanv coords $fprogitem 0 0 [expr {$w * $fprogcoord}] $h
2752    $progresscanv coords $rprogitem 0 0 [expr {$w * $rprogcoord}] $h
2753    set now [clock clicks -milliseconds]
2754    if {$now >= $lastprogupdate + 100} {
2755        set progupdatepending 0
2756        update
2757    } elseif {!$progupdatepending} {
2758        set progupdatepending 1
2759        after [expr {$lastprogupdate + 100 - $now}] doprogupdate
2760    }
2761}
2762
2763proc doprogupdate {} {
2764    global lastprogupdate progupdatepending
2765
2766    if {$progupdatepending} {
2767        set progupdatepending 0
2768        set lastprogupdate [clock clicks -milliseconds]
2769        update
2770    }
2771}
2772
2773proc savestuff {w} {
2774    global canv canv2 canv3 mainfont textfont uifont tabstop
2775    global stuffsaved findmergefiles maxgraphpct
2776    global maxwidth showneartags showlocalchanges
2777    global viewname viewfiles viewargs viewargscmd viewperm nextviewnum
2778    global cmitmode wrapcomment datetimeformat limitdiffs
2779    global colors uicolor bgcolor fgcolor diffcolors diffcontext selectbgcolor
2780    global uifgcolor uifgdisabledcolor
2781    global headbgcolor headfgcolor headoutlinecolor remotebgcolor
2782    global tagbgcolor tagfgcolor tagoutlinecolor
2783    global reflinecolor filesepbgcolor filesepfgcolor
2784    global mergecolors foundbgcolor currentsearchhitbgcolor
2785    global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor circlecolors
2786    global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
2787    global linkfgcolor circleoutlinecolor
2788    global autoselect autosellen extdifftool perfile_attrs markbgcolor use_ttk
2789    global hideremotes want_ttk maxrefs
2790    global config_file config_file_tmp
2791
2792    if {$stuffsaved} return
2793    if {![winfo viewable .]} return
2794    catch {
2795        if {[file exists $config_file_tmp]} {
2796            file delete -force $config_file_tmp
2797        }
2798        set f [open $config_file_tmp w]
2799        if {$::tcl_platform(platform) eq {windows}} {
2800            file attributes $config_file_tmp -hidden true
2801        }
2802        puts $f [list set mainfont $mainfont]
2803        puts $f [list set textfont $textfont]
2804        puts $f [list set uifont $uifont]
2805        puts $f [list set tabstop $tabstop]
2806        puts $f [list set findmergefiles $findmergefiles]
2807        puts $f [list set maxgraphpct $maxgraphpct]
2808        puts $f [list set maxwidth $maxwidth]
2809        puts $f [list set cmitmode $cmitmode]
2810        puts $f [list set wrapcomment $wrapcomment]
2811        puts $f [list set autoselect $autoselect]
2812        puts $f [list set autosellen $autosellen]
2813        puts $f [list set showneartags $showneartags]
2814        puts $f [list set maxrefs $maxrefs]
2815        puts $f [list set hideremotes $hideremotes]
2816        puts $f [list set showlocalchanges $showlocalchanges]
2817        puts $f [list set datetimeformat $datetimeformat]
2818        puts $f [list set limitdiffs $limitdiffs]
2819        puts $f [list set uicolor $uicolor]
2820        puts $f [list set want_ttk $want_ttk]
2821        puts $f [list set bgcolor $bgcolor]
2822        puts $f [list set fgcolor $fgcolor]
2823        puts $f [list set uifgcolor $uifgcolor]
2824        puts $f [list set uifgdisabledcolor $uifgdisabledcolor]
2825        puts $f [list set colors $colors]
2826        puts $f [list set diffcolors $diffcolors]
2827        puts $f [list set mergecolors $mergecolors]
2828        puts $f [list set markbgcolor $markbgcolor]
2829        puts $f [list set diffcontext $diffcontext]
2830        puts $f [list set selectbgcolor $selectbgcolor]
2831        puts $f [list set foundbgcolor $foundbgcolor]
2832        puts $f [list set currentsearchhitbgcolor $currentsearchhitbgcolor]
2833        puts $f [list set extdifftool $extdifftool]
2834        puts $f [list set perfile_attrs $perfile_attrs]
2835        puts $f [list set headbgcolor $headbgcolor]
2836        puts $f [list set headfgcolor $headfgcolor]
2837        puts $f [list set headoutlinecolor $headoutlinecolor]
2838        puts $f [list set remotebgcolor $remotebgcolor]
2839        puts $f [list set tagbgcolor $tagbgcolor]
2840        puts $f [list set tagfgcolor $tagfgcolor]
2841        puts $f [list set tagoutlinecolor $tagoutlinecolor]
2842        puts $f [list set reflinecolor $reflinecolor]
2843        puts $f [list set filesepbgcolor $filesepbgcolor]
2844        puts $f [list set filesepfgcolor $filesepfgcolor]
2845        puts $f [list set linehoverbgcolor $linehoverbgcolor]
2846        puts $f [list set linehoverfgcolor $linehoverfgcolor]
2847        puts $f [list set linehoveroutlinecolor $linehoveroutlinecolor]
2848        puts $f [list set mainheadcirclecolor $mainheadcirclecolor]
2849        puts $f [list set workingfilescirclecolor $workingfilescirclecolor]
2850        puts $f [list set indexcirclecolor $indexcirclecolor]
2851        puts $f [list set circlecolors $circlecolors]
2852        puts $f [list set linkfgcolor $linkfgcolor]
2853        puts $f [list set circleoutlinecolor $circleoutlinecolor]
2854
2855        puts $f "set geometry(main) [wm geometry .]"
2856        puts $f "set geometry(state) [wm state .]"
2857        puts $f "set geometry(topwidth) [winfo width .tf]"
2858        puts $f "set geometry(topheight) [winfo height .tf]"
2859        if {$use_ttk} {
2860            puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sashpos 0] 1\""
2861            puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sashpos 1] 1\""
2862        } else {
2863            puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sash coord 0]\""
2864            puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sash coord 1]\""
2865        }
2866        puts $f "set geometry(botwidth) [winfo width .bleft]"
2867        puts $f "set geometry(botheight) [winfo height .bleft]"
2868
2869        puts -nonewline $f "set permviews {"
2870        for {set v 0} {$v < $nextviewnum} {incr v} {
2871            if {$viewperm($v)} {
2872                puts $f "{[list $viewname($v) $viewfiles($v) $viewargs($v) $viewargscmd($v)]}"
2873            }
2874        }
2875        puts $f "}"
2876        close $f
2877        file rename -force $config_file_tmp $config_file
2878    }
2879    set stuffsaved 1
2880}
2881
2882proc resizeclistpanes {win w} {
2883    global oldwidth use_ttk
2884    if {[info exists oldwidth($win)]} {
2885        if {$use_ttk} {
2886            set s0 [$win sashpos 0]
2887            set s1 [$win sashpos 1]
2888        } else {
2889            set s0 [$win sash coord 0]
2890            set s1 [$win sash coord 1]
2891        }
2892        if {$w < 60} {
2893            set sash0 [expr {int($w/2 - 2)}]
2894            set sash1 [expr {int($w*5/6 - 2)}]
2895        } else {
2896            set factor [expr {1.0 * $w / $oldwidth($win)}]
2897            set sash0 [expr {int($factor * [lindex $s0 0])}]
2898            set sash1 [expr {int($factor * [lindex $s1 0])}]
2899            if {$sash0 < 30} {
2900                set sash0 30
2901            }
2902            if {$sash1 < $sash0 + 20} {
2903                set sash1 [expr {$sash0 + 20}]
2904            }
2905            if {$sash1 > $w - 10} {
2906                set sash1 [expr {$w - 10}]
2907                if {$sash0 > $sash1 - 20} {
2908                    set sash0 [expr {$sash1 - 20}]
2909                }
2910            }
2911        }
2912        if {$use_ttk} {
2913            $win sashpos 0 $sash0
2914            $win sashpos 1 $sash1
2915        } else {
2916            $win sash place 0 $sash0 [lindex $s0 1]
2917            $win sash place 1 $sash1 [lindex $s1 1]
2918        }
2919    }
2920    set oldwidth($win) $w
2921}
2922
2923proc resizecdetpanes {win w} {
2924    global oldwidth use_ttk
2925    if {[info exists oldwidth($win)]} {
2926        if {$use_ttk} {
2927            set s0 [$win sashpos 0]
2928        } else {
2929            set s0 [$win sash coord 0]
2930        }
2931        if {$w < 60} {
2932            set sash0 [expr {int($w*3/4 - 2)}]
2933        } else {
2934            set factor [expr {1.0 * $w / $oldwidth($win)}]
2935            set sash0 [expr {int($factor * [lindex $s0 0])}]
2936            if {$sash0 < 45} {
2937                set sash0 45
2938            }
2939            if {$sash0 > $w - 15} {
2940                set sash0 [expr {$w - 15}]
2941            }
2942        }
2943        if {$use_ttk} {
2944            $win sashpos 0 $sash0
2945        } else {
2946            $win sash place 0 $sash0 [lindex $s0 1]
2947        }
2948    }
2949    set oldwidth($win) $w
2950}
2951
2952proc allcanvs args {
2953    global canv canv2 canv3
2954    eval $canv $args
2955    eval $canv2 $args
2956    eval $canv3 $args
2957}
2958
2959proc bindall {event action} {
2960    global canv canv2 canv3
2961    bind $canv $event $action
2962    bind $canv2 $event $action
2963    bind $canv3 $event $action
2964}
2965
2966proc about {} {
2967    global uifont NS
2968    set w .about
2969    if {[winfo exists $w]} {
2970        raise $w
2971        return
2972    }
2973    ttk_toplevel $w
2974    wm title $w [mc "About gitk"]
2975    make_transient $w .
2976    message $w.m -text [mc "
2977Gitk - a commit viewer for git
2978
2979Copyright \u00a9 2005-2014 Paul Mackerras
2980
2981Use and redistribute under the terms of the GNU General Public License"] \
2982            -justify center -aspect 400 -border 2 -bg white -relief groove
2983    pack $w.m -side top -fill x -padx 2 -pady 2
2984    ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
2985    pack $w.ok -side bottom
2986    bind $w <Visibility> "focus $w.ok"
2987    bind $w <Key-Escape> "destroy $w"
2988    bind $w <Key-Return> "destroy $w"
2989    tk::PlaceWindow $w widget .
2990}
2991
2992proc keys {} {
2993    global NS
2994    set w .keys
2995    if {[winfo exists $w]} {
2996        raise $w
2997        return
2998    }
2999    if {[tk windowingsystem] eq {aqua}} {
3000        set M1T Cmd
3001    } else {
3002        set M1T Ctrl
3003    }
3004    ttk_toplevel $w
3005    wm title $w [mc "Gitk key bindings"]
3006    make_transient $w .
3007    message $w.m -text "
3008[mc "Gitk key bindings:"]
3009
3010[mc "<%s-Q>             Quit" $M1T]
3011[mc "<%s-W>             Close window" $M1T]
3012[mc "<Home>             Move to first commit"]
3013[mc "<End>              Move to last commit"]
3014[mc "<Up>, p, k Move up one commit"]
3015[mc "<Down>, n, j       Move down one commit"]
3016[mc "<Left>, z, h       Go back in history list"]
3017[mc "<Right>, x, l      Go forward in history list"]
3018[mc "<PageUp>   Move up one page in commit list"]
3019[mc "<PageDown> Move down one page in commit list"]
3020[mc "<%s-Home>  Scroll to top of commit list" $M1T]
3021[mc "<%s-End>   Scroll to bottom of commit list" $M1T]
3022[mc "<%s-Up>    Scroll commit list up one line" $M1T]
3023[mc "<%s-Down>  Scroll commit list down one line" $M1T]
3024[mc "<%s-PageUp>        Scroll commit list up one page" $M1T]
3025[mc "<%s-PageDown>      Scroll commit list down one page" $M1T]
3026[mc "<Shift-Up> Find backwards (upwards, later commits)"]
3027[mc "<Shift-Down>       Find forwards (downwards, earlier commits)"]
3028[mc "<Delete>, b        Scroll diff view up one page"]
3029[mc "<Backspace>        Scroll diff view up one page"]
3030[mc "<Space>            Scroll diff view down one page"]
3031[mc "u          Scroll diff view up 18 lines"]
3032[mc "d          Scroll diff view down 18 lines"]
3033[mc "<%s-F>             Find" $M1T]
3034[mc "<%s-G>             Move to next find hit" $M1T]
3035[mc "<Return>   Move to next find hit"]
3036[mc "/          Focus the search box"]
3037[mc "?          Move to previous find hit"]
3038[mc "f          Scroll diff view to next file"]
3039[mc "<%s-S>             Search for next hit in diff view" $M1T]
3040[mc "<%s-R>             Search for previous hit in diff view" $M1T]
3041[mc "<%s-KP+>   Increase font size" $M1T]
3042[mc "<%s-plus>  Increase font size" $M1T]
3043[mc "<%s-KP->   Decrease font size" $M1T]
3044[mc "<%s-minus> Decrease font size" $M1T]
3045[mc "<F5>               Update"]
3046" \
3047            -justify left -bg white -border 2 -relief groove
3048    pack $w.m -side top -fill both -padx 2 -pady 2
3049    ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
3050    bind $w <Key-Escape> [list destroy $w]
3051    pack $w.ok -side bottom
3052    bind $w <Visibility> "focus $w.ok"
3053    bind $w <Key-Escape> "destroy $w"
3054    bind $w <Key-Return> "destroy $w"
3055}
3056
3057# Procedures for manipulating the file list window at the
3058# bottom right of the overall window.
3059
3060proc treeview {w l openlevs} {
3061    global treecontents treediropen treeheight treeparent treeindex
3062
3063    set ix 0
3064    set treeindex() 0
3065    set lev 0
3066    set prefix {}
3067    set prefixend -1
3068    set prefendstack {}
3069    set htstack {}
3070    set ht 0
3071    set treecontents() {}
3072    $w conf -state normal
3073    foreach f $l {
3074        while {[string range $f 0 $prefixend] ne $prefix} {
3075            if {$lev <= $openlevs} {
3076                $w mark set e:$treeindex($prefix) "end -1c"
3077                $w mark gravity e:$treeindex($prefix) left
3078            }
3079            set treeheight($prefix) $ht
3080            incr ht [lindex $htstack end]
3081            set htstack [lreplace $htstack end end]
3082            set prefixend [lindex $prefendstack end]
3083            set prefendstack [lreplace $prefendstack end end]
3084            set prefix [string range $prefix 0 $prefixend]
3085            incr lev -1
3086        }
3087        set tail [string range $f [expr {$prefixend+1}] end]
3088        while {[set slash [string first "/" $tail]] >= 0} {
3089            lappend htstack $ht
3090            set ht 0
3091            lappend prefendstack $prefixend
3092            incr prefixend [expr {$slash + 1}]
3093            set d [string range $tail 0 $slash]
3094            lappend treecontents($prefix) $d
3095            set oldprefix $prefix
3096            append prefix $d
3097            set treecontents($prefix) {}
3098            set treeindex($prefix) [incr ix]
3099            set treeparent($prefix) $oldprefix
3100            set tail [string range $tail [expr {$slash+1}] end]
3101            if {$lev <= $openlevs} {
3102                set ht 1
3103                set treediropen($prefix) [expr {$lev < $openlevs}]
3104                set bm [expr {$lev == $openlevs? "tri-rt": "tri-dn"}]
3105                $w mark set d:$ix "end -1c"
3106                $w mark gravity d:$ix left
3107                set str "\n"
3108                for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3109                $w insert end $str
3110                $w image create end -align center -image $bm -padx 1 \
3111                    -name a:$ix
3112                $w insert end $d [highlight_tag $prefix]
3113                $w mark set s:$ix "end -1c"
3114                $w mark gravity s:$ix left
3115            }
3116            incr lev
3117        }
3118        if {$tail ne {}} {
3119            if {$lev <= $openlevs} {
3120                incr ht
3121                set str "\n"
3122                for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3123                $w insert end $str
3124                $w insert end $tail [highlight_tag $f]
3125            }
3126            lappend treecontents($prefix) $tail
3127        }
3128    }
3129    while {$htstack ne {}} {
3130        set treeheight($prefix) $ht
3131        incr ht [lindex $htstack end]
3132        set htstack [lreplace $htstack end end]
3133        set prefixend [lindex $prefendstack end]
3134        set prefendstack [lreplace $prefendstack end end]
3135        set prefix [string range $prefix 0 $prefixend]
3136    }
3137    $w conf -state disabled
3138}
3139
3140proc linetoelt {l} {
3141    global treeheight treecontents
3142
3143    set y 2
3144    set prefix {}
3145    while {1} {
3146        foreach e $treecontents($prefix) {
3147            if {$y == $l} {
3148                return "$prefix$e"
3149            }
3150            set n 1
3151            if {[string index $e end] eq "/"} {
3152                set n $treeheight($prefix$e)
3153                if {$y + $n > $l} {
3154                    append prefix $e
3155                    incr y
3156                    break
3157                }
3158            }
3159            incr y $n
3160        }
3161    }
3162}
3163
3164proc highlight_tree {y prefix} {
3165    global treeheight treecontents cflist
3166
3167    foreach e $treecontents($prefix) {
3168        set path $prefix$e
3169        if {[highlight_tag $path] ne {}} {
3170            $cflist tag add bold $y.0 "$y.0 lineend"
3171        }
3172        incr y
3173        if {[string index $e end] eq "/" && $treeheight($path) > 1} {
3174            set y [highlight_tree $y $path]
3175        }
3176    }
3177    return $y
3178}
3179
3180proc treeclosedir {w dir} {
3181    global treediropen treeheight treeparent treeindex
3182
3183    set ix $treeindex($dir)
3184    $w conf -state normal
3185    $w delete s:$ix e:$ix
3186    set treediropen($dir) 0
3187    $w image configure a:$ix -image tri-rt
3188    $w conf -state disabled
3189    set n [expr {1 - $treeheight($dir)}]
3190    while {$dir ne {}} {
3191        incr treeheight($dir) $n
3192        set dir $treeparent($dir)
3193    }
3194}
3195
3196proc treeopendir {w dir} {
3197    global treediropen treeheight treeparent treecontents treeindex
3198
3199    set ix $treeindex($dir)
3200    $w conf -state normal
3201    $w image configure a:$ix -image tri-dn
3202    $w mark set e:$ix s:$ix
3203    $w mark gravity e:$ix right
3204    set lev 0
3205    set str "\n"
3206    set n [llength $treecontents($dir)]
3207    for {set x $dir} {$x ne {}} {set x $treeparent($x)} {
3208        incr lev
3209        append str "\t"
3210        incr treeheight($x) $n
3211    }
3212    foreach e $treecontents($dir) {
3213        set de $dir$e
3214        if {[string index $e end] eq "/"} {
3215            set iy $treeindex($de)
3216            $w mark set d:$iy e:$ix
3217            $w mark gravity d:$iy left
3218            $w insert e:$ix $str
3219            set treediropen($de) 0
3220            $w image create e:$ix -align center -image tri-rt -padx 1 \
3221                -name a:$iy
3222            $w insert e:$ix $e [highlight_tag $de]
3223            $w mark set s:$iy e:$ix
3224            $w mark gravity s:$iy left
3225            set treeheight($de) 1
3226        } else {
3227            $w insert e:$ix $str
3228            $w insert e:$ix $e [highlight_tag $de]
3229        }
3230    }
3231    $w mark gravity e:$ix right
3232    $w conf -state disabled
3233    set treediropen($dir) 1
3234    set top [lindex [split [$w index @0,0] .] 0]
3235    set ht [$w cget -height]
3236    set l [lindex [split [$w index s:$ix] .] 0]
3237    if {$l < $top} {
3238        $w yview $l.0
3239    } elseif {$l + $n + 1 > $top + $ht} {
3240        set top [expr {$l + $n + 2 - $ht}]
3241        if {$l < $top} {
3242            set top $l
3243        }
3244        $w yview $top.0
3245    }
3246}
3247
3248proc treeclick {w x y} {
3249    global treediropen cmitmode ctext cflist cflist_top
3250
3251    if {$cmitmode ne "tree"} return
3252    if {![info exists cflist_top]} return
3253    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3254    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3255    $cflist tag add highlight $l.0 "$l.0 lineend"
3256    set cflist_top $l
3257    if {$l == 1} {
3258        $ctext yview 1.0
3259        return
3260    }
3261    set e [linetoelt $l]
3262    if {[string index $e end] ne "/"} {
3263        showfile $e
3264    } elseif {$treediropen($e)} {
3265        treeclosedir $w $e
3266    } else {
3267        treeopendir $w $e
3268    }
3269}
3270
3271proc setfilelist {id} {
3272    global treefilelist cflist jump_to_here
3273
3274    treeview $cflist $treefilelist($id) 0
3275    if {$jump_to_here ne {}} {
3276        set f [lindex $jump_to_here 0]
3277        if {[lsearch -exact $treefilelist($id) $f] >= 0} {
3278            showfile $f
3279        }
3280    }
3281}
3282
3283image create bitmap tri-rt -background black -foreground blue -data {
3284    #define tri-rt_width 13
3285    #define tri-rt_height 13
3286    static unsigned char tri-rt_bits[] = {
3287       0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x30, 0x00, 0x70, 0x00, 0xf0, 0x00,
3288       0xf0, 0x01, 0xf0, 0x00, 0x70, 0x00, 0x30, 0x00, 0x10, 0x00, 0x00, 0x00,
3289       0x00, 0x00};
3290} -maskdata {
3291    #define tri-rt-mask_width 13
3292    #define tri-rt-mask_height 13
3293    static unsigned char tri-rt-mask_bits[] = {
3294       0x08, 0x00, 0x18, 0x00, 0x38, 0x00, 0x78, 0x00, 0xf8, 0x00, 0xf8, 0x01,
3295       0xf8, 0x03, 0xf8, 0x01, 0xf8, 0x00, 0x78, 0x00, 0x38, 0x00, 0x18, 0x00,
3296       0x08, 0x00};
3297}
3298image create bitmap tri-dn -background black -foreground blue -data {
3299    #define tri-dn_width 13
3300    #define tri-dn_height 13
3301    static unsigned char tri-dn_bits[] = {
3302       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xf8, 0x03,
3303       0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3304       0x00, 0x00};
3305} -maskdata {
3306    #define tri-dn-mask_width 13
3307    #define tri-dn-mask_height 13
3308    static unsigned char tri-dn-mask_bits[] = {
3309       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x1f, 0xfe, 0x0f, 0xfc, 0x07,
3310       0xf8, 0x03, 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
3311       0x00, 0x00};
3312}
3313
3314image create bitmap reficon-T -background black -foreground yellow -data {
3315    #define tagicon_width 13
3316    #define tagicon_height 9
3317    static unsigned char tagicon_bits[] = {
3318       0x00, 0x00, 0x00, 0x00, 0xf0, 0x07, 0xf8, 0x07,
3319       0xfc, 0x07, 0xf8, 0x07, 0xf0, 0x07, 0x00, 0x00, 0x00, 0x00};
3320} -maskdata {
3321    #define tagicon-mask_width 13
3322    #define tagicon-mask_height 9
3323    static unsigned char tagicon-mask_bits[] = {
3324       0x00, 0x00, 0xf0, 0x0f, 0xf8, 0x0f, 0xfc, 0x0f,
3325       0xfe, 0x0f, 0xfc, 0x0f, 0xf8, 0x0f, 0xf0, 0x0f, 0x00, 0x00};
3326}
3327set rectdata {
3328    #define headicon_width 13
3329    #define headicon_height 9
3330    static unsigned char headicon_bits[] = {
3331       0x00, 0x00, 0x00, 0x00, 0xf8, 0x07, 0xf8, 0x07,
3332       0xf8, 0x07, 0xf8, 0x07, 0xf8, 0x07, 0x00, 0x00, 0x00, 0x00};
3333}
3334set rectmask {
3335    #define headicon-mask_width 13
3336    #define headicon-mask_height 9
3337    static unsigned char headicon-mask_bits[] = {
3338       0x00, 0x00, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f,
3339       0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0x00, 0x00};
3340}
3341image create bitmap reficon-H -background black -foreground green \
3342    -data $rectdata -maskdata $rectmask
3343image create bitmap reficon-o -background black -foreground "#ddddff" \
3344    -data $rectdata -maskdata $rectmask
3345
3346proc init_flist {first} {
3347    global cflist cflist_top difffilestart
3348
3349    $cflist conf -state normal
3350    $cflist delete 0.0 end
3351    if {$first ne {}} {
3352        $cflist insert end $first
3353        set cflist_top 1
3354        $cflist tag add highlight 1.0 "1.0 lineend"
3355    } else {
3356        catch {unset cflist_top}
3357    }
3358    $cflist conf -state disabled
3359    set difffilestart {}
3360}
3361
3362proc highlight_tag {f} {
3363    global highlight_paths
3364
3365    foreach p $highlight_paths {
3366        if {[string match $p $f]} {
3367            return "bold"
3368        }
3369    }
3370    return {}
3371}
3372
3373proc highlight_filelist {} {
3374    global cmitmode cflist
3375
3376    $cflist conf -state normal
3377    if {$cmitmode ne "tree"} {
3378        set end [lindex [split [$cflist index end] .] 0]
3379        for {set l 2} {$l < $end} {incr l} {
3380            set line [$cflist get $l.0 "$l.0 lineend"]
3381            if {[highlight_tag $line] ne {}} {
3382                $cflist tag add bold $l.0 "$l.0 lineend"
3383            }
3384        }
3385    } else {
3386        highlight_tree 2 {}
3387    }
3388    $cflist conf -state disabled
3389}
3390
3391proc unhighlight_filelist {} {
3392    global cflist
3393
3394    $cflist conf -state normal
3395    $cflist tag remove bold 1.0 end
3396    $cflist conf -state disabled
3397}
3398
3399proc add_flist {fl} {
3400    global cflist
3401
3402    $cflist conf -state normal
3403    foreach f $fl {
3404        $cflist insert end "\n"
3405        $cflist insert end $f [highlight_tag $f]
3406    }
3407    $cflist conf -state disabled
3408}
3409
3410proc sel_flist {w x y} {
3411    global ctext difffilestart cflist cflist_top cmitmode
3412
3413    if {$cmitmode eq "tree"} return
3414    if {![info exists cflist_top]} return
3415    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3416    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3417    $cflist tag add highlight $l.0 "$l.0 lineend"
3418    set cflist_top $l
3419    if {$l == 1} {
3420        $ctext yview 1.0
3421    } else {
3422        catch {$ctext yview [lindex $difffilestart [expr {$l - 2}]]}
3423    }
3424    suppress_highlighting_file_for_current_scrollpos
3425}
3426
3427proc pop_flist_menu {w X Y x y} {
3428    global ctext cflist cmitmode flist_menu flist_menu_file
3429    global treediffs diffids
3430
3431    stopfinding
3432    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3433    if {$l <= 1} return
3434    if {$cmitmode eq "tree"} {
3435        set e [linetoelt $l]
3436        if {[string index $e end] eq "/"} return
3437    } else {
3438        set e [lindex $treediffs($diffids) [expr {$l-2}]]
3439    }
3440    set flist_menu_file $e
3441    set xdiffstate "normal"
3442    if {$cmitmode eq "tree"} {
3443        set xdiffstate "disabled"
3444    }
3445    # Disable "External diff" item in tree mode
3446    $flist_menu entryconf 2 -state $xdiffstate
3447    tk_popup $flist_menu $X $Y
3448}
3449
3450proc find_ctext_fileinfo {line} {
3451    global ctext_file_names ctext_file_lines
3452
3453    set ok [bsearch $ctext_file_lines $line]
3454    set tline [lindex $ctext_file_lines $ok]
3455
3456    if {$ok >= [llength $ctext_file_lines] || $line < $tline} {
3457        return {}
3458    } else {
3459        return [list [lindex $ctext_file_names $ok] $tline]
3460    }
3461}
3462
3463proc pop_diff_menu {w X Y x y} {
3464    global ctext diff_menu flist_menu_file
3465    global diff_menu_txtpos diff_menu_line
3466    global diff_menu_filebase
3467
3468    set diff_menu_txtpos [split [$w index "@$x,$y"] "."]
3469    set diff_menu_line [lindex $diff_menu_txtpos 0]
3470    # don't pop up the menu on hunk-separator or file-separator lines
3471    if {[lsearch -glob [$ctext tag names $diff_menu_line.0] "*sep"] >= 0} {
3472        return
3473    }
3474    stopfinding
3475    set f [find_ctext_fileinfo $diff_menu_line]
3476    if {$f eq {}} return
3477    set flist_menu_file [lindex $f 0]
3478    set diff_menu_filebase [lindex $f 1]
3479    tk_popup $diff_menu $X $Y
3480}
3481
3482proc flist_hl {only} {
3483    global flist_menu_file findstring gdttype
3484
3485    set x [shellquote $flist_menu_file]
3486    if {$only || $findstring eq {} || $gdttype ne [mc "touching paths:"]} {
3487        set findstring $x
3488    } else {
3489        append findstring " " $x
3490    }
3491    set gdttype [mc "touching paths:"]
3492}
3493
3494proc gitknewtmpdir {} {
3495    global diffnum gitktmpdir gitdir
3496
3497    if {![info exists gitktmpdir]} {
3498        set gitktmpdir [file join $gitdir [format ".gitk-tmp.%s" [pid]]]
3499        if {[catch {file mkdir $gitktmpdir} err]} {
3500            error_popup "[mc "Error creating temporary directory %s:" $gitktmpdir] $err"
3501            unset gitktmpdir
3502            return {}
3503        }
3504        set diffnum 0
3505    }
3506    incr diffnum
3507    set diffdir [file join $gitktmpdir $diffnum]
3508    if {[catch {file mkdir $diffdir} err]} {
3509        error_popup "[mc "Error creating temporary directory %s:" $diffdir] $err"
3510        return {}
3511    }
3512    return $diffdir
3513}
3514
3515proc save_file_from_commit {filename output what} {
3516    global nullfile
3517
3518    if {[catch {exec git show $filename -- > $output} err]} {
3519        if {[string match "fatal: bad revision *" $err]} {
3520            return $nullfile
3521        }
3522        error_popup "[mc "Error getting \"%s\" from %s:" $filename $what] $err"
3523        return {}
3524    }
3525    return $output
3526}
3527
3528proc external_diff_get_one_file {diffid filename diffdir} {
3529    global nullid nullid2 nullfile
3530    global worktree
3531
3532    if {$diffid == $nullid} {
3533        set difffile [file join $worktree $filename]
3534        if {[file exists $difffile]} {
3535            return $difffile
3536        }
3537        return $nullfile
3538    }
3539    if {$diffid == $nullid2} {
3540        set difffile [file join $diffdir "\[index\] [file tail $filename]"]
3541        return [save_file_from_commit :$filename $difffile index]
3542    }
3543    set difffile [file join $diffdir "\[$diffid\] [file tail $filename]"]
3544    return [save_file_from_commit $diffid:$filename $difffile \
3545               "revision $diffid"]
3546}
3547
3548proc external_diff {} {
3549    global nullid nullid2
3550    global flist_menu_file
3551    global diffids
3552    global extdifftool
3553
3554    if {[llength $diffids] == 1} {
3555        # no reference commit given
3556        set diffidto [lindex $diffids 0]
3557        if {$diffidto eq $nullid} {
3558            # diffing working copy with index
3559            set diffidfrom $nullid2
3560        } elseif {$diffidto eq $nullid2} {
3561            # diffing index with HEAD
3562            set diffidfrom "HEAD"
3563        } else {
3564            # use first parent commit
3565            global parentlist selectedline
3566            set diffidfrom [lindex $parentlist $selectedline 0]
3567        }
3568    } else {
3569        set diffidfrom [lindex $diffids 0]
3570        set diffidto [lindex $diffids 1]
3571    }
3572
3573    # make sure that several diffs wont collide
3574    set diffdir [gitknewtmpdir]
3575    if {$diffdir eq {}} return
3576
3577    # gather files to diff
3578    set difffromfile [external_diff_get_one_file $diffidfrom $flist_menu_file $diffdir]
3579    set difftofile [external_diff_get_one_file $diffidto $flist_menu_file $diffdir]
3580
3581    if {$difffromfile ne {} && $difftofile ne {}} {
3582        set cmd [list [shellsplit $extdifftool] $difffromfile $difftofile]
3583        if {[catch {set fl [open |$cmd r]} err]} {
3584            file delete -force $diffdir
3585            error_popup "$extdifftool: [mc "command failed:"] $err"
3586        } else {
3587            fconfigure $fl -blocking 0
3588            filerun $fl [list delete_at_eof $fl $diffdir]
3589        }
3590    }
3591}
3592
3593proc find_hunk_blamespec {base line} {
3594    global ctext
3595
3596    # Find and parse the hunk header
3597    set s_lix [$ctext search -backwards -regexp ^@@ "$line.0 lineend" $base.0]
3598    if {$s_lix eq {}} return
3599
3600    set s_line [$ctext get $s_lix "$s_lix + 1 lines"]
3601    if {![regexp {^@@@*(( -\d+(,\d+)?)+) \+(\d+)(,\d+)? @@} $s_line \
3602            s_line old_specs osz osz1 new_line nsz]} {
3603        return
3604    }
3605
3606    # base lines for the parents
3607    set base_lines [list $new_line]
3608    foreach old_spec [lrange [split $old_specs " "] 1 end] {
3609        if {![regexp -- {-(\d+)(,\d+)?} $old_spec \
3610                old_spec old_line osz]} {
3611            return
3612        }
3613        lappend base_lines $old_line
3614    }
3615
3616    # Now scan the lines to determine offset within the hunk
3617    set max_parent [expr {[llength $base_lines]-2}]
3618    set dline 0
3619    set s_lno [lindex [split $s_lix "."] 0]
3620
3621    # Determine if the line is removed
3622    set chunk [$ctext get $line.0 "$line.1 + $max_parent chars"]
3623    if {[string match {[-+ ]*} $chunk]} {
3624        set removed_idx [string first "-" $chunk]
3625        # Choose a parent index
3626        if {$removed_idx >= 0} {
3627            set parent $removed_idx
3628        } else {
3629            set unchanged_idx [string first " " $chunk]
3630            if {$unchanged_idx >= 0} {
3631                set parent $unchanged_idx
3632            } else {
3633                # blame the current commit
3634                set parent -1
3635            }
3636        }
3637        # then count other lines that belong to it
3638        for {set i $line} {[incr i -1] > $s_lno} {} {
3639            set chunk [$ctext get $i.0 "$i.1 + $max_parent chars"]
3640            # Determine if the line is removed
3641            set removed_idx [string first "-" $chunk]
3642            if {$parent >= 0} {
3643                set code [string index $chunk $parent]
3644                if {$code eq "-" || ($removed_idx < 0 && $code ne "+")} {
3645                    incr dline
3646                }
3647            } else {
3648                if {$removed_idx < 0} {
3649                    incr dline
3650                }
3651            }
3652        }
3653        incr parent
3654    } else {
3655        set parent 0
3656    }
3657
3658    incr dline [lindex $base_lines $parent]
3659    return [list $parent $dline]
3660}
3661
3662proc external_blame_diff {} {
3663    global currentid cmitmode
3664    global diff_menu_txtpos diff_menu_line
3665    global diff_menu_filebase flist_menu_file
3666
3667    if {$cmitmode eq "tree"} {
3668        set parent_idx 0
3669        set line [expr {$diff_menu_line - $diff_menu_filebase}]
3670    } else {
3671        set hinfo [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3672        if {$hinfo ne {}} {
3673            set parent_idx [lindex $hinfo 0]
3674            set line [lindex $hinfo 1]
3675        } else {
3676            set parent_idx 0
3677            set line 0
3678        }
3679    }
3680
3681    external_blame $parent_idx $line
3682}
3683
3684# Find the SHA1 ID of the blob for file $fname in the index
3685# at stage 0 or 2
3686proc index_sha1 {fname} {
3687    set f [open [list | git ls-files -s $fname] r]
3688    while {[gets $f line] >= 0} {
3689        set info [lindex [split $line "\t"] 0]
3690        set stage [lindex $info 2]
3691        if {$stage eq "0" || $stage eq "2"} {
3692            close $f
3693            return [lindex $info 1]
3694        }
3695    }
3696    close $f
3697    return {}
3698}
3699
3700# Turn an absolute path into one relative to the current directory
3701proc make_relative {f} {
3702    if {[file pathtype $f] eq "relative"} {
3703        return $f
3704    }
3705    set elts [file split $f]
3706    set here [file split [pwd]]
3707    set ei 0
3708    set hi 0
3709    set res {}
3710    foreach d $here {
3711        if {$ei < $hi || $ei >= [llength $elts] || [lindex $elts $ei] ne $d} {
3712            lappend res ".."
3713        } else {
3714            incr ei
3715        }
3716        incr hi
3717    }
3718    set elts [concat $res [lrange $elts $ei end]]
3719    return [eval file join $elts]
3720}
3721
3722proc external_blame {parent_idx {line {}}} {
3723    global flist_menu_file cdup
3724    global nullid nullid2
3725    global parentlist selectedline currentid
3726
3727    if {$parent_idx > 0} {
3728        set base_commit [lindex $parentlist $selectedline [expr {$parent_idx-1}]]
3729    } else {
3730        set base_commit $currentid
3731    }
3732
3733    if {$base_commit eq {} || $base_commit eq $nullid || $base_commit eq $nullid2} {
3734        error_popup [mc "No such commit"]
3735        return
3736    }
3737
3738    set cmdline [list git gui blame]
3739    if {$line ne {} && $line > 1} {
3740        lappend cmdline "--line=$line"
3741    }
3742    set f [file join $cdup $flist_menu_file]
3743    # Unfortunately it seems git gui blame doesn't like
3744    # being given an absolute path...
3745    set f [make_relative $f]
3746    lappend cmdline $base_commit $f
3747    if {[catch {eval exec $cmdline &} err]} {
3748        error_popup "[mc "git gui blame: command failed:"] $err"
3749    }
3750}
3751
3752proc show_line_source {} {
3753    global cmitmode currentid parents curview blamestuff blameinst
3754    global diff_menu_line diff_menu_filebase flist_menu_file
3755    global nullid nullid2 gitdir cdup
3756
3757    set from_index {}
3758    if {$cmitmode eq "tree"} {
3759        set id $currentid
3760        set line [expr {$diff_menu_line - $diff_menu_filebase}]
3761    } else {
3762        set h [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3763        if {$h eq {}} return
3764        set pi [lindex $h 0]
3765        if {$pi == 0} {
3766            mark_ctext_line $diff_menu_line
3767            return
3768        }
3769        incr pi -1
3770        if {$currentid eq $nullid} {
3771            if {$pi > 0} {
3772                # must be a merge in progress...
3773                if {[catch {
3774                    # get the last line from .git/MERGE_HEAD
3775                    set f [open [file join $gitdir MERGE_HEAD] r]
3776                    set id [lindex [split [read $f] "\n"] end-1]
3777                    close $f
3778                } err]} {
3779                    error_popup [mc "Couldn't read merge head: %s" $err]
3780                    return
3781                }
3782            } elseif {$parents($curview,$currentid) eq $nullid2} {
3783                # need to do the blame from the index
3784                if {[catch {
3785                    set from_index [index_sha1 $flist_menu_file]
3786                } err]} {
3787                    error_popup [mc "Error reading index: %s" $err]
3788                    return
3789                }
3790            } else {
3791                set id $parents($curview,$currentid)
3792            }
3793        } else {
3794            set id [lindex $parents($curview,$currentid) $pi]
3795        }
3796        set line [lindex $h 1]
3797    }
3798    set blameargs {}
3799    if {$from_index ne {}} {
3800        lappend blameargs | git cat-file blob $from_index
3801    }
3802    lappend blameargs | git blame -p -L$line,+1
3803    if {$from_index ne {}} {
3804        lappend blameargs --contents -
3805    } else {
3806        lappend blameargs $id
3807    }
3808    lappend blameargs -- [file join $cdup $flist_menu_file]
3809    if {[catch {
3810        set f [open $blameargs r]
3811    } err]} {
3812        error_popup [mc "Couldn't start git blame: %s" $err]
3813        return
3814    }
3815    nowbusy blaming [mc "Searching"]
3816    fconfigure $f -blocking 0
3817    set i [reg_instance $f]
3818    set blamestuff($i) {}
3819    set blameinst $i
3820    filerun $f [list read_line_source $f $i]
3821}
3822
3823proc stopblaming {} {
3824    global blameinst
3825
3826    if {[info exists blameinst]} {
3827        stop_instance $blameinst
3828        unset blameinst
3829        notbusy blaming
3830    }
3831}
3832
3833proc read_line_source {fd inst} {
3834    global blamestuff curview commfd blameinst nullid nullid2
3835
3836    while {[gets $fd line] >= 0} {
3837        lappend blamestuff($inst) $line
3838    }
3839    if {![eof $fd]} {
3840        return 1
3841    }
3842    unset commfd($inst)
3843    unset blameinst
3844    notbusy blaming
3845    fconfigure $fd -blocking 1
3846    if {[catch {close $fd} err]} {
3847        error_popup [mc "Error running git blame: %s" $err]
3848        return 0
3849    }
3850
3851    set fname {}
3852    set line [split [lindex $blamestuff($inst) 0] " "]
3853    set id [lindex $line 0]
3854    set lnum [lindex $line 1]
3855    if {[string length $id] == 40 && [string is xdigit $id] &&
3856        [string is digit -strict $lnum]} {
3857        # look for "filename" line
3858        foreach l $blamestuff($inst) {
3859            if {[string match "filename *" $l]} {
3860                set fname [string range $l 9 end]
3861                break
3862            }
3863        }
3864    }
3865    if {$fname ne {}} {
3866        # all looks good, select it
3867        if {$id eq $nullid} {
3868            # blame uses all-zeroes to mean not committed,
3869            # which would mean a change in the index
3870            set id $nullid2
3871        }
3872        if {[commitinview $id $curview]} {
3873            selectline [rowofcommit $id] 1 [list $fname $lnum]
3874        } else {
3875            error_popup [mc "That line comes from commit %s, \
3876                             which is not in this view" [shortids $id]]
3877        }
3878    } else {
3879        puts "oops couldn't parse git blame output"
3880    }
3881    return 0
3882}
3883
3884# delete $dir when we see eof on $f (presumably because the child has exited)
3885proc delete_at_eof {f dir} {
3886    while {[gets $f line] >= 0} {}
3887    if {[eof $f]} {
3888        if {[catch {close $f} err]} {
3889            error_popup "[mc "External diff viewer failed:"] $err"
3890        }
3891        file delete -force $dir
3892        return 0
3893    }
3894    return 1
3895}
3896
3897# Functions for adding and removing shell-type quoting
3898
3899proc shellquote {str} {
3900    if {![string match "*\['\"\\ \t]*" $str]} {
3901        return $str
3902    }
3903    if {![string match "*\['\"\\]*" $str]} {
3904        return "\"$str\""
3905    }
3906    if {![string match "*'*" $str]} {
3907        return "'$str'"
3908    }
3909    return "\"[string map {\" \\\" \\ \\\\} $str]\""
3910}
3911
3912proc shellarglist {l} {
3913    set str {}
3914    foreach a $l {
3915        if {$str ne {}} {
3916            append str " "
3917        }
3918        append str [shellquote $a]
3919    }
3920    return $str
3921}
3922
3923proc shelldequote {str} {
3924    set ret {}
3925    set used -1
3926    while {1} {
3927        incr used
3928        if {![regexp -start $used -indices "\['\"\\\\ \t]" $str first]} {
3929            append ret [string range $str $used end]
3930            set used [string length $str]
3931            break
3932        }
3933        set first [lindex $first 0]
3934        set ch [string index $str $first]
3935        if {$first > $used} {
3936            append ret [string range $str $used [expr {$first - 1}]]
3937            set used $first
3938        }
3939        if {$ch eq " " || $ch eq "\t"} break
3940        incr used
3941        if {$ch eq "'"} {
3942            set first [string first "'" $str $used]
3943            if {$first < 0} {
3944                error "unmatched single-quote"
3945            }
3946            append ret [string range $str $used [expr {$first - 1}]]
3947            set used $first
3948            continue
3949        }
3950        if {$ch eq "\\"} {
3951            if {$used >= [string length $str]} {
3952                error "trailing backslash"
3953            }
3954            append ret [string index $str $used]
3955            continue
3956        }
3957        # here ch == "\""
3958        while {1} {
3959            if {![regexp -start $used -indices "\[\"\\\\]" $str first]} {
3960                error "unmatched double-quote"
3961            }
3962            set first [lindex $first 0]
3963            set ch [string index $str $first]
3964            if {$first > $used} {
3965                append ret [string range $str $used [expr {$first - 1}]]
3966                set used $first
3967            }
3968            if {$ch eq "\""} break
3969            incr used
3970            append ret [string index $str $used]
3971            incr used
3972        }
3973    }
3974    return [list $used $ret]
3975}
3976
3977proc shellsplit {str} {
3978    set l {}
3979    while {1} {
3980        set str [string trimleft $str]
3981        if {$str eq {}} break
3982        set dq [shelldequote $str]
3983        set n [lindex $dq 0]
3984        set word [lindex $dq 1]
3985        set str [string range $str $n end]
3986        lappend l $word
3987    }
3988    return $l
3989}
3990
3991# Code to implement multiple views
3992
3993proc newview {ishighlight} {
3994    global nextviewnum newviewname newishighlight
3995    global revtreeargs viewargscmd newviewopts curview
3996
3997    set newishighlight $ishighlight
3998    set top .gitkview
3999    if {[winfo exists $top]} {
4000        raise $top
4001        return
4002    }
4003    decode_view_opts $nextviewnum $revtreeargs
4004    set newviewname($nextviewnum) "[mc "View"] $nextviewnum"
4005    set newviewopts($nextviewnum,perm) 0
4006    set newviewopts($nextviewnum,cmd)  $viewargscmd($curview)
4007    vieweditor $top $nextviewnum [mc "Gitk view definition"]
4008}
4009
4010set known_view_options {
4011    {perm      b    .  {}               {mc "Remember this view"}}
4012    {reflabel  l    +  {}               {mc "References (space separated list):"}}
4013    {refs      t15  .. {}               {mc "Branches & tags:"}}
4014    {allrefs   b    *. "--all"          {mc "All refs"}}
4015    {branches  b    .  "--branches"     {mc "All (local) branches"}}
4016    {tags      b    .  "--tags"         {mc "All tags"}}
4017    {remotes   b    .  "--remotes"      {mc "All remote-tracking branches"}}
4018    {commitlbl l    +  {}               {mc "Commit Info (regular expressions):"}}
4019    {author    t15  .. "--author=*"     {mc "Author:"}}
4020    {committer t15  .  "--committer=*"  {mc "Committer:"}}
4021    {loginfo   t15  .. "--grep=*"       {mc "Commit Message:"}}
4022    {allmatch  b    .. "--all-match"    {mc "Matches all Commit Info criteria"}}
4023    {changes_l l    +  {}               {mc "Changes to Files:"}}
4024    {pickaxe_s r0   .  {}               {mc "Fixed String"}}
4025    {pickaxe_t r1   .  "--pickaxe-regex"  {mc "Regular Expression"}}
4026    {pickaxe   t15  .. "-S*"            {mc "Search string:"}}
4027    {datelabel l    +  {}               {mc "Commit Dates (\"2 weeks ago\", \"2009-03-17 15:27:38\", \"March 17, 2009 15:27:38\"):"}}
4028    {since     t15  ..  {"--since=*" "--after=*"}  {mc "Since:"}}
4029    {until     t15  .   {"--until=*" "--before=*"} {mc "Until:"}}
4030    {limit_lbl l    +  {}               {mc "Limit and/or skip a number of revisions (positive integer):"}}
4031    {limit     t10  *. "--max-count=*"  {mc "Number to show:"}}
4032    {skip      t10  .  "--skip=*"       {mc "Number to skip:"}}
4033    {misc_lbl  l    +  {}               {mc "Miscellaneous options:"}}
4034    {dorder    b    *. {"--date-order" "-d"}      {mc "Strictly sort by date"}}
4035    {lright    b    .  "--left-right"   {mc "Mark branch sides"}}
4036    {first     b    .  "--first-parent" {mc "Limit to first parent"}}
4037    {smplhst   b    .  "--simplify-by-decoration"   {mc "Simple history"}}
4038    {args      t50  *. {}               {mc "Additional arguments to git log:"}}
4039    {allpaths  path +  {}               {mc "Enter files and directories to include, one per line:"}}
4040    {cmd       t50= +  {}               {mc "Command to generate more commits to include:"}}
4041    }
4042
4043# Convert $newviewopts($n, ...) into args for git log.
4044proc encode_view_opts {n} {
4045    global known_view_options newviewopts
4046
4047    set rargs [list]
4048    foreach opt $known_view_options {
4049        set patterns [lindex $opt 3]
4050        if {$patterns eq {}} continue
4051        set pattern [lindex $patterns 0]
4052
4053        if {[lindex $opt 1] eq "b"} {
4054            set val $newviewopts($n,[lindex $opt 0])
4055            if {$val} {
4056                lappend rargs $pattern
4057            }
4058        } elseif {[regexp {^r(\d+)$} [lindex $opt 1] type value]} {
4059            regexp {^(.*_)} [lindex $opt 0] uselessvar button_id
4060            set val $newviewopts($n,$button_id)
4061            if {$val eq $value} {
4062                lappend rargs $pattern
4063            }
4064        } else {
4065            set val $newviewopts($n,[lindex $opt 0])
4066            set val [string trim $val]
4067            if {$val ne {}} {
4068                set pfix [string range $pattern 0 end-1]
4069                lappend rargs $pfix$val
4070            }
4071        }
4072    }
4073    set rargs [concat $rargs [shellsplit $newviewopts($n,refs)]]
4074    return [concat $rargs [shellsplit $newviewopts($n,args)]]
4075}
4076
4077# Fill $newviewopts($n, ...) based on args for git log.
4078proc decode_view_opts {n view_args} {
4079    global known_view_options newviewopts
4080
4081    foreach opt $known_view_options {
4082        set id [lindex $opt 0]
4083        if {[lindex $opt 1] eq "b"} {
4084            # Checkboxes
4085            set val 0
4086        } elseif {[regexp {^r(\d+)$} [lindex $opt 1]]} {
4087            # Radiobuttons
4088            regexp {^(.*_)} $id uselessvar id
4089            set val 0
4090        } else {
4091            # Text fields
4092            set val {}
4093        }
4094        set newviewopts($n,$id) $val
4095    }
4096    set oargs [list]
4097    set refargs [list]
4098    foreach arg $view_args {
4099        if {[regexp -- {^-([0-9]+)$} $arg arg cnt]
4100            && ![info exists found(limit)]} {
4101            set newviewopts($n,limit) $cnt
4102            set found(limit) 1
4103            continue
4104        }
4105        catch { unset val }
4106        foreach opt $known_view_options {
4107            set id [lindex $opt 0]
4108            if {[info exists found($id)]} continue
4109            foreach pattern [lindex $opt 3] {
4110                if {![string match $pattern $arg]} continue
4111                if {[lindex $opt 1] eq "b"} {
4112                    # Check buttons
4113                    set val 1
4114                } elseif {[regexp {^r(\d+)$} [lindex $opt 1] match num]} {
4115                    # Radio buttons
4116                    regexp {^(.*_)} $id uselessvar id
4117                    set val $num
4118                } else {
4119                    # Text input fields
4120                    set size [string length $pattern]
4121                    set val [string range $arg [expr {$size-1}] end]
4122                }
4123                set newviewopts($n,$id) $val
4124                set found($id) 1
4125                break
4126            }
4127            if {[info exists val]} break
4128        }
4129        if {[info exists val]} continue
4130        if {[regexp {^-} $arg]} {
4131            lappend oargs $arg
4132        } else {
4133            lappend refargs $arg
4134        }
4135    }
4136    set newviewopts($n,refs) [shellarglist $refargs]
4137    set newviewopts($n,args) [shellarglist $oargs]
4138}
4139
4140proc edit_or_newview {} {
4141    global curview
4142
4143    if {$curview > 0} {
4144        editview
4145    } else {
4146        newview 0
4147    }
4148}
4149
4150proc editview {} {
4151    global curview
4152    global viewname viewperm newviewname newviewopts
4153    global viewargs viewargscmd
4154
4155    set top .gitkvedit-$curview
4156    if {[winfo exists $top]} {
4157        raise $top
4158        return
4159    }
4160    decode_view_opts $curview $viewargs($curview)
4161    set newviewname($curview)      $viewname($curview)
4162    set newviewopts($curview,perm) $viewperm($curview)
4163    set newviewopts($curview,cmd)  $viewargscmd($curview)
4164    vieweditor $top $curview "[mc "Gitk: edit view"] $viewname($curview)"
4165}
4166
4167proc vieweditor {top n title} {
4168    global newviewname newviewopts viewfiles bgcolor
4169    global known_view_options NS
4170
4171    ttk_toplevel $top
4172    wm title $top [concat $title [mc "-- criteria for selecting revisions"]]
4173    make_transient $top .
4174
4175    # View name
4176    ${NS}::frame $top.nfr
4177    ${NS}::label $top.nl -text [mc "View Name"]
4178    ${NS}::entry $top.name -width 20 -textvariable newviewname($n)
4179    pack $top.nfr -in $top -fill x -pady 5 -padx 3
4180    pack $top.nl -in $top.nfr -side left -padx {0 5}
4181    pack $top.name -in $top.nfr -side left -padx {0 25}
4182
4183    # View options
4184    set cframe $top.nfr
4185    set cexpand 0
4186    set cnt 0
4187    foreach opt $known_view_options {
4188        set id [lindex $opt 0]
4189        set type [lindex $opt 1]
4190        set flags [lindex $opt 2]
4191        set title [eval [lindex $opt 4]]
4192        set lxpad 0
4193
4194        if {$flags eq "+" || $flags eq "*"} {
4195            set cframe $top.fr$cnt
4196            incr cnt
4197            ${NS}::frame $cframe
4198            pack $cframe -in $top -fill x -pady 3 -padx 3
4199            set cexpand [expr {$flags eq "*"}]
4200        } elseif {$flags eq ".." || $flags eq "*."} {
4201            set cframe $top.fr$cnt
4202            incr cnt
4203            ${NS}::frame $cframe
4204            pack $cframe -in $top -fill x -pady 3 -padx [list 15 3]
4205            set cexpand [expr {$flags eq "*."}]
4206        } else {
4207            set lxpad 5
4208        }
4209
4210        if {$type eq "l"} {
4211            ${NS}::label $cframe.l_$id -text $title
4212            pack $cframe.l_$id -in $cframe -side left -pady [list 3 0] -anchor w
4213        } elseif {$type eq "b"} {
4214            ${NS}::checkbutton $cframe.c_$id -text $title -variable newviewopts($n,$id)
4215            pack $cframe.c_$id -in $cframe -side left \
4216                -padx [list $lxpad 0] -expand $cexpand -anchor w
4217        } elseif {[regexp {^r(\d+)$} $type type sz]} {
4218            regexp {^(.*_)} $id uselessvar button_id
4219            ${NS}::radiobutton $cframe.c_$id -text $title -variable newviewopts($n,$button_id) -value $sz
4220            pack $cframe.c_$id -in $cframe -side left \
4221                -padx [list $lxpad 0] -expand $cexpand -anchor w
4222        } elseif {[regexp {^t(\d+)$} $type type sz]} {
4223            ${NS}::label $cframe.l_$id -text $title
4224            ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4225                -textvariable newviewopts($n,$id)
4226            pack $cframe.l_$id -in $cframe -side left -padx [list $lxpad 0]
4227            pack $cframe.e_$id -in $cframe -side left -expand 1 -fill x
4228        } elseif {[regexp {^t(\d+)=$} $type type sz]} {
4229            ${NS}::label $cframe.l_$id -text $title
4230            ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4231                -textvariable newviewopts($n,$id)
4232            pack $cframe.l_$id -in $cframe -side top -pady [list 3 0] -anchor w
4233            pack $cframe.e_$id -in $cframe -side top -fill x
4234        } elseif {$type eq "path"} {
4235            ${NS}::label $top.l -text $title
4236            pack $top.l -in $top -side top -pady [list 3 0] -anchor w -padx 3
4237            text $top.t -width 40 -height 5 -background $bgcolor
4238            if {[info exists viewfiles($n)]} {
4239                foreach f $viewfiles($n) {
4240                    $top.t insert end $f
4241                    $top.t insert end "\n"
4242                }
4243                $top.t delete {end - 1c} end
4244                $top.t mark set insert 0.0
4245            }
4246            pack $top.t -in $top -side top -pady [list 0 5] -fill both -expand 1 -padx 3
4247        }
4248    }
4249
4250    ${NS}::frame $top.buts
4251    ${NS}::button $top.buts.ok -text [mc "OK"] -command [list newviewok $top $n]
4252    ${NS}::button $top.buts.apply -text [mc "Apply (F5)"] -command [list newviewok $top $n 1]
4253    ${NS}::button $top.buts.can -text [mc "Cancel"] -command [list destroy $top]
4254    bind $top <Control-Return> [list newviewok $top $n]
4255    bind $top <F5> [list newviewok $top $n 1]
4256    bind $top <Escape> [list destroy $top]
4257    grid $top.buts.ok $top.buts.apply $top.buts.can
4258    grid columnconfigure $top.buts 0 -weight 1 -uniform a
4259    grid columnconfigure $top.buts 1 -weight 1 -uniform a
4260    grid columnconfigure $top.buts 2 -weight 1 -uniform a
4261    pack $top.buts -in $top -side top -fill x
4262    focus $top.t
4263}
4264
4265proc doviewmenu {m first cmd op argv} {
4266    set nmenu [$m index end]
4267    for {set i $first} {$i <= $nmenu} {incr i} {
4268        if {[$m entrycget $i -command] eq $cmd} {
4269            eval $m $op $i $argv
4270            break
4271        }
4272    }
4273}
4274
4275proc allviewmenus {n op args} {
4276    # global viewhlmenu
4277
4278    doviewmenu .bar.view 5 [list showview $n] $op $args
4279    # doviewmenu $viewhlmenu 1 [list addvhighlight $n] $op $args
4280}
4281
4282proc newviewok {top n {apply 0}} {
4283    global nextviewnum newviewperm newviewname newishighlight
4284    global viewname viewfiles viewperm selectedview curview
4285    global viewargs viewargscmd newviewopts viewhlmenu
4286
4287    if {[catch {
4288        set newargs [encode_view_opts $n]
4289    } err]} {
4290        error_popup "[mc "Error in commit selection arguments:"] $err" $top
4291        return
4292    }
4293    set files {}
4294    foreach f [split [$top.t get 0.0 end] "\n"] {
4295        set ft [string trim $f]
4296        if {$ft ne {}} {
4297            lappend files $ft
4298        }
4299    }
4300    if {![info exists viewfiles($n)]} {
4301        # creating a new view
4302        incr nextviewnum
4303        set viewname($n) $newviewname($n)
4304        set viewperm($n) $newviewopts($n,perm)
4305        set viewfiles($n) $files
4306        set viewargs($n) $newargs
4307        set viewargscmd($n) $newviewopts($n,cmd)
4308        addviewmenu $n
4309        if {!$newishighlight} {
4310            run showview $n
4311        } else {
4312            run addvhighlight $n
4313        }
4314    } else {
4315        # editing an existing view
4316        set viewperm($n) $newviewopts($n,perm)
4317        if {$newviewname($n) ne $viewname($n)} {
4318            set viewname($n) $newviewname($n)
4319            doviewmenu .bar.view 5 [list showview $n] \
4320                entryconf [list -label $viewname($n)]
4321            # doviewmenu $viewhlmenu 1 [list addvhighlight $n] \
4322                # entryconf [list -label $viewname($n) -value $viewname($n)]
4323        }
4324        if {$files ne $viewfiles($n) || $newargs ne $viewargs($n) || \
4325                $newviewopts($n,cmd) ne $viewargscmd($n)} {
4326            set viewfiles($n) $files
4327            set viewargs($n) $newargs
4328            set viewargscmd($n) $newviewopts($n,cmd)
4329            if {$curview == $n} {
4330                run reloadcommits
4331            }
4332        }
4333    }
4334    if {$apply} return
4335    catch {destroy $top}
4336}
4337
4338proc delview {} {
4339    global curview viewperm hlview selectedhlview
4340
4341    if {$curview == 0} return
4342    if {[info exists hlview] && $hlview == $curview} {
4343        set selectedhlview [mc "None"]
4344        unset hlview
4345    }
4346    allviewmenus $curview delete
4347    set viewperm($curview) 0
4348    showview 0
4349}
4350
4351proc addviewmenu {n} {
4352    global viewname viewhlmenu
4353
4354    .bar.view add radiobutton -label $viewname($n) \
4355        -command [list showview $n] -variable selectedview -value $n
4356    #$viewhlmenu add radiobutton -label $viewname($n) \
4357    #   -command [list addvhighlight $n] -variable selectedhlview
4358}
4359
4360proc showview {n} {
4361    global curview cached_commitrow ordertok
4362    global displayorder parentlist rowidlist rowisopt rowfinal
4363    global colormap rowtextx nextcolor canvxmax
4364    global numcommits viewcomplete
4365    global selectedline currentid canv canvy0
4366    global treediffs
4367    global pending_select mainheadid
4368    global commitidx
4369    global selectedview
4370    global hlview selectedhlview commitinterest
4371
4372    if {$n == $curview} return
4373    set selid {}
4374    set ymax [lindex [$canv cget -scrollregion] 3]
4375    set span [$canv yview]
4376    set ytop [expr {[lindex $span 0] * $ymax}]
4377    set ybot [expr {[lindex $span 1] * $ymax}]
4378    set yscreen [expr {($ybot - $ytop) / 2}]
4379    if {$selectedline ne {}} {
4380        set selid $currentid
4381        set y [yc $selectedline]
4382        if {$ytop < $y && $y < $ybot} {
4383            set yscreen [expr {$y - $ytop}]
4384        }
4385    } elseif {[info exists pending_select]} {
4386        set selid $pending_select
4387        unset pending_select
4388    }
4389    unselectline
4390    normalline
4391    catch {unset treediffs}
4392    clear_display
4393    if {[info exists hlview] && $hlview == $n} {
4394        unset hlview
4395        set selectedhlview [mc "None"]
4396    }
4397    catch {unset commitinterest}
4398    catch {unset cached_commitrow}
4399    catch {unset ordertok}
4400
4401    set curview $n
4402    set selectedview $n
4403    .bar.view entryconf [mca "Edit view..."] -state [expr {$n == 0? "disabled": "normal"}]
4404    .bar.view entryconf [mca "Delete view"] -state [expr {$n == 0? "disabled": "normal"}]
4405
4406    run refill_reflist
4407    if {![info exists viewcomplete($n)]} {
4408        getcommits $selid
4409        return
4410    }
4411
4412    set displayorder {}
4413    set parentlist {}
4414    set rowidlist {}
4415    set rowisopt {}
4416    set rowfinal {}
4417    set numcommits $commitidx($n)
4418
4419    catch {unset colormap}
4420    catch {unset rowtextx}
4421    set nextcolor 0
4422    set canvxmax [$canv cget -width]
4423    set curview $n
4424    set row 0
4425    setcanvscroll
4426    set yf 0
4427    set row {}
4428    if {$selid ne {} && [commitinview $selid $n]} {
4429        set row [rowofcommit $selid]
4430        # try to get the selected row in the same position on the screen
4431        set ymax [lindex [$canv cget -scrollregion] 3]
4432        set ytop [expr {[yc $row] - $yscreen}]
4433        if {$ytop < 0} {
4434            set ytop 0
4435        }
4436        set yf [expr {$ytop * 1.0 / $ymax}]
4437    }
4438    allcanvs yview moveto $yf
4439    drawvisible
4440    if {$row ne {}} {
4441        selectline $row 0
4442    } elseif {!$viewcomplete($n)} {
4443        reset_pending_select $selid
4444    } else {
4445        reset_pending_select {}
4446
4447        if {[commitinview $pending_select $curview]} {
4448            selectline [rowofcommit $pending_select] 1
4449        } else {
4450            set row [first_real_row]
4451            if {$row < $numcommits} {
4452                selectline $row 0
4453            }
4454        }
4455    }
4456    if {!$viewcomplete($n)} {
4457        if {$numcommits == 0} {
4458            show_status [mc "Reading commits..."]
4459        }
4460    } elseif {$numcommits == 0} {
4461        show_status [mc "No commits selected"]
4462    }
4463}
4464
4465# Stuff relating to the highlighting facility
4466
4467proc ishighlighted {id} {
4468    global vhighlights fhighlights nhighlights rhighlights
4469
4470    if {[info exists nhighlights($id)] && $nhighlights($id) > 0} {
4471        return $nhighlights($id)
4472    }
4473    if {[info exists vhighlights($id)] && $vhighlights($id) > 0} {
4474        return $vhighlights($id)
4475    }
4476    if {[info exists fhighlights($id)] && $fhighlights($id) > 0} {
4477        return $fhighlights($id)
4478    }
4479    if {[info exists rhighlights($id)] && $rhighlights($id) > 0} {
4480        return $rhighlights($id)
4481    }
4482    return 0
4483}
4484
4485proc bolden {id font} {
4486    global canv linehtag currentid boldids need_redisplay markedid
4487
4488    # need_redisplay = 1 means the display is stale and about to be redrawn
4489    if {$need_redisplay} return
4490    lappend boldids $id
4491    $canv itemconf $linehtag($id) -font $font
4492    if {[info exists currentid] && $id eq $currentid} {
4493        $canv delete secsel
4494        set t [eval $canv create rect [$canv bbox $linehtag($id)] \
4495                   -outline {{}} -tags secsel \
4496                   -fill [$canv cget -selectbackground]]
4497        $canv lower $t
4498    }
4499    if {[info exists markedid] && $id eq $markedid} {
4500        make_idmark $id
4501    }
4502}
4503
4504proc bolden_name {id font} {
4505    global canv2 linentag currentid boldnameids need_redisplay
4506
4507    if {$need_redisplay} return
4508    lappend boldnameids $id
4509    $canv2 itemconf $linentag($id) -font $font
4510    if {[info exists currentid] && $id eq $currentid} {
4511        $canv2 delete secsel
4512        set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] \
4513                   -outline {{}} -tags secsel \
4514                   -fill [$canv2 cget -selectbackground]]
4515        $canv2 lower $t
4516    }
4517}
4518
4519proc unbolden {} {
4520    global boldids
4521
4522    set stillbold {}
4523    foreach id $boldids {
4524        if {![ishighlighted $id]} {
4525            bolden $id mainfont
4526        } else {
4527            lappend stillbold $id
4528        }
4529    }
4530    set boldids $stillbold
4531}
4532
4533proc addvhighlight {n} {
4534    global hlview viewcomplete curview vhl_done commitidx
4535
4536    if {[info exists hlview]} {
4537        delvhighlight
4538    }
4539    set hlview $n
4540    if {$n != $curview && ![info exists viewcomplete($n)]} {
4541        start_rev_list $n
4542    }
4543    set vhl_done $commitidx($hlview)
4544    if {$vhl_done > 0} {
4545        drawvisible
4546    }
4547}
4548
4549proc delvhighlight {} {
4550    global hlview vhighlights
4551
4552    if {![info exists hlview]} return
4553    unset hlview
4554    catch {unset vhighlights}
4555    unbolden
4556}
4557
4558proc vhighlightmore {} {
4559    global hlview vhl_done commitidx vhighlights curview
4560
4561    set max $commitidx($hlview)
4562    set vr [visiblerows]
4563    set r0 [lindex $vr 0]
4564    set r1 [lindex $vr 1]
4565    for {set i $vhl_done} {$i < $max} {incr i} {
4566        set id [commitonrow $i $hlview]
4567        if {[commitinview $id $curview]} {
4568            set row [rowofcommit $id]
4569            if {$r0 <= $row && $row <= $r1} {
4570                if {![highlighted $row]} {
4571                    bolden $id mainfontbold
4572                }
4573                set vhighlights($id) 1
4574            }
4575        }
4576    }
4577    set vhl_done $max
4578    return 0
4579}
4580
4581proc askvhighlight {row id} {
4582    global hlview vhighlights iddrawn
4583
4584    if {[commitinview $id $hlview]} {
4585        if {[info exists iddrawn($id)] && ![ishighlighted $id]} {
4586            bolden $id mainfontbold
4587        }
4588        set vhighlights($id) 1
4589    } else {
4590        set vhighlights($id) 0
4591    }
4592}
4593
4594proc hfiles_change {} {
4595    global highlight_files filehighlight fhighlights fh_serial
4596    global highlight_paths
4597
4598    if {[info exists filehighlight]} {
4599        # delete previous highlights
4600        catch {close $filehighlight}
4601        unset filehighlight
4602        catch {unset fhighlights}
4603        unbolden
4604        unhighlight_filelist
4605    }
4606    set highlight_paths {}
4607    after cancel do_file_hl $fh_serial
4608    incr fh_serial
4609    if {$highlight_files ne {}} {
4610        after 300 do_file_hl $fh_serial
4611    }
4612}
4613
4614proc gdttype_change {name ix op} {
4615    global gdttype highlight_files findstring findpattern
4616
4617    stopfinding
4618    if {$findstring ne {}} {
4619        if {$gdttype eq [mc "containing:"]} {
4620            if {$highlight_files ne {}} {
4621                set highlight_files {}
4622                hfiles_change
4623            }
4624            findcom_change
4625        } else {
4626            if {$findpattern ne {}} {
4627                set findpattern {}
4628                findcom_change
4629            }
4630            set highlight_files $findstring
4631            hfiles_change
4632        }
4633        drawvisible
4634    }
4635    # enable/disable findtype/findloc menus too
4636}
4637
4638proc find_change {name ix op} {
4639    global gdttype findstring highlight_files
4640
4641    stopfinding
4642    if {$gdttype eq [mc "containing:"]} {
4643        findcom_change
4644    } else {
4645        if {$highlight_files ne $findstring} {
4646            set highlight_files $findstring
4647            hfiles_change
4648        }
4649    }
4650    drawvisible
4651}
4652
4653proc findcom_change args {
4654    global nhighlights boldnameids
4655    global findpattern findtype findstring gdttype
4656
4657    stopfinding
4658    # delete previous highlights, if any
4659    foreach id $boldnameids {
4660        bolden_name $id mainfont
4661    }
4662    set boldnameids {}
4663    catch {unset nhighlights}
4664    unbolden
4665    unmarkmatches
4666    if {$gdttype ne [mc "containing:"] || $findstring eq {}} {
4667        set findpattern {}
4668    } elseif {$findtype eq [mc "Regexp"]} {
4669        set findpattern $findstring
4670    } else {
4671        set e [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} \
4672                   $findstring]
4673        set findpattern "*$e*"
4674    }
4675}
4676
4677proc makepatterns {l} {
4678    set ret {}
4679    foreach e $l {
4680        set ee [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} $e]
4681        if {[string index $ee end] eq "/"} {
4682            lappend ret "$ee*"
4683        } else {
4684            lappend ret $ee
4685            lappend ret "$ee/*"
4686        }
4687    }
4688    return $ret
4689}
4690
4691proc do_file_hl {serial} {
4692    global highlight_files filehighlight highlight_paths gdttype fhl_list
4693    global cdup findtype
4694
4695    if {$gdttype eq [mc "touching paths:"]} {
4696        # If "exact" match then convert backslashes to forward slashes.
4697        # Most useful to support Windows-flavoured file paths.
4698        if {$findtype eq [mc "Exact"]} {
4699            set highlight_files [string map {"\\" "/"} $highlight_files]
4700        }
4701        if {[catch {set paths [shellsplit $highlight_files]}]} return
4702        set highlight_paths [makepatterns $paths]
4703        highlight_filelist
4704        set relative_paths {}
4705        foreach path $paths {
4706            lappend relative_paths [file join $cdup $path]
4707        }
4708        set gdtargs [concat -- $relative_paths]
4709    } elseif {$gdttype eq [mc "adding/removing string:"]} {
4710        set gdtargs [list "-S$highlight_files"]
4711    } elseif {$gdttype eq [mc "changing lines matching:"]} {
4712        set gdtargs [list "-G$highlight_files"]
4713    } else {
4714        # must be "containing:", i.e. we're searching commit info
4715        return
4716    }
4717    set cmd [concat | git diff-tree -r -s --stdin $gdtargs]
4718    set filehighlight [open $cmd r+]
4719    fconfigure $filehighlight -blocking 0
4720    filerun $filehighlight readfhighlight
4721    set fhl_list {}
4722    drawvisible
4723    flushhighlights
4724}
4725
4726proc flushhighlights {} {
4727    global filehighlight fhl_list
4728
4729    if {[info exists filehighlight]} {
4730        lappend fhl_list {}
4731        puts $filehighlight ""
4732        flush $filehighlight
4733    }
4734}
4735
4736proc askfilehighlight {row id} {
4737    global filehighlight fhighlights fhl_list
4738
4739    lappend fhl_list $id
4740    set fhighlights($id) -1
4741    puts $filehighlight $id
4742}
4743
4744proc readfhighlight {} {
4745    global filehighlight fhighlights curview iddrawn
4746    global fhl_list find_dirn
4747
4748    if {![info exists filehighlight]} {
4749        return 0
4750    }
4751    set nr 0
4752    while {[incr nr] <= 100 && [gets $filehighlight line] >= 0} {
4753        set line [string trim $line]
4754        set i [lsearch -exact $fhl_list $line]
4755        if {$i < 0} continue
4756        for {set j 0} {$j < $i} {incr j} {
4757            set id [lindex $fhl_list $j]
4758            set fhighlights($id) 0
4759        }
4760        set fhl_list [lrange $fhl_list [expr {$i+1}] end]
4761        if {$line eq {}} continue
4762        if {![commitinview $line $curview]} continue
4763        if {[info exists iddrawn($line)] && ![ishighlighted $line]} {
4764            bolden $line mainfontbold
4765        }
4766        set fhighlights($line) 1
4767    }
4768    if {[eof $filehighlight]} {
4769        # strange...
4770        puts "oops, git diff-tree died"
4771        catch {close $filehighlight}
4772        unset filehighlight
4773        return 0
4774    }
4775    if {[info exists find_dirn]} {
4776        run findmore
4777    }
4778    return 1
4779}
4780
4781proc doesmatch {f} {
4782    global findtype findpattern
4783
4784    if {$findtype eq [mc "Regexp"]} {
4785        return [regexp $findpattern $f]
4786    } elseif {$findtype eq [mc "IgnCase"]} {
4787        return [string match -nocase $findpattern $f]
4788    } else {
4789        return [string match $findpattern $f]
4790    }
4791}
4792
4793proc askfindhighlight {row id} {
4794    global nhighlights commitinfo iddrawn
4795    global findloc
4796    global markingmatches
4797
4798    if {![info exists commitinfo($id)]} {
4799        getcommit $id
4800    }
4801    set info $commitinfo($id)
4802    set isbold 0
4803    set fldtypes [list [mc Headline] [mc Author] "" [mc Committer] "" [mc Comments]]
4804    foreach f $info ty $fldtypes {
4805        if {$ty eq ""} continue
4806        if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
4807            [doesmatch $f]} {
4808            if {$ty eq [mc "Author"]} {
4809                set isbold 2
4810                break
4811            }
4812            set isbold 1
4813        }
4814    }
4815    if {$isbold && [info exists iddrawn($id)]} {
4816        if {![ishighlighted $id]} {
4817            bolden $id mainfontbold
4818            if {$isbold > 1} {
4819                bolden_name $id mainfontbold
4820            }
4821        }
4822        if {$markingmatches} {
4823            markrowmatches $row $id
4824        }
4825    }
4826    set nhighlights($id) $isbold
4827}
4828
4829proc markrowmatches {row id} {
4830    global canv canv2 linehtag linentag commitinfo findloc
4831
4832    set headline [lindex $commitinfo($id) 0]
4833    set author [lindex $commitinfo($id) 1]
4834    $canv delete match$row
4835    $canv2 delete match$row
4836    if {$findloc eq [mc "All fields"] || $findloc eq [mc "Headline"]} {
4837        set m [findmatches $headline]
4838        if {$m ne {}} {
4839            markmatches $canv $row $headline $linehtag($id) $m \
4840                [$canv itemcget $linehtag($id) -font] $row
4841        }
4842    }
4843    if {$findloc eq [mc "All fields"] || $findloc eq [mc "Author"]} {
4844        set m [findmatches $author]
4845        if {$m ne {}} {
4846            markmatches $canv2 $row $author $linentag($id) $m \
4847                [$canv2 itemcget $linentag($id) -font] $row
4848        }
4849    }
4850}
4851
4852proc vrel_change {name ix op} {
4853    global highlight_related
4854
4855    rhighlight_none
4856    if {$highlight_related ne [mc "None"]} {
4857        run drawvisible
4858    }
4859}
4860
4861# prepare for testing whether commits are descendents or ancestors of a
4862proc rhighlight_sel {a} {
4863    global descendent desc_todo ancestor anc_todo
4864    global highlight_related
4865
4866    catch {unset descendent}
4867    set desc_todo [list $a]
4868    catch {unset ancestor}
4869    set anc_todo [list $a]
4870    if {$highlight_related ne [mc "None"]} {
4871        rhighlight_none
4872        run drawvisible
4873    }
4874}
4875
4876proc rhighlight_none {} {
4877    global rhighlights
4878
4879    catch {unset rhighlights}
4880    unbolden
4881}
4882
4883proc is_descendent {a} {
4884    global curview children descendent desc_todo
4885
4886    set v $curview
4887    set la [rowofcommit $a]
4888    set todo $desc_todo
4889    set leftover {}
4890    set done 0
4891    for {set i 0} {$i < [llength $todo]} {incr i} {
4892        set do [lindex $todo $i]
4893        if {[rowofcommit $do] < $la} {
4894            lappend leftover $do
4895            continue
4896        }
4897        foreach nk $children($v,$do) {
4898            if {![info exists descendent($nk)]} {
4899                set descendent($nk) 1
4900                lappend todo $nk
4901                if {$nk eq $a} {
4902                    set done 1
4903                }
4904            }
4905        }
4906        if {$done} {
4907            set desc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4908            return
4909        }
4910    }
4911    set descendent($a) 0
4912    set desc_todo $leftover
4913}
4914
4915proc is_ancestor {a} {
4916    global curview parents ancestor anc_todo
4917
4918    set v $curview
4919    set la [rowofcommit $a]
4920    set todo $anc_todo
4921    set leftover {}
4922    set done 0
4923    for {set i 0} {$i < [llength $todo]} {incr i} {
4924        set do [lindex $todo $i]
4925        if {![commitinview $do $v] || [rowofcommit $do] > $la} {
4926            lappend leftover $do
4927            continue
4928        }
4929        foreach np $parents($v,$do) {
4930            if {![info exists ancestor($np)]} {
4931                set ancestor($np) 1
4932                lappend todo $np
4933                if {$np eq $a} {
4934                    set done 1
4935                }
4936            }
4937        }
4938        if {$done} {
4939            set anc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4940            return
4941        }
4942    }
4943    set ancestor($a) 0
4944    set anc_todo $leftover
4945}
4946
4947proc askrelhighlight {row id} {
4948    global descendent highlight_related iddrawn rhighlights
4949    global selectedline ancestor
4950
4951    if {$selectedline eq {}} return
4952    set isbold 0
4953    if {$highlight_related eq [mc "Descendant"] ||
4954        $highlight_related eq [mc "Not descendant"]} {
4955        if {![info exists descendent($id)]} {
4956            is_descendent $id
4957        }
4958        if {$descendent($id) == ($highlight_related eq [mc "Descendant"])} {
4959            set isbold 1
4960        }
4961    } elseif {$highlight_related eq [mc "Ancestor"] ||
4962              $highlight_related eq [mc "Not ancestor"]} {
4963        if {![info exists ancestor($id)]} {
4964            is_ancestor $id
4965        }
4966        if {$ancestor($id) == ($highlight_related eq [mc "Ancestor"])} {
4967            set isbold 1
4968        }
4969    }
4970    if {[info exists iddrawn($id)]} {
4971        if {$isbold && ![ishighlighted $id]} {
4972            bolden $id mainfontbold
4973        }
4974    }
4975    set rhighlights($id) $isbold
4976}
4977
4978# Graph layout functions
4979
4980proc shortids {ids} {
4981    set res {}
4982    foreach id $ids {
4983        if {[llength $id] > 1} {
4984            lappend res [shortids $id]
4985        } elseif {[regexp {^[0-9a-f]{40}$} $id]} {
4986            lappend res [string range $id 0 7]
4987        } else {
4988            lappend res $id
4989        }
4990    }
4991    return $res
4992}
4993
4994proc ntimes {n o} {
4995    set ret {}
4996    set o [list $o]
4997    for {set mask 1} {$mask <= $n} {incr mask $mask} {
4998        if {($n & $mask) != 0} {
4999            set ret [concat $ret $o]
5000        }
5001        set o [concat $o $o]
5002    }
5003    return $ret
5004}
5005
5006proc ordertoken {id} {
5007    global ordertok curview varcid varcstart varctok curview parents children
5008    global nullid nullid2
5009
5010    if {[info exists ordertok($id)]} {
5011        return $ordertok($id)
5012    }
5013    set origid $id
5014    set todo {}
5015    while {1} {
5016        if {[info exists varcid($curview,$id)]} {
5017            set a $varcid($curview,$id)
5018            set p [lindex $varcstart($curview) $a]
5019        } else {
5020            set p [lindex $children($curview,$id) 0]
5021        }
5022        if {[info exists ordertok($p)]} {
5023            set tok $ordertok($p)
5024            break
5025        }
5026        set id [first_real_child $curview,$p]
5027        if {$id eq {}} {
5028            # it's a root
5029            set tok [lindex $varctok($curview) $varcid($curview,$p)]
5030            break
5031        }
5032        if {[llength $parents($curview,$id)] == 1} {
5033            lappend todo [list $p {}]
5034        } else {
5035            set j [lsearch -exact $parents($curview,$id) $p]
5036            if {$j < 0} {
5037                puts "oops didn't find [shortids $p] in parents of [shortids $id]"
5038            }
5039            lappend todo [list $p [strrep $j]]
5040        }
5041    }
5042    for {set i [llength $todo]} {[incr i -1] >= 0} {} {
5043        set p [lindex $todo $i 0]
5044        append tok [lindex $todo $i 1]
5045        set ordertok($p) $tok
5046    }
5047    set ordertok($origid) $tok
5048    return $tok
5049}
5050
5051# Work out where id should go in idlist so that order-token
5052# values increase from left to right
5053proc idcol {idlist id {i 0}} {
5054    set t [ordertoken $id]
5055    if {$i < 0} {
5056        set i 0
5057    }
5058    if {$i >= [llength $idlist] || $t < [ordertoken [lindex $idlist $i]]} {
5059        if {$i > [llength $idlist]} {
5060            set i [llength $idlist]
5061        }
5062        while {[incr i -1] >= 0 && $t < [ordertoken [lindex $idlist $i]]} {}
5063        incr i
5064    } else {
5065        if {$t > [ordertoken [lindex $idlist $i]]} {
5066            while {[incr i] < [llength $idlist] &&
5067                   $t >= [ordertoken [lindex $idlist $i]]} {}
5068        }
5069    }
5070    return $i
5071}
5072
5073proc initlayout {} {
5074    global rowidlist rowisopt rowfinal displayorder parentlist
5075    global numcommits canvxmax canv
5076    global nextcolor
5077    global colormap rowtextx
5078
5079    set numcommits 0
5080    set displayorder {}
5081    set parentlist {}
5082    set nextcolor 0
5083    set rowidlist {}
5084    set rowisopt {}
5085    set rowfinal {}
5086    set canvxmax [$canv cget -width]
5087    catch {unset colormap}
5088    catch {unset rowtextx}
5089    setcanvscroll
5090}
5091
5092proc setcanvscroll {} {
5093    global canv canv2 canv3 numcommits linespc canvxmax canvy0
5094    global lastscrollset lastscrollrows
5095
5096    set ymax [expr {$canvy0 + ($numcommits - 0.5) * $linespc + 2}]
5097    $canv conf -scrollregion [list 0 0 $canvxmax $ymax]
5098    $canv2 conf -scrollregion [list 0 0 0 $ymax]
5099    $canv3 conf -scrollregion [list 0 0 0 $ymax]
5100    set lastscrollset [clock clicks -milliseconds]
5101    set lastscrollrows $numcommits
5102}
5103
5104proc visiblerows {} {
5105    global canv numcommits linespc
5106
5107    set ymax [lindex [$canv cget -scrollregion] 3]
5108    if {$ymax eq {} || $ymax == 0} return
5109    set f [$canv yview]
5110    set y0 [expr {int([lindex $f 0] * $ymax)}]
5111    set r0 [expr {int(($y0 - 3) / $linespc) - 1}]
5112    if {$r0 < 0} {
5113        set r0 0
5114    }
5115    set y1 [expr {int([lindex $f 1] * $ymax)}]
5116    set r1 [expr {int(($y1 - 3) / $linespc) + 1}]
5117    if {$r1 >= $numcommits} {
5118        set r1 [expr {$numcommits - 1}]
5119    }
5120    return [list $r0 $r1]
5121}
5122
5123proc layoutmore {} {
5124    global commitidx viewcomplete curview
5125    global numcommits pending_select curview
5126    global lastscrollset lastscrollrows
5127
5128    if {$lastscrollrows < 100 || $viewcomplete($curview) ||
5129        [clock clicks -milliseconds] - $lastscrollset > 500} {
5130        setcanvscroll
5131    }
5132    if {[info exists pending_select] &&
5133        [commitinview $pending_select $curview]} {
5134        update
5135        selectline [rowofcommit $pending_select] 1
5136    }
5137    drawvisible
5138}
5139
5140# With path limiting, we mightn't get the actual HEAD commit,
5141# so ask git rev-list what is the first ancestor of HEAD that
5142# touches a file in the path limit.
5143proc get_viewmainhead {view} {
5144    global viewmainheadid vfilelimit viewinstances mainheadid
5145
5146    catch {
5147        set rfd [open [concat | git rev-list -1 $mainheadid \
5148                           -- $vfilelimit($view)] r]
5149        set j [reg_instance $rfd]
5150        lappend viewinstances($view) $j
5151        fconfigure $rfd -blocking 0
5152        filerun $rfd [list getviewhead $rfd $j $view]
5153        set viewmainheadid($curview) {}
5154    }
5155}
5156
5157# git rev-list should give us just 1 line to use as viewmainheadid($view)
5158proc getviewhead {fd inst view} {
5159    global viewmainheadid commfd curview viewinstances showlocalchanges
5160
5161    set id {}
5162    if {[gets $fd line] < 0} {
5163        if {![eof $fd]} {
5164            return 1
5165        }
5166    } elseif {[string length $line] == 40 && [string is xdigit $line]} {
5167        set id $line
5168    }
5169    set viewmainheadid($view) $id
5170    close $fd
5171    unset commfd($inst)
5172    set i [lsearch -exact $viewinstances($view) $inst]
5173    if {$i >= 0} {
5174        set viewinstances($view) [lreplace $viewinstances($view) $i $i]
5175    }
5176    if {$showlocalchanges && $id ne {} && $view == $curview} {
5177        doshowlocalchanges
5178    }
5179    return 0
5180}
5181
5182proc doshowlocalchanges {} {
5183    global curview viewmainheadid
5184
5185    if {$viewmainheadid($curview) eq {}} return
5186    if {[commitinview $viewmainheadid($curview) $curview]} {
5187        dodiffindex
5188    } else {
5189        interestedin $viewmainheadid($curview) dodiffindex
5190    }
5191}
5192
5193proc dohidelocalchanges {} {
5194    global nullid nullid2 lserial curview
5195
5196    if {[commitinview $nullid $curview]} {
5197        removefakerow $nullid
5198    }
5199    if {[commitinview $nullid2 $curview]} {
5200        removefakerow $nullid2
5201    }
5202    incr lserial
5203}
5204
5205# spawn off a process to do git diff-index --cached HEAD
5206proc dodiffindex {} {
5207    global lserial showlocalchanges vfilelimit curview
5208    global hasworktree
5209
5210    if {!$showlocalchanges || !$hasworktree} return
5211    incr lserial
5212    set cmd "|git diff-index --cached HEAD"
5213    if {$vfilelimit($curview) ne {}} {
5214        set cmd [concat $cmd -- $vfilelimit($curview)]
5215    }
5216    set fd [open $cmd r]
5217    fconfigure $fd -blocking 0
5218    set i [reg_instance $fd]
5219    filerun $fd [list readdiffindex $fd $lserial $i]
5220}
5221
5222proc readdiffindex {fd serial inst} {
5223    global viewmainheadid nullid nullid2 curview commitinfo commitdata lserial
5224    global vfilelimit
5225
5226    set isdiff 1
5227    if {[gets $fd line] < 0} {
5228        if {![eof $fd]} {
5229            return 1
5230        }
5231        set isdiff 0
5232    }
5233    # we only need to see one line and we don't really care what it says...
5234    stop_instance $inst
5235
5236    if {$serial != $lserial} {
5237        return 0
5238    }
5239
5240    # now see if there are any local changes not checked in to the index
5241    set cmd "|git diff-files"
5242    if {$vfilelimit($curview) ne {}} {
5243        set cmd [concat $cmd -- $vfilelimit($curview)]
5244    }
5245    set fd [open $cmd r]
5246    fconfigure $fd -blocking 0
5247    set i [reg_instance $fd]
5248    filerun $fd [list readdifffiles $fd $serial $i]
5249
5250    if {$isdiff && ![commitinview $nullid2 $curview]} {
5251        # add the line for the changes in the index to the graph
5252        set hl [mc "Local changes checked in to index but not committed"]
5253        set commitinfo($nullid2) [list  $hl {} {} {} {} "    $hl\n"]
5254        set commitdata($nullid2) "\n    $hl\n"
5255        if {[commitinview $nullid $curview]} {
5256            removefakerow $nullid
5257        }
5258        insertfakerow $nullid2 $viewmainheadid($curview)
5259    } elseif {!$isdiff && [commitinview $nullid2 $curview]} {
5260        if {[commitinview $nullid $curview]} {
5261            removefakerow $nullid
5262        }
5263        removefakerow $nullid2
5264    }
5265    return 0
5266}
5267
5268proc readdifffiles {fd serial inst} {
5269    global viewmainheadid nullid nullid2 curview
5270    global commitinfo commitdata lserial
5271
5272    set isdiff 1
5273    if {[gets $fd line] < 0} {
5274        if {![eof $fd]} {
5275            return 1
5276        }
5277        set isdiff 0
5278    }
5279    # we only need to see one line and we don't really care what it says...
5280    stop_instance $inst
5281
5282    if {$serial != $lserial} {
5283        return 0
5284    }
5285
5286    if {$isdiff && ![commitinview $nullid $curview]} {
5287        # add the line for the local diff to the graph
5288        set hl [mc "Local uncommitted changes, not checked in to index"]
5289        set commitinfo($nullid) [list  $hl {} {} {} {} "    $hl\n"]
5290        set commitdata($nullid) "\n    $hl\n"
5291        if {[commitinview $nullid2 $curview]} {
5292            set p $nullid2
5293        } else {
5294            set p $viewmainheadid($curview)
5295        }
5296        insertfakerow $nullid $p
5297    } elseif {!$isdiff && [commitinview $nullid $curview]} {
5298        removefakerow $nullid
5299    }
5300    return 0
5301}
5302
5303proc nextuse {id row} {
5304    global curview children
5305
5306    if {[info exists children($curview,$id)]} {
5307        foreach kid $children($curview,$id) {
5308            if {![commitinview $kid $curview]} {
5309                return -1
5310            }
5311            if {[rowofcommit $kid] > $row} {
5312                return [rowofcommit $kid]
5313            }
5314        }
5315    }
5316    if {[commitinview $id $curview]} {
5317        return [rowofcommit $id]
5318    }
5319    return -1
5320}
5321
5322proc prevuse {id row} {
5323    global curview children
5324
5325    set ret -1
5326    if {[info exists children($curview,$id)]} {
5327        foreach kid $children($curview,$id) {
5328            if {![commitinview $kid $curview]} break
5329            if {[rowofcommit $kid] < $row} {
5330                set ret [rowofcommit $kid]
5331            }
5332        }
5333    }
5334    return $ret
5335}
5336
5337proc make_idlist {row} {
5338    global displayorder parentlist uparrowlen downarrowlen mingaplen
5339    global commitidx curview children
5340
5341    set r [expr {$row - $mingaplen - $downarrowlen - 1}]
5342    if {$r < 0} {
5343        set r 0
5344    }
5345    set ra [expr {$row - $downarrowlen}]
5346    if {$ra < 0} {
5347        set ra 0
5348    }
5349    set rb [expr {$row + $uparrowlen}]
5350    if {$rb > $commitidx($curview)} {
5351        set rb $commitidx($curview)
5352    }
5353    make_disporder $r [expr {$rb + 1}]
5354    set ids {}
5355    for {} {$r < $ra} {incr r} {
5356        set nextid [lindex $displayorder [expr {$r + 1}]]
5357        foreach p [lindex $parentlist $r] {
5358            if {$p eq $nextid} continue
5359            set rn [nextuse $p $r]
5360            if {$rn >= $row &&
5361                $rn <= $r + $downarrowlen + $mingaplen + $uparrowlen} {
5362                lappend ids [list [ordertoken $p] $p]
5363            }
5364        }
5365    }
5366    for {} {$r < $row} {incr r} {
5367        set nextid [lindex $displayorder [expr {$r + 1}]]
5368        foreach p [lindex $parentlist $r] {
5369            if {$p eq $nextid} continue
5370            set rn [nextuse $p $r]
5371            if {$rn < 0 || $rn >= $row} {
5372                lappend ids [list [ordertoken $p] $p]
5373            }
5374        }
5375    }
5376    set id [lindex $displayorder $row]
5377    lappend ids [list [ordertoken $id] $id]
5378    while {$r < $rb} {
5379        foreach p [lindex $parentlist $r] {
5380            set firstkid [lindex $children($curview,$p) 0]
5381            if {[rowofcommit $firstkid] < $row} {
5382                lappend ids [list [ordertoken $p] $p]
5383            }
5384        }
5385        incr r
5386        set id [lindex $displayorder $r]
5387        if {$id ne {}} {
5388            set firstkid [lindex $children($curview,$id) 0]
5389            if {$firstkid ne {} && [rowofcommit $firstkid] < $row} {
5390                lappend ids [list [ordertoken $id] $id]
5391            }
5392        }
5393    }
5394    set idlist {}
5395    foreach idx [lsort -unique $ids] {
5396        lappend idlist [lindex $idx 1]
5397    }
5398    return $idlist
5399}
5400
5401proc rowsequal {a b} {
5402    while {[set i [lsearch -exact $a {}]] >= 0} {
5403        set a [lreplace $a $i $i]
5404    }
5405    while {[set i [lsearch -exact $b {}]] >= 0} {
5406        set b [lreplace $b $i $i]
5407    }
5408    return [expr {$a eq $b}]
5409}
5410
5411proc makeupline {id row rend col} {
5412    global rowidlist uparrowlen downarrowlen mingaplen
5413
5414    for {set r $rend} {1} {set r $rstart} {
5415        set rstart [prevuse $id $r]
5416        if {$rstart < 0} return
5417        if {$rstart < $row} break
5418    }
5419    if {$rstart + $uparrowlen + $mingaplen + $downarrowlen < $rend} {
5420        set rstart [expr {$rend - $uparrowlen - 1}]
5421    }
5422    for {set r $rstart} {[incr r] <= $row} {} {
5423        set idlist [lindex $rowidlist $r]
5424        if {$idlist ne {} && [lsearch -exact $idlist $id] < 0} {
5425            set col [idcol $idlist $id $col]
5426            lset rowidlist $r [linsert $idlist $col $id]
5427            changedrow $r
5428        }
5429    }
5430}
5431
5432proc layoutrows {row endrow} {
5433    global rowidlist rowisopt rowfinal displayorder
5434    global uparrowlen downarrowlen maxwidth mingaplen
5435    global children parentlist
5436    global commitidx viewcomplete curview
5437
5438    make_disporder [expr {$row - 1}] [expr {$endrow + $uparrowlen}]
5439    set idlist {}
5440    if {$row > 0} {
5441        set rm1 [expr {$row - 1}]
5442        foreach id [lindex $rowidlist $rm1] {
5443            if {$id ne {}} {
5444                lappend idlist $id
5445            }
5446        }
5447        set final [lindex $rowfinal $rm1]
5448    }
5449    for {} {$row < $endrow} {incr row} {
5450        set rm1 [expr {$row - 1}]
5451        if {$rm1 < 0 || $idlist eq {}} {
5452            set idlist [make_idlist $row]
5453            set final 1
5454        } else {
5455            set id [lindex $displayorder $rm1]
5456            set col [lsearch -exact $idlist $id]
5457            set idlist [lreplace $idlist $col $col]
5458            foreach p [lindex $parentlist $rm1] {
5459                if {[lsearch -exact $idlist $p] < 0} {
5460                    set col [idcol $idlist $p $col]
5461                    set idlist [linsert $idlist $col $p]
5462                    # if not the first child, we have to insert a line going up
5463                    if {$id ne [lindex $children($curview,$p) 0]} {
5464                        makeupline $p $rm1 $row $col
5465                    }
5466                }
5467            }
5468            set id [lindex $displayorder $row]
5469            if {$row > $downarrowlen} {
5470                set termrow [expr {$row - $downarrowlen - 1}]
5471                foreach p [lindex $parentlist $termrow] {
5472                    set i [lsearch -exact $idlist $p]
5473                    if {$i < 0} continue
5474                    set nr [nextuse $p $termrow]
5475                    if {$nr < 0 || $nr >= $row + $mingaplen + $uparrowlen} {
5476                        set idlist [lreplace $idlist $i $i]
5477                    }
5478                }
5479            }
5480            set col [lsearch -exact $idlist $id]
5481            if {$col < 0} {
5482                set col [idcol $idlist $id]
5483                set idlist [linsert $idlist $col $id]
5484                if {$children($curview,$id) ne {}} {
5485                    makeupline $id $rm1 $row $col
5486                }
5487            }
5488            set r [expr {$row + $uparrowlen - 1}]
5489            if {$r < $commitidx($curview)} {
5490                set x $col
5491                foreach p [lindex $parentlist $r] {
5492                    if {[lsearch -exact $idlist $p] >= 0} continue
5493                    set fk [lindex $children($curview,$p) 0]
5494                    if {[rowofcommit $fk] < $row} {
5495                        set x [idcol $idlist $p $x]
5496                        set idlist [linsert $idlist $x $p]
5497                    }
5498                }
5499                if {[incr r] < $commitidx($curview)} {
5500                    set p [lindex $displayorder $r]
5501                    if {[lsearch -exact $idlist $p] < 0} {
5502                        set fk [lindex $children($curview,$p) 0]
5503                        if {$fk ne {} && [rowofcommit $fk] < $row} {
5504                            set x [idcol $idlist $p $x]
5505                            set idlist [linsert $idlist $x $p]
5506                        }
5507                    }
5508                }
5509            }
5510        }
5511        if {$final && !$viewcomplete($curview) &&
5512            $row + $uparrowlen + $mingaplen + $downarrowlen
5513                >= $commitidx($curview)} {
5514            set final 0
5515        }
5516        set l [llength $rowidlist]
5517        if {$row == $l} {
5518            lappend rowidlist $idlist
5519            lappend rowisopt 0
5520            lappend rowfinal $final
5521        } elseif {$row < $l} {
5522            if {![rowsequal $idlist [lindex $rowidlist $row]]} {
5523                lset rowidlist $row $idlist
5524                changedrow $row
5525            }
5526            lset rowfinal $row $final
5527        } else {
5528            set pad [ntimes [expr {$row - $l}] {}]
5529            set rowidlist [concat $rowidlist $pad]
5530            lappend rowidlist $idlist
5531            set rowfinal [concat $rowfinal $pad]
5532            lappend rowfinal $final
5533            set rowisopt [concat $rowisopt [ntimes [expr {$row - $l + 1}] 0]]
5534        }
5535    }
5536    return $row
5537}
5538
5539proc changedrow {row} {
5540    global displayorder iddrawn rowisopt need_redisplay
5541
5542    set l [llength $rowisopt]
5543    if {$row < $l} {
5544        lset rowisopt $row 0
5545        if {$row + 1 < $l} {
5546            lset rowisopt [expr {$row + 1}] 0
5547            if {$row + 2 < $l} {
5548                lset rowisopt [expr {$row + 2}] 0
5549            }
5550        }
5551    }
5552    set id [lindex $displayorder $row]
5553    if {[info exists iddrawn($id)]} {
5554        set need_redisplay 1
5555    }
5556}
5557
5558proc insert_pad {row col npad} {
5559    global rowidlist
5560
5561    set pad [ntimes $npad {}]
5562    set idlist [lindex $rowidlist $row]
5563    set bef [lrange $idlist 0 [expr {$col - 1}]]
5564    set aft [lrange $idlist $col end]
5565    set i [lsearch -exact $aft {}]
5566    if {$i > 0} {
5567        set aft [lreplace $aft $i $i]
5568    }
5569    lset rowidlist $row [concat $bef $pad $aft]
5570    changedrow $row
5571}
5572
5573proc optimize_rows {row col endrow} {
5574    global rowidlist rowisopt displayorder curview children
5575
5576    if {$row < 1} {
5577        set row 1
5578    }
5579    for {} {$row < $endrow} {incr row; set col 0} {
5580        if {[lindex $rowisopt $row]} continue
5581        set haspad 0
5582        set y0 [expr {$row - 1}]
5583        set ym [expr {$row - 2}]
5584        set idlist [lindex $rowidlist $row]
5585        set previdlist [lindex $rowidlist $y0]
5586        if {$idlist eq {} || $previdlist eq {}} continue
5587        if {$ym >= 0} {
5588            set pprevidlist [lindex $rowidlist $ym]
5589            if {$pprevidlist eq {}} continue
5590        } else {
5591            set pprevidlist {}
5592        }
5593        set x0 -1
5594        set xm -1
5595        for {} {$col < [llength $idlist]} {incr col} {
5596            set id [lindex $idlist $col]
5597            if {[lindex $previdlist $col] eq $id} continue
5598            if {$id eq {}} {
5599                set haspad 1
5600                continue
5601            }
5602            set x0 [lsearch -exact $previdlist $id]
5603            if {$x0 < 0} continue
5604            set z [expr {$x0 - $col}]
5605            set isarrow 0
5606            set z0 {}
5607            if {$ym >= 0} {
5608                set xm [lsearch -exact $pprevidlist $id]
5609                if {$xm >= 0} {
5610                    set z0 [expr {$xm - $x0}]
5611                }
5612            }
5613            if {$z0 eq {}} {
5614                # if row y0 is the first child of $id then it's not an arrow
5615                if {[lindex $children($curview,$id) 0] ne
5616                    [lindex $displayorder $y0]} {
5617                    set isarrow 1
5618                }
5619            }
5620            if {!$isarrow && $id ne [lindex $displayorder $row] &&
5621                [lsearch -exact [lindex $rowidlist [expr {$row+1}]] $id] < 0} {
5622                set isarrow 1
5623            }
5624            # Looking at lines from this row to the previous row,
5625            # make them go straight up if they end in an arrow on
5626            # the previous row; otherwise make them go straight up
5627            # or at 45 degrees.
5628            if {$z < -1 || ($z < 0 && $isarrow)} {
5629                # Line currently goes left too much;
5630                # insert pads in the previous row, then optimize it
5631                set npad [expr {-1 - $z + $isarrow}]
5632                insert_pad $y0 $x0 $npad
5633                if {$y0 > 0} {
5634                    optimize_rows $y0 $x0 $row
5635                }
5636                set previdlist [lindex $rowidlist $y0]
5637                set x0 [lsearch -exact $previdlist $id]
5638                set z [expr {$x0 - $col}]
5639                if {$z0 ne {}} {
5640                    set pprevidlist [lindex $rowidlist $ym]
5641                    set xm [lsearch -exact $pprevidlist $id]
5642                    set z0 [expr {$xm - $x0}]
5643                }
5644            } elseif {$z > 1 || ($z > 0 && $isarrow)} {
5645                # Line currently goes right too much;
5646                # insert pads in this line
5647                set npad [expr {$z - 1 + $isarrow}]
5648                insert_pad $row $col $npad
5649                set idlist [lindex $rowidlist $row]
5650                incr col $npad
5651                set z [expr {$x0 - $col}]
5652                set haspad 1
5653            }
5654            if {$z0 eq {} && !$isarrow && $ym >= 0} {
5655                # this line links to its first child on row $row-2
5656                set id [lindex $displayorder $ym]
5657                set xc [lsearch -exact $pprevidlist $id]
5658                if {$xc >= 0} {
5659                    set z0 [expr {$xc - $x0}]
5660                }
5661            }
5662            # avoid lines jigging left then immediately right
5663            if {$z0 ne {} && $z < 0 && $z0 > 0} {
5664                insert_pad $y0 $x0 1
5665                incr x0
5666                optimize_rows $y0 $x0 $row
5667                set previdlist [lindex $rowidlist $y0]
5668            }
5669        }
5670        if {!$haspad} {
5671            # Find the first column that doesn't have a line going right
5672            for {set col [llength $idlist]} {[incr col -1] >= 0} {} {
5673                set id [lindex $idlist $col]
5674                if {$id eq {}} break
5675                set x0 [lsearch -exact $previdlist $id]
5676                if {$x0 < 0} {
5677                    # check if this is the link to the first child
5678                    set kid [lindex $displayorder $y0]
5679                    if {[lindex $children($curview,$id) 0] eq $kid} {
5680                        # it is, work out offset to child
5681                        set x0 [lsearch -exact $previdlist $kid]
5682                    }
5683                }
5684                if {$x0 <= $col} break
5685            }
5686            # Insert a pad at that column as long as it has a line and
5687            # isn't the last column
5688            if {$x0 >= 0 && [incr col] < [llength $idlist]} {
5689                set idlist [linsert $idlist $col {}]
5690                lset rowidlist $row $idlist
5691                changedrow $row
5692            }
5693        }
5694    }
5695}
5696
5697proc xc {row col} {
5698    global canvx0 linespc
5699    return [expr {$canvx0 + $col * $linespc}]
5700}
5701
5702proc yc {row} {
5703    global canvy0 linespc
5704    return [expr {$canvy0 + $row * $linespc}]
5705}
5706
5707proc linewidth {id} {
5708    global thickerline lthickness
5709
5710    set wid $lthickness
5711    if {[info exists thickerline] && $id eq $thickerline} {
5712        set wid [expr {2 * $lthickness}]
5713    }
5714    return $wid
5715}
5716
5717proc rowranges {id} {
5718    global curview children uparrowlen downarrowlen
5719    global rowidlist
5720
5721    set kids $children($curview,$id)
5722    if {$kids eq {}} {
5723        return {}
5724    }
5725    set ret {}
5726    lappend kids $id
5727    foreach child $kids {
5728        if {![commitinview $child $curview]} break
5729        set row [rowofcommit $child]
5730        if {![info exists prev]} {
5731            lappend ret [expr {$row + 1}]
5732        } else {
5733            if {$row <= $prevrow} {
5734                puts "oops children of [shortids $id] out of order [shortids $child] $row <= [shortids $prev] $prevrow"
5735            }
5736            # see if the line extends the whole way from prevrow to row
5737            if {$row > $prevrow + $uparrowlen + $downarrowlen &&
5738                [lsearch -exact [lindex $rowidlist \
5739                            [expr {int(($row + $prevrow) / 2)}]] $id] < 0} {
5740                # it doesn't, see where it ends
5741                set r [expr {$prevrow + $downarrowlen}]
5742                if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5743                    while {[incr r -1] > $prevrow &&
5744                           [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5745                } else {
5746                    while {[incr r] <= $row &&
5747                           [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5748                    incr r -1
5749                }
5750                lappend ret $r
5751                # see where it starts up again
5752                set r [expr {$row - $uparrowlen}]
5753                if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5754                    while {[incr r] < $row &&
5755                           [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5756                } else {
5757                    while {[incr r -1] >= $prevrow &&
5758                           [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5759                    incr r
5760                }
5761                lappend ret $r
5762            }
5763        }
5764        if {$child eq $id} {
5765            lappend ret $row
5766        }
5767        set prev $child
5768        set prevrow $row
5769    }
5770    return $ret
5771}
5772
5773proc drawlineseg {id row endrow arrowlow} {
5774    global rowidlist displayorder iddrawn linesegs
5775    global canv colormap linespc curview maxlinelen parentlist
5776
5777    set cols [list [lsearch -exact [lindex $rowidlist $row] $id]]
5778    set le [expr {$row + 1}]
5779    set arrowhigh 1
5780    while {1} {
5781        set c [lsearch -exact [lindex $rowidlist $le] $id]
5782        if {$c < 0} {
5783            incr le -1
5784            break
5785        }
5786        lappend cols $c
5787        set x [lindex $displayorder $le]
5788        if {$x eq $id} {
5789            set arrowhigh 0
5790            break
5791        }
5792        if {[info exists iddrawn($x)] || $le == $endrow} {
5793            set c [lsearch -exact [lindex $rowidlist [expr {$le+1}]] $id]
5794            if {$c >= 0} {
5795                lappend cols $c
5796                set arrowhigh 0
5797            }
5798            break
5799        }
5800        incr le
5801    }
5802    if {$le <= $row} {
5803        return $row
5804    }
5805
5806    set lines {}
5807    set i 0
5808    set joinhigh 0
5809    if {[info exists linesegs($id)]} {
5810        set lines $linesegs($id)
5811        foreach li $lines {
5812            set r0 [lindex $li 0]
5813            if {$r0 > $row} {
5814                if {$r0 == $le && [lindex $li 1] - $row <= $maxlinelen} {
5815                    set joinhigh 1
5816                }
5817                break
5818            }
5819            incr i
5820        }
5821    }
5822    set joinlow 0
5823    if {$i > 0} {
5824        set li [lindex $lines [expr {$i-1}]]
5825        set r1 [lindex $li 1]
5826        if {$r1 == $row && $le - [lindex $li 0] <= $maxlinelen} {
5827            set joinlow 1
5828        }
5829    }
5830
5831    set x [lindex $cols [expr {$le - $row}]]
5832    set xp [lindex $cols [expr {$le - 1 - $row}]]
5833    set dir [expr {$xp - $x}]
5834    if {$joinhigh} {
5835        set ith [lindex $lines $i 2]
5836        set coords [$canv coords $ith]
5837        set ah [$canv itemcget $ith -arrow]
5838        set arrowhigh [expr {$ah eq "first" || $ah eq "both"}]
5839        set x2 [lindex $cols [expr {$le + 1 - $row}]]
5840        if {$x2 ne {} && $x - $x2 == $dir} {
5841            set coords [lrange $coords 0 end-2]
5842        }
5843    } else {
5844        set coords [list [xc $le $x] [yc $le]]
5845    }
5846    if {$joinlow} {
5847        set itl [lindex $lines [expr {$i-1}] 2]
5848        set al [$canv itemcget $itl -arrow]
5849        set arrowlow [expr {$al eq "last" || $al eq "both"}]
5850    } elseif {$arrowlow} {
5851        if {[lsearch -exact [lindex $rowidlist [expr {$row-1}]] $id] >= 0 ||
5852            [lsearch -exact [lindex $parentlist [expr {$row-1}]] $id] >= 0} {
5853            set arrowlow 0
5854        }
5855    }
5856    set arrow [lindex {none first last both} [expr {$arrowhigh + 2*$arrowlow}]]
5857    for {set y $le} {[incr y -1] > $row} {} {
5858        set x $xp
5859        set xp [lindex $cols [expr {$y - 1 - $row}]]
5860        set ndir [expr {$xp - $x}]
5861        if {$dir != $ndir || $xp < 0} {
5862            lappend coords [xc $y $x] [yc $y]
5863        }
5864        set dir $ndir
5865    }
5866    if {!$joinlow} {
5867        if {$xp < 0} {
5868            # join parent line to first child
5869            set ch [lindex $displayorder $row]
5870            set xc [lsearch -exact [lindex $rowidlist $row] $ch]
5871            if {$xc < 0} {
5872                puts "oops: drawlineseg: child $ch not on row $row"
5873            } elseif {$xc != $x} {
5874                if {($arrowhigh && $le == $row + 1) || $dir == 0} {
5875                    set d [expr {int(0.5 * $linespc)}]
5876                    set x1 [xc $row $x]
5877                    if {$xc < $x} {
5878                        set x2 [expr {$x1 - $d}]
5879                    } else {
5880                        set x2 [expr {$x1 + $d}]
5881                    }
5882                    set y2 [yc $row]
5883                    set y1 [expr {$y2 + $d}]
5884                    lappend coords $x1 $y1 $x2 $y2
5885                } elseif {$xc < $x - 1} {
5886                    lappend coords [xc $row [expr {$x-1}]] [yc $row]
5887                } elseif {$xc > $x + 1} {
5888                    lappend coords [xc $row [expr {$x+1}]] [yc $row]
5889                }
5890                set x $xc
5891            }
5892            lappend coords [xc $row $x] [yc $row]
5893        } else {
5894            set xn [xc $row $xp]
5895            set yn [yc $row]
5896            lappend coords $xn $yn
5897        }
5898        if {!$joinhigh} {
5899            assigncolor $id
5900            set t [$canv create line $coords -width [linewidth $id] \
5901                       -fill $colormap($id) -tags lines.$id -arrow $arrow]
5902            $canv lower $t
5903            bindline $t $id
5904            set lines [linsert $lines $i [list $row $le $t]]
5905        } else {
5906            $canv coords $ith $coords
5907            if {$arrow ne $ah} {
5908                $canv itemconf $ith -arrow $arrow
5909            }
5910            lset lines $i 0 $row
5911        }
5912    } else {
5913        set xo [lsearch -exact [lindex $rowidlist [expr {$row - 1}]] $id]
5914        set ndir [expr {$xo - $xp}]
5915        set clow [$canv coords $itl]
5916        if {$dir == $ndir} {
5917            set clow [lrange $clow 2 end]
5918        }
5919        set coords [concat $coords $clow]
5920        if {!$joinhigh} {
5921            lset lines [expr {$i-1}] 1 $le
5922        } else {
5923            # coalesce two pieces
5924            $canv delete $ith
5925            set b [lindex $lines [expr {$i-1}] 0]
5926            set e [lindex $lines $i 1]
5927            set lines [lreplace $lines [expr {$i-1}] $i [list $b $e $itl]]
5928        }
5929        $canv coords $itl $coords
5930        if {$arrow ne $al} {
5931            $canv itemconf $itl -arrow $arrow
5932        }
5933    }
5934
5935    set linesegs($id) $lines
5936    return $le
5937}
5938
5939proc drawparentlinks {id row} {
5940    global rowidlist canv colormap curview parentlist
5941    global idpos linespc
5942
5943    set rowids [lindex $rowidlist $row]
5944    set col [lsearch -exact $rowids $id]
5945    if {$col < 0} return
5946    set olds [lindex $parentlist $row]
5947    set row2 [expr {$row + 1}]
5948    set x [xc $row $col]
5949    set y [yc $row]
5950    set y2 [yc $row2]
5951    set d [expr {int(0.5 * $linespc)}]
5952    set ymid [expr {$y + $d}]
5953    set ids [lindex $rowidlist $row2]
5954    # rmx = right-most X coord used
5955    set rmx 0
5956    foreach p $olds {
5957        set i [lsearch -exact $ids $p]
5958        if {$i < 0} {
5959            puts "oops, parent $p of $id not in list"
5960            continue
5961        }
5962        set x2 [xc $row2 $i]
5963        if {$x2 > $rmx} {
5964            set rmx $x2
5965        }
5966        set j [lsearch -exact $rowids $p]
5967        if {$j < 0} {
5968            # drawlineseg will do this one for us
5969            continue
5970        }
5971        assigncolor $p
5972        # should handle duplicated parents here...
5973        set coords [list $x $y]
5974        if {$i != $col} {
5975            # if attaching to a vertical segment, draw a smaller
5976            # slant for visual distinctness
5977            if {$i == $j} {
5978                if {$i < $col} {
5979                    lappend coords [expr {$x2 + $d}] $y $x2 $ymid
5980                } else {
5981                    lappend coords [expr {$x2 - $d}] $y $x2 $ymid
5982                }
5983            } elseif {$i < $col && $i < $j} {
5984                # segment slants towards us already
5985                lappend coords [xc $row $j] $y
5986            } else {
5987                if {$i < $col - 1} {
5988                    lappend coords [expr {$x2 + $linespc}] $y
5989                } elseif {$i > $col + 1} {
5990                    lappend coords [expr {$x2 - $linespc}] $y
5991                }
5992                lappend coords $x2 $y2
5993            }
5994        } else {
5995            lappend coords $x2 $y2
5996        }
5997        set t [$canv create line $coords -width [linewidth $p] \
5998                   -fill $colormap($p) -tags lines.$p]
5999        $canv lower $t
6000        bindline $t $p
6001    }
6002    if {$rmx > [lindex $idpos($id) 1]} {
6003        lset idpos($id) 1 $rmx
6004        redrawtags $id
6005    }
6006}
6007
6008proc drawlines {id} {
6009    global canv
6010
6011    $canv itemconf lines.$id -width [linewidth $id]
6012}
6013
6014proc drawcmittext {id row col} {
6015    global linespc canv canv2 canv3 fgcolor curview
6016    global cmitlisted commitinfo rowidlist parentlist
6017    global rowtextx idpos idtags idheads idotherrefs
6018    global linehtag linentag linedtag selectedline
6019    global canvxmax boldids boldnameids fgcolor markedid
6020    global mainheadid nullid nullid2 circleitem circlecolors ctxbut
6021    global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
6022    global circleoutlinecolor
6023
6024    # listed is 0 for boundary, 1 for normal, 2 for negative, 3 for left, 4 for right
6025    set listed $cmitlisted($curview,$id)
6026    if {$id eq $nullid} {
6027        set ofill $workingfilescirclecolor
6028    } elseif {$id eq $nullid2} {
6029        set ofill $indexcirclecolor
6030    } elseif {$id eq $mainheadid} {
6031        set ofill $mainheadcirclecolor
6032    } else {
6033        set ofill [lindex $circlecolors $listed]
6034    }
6035    set x [xc $row $col]
6036    set y [yc $row]
6037    set orad [expr {$linespc / 3}]
6038    if {$listed <= 2} {
6039        set t [$canv create oval [expr {$x - $orad}] [expr {$y - $orad}] \
6040                   [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6041                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6042    } elseif {$listed == 3} {
6043        # triangle pointing left for left-side commits
6044        set t [$canv create polygon \
6045                   [expr {$x - $orad}] $y \
6046                   [expr {$x + $orad - 1}] [expr {$y - $orad}] \
6047                   [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6048                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6049    } else {
6050        # triangle pointing right for right-side commits
6051        set t [$canv create polygon \
6052                   [expr {$x + $orad - 1}] $y \
6053                   [expr {$x - $orad}] [expr {$y - $orad}] \
6054                   [expr {$x - $orad}] [expr {$y + $orad - 1}] \
6055                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6056    }
6057    set circleitem($row) $t
6058    $canv raise $t
6059    $canv bind $t <1> {selcanvline {} %x %y}
6060    set rmx [llength [lindex $rowidlist $row]]
6061    set olds [lindex $parentlist $row]
6062    if {$olds ne {}} {
6063        set nextids [lindex $rowidlist [expr {$row + 1}]]
6064        foreach p $olds {
6065            set i [lsearch -exact $nextids $p]
6066            if {$i > $rmx} {
6067                set rmx $i
6068            }
6069        }
6070    }
6071    set xt [xc $row $rmx]
6072    set rowtextx($row) $xt
6073    set idpos($id) [list $x $xt $y]
6074    if {[info exists idtags($id)] || [info exists idheads($id)]
6075        || [info exists idotherrefs($id)]} {
6076        set xt [drawtags $id $x $xt $y]
6077    }
6078    if {[lindex $commitinfo($id) 6] > 0} {
6079        set xt [drawnotesign $xt $y]
6080    }
6081    set headline [lindex $commitinfo($id) 0]
6082    set name [lindex $commitinfo($id) 1]
6083    set date [lindex $commitinfo($id) 2]
6084    set date [formatdate $date]
6085    set font mainfont
6086    set nfont mainfont
6087    set isbold [ishighlighted $id]
6088    if {$isbold > 0} {
6089        lappend boldids $id
6090        set font mainfontbold
6091        if {$isbold > 1} {
6092            lappend boldnameids $id
6093            set nfont mainfontbold
6094        }
6095    }
6096    set linehtag($id) [$canv create text $xt $y -anchor w -fill $fgcolor \
6097                           -text $headline -font $font -tags text]
6098    $canv bind $linehtag($id) $ctxbut "rowmenu %X %Y $id"
6099    set linentag($id) [$canv2 create text 3 $y -anchor w -fill $fgcolor \
6100                           -text $name -font $nfont -tags text]
6101    set linedtag($id) [$canv3 create text 3 $y -anchor w -fill $fgcolor \
6102                           -text $date -font mainfont -tags text]
6103    if {$selectedline == $row} {
6104        make_secsel $id
6105    }
6106    if {[info exists markedid] && $markedid eq $id} {
6107        make_idmark $id
6108    }
6109    set xr [expr {$xt + [font measure $font $headline]}]
6110    if {$xr > $canvxmax} {
6111        set canvxmax $xr
6112        setcanvscroll
6113    }
6114}
6115
6116proc drawcmitrow {row} {
6117    global displayorder rowidlist nrows_drawn
6118    global iddrawn markingmatches
6119    global commitinfo numcommits
6120    global filehighlight fhighlights findpattern nhighlights
6121    global hlview vhighlights
6122    global highlight_related rhighlights
6123
6124    if {$row >= $numcommits} return
6125
6126    set id [lindex $displayorder $row]
6127    if {[info exists hlview] && ![info exists vhighlights($id)]} {
6128        askvhighlight $row $id
6129    }
6130    if {[info exists filehighlight] && ![info exists fhighlights($id)]} {
6131        askfilehighlight $row $id
6132    }
6133    if {$findpattern ne {} && ![info exists nhighlights($id)]} {
6134        askfindhighlight $row $id
6135    }
6136    if {$highlight_related ne [mc "None"] && ![info exists rhighlights($id)]} {
6137        askrelhighlight $row $id
6138    }
6139    if {![info exists iddrawn($id)]} {
6140        set col [lsearch -exact [lindex $rowidlist $row] $id]
6141        if {$col < 0} {
6142            puts "oops, row $row id $id not in list"
6143            return
6144        }
6145        if {![info exists commitinfo($id)]} {
6146            getcommit $id
6147        }
6148        assigncolor $id
6149        drawcmittext $id $row $col
6150        set iddrawn($id) 1
6151        incr nrows_drawn
6152    }
6153    if {$markingmatches} {
6154        markrowmatches $row $id
6155    }
6156}
6157
6158proc drawcommits {row {endrow {}}} {
6159    global numcommits iddrawn displayorder curview need_redisplay
6160    global parentlist rowidlist rowfinal uparrowlen downarrowlen nrows_drawn
6161
6162    if {$row < 0} {
6163        set row 0
6164    }
6165    if {$endrow eq {}} {
6166        set endrow $row
6167    }
6168    if {$endrow >= $numcommits} {
6169        set endrow [expr {$numcommits - 1}]
6170    }
6171
6172    set rl1 [expr {$row - $downarrowlen - 3}]
6173    if {$rl1 < 0} {
6174        set rl1 0
6175    }
6176    set ro1 [expr {$row - 3}]
6177    if {$ro1 < 0} {
6178        set ro1 0
6179    }
6180    set r2 [expr {$endrow + $uparrowlen + 3}]
6181    if {$r2 > $numcommits} {
6182        set r2 $numcommits
6183    }
6184    for {set r $rl1} {$r < $r2} {incr r} {
6185        if {[lindex $rowidlist $r] ne {} && [lindex $rowfinal $r]} {
6186            if {$rl1 < $r} {
6187                layoutrows $rl1 $r
6188            }
6189            set rl1 [expr {$r + 1}]
6190        }
6191    }
6192    if {$rl1 < $r} {
6193        layoutrows $rl1 $r
6194    }
6195    optimize_rows $ro1 0 $r2
6196    if {$need_redisplay || $nrows_drawn > 2000} {
6197        clear_display
6198    }
6199
6200    # make the lines join to already-drawn rows either side
6201    set r [expr {$row - 1}]
6202    if {$r < 0 || ![info exists iddrawn([lindex $displayorder $r])]} {
6203        set r $row
6204    }
6205    set er [expr {$endrow + 1}]
6206    if {$er >= $numcommits ||
6207        ![info exists iddrawn([lindex $displayorder $er])]} {
6208        set er $endrow
6209    }
6210    for {} {$r <= $er} {incr r} {
6211        set id [lindex $displayorder $r]
6212        set wasdrawn [info exists iddrawn($id)]
6213        drawcmitrow $r
6214        if {$r == $er} break
6215        set nextid [lindex $displayorder [expr {$r + 1}]]
6216        if {$wasdrawn && [info exists iddrawn($nextid)]} continue
6217        drawparentlinks $id $r
6218
6219        set rowids [lindex $rowidlist $r]
6220        foreach lid $rowids {
6221            if {$lid eq {}} continue
6222            if {[info exists lineend($lid)] && $lineend($lid) > $r} continue
6223            if {$lid eq $id} {
6224                # see if this is the first child of any of its parents
6225                foreach p [lindex $parentlist $r] {
6226                    if {[lsearch -exact $rowids $p] < 0} {
6227                        # make this line extend up to the child
6228                        set lineend($p) [drawlineseg $p $r $er 0]
6229                    }
6230                }
6231            } else {
6232                set lineend($lid) [drawlineseg $lid $r $er 1]
6233            }
6234        }
6235    }
6236}
6237
6238proc undolayout {row} {
6239    global uparrowlen mingaplen downarrowlen
6240    global rowidlist rowisopt rowfinal need_redisplay
6241
6242    set r [expr {$row - ($uparrowlen + $mingaplen + $downarrowlen)}]
6243    if {$r < 0} {
6244        set r 0
6245    }
6246    if {[llength $rowidlist] > $r} {
6247        incr r -1
6248        set rowidlist [lrange $rowidlist 0 $r]
6249        set rowfinal [lrange $rowfinal 0 $r]
6250        set rowisopt [lrange $rowisopt 0 $r]
6251        set need_redisplay 1
6252        run drawvisible
6253    }
6254}
6255
6256proc drawvisible {} {
6257    global canv linespc curview vrowmod selectedline targetrow targetid
6258    global need_redisplay cscroll numcommits
6259
6260    set fs [$canv yview]
6261    set ymax [lindex [$canv cget -scrollregion] 3]
6262    if {$ymax eq {} || $ymax == 0 || $numcommits == 0} return
6263    set f0 [lindex $fs 0]
6264    set f1 [lindex $fs 1]
6265    set y0 [expr {int($f0 * $ymax)}]
6266    set y1 [expr {int($f1 * $ymax)}]
6267
6268    if {[info exists targetid]} {
6269        if {[commitinview $targetid $curview]} {
6270            set r [rowofcommit $targetid]
6271            if {$r != $targetrow} {
6272                # Fix up the scrollregion and change the scrolling position
6273                # now that our target row has moved.
6274                set diff [expr {($r - $targetrow) * $linespc}]
6275                set targetrow $r
6276                setcanvscroll
6277                set ymax [lindex [$canv cget -scrollregion] 3]
6278                incr y0 $diff
6279                incr y1 $diff
6280                set f0 [expr {$y0 / $ymax}]
6281                set f1 [expr {$y1 / $ymax}]
6282                allcanvs yview moveto $f0
6283                $cscroll set $f0 $f1
6284                set need_redisplay 1
6285            }
6286        } else {
6287            unset targetid
6288        }
6289    }
6290
6291    set row [expr {int(($y0 - 3) / $linespc) - 1}]
6292    set endrow [expr {int(($y1 - 3) / $linespc) + 1}]
6293    if {$endrow >= $vrowmod($curview)} {
6294        update_arcrows $curview
6295    }
6296    if {$selectedline ne {} &&
6297        $row <= $selectedline && $selectedline <= $endrow} {
6298        set targetrow $selectedline
6299    } elseif {[info exists targetid]} {
6300        set targetrow [expr {int(($row + $endrow) / 2)}]
6301    }
6302    if {[info exists targetrow]} {
6303        if {$targetrow >= $numcommits} {
6304            set targetrow [expr {$numcommits - 1}]
6305        }
6306        set targetid [commitonrow $targetrow]
6307    }
6308    drawcommits $row $endrow
6309}
6310
6311proc clear_display {} {
6312    global iddrawn linesegs need_redisplay nrows_drawn
6313    global vhighlights fhighlights nhighlights rhighlights
6314    global linehtag linentag linedtag boldids boldnameids
6315
6316    allcanvs delete all
6317    catch {unset iddrawn}
6318    catch {unset linesegs}
6319    catch {unset linehtag}
6320    catch {unset linentag}
6321    catch {unset linedtag}
6322    set boldids {}
6323    set boldnameids {}
6324    catch {unset vhighlights}
6325    catch {unset fhighlights}
6326    catch {unset nhighlights}
6327    catch {unset rhighlights}
6328    set need_redisplay 0
6329    set nrows_drawn 0
6330}
6331
6332proc findcrossings {id} {
6333    global rowidlist parentlist numcommits displayorder
6334
6335    set cross {}
6336    set ccross {}
6337    foreach {s e} [rowranges $id] {
6338        if {$e >= $numcommits} {
6339            set e [expr {$numcommits - 1}]
6340        }
6341        if {$e <= $s} continue
6342        for {set row $e} {[incr row -1] >= $s} {} {
6343            set x [lsearch -exact [lindex $rowidlist $row] $id]
6344            if {$x < 0} break
6345            set olds [lindex $parentlist $row]
6346            set kid [lindex $displayorder $row]
6347            set kidx [lsearch -exact [lindex $rowidlist $row] $kid]
6348            if {$kidx < 0} continue
6349            set nextrow [lindex $rowidlist [expr {$row + 1}]]
6350            foreach p $olds {
6351                set px [lsearch -exact $nextrow $p]
6352                if {$px < 0} continue
6353                if {($kidx < $x && $x < $px) || ($px < $x && $x < $kidx)} {
6354                    if {[lsearch -exact $ccross $p] >= 0} continue
6355                    if {$x == $px + ($kidx < $px? -1: 1)} {
6356                        lappend ccross $p
6357                    } elseif {[lsearch -exact $cross $p] < 0} {
6358                        lappend cross $p
6359                    }
6360                }
6361            }
6362        }
6363    }
6364    return [concat $ccross {{}} $cross]
6365}
6366
6367proc assigncolor {id} {
6368    global colormap colors nextcolor
6369    global parents children children curview
6370
6371    if {[info exists colormap($id)]} return
6372    set ncolors [llength $colors]
6373    if {[info exists children($curview,$id)]} {
6374        set kids $children($curview,$id)
6375    } else {
6376        set kids {}
6377    }
6378    if {[llength $kids] == 1} {
6379        set child [lindex $kids 0]
6380        if {[info exists colormap($child)]
6381            && [llength $parents($curview,$child)] == 1} {
6382            set colormap($id) $colormap($child)
6383            return
6384        }
6385    }
6386    set badcolors {}
6387    set origbad {}
6388    foreach x [findcrossings $id] {
6389        if {$x eq {}} {
6390            # delimiter between corner crossings and other crossings
6391            if {[llength $badcolors] >= $ncolors - 1} break
6392            set origbad $badcolors
6393        }
6394        if {[info exists colormap($x)]
6395            && [lsearch -exact $badcolors $colormap($x)] < 0} {
6396            lappend badcolors $colormap($x)
6397        }
6398    }
6399    if {[llength $badcolors] >= $ncolors} {
6400        set badcolors $origbad
6401    }
6402    set origbad $badcolors
6403    if {[llength $badcolors] < $ncolors - 1} {
6404        foreach child $kids {
6405            if {[info exists colormap($child)]
6406                && [lsearch -exact $badcolors $colormap($child)] < 0} {
6407                lappend badcolors $colormap($child)
6408            }
6409            foreach p $parents($curview,$child) {
6410                if {[info exists colormap($p)]
6411                    && [lsearch -exact $badcolors $colormap($p)] < 0} {
6412                    lappend badcolors $colormap($p)
6413                }
6414            }
6415        }
6416        if {[llength $badcolors] >= $ncolors} {
6417            set badcolors $origbad
6418        }
6419    }
6420    for {set i 0} {$i <= $ncolors} {incr i} {
6421        set c [lindex $colors $nextcolor]
6422        if {[incr nextcolor] >= $ncolors} {
6423            set nextcolor 0
6424        }
6425        if {[lsearch -exact $badcolors $c]} break
6426    }
6427    set colormap($id) $c
6428}
6429
6430proc bindline {t id} {
6431    global canv
6432
6433    $canv bind $t <Enter> "lineenter %x %y $id"
6434    $canv bind $t <Motion> "linemotion %x %y $id"
6435    $canv bind $t <Leave> "lineleave $id"
6436    $canv bind $t <Button-1> "lineclick %x %y $id 1"
6437}
6438
6439proc graph_pane_width {} {
6440    global use_ttk
6441
6442    if {$use_ttk} {
6443        set g [.tf.histframe.pwclist sashpos 0]
6444    } else {
6445        set g [.tf.histframe.pwclist sash coord 0]
6446    }
6447    return [lindex $g 0]
6448}
6449
6450proc totalwidth {l font extra} {
6451    set tot 0
6452    foreach str $l {
6453        set tot [expr {$tot + [font measure $font $str] + $extra}]
6454    }
6455    return $tot
6456}
6457
6458proc drawtags {id x xt y1} {
6459    global idtags idheads idotherrefs mainhead
6460    global linespc lthickness
6461    global canv rowtextx curview fgcolor bgcolor ctxbut
6462    global headbgcolor headfgcolor headoutlinecolor remotebgcolor
6463    global tagbgcolor tagfgcolor tagoutlinecolor
6464    global reflinecolor
6465
6466    set marks {}
6467    set ntags 0
6468    set nheads 0
6469    set singletag 0
6470    set maxtags 3
6471    set maxtagpct 25
6472    set maxwidth [expr {[graph_pane_width] * $maxtagpct / 100}]
6473    set delta [expr {int(0.5 * ($linespc - $lthickness))}]
6474    set extra [expr {$delta + $lthickness + $linespc}]
6475
6476    if {[info exists idtags($id)]} {
6477        set marks $idtags($id)
6478        set ntags [llength $marks]
6479        if {$ntags > $maxtags ||
6480            [totalwidth $marks mainfont $extra] > $maxwidth} {
6481            # show just a single "n tags..." tag
6482            set singletag 1
6483            if {$ntags == 1} {
6484                set marks [list "tag..."]
6485            } else {
6486                set marks [list [format "%d tags..." $ntags]]
6487            }
6488            set ntags 1
6489        }
6490    }
6491    if {[info exists idheads($id)]} {
6492        set marks [concat $marks $idheads($id)]
6493        set nheads [llength $idheads($id)]
6494    }
6495    if {[info exists idotherrefs($id)]} {
6496        set marks [concat $marks $idotherrefs($id)]
6497    }
6498    if {$marks eq {}} {
6499        return $xt
6500    }
6501
6502    set yt [expr {$y1 - 0.5 * $linespc}]
6503    set yb [expr {$yt + $linespc - 1}]
6504    set xvals {}
6505    set wvals {}
6506    set i -1
6507    foreach tag $marks {
6508        incr i
6509        if {$i >= $ntags && $i < $ntags + $nheads && $tag eq $mainhead} {
6510            set wid [font measure mainfontbold $tag]
6511        } else {
6512            set wid [font measure mainfont $tag]
6513        }
6514        lappend xvals $xt
6515        lappend wvals $wid
6516        set xt [expr {$xt + $wid + $extra}]
6517    }
6518    set t [$canv create line $x $y1 [lindex $xvals end] $y1 \
6519               -width $lthickness -fill $reflinecolor -tags tag.$id]
6520    $canv lower $t
6521    foreach tag $marks x $xvals wid $wvals {
6522        set tag_quoted [string map {% %%} $tag]
6523        set xl [expr {$x + $delta}]
6524        set xr [expr {$x + $delta + $wid + $lthickness}]
6525        set font mainfont
6526        if {[incr ntags -1] >= 0} {
6527            # draw a tag
6528            set t [$canv create polygon $x [expr {$yt + $delta}] $xl $yt \
6529                       $xr $yt $xr $yb $xl $yb $x [expr {$yb - $delta}] \
6530                       -width 1 -outline $tagoutlinecolor -fill $tagbgcolor \
6531                       -tags tag.$id]
6532            if {$singletag} {
6533                set tagclick [list showtags $id 1]
6534            } else {
6535                set tagclick [list showtag $tag_quoted 1]
6536            }
6537            $canv bind $t <1> $tagclick
6538            set rowtextx([rowofcommit $id]) [expr {$xr + $linespc}]
6539        } else {
6540            # draw a head or other ref
6541            if {[incr nheads -1] >= 0} {
6542                set col $headbgcolor
6543                if {$tag eq $mainhead} {
6544                    set font mainfontbold
6545                }
6546            } else {
6547                set col "#ddddff"
6548            }
6549            set xl [expr {$xl - $delta/2}]
6550            $canv create polygon $x $yt $xr $yt $xr $yb $x $yb \
6551                -width 1 -outline black -fill $col -tags tag.$id
6552            if {[regexp {^(remotes/.*/|remotes/)} $tag match remoteprefix]} {
6553                set rwid [font measure mainfont $remoteprefix]
6554                set xi [expr {$x + 1}]
6555                set yti [expr {$yt + 1}]
6556                set xri [expr {$x + $rwid}]
6557                $canv create polygon $xi $yti $xri $yti $xri $yb $xi $yb \
6558                        -width 0 -fill $remotebgcolor -tags tag.$id
6559            }
6560        }
6561        set t [$canv create text $xl $y1 -anchor w -text $tag -fill $headfgcolor \
6562                   -font $font -tags [list tag.$id text]]
6563        if {$ntags >= 0} {
6564            $canv bind $t <1> $tagclick
6565        } elseif {$nheads >= 0} {
6566            $canv bind $t $ctxbut [list headmenu %X %Y $id $tag_quoted]
6567        }
6568    }
6569    return $xt
6570}
6571
6572proc drawnotesign {xt y} {
6573    global linespc canv fgcolor
6574
6575    set orad [expr {$linespc / 3}]
6576    set t [$canv create rectangle [expr {$xt - $orad}] [expr {$y - $orad}] \
6577               [expr {$xt + $orad - 1}] [expr {$y + $orad - 1}] \
6578               -fill yellow -outline $fgcolor -width 1 -tags circle]
6579    set xt [expr {$xt + $orad * 3}]
6580    return $xt
6581}
6582
6583proc xcoord {i level ln} {
6584    global canvx0 xspc1 xspc2
6585
6586    set x [expr {$canvx0 + $i * $xspc1($ln)}]
6587    if {$i > 0 && $i == $level} {
6588        set x [expr {$x + 0.5 * ($xspc2 - $xspc1($ln))}]
6589    } elseif {$i > $level} {
6590        set x [expr {$x + $xspc2 - $xspc1($ln)}]
6591    }
6592    return $x
6593}
6594
6595proc show_status {msg} {
6596    global canv fgcolor
6597
6598    clear_display
6599    $canv create text 3 3 -anchor nw -text $msg -font mainfont \
6600        -tags text -fill $fgcolor
6601}
6602
6603# Don't change the text pane cursor if it is currently the hand cursor,
6604# showing that we are over a sha1 ID link.
6605proc settextcursor {c} {
6606    global ctext curtextcursor
6607
6608    if {[$ctext cget -cursor] == $curtextcursor} {
6609        $ctext config -cursor $c
6610    }
6611    set curtextcursor $c
6612}
6613
6614proc nowbusy {what {name {}}} {
6615    global isbusy busyname statusw
6616
6617    if {[array names isbusy] eq {}} {
6618        . config -cursor watch
6619        settextcursor watch
6620    }
6621    set isbusy($what) 1
6622    set busyname($what) $name
6623    if {$name ne {}} {
6624        $statusw conf -text $name
6625    }
6626}
6627
6628proc notbusy {what} {
6629    global isbusy maincursor textcursor busyname statusw
6630
6631    catch {
6632        unset isbusy($what)
6633        if {$busyname($what) ne {} &&
6634            [$statusw cget -text] eq $busyname($what)} {
6635            $statusw conf -text {}
6636        }
6637    }
6638    if {[array names isbusy] eq {}} {
6639        . config -cursor $maincursor
6640        settextcursor $textcursor
6641    }
6642}
6643
6644proc findmatches {f} {
6645    global findtype findstring
6646    if {$findtype == [mc "Regexp"]} {
6647        set matches [regexp -indices -all -inline $findstring $f]
6648    } else {
6649        set fs $findstring
6650        if {$findtype == [mc "IgnCase"]} {
6651            set f [string tolower $f]
6652            set fs [string tolower $fs]
6653        }
6654        set matches {}
6655        set i 0
6656        set l [string length $fs]
6657        while {[set j [string first $fs $f $i]] >= 0} {
6658            lappend matches [list $j [expr {$j+$l-1}]]
6659            set i [expr {$j + $l}]
6660        }
6661    }
6662    return $matches
6663}
6664
6665proc dofind {{dirn 1} {wrap 1}} {
6666    global findstring findstartline findcurline selectedline numcommits
6667    global gdttype filehighlight fh_serial find_dirn findallowwrap
6668
6669    if {[info exists find_dirn]} {
6670        if {$find_dirn == $dirn} return
6671        stopfinding
6672    }
6673    focus .
6674    if {$findstring eq {} || $numcommits == 0} return
6675    if {$selectedline eq {}} {
6676        set findstartline [lindex [visiblerows] [expr {$dirn < 0}]]
6677    } else {
6678        set findstartline $selectedline
6679    }
6680    set findcurline $findstartline
6681    nowbusy finding [mc "Searching"]
6682    if {$gdttype ne [mc "containing:"] && ![info exists filehighlight]} {
6683        after cancel do_file_hl $fh_serial
6684        do_file_hl $fh_serial
6685    }
6686    set find_dirn $dirn
6687    set findallowwrap $wrap
6688    run findmore
6689}
6690
6691proc stopfinding {} {
6692    global find_dirn findcurline fprogcoord
6693
6694    if {[info exists find_dirn]} {
6695        unset find_dirn
6696        unset findcurline
6697        notbusy finding
6698        set fprogcoord 0
6699        adjustprogress
6700    }
6701    stopblaming
6702}
6703
6704proc findmore {} {
6705    global commitdata commitinfo numcommits findpattern findloc
6706    global findstartline findcurline findallowwrap
6707    global find_dirn gdttype fhighlights fprogcoord
6708    global curview varcorder vrownum varccommits vrowmod
6709
6710    if {![info exists find_dirn]} {
6711        return 0
6712    }
6713    set fldtypes [list [mc "Headline"] [mc "Author"] "" [mc "Committer"] "" [mc "Comments"]]
6714    set l $findcurline
6715    set moretodo 0
6716    if {$find_dirn > 0} {
6717        incr l
6718        if {$l >= $numcommits} {
6719            set l 0
6720        }
6721        if {$l <= $findstartline} {
6722            set lim [expr {$findstartline + 1}]
6723        } else {
6724            set lim $numcommits
6725            set moretodo $findallowwrap
6726        }
6727    } else {
6728        if {$l == 0} {
6729            set l $numcommits
6730        }
6731        incr l -1
6732        if {$l >= $findstartline} {
6733            set lim [expr {$findstartline - 1}]
6734        } else {
6735            set lim -1
6736            set moretodo $findallowwrap
6737        }
6738    }
6739    set n [expr {($lim - $l) * $find_dirn}]
6740    if {$n > 500} {
6741        set n 500
6742        set moretodo 1
6743    }
6744    if {$l + ($find_dirn > 0? $n: 1) > $vrowmod($curview)} {
6745        update_arcrows $curview
6746    }
6747    set found 0
6748    set domore 1
6749    set ai [bsearch $vrownum($curview) $l]
6750    set a [lindex $varcorder($curview) $ai]
6751    set arow [lindex $vrownum($curview) $ai]
6752    set ids [lindex $varccommits($curview,$a)]
6753    set arowend [expr {$arow + [llength $ids]}]
6754    if {$gdttype eq [mc "containing:"]} {
6755        for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6756            if {$l < $arow || $l >= $arowend} {
6757                incr ai $find_dirn
6758                set a [lindex $varcorder($curview) $ai]
6759                set arow [lindex $vrownum($curview) $ai]
6760                set ids [lindex $varccommits($curview,$a)]
6761                set arowend [expr {$arow + [llength $ids]}]
6762            }
6763            set id [lindex $ids [expr {$l - $arow}]]
6764            # shouldn't happen unless git log doesn't give all the commits...
6765            if {![info exists commitdata($id)] ||
6766                ![doesmatch $commitdata($id)]} {
6767                continue
6768            }
6769            if {![info exists commitinfo($id)]} {
6770                getcommit $id
6771            }
6772            set info $commitinfo($id)
6773            foreach f $info ty $fldtypes {
6774                if {$ty eq ""} continue
6775                if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
6776                    [doesmatch $f]} {
6777                    set found 1
6778                    break
6779                }
6780            }
6781            if {$found} break
6782        }
6783    } else {
6784        for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6785            if {$l < $arow || $l >= $arowend} {
6786                incr ai $find_dirn
6787                set a [lindex $varcorder($curview) $ai]
6788                set arow [lindex $vrownum($curview) $ai]
6789                set ids [lindex $varccommits($curview,$a)]
6790                set arowend [expr {$arow + [llength $ids]}]
6791            }
6792            set id [lindex $ids [expr {$l - $arow}]]
6793            if {![info exists fhighlights($id)]} {
6794                # this sets fhighlights($id) to -1
6795                askfilehighlight $l $id
6796            }
6797            if {$fhighlights($id) > 0} {
6798                set found $domore
6799                break
6800            }
6801            if {$fhighlights($id) < 0} {
6802                if {$domore} {
6803                    set domore 0
6804                    set findcurline [expr {$l - $find_dirn}]
6805                }
6806            }
6807        }
6808    }
6809    if {$found || ($domore && !$moretodo)} {
6810        unset findcurline
6811        unset find_dirn
6812        notbusy finding
6813        set fprogcoord 0
6814        adjustprogress
6815        if {$found} {
6816            findselectline $l
6817        } else {
6818            bell
6819        }
6820        return 0
6821    }
6822    if {!$domore} {
6823        flushhighlights
6824    } else {
6825        set findcurline [expr {$l - $find_dirn}]
6826    }
6827    set n [expr {($findcurline - $findstartline) * $find_dirn - 1}]
6828    if {$n < 0} {
6829        incr n $numcommits
6830    }
6831    set fprogcoord [expr {$n * 1.0 / $numcommits}]
6832    adjustprogress
6833    return $domore
6834}
6835
6836proc findselectline {l} {
6837    global findloc commentend ctext findcurline markingmatches gdttype
6838
6839    set markingmatches [expr {$gdttype eq [mc "containing:"]}]
6840    set findcurline $l
6841    selectline $l 1
6842    if {$markingmatches &&
6843        ($findloc eq [mc "All fields"] || $findloc eq [mc "Comments"])} {
6844        # highlight the matches in the comments
6845        set f [$ctext get 1.0 $commentend]
6846        set matches [findmatches $f]
6847        foreach match $matches {
6848            set start [lindex $match 0]
6849            set end [expr {[lindex $match 1] + 1}]
6850            $ctext tag add found "1.0 + $start c" "1.0 + $end c"
6851        }
6852    }
6853    drawvisible
6854}
6855
6856# mark the bits of a headline or author that match a find string
6857proc markmatches {canv l str tag matches font row} {
6858    global selectedline
6859
6860    set bbox [$canv bbox $tag]
6861    set x0 [lindex $bbox 0]
6862    set y0 [lindex $bbox 1]
6863    set y1 [lindex $bbox 3]
6864    foreach match $matches {
6865        set start [lindex $match 0]
6866        set end [lindex $match 1]
6867        if {$start > $end} continue
6868        set xoff [font measure $font [string range $str 0 [expr {$start-1}]]]
6869        set xlen [font measure $font [string range $str 0 [expr {$end}]]]
6870        set t [$canv create rect [expr {$x0+$xoff}] $y0 \
6871                   [expr {$x0+$xlen+2}] $y1 \
6872                   -outline {} -tags [list match$l matches] -fill yellow]
6873        $canv lower $t
6874        if {$row == $selectedline} {
6875            $canv raise $t secsel
6876        }
6877    }
6878}
6879
6880proc unmarkmatches {} {
6881    global markingmatches
6882
6883    allcanvs delete matches
6884    set markingmatches 0
6885    stopfinding
6886}
6887
6888proc selcanvline {w x y} {
6889    global canv canvy0 ctext linespc
6890    global rowtextx
6891    set ymax [lindex [$canv cget -scrollregion] 3]
6892    if {$ymax == {}} return
6893    set yfrac [lindex [$canv yview] 0]
6894    set y [expr {$y + $yfrac * $ymax}]
6895    set l [expr {int(($y - $canvy0) / $linespc + 0.5)}]
6896    if {$l < 0} {
6897        set l 0
6898    }
6899    if {$w eq $canv} {
6900        set xmax [lindex [$canv cget -scrollregion] 2]
6901        set xleft [expr {[lindex [$canv xview] 0] * $xmax}]
6902        if {![info exists rowtextx($l)] || $xleft + $x < $rowtextx($l)} return
6903    }
6904    unmarkmatches
6905    selectline $l 1
6906}
6907
6908proc commit_descriptor {p} {
6909    global commitinfo
6910    if {![info exists commitinfo($p)]} {
6911        getcommit $p
6912    }
6913    set l "..."
6914    if {[llength $commitinfo($p)] > 1} {
6915        set l [lindex $commitinfo($p) 0]
6916    }
6917    return "$p ($l)\n"
6918}
6919
6920# append some text to the ctext widget, and make any SHA1 ID
6921# that we know about be a clickable link.
6922proc appendwithlinks {text tags} {
6923    global ctext linknum curview
6924
6925    set start [$ctext index "end - 1c"]
6926    $ctext insert end $text $tags
6927    set links [regexp -indices -all -inline {(?:\m|-g)[0-9a-f]{6,40}\M} $text]
6928    foreach l $links {
6929        set s [lindex $l 0]
6930        set e [lindex $l 1]
6931        set linkid [string range $text $s $e]
6932        incr e
6933        $ctext tag delete link$linknum
6934        $ctext tag add link$linknum "$start + $s c" "$start + $e c"
6935        setlink $linkid link$linknum
6936        incr linknum
6937    }
6938}
6939
6940proc setlink {id lk} {
6941    global curview ctext pendinglinks
6942    global linkfgcolor
6943
6944    if {[string range $id 0 1] eq "-g"} {
6945      set id [string range $id 2 end]
6946    }
6947
6948    set known 0
6949    if {[string length $id] < 40} {
6950        set matches [longid $id]
6951        if {[llength $matches] > 0} {
6952            if {[llength $matches] > 1} return
6953            set known 1
6954            set id [lindex $matches 0]
6955        }
6956    } else {
6957        set known [commitinview $id $curview]
6958    }
6959    if {$known} {
6960        $ctext tag conf $lk -foreground $linkfgcolor -underline 1
6961        $ctext tag bind $lk <1> [list selbyid $id]
6962        $ctext tag bind $lk <Enter> {linkcursor %W 1}
6963        $ctext tag bind $lk <Leave> {linkcursor %W -1}
6964    } else {
6965        lappend pendinglinks($id) $lk
6966        interestedin $id {makelink %P}
6967    }
6968}
6969
6970proc appendshortlink {id {pre {}} {post {}}} {
6971    global ctext linknum
6972
6973    $ctext insert end $pre
6974    $ctext tag delete link$linknum
6975    $ctext insert end [string range $id 0 7] link$linknum
6976    $ctext insert end $post
6977    setlink $id link$linknum
6978    incr linknum
6979}
6980
6981proc makelink {id} {
6982    global pendinglinks
6983
6984    if {![info exists pendinglinks($id)]} return
6985    foreach lk $pendinglinks($id) {
6986        setlink $id $lk
6987    }
6988    unset pendinglinks($id)
6989}
6990
6991proc linkcursor {w inc} {
6992    global linkentercount curtextcursor
6993
6994    if {[incr linkentercount $inc] > 0} {
6995        $w configure -cursor hand2
6996    } else {
6997        $w configure -cursor $curtextcursor
6998        if {$linkentercount < 0} {
6999            set linkentercount 0
7000        }
7001    }
7002}
7003
7004proc viewnextline {dir} {
7005    global canv linespc
7006
7007    $canv delete hover
7008    set ymax [lindex [$canv cget -scrollregion] 3]
7009    set wnow [$canv yview]
7010    set wtop [expr {[lindex $wnow 0] * $ymax}]
7011    set newtop [expr {$wtop + $dir * $linespc}]
7012    if {$newtop < 0} {
7013        set newtop 0
7014    } elseif {$newtop > $ymax} {
7015        set newtop $ymax
7016    }
7017    allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7018}
7019
7020# add a list of tag or branch names at position pos
7021# returns the number of names inserted
7022proc appendrefs {pos ids var} {
7023    global ctext linknum curview $var maxrefs mainheadid
7024
7025    if {[catch {$ctext index $pos}]} {
7026        return 0
7027    }
7028    $ctext conf -state normal
7029    $ctext delete $pos "$pos lineend"
7030    set tags {}
7031    foreach id $ids {
7032        foreach tag [set $var\($id\)] {
7033            lappend tags [list $tag $id]
7034        }
7035    }
7036
7037    set sep {}
7038    set tags [lsort -index 0 -decreasing $tags]
7039    set nutags 0
7040
7041    if {[llength $tags] > $maxrefs} {
7042        # If we are displaying heads, and there are too many,
7043        # see if there are some important heads to display.
7044        # Currently this means "master" and the current head.
7045        set itags {}
7046        if {$var eq "idheads"} {
7047            set utags {}
7048            foreach ti $tags {
7049                set hname [lindex $ti 0]
7050                set id [lindex $ti 1]
7051                if {($hname eq "master" || $id eq $mainheadid) &&
7052                    [llength $itags] < $maxrefs} {
7053                    lappend itags $ti
7054                } else {
7055                    lappend utags $ti
7056                }
7057            }
7058            set tags $utags
7059        }
7060        if {$itags ne {}} {
7061            set str [mc "and many more"]
7062            set sep " "
7063        } else {
7064            set str [mc "many"]
7065        }
7066        $ctext insert $pos "$str ([llength $tags])"
7067        set nutags [llength $tags]
7068        set tags $itags
7069    }
7070
7071    foreach ti $tags {
7072        set id [lindex $ti 1]
7073        set lk link$linknum
7074        incr linknum
7075        $ctext tag delete $lk
7076        $ctext insert $pos $sep
7077        $ctext insert $pos [lindex $ti 0] $lk
7078        setlink $id $lk
7079        set sep ", "
7080    }
7081    $ctext tag add wwrap "$pos linestart" "$pos lineend"
7082    $ctext conf -state disabled
7083    return [expr {[llength $tags] + $nutags}]
7084}
7085
7086# called when we have finished computing the nearby tags
7087proc dispneartags {delay} {
7088    global selectedline currentid showneartags tagphase
7089
7090    if {$selectedline eq {} || !$showneartags} return
7091    after cancel dispnexttag
7092    if {$delay} {
7093        after 200 dispnexttag
7094        set tagphase -1
7095    } else {
7096        after idle dispnexttag
7097        set tagphase 0
7098    }
7099}
7100
7101proc dispnexttag {} {
7102    global selectedline currentid showneartags tagphase ctext
7103
7104    if {$selectedline eq {} || !$showneartags} return
7105    switch -- $tagphase {
7106        0 {
7107            set dtags [desctags $currentid]
7108            if {$dtags ne {}} {
7109                appendrefs precedes $dtags idtags
7110            }
7111        }
7112        1 {
7113            set atags [anctags $currentid]
7114            if {$atags ne {}} {
7115                appendrefs follows $atags idtags
7116            }
7117        }
7118        2 {
7119            set dheads [descheads $currentid]
7120            if {$dheads ne {}} {
7121                if {[appendrefs branch $dheads idheads] > 1
7122                    && [$ctext get "branch -3c"] eq "h"} {
7123                    # turn "Branch" into "Branches"
7124                    $ctext conf -state normal
7125                    $ctext insert "branch -2c" "es"
7126                    $ctext conf -state disabled
7127                }
7128            }
7129        }
7130    }
7131    if {[incr tagphase] <= 2} {
7132        after idle dispnexttag
7133    }
7134}
7135
7136proc make_secsel {id} {
7137    global linehtag linentag linedtag canv canv2 canv3
7138
7139    if {![info exists linehtag($id)]} return
7140    $canv delete secsel
7141    set t [eval $canv create rect [$canv bbox $linehtag($id)] -outline {{}} \
7142               -tags secsel -fill [$canv cget -selectbackground]]
7143    $canv lower $t
7144    $canv2 delete secsel
7145    set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] -outline {{}} \
7146               -tags secsel -fill [$canv2 cget -selectbackground]]
7147    $canv2 lower $t
7148    $canv3 delete secsel
7149    set t [eval $canv3 create rect [$canv3 bbox $linedtag($id)] -outline {{}} \
7150               -tags secsel -fill [$canv3 cget -selectbackground]]
7151    $canv3 lower $t
7152}
7153
7154proc make_idmark {id} {
7155    global linehtag canv fgcolor
7156
7157    if {![info exists linehtag($id)]} return
7158    $canv delete markid
7159    set t [eval $canv create rect [$canv bbox $linehtag($id)] \
7160               -tags markid -outline $fgcolor]
7161    $canv raise $t
7162}
7163
7164proc selectline {l isnew {desired_loc {}}} {
7165    global canv ctext commitinfo selectedline
7166    global canvy0 linespc parents children curview
7167    global currentid sha1entry
7168    global commentend idtags linknum
7169    global mergemax numcommits pending_select
7170    global cmitmode showneartags allcommits
7171    global targetrow targetid lastscrollrows
7172    global autoselect autosellen jump_to_here
7173    global vinlinediff
7174
7175    catch {unset pending_select}
7176    $canv delete hover
7177    normalline
7178    unsel_reflist
7179    stopfinding
7180    if {$l < 0 || $l >= $numcommits} return
7181    set id [commitonrow $l]
7182    set targetid $id
7183    set targetrow $l
7184    set selectedline $l
7185    set currentid $id
7186    if {$lastscrollrows < $numcommits} {
7187        setcanvscroll
7188    }
7189
7190    set y [expr {$canvy0 + $l * $linespc}]
7191    set ymax [lindex [$canv cget -scrollregion] 3]
7192    set ytop [expr {$y - $linespc - 1}]
7193    set ybot [expr {$y + $linespc + 1}]
7194    set wnow [$canv yview]
7195    set wtop [expr {[lindex $wnow 0] * $ymax}]
7196    set wbot [expr {[lindex $wnow 1] * $ymax}]
7197    set wh [expr {$wbot - $wtop}]
7198    set newtop $wtop
7199    if {$ytop < $wtop} {
7200        if {$ybot < $wtop} {
7201            set newtop [expr {$y - $wh / 2.0}]
7202        } else {
7203            set newtop $ytop
7204            if {$newtop > $wtop - $linespc} {
7205                set newtop [expr {$wtop - $linespc}]
7206            }
7207        }
7208    } elseif {$ybot > $wbot} {
7209        if {$ytop > $wbot} {
7210            set newtop [expr {$y - $wh / 2.0}]
7211        } else {
7212            set newtop [expr {$ybot - $wh}]
7213            if {$newtop < $wtop + $linespc} {
7214                set newtop [expr {$wtop + $linespc}]
7215            }
7216        }
7217    }
7218    if {$newtop != $wtop} {
7219        if {$newtop < 0} {
7220            set newtop 0
7221        }
7222        allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7223        drawvisible
7224    }
7225
7226    make_secsel $id
7227
7228    if {$isnew} {
7229        addtohistory [list selbyid $id 0] savecmitpos
7230    }
7231
7232    $sha1entry delete 0 end
7233    $sha1entry insert 0 $id
7234    if {$autoselect} {
7235        $sha1entry selection range 0 $autosellen
7236    }
7237    rhighlight_sel $id
7238
7239    $ctext conf -state normal
7240    clear_ctext
7241    set linknum 0
7242    if {![info exists commitinfo($id)]} {
7243        getcommit $id
7244    }
7245    set info $commitinfo($id)
7246    set date [formatdate [lindex $info 2]]
7247    $ctext insert end "[mc "Author"]: [lindex $info 1]  $date\n"
7248    set date [formatdate [lindex $info 4]]
7249    $ctext insert end "[mc "Committer"]: [lindex $info 3]  $date\n"
7250    if {[info exists idtags($id)]} {
7251        $ctext insert end [mc "Tags:"]
7252        foreach tag $idtags($id) {
7253            $ctext insert end " $tag"
7254        }
7255        $ctext insert end "\n"
7256    }
7257
7258    set headers {}
7259    set olds $parents($curview,$id)
7260    if {[llength $olds] > 1} {
7261        set np 0
7262        foreach p $olds {
7263            if {$np >= $mergemax} {
7264                set tag mmax
7265            } else {
7266                set tag m$np
7267            }
7268            $ctext insert end "[mc "Parent"]: " $tag
7269            appendwithlinks [commit_descriptor $p] {}
7270            incr np
7271        }
7272    } else {
7273        foreach p $olds {
7274            append headers "[mc "Parent"]: [commit_descriptor $p]"
7275        }
7276    }
7277
7278    foreach c $children($curview,$id) {
7279        append headers "[mc "Child"]:  [commit_descriptor $c]"
7280    }
7281
7282    # make anything that looks like a SHA1 ID be a clickable link
7283    appendwithlinks $headers {}
7284    if {$showneartags} {
7285        if {![info exists allcommits]} {
7286            getallcommits
7287        }
7288        $ctext insert end "[mc "Branch"]: "
7289        $ctext mark set branch "end -1c"
7290        $ctext mark gravity branch left
7291        $ctext insert end "\n[mc "Follows"]: "
7292        $ctext mark set follows "end -1c"
7293        $ctext mark gravity follows left
7294        $ctext insert end "\n[mc "Precedes"]: "
7295        $ctext mark set precedes "end -1c"
7296        $ctext mark gravity precedes left
7297        $ctext insert end "\n"
7298        dispneartags 1
7299    }
7300    $ctext insert end "\n"
7301    set comment [lindex $info 5]
7302    if {[string first "\r" $comment] >= 0} {
7303        set comment [string map {"\r" "\n    "} $comment]
7304    }
7305    appendwithlinks $comment {comment}
7306
7307    $ctext tag remove found 1.0 end
7308    $ctext conf -state disabled
7309    set commentend [$ctext index "end - 1c"]
7310
7311    set jump_to_here $desired_loc
7312    init_flist [mc "Comments"]
7313    if {$cmitmode eq "tree"} {
7314        gettree $id
7315    } elseif {$vinlinediff($curview) == 1} {
7316        showinlinediff $id
7317    } elseif {[llength $olds] <= 1} {
7318        startdiff $id
7319    } else {
7320        mergediff $id
7321    }
7322}
7323
7324proc selfirstline {} {
7325    unmarkmatches
7326    selectline 0 1
7327}
7328
7329proc sellastline {} {
7330    global numcommits
7331    unmarkmatches
7332    set l [expr {$numcommits - 1}]
7333    selectline $l 1
7334}
7335
7336proc selnextline {dir} {
7337    global selectedline
7338    focus .
7339    if {$selectedline eq {}} return
7340    set l [expr {$selectedline + $dir}]
7341    unmarkmatches
7342    selectline $l 1
7343}
7344
7345proc selnextpage {dir} {
7346    global canv linespc selectedline numcommits
7347
7348    set lpp [expr {([winfo height $canv] - 2) / $linespc}]
7349    if {$lpp < 1} {
7350        set lpp 1
7351    }
7352    allcanvs yview scroll [expr {$dir * $lpp}] units
7353    drawvisible
7354    if {$selectedline eq {}} return
7355    set l [expr {$selectedline + $dir * $lpp}]
7356    if {$l < 0} {
7357        set l 0
7358    } elseif {$l >= $numcommits} {
7359        set l [expr $numcommits - 1]
7360    }
7361    unmarkmatches
7362    selectline $l 1
7363}
7364
7365proc unselectline {} {
7366    global selectedline currentid
7367
7368    set selectedline {}
7369    catch {unset currentid}
7370    allcanvs delete secsel
7371    rhighlight_none
7372}
7373
7374proc reselectline {} {
7375    global selectedline
7376
7377    if {$selectedline ne {}} {
7378        selectline $selectedline 0
7379    }
7380}
7381
7382proc addtohistory {cmd {saveproc {}}} {
7383    global history historyindex curview
7384
7385    unset_posvars
7386    save_position
7387    set elt [list $curview $cmd $saveproc {}]
7388    if {$historyindex > 0
7389        && [lindex $history [expr {$historyindex - 1}]] == $elt} {
7390        return
7391    }
7392
7393    if {$historyindex < [llength $history]} {
7394        set history [lreplace $history $historyindex end $elt]
7395    } else {
7396        lappend history $elt
7397    }
7398    incr historyindex
7399    if {$historyindex > 1} {
7400        .tf.bar.leftbut conf -state normal
7401    } else {
7402        .tf.bar.leftbut conf -state disabled
7403    }
7404    .tf.bar.rightbut conf -state disabled
7405}
7406
7407# save the scrolling position of the diff display pane
7408proc save_position {} {
7409    global historyindex history
7410
7411    if {$historyindex < 1} return
7412    set hi [expr {$historyindex - 1}]
7413    set fn [lindex $history $hi 2]
7414    if {$fn ne {}} {
7415        lset history $hi 3 [eval $fn]
7416    }
7417}
7418
7419proc unset_posvars {} {
7420    global last_posvars
7421
7422    if {[info exists last_posvars]} {
7423        foreach {var val} $last_posvars {
7424            global $var
7425            catch {unset $var}
7426        }
7427        unset last_posvars
7428    }
7429}
7430
7431proc godo {elt} {
7432    global curview last_posvars
7433
7434    set view [lindex $elt 0]
7435    set cmd [lindex $elt 1]
7436    set pv [lindex $elt 3]
7437    if {$curview != $view} {
7438        showview $view
7439    }
7440    unset_posvars
7441    foreach {var val} $pv {
7442        global $var
7443        set $var $val
7444    }
7445    set last_posvars $pv
7446    eval $cmd
7447}
7448
7449proc goback {} {
7450    global history historyindex
7451    focus .
7452
7453    if {$historyindex > 1} {
7454        save_position
7455        incr historyindex -1
7456        godo [lindex $history [expr {$historyindex - 1}]]
7457        .tf.bar.rightbut conf -state normal
7458    }
7459    if {$historyindex <= 1} {
7460        .tf.bar.leftbut conf -state disabled
7461    }
7462}
7463
7464proc goforw {} {
7465    global history historyindex
7466    focus .
7467
7468    if {$historyindex < [llength $history]} {
7469        save_position
7470        set cmd [lindex $history $historyindex]
7471        incr historyindex
7472        godo $cmd
7473        .tf.bar.leftbut conf -state normal
7474    }
7475    if {$historyindex >= [llength $history]} {
7476        .tf.bar.rightbut conf -state disabled
7477    }
7478}
7479
7480proc gettree {id} {
7481    global treefilelist treeidlist diffids diffmergeid treepending
7482    global nullid nullid2
7483
7484    set diffids $id
7485    catch {unset diffmergeid}
7486    if {![info exists treefilelist($id)]} {
7487        if {![info exists treepending]} {
7488            if {$id eq $nullid} {
7489                set cmd [list | git ls-files]
7490            } elseif {$id eq $nullid2} {
7491                set cmd [list | git ls-files --stage -t]
7492            } else {
7493                set cmd [list | git ls-tree -r $id]
7494            }
7495            if {[catch {set gtf [open $cmd r]}]} {
7496                return
7497            }
7498            set treepending $id
7499            set treefilelist($id) {}
7500            set treeidlist($id) {}
7501            fconfigure $gtf -blocking 0 -encoding binary
7502            filerun $gtf [list gettreeline $gtf $id]
7503        }
7504    } else {
7505        setfilelist $id
7506    }
7507}
7508
7509proc gettreeline {gtf id} {
7510    global treefilelist treeidlist treepending cmitmode diffids nullid nullid2
7511
7512    set nl 0
7513    while {[incr nl] <= 1000 && [gets $gtf line] >= 0} {
7514        if {$diffids eq $nullid} {
7515            set fname $line
7516        } else {
7517            set i [string first "\t" $line]
7518            if {$i < 0} continue
7519            set fname [string range $line [expr {$i+1}] end]
7520            set line [string range $line 0 [expr {$i-1}]]
7521            if {$diffids ne $nullid2 && [lindex $line 1] ne "blob"} continue
7522            set sha1 [lindex $line 2]
7523            lappend treeidlist($id) $sha1
7524        }
7525        if {[string index $fname 0] eq "\""} {
7526            set fname [lindex $fname 0]
7527        }
7528        set fname [encoding convertfrom $fname]
7529        lappend treefilelist($id) $fname
7530    }
7531    if {![eof $gtf]} {
7532        return [expr {$nl >= 1000? 2: 1}]
7533    }
7534    close $gtf
7535    unset treepending
7536    if {$cmitmode ne "tree"} {
7537        if {![info exists diffmergeid]} {
7538            gettreediffs $diffids
7539        }
7540    } elseif {$id ne $diffids} {
7541        gettree $diffids
7542    } else {
7543        setfilelist $id
7544    }
7545    return 0
7546}
7547
7548proc showfile {f} {
7549    global treefilelist treeidlist diffids nullid nullid2
7550    global ctext_file_names ctext_file_lines
7551    global ctext commentend
7552
7553    set i [lsearch -exact $treefilelist($diffids) $f]
7554    if {$i < 0} {
7555        puts "oops, $f not in list for id $diffids"
7556        return
7557    }
7558    if {$diffids eq $nullid} {
7559        if {[catch {set bf [open $f r]} err]} {
7560            puts "oops, can't read $f: $err"
7561            return
7562        }
7563    } else {
7564        set blob [lindex $treeidlist($diffids) $i]
7565        if {[catch {set bf [open [concat | git cat-file blob $blob] r]} err]} {
7566            puts "oops, error reading blob $blob: $err"
7567            return
7568        }
7569    }
7570    fconfigure $bf -blocking 0 -encoding [get_path_encoding $f]
7571    filerun $bf [list getblobline $bf $diffids]
7572    $ctext config -state normal
7573    clear_ctext $commentend
7574    lappend ctext_file_names $f
7575    lappend ctext_file_lines [lindex [split $commentend "."] 0]
7576    $ctext insert end "\n"
7577    $ctext insert end "$f\n" filesep
7578    $ctext config -state disabled
7579    $ctext yview $commentend
7580    settabs 0
7581}
7582
7583proc getblobline {bf id} {
7584    global diffids cmitmode ctext
7585
7586    if {$id ne $diffids || $cmitmode ne "tree"} {
7587        catch {close $bf}
7588        return 0
7589    }
7590    $ctext config -state normal
7591    set nl 0
7592    while {[incr nl] <= 1000 && [gets $bf line] >= 0} {
7593        $ctext insert end "$line\n"
7594    }
7595    if {[eof $bf]} {
7596        global jump_to_here ctext_file_names commentend
7597
7598        # delete last newline
7599        $ctext delete "end - 2c" "end - 1c"
7600        close $bf
7601        if {$jump_to_here ne {} &&
7602            [lindex $jump_to_here 0] eq [lindex $ctext_file_names 0]} {
7603            set lnum [expr {[lindex $jump_to_here 1] +
7604                            [lindex [split $commentend .] 0]}]
7605            mark_ctext_line $lnum
7606        }
7607        $ctext config -state disabled
7608        return 0
7609    }
7610    $ctext config -state disabled
7611    return [expr {$nl >= 1000? 2: 1}]
7612}
7613
7614proc mark_ctext_line {lnum} {
7615    global ctext markbgcolor
7616
7617    $ctext tag delete omark
7618    $ctext tag add omark $lnum.0 "$lnum.0 + 1 line"
7619    $ctext tag conf omark -background $markbgcolor
7620    $ctext see $lnum.0
7621}
7622
7623proc mergediff {id} {
7624    global diffmergeid
7625    global diffids treediffs
7626    global parents curview
7627
7628    set diffmergeid $id
7629    set diffids $id
7630    set treediffs($id) {}
7631    set np [llength $parents($curview,$id)]
7632    settabs $np
7633    getblobdiffs $id
7634}
7635
7636proc startdiff {ids} {
7637    global treediffs diffids treepending diffmergeid nullid nullid2
7638
7639    settabs 1
7640    set diffids $ids
7641    catch {unset diffmergeid}
7642    if {![info exists treediffs($ids)] ||
7643        [lsearch -exact $ids $nullid] >= 0 ||
7644        [lsearch -exact $ids $nullid2] >= 0} {
7645        if {![info exists treepending]} {
7646            gettreediffs $ids
7647        }
7648    } else {
7649        addtocflist $ids
7650    }
7651}
7652
7653proc showinlinediff {ids} {
7654    global commitinfo commitdata ctext
7655    global treediffs
7656
7657    set info $commitinfo($ids)
7658    set diff [lindex $info 7]
7659    set difflines [split $diff "\n"]
7660
7661    initblobdiffvars
7662    set treediff {}
7663
7664    set inhdr 0
7665    foreach line $difflines {
7666        if {![string compare -length 5 "diff " $line]} {
7667            set inhdr 1
7668        } elseif {$inhdr && ![string compare -length 4 "+++ " $line]} {
7669            # offset also accounts for the b/ prefix
7670            lappend treediff [string range $line 6 end]
7671            set inhdr 0
7672        }
7673    }
7674
7675    set treediffs($ids) $treediff
7676    add_flist $treediff
7677
7678    $ctext conf -state normal
7679    foreach line $difflines {
7680        parseblobdiffline $ids $line
7681    }
7682    maybe_scroll_ctext 1
7683    $ctext conf -state disabled
7684}
7685
7686# If the filename (name) is under any of the passed filter paths
7687# then return true to include the file in the listing.
7688proc path_filter {filter name} {
7689    set worktree [gitworktree]
7690    foreach p $filter {
7691        set fq_p [file normalize $p]
7692        set fq_n [file normalize [file join $worktree $name]]
7693        if {[string match [file normalize $fq_p]* $fq_n]} {
7694            return 1
7695        }
7696    }
7697    return 0
7698}
7699
7700proc addtocflist {ids} {
7701    global treediffs
7702
7703    add_flist $treediffs($ids)
7704    getblobdiffs $ids
7705}
7706
7707proc diffcmd {ids flags} {
7708    global log_showroot nullid nullid2
7709
7710    set i [lsearch -exact $ids $nullid]
7711    set j [lsearch -exact $ids $nullid2]
7712    if {$i >= 0} {
7713        if {[llength $ids] > 1 && $j < 0} {
7714            # comparing working directory with some specific revision
7715            set cmd [concat | git diff-index $flags]
7716            if {$i == 0} {
7717                lappend cmd -R [lindex $ids 1]
7718            } else {
7719                lappend cmd [lindex $ids 0]
7720            }
7721        } else {
7722            # comparing working directory with index
7723            set cmd [concat | git diff-files $flags]
7724            if {$j == 1} {
7725                lappend cmd -R
7726            }
7727        }
7728    } elseif {$j >= 0} {
7729        set cmd [concat | git diff-index --cached $flags]
7730        if {[llength $ids] > 1} {
7731            # comparing index with specific revision
7732            if {$j == 0} {
7733                lappend cmd -R [lindex $ids 1]
7734            } else {
7735                lappend cmd [lindex $ids 0]
7736            }
7737        } else {
7738            # comparing index with HEAD
7739            lappend cmd HEAD
7740        }
7741    } else {
7742        if {$log_showroot} {
7743            lappend flags --root
7744        }
7745        set cmd [concat | git diff-tree -r $flags $ids]
7746    }
7747    return $cmd
7748}
7749
7750proc gettreediffs {ids} {
7751    global treediff treepending limitdiffs vfilelimit curview
7752
7753    set cmd [diffcmd $ids {--no-commit-id}]
7754    if {$limitdiffs && $vfilelimit($curview) ne {}} {
7755            set cmd [concat $cmd -- $vfilelimit($curview)]
7756    }
7757    if {[catch {set gdtf [open $cmd r]}]} return
7758
7759    set treepending $ids
7760    set treediff {}
7761    fconfigure $gdtf -blocking 0 -encoding binary
7762    filerun $gdtf [list gettreediffline $gdtf $ids]
7763}
7764
7765proc gettreediffline {gdtf ids} {
7766    global treediff treediffs treepending diffids diffmergeid
7767    global cmitmode vfilelimit curview limitdiffs perfile_attrs
7768
7769    set nr 0
7770    set sublist {}
7771    set max 1000
7772    if {$perfile_attrs} {
7773        # cache_gitattr is slow, and even slower on win32 where we
7774        # have to invoke it for only about 30 paths at a time
7775        set max 500
7776        if {[tk windowingsystem] == "win32"} {
7777            set max 120
7778        }
7779    }
7780    while {[incr nr] <= $max && [gets $gdtf line] >= 0} {
7781        set i [string first "\t" $line]
7782        if {$i >= 0} {
7783            set file [string range $line [expr {$i+1}] end]
7784            if {[string index $file 0] eq "\""} {
7785                set file [lindex $file 0]
7786            }
7787            set file [encoding convertfrom $file]
7788            if {$file ne [lindex $treediff end]} {
7789                lappend treediff $file
7790                lappend sublist $file
7791            }
7792        }
7793    }
7794    if {$perfile_attrs} {
7795        cache_gitattr encoding $sublist
7796    }
7797    if {![eof $gdtf]} {
7798        return [expr {$nr >= $max? 2: 1}]
7799    }
7800    close $gdtf
7801    set treediffs($ids) $treediff
7802    unset treepending
7803    if {$cmitmode eq "tree" && [llength $diffids] == 1} {
7804        gettree $diffids
7805    } elseif {$ids != $diffids} {
7806        if {![info exists diffmergeid]} {
7807            gettreediffs $diffids
7808        }
7809    } else {
7810        addtocflist $ids
7811    }
7812    return 0
7813}
7814
7815# empty string or positive integer
7816proc diffcontextvalidate {v} {
7817    return [regexp {^(|[1-9][0-9]*)$} $v]
7818}
7819
7820proc diffcontextchange {n1 n2 op} {
7821    global diffcontextstring diffcontext
7822
7823    if {[string is integer -strict $diffcontextstring]} {
7824        if {$diffcontextstring >= 0} {
7825            set diffcontext $diffcontextstring
7826            reselectline
7827        }
7828    }
7829}
7830
7831proc changeignorespace {} {
7832    reselectline
7833}
7834
7835proc changeworddiff {name ix op} {
7836    reselectline
7837}
7838
7839proc initblobdiffvars {} {
7840    global diffencoding targetline diffnparents
7841    global diffinhdr currdiffsubmod diffseehere
7842    set targetline {}
7843    set diffnparents 0
7844    set diffinhdr 0
7845    set diffencoding [get_path_encoding {}]
7846    set currdiffsubmod ""
7847    set diffseehere -1
7848}
7849
7850proc getblobdiffs {ids} {
7851    global blobdifffd diffids env
7852    global treediffs
7853    global diffcontext
7854    global ignorespace
7855    global worddiff
7856    global limitdiffs vfilelimit curview
7857    global git_version
7858
7859    set textconv {}
7860    if {[package vcompare $git_version "1.6.1"] >= 0} {
7861        set textconv "--textconv"
7862    }
7863    set submodule {}
7864    if {[package vcompare $git_version "1.6.6"] >= 0} {
7865        set submodule "--submodule"
7866    }
7867    set cmd [diffcmd $ids "-p $textconv $submodule  -C --cc --no-commit-id -U$diffcontext"]
7868    if {$ignorespace} {
7869        append cmd " -w"
7870    }
7871    if {$worddiff ne [mc "Line diff"]} {
7872        append cmd " --word-diff=porcelain"
7873    }
7874    if {$limitdiffs && $vfilelimit($curview) ne {}} {
7875        set cmd [concat $cmd -- $vfilelimit($curview)]
7876    }
7877    if {[catch {set bdf [open $cmd r]} err]} {
7878        error_popup [mc "Error getting diffs: %s" $err]
7879        return
7880    }
7881    fconfigure $bdf -blocking 0 -encoding binary -eofchar {}
7882    set blobdifffd($ids) $bdf
7883    initblobdiffvars
7884    filerun $bdf [list getblobdiffline $bdf $diffids]
7885}
7886
7887proc savecmitpos {} {
7888    global ctext cmitmode
7889
7890    if {$cmitmode eq "tree"} {
7891        return {}
7892    }
7893    return [list target_scrollpos [$ctext index @0,0]]
7894}
7895
7896proc savectextpos {} {
7897    global ctext
7898
7899    return [list target_scrollpos [$ctext index @0,0]]
7900}
7901
7902proc maybe_scroll_ctext {ateof} {
7903    global ctext target_scrollpos
7904
7905    if {![info exists target_scrollpos]} return
7906    if {!$ateof} {
7907        set nlines [expr {[winfo height $ctext]
7908                          / [font metrics textfont -linespace]}]
7909        if {[$ctext compare "$target_scrollpos + $nlines lines" <= end]} return
7910    }
7911    $ctext yview $target_scrollpos
7912    unset target_scrollpos
7913}
7914
7915proc setinlist {var i val} {
7916    global $var
7917
7918    while {[llength [set $var]] < $i} {
7919        lappend $var {}
7920    }
7921    if {[llength [set $var]] == $i} {
7922        lappend $var $val
7923    } else {
7924        lset $var $i $val
7925    }
7926}
7927
7928proc makediffhdr {fname ids} {
7929    global ctext curdiffstart treediffs diffencoding
7930    global ctext_file_names jump_to_here targetline diffline
7931
7932    set fname [encoding convertfrom $fname]
7933    set diffencoding [get_path_encoding $fname]
7934    set i [lsearch -exact $treediffs($ids) $fname]
7935    if {$i >= 0} {
7936        setinlist difffilestart $i $curdiffstart
7937    }
7938    lset ctext_file_names end $fname
7939    set l [expr {(78 - [string length $fname]) / 2}]
7940    set pad [string range "----------------------------------------" 1 $l]
7941    $ctext insert $curdiffstart "$pad $fname $pad" filesep
7942    set targetline {}
7943    if {$jump_to_here ne {} && [lindex $jump_to_here 0] eq $fname} {
7944        set targetline [lindex $jump_to_here 1]
7945    }
7946    set diffline 0
7947}
7948
7949proc blobdiffmaybeseehere {ateof} {
7950    global diffseehere
7951    if {$diffseehere >= 0} {
7952        mark_ctext_line [lindex [split $diffseehere .] 0]
7953    }
7954    maybe_scroll_ctext $ateof
7955}
7956
7957proc getblobdiffline {bdf ids} {
7958    global diffids blobdifffd
7959    global ctext
7960
7961    set nr 0
7962    $ctext conf -state normal
7963    while {[incr nr] <= 1000 && [gets $bdf line] >= 0} {
7964        if {$ids != $diffids || $bdf != $blobdifffd($ids)} {
7965            catch {close $bdf}
7966            return 0
7967        }
7968        parseblobdiffline $ids $line
7969    }
7970    $ctext conf -state disabled
7971    blobdiffmaybeseehere [eof $bdf]
7972    if {[eof $bdf]} {
7973        catch {close $bdf}
7974        return 0
7975    }
7976    return [expr {$nr >= 1000? 2: 1}]
7977}
7978
7979proc parseblobdiffline {ids line} {
7980    global ctext curdiffstart
7981    global diffnexthead diffnextnote difffilestart
7982    global ctext_file_names ctext_file_lines
7983    global diffinhdr treediffs mergemax diffnparents
7984    global diffencoding jump_to_here targetline diffline currdiffsubmod
7985    global worddiff diffseehere
7986
7987    if {![string compare -length 5 "diff " $line]} {
7988        if {![regexp {^diff (--cc|--git) } $line m type]} {
7989            set line [encoding convertfrom $line]
7990            $ctext insert end "$line\n" hunksep
7991            continue
7992        }
7993        # start of a new file
7994        set diffinhdr 1
7995        $ctext insert end "\n"
7996        set curdiffstart [$ctext index "end - 1c"]
7997        lappend ctext_file_names ""
7998        lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
7999        $ctext insert end "\n" filesep
8000
8001        if {$type eq "--cc"} {
8002            # start of a new file in a merge diff
8003            set fname [string range $line 10 end]
8004            if {[lsearch -exact $treediffs($ids) $fname] < 0} {
8005                lappend treediffs($ids) $fname
8006                add_flist [list $fname]
8007            }
8008
8009        } else {
8010            set line [string range $line 11 end]
8011            # If the name hasn't changed the length will be odd,
8012            # the middle char will be a space, and the two bits either
8013            # side will be a/name and b/name, or "a/name" and "b/name".
8014            # If the name has changed we'll get "rename from" and
8015            # "rename to" or "copy from" and "copy to" lines following
8016            # this, and we'll use them to get the filenames.
8017            # This complexity is necessary because spaces in the
8018            # filename(s) don't get escaped.
8019            set l [string length $line]
8020            set i [expr {$l / 2}]
8021            if {!(($l & 1) && [string index $line $i] eq " " &&
8022                  [string range $line 2 [expr {$i - 1}]] eq \
8023                      [string range $line [expr {$i + 3}] end])} {
8024                return
8025            }
8026            # unescape if quoted and chop off the a/ from the front
8027            if {[string index $line 0] eq "\""} {
8028                set fname [string range [lindex $line 0] 2 end]
8029            } else {
8030                set fname [string range $line 2 [expr {$i - 1}]]
8031            }
8032        }
8033        makediffhdr $fname $ids
8034
8035    } elseif {![string compare -length 16 "* Unmerged path " $line]} {
8036        set fname [encoding convertfrom [string range $line 16 end]]
8037        $ctext insert end "\n"
8038        set curdiffstart [$ctext index "end - 1c"]
8039        lappend ctext_file_names $fname
8040        lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8041        $ctext insert end "$line\n" filesep
8042        set i [lsearch -exact $treediffs($ids) $fname]
8043        if {$i >= 0} {
8044            setinlist difffilestart $i $curdiffstart
8045        }
8046
8047    } elseif {![string compare -length 2 "@@" $line]} {
8048        regexp {^@@+} $line ats
8049        set line [encoding convertfrom $diffencoding $line]
8050        $ctext insert end "$line\n" hunksep
8051        if {[regexp { \+(\d+),\d+ @@} $line m nl]} {
8052            set diffline $nl
8053        }
8054        set diffnparents [expr {[string length $ats] - 1}]
8055        set diffinhdr 0
8056
8057    } elseif {![string compare -length 10 "Submodule " $line]} {
8058        # start of a new submodule
8059        if {[regexp -indices "\[0-9a-f\]+\\.\\." $line nameend]} {
8060            set fname [string range $line 10 [expr [lindex $nameend 0] - 2]]
8061        } else {
8062            set fname [string range $line 10 [expr [string first "contains " $line] - 2]]
8063        }
8064        if {$currdiffsubmod != $fname} {
8065            $ctext insert end "\n";     # Add newline after commit message
8066        }
8067        set curdiffstart [$ctext index "end - 1c"]
8068        lappend ctext_file_names ""
8069        if {$currdiffsubmod != $fname} {
8070            lappend ctext_file_lines $fname
8071            makediffhdr $fname $ids
8072            set currdiffsubmod $fname
8073            $ctext insert end "\n$line\n" filesep
8074        } else {
8075            $ctext insert end "$line\n" filesep
8076        }
8077    } elseif {![string compare -length 3 "  >" $line]} {
8078        set $currdiffsubmod ""
8079        set line [encoding convertfrom $diffencoding $line]
8080        $ctext insert end "$line\n" dresult
8081    } elseif {![string compare -length 3 "  <" $line]} {
8082        set $currdiffsubmod ""
8083        set line [encoding convertfrom $diffencoding $line]
8084        $ctext insert end "$line\n" d0
8085    } elseif {$diffinhdr} {
8086        if {![string compare -length 12 "rename from " $line]} {
8087            set fname [string range $line [expr 6 + [string first " from " $line] ] end]
8088            if {[string index $fname 0] eq "\""} {
8089                set fname [lindex $fname 0]
8090            }
8091            set fname [encoding convertfrom $fname]
8092            set i [lsearch -exact $treediffs($ids) $fname]
8093            if {$i >= 0} {
8094                setinlist difffilestart $i $curdiffstart
8095            }
8096        } elseif {![string compare -length 10 $line "rename to "] ||
8097                  ![string compare -length 8 $line "copy to "]} {
8098            set fname [string range $line [expr 4 + [string first " to " $line] ] end]
8099            if {[string index $fname 0] eq "\""} {
8100                set fname [lindex $fname 0]
8101            }
8102            makediffhdr $fname $ids
8103        } elseif {[string compare -length 3 $line "---"] == 0} {
8104            # do nothing
8105            return
8106        } elseif {[string compare -length 3 $line "+++"] == 0} {
8107            set diffinhdr 0
8108            return
8109        }
8110        $ctext insert end "$line\n" filesep
8111
8112    } else {
8113        set line [string map {\x1A ^Z} \
8114                      [encoding convertfrom $diffencoding $line]]
8115        # parse the prefix - one ' ', '-' or '+' for each parent
8116        set prefix [string range $line 0 [expr {$diffnparents - 1}]]
8117        set tag [expr {$diffnparents > 1? "m": "d"}]
8118        set dowords [expr {$worddiff ne [mc "Line diff"] && $diffnparents == 1}]
8119        set words_pre_markup ""
8120        set words_post_markup ""
8121        if {[string trim $prefix " -+"] eq {}} {
8122            # prefix only has " ", "-" and "+" in it: normal diff line
8123            set num [string first "-" $prefix]
8124            if {$dowords} {
8125                set line [string range $line 1 end]
8126            }
8127            if {$num >= 0} {
8128                # removed line, first parent with line is $num
8129                if {$num >= $mergemax} {
8130                    set num "max"
8131                }
8132                if {$dowords && $worddiff eq [mc "Markup words"]} {
8133                    $ctext insert end "\[-$line-\]" $tag$num
8134                } else {
8135                    $ctext insert end "$line" $tag$num
8136                }
8137                if {!$dowords} {
8138                    $ctext insert end "\n" $tag$num
8139                }
8140            } else {
8141                set tags {}
8142                if {[string first "+" $prefix] >= 0} {
8143                    # added line
8144                    lappend tags ${tag}result
8145                    if {$diffnparents > 1} {
8146                        set num [string first " " $prefix]
8147                        if {$num >= 0} {
8148                            if {$num >= $mergemax} {
8149                                set num "max"
8150                            }
8151                            lappend tags m$num
8152                        }
8153                    }
8154                    set words_pre_markup "{+"
8155                    set words_post_markup "+}"
8156                }
8157                if {$targetline ne {}} {
8158                    if {$diffline == $targetline} {
8159                        set diffseehere [$ctext index "end - 1 chars"]
8160                        set targetline {}
8161                    } else {
8162                        incr diffline
8163                    }
8164                }
8165                if {$dowords && $worddiff eq [mc "Markup words"]} {
8166                    $ctext insert end "$words_pre_markup$line$words_post_markup" $tags
8167                } else {
8168                    $ctext insert end "$line" $tags
8169                }
8170                if {!$dowords} {
8171                    $ctext insert end "\n" $tags
8172                }
8173            }
8174        } elseif {$dowords && $prefix eq "~"} {
8175            $ctext insert end "\n" {}
8176        } else {
8177            # "\ No newline at end of file",
8178            # or something else we don't recognize
8179            $ctext insert end "$line\n" hunksep
8180        }
8181    }
8182}
8183
8184proc changediffdisp {} {
8185    global ctext diffelide
8186
8187    $ctext tag conf d0 -elide [lindex $diffelide 0]
8188    $ctext tag conf dresult -elide [lindex $diffelide 1]
8189}
8190
8191proc highlightfile {cline} {
8192    global cflist cflist_top
8193
8194    if {![info exists cflist_top]} return
8195
8196    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
8197    $cflist tag add highlight $cline.0 "$cline.0 lineend"
8198    $cflist see $cline.0
8199    set cflist_top $cline
8200}
8201
8202proc highlightfile_for_scrollpos {topidx} {
8203    global cmitmode difffilestart
8204
8205    if {$cmitmode eq "tree"} return
8206    if {![info exists difffilestart]} return
8207
8208    set top [lindex [split $topidx .] 0]
8209    if {$difffilestart eq {} || $top < [lindex $difffilestart 0]} {
8210        highlightfile 0
8211    } else {
8212        highlightfile [expr {[bsearch $difffilestart $top] + 2}]
8213    }
8214}
8215
8216proc prevfile {} {
8217    global difffilestart ctext cmitmode
8218
8219    if {$cmitmode eq "tree"} return
8220    set prev 0.0
8221    set here [$ctext index @0,0]
8222    foreach loc $difffilestart {
8223        if {[$ctext compare $loc >= $here]} {
8224            $ctext yview $prev
8225            return
8226        }
8227        set prev $loc
8228    }
8229    $ctext yview $prev
8230}
8231
8232proc nextfile {} {
8233    global difffilestart ctext cmitmode
8234
8235    if {$cmitmode eq "tree"} return
8236    set here [$ctext index @0,0]
8237    foreach loc $difffilestart {
8238        if {[$ctext compare $loc > $here]} {
8239            $ctext yview $loc
8240            return
8241        }
8242    }
8243}
8244
8245proc clear_ctext {{first 1.0}} {
8246    global ctext smarktop smarkbot
8247    global ctext_file_names ctext_file_lines
8248    global pendinglinks
8249
8250    set l [lindex [split $first .] 0]
8251    if {![info exists smarktop] || [$ctext compare $first < $smarktop.0]} {
8252        set smarktop $l
8253    }
8254    if {![info exists smarkbot] || [$ctext compare $first < $smarkbot.0]} {
8255        set smarkbot $l
8256    }
8257    $ctext delete $first end
8258    if {$first eq "1.0"} {
8259        catch {unset pendinglinks}
8260    }
8261    set ctext_file_names {}
8262    set ctext_file_lines {}
8263}
8264
8265proc settabs {{firstab {}}} {
8266    global firsttabstop tabstop ctext have_tk85
8267
8268    if {$firstab ne {} && $have_tk85} {
8269        set firsttabstop $firstab
8270    }
8271    set w [font measure textfont "0"]
8272    if {$firsttabstop != 0} {
8273        $ctext conf -tabs [list [expr {($firsttabstop + $tabstop) * $w}] \
8274                               [expr {($firsttabstop + 2 * $tabstop) * $w}]]
8275    } elseif {$have_tk85 || $tabstop != 8} {
8276        $ctext conf -tabs [expr {$tabstop * $w}]
8277    } else {
8278        $ctext conf -tabs {}
8279    }
8280}
8281
8282proc incrsearch {name ix op} {
8283    global ctext searchstring searchdirn
8284
8285    if {[catch {$ctext index anchor}]} {
8286        # no anchor set, use start of selection, or of visible area
8287        set sel [$ctext tag ranges sel]
8288        if {$sel ne {}} {
8289            $ctext mark set anchor [lindex $sel 0]
8290        } elseif {$searchdirn eq "-forwards"} {
8291            $ctext mark set anchor @0,0
8292        } else {
8293            $ctext mark set anchor @0,[winfo height $ctext]
8294        }
8295    }
8296    if {$searchstring ne {}} {
8297        set here [$ctext search -count mlen $searchdirn -- $searchstring anchor]
8298        if {$here ne {}} {
8299            $ctext see $here
8300            set mend "$here + $mlen c"
8301            $ctext tag remove sel 1.0 end
8302            $ctext tag add sel $here $mend
8303            suppress_highlighting_file_for_current_scrollpos
8304            highlightfile_for_scrollpos $here
8305        }
8306    }
8307    rehighlight_search_results
8308}
8309
8310proc dosearch {} {
8311    global sstring ctext searchstring searchdirn
8312
8313    focus $sstring
8314    $sstring icursor end
8315    set searchdirn -forwards
8316    if {$searchstring ne {}} {
8317        set sel [$ctext tag ranges sel]
8318        if {$sel ne {}} {
8319            set start "[lindex $sel 0] + 1c"
8320        } elseif {[catch {set start [$ctext index anchor]}]} {
8321            set start "@0,0"
8322        }
8323        set match [$ctext search -count mlen -- $searchstring $start]
8324        $ctext tag remove sel 1.0 end
8325        if {$match eq {}} {
8326            bell
8327            return
8328        }
8329        $ctext see $match
8330        suppress_highlighting_file_for_current_scrollpos
8331        highlightfile_for_scrollpos $match
8332        set mend "$match + $mlen c"
8333        $ctext tag add sel $match $mend
8334        $ctext mark unset anchor
8335        rehighlight_search_results
8336    }
8337}
8338
8339proc dosearchback {} {
8340    global sstring ctext searchstring searchdirn
8341
8342    focus $sstring
8343    $sstring icursor end
8344    set searchdirn -backwards
8345    if {$searchstring ne {}} {
8346        set sel [$ctext tag ranges sel]
8347        if {$sel ne {}} {
8348            set start [lindex $sel 0]
8349        } elseif {[catch {set start [$ctext index anchor]}]} {
8350            set start @0,[winfo height $ctext]
8351        }
8352        set match [$ctext search -backwards -count ml -- $searchstring $start]
8353        $ctext tag remove sel 1.0 end
8354        if {$match eq {}} {
8355            bell
8356            return
8357        }
8358        $ctext see $match
8359        suppress_highlighting_file_for_current_scrollpos
8360        highlightfile_for_scrollpos $match
8361        set mend "$match + $ml c"
8362        $ctext tag add sel $match $mend
8363        $ctext mark unset anchor
8364        rehighlight_search_results
8365    }
8366}
8367
8368proc rehighlight_search_results {} {
8369    global ctext searchstring
8370
8371    $ctext tag remove found 1.0 end
8372    $ctext tag remove currentsearchhit 1.0 end
8373
8374    if {$searchstring ne {}} {
8375        searchmarkvisible 1
8376    }
8377}
8378
8379proc searchmark {first last} {
8380    global ctext searchstring
8381
8382    set sel [$ctext tag ranges sel]
8383
8384    set mend $first.0
8385    while {1} {
8386        set match [$ctext search -count mlen -- $searchstring $mend $last.end]
8387        if {$match eq {}} break
8388        set mend "$match + $mlen c"
8389        if {$sel ne {} && [$ctext compare $match == [lindex $sel 0]]} {
8390            $ctext tag add currentsearchhit $match $mend
8391        } else {
8392            $ctext tag add found $match $mend
8393        }
8394    }
8395}
8396
8397proc searchmarkvisible {doall} {
8398    global ctext smarktop smarkbot
8399
8400    set topline [lindex [split [$ctext index @0,0] .] 0]
8401    set botline [lindex [split [$ctext index @0,[winfo height $ctext]] .] 0]
8402    if {$doall || $botline < $smarktop || $topline > $smarkbot} {
8403        # no overlap with previous
8404        searchmark $topline $botline
8405        set smarktop $topline
8406        set smarkbot $botline
8407    } else {
8408        if {$topline < $smarktop} {
8409            searchmark $topline [expr {$smarktop-1}]
8410            set smarktop $topline
8411        }
8412        if {$botline > $smarkbot} {
8413            searchmark [expr {$smarkbot+1}] $botline
8414            set smarkbot $botline
8415        }
8416    }
8417}
8418
8419proc suppress_highlighting_file_for_current_scrollpos {} {
8420    global ctext suppress_highlighting_file_for_this_scrollpos
8421
8422    set suppress_highlighting_file_for_this_scrollpos [$ctext index @0,0]
8423}
8424
8425proc scrolltext {f0 f1} {
8426    global searchstring cmitmode ctext
8427    global suppress_highlighting_file_for_this_scrollpos
8428
8429    set topidx [$ctext index @0,0]
8430    if {![info exists suppress_highlighting_file_for_this_scrollpos]
8431        || $topidx ne $suppress_highlighting_file_for_this_scrollpos} {
8432        highlightfile_for_scrollpos $topidx
8433    }
8434
8435    catch {unset suppress_highlighting_file_for_this_scrollpos}
8436
8437    .bleft.bottom.sb set $f0 $f1
8438    if {$searchstring ne {}} {
8439        searchmarkvisible 0
8440    }
8441}
8442
8443proc setcoords {} {
8444    global linespc charspc canvx0 canvy0
8445    global xspc1 xspc2 lthickness
8446
8447    set linespc [font metrics mainfont -linespace]
8448    set charspc [font measure mainfont "m"]
8449    set canvy0 [expr {int(3 + 0.5 * $linespc)}]
8450    set canvx0 [expr {int(3 + 0.5 * $linespc)}]
8451    set lthickness [expr {int($linespc / 9) + 1}]
8452    set xspc1(0) $linespc
8453    set xspc2 $linespc
8454}
8455
8456proc redisplay {} {
8457    global canv
8458    global selectedline
8459
8460    set ymax [lindex [$canv cget -scrollregion] 3]
8461    if {$ymax eq {} || $ymax == 0} return
8462    set span [$canv yview]
8463    clear_display
8464    setcanvscroll
8465    allcanvs yview moveto [lindex $span 0]
8466    drawvisible
8467    if {$selectedline ne {}} {
8468        selectline $selectedline 0
8469        allcanvs yview moveto [lindex $span 0]
8470    }
8471}
8472
8473proc parsefont {f n} {
8474    global fontattr
8475
8476    set fontattr($f,family) [lindex $n 0]
8477    set s [lindex $n 1]
8478    if {$s eq {} || $s == 0} {
8479        set s 10
8480    } elseif {$s < 0} {
8481        set s [expr {int(-$s / [winfo fpixels . 1p] + 0.5)}]
8482    }
8483    set fontattr($f,size) $s
8484    set fontattr($f,weight) normal
8485    set fontattr($f,slant) roman
8486    foreach style [lrange $n 2 end] {
8487        switch -- $style {
8488            "normal" -
8489            "bold"   {set fontattr($f,weight) $style}
8490            "roman" -
8491            "italic" {set fontattr($f,slant) $style}
8492        }
8493    }
8494}
8495
8496proc fontflags {f {isbold 0}} {
8497    global fontattr
8498
8499    return [list -family $fontattr($f,family) -size $fontattr($f,size) \
8500                -weight [expr {$isbold? "bold": $fontattr($f,weight)}] \
8501                -slant $fontattr($f,slant)]
8502}
8503
8504proc fontname {f} {
8505    global fontattr
8506
8507    set n [list $fontattr($f,family) $fontattr($f,size)]
8508    if {$fontattr($f,weight) eq "bold"} {
8509        lappend n "bold"
8510    }
8511    if {$fontattr($f,slant) eq "italic"} {
8512        lappend n "italic"
8513    }
8514    return $n
8515}
8516
8517proc incrfont {inc} {
8518    global mainfont textfont ctext canv cflist showrefstop
8519    global stopped entries fontattr
8520
8521    unmarkmatches
8522    set s $fontattr(mainfont,size)
8523    incr s $inc
8524    if {$s < 1} {
8525        set s 1
8526    }
8527    set fontattr(mainfont,size) $s
8528    font config mainfont -size $s
8529    font config mainfontbold -size $s
8530    set mainfont [fontname mainfont]
8531    set s $fontattr(textfont,size)
8532    incr s $inc
8533    if {$s < 1} {
8534        set s 1
8535    }
8536    set fontattr(textfont,size) $s
8537    font config textfont -size $s
8538    font config textfontbold -size $s
8539    set textfont [fontname textfont]
8540    setcoords
8541    settabs
8542    redisplay
8543}
8544
8545proc clearsha1 {} {
8546    global sha1entry sha1string
8547    if {[string length $sha1string] == 40} {
8548        $sha1entry delete 0 end
8549    }
8550}
8551
8552proc sha1change {n1 n2 op} {
8553    global sha1string currentid sha1but
8554    if {$sha1string == {}
8555        || ([info exists currentid] && $sha1string == $currentid)} {
8556        set state disabled
8557    } else {
8558        set state normal
8559    }
8560    if {[$sha1but cget -state] == $state} return
8561    if {$state == "normal"} {
8562        $sha1but conf -state normal -relief raised -text "[mc "Goto:"] "
8563    } else {
8564        $sha1but conf -state disabled -relief flat -text "[mc "SHA1 ID:"] "
8565    }
8566}
8567
8568proc gotocommit {} {
8569    global sha1string tagids headids curview varcid
8570
8571    if {$sha1string == {}
8572        || ([info exists currentid] && $sha1string == $currentid)} return
8573    if {[info exists tagids($sha1string)]} {
8574        set id $tagids($sha1string)
8575    } elseif {[info exists headids($sha1string)]} {
8576        set id $headids($sha1string)
8577    } else {
8578        set id [string tolower $sha1string]
8579        if {[regexp {^[0-9a-f]{4,39}$} $id]} {
8580            set matches [longid $id]
8581            if {$matches ne {}} {
8582                if {[llength $matches] > 1} {
8583                    error_popup [mc "Short SHA1 id %s is ambiguous" $id]
8584                    return
8585                }
8586                set id [lindex $matches 0]
8587            }
8588        } else {
8589            if {[catch {set id [exec git rev-parse --verify $sha1string]}]} {
8590                error_popup [mc "Revision %s is not known" $sha1string]
8591                return
8592            }
8593        }
8594    }
8595    if {[commitinview $id $curview]} {
8596        selectline [rowofcommit $id] 1
8597        return
8598    }
8599    if {[regexp {^[0-9a-fA-F]{4,}$} $sha1string]} {
8600        set msg [mc "SHA1 id %s is not known" $sha1string]
8601    } else {
8602        set msg [mc "Revision %s is not in the current view" $sha1string]
8603    }
8604    error_popup $msg
8605}
8606
8607proc lineenter {x y id} {
8608    global hoverx hovery hoverid hovertimer
8609    global commitinfo canv
8610
8611    if {![info exists commitinfo($id)] && ![getcommit $id]} return
8612    set hoverx $x
8613    set hovery $y
8614    set hoverid $id
8615    if {[info exists hovertimer]} {
8616        after cancel $hovertimer
8617    }
8618    set hovertimer [after 500 linehover]
8619    $canv delete hover
8620}
8621
8622proc linemotion {x y id} {
8623    global hoverx hovery hoverid hovertimer
8624
8625    if {[info exists hoverid] && $id == $hoverid} {
8626        set hoverx $x
8627        set hovery $y
8628        if {[info exists hovertimer]} {
8629            after cancel $hovertimer
8630        }
8631        set hovertimer [after 500 linehover]
8632    }
8633}
8634
8635proc lineleave {id} {
8636    global hoverid hovertimer canv
8637
8638    if {[info exists hoverid] && $id == $hoverid} {
8639        $canv delete hover
8640        if {[info exists hovertimer]} {
8641            after cancel $hovertimer
8642            unset hovertimer
8643        }
8644        unset hoverid
8645    }
8646}
8647
8648proc linehover {} {
8649    global hoverx hovery hoverid hovertimer
8650    global canv linespc lthickness
8651    global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor
8652
8653    global commitinfo
8654
8655    set text [lindex $commitinfo($hoverid) 0]
8656    set ymax [lindex [$canv cget -scrollregion] 3]
8657    if {$ymax == {}} return
8658    set yfrac [lindex [$canv yview] 0]
8659    set x [expr {$hoverx + 2 * $linespc}]
8660    set y [expr {$hovery + $yfrac * $ymax - $linespc / 2}]
8661    set x0 [expr {$x - 2 * $lthickness}]
8662    set y0 [expr {$y - 2 * $lthickness}]
8663    set x1 [expr {$x + [font measure mainfont $text] + 2 * $lthickness}]
8664    set y1 [expr {$y + $linespc + 2 * $lthickness}]
8665    set t [$canv create rectangle $x0 $y0 $x1 $y1 \
8666               -fill $linehoverbgcolor -outline $linehoveroutlinecolor \
8667               -width 1 -tags hover]
8668    $canv raise $t
8669    set t [$canv create text $x $y -anchor nw -text $text -tags hover \
8670               -font mainfont -fill $linehoverfgcolor]
8671    $canv raise $t
8672}
8673
8674proc clickisonarrow {id y} {
8675    global lthickness
8676
8677    set ranges [rowranges $id]
8678    set thresh [expr {2 * $lthickness + 6}]
8679    set n [expr {[llength $ranges] - 1}]
8680    for {set i 1} {$i < $n} {incr i} {
8681        set row [lindex $ranges $i]
8682        if {abs([yc $row] - $y) < $thresh} {
8683            return $i
8684        }
8685    }
8686    return {}
8687}
8688
8689proc arrowjump {id n y} {
8690    global canv
8691
8692    # 1 <-> 2, 3 <-> 4, etc...
8693    set n [expr {(($n - 1) ^ 1) + 1}]
8694    set row [lindex [rowranges $id] $n]
8695    set yt [yc $row]
8696    set ymax [lindex [$canv cget -scrollregion] 3]
8697    if {$ymax eq {} || $ymax <= 0} return
8698    set view [$canv yview]
8699    set yspan [expr {[lindex $view 1] - [lindex $view 0]}]
8700    set yfrac [expr {$yt / $ymax - $yspan / 2}]
8701    if {$yfrac < 0} {
8702        set yfrac 0
8703    }
8704    allcanvs yview moveto $yfrac
8705}
8706
8707proc lineclick {x y id isnew} {
8708    global ctext commitinfo children canv thickerline curview
8709
8710    if {![info exists commitinfo($id)] && ![getcommit $id]} return
8711    unmarkmatches
8712    unselectline
8713    normalline
8714    $canv delete hover
8715    # draw this line thicker than normal
8716    set thickerline $id
8717    drawlines $id
8718    if {$isnew} {
8719        set ymax [lindex [$canv cget -scrollregion] 3]
8720        if {$ymax eq {}} return
8721        set yfrac [lindex [$canv yview] 0]
8722        set y [expr {$y + $yfrac * $ymax}]
8723    }
8724    set dirn [clickisonarrow $id $y]
8725    if {$dirn ne {}} {
8726        arrowjump $id $dirn $y
8727        return
8728    }
8729
8730    if {$isnew} {
8731        addtohistory [list lineclick $x $y $id 0] savectextpos
8732    }
8733    # fill the details pane with info about this line
8734    $ctext conf -state normal
8735    clear_ctext
8736    settabs 0
8737    $ctext insert end "[mc "Parent"]:\t"
8738    $ctext insert end $id link0
8739    setlink $id link0
8740    set info $commitinfo($id)
8741    $ctext insert end "\n\t[lindex $info 0]\n"
8742    $ctext insert end "\t[mc "Author"]:\t[lindex $info 1]\n"
8743    set date [formatdate [lindex $info 2]]
8744    $ctext insert end "\t[mc "Date"]:\t$date\n"
8745    set kids $children($curview,$id)
8746    if {$kids ne {}} {
8747        $ctext insert end "\n[mc "Children"]:"
8748        set i 0
8749        foreach child $kids {
8750            incr i
8751            if {![info exists commitinfo($child)] && ![getcommit $child]} continue
8752            set info $commitinfo($child)
8753            $ctext insert end "\n\t"
8754            $ctext insert end $child link$i
8755            setlink $child link$i
8756            $ctext insert end "\n\t[lindex $info 0]"
8757            $ctext insert end "\n\t[mc "Author"]:\t[lindex $info 1]"
8758            set date [formatdate [lindex $info 2]]
8759            $ctext insert end "\n\t[mc "Date"]:\t$date\n"
8760        }
8761    }
8762    maybe_scroll_ctext 1
8763    $ctext conf -state disabled
8764    init_flist {}
8765}
8766
8767proc normalline {} {
8768    global thickerline
8769    if {[info exists thickerline]} {
8770        set id $thickerline
8771        unset thickerline
8772        drawlines $id
8773    }
8774}
8775
8776proc selbyid {id {isnew 1}} {
8777    global curview
8778    if {[commitinview $id $curview]} {
8779        selectline [rowofcommit $id] $isnew
8780    }
8781}
8782
8783proc mstime {} {
8784    global startmstime
8785    if {![info exists startmstime]} {
8786        set startmstime [clock clicks -milliseconds]
8787    }
8788    return [format "%.3f" [expr {([clock click -milliseconds] - $startmstime) / 1000.0}]]
8789}
8790
8791proc rowmenu {x y id} {
8792    global rowctxmenu selectedline rowmenuid curview
8793    global nullid nullid2 fakerowmenu mainhead markedid
8794
8795    stopfinding
8796    set rowmenuid $id
8797    if {$selectedline eq {} || [rowofcommit $id] eq $selectedline} {
8798        set state disabled
8799    } else {
8800        set state normal
8801    }
8802    if {[info exists markedid] && $markedid ne $id} {
8803        set mstate normal
8804    } else {
8805        set mstate disabled
8806    }
8807    if {$id ne $nullid && $id ne $nullid2} {
8808        set menu $rowctxmenu
8809        if {$mainhead ne {}} {
8810            $menu entryconfigure 7 -label [mc "Reset %s branch to here" $mainhead] -state normal
8811        } else {
8812            $menu entryconfigure 7 -label [mc "Detached head: can't reset" $mainhead] -state disabled
8813        }
8814        $menu entryconfigure 9 -state $mstate
8815        $menu entryconfigure 10 -state $mstate
8816        $menu entryconfigure 11 -state $mstate
8817    } else {
8818        set menu $fakerowmenu
8819    }
8820    $menu entryconfigure [mca "Diff this -> selected"] -state $state
8821    $menu entryconfigure [mca "Diff selected -> this"] -state $state
8822    $menu entryconfigure [mca "Make patch"] -state $state
8823    $menu entryconfigure [mca "Diff this -> marked commit"] -state $mstate
8824    $menu entryconfigure [mca "Diff marked commit -> this"] -state $mstate
8825    tk_popup $menu $x $y
8826}
8827
8828proc markhere {} {
8829    global rowmenuid markedid canv
8830
8831    set markedid $rowmenuid
8832    make_idmark $markedid
8833}
8834
8835proc gotomark {} {
8836    global markedid
8837
8838    if {[info exists markedid]} {
8839        selbyid $markedid
8840    }
8841}
8842
8843proc replace_by_kids {l r} {
8844    global curview children
8845
8846    set id [commitonrow $r]
8847    set l [lreplace $l 0 0]
8848    foreach kid $children($curview,$id) {
8849        lappend l [rowofcommit $kid]
8850    }
8851    return [lsort -integer -decreasing -unique $l]
8852}
8853
8854proc find_common_desc {} {
8855    global markedid rowmenuid curview children
8856
8857    if {![info exists markedid]} return
8858    if {![commitinview $markedid $curview] ||
8859        ![commitinview $rowmenuid $curview]} return
8860    #set t1 [clock clicks -milliseconds]
8861    set l1 [list [rowofcommit $markedid]]
8862    set l2 [list [rowofcommit $rowmenuid]]
8863    while 1 {
8864        set r1 [lindex $l1 0]
8865        set r2 [lindex $l2 0]
8866        if {$r1 eq {} || $r2 eq {}} break
8867        if {$r1 == $r2} {
8868            selectline $r1 1
8869            break
8870        }
8871        if {$r1 > $r2} {
8872            set l1 [replace_by_kids $l1 $r1]
8873        } else {
8874            set l2 [replace_by_kids $l2 $r2]
8875        }
8876    }
8877    #set t2 [clock clicks -milliseconds]
8878    #puts "took [expr {$t2-$t1}]ms"
8879}
8880
8881proc compare_commits {} {
8882    global markedid rowmenuid curview children
8883
8884    if {![info exists markedid]} return
8885    if {![commitinview $markedid $curview]} return
8886    addtohistory [list do_cmp_commits $markedid $rowmenuid]
8887    do_cmp_commits $markedid $rowmenuid
8888}
8889
8890proc getpatchid {id} {
8891    global patchids
8892
8893    if {![info exists patchids($id)]} {
8894        set cmd [diffcmd [list $id] {-p --root}]
8895        # trim off the initial "|"
8896        set cmd [lrange $cmd 1 end]
8897        if {[catch {
8898            set x [eval exec $cmd | git patch-id]
8899            set patchids($id) [lindex $x 0]
8900        }]} {
8901            set patchids($id) "error"
8902        }
8903    }
8904    return $patchids($id)
8905}
8906
8907proc do_cmp_commits {a b} {
8908    global ctext curview parents children patchids commitinfo
8909
8910    $ctext conf -state normal
8911    clear_ctext
8912    init_flist {}
8913    for {set i 0} {$i < 100} {incr i} {
8914        set skipa 0
8915        set skipb 0
8916        if {[llength $parents($curview,$a)] > 1} {
8917            appendshortlink $a [mc "Skipping merge commit "] "\n"
8918            set skipa 1
8919        } else {
8920            set patcha [getpatchid $a]
8921        }
8922        if {[llength $parents($curview,$b)] > 1} {
8923            appendshortlink $b [mc "Skipping merge commit "] "\n"
8924            set skipb 1
8925        } else {
8926            set patchb [getpatchid $b]
8927        }
8928        if {!$skipa && !$skipb} {
8929            set heada [lindex $commitinfo($a) 0]
8930            set headb [lindex $commitinfo($b) 0]
8931            if {$patcha eq "error"} {
8932                appendshortlink $a [mc "Error getting patch ID for "] \
8933                    [mc " - stopping\n"]
8934                break
8935            }
8936            if {$patchb eq "error"} {
8937                appendshortlink $b [mc "Error getting patch ID for "] \
8938                    [mc " - stopping\n"]
8939                break
8940            }
8941            if {$patcha eq $patchb} {
8942                if {$heada eq $headb} {
8943                    appendshortlink $a [mc "Commit "]
8944                    appendshortlink $b " == " "  $heada\n"
8945                } else {
8946                    appendshortlink $a [mc "Commit "] "  $heada\n"
8947                    appendshortlink $b [mc " is the same patch as\n       "] \
8948                        "  $headb\n"
8949                }
8950                set skipa 1
8951                set skipb 1
8952            } else {
8953                $ctext insert end "\n"
8954                appendshortlink $a [mc "Commit "] "  $heada\n"
8955                appendshortlink $b [mc " differs from\n       "] \
8956                    "  $headb\n"
8957                $ctext insert end [mc "Diff of commits:\n\n"]
8958                $ctext conf -state disabled
8959                update
8960                diffcommits $a $b
8961                return
8962            }
8963        }
8964        if {$skipa} {
8965            set kids [real_children $curview,$a]
8966            if {[llength $kids] != 1} {
8967                $ctext insert end "\n"
8968                appendshortlink $a [mc "Commit "] \
8969                    [mc " has %s children - stopping\n" [llength $kids]]
8970                break
8971            }
8972            set a [lindex $kids 0]
8973        }
8974        if {$skipb} {
8975            set kids [real_children $curview,$b]
8976            if {[llength $kids] != 1} {
8977                appendshortlink $b [mc "Commit "] \
8978                    [mc " has %s children - stopping\n" [llength $kids]]
8979                break
8980            }
8981            set b [lindex $kids 0]
8982        }
8983    }
8984    $ctext conf -state disabled
8985}
8986
8987proc diffcommits {a b} {
8988    global diffcontext diffids blobdifffd diffinhdr currdiffsubmod
8989
8990    set tmpdir [gitknewtmpdir]
8991    set fna [file join $tmpdir "commit-[string range $a 0 7]"]
8992    set fnb [file join $tmpdir "commit-[string range $b 0 7]"]
8993    if {[catch {
8994        exec git diff-tree -p --pretty $a >$fna
8995        exec git diff-tree -p --pretty $b >$fnb
8996    } err]} {
8997        error_popup [mc "Error writing commit to file: %s" $err]
8998        return
8999    }
9000    if {[catch {
9001        set fd [open "| diff -U$diffcontext $fna $fnb" r]
9002    } err]} {
9003        error_popup [mc "Error diffing commits: %s" $err]
9004        return
9005    }
9006    set diffids [list commits $a $b]
9007    set blobdifffd($diffids) $fd
9008    set diffinhdr 0
9009    set currdiffsubmod ""
9010    filerun $fd [list getblobdiffline $fd $diffids]
9011}
9012
9013proc diffvssel {dirn} {
9014    global rowmenuid selectedline
9015
9016    if {$selectedline eq {}} return
9017    if {$dirn} {
9018        set oldid [commitonrow $selectedline]
9019        set newid $rowmenuid
9020    } else {
9021        set oldid $rowmenuid
9022        set newid [commitonrow $selectedline]
9023    }
9024    addtohistory [list doseldiff $oldid $newid] savectextpos
9025    doseldiff $oldid $newid
9026}
9027
9028proc diffvsmark {dirn} {
9029    global rowmenuid markedid
9030
9031    if {![info exists markedid]} return
9032    if {$dirn} {
9033        set oldid $markedid
9034        set newid $rowmenuid
9035    } else {
9036        set oldid $rowmenuid
9037        set newid $markedid
9038    }
9039    addtohistory [list doseldiff $oldid $newid] savectextpos
9040    doseldiff $oldid $newid
9041}
9042
9043proc doseldiff {oldid newid} {
9044    global ctext
9045    global commitinfo
9046
9047    $ctext conf -state normal
9048    clear_ctext
9049    init_flist [mc "Top"]
9050    $ctext insert end "[mc "From"] "
9051    $ctext insert end $oldid link0
9052    setlink $oldid link0
9053    $ctext insert end "\n     "
9054    $ctext insert end [lindex $commitinfo($oldid) 0]
9055    $ctext insert end "\n\n[mc "To"]   "
9056    $ctext insert end $newid link1
9057    setlink $newid link1
9058    $ctext insert end "\n     "
9059    $ctext insert end [lindex $commitinfo($newid) 0]
9060    $ctext insert end "\n"
9061    $ctext conf -state disabled
9062    $ctext tag remove found 1.0 end
9063    startdiff [list $oldid $newid]
9064}
9065
9066proc mkpatch {} {
9067    global rowmenuid currentid commitinfo patchtop patchnum NS
9068
9069    if {![info exists currentid]} return
9070    set oldid $currentid
9071    set oldhead [lindex $commitinfo($oldid) 0]
9072    set newid $rowmenuid
9073    set newhead [lindex $commitinfo($newid) 0]
9074    set top .patch
9075    set patchtop $top
9076    catch {destroy $top}
9077    ttk_toplevel $top
9078    make_transient $top .
9079    ${NS}::label $top.title -text [mc "Generate patch"]
9080    grid $top.title - -pady 10
9081    ${NS}::label $top.from -text [mc "From:"]
9082    ${NS}::entry $top.fromsha1 -width 40
9083    $top.fromsha1 insert 0 $oldid
9084    $top.fromsha1 conf -state readonly
9085    grid $top.from $top.fromsha1 -sticky w
9086    ${NS}::entry $top.fromhead -width 60
9087    $top.fromhead insert 0 $oldhead
9088    $top.fromhead conf -state readonly
9089    grid x $top.fromhead -sticky w
9090    ${NS}::label $top.to -text [mc "To:"]
9091    ${NS}::entry $top.tosha1 -width 40
9092    $top.tosha1 insert 0 $newid
9093    $top.tosha1 conf -state readonly
9094    grid $top.to $top.tosha1 -sticky w
9095    ${NS}::entry $top.tohead -width 60
9096    $top.tohead insert 0 $newhead
9097    $top.tohead conf -state readonly
9098    grid x $top.tohead -sticky w
9099    ${NS}::button $top.rev -text [mc "Reverse"] -command mkpatchrev
9100    grid $top.rev x -pady 10 -padx 5
9101    ${NS}::label $top.flab -text [mc "Output file:"]
9102    ${NS}::entry $top.fname -width 60
9103    $top.fname insert 0 [file normalize "patch$patchnum.patch"]
9104    incr patchnum
9105    grid $top.flab $top.fname -sticky w
9106    ${NS}::frame $top.buts
9107    ${NS}::button $top.buts.gen -text [mc "Generate"] -command mkpatchgo
9108    ${NS}::button $top.buts.can -text [mc "Cancel"] -command mkpatchcan
9109    bind $top <Key-Return> mkpatchgo
9110    bind $top <Key-Escape> mkpatchcan
9111    grid $top.buts.gen $top.buts.can
9112    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9113    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9114    grid $top.buts - -pady 10 -sticky ew
9115    focus $top.fname
9116}
9117
9118proc mkpatchrev {} {
9119    global patchtop
9120
9121    set oldid [$patchtop.fromsha1 get]
9122    set oldhead [$patchtop.fromhead get]
9123    set newid [$patchtop.tosha1 get]
9124    set newhead [$patchtop.tohead get]
9125    foreach e [list fromsha1 fromhead tosha1 tohead] \
9126            v [list $newid $newhead $oldid $oldhead] {
9127        $patchtop.$e conf -state normal
9128        $patchtop.$e delete 0 end
9129        $patchtop.$e insert 0 $v
9130        $patchtop.$e conf -state readonly
9131    }
9132}
9133
9134proc mkpatchgo {} {
9135    global patchtop nullid nullid2
9136
9137    set oldid [$patchtop.fromsha1 get]
9138    set newid [$patchtop.tosha1 get]
9139    set fname [$patchtop.fname get]
9140    set cmd [diffcmd [list $oldid $newid] -p]
9141    # trim off the initial "|"
9142    set cmd [lrange $cmd 1 end]
9143    lappend cmd >$fname &
9144    if {[catch {eval exec $cmd} err]} {
9145        error_popup "[mc "Error creating patch:"] $err" $patchtop
9146    }
9147    catch {destroy $patchtop}
9148    unset patchtop
9149}
9150
9151proc mkpatchcan {} {
9152    global patchtop
9153
9154    catch {destroy $patchtop}
9155    unset patchtop
9156}
9157
9158proc mktag {} {
9159    global rowmenuid mktagtop commitinfo NS
9160
9161    set top .maketag
9162    set mktagtop $top
9163    catch {destroy $top}
9164    ttk_toplevel $top
9165    make_transient $top .
9166    ${NS}::label $top.title -text [mc "Create tag"]
9167    grid $top.title - -pady 10
9168    ${NS}::label $top.id -text [mc "ID:"]
9169    ${NS}::entry $top.sha1 -width 40
9170    $top.sha1 insert 0 $rowmenuid
9171    $top.sha1 conf -state readonly
9172    grid $top.id $top.sha1 -sticky w
9173    ${NS}::entry $top.head -width 60
9174    $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9175    $top.head conf -state readonly
9176    grid x $top.head -sticky w
9177    ${NS}::label $top.tlab -text [mc "Tag name:"]
9178    ${NS}::entry $top.tag -width 60
9179    grid $top.tlab $top.tag -sticky w
9180    ${NS}::label $top.op -text [mc "Tag message is optional"]
9181    grid $top.op -columnspan 2 -sticky we
9182    ${NS}::label $top.mlab -text [mc "Tag message:"]
9183    ${NS}::entry $top.msg -width 60
9184    grid $top.mlab $top.msg -sticky w
9185    ${NS}::frame $top.buts
9186    ${NS}::button $top.buts.gen -text [mc "Create"] -command mktaggo
9187    ${NS}::button $top.buts.can -text [mc "Cancel"] -command mktagcan
9188    bind $top <Key-Return> mktaggo
9189    bind $top <Key-Escape> mktagcan
9190    grid $top.buts.gen $top.buts.can
9191    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9192    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9193    grid $top.buts - -pady 10 -sticky ew
9194    focus $top.tag
9195}
9196
9197proc domktag {} {
9198    global mktagtop env tagids idtags
9199
9200    set id [$mktagtop.sha1 get]
9201    set tag [$mktagtop.tag get]
9202    set msg [$mktagtop.msg get]
9203    if {$tag == {}} {
9204        error_popup [mc "No tag name specified"] $mktagtop
9205        return 0
9206    }
9207    if {[info exists tagids($tag)]} {
9208        error_popup [mc "Tag \"%s\" already exists" $tag] $mktagtop
9209        return 0
9210    }
9211    if {[catch {
9212        if {$msg != {}} {
9213            exec git tag -a -m $msg $tag $id
9214        } else {
9215            exec git tag $tag $id
9216        }
9217    } err]} {
9218        error_popup "[mc "Error creating tag:"] $err" $mktagtop
9219        return 0
9220    }
9221
9222    set tagids($tag) $id
9223    lappend idtags($id) $tag
9224    redrawtags $id
9225    addedtag $id
9226    dispneartags 0
9227    run refill_reflist
9228    return 1
9229}
9230
9231proc redrawtags {id} {
9232    global canv linehtag idpos currentid curview cmitlisted markedid
9233    global canvxmax iddrawn circleitem mainheadid circlecolors
9234    global mainheadcirclecolor
9235
9236    if {![commitinview $id $curview]} return
9237    if {![info exists iddrawn($id)]} return
9238    set row [rowofcommit $id]
9239    if {$id eq $mainheadid} {
9240        set ofill $mainheadcirclecolor
9241    } else {
9242        set ofill [lindex $circlecolors $cmitlisted($curview,$id)]
9243    }
9244    $canv itemconf $circleitem($row) -fill $ofill
9245    $canv delete tag.$id
9246    set xt [eval drawtags $id $idpos($id)]
9247    $canv coords $linehtag($id) $xt [lindex $idpos($id) 2]
9248    set text [$canv itemcget $linehtag($id) -text]
9249    set font [$canv itemcget $linehtag($id) -font]
9250    set xr [expr {$xt + [font measure $font $text]}]
9251    if {$xr > $canvxmax} {
9252        set canvxmax $xr
9253        setcanvscroll
9254    }
9255    if {[info exists currentid] && $currentid == $id} {
9256        make_secsel $id
9257    }
9258    if {[info exists markedid] && $markedid eq $id} {
9259        make_idmark $id
9260    }
9261}
9262
9263proc mktagcan {} {
9264    global mktagtop
9265
9266    catch {destroy $mktagtop}
9267    unset mktagtop
9268}
9269
9270proc mktaggo {} {
9271    if {![domktag]} return
9272    mktagcan
9273}
9274
9275proc writecommit {} {
9276    global rowmenuid wrcomtop commitinfo wrcomcmd NS
9277
9278    set top .writecommit
9279    set wrcomtop $top
9280    catch {destroy $top}
9281    ttk_toplevel $top
9282    make_transient $top .
9283    ${NS}::label $top.title -text [mc "Write commit to file"]
9284    grid $top.title - -pady 10
9285    ${NS}::label $top.id -text [mc "ID:"]
9286    ${NS}::entry $top.sha1 -width 40
9287    $top.sha1 insert 0 $rowmenuid
9288    $top.sha1 conf -state readonly
9289    grid $top.id $top.sha1 -sticky w
9290    ${NS}::entry $top.head -width 60
9291    $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9292    $top.head conf -state readonly
9293    grid x $top.head -sticky w
9294    ${NS}::label $top.clab -text [mc "Command:"]
9295    ${NS}::entry $top.cmd -width 60 -textvariable wrcomcmd
9296    grid $top.clab $top.cmd -sticky w -pady 10
9297    ${NS}::label $top.flab -text [mc "Output file:"]
9298    ${NS}::entry $top.fname -width 60
9299    $top.fname insert 0 [file normalize "commit-[string range $rowmenuid 0 6]"]
9300    grid $top.flab $top.fname -sticky w
9301    ${NS}::frame $top.buts
9302    ${NS}::button $top.buts.gen -text [mc "Write"] -command wrcomgo
9303    ${NS}::button $top.buts.can -text [mc "Cancel"] -command wrcomcan
9304    bind $top <Key-Return> wrcomgo
9305    bind $top <Key-Escape> wrcomcan
9306    grid $top.buts.gen $top.buts.can
9307    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9308    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9309    grid $top.buts - -pady 10 -sticky ew
9310    focus $top.fname
9311}
9312
9313proc wrcomgo {} {
9314    global wrcomtop
9315
9316    set id [$wrcomtop.sha1 get]
9317    set cmd "echo $id | [$wrcomtop.cmd get]"
9318    set fname [$wrcomtop.fname get]
9319    if {[catch {exec sh -c $cmd >$fname &} err]} {
9320        error_popup "[mc "Error writing commit:"] $err" $wrcomtop
9321    }
9322    catch {destroy $wrcomtop}
9323    unset wrcomtop
9324}
9325
9326proc wrcomcan {} {
9327    global wrcomtop
9328
9329    catch {destroy $wrcomtop}
9330    unset wrcomtop
9331}
9332
9333proc mkbranch {} {
9334    global rowmenuid mkbrtop NS
9335
9336    set top .makebranch
9337    catch {destroy $top}
9338    ttk_toplevel $top
9339    make_transient $top .
9340    ${NS}::label $top.title -text [mc "Create new branch"]
9341    grid $top.title - -pady 10
9342    ${NS}::label $top.id -text [mc "ID:"]
9343    ${NS}::entry $top.sha1 -width 40
9344    $top.sha1 insert 0 $rowmenuid
9345    $top.sha1 conf -state readonly
9346    grid $top.id $top.sha1 -sticky w
9347    ${NS}::label $top.nlab -text [mc "Name:"]
9348    ${NS}::entry $top.name -width 40
9349    grid $top.nlab $top.name -sticky w
9350    ${NS}::frame $top.buts
9351    ${NS}::button $top.buts.go -text [mc "Create"] -command [list mkbrgo $top]
9352    ${NS}::button $top.buts.can -text [mc "Cancel"] -command "catch {destroy $top}"
9353    bind $top <Key-Return> [list mkbrgo $top]
9354    bind $top <Key-Escape> "catch {destroy $top}"
9355    grid $top.buts.go $top.buts.can
9356    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9357    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9358    grid $top.buts - -pady 10 -sticky ew
9359    focus $top.name
9360}
9361
9362proc mkbrgo {top} {
9363    global headids idheads
9364
9365    set name [$top.name get]
9366    set id [$top.sha1 get]
9367    set cmdargs {}
9368    set old_id {}
9369    if {$name eq {}} {
9370        error_popup [mc "Please specify a name for the new branch"] $top
9371        return
9372    }
9373    if {[info exists headids($name)]} {
9374        if {![confirm_popup [mc \
9375                "Branch '%s' already exists. Overwrite?" $name] $top]} {
9376            return
9377        }
9378        set old_id $headids($name)
9379        lappend cmdargs -f
9380    }
9381    catch {destroy $top}
9382    lappend cmdargs $name $id
9383    nowbusy newbranch
9384    update
9385    if {[catch {
9386        eval exec git branch $cmdargs
9387    } err]} {
9388        notbusy newbranch
9389        error_popup $err
9390    } else {
9391        notbusy newbranch
9392        if {$old_id ne {}} {
9393            movehead $id $name
9394            movedhead $id $name
9395            redrawtags $old_id
9396            redrawtags $id
9397        } else {
9398            set headids($name) $id
9399            lappend idheads($id) $name
9400            addedhead $id $name
9401            redrawtags $id
9402        }
9403        dispneartags 0
9404        run refill_reflist
9405    }
9406}
9407
9408proc exec_citool {tool_args {baseid {}}} {
9409    global commitinfo env
9410
9411    set save_env [array get env GIT_AUTHOR_*]
9412
9413    if {$baseid ne {}} {
9414        if {![info exists commitinfo($baseid)]} {
9415            getcommit $baseid
9416        }
9417        set author [lindex $commitinfo($baseid) 1]
9418        set date [lindex $commitinfo($baseid) 2]
9419        if {[regexp {^\s*(\S.*\S|\S)\s*<(.*)>\s*$} \
9420                    $author author name email]
9421            && $date ne {}} {
9422            set env(GIT_AUTHOR_NAME) $name
9423            set env(GIT_AUTHOR_EMAIL) $email
9424            set env(GIT_AUTHOR_DATE) $date
9425        }
9426    }
9427
9428    eval exec git citool $tool_args &
9429
9430    array unset env GIT_AUTHOR_*
9431    array set env $save_env
9432}
9433
9434proc cherrypick {} {
9435    global rowmenuid curview
9436    global mainhead mainheadid
9437    global gitdir
9438
9439    set oldhead [exec git rev-parse HEAD]
9440    set dheads [descheads $rowmenuid]
9441    if {$dheads ne {} && [lsearch -exact $dheads $oldhead] >= 0} {
9442        set ok [confirm_popup [mc "Commit %s is already\
9443                included in branch %s -- really re-apply it?" \
9444                                   [string range $rowmenuid 0 7] $mainhead]]
9445        if {!$ok} return
9446    }
9447    nowbusy cherrypick [mc "Cherry-picking"]
9448    update
9449    # Unfortunately git-cherry-pick writes stuff to stderr even when
9450    # no error occurs, and exec takes that as an indication of error...
9451    if {[catch {exec sh -c "git cherry-pick -r $rowmenuid 2>&1"} err]} {
9452        notbusy cherrypick
9453        if {[regexp -line \
9454                 {Entry '(.*)' (would be overwritten by merge|not uptodate)} \
9455                 $err msg fname]} {
9456            error_popup [mc "Cherry-pick failed because of local changes\
9457                        to file '%s'.\nPlease commit, reset or stash\
9458                        your changes and try again." $fname]
9459        } elseif {[regexp -line \
9460                       {^(CONFLICT \(.*\):|Automatic cherry-pick failed|error: could not apply)} \
9461                       $err]} {
9462            if {[confirm_popup [mc "Cherry-pick failed because of merge\
9463                        conflict.\nDo you wish to run git citool to\
9464                        resolve it?"]]} {
9465                # Force citool to read MERGE_MSG
9466                file delete [file join $gitdir "GITGUI_MSG"]
9467                exec_citool {} $rowmenuid
9468            }
9469        } else {
9470            error_popup $err
9471        }
9472        run updatecommits
9473        return
9474    }
9475    set newhead [exec git rev-parse HEAD]
9476    if {$newhead eq $oldhead} {
9477        notbusy cherrypick
9478        error_popup [mc "No changes committed"]
9479        return
9480    }
9481    addnewchild $newhead $oldhead
9482    if {[commitinview $oldhead $curview]} {
9483        # XXX this isn't right if we have a path limit...
9484        insertrow $newhead $oldhead $curview
9485        if {$mainhead ne {}} {
9486            movehead $newhead $mainhead
9487            movedhead $newhead $mainhead
9488        }
9489        set mainheadid $newhead
9490        redrawtags $oldhead
9491        redrawtags $newhead
9492        selbyid $newhead
9493    }
9494    notbusy cherrypick
9495}
9496
9497proc revert {} {
9498    global rowmenuid curview
9499    global mainhead mainheadid
9500    global gitdir
9501
9502    set oldhead [exec git rev-parse HEAD]
9503    set dheads [descheads $rowmenuid]
9504    if { $dheads eq {} || [lsearch -exact $dheads $oldhead] == -1 } {
9505       set ok [confirm_popup [mc "Commit %s is not\
9506           included in branch %s -- really revert it?" \
9507                      [string range $rowmenuid 0 7] $mainhead]]
9508       if {!$ok} return
9509    }
9510    nowbusy revert [mc "Reverting"]
9511    update
9512
9513    if [catch {exec git revert --no-edit $rowmenuid} err] {
9514        notbusy revert
9515        if [regexp {files would be overwritten by merge:(\n(( |\t)+[^\n]+\n)+)}\
9516                $err match files] {
9517            regsub {\n( |\t)+} $files "\n" files
9518            error_popup [mc "Revert failed because of local changes to\
9519                the following files:%s Please commit, reset or stash \
9520                your changes and try again." $files]
9521        } elseif [regexp {error: could not revert} $err] {
9522            if [confirm_popup [mc "Revert failed because of merge conflict.\n\
9523                Do you wish to run git citool to resolve it?"]] {
9524                # Force citool to read MERGE_MSG
9525                file delete [file join $gitdir "GITGUI_MSG"]
9526                exec_citool {} $rowmenuid
9527            }
9528        } else { error_popup $err }
9529        run updatecommits
9530        return
9531    }
9532
9533    set newhead [exec git rev-parse HEAD]
9534    if { $newhead eq $oldhead } {
9535        notbusy revert
9536        error_popup [mc "No changes committed"]
9537        return
9538    }
9539
9540    addnewchild $newhead $oldhead
9541
9542    if [commitinview $oldhead $curview] {
9543        # XXX this isn't right if we have a path limit...
9544        insertrow $newhead $oldhead $curview
9545        if {$mainhead ne {}} {
9546            movehead $newhead $mainhead
9547            movedhead $newhead $mainhead
9548        }
9549        set mainheadid $newhead
9550        redrawtags $oldhead
9551        redrawtags $newhead
9552        selbyid $newhead
9553    }
9554
9555    notbusy revert
9556}
9557
9558proc resethead {} {
9559    global mainhead rowmenuid confirm_ok resettype NS
9560
9561    set confirm_ok 0
9562    set w ".confirmreset"
9563    ttk_toplevel $w
9564    make_transient $w .
9565    wm title $w [mc "Confirm reset"]
9566    ${NS}::label $w.m -text \
9567        [mc "Reset branch %s to %s?" $mainhead [string range $rowmenuid 0 7]]
9568    pack $w.m -side top -fill x -padx 20 -pady 20
9569    ${NS}::labelframe $w.f -text [mc "Reset type:"]
9570    set resettype mixed
9571    ${NS}::radiobutton $w.f.soft -value soft -variable resettype \
9572        -text [mc "Soft: Leave working tree and index untouched"]
9573    grid $w.f.soft -sticky w
9574    ${NS}::radiobutton $w.f.mixed -value mixed -variable resettype \
9575        -text [mc "Mixed: Leave working tree untouched, reset index"]
9576    grid $w.f.mixed -sticky w
9577    ${NS}::radiobutton $w.f.hard -value hard -variable resettype \
9578        -text [mc "Hard: Reset working tree and index\n(discard ALL local changes)"]
9579    grid $w.f.hard -sticky w
9580    pack $w.f -side top -fill x -padx 4
9581    ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
9582    pack $w.ok -side left -fill x -padx 20 -pady 20
9583    ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
9584    bind $w <Key-Escape> [list destroy $w]
9585    pack $w.cancel -side right -fill x -padx 20 -pady 20
9586    bind $w <Visibility> "grab $w; focus $w"
9587    tkwait window $w
9588    if {!$confirm_ok} return
9589    if {[catch {set fd [open \
9590            [list | git reset --$resettype $rowmenuid 2>@1] r]} err]} {
9591        error_popup $err
9592    } else {
9593        dohidelocalchanges
9594        filerun $fd [list readresetstat $fd]
9595        nowbusy reset [mc "Resetting"]
9596        selbyid $rowmenuid
9597    }
9598}
9599
9600proc readresetstat {fd} {
9601    global mainhead mainheadid showlocalchanges rprogcoord
9602
9603    if {[gets $fd line] >= 0} {
9604        if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9605            set rprogcoord [expr {1.0 * $m / $n}]
9606            adjustprogress
9607        }
9608        return 1
9609    }
9610    set rprogcoord 0
9611    adjustprogress
9612    notbusy reset
9613    if {[catch {close $fd} err]} {
9614        error_popup $err
9615    }
9616    set oldhead $mainheadid
9617    set newhead [exec git rev-parse HEAD]
9618    if {$newhead ne $oldhead} {
9619        movehead $newhead $mainhead
9620        movedhead $newhead $mainhead
9621        set mainheadid $newhead
9622        redrawtags $oldhead
9623        redrawtags $newhead
9624    }
9625    if {$showlocalchanges} {
9626        doshowlocalchanges
9627    }
9628    return 0
9629}
9630
9631# context menu for a head
9632proc headmenu {x y id head} {
9633    global headmenuid headmenuhead headctxmenu mainhead
9634
9635    stopfinding
9636    set headmenuid $id
9637    set headmenuhead $head
9638    set state normal
9639    if {[string match "remotes/*" $head]} {
9640        set state disabled
9641    }
9642    if {$head eq $mainhead} {
9643        set state disabled
9644    }
9645    $headctxmenu entryconfigure 0 -state $state
9646    $headctxmenu entryconfigure 1 -state $state
9647    tk_popup $headctxmenu $x $y
9648}
9649
9650proc cobranch {} {
9651    global headmenuid headmenuhead headids
9652    global showlocalchanges
9653
9654    # check the tree is clean first??
9655    nowbusy checkout [mc "Checking out"]
9656    update
9657    dohidelocalchanges
9658    if {[catch {
9659        set fd [open [list | git checkout $headmenuhead 2>@1] r]
9660    } err]} {
9661        notbusy checkout
9662        error_popup $err
9663        if {$showlocalchanges} {
9664            dodiffindex
9665        }
9666    } else {
9667        filerun $fd [list readcheckoutstat $fd $headmenuhead $headmenuid]
9668    }
9669}
9670
9671proc readcheckoutstat {fd newhead newheadid} {
9672    global mainhead mainheadid headids showlocalchanges progresscoords
9673    global viewmainheadid curview
9674
9675    if {[gets $fd line] >= 0} {
9676        if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9677            set progresscoords [list 0 [expr {1.0 * $m / $n}]]
9678            adjustprogress
9679        }
9680        return 1
9681    }
9682    set progresscoords {0 0}
9683    adjustprogress
9684    notbusy checkout
9685    if {[catch {close $fd} err]} {
9686        error_popup $err
9687    }
9688    set oldmainid $mainheadid
9689    set mainhead $newhead
9690    set mainheadid $newheadid
9691    set viewmainheadid($curview) $newheadid
9692    redrawtags $oldmainid
9693    redrawtags $newheadid
9694    selbyid $newheadid
9695    if {$showlocalchanges} {
9696        dodiffindex
9697    }
9698}
9699
9700proc rmbranch {} {
9701    global headmenuid headmenuhead mainhead
9702    global idheads
9703
9704    set head $headmenuhead
9705    set id $headmenuid
9706    # this check shouldn't be needed any more...
9707    if {$head eq $mainhead} {
9708        error_popup [mc "Cannot delete the currently checked-out branch"]
9709        return
9710    }
9711    set dheads [descheads $id]
9712    if {[llength $dheads] == 1 && $idheads($dheads) eq $head} {
9713        # the stuff on this branch isn't on any other branch
9714        if {![confirm_popup [mc "The commits on branch %s aren't on any other\
9715                        branch.\nReally delete branch %s?" $head $head]]} return
9716    }
9717    nowbusy rmbranch
9718    update
9719    if {[catch {exec git branch -D $head} err]} {
9720        notbusy rmbranch
9721        error_popup $err
9722        return
9723    }
9724    removehead $id $head
9725    removedhead $id $head
9726    redrawtags $id
9727    notbusy rmbranch
9728    dispneartags 0
9729    run refill_reflist
9730}
9731
9732# Display a list of tags and heads
9733proc showrefs {} {
9734    global showrefstop bgcolor fgcolor selectbgcolor NS
9735    global bglist fglist reflistfilter reflist maincursor
9736
9737    set top .showrefs
9738    set showrefstop $top
9739    if {[winfo exists $top]} {
9740        raise $top
9741        refill_reflist
9742        return
9743    }
9744    ttk_toplevel $top
9745    wm title $top [mc "Tags and heads: %s" [file tail [pwd]]]
9746    make_transient $top .
9747    text $top.list -background $bgcolor -foreground $fgcolor \
9748        -selectbackground $selectbgcolor -font mainfont \
9749        -xscrollcommand "$top.xsb set" -yscrollcommand "$top.ysb set" \
9750        -width 30 -height 20 -cursor $maincursor \
9751        -spacing1 1 -spacing3 1 -state disabled
9752    $top.list tag configure highlight -background $selectbgcolor
9753    lappend bglist $top.list
9754    lappend fglist $top.list
9755    ${NS}::scrollbar $top.ysb -command "$top.list yview" -orient vertical
9756    ${NS}::scrollbar $top.xsb -command "$top.list xview" -orient horizontal
9757    grid $top.list $top.ysb -sticky nsew
9758    grid $top.xsb x -sticky ew
9759    ${NS}::frame $top.f
9760    ${NS}::label $top.f.l -text "[mc "Filter"]: "
9761    ${NS}::entry $top.f.e -width 20 -textvariable reflistfilter
9762    set reflistfilter "*"
9763    trace add variable reflistfilter write reflistfilter_change
9764    pack $top.f.e -side right -fill x -expand 1
9765    pack $top.f.l -side left
9766    grid $top.f - -sticky ew -pady 2
9767    ${NS}::button $top.close -command [list destroy $top] -text [mc "Close"]
9768    bind $top <Key-Escape> [list destroy $top]
9769    grid $top.close -
9770    grid columnconfigure $top 0 -weight 1
9771    grid rowconfigure $top 0 -weight 1
9772    bind $top.list <1> {break}
9773    bind $top.list <B1-Motion> {break}
9774    bind $top.list <ButtonRelease-1> {sel_reflist %W %x %y; break}
9775    set reflist {}
9776    refill_reflist
9777}
9778
9779proc sel_reflist {w x y} {
9780    global showrefstop reflist headids tagids otherrefids
9781
9782    if {![winfo exists $showrefstop]} return
9783    set l [lindex [split [$w index "@$x,$y"] "."] 0]
9784    set ref [lindex $reflist [expr {$l-1}]]
9785    set n [lindex $ref 0]
9786    switch -- [lindex $ref 1] {
9787        "H" {selbyid $headids($n)}
9788        "T" {selbyid $tagids($n)}
9789        "o" {selbyid $otherrefids($n)}
9790    }
9791    $showrefstop.list tag add highlight $l.0 "$l.0 lineend"
9792}
9793
9794proc unsel_reflist {} {
9795    global showrefstop
9796
9797    if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9798    $showrefstop.list tag remove highlight 0.0 end
9799}
9800
9801proc reflistfilter_change {n1 n2 op} {
9802    global reflistfilter
9803
9804    after cancel refill_reflist
9805    after 200 refill_reflist
9806}
9807
9808proc refill_reflist {} {
9809    global reflist reflistfilter showrefstop headids tagids otherrefids
9810    global curview
9811
9812    if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9813    set refs {}
9814    foreach n [array names headids] {
9815        if {[string match $reflistfilter $n]} {
9816            if {[commitinview $headids($n) $curview]} {
9817                lappend refs [list $n H]
9818            } else {
9819                interestedin $headids($n) {run refill_reflist}
9820            }
9821        }
9822    }
9823    foreach n [array names tagids] {
9824        if {[string match $reflistfilter $n]} {
9825            if {[commitinview $tagids($n) $curview]} {
9826                lappend refs [list $n T]
9827            } else {
9828                interestedin $tagids($n) {run refill_reflist}
9829            }
9830        }
9831    }
9832    foreach n [array names otherrefids] {
9833        if {[string match $reflistfilter $n]} {
9834            if {[commitinview $otherrefids($n) $curview]} {
9835                lappend refs [list $n o]
9836            } else {
9837                interestedin $otherrefids($n) {run refill_reflist}
9838            }
9839        }
9840    }
9841    set refs [lsort -index 0 $refs]
9842    if {$refs eq $reflist} return
9843
9844    # Update the contents of $showrefstop.list according to the
9845    # differences between $reflist (old) and $refs (new)
9846    $showrefstop.list conf -state normal
9847    $showrefstop.list insert end "\n"
9848    set i 0
9849    set j 0
9850    while {$i < [llength $reflist] || $j < [llength $refs]} {
9851        if {$i < [llength $reflist]} {
9852            if {$j < [llength $refs]} {
9853                set cmp [string compare [lindex $reflist $i 0] \
9854                             [lindex $refs $j 0]]
9855                if {$cmp == 0} {
9856                    set cmp [string compare [lindex $reflist $i 1] \
9857                                 [lindex $refs $j 1]]
9858                }
9859            } else {
9860                set cmp -1
9861            }
9862        } else {
9863            set cmp 1
9864        }
9865        switch -- $cmp {
9866            -1 {
9867                $showrefstop.list delete "[expr {$j+1}].0" "[expr {$j+2}].0"
9868                incr i
9869            }
9870            0 {
9871                incr i
9872                incr j
9873            }
9874            1 {
9875                set l [expr {$j + 1}]
9876                $showrefstop.list image create $l.0 -align baseline \
9877                    -image reficon-[lindex $refs $j 1] -padx 2
9878                $showrefstop.list insert $l.1 "[lindex $refs $j 0]\n"
9879                incr j
9880            }
9881        }
9882    }
9883    set reflist $refs
9884    # delete last newline
9885    $showrefstop.list delete end-2c end-1c
9886    $showrefstop.list conf -state disabled
9887}
9888
9889# Stuff for finding nearby tags
9890proc getallcommits {} {
9891    global allcommits nextarc seeds allccache allcwait cachedarcs allcupdate
9892    global idheads idtags idotherrefs allparents tagobjid
9893    global gitdir
9894
9895    if {![info exists allcommits]} {
9896        set nextarc 0
9897        set allcommits 0
9898        set seeds {}
9899        set allcwait 0
9900        set cachedarcs 0
9901        set allccache [file join $gitdir "gitk.cache"]
9902        if {![catch {
9903            set f [open $allccache r]
9904            set allcwait 1
9905            getcache $f
9906        }]} return
9907    }
9908
9909    if {$allcwait} {
9910        return
9911    }
9912    set cmd [list | git rev-list --parents]
9913    set allcupdate [expr {$seeds ne {}}]
9914    if {!$allcupdate} {
9915        set ids "--all"
9916    } else {
9917        set refs [concat [array names idheads] [array names idtags] \
9918                      [array names idotherrefs]]
9919        set ids {}
9920        set tagobjs {}
9921        foreach name [array names tagobjid] {
9922            lappend tagobjs $tagobjid($name)
9923        }
9924        foreach id [lsort -unique $refs] {
9925            if {![info exists allparents($id)] &&
9926                [lsearch -exact $tagobjs $id] < 0} {
9927                lappend ids $id
9928            }
9929        }
9930        if {$ids ne {}} {
9931            foreach id $seeds {
9932                lappend ids "^$id"
9933            }
9934        }
9935    }
9936    if {$ids ne {}} {
9937        set fd [open [concat $cmd $ids] r]
9938        fconfigure $fd -blocking 0
9939        incr allcommits
9940        nowbusy allcommits
9941        filerun $fd [list getallclines $fd]
9942    } else {
9943        dispneartags 0
9944    }
9945}
9946
9947# Since most commits have 1 parent and 1 child, we group strings of
9948# such commits into "arcs" joining branch/merge points (BMPs), which
9949# are commits that either don't have 1 parent or don't have 1 child.
9950#
9951# arcnos(id) - incoming arcs for BMP, arc we're on for other nodes
9952# arcout(id) - outgoing arcs for BMP
9953# arcids(a) - list of IDs on arc including end but not start
9954# arcstart(a) - BMP ID at start of arc
9955# arcend(a) - BMP ID at end of arc
9956# growing(a) - arc a is still growing
9957# arctags(a) - IDs out of arcids (excluding end) that have tags
9958# archeads(a) - IDs out of arcids (excluding end) that have heads
9959# The start of an arc is at the descendent end, so "incoming" means
9960# coming from descendents, and "outgoing" means going towards ancestors.
9961
9962proc getallclines {fd} {
9963    global allparents allchildren idtags idheads nextarc
9964    global arcnos arcids arctags arcout arcend arcstart archeads growing
9965    global seeds allcommits cachedarcs allcupdate
9966
9967    set nid 0
9968    while {[incr nid] <= 1000 && [gets $fd line] >= 0} {
9969        set id [lindex $line 0]
9970        if {[info exists allparents($id)]} {
9971            # seen it already
9972            continue
9973        }
9974        set cachedarcs 0
9975        set olds [lrange $line 1 end]
9976        set allparents($id) $olds
9977        if {![info exists allchildren($id)]} {
9978            set allchildren($id) {}
9979            set arcnos($id) {}
9980            lappend seeds $id
9981        } else {
9982            set a $arcnos($id)
9983            if {[llength $olds] == 1 && [llength $a] == 1} {
9984                lappend arcids($a) $id
9985                if {[info exists idtags($id)]} {
9986                    lappend arctags($a) $id
9987                }
9988                if {[info exists idheads($id)]} {
9989                    lappend archeads($a) $id
9990                }
9991                if {[info exists allparents($olds)]} {
9992                    # seen parent already
9993                    if {![info exists arcout($olds)]} {
9994                        splitarc $olds
9995                    }
9996                    lappend arcids($a) $olds
9997                    set arcend($a) $olds
9998                    unset growing($a)
9999                }
10000                lappend allchildren($olds) $id
10001                lappend arcnos($olds) $a
10002                continue
10003            }
10004        }
10005        foreach a $arcnos($id) {
10006            lappend arcids($a) $id
10007            set arcend($a) $id
10008            unset growing($a)
10009        }
10010
10011        set ao {}
10012        foreach p $olds {
10013            lappend allchildren($p) $id
10014            set a [incr nextarc]
10015            set arcstart($a) $id
10016            set archeads($a) {}
10017            set arctags($a) {}
10018            set archeads($a) {}
10019            set arcids($a) {}
10020            lappend ao $a
10021            set growing($a) 1
10022            if {[info exists allparents($p)]} {
10023                # seen it already, may need to make a new branch
10024                if {![info exists arcout($p)]} {
10025                    splitarc $p
10026                }
10027                lappend arcids($a) $p
10028                set arcend($a) $p
10029                unset growing($a)
10030            }
10031            lappend arcnos($p) $a
10032        }
10033        set arcout($id) $ao
10034    }
10035    if {$nid > 0} {
10036        global cached_dheads cached_dtags cached_atags
10037        catch {unset cached_dheads}
10038        catch {unset cached_dtags}
10039        catch {unset cached_atags}
10040    }
10041    if {![eof $fd]} {
10042        return [expr {$nid >= 1000? 2: 1}]
10043    }
10044    set cacheok 1
10045    if {[catch {
10046        fconfigure $fd -blocking 1
10047        close $fd
10048    } err]} {
10049        # got an error reading the list of commits
10050        # if we were updating, try rereading the whole thing again
10051        if {$allcupdate} {
10052            incr allcommits -1
10053            dropcache $err
10054            return
10055        }
10056        error_popup "[mc "Error reading commit topology information;\
10057                branch and preceding/following tag information\
10058                will be incomplete."]\n($err)"
10059        set cacheok 0
10060    }
10061    if {[incr allcommits -1] == 0} {
10062        notbusy allcommits
10063        if {$cacheok} {
10064            run savecache
10065        }
10066    }
10067    dispneartags 0
10068    return 0
10069}
10070
10071proc recalcarc {a} {
10072    global arctags archeads arcids idtags idheads
10073
10074    set at {}
10075    set ah {}
10076    foreach id [lrange $arcids($a) 0 end-1] {
10077        if {[info exists idtags($id)]} {
10078            lappend at $id
10079        }
10080        if {[info exists idheads($id)]} {
10081            lappend ah $id
10082        }
10083    }
10084    set arctags($a) $at
10085    set archeads($a) $ah
10086}
10087
10088proc splitarc {p} {
10089    global arcnos arcids nextarc arctags archeads idtags idheads
10090    global arcstart arcend arcout allparents growing
10091
10092    set a $arcnos($p)
10093    if {[llength $a] != 1} {
10094        puts "oops splitarc called but [llength $a] arcs already"
10095        return
10096    }
10097    set a [lindex $a 0]
10098    set i [lsearch -exact $arcids($a) $p]
10099    if {$i < 0} {
10100        puts "oops splitarc $p not in arc $a"
10101        return
10102    }
10103    set na [incr nextarc]
10104    if {[info exists arcend($a)]} {
10105        set arcend($na) $arcend($a)
10106    } else {
10107        set l [lindex $allparents([lindex $arcids($a) end]) 0]
10108        set j [lsearch -exact $arcnos($l) $a]
10109        set arcnos($l) [lreplace $arcnos($l) $j $j $na]
10110    }
10111    set tail [lrange $arcids($a) [expr {$i+1}] end]
10112    set arcids($a) [lrange $arcids($a) 0 $i]
10113    set arcend($a) $p
10114    set arcstart($na) $p
10115    set arcout($p) $na
10116    set arcids($na) $tail
10117    if {[info exists growing($a)]} {
10118        set growing($na) 1
10119        unset growing($a)
10120    }
10121
10122    foreach id $tail {
10123        if {[llength $arcnos($id)] == 1} {
10124            set arcnos($id) $na
10125        } else {
10126            set j [lsearch -exact $arcnos($id) $a]
10127            set arcnos($id) [lreplace $arcnos($id) $j $j $na]
10128        }
10129    }
10130
10131    # reconstruct tags and heads lists
10132    if {$arctags($a) ne {} || $archeads($a) ne {}} {
10133        recalcarc $a
10134        recalcarc $na
10135    } else {
10136        set arctags($na) {}
10137        set archeads($na) {}
10138    }
10139}
10140
10141# Update things for a new commit added that is a child of one
10142# existing commit.  Used when cherry-picking.
10143proc addnewchild {id p} {
10144    global allparents allchildren idtags nextarc
10145    global arcnos arcids arctags arcout arcend arcstart archeads growing
10146    global seeds allcommits
10147
10148    if {![info exists allcommits] || ![info exists arcnos($p)]} return
10149    set allparents($id) [list $p]
10150    set allchildren($id) {}
10151    set arcnos($id) {}
10152    lappend seeds $id
10153    lappend allchildren($p) $id
10154    set a [incr nextarc]
10155    set arcstart($a) $id
10156    set archeads($a) {}
10157    set arctags($a) {}
10158    set arcids($a) [list $p]
10159    set arcend($a) $p
10160    if {![info exists arcout($p)]} {
10161        splitarc $p
10162    }
10163    lappend arcnos($p) $a
10164    set arcout($id) [list $a]
10165}
10166
10167# This implements a cache for the topology information.
10168# The cache saves, for each arc, the start and end of the arc,
10169# the ids on the arc, and the outgoing arcs from the end.
10170proc readcache {f} {
10171    global arcnos arcids arcout arcstart arcend arctags archeads nextarc
10172    global idtags idheads allparents cachedarcs possible_seeds seeds growing
10173    global allcwait
10174
10175    set a $nextarc
10176    set lim $cachedarcs
10177    if {$lim - $a > 500} {
10178        set lim [expr {$a + 500}]
10179    }
10180    if {[catch {
10181        if {$a == $lim} {
10182            # finish reading the cache and setting up arctags, etc.
10183            set line [gets $f]
10184            if {$line ne "1"} {error "bad final version"}
10185            close $f
10186            foreach id [array names idtags] {
10187                if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10188                    [llength $allparents($id)] == 1} {
10189                    set a [lindex $arcnos($id) 0]
10190                    if {$arctags($a) eq {}} {
10191                        recalcarc $a
10192                    }
10193                }
10194            }
10195            foreach id [array names idheads] {
10196                if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10197                    [llength $allparents($id)] == 1} {
10198                    set a [lindex $arcnos($id) 0]
10199                    if {$archeads($a) eq {}} {
10200                        recalcarc $a
10201                    }
10202                }
10203            }
10204            foreach id [lsort -unique $possible_seeds] {
10205                if {$arcnos($id) eq {}} {
10206                    lappend seeds $id
10207                }
10208            }
10209            set allcwait 0
10210        } else {
10211            while {[incr a] <= $lim} {
10212                set line [gets $f]
10213                if {[llength $line] != 3} {error "bad line"}
10214                set s [lindex $line 0]
10215                set arcstart($a) $s
10216                lappend arcout($s) $a
10217                if {![info exists arcnos($s)]} {
10218                    lappend possible_seeds $s
10219                    set arcnos($s) {}
10220                }
10221                set e [lindex $line 1]
10222                if {$e eq {}} {
10223                    set growing($a) 1
10224                } else {
10225                    set arcend($a) $e
10226                    if {![info exists arcout($e)]} {
10227                        set arcout($e) {}
10228                    }
10229                }
10230                set arcids($a) [lindex $line 2]
10231                foreach id $arcids($a) {
10232                    lappend allparents($s) $id
10233                    set s $id
10234                    lappend arcnos($id) $a
10235                }
10236                if {![info exists allparents($s)]} {
10237                    set allparents($s) {}
10238                }
10239                set arctags($a) {}
10240                set archeads($a) {}
10241            }
10242            set nextarc [expr {$a - 1}]
10243        }
10244    } err]} {
10245        dropcache $err
10246        return 0
10247    }
10248    if {!$allcwait} {
10249        getallcommits
10250    }
10251    return $allcwait
10252}
10253
10254proc getcache {f} {
10255    global nextarc cachedarcs possible_seeds
10256
10257    if {[catch {
10258        set line [gets $f]
10259        if {[llength $line] != 2 || [lindex $line 0] ne "1"} {error "bad version"}
10260        # make sure it's an integer
10261        set cachedarcs [expr {int([lindex $line 1])}]
10262        if {$cachedarcs < 0} {error "bad number of arcs"}
10263        set nextarc 0
10264        set possible_seeds {}
10265        run readcache $f
10266    } err]} {
10267        dropcache $err
10268    }
10269    return 0
10270}
10271
10272proc dropcache {err} {
10273    global allcwait nextarc cachedarcs seeds
10274
10275    #puts "dropping cache ($err)"
10276    foreach v {arcnos arcout arcids arcstart arcend growing \
10277                   arctags archeads allparents allchildren} {
10278        global $v
10279        catch {unset $v}
10280    }
10281    set allcwait 0
10282    set nextarc 0
10283    set cachedarcs 0
10284    set seeds {}
10285    getallcommits
10286}
10287
10288proc writecache {f} {
10289    global cachearc cachedarcs allccache
10290    global arcstart arcend arcnos arcids arcout
10291
10292    set a $cachearc
10293    set lim $cachedarcs
10294    if {$lim - $a > 1000} {
10295        set lim [expr {$a + 1000}]
10296    }
10297    if {[catch {
10298        while {[incr a] <= $lim} {
10299            if {[info exists arcend($a)]} {
10300                puts $f [list $arcstart($a) $arcend($a) $arcids($a)]
10301            } else {
10302                puts $f [list $arcstart($a) {} $arcids($a)]
10303            }
10304        }
10305    } err]} {
10306        catch {close $f}
10307        catch {file delete $allccache}
10308        #puts "writing cache failed ($err)"
10309        return 0
10310    }
10311    set cachearc [expr {$a - 1}]
10312    if {$a > $cachedarcs} {
10313        puts $f "1"
10314        close $f
10315        return 0
10316    }
10317    return 1
10318}
10319
10320proc savecache {} {
10321    global nextarc cachedarcs cachearc allccache
10322
10323    if {$nextarc == $cachedarcs} return
10324    set cachearc 0
10325    set cachedarcs $nextarc
10326    catch {
10327        set f [open $allccache w]
10328        puts $f [list 1 $cachedarcs]
10329        run writecache $f
10330    }
10331}
10332
10333# Returns 1 if a is an ancestor of b, -1 if b is an ancestor of a,
10334# or 0 if neither is true.
10335proc anc_or_desc {a b} {
10336    global arcout arcstart arcend arcnos cached_isanc
10337
10338    if {$arcnos($a) eq $arcnos($b)} {
10339        # Both are on the same arc(s); either both are the same BMP,
10340        # or if one is not a BMP, the other is also not a BMP or is
10341        # the BMP at end of the arc (and it only has 1 incoming arc).
10342        # Or both can be BMPs with no incoming arcs.
10343        if {$a eq $b || $arcnos($a) eq {}} {
10344            return 0
10345        }
10346        # assert {[llength $arcnos($a)] == 1}
10347        set arc [lindex $arcnos($a) 0]
10348        set i [lsearch -exact $arcids($arc) $a]
10349        set j [lsearch -exact $arcids($arc) $b]
10350        if {$i < 0 || $i > $j} {
10351            return 1
10352        } else {
10353            return -1
10354        }
10355    }
10356
10357    if {![info exists arcout($a)]} {
10358        set arc [lindex $arcnos($a) 0]
10359        if {[info exists arcend($arc)]} {
10360            set aend $arcend($arc)
10361        } else {
10362            set aend {}
10363        }
10364        set a $arcstart($arc)
10365    } else {
10366        set aend $a
10367    }
10368    if {![info exists arcout($b)]} {
10369        set arc [lindex $arcnos($b) 0]
10370        if {[info exists arcend($arc)]} {
10371            set bend $arcend($arc)
10372        } else {
10373            set bend {}
10374        }
10375        set b $arcstart($arc)
10376    } else {
10377        set bend $b
10378    }
10379    if {$a eq $bend} {
10380        return 1
10381    }
10382    if {$b eq $aend} {
10383        return -1
10384    }
10385    if {[info exists cached_isanc($a,$bend)]} {
10386        if {$cached_isanc($a,$bend)} {
10387            return 1
10388        }
10389    }
10390    if {[info exists cached_isanc($b,$aend)]} {
10391        if {$cached_isanc($b,$aend)} {
10392            return -1
10393        }
10394        if {[info exists cached_isanc($a,$bend)]} {
10395            return 0
10396        }
10397    }
10398
10399    set todo [list $a $b]
10400    set anc($a) a
10401    set anc($b) b
10402    for {set i 0} {$i < [llength $todo]} {incr i} {
10403        set x [lindex $todo $i]
10404        if {$anc($x) eq {}} {
10405            continue
10406        }
10407        foreach arc $arcnos($x) {
10408            set xd $arcstart($arc)
10409            if {$xd eq $bend} {
10410                set cached_isanc($a,$bend) 1
10411                set cached_isanc($b,$aend) 0
10412                return 1
10413            } elseif {$xd eq $aend} {
10414                set cached_isanc($b,$aend) 1
10415                set cached_isanc($a,$bend) 0
10416                return -1
10417            }
10418            if {![info exists anc($xd)]} {
10419                set anc($xd) $anc($x)
10420                lappend todo $xd
10421            } elseif {$anc($xd) ne $anc($x)} {
10422                set anc($xd) {}
10423            }
10424        }
10425    }
10426    set cached_isanc($a,$bend) 0
10427    set cached_isanc($b,$aend) 0
10428    return 0
10429}
10430
10431# This identifies whether $desc has an ancestor that is
10432# a growing tip of the graph and which is not an ancestor of $anc
10433# and returns 0 if so and 1 if not.
10434# If we subsequently discover a tag on such a growing tip, and that
10435# turns out to be a descendent of $anc (which it could, since we
10436# don't necessarily see children before parents), then $desc
10437# isn't a good choice to display as a descendent tag of
10438# $anc (since it is the descendent of another tag which is
10439# a descendent of $anc).  Similarly, $anc isn't a good choice to
10440# display as a ancestor tag of $desc.
10441#
10442proc is_certain {desc anc} {
10443    global arcnos arcout arcstart arcend growing problems
10444
10445    set certain {}
10446    if {[llength $arcnos($anc)] == 1} {
10447        # tags on the same arc are certain
10448        if {$arcnos($desc) eq $arcnos($anc)} {
10449            return 1
10450        }
10451        if {![info exists arcout($anc)]} {
10452            # if $anc is partway along an arc, use the start of the arc instead
10453            set a [lindex $arcnos($anc) 0]
10454            set anc $arcstart($a)
10455        }
10456    }
10457    if {[llength $arcnos($desc)] > 1 || [info exists arcout($desc)]} {
10458        set x $desc
10459    } else {
10460        set a [lindex $arcnos($desc) 0]
10461        set x $arcend($a)
10462    }
10463    if {$x == $anc} {
10464        return 1
10465    }
10466    set anclist [list $x]
10467    set dl($x) 1
10468    set nnh 1
10469    set ngrowanc 0
10470    for {set i 0} {$i < [llength $anclist] && ($nnh > 0 || $ngrowanc > 0)} {incr i} {
10471        set x [lindex $anclist $i]
10472        if {$dl($x)} {
10473            incr nnh -1
10474        }
10475        set done($x) 1
10476        foreach a $arcout($x) {
10477            if {[info exists growing($a)]} {
10478                if {![info exists growanc($x)] && $dl($x)} {
10479                    set growanc($x) 1
10480                    incr ngrowanc
10481                }
10482            } else {
10483                set y $arcend($a)
10484                if {[info exists dl($y)]} {
10485                    if {$dl($y)} {
10486                        if {!$dl($x)} {
10487                            set dl($y) 0
10488                            if {![info exists done($y)]} {
10489                                incr nnh -1
10490                            }
10491                            if {[info exists growanc($x)]} {
10492                                incr ngrowanc -1
10493                            }
10494                            set xl [list $y]
10495                            for {set k 0} {$k < [llength $xl]} {incr k} {
10496                                set z [lindex $xl $k]
10497                                foreach c $arcout($z) {
10498                                    if {[info exists arcend($c)]} {
10499                                        set v $arcend($c)
10500                                        if {[info exists dl($v)] && $dl($v)} {
10501                                            set dl($v) 0
10502                                            if {![info exists done($v)]} {
10503                                                incr nnh -1
10504                                            }
10505                                            if {[info exists growanc($v)]} {
10506                                                incr ngrowanc -1
10507                                            }
10508                                            lappend xl $v
10509                                        }
10510                                    }
10511                                }
10512                            }
10513                        }
10514                    }
10515                } elseif {$y eq $anc || !$dl($x)} {
10516                    set dl($y) 0
10517                    lappend anclist $y
10518                } else {
10519                    set dl($y) 1
10520                    lappend anclist $y
10521                    incr nnh
10522                }
10523            }
10524        }
10525    }
10526    foreach x [array names growanc] {
10527        if {$dl($x)} {
10528            return 0
10529        }
10530        return 0
10531    }
10532    return 1
10533}
10534
10535proc validate_arctags {a} {
10536    global arctags idtags
10537
10538    set i -1
10539    set na $arctags($a)
10540    foreach id $arctags($a) {
10541        incr i
10542        if {![info exists idtags($id)]} {
10543            set na [lreplace $na $i $i]
10544            incr i -1
10545        }
10546    }
10547    set arctags($a) $na
10548}
10549
10550proc validate_archeads {a} {
10551    global archeads idheads
10552
10553    set i -1
10554    set na $archeads($a)
10555    foreach id $archeads($a) {
10556        incr i
10557        if {![info exists idheads($id)]} {
10558            set na [lreplace $na $i $i]
10559            incr i -1
10560        }
10561    }
10562    set archeads($a) $na
10563}
10564
10565# Return the list of IDs that have tags that are descendents of id,
10566# ignoring IDs that are descendents of IDs already reported.
10567proc desctags {id} {
10568    global arcnos arcstart arcids arctags idtags allparents
10569    global growing cached_dtags
10570
10571    if {![info exists allparents($id)]} {
10572        return {}
10573    }
10574    set t1 [clock clicks -milliseconds]
10575    set argid $id
10576    if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10577        # part-way along an arc; check that arc first
10578        set a [lindex $arcnos($id) 0]
10579        if {$arctags($a) ne {}} {
10580            validate_arctags $a
10581            set i [lsearch -exact $arcids($a) $id]
10582            set tid {}
10583            foreach t $arctags($a) {
10584                set j [lsearch -exact $arcids($a) $t]
10585                if {$j >= $i} break
10586                set tid $t
10587            }
10588            if {$tid ne {}} {
10589                return $tid
10590            }
10591        }
10592        set id $arcstart($a)
10593        if {[info exists idtags($id)]} {
10594            return $id
10595        }
10596    }
10597    if {[info exists cached_dtags($id)]} {
10598        return $cached_dtags($id)
10599    }
10600
10601    set origid $id
10602    set todo [list $id]
10603    set queued($id) 1
10604    set nc 1
10605    for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10606        set id [lindex $todo $i]
10607        set done($id) 1
10608        set ta [info exists hastaggedancestor($id)]
10609        if {!$ta} {
10610            incr nc -1
10611        }
10612        # ignore tags on starting node
10613        if {!$ta && $i > 0} {
10614            if {[info exists idtags($id)]} {
10615                set tagloc($id) $id
10616                set ta 1
10617            } elseif {[info exists cached_dtags($id)]} {
10618                set tagloc($id) $cached_dtags($id)
10619                set ta 1
10620            }
10621        }
10622        foreach a $arcnos($id) {
10623            set d $arcstart($a)
10624            if {!$ta && $arctags($a) ne {}} {
10625                validate_arctags $a
10626                if {$arctags($a) ne {}} {
10627                    lappend tagloc($id) [lindex $arctags($a) end]
10628                }
10629            }
10630            if {$ta || $arctags($a) ne {}} {
10631                set tomark [list $d]
10632                for {set j 0} {$j < [llength $tomark]} {incr j} {
10633                    set dd [lindex $tomark $j]
10634                    if {![info exists hastaggedancestor($dd)]} {
10635                        if {[info exists done($dd)]} {
10636                            foreach b $arcnos($dd) {
10637                                lappend tomark $arcstart($b)
10638                            }
10639                            if {[info exists tagloc($dd)]} {
10640                                unset tagloc($dd)
10641                            }
10642                        } elseif {[info exists queued($dd)]} {
10643                            incr nc -1
10644                        }
10645                        set hastaggedancestor($dd) 1
10646                    }
10647                }
10648            }
10649            if {![info exists queued($d)]} {
10650                lappend todo $d
10651                set queued($d) 1
10652                if {![info exists hastaggedancestor($d)]} {
10653                    incr nc
10654                }
10655            }
10656        }
10657    }
10658    set tags {}
10659    foreach id [array names tagloc] {
10660        if {![info exists hastaggedancestor($id)]} {
10661            foreach t $tagloc($id) {
10662                if {[lsearch -exact $tags $t] < 0} {
10663                    lappend tags $t
10664                }
10665            }
10666        }
10667    }
10668    set t2 [clock clicks -milliseconds]
10669    set loopix $i
10670
10671    # remove tags that are descendents of other tags
10672    for {set i 0} {$i < [llength $tags]} {incr i} {
10673        set a [lindex $tags $i]
10674        for {set j 0} {$j < $i} {incr j} {
10675            set b [lindex $tags $j]
10676            set r [anc_or_desc $a $b]
10677            if {$r == 1} {
10678                set tags [lreplace $tags $j $j]
10679                incr j -1
10680                incr i -1
10681            } elseif {$r == -1} {
10682                set tags [lreplace $tags $i $i]
10683                incr i -1
10684                break
10685            }
10686        }
10687    }
10688
10689    if {[array names growing] ne {}} {
10690        # graph isn't finished, need to check if any tag could get
10691        # eclipsed by another tag coming later.  Simply ignore any
10692        # tags that could later get eclipsed.
10693        set ctags {}
10694        foreach t $tags {
10695            if {[is_certain $t $origid]} {
10696                lappend ctags $t
10697            }
10698        }
10699        if {$tags eq $ctags} {
10700            set cached_dtags($origid) $tags
10701        } else {
10702            set tags $ctags
10703        }
10704    } else {
10705        set cached_dtags($origid) $tags
10706    }
10707    set t3 [clock clicks -milliseconds]
10708    if {0 && $t3 - $t1 >= 100} {
10709        puts "iterating descendents ($loopix/[llength $todo] nodes) took\
10710            [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10711    }
10712    return $tags
10713}
10714
10715proc anctags {id} {
10716    global arcnos arcids arcout arcend arctags idtags allparents
10717    global growing cached_atags
10718
10719    if {![info exists allparents($id)]} {
10720        return {}
10721    }
10722    set t1 [clock clicks -milliseconds]
10723    set argid $id
10724    if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10725        # part-way along an arc; check that arc first
10726        set a [lindex $arcnos($id) 0]
10727        if {$arctags($a) ne {}} {
10728            validate_arctags $a
10729            set i [lsearch -exact $arcids($a) $id]
10730            foreach t $arctags($a) {
10731                set j [lsearch -exact $arcids($a) $t]
10732                if {$j > $i} {
10733                    return $t
10734                }
10735            }
10736        }
10737        if {![info exists arcend($a)]} {
10738            return {}
10739        }
10740        set id $arcend($a)
10741        if {[info exists idtags($id)]} {
10742            return $id
10743        }
10744    }
10745    if {[info exists cached_atags($id)]} {
10746        return $cached_atags($id)
10747    }
10748
10749    set origid $id
10750    set todo [list $id]
10751    set queued($id) 1
10752    set taglist {}
10753    set nc 1
10754    for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10755        set id [lindex $todo $i]
10756        set done($id) 1
10757        set td [info exists hastaggeddescendent($id)]
10758        if {!$td} {
10759            incr nc -1
10760        }
10761        # ignore tags on starting node
10762        if {!$td && $i > 0} {
10763            if {[info exists idtags($id)]} {
10764                set tagloc($id) $id
10765                set td 1
10766            } elseif {[info exists cached_atags($id)]} {
10767                set tagloc($id) $cached_atags($id)
10768                set td 1
10769            }
10770        }
10771        foreach a $arcout($id) {
10772            if {!$td && $arctags($a) ne {}} {
10773                validate_arctags $a
10774                if {$arctags($a) ne {}} {
10775                    lappend tagloc($id) [lindex $arctags($a) 0]
10776                }
10777            }
10778            if {![info exists arcend($a)]} continue
10779            set d $arcend($a)
10780            if {$td || $arctags($a) ne {}} {
10781                set tomark [list $d]
10782                for {set j 0} {$j < [llength $tomark]} {incr j} {
10783                    set dd [lindex $tomark $j]
10784                    if {![info exists hastaggeddescendent($dd)]} {
10785                        if {[info exists done($dd)]} {
10786                            foreach b $arcout($dd) {
10787                                if {[info exists arcend($b)]} {
10788                                    lappend tomark $arcend($b)
10789                                }
10790                            }
10791                            if {[info exists tagloc($dd)]} {
10792                                unset tagloc($dd)
10793                            }
10794                        } elseif {[info exists queued($dd)]} {
10795                            incr nc -1
10796                        }
10797                        set hastaggeddescendent($dd) 1
10798                    }
10799                }
10800            }
10801            if {![info exists queued($d)]} {
10802                lappend todo $d
10803                set queued($d) 1
10804                if {![info exists hastaggeddescendent($d)]} {
10805                    incr nc
10806                }
10807            }
10808        }
10809    }
10810    set t2 [clock clicks -milliseconds]
10811    set loopix $i
10812    set tags {}
10813    foreach id [array names tagloc] {
10814        if {![info exists hastaggeddescendent($id)]} {
10815            foreach t $tagloc($id) {
10816                if {[lsearch -exact $tags $t] < 0} {
10817                    lappend tags $t
10818                }
10819            }
10820        }
10821    }
10822
10823    # remove tags that are ancestors of other tags
10824    for {set i 0} {$i < [llength $tags]} {incr i} {
10825        set a [lindex $tags $i]
10826        for {set j 0} {$j < $i} {incr j} {
10827            set b [lindex $tags $j]
10828            set r [anc_or_desc $a $b]
10829            if {$r == -1} {
10830                set tags [lreplace $tags $j $j]
10831                incr j -1
10832                incr i -1
10833            } elseif {$r == 1} {
10834                set tags [lreplace $tags $i $i]
10835                incr i -1
10836                break
10837            }
10838        }
10839    }
10840
10841    if {[array names growing] ne {}} {
10842        # graph isn't finished, need to check if any tag could get
10843        # eclipsed by another tag coming later.  Simply ignore any
10844        # tags that could later get eclipsed.
10845        set ctags {}
10846        foreach t $tags {
10847            if {[is_certain $origid $t]} {
10848                lappend ctags $t
10849            }
10850        }
10851        if {$tags eq $ctags} {
10852            set cached_atags($origid) $tags
10853        } else {
10854            set tags $ctags
10855        }
10856    } else {
10857        set cached_atags($origid) $tags
10858    }
10859    set t3 [clock clicks -milliseconds]
10860    if {0 && $t3 - $t1 >= 100} {
10861        puts "iterating ancestors ($loopix/[llength $todo] nodes) took\
10862            [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10863    }
10864    return $tags
10865}
10866
10867# Return the list of IDs that have heads that are descendents of id,
10868# including id itself if it has a head.
10869proc descheads {id} {
10870    global arcnos arcstart arcids archeads idheads cached_dheads
10871    global allparents arcout
10872
10873    if {![info exists allparents($id)]} {
10874        return {}
10875    }
10876    set aret {}
10877    if {![info exists arcout($id)]} {
10878        # part-way along an arc; check it first
10879        set a [lindex $arcnos($id) 0]
10880        if {$archeads($a) ne {}} {
10881            validate_archeads $a
10882            set i [lsearch -exact $arcids($a) $id]
10883            foreach t $archeads($a) {
10884                set j [lsearch -exact $arcids($a) $t]
10885                if {$j > $i} break
10886                lappend aret $t
10887            }
10888        }
10889        set id $arcstart($a)
10890    }
10891    set origid $id
10892    set todo [list $id]
10893    set seen($id) 1
10894    set ret {}
10895    for {set i 0} {$i < [llength $todo]} {incr i} {
10896        set id [lindex $todo $i]
10897        if {[info exists cached_dheads($id)]} {
10898            set ret [concat $ret $cached_dheads($id)]
10899        } else {
10900            if {[info exists idheads($id)]} {
10901                lappend ret $id
10902            }
10903            foreach a $arcnos($id) {
10904                if {$archeads($a) ne {}} {
10905                    validate_archeads $a
10906                    if {$archeads($a) ne {}} {
10907                        set ret [concat $ret $archeads($a)]
10908                    }
10909                }
10910                set d $arcstart($a)
10911                if {![info exists seen($d)]} {
10912                    lappend todo $d
10913                    set seen($d) 1
10914                }
10915            }
10916        }
10917    }
10918    set ret [lsort -unique $ret]
10919    set cached_dheads($origid) $ret
10920    return [concat $ret $aret]
10921}
10922
10923proc addedtag {id} {
10924    global arcnos arcout cached_dtags cached_atags
10925
10926    if {![info exists arcnos($id)]} return
10927    if {![info exists arcout($id)]} {
10928        recalcarc [lindex $arcnos($id) 0]
10929    }
10930    catch {unset cached_dtags}
10931    catch {unset cached_atags}
10932}
10933
10934proc addedhead {hid head} {
10935    global arcnos arcout cached_dheads
10936
10937    if {![info exists arcnos($hid)]} return
10938    if {![info exists arcout($hid)]} {
10939        recalcarc [lindex $arcnos($hid) 0]
10940    }
10941    catch {unset cached_dheads}
10942}
10943
10944proc removedhead {hid head} {
10945    global cached_dheads
10946
10947    catch {unset cached_dheads}
10948}
10949
10950proc movedhead {hid head} {
10951    global arcnos arcout cached_dheads
10952
10953    if {![info exists arcnos($hid)]} return
10954    if {![info exists arcout($hid)]} {
10955        recalcarc [lindex $arcnos($hid) 0]
10956    }
10957    catch {unset cached_dheads}
10958}
10959
10960proc changedrefs {} {
10961    global cached_dheads cached_dtags cached_atags cached_tagcontent
10962    global arctags archeads arcnos arcout idheads idtags
10963
10964    foreach id [concat [array names idheads] [array names idtags]] {
10965        if {[info exists arcnos($id)] && ![info exists arcout($id)]} {
10966            set a [lindex $arcnos($id) 0]
10967            if {![info exists donearc($a)]} {
10968                recalcarc $a
10969                set donearc($a) 1
10970            }
10971        }
10972    }
10973    catch {unset cached_tagcontent}
10974    catch {unset cached_dtags}
10975    catch {unset cached_atags}
10976    catch {unset cached_dheads}
10977}
10978
10979proc rereadrefs {} {
10980    global idtags idheads idotherrefs mainheadid
10981
10982    set refids [concat [array names idtags] \
10983                    [array names idheads] [array names idotherrefs]]
10984    foreach id $refids {
10985        if {![info exists ref($id)]} {
10986            set ref($id) [listrefs $id]
10987        }
10988    }
10989    set oldmainhead $mainheadid
10990    readrefs
10991    changedrefs
10992    set refids [lsort -unique [concat $refids [array names idtags] \
10993                        [array names idheads] [array names idotherrefs]]]
10994    foreach id $refids {
10995        set v [listrefs $id]
10996        if {![info exists ref($id)] || $ref($id) != $v} {
10997            redrawtags $id
10998        }
10999    }
11000    if {$oldmainhead ne $mainheadid} {
11001        redrawtags $oldmainhead
11002        redrawtags $mainheadid
11003    }
11004    run refill_reflist
11005}
11006
11007proc listrefs {id} {
11008    global idtags idheads idotherrefs
11009
11010    set x {}
11011    if {[info exists idtags($id)]} {
11012        set x $idtags($id)
11013    }
11014    set y {}
11015    if {[info exists idheads($id)]} {
11016        set y $idheads($id)
11017    }
11018    set z {}
11019    if {[info exists idotherrefs($id)]} {
11020        set z $idotherrefs($id)
11021    }
11022    return [list $x $y $z]
11023}
11024
11025proc add_tag_ctext {tag} {
11026    global ctext cached_tagcontent tagids
11027
11028    if {![info exists cached_tagcontent($tag)]} {
11029        catch {
11030            set cached_tagcontent($tag) [exec git cat-file -p $tag]
11031        }
11032    }
11033    $ctext insert end "[mc "Tag"]: $tag\n" bold
11034    if {[info exists cached_tagcontent($tag)]} {
11035        set text $cached_tagcontent($tag)
11036    } else {
11037        set text "[mc "Id"]:  $tagids($tag)"
11038    }
11039    appendwithlinks $text {}
11040}
11041
11042proc showtag {tag isnew} {
11043    global ctext cached_tagcontent tagids linknum tagobjid
11044
11045    if {$isnew} {
11046        addtohistory [list showtag $tag 0] savectextpos
11047    }
11048    $ctext conf -state normal
11049    clear_ctext
11050    settabs 0
11051    set linknum 0
11052    add_tag_ctext $tag
11053    maybe_scroll_ctext 1
11054    $ctext conf -state disabled
11055    init_flist {}
11056}
11057
11058proc showtags {id isnew} {
11059    global idtags ctext linknum
11060
11061    if {$isnew} {
11062        addtohistory [list showtags $id 0] savectextpos
11063    }
11064    $ctext conf -state normal
11065    clear_ctext
11066    settabs 0
11067    set linknum 0
11068    set sep {}
11069    foreach tag $idtags($id) {
11070        $ctext insert end $sep
11071        add_tag_ctext $tag
11072        set sep "\n\n"
11073    }
11074    maybe_scroll_ctext 1
11075    $ctext conf -state disabled
11076    init_flist {}
11077}
11078
11079proc doquit {} {
11080    global stopped
11081    global gitktmpdir
11082
11083    set stopped 100
11084    savestuff .
11085    destroy .
11086
11087    if {[info exists gitktmpdir]} {
11088        catch {file delete -force $gitktmpdir}
11089    }
11090}
11091
11092proc mkfontdisp {font top which} {
11093    global fontattr fontpref $font NS use_ttk
11094
11095    set fontpref($font) [set $font]
11096    ${NS}::button $top.${font}but -text $which \
11097        -command [list choosefont $font $which]
11098    ${NS}::label $top.$font -relief flat -font $font \
11099        -text $fontattr($font,family) -justify left
11100    grid x $top.${font}but $top.$font -sticky w
11101}
11102
11103proc choosefont {font which} {
11104    global fontparam fontlist fonttop fontattr
11105    global prefstop NS
11106
11107    set fontparam(which) $which
11108    set fontparam(font) $font
11109    set fontparam(family) [font actual $font -family]
11110    set fontparam(size) $fontattr($font,size)
11111    set fontparam(weight) $fontattr($font,weight)
11112    set fontparam(slant) $fontattr($font,slant)
11113    set top .gitkfont
11114    set fonttop $top
11115    if {![winfo exists $top]} {
11116        font create sample
11117        eval font config sample [font actual $font]
11118        ttk_toplevel $top
11119        make_transient $top $prefstop
11120        wm title $top [mc "Gitk font chooser"]
11121        ${NS}::label $top.l -textvariable fontparam(which)
11122        pack $top.l -side top
11123        set fontlist [lsort [font families]]
11124        ${NS}::frame $top.f
11125        listbox $top.f.fam -listvariable fontlist \
11126            -yscrollcommand [list $top.f.sb set]
11127        bind $top.f.fam <<ListboxSelect>> selfontfam
11128        ${NS}::scrollbar $top.f.sb -command [list $top.f.fam yview]
11129        pack $top.f.sb -side right -fill y
11130        pack $top.f.fam -side left -fill both -expand 1
11131        pack $top.f -side top -fill both -expand 1
11132        ${NS}::frame $top.g
11133        spinbox $top.g.size -from 4 -to 40 -width 4 \
11134            -textvariable fontparam(size) \
11135            -validatecommand {string is integer -strict %s}
11136        checkbutton $top.g.bold -padx 5 \
11137            -font {{Times New Roman} 12 bold} -text [mc "B"] -indicatoron 0 \
11138            -variable fontparam(weight) -onvalue bold -offvalue normal
11139        checkbutton $top.g.ital -padx 5 \
11140            -font {{Times New Roman} 12 italic} -text [mc "I"] -indicatoron 0  \
11141            -variable fontparam(slant) -onvalue italic -offvalue roman
11142        pack $top.g.size $top.g.bold $top.g.ital -side left
11143        pack $top.g -side top
11144        canvas $top.c -width 150 -height 50 -border 2 -relief sunk \
11145            -background white
11146        $top.c create text 100 25 -anchor center -text $which -font sample \
11147            -fill black -tags text
11148        bind $top.c <Configure> [list centertext $top.c]
11149        pack $top.c -side top -fill x
11150        ${NS}::frame $top.buts
11151        ${NS}::button $top.buts.ok -text [mc "OK"] -command fontok -default active
11152        ${NS}::button $top.buts.can -text [mc "Cancel"] -command fontcan -default normal
11153        bind $top <Key-Return> fontok
11154        bind $top <Key-Escape> fontcan
11155        grid $top.buts.ok $top.buts.can
11156        grid columnconfigure $top.buts 0 -weight 1 -uniform a
11157        grid columnconfigure $top.buts 1 -weight 1 -uniform a
11158        pack $top.buts -side bottom -fill x
11159        trace add variable fontparam write chg_fontparam
11160    } else {
11161        raise $top
11162        $top.c itemconf text -text $which
11163    }
11164    set i [lsearch -exact $fontlist $fontparam(family)]
11165    if {$i >= 0} {
11166        $top.f.fam selection set $i
11167        $top.f.fam see $i
11168    }
11169}
11170
11171proc centertext {w} {
11172    $w coords text [expr {[winfo width $w] / 2}] [expr {[winfo height $w] / 2}]
11173}
11174
11175proc fontok {} {
11176    global fontparam fontpref prefstop
11177
11178    set f $fontparam(font)
11179    set fontpref($f) [list $fontparam(family) $fontparam(size)]
11180    if {$fontparam(weight) eq "bold"} {
11181        lappend fontpref($f) "bold"
11182    }
11183    if {$fontparam(slant) eq "italic"} {
11184        lappend fontpref($f) "italic"
11185    }
11186    set w $prefstop.notebook.fonts.$f
11187    $w conf -text $fontparam(family) -font $fontpref($f)
11188
11189    fontcan
11190}
11191
11192proc fontcan {} {
11193    global fonttop fontparam
11194
11195    if {[info exists fonttop]} {
11196        catch {destroy $fonttop}
11197        catch {font delete sample}
11198        unset fonttop
11199        unset fontparam
11200    }
11201}
11202
11203if {[package vsatisfies [package provide Tk] 8.6]} {
11204    # In Tk 8.6 we have a native font chooser dialog. Overwrite the above
11205    # function to make use of it.
11206    proc choosefont {font which} {
11207        tk fontchooser configure -title $which -font $font \
11208            -command [list on_choosefont $font $which]
11209        tk fontchooser show
11210    }
11211    proc on_choosefont {font which newfont} {
11212        global fontparam
11213        puts stderr "$font $newfont"
11214        array set f [font actual $newfont]
11215        set fontparam(which) $which
11216        set fontparam(font) $font
11217        set fontparam(family) $f(-family)
11218        set fontparam(size) $f(-size)
11219        set fontparam(weight) $f(-weight)
11220        set fontparam(slant) $f(-slant)
11221        fontok
11222    }
11223}
11224
11225proc selfontfam {} {
11226    global fonttop fontparam
11227
11228    set i [$fonttop.f.fam curselection]
11229    if {$i ne {}} {
11230        set fontparam(family) [$fonttop.f.fam get $i]
11231    }
11232}
11233
11234proc chg_fontparam {v sub op} {
11235    global fontparam
11236
11237    font config sample -$sub $fontparam($sub)
11238}
11239
11240# Create a property sheet tab page
11241proc create_prefs_page {w} {
11242    global NS
11243    set parent [join [lrange [split $w .] 0 end-1] .]
11244    if {[winfo class $parent] eq "TNotebook"} {
11245        ${NS}::frame $w
11246    } else {
11247        ${NS}::labelframe $w
11248    }
11249}
11250
11251proc prefspage_general {notebook} {
11252    global NS maxwidth maxgraphpct showneartags showlocalchanges
11253    global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11254    global hideremotes want_ttk have_ttk maxrefs
11255
11256    set page [create_prefs_page $notebook.general]
11257
11258    ${NS}::label $page.ldisp -text [mc "Commit list display options"]
11259    grid $page.ldisp - -sticky w -pady 10
11260    ${NS}::label $page.spacer -text " "
11261    ${NS}::label $page.maxwidthl -text [mc "Maximum graph width (lines)"]
11262    spinbox $page.maxwidth -from 0 -to 100 -width 4 -textvariable maxwidth
11263    grid $page.spacer $page.maxwidthl $page.maxwidth -sticky w
11264    ${NS}::label $page.maxpctl -text [mc "Maximum graph width (% of pane)"]
11265    spinbox $page.maxpct -from 1 -to 100 -width 4 -textvariable maxgraphpct
11266    grid x $page.maxpctl $page.maxpct -sticky w
11267    ${NS}::checkbutton $page.showlocal -text [mc "Show local changes"] \
11268        -variable showlocalchanges
11269    grid x $page.showlocal -sticky w
11270    ${NS}::checkbutton $page.autoselect -text [mc "Auto-select SHA1 (length)"] \
11271        -variable autoselect
11272    spinbox $page.autosellen -from 1 -to 40 -width 4 -textvariable autosellen
11273    grid x $page.autoselect $page.autosellen -sticky w
11274    ${NS}::checkbutton $page.hideremotes -text [mc "Hide remote refs"] \
11275        -variable hideremotes
11276    grid x $page.hideremotes -sticky w
11277
11278    ${NS}::label $page.ddisp -text [mc "Diff display options"]
11279    grid $page.ddisp - -sticky w -pady 10
11280    ${NS}::label $page.tabstopl -text [mc "Tab spacing"]
11281    spinbox $page.tabstop -from 1 -to 20 -width 4 -textvariable tabstop
11282    grid x $page.tabstopl $page.tabstop -sticky w
11283    ${NS}::checkbutton $page.ntag -text [mc "Display nearby tags/heads"] \
11284        -variable showneartags
11285    grid x $page.ntag -sticky w
11286    ${NS}::label $page.maxrefsl -text [mc "Maximum # tags/heads to show"]
11287    spinbox $page.maxrefs -from 1 -to 1000 -width 4 -textvariable maxrefs
11288    grid x $page.maxrefsl $page.maxrefs -sticky w
11289    ${NS}::checkbutton $page.ldiff -text [mc "Limit diffs to listed paths"] \
11290        -variable limitdiffs
11291    grid x $page.ldiff -sticky w
11292    ${NS}::checkbutton $page.lattr -text [mc "Support per-file encodings"] \
11293        -variable perfile_attrs
11294    grid x $page.lattr -sticky w
11295
11296    ${NS}::entry $page.extdifft -textvariable extdifftool
11297    ${NS}::frame $page.extdifff
11298    ${NS}::label $page.extdifff.l -text [mc "External diff tool" ]
11299    ${NS}::button $page.extdifff.b -text [mc "Choose..."] -command choose_extdiff
11300    pack $page.extdifff.l $page.extdifff.b -side left
11301    pack configure $page.extdifff.l -padx 10
11302    grid x $page.extdifff $page.extdifft -sticky ew
11303
11304    ${NS}::label $page.lgen -text [mc "General options"]
11305    grid $page.lgen - -sticky w -pady 10
11306    ${NS}::checkbutton $page.want_ttk -variable want_ttk \
11307        -text [mc "Use themed widgets"]
11308    if {$have_ttk} {
11309        ${NS}::label $page.ttk_note -text [mc "(change requires restart)"]
11310    } else {
11311        ${NS}::label $page.ttk_note -text [mc "(currently unavailable)"]
11312    }
11313    grid x $page.want_ttk $page.ttk_note -sticky w
11314    return $page
11315}
11316
11317proc prefspage_colors {notebook} {
11318    global NS uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11319
11320    set page [create_prefs_page $notebook.colors]
11321
11322    ${NS}::label $page.cdisp -text [mc "Colors: press to choose"]
11323    grid $page.cdisp - -sticky w -pady 10
11324    label $page.ui -padx 40 -relief sunk -background $uicolor
11325    ${NS}::button $page.uibut -text [mc "Interface"] \
11326       -command [list choosecolor uicolor {} $page.ui [mc "interface"] setui]
11327    grid x $page.uibut $page.ui -sticky w
11328    label $page.bg -padx 40 -relief sunk -background $bgcolor
11329    ${NS}::button $page.bgbut -text [mc "Background"] \
11330        -command [list choosecolor bgcolor {} $page.bg [mc "background"] setbg]
11331    grid x $page.bgbut $page.bg -sticky w
11332    label $page.fg -padx 40 -relief sunk -background $fgcolor
11333    ${NS}::button $page.fgbut -text [mc "Foreground"] \
11334        -command [list choosecolor fgcolor {} $page.fg [mc "foreground"] setfg]
11335    grid x $page.fgbut $page.fg -sticky w
11336    label $page.diffold -padx 40 -relief sunk -background [lindex $diffcolors 0]
11337    ${NS}::button $page.diffoldbut -text [mc "Diff: old lines"] \
11338        -command [list choosecolor diffcolors 0 $page.diffold [mc "diff old lines"] \
11339                      [list $ctext tag conf d0 -foreground]]
11340    grid x $page.diffoldbut $page.diffold -sticky w
11341    label $page.diffnew -padx 40 -relief sunk -background [lindex $diffcolors 1]
11342    ${NS}::button $page.diffnewbut -text [mc "Diff: new lines"] \
11343        -command [list choosecolor diffcolors 1 $page.diffnew [mc "diff new lines"] \
11344                      [list $ctext tag conf dresult -foreground]]
11345    grid x $page.diffnewbut $page.diffnew -sticky w
11346    label $page.hunksep -padx 40 -relief sunk -background [lindex $diffcolors 2]
11347    ${NS}::button $page.hunksepbut -text [mc "Diff: hunk header"] \
11348        -command [list choosecolor diffcolors 2 $page.hunksep \
11349                      [mc "diff hunk header"] \
11350                      [list $ctext tag conf hunksep -foreground]]
11351    grid x $page.hunksepbut $page.hunksep -sticky w
11352    label $page.markbgsep -padx 40 -relief sunk -background $markbgcolor
11353    ${NS}::button $page.markbgbut -text [mc "Marked line bg"] \
11354        -command [list choosecolor markbgcolor {} $page.markbgsep \
11355                      [mc "marked line background"] \
11356                      [list $ctext tag conf omark -background]]
11357    grid x $page.markbgbut $page.markbgsep -sticky w
11358    label $page.selbgsep -padx 40 -relief sunk -background $selectbgcolor
11359    ${NS}::button $page.selbgbut -text [mc "Select bg"] \
11360        -command [list choosecolor selectbgcolor {} $page.selbgsep [mc "background"] setselbg]
11361    grid x $page.selbgbut $page.selbgsep -sticky w
11362    return $page
11363}
11364
11365proc prefspage_fonts {notebook} {
11366    global NS
11367    set page [create_prefs_page $notebook.fonts]
11368    ${NS}::label $page.cfont -text [mc "Fonts: press to choose"]
11369    grid $page.cfont - -sticky w -pady 10
11370    mkfontdisp mainfont $page [mc "Main font"]
11371    mkfontdisp textfont $page [mc "Diff display font"]
11372    mkfontdisp uifont $page [mc "User interface font"]
11373    return $page
11374}
11375
11376proc doprefs {} {
11377    global maxwidth maxgraphpct use_ttk NS
11378    global oldprefs prefstop showneartags showlocalchanges
11379    global uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11380    global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11381    global hideremotes want_ttk have_ttk
11382
11383    set top .gitkprefs
11384    set prefstop $top
11385    if {[winfo exists $top]} {
11386        raise $top
11387        return
11388    }
11389    foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11390                   limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11391        set oldprefs($v) [set $v]
11392    }
11393    ttk_toplevel $top
11394    wm title $top [mc "Gitk preferences"]
11395    make_transient $top .
11396
11397    if {[set use_notebook [expr {$use_ttk && [info command ::ttk::notebook] ne ""}]]} {
11398        set notebook [ttk::notebook $top.notebook]
11399    } else {
11400        set notebook [${NS}::frame $top.notebook -borderwidth 0 -relief flat]
11401    }
11402
11403    lappend pages [prefspage_general $notebook] [mc "General"]
11404    lappend pages [prefspage_colors $notebook] [mc "Colors"]
11405    lappend pages [prefspage_fonts $notebook] [mc "Fonts"]
11406    set col 0
11407    foreach {page title} $pages {
11408        if {$use_notebook} {
11409            $notebook add $page -text $title
11410        } else {
11411            set btn [${NS}::button $notebook.b_[string map {. X} $page] \
11412                         -text $title -command [list raise $page]]
11413            $page configure -text $title
11414            grid $btn -row 0 -column [incr col] -sticky w
11415            grid $page -row 1 -column 0 -sticky news -columnspan 100
11416        }
11417    }
11418
11419    if {!$use_notebook} {
11420        grid columnconfigure $notebook 0 -weight 1
11421        grid rowconfigure $notebook 1 -weight 1
11422        raise [lindex $pages 0]
11423    }
11424
11425    grid $notebook -sticky news -padx 2 -pady 2
11426    grid rowconfigure $top 0 -weight 1
11427    grid columnconfigure $top 0 -weight 1
11428
11429    ${NS}::frame $top.buts
11430    ${NS}::button $top.buts.ok -text [mc "OK"] -command prefsok -default active
11431    ${NS}::button $top.buts.can -text [mc "Cancel"] -command prefscan -default normal
11432    bind $top <Key-Return> prefsok
11433    bind $top <Key-Escape> prefscan
11434    grid $top.buts.ok $top.buts.can
11435    grid columnconfigure $top.buts 0 -weight 1 -uniform a
11436    grid columnconfigure $top.buts 1 -weight 1 -uniform a
11437    grid $top.buts - - -pady 10 -sticky ew
11438    grid columnconfigure $top 2 -weight 1
11439    bind $top <Visibility> [list focus $top.buts.ok]
11440}
11441
11442proc choose_extdiff {} {
11443    global extdifftool
11444
11445    set prog [tk_getOpenFile -title [mc "External diff tool"] -multiple false]
11446    if {$prog ne {}} {
11447        set extdifftool $prog
11448    }
11449}
11450
11451proc choosecolor {v vi w x cmd} {
11452    global $v
11453
11454    set c [tk_chooseColor -initialcolor [lindex [set $v] $vi] \
11455               -title [mc "Gitk: choose color for %s" $x]]
11456    if {$c eq {}} return
11457    $w conf -background $c
11458    lset $v $vi $c
11459    eval $cmd $c
11460}
11461
11462proc setselbg {c} {
11463    global bglist cflist
11464    foreach w $bglist {
11465        $w configure -selectbackground $c
11466    }
11467    $cflist tag configure highlight \
11468        -background [$cflist cget -selectbackground]
11469    allcanvs itemconf secsel -fill $c
11470}
11471
11472# This sets the background color and the color scheme for the whole UI.
11473# For some reason, tk_setPalette chooses a nasty dark red for selectColor
11474# if we don't specify one ourselves, which makes the checkbuttons and
11475# radiobuttons look bad.  This chooses white for selectColor if the
11476# background color is light, or black if it is dark.
11477proc setui {c} {
11478    if {[tk windowingsystem] eq "win32"} { return }
11479    set bg [winfo rgb . $c]
11480    set selc black
11481    if {[lindex $bg 0] + 1.5 * [lindex $bg 1] + 0.5 * [lindex $bg 2] > 100000} {
11482        set selc white
11483    }
11484    tk_setPalette background $c selectColor $selc
11485}
11486
11487proc setbg {c} {
11488    global bglist
11489
11490    foreach w $bglist {
11491        $w conf -background $c
11492    }
11493}
11494
11495proc setfg {c} {
11496    global fglist canv
11497
11498    foreach w $fglist {
11499        $w conf -foreground $c
11500    }
11501    allcanvs itemconf text -fill $c
11502    $canv itemconf circle -outline $c
11503    $canv itemconf markid -outline $c
11504}
11505
11506proc prefscan {} {
11507    global oldprefs prefstop
11508
11509    foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11510                   limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11511        global $v
11512        set $v $oldprefs($v)
11513    }
11514    catch {destroy $prefstop}
11515    unset prefstop
11516    fontcan
11517}
11518
11519proc prefsok {} {
11520    global maxwidth maxgraphpct
11521    global oldprefs prefstop showneartags showlocalchanges
11522    global fontpref mainfont textfont uifont
11523    global limitdiffs treediffs perfile_attrs
11524    global hideremotes
11525
11526    catch {destroy $prefstop}
11527    unset prefstop
11528    fontcan
11529    set fontchanged 0
11530    if {$mainfont ne $fontpref(mainfont)} {
11531        set mainfont $fontpref(mainfont)
11532        parsefont mainfont $mainfont
11533        eval font configure mainfont [fontflags mainfont]
11534        eval font configure mainfontbold [fontflags mainfont 1]
11535        setcoords
11536        set fontchanged 1
11537    }
11538    if {$textfont ne $fontpref(textfont)} {
11539        set textfont $fontpref(textfont)
11540        parsefont textfont $textfont
11541        eval font configure textfont [fontflags textfont]
11542        eval font configure textfontbold [fontflags textfont 1]
11543    }
11544    if {$uifont ne $fontpref(uifont)} {
11545        set uifont $fontpref(uifont)
11546        parsefont uifont $uifont
11547        eval font configure uifont [fontflags uifont]
11548    }
11549    settabs
11550    if {$showlocalchanges != $oldprefs(showlocalchanges)} {
11551        if {$showlocalchanges} {
11552            doshowlocalchanges
11553        } else {
11554            dohidelocalchanges
11555        }
11556    }
11557    if {$limitdiffs != $oldprefs(limitdiffs) ||
11558        ($perfile_attrs && !$oldprefs(perfile_attrs))} {
11559        # treediffs elements are limited by path;
11560        # won't have encodings cached if perfile_attrs was just turned on
11561        catch {unset treediffs}
11562    }
11563    if {$fontchanged || $maxwidth != $oldprefs(maxwidth)
11564        || $maxgraphpct != $oldprefs(maxgraphpct)} {
11565        redisplay
11566    } elseif {$showneartags != $oldprefs(showneartags) ||
11567          $limitdiffs != $oldprefs(limitdiffs)} {
11568        reselectline
11569    }
11570    if {$hideremotes != $oldprefs(hideremotes)} {
11571        rereadrefs
11572    }
11573}
11574
11575proc formatdate {d} {
11576    global datetimeformat
11577    if {$d ne {}} {
11578        set d [clock format [lindex $d 0] -format $datetimeformat]
11579    }
11580    return $d
11581}
11582
11583# This list of encoding names and aliases is distilled from
11584# http://www.iana.org/assignments/character-sets.
11585# Not all of them are supported by Tcl.
11586set encoding_aliases {
11587    { ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ASCII
11588      ISO646-US US-ASCII us IBM367 cp367 csASCII }
11589    { ISO-10646-UTF-1 csISO10646UTF1 }
11590    { ISO_646.basic:1983 ref csISO646basic1983 }
11591    { INVARIANT csINVARIANT }
11592    { ISO_646.irv:1983 iso-ir-2 irv csISO2IntlRefVersion }
11593    { BS_4730 iso-ir-4 ISO646-GB gb uk csISO4UnitedKingdom }
11594    { NATS-SEFI iso-ir-8-1 csNATSSEFI }
11595    { NATS-SEFI-ADD iso-ir-8-2 csNATSSEFIADD }
11596    { NATS-DANO iso-ir-9-1 csNATSDANO }
11597    { NATS-DANO-ADD iso-ir-9-2 csNATSDANOADD }
11598    { SEN_850200_B iso-ir-10 FI ISO646-FI ISO646-SE se csISO10Swedish }
11599    { SEN_850200_C iso-ir-11 ISO646-SE2 se2 csISO11SwedishForNames }
11600    { KS_C_5601-1987 iso-ir-149 KS_C_5601-1989 KSC_5601 korean csKSC56011987 }
11601    { ISO-2022-KR csISO2022KR }
11602    { EUC-KR csEUCKR }
11603    { ISO-2022-JP csISO2022JP }
11604    { ISO-2022-JP-2 csISO2022JP2 }
11605    { JIS_C6220-1969-jp JIS_C6220-1969 iso-ir-13 katakana x0201-7
11606      csISO13JISC6220jp }
11607    { JIS_C6220-1969-ro iso-ir-14 jp ISO646-JP csISO14JISC6220ro }
11608    { IT iso-ir-15 ISO646-IT csISO15Italian }
11609    { PT iso-ir-16 ISO646-PT csISO16Portuguese }
11610    { ES iso-ir-17 ISO646-ES csISO17Spanish }
11611    { greek7-old iso-ir-18 csISO18Greek7Old }
11612    { latin-greek iso-ir-19 csISO19LatinGreek }
11613    { DIN_66003 iso-ir-21 de ISO646-DE csISO21German }
11614    { NF_Z_62-010_(1973) iso-ir-25 ISO646-FR1 csISO25French }
11615    { Latin-greek-1 iso-ir-27 csISO27LatinGreek1 }
11616    { ISO_5427 iso-ir-37 csISO5427Cyrillic }
11617    { JIS_C6226-1978 iso-ir-42 csISO42JISC62261978 }
11618    { BS_viewdata iso-ir-47 csISO47BSViewdata }
11619    { INIS iso-ir-49 csISO49INIS }
11620    { INIS-8 iso-ir-50 csISO50INIS8 }
11621    { INIS-cyrillic iso-ir-51 csISO51INISCyrillic }
11622    { ISO_5427:1981 iso-ir-54 ISO5427Cyrillic1981 }
11623    { ISO_5428:1980 iso-ir-55 csISO5428Greek }
11624    { GB_1988-80 iso-ir-57 cn ISO646-CN csISO57GB1988 }
11625    { GB_2312-80 iso-ir-58 chinese csISO58GB231280 }
11626    { NS_4551-1 iso-ir-60 ISO646-NO no csISO60DanishNorwegian
11627      csISO60Norwegian1 }
11628    { NS_4551-2 ISO646-NO2 iso-ir-61 no2 csISO61Norwegian2 }
11629    { NF_Z_62-010 iso-ir-69 ISO646-FR fr csISO69French }
11630    { videotex-suppl iso-ir-70 csISO70VideotexSupp1 }
11631    { PT2 iso-ir-84 ISO646-PT2 csISO84Portuguese2 }
11632    { ES2 iso-ir-85 ISO646-ES2 csISO85Spanish2 }
11633    { MSZ_7795.3 iso-ir-86 ISO646-HU hu csISO86Hungarian }
11634    { JIS_C6226-1983 iso-ir-87 x0208 JIS_X0208-1983 csISO87JISX0208 }
11635    { greek7 iso-ir-88 csISO88Greek7 }
11636    { ASMO_449 ISO_9036 arabic7 iso-ir-89 csISO89ASMO449 }
11637    { iso-ir-90 csISO90 }
11638    { JIS_C6229-1984-a iso-ir-91 jp-ocr-a csISO91JISC62291984a }
11639    { JIS_C6229-1984-b iso-ir-92 ISO646-JP-OCR-B jp-ocr-b
11640      csISO92JISC62991984b }
11641    { JIS_C6229-1984-b-add iso-ir-93 jp-ocr-b-add csISO93JIS62291984badd }
11642    { JIS_C6229-1984-hand iso-ir-94 jp-ocr-hand csISO94JIS62291984hand }
11643    { JIS_C6229-1984-hand-add iso-ir-95 jp-ocr-hand-add
11644      csISO95JIS62291984handadd }
11645    { JIS_C6229-1984-kana iso-ir-96 csISO96JISC62291984kana }
11646    { ISO_2033-1983 iso-ir-98 e13b csISO2033 }
11647    { ANSI_X3.110-1983 iso-ir-99 CSA_T500-1983 NAPLPS csISO99NAPLPS }
11648    { ISO_8859-1:1987 iso-ir-100 ISO_8859-1 ISO-8859-1 latin1 l1 IBM819
11649      CP819 csISOLatin1 }
11650    { ISO_8859-2:1987 iso-ir-101 ISO_8859-2 ISO-8859-2 latin2 l2 csISOLatin2 }
11651    { T.61-7bit iso-ir-102 csISO102T617bit }
11652    { T.61-8bit T.61 iso-ir-103 csISO103T618bit }
11653    { ISO_8859-3:1988 iso-ir-109 ISO_8859-3 ISO-8859-3 latin3 l3 csISOLatin3 }
11654    { ISO_8859-4:1988 iso-ir-110 ISO_8859-4 ISO-8859-4 latin4 l4 csISOLatin4 }
11655    { ECMA-cyrillic iso-ir-111 KOI8-E csISO111ECMACyrillic }
11656    { CSA_Z243.4-1985-1 iso-ir-121 ISO646-CA csa7-1 ca csISO121Canadian1 }
11657    { CSA_Z243.4-1985-2 iso-ir-122 ISO646-CA2 csa7-2 csISO122Canadian2 }
11658    { CSA_Z243.4-1985-gr iso-ir-123 csISO123CSAZ24341985gr }
11659    { ISO_8859-6:1987 iso-ir-127 ISO_8859-6 ISO-8859-6 ECMA-114 ASMO-708
11660      arabic csISOLatinArabic }
11661    { ISO_8859-6-E csISO88596E ISO-8859-6-E }
11662    { ISO_8859-6-I csISO88596I ISO-8859-6-I }
11663    { ISO_8859-7:1987 iso-ir-126 ISO_8859-7 ISO-8859-7 ELOT_928 ECMA-118
11664      greek greek8 csISOLatinGreek }
11665    { T.101-G2 iso-ir-128 csISO128T101G2 }
11666    { ISO_8859-8:1988 iso-ir-138 ISO_8859-8 ISO-8859-8 hebrew
11667      csISOLatinHebrew }
11668    { ISO_8859-8-E csISO88598E ISO-8859-8-E }
11669    { ISO_8859-8-I csISO88598I ISO-8859-8-I }
11670    { CSN_369103 iso-ir-139 csISO139CSN369103 }
11671    { JUS_I.B1.002 iso-ir-141 ISO646-YU js yu csISO141JUSIB1002 }
11672    { ISO_6937-2-add iso-ir-142 csISOTextComm }
11673    { IEC_P27-1 iso-ir-143 csISO143IECP271 }
11674    { ISO_8859-5:1988 iso-ir-144 ISO_8859-5 ISO-8859-5 cyrillic
11675      csISOLatinCyrillic }
11676    { JUS_I.B1.003-serb iso-ir-146 serbian csISO146Serbian }
11677    { JUS_I.B1.003-mac macedonian iso-ir-147 csISO147Macedonian }
11678    { ISO_8859-9:1989 iso-ir-148 ISO_8859-9 ISO-8859-9 latin5 l5 csISOLatin5 }
11679    { greek-ccitt iso-ir-150 csISO150 csISO150GreekCCITT }
11680    { NC_NC00-10:81 cuba iso-ir-151 ISO646-CU csISO151Cuba }
11681    { ISO_6937-2-25 iso-ir-152 csISO6937Add }
11682    { GOST_19768-74 ST_SEV_358-88 iso-ir-153 csISO153GOST1976874 }
11683    { ISO_8859-supp iso-ir-154 latin1-2-5 csISO8859Supp }
11684    { ISO_10367-box iso-ir-155 csISO10367Box }
11685    { ISO-8859-10 iso-ir-157 l6 ISO_8859-10:1992 csISOLatin6 latin6 }
11686    { latin-lap lap iso-ir-158 csISO158Lap }
11687    { JIS_X0212-1990 x0212 iso-ir-159 csISO159JISX02121990 }
11688    { DS_2089 DS2089 ISO646-DK dk csISO646Danish }
11689    { us-dk csUSDK }
11690    { dk-us csDKUS }
11691    { JIS_X0201 X0201 csHalfWidthKatakana }
11692    { KSC5636 ISO646-KR csKSC5636 }
11693    { ISO-10646-UCS-2 csUnicode }
11694    { ISO-10646-UCS-4 csUCS4 }
11695    { DEC-MCS dec csDECMCS }
11696    { hp-roman8 roman8 r8 csHPRoman8 }
11697    { macintosh mac csMacintosh }
11698    { IBM037 cp037 ebcdic-cp-us ebcdic-cp-ca ebcdic-cp-wt ebcdic-cp-nl
11699      csIBM037 }
11700    { IBM038 EBCDIC-INT cp038 csIBM038 }
11701    { IBM273 CP273 csIBM273 }
11702    { IBM274 EBCDIC-BE CP274 csIBM274 }
11703    { IBM275 EBCDIC-BR cp275 csIBM275 }
11704    { IBM277 EBCDIC-CP-DK EBCDIC-CP-NO csIBM277 }
11705    { IBM278 CP278 ebcdic-cp-fi ebcdic-cp-se csIBM278 }
11706    { IBM280 CP280 ebcdic-cp-it csIBM280 }
11707    { IBM281 EBCDIC-JP-E cp281 csIBM281 }
11708    { IBM284 CP284 ebcdic-cp-es csIBM284 }
11709    { IBM285 CP285 ebcdic-cp-gb csIBM285 }
11710    { IBM290 cp290 EBCDIC-JP-kana csIBM290 }
11711    { IBM297 cp297 ebcdic-cp-fr csIBM297 }
11712    { IBM420 cp420 ebcdic-cp-ar1 csIBM420 }
11713    { IBM423 cp423 ebcdic-cp-gr csIBM423 }
11714    { IBM424 cp424 ebcdic-cp-he csIBM424 }
11715    { IBM437 cp437 437 csPC8CodePage437 }
11716    { IBM500 CP500 ebcdic-cp-be ebcdic-cp-ch csIBM500 }
11717    { IBM775 cp775 csPC775Baltic }
11718    { IBM850 cp850 850 csPC850Multilingual }
11719    { IBM851 cp851 851 csIBM851 }
11720    { IBM852 cp852 852 csPCp852 }
11721    { IBM855 cp855 855 csIBM855 }
11722    { IBM857 cp857 857 csIBM857 }
11723    { IBM860 cp860 860 csIBM860 }
11724    { IBM861 cp861 861 cp-is csIBM861 }
11725    { IBM862 cp862 862 csPC862LatinHebrew }
11726    { IBM863 cp863 863 csIBM863 }
11727    { IBM864 cp864 csIBM864 }
11728    { IBM865 cp865 865 csIBM865 }
11729    { IBM866 cp866 866 csIBM866 }
11730    { IBM868 CP868 cp-ar csIBM868 }
11731    { IBM869 cp869 869 cp-gr csIBM869 }
11732    { IBM870 CP870 ebcdic-cp-roece ebcdic-cp-yu csIBM870 }
11733    { IBM871 CP871 ebcdic-cp-is csIBM871 }
11734    { IBM880 cp880 EBCDIC-Cyrillic csIBM880 }
11735    { IBM891 cp891 csIBM891 }
11736    { IBM903 cp903 csIBM903 }
11737    { IBM904 cp904 904 csIBBM904 }
11738    { IBM905 CP905 ebcdic-cp-tr csIBM905 }
11739    { IBM918 CP918 ebcdic-cp-ar2 csIBM918 }
11740    { IBM1026 CP1026 csIBM1026 }
11741    { EBCDIC-AT-DE csIBMEBCDICATDE }
11742    { EBCDIC-AT-DE-A csEBCDICATDEA }
11743    { EBCDIC-CA-FR csEBCDICCAFR }
11744    { EBCDIC-DK-NO csEBCDICDKNO }
11745    { EBCDIC-DK-NO-A csEBCDICDKNOA }
11746    { EBCDIC-FI-SE csEBCDICFISE }
11747    { EBCDIC-FI-SE-A csEBCDICFISEA }
11748    { EBCDIC-FR csEBCDICFR }
11749    { EBCDIC-IT csEBCDICIT }
11750    { EBCDIC-PT csEBCDICPT }
11751    { EBCDIC-ES csEBCDICES }
11752    { EBCDIC-ES-A csEBCDICESA }
11753    { EBCDIC-ES-S csEBCDICESS }
11754    { EBCDIC-UK csEBCDICUK }
11755    { EBCDIC-US csEBCDICUS }
11756    { UNKNOWN-8BIT csUnknown8BiT }
11757    { MNEMONIC csMnemonic }
11758    { MNEM csMnem }
11759    { VISCII csVISCII }
11760    { VIQR csVIQR }
11761    { KOI8-R csKOI8R }
11762    { IBM00858 CCSID00858 CP00858 PC-Multilingual-850+euro }
11763    { IBM00924 CCSID00924 CP00924 ebcdic-Latin9--euro }
11764    { IBM01140 CCSID01140 CP01140 ebcdic-us-37+euro }
11765    { IBM01141 CCSID01141 CP01141 ebcdic-de-273+euro }
11766    { IBM01142 CCSID01142 CP01142 ebcdic-dk-277+euro ebcdic-no-277+euro }
11767    { IBM01143 CCSID01143 CP01143 ebcdic-fi-278+euro ebcdic-se-278+euro }
11768    { IBM01144 CCSID01144 CP01144 ebcdic-it-280+euro }
11769    { IBM01145 CCSID01145 CP01145 ebcdic-es-284+euro }
11770    { IBM01146 CCSID01146 CP01146 ebcdic-gb-285+euro }
11771    { IBM01147 CCSID01147 CP01147 ebcdic-fr-297+euro }
11772    { IBM01148 CCSID01148 CP01148 ebcdic-international-500+euro }
11773    { IBM01149 CCSID01149 CP01149 ebcdic-is-871+euro }
11774    { IBM1047 IBM-1047 }
11775    { PTCP154 csPTCP154 PT154 CP154 Cyrillic-Asian }
11776    { Amiga-1251 Ami1251 Amiga1251 Ami-1251 }
11777    { UNICODE-1-1 csUnicode11 }
11778    { CESU-8 csCESU-8 }
11779    { BOCU-1 csBOCU-1 }
11780    { UNICODE-1-1-UTF-7 csUnicode11UTF7 }
11781    { ISO-8859-14 iso-ir-199 ISO_8859-14:1998 ISO_8859-14 latin8 iso-celtic
11782      l8 }
11783    { ISO-8859-15 ISO_8859-15 Latin-9 }
11784    { ISO-8859-16 iso-ir-226 ISO_8859-16:2001 ISO_8859-16 latin10 l10 }
11785    { GBK CP936 MS936 windows-936 }
11786    { JIS_Encoding csJISEncoding }
11787    { Shift_JIS MS_Kanji csShiftJIS ShiftJIS Shift-JIS }
11788    { Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese
11789      EUC-JP }
11790    { Extended_UNIX_Code_Fixed_Width_for_Japanese csEUCFixWidJapanese }
11791    { ISO-10646-UCS-Basic csUnicodeASCII }
11792    { ISO-10646-Unicode-Latin1 csUnicodeLatin1 ISO-10646 }
11793    { ISO-Unicode-IBM-1261 csUnicodeIBM1261 }
11794    { ISO-Unicode-IBM-1268 csUnicodeIBM1268 }
11795    { ISO-Unicode-IBM-1276 csUnicodeIBM1276 }
11796    { ISO-Unicode-IBM-1264 csUnicodeIBM1264 }
11797    { ISO-Unicode-IBM-1265 csUnicodeIBM1265 }
11798    { ISO-8859-1-Windows-3.0-Latin-1 csWindows30Latin1 }
11799    { ISO-8859-1-Windows-3.1-Latin-1 csWindows31Latin1 }
11800    { ISO-8859-2-Windows-Latin-2 csWindows31Latin2 }
11801    { ISO-8859-9-Windows-Latin-5 csWindows31Latin5 }
11802    { Adobe-Standard-Encoding csAdobeStandardEncoding }
11803    { Ventura-US csVenturaUS }
11804    { Ventura-International csVenturaInternational }
11805    { PC8-Danish-Norwegian csPC8DanishNorwegian }
11806    { PC8-Turkish csPC8Turkish }
11807    { IBM-Symbols csIBMSymbols }
11808    { IBM-Thai csIBMThai }
11809    { HP-Legal csHPLegal }
11810    { HP-Pi-font csHPPiFont }
11811    { HP-Math8 csHPMath8 }
11812    { Adobe-Symbol-Encoding csHPPSMath }
11813    { HP-DeskTop csHPDesktop }
11814    { Ventura-Math csVenturaMath }
11815    { Microsoft-Publishing csMicrosoftPublishing }
11816    { Windows-31J csWindows31J }
11817    { GB2312 csGB2312 }
11818    { Big5 csBig5 }
11819}
11820
11821proc tcl_encoding {enc} {
11822    global encoding_aliases tcl_encoding_cache
11823    if {[info exists tcl_encoding_cache($enc)]} {
11824        return $tcl_encoding_cache($enc)
11825    }
11826    set names [encoding names]
11827    set lcnames [string tolower $names]
11828    set enc [string tolower $enc]
11829    set i [lsearch -exact $lcnames $enc]
11830    if {$i < 0} {
11831        # look for "isonnn" instead of "iso-nnn" or "iso_nnn"
11832        if {[regsub {^(iso|cp|ibm|jis)[-_]} $enc {\1} encx]} {
11833            set i [lsearch -exact $lcnames $encx]
11834        }
11835    }
11836    if {$i < 0} {
11837        foreach l $encoding_aliases {
11838            set ll [string tolower $l]
11839            if {[lsearch -exact $ll $enc] < 0} continue
11840            # look through the aliases for one that tcl knows about
11841            foreach e $ll {
11842                set i [lsearch -exact $lcnames $e]
11843                if {$i < 0} {
11844                    if {[regsub {^(iso|cp|ibm|jis)[-_]} $e {\1} ex]} {
11845                        set i [lsearch -exact $lcnames $ex]
11846                    }
11847                }
11848                if {$i >= 0} break
11849            }
11850            break
11851        }
11852    }
11853    set tclenc {}
11854    if {$i >= 0} {
11855        set tclenc [lindex $names $i]
11856    }
11857    set tcl_encoding_cache($enc) $tclenc
11858    return $tclenc
11859}
11860
11861proc gitattr {path attr default} {
11862    global path_attr_cache
11863    if {[info exists path_attr_cache($attr,$path)]} {
11864        set r $path_attr_cache($attr,$path)
11865    } else {
11866        set r "unspecified"
11867        if {![catch {set line [exec git check-attr $attr -- $path]}]} {
11868            regexp "(.*): $attr: (.*)" $line m f r
11869        }
11870        set path_attr_cache($attr,$path) $r
11871    }
11872    if {$r eq "unspecified"} {
11873        return $default
11874    }
11875    return $r
11876}
11877
11878proc cache_gitattr {attr pathlist} {
11879    global path_attr_cache
11880    set newlist {}
11881    foreach path $pathlist {
11882        if {![info exists path_attr_cache($attr,$path)]} {
11883            lappend newlist $path
11884        }
11885    }
11886    set lim 1000
11887    if {[tk windowingsystem] == "win32"} {
11888        # windows has a 32k limit on the arguments to a command...
11889        set lim 30
11890    }
11891    while {$newlist ne {}} {
11892        set head [lrange $newlist 0 [expr {$lim - 1}]]
11893        set newlist [lrange $newlist $lim end]
11894        if {![catch {set rlist [eval exec git check-attr $attr -- $head]}]} {
11895            foreach row [split $rlist "\n"] {
11896                if {[regexp "(.*): $attr: (.*)" $row m path value]} {
11897                    if {[string index $path 0] eq "\""} {
11898                        set path [encoding convertfrom [lindex $path 0]]
11899                    }
11900                    set path_attr_cache($attr,$path) $value
11901                }
11902            }
11903        }
11904    }
11905}
11906
11907proc get_path_encoding {path} {
11908    global gui_encoding perfile_attrs
11909    set tcl_enc $gui_encoding
11910    if {$path ne {} && $perfile_attrs} {
11911        set enc2 [tcl_encoding [gitattr $path encoding $tcl_enc]]
11912        if {$enc2 ne {}} {
11913            set tcl_enc $enc2
11914        }
11915    }
11916    return $tcl_enc
11917}
11918
11919# First check that Tcl/Tk is recent enough
11920if {[catch {package require Tk 8.4} err]} {
11921    show_error {} . "Sorry, gitk cannot run with this version of Tcl/Tk.\n\
11922                     Gitk requires at least Tcl/Tk 8.4." list
11923    exit 1
11924}
11925
11926# on OSX bring the current Wish process window to front
11927if {[tk windowingsystem] eq "aqua"} {
11928    exec osascript -e [format {
11929        tell application "System Events"
11930            set frontmost of processes whose unix id is %d to true
11931        end tell
11932    } [pid] ]
11933}
11934
11935# Unset GIT_TRACE var if set
11936if { [info exists ::env(GIT_TRACE)] } {
11937    unset ::env(GIT_TRACE)
11938}
11939
11940# defaults...
11941set wrcomcmd "git diff-tree --stdin -p --pretty"
11942
11943set gitencoding {}
11944catch {
11945    set gitencoding [exec git config --get i18n.commitencoding]
11946}
11947catch {
11948    set gitencoding [exec git config --get i18n.logoutputencoding]
11949}
11950if {$gitencoding == ""} {
11951    set gitencoding "utf-8"
11952}
11953set tclencoding [tcl_encoding $gitencoding]
11954if {$tclencoding == {}} {
11955    puts stderr "Warning: encoding $gitencoding is not supported by Tcl/Tk"
11956}
11957
11958set gui_encoding [encoding system]
11959catch {
11960    set enc [exec git config --get gui.encoding]
11961    if {$enc ne {}} {
11962        set tclenc [tcl_encoding $enc]
11963        if {$tclenc ne {}} {
11964            set gui_encoding $tclenc
11965        } else {
11966            puts stderr "Warning: encoding $enc is not supported by Tcl/Tk"
11967        }
11968    }
11969}
11970
11971set log_showroot true
11972catch {
11973    set log_showroot [exec git config --bool --get log.showroot]
11974}
11975
11976if {[tk windowingsystem] eq "aqua"} {
11977    set mainfont {{Lucida Grande} 9}
11978    set textfont {Monaco 9}
11979    set uifont {{Lucida Grande} 9 bold}
11980} elseif {![catch {::tk::pkgconfig get fontsystem} xft] && $xft eq "xft"} {
11981    # fontconfig!
11982    set mainfont {sans 9}
11983    set textfont {monospace 9}
11984    set uifont {sans 9 bold}
11985} else {
11986    set mainfont {Helvetica 9}
11987    set textfont {Courier 9}
11988    set uifont {Helvetica 9 bold}
11989}
11990set tabstop 8
11991set findmergefiles 0
11992set maxgraphpct 50
11993set maxwidth 16
11994set revlistorder 0
11995set fastdate 0
11996set uparrowlen 5
11997set downarrowlen 5
11998set mingaplen 100
11999set cmitmode "patch"
12000set wrapcomment "none"
12001set showneartags 1
12002set hideremotes 0
12003set maxrefs 20
12004set maxlinelen 200
12005set showlocalchanges 1
12006set limitdiffs 1
12007set datetimeformat "%Y-%m-%d %H:%M:%S"
12008set autoselect 1
12009set autosellen 40
12010set perfile_attrs 0
12011set want_ttk 1
12012
12013if {[tk windowingsystem] eq "aqua"} {
12014    set extdifftool "opendiff"
12015} else {
12016    set extdifftool "meld"
12017}
12018
12019set colors {green red blue magenta darkgrey brown orange}
12020if {[tk windowingsystem] eq "win32"} {
12021    set uicolor SystemButtonFace
12022    set uifgcolor SystemButtonText
12023    set uifgdisabledcolor SystemDisabledText
12024    set bgcolor SystemWindow
12025    set fgcolor SystemWindowText
12026    set selectbgcolor SystemHighlight
12027} else {
12028    set uicolor grey85
12029    set uifgcolor black
12030    set uifgdisabledcolor "#999"
12031    set bgcolor white
12032    set fgcolor black
12033    set selectbgcolor gray85
12034}
12035set diffcolors {red "#00a000" blue}
12036set diffcontext 3
12037set mergecolors {red blue green purple brown "#009090" magenta "#808000" "#009000" "#ff0080" cyan "#b07070" "#70b0f0" "#70f0b0" "#f0b070" "#ff70b0"}
12038set ignorespace 0
12039set worddiff ""
12040set markbgcolor "#e0e0ff"
12041
12042set headbgcolor green
12043set headfgcolor black
12044set headoutlinecolor black
12045set remotebgcolor #ffddaa
12046set tagbgcolor yellow
12047set tagfgcolor black
12048set tagoutlinecolor black
12049set reflinecolor black
12050set filesepbgcolor #aaaaaa
12051set filesepfgcolor black
12052set linehoverbgcolor #ffff80
12053set linehoverfgcolor black
12054set linehoveroutlinecolor black
12055set mainheadcirclecolor yellow
12056set workingfilescirclecolor red
12057set indexcirclecolor green
12058set circlecolors {white blue gray blue blue}
12059set linkfgcolor blue
12060set circleoutlinecolor $fgcolor
12061set foundbgcolor yellow
12062set currentsearchhitbgcolor orange
12063
12064# button for popping up context menus
12065if {[tk windowingsystem] eq "aqua"} {
12066    set ctxbut <Button-2>
12067} else {
12068    set ctxbut <Button-3>
12069}
12070
12071## For msgcat loading, first locate the installation location.
12072if { [info exists ::env(GITK_MSGSDIR)] } {
12073    ## Msgsdir was manually set in the environment.
12074    set gitk_msgsdir $::env(GITK_MSGSDIR)
12075} else {
12076    ## Let's guess the prefix from argv0.
12077    set gitk_prefix [file dirname [file dirname [file normalize $argv0]]]
12078    set gitk_libdir [file join $gitk_prefix share gitk lib]
12079    set gitk_msgsdir [file join $gitk_libdir msgs]
12080    unset gitk_prefix
12081}
12082
12083## Internationalization (i18n) through msgcat and gettext. See
12084## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
12085package require msgcat
12086namespace import ::msgcat::mc
12087## And eventually load the actual message catalog
12088::msgcat::mcload $gitk_msgsdir
12089
12090catch {
12091    # follow the XDG base directory specification by default. See
12092    # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
12093    if {[info exists env(XDG_CONFIG_HOME)] && $env(XDG_CONFIG_HOME) ne ""} {
12094        # XDG_CONFIG_HOME environment variable is set
12095        set config_file [file join $env(XDG_CONFIG_HOME) git gitk]
12096        set config_file_tmp [file join $env(XDG_CONFIG_HOME) git gitk-tmp]
12097    } else {
12098        # default XDG_CONFIG_HOME
12099        set config_file "~/.config/git/gitk"
12100        set config_file_tmp "~/.config/git/gitk-tmp"
12101    }
12102    if {![file exists $config_file]} {
12103        # for backward compatibility use the old config file if it exists
12104        if {[file exists "~/.gitk"]} {
12105            set config_file "~/.gitk"
12106            set config_file_tmp "~/.gitk-tmp"
12107        } elseif {![file exists [file dirname $config_file]]} {
12108            file mkdir [file dirname $config_file]
12109        }
12110    }
12111    source $config_file
12112}
12113
12114parsefont mainfont $mainfont
12115eval font create mainfont [fontflags mainfont]
12116eval font create mainfontbold [fontflags mainfont 1]
12117
12118parsefont textfont $textfont
12119eval font create textfont [fontflags textfont]
12120eval font create textfontbold [fontflags textfont 1]
12121
12122parsefont uifont $uifont
12123eval font create uifont [fontflags uifont]
12124
12125setui $uicolor
12126
12127setoptions
12128
12129# check that we can find a .git directory somewhere...
12130if {[catch {set gitdir [exec git rev-parse --git-dir]}]} {
12131    show_error {} . [mc "Cannot find a git repository here."]
12132    exit 1
12133}
12134
12135set selecthead {}
12136set selectheadid {}
12137
12138set revtreeargs {}
12139set cmdline_files {}
12140set i 0
12141set revtreeargscmd {}
12142foreach arg $argv {
12143    switch -glob -- $arg {
12144        "" { }
12145        "--" {
12146            set cmdline_files [lrange $argv [expr {$i + 1}] end]
12147            break
12148        }
12149        "--select-commit=*" {
12150            set selecthead [string range $arg 16 end]
12151        }
12152        "--argscmd=*" {
12153            set revtreeargscmd [string range $arg 10 end]
12154        }
12155        default {
12156            lappend revtreeargs $arg
12157        }
12158    }
12159    incr i
12160}
12161
12162if {$selecthead eq "HEAD"} {
12163    set selecthead {}
12164}
12165
12166if {$i >= [llength $argv] && $revtreeargs ne {}} {
12167    # no -- on command line, but some arguments (other than --argscmd)
12168    if {[catch {
12169        set f [eval exec git rev-parse --no-revs --no-flags $revtreeargs]
12170        set cmdline_files [split $f "\n"]
12171        set n [llength $cmdline_files]
12172        set revtreeargs [lrange $revtreeargs 0 end-$n]
12173        # Unfortunately git rev-parse doesn't produce an error when
12174        # something is both a revision and a filename.  To be consistent
12175        # with git log and git rev-list, check revtreeargs for filenames.
12176        foreach arg $revtreeargs {
12177            if {[file exists $arg]} {
12178                show_error {} . [mc "Ambiguous argument '%s': both revision\
12179                                 and filename" $arg]
12180                exit 1
12181            }
12182        }
12183    } err]} {
12184        # unfortunately we get both stdout and stderr in $err,
12185        # so look for "fatal:".
12186        set i [string first "fatal:" $err]
12187        if {$i > 0} {
12188            set err [string range $err [expr {$i + 6}] end]
12189        }
12190        show_error {} . "[mc "Bad arguments to gitk:"]\n$err"
12191        exit 1
12192    }
12193}
12194
12195set nullid "0000000000000000000000000000000000000000"
12196set nullid2 "0000000000000000000000000000000000000001"
12197set nullfile "/dev/null"
12198
12199set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
12200if {![info exists have_ttk]} {
12201    set have_ttk [llength [info commands ::ttk::style]]
12202}
12203set use_ttk [expr {$have_ttk && $want_ttk}]
12204set NS [expr {$use_ttk ? "ttk" : ""}]
12205
12206regexp {^git version ([\d.]*\d)} [exec git version] _ git_version
12207
12208set show_notes {}
12209if {[package vcompare $git_version "1.6.6.2"] >= 0} {
12210    set show_notes "--show-notes"
12211}
12212
12213set appname "gitk"
12214
12215set runq {}
12216set history {}
12217set historyindex 0
12218set fh_serial 0
12219set nhl_names {}
12220set highlight_paths {}
12221set findpattern {}
12222set searchdirn -forwards
12223set boldids {}
12224set boldnameids {}
12225set diffelide {0 0}
12226set markingmatches 0
12227set linkentercount 0
12228set need_redisplay 0
12229set nrows_drawn 0
12230set firsttabstop 0
12231
12232set nextviewnum 1
12233set curview 0
12234set selectedview 0
12235set selectedhlview [mc "None"]
12236set highlight_related [mc "None"]
12237set highlight_files {}
12238set viewfiles(0) {}
12239set viewperm(0) 0
12240set viewargs(0) {}
12241set viewargscmd(0) {}
12242
12243set selectedline {}
12244set numcommits 0
12245set loginstance 0
12246set cmdlineok 0
12247set stopped 0
12248set stuffsaved 0
12249set patchnum 0
12250set lserial 0
12251set hasworktree [hasworktree]
12252set cdup {}
12253if {[expr {[exec git rev-parse --is-inside-work-tree] == "true"}]} {
12254    set cdup [exec git rev-parse --show-cdup]
12255}
12256set worktree [exec git rev-parse --show-toplevel]
12257setcoords
12258makewindow
12259catch {
12260    image create photo gitlogo      -width 16 -height 16
12261
12262    image create photo gitlogominus -width  4 -height  2
12263    gitlogominus put #C00000 -to 0 0 4 2
12264    gitlogo copy gitlogominus -to  1 5
12265    gitlogo copy gitlogominus -to  6 5
12266    gitlogo copy gitlogominus -to 11 5
12267    image delete gitlogominus
12268
12269    image create photo gitlogoplus  -width  4 -height  4
12270    gitlogoplus  put #008000 -to 1 0 3 4
12271    gitlogoplus  put #008000 -to 0 1 4 3
12272    gitlogo copy gitlogoplus  -to  1 9
12273    gitlogo copy gitlogoplus  -to  6 9
12274    gitlogo copy gitlogoplus  -to 11 9
12275    image delete gitlogoplus
12276
12277    image create photo gitlogo32    -width 32 -height 32
12278    gitlogo32 copy gitlogo -zoom 2 2
12279
12280    wm iconphoto . -default gitlogo gitlogo32
12281}
12282# wait for the window to become visible
12283tkwait visibility .
12284wm title . "$appname: [reponame]"
12285update
12286readrefs
12287
12288if {$cmdline_files ne {} || $revtreeargs ne {} || $revtreeargscmd ne {}} {
12289    # create a view for the files/dirs specified on the command line
12290    set curview 1
12291    set selectedview 1
12292    set nextviewnum 2
12293    set viewname(1) [mc "Command line"]
12294    set viewfiles(1) $cmdline_files
12295    set viewargs(1) $revtreeargs
12296    set viewargscmd(1) $revtreeargscmd
12297    set viewperm(1) 0
12298    set vdatemode(1) 0
12299    addviewmenu 1
12300    .bar.view entryconf [mca "Edit view..."] -state normal
12301    .bar.view entryconf [mca "Delete view"] -state normal
12302}
12303
12304if {[info exists permviews]} {
12305    foreach v $permviews {
12306        set n $nextviewnum
12307        incr nextviewnum
12308        set viewname($n) [lindex $v 0]
12309        set viewfiles($n) [lindex $v 1]
12310        set viewargs($n) [lindex $v 2]
12311        set viewargscmd($n) [lindex $v 3]
12312        set viewperm($n) 1
12313        addviewmenu $n
12314    }
12315}
12316
12317if {[tk windowingsystem] eq "win32"} {
12318    focus -force .
12319}
12320
12321getcommits {}
12322
12323# Local variables:
12324# mode: tcl
12325# indent-tabs-mode: t
12326# tab-width: 8
12327# End: